Forked mumble-django project from https://bitbucket.org/Svedrin/mumble-django
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

558 lines
20 KiB

15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright (C) 2009, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  4. *
  5. * Mumble-Django is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This package is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. """
  15. import socket
  16. from django.utils.translation import ugettext_lazy as _
  17. from django.contrib.auth.models import User
  18. from django.db import models
  19. from django.db.models import signals
  20. from django.conf import settings
  21. from mmobjects import *
  22. from mctl import *
  23. class Mumble( models.Model ):
  24. """ Represents a Murmur server instance.
  25. All configurable settings are represented by a field in this model. To change the
  26. settings, just update the appropriate field and call the save() method.
  27. To set up a new server instance, instanciate this Model. The first field you should
  28. define is the "dbus" field, which tells the connector subsystem how to connect to
  29. the Murmurd master process. Set this to the appropriate DBus service name or the
  30. Ice proxy string.
  31. When an instance of this model is deleted, the according server instance will be
  32. deleted as well.
  33. """
  34. name = models.CharField( _('Server Name'), max_length = 200 );
  35. dbus = models.CharField( _('DBus or ICE base'), max_length = 200, default = settings.DEFAULT_CONN, help_text=_("Examples: 'net.sourceforge.mumble.murmur' for DBus or 'Meta:tcp -h 127.0.0.1 -p 6502' for Ice.") );
  36. srvid = models.IntegerField( _('Server ID'), editable = False );
  37. addr = models.CharField( _('Server Address'), max_length = 200, help_text=_("Hostname or IP address to bind to. You should use a hostname here, because it will appear on the global server list.") );
  38. port = models.IntegerField( _('Server Port'), help_text=_("Port number to bind to. Use -1 to auto assign one."), default=settings.MUMBLE_DEFAULT_PORT );
  39. url = models.CharField( _('Website URL'), max_length = 200, blank = True );
  40. motd = models.TextField( _('Welcome Message'), blank = True );
  41. passwd = models.CharField( _('Server Password'), max_length = 200, blank = True, help_text=_("Password required to join. Leave empty for public servers.") );
  42. supw = models.CharField( _('Superuser Password'), max_length = 200, blank = True );
  43. users = models.IntegerField( _('Max. Users'), blank = True, null = True );
  44. bwidth = models.IntegerField( _('Bandwidth [Bps]'), blank = True, null = True );
  45. sslcrt = models.TextField( _('SSL Certificate'), blank = True );
  46. sslkey = models.TextField( _('SSL Key'), blank = True );
  47. obfsc = models.BooleanField( _('IP Obfuscation'), default = False, help_text=_("If on, IP adresses of the clients are not logged.") );
  48. player = models.CharField( _('Player name regex'), max_length=200, default=r'[-=\w\[\]\{\}\(\)\@\|\.]+' );
  49. channel = models.CharField( _('Channel name regex'), max_length=200, default=r'[ \-=\w\#\[\]\{\}\(\)\@\|]+' );
  50. defchan = models.IntegerField( _('Default channel'), default=0, help_text=_("Enter the ID of the default channel here. The Channel viewer displays the ID to server admins on the channel detail page."));
  51. booted = models.BooleanField( _('Boot Server'), default = True );
  52. class Meta:
  53. unique_together = ( ( 'dbus', 'srvid' ), ( 'addr', 'port' ), );
  54. verbose_name = _('Server instance');
  55. verbose_name_plural = _('Server instances');
  56. def __init__( self, *args, **kwargs ):
  57. models.Model.__init__( self, *args, **kwargs );
  58. self._ctl = None;
  59. self._channels = None;
  60. self._rootchan = None;
  61. def __unicode__( self ):
  62. if not self.id:
  63. return u'Murmur "%s" (NOT YET CREATED)' % self.name;
  64. return u'Murmur "%s" (%d)' % ( self.name, self.srvid );
  65. users_regged = property( lambda self: self.mumbleuser_set.count(), doc="Number of registered users." );
  66. users_online = property( lambda self: len(self.ctl.getPlayers(self.srvid)), doc="Number of online users." );
  67. channel_cnt = property( lambda self: len(self.ctl.getChannels(self.srvid)), doc="Number of channels." );
  68. is_public = property( lambda self: self.passwd == '', doc="False if a password is needed to join this server." );
  69. is_server = True;
  70. is_channel = False;
  71. is_player = False;
  72. # Ctl instantiation
  73. def getCtl( self ):
  74. """Instantiate and return a MumbleCtl object for this server.
  75. Only one instance will be created, and reused on subsequent calls.
  76. """
  77. if not self._ctl:
  78. self._ctl = MumbleCtlBase.newInstance( self.dbus );
  79. return self._ctl;
  80. ctl = property( getCtl, doc="Get a Control object for this server. The ctl is cached for later reuse." );
  81. def save( self, dontConfigureMurmur=False ):
  82. """
  83. Save the options configured in this model instance not only to Django's database,
  84. but to Murmur as well.
  85. """
  86. if dontConfigureMurmur:
  87. # skip murmur configuration, e.g. because we're inserting models for existing servers.
  88. return models.Model.save( self );
  89. # check if this server already exists, if not call newServer and set my srvid first
  90. if self.id is None:
  91. self.srvid = self.ctl.newServer();
  92. if self.port == -1:
  93. self.port = max( [ rec['port'] for rec in Mumble.objects.values('port') ] ) + 1;
  94. if self.port < 1 or self.port >= 2**16:
  95. raise ValueError( _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  96. 'portno': self.port,
  97. 'minrange': 1,
  98. 'maxrange': 2**16,
  99. });
  100. self.ctl.setConf( self.srvid, 'host', socket.gethostbyname( self.addr ) );
  101. self.ctl.setConf( self.srvid, 'port', str(self.port) );
  102. self.ctl.setConf( self.srvid, 'registername', self.name );
  103. self.ctl.setConf( self.srvid, 'registerurl', self.url );
  104. self.ctl.setConf( self.srvid, 'welcometext', self.motd );
  105. self.ctl.setConf( self.srvid, 'password', self.passwd );
  106. self.ctl.setConf( self.srvid, 'certificate', self.sslcrt );
  107. self.ctl.setConf( self.srvid, 'key', self.sslkey );
  108. self.ctl.setConf( self.srvid, 'obfuscate', str(self.obfsc).lower() );
  109. if self.ctl.getVersion()[:2] == ( 1, 2 ):
  110. self.ctl.setConf( self.srvid, 'username', self.player );
  111. else:
  112. self.ctl.setConf( self.srvid, 'playername', self.player );
  113. self.ctl.setConf( self.srvid, 'channelname', self.channel );
  114. self.ctl.setConf( self.srvid, 'defaultchannel', str(self.defchan) );
  115. if self.users is not None:
  116. self.ctl.setConf( self.srvid, 'users', str(self.users) );
  117. else:
  118. self.ctl.setConf( self.srvid, 'users', '' );
  119. if self.bwidth is not None:
  120. self.ctl.setConf( self.srvid, 'bandwidth', str(self.bwidth) );
  121. else:
  122. self.ctl.setConf( self.srvid, 'bandwidth', '' );
  123. # registerHostname needs to take the port no into account
  124. if self.port and self.port != settings.MUMBLE_DEFAULT_PORT:
  125. self.ctl.setConf( self.srvid, 'registerhostname', "%s:%d" % ( self.addr, self.port ) );
  126. else:
  127. self.ctl.setConf( self.srvid, 'registerhostname', self.addr );
  128. if self.supw:
  129. self.ctl.setSuperUserPassword( self.srvid, self.supw );
  130. self.supw = '';
  131. if self.booted != self.ctl.isBooted( self.srvid ):
  132. if self.booted:
  133. self.ctl.start( self.srvid );
  134. else:
  135. self.ctl.stop( self.srvid );
  136. # Now allow django to save the record set
  137. return models.Model.save( self );
  138. def configureFromMurmur( self ):
  139. default = self.ctl.getDefaultConf();
  140. conf = self.ctl.getAllConf( self.srvid );
  141. def find_in_dicts( keys, valueIfNotFound=None ):
  142. if not isinstance( keys, tuple ):
  143. keys = ( keys, );
  144. for keyword in keys:
  145. if keyword in conf:
  146. return conf[keyword];
  147. for keyword in keys:
  148. keyword = keyword.lower();
  149. if keyword in default:
  150. return default[keyword];
  151. return valueIfNotFound;
  152. servername = find_in_dicts( "registername", "noname" );
  153. if not servername:
  154. # RegistrationName was found in the dicts, but is an empty string
  155. servername = "noname";
  156. addr = find_in_dicts( ( "registerhostname", "host" ), "0.0.0.0" );
  157. if addr.find( ':' ) != -1:
  158. # The addr is a hostname which actually contains a port number, but we already got that from
  159. # the port field, so we can simply drop it.
  160. addr = addr.split(':')[0];
  161. self.name = servername;
  162. self.addr = addr;
  163. self.port = find_in_dicts( "port" );
  164. self.url = find_in_dicts( "registerurl" );
  165. self.motd = find_in_dicts( "welcometext" );
  166. self.passwd = find_in_dicts( "password" );
  167. self.supw = '';
  168. self.users = find_in_dicts( "users" );
  169. self.bwidth = find_in_dicts( "bandwidth" );
  170. self.sslcrt = find_in_dicts( "certificate" );
  171. self.sslkey = find_in_dicts( "key" );
  172. self.obfsc = bool( find_in_dicts( 'obfuscate' ) );
  173. pldefault = self._meta.get_field_by_name('player')[0].default;
  174. if self.ctl.getVersion()[:2] == ( 1, 2 ):
  175. self.player = find_in_dicts( ( 'username', 'playername' ), pldefault );
  176. else:
  177. self.player = find_in_dicts( 'playername', pldefault );
  178. chdefault = self._meta.get_field_by_name('channel')[0].default;
  179. self.channel = find_in_dicts( 'channelname', chdefault );
  180. self.defchan = int( find_in_dicts( 'defaultchannel', 0 ) );
  181. self.booted = ( self.srvid in self.ctl.getBootedServers() );
  182. self.save( dontConfigureMurmur=True );
  183. def readUsersFromMurmur( self, verbose=0 ):
  184. if not self.booted:
  185. raise SystemError( "This murmur instance is not currently running, can't sync." );
  186. players = self.ctl.getRegisteredPlayers(self.srvid);
  187. for idx in players:
  188. playerdata = players[idx];
  189. if playerdata.userid == 0: # Skip SuperUsers
  190. continue;
  191. if verbose > 1:
  192. print "Checking Player with id %d and name '%s'." % ( playerdata.userid, playerdata.name );
  193. try:
  194. playerinstance = MumbleUser.objects.get( server=self, mumbleid=playerdata.userid );
  195. except MumbleUser.DoesNotExist:
  196. if verbose:
  197. print 'Found new Player "%s".' % playerdata.name;
  198. playerinstance = MumbleUser(
  199. mumbleid = playerdata.userid,
  200. name = playerdata.name,
  201. password = '',
  202. server = self,
  203. owner = None
  204. );
  205. else:
  206. if verbose > 1:
  207. print "This player is already listed in the database.";
  208. playerinstance.name = playerdata.name;
  209. playerinstance.isAdmin = playerinstance.getAdmin();
  210. playerinstance.save( dontConfigureMurmur=True );
  211. def isUserAdmin( self, user ):
  212. """Determine if the given user is an admin on this server."""
  213. if user.is_authenticated():
  214. try:
  215. return self.mumbleuser_set.get( owner=user ).getAdmin();
  216. except MumbleUser.DoesNotExist:
  217. return False;
  218. return False;
  219. # Deletion handler
  220. def deleteServer( self ):
  221. """Delete this server instance from Murmur."""
  222. self.ctl.deleteServer(self.srvid)
  223. @staticmethod
  224. def pre_delete_listener( **kwargs ):
  225. kwargs['instance'].deleteServer();
  226. # Channel list
  227. def getChannels( self ):
  228. """ Query the channels from Murmur and create a tree structure.
  229. Again, this will only be done for the first call to this function. Subsequent
  230. calls will simply return the list created last time.
  231. """
  232. if self._channels is None:
  233. self._channels = {};
  234. chanlist = self.ctl.getChannels(self.srvid).values();
  235. links = {};
  236. # sometimes, ICE seems to return the Channel list in a weird order.
  237. # itercount prevents infinite loops.
  238. itercount = 0;
  239. maxiter = len(chanlist) * 3;
  240. while len(chanlist) and itercount < maxiter:
  241. itercount += 1;
  242. for theChan in chanlist:
  243. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  244. if( theChan.parent == -1 ):
  245. # No parent
  246. self._channels[theChan.id] = mmChannel( self, theChan );
  247. elif theChan.parent in self.channels:
  248. # parent already known
  249. self._channels[theChan.id] = mmChannel( self, theChan, self.channels[theChan.parent] );
  250. else:
  251. continue;
  252. chanlist.remove( theChan );
  253. self._channels[theChan.id].serverId = self.id;
  254. # process links - if the linked channels are known, link; else save their ids to link later
  255. for linked in theChan.links:
  256. if linked in self._channels:
  257. self._channels[theChan.id].linked.append( self._channels[linked] );
  258. else:
  259. if linked not in links:
  260. links[linked] = list();
  261. links[linked].append( self._channels[theChan.id] );
  262. # check if earlier round trips saved channel ids to be linked to the current channel
  263. if theChan.id in links:
  264. for targetChan in links[theChan.id]:
  265. targetChan.linked.append( self._channels[theChan.id] );
  266. self._channels[0].name = self.name;
  267. self.players = {};
  268. for thePlayer in self.ctl.getPlayers(self.srvid).values():
  269. # Players - Fields: 0 = UserID, 6 = ChannelID
  270. self.players[ thePlayer.session ] = mmPlayer( self, thePlayer, self._channels[ thePlayer.channel ] );
  271. self._channels[0].sort();
  272. return self._channels;
  273. channels = property( getChannels, doc="A convenience wrapper for getChannels()." );
  274. rootchan = property( lambda self: self.channels[0], doc="A convenience wrapper for getChannels()[0]." );
  275. def getURL( self, forUser = None ):
  276. """Create an URL of the form mumble://username@host:port/ for this server."""
  277. userstr = "";
  278. if forUser is not None:
  279. userstr = "%s@" % forUser.name;
  280. versionstr = "version=%d.%d.%d" % tuple(self.version[0:3]);
  281. if self.port != settings.MUMBLE_DEFAULT_PORT:
  282. return "mumble://%s%s:%d/?%s" % ( userstr, self.addr, self.port, versionstr );
  283. return "mumble://%s%s/?%s" % ( userstr, self.addr, versionstr );
  284. connecturl = property( getURL, doc="A convenience wrapper for getURL()." );
  285. version = property( lambda self: self.ctl.getVersion(), doc="The version of Murmur." );
  286. def asDict( self ):
  287. return { 'name': self.name,
  288. 'id': self.id,
  289. 'root': self.rootchan.asDict()
  290. };
  291. class MumbleUser( models.Model ):
  292. """ Represents a User account in Murmur.
  293. To change an account, simply set the according field in this model and call the save()
  294. method to update the account in Murmur and in Django's database. Note that, once saved
  295. for the first time, the server field must not be changed. Attempting to do this will
  296. result in an AttributeError. To move an account to a new server, recreate it on the
  297. new server and delete the old model.
  298. When you delete an instance of this model, the according user account will be deleted
  299. in Murmur as well, after revoking the user's admin privileges.
  300. """
  301. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 );
  302. name = models.CharField( _('User name and Login'), max_length = 200 );
  303. password = models.CharField( _('Login password'), max_length = 200, blank=True );
  304. server = models.ForeignKey( Mumble, verbose_name=_('Server instance') );
  305. owner = models.ForeignKey( User, verbose_name=_('Account owner'), null=True, blank=True );
  306. isAdmin = models.BooleanField( _('Admin on root channel'), default = False );
  307. class Meta:
  308. unique_together = ( ( 'server', 'owner' ), ( 'server', 'mumbleid' ) );
  309. verbose_name = _( 'User account' );
  310. verbose_name_plural = _( 'User accounts' );
  311. is_server = False;
  312. is_channel = False;
  313. is_player = True;
  314. def __init__( self, *args, **kwargs ):
  315. models.Model.__init__( self, *args, **kwargs );
  316. self._registration = None;
  317. def __unicode__( self ):
  318. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % { 'mu': self.name, 'srv': self.server, 'du': self.owner };
  319. def save( self, dontConfigureMurmur=False ):
  320. """Save the settings in this model to Murmur."""
  321. if dontConfigureMurmur:
  322. # skip murmur configuration, e.g. because we're inserting models for existing players.
  323. return models.Model.save( self );
  324. # Before the record set is saved, update Murmur via controller.
  325. ctl = self.server.ctl;
  326. if self.owner:
  327. email = self.owner.email;
  328. else:
  329. email = settings.DEFAULT_FROM_EMAIL;
  330. if self.id is None:
  331. # This is a new user record, so Murmur doesn't know about it yet
  332. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  333. raise ValueError( _( "Another player already registered that name." ) );
  334. if not self.password:
  335. raise ValueError( _( "Cannot register player without a password!" ) );
  336. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password );
  337. # Update user's registration
  338. elif self.password:
  339. ctl.setRegistration(
  340. self.server.srvid,
  341. self.mumbleid,
  342. self.name,
  343. email,
  344. self.password
  345. );
  346. # Don't save the users' passwords, we don't need them anyway
  347. self.password = '';
  348. self.aclAdmin = self.isAdmin;
  349. # Now allow django to save the record set
  350. return models.Model.save( self );
  351. # Admin handlers
  352. def getAdmin( self ):
  353. """Get ACL of root Channel, get the admin group and see if this user is in it."""
  354. return self.server.rootchan.acl.groupHasMember( "admin", self.mumbleid );
  355. def setAdmin( self, value ):
  356. """Set or revoke this user's membership in the admin group on the root channel."""
  357. if value:
  358. self.server.rootchan.acl.groupAddMember( "admin", self.mumbleid );
  359. else:
  360. self.server.rootchan.acl.groupRemoveMember( "admin", self.mumbleid );
  361. self.server.rootchan.acl.save();
  362. return value;
  363. aclAdmin = property( getAdmin, setAdmin, doc="Wrapper around getAdmin/setAdmin (not a database field like isAdmin)" );
  364. # Registration fetching
  365. def getRegistration( self ):
  366. """Retrieve a user's registration from Murmur as a dict."""
  367. if not self._registration:
  368. self._registration = self.server.ctl.getRegistration( self.server.srvid, self.mumbleid );
  369. return self._registration;
  370. registration = property( getRegistration, doc=getRegistration.__doc__ );
  371. def getComment( self ):
  372. """Retrieve a user's comment, if any."""
  373. if "comment" in self.registration:
  374. return self.registration["comment"];
  375. else:
  376. return None;
  377. comment = property( getComment, doc=getComment.__doc__ );
  378. def getHash( self ):
  379. if "hash" in self.registration:
  380. return self.registration["hash"];
  381. else:
  382. return None;
  383. hash = property( getHash, doc=getHash.__doc__ );
  384. # Texture handlers
  385. def getTexture( self ):
  386. """Get the user texture as a PIL Image."""
  387. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid);
  388. def setTexture( self, infile ):
  389. """Read an image from the infile and install it as the user's texture."""
  390. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, infile)
  391. texture = property( getTexture, setTexture, doc="Get the texture as a PIL Image or read from a file (pass the path)." );
  392. def hasTexture( self ):
  393. """ Check if this user has a texture set. """
  394. try:
  395. self.getTexture();
  396. except ValueError:
  397. return False;
  398. else:
  399. return True;
  400. def getTextureUrl( self ):
  401. """ Get a URL under which the texture can be retrieved. """
  402. from views import showTexture
  403. from django.core.urlresolvers import reverse
  404. return reverse( showTexture, kwargs={ 'server': self.server.id, 'userid': self.id } );
  405. textureUrl = property( getTextureUrl, doc=getTextureUrl.__doc__ );
  406. # Deletion handler
  407. @staticmethod
  408. def pre_delete_listener( **kwargs ):
  409. kwargs['instance'].unregister();
  410. def unregister( self ):
  411. """Delete this user account from Murmur."""
  412. if self.getAdmin():
  413. self.setAdmin( False );
  414. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  415. # "server" field protection
  416. def __setattr__( self, name, value ):
  417. if name == 'server':
  418. if self.id is not None and self.server != value:
  419. raise AttributeError( _( "This field must not be updated once the record has been saved." ) );
  420. models.Model.__setattr__( self, name, value );
  421. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  422. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );