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.

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