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

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