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.

732 lines
24 KiB

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