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.

533 lines
16 KiB

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