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.

415 lines
16 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
  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, help_text=_("Examples: 'net.sourceforge.mumble.murmur' for DBus or 'Meta:tcp -h 127.0.0.1 -p 6502' for Ice.") );
  38. srvid = models.IntegerField( _('Server ID'), editable = False );
  39. addr = models.CharField( _('Server Address'), max_length = 200, help_text=_("Hostname or IP address to bind to. You should use a hostname here, because it will appear on the global server list.") );
  40. port = models.IntegerField( _('Server Port'), help_text=_("Port number to bind to. Use -1 to auto assign one.") );
  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, help_text=_("Password required to join. Leave empty for public servers.") );
  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, help_text=_("If on, IP adresses of the clients are not logged.") );
  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, help_text=_("Enter the ID of the default channel here. The Channel viewer displays the ID to server admins on the channel detail page."));
  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. if self.port == -1:
  95. self.port = max( [ mm.port for mm in Mumble.objects.all() ] ) + 1;
  96. if self.port < 0 or self.port >= 2**16:
  97. raise ValueError( _("Port number %(portno)d is not within the allowed range %(minrange)d - %(maxrange)d") % {
  98. 'portno': self.port,
  99. 'minrange': 0,
  100. 'maxrange': 2**16,
  101. });
  102. self.ctl.setConf( self.srvid, 'host', socket.gethostbyname( self.addr ) );
  103. self.ctl.setConf( self.srvid, 'port', str(self.port) );
  104. self.ctl.setConf( self.srvid, 'registername', self.name );
  105. self.ctl.setConf( self.srvid, 'registerurl', self.url );
  106. self.ctl.setConf( self.srvid, 'welcometext', self.motd );
  107. self.ctl.setConf( self.srvid, 'password', self.passwd );
  108. self.ctl.setConf( self.srvid, 'certificate', self.sslcrt );
  109. self.ctl.setConf( self.srvid, 'key', self.sslkey );
  110. self.ctl.setConf( self.srvid, 'obfuscate', str(self.obfsc).lower() );
  111. self.ctl.setConf( self.srvid, 'playername', self.player );
  112. self.ctl.setConf( self.srvid, 'channelname', self.channel );
  113. self.ctl.setConf( self.srvid, 'defaultchannel', str(self.defchan) );
  114. if self.users is not None:
  115. self.ctl.setConf( self.srvid, 'users', str(self.users) );
  116. else:
  117. self.ctl.setConf( self.srvid, 'users', '' );
  118. if self.bwidth is not None:
  119. self.ctl.setConf( self.srvid, 'bandwidth', str(self.bwidth) );
  120. else:
  121. self.ctl.setConf( self.srvid, 'bandwidth', '' );
  122. # registerHostname needs to take the port no into account
  123. if self.port and self.port != settings.MUMBLE_DEFAULT_PORT:
  124. self.ctl.setConf( self.srvid, 'registerhostname', "%s:%d" % ( self.addr, self.port ) );
  125. else:
  126. self.ctl.setConf( self.srvid, 'registerhostname', self.addr );
  127. if self.supw:
  128. self.ctl.setSuperUserPassword( self.srvid, self.supw );
  129. self.supw = '';
  130. if self.booted != self.ctl.isBooted( self.srvid ):
  131. if self.booted:
  132. self.ctl.start( self.srvid );
  133. else:
  134. self.ctl.stop( self.srvid );
  135. # Now allow django to save the record set
  136. return models.Model.save( self );
  137. def isUserAdmin( self, user ):
  138. """Determine if the given user is an admin on this server."""
  139. if user.is_authenticated():
  140. try:
  141. return self.mumbleuser_set.get( owner=user ).getAdmin();
  142. except MumbleUser.DoesNotExist:
  143. return False;
  144. return False;
  145. # Deletion handler
  146. def deleteServer( self ):
  147. """Delete this server instance from Murmur."""
  148. self.ctl.deleteServer(self.srvid)
  149. @staticmethod
  150. def pre_delete_listener( **kwargs ):
  151. kwargs['instance'].deleteServer();
  152. # Channel list
  153. def getChannels( self ):
  154. """Query the channels from Murmur and create a tree structure.
  155. Again, this will only be done for the first call to this function. Subsequent
  156. calls will simply return the list created last time.
  157. """
  158. if self._channels is None:
  159. self._channels = {};
  160. chanlist = self.ctl.getChannels(self.srvid);
  161. links = {};
  162. # sometimes, ICE seems to return the Channel list in a weird order.
  163. # itercount prevents infinite loops.
  164. itercount = 0;
  165. maxiter = len(chanlist) * 3;
  166. while len(chanlist) and itercount < maxiter:
  167. itercount += 1;
  168. for theChan in chanlist:
  169. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  170. if( theChan[2] == -1 ):
  171. # No parent
  172. self._channels[theChan[0]] = mmChannel( self, theChan );
  173. elif theChan[2] in self.channels:
  174. # parent already known
  175. self._channels[theChan[0]] = mmChannel( self, theChan, self.channels[theChan[2]] );
  176. else:
  177. continue;
  178. chanlist.remove( theChan );
  179. self._channels[theChan[0]].serverId = self.id;
  180. # process links - if the linked channels are known, link; else save their ids to link later
  181. for linked in theChan[3]:
  182. if linked in self._channels:
  183. self._channels[theChan[0]].linked.append( self._channels[linked] );
  184. else:
  185. if linked not in links:
  186. links[linked] = list();
  187. links[linked].append( self._channels[theChan[0]] );
  188. # check if earlier round trips saved channel ids to be linked to the current channel
  189. if theChan[0] in links:
  190. for targetChan in links[theChan[0]]:
  191. targetChan.linked.append( self._channels[theChan[0]] );
  192. self._channels[0].name = self.name;
  193. self.players = {};
  194. for thePlayer in self.ctl.getPlayers(self.srvid):
  195. # Players - Fields: 0 = UserID, 6 = ChannelID
  196. self.players[ thePlayer[0] ] = mmPlayer( self, thePlayer, self._channels[ thePlayer[6] ] );
  197. self._channels[0].sort();
  198. return self._channels;
  199. channels = property( getChannels, None ); """A convenience wrapper for getChannels()."""
  200. rootchan = property( lambda self: self.channels[0], None ); """A convenience wrapper for getChannels()[0]."""
  201. def getURL( self, forUser = None ):
  202. """Create an URL of the form mumble://username@host:port/ for this server."""
  203. userstr = "";
  204. if forUser is not None:
  205. userstr = "%s@" % forUser.name;
  206. if self.port != settings.MUMBLE_DEFAULT_PORT:
  207. return "mumble://%s%s:%d/" % ( userstr, self.addr, self.port );
  208. return "mumble://%s%s/" % ( userstr, self.addr );
  209. connecturl = property( getURL, None ); """A convenience wrapper for getURL()."""
  210. version = property( lambda self: self.ctl.getVersion(), None ); """Get the version of Murmur."""
  211. class MumbleUser( models.Model ):
  212. """Represents a User account in Murmur.
  213. To change an account, simply set the according field in this model and call the save()
  214. method to update the account in Murmur and in Django's database. Note that, once saved
  215. for the first time, the server field must not be changed. Attempting to do this will
  216. result in an AttributeError. To move an account to a new server, recreate it on the
  217. new server and delete the old model.
  218. When you delete an instance of this model, the according user account will be deleted
  219. in Murmur as well, after revoking the user's admin privileges.
  220. """
  221. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 );
  222. name = models.CharField( _('User name and Login'), max_length = 200 );
  223. password = models.CharField( _('Login password'), max_length = 200, blank=True );
  224. server = models.ForeignKey( Mumble, verbose_name=_('Server instance') );
  225. owner = models.ForeignKey( User, verbose_name=_('Account owner'), null=True, blank=True );
  226. isAdmin = models.BooleanField( _('Admin on root channel'), default = False );
  227. class Meta:
  228. unique_together = ( ( 'server', 'owner' ), );
  229. verbose_name = _( 'User account' );
  230. verbose_name_plural = _( 'User accounts' );
  231. is_server = False;
  232. is_channel = False;
  233. is_player = True;
  234. def __unicode__( self ):
  235. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % { 'mu': self.name, 'srv': self.server, 'du': self.owner };
  236. def save( self, dontConfigureMurmur=False ):
  237. """Save the settings in this model to Murmur."""
  238. if dontConfigureMurmur:
  239. # skip murmur configuration, e.g. because we're inserting models for existing players.
  240. return models.Model.save( self );
  241. # Before the record set is saved, update Murmur via controller.
  242. ctl = self.server.ctl;
  243. if self.owner:
  244. email = self.owner.email;
  245. else:
  246. email = settings.DEFAULT_FROM_EMAIL;
  247. if self.id is None:
  248. # This is a new user record, so Murmur doesn't know about it yet
  249. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  250. raise ValueError( _( "Another player already registered that name." ) );
  251. if not self.password:
  252. raise ValueError( _( "Cannot register player without a password!" ) );
  253. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password );
  254. # Update user's registration
  255. elif self.password:
  256. ctl.setRegistration(
  257. self.server.srvid,
  258. self.mumbleid,
  259. self.name,
  260. email,
  261. self.password
  262. );
  263. # Don't save the users' passwords, we don't need them anyway
  264. self.password = '';
  265. self.setAdmin( self.isAdmin );
  266. # Now allow django to save the record set
  267. return models.Model.save( self );
  268. # Admin handlers
  269. def getAdmin( self ):
  270. """Get ACL of root Channel, get the admin group and see if this user is in it."""
  271. acl = mmACL( 0, self.server.ctl.getACL(self.server.srvid, 0) );
  272. if not hasattr( acl, "admingroup" ):
  273. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  274. return self.mumbleid in acl.admingroup['add'];
  275. def setAdmin( self, value ):
  276. """Set or revoke this user's membership in the admin group on the root channel."""
  277. ctl = self.server.ctl;
  278. acl = mmACL( 0, ctl.getACL(self.server.srvid, 0) );
  279. if not hasattr( acl, "admingroup" ):
  280. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  281. if value != ( self.mumbleid in acl.admingroup['add'] ):
  282. if value:
  283. acl.admingroup['add'].append( self.mumbleid );
  284. else:
  285. acl.admingroup['add'].remove( self.mumbleid );
  286. ctl.setACL(self.server.srvid, acl);
  287. return value;
  288. # Texture handlers
  289. def getTexture( self ):
  290. """Get the user texture as a PIL Image."""
  291. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid);
  292. def setTexture( self, infile ):
  293. """Read an image from the infile and install it as the user's texture."""
  294. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, infile)
  295. # Deletion handler
  296. @staticmethod
  297. def pre_delete_listener( **kwargs ):
  298. kwargs['instance'].unregister();
  299. def unregister( self ):
  300. """Delete this user account from Murmur."""
  301. if self.getAdmin():
  302. self.setAdmin( False );
  303. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  304. # "server" field protection
  305. def __setattr__( self, name, value ):
  306. if name == 'server':
  307. if self.id is not None and self.server != value:
  308. raise AttributeError( _( "This field must not be updated once the record has been saved." ) );
  309. models.Model.__setattr__( self, name, value );
  310. from django.db.models import signals
  311. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  312. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );