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.

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