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.

427 lines
13 KiB

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