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.

355 lines
12 KiB

16 years ago
16 years ago
16 years ago
15 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 simplejson
  17. from StringIO import StringIO
  18. from PIL import Image
  19. from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
  20. from django.template import RequestContext
  21. from django.http import Http404, HttpResponse, HttpResponseRedirect
  22. from django.conf import settings
  23. from django.contrib.auth.decorators import login_required
  24. from django.contrib.auth.models import User
  25. from django.contrib.auth import views as auth_views
  26. from django.core.urlresolvers import reverse
  27. from models import Mumble, MumbleUser
  28. from forms import MumbleForm, MumbleUserForm, MumbleUserPasswordForm
  29. from forms import MumbleUserLinkForm, MumbleTextureForm, MumbleKickForm
  30. from extdirect import Provider
  31. EXT_DIRECT_PROVIDER = Provider()
  32. @EXT_DIRECT_PROVIDER.register_method( "omgfu" )
  33. def ohai( request ):
  34. return "plzkthx"
  35. def redir( request ):
  36. """ Redirect to the servers list. """
  37. if request.META['HTTP_USER_AGENT'].startswith( 'BlackBerry' ) or \
  38. "Opera Mobi" in request.META['HTTP_USER_AGENT'] or \
  39. "Opera Mini" in request.META['HTTP_USER_AGENT'] or \
  40. "Windows CE" in request.META['HTTP_USER_AGENT'] or \
  41. "MIDP" in request.META['HTTP_USER_AGENT'] or \
  42. "Palm" in request.META['HTTP_USER_AGENT'] or \
  43. "NetFront" in request.META['HTTP_USER_AGENT'] or \
  44. "Nokia" in request.META['HTTP_USER_AGENT'] or \
  45. "Symbian" in request.META['HTTP_USER_AGENT'] or \
  46. "UP.Browser" in request.META['HTTP_USER_AGENT'] or \
  47. "UP.Link" in request.META['HTTP_USER_AGENT'] or \
  48. "WinWAP" in request.META['HTTP_USER_AGENT'] or \
  49. "Android" in request.META['HTTP_USER_AGENT'] or \
  50. "DoCoMo" in request.META['HTTP_USER_AGENT'] or \
  51. "KDDI-" in request.META['HTTP_USER_AGENT'] or \
  52. "Softbank" in request.META['HTTP_USER_AGENT'] or \
  53. "J-Phone" in request.META['HTTP_USER_AGENT'] or \
  54. "IEMobile" in request.META['HTTP_USER_AGENT'] or \
  55. "iPod" in request.META['HTTP_USER_AGENT'] or \
  56. "iPhone" in request.META['HTTP_USER_AGENT']:
  57. return HttpResponseRedirect( reverse( mobile_mumbles ) )
  58. else:
  59. return HttpResponseRedirect( reverse( mumbles ) )
  60. def mobile_mumbles( request ):
  61. return mumbles( request, mobile=True )
  62. def mumbles( request, mobile=False ):
  63. """ Display a list of all configured Mumble servers, or redirect if only one configured. """
  64. mms = Mumble.objects.all().order_by( "name" )
  65. if len(mms) == 1:
  66. return HttpResponseRedirect( reverse(
  67. { False: show, True: mobile_show }[mobile],
  68. kwargs={ 'server': mms[0].id, }
  69. ) )
  70. return render_to_response(
  71. 'mumble/%s.html' % { False: 'list', True: 'mobile_list' }[mobile],
  72. { 'MumbleObjects': mms,
  73. 'MumbleActive': True,
  74. },
  75. context_instance = RequestContext(request)
  76. )
  77. def show( request, server ):
  78. """ Display the channel list for the given Server ID.
  79. This includes not only the channel list itself, but indeed the user registration,
  80. server admin and user texture form as well. The template then uses JavaScript
  81. to display these forms integrated into the Channel viewer.
  82. """
  83. srv = get_object_or_404( Mumble, id=server )
  84. if not srv.booted:
  85. return render_to_response(
  86. 'mumble/offline.html',
  87. { 'DBaseObject': srv,
  88. 'MumbleActive': True,
  89. }, context_instance = RequestContext(request) )
  90. isAdmin = srv.isUserAdmin( request.user )
  91. try:
  92. user = MumbleUser.objects.get( server=srv, owner=request.user )
  93. except MumbleUser.DoesNotExist:
  94. user = None
  95. from mumble.forms import EXT_FORMS_PROVIDER, MumbleUserPasswordForm, MumbleUserLinkForm, MumbleUserForm
  96. regformname = None
  97. if not user:
  98. # Unregistered users may or may not need a password to register.
  99. if settings.PROTECTED_MODE and srv.passwd:
  100. regformname = "MumbleUserPasswordForm"
  101. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  102. # Unregistered users may or may not want to link an existing account
  103. elif settings.ALLOW_ACCOUNT_LINKING:
  104. regformname = "MumbleUserLinkForm"
  105. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  106. if not regformname:
  107. regformname = "MumbleUserForm"
  108. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  109. return render_to_response( 'mumble/mumble.html', {
  110. 'MumbleServer': srv,
  111. 'RegForm': regformname,
  112. 'MumbleActive': True,
  113. 'MumbleAccount':user,
  114. }, context_instance = RequestContext(request) )
  115. def mobile_show( request, server ):
  116. """ Display the channel list for the given Server ID. """
  117. srv = get_object_or_404( Mumble, id=server )
  118. user = None
  119. if request.user.is_authenticated():
  120. try:
  121. user = MumbleUser.objects.get( server=srv, owner=request.user )
  122. except MumbleUser.DoesNotExist:
  123. pass
  124. return render_to_response( 'mumble/mobile_mumble.html', {
  125. 'DBaseObject': srv,
  126. 'MumbleActive': True,
  127. 'MumbleAccount':user,
  128. }, context_instance = RequestContext(request) )
  129. def showTexture( request, server, userid ):
  130. """ Pack the given user's texture into an HttpResponse.
  131. If userid is none, use the currently logged in User.
  132. """
  133. srv = get_object_or_404( Mumble, id=int(server) )
  134. user = get_object_or_404( MumbleUser, server=srv, id=int(userid) )
  135. try:
  136. img = user.getTexture()
  137. except ValueError:
  138. raise Http404()
  139. else:
  140. buf = StringIO()
  141. img.save( buf, "PNG" )
  142. return HttpResponse( buf.getvalue(), "image/png" )
  143. @login_required
  144. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  145. def get_admin( request, server ):
  146. srv = get_object_or_404( Mumble, id=int(server) )
  147. if not srv.isUserAdmin( request.user ):
  148. raise Exception( 'Access denied' )
  149. adminform = MumbleForm( request.POST, instance=srv )
  150. data = {}
  151. for fld in adminform.fields:
  152. data[fld] = getattr( srv, fld )
  153. return { 'data': data, 'success': True }
  154. @login_required
  155. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  156. def users( request, server ):
  157. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  158. If the request has a "data" field, evaluate that and update the user records.
  159. """
  160. srv = get_object_or_404( Mumble, id=int(server) )
  161. if "resync" in request.POST and request.POST['resync'] == "true":
  162. srv.readUsersFromMurmur()
  163. if not srv.isUserAdmin( request.user ):
  164. raise Exception( 'Access denied' )
  165. users = []
  166. for mu in srv.mumbleuser_set.all():
  167. owner = None
  168. if mu.owner is not None:
  169. owner = mu.owner.id
  170. users.append( {
  171. 'id': mu.id,
  172. 'name': mu.name,
  173. 'password': None,
  174. 'owner': owner,
  175. 'admin': mu.aclAdmin,
  176. } )
  177. return users
  178. @login_required
  179. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  180. def djangousers( request ):
  181. """ Return a list of all Django users' names and IDs. """
  182. users = [ { 'uid': '', 'uname': '------' } ]
  183. for du in User.objects.all().order_by( 'username' ):
  184. users.append( {
  185. 'uid': du.id,
  186. 'uname': unicode( du ),
  187. } )
  188. return users
  189. def mmng_tree( request, server ):
  190. """ Return a JSON representation of the channel tree suitable for
  191. Murmur Manager:
  192. http://github.com/cheald/murmur-manager/tree/master/widget/
  193. To make the client widget query this view, set the URL attribute
  194. to "http://<mumble-django base URL>/mumble"
  195. """
  196. srv = get_object_or_404( Mumble, id=int(server) )
  197. chanlist = []
  198. userlist = []
  199. for chanid in srv.channels:
  200. channel = srv.channels[chanid]
  201. if channel.parent is not None:
  202. parent = channel.parent.chanid
  203. else:
  204. parent = -1
  205. chanlist.append({
  206. "type": "channel",
  207. "id": channel.chanid,
  208. "name": channel.name,
  209. "parent": parent,
  210. "position": channel.position,
  211. "state": channel.temporary and "temporary" or "permanent"
  212. })
  213. for sessionid in srv.players:
  214. user = srv.players[sessionid]
  215. userlist.append({
  216. "type": "player",
  217. "name": user.name,
  218. "channel": user.channel.chanid,
  219. "mute": user.mute or user.selfMute or user.suppress,
  220. "deaf": user.deaf or user.selfDeaf,
  221. "online": user.onlinesecs,
  222. "state": "online"
  223. })
  224. if "callback" in request.GET:
  225. prefix = request.GET["callback"]
  226. else:
  227. prefix = ""
  228. return HttpResponse(
  229. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  230. mimetype='text/javascript'
  231. )
  232. def cvp_checkauth( request, srv ):
  233. """ Check if the user is allowed to see private fields. """
  234. # http://www.djangosnippets.org/snippets/243/
  235. if srv.isUserAdmin( request.user ):
  236. return True
  237. if 'HTTP_AUTHORIZATION' in request.META:
  238. auth = request.META['HTTP_AUTHORIZATION'].split()
  239. if len(auth) == 2:
  240. # NOTE: We only support basic authentication for now.
  241. if auth[0].lower() == "basic":
  242. import base64
  243. from django.contrib.auth import authenticate
  244. uname, passwd = base64.b64decode(auth[1]).split(':')
  245. user = authenticate(username=uname, password=passwd)
  246. if user is not None and user.is_active and srv.isUserAdmin( user ):
  247. return True
  248. return False
  249. def cvp_json( request, server ):
  250. """ JSON reference implementation for the Channel Viewer Protocol.
  251. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  252. """
  253. srv = get_object_or_404( Mumble, id=int(server) )
  254. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  255. if "callback" in request.GET:
  256. ret = "%s(%s)" % ( request.GET["callback"], json )
  257. else:
  258. ret = json
  259. return HttpResponse( ret, mimetype='application/json' )
  260. def cvp_xml( request, server ):
  261. """ XML reference implementation for the Channel Viewer Protocol.
  262. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  263. """
  264. from xml.etree.cElementTree import tostring as xml_to_string
  265. srv = get_object_or_404( Mumble, id=int(server) )
  266. return HttpResponse(
  267. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  268. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  269. mimetype='text/xml'
  270. )
  271. def mumbleviewer_tree_xml( request, server ):
  272. """ Get the XML tree from the server and serialize it to the client. """
  273. from xml.etree.cElementTree import tostring as xml_to_string
  274. srv = get_object_or_404( Mumble, id=int(server) )
  275. return HttpResponse(
  276. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  277. mimetype='text/xml'
  278. )
  279. def mumbleviewer_tree_json( request, server ):
  280. """ Get the Dict from the server and serialize it as JSON to the client. """
  281. srv = get_object_or_404( Mumble, id=int(server) )
  282. if "jsonp_callback" in request.GET:
  283. prefix = request.GET["jsonp_callback"]
  284. else:
  285. prefix = ""
  286. return HttpResponse(
  287. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  288. mimetype='text/javascript'
  289. )