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.

753 lines
25 KiB

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