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.

640 lines
22 KiB

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