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.

492 lines
15 KiB

15 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, join
  17. from os import unlink, name as os_name
  18. from PIL import Image
  19. from struct import pack, unpack
  20. from zlib import compress, decompress
  21. from mctl import MumbleCtlBase
  22. from utils import ObjectInfo
  23. import Ice, IcePy, tempfile
  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. """ Call the original function and catch Ice exceptions. """
  33. try:
  34. return func( *args, **kwargs );
  35. except Ice.Exception, e:
  36. raise e;
  37. protection_wrapper.innerfunc = func
  38. return protection_wrapper;
  39. @protectDjangoErrPage
  40. def MumbleCtlIce( connstring, slicefile=None, icesecret=None ):
  41. """ Choose the correct Ice handler to use (1.1.8 or 1.2.x), and make sure the
  42. Murmur version matches the slice Version.
  43. Optional parameters are the path to the slice file and the Ice secret
  44. necessary to authenticate to Murmur.
  45. The path can be omitted only if running Murmur 1.2.3 or later, which
  46. exports a getSlice method to retrieve the Slice from.
  47. """
  48. prop = Ice.createProperties([])
  49. prop.setProperty("Ice.ImplicitContext", "Shared")
  50. idd = Ice.InitializationData()
  51. idd.properties = prop
  52. ice = Ice.initialize(idd)
  53. if icesecret:
  54. ice.getImplicitContext().put( "secret", icesecret.encode("utf-8") )
  55. prx = ice.stringToProxy( connstring.encode("utf-8") )
  56. try:
  57. import Murmur
  58. except ImportError:
  59. # Try loading the Slice from Murmur directly via its getSlice method.
  60. # See scripts/testdynamic.py in Mumble's Git repository.
  61. try:
  62. slice = IcePy.Operation( 'getSlice',
  63. Ice.OperationMode.Idempotent, Ice.OperationMode.Idempotent,
  64. True, (), (), (), IcePy._t_string, ()
  65. ).invoke(prx, ((), None))
  66. except (TypeError, Ice.OperationNotExistException):
  67. if not slicefile:
  68. raise EnvironmentError(
  69. "You didn't configure a slice file. Please set the SLICE variable in settings.py." )
  70. if not exists( slicefile ):
  71. raise EnvironmentError(
  72. "The slice file does not exist: '%s' - please check the settings." % slicefile )
  73. if " " in slicefile:
  74. raise EnvironmentError(
  75. "You have a space char in your Slice path. This will confuse Ice, please check." )
  76. if not slicefile.endswith( ".ice" ):
  77. raise EnvironmentError( "The slice file name MUST end with '.ice'." )
  78. try:
  79. Ice.loadSlice( slicefile )
  80. except RuntimeError:
  81. raise RuntimeError( "Slice preprocessing failed. Please check your server's error log." )
  82. else:
  83. if os_name == "nt":
  84. # It weren't Windows if it didn't need to be treated differently. *sigh*
  85. temppath = join( tempfile.gettempdir(), "Murmur.ice" )
  86. slicetemp = open( temppath, "w+b" )
  87. try:
  88. slicetemp.write( slice )
  89. finally:
  90. slicetemp.close()
  91. try:
  92. Ice.loadSlice( temppath )
  93. except RuntimeError:
  94. raise RuntimeError( "Slice preprocessing failed. Please check your server's error log." )
  95. finally:
  96. unlink(temppath)
  97. else:
  98. slicetemp = tempfile.NamedTemporaryFile( suffix='.ice' )
  99. try:
  100. slicetemp.write( slice )
  101. slicetemp.flush()
  102. Ice.loadSlice( slicetemp.name )
  103. except RuntimeError:
  104. raise RuntimeError( "Slice preprocessing failed. Please check your server's error log." )
  105. finally:
  106. slicetemp.close()
  107. import Murmur
  108. meta = Murmur.MetaPrx.checkedCast(prx)
  109. murmurversion = meta.getVersion()[:3]
  110. if murmurversion == (1, 1, 8):
  111. return MumbleCtlIce_118( connstring, meta );
  112. elif murmurversion[:2] == (1, 2):
  113. return MumbleCtlIce_120( connstring, meta );
  114. class MumbleCtlIce_118(MumbleCtlBase):
  115. method = "ICE";
  116. def __init__( self, connstring, meta ):
  117. self.proxy = connstring;
  118. self.meta = meta;
  119. @protectDjangoErrPage
  120. def _getIceServerObject(self, srvid):
  121. return self.meta.getServer(srvid);
  122. @protectDjangoErrPage
  123. def getBootedServers(self):
  124. ret = []
  125. for x in self.meta.getBootedServers():
  126. ret.append(x.id())
  127. return ret
  128. @protectDjangoErrPage
  129. def getVersion( self ):
  130. return self.meta.getVersion();
  131. @protectDjangoErrPage
  132. def getAllServers(self):
  133. ret = []
  134. for x in self.meta.getAllServers():
  135. ret.append(x.id())
  136. return ret
  137. @protectDjangoErrPage
  138. def getRegisteredPlayers(self, srvid, filter = ''):
  139. users = self._getIceServerObject(srvid).getRegisteredPlayers( filter.encode( "UTF-8" ) )
  140. ret = {};
  141. for user in users:
  142. ret[user.playerid] = ObjectInfo(
  143. userid = int( user.playerid ),
  144. name = unicode( user.name, "utf8" ),
  145. email = unicode( user.email, "utf8" ),
  146. pw = unicode( user.pw, "utf8" )
  147. );
  148. return ret
  149. @protectDjangoErrPage
  150. def getChannels(self, srvid):
  151. return self._getIceServerObject(srvid).getChannels();
  152. @protectDjangoErrPage
  153. def getPlayers(self, srvid):
  154. users = self._getIceServerObject(srvid).getPlayers()
  155. ret = {};
  156. for useridx in users:
  157. user = users[useridx];
  158. ret[ user.session ] = ObjectInfo(
  159. session = user.session,
  160. userid = user.playerid,
  161. mute = user.mute,
  162. deaf = user.deaf,
  163. suppress = user.suppressed,
  164. selfMute = user.selfMute,
  165. selfDeaf = user.selfDeaf,
  166. channel = user.channel,
  167. name = user.name,
  168. onlinesecs = user.onlinesecs,
  169. bytespersec = user.bytespersec
  170. );
  171. return ret;
  172. @protectDjangoErrPage
  173. def getDefaultConf(self):
  174. return self.setUnicodeFlag(self.meta.getDefaultConf())
  175. @protectDjangoErrPage
  176. def getAllConf(self, srvid):
  177. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  178. info = {};
  179. for key in conf:
  180. if key == "playername":
  181. info['username'] = conf[key];
  182. else:
  183. info[str(key)] = conf[key];
  184. return info;
  185. @protectDjangoErrPage
  186. def newServer(self):
  187. return self.meta.newServer().id()
  188. @protectDjangoErrPage
  189. def isBooted( self, srvid ):
  190. return bool( self._getIceServerObject(srvid).isRunning() );
  191. @protectDjangoErrPage
  192. def start( self, srvid ):
  193. self._getIceServerObject(srvid).start();
  194. @protectDjangoErrPage
  195. def stop( self, srvid ):
  196. self._getIceServerObject(srvid).stop();
  197. @protectDjangoErrPage
  198. def deleteServer( self, srvid ):
  199. if self._getIceServerObject(srvid).isRunning():
  200. self._getIceServerObject(srvid).stop()
  201. self._getIceServerObject(srvid).delete()
  202. @protectDjangoErrPage
  203. def setSuperUserPassword(self, srvid, value):
  204. self._getIceServerObject(srvid).setSuperuserPassword( value.encode( "UTF-8" ) )
  205. @protectDjangoErrPage
  206. def getConf(self, srvid, key):
  207. if key == "username":
  208. key = "playername";
  209. return self._getIceServerObject(srvid).getConf( key )
  210. @protectDjangoErrPage
  211. def setConf(self, srvid, key, value):
  212. if key == "username":
  213. key = "playername";
  214. if value is None:
  215. value = ''
  216. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  217. @protectDjangoErrPage
  218. def registerPlayer(self, srvid, name, email, password):
  219. mumbleid = self._getIceServerObject(srvid).registerPlayer( name.encode( "UTF-8" ) )
  220. self.setRegistration( srvid, mumbleid, name, email, password );
  221. return mumbleid;
  222. @protectDjangoErrPage
  223. def unregisterPlayer(self, srvid, mumbleid):
  224. self._getIceServerObject(srvid).unregisterPlayer(mumbleid)
  225. @protectDjangoErrPage
  226. def getRegistration(self, srvid, mumbleid):
  227. user = self._getIceServerObject(srvid).getRegistration(mumbleid)
  228. return ObjectInfo(
  229. userid = mumbleid,
  230. name = user.name,
  231. email = user.email,
  232. pw = '',
  233. );
  234. @protectDjangoErrPage
  235. def setRegistration(self, srvid, mumbleid, name, email, password):
  236. import Murmur
  237. user = Murmur.Player()
  238. user.playerid = mumbleid;
  239. user.name = name.encode( "UTF-8" )
  240. user.email = email.encode( "UTF-8" )
  241. user.pw = password.encode( "UTF-8" )
  242. # update*r*egistration r is lowercase...
  243. return self._getIceServerObject(srvid).updateregistration(user)
  244. @protectDjangoErrPage
  245. def getACL(self, srvid, channelid):
  246. # need to convert acls to say "userid" instead of "playerid". meh.
  247. raw_acls, raw_groups, raw_inherit = self._getIceServerObject(srvid).getACL(channelid)
  248. acls = [ ObjectInfo(
  249. applyHere = rule.applyHere,
  250. applySubs = rule.applySubs,
  251. inherited = rule.inherited,
  252. userid = rule.playerid,
  253. group = rule.group,
  254. allow = rule.allow,
  255. deny = rule.deny,
  256. )
  257. for rule in raw_acls
  258. ];
  259. return acls, raw_groups, raw_inherit;
  260. @protectDjangoErrPage
  261. def setACL(self, srvid, channelid, acls, groups, inherit):
  262. import Murmur
  263. ice_acls = [];
  264. for rule in acls:
  265. ice_rule = Murmur.ACL();
  266. ice_rule.applyHere = rule.applyHere;
  267. ice_rule.applySubs = rule.applySubs;
  268. ice_rule.inherited = rule.inherited;
  269. ice_rule.playerid = rule.userid;
  270. ice_rule.group = rule.group;
  271. ice_rule.allow = rule.allow;
  272. ice_rule.deny = rule.deny;
  273. ice_acls.append(ice_rule);
  274. return self._getIceServerObject(srvid).setACL( channelid, ice_acls, groups, inherit );
  275. @protectDjangoErrPage
  276. def getTexture(self, srvid, mumbleid):
  277. texture = self._getIceServerObject(srvid).getTexture(mumbleid)
  278. if len(texture) == 0:
  279. raise ValueError( "No Texture has been set." );
  280. # this returns a list of bytes.
  281. decompressed = decompress( texture );
  282. # iterate over 4 byte chunks of the string
  283. imgdata = "";
  284. for idx in range( 0, len(decompressed), 4 ):
  285. # read 4 bytes = BGRA and convert to RGBA
  286. # manual wrote getTexture returns "Textures are stored as zlib compress()ed 600x60 32-bit RGBA data."
  287. # http://mumble.sourceforge.net/slice/Murmur/Server.html#getTexture
  288. # but return values BGRA X(
  289. bgra = unpack( "4B", decompressed[idx:idx+4] );
  290. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  291. # return an 600x60 RGBA image object created from the data
  292. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  293. @protectDjangoErrPage
  294. def setTexture(self, srvid, mumbleid, infile):
  295. # open image, convert to RGBA, and resize to 600x60
  296. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  297. # iterate over the list and pack everything into a string
  298. bgrastring = "";
  299. for ent in list( img.getdata() ):
  300. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  301. # to be reordered when passed to pack()
  302. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  303. # compress using zlib
  304. compressed = compress( bgrastring );
  305. # pack the original length in 4 byte big endian, and concat the compressed
  306. # data to it to emulate qCompress().
  307. texture = pack( ">L", len(bgrastring) ) + compressed;
  308. # finally call murmur and set the texture
  309. self._getIceServerObject(srvid).setTexture(mumbleid, texture)
  310. @protectDjangoErrPage
  311. def verifyPassword(self, srvid, username, password):
  312. return self._getIceServerObject(srvid).verifyPassword(username, password);
  313. @staticmethod
  314. def setUnicodeFlag(data):
  315. ret = ''
  316. if isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict):
  317. ret = {}
  318. for key in data.keys():
  319. ret[MumbleCtlIce_118.setUnicodeFlag(key)] = MumbleCtlIce_118.setUnicodeFlag(data[key])
  320. else:
  321. ret = unicode(data, 'utf-8')
  322. return ret
  323. class MumbleCtlIce_120(MumbleCtlIce_118):
  324. @protectDjangoErrPage
  325. def getRegisteredPlayers(self, srvid, filter = ''):
  326. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  327. ret = {};
  328. for id in users:
  329. ret[id] = ObjectInfo(
  330. userid = id,
  331. name = unicode( users[id], "utf8" ),
  332. email = '',
  333. pw = ''
  334. );
  335. return ret
  336. @protectDjangoErrPage
  337. def getPlayers(self, srvid):
  338. userdata = self._getIceServerObject(srvid).getUsers();
  339. for key in userdata:
  340. if isinstance( userdata[key], str ):
  341. userdata[key] = userdata[key].decode( "UTF-8" )
  342. return userdata
  343. @protectDjangoErrPage
  344. def registerPlayer(self, srvid, name, email, password):
  345. # To get the real values of these ENUM entries, try
  346. # Murmur.UserInfo.UserX.value
  347. import Murmur
  348. user = {
  349. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  350. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  351. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  352. };
  353. return self._getIceServerObject(srvid).registerUser( user );
  354. @protectDjangoErrPage
  355. def unregisterPlayer(self, srvid, mumbleid):
  356. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  357. @protectDjangoErrPage
  358. def getRegistration(self, srvid, mumbleid):
  359. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  360. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" );
  361. import Murmur
  362. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName];
  363. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail];
  364. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment];
  365. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash];
  366. return user;
  367. @protectDjangoErrPage
  368. def setRegistration(self, srvid, mumbleid, name, email, password):
  369. import Murmur
  370. user = {
  371. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  372. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  373. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  374. };
  375. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  376. @protectDjangoErrPage
  377. def getAllConf(self, srvid):
  378. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  379. info = {};
  380. for key in conf:
  381. if key == "playername" and conf[key]:
  382. # Buggy database transition from 1.1.8 -> 1.2.0
  383. # Store username as "username" field and set playername field to empty
  384. info['username'] = conf[key];
  385. self.setConf( srvid, "playername", "" );
  386. self.setConf( srvid, "username", conf[key] );
  387. else:
  388. info[str(key)] = conf[key];
  389. return info;
  390. @protectDjangoErrPage
  391. def getConf(self, srvid, key):
  392. return self._getIceServerObject(srvid).getConf( key )
  393. @protectDjangoErrPage
  394. def setConf(self, srvid, key, value):
  395. if value is None:
  396. value = ''
  397. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  398. @protectDjangoErrPage
  399. def getACL(self, srvid, channelid):
  400. return self._getIceServerObject(srvid).getACL(channelid)
  401. @protectDjangoErrPage
  402. def setACL(self, srvid, channelid, acls, groups, inherit):
  403. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit );