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.

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