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.

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