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.

944 lines
38 KiB

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. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright © 2009-2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * Mumble-Django is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This package is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. """
  16. import re
  17. import datetime
  18. from time import time
  19. from sys import stderr
  20. from urllib import urlopen
  21. from StringIO import StringIO
  22. from PIL import Image
  23. from django.utils.translation import ugettext_noop, ugettext_lazy as _
  24. from django.contrib.auth.models import User
  25. from django.db import models
  26. from django.db.models import signals
  27. from django.conf import settings
  28. from django.utils.encoding import smart_str
  29. from mumble.mmobjects import mmChannel, mmPlayer
  30. from mumble.mctl import MumbleCtlBase
  31. def mk_config_property( field, doc="", get_coerce=None, get_none=None, set_coerce=unicode, set_none='' ):
  32. """ Create a property for the given config field. """
  33. def get_field( self ):
  34. if self.id is not None:
  35. val = self.getConf( field )
  36. if val is None or val == '':
  37. return get_none
  38. if callable(get_coerce):
  39. return get_coerce( val )
  40. return val
  41. return None
  42. def set_field( self, value ):
  43. if value is None:
  44. self.setConf( field, set_none )
  45. elif callable(set_coerce):
  46. self.setConf( field, set_coerce(value) )
  47. else:
  48. self.setConf( field, value )
  49. return property( get_field, set_field, doc=doc )
  50. def mk_config_bool_property( field, doc="" ):
  51. return mk_config_property( field, doc=doc,
  52. get_coerce = lambda value: value == "true",
  53. set_coerce = lambda value: str(value).lower()
  54. )
  55. class MumbleServer( models.Model ):
  56. """ Represents a Murmur server installation. """
  57. dbus = models.CharField( _('DBus or ICE base'), max_length=200, unique=True, default=settings.DEFAULT_CONN, help_text=_(
  58. "Examples: 'net.sourceforge.mumble.murmur' for DBus or 'Meta:tcp -h 127.0.0.1 -p 6502' for Ice.") )
  59. secret = models.CharField( _('Ice Secret'), max_length=200, blank=True )
  60. class Meta:
  61. verbose_name = _('Mumble Server')
  62. verbose_name_plural = _('Mumble Servers')
  63. def __init__( self, *args, **kwargs ):
  64. models.Model.__init__( self, *args, **kwargs )
  65. self._ctl = None
  66. self._conf = None
  67. self._version = None
  68. def __unicode__( self ):
  69. return self.dbus
  70. # Ctl instantiation
  71. def getCtl( self ):
  72. """ Instantiate and return a MumbleCtl object for this server.
  73. Only one instance will be created, and reused on subsequent calls.
  74. """
  75. if not self._ctl:
  76. self._ctl = MumbleCtlBase.newInstance( self.dbus, settings.SLICE, self.secret )
  77. return self._ctl
  78. ctl = property( getCtl, doc="Get a Control object for this server. The ctl is cached for later reuse." )
  79. def isMethodDbus(self):
  80. """ Return true if this instance uses DBus. """
  81. rd = re.compile( r'^(\w+\.)*\w+$' )
  82. return bool(rd.match(self.dbus))
  83. method_dbus = property( isMethodDbus )
  84. method_ice = property( lambda self: not self.isMethodDbus(), doc="Return true if this instance uses Ice." )
  85. def getDefaultConf( self, field=None ):
  86. """ Get a field from the default conf dictionary, or None if the field isn't set. """
  87. if self._conf is None:
  88. self._conf = self.ctl.getDefaultConf()
  89. if field is None:
  90. return self._conf
  91. if field in self._conf:
  92. return self._conf[field]
  93. return None
  94. def isOnline( self ):
  95. """ Return true if this server process is running. """
  96. possibleexceptions = []
  97. try:
  98. from Ice import ConnectionRefusedException
  99. except ImportError, err:
  100. if self.method_ice:
  101. print >> stderr, err
  102. return None
  103. else:
  104. possibleexceptions.append( ConnectionRefusedException )
  105. try:
  106. from dbus import DBusException
  107. except ImportError, err:
  108. if self.method_dbus:
  109. print >> stderr, err
  110. return None
  111. else:
  112. possibleexceptions.append( DBusException )
  113. try:
  114. self.ctl
  115. except tuple(possibleexceptions), err:
  116. print >> stderr, err
  117. return False
  118. except (EnvironmentError, RuntimeError), err:
  119. print >> stderr, err
  120. return None
  121. else:
  122. return True
  123. online = property( isOnline )
  124. defaultconf = property( getDefaultConf, doc="The default config dictionary." )
  125. def getDefaultPort( self ):
  126. """ Return the default port configured on this server. """
  127. if "port" in self.defaultconf:
  128. return int(self.defaultconf['port'])
  129. else:
  130. return settings.MUMBLE_DEFAULT_PORT
  131. defaultPort = property( getDefaultPort )
  132. def getVersion( self ):
  133. """ Return the version of Murmur. """
  134. if self._version is None:
  135. self._version = self.ctl.getVersion()
  136. return self._version
  137. version = property( getVersion )
  138. prettyversion = property( lambda self: '.'.join( map( str, self.version[:3] ) ),
  139. doc="Pretty-Printed version" )
  140. def save( self, run_detection=True, verbosity=0, *args, **kwargs ):
  141. ret = models.Model.save( self, *args, **kwargs )
  142. if not run_detection:
  143. return ret
  144. servIDs = self.ctl.getAllServers()
  145. unseen_ids = [rec["srvid"] for rec in Mumble.objects.values( "srvid" )]
  146. for id in servIDs:
  147. if id in unseen_ids:
  148. unseen_ids.remove(id)
  149. if verbosity > 1:
  150. print "Checking Murmur instance with id %d." % id
  151. # first check that the server has not yet been inserted into the DB
  152. try:
  153. instance = Mumble.objects.get( server=self, srvid=id )
  154. except Mumble.DoesNotExist:
  155. if verbosity:
  156. print "Found new Murmur instance %d on bus '%s'... " % ( id, self.dbus )
  157. # now create a model for the record set (configureFromMurmur will save() it).
  158. instance = Mumble( server=self, srvid=id )
  159. else:
  160. if verbosity:
  161. print "Syncing Murmur instance %d: '%s'... " % ( instance.id, instance.name )
  162. try:
  163. instance.configureFromMurmur()
  164. except DatabaseError, err:
  165. try:
  166. # Find instances with the same address/port
  167. dup = Mumble.objects.get( addr=instance.addr, port=instance.port )
  168. except Mumble.DoesNotExist:
  169. # None exist - this must've been something else.
  170. if verbosity:
  171. print "Server ID / Name: %d / %s" % ( instance.srvid, instance.name )
  172. raise err
  173. else:
  174. if verbosity:
  175. print "ERROR: There is already another server instance registered"
  176. print " on the same address and port."
  177. print " -------------"
  178. print " New Server ID:", instance.srvid,
  179. print " New Server Name:", instance.name
  180. print " Address:", instance.addr
  181. print " Port:", instance.port
  182. print " Connection string:", instance.server.dbus
  183. print " -------------"
  184. print " Duplicate Server ID:", dup.srvid,
  185. print "Duplicate Server Name:", dup.name
  186. print " Address:", dup.addr
  187. print " Port:", dup.port
  188. print " Connection string:", dup.server.dbus
  189. raise err
  190. except Exception, err:
  191. if verbosity:
  192. print "Server ID / Name: %d / %s" % ( instance.srvid, instance.name )
  193. raise err
  194. # Now search for players on this server that have not yet been registered
  195. if instance.booted:
  196. if verbosity > 1:
  197. print "Looking for registered Players on Server id %d." % id
  198. instance.readUsersFromMurmur( verbose=verbosity )
  199. elif verbosity:
  200. print "This server is not running, can't sync players."
  201. signals.pre_delete.disconnect( Mumble.pre_delete_listener, sender=Mumble )
  202. for srvid in unseen_ids:
  203. mm = Mumble.objects.get( srvid=srvid )
  204. if verbosity:
  205. print 'Found stale Mumble instance "%s".' % mm.name
  206. mm.delete()
  207. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble )
  208. return ret
  209. class Mumble( models.Model ):
  210. """ Represents a Murmur server instance.
  211. All configurable settings are represented by a field in this model. To change the
  212. settings, just update the appropriate field and call the save() method.
  213. To set up a new server instance, instanciate and save this Model.
  214. When an instance of this model is deleted, the according server instance will be
  215. deleted as well.
  216. """
  217. server = models.ForeignKey( MumbleServer, verbose_name=_("Mumble Server") )
  218. name = models.CharField( _('Server Name'), max_length=200 )
  219. srvid = models.IntegerField( _('Server ID'), editable=False )
  220. addr = models.CharField( _('Server Address'), max_length=200, blank=True, help_text=_(
  221. "Hostname or IP address to bind to. You should use a hostname here, because it will appear on the "
  222. "global server list.") )
  223. port = models.IntegerField( _('Server Port'), blank=True, null=True, help_text=_(
  224. "Port number to bind to. Leave empty to auto assign one.") )
  225. display = models.CharField( _('Server Display Address'), max_length=200, blank=True, help_text=_(
  226. "This field is only relevant if you are located behind a NAT, and names the Hostname or IP address "
  227. "to use in the Channel Viewer and for the global server list registration. If not given, the addr "
  228. "and port fields are used. If display and bind ports are equal, you can omit it here.") )
  229. supw = property( lambda self: '',
  230. lambda self, value: ( value and self.ctl.setSuperUserPassword( self.srvid, value ) ) or None,
  231. doc=_('Superuser Password')
  232. )
  233. url = mk_config_property( "registerurl", ugettext_noop("Website URL") )
  234. motd = mk_config_property( "welcometext", ugettext_noop("Welcome Message") )
  235. passwd = mk_config_property( "password", ugettext_noop("Server Password") )
  236. users = mk_config_property( "users", ugettext_noop("Max. Users"), get_coerce=int )
  237. bwidth = mk_config_property( "bandwidth", ugettext_noop("Bandwidth [Bps]"), get_coerce=int )
  238. sslcrt = mk_config_property( "certificate", ugettext_noop("SSL Certificate") )
  239. sslkey = mk_config_property( "key", ugettext_noop("SSL Key") )
  240. player = mk_config_property( "username", ugettext_noop("Player name regex") )
  241. channel = mk_config_property( "channelname", ugettext_noop("Channel name regex") )
  242. defchan = mk_config_property( "defaultchannel", ugettext_noop("Default channel"), get_coerce=int )
  243. timeout = mk_config_property( "timeout", ugettext_noop("Timeout"), get_coerce=int )
  244. textmessagelength = mk_config_property( "textmessagelength", ugettext_noop("Maximum length of text messages") )
  245. imagemessagelength = mk_config_property( "imagemessagelength", ugettext_noop("Maximum length of text messages containing images") )
  246. usersperchannel = mk_config_property( "usersperchannel", ugettext_noop("Users per channel"), get_coerce=int )
  247. suggestversion = mk_config_property( "suggestversion", ugettext_noop("Version to recommend") )
  248. suggestpositional = mk_config_property( "suggestpositional", ugettext_noop("Suggest to use positional audio") )
  249. suggestpushtotalk = mk_config_property( "suggestpushtotalk", ugettext_noop("Suggest to use Push-To-Talk") )
  250. sslca = mk_config_property( "sslca", ugettext_noop("CA Certificate") )
  251. sslpassphrase = mk_config_property( "sslpassphrase", ugettext_noop("Key passphrase") )
  252. opusthreshold = mk_config_property( "opusthreshold", ugettext_noop("Opusthreshold") )
  253. channelnestinglimit = mk_config_property( "channelnestinglimit", ugettext_noop("Channel nesting limit") )
  254. registerlocation = mk_config_property( "registerlocation", ugettext_noop("Server location") )
  255. registerpassword = mk_config_property( "registerpassword", ugettext_noop("Registration password") )
  256. certrequired = mk_config_bool_property( "certrequired", ugettext_noop("Require Certificate") )
  257. allowhtml = mk_config_bool_property( "allowhtml", ugettext_noop("Allow HTML to be used in messages") )
  258. bonjour = mk_config_bool_property( "bonjour", ugettext_noop("Publish this server via Bonjour") )
  259. autoboot = mk_config_bool_property( "boot", ugettext_noop("Boot Server when Murmur starts") )
  260. rememberchannel = mk_config_bool_property( "rememberchannel", ugettext_noop("Remember last channel") )
  261. allowping = mk_config_bool_property( "allowping", ugettext_noop("Allow ping packets") )
  262. sendversion = mk_config_bool_property( "sendversion", ugettext_noop("Allow to send system version") )
  263. def get_absolute_url( self ):
  264. from views import show
  265. from django.core.urlresolvers import reverse
  266. return reverse( show, kwargs={ 'server': self.id } )
  267. def getBooted( self ):
  268. if self.id is not None:
  269. if self.server.online:
  270. return self.ctl.isBooted( self.srvid )
  271. else:
  272. return None
  273. else:
  274. return False
  275. def setBooted( self, value ):
  276. if value != self.getBooted():
  277. if value:
  278. self.ctl.start( self.srvid )
  279. else:
  280. self.ctl.stop( self.srvid )
  281. booted = property( getBooted, setBooted, doc=ugettext_noop("Boot Server") )
  282. online = property( getBooted, setBooted, doc=ugettext_noop("Boot Server") )
  283. defaultPort = property( lambda self: self.server.defaultPort + self.srvid - 1,
  284. doc="Default port for this server instance" )
  285. boundPort = property( lambda self: self.port or self.defaultPort,
  286. doc="The port that this instance actually binds to" )
  287. class Meta:
  288. unique_together = ( ( 'server', 'srvid' ), )
  289. verbose_name = _('Server instance')
  290. verbose_name_plural = _('Server instances')
  291. def __unicode__( self ):
  292. if not self.id:
  293. return u'Murmur "%s" (NOT YET CREATED)' % self.name
  294. return u'Murmur "%s" (%d)' % ( self.name, self.srvid )
  295. def save( self, dontConfigureMurmur=False, *args, **kwargs ):
  296. """ Save the options configured in this model instance not only to Django's database,
  297. but to Murmur as well.
  298. """
  299. if dontConfigureMurmur:
  300. return models.Model.save( self, *args, **kwargs )
  301. if self.id is None:
  302. self.srvid = self.ctl.newServer()
  303. self.ctl.setConf( self.srvid, 'registername', self.name )
  304. if self.addr:
  305. self.ctl.setConf( self.srvid, 'host', self.addr )
  306. else:
  307. self.ctl.setConf( self.srvid, 'host', '' )
  308. if self.port and self.port != self.defaultPort:
  309. self.ctl.setConf( self.srvid, 'port', str(self.port) )
  310. else:
  311. self.ctl.setConf( self.srvid, 'port', '' )
  312. if self.display:
  313. # if self.display contains a port, we're screwed here...
  314. self.ctl.setConf( self.srvid, 'registerhostname', self.display )
  315. elif self.addr:
  316. # If Murmur binds to multiple addresses, use the first
  317. self.ctl.setConf( self.srvid, 'registerhostname', self.addr.split(" ")[0] )
  318. else:
  319. self.ctl.setConf( self.srvid, 'registerhostname', '' )
  320. return models.Model.save( self, *args, **kwargs )
  321. def __init__( self, *args, **kwargs ):
  322. models.Model.__init__( self, *args, **kwargs )
  323. self._channels = None
  324. self._rootchan = None
  325. users_regged = property( lambda self: self.mumbleuser_set.count(), doc="Number of registered users." )
  326. users_online = property( lambda self: len(self.ctl.getPlayers(self.srvid)), doc="Number of online users." )
  327. channel_cnt = property( lambda self: len(self.ctl.getChannels(self.srvid)), doc="Number of channels." )
  328. is_public = property( lambda self: not self.passwd,
  329. doc="False if a password is needed to join this server." )
  330. uptime = property( lambda self: self.ctl.getUptime(self.srvid),
  331. doc="Number of seconds this instance has been running." )
  332. @property
  333. def upsince(self):
  334. """Datetime since when the server is running."""
  335. if self.uptime is not None:
  336. return datetime.datetime.fromtimestamp( float( time() - self.uptime ) )
  337. return None
  338. is_server = True
  339. is_channel = False
  340. is_player = False
  341. ctl = property( lambda self: self.server.ctl )
  342. def getBans( self ):
  343. return self.ctl.getBans( self.srvid )
  344. def removeBan( self, **kwargs ):
  345. return self.ctl.removeBan( self.srvid, **kwargs )
  346. def getConf( self, field ):
  347. return self.ctl.getConf( self.srvid, field )
  348. def setConf( self, field, value ):
  349. return self.ctl.setConf( self.srvid, field, value )
  350. def configureFromMurmur( self ):
  351. conf = self.ctl.getAllConf( self.srvid )
  352. if "registername" not in conf or not conf["registername"]:
  353. self.name = "noname"
  354. else:
  355. self.name = conf["registername"]
  356. if "host" in conf:
  357. self.addr = conf["host"]
  358. else:
  359. self.addr = ""
  360. if "port" in conf:
  361. self.port = int(conf["port"])
  362. else:
  363. self.port = None
  364. if "registerhostname" in conf and conf["registerhostname"] != self.addr:
  365. self.display = conf["registerhostname"]
  366. if ' ' in self.addr and self.display == self.addr.split(' ')[0]:
  367. self.display = ""
  368. else:
  369. self.display = ""
  370. self.save( dontConfigureMurmur=True )
  371. def readUsersFromMurmur( self, verbose=0 ):
  372. if not self.booted:
  373. raise SystemError( "This murmur instance is not currently running, can't sync." )
  374. players = self.ctl.getRegisteredPlayers(self.srvid)
  375. unseen_ids = [rec["mumbleid"]
  376. for rec in MumbleUser.objects.filter( server=self ).values( "mumbleid" )
  377. ]
  378. for idx in players:
  379. playerdata = players[idx]
  380. if playerdata.userid == 0: # Skip SuperUsers
  381. continue
  382. if verbose > 1:
  383. print "Checking User with id %d." % playerdata.userid
  384. if playerdata.userid not in unseen_ids:
  385. if verbose:
  386. print 'Found new User "%s".' % smart_str(playerdata.name)
  387. playerinstance = MumbleUser(
  388. mumbleid = playerdata.userid,
  389. name = playerdata.name,
  390. password = '',
  391. server = self,
  392. owner = None
  393. )
  394. else:
  395. if verbose > 1:
  396. print "User '%s' is already known." % smart_str(playerdata.name)
  397. unseen_ids.remove(playerdata.userid)
  398. playerinstance = MumbleUser.objects.get( server=self, mumbleid=playerdata.userid )
  399. playerinstance.name = playerdata.name
  400. playerinstance.save( dontConfigureMurmur=True )
  401. signals.pre_delete.disconnect( MumbleUser.pre_delete_listener, sender=MumbleUser )
  402. for uid in unseen_ids:
  403. mu = MumbleUser.objects.get( server=self, mumbleid=uid )
  404. if verbose:
  405. print 'Found stale MumbleUser "%s".' % mu.name
  406. mu.delete()
  407. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser )
  408. def isUserAdmin( self, user ):
  409. """ Determine if the given user is an admin on this server. """
  410. if user.is_authenticated():
  411. if user.is_superuser:
  412. return True
  413. try:
  414. return self.mumbleuser_set.get( owner=user ).getAdmin()
  415. except MumbleUser.DoesNotExist:
  416. return False
  417. return False
  418. # Deletion handler
  419. def deleteServer( self ):
  420. """ Delete this server instance from Murmur. """
  421. self.ctl.deleteServer(self.srvid)
  422. @staticmethod
  423. def pre_delete_listener( **kwargs ):
  424. kwargs['instance'].deleteServer()
  425. # Channel list
  426. def getChannels( self ):
  427. """ Query the channels from Murmur and create a tree structure.
  428. Again, this will only be done for the first call to this function. Subsequent
  429. calls will simply return the list created last time.
  430. """
  431. if self._channels is None:
  432. self._channels = {}
  433. chanlist = self.ctl.getChannels(self.srvid).values()
  434. links = {}
  435. # sometimes, ICE seems to return the Channel list in a weird order.
  436. # itercount prevents infinite loops.
  437. itercount = 0
  438. maxiter = len(chanlist) * 3
  439. while len(chanlist) and itercount < maxiter:
  440. itercount += 1
  441. for theChan in chanlist:
  442. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  443. if( theChan.parent == -1 ):
  444. # No parent
  445. self._channels[theChan.id] = mmChannel( self, theChan )
  446. elif theChan.parent in self.channels:
  447. # parent already known
  448. self._channels[theChan.id] = mmChannel( self, theChan, self.channels[theChan.parent] )
  449. else:
  450. continue
  451. chanlist.remove( theChan )
  452. self._channels[theChan.id].serverId = self.id
  453. # process links - if the linked channels are known, link; else save their ids to link later
  454. for linked in theChan.links:
  455. if linked in self._channels:
  456. self._channels[theChan.id].linked.append( self._channels[linked] )
  457. else:
  458. if linked not in links:
  459. links[linked] = list()
  460. links[linked].append( self._channels[theChan.id] )
  461. # check if earlier round trips saved channel ids to be linked to the current channel
  462. if theChan.id in links:
  463. for targetChan in links[theChan.id]:
  464. targetChan.linked.append( self._channels[theChan.id] )
  465. self._channels[0].name = self.name
  466. self.players = {}
  467. for thePlayer in self.ctl.getPlayers(self.srvid).values():
  468. # Players - Fields: 0 = UserID, 6 = ChannelID
  469. self.players[ thePlayer.session ] = mmPlayer( self, thePlayer, self._channels[ thePlayer.channel ] )
  470. self._channels[0].sort()
  471. return self._channels
  472. channels = property( getChannels, doc="A convenience wrapper for getChannels()." )
  473. rootchan = property( lambda self: self.channels[0], doc="A convenience wrapper for getChannels()[0]." )
  474. def getNetloc( self ):
  475. """ Return the address from the Display field (if any), or the server address.
  476. Users from outside a NAT will need to use the Display address to connect
  477. to this server instance.
  478. """
  479. if self.display:
  480. # Find out if this is a sensible address *with port*.
  481. # Regex checks for (hostname OR [ipv6] OR ipv4):port.
  482. if re.match( r'^([^:]+|\[[\da-fA-F]{0,4}(:[\da-fA-F]{0,4})+\]|\d{1,3}(\.\d{1,3}){3}):\d{1,5}$', self.display):
  483. return self.display
  484. else:
  485. daddr = self.display
  486. elif " " in self.addr:
  487. # If Murmur binds to multiple addresses, use the first
  488. daddr = self.addr.split(" ")[0]
  489. else:
  490. daddr = self.addr
  491. if ":" in daddr:
  492. # []-escape IPv6 addresses
  493. daddr = "[%s]" % daddr
  494. if self.boundPort != settings.MUMBLE_DEFAULT_PORT:
  495. return "%s:%d" % (daddr, self.boundPort)
  496. else:
  497. return daddr
  498. netloc = property( getNetloc )
  499. def getURL( self, forUser = None ):
  500. """ Create an URL of the form mumble://username@host:port/ for this server. """
  501. if not self.netloc:
  502. return None
  503. from urlparse import urlunsplit
  504. versionstr = "version=%s" % self.prettyversion
  505. if forUser is not None:
  506. netloc = "%s@%s" % ( forUser.name, self.netloc )
  507. return urlunsplit(( "mumble", netloc, "", versionstr, "" ))
  508. else:
  509. return urlunsplit(( "mumble", self.netloc, "", versionstr, "" ))
  510. connecturl = property( getURL )
  511. version = property( lambda self: self.server.version, doc="The version of Murmur." )
  512. prettyversion = property( lambda self: self.server.prettyversion )
  513. def asDict( self, authed=False ):
  514. return { 'name': self.name,
  515. 'id': self.id,
  516. 'root': self.rootchan.asDict( authed ),
  517. 'x_connecturl': self.connecturl,
  518. 'x_uptime': self.uptime,
  519. }
  520. def asXml( self, authed=False ):
  521. from xml.etree.cElementTree import Element
  522. root = Element( "server",
  523. xmlns="http://mumble.sourceforge.net/Channel_Viewer_Protocol",
  524. id=unicode(self.id), name=self.name
  525. )
  526. root.set( 'x_connecturl', self.connecturl )
  527. root.set( 'x_uptime', unicode(self.uptime) )
  528. root.set( 'xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance" )
  529. root.set( 'xsi:schemaLocation',
  530. "http://bitbucket.org/Svedrin/mumble-django/wiki/channel-viewer-protocol_murmur-%d-%d-%d.xsd" % self.version[:3]
  531. )
  532. self.rootchan.asXml( root, authed )
  533. return root
  534. def asMvXml( self ):
  535. """ Return an XML tree for this server suitable for MumbleViewer-ng. """
  536. from xml.etree.cElementTree import Element
  537. root = Element("root")
  538. self.rootchan.asMvXml(root)
  539. return root
  540. def asMvJson( self ):
  541. """ Return a Dict for this server suitable for MumbleViewer-ng. """
  542. return self.rootchan.asMvJson()
  543. # "server" field protection
  544. def __setattr__( self, name, value ):
  545. if name == 'server':
  546. if self.id is not None and self.server != value:
  547. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  548. models.Model.__setattr__( self, name, value )
  549. def kickUser( self, sessionid, reason="" ):
  550. return self.ctl.kickUser( self.srvid, sessionid, reason )
  551. def banUser( self, sessionid, reason="", duration=0 ):
  552. return self.ctl.addBanForSession( self.srvid, sessionid, reason=reason, duration=duration )
  553. def moveUser( self, sessionid, channelid ):
  554. return self.ctl.moveUser( self.srvid, sessionid, channelid )
  555. def muteUser( self, sessionid, mute=True ):
  556. return self.ctl.muteUser( self.srvid, sessionid, mute )
  557. def deafenUser( self, sessionid, deafen=True ):
  558. return self.ctl.deafenUser( self.srvid, sessionid, deafen )
  559. def sendMessage( self, sessionid, message ):
  560. return self.ctl.sendMessage( self.srvid, sessionid, message )
  561. def sendMessageChannel( self, channelid, tree, message ):
  562. return self.ctl.sendMessageChannel( self.srvid, channelid, tree, message )
  563. def hasUserTexture( self, userid ):
  564. """ Check if this user has a texture set. """
  565. if userid == -1:
  566. return False
  567. try:
  568. self.getUserTexture( userid )
  569. except ValueError:
  570. return False
  571. else:
  572. return True
  573. def getUserTexture( self, userid ):
  574. return self.ctl.getTexture( self.srvid, userid )
  575. def setUserTexture( self, userid, image ):
  576. return self.ctl.setTexture( self.srvid, userid, image )
  577. def addChannel( self, name, parentid ):
  578. regex = (self.channel or self.server.getDefaultConf()['channelname'])
  579. if regex and not re.match( regex, name ):
  580. raise NameError(_("That name is forbidden by the server."))
  581. return self.ctl.addChannel( self.srvid, name, parentid )
  582. def removeChannel( self, channelid ):
  583. return self.ctl.removeChannel( self.srvid, channelid )
  584. def renameChannel( self, channelid, name, description ):
  585. regex = (self.channel or self.server.getDefaultConf()['channelname'])
  586. if regex and not re.match( regex, name ):
  587. raise NameError(_("That name is forbidden by the server."))
  588. return self.ctl.renameChannel( self.srvid, channelid, name, description )
  589. def moveChannel( self, channelid, parentid ):
  590. return self.ctl.moveChannel( self.srvid, channelid, parentid )
  591. def getLog( self, first=0, last=100, filter="" ):
  592. """ Return log entries from ``first`` to ``last`` that contain ``filter`` (if any). """
  593. logentries = self.ctl.getLog( self.srvid, first, last )
  594. if not filter:
  595. return logentries
  596. return [ logentry for logentry in logentries if filter in logentry.txt ]
  597. def mk_registration_property( field, doc="" ):
  598. """ Create a property for the given registration field. """
  599. def get_field( self ):
  600. if field in self.registration:
  601. return self.registration[field]
  602. else:
  603. return None
  604. return property( get_field, doc=doc )
  605. class MumbleUser( models.Model ):
  606. """ Represents a User account in Murmur.
  607. To change an account, simply set the according field in this model and call the save()
  608. method to update the account in Murmur and in Django's database. Note that, once saved
  609. for the first time, the server field must not be changed. Attempting to do this will
  610. result in an AttributeError. To move an account to a new server, recreate it on the
  611. new server and delete the old model.
  612. When you delete an instance of this model, the according user account will be deleted
  613. in Murmur as well, after revoking the user's admin privileges.
  614. """
  615. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 )
  616. name = models.CharField( _('User name and Login'), max_length = 200 )
  617. password = models.CharField( _('Login password'), max_length = 200, blank=True )
  618. server = models.ForeignKey( Mumble, verbose_name=_('Server instance'), related_name="mumbleuser_set" )
  619. owner = models.ForeignKey( User, verbose_name=_('Account owner'), related_name="mumbleuser_set", null=True, blank=True )
  620. comment = mk_registration_property( "comment", doc=ugettext_noop("The user's comment.") )
  621. hash = mk_registration_property( "hash", doc=ugettext_noop("The user's hash.") )
  622. gravatar256 = property( lambda self: self.gravatarUrl( size=256 ) )
  623. gravatar128 = property( lambda self: self.gravatarUrl( size=128 ) )
  624. gravatar64 = property( lambda self: self.gravatarUrl( size=64 ) )
  625. gravatar = property( lambda self: self.gravatarUrl() )
  626. class Meta:
  627. unique_together = ( ( 'server', 'owner' ), ( 'server', 'mumbleid' ) )
  628. verbose_name = _( 'User account' )
  629. verbose_name_plural = _( 'User accounts' )
  630. is_server = False
  631. is_channel = False
  632. is_player = True
  633. def __unicode__( self ):
  634. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % {
  635. 'mu': self.name,
  636. 'srv': self.server,
  637. 'du': self.owner
  638. }
  639. def save( self, dontConfigureMurmur=False, *args, **kwargs ):
  640. """ Save the settings in this model to Murmur. """
  641. if dontConfigureMurmur:
  642. return models.Model.save( self, *args, **kwargs )
  643. ctl = self.server.ctl
  644. if self.owner:
  645. email = self.owner.email
  646. else:
  647. email = settings.DEFAULT_FROM_EMAIL
  648. if self.id is None:
  649. # This is a new user record, so Murmur doesn't know about it yet
  650. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  651. raise ValueError( "Another player already registered that name." )
  652. if not self.password:
  653. raise ValueError( "Cannot register player without a password!" )
  654. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password )
  655. # Update user's registration
  656. elif self.password:
  657. ctl.setRegistration(
  658. self.server.srvid,
  659. self.mumbleid,
  660. self.name,
  661. email,
  662. self.password
  663. )
  664. # Don't save the users' passwords, we don't need them anyway
  665. self.password = ''
  666. # If enabled (and possible), set Gravatar as default Avatar
  667. if not self.hasTexture and settings.USE_GRAVATAR and self.gravatar:
  668. self.setTextureFromUrl( self.gravatar )
  669. return models.Model.save( self, *args, **kwargs )
  670. def __init__( self, *args, **kwargs ):
  671. models.Model.__init__( self, *args, **kwargs )
  672. self._registration = None
  673. # Admin handlers
  674. def getAdmin( self ):
  675. """ Get ACL of root Channel, get the admin group and see if this user is in it. """
  676. if self.mumbleid == -1:
  677. return False
  678. else:
  679. return self.server.rootchan.acl.group_has_member( "admin", self.mumbleid )
  680. def setAdmin( self, value ):
  681. """ Set or revoke this user's membership in the admin group on the root channel. """
  682. if self.mumbleid == -1:
  683. return False
  684. if value:
  685. self.server.rootchan.acl.group_add_member( "admin", self.mumbleid )
  686. else:
  687. self.server.rootchan.acl.group_remove_member( "admin", self.mumbleid )
  688. self.server.rootchan.acl.save()
  689. return value
  690. aclAdmin = property( getAdmin, setAdmin, doc=ugettext_noop('Admin on root channel') )
  691. # Registration fetching
  692. def getRegistration( self ):
  693. """ Retrieve a user's registration from Murmur as a dict. """
  694. if not self._registration:
  695. self._registration = self.server.ctl.getRegistration( self.server.srvid, self.mumbleid )
  696. return self._registration
  697. registration = property( getRegistration )
  698. # Texture handlers
  699. def getTexture( self ):
  700. """ Get the user texture as a PIL Image. """
  701. return self.server.getUserTexture( self.mumbleid )
  702. def setTexture( self, image ):
  703. """ Install the given image as the user's texture. """
  704. self.server.setUserTexture( self.mumbleid, image )
  705. def setTextureFromUrl( self, url, transparency=None ):
  706. """ Retrieve the image at the given URL and set it as my texture. """
  707. img = Image.open( StringIO( urlopen( url ).read() ) )
  708. self.setTexture( img )
  709. def setTextureFromGravatar( self ):
  710. return self.setTextureFromUrl( self.gravatar )
  711. texture = property( getTexture, setTexture,
  712. doc="Get the texture as a PIL Image or set the Image as the texture."
  713. )
  714. def hasTexture( self ):
  715. """ Check if this user has a texture set. """
  716. return self.server.hasUserTexture( self.mumbleid )
  717. def gravatarUrl( self, size=80 ):
  718. """ Get a Gravatar URL for my owner's email adress (if any), or using the User's cert hash.
  719. The size parameter is optional, and defaults to 80 pixels (the default used by Gravatar
  720. if you omit this parameter in the URL).
  721. """
  722. if self.owner and self.owner.email:
  723. from hashlib import md5
  724. return settings.GRAVATAR_URL % { 'hash': md5(self.owner.email).hexdigest(), 'size': size }
  725. elif self.hash:
  726. return settings.GRAVATAR_URL % { 'hash': self.hash, 'size': size }
  727. return None
  728. def getTextureUrl( self ):
  729. """ Get a URL under which the texture can be retrieved. """
  730. from views import showTexture
  731. from django.core.urlresolvers import reverse
  732. return reverse( showTexture, kwargs={ 'server': self.server.id, 'userid': self.id } )
  733. textureUrl = property( getTextureUrl )
  734. # Deletion handler
  735. @staticmethod
  736. def pre_delete_listener( **kwargs ):
  737. kwargs['instance'].unregister()
  738. def unregister( self ):
  739. """ Delete this user account from Murmur. """
  740. if self.getAdmin():
  741. self.setAdmin( False )
  742. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  743. # "server" field protection
  744. def __setattr__( self, name, value ):
  745. if name == 'server':
  746. if self.id is not None and self.server != value:
  747. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  748. models.Model.__setattr__( self, name, value )
  749. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble )
  750. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser )