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.

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