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.

410 lines
15 KiB

16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright (C) 2009, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  4. *
  5. * Mumble-Django is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This package is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. """
  15. import socket
  16. from PIL import Image
  17. from struct import pack, unpack
  18. from zlib import compress, decompress
  19. from django.utils.translation import ugettext_lazy as _
  20. from django.contrib.auth.models import User
  21. from django.db import models
  22. from django.conf import settings
  23. from mmobjects import *
  24. from mctl import *
  25. class Mumble( models.Model ):
  26. """Represents a Murmur server instance.
  27. All configurable settings are represented by a field in this model. To change the
  28. settings, just update the appropriate field and call the save() method.
  29. To set up a new server instance, instanciate this Model. The first field you should
  30. define is the "dbus" field, which tells the connector subsystem how to connect to
  31. the Murmurd master process. Set this to the appropriate DBus service name or the
  32. Ice proxy string.
  33. When an instance of this model is deleted, the according server instance will be
  34. deleted as well.
  35. """
  36. name = models.CharField( _('Server Name'), max_length = 200 );
  37. dbus = models.CharField( _('DBus or ICE base'), max_length = 200, default = settings.DEFAULT_CONN );
  38. srvid = models.IntegerField( _('Server ID'), editable = False );
  39. addr = models.CharField( _('Server Address'), max_length = 200 );
  40. port = models.IntegerField( _('Server Port'), blank = True, null = True );
  41. url = models.CharField( _('Website URL'), max_length = 200, blank = True );
  42. motd = models.TextField( _('Welcome Message'), blank = True );
  43. passwd = models.CharField( _('Server Password'), max_length = 200, blank = True );
  44. supw = models.CharField( _('Superuser Password'), max_length = 200, blank = True );
  45. users = models.IntegerField( _('Max. Users'), blank = True, null = True );
  46. bwidth = models.IntegerField( _('Bandwidth [Bps]'), blank = True, null = True );
  47. sslcrt = models.TextField( _('SSL Certificate'), blank = True );
  48. sslkey = models.TextField( _('SSL Key'), blank = True );
  49. obfsc = models.BooleanField( _('IP Obfuscation'), default = False );
  50. player = models.CharField( _('Player name regex'), max_length=200, default=r'[-=\w\[\]\{\}\(\)\@\|\.]+' );
  51. channel = models.CharField( _('Channel name regex'), max_length=200, default=r'[ \-=\w\#\[\]\{\}\(\)\@\|]+' );
  52. defchan = models.IntegerField( _('Default channel'), default=0 );
  53. booted = models.BooleanField( _('Boot Server'), default = True );
  54. class Meta:
  55. unique_together = ( ( 'dbus', 'srvid' ), ( 'addr', 'port' ), );
  56. verbose_name = _('Server instance');
  57. verbose_name_plural = _('Server instances');
  58. def __init__( self, *args, **kwargs ):
  59. models.Model.__init__( self, *args, **kwargs );
  60. self._ctl = None;
  61. self._channels = None;
  62. self._rootchan = None;
  63. def __unicode__( self ):
  64. if not self.id:
  65. return u'Murmur "%s" (NOT YET CREATED)' % self.name;
  66. return u'Murmur "%s" (%d)' % ( self.name, self.srvid );
  67. users_regged = property( lambda self: self.mumbleuser_set.count(), None );
  68. users_online = property( lambda self: len(self.ctl.getPlayers(self.srvid)), None );
  69. channel_cnt = property( lambda self: len(self.ctl.getChannels(self.srvid)), None );
  70. is_public = property( lambda self: self.passwd == '', None );
  71. is_server = True;
  72. is_channel = False;
  73. is_player = False;
  74. # Ctl instantiation
  75. def getCtl( self ):
  76. """Instantiate and return a MumbleCtl object for this server.
  77. Only one instance will be created, and reused on subsequent calls.
  78. """
  79. if not self._ctl:
  80. self._ctl = MumbleCtlBase.newInstance( self.dbus );
  81. return self._ctl;
  82. ctl = property( getCtl, None );
  83. def save( self, dontConfigureMurmur=False ):
  84. """
  85. Save the options configured in this model instance not only to Django's database,
  86. but to Murmur as well.
  87. """
  88. if dontConfigureMurmur:
  89. # skip murmur configuration, e.g. because we're inserting models for existing servers.
  90. return models.Model.save( self );
  91. # check if this server already exists, if not call newServer and set my srvid first
  92. if self.id is None:
  93. self.srvid = self.ctl.newServer();
  94. self.ctl.setConf( self.srvid, 'host', socket.gethostbyname( self.addr ) );
  95. self.ctl.setConf( self.srvid, 'registername', self.name );
  96. self.ctl.setConf( self.srvid, 'registerurl', self.url );
  97. self.ctl.setConf( self.srvid, 'welcometext', self.motd );
  98. self.ctl.setConf( self.srvid, 'password', self.passwd );
  99. self.ctl.setConf( self.srvid, 'certificate', self.sslcrt );
  100. self.ctl.setConf( self.srvid, 'key', self.sslkey );
  101. self.ctl.setConf( self.srvid, 'obfuscate', str(self.obfsc).lower() );
  102. self.ctl.setConf( self.srvid, 'playername', self.player );
  103. self.ctl.setConf( self.srvid, 'channelname', self.channel );
  104. self.ctl.setConf( self.srvid, 'defaultchannel', str(self.defchan) );
  105. if self.port is not None:
  106. self.ctl.setConf( self.srvid, 'port', str(self.port) );
  107. else:
  108. self.ctl.setConf( self.srvid, 'port', '' );
  109. if self.users is not None:
  110. self.ctl.setConf( self.srvid, 'users', str(self.users) );
  111. else:
  112. self.ctl.setConf( self.srvid, 'users', '' );
  113. if self.bwidth is not None:
  114. self.ctl.setConf( self.srvid, 'bandwidth', str(self.bwidth) );
  115. else:
  116. self.ctl.setConf( self.srvid, 'bandwidth', '' );
  117. # registerHostname needs to take the port no into account
  118. if self.port and self.port != settings.MUMBLE_DEFAULT_PORT:
  119. self.ctl.setConf( self.srvid, 'registerhostname', "%s:%d" % ( self.addr, self.port ) );
  120. else:
  121. self.ctl.setConf( self.srvid, 'registerhostname', self.addr );
  122. if self.supw:
  123. self.ctl.setSuperUserPassword( self.srvid, self.supw );
  124. self.supw = '';
  125. if self.booted != self.ctl.isBooted( self.srvid ):
  126. if self.booted:
  127. self.ctl.start( self.srvid );
  128. else:
  129. self.ctl.stop( self.srvid );
  130. # Now allow django to save the record set
  131. return models.Model.save( self );
  132. def isUserAdmin( self, user ):
  133. """Determine if the given user is an admin on this server."""
  134. if user.is_authenticated():
  135. try:
  136. return self.mumbleuser_set.get( owner=user ).getAdmin();
  137. except MumbleUser.DoesNotExist:
  138. return False;
  139. return False;
  140. # Deletion handler
  141. def deleteServer( self ):
  142. """Delete this server instance from Murmur."""
  143. self.ctl.deleteServer(self.srvid)
  144. @staticmethod
  145. def pre_delete_listener( **kwargs ):
  146. kwargs['instance'].deleteServer();
  147. # Channel list
  148. def getChannels( self ):
  149. """Query the channels from Murmur and create a tree structure.
  150. Again, this will only be done for the first call to this function. Subsequent
  151. calls will simply return the list created last time.
  152. """
  153. if self._channels is None:
  154. self._channels = {};
  155. chanlist = self.ctl.getChannels(self.srvid);
  156. links = {};
  157. # sometimes, ICE seems to return the Channel list in a weird order.
  158. # itercount prevents infinite loops.
  159. itercount = 0;
  160. maxiter = len(chanlist) * 3;
  161. while len(chanlist) and itercount < maxiter:
  162. itercount += 1;
  163. for theChan in chanlist:
  164. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  165. if( theChan[2] == -1 ):
  166. # No parent
  167. self._channels[theChan[0]] = mmChannel( self, theChan );
  168. elif theChan[2] in self.channels:
  169. # parent already known
  170. self._channels[theChan[0]] = mmChannel( self, theChan, self.channels[theChan[2]] );
  171. else:
  172. continue;
  173. chanlist.remove( theChan );
  174. self._channels[theChan[0]].serverId = self.id;
  175. # process links - if the linked channels are known, link; else save their ids to link later
  176. for linked in theChan[3]:
  177. if linked in self._channels:
  178. self._channels[theChan[0]].linked.append( self._channels[linked] );
  179. else:
  180. if linked not in links:
  181. links[linked] = list();
  182. links[linked].append( self._channels[theChan[0]] );
  183. # check if earlier round trips saved channel ids to be linked to the current channel
  184. if theChan[0] in links:
  185. for targetChan in links[theChan[0]]:
  186. targetChan.linked.append( self._channels[theChan[0]] );
  187. self._channels[0].name = self.name;
  188. self.players = {};
  189. for thePlayer in self.ctl.getPlayers(self.srvid):
  190. # Players - Fields: 0 = UserID, 6 = ChannelID
  191. self.players[ thePlayer[0] ] = mmPlayer( self, thePlayer, self._channels[ thePlayer[6] ] );
  192. self._channels[0].sort();
  193. return self._channels;
  194. channels = property( getChannels, None ); """A convenience wrapper for getChannels()."""
  195. rootchan = property( lambda self: self.channels[0], None ); """A convenience wrapper for getChannels()[0]."""
  196. def getURL( self, forUser = None ):
  197. """Create an URL of the form mumble://username@host:port/ for this server."""
  198. userstr = "";
  199. if forUser is not None:
  200. userstr = "%s@" % forUser.name;
  201. if self.port != settings.MUMBLE_DEFAULT_PORT:
  202. return "mumble://%s%s:%d/" % ( userstr, self.addr, self.port );
  203. return "mumble://%s%s/" % ( userstr, self.addr );
  204. connecturl = property( getURL, None ); """A convenience wrapper for getURL()."""
  205. version = property( lambda self: self.ctl.getVersion(), None ); """Get the version of Murmur."""
  206. class MumbleUser( models.Model ):
  207. """Represents a User account in Murmur.
  208. To change an account, simply set the according field in this model and call the save()
  209. method to update the account in Murmur and in Django's database. Note that, once saved
  210. for the first time, the server field must not be changed. Attempting to do this will
  211. result in an AttributeError. To move an account to a new server, recreate it on the
  212. new server and delete the old model.
  213. When you delete an instance of this model, the according user account will be deleted
  214. in Murmur as well, after revoking the user's admin privileges.
  215. """
  216. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 );
  217. name = models.CharField( _('User name and Login'), max_length = 200 );
  218. password = models.CharField( _('Login password'), max_length = 200, blank=True );
  219. server = models.ForeignKey( Mumble, verbose_name=_('Server instance') );
  220. owner = models.ForeignKey( User, verbose_name=_('Account owner'), null=True, blank=True );
  221. isAdmin = models.BooleanField( _('Admin on root channel'), default = False );
  222. class Meta:
  223. unique_together = ( ( 'server', 'owner' ), );
  224. verbose_name = _( 'User account' );
  225. verbose_name_plural = _( 'User accounts' );
  226. is_server = False;
  227. is_channel = False;
  228. is_player = True;
  229. def __unicode__( self ):
  230. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % { 'mu': self.name, 'srv': self.server, 'du': self.owner };
  231. def save( self, dontConfigureMurmur=False ):
  232. """Save the settings in this model to Murmur."""
  233. if dontConfigureMurmur:
  234. # skip murmur configuration, e.g. because we're inserting models for existing players.
  235. return models.Model.save( self );
  236. # Before the record set is saved, update Murmur via controller.
  237. ctl = self.server.ctl;
  238. if self.owner:
  239. email = self.owner.email;
  240. else:
  241. email = settings.DEFAULT_FROM_EMAIL;
  242. if self.id is None:
  243. # This is a new user record, so Murmur doesn't know about it yet
  244. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  245. raise ValueError( _( "Another player already registered that name." ) );
  246. if not self.password:
  247. raise ValueError( _( "Cannot register player without a password!" ) );
  248. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password );
  249. # Update user's registration
  250. elif self.password:
  251. ctl.setRegistration(
  252. self.server.srvid,
  253. self.mumbleid,
  254. self.name,
  255. email,
  256. self.password
  257. );
  258. # Don't save the users' passwords, we don't need them anyway
  259. self.password = '';
  260. self.setAdmin( self.isAdmin );
  261. # Now allow django to save the record set
  262. return models.Model.save( self );
  263. # Admin handlers
  264. def getAdmin( self ):
  265. """Get ACL of root Channel, get the admin group and see if this user is in it."""
  266. acl = mmACL( 0, self.server.ctl.getACL(self.server.srvid, 0) );
  267. if not hasattr( acl, "admingroup" ):
  268. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  269. return self.mumbleid in acl.admingroup['add'];
  270. def setAdmin( self, value ):
  271. """Set or revoke this user's membership in the admin group on the root channel."""
  272. ctl = self.server.ctl;
  273. acl = mmACL( 0, ctl.getACL(self.server.srvid, 0) );
  274. if not hasattr( acl, "admingroup" ):
  275. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  276. if value != ( self.mumbleid in acl.admingroup['add'] ):
  277. if value:
  278. acl.admingroup['add'].append( self.mumbleid );
  279. else:
  280. acl.admingroup['add'].remove( self.mumbleid );
  281. ctl.setACL(self.server.srvid, acl);
  282. return value;
  283. # Texture handlers
  284. def getTexture( self ):
  285. """Get the user texture as a PIL Image."""
  286. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid);
  287. def setTexture( self, infile ):
  288. """Read an image from the infile and install it as the user's texture."""
  289. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, infile)
  290. # Deletion handler
  291. @staticmethod
  292. def pre_delete_listener( **kwargs ):
  293. kwargs['instance'].unregister();
  294. def unregister( self ):
  295. """Delete this user account from Murmur."""
  296. if self.getAdmin():
  297. self.setAdmin( False );
  298. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  299. # "server" field protection
  300. def __setattr__( self, name, value ):
  301. if name == 'server':
  302. if self.id is not None and self.server != value:
  303. raise AttributeError( _( "This field must not be updated once the record has been saved." ) );
  304. models.Model.__setattr__( self, name, value );
  305. from django.db.models import signals
  306. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  307. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );