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.

836 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 and save this Model.
  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. textlen = mk_config_property( "textmessagelength", ugettext_noop("Maximum length of text messages") )
  175. usersperchannel = mk_config_property( "usersperchannel",ugettext_noop("Users per channel"), get_coerce=int )
  176. certreq = mk_config_bool_property( "certrequired", ugettext_noop("Require Certificate") )
  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. rememchn= mk_config_bool_property( "rememberchannel", ugettext_noop("Remember last channel") )
  181. def get_absolute_url( self ):
  182. from views import show
  183. from django.core.urlresolvers import reverse
  184. return reverse( show, kwargs={ 'server': self.id } )
  185. def getBooted( self ):
  186. if self.id is not None:
  187. if self.server.online:
  188. return self.ctl.isBooted( self.srvid )
  189. else:
  190. return None
  191. else:
  192. return False
  193. def setBooted( self, value ):
  194. if value != self.getBooted():
  195. if value:
  196. self.ctl.start( self.srvid )
  197. else:
  198. self.ctl.stop( self.srvid )
  199. booted = property( getBooted, setBooted, doc=ugettext_noop("Boot Server") )
  200. online = property( getBooted, setBooted, doc=ugettext_noop("Boot Server") )
  201. defaultPort = property( lambda self: self.server.defaultPort + self.srvid - 1,
  202. doc="Default port for this server instance" )
  203. boundPort = property( lambda self: self.port or self.defaultPort,
  204. doc="The port that this instance actually binds to" )
  205. class Meta:
  206. unique_together = ( ( 'server', 'srvid' ), )
  207. verbose_name = _('Server instance')
  208. verbose_name_plural = _('Server instances')
  209. def __unicode__( self ):
  210. if not self.id:
  211. return u'Murmur "%s" (NOT YET CREATED)' % self.name
  212. return u'Murmur "%s" (%d)' % ( self.name, self.srvid )
  213. def save( self, dontConfigureMurmur=False, *args, **kwargs ):
  214. """ Save the options configured in this model instance not only to Django's database,
  215. but to Murmur as well.
  216. """
  217. if dontConfigureMurmur:
  218. return models.Model.save( self, *args, **kwargs )
  219. if self.id is None:
  220. self.srvid = self.ctl.newServer()
  221. self.ctl.setConf( self.srvid, 'registername', self.name )
  222. if self.addr:
  223. self.ctl.setConf( self.srvid, 'host', self.addr )
  224. else:
  225. self.ctl.setConf( self.srvid, 'host', '' )
  226. if self.port and self.port != self.defaultPort:
  227. self.ctl.setConf( self.srvid, 'port', str(self.port) )
  228. else:
  229. self.ctl.setConf( self.srvid, 'port', '' )
  230. if self.netloc:
  231. self.ctl.setConf( self.srvid, 'registerhostname', self.netloc )
  232. else:
  233. self.ctl.setConf( self.srvid, 'registerhostname', '' )
  234. return models.Model.save( self, *args, **kwargs )
  235. def __init__( self, *args, **kwargs ):
  236. models.Model.__init__( self, *args, **kwargs )
  237. self._channels = None
  238. self._rootchan = None
  239. users_regged = property( lambda self: self.mumbleuser_set.count(), doc="Number of registered users." )
  240. users_online = property( lambda self: len(self.ctl.getPlayers(self.srvid)), doc="Number of online users." )
  241. channel_cnt = property( lambda self: len(self.ctl.getChannels(self.srvid)), doc="Number of channels." )
  242. is_public = property( lambda self: not self.passwd,
  243. doc="False if a password is needed to join this server." )
  244. uptime = property( lambda self: self.ctl.getUptime(self.srvid),
  245. doc="Number of seconds this instance has been running." )
  246. @property
  247. def upsince(self):
  248. """Datetime since when the server is running."""
  249. if self.uptime is not None:
  250. return datetime.datetime.fromtimestamp( float( time() - self.uptime ) )
  251. return None
  252. is_server = True
  253. is_channel = False
  254. is_player = False
  255. ctl = property( lambda self: self.server.ctl )
  256. def getBans( self ):
  257. return self.ctl.getBans( self.srvid )
  258. def getConf( self, field ):
  259. return self.ctl.getConf( self.srvid, field )
  260. def setConf( self, field, value ):
  261. return self.ctl.setConf( self.srvid, field, value )
  262. def configureFromMurmur( self ):
  263. conf = self.ctl.getAllConf( self.srvid )
  264. if "registername" not in conf or not conf["registername"]:
  265. self.name = "noname"
  266. else:
  267. self.name = conf["registername"]
  268. if "host" in conf:
  269. self.addr = conf["host"]
  270. else:
  271. self.addr = ""
  272. if "port" in conf:
  273. self.port = int(conf["port"])
  274. else:
  275. self.port = None
  276. if "registerhostname" in conf and conf["registerhostname"] != self.addr:
  277. self.display = conf["registerhostname"]
  278. if ' ' in self.addr and self.display == self.addr.split(' ')[0]:
  279. self.display = ""
  280. else:
  281. self.display = ""
  282. self.save( dontConfigureMurmur=True )
  283. def readUsersFromMurmur( self, verbose=0 ):
  284. if not self.booted:
  285. raise SystemError( "This murmur instance is not currently running, can't sync." )
  286. players = self.ctl.getRegisteredPlayers(self.srvid)
  287. unseen_ids = [rec["mumbleid"]
  288. for rec in MumbleUser.objects.filter( server=self ).values( "mumbleid" )
  289. ]
  290. for idx in players:
  291. playerdata = players[idx]
  292. if playerdata.userid == 0: # Skip SuperUsers
  293. continue
  294. if verbose > 1:
  295. print "Checking User with id %d." % playerdata.userid
  296. if playerdata.userid not in unseen_ids:
  297. if verbose:
  298. print 'Found new User "%s".' % playerdata.name
  299. playerinstance = MumbleUser(
  300. mumbleid = playerdata.userid,
  301. name = playerdata.name,
  302. password = '',
  303. server = self,
  304. owner = None
  305. )
  306. else:
  307. if verbose > 1:
  308. print "User '%s' is already known." % playerdata.name
  309. unseen_ids.remove(playerdata.userid)
  310. playerinstance = MumbleUser.objects.get( server=self, mumbleid=playerdata.userid )
  311. playerinstance.name = playerdata.name
  312. playerinstance.save( dontConfigureMurmur=True )
  313. signals.pre_delete.disconnect( MumbleUser.pre_delete_listener, sender=MumbleUser )
  314. for uid in unseen_ids:
  315. mu = MumbleUser.objects.get( mumbleid=uid )
  316. if verbose:
  317. print 'Found stale MumbleUser "%s".' % mu.name
  318. mu.delete()
  319. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser )
  320. def isUserAdmin( self, user ):
  321. """ Determine if the given user is an admin on this server. """
  322. if user.is_authenticated():
  323. if user.is_superuser:
  324. return True
  325. try:
  326. return self.mumbleuser_set.get( owner=user ).getAdmin()
  327. except MumbleUser.DoesNotExist:
  328. return False
  329. return False
  330. # Deletion handler
  331. def deleteServer( self ):
  332. """ Delete this server instance from Murmur. """
  333. self.ctl.deleteServer(self.srvid)
  334. @staticmethod
  335. def pre_delete_listener( **kwargs ):
  336. kwargs['instance'].deleteServer()
  337. # Channel list
  338. def getChannels( self ):
  339. """ Query the channels from Murmur and create a tree structure.
  340. Again, this will only be done for the first call to this function. Subsequent
  341. calls will simply return the list created last time.
  342. """
  343. if self._channels is None:
  344. self._channels = {}
  345. chanlist = self.ctl.getChannels(self.srvid).values()
  346. links = {}
  347. # sometimes, ICE seems to return the Channel list in a weird order.
  348. # itercount prevents infinite loops.
  349. itercount = 0
  350. maxiter = len(chanlist) * 3
  351. while len(chanlist) and itercount < maxiter:
  352. itercount += 1
  353. for theChan in chanlist:
  354. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  355. if( theChan.parent == -1 ):
  356. # No parent
  357. self._channels[theChan.id] = mmChannel( self, theChan )
  358. elif theChan.parent in self.channels:
  359. # parent already known
  360. self._channels[theChan.id] = mmChannel( self, theChan, self.channels[theChan.parent] )
  361. else:
  362. continue
  363. chanlist.remove( theChan )
  364. self._channels[theChan.id].serverId = self.id
  365. # process links - if the linked channels are known, link; else save their ids to link later
  366. for linked in theChan.links:
  367. if linked in self._channels:
  368. self._channels[theChan.id].linked.append( self._channels[linked] )
  369. else:
  370. if linked not in links:
  371. links[linked] = list()
  372. links[linked].append( self._channels[theChan.id] )
  373. # check if earlier round trips saved channel ids to be linked to the current channel
  374. if theChan.id in links:
  375. for targetChan in links[theChan.id]:
  376. targetChan.linked.append( self._channels[theChan.id] )
  377. self._channels[0].name = self.name
  378. self.players = {}
  379. for thePlayer in self.ctl.getPlayers(self.srvid).values():
  380. # Players - Fields: 0 = UserID, 6 = ChannelID
  381. self.players[ thePlayer.session ] = mmPlayer( self, thePlayer, self._channels[ thePlayer.channel ] )
  382. self._channels[0].sort()
  383. return self._channels
  384. channels = property( getChannels, doc="A convenience wrapper for getChannels()." )
  385. rootchan = property( lambda self: self.channels[0], doc="A convenience wrapper for getChannels()[0]." )
  386. def getNetloc( self ):
  387. """ Return the address from the Display field (if any), or the server address.
  388. Users from outside a NAT will need to use the Display address to connect
  389. to this server instance.
  390. """
  391. if self.display:
  392. # Find out if this is a sensible address *with port*.
  393. # Regex checks for (hostname OR [ipv6] OR ipv4):port.
  394. 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):
  395. return self.display
  396. else:
  397. daddr = self.display
  398. elif " " in self.addr:
  399. # If Murmur binds to multiple addresses, use the first
  400. daddr = self.addr.split(" ")[0]
  401. else:
  402. daddr = self.addr
  403. if ":" in daddr:
  404. # []-escape IPv6 addresses
  405. daddr = "[%s]" % daddr
  406. if self.boundPort != settings.MUMBLE_DEFAULT_PORT:
  407. return "%s:%d" % (daddr, self.boundPort)
  408. else:
  409. return daddr
  410. netloc = property( getNetloc )
  411. def getURL( self, forUser = None ):
  412. """ Create an URL of the form mumble://username@host:port/ for this server. """
  413. if not self.netloc:
  414. return None
  415. from urlparse import urlunsplit
  416. versionstr = "version=%s" % self.prettyversion
  417. if forUser is not None:
  418. netloc = "%s@%s" % ( forUser.name, self.netloc )
  419. return urlunsplit(( "mumble", netloc, "", versionstr, "" ))
  420. else:
  421. return urlunsplit(( "mumble", self.netloc, "", versionstr, "" ))
  422. connecturl = property( getURL )
  423. version = property( lambda self: self.server.version, doc="The version of Murmur." )
  424. prettyversion = property( lambda self: self.server.prettyversion )
  425. def asDict( self, authed=False ):
  426. return { 'name': self.name,
  427. 'id': self.id,
  428. 'root': self.rootchan.asDict( authed ),
  429. 'x_connecturl': self.connecturl,
  430. 'x_uptime': self.uptime,
  431. }
  432. def asXml( self, authed=False ):
  433. from xml.etree.cElementTree import Element
  434. root = Element( "server",
  435. xmlns="http://mumble.sourceforge.net/Channel_Viewer_Protocol",
  436. id=unicode(self.id), name=self.name
  437. )
  438. root.set( 'x_connecturl', self.connecturl )
  439. root.set( 'x_uptime', unicode(self.uptime) )
  440. root.set( 'xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance" )
  441. root.set( 'xsi:schemaLocation',
  442. "http://bitbucket.org/Svedrin/mumble-django/wiki/channel-viewer-protocol_murmur-%d-%d-%d.xsd" % self.version[:3]
  443. )
  444. self.rootchan.asXml( root, authed )
  445. return root
  446. def asMvXml( self ):
  447. """ Return an XML tree for this server suitable for MumbleViewer-ng. """
  448. from xml.etree.cElementTree import Element
  449. root = Element("root")
  450. self.rootchan.asMvXml(root)
  451. return root
  452. def asMvJson( self ):
  453. """ Return a Dict for this server suitable for MumbleViewer-ng. """
  454. return self.rootchan.asMvJson()
  455. # "server" field protection
  456. def __setattr__( self, name, value ):
  457. if name == 'server':
  458. if self.id is not None and self.server != value:
  459. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  460. models.Model.__setattr__( self, name, value )
  461. def kickUser( self, sessionid, reason="" ):
  462. return self.ctl.kickUser( self.srvid, sessionid, reason )
  463. def banUser( self, sessionid, reason="", duration=0 ):
  464. return self.ctl.addBanForSession( self.srvid, sessionid, reason=reason, duration=duration )
  465. def moveUser( self, sessionid, channelid ):
  466. return self.ctl.moveUser( self.srvid, sessionid, channelid )
  467. def muteUser( self, sessionid, mute=True ):
  468. return self.ctl.muteUser( self.srvid, sessionid, mute )
  469. def deafenUser( self, sessionid, deafen=True ):
  470. return self.ctl.deafenUser( self.srvid, sessionid, deafen )
  471. def sendMessage( self, sessionid, message ):
  472. return self.ctl.sendMessage( self.srvid, sessionid, message )
  473. def sendMessageChannel( self, channelid, tree, message ):
  474. return self.ctl.sendMessageChannel( self.srvid, channelid, tree, message )
  475. def hasUserTexture( self, userid ):
  476. """ Check if this user has a texture set. """
  477. if userid == -1:
  478. return False
  479. try:
  480. self.getUserTexture( userid )
  481. except ValueError:
  482. return False
  483. else:
  484. return True
  485. def getUserTexture( self, userid ):
  486. return self.ctl.getTexture( self.srvid, userid )
  487. def setUserTexture( self, userid, image ):
  488. return self.ctl.setTexture( self.srvid, userid, image )
  489. def addChannel( self, name, parentid ):
  490. return self.ctl.addChannel( self.srvid, name, parentid )
  491. def removeChannel( self, channelid ):
  492. return self.ctl.removeChannel( self.srvid, channelid )
  493. def renameChannel( self, channelid, name, description ):
  494. return self.ctl.renameChannel( self.srvid, channelid, name, description )
  495. def moveChannel( self, channelid, parentid ):
  496. return self.ctl.moveChannel( self.srvid, channelid, parentid )
  497. def getLog( self, first=0, last=100, filter="" ):
  498. """ Return log entries from ``first`` to ``last`` that contain ``filter`` (if any). """
  499. logentries = self.ctl.getLog( self.srvid, first, last )
  500. if not filter:
  501. return logentries
  502. return [ logentry for logentry in logentries if filter in logentry.txt ]
  503. def mk_registration_property( field, doc="" ):
  504. """ Create a property for the given registration field. """
  505. def get_field( self ):
  506. if field in self.registration:
  507. return self.registration[field]
  508. else:
  509. return None
  510. return property( get_field, doc=doc )
  511. class MumbleUser( models.Model ):
  512. """ Represents a User account in Murmur.
  513. To change an account, simply set the according field in this model and call the save()
  514. method to update the account in Murmur and in Django's database. Note that, once saved
  515. for the first time, the server field must not be changed. Attempting to do this will
  516. result in an AttributeError. To move an account to a new server, recreate it on the
  517. new server and delete the old model.
  518. When you delete an instance of this model, the according user account will be deleted
  519. in Murmur as well, after revoking the user's admin privileges.
  520. """
  521. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 )
  522. name = models.CharField( _('User name and Login'), max_length = 200 )
  523. password = models.CharField( _('Login password'), max_length = 200, blank=True )
  524. server = models.ForeignKey( Mumble, verbose_name=_('Server instance'), related_name="mumbleuser_set" )
  525. owner = models.ForeignKey( User, verbose_name=_('Account owner'), related_name="mumbleuser_set", null=True, blank=True )
  526. comment = mk_registration_property( "comment", doc=ugettext_noop("The user's comment.") )
  527. hash = mk_registration_property( "hash", doc=ugettext_noop("The user's hash.") )
  528. gravatar256 = property( lambda self: self.gravatarUrl( size=256 ) )
  529. gravatar128 = property( lambda self: self.gravatarUrl( size=128 ) )
  530. gravatar64 = property( lambda self: self.gravatarUrl( size=64 ) )
  531. gravatar = property( lambda self: self.gravatarUrl() )
  532. class Meta:
  533. unique_together = ( ( 'server', 'owner' ), ( 'server', 'mumbleid' ) )
  534. verbose_name = _( 'User account' )
  535. verbose_name_plural = _( 'User accounts' )
  536. is_server = False
  537. is_channel = False
  538. is_player = True
  539. def __unicode__( self ):
  540. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % {
  541. 'mu': self.name,
  542. 'srv': self.server,
  543. 'du': self.owner
  544. }
  545. def save( self, dontConfigureMurmur=False, *args, **kwargs ):
  546. """ Save the settings in this model to Murmur. """
  547. if dontConfigureMurmur:
  548. return models.Model.save( self, *args, **kwargs )
  549. ctl = self.server.ctl
  550. if self.owner:
  551. email = self.owner.email
  552. else:
  553. email = settings.DEFAULT_FROM_EMAIL
  554. if self.id is None:
  555. # This is a new user record, so Murmur doesn't know about it yet
  556. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  557. raise ValueError( "Another player already registered that name." )
  558. if not self.password:
  559. raise ValueError( "Cannot register player without a password!" )
  560. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password )
  561. # Update user's registration
  562. elif self.password:
  563. ctl.setRegistration(
  564. self.server.srvid,
  565. self.mumbleid,
  566. self.name,
  567. email,
  568. self.password
  569. )
  570. # Don't save the users' passwords, we don't need them anyway
  571. self.password = ''
  572. # If enabled (and possible), set Gravatar as default Avatar
  573. if not self.hasTexture and settings.USE_GRAVATAR and self.gravatar:
  574. self.setTextureFromUrl( self.gravatar )
  575. return models.Model.save( self, *args, **kwargs )
  576. def __init__( self, *args, **kwargs ):
  577. models.Model.__init__( self, *args, **kwargs )
  578. self._registration = None
  579. # Admin handlers
  580. def getAdmin( self ):
  581. """ Get ACL of root Channel, get the admin group and see if this user is in it. """
  582. if self.mumbleid == -1:
  583. return False
  584. else:
  585. return self.server.rootchan.acl.group_has_member( "admin", self.mumbleid )
  586. def setAdmin( self, value ):
  587. """ Set or revoke this user's membership in the admin group on the root channel. """
  588. if self.mumbleid == -1:
  589. return False
  590. if value:
  591. self.server.rootchan.acl.group_add_member( "admin", self.mumbleid )
  592. else:
  593. self.server.rootchan.acl.group_remove_member( "admin", self.mumbleid )
  594. self.server.rootchan.acl.save()
  595. return value
  596. aclAdmin = property( getAdmin, setAdmin, doc=ugettext_noop('Admin on root channel') )
  597. # Registration fetching
  598. def getRegistration( self ):
  599. """ Retrieve a user's registration from Murmur as a dict. """
  600. if not self._registration:
  601. self._registration = self.server.ctl.getRegistration( self.server.srvid, self.mumbleid )
  602. return self._registration
  603. registration = property( getRegistration )
  604. # Texture handlers
  605. def getTexture( self ):
  606. """ Get the user texture as a PIL Image. """
  607. return self.server.getUserTexture( self.mumbleid )
  608. def setTexture( self, image ):
  609. """ Install the given image as the user's texture. """
  610. self.server.setUserTexture( self.mumbleid, image )
  611. def setTextureFromUrl( self, url, transparency=None ):
  612. """ Retrieve the image at the given URL and set it as my texture. """
  613. img = Image.open( StringIO( urlopen( url ).read() ) )
  614. self.setTexture( img )
  615. def setTextureFromGravatar( self ):
  616. return self.setTextureFromUrl( self.gravatar )
  617. texture = property( getTexture, setTexture,
  618. doc="Get the texture as a PIL Image or set the Image as the texture."
  619. )
  620. def hasTexture( self ):
  621. """ Check if this user has a texture set. """
  622. return self.server.hasUserTexture( self.mumbleid )
  623. def gravatarUrl( self, size=80 ):
  624. """ Get a Gravatar URL for my owner's email adress (if any), or using the User's cert hash.
  625. The size parameter is optional, and defaults to 80 pixels (the default used by Gravatar
  626. if you omit this parameter in the URL).
  627. """
  628. if self.owner and self.owner.email:
  629. from hashlib import md5
  630. return settings.GRAVATAR_URL % { 'hash': md5(self.owner.email).hexdigest(), 'size': size }
  631. elif self.hash:
  632. return settings.GRAVATAR_URL % { 'hash': self.hash, 'size': size }
  633. return None
  634. def getTextureUrl( self ):
  635. """ Get a URL under which the texture can be retrieved. """
  636. from views import showTexture
  637. from django.core.urlresolvers import reverse
  638. return reverse( showTexture, kwargs={ 'server': self.server.id, 'userid': self.id } )
  639. textureUrl = property( getTextureUrl )
  640. # Deletion handler
  641. @staticmethod
  642. def pre_delete_listener( **kwargs ):
  643. kwargs['instance'].unregister()
  644. def unregister( self ):
  645. """ Delete this user account from Murmur. """
  646. if self.getAdmin():
  647. self.setAdmin( False )
  648. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  649. # "server" field protection
  650. def __setattr__( self, name, value ):
  651. if name == 'server':
  652. if self.id is not None and self.server != value:
  653. raise AttributeError( _( "This field must not be updated once the record has been saved." ) )
  654. models.Model.__setattr__( self, name, value )
  655. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble )
  656. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser )