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.

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