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.

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