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.

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