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.

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