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.

428 lines
13 KiB

15 years ago
15 years ago
15 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright (C) 2009, withgod <withgod@sourceforge.net>
  4. * Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
  5. *
  6. * Mumble-Django is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This package is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. """
  16. from os.path import join
  17. from PIL import Image
  18. from struct import pack, unpack
  19. from zlib import compress, decompress
  20. from django.conf import settings
  21. from mctl import MumbleCtlBase
  22. from utils import ObjectInfo
  23. import Ice, sys
  24. def protectDjangoErrPage( func ):
  25. """ Catch and reraise Ice exceptions to prevent the Django page from failing.
  26. Since I need to "import Murmur", Django would try to read a murmur.py file
  27. which doesn't exist, and thereby produce an IndexError exception. This method
  28. erases the exception's traceback, preventing Django from trying to read any
  29. non-existant files and borking.
  30. """
  31. def protection_wrapper( *args, **kwargs ):
  32. try:
  33. return func( *args, **kwargs );
  34. except Ice.Exception, e:
  35. raise e;
  36. return protection_wrapper;
  37. @protectDjangoErrPage
  38. def MumbleCtlIce( connstring ):
  39. """ Choose the correct Ice handler to use (1.1.8 or 1.2.0), and make sure the
  40. Murmur version matches the slice Version.
  41. """
  42. candidates = (
  43. ( settings.SLICE_VERSION, settings.SLICE ),
  44. ( ( 1, 1, 8 ), None ),
  45. ( ( 1, 2, 0 ), None ),
  46. ( ( 1, 2, 1 ), None ),
  47. );
  48. for version, slice in candidates:
  49. if not slice:
  50. slice = join(
  51. settings.MUMBLE_DJANGO_ROOT, 'pyweb', 'mumble',
  52. 'Murmur_%d-%d-%d.ice' % (version[0], version[1], version[2] )
  53. );
  54. Ice.loadSlice( slice )
  55. ice = Ice.initialize()
  56. import Murmur
  57. prx = ice.stringToProxy( connstring.encode("utf-8") )
  58. meta = Murmur.MetaPrx.checkedCast(prx)
  59. murmurversion = meta.getVersion();
  60. if murmurversion[0] != version[0] or murmurversion[1] != version[1] or murmurversion[2] != version[2]:
  61. # Version mismatch. Use sys.modules.pop fakery to unload the Module, and allow
  62. # a later iteration to run Ice's "from nowhere import Murmur" fakery again.
  63. # Two wrongs don't make a right, but at least it works. (I really do miss DBus.)
  64. ice.destroy();
  65. sys.modules.pop("Murmur");
  66. elif murmurversion[0] == murmurversion[1] == 1 and murmurversion[2] <= 8:
  67. return MumbleCtlIce_118( connstring, meta );
  68. elif murmurversion[0] == 1 and murmurversion[1] == 2:
  69. return MumbleCtlIce_120( connstring, meta );
  70. raise EnvironmentError( "Could not find a Slice matching your version of Murmur." );
  71. class MumbleCtlIce_118(MumbleCtlBase):
  72. method = "ICE";
  73. def __init__( self, connstring, meta ):
  74. self.proxy = connstring;
  75. self.meta = meta;
  76. @protectDjangoErrPage
  77. def _getIceServerObject(self, srvid):
  78. return self.meta.getServer(srvid);
  79. @protectDjangoErrPage
  80. def getBootedServers(self):
  81. ret = []
  82. for x in self.meta.getBootedServers():
  83. ret.append(x.id())
  84. return ret
  85. @protectDjangoErrPage
  86. def getVersion( self ):
  87. return self.meta.getVersion();
  88. @protectDjangoErrPage
  89. def getAllServers(self):
  90. ret = []
  91. for x in self.meta.getAllServers():
  92. ret.append(x.id())
  93. return ret
  94. @protectDjangoErrPage
  95. def getRegisteredPlayers(self, srvid, filter = ''):
  96. users = self._getIceServerObject(srvid).getRegisteredPlayers( filter.encode( "UTF-8" ) )
  97. ret = {};
  98. for user in users:
  99. ret[user.playerid] = ObjectInfo(
  100. userid = int( user.playerid ),
  101. name = unicode( user.name, "utf8" ),
  102. email = unicode( user.email, "utf8" ),
  103. pw = unicode( user.pw, "utf8" )
  104. );
  105. return ret
  106. @protectDjangoErrPage
  107. def getChannels(self, srvid):
  108. return self._getIceServerObject(srvid).getChannels();
  109. @protectDjangoErrPage
  110. def getPlayers(self, srvid):
  111. users = self._getIceServerObject(srvid).getPlayers()
  112. ret = {};
  113. for useridx in users:
  114. user = users[useridx];
  115. ret[ user.session ] = ObjectInfo(
  116. session = user.session,
  117. userid = user.playerid,
  118. mute = user.mute,
  119. deaf = user.deaf,
  120. suppress = user.suppressed,
  121. selfMute = user.selfMute,
  122. selfDeaf = user.selfDeaf,
  123. channel = user.channel,
  124. name = user.name,
  125. onlinesecs = user.onlinesecs,
  126. bytespersec = user.bytespersec
  127. );
  128. return ret;
  129. @protectDjangoErrPage
  130. def getDefaultConf(self):
  131. return self.setUnicodeFlag(self.meta.getDefaultConf())
  132. @protectDjangoErrPage
  133. def getAllConf(self, srvid):
  134. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  135. info = {};
  136. for key in conf:
  137. if key == "playername":
  138. info['username'] = conf[key];
  139. else:
  140. info[str(key)] = conf[key];
  141. return info;
  142. @protectDjangoErrPage
  143. def newServer(self):
  144. return self.meta.newServer().id()
  145. @protectDjangoErrPage
  146. def isBooted( self, srvid ):
  147. return bool( self._getIceServerObject(srvid).isRunning() );
  148. @protectDjangoErrPage
  149. def start( self, srvid ):
  150. self._getIceServerObject(srvid).start();
  151. @protectDjangoErrPage
  152. def stop( self, srvid ):
  153. self._getIceServerObject(srvid).stop();
  154. @protectDjangoErrPage
  155. def deleteServer( self, srvid ):
  156. if self._getIceServerObject(srvid).isRunning():
  157. self._getIceServerObject(srvid).stop()
  158. self._getIceServerObject(srvid).delete()
  159. @protectDjangoErrPage
  160. def setSuperUserPassword(self, srvid, value):
  161. self._getIceServerObject(srvid).setSuperuserPassword( value.encode( "UTF-8" ) )
  162. @protectDjangoErrPage
  163. def setConf(self, srvid, key, value):
  164. if key == "username":
  165. key = "playername";
  166. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  167. @protectDjangoErrPage
  168. def registerPlayer(self, srvid, name, email, password):
  169. mumbleid = self._getIceServerObject(srvid).registerPlayer( name.encode( "UTF-8" ) )
  170. self.setRegistration( srvid, mumbleid, name, email, password );
  171. return mumbleid;
  172. @protectDjangoErrPage
  173. def unregisterPlayer(self, srvid, mumbleid):
  174. self._getIceServerObject(srvid).unregisterPlayer(mumbleid)
  175. @protectDjangoErrPage
  176. def getRegistration(self, srvid, mumbleid):
  177. user = self._getIceServerObject(srvid).getRegistration(mumbleid)
  178. return ObjectInfo(
  179. userid = mumbleid,
  180. name = user.name,
  181. email = user.email,
  182. pw = '',
  183. );
  184. @protectDjangoErrPage
  185. def setRegistration(self, srvid, mumbleid, name, email, password):
  186. import Murmur
  187. user = Murmur.Player()
  188. user.playerid = mumbleid;
  189. user.name = name.encode( "UTF-8" )
  190. user.email = email.encode( "UTF-8" )
  191. user.pw = password.encode( "UTF-8" )
  192. # update*r*egistration r is lowercase...
  193. return self._getIceServerObject(srvid).updateregistration(user)
  194. @protectDjangoErrPage
  195. def getACL(self, srvid, channelid):
  196. # need to convert acls to say "userid" instead of "playerid". meh.
  197. raw_acls, raw_groups, raw_inherit = self._getIceServerObject(srvid).getACL(channelid)
  198. acls = [ ObjectInfo(
  199. applyHere = rule.applyHere,
  200. applySubs = rule.applySubs,
  201. inherited = rule.inherited,
  202. userid = rule.playerid,
  203. group = rule.group,
  204. allow = rule.allow,
  205. deny = rule.deny,
  206. )
  207. for rule in raw_acls
  208. ];
  209. return acls, raw_groups, raw_inherit;
  210. @protectDjangoErrPage
  211. def setACL(self, srvid, channelid, acls, groups, inherit):
  212. import Murmur
  213. ice_acls = [];
  214. for rule in acls:
  215. ice_rule = Murmur.ACL();
  216. ice_rule.applyHere = rule.applyHere;
  217. ice_rule.applySubs = rule.applySubs;
  218. ice_rule.inherited = rule.inherited;
  219. ice_rule.playerid = rule.userid;
  220. ice_rule.group = rule.group;
  221. ice_rule.allow = rule.allow;
  222. ice_rule.deny = rule.deny;
  223. ice_acls.append(ice_rule);
  224. return self._getIceServerObject(srvid).setACL( channelid, ice_acls, groups, inherit );
  225. @protectDjangoErrPage
  226. def getTexture(self, srvid, mumbleid):
  227. texture = self._getIceServerObject(srvid).getTexture(mumbleid)
  228. if len(texture) == 0:
  229. raise ValueError( "No Texture has been set." );
  230. # this returns a list of bytes.
  231. decompressed = decompress( texture );
  232. # iterate over 4 byte chunks of the string
  233. imgdata = "";
  234. for idx in range( 0, len(decompressed), 4 ):
  235. # read 4 bytes = BGRA and convert to RGBA
  236. # manual wrote getTexture returns "Textures are stored as zlib compress()ed 600x60 32-bit RGBA data."
  237. # http://mumble.sourceforge.net/slice/Murmur/Server.html#getTexture
  238. # but return values BGRA X(
  239. bgra = unpack( "4B", decompressed[idx:idx+4] );
  240. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  241. # return an 600x60 RGBA image object created from the data
  242. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  243. @protectDjangoErrPage
  244. def setTexture(self, srvid, mumbleid, infile):
  245. # open image, convert to RGBA, and resize to 600x60
  246. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  247. # iterate over the list and pack everything into a string
  248. bgrastring = "";
  249. for ent in list( img.getdata() ):
  250. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  251. # to be reordered when passed to pack()
  252. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  253. # compress using zlib
  254. compressed = compress( bgrastring );
  255. # pack the original length in 4 byte big endian, and concat the compressed
  256. # data to it to emulate qCompress().
  257. texture = pack( ">L", len(bgrastring) ) + compressed;
  258. # finally call murmur and set the texture
  259. self._getIceServerObject(srvid).setTexture(mumbleid, texture)
  260. @protectDjangoErrPage
  261. def verifyPassword(self, srvid, username, password):
  262. return self._getIceServerObject(srvid).verifyPassword(username, password);
  263. @staticmethod
  264. def setUnicodeFlag(data):
  265. ret = ''
  266. if isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict):
  267. ret = {}
  268. for key in data.keys():
  269. ret[MumbleCtlIce_118.setUnicodeFlag(key)] = MumbleCtlIce_118.setUnicodeFlag(data[key])
  270. else:
  271. ret = unicode(data, 'utf-8')
  272. return ret
  273. class MumbleCtlIce_120(MumbleCtlIce_118):
  274. @protectDjangoErrPage
  275. def getRegisteredPlayers(self, srvid, filter = ''):
  276. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  277. ret = {};
  278. for id in users:
  279. ret[id] = ObjectInfo(
  280. userid = id,
  281. name = unicode( users[id], "utf8" ),
  282. email = '',
  283. pw = ''
  284. );
  285. return ret
  286. @protectDjangoErrPage
  287. def getPlayers(self, srvid):
  288. return self._getIceServerObject(srvid).getUsers();
  289. @protectDjangoErrPage
  290. def registerPlayer(self, srvid, name, email, password):
  291. # To get the real values of these ENUM entries, try
  292. # Murmur.UserInfo.UserX.value
  293. import Murmur
  294. user = {
  295. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  296. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  297. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  298. };
  299. return self._getIceServerObject(srvid).registerUser( user );
  300. @protectDjangoErrPage
  301. def unregisterPlayer(self, srvid, mumbleid):
  302. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  303. @protectDjangoErrPage
  304. def getRegistration(self, srvid, mumbleid):
  305. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  306. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" );
  307. import Murmur
  308. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName];
  309. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail];
  310. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment];
  311. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash];
  312. return user;
  313. @protectDjangoErrPage
  314. def setRegistration(self, srvid, mumbleid, name, email, password):
  315. import Murmur
  316. user = {
  317. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  318. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  319. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  320. };
  321. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  322. @protectDjangoErrPage
  323. def getAllConf(self, srvid):
  324. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  325. info = {};
  326. for key in conf:
  327. if key == "playername" and conf[key]:
  328. # Buggy database transition from 1.1.8 -> 1.2.0
  329. # Store username as "username" field and set playername field to empty
  330. info['username'] = conf[key];
  331. self.setConf( srvid, "playername", "" );
  332. self.setConf( srvid, "username", conf[key] );
  333. else:
  334. info[str(key)] = conf[key];
  335. return info;
  336. @protectDjangoErrPage
  337. def setConf(self, srvid, key, value):
  338. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  339. @protectDjangoErrPage
  340. def getACL(self, srvid, channelid):
  341. return self._getIceServerObject(srvid).getACL(channelid)
  342. @protectDjangoErrPage
  343. def setACL(self, srvid, channelid, acls, groups, inherit):
  344. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit );