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.

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