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.

351 lines
12 KiB

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 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 ):
  120. chandata = self.channel_obj.__dict__.copy()
  121. chandata['players'] = [ pl.asDict() for pl in self.players ]
  122. chandata['subchans'] = [ sc.asDict() for sc in self.subchans ]
  123. return chandata
  124. def asMvXml( self, parentnode ):
  125. """ Return an XML tree for this channel suitable for MumbleViewer-ng. """
  126. from xml.etree.cElementTree import SubElement
  127. me = SubElement( parentnode, "item" , id=self.id, rel='channel' )
  128. content = SubElement( me, "content" )
  129. name = SubElement( content , "name" )
  130. name.text = self.name
  131. for sc in self.subchans:
  132. sc.asMvXml(me)
  133. for pl in self.players:
  134. pl.asMvXml(me)
  135. def asMvJson( self ):
  136. """ Return a Dict for this channel suitable for MumbleViewer-ng. """
  137. return {
  138. "attributes": {
  139. "href": self.connecturl,
  140. "id": self.id,
  141. "rel": "channel",
  142. },
  143. "data": self.name,
  144. "children": [ sc.asMvJson() for sc in self.subchans ] + \
  145. [ pl.asMvJson() for pl in self.players ],
  146. "state": { False: "closed", True: "open" }[self.top_or_not_empty],
  147. }
  148. class mmPlayer( object ):
  149. """ Represents a Player in Murmur. """
  150. def __init__( self, server, player_obj, player_chan ):
  151. self.player_obj = player_obj
  152. self.onlinesince = datetime.datetime.fromtimestamp( float( time() - player_obj.onlinesecs ) )
  153. self.channel = player_chan
  154. self.channel.players.append( self )
  155. if self.isAuthed:
  156. from mumble.models import MumbleUser
  157. try:
  158. self.mumbleuser = MumbleUser.objects.get( mumbleid=self.userid, server=server )
  159. except MumbleUser.DoesNotExist:
  160. self.mumbleuser = None
  161. else:
  162. self.mumbleuser = None
  163. # Lookup unknown attributes in self.player_obj to automatically include Murmur's fields
  164. def __getattr__( self, key ):
  165. if hasattr( self.player_obj, key ):
  166. return getattr( self.player_obj, key )
  167. else:
  168. raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, key ) )
  169. def __str__( self ):
  170. return '<Player "%s" (%d, %d)>' % ( self.name, self.session, self.userid )
  171. hasComment = property(
  172. lambda self: hasattr( self.player_obj, "comment" ) and bool(self.player_obj.comment),
  173. doc="True if this player has a comment set."
  174. )
  175. isAuthed = property(
  176. lambda self: self.userid != -1,
  177. doc="True if this player is authenticated (+A)."
  178. )
  179. isAdmin = property(
  180. lambda self: self.mumbleuser and self.mumbleuser.getAdmin(),
  181. doc="True if this player is in the Admin group in the ACL."
  182. )
  183. is_server = False
  184. is_channel = False
  185. is_player = True
  186. def getIpAsString( self ):
  187. """ Get the client's IPv4 or IPv6 address, in a pretty format. """
  188. addr = self.player_obj.address
  189. if max( addr[:10] ) == 0 and addr[10:12] == (255, 255):
  190. return "%d.%d.%d.%d" % tuple( addr[12:] )
  191. ip6addr = [(hi << 8 | lo) for (hi, lo) in zip(addr[0::2], addr[1::2])]
  192. # colon-separated string:
  193. ipstr = ':'.join([ ("%x" % part) for part in ip6addr ])
  194. # 0:0:0 -> ::
  195. return re.sub( "((^|:)(0:){2,})", '::', ipstr, 1 )
  196. ipaddress = property( getIpAsString )
  197. fqdn = property( lambda self: socket.getfqdn( self.ipaddress ),
  198. doc="The fully qualified domain name of the user's host." )
  199. # kept for compatibility to mmChannel (useful for traversal funcs)
  200. playerCount = property( lambda self: -1, doc="Exists only for compatibility to mmChannel." )
  201. id = property(
  202. lambda self: "player_%d"%self.session,
  203. doc="A string ready to be used in an id property of an HTML tag."
  204. )
  205. def visit( self, callback, lvl = 0 ):
  206. """ Call callback on myself. """
  207. callback( self, lvl )
  208. def asDict( self ):
  209. pldata = self.player_obj.__dict__.copy()
  210. if self.mumbleuser:
  211. if self.mumbleuser.hasTexture():
  212. pldata['texture'] = self.mumbleuser.textureUrl
  213. return pldata
  214. def asMvXml( self, parentnode ):
  215. """ Return an XML node for this player suitable for MumbleViewer-ng. """
  216. from xml.etree.cElementTree import SubElement
  217. me = SubElement( parentnode, "item" , id=self.id, rel='user' )
  218. content = SubElement( me, "content" )
  219. name = SubElement( content , "name" )
  220. name.text = self.name
  221. def asMvJson( self ):
  222. """ Return a Dict for this player suitable for MumbleViewer-ng. """
  223. return {
  224. "attributes": {
  225. "id": self.id,
  226. "rel": "user",
  227. },
  228. 'data': self.name,
  229. }
  230. class mmACL( object ):
  231. """ Represents an ACL for a certain channel. """
  232. def __init__( self, channel, acl_obj ):
  233. self.channel = channel
  234. self.acls, self.groups, self.inherit = acl_obj
  235. self.groups_dict = {}
  236. for group in self.groups:
  237. self.groups_dict[ group.name ] = group
  238. def group_has_member( self, name, userid ):
  239. """ Checks if the given userid is a member of the given group in this channel. """
  240. if name not in self.groups_dict:
  241. raise ReferenceError( "No such group '%s'" % name )
  242. return userid in self.groups_dict[name].add or userid in self.groups_dict[name].members
  243. def group_add_member( self, name, userid ):
  244. """ Make sure this userid is a member of the group in this channel (and subs). """
  245. if name not in self.groups_dict:
  246. raise ReferenceError( "No such group '%s'" % name )
  247. group = self.groups_dict[name]
  248. # if neither inherited nor to be added, add
  249. if userid not in group.members and userid not in group.add:
  250. group.add.append( userid )
  251. # if to be removed, unremove
  252. if userid in group.remove:
  253. group.remove.remove( userid )
  254. def group_remove_member( self, name, userid ):
  255. """ Make sure this userid is NOT a member of the group in this channel (and subs). """
  256. if name not in self.groups_dict:
  257. raise ReferenceError( "No such group '%s'" % name )
  258. group = self.groups_dict[name]
  259. # if added here, unadd
  260. if userid in group.add:
  261. group.add.remove( userid )
  262. # if member and not in remove, add to remove
  263. elif userid in group.members and userid not in group.remove:
  264. group.remove.append( userid )
  265. def save( self ):
  266. """ Send this ACL to Murmur. """
  267. return self.channel.server.ctl.setACL(
  268. self.channel.server.srvid,
  269. self.channel.chanid,
  270. self.acls, self.groups, self.inherit
  271. )