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.

495 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, 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):
  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. try:
  282. decompressed = decompress( texture );
  283. except error, err:
  284. raise ValueError( err )
  285. # iterate over 4 byte chunks of the string
  286. imgdata = "";
  287. for idx in range( 0, len(decompressed), 4 ):
  288. # read 4 bytes = BGRA and convert to RGBA
  289. # manual wrote getTexture returns "Textures are stored as zlib compress()ed 600x60 32-bit RGBA data."
  290. # http://mumble.sourceforge.net/slice/Murmur/Server.html#getTexture
  291. # but return values BGRA X(
  292. bgra = unpack( "4B", decompressed[idx:idx+4] );
  293. imgdata += pack( "4B", bgra[2], bgra[1], bgra[0], bgra[3] );
  294. # return an 600x60 RGBA image object created from the data
  295. return Image.fromstring( "RGBA", ( 600, 60 ), imgdata );
  296. @protectDjangoErrPage
  297. def setTexture(self, srvid, mumbleid, infile):
  298. # open image, convert to RGBA, and resize to 600x60
  299. img = Image.open( infile ).convert( "RGBA" ).transform( ( 600, 60 ), Image.EXTENT, ( 0, 0, 600, 60 ) );
  300. # iterate over the list and pack everything into a string
  301. bgrastring = "";
  302. for ent in list( img.getdata() ):
  303. # ent is in RGBA format, but Murmur wants BGRA (ARGB inverse), so stuff needs
  304. # to be reordered when passed to pack()
  305. bgrastring += pack( "4B", ent[2], ent[1], ent[0], ent[3] );
  306. # compress using zlib
  307. compressed = compress( bgrastring );
  308. # pack the original length in 4 byte big endian, and concat the compressed
  309. # data to it to emulate qCompress().
  310. texture = pack( ">L", len(bgrastring) ) + compressed;
  311. # finally call murmur and set the texture
  312. self._getIceServerObject(srvid).setTexture(mumbleid, texture)
  313. @protectDjangoErrPage
  314. def verifyPassword(self, srvid, username, password):
  315. return self._getIceServerObject(srvid).verifyPassword(username, password);
  316. @staticmethod
  317. def setUnicodeFlag(data):
  318. ret = ''
  319. if isinstance(data, tuple) or isinstance(data, list) or isinstance(data, dict):
  320. ret = {}
  321. for key in data.keys():
  322. ret[MumbleCtlIce_118.setUnicodeFlag(key)] = MumbleCtlIce_118.setUnicodeFlag(data[key])
  323. else:
  324. ret = unicode(data, 'utf-8')
  325. return ret
  326. class MumbleCtlIce_120(MumbleCtlIce_118):
  327. @protectDjangoErrPage
  328. def getRegisteredPlayers(self, srvid, filter = ''):
  329. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  330. ret = {};
  331. for id in users:
  332. ret[id] = ObjectInfo(
  333. userid = id,
  334. name = unicode( users[id], "utf8" ),
  335. email = '',
  336. pw = ''
  337. );
  338. return ret
  339. @protectDjangoErrPage
  340. def getPlayers(self, srvid):
  341. userdata = self._getIceServerObject(srvid).getUsers();
  342. for key in userdata:
  343. if isinstance( userdata[key], str ):
  344. userdata[key] = userdata[key].decode( "UTF-8" )
  345. return userdata
  346. @protectDjangoErrPage
  347. def registerPlayer(self, srvid, name, email, password):
  348. # To get the real values of these ENUM entries, try
  349. # Murmur.UserInfo.UserX.value
  350. import Murmur
  351. user = {
  352. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  353. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  354. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  355. };
  356. return self._getIceServerObject(srvid).registerUser( user );
  357. @protectDjangoErrPage
  358. def unregisterPlayer(self, srvid, mumbleid):
  359. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  360. @protectDjangoErrPage
  361. def getRegistration(self, srvid, mumbleid):
  362. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  363. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" );
  364. import Murmur
  365. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName];
  366. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail];
  367. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment];
  368. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash];
  369. return user;
  370. @protectDjangoErrPage
  371. def setRegistration(self, srvid, mumbleid, name, email, password):
  372. import Murmur
  373. user = {
  374. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  375. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  376. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  377. };
  378. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  379. @protectDjangoErrPage
  380. def getAllConf(self, srvid):
  381. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  382. info = {};
  383. for key in conf:
  384. if key == "playername" and conf[key]:
  385. # Buggy database transition from 1.1.8 -> 1.2.0
  386. # Store username as "username" field and set playername field to empty
  387. info['username'] = conf[key];
  388. self.setConf( srvid, "playername", "" );
  389. self.setConf( srvid, "username", conf[key] );
  390. else:
  391. info[str(key)] = conf[key];
  392. return info;
  393. @protectDjangoErrPage
  394. def getConf(self, srvid, key):
  395. return self._getIceServerObject(srvid).getConf( key )
  396. @protectDjangoErrPage
  397. def setConf(self, srvid, key, value):
  398. if value is None:
  399. value = ''
  400. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  401. @protectDjangoErrPage
  402. def getACL(self, srvid, channelid):
  403. return self._getIceServerObject(srvid).getACL(channelid)
  404. @protectDjangoErrPage
  405. def setACL(self, srvid, channelid, acls, groups, inherit):
  406. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit );