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.

379 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 djextdirect 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. if request.user.is_authenticated():
  93. try:
  94. user = MumbleUser.objects.get( server=srv, owner=request.user )
  95. except MumbleUser.DoesNotExist:
  96. user = None
  97. else:
  98. user = None
  99. from mumble.forms import EXT_FORMS_PROVIDER, MumbleUserPasswordForm, MumbleUserLinkForm, MumbleUserForm
  100. regformname = None
  101. if not user:
  102. # Unregistered users may or may not need a password to register.
  103. if settings.PROTECTED_MODE and srv.passwd:
  104. regformname = "MumbleUserPasswordForm"
  105. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  106. # Unregistered users may or may not want to link an existing account
  107. elif settings.ALLOW_ACCOUNT_LINKING:
  108. regformname = "MumbleUserLinkForm"
  109. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  110. if not regformname:
  111. regformname = "MumbleUserForm"
  112. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  113. return render_to_response( 'mumble/mumble.html', {
  114. 'MumbleServer': srv,
  115. 'RegForm': regformname,
  116. 'MumbleActive': True,
  117. 'MumbleAccount':user,
  118. 'IsAdmin': isAdmin,
  119. }, context_instance = RequestContext(request) )
  120. def mobile_show( request, server ):
  121. """ Display the channel list for the given Server ID. """
  122. srv = get_object_or_404( Mumble, id=server )
  123. user = None
  124. if request.user.is_authenticated():
  125. try:
  126. user = MumbleUser.objects.get( server=srv, owner=request.user )
  127. except MumbleUser.DoesNotExist:
  128. pass
  129. return render_to_response( 'mumble/mobile_mumble.html', {
  130. 'DBaseObject': srv,
  131. 'MumbleActive': True,
  132. 'MumbleAccount':user,
  133. }, context_instance = RequestContext(request) )
  134. def showTexture( request, server, userid ):
  135. """ Pack the given user's texture into an HttpResponse.
  136. If userid is none, use the currently logged in User.
  137. """
  138. srv = get_object_or_404( Mumble, id=int(server) )
  139. user = get_object_or_404( MumbleUser, server=srv, id=int(userid) )
  140. try:
  141. img = user.getTexture()
  142. except ValueError:
  143. raise Http404()
  144. else:
  145. buf = StringIO()
  146. img.save( buf, "PNG" )
  147. return HttpResponse( buf.getvalue(), "image/png" )
  148. @login_required
  149. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  150. def get_admin( request, server ):
  151. srv = get_object_or_404( Mumble, id=int(server) )
  152. if not srv.isUserAdmin( request.user ):
  153. raise Exception( 'Access denied' )
  154. adminform = MumbleForm( request.POST, instance=srv )
  155. data = {}
  156. for fld in adminform.fields:
  157. data[fld] = getattr( srv, fld )
  158. return { 'data': data, 'success': True }
  159. @login_required
  160. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  161. def users( request, server ):
  162. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  163. If the request has a "data" field, evaluate that and update the user records.
  164. """
  165. srv = get_object_or_404( Mumble, id=int(server) )
  166. if "resync" in request.POST and request.POST['resync'] == "true":
  167. srv.readUsersFromMurmur()
  168. if not srv.isUserAdmin( request.user ):
  169. raise Exception( 'Access denied' )
  170. users = []
  171. for mu in srv.mumbleuser_set.all():
  172. owner = None
  173. if mu.owner is not None:
  174. owner = mu.owner.id
  175. users.append( {
  176. 'id': mu.id,
  177. 'name': mu.name,
  178. 'password': None,
  179. 'owner': owner,
  180. 'admin': mu.aclAdmin,
  181. } )
  182. return users
  183. @login_required
  184. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  185. def djangousers( request ):
  186. """ Return a list of all Django users' names and IDs. """
  187. users = [ { 'uid': '', 'uname': '------' } ]
  188. for du in User.objects.all().order_by( 'username' ):
  189. users.append( {
  190. 'uid': du.id,
  191. 'uname': unicode( du ),
  192. } )
  193. return users
  194. @login_required
  195. @csrf_exempt
  196. def update_avatar( request, userid ):
  197. try:
  198. user = MumbleUser.objects.get( id=userid )
  199. except MumbleUser.DoesNotExist:
  200. return HttpResponse( "false", mimetype="text/html" )
  201. textureform = MumbleTextureForm( request.POST, request.FILES )
  202. if textureform.is_valid():
  203. if 'usegravatar' in textureform.cleaned_data and user.gravatar:
  204. user.setTextureFromUrl( user.gravatar )
  205. elif 'texturefile' in request.FILES:
  206. user.setTexture( Image.open( request.FILES['texturefile'] ) )
  207. return HttpResponse( "true", mimetype="text/html" )
  208. return HttpResponse( "false", mimetype="text/html" )
  209. def mmng_tree( request, server ):
  210. """ Return a JSON representation of the channel tree suitable for
  211. Murmur Manager:
  212. http://github.com/cheald/murmur-manager/tree/master/widget/
  213. To make the client widget query this view, set the URL attribute
  214. to "http://<mumble-django base URL>/mumble"
  215. """
  216. srv = get_object_or_404( Mumble, id=int(server) )
  217. chanlist = []
  218. userlist = []
  219. for chanid in srv.channels:
  220. channel = srv.channels[chanid]
  221. if channel.parent is not None:
  222. parent = channel.parent.chanid
  223. else:
  224. parent = -1
  225. chanlist.append({
  226. "type": "channel",
  227. "id": channel.chanid,
  228. "name": channel.name,
  229. "parent": parent,
  230. "position": channel.position,
  231. "state": channel.temporary and "temporary" or "permanent"
  232. })
  233. for sessionid in srv.players:
  234. user = srv.players[sessionid]
  235. userlist.append({
  236. "type": "player",
  237. "name": user.name,
  238. "channel": user.channel.chanid,
  239. "mute": user.mute or user.selfMute or user.suppress,
  240. "deaf": user.deaf or user.selfDeaf,
  241. "online": user.onlinesecs,
  242. "state": "online"
  243. })
  244. if "callback" in request.GET:
  245. prefix = request.GET["callback"]
  246. else:
  247. prefix = ""
  248. return HttpResponse(
  249. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  250. mimetype='text/javascript'
  251. )
  252. def cvp_checkauth( request, srv ):
  253. """ Check if the user is allowed to see private fields. """
  254. # http://www.djangosnippets.org/snippets/243/
  255. if srv.isUserAdmin( request.user ):
  256. return True
  257. if 'HTTP_AUTHORIZATION' in request.META:
  258. auth = request.META['HTTP_AUTHORIZATION'].split()
  259. if len(auth) == 2:
  260. # NOTE: We only support basic authentication for now.
  261. if auth[0].lower() == "basic":
  262. import base64
  263. from django.contrib.auth import authenticate
  264. uname, passwd = base64.b64decode(auth[1]).split(':')
  265. user = authenticate(username=uname, password=passwd)
  266. if user is not None and user.is_active and srv.isUserAdmin( user ):
  267. return True
  268. return False
  269. def cvp_json( request, server ):
  270. """ JSON reference implementation for the Channel Viewer Protocol.
  271. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  272. """
  273. srv = get_object_or_404( Mumble, id=int(server) )
  274. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  275. if "callback" in request.GET:
  276. ret = "%s(%s)" % ( request.GET["callback"], json )
  277. else:
  278. ret = json
  279. return HttpResponse( ret, mimetype='application/json' )
  280. def cvp_xml( request, server ):
  281. """ XML reference implementation for the Channel Viewer Protocol.
  282. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  283. """
  284. from xml.etree.cElementTree import tostring as xml_to_string
  285. srv = get_object_or_404( Mumble, id=int(server) )
  286. return HttpResponse(
  287. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  288. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  289. mimetype='text/xml'
  290. )
  291. def mumbleviewer_tree_xml( request, server ):
  292. """ Get the XML tree from the server and serialize it to the client. """
  293. from xml.etree.cElementTree import tostring as xml_to_string
  294. srv = get_object_or_404( Mumble, id=int(server) )
  295. return HttpResponse(
  296. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  297. mimetype='text/xml'
  298. )
  299. def mumbleviewer_tree_json( request, server ):
  300. """ Get the Dict from the server and serialize it as JSON to the client. """
  301. srv = get_object_or_404( Mumble, id=int(server) )
  302. if "jsonp_callback" in request.GET:
  303. prefix = request.GET["jsonp_callback"]
  304. else:
  305. prefix = ""
  306. return HttpResponse(
  307. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  308. mimetype='text/javascript'
  309. )