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.

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