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.

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