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.

744 lines
25 KiB

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