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.

468 lines
18 KiB

15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 years ago
16 years ago
15 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
15 years ago
16 years ago
15 years ago
16 years ago
15 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."), default=settings.MUMBLE_DEFAULT_PORT );
  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 configureFromMurmur( self ):
  136. default = self.ctl.getDefaultConf();
  137. conf = self.ctl.getAllConf( self.srvid );
  138. def find_in_dicts( keys, valueIfNotFound=None ):
  139. if not isinstance( keys, tuple ):
  140. keys = ( keys, );
  141. for keyword in keys:
  142. if keyword in conf:
  143. return conf[keyword];
  144. for keyword in keys:
  145. keyword = keyword.lower();
  146. if keyword in default:
  147. return default[keyword];
  148. return valueIfNotFound;
  149. servername = find_in_dicts( "registername", "noname" );
  150. if not servername:
  151. # RegistrationName was found in the dicts, but is an empty string
  152. servername = "noname";
  153. addr = find_in_dicts( ( "registerhostname", "host" ), "0.0.0.0" );
  154. if addr.find( ':' ) != -1:
  155. # The addr is a hostname which actually contains a port number, but we already got that from
  156. # the port field, so we can simply drop it.
  157. addr = addr.split(':')[0];
  158. self.name = servername;
  159. self.addr = addr;
  160. self.port = find_in_dicts( "port" );
  161. self.url = find_in_dicts( "registerurl" );
  162. self.motd = find_in_dicts( "welcometext" );
  163. self.passwd = find_in_dicts( "password" );
  164. self.supw = '';
  165. self.users = find_in_dicts( "users" );
  166. self.bwidth = find_in_dicts( "bandwidth" );
  167. self.sslcrt = find_in_dicts( "certificate" );
  168. self.sslkey = find_in_dicts( "key" );
  169. self.obfsc = bool( find_in_dicts( 'obfuscate' ) );
  170. self.player = find_in_dicts( 'playername' );
  171. self.channel = find_in_dicts( 'channelname' );
  172. self.defchan = int( find_in_dicts( 'defaultchannel' ) );
  173. self.booted = ( self.srvid in self.ctl.getBootedServers() );
  174. self.save( dontConfigureMurmur=True );
  175. def isUserAdmin( self, user ):
  176. """Determine if the given user is an admin on this server."""
  177. if user.is_authenticated():
  178. try:
  179. return self.mumbleuser_set.get( owner=user ).getAdmin();
  180. except MumbleUser.DoesNotExist:
  181. return False;
  182. return False;
  183. # Deletion handler
  184. def deleteServer( self ):
  185. """Delete this server instance from Murmur."""
  186. self.ctl.deleteServer(self.srvid)
  187. @staticmethod
  188. def pre_delete_listener( **kwargs ):
  189. kwargs['instance'].deleteServer();
  190. # Channel list
  191. def getChannels( self ):
  192. """Query the channels from Murmur and create a tree structure.
  193. Again, this will only be done for the first call to this function. Subsequent
  194. calls will simply return the list created last time.
  195. """
  196. if self._channels is None:
  197. self._channels = {};
  198. chanlist = self.ctl.getChannels(self.srvid);
  199. links = {};
  200. # sometimes, ICE seems to return the Channel list in a weird order.
  201. # itercount prevents infinite loops.
  202. itercount = 0;
  203. maxiter = len(chanlist) * 3;
  204. while len(chanlist) and itercount < maxiter:
  205. itercount += 1;
  206. for theChan in chanlist:
  207. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  208. if( theChan[2] == -1 ):
  209. # No parent
  210. self._channels[theChan[0]] = mmChannel( self, theChan );
  211. elif theChan[2] in self.channels:
  212. # parent already known
  213. self._channels[theChan[0]] = mmChannel( self, theChan, self.channels[theChan[2]] );
  214. else:
  215. continue;
  216. chanlist.remove( theChan );
  217. self._channels[theChan[0]].serverId = self.id;
  218. # process links - if the linked channels are known, link; else save their ids to link later
  219. for linked in theChan[3]:
  220. if linked in self._channels:
  221. self._channels[theChan[0]].linked.append( self._channels[linked] );
  222. else:
  223. if linked not in links:
  224. links[linked] = list();
  225. links[linked].append( self._channels[theChan[0]] );
  226. # check if earlier round trips saved channel ids to be linked to the current channel
  227. if theChan[0] in links:
  228. for targetChan in links[theChan[0]]:
  229. targetChan.linked.append( self._channels[theChan[0]] );
  230. self._channels[0].name = self.name;
  231. self.players = {};
  232. for thePlayer in self.ctl.getPlayers(self.srvid):
  233. # Players - Fields: 0 = UserID, 6 = ChannelID
  234. self.players[ thePlayer[0] ] = mmPlayer( self, thePlayer, self._channels[ thePlayer[6] ] );
  235. self._channels[0].sort();
  236. return self._channels;
  237. channels = property( getChannels, doc="A convenience wrapper for getChannels()." );
  238. rootchan = property( lambda self: self.channels[0], doc="A convenience wrapper for getChannels()[0]." );
  239. def getURL( self, forUser = None ):
  240. """Create an URL of the form mumble://username@host:port/ for this server."""
  241. userstr = "";
  242. if forUser is not None:
  243. userstr = "%s@" % forUser.name;
  244. if self.port != settings.MUMBLE_DEFAULT_PORT:
  245. return "mumble://%s%s:%d/" % ( userstr, self.addr, self.port );
  246. return "mumble://%s%s/" % ( userstr, self.addr );
  247. connecturl = property( getURL, doc="A convenience wrapper for getURL()." );
  248. version = property( lambda self: self.ctl.getVersion(), doc="The version of Murmur." );
  249. class MumbleUser( models.Model ):
  250. """ Represents a User account in Murmur.
  251. To change an account, simply set the according field in this model and call the save()
  252. method to update the account in Murmur and in Django's database. Note that, once saved
  253. for the first time, the server field must not be changed. Attempting to do this will
  254. result in an AttributeError. To move an account to a new server, recreate it on the
  255. new server and delete the old model.
  256. When you delete an instance of this model, the according user account will be deleted
  257. in Murmur as well, after revoking the user's admin privileges.
  258. """
  259. mumbleid = models.IntegerField( _('Mumble player_id'), editable = False, default = -1 );
  260. name = models.CharField( _('User name and Login'), max_length = 200 );
  261. password = models.CharField( _('Login password'), max_length = 200, blank=True );
  262. server = models.ForeignKey( Mumble, verbose_name=_('Server instance') );
  263. owner = models.ForeignKey( User, verbose_name=_('Account owner'), null=True, blank=True );
  264. isAdmin = models.BooleanField( _('Admin on root channel'), default = False );
  265. class Meta:
  266. unique_together = ( ( 'server', 'owner' ), );
  267. verbose_name = _( 'User account' );
  268. verbose_name_plural = _( 'User accounts' );
  269. is_server = False;
  270. is_channel = False;
  271. is_player = True;
  272. def __unicode__( self ):
  273. return _("Mumble user %(mu)s on %(srv)s owned by Django user %(du)s") % { 'mu': self.name, 'srv': self.server, 'du': self.owner };
  274. def save( self, dontConfigureMurmur=False ):
  275. """Save the settings in this model to Murmur."""
  276. if dontConfigureMurmur:
  277. # skip murmur configuration, e.g. because we're inserting models for existing players.
  278. return models.Model.save( self );
  279. # Before the record set is saved, update Murmur via controller.
  280. ctl = self.server.ctl;
  281. if self.owner:
  282. email = self.owner.email;
  283. else:
  284. email = settings.DEFAULT_FROM_EMAIL;
  285. if self.id is None:
  286. # This is a new user record, so Murmur doesn't know about it yet
  287. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  288. raise ValueError( _( "Another player already registered that name." ) );
  289. if not self.password:
  290. raise ValueError( _( "Cannot register player without a password!" ) );
  291. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password );
  292. # Update user's registration
  293. elif self.password:
  294. ctl.setRegistration(
  295. self.server.srvid,
  296. self.mumbleid,
  297. self.name,
  298. email,
  299. self.password
  300. );
  301. # Don't save the users' passwords, we don't need them anyway
  302. self.password = '';
  303. self.setAdmin( self.isAdmin );
  304. # Now allow django to save the record set
  305. return models.Model.save( self );
  306. # Admin handlers
  307. def getAdmin( self ):
  308. """Get ACL of root Channel, get the admin group and see if this user is in it."""
  309. acl = mmACL( 0, self.server.ctl.getACL(self.server.srvid, 0) );
  310. if not hasattr( acl, "admingroup" ):
  311. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  312. return self.mumbleid in acl.admingroup['add'];
  313. def setAdmin( self, value ):
  314. """Set or revoke this user's membership in the admin group on the root channel."""
  315. ctl = self.server.ctl;
  316. acl = mmACL( 0, ctl.getACL(self.server.srvid, 0) );
  317. if not hasattr( acl, "admingroup" ):
  318. raise ReferenceError( _( "The admin group was not found in the ACL's groups list!" ) );
  319. if value != ( self.mumbleid in acl.admingroup['add'] ):
  320. if value:
  321. acl.admingroup['add'].append( self.mumbleid );
  322. else:
  323. acl.admingroup['add'].remove( self.mumbleid );
  324. ctl.setACL(self.server.srvid, acl);
  325. return value;
  326. # Texture handlers
  327. def getTexture( self ):
  328. """Get the user texture as a PIL Image."""
  329. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid);
  330. def setTexture( self, infile ):
  331. """Read an image from the infile and install it as the user's texture."""
  332. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, infile)
  333. def hasTexture( self ):
  334. try:
  335. self.getTexture();
  336. except ValueError:
  337. return False;
  338. else:
  339. return True;
  340. # Deletion handler
  341. @staticmethod
  342. def pre_delete_listener( **kwargs ):
  343. kwargs['instance'].unregister();
  344. def unregister( self ):
  345. """Delete this user account from Murmur."""
  346. if self.getAdmin():
  347. self.setAdmin( False );
  348. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  349. # "server" field protection
  350. def __setattr__( self, name, value ):
  351. if name == 'server':
  352. if self.id is not None and self.server != value:
  353. raise AttributeError( _( "This field must not be updated once the record has been saved." ) );
  354. models.Model.__setattr__( self, name, value );
  355. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  356. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );