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.

350 lines
11 KiB

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