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.

455 lines
16 KiB

16 years ago
16 years ago
16 years ago
15 years ago
16 years ago
14 years ago
14 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( "MumbleUserAdmin" )
  211. def users( request, server ):
  212. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  213. If the request has a "data" field, evaluate that and update the user records.
  214. """
  215. srv = get_object_or_404( Mumble, id=int(server) )
  216. if "resync" in request.POST and request.POST['resync'] == "true":
  217. srv.readUsersFromMurmur()
  218. if not srv.isUserAdmin( request.user ):
  219. raise Exception( 'Access denied' )
  220. users = []
  221. for mu in srv.mumbleuser_set.all():
  222. owner = None
  223. if mu.owner is not None:
  224. owner = mu.owner.id
  225. users.append( {
  226. 'id': mu.id,
  227. 'name': mu.name,
  228. 'password': None,
  229. 'owner': owner,
  230. 'admin': mu.aclAdmin,
  231. } )
  232. return users
  233. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  234. def djangousers( request ):
  235. """ Return a list of all Django users' names and IDs. """
  236. users = [ { 'uid': '', 'uname': '------' } ]
  237. for du in User.objects.all().order_by( 'username' ):
  238. users.append( {
  239. 'uid': du.id,
  240. 'uname': unicode( du ),
  241. } )
  242. return users
  243. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  244. def update( request, server, data ):
  245. srv = get_object_or_404( Mumble, id=int(server) )
  246. for record in data:
  247. if record['id'] == -1:
  248. if record['delete']:
  249. continue
  250. mu = MumbleUser( server=srv )
  251. else:
  252. mu = MumbleUser.objects.get( id=record['id'] )
  253. if record['delete']:
  254. mu.delete()
  255. continue
  256. mu.name = record['name']
  257. mu.password = record['password']
  258. if record['owner']:
  259. mu.owner = User.objects.get( id=int(record['owner']) )
  260. mu.save()
  261. mu.aclAdmin = record['admin']
  262. return { 'success': True }
  263. @login_required
  264. @csrf_exempt
  265. def update_avatar( request, userid ):
  266. try:
  267. user = MumbleUser.objects.get( id=userid )
  268. except MumbleUser.DoesNotExist:
  269. return HttpResponse( "false", mimetype="text/html" )
  270. textureform = MumbleTextureForm( request.POST, request.FILES )
  271. if textureform.is_valid():
  272. if 'usegravatar' in textureform.cleaned_data and user.gravatar:
  273. user.setTextureFromUrl( user.gravatar )
  274. elif 'texturefile' in request.FILES:
  275. user.setTexture( Image.open( request.FILES['texturefile'] ) )
  276. return HttpResponse( "true", mimetype="text/html" )
  277. return HttpResponse( "false", mimetype="text/html" )
  278. def mmng_tree( request, server ):
  279. """ Return a JSON representation of the channel tree suitable for
  280. Murmur Manager:
  281. http://github.com/cheald/murmur-manager/tree/master/widget/
  282. To make the client widget query this view, set the URL attribute
  283. to "http://<mumble-django base URL>/mumble"
  284. """
  285. srv = get_object_or_404( Mumble, id=int(server) )
  286. chanlist = []
  287. userlist = []
  288. for chanid in srv.channels:
  289. channel = srv.channels[chanid]
  290. if channel.parent is not None:
  291. parent = channel.parent.chanid
  292. else:
  293. parent = -1
  294. chanlist.append({
  295. "type": "channel",
  296. "id": channel.chanid,
  297. "name": channel.name,
  298. "parent": parent,
  299. "position": channel.position,
  300. "state": channel.temporary and "temporary" or "permanent"
  301. })
  302. for sessionid in srv.players:
  303. user = srv.players[sessionid]
  304. userlist.append({
  305. "type": "player",
  306. "name": user.name,
  307. "channel": user.channel.chanid,
  308. "mute": user.mute or user.selfMute or user.suppress,
  309. "deaf": user.deaf or user.selfDeaf,
  310. "online": user.onlinesecs,
  311. "state": "online"
  312. })
  313. if "callback" in request.GET:
  314. prefix = request.GET["callback"]
  315. else:
  316. prefix = ""
  317. return HttpResponse(
  318. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  319. mimetype='text/javascript'
  320. )
  321. def cvp_checkauth( request, srv ):
  322. """ Check if the user is allowed to see private fields. """
  323. # http://www.djangosnippets.org/snippets/243/
  324. if srv.isUserAdmin( request.user ):
  325. return True
  326. if 'HTTP_AUTHORIZATION' in request.META:
  327. auth = request.META['HTTP_AUTHORIZATION'].split()
  328. if len(auth) == 2:
  329. # NOTE: We only support basic authentication for now.
  330. if auth[0].lower() == "basic":
  331. import base64
  332. from django.contrib.auth import authenticate
  333. uname, passwd = base64.b64decode(auth[1]).split(':')
  334. user = authenticate(username=uname, password=passwd)
  335. if user is not None and user.is_active and srv.isUserAdmin( user ):
  336. return True
  337. return False
  338. def cvp_json( request, server ):
  339. """ JSON reference implementation for the Channel Viewer Protocol.
  340. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  341. """
  342. srv = get_object_or_404( Mumble, id=int(server) )
  343. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  344. if "callback" in request.GET:
  345. ret = "%s(%s)" % ( request.GET["callback"], json )
  346. else:
  347. ret = json
  348. return HttpResponse( ret, mimetype='application/json' )
  349. def cvp_xml( request, server ):
  350. """ XML reference implementation for the Channel Viewer Protocol.
  351. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  352. """
  353. from xml.etree.cElementTree import tostring as xml_to_string
  354. srv = get_object_or_404( Mumble, id=int(server) )
  355. return HttpResponse(
  356. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  357. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  358. mimetype='text/xml'
  359. )
  360. def mumbleviewer_tree_xml( request, server ):
  361. """ Get the XML tree from the server and serialize it to the client. """
  362. from xml.etree.cElementTree import tostring as xml_to_string
  363. srv = get_object_or_404( Mumble, id=int(server) )
  364. return HttpResponse(
  365. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  366. mimetype='text/xml'
  367. )
  368. def mumbleviewer_tree_json( request, server ):
  369. """ Get the Dict from the server and serialize it as JSON to the client. """
  370. srv = get_object_or_404( Mumble, id=int(server) )
  371. if "jsonp_callback" in request.GET:
  372. prefix = request.GET["jsonp_callback"]
  373. else:
  374. prefix = ""
  375. return HttpResponse(
  376. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  377. mimetype='text/javascript'
  378. )