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.

426 lines
15 KiB

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