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.

564 lines
20 KiB

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