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.

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