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.

444 lines
14 KiB

15 years ago
16 years ago
16 years ago
15 years ago
15 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. * Copyright © 2009, withgod <withgod@sourceforge.net>
  4. * 2009-2010, 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 exists
  17. from PIL import Image
  18. from struct import pack, unpack
  19. from zlib import compress, decompress
  20. from mctl import MumbleCtlBase
  21. from utils import ObjectInfo
  22. import Ice
  23. def protectDjangoErrPage( func ):
  24. """ Catch and reraise Ice exceptions to prevent the Django page from failing.
  25. Since I need to "import Murmur", Django would try to read a murmur.py file
  26. which doesn't exist, and thereby produce an IndexError exception. This method
  27. erases the exception's traceback, preventing Django from trying to read any
  28. non-existant files and borking.
  29. """
  30. def protection_wrapper( *args, **kwargs ):
  31. """ Call the original function and catch Ice exceptions. """
  32. try:
  33. return func( *args, **kwargs );
  34. except Ice.Exception, e:
  35. raise e;
  36. protection_wrapper.innerfunc = func
  37. return protection_wrapper;
  38. @protectDjangoErrPage
  39. def MumbleCtlIce( connstring, slicefile=None, icesecret=None ):
  40. """ Choose the correct Ice handler to use (1.1.8 or 1.2.x), and make sure the
  41. Murmur version matches the slice Version.
  42. Optional parameters are the path to the slice file and the Ice secret
  43. necessary to authenticate to Murmur.
  44. The path can be omitted only if running Murmur 1.2.3 or later, which
  45. exports a getSlice method to retrieve the Slice from.
  46. """
  47. try:
  48. import Murmur
  49. except ImportError:
  50. if not slicefile:
  51. raise EnvironmentError( "You didn't configure a slice file. Please set the SLICE variable in settings.py." )
  52. if not exists( slicefile ):
  53. raise EnvironmentError( "The slice file does not exist: '%s' - please check the settings." % slicefile )
  54. if " " in slicefile:
  55. raise EnvironmentError( "You have a space char in your Slice path. This will confuse Ice, please check." )
  56. if not slicefile.endswith( ".ice" ):
  57. raise EnvironmentError( "The slice file name MUST end with '.ice'." )
  58. Ice.loadSlice( slicefile )
  59. import Murmur
  60. ice = Ice.initialize()
  61. if icesecret:
  62. ice.getImplicitContext().put("secret", icesecret)
  63. prx = ice.stringToProxy( connstring.encode("utf-8") )
  64. meta = Murmur.MetaPrx.checkedCast(prx)
  65. murmurversion = meta.getVersion()[:3]
  66. if murmurversion == (1, 1, 8):
  67. return MumbleCtlIce_118( connstring, meta );
  68. elif murmurversion[:2] == (1, 2):
  69. return MumbleCtlIce_120( connstring, meta );
  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 getConf(self, srvid, key):
  163. if key == "username":
  164. key = "playername";
  165. return self._getIceServerObject(srvid).getConf( key )
  166. @protectDjangoErrPage
  167. def setConf(self, srvid, key, value):
  168. if key == "username":
  169. key = "playername";
  170. if value is None:
  171. value = ''
  172. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  173. @protectDjangoErrPage
  174. def registerPlayer(self, srvid, name, email, password):
  175. mumbleid = self._getIceServerObject(srvid).registerPlayer( name.encode( "UTF-8" ) )
  176. self.setRegistration( srvid, mumbleid, name, email, password );
  177. return mumbleid;
  178. @protectDjangoErrPage
  179. def unregisterPlayer(self, srvid, mumbleid):
  180. self._getIceServerObject(srvid).unregisterPlayer(mumbleid)
  181. @protectDjangoErrPage
  182. def getRegistration(self, srvid, mumbleid):
  183. user = self._getIceServerObject(srvid).getRegistration(mumbleid)
  184. return ObjectInfo(
  185. userid = mumbleid,
  186. name = user.name,
  187. email = user.email,
  188. pw = '',
  189. );
  190. @protectDjangoErrPage
  191. def setRegistration(self, srvid, mumbleid, name, email, password):
  192. import Murmur
  193. user = Murmur.Player()
  194. user.playerid = mumbleid;
  195. user.name = name.encode( "UTF-8" )
  196. user.email = email.encode( "UTF-8" )
  197. user.pw = password.encode( "UTF-8" )
  198. # update*r*egistration r is lowercase...
  199. return self._getIceServerObject(srvid).updateregistration(user)
  200. @protectDjangoErrPage
  201. def getACL(self, srvid, channelid):
  202. # need to convert acls to say "userid" instead of "playerid". meh.
  203. raw_acls, raw_groups, raw_inherit = self._getIceServerObject(srvid).getACL(channelid)
  204. acls = [ ObjectInfo(
  205. applyHere = rule.applyHere,
  206. applySubs = rule.applySubs,
  207. inherited = rule.inherited,
  208. userid = rule.playerid,
  209. group = rule.group,
  210. allow = rule.allow,
  211. deny = rule.deny,
  212. )
  213. for rule in raw_acls
  214. ];
  215. return acls, raw_groups, raw_inherit;
  216. @protectDjangoErrPage
  217. def setACL(self, srvid, channelid, acls, groups, inherit):
  218. import Murmur
  219. ice_acls = [];
  220. for rule in acls:
  221. ice_rule = Murmur.ACL();
  222. ice_rule.applyHere = rule.applyHere;
  223. ice_rule.applySubs = rule.applySubs;
  224. ice_rule.inherited = rule.inherited;
  225. ice_rule.playerid = rule.userid;
  226. ice_rule.group = rule.group;
  227. ice_rule.allow = rule.allow;
  228. ice_rule.deny = rule.deny;
  229. ice_acls.append(ice_rule);
  230. return self._getIceServerObject(srvid).setACL( channelid, ice_acls, groups, inherit );
  231. @protectDjangoErrPage
  232. def getTexture(self, srvid, mumbleid):
  233. texture = self._getIceServerObject(srvid).getTexture(mumbleid)
  234. if len(texture) == 0:
  235. raise ValueError( "No Texture has been set." );
  236. # this returns a list of bytes.
  237. decompressed = decompress( texture );
  238. # iterate over 4 byte chunks of the string
  239. imgdata = "";
  240. for idx in range( 0, len(decompressed), 4 ):
  241. # read 4 bytes = BGRA and convert to RGBA
  242. # manual wrote getTexture returns "Textures are stored as zlib compress()ed 600x60 32-bit RGBA data."
  243. # http://mumble.sourceforge.net/slice/Murmur/Server.html#getTexture
  244. # but return values BGRA X(
  245. bgra = unpack( "4B", decompressed[idx:idx+4] );
  246. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  247. # return an 600x60 RGBA image object created from the data
  248. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  249. @protectDjangoErrPage
  250. def setTexture(self, srvid, mumbleid, infile):
  251. # open image, convert to RGBA, and resize to 600x60
  252. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  253. # iterate over the list and pack everything into a string
  254. bgrastring = "";
  255. for ent in list( img.getdata() ):
  256. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  257. # to be reordered when passed to pack()
  258. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  259. # compress using zlib
  260. compressed = compress( bgrastring );
  261. # pack the original length in 4 byte big endian, and concat the compressed
  262. # data to it to emulate qCompress().
  263. texture = pack( ">L", len(bgrastring) ) + compressed;
  264. # finally call murmur and set the texture
  265. self._getIceServerObject(srvid).setTexture(mumbleid, texture)
  266. @protectDjangoErrPage
  267. def verifyPassword(self, srvid, username, password):
  268. return self._getIceServerObject(srvid).verifyPassword(username, password);
  269. @staticmethod
  270. def setUnicodeFlag(data):
  271. ret = ''
  272. if isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict):
  273. ret = {}
  274. for key in data.keys():
  275. ret[MumbleCtlIce_118.setUnicodeFlag(key)] = MumbleCtlIce_118.setUnicodeFlag(data[key])
  276. else:
  277. ret = unicode(data, 'utf-8')
  278. return ret
  279. class MumbleCtlIce_120(MumbleCtlIce_118):
  280. @protectDjangoErrPage
  281. def getRegisteredPlayers(self, srvid, filter = ''):
  282. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  283. ret = {};
  284. for id in users:
  285. ret[id] = ObjectInfo(
  286. userid = id,
  287. name = unicode( users[id], "utf8" ),
  288. email = '',
  289. pw = ''
  290. );
  291. return ret
  292. @protectDjangoErrPage
  293. def getPlayers(self, srvid):
  294. return self._getIceServerObject(srvid).getUsers();
  295. @protectDjangoErrPage
  296. def registerPlayer(self, srvid, name, email, password):
  297. # To get the real values of these ENUM entries, try
  298. # Murmur.UserInfo.UserX.value
  299. import Murmur
  300. user = {
  301. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  302. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  303. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  304. };
  305. return self._getIceServerObject(srvid).registerUser( user );
  306. @protectDjangoErrPage
  307. def unregisterPlayer(self, srvid, mumbleid):
  308. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  309. @protectDjangoErrPage
  310. def getRegistration(self, srvid, mumbleid):
  311. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  312. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" );
  313. import Murmur
  314. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName];
  315. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail];
  316. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment];
  317. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash];
  318. return user;
  319. @protectDjangoErrPage
  320. def setRegistration(self, srvid, mumbleid, name, email, password):
  321. import Murmur
  322. user = {
  323. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  324. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  325. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  326. };
  327. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  328. @protectDjangoErrPage
  329. def getAllConf(self, srvid):
  330. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  331. info = {};
  332. for key in conf:
  333. if key == "playername" and conf[key]:
  334. # Buggy database transition from 1.1.8 -> 1.2.0
  335. # Store username as "username" field and set playername field to empty
  336. info['username'] = conf[key];
  337. self.setConf( srvid, "playername", "" );
  338. self.setConf( srvid, "username", conf[key] );
  339. else:
  340. info[str(key)] = conf[key];
  341. return info;
  342. @protectDjangoErrPage
  343. def getConf(self, srvid, key):
  344. return self._getIceServerObject(srvid).getConf( key )
  345. @protectDjangoErrPage
  346. def setConf(self, srvid, key, value):
  347. if value is None:
  348. value = ''
  349. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  350. @protectDjangoErrPage
  351. def getACL(self, srvid, channelid):
  352. return self._getIceServerObject(srvid).getACL(channelid)
  353. @protectDjangoErrPage
  354. def setACL(self, srvid, channelid, acls, groups, inherit):
  355. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit );