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.

415 lines
15 KiB

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