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.

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