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.

399 lines
14 KiB

16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
16 years ago
  1. # -*- coding: utf-8 -*-
  2. # kate: space-indent on; indent-width 4; replace-tabs on;
  3. """
  4. * Copyright © 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. import socket
  17. import datetime
  18. import re
  19. from time import time
  20. from django.utils.http import urlquote
  21. from django.conf import settings
  22. def cmp_channels( left, rite ):
  23. """ Compare two channels, first by position, and if that equals, by name. """
  24. if hasattr( left, "position" ) and hasattr( rite, "position" ):
  25. byorder = cmp( left.position, rite.position )
  26. if byorder != 0:
  27. return byorder
  28. return cmp_names( left, rite )
  29. def cmp_names( left, rite ):
  30. """ Compare two objects by their name property. """
  31. return cmp( left.name, rite.name )
  32. class mmChannel( object ):
  33. """ Represents a channel in Murmur. """
  34. def __init__( self, server, channel_obj, parent_chan = None ):
  35. self.server = server
  36. self.players = list()
  37. self.subchans = list()
  38. self.linked = list()
  39. self.channel_obj = channel_obj
  40. self.chanid = channel_obj.id
  41. self.parent = parent_chan
  42. if self.parent is not None:
  43. self.parent.subchans.append( self )
  44. self._acl = None
  45. # Lookup unknown attributes in self.channel_obj to automatically include Murmur's fields
  46. def __getattr__( self, key ):
  47. if hasattr( self.channel_obj, key ):
  48. return getattr( self.channel_obj, key )
  49. else:
  50. raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, key ) )
  51. def parent_channels( self ):
  52. """ Return the names of this channel's parents in the channel tree. """
  53. if self.parent is None or self.parent.is_server or self.parent.chanid == 0:
  54. return []
  55. return self.parent.parent_channels() + [self.parent.name]
  56. def getACL( self ):
  57. """ Retrieve the ACL for this channel. """
  58. if not self._acl:
  59. self._acl = mmACL( self, self.server.ctl.getACL( self.server.srvid, self.chanid ) )
  60. return self._acl
  61. acl = property( getACL )
  62. is_server = False
  63. is_channel = True
  64. is_player = False
  65. playerCount = property(
  66. lambda self: len( self.players ) + sum( [ chan.playerCount for chan in self.subchans ] ),
  67. doc="The number of players in this channel."
  68. )
  69. id = property(
  70. lambda self: "channel_%d"%self.chanid,
  71. doc="A string ready to be used in an id property of an HTML tag."
  72. )
  73. top_or_not_empty = property(
  74. lambda self: self.parent is None or self.parent.chanid == 0 or self.playerCount > 0,
  75. doc="True if this channel needs to be shown because it is root, a child of root, or has players."
  76. )
  77. show = property( lambda self: settings.SHOW_EMPTY_SUBCHANS or self.top_or_not_empty )
  78. def __str__( self ):
  79. return '<Channel "%s" (%d)>' % ( self.name, self.chanid )
  80. def sort( self ):
  81. """ Sort my subchannels and players, and then iterate over them and sort them recursively. """
  82. self.subchans.sort( cmp_channels )
  83. self.players.sort( cmp_names )
  84. for subc in self.subchans:
  85. subc.sort()
  86. def visit( self, callback, lvl = 0 ):
  87. """ Call callback on myself, then visit my subchans, then my players. """
  88. callback( self, lvl )
  89. for subc in self.subchans:
  90. subc.visit( callback, lvl + 1 )
  91. for plr in self.players:
  92. plr.visit( callback, lvl + 1 )
  93. def getURL( self, for_user = None ):
  94. """ Create an URL to connect to this channel. The URL is of the form
  95. mumble://username@host:port/parentchans/self.name
  96. """
  97. from urlparse import urlunsplit
  98. versionstr = "version=%s" % self.server.prettyversion
  99. if self.parent is not None:
  100. chanlist = self.parent_channels() + [self.name]
  101. chanlist = [ urlquote( chan ) for chan in chanlist ]
  102. urlpath = "/".join( chanlist )
  103. else:
  104. urlpath = ""
  105. if for_user is not None:
  106. netloc = "%s@%s" % ( for_user.name, self.server.netloc )
  107. return urlunsplit(( "mumble", netloc, urlpath, versionstr, "" ))
  108. else:
  109. return urlunsplit(( "mumble", self.server.netloc, urlpath, versionstr, "" ))
  110. connecturl = property( getURL )
  111. def setDefault( self ):
  112. """ Make this the server's default channel. """
  113. self.server.defchan = self.chanid
  114. self.server.save()
  115. is_default = property(
  116. lambda self: self.server.defchan == self.chanid,
  117. doc="True if this channel is the server's default channel."
  118. )
  119. def asDict( self, authed=False ):
  120. chandata = self.channel_obj.__dict__.copy()
  121. chandata['users'] = [ pl.asDict( authed ) for pl in self.players ]
  122. chandata['channels'] = [ sc.asDict( authed ) for sc in self.subchans ]
  123. chandata['x-connecturl'] = self.connecturl
  124. return chandata
  125. def asXml( self, parentnode, authed=False ):
  126. from xml.etree.cElementTree import SubElement
  127. me = SubElement( parentnode, "channel" )
  128. for key in self.channel_obj.__dict__:
  129. val = getattr( self.channel_obj, key )
  130. if isinstance( val, bool ):
  131. me.set( key, unicode(val).lower() )
  132. elif isinstance( val, list ) or isinstance( val, tuple ):
  133. me.set( key, ','.join( ( unicode(elem) for elem in val ) ) )
  134. elif isinstance( val, str ):
  135. me.set( key, unicode(val, "utf8") )
  136. else:
  137. me.set( key, unicode(val) )
  138. me.set( "x-connecturl", self.connecturl )
  139. for sc in self.subchans:
  140. sc.asXml(me, authed)
  141. for pl in self.players:
  142. pl.asXml(me, authed)
  143. def asMvXml( self, parentnode ):
  144. """ Return an XML tree for this channel suitable for MumbleViewer-ng. """
  145. from xml.etree.cElementTree import SubElement
  146. me = SubElement( parentnode, "item" , id=self.id, rel='channel' )
  147. content = SubElement( me, "content" )
  148. name = SubElement( content , "name" )
  149. name.text = self.name
  150. for sc in self.subchans:
  151. sc.asMvXml(me)
  152. for pl in self.players:
  153. pl.asMvXml(me)
  154. def asMvJson( self ):
  155. """ Return a Dict for this channel suitable for MumbleViewer-ng. """
  156. return {
  157. "attributes": {
  158. "href": self.connecturl,
  159. "id": self.id,
  160. "rel": "channel",
  161. },
  162. "data": self.name,
  163. "children": [ sc.asMvJson() for sc in self.subchans ] + \
  164. [ pl.asMvJson() for pl in self.players ],
  165. "state": { False: "closed", True: "open" }[self.top_or_not_empty],
  166. }
  167. class mmPlayer( object ):
  168. """ Represents a Player in Murmur. """
  169. def __init__( self, server, player_obj, player_chan ):
  170. self.player_obj = player_obj
  171. self.onlinesince = datetime.datetime.fromtimestamp( float( time() - player_obj.onlinesecs ) )
  172. self.channel = player_chan
  173. self.channel.players.append( self )
  174. if self.isAuthed:
  175. from mumble.models import MumbleUser
  176. try:
  177. self.mumbleuser = MumbleUser.objects.get( mumbleid=self.userid, server=server )
  178. except MumbleUser.DoesNotExist:
  179. self.mumbleuser = None
  180. else:
  181. self.mumbleuser = None
  182. # Lookup unknown attributes in self.player_obj to automatically include Murmur's fields
  183. def __getattr__( self, key ):
  184. if hasattr( self.player_obj, key ):
  185. return getattr( self.player_obj, key )
  186. else:
  187. raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, key ) )
  188. def __str__( self ):
  189. return '<Player "%s" (%d, %d)>' % ( self.name, self.session, self.userid )
  190. hasComment = property(
  191. lambda self: hasattr( self.player_obj, "comment" ) and bool(self.player_obj.comment),
  192. doc="True if this player has a comment set."
  193. )
  194. isAuthed = property(
  195. lambda self: self.userid != -1,
  196. doc="True if this player is authenticated (+A)."
  197. )
  198. isAdmin = property(
  199. lambda self: self.mumbleuser and self.mumbleuser.getAdmin(),
  200. doc="True if this player is in the Admin group in the ACL."
  201. )
  202. is_server = False
  203. is_channel = False
  204. is_player = True
  205. def getIpAsString( self ):
  206. """ Get the client's IPv4 or IPv6 address, in a pretty format. """
  207. addr = self.player_obj.address
  208. if max( addr[:10] ) == 0 and addr[10:12] == (255, 255):
  209. return "%d.%d.%d.%d" % tuple( addr[12:] )
  210. ip6addr = [(hi << 8 | lo) for (hi, lo) in zip(addr[0::2], addr[1::2])]
  211. # colon-separated string:
  212. ipstr = ':'.join([ ("%x" % part) for part in ip6addr ])
  213. # 0:0:0 -> ::
  214. return re.sub( "((^|:)(0:){2,})", '::', ipstr, 1 )
  215. ipaddress = property( getIpAsString )
  216. fqdn = property( lambda self: socket.getfqdn( self.ipaddress ),
  217. doc="The fully qualified domain name of the user's host." )
  218. # kept for compatibility to mmChannel (useful for traversal funcs)
  219. playerCount = property( lambda self: -1, doc="Exists only for compatibility to mmChannel." )
  220. id = property(
  221. lambda self: "player_%d"%self.session,
  222. doc="A string ready to be used in an id property of an HTML tag."
  223. )
  224. def visit( self, callback, lvl = 0 ):
  225. """ Call callback on myself. """
  226. callback( self, lvl )
  227. def asDict( self, authed=False ):
  228. pldata = self.player_obj.__dict__.copy()
  229. if authed:
  230. pldata["x-addrstring"] = self.ipaddress
  231. else:
  232. del pldata["address"]
  233. if self.mumbleuser and self.mumbleuser.hasTexture():
  234. pldata['x-texture'] = self.mumbleuser.textureUrl
  235. return pldata
  236. def asXml( self, parentnode, authed=False ):
  237. from xml.etree.cElementTree import SubElement
  238. me = SubElement( parentnode, "user" )
  239. for key in self.player_obj.__dict__:
  240. val = getattr( self.player_obj, key )
  241. if isinstance( val, bool ):
  242. me.set( key, unicode(val).lower() )
  243. elif isinstance( val, list ) or isinstance( val, tuple ):
  244. me.set( key, ','.join( ( unicode(elem) for elem in val ) ) )
  245. elif isinstance( val, str ):
  246. me.set( key, unicode(val, "utf8") )
  247. else:
  248. me.set( key, unicode(val) )
  249. if authed:
  250. me.set( "x-addrstring", self.ipaddress )
  251. else:
  252. me.set( "address", "" )
  253. if self.mumbleuser and self.mumbleuser.hasTexture():
  254. me.set( 'x-texture', self.mumbleuser.textureUrl )
  255. def asMvXml( self, parentnode ):
  256. """ Return an XML node for this player suitable for MumbleViewer-ng. """
  257. from xml.etree.cElementTree import SubElement
  258. me = SubElement( parentnode, "item" , id=self.id, rel='user' )
  259. content = SubElement( me, "content" )
  260. name = SubElement( content , "name" )
  261. name.text = self.name
  262. def asMvJson( self ):
  263. """ Return a Dict for this player suitable for MumbleViewer-ng. """
  264. return {
  265. "attributes": {
  266. "id": self.id,
  267. "rel": "user",
  268. },
  269. 'data': self.name,
  270. }
  271. class mmACL( object ):
  272. """ Represents an ACL for a certain channel. """
  273. def __init__( self, channel, acl_obj ):
  274. self.channel = channel
  275. self.acls, self.groups, self.inherit = acl_obj
  276. self.groups_dict = {}
  277. for group in self.groups:
  278. self.groups_dict[ group.name ] = group
  279. def group_has_member( self, name, userid ):
  280. """ Checks if the given userid is a member of the given group in this channel. """
  281. if name not in self.groups_dict:
  282. raise ReferenceError( "No such group '%s'" % name )
  283. return userid in self.groups_dict[name].add or userid in self.groups_dict[name].members
  284. def group_add_member( self, name, userid ):
  285. """ Make sure this userid is a member of the group in this channel (and subs). """
  286. if name not in self.groups_dict:
  287. raise ReferenceError( "No such group '%s'" % name )
  288. group = self.groups_dict[name]
  289. # if neither inherited nor to be added, add
  290. if userid not in group.members and userid not in group.add:
  291. group.add.append( userid )
  292. # if to be removed, unremove
  293. if userid in group.remove:
  294. group.remove.remove( userid )
  295. def group_remove_member( self, name, userid ):
  296. """ Make sure this userid is NOT a member of the group in this channel (and subs). """
  297. if name not in self.groups_dict:
  298. raise ReferenceError( "No such group '%s'" % name )
  299. group = self.groups_dict[name]
  300. # if added here, unadd
  301. if userid in group.add:
  302. group.add.remove( userid )
  303. # if member and not in remove, add to remove
  304. elif userid in group.members and userid not in group.remove:
  305. group.remove.append( userid )
  306. def save( self ):
  307. """ Send this ACL to Murmur. """
  308. return self.channel.server.ctl.setACL(
  309. self.channel.server.srvid,
  310. self.channel.chanid,
  311. self.acls, self.groups, self.inherit
  312. )