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