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.

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