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.

526 lines
16 KiB

16 years ago
16 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, error
  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) and murmurversion[:3] < 2:
  113. return MumbleCtlIce_120( connstring, meta );
  114. else:
  115. return MumbleCtlIce_122( connstring, meta );
  116. class MumbleCtlIce_118(MumbleCtlBase):
  117. method = "ICE";
  118. def __init__( self, connstring, meta ):
  119. self.proxy = connstring;
  120. self.meta = meta;
  121. @protectDjangoErrPage
  122. def _getIceServerObject(self, srvid):
  123. return self.meta.getServer(srvid);
  124. @protectDjangoErrPage
  125. def getBootedServers(self):
  126. ret = []
  127. for x in self.meta.getBootedServers():
  128. ret.append(x.id())
  129. return ret
  130. @protectDjangoErrPage
  131. def getVersion( self ):
  132. return self.meta.getVersion();
  133. @protectDjangoErrPage
  134. def getAllServers(self):
  135. ret = []
  136. for x in self.meta.getAllServers():
  137. ret.append(x.id())
  138. return ret
  139. @protectDjangoErrPage
  140. def getRegisteredPlayers(self, srvid, filter = ''):
  141. users = self._getIceServerObject(srvid).getRegisteredPlayers( filter.encode( "UTF-8" ) )
  142. ret = {};
  143. for user in users:
  144. ret[user.playerid] = ObjectInfo(
  145. userid = int( user.playerid ),
  146. name = unicode( user.name, "utf8" ),
  147. email = unicode( user.email, "utf8" ),
  148. pw = unicode( user.pw, "utf8" )
  149. );
  150. return ret
  151. @protectDjangoErrPage
  152. def getChannels(self, srvid):
  153. return self._getIceServerObject(srvid).getChannels();
  154. @protectDjangoErrPage
  155. def getPlayers(self, srvid):
  156. users = self._getIceServerObject(srvid).getPlayers()
  157. ret = {};
  158. for useridx in users:
  159. user = users[useridx];
  160. ret[ user.session ] = ObjectInfo(
  161. session = user.session,
  162. userid = user.playerid,
  163. mute = user.mute,
  164. deaf = user.deaf,
  165. suppress = user.suppressed,
  166. selfMute = user.selfMute,
  167. selfDeaf = user.selfDeaf,
  168. channel = user.channel,
  169. name = user.name,
  170. onlinesecs = user.onlinesecs,
  171. bytespersec = user.bytespersec
  172. );
  173. return ret;
  174. @protectDjangoErrPage
  175. def getDefaultConf(self):
  176. return self.setUnicodeFlag(self.meta.getDefaultConf())
  177. @protectDjangoErrPage
  178. def getAllConf(self, srvid):
  179. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  180. info = {};
  181. for key in conf:
  182. if key == "playername":
  183. info['username'] = conf[key];
  184. else:
  185. info[str(key)] = conf[key];
  186. return info;
  187. @protectDjangoErrPage
  188. def newServer(self):
  189. return self.meta.newServer().id()
  190. @protectDjangoErrPage
  191. def isBooted( self, srvid ):
  192. return bool( self._getIceServerObject(srvid).isRunning() );
  193. @protectDjangoErrPage
  194. def start( self, srvid ):
  195. self._getIceServerObject(srvid).start();
  196. @protectDjangoErrPage
  197. def stop( self, srvid ):
  198. self._getIceServerObject(srvid).stop();
  199. @protectDjangoErrPage
  200. def deleteServer( self, srvid ):
  201. if self._getIceServerObject(srvid).isRunning():
  202. self._getIceServerObject(srvid).stop()
  203. self._getIceServerObject(srvid).delete()
  204. @protectDjangoErrPage
  205. def setSuperUserPassword(self, srvid, value):
  206. self._getIceServerObject(srvid).setSuperuserPassword( value.encode( "UTF-8" ) )
  207. @protectDjangoErrPage
  208. def getConf(self, srvid, key):
  209. if key == "username":
  210. key = "playername";
  211. return self._getIceServerObject(srvid).getConf( key )
  212. @protectDjangoErrPage
  213. def setConf(self, srvid, key, value):
  214. if key == "username":
  215. key = "playername";
  216. if value is None:
  217. value = ''
  218. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  219. @protectDjangoErrPage
  220. def registerPlayer(self, srvid, name, email, password):
  221. mumbleid = self._getIceServerObject(srvid).registerPlayer( name.encode( "UTF-8" ) )
  222. self.setRegistration( srvid, mumbleid, name, email, password );
  223. return mumbleid;
  224. @protectDjangoErrPage
  225. def unregisterPlayer(self, srvid, mumbleid):
  226. self._getIceServerObject(srvid).unregisterPlayer(mumbleid)
  227. @protectDjangoErrPage
  228. def getRegistration(self, srvid, mumbleid):
  229. user = self._getIceServerObject(srvid).getRegistration(mumbleid)
  230. return ObjectInfo(
  231. userid = mumbleid,
  232. name = user.name,
  233. email = user.email,
  234. pw = '',
  235. );
  236. @protectDjangoErrPage
  237. def setRegistration(self, srvid, mumbleid, name, email, password):
  238. import Murmur
  239. user = Murmur.Player()
  240. user.playerid = mumbleid;
  241. user.name = name.encode( "UTF-8" )
  242. user.email = email.encode( "UTF-8" )
  243. user.pw = password.encode( "UTF-8" )
  244. # update*r*egistration r is lowercase...
  245. return self._getIceServerObject(srvid).updateregistration(user)
  246. @protectDjangoErrPage
  247. def getACL(self, srvid, channelid):
  248. # need to convert acls to say "userid" instead of "playerid". meh.
  249. raw_acls, raw_groups, raw_inherit = self._getIceServerObject(srvid).getACL(channelid)
  250. acls = [ ObjectInfo(
  251. applyHere = rule.applyHere,
  252. applySubs = rule.applySubs,
  253. inherited = rule.inherited,
  254. userid = rule.playerid,
  255. group = rule.group,
  256. allow = rule.allow,
  257. deny = rule.deny,
  258. )
  259. for rule in raw_acls
  260. ];
  261. return acls, raw_groups, raw_inherit;
  262. @protectDjangoErrPage
  263. def setACL(self, srvid, channelid, acls, groups, inherit):
  264. import Murmur
  265. ice_acls = [];
  266. for rule in acls:
  267. ice_rule = Murmur.ACL();
  268. ice_rule.applyHere = rule.applyHere;
  269. ice_rule.applySubs = rule.applySubs;
  270. ice_rule.inherited = rule.inherited;
  271. ice_rule.playerid = rule.userid;
  272. ice_rule.group = rule.group;
  273. ice_rule.allow = rule.allow;
  274. ice_rule.deny = rule.deny;
  275. ice_acls.append(ice_rule);
  276. return self._getIceServerObject(srvid).setACL( channelid, ice_acls, groups, inherit );
  277. @protectDjangoErrPage
  278. def getTexture(self, srvid, mumbleid):
  279. texture = self._getIceServerObject(srvid).getTexture(mumbleid)
  280. if len(texture) == 0:
  281. raise ValueError( "No Texture has been set." );
  282. # this returns a list of bytes.
  283. try:
  284. decompressed = decompress( texture );
  285. except error, err:
  286. raise ValueError( err )
  287. # iterate over 4 byte chunks of the string
  288. imgdata = "";
  289. for idx in range( 0, len(decompressed), 4 ):
  290. # read 4 bytes = BGRA and convert to RGBA
  291. # manual wrote getTexture returns "Textures are stored as zlib compress()ed 600x60 32-bit RGBA data."
  292. # http://mumble.sourceforge.net/slice/Murmur/Server.html#getTexture
  293. # but return values BGRA X(
  294. bgra = unpack( "4B", decompressed[idx:idx+4] );
  295. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  296. # return an 600x60 RGBA image object created from the data
  297. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  298. @protectDjangoErrPage
  299. def setTexture(self, srvid, mumbleid, infile):
  300. # open image, convert to RGBA, and resize to 600x60
  301. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  302. # iterate over the list and pack everything into a string
  303. bgrastring = "";
  304. for ent in list( img.getdata() ):
  305. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  306. # to be reordered when passed to pack()
  307. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  308. # compress using zlib
  309. compressed = compress( bgrastring );
  310. # pack the original length in 4 byte big endian, and concat the compressed
  311. # data to it to emulate qCompress().
  312. texture = pack( ">L", len(bgrastring) ) + compressed;
  313. # finally call murmur and set the texture
  314. self._getIceServerObject(srvid).setTexture(mumbleid, texture)
  315. @protectDjangoErrPage
  316. def verifyPassword(self, srvid, username, password):
  317. return self._getIceServerObject(srvid).verifyPassword(username, password);
  318. @staticmethod
  319. def setUnicodeFlag(data):
  320. ret = ''
  321. if isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict):
  322. ret = {}
  323. for key in data.keys():
  324. ret[MumbleCtlIce_118.setUnicodeFlag(key)] = MumbleCtlIce_118.setUnicodeFlag(data[key])
  325. else:
  326. ret = unicode(data, 'utf-8')
  327. return ret
  328. class MumbleCtlIce_120(MumbleCtlIce_118):
  329. @protectDjangoErrPage
  330. def getRegisteredPlayers(self, srvid, filter = ''):
  331. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  332. ret = {};
  333. for id in users:
  334. ret[id] = ObjectInfo(
  335. userid = id,
  336. name = unicode( users[id], "utf8" ),
  337. email = '',
  338. pw = ''
  339. );
  340. return ret
  341. @protectDjangoErrPage
  342. def getPlayers(self, srvid):
  343. userdata = self._getIceServerObject(srvid).getUsers();
  344. for key in userdata:
  345. if isinstance( userdata[key], str ):
  346. userdata[key] = userdata[key].decode( "UTF-8" )
  347. return userdata
  348. @protectDjangoErrPage
  349. def registerPlayer(self, srvid, name, email, password):
  350. # To get the real values of these ENUM entries, try
  351. # Murmur.UserInfo.UserX.value
  352. import Murmur
  353. user = {
  354. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  355. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  356. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  357. };
  358. return self._getIceServerObject(srvid).registerUser( user );
  359. @protectDjangoErrPage
  360. def unregisterPlayer(self, srvid, mumbleid):
  361. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  362. @protectDjangoErrPage
  363. def getRegistration(self, srvid, mumbleid):
  364. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  365. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" );
  366. import Murmur
  367. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName];
  368. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail];
  369. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment];
  370. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash];
  371. return user;
  372. @protectDjangoErrPage
  373. def setRegistration(self, srvid, mumbleid, name, email, password):
  374. import Murmur
  375. user = {
  376. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  377. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  378. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  379. };
  380. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  381. @protectDjangoErrPage
  382. def getAllConf(self, srvid):
  383. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  384. info = {};
  385. for key in conf:
  386. if key == "playername" and conf[key]:
  387. # Buggy database transition from 1.1.8 -> 1.2.0
  388. # Store username as "username" field and set playername field to empty
  389. info['username'] = conf[key];
  390. self.setConf( srvid, "playername", "" );
  391. self.setConf( srvid, "username", conf[key] );
  392. else:
  393. info[str(key)] = conf[key];
  394. return info;
  395. @protectDjangoErrPage
  396. def getConf(self, srvid, key):
  397. return self._getIceServerObject(srvid).getConf( key )
  398. @protectDjangoErrPage
  399. def setConf(self, srvid, key, value):
  400. if value is None:
  401. value = ''
  402. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  403. @protectDjangoErrPage
  404. def getACL(self, srvid, channelid):
  405. return self._getIceServerObject(srvid).getACL(channelid)
  406. @protectDjangoErrPage
  407. def setACL(self, srvid, channelid, acls, groups, inherit):
  408. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit );
  409. class MumbleCtlIce_122(MumbleCtlIce_120):
  410. @protectDjangoErrPage
  411. def getTexture(self, srvid, mumbleid):
  412. texture = self._getIceServerObject(srvid).getTexture(mumbleid)
  413. if len(texture) == 0:
  414. raise ValueError( "No Texture has been set." );
  415. imgdata = ""
  416. for idx in range( 0, len(texture)-4, 4 ):
  417. bgra = unpack( "4B", texture[idx:idx+4] );
  418. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  419. # return an 600x60 RGBA image object created from the data
  420. return Image.fromstring( "RGBA", ( 88, 60 ), imgdata );
  421. @protectDjangoErrPage
  422. def setTexture(self, srvid, mumbleid, infile):
  423. # open image, convert to RGBA, and resize to 600x60
  424. img = Image.open( infile ).convert( "RGBA" ).transform( ( 88, 60 ), Image.EXTENT, ( 0, 0, 88, 60 ) );
  425. # iterate over the list and pack everything into a string
  426. bgrastring = "";
  427. for ent in list( img.getdata() ):
  428. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  429. # to be reordered when passed to pack()
  430. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  431. # finally call murmur and set the texture
  432. self._getIceServerObject(srvid).setTexture(mumbleid, bgrastring)