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.

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