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.

408 lines
14 KiB

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