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.

774 lines
30 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 getConf( self, field ):
  252. return self.ctl.getConf( self.srvid, field )
  253. def setConf( self, field, value ):
  254. return self.ctl.setConf( self.srvid, field, value )
  255. def configureFromMurmur( self ):
  256. conf = self.ctl.getAllConf( self.srvid )
  257. if "registername" not in conf or not conf["registername"]:
  258. self.name = "noname"
  259. else:
  260. self.name = conf["registername"]
  261. if "host" in conf:
  262. self.addr = conf["host"]
  263. else:
  264. self.addr = ""
  265. if "port" in conf:
  266. self.port = int(conf["port"])
  267. else:
  268. self.port = None
  269. if "registerhostname" in conf and conf["registerhostname"] != self.addr:
  270. self.display = conf["registerhostname"]
  271. if ' ' in self.addr and self.display == self.addr.split(' ')[0]:
  272. self.display = ""
  273. else:
  274. self.display = ""
  275. self.save( dontConfigureMurmur=True )
  276. def readUsersFromMurmur( self, verbose=0 ):
  277. if not self.booted:
  278. raise SystemError( "This murmur instance is not currently running, can't sync." )
  279. players = self.ctl.getRegisteredPlayers(self.srvid)
  280. known_ids = [rec["mumbleid"]
  281. for rec in MumbleUser.objects.filter( server=self ).values( "mumbleid" )
  282. ]
  283. for idx in players:
  284. playerdata = players[idx]
  285. if playerdata.userid == 0: # Skip SuperUsers
  286. continue
  287. if verbose > 1:
  288. print "Checking Player with id %d." % playerdata.userid
  289. if playerdata.userid not in known_ids:
  290. if verbose:
  291. print 'Found new Player "%s".' % playerdata.name
  292. playerinstance = MumbleUser(
  293. mumbleid = playerdata.userid,
  294. name = playerdata.name,
  295. password = '',
  296. server = self,
  297. owner = None
  298. )
  299. else:
  300. if verbose > 1:
  301. print "Player '%s' is already known." % playerdata.name
  302. playerinstance = MumbleUser.objects.get( server=self, mumbleid=playerdata.userid )
  303. playerinstance.name = playerdata.name
  304. playerinstance.save( dontConfigureMurmur=True )
  305. def isUserAdmin( self, user ):
  306. """ Determine if the given user is an admin on this server. """
  307. if user.is_authenticated():
  308. if user.is_superuser:
  309. return True
  310. try:
  311. return self.mumbleuser_set.get( owner=user ).getAdmin()
  312. except MumbleUser.DoesNotExist:
  313. return False
  314. return False
  315. # Deletion handler
  316. def deleteServer( self ):
  317. """ Delete this server instance from Murmur. """
  318. self.ctl.deleteServer(self.srvid)
  319. @staticmethod
  320. def pre_delete_listener( **kwargs ):
  321. kwargs['instance'].deleteServer()
  322. # Channel list
  323. def getChannels( self ):
  324. """ Query the channels from Murmur and create a tree structure.
  325. Again, this will only be done for the first call to this function. Subsequent
  326. calls will simply return the list created last time.
  327. """
  328. if self._channels is None:
  329. self._channels = {}
  330. chanlist = self.ctl.getChannels(self.srvid).values()
  331. links = {}
  332. # sometimes, ICE seems to return the Channel list in a weird order.
  333. # itercount prevents infinite loops.
  334. itercount = 0
  335. maxiter = len(chanlist) * 3
  336. while len(chanlist) and itercount < maxiter:
  337. itercount += 1
  338. for theChan in chanlist:
  339. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  340. if( theChan.parent == -1 ):
  341. # No parent
  342. self._channels[theChan.id] = mmChannel( self, theChan )
  343. elif theChan.parent in self.channels:
  344. # parent already known
  345. self._channels[theChan.id] = mmChannel( self, theChan, self.channels[theChan.parent] )
  346. else:
  347. continue
  348. chanlist.remove( theChan )
  349. self._channels[theChan.id].serverId = self.id
  350. # process links - if the linked channels are known, link; else save their ids to link later
  351. for linked in theChan.links:
  352. if linked in self._channels:
  353. self._channels[theChan.id].linked.append( self._channels[linked] )
  354. else:
  355. if linked not in links:
  356. links[linked] = list()
  357. links[linked].append( self._channels[theChan.id] )
  358. # check if earlier round trips saved channel ids to be linked to the current channel
  359. if theChan.id in links:
  360. for targetChan in links[theChan.id]:
  361. targetChan.linked.append( self._channels[theChan.id] )
  362. self._channels[0].name = self.name
  363. self.players = {}
  364. for thePlayer in self.ctl.getPlayers(self.srvid).values():
  365. # Players - Fields: 0 = UserID, 6 = ChannelID
  366. self.players[ thePlayer.session ] = mmPlayer( self, thePlayer, self._channels[ thePlayer.channel ] )
  367. self._channels[0].sort()
  368. return self._channels
  369. channels = property( getChannels, doc="A convenience wrapper for getChannels()." )
  370. rootchan = property( lambda self: self.channels[0], doc="A convenience wrapper for getChannels()[0]." )
  371. def getNetloc( self ):
  372. """ Return the address from the Display field (if any), or the server address.
  373. Users from outside a NAT will need to use the Display address to connect
  374. to this server instance.
  375. """
  376. if self.display:
  377. # Find out if this is a sensible address *with port*.
  378. # Regex checks for (hostname OR [ipv6] OR ipv4):port.
  379. 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):
  380. return self.display
  381. else:
  382. daddr = self.display
  383. elif " " in self.addr:
  384. # If Murmur binds to multiple addresses, use the first
  385. daddr = self.addr.split(" ")[0]
  386. else:
  387. daddr = self.addr
  388. if ":" in daddr:
  389. # []-escape IPv6 addresses
  390. daddr = "[%s]" % daddr
  391. if self.boundPort != settings.MUMBLE_DEFAULT_PORT:
  392. return "%s:%d" % (daddr, self.boundPort)
  393. else:
  394. return daddr
  395. netloc = property( getNetloc )
  396. def getURL( self, forUser = None ):
  397. """ Create an URL of the form mumble://username@host:port/ for this server. """
  398. if not self.netloc:
  399. return None
  400. from urlparse import urlunsplit
  401. versionstr = "version=%s" % self.prettyversion
  402. if forUser is not None:
  403. netloc = "%s@%s" % ( forUser.name, self.netloc )
  404. return urlunsplit(( "mumble", netloc, "", versionstr, "" ))
  405. else:
  406. return urlunsplit(( "mumble", self.netloc, "", versionstr, "" ))
  407. connecturl = property( getURL )
  408. version = property( lambda self: self.server.version, doc="The version of Murmur." )
  409. prettyversion = property( lambda self: self.server.prettyversion )
  410. def asDict( self, authed=False ):
  411. return { 'name': self.name,
  412. 'id': self.id,
  413. 'root': self.rootchan.asDict( authed ),
  414. 'x_connecturl': self.connecturl,
  415. 'x_uptime': self.uptime,
  416. }
  417. def asXml( self, authed=False ):
  418. from xml.etree.cElementTree import Element
  419. root = Element( "server",
  420. xmlns="http://mumble.sourceforge.net/Channel_Viewer_Protocol",
  421. id=unicode(self.id), name=self.name
  422. )
  423. root.set( 'x_connecturl', self.connecturl )
  424. root.set( 'x_uptime', unicode(self.uptime) )
  425. root.set( 'xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance" )
  426. root.set( 'xsi:schemaLocation',
  427. "http://bitbucket.org/Svedrin/mumble-django/wiki/channel-viewer-protocol_murmur-%d-%d-%d.xsd" % self.version[:3]
  428. )
  429. self.rootchan.asXml( root, authed )
  430. return root
  431. def asMvXml( self ):
  432. """ Return an XML tree for this server suitable for MumbleViewer-ng. """
  433. from xml.etree.cElementTree import Element
  434. root = Element("root")
  435. self.rootchan.asMvXml(root)
  436. return root
  437. def asMvJson( self ):
  438. """ Return a Dict for this server suitable for MumbleViewer-ng. """
  439. return self.rootchan.asMvJson()
  440. # "server" field protection
  441. def __setattr__( self, name, value ):
  442. if name == 'server':
  443. if self.id is not None and self.server != value:
  444. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  445. models.Model.__setattr__( self, name, value )
  446. def kickUser( self, sessionid, reason="" ):
  447. return self.ctl.kickUser( self.srvid, sessionid, reason )
  448. def banUser( self, sessionid, reason="" ):
  449. return self.ctl.addBanForSession( self.srvid, sessionid, reason=reason )
  450. def getLog( self, first=0, last=100, filter="" ):
  451. """ Return log entries from ``first`` to ``last`` that contain ``filter`` (if any). """
  452. logentries = self.ctl.getLog( self.srvid, first, last )
  453. if not filter:
  454. return logentries
  455. return [ logentry for logentry in logentries if filter in logentry.txt ]
  456. def mk_registration_property( field, doc="" ):
  457. """ Create a property for the given registration field. """
  458. def get_field( self ):
  459. if field in self.registration:
  460. return self.registration[field]
  461. else:
  462. return None
  463. return property( get_field, doc=doc )
  464. class MumbleUser( models.Model ):
  465. """ Represents a User account in Murmur.
  466. To change an account, simply set the according field in this model and call the save()
  467. method to update the account in Murmur and in Django's database. Note that, once saved
  468. for the first time, the server field must not be changed. Attempting to do this will
  469. result in an AttributeError. To move an account to a new server, recreate it on the
  470. new server and delete the old model.
  471. When you delete an instance of this model, the according user account will be deleted
  472. in Murmur as well, after revoking the user's admin privileges.
  473. """
  474. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 )
  475. name = models.CharField( _('User name and Login'), max_length = 200 )
  476. password = models.CharField( _('Login password'), max_length = 200, blank=True )
  477. server = models.ForeignKey( Mumble, verbose_name=_('Server instance'), related_name="mumbleuser_set" )
  478. owner = models.ForeignKey( User, verbose_name=_('Account owner'), related_name="mumbleuser_set", null=True, blank=True )
  479. comment = mk_registration_property( "comment", doc=ugettext_noop("The user's comment.") )
  480. hash = mk_registration_property( "hash", doc=ugettext_noop("The user's hash.") )
  481. gravatar256 = property( lambda self: self.gravatarUrl( size=256 ) )
  482. gravatar128 = property( lambda self: self.gravatarUrl( size=128 ) )
  483. gravatar64 = property( lambda self: self.gravatarUrl( size=64 ) )
  484. gravatar = property( lambda self: self.gravatarUrl() )
  485. class Meta:
  486. unique_together = ( ( 'server', 'owner' ), ( 'server', 'mumbleid' ) )
  487. verbose_name = _( 'User account' )
  488. verbose_name_plural = _( 'User accounts' )
  489. is_server = False
  490. is_channel = False
  491. is_player = True
  492. def __unicode__( self ):
  493. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % {
  494. 'mu': self.name,
  495. 'srv': self.server,
  496. 'du': self.owner
  497. }
  498. def save( self, dontConfigureMurmur=False, *args, **kwargs ):
  499. """ Save the settings in this model to Murmur. """
  500. if dontConfigureMurmur:
  501. return models.Model.save( self, *args, **kwargs )
  502. ctl = self.server.ctl
  503. if self.owner:
  504. email = self.owner.email
  505. else:
  506. email = settings.DEFAULT_FROM_EMAIL
  507. if self.id is None:
  508. # This is a new user record, so Murmur doesn't know about it yet
  509. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  510. raise ValueError( _( "Another player already registered that name." ) )
  511. if not self.password:
  512. raise ValueError( _( "Cannot register player without a password!" ) )
  513. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password )
  514. # Update user's registration
  515. elif self.password:
  516. ctl.setRegistration(
  517. self.server.srvid,
  518. self.mumbleid,
  519. self.name,
  520. email,
  521. self.password
  522. )
  523. # Don't save the users' passwords, we don't need them anyway
  524. self.password = ''
  525. # If enabled (and possible), set Gravatar as default Avatar
  526. if not self.hasTexture and settings.USE_GRAVATAR and self.gravatar:
  527. self.setTextureFromUrl( self.gravatar )
  528. return models.Model.save( self, *args, **kwargs )
  529. def __init__( self, *args, **kwargs ):
  530. models.Model.__init__( self, *args, **kwargs )
  531. self._registration = None
  532. # Admin handlers
  533. def getAdmin( self ):
  534. """ Get ACL of root Channel, get the admin group and see if this user is in it. """
  535. if self.mumbleid == -1:
  536. return False
  537. else:
  538. return self.server.rootchan.acl.group_has_member( "admin", self.mumbleid )
  539. def setAdmin( self, value ):
  540. """ Set or revoke this user's membership in the admin group on the root channel. """
  541. if self.mumbleid == -1:
  542. return False
  543. if value:
  544. self.server.rootchan.acl.group_add_member( "admin", self.mumbleid )
  545. else:
  546. self.server.rootchan.acl.group_remove_member( "admin", self.mumbleid )
  547. self.server.rootchan.acl.save()
  548. return value
  549. aclAdmin = property( getAdmin, setAdmin, doc=ugettext_noop('Admin on root channel') )
  550. # Registration fetching
  551. def getRegistration( self ):
  552. """ Retrieve a user's registration from Murmur as a dict. """
  553. if not self._registration:
  554. self._registration = self.server.ctl.getRegistration( self.server.srvid, self.mumbleid )
  555. return self._registration
  556. registration = property( getRegistration )
  557. # Texture handlers
  558. def getTexture( self ):
  559. """ Get the user texture as a PIL Image. """
  560. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid)
  561. def setTexture( self, image ):
  562. """ Install the given image as the user's texture. """
  563. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, image)
  564. def setTextureFromUrl( self, url, transparency=None ):
  565. """ Retrieve the image at the given URL and set it as my texture. """
  566. img = Image.open( StringIO( urlopen( url ).read() ) )
  567. self.setTexture( img )
  568. texture = property( getTexture, setTexture,
  569. doc="Get the texture as a PIL Image or set the Image as the texture."
  570. )
  571. def hasTexture( self ):
  572. """ Check if this user has a texture set. """
  573. try:
  574. self.getTexture()
  575. except ValueError:
  576. return False
  577. else:
  578. return True
  579. def gravatarUrl( self, size=80 ):
  580. """ Get a Gravatar URL for my owner's email adress (if any), or using the User's cert hash.
  581. The size parameter is optional, and defaults to 80 pixels (the default used by Gravatar
  582. if you omit this parameter in the URL).
  583. """
  584. if self.owner and self.owner.email:
  585. from hashlib import md5
  586. return settings.GRAVATAR_URL % { 'hash': md5(self.owner.email).hexdigest(), 'size': size }
  587. elif self.hash:
  588. return settings.GRAVATAR_URL % { 'hash': self.hash, 'size': size }
  589. return None
  590. def getTextureUrl( self ):
  591. """ Get a URL under which the texture can be retrieved. """
  592. from views import showTexture
  593. from django.core.urlresolvers import reverse
  594. return reverse( showTexture, kwargs={ 'server': self.server.id, 'userid': self.id } )
  595. textureUrl = property( getTextureUrl )
  596. # Deletion handler
  597. @staticmethod
  598. def pre_delete_listener( **kwargs ):
  599. kwargs['instance'].unregister()
  600. def unregister( self ):
  601. """ Delete this user account from Murmur. """
  602. if self.getAdmin():
  603. self.setAdmin( False )
  604. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  605. # "server" field protection
  606. def __setattr__( self, name, value ):
  607. if name == 'server':
  608. if self.id is not None and self.server != value:
  609. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  610. models.Model.__setattr__( self, name, value )
  611. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble )
  612. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser )