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.

647 lines
23 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 moveChannel(self, srvid, channelid, parentid):
  359. srv = self._getIceServerObject(srvid)
  360. state = srv.getChannelState(channelid)
  361. state.parent = parentid
  362. srv.setChannelState(state)
  363. @protectDjangoErrPage
  364. def moveUser(self, srvid, sessionid, channelid):
  365. srv = self._getIceServerObject(srvid)
  366. state = srv.getState(sessionid)
  367. state.channel = channelid
  368. srv.setState(state)
  369. @protectDjangoErrPage
  370. def muteUser(self, srvid, sessionid, mute=True):
  371. srv = self._getIceServerObject(srvid)
  372. state = srv.getState(sessionid)
  373. state.mute = mute
  374. srv.setState(state)
  375. @protectDjangoErrPage
  376. def deafenUser(self, srvid, sessionid, deaf=True):
  377. srv = self._getIceServerObject(srvid)
  378. state = srv.getState(sessionid)
  379. state.deaf = deaf
  380. srv.setState(state)
  381. class MumbleCtlIce_120(MumbleCtlIce_118):
  382. @protectDjangoErrPage
  383. def getRegisteredPlayers(self, srvid, filter = ''):
  384. users = self._getIceServerObject( srvid ).getRegisteredUsers( filter.encode( "UTF-8" ) )
  385. ret = {}
  386. for id in users:
  387. ret[id] = ObjectInfo(
  388. userid = id,
  389. name = unicode( users[id], "utf8" ),
  390. email = '',
  391. pw = ''
  392. )
  393. return ret
  394. @protectDjangoErrPage
  395. def getPlayers(self, srvid):
  396. userdata = self._getIceServerObject(srvid).getUsers()
  397. for key in userdata:
  398. if isinstance( userdata[key], str ):
  399. userdata[key] = userdata[key].decode( "UTF-8" )
  400. return userdata
  401. @protectDjangoErrPage
  402. def getState(self, srvid, sessionid):
  403. userdata = self._getIceServerObject(srvid).getState(sessionid)
  404. for key in userdata.__dict__:
  405. attr = getattr( userdata, key )
  406. if isinstance( attr, str ):
  407. setattr( userdata, key, attr.decode( "UTF-8" ) )
  408. return userdata
  409. @protectDjangoErrPage
  410. def registerPlayer(self, srvid, name, email, password):
  411. # To get the real values of these ENUM entries, try
  412. # Murmur.UserInfo.UserX.value
  413. import Murmur
  414. user = {
  415. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  416. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  417. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  418. }
  419. return self._getIceServerObject(srvid).registerUser( user )
  420. @protectDjangoErrPage
  421. def unregisterPlayer(self, srvid, mumbleid):
  422. self._getIceServerObject(srvid).unregisterUser(mumbleid)
  423. @protectDjangoErrPage
  424. def getRegistration(self, srvid, mumbleid):
  425. reg = self._getIceServerObject( srvid ).getRegistration( mumbleid )
  426. user = ObjectInfo( userid=mumbleid, name="", email="", comment="", hash="", pw="" )
  427. import Murmur
  428. if Murmur.UserInfo.UserName in reg: user.name = reg[Murmur.UserInfo.UserName]
  429. if Murmur.UserInfo.UserEmail in reg: user.email = reg[Murmur.UserInfo.UserEmail]
  430. if Murmur.UserInfo.UserComment in reg: user.comment = reg[Murmur.UserInfo.UserComment]
  431. if Murmur.UserInfo.UserHash in reg: user.hash = reg[Murmur.UserInfo.UserHash]
  432. return user
  433. @protectDjangoErrPage
  434. def setRegistration(self, srvid, mumbleid, name, email, password):
  435. import Murmur
  436. user = {
  437. Murmur.UserInfo.UserName: name.encode( "UTF-8" ),
  438. Murmur.UserInfo.UserEmail: email.encode( "UTF-8" ),
  439. Murmur.UserInfo.UserPassword: password.encode( "UTF-8" ),
  440. }
  441. return self._getIceServerObject( srvid ).updateRegistration( mumbleid, user )
  442. @protectDjangoErrPage
  443. def getAllConf(self, srvid):
  444. conf = self.setUnicodeFlag(self._getIceServerObject(srvid).getAllConf())
  445. info = {}
  446. for key in conf:
  447. if key == "playername" and conf[key]:
  448. # Buggy database transition from 1.1.8 -> 1.2.0
  449. # Store username as "username" field and set playername field to empty
  450. info['username'] = conf[key]
  451. self.setConf( srvid, "playername", "" )
  452. self.setConf( srvid, "username", conf[key] )
  453. else:
  454. info[str(key)] = conf[key]
  455. return info
  456. @protectDjangoErrPage
  457. def getConf(self, srvid, key):
  458. return self._getIceServerObject(srvid).getConf( key )
  459. @protectDjangoErrPage
  460. def setConf(self, srvid, key, value):
  461. if value is None:
  462. value = ''
  463. self._getIceServerObject(srvid).setConf( key, value.encode( "UTF-8" ) )
  464. @protectDjangoErrPage
  465. def getACL(self, srvid, channelid):
  466. return self._getIceServerObject(srvid).getACL(channelid)
  467. @protectDjangoErrPage
  468. def setACL(self, srvid, channelid, acls, groups, inherit):
  469. return self._getIceServerObject(srvid).setACL( channelid, acls, groups, inherit )
  470. @protectDjangoErrPage
  471. def getBans(self, srvid):
  472. return self._getIceServerObject(srvid).getBans()
  473. @protectDjangoErrPage
  474. def setBans(self, srvid, bans):
  475. return self._getIceServerObject(srvid).setBans(bans)
  476. @protectDjangoErrPage
  477. def addBanForSession(self, srvid, sessionid, **kwargs):
  478. session = self.getState(srvid, sessionid)
  479. if "bits" not in kwargs:
  480. kwargs["bits"] = 128
  481. if "start" not in kwargs:
  482. kwargs["start"] = int(time())
  483. if "duration" not in kwargs:
  484. kwargs["duration"] = 3600
  485. return self.addBan(srvid, address=session.address, **kwargs)
  486. @protectDjangoErrPage
  487. def addBan(self, srvid, **kwargs):
  488. for key in kwargs:
  489. if isinstance( kwargs[key], unicode ):
  490. kwargs[key] = kwargs[key].encode("UTF-8")
  491. from Murmur import Ban
  492. srvbans = self.getBans(srvid)
  493. srvbans.append( Ban( **kwargs ) )
  494. return self.setBans(srvid, srvbans)
  495. @protectDjangoErrPage
  496. def kickUser(self, srvid, userid, reason=""):
  497. return self._getIceServerObject(srvid).kickUser( userid, reason.encode("UTF-8") )
  498. @protectDjangoErrPage
  499. def getUptime(self, srvid):
  500. return self._getIceServerObject(srvid).getUptime()
  501. class MumbleCtlIce_122(MumbleCtlIce_120):
  502. @protectDjangoErrPage
  503. def getTexture(self, srvid, mumbleid):
  504. raise ValueError( "This method is buggy in 1.2.2, sorry dude." )
  505. @protectDjangoErrPage
  506. def setTexture(self, srvid, mumbleid, infile):
  507. buf = StringIO()
  508. infile.save( buf, "PNG" )
  509. buf.seek(0)
  510. self._getIceServerObject(srvid).setTexture(mumbleid, buf.read())
  511. class MumbleCtlIce_123(MumbleCtlIce_120):
  512. @protectDjangoErrPage
  513. def getRawTexture(self, srvid, mumbleid):
  514. return self._getIceServerObject(srvid).getTexture(mumbleid)
  515. @protectDjangoErrPage
  516. def getTexture(self, srvid, mumbleid):
  517. texture = self.getRawTexture(srvid, mumbleid)
  518. if len(texture) == 0:
  519. raise ValueError( "No Texture has been set." )
  520. from StringIO import StringIO
  521. try:
  522. return Image.open( StringIO( texture ) )
  523. except IOError, err:
  524. raise ValueError( err )
  525. @protectDjangoErrPage
  526. def setTexture(self, srvid, mumbleid, infile):
  527. buf = StringIO()
  528. infile.save( buf, "PNG" )
  529. buf.seek(0)
  530. self._getIceServerObject(srvid).setTexture(mumbleid, buf.read())