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.

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