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.

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