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.

357 lines
12 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
  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.contrib.auth.models import User
  20. from django.db import models
  21. from django.conf import settings
  22. from mmobjects import *
  23. from mctl import *
  24. class Mumble( models.Model ):
  25. name = models.CharField( 'Server Name', max_length = 200 );
  26. dbus = models.CharField( 'DBus or ICE base', max_length = 200, default = settings.DEFAULT_CONN );
  27. srvid = models.IntegerField( 'Server ID', editable = False );
  28. addr = models.CharField( 'Server Address', max_length = 200 );
  29. port = models.IntegerField( 'Server Port', blank = True, null = True );
  30. url = models.CharField( 'Website URL', max_length = 200, blank = True );
  31. motd = models.TextField( 'Welcome Message', blank = True );
  32. passwd = models.CharField( 'Server Password', max_length = 200, blank = True );
  33. supw = models.CharField( 'Superuser Password', max_length = 200, blank = True );
  34. users = models.IntegerField( 'Max. Users', blank = True, null = True );
  35. bwidth = models.IntegerField( 'Bandwidth [Bps]', blank = True, null = True );
  36. sslcrt = models.TextField( 'SSL Certificate', blank = True );
  37. sslkey = models.TextField( 'SSL Key', blank = True );
  38. obfsc = models.BooleanField( 'IP Obfuscation', default = False );
  39. player = models.CharField( 'Player name regex', max_length=200, default=r'[-=\w\[\]\{\}\(\)\@\|\.]+' );
  40. channel= models.CharField( 'Channel name regex', max_length=200, default=r'[ \-=\w\#\[\]\{\}\(\)\@\|]+' );
  41. defchan= models.IntegerField( 'Default channel', default=0 );
  42. booted = models.BooleanField( 'Boot Server', default = True );
  43. class Meta:
  44. unique_together = ( ( 'dbus', 'srvid' ), ( 'addr', 'port' ), );
  45. def __init__( self, *args, **kwargs ):
  46. models.Model.__init__( self, *args, **kwargs );
  47. self._ctl = None;
  48. self._channels = None;
  49. self._rootchan = None;
  50. def __unicode__( self ):
  51. return u'Murmur "%s" (%d)' % ( self.name, self.srvid );
  52. is_server = True;
  53. is_channel = False;
  54. is_player = False;
  55. # Ctl instantiation
  56. def getCtl( self ):
  57. if not self._ctl:
  58. self._ctl = MumbleCtlBase.newInstance( self.dbus );
  59. return self._ctl;
  60. ctl = property( getCtl, None );
  61. def save( self, dontConfigureMurmur=False ):
  62. if dontConfigureMurmur:
  63. # skip murmur configuration, e.g. because we're inserting models for existing servers.
  64. return models.Model.save( self );
  65. # check if this server already exists, if not call newServer and set my srvid first
  66. if self.id is None:
  67. self.srvid = self.ctl.newServer();
  68. self.ctl.setConf( self.srvid, 'host', socket.gethostbyname( self.addr ) );
  69. self.ctl.setConf( self.srvid, 'registername', self.name );
  70. self.ctl.setConf( self.srvid, 'registerurl', self.url );
  71. self.ctl.setConf( self.srvid, 'welcometext', self.motd );
  72. self.ctl.setConf( self.srvid, 'password', self.passwd );
  73. self.ctl.setConf( self.srvid, 'certificate', self.sslcrt );
  74. self.ctl.setConf( self.srvid, 'key', self.sslkey );
  75. self.ctl.setConf( self.srvid, 'obfuscate', str(self.obfsc).lower() );
  76. self.ctl.setConf( self.srvid, 'playername', self.player );
  77. self.ctl.setConf( self.srvid, 'channelname', self.channel );
  78. self.ctl.setConf( self.srvid, 'defaultchannel', str(self.defchan) );
  79. if self.port is not None:
  80. self.ctl.setConf( self.srvid, 'port', str(self.port) );
  81. else:
  82. self.ctl.setConf( self.srvid, 'port', '' );
  83. if self.users is not None:
  84. self.ctl.setConf( self.srvid, 'users', str(self.users) );
  85. else:
  86. self.ctl.setConf( self.srvid, 'users', '' );
  87. if self.bwidth is not None:
  88. self.ctl.setConf( self.srvid, 'bandwidth', str(self.bwidth) );
  89. else:
  90. self.ctl.setConf( self.srvid, 'bandwidth', '' );
  91. # registerHostname needs to take the port no into account
  92. if self.port and self.port != settings.MUMBLE_DEFAULT_PORT:
  93. self.ctl.setConf( self.srvid, 'registerhostname', "%s:%d" % ( self.addr, self.port ) );
  94. else:
  95. self.ctl.setConf( self.srvid, 'registerhostname', self.addr );
  96. if self.supw:
  97. self.ctl.setSuperUserPassword( self.srvid, self.supw );
  98. self.supw = '';
  99. if self.booted != self.ctl.isBooted( self.srvid ):
  100. if self.booted:
  101. self.ctl.start( self.srvid );
  102. else:
  103. self.ctl.stop( self.srvid );
  104. # Now allow django to save the record set
  105. return models.Model.save( self );
  106. def isUserAdmin( self, user ):
  107. if user.is_authenticated():
  108. try:
  109. return self.mumbleuser_set.get( owner=user ).getAdmin();
  110. except MumbleUser.DoesNotExist:
  111. return False;
  112. return False;
  113. # Deletion handler
  114. def deleteServer( self ):
  115. self.ctl.deleteServer(self.srvid)
  116. @staticmethod
  117. def pre_delete_listener( **kwargs ):
  118. kwargs['instance'].deleteServer();
  119. # Channel list
  120. def getChannels( self ):
  121. if self._channels is None:
  122. self._channels = {};
  123. chanlist = self.ctl.getChannels(self.srvid);
  124. links = {};
  125. # sometimes, ICE seems to return the Channel list in a weird order.
  126. # itercount prevents infinite loops.
  127. itercount = 0;
  128. maxiter = len(chanlist) * 3;
  129. while len(chanlist) and itercount < maxiter:
  130. itercount += 1;
  131. for theChan in chanlist:
  132. # Channels - Fields: 0 = ID, 1 = Name, 2 = Parent-ID, 3 = Links
  133. if( theChan[2] == -1 ):
  134. # No parent
  135. self._channels[theChan[0]] = mmChannel( self, theChan );
  136. elif theChan[2] in self.channels:
  137. # parent already known
  138. self._channels[theChan[0]] = mmChannel( self, theChan, self.channels[theChan[2]] );
  139. else:
  140. continue;
  141. chanlist.remove( theChan );
  142. self._channels[theChan[0]].serverId = self.id;
  143. # process links - if the linked channels are known, link; else save their ids to link later
  144. for linked in theChan[3]:
  145. if linked in self._channels:
  146. self._channels[theChan[0]].linked.append( self._channels[linked] );
  147. else:
  148. if linked not in links:
  149. links[linked] = list();
  150. links[linked].append( self._channels[theChan[0]] );
  151. # check if earlier round trips saved channel ids to be linked to the current channel
  152. if theChan[0] in links:
  153. for targetChan in links[theChan[0]]:
  154. targetChan.linked.append( self._channels[theChan[0]] );
  155. self._channels[0].name = self.name;
  156. self.players = {};
  157. for thePlayer in self.ctl.getPlayers(self.srvid):
  158. # Players - Fields: 0 = UserID, 6 = ChannelID
  159. self.players[ thePlayer[0] ] = mmPlayer( self, thePlayer, self._channels[ thePlayer[6] ] );
  160. self._channels[0].sort();
  161. return self._channels;
  162. channels = property( getChannels, None );
  163. rootchan = property( lambda self: self.channels[0], None );
  164. def getURL( self, forUser = None ):
  165. # mumble://username@host:port/
  166. userstr = "";
  167. if forUser is not None:
  168. userstr = "%s@" % forUser.name;
  169. if self.port != settings.MUMBLE_DEFAULT_PORT:
  170. return "mumble://%s%s:%d/" % ( userstr, self.addr, self.port );
  171. return "mumble://%s%s/" % ( userstr, self.addr );
  172. connecturl = property( getURL, None );
  173. version = property( lambda self: self.ctl.getVersion(), None );
  174. class MumbleUser( models.Model ):
  175. mumbleid = models.IntegerField( 'Mumble player_id', editable = False, default = -1 );
  176. name = models.CharField( 'User name and Login', max_length = 200 );
  177. password = models.CharField( 'Login password', max_length = 200, blank=True );
  178. server = models.ForeignKey( Mumble );
  179. owner = models.ForeignKey( User, null=True, blank=True );
  180. isAdmin = models.BooleanField( 'Admin on root channel', default = False );
  181. class Meta:
  182. unique_together = ( ( 'server', 'owner' ), );
  183. is_server = False;
  184. is_channel = False;
  185. is_player = True;
  186. def __unicode__( self ):
  187. return u"Mumble user %s on %s owned by Django user %s" % ( self.name, self.server, self.owner );
  188. def save( self, dontConfigureMurmur=False ):
  189. if dontConfigureMurmur:
  190. # skip murmur configuration, e.g. because we're inserting models for existing players.
  191. return models.Model.save( self );
  192. # Before the record set is saved, update Murmur via controller.
  193. ctl = self.server.ctl;
  194. if self.owner:
  195. email = self.owner.email;
  196. else:
  197. email = settings.DEFAULT_FROM_EMAIL;
  198. if self.id is None:
  199. # This is a new user record, so Murmur doesn't know about it yet
  200. if len( ctl.getRegisteredPlayers( self.server.srvid, self.name ) ) > 0:
  201. raise ValueError( "Another player already registered that name." );
  202. if not self.password:
  203. raise ValueError( "Cannot register player without a password!" );
  204. self.mumbleid = ctl.registerPlayer( self.server.srvid, self.name, email, self.password );
  205. # Update user's registration
  206. elif self.password:
  207. ctl.setRegistration(
  208. self.server.srvid,
  209. self.mumbleid,
  210. self.name,
  211. email,
  212. self.password
  213. );
  214. # Don't save the users' passwords, we don't need them anyway
  215. self.password = '';
  216. self.setAdmin( self.isAdmin );
  217. # Now allow django to save the record set
  218. return models.Model.save( self );
  219. # Admin handlers
  220. def getAdmin( self ):
  221. # Get ACL of root Channel, get the admin group and see if I'm in it
  222. acl = mmACL( 0, self.server.ctl.getACL(self.server.srvid, 0) );
  223. if not hasattr( acl, "admingroup" ):
  224. raise ReferenceError( "The admin group was not found in the ACL's groups list!" );
  225. return self.mumbleid in acl.admingroup['add'];
  226. def setAdmin( self, value ):
  227. # Get ACL of root Channel, get the admin group and see if I'm in it
  228. ctl = self.server.ctl;
  229. acl = mmACL( 0, ctl.getACL(self.server.srvid, 0) );
  230. if not hasattr( acl, "admingroup" ):
  231. raise ReferenceError( "The admin group was not found in the ACL's groups list!" );
  232. if value != ( self.mumbleid in acl.admingroup['add'] ):
  233. if value:
  234. acl.admingroup['add'].append( self.mumbleid );
  235. else:
  236. acl.admingroup['add'].remove( self.mumbleid );
  237. ctl.setACL(self.server.srvid, acl);
  238. return value;
  239. # Texture handlers
  240. def getTexture( self ):
  241. return self.server.ctl.getTexture(self.server.srvid, self.mumbleid);
  242. def setTexture( self, infile ):
  243. self.server.ctl.setTexture(self.server.srvid, self.mumbleid, infile)
  244. # Deletion handler
  245. @staticmethod
  246. def pre_delete_listener( **kwargs ):
  247. kwargs['instance'].unregister();
  248. def unregister( self ):
  249. if self.getAdmin():
  250. self.setAdmin( False );
  251. self.server.ctl.unregisterPlayer(self.server.srvid, self.mumbleid)
  252. # "server" field protection
  253. def __setattr__( self, name, value ):
  254. if name == 'server':
  255. if self.id is not None and self.server != value:
  256. raise AttributeError( "This field must not be updated once the Record has been saved." );
  257. models.Model.__setattr__( self, name, value );
  258. from django.db.models import signals
  259. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  260. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );