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.

468 lines
16 KiB

16 years ago
16 years ago
16 years ago
15 years ago
16 years ago
15 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. @EXT_DIRECT_PROVIDER.register_method( "MumbleList" )
  95. def servers( request ):
  96. mms = Mumble.objects.all().order_by( "name" ).values( "id", "name" )
  97. return [{ 'id': mm['id'], 'name': mm['name'] } for mm in mms]
  98. @EXT_DIRECT_PROVIDER.register_method( "MumbleList" )
  99. def serverinfo( request, server ):
  100. srv = Mumble.objects.get( id=int(server) )
  101. # users_regged users_online channel_cnt uptime upsince minurl
  102. return {
  103. 'id': srv.id,
  104. 'name': srv.name,
  105. 'motd': srv.motd,
  106. 'connecturl': srv.connecturl,
  107. 'prettyversion': srv.prettyversion,
  108. 'url': srv.url,
  109. 'users_regged': srv.users_regged,
  110. 'users_online': srv.users_online,
  111. 'channel_cnt': srv.channel_cnt,
  112. 'uptime': srv.uptime,
  113. 'upsince': unicode(srv.upsince),
  114. 'minurl': reverse( mobile_show, args=(server,) )
  115. }
  116. @EXT_DIRECT_PROVIDER.register_method( "MumbleList" )
  117. def serverurl( request, server ):
  118. return reverse( show, args=(int(server),) );
  119. def show( request, server ):
  120. """ Display the channel list for the given Server ID.
  121. This includes not only the channel list itself, but indeed the user registration,
  122. server admin and user texture form as well. The template then uses JavaScript
  123. to display these forms integrated into the Channel viewer.
  124. """
  125. srv = get_object_or_404( Mumble, id=server )
  126. if not srv.booted:
  127. return render_to_response(
  128. 'mumble/offline.html',
  129. { 'DBaseObject': srv,
  130. 'MumbleActive': True,
  131. }, context_instance = RequestContext(request) )
  132. isAdmin = srv.isUserAdmin( request.user )
  133. if request.user.is_authenticated():
  134. try:
  135. user = MumbleUser.objects.get( server=srv, owner=request.user )
  136. except MumbleUser.DoesNotExist:
  137. user = None
  138. else:
  139. user = None
  140. from mumble.forms import EXT_FORMS_PROVIDER, MumbleUserPasswordForm, MumbleUserLinkForm, MumbleUserForm
  141. regformname = None
  142. if not user:
  143. # Unregistered users may or may not need a password to register.
  144. if settings.PROTECTED_MODE and srv.passwd:
  145. regformname = "MumbleUserPasswordForm"
  146. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  147. # Unregistered users may or may not want to link an existing account
  148. elif settings.ALLOW_ACCOUNT_LINKING:
  149. regformname = "MumbleUserLinkForm"
  150. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  151. if not regformname:
  152. regformname = "MumbleUserForm"
  153. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  154. return render_to_response( 'mumble/mumble.html', {
  155. 'MumbleServer': srv,
  156. 'ServerDict': simplejson.dumps(serverinfo(request, server)),
  157. 'RegForm': regformname,
  158. 'MumbleActive': True,
  159. 'MumbleAccount':user,
  160. 'IsAdmin': isAdmin,
  161. }, context_instance = RequestContext(request) )
  162. def mobile_show( request, server ):
  163. """ Display the channel list for the given Server ID. """
  164. srv = get_object_or_404( Mumble, id=server )
  165. user = None
  166. if request.user.is_authenticated():
  167. try:
  168. user = MumbleUser.objects.get( server=srv, owner=request.user )
  169. except MumbleUser.DoesNotExist:
  170. pass
  171. return render_to_response( 'mumble/mobile_mumble.html', {
  172. 'DBaseObject': srv,
  173. 'MumbleActive': True,
  174. 'MumbleAccount':user,
  175. }, context_instance = RequestContext(request) )
  176. def showTexture( request, server, userid ):
  177. """ Pack the given user's texture into an HttpResponse.
  178. If userid is none, use the currently logged in User.
  179. """
  180. srv = get_object_or_404( Mumble, id=int(server) )
  181. user = get_object_or_404( MumbleUser, server=srv, id=int(userid) )
  182. try:
  183. img = user.getTexture()
  184. except ValueError:
  185. raise Http404()
  186. else:
  187. buf = StringIO()
  188. img.save( buf, "PNG" )
  189. return HttpResponse( buf.getvalue(), "image/png" )
  190. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  191. def get_admin( request, server ):
  192. srv = get_object_or_404( Mumble, id=int(server) )
  193. if not srv.isUserAdmin( request.user ):
  194. raise Exception( 'Access denied' )
  195. adminform = MumbleForm( request.POST, instance=srv )
  196. data = {}
  197. for fld in adminform.fields:
  198. data[fld] = getattr( srv, fld )
  199. return { 'data': data, 'success': True }
  200. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  201. def log( request, server, start, limit, filter ):
  202. """ Retrieve log messages. """
  203. srv = get_object_or_404( Mumble, id=int(server) )
  204. if not srv.isUserAdmin( request.user ):
  205. raise Exception( "Access denied" )
  206. return { 'data': [
  207. { 'timestamp': ent.timestamp, 'txt': ent.txt }
  208. for ent in srv.getLog( start, (start + limit), filter )
  209. ], 'success': True }
  210. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  211. def moveUser( request, server, sessionid, channelid ):
  212. srv = get_object_or_404( Mumble, id=int(server) )
  213. if not srv.isUserAdmin( request.user ):
  214. raise Exception( 'Access denied' )
  215. srv.moveUser( sessionid, channelid )
  216. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  217. def moveChannel( request, server, channelid, parentid ):
  218. srv = get_object_or_404( Mumble, id=int(server) )
  219. if not srv.isUserAdmin( request.user ):
  220. raise Exception( 'Access denied' )
  221. srv.moveChannel( channelid, parentid )
  222. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  223. def users( request, server ):
  224. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  225. If the request has a "data" field, evaluate that and update the user records.
  226. """
  227. srv = get_object_or_404( Mumble, id=int(server) )
  228. if "resync" in request.POST and request.POST['resync'] == "true":
  229. srv.readUsersFromMurmur()
  230. if not srv.isUserAdmin( request.user ):
  231. raise Exception( 'Access denied' )
  232. users = []
  233. for mu in srv.mumbleuser_set.all():
  234. owner = None
  235. if mu.owner is not None:
  236. owner = mu.owner.id
  237. users.append( {
  238. 'id': mu.id,
  239. 'name': mu.name,
  240. 'password': None,
  241. 'owner': owner,
  242. 'admin': mu.aclAdmin,
  243. } )
  244. return users
  245. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  246. def djangousers( request ):
  247. """ Return a list of all Django users' names and IDs. """
  248. users = [ { 'uid': '', 'uname': '------' } ]
  249. for du in User.objects.all().order_by( 'username' ):
  250. users.append( {
  251. 'uid': du.id,
  252. 'uname': unicode( du ),
  253. } )
  254. return users
  255. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  256. def update( request, server, data ):
  257. srv = get_object_or_404( Mumble, id=int(server) )
  258. for record in data:
  259. if record['id'] == -1:
  260. if record['delete']:
  261. continue
  262. mu = MumbleUser( server=srv )
  263. else:
  264. mu = MumbleUser.objects.get( id=record['id'] )
  265. if record['delete']:
  266. mu.delete()
  267. continue
  268. mu.name = record['name']
  269. mu.password = record['password']
  270. if record['owner']:
  271. mu.owner = User.objects.get( id=int(record['owner']) )
  272. mu.save()
  273. mu.aclAdmin = record['admin']
  274. return { 'success': True }
  275. @login_required
  276. @csrf_exempt
  277. def update_avatar( request, userid ):
  278. try:
  279. user = MumbleUser.objects.get( id=userid )
  280. except MumbleUser.DoesNotExist:
  281. return HttpResponse( "false", mimetype="text/html" )
  282. textureform = MumbleTextureForm( request.POST, request.FILES )
  283. if textureform.is_valid():
  284. if 'usegravatar' in textureform.cleaned_data and user.gravatar:
  285. user.setTextureFromUrl( user.gravatar )
  286. elif 'texturefile' in request.FILES:
  287. user.setTexture( Image.open( request.FILES['texturefile'] ) )
  288. return HttpResponse( "true", mimetype="text/html" )
  289. return HttpResponse( "false", mimetype="text/html" )
  290. def mmng_tree( request, server ):
  291. """ Return a JSON representation of the channel tree suitable for
  292. Murmur Manager:
  293. http://github.com/cheald/murmur-manager/tree/master/widget/
  294. To make the client widget query this view, set the URL attribute
  295. to "http://<mumble-django base URL>/mumble"
  296. """
  297. srv = get_object_or_404( Mumble, id=int(server) )
  298. chanlist = []
  299. userlist = []
  300. for chanid in srv.channels:
  301. channel = srv.channels[chanid]
  302. if channel.parent is not None:
  303. parent = channel.parent.chanid
  304. else:
  305. parent = -1
  306. chanlist.append({
  307. "type": "channel",
  308. "id": channel.chanid,
  309. "name": channel.name,
  310. "parent": parent,
  311. "position": channel.position,
  312. "state": channel.temporary and "temporary" or "permanent"
  313. })
  314. for sessionid in srv.players:
  315. user = srv.players[sessionid]
  316. userlist.append({
  317. "type": "player",
  318. "name": user.name,
  319. "channel": user.channel.chanid,
  320. "mute": user.mute or user.selfMute or user.suppress,
  321. "deaf": user.deaf or user.selfDeaf,
  322. "online": user.onlinesecs,
  323. "state": "online"
  324. })
  325. if "callback" in request.GET:
  326. prefix = request.GET["callback"]
  327. else:
  328. prefix = ""
  329. return HttpResponse(
  330. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  331. mimetype='text/javascript'
  332. )
  333. def cvp_checkauth( request, srv ):
  334. """ Check if the user is allowed to see private fields. """
  335. # http://www.djangosnippets.org/snippets/243/
  336. if srv.isUserAdmin( request.user ):
  337. return True
  338. if 'HTTP_AUTHORIZATION' in request.META:
  339. auth = request.META['HTTP_AUTHORIZATION'].split()
  340. if len(auth) == 2:
  341. # NOTE: We only support basic authentication for now.
  342. if auth[0].lower() == "basic":
  343. import base64
  344. from django.contrib.auth import authenticate
  345. uname, passwd = base64.b64decode(auth[1]).split(':')
  346. user = authenticate(username=uname, password=passwd)
  347. if user is not None and user.is_active and srv.isUserAdmin( user ):
  348. return True
  349. return False
  350. def cvp_json( request, server ):
  351. """ JSON reference implementation for the Channel Viewer Protocol.
  352. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  353. """
  354. srv = get_object_or_404( Mumble, id=int(server) )
  355. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  356. if "callback" in request.GET:
  357. ret = "%s(%s)" % ( request.GET["callback"], json )
  358. else:
  359. ret = json
  360. return HttpResponse( ret, mimetype='application/json' )
  361. def cvp_xml( request, server ):
  362. """ XML reference implementation for the Channel Viewer Protocol.
  363. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  364. """
  365. from xml.etree.cElementTree import tostring as xml_to_string
  366. srv = get_object_or_404( Mumble, id=int(server) )
  367. return HttpResponse(
  368. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  369. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  370. mimetype='text/xml'
  371. )
  372. def mumbleviewer_tree_xml( request, server ):
  373. """ Get the XML tree from the server and serialize it to the client. """
  374. from xml.etree.cElementTree import tostring as xml_to_string
  375. srv = get_object_or_404( Mumble, id=int(server) )
  376. return HttpResponse(
  377. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  378. mimetype='text/xml'
  379. )
  380. def mumbleviewer_tree_json( request, server ):
  381. """ Get the Dict from the server and serialize it as JSON to the client. """
  382. srv = get_object_or_404( Mumble, id=int(server) )
  383. if "jsonp_callback" in request.GET:
  384. prefix = request.GET["jsonp_callback"]
  385. else:
  386. prefix = ""
  387. return HttpResponse(
  388. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  389. mimetype='text/javascript'
  390. )