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.

290 lines
11 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
  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. from PIL import Image
  16. from struct import pack, unpack
  17. from zlib import compress, decompress
  18. from django.contrib.auth.models import User
  19. from django.db import models
  20. from mmobjects import mmServer, mmACL
  21. from django.conf import settings
  22. import dbus
  23. import socket
  24. class Mumble( models.Model ):
  25. name = models.CharField( 'Server Name', max_length = 200 );
  26. dbus = models.CharField( 'DBus base', max_length = 200, default = 'net.sourceforge.mumble.murmur' );
  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. def getDbusMeta( self ):
  44. return dbus.Interface( dbus.SystemBus().get_object( self.dbus, '/' ), 'net.sourceforge.mumble.Meta' );
  45. def getDbusObject( self ):
  46. "Connects to DBus and returns an mmServer object representing this Murmur instance."
  47. bus = dbus.SystemBus();
  48. murmur = dbus.Interface( bus.get_object( self.dbus, '/' ), 'net.sourceforge.mumble.Meta');
  49. if self.srvid not in murmur.getBootedServers():
  50. raise Exception, 'No murmur process with the given server ID (%d) is running and attached to system dbus under %s.' % ( self.srvid, self.dbus );
  51. return dbus.Interface( bus.get_object( self.dbus, '/%d' % self.srvid ), 'net.sourceforge.mumble.Murmur' );
  52. def getServerObject( self ):
  53. return mmServer( self.srvid, self.getDbusObject(), self.name );
  54. def __unicode__( self ):
  55. return u'Murmur "%s" (%d)' % ( self.name, self.srvid );
  56. def save( self, dontConfigureMurmur=False ):
  57. if dontConfigureMurmur:
  58. # skip murmur configuration, e.g. because we're inserting models for existing servers.
  59. return models.Model.save( self );
  60. # Prior to saving the model, connect to murmur via dbus and update its settings.
  61. murmur = self.getDbusMeta();
  62. # check if this server already exists, if not call newServer and set my srvid first
  63. if self.id is None:
  64. self.srvid = murmur.newServer();
  65. srvid = dbus.Int32( self.srvid );
  66. murmur.setConf( srvid, 'host', socket.gethostbyname( self.addr ) );
  67. murmur.setConf( srvid, 'registername', self.name );
  68. murmur.setConf( srvid, 'registerurl', self.url );
  69. murmur.setConf( srvid, 'welcometext', self.motd );
  70. murmur.setConf( srvid, 'password', self.passwd );
  71. murmur.setConf( srvid, 'certificate', self.sslcrt );
  72. murmur.setConf( srvid, 'key', self.sslkey );
  73. murmur.setConf( srvid, 'obfuscate', str(self.obfsc).lower() );
  74. murmur.setConf( srvid, 'playername', self.player );
  75. murmur.setConf( srvid, 'channelname', self.channel );
  76. murmur.setConf( srvid, 'defaultchannel', str(self.defchan) );
  77. if self.port is not None:
  78. murmur.setConf( srvid, 'port', str(self.port) );
  79. else:
  80. murmur.setConf( srvid, 'port', '' );
  81. if self.users is not None:
  82. murmur.setConf( srvid, 'users', str(self.users) );
  83. else:
  84. murmur.setConf( srvid, 'users', '' );
  85. if self.bwidth is not None:
  86. murmur.setConf( srvid, 'bandwidth', str(self.bwidth) );
  87. else:
  88. murmur.setConf( srvid, 'bandwidth', '' );
  89. # registerHostname needs to take the port no into account
  90. if self.port and self.port != 64738:
  91. murmur.setConf( srvid, 'registerhostname', "%s:%d" % ( self.addr, self.port ) );
  92. else:
  93. murmur.setConf( srvid, 'registerhostname', self.addr );
  94. if self.supw:
  95. murmur.setSuperUserPassword( srvid, self.supw );
  96. self.supw = '';
  97. if self.booted != murmur.isBooted( srvid ):
  98. if self.booted:
  99. murmur.start( srvid );
  100. else:
  101. murmur.stop( srvid );
  102. # Now allow django to save the record set
  103. return models.Model.save( self );
  104. def isUserAdmin( self, user ):
  105. if user.is_authenticated():
  106. try:
  107. return self.mumbleuser_set.get( owner=user ).getAdmin();
  108. except MumbleUser.DoesNotExist:
  109. return False;
  110. return False;
  111. def deleteServer( self ):
  112. srvid = dbus.Int32( self.srvid );
  113. murmur = self.getDbusMeta();
  114. if murmur.isBooted( srvid ):
  115. murmur.stop( srvid );
  116. murmur.deleteServer( srvid );
  117. @staticmethod
  118. def pre_delete_listener( **kwargs ):
  119. kwargs['instance'].deleteServer();
  120. class MumbleUser( models.Model ):
  121. mumbleid = models.IntegerField( 'Mumble player_id', editable = False, default = -1 );
  122. name = models.CharField( 'User name and Login', max_length = 200 );
  123. password = models.CharField( 'Login password', max_length = 200, blank=True );
  124. server = models.ForeignKey( Mumble );
  125. owner = models.ForeignKey( User, null=True, blank=True );
  126. isAdmin = models.BooleanField( 'Admin on root channel', default = False );
  127. def __unicode__( self ):
  128. return u"Mumble user %s on %s owned by Django user %s" % ( self.name, self.server, self.owner );
  129. def save( self, dontConfigureMurmur=False ):
  130. if dontConfigureMurmur:
  131. # skip murmur configuration, e.g. because we're inserting models for existing players.
  132. return models.Model.save( self );
  133. # Before the record set is saved, update Murmur via dbus.
  134. murmur = self.server.getDbusObject();
  135. if self.id is None:
  136. # This is a new user record, so Murmur doesn't know about it yet
  137. self.mumbleid = murmur.registerPlayer( dbus.String( self.name ) );
  138. # Update user's registration
  139. if self.password:
  140. if self.owner:
  141. email = self.owner.email
  142. else:
  143. email = settings.DEFAULT_FROM_EMAIL;
  144. murmur.setRegistration(
  145. dbus.Int32( self.mumbleid ),
  146. dbus.String( self.name ),
  147. dbus.String( email ),
  148. dbus.String( self.password )
  149. );
  150. # Don't save the users' passwords, we don't need them anyway
  151. self.password = '';
  152. self.setAdmin( self.isAdmin );
  153. # Now allow django to save the record set
  154. return models.Model.save( self );
  155. def getAdmin( self ):
  156. # Get ACL of root Channel, get the admin group and see if I'm in it
  157. bus = self.server.getDbusObject();
  158. acl = mmACL( 0, bus.getACL(0) );
  159. if not hasattr( acl, "admingroup" ):
  160. raise ValueError( "The admin group was not found in the ACL's groups list!" );
  161. return self.mumbleid in acl.admingroup['add'];
  162. def setAdmin( self, value ):
  163. # Get ACL of root Channel, get the admin group and see if I'm in it
  164. bus = self.server.getDbusObject();
  165. acl = mmACL( 0, bus.getACL(0) );
  166. if not hasattr( acl, "admingroup" ):
  167. raise ValueError( "The admin group was not found in the ACL's groups list!" );
  168. if value != ( self.mumbleid in acl.admingroup['add'] ):
  169. if value:
  170. acl.admingroup['add'].append( dbus.Int32(self.mumbleid) );
  171. else:
  172. acl.admingroup['add'].remove( self.mumbleid );
  173. bus.setACL( *acl.pack() );
  174. return value;
  175. def getTexture( self ):
  176. murmur = self.server.getDbusObject();
  177. texture = murmur.getTexture( dbus.Int32( self.mumbleid ) );
  178. if len(texture) == 0:
  179. raise ValueError( "No Texture has been set." );
  180. # this returns a list of bytes.
  181. # first 4 bytes: Length of uncompressed string, rest: compressed data
  182. orig_len = ( texture[0] << 24 ) | ( texture[1] << 16 ) | ( texture[2] << 8 ) | ( texture[3] );
  183. # convert rest to string and run decompress
  184. bytestr = "";
  185. for byte in texture[4:]:
  186. bytestr += pack( "B", int(byte) );
  187. decompressed = decompress( bytestr );
  188. # iterate over 4 byte chunks of the string
  189. imgdata = "";
  190. for idx in range( 0, orig_len, 4 ):
  191. # read 4 bytes = BGRA and convert to RGBA
  192. bgra = unpack( "4B", decompressed[idx:idx+4] );
  193. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  194. # return an 600x60 RGBA image object created from the data
  195. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  196. def setTexture( self, infile ):
  197. # open image, convert to RGBA, and resize to 600x60
  198. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  199. # iterate over the list and pack everything into a string
  200. bgrastring = "";
  201. for ent in list( img.getdata() ):
  202. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  203. # to be reordered when passed to pack()
  204. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  205. # compress using zlib
  206. compressed = compress( bgrastring );
  207. # pack the original length in 4 byte big endian, and concat the compressed
  208. # data to it to emulate qCompress().
  209. texture = pack( ">L", len(bgrastring) ) + compressed;
  210. # finally call murmur and set the texture
  211. murmur = self.server.getDbusObject();
  212. murmur.setTexture( dbus.Int32( self.mumbleid ), texture );
  213. @staticmethod
  214. def pre_delete_listener( **kwargs ):
  215. kwargs['instance'].unregister();
  216. def unregister( self ):
  217. # Unregister this player in Murmur via dbus.
  218. murmur = self.server.getDbusObject();
  219. murmur.unregisterPlayer( dbus.Int32( self.mumbleid ) );
  220. def __setattr__( self, name, value ):
  221. if name == 'server':
  222. if self.id is not None and self.server != value:
  223. raise AttributeError( "This field must not be updated once the Record has been saved." );
  224. models.Model.__setattr__( self, name, value );
  225. from django.db.models import signals
  226. signals.pre_delete.connect( Mumble.pre_delete_listener, sender=Mumble );
  227. signals.pre_delete.connect( MumbleUser.pre_delete_listener, sender=MumbleUser );