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.

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