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.

571 lines
20 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. try:
  17. import simplejson
  18. except ImportError:
  19. import json as simplejson
  20. from StringIO import StringIO
  21. from PIL import Image
  22. from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
  23. from django.template import RequestContext
  24. from django.http import Http404, HttpResponse, HttpResponseRedirect
  25. from django.conf import settings
  26. from django.contrib.auth.decorators import login_required
  27. from django.contrib.auth.models import User
  28. from django.contrib.auth import views as auth_views
  29. from django.core.urlresolvers import reverse
  30. from django.views.decorators.csrf import csrf_exempt
  31. from models import Mumble, MumbleUser
  32. from forms import MumbleForm, MumbleUserForm, MumbleUserPasswordForm
  33. from forms import MumbleUserLinkForm, MumbleTextureForm, MumbleKickForm
  34. from djextdirect.provider import Provider
  35. from djextdirect.views import login, logout
  36. EXT_DIRECT_PROVIDER = Provider()
  37. EXT_DIRECT_PROVIDER._register_method( "Accounts", login )
  38. EXT_DIRECT_PROVIDER._register_method( "Accounts", logout )
  39. def redir( request ):
  40. """ Redirect to the servers list. """
  41. if request.META['HTTP_USER_AGENT'].startswith( 'BlackBerry' ) or \
  42. "Opera Mobi" in request.META['HTTP_USER_AGENT'] or \
  43. "Opera Mini" in request.META['HTTP_USER_AGENT'] or \
  44. "Windows CE" in request.META['HTTP_USER_AGENT'] or \
  45. "MIDP" in request.META['HTTP_USER_AGENT'] or \
  46. "Palm" in request.META['HTTP_USER_AGENT'] or \
  47. "NetFront" in request.META['HTTP_USER_AGENT'] or \
  48. "Nokia" in request.META['HTTP_USER_AGENT'] or \
  49. "Symbian" in request.META['HTTP_USER_AGENT'] or \
  50. "UP.Browser" in request.META['HTTP_USER_AGENT'] or \
  51. "UP.Link" in request.META['HTTP_USER_AGENT'] or \
  52. "WinWAP" in request.META['HTTP_USER_AGENT'] or \
  53. "Android" in request.META['HTTP_USER_AGENT'] or \
  54. "DoCoMo" in request.META['HTTP_USER_AGENT'] or \
  55. "KDDI-" in request.META['HTTP_USER_AGENT'] or \
  56. "Softbank" in request.META['HTTP_USER_AGENT'] or \
  57. "J-Phone" in request.META['HTTP_USER_AGENT'] or \
  58. "IEMobile" in request.META['HTTP_USER_AGENT'] or \
  59. "iPod" in request.META['HTTP_USER_AGENT'] or \
  60. "iPhone" in request.META['HTTP_USER_AGENT']:
  61. return HttpResponseRedirect( reverse( mobile_mumbles ) )
  62. else:
  63. return HttpResponseRedirect( reverse( mumbles ) )
  64. def mobile_mumbles( request ):
  65. return mumbles( request, mobile=True )
  66. def mumbles( request, mobile=False ):
  67. """ Display a list of all configured Mumble servers, or redirect if only one configured. """
  68. mms = Mumble.objects.all().order_by( "name" )
  69. if len(mms) == 1:
  70. return HttpResponseRedirect( reverse(
  71. { False: show, True: mobile_show }[mobile],
  72. kwargs={ 'server': mms[0].id, }
  73. ) )
  74. return render_to_response(
  75. 'mumble/%s.html' % { False: 'list', True: 'mobile_list' }[mobile],
  76. { 'MumbleObjects': mms,
  77. 'MumbleActive': True,
  78. },
  79. context_instance = RequestContext(request)
  80. )
  81. @EXT_DIRECT_PROVIDER.register_method( "MumbleList" )
  82. def servers( request ):
  83. mms = Mumble.objects.all().order_by( "name" )
  84. return [{ 'id': mm.id, 'name': mm.name, 'booted': mm.booted } for mm in mms]
  85. @EXT_DIRECT_PROVIDER.register_method( "MumbleList" )
  86. def serverinfo( request, server ):
  87. srv = Mumble.objects.get( id=int(server) )
  88. if srv.booted:
  89. return {
  90. 'id': srv.id,
  91. 'name': srv.name,
  92. 'booted': True,
  93. 'motd': srv.motd,
  94. 'connecturl': srv.connecturl,
  95. 'prettyversion': srv.prettyversion,
  96. 'url': srv.url,
  97. 'users_regged': srv.users_regged,
  98. 'users_online': srv.users_online,
  99. 'channel_cnt': srv.channel_cnt,
  100. 'uptime': srv.uptime,
  101. 'upsince': unicode(srv.upsince),
  102. 'minurl': reverse( mobile_show, args=(server,) ),
  103. 'detailsurl': reverse( show, args=(server,) ),
  104. }
  105. else:
  106. return{
  107. 'id': srv.id,
  108. 'name': srv.name,
  109. 'booted': False,
  110. 'minurl': reverse( mobile_show, args=(server,) ),
  111. 'detailsurl': reverse( show, args=(server,) ),
  112. }
  113. def show( request, server ):
  114. """ Display the channel list for the given Server ID.
  115. This includes not only the channel list itself, but indeed the user registration,
  116. server admin and user texture form as well. The template then uses JavaScript
  117. to display these forms integrated into the Channel viewer.
  118. """
  119. srv = get_object_or_404( Mumble, id=server )
  120. if not srv.booted:
  121. return render_to_response(
  122. 'mumble/offline.html',
  123. { 'DBaseObject': srv,
  124. 'MumbleActive': True,
  125. }, context_instance = RequestContext(request) )
  126. isAdmin = srv.isUserAdmin( request.user )
  127. if request.user.is_authenticated():
  128. try:
  129. user = MumbleUser.objects.get( server=srv, owner=request.user )
  130. except MumbleUser.DoesNotExist:
  131. user = None
  132. else:
  133. user = None
  134. from mumble.forms import EXT_FORMS_PROVIDER, MumbleUserPasswordForm, MumbleUserLinkForm, MumbleUserForm
  135. regformname = None
  136. if not user:
  137. # Unregistered users may or may not need a password to register.
  138. if settings.PROTECTED_MODE and srv.passwd:
  139. regformname = "MumbleUserPasswordForm"
  140. EXT_FORMS_PROVIDER.register_form( MumbleUserPasswordForm )
  141. # Unregistered users may or may not want to link an existing account
  142. elif settings.ALLOW_ACCOUNT_LINKING:
  143. regformname = "MumbleUserLinkForm"
  144. EXT_FORMS_PROVIDER.register_form( MumbleUserLinkForm )
  145. if not regformname:
  146. regformname = "MumbleUserForm"
  147. EXT_FORMS_PROVIDER.register_form( MumbleUserForm )
  148. try:
  149. import qrencode
  150. except ImportError:
  151. qravail = False
  152. else:
  153. qravail = True
  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. 'QRAvailable': qravail,
  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. def embed( request, server ):
  178. """ Display the channel viewer for the given Server ID. """
  179. srv = get_object_or_404( Mumble, id=server )
  180. return render_to_response( 'mumble/embed.html', {
  181. 'MumbleServer': srv,
  182. 'MumbleActive': True,
  183. }, context_instance = RequestContext(request) )
  184. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  185. def hasTexture( request, server, userid ):
  186. srv = get_object_or_404( Mumble, id=int(server) )
  187. if srv.hasUserTexture(int(userid)):
  188. return {
  189. 'has': True,
  190. 'url': reverse( showTexture, kwargs={ 'server': server, 'userid': userid } )
  191. }
  192. else:
  193. return { 'has': False, 'url': None }
  194. def showTexture( request, server, userid ):
  195. """ Pack the given user's texture into an HttpResponse. """
  196. srv = get_object_or_404( Mumble, id=int(server) )
  197. try:
  198. img = srv.getUserTexture(int(userid))
  199. except ValueError:
  200. raise Http404()
  201. else:
  202. buf = StringIO()
  203. img.save( buf, "PNG" )
  204. return HttpResponse( buf.getvalue(), "image/png" )
  205. def qrcode( request, server ):
  206. """ Show a QR Coce image that links to the server's embedded page. """
  207. try:
  208. import qrencode
  209. except ImportError:
  210. return HttpResponse( "oh noez" )
  211. else:
  212. from django.contrib.sites.models import Site
  213. version, size, img = qrencode.encode_scaled( "%s://%s%s" % (
  214. { False: "http", True: "https" }[request.is_secure()],
  215. Site.objects.get_current().domain,
  216. reverse( embed, kwargs={ 'server': server } )
  217. ), 82 )
  218. buf = StringIO()
  219. img.save( buf, "PNG" )
  220. return HttpResponse( buf.getvalue(), "image/png" )
  221. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  222. def get_admin( request, server ):
  223. srv = get_object_or_404( Mumble, id=int(server) )
  224. if not srv.isUserAdmin( request.user ):
  225. raise Exception( 'Access denied' )
  226. adminform = MumbleForm( request.POST, instance=srv )
  227. data = {}
  228. for fld in adminform.fields:
  229. data[fld] = getattr( srv, fld )
  230. return { 'data': data, 'success': True }
  231. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  232. def log( request, server, start, limit, filter ):
  233. """ Retrieve log messages. """
  234. srv = get_object_or_404( Mumble, id=int(server) )
  235. if not srv.isUserAdmin( request.user ):
  236. raise Exception( "Access denied" )
  237. return { 'data': [
  238. { 'timestamp': ent.timestamp, 'txt': ent.txt }
  239. for ent in srv.getLog( start, (start + limit), filter )
  240. ], 'success': True }
  241. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  242. def bans( request, server ):
  243. """ Retrieve log messages. """
  244. srv = get_object_or_404( Mumble, id=int(server) )
  245. if not srv.isUserAdmin( request.user ):
  246. raise Exception( "Access denied" )
  247. return { 'data': [
  248. { 'start': ent.start, 'address': ent.address, 'bits': ent.bits,
  249. 'duration': ent.duration, 'reason': ent.reason }
  250. for ent in srv.getBans()
  251. ], 'success': True }
  252. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  253. def moveUser( request, server, sessionid, channelid ):
  254. srv = get_object_or_404( Mumble, id=int(server) )
  255. if not srv.isUserAdmin( request.user ):
  256. raise Exception( 'Access denied' )
  257. srv.moveUser( sessionid, channelid )
  258. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  259. def moveChannel( request, server, channelid, parentid ):
  260. srv = get_object_or_404( Mumble, id=int(server) )
  261. if not srv.isUserAdmin( request.user ):
  262. raise Exception( 'Access denied' )
  263. srv.moveChannel( channelid, parentid )
  264. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  265. def kickUser( request, server, sessionid, reason, ban, duration ):
  266. srv = get_object_or_404( Mumble, id=int(server) )
  267. if not srv.isUserAdmin( request.user ):
  268. raise Exception( 'Access denied' )
  269. if ban:
  270. srv.banUser( sessionid, reason, duration )
  271. srv.kickUser( sessionid, reason )
  272. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  273. def muteUser( request, server, sessionid, mute ):
  274. srv = get_object_or_404( Mumble, id=int(server) )
  275. if not srv.isUserAdmin( request.user ):
  276. raise Exception( 'Access denied' )
  277. srv.muteUser(sessionid, mute)
  278. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  279. def deafenUser( request, server, sessionid, deaf ):
  280. srv = get_object_or_404( Mumble, id=int(server) )
  281. if not srv.isUserAdmin( request.user ):
  282. raise Exception( 'Access denied' )
  283. srv.deafenUser(sessionid, deaf)
  284. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  285. def addChannel( request, server, name, parentid ):
  286. srv = get_object_or_404( Mumble, id=int(server) )
  287. if not srv.isUserAdmin( request.user ):
  288. raise Exception( 'Access denied' )
  289. srv.addChannel(name, parentid)
  290. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  291. def removeChannel( request, server, channelid ):
  292. srv = get_object_or_404( Mumble, id=int(server) )
  293. if not srv.isUserAdmin( request.user ):
  294. raise Exception( 'Access denied' )
  295. srv.removeChannel(channelid)
  296. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  297. def renameChannel( request, server, channelid, name, description ):
  298. srv = get_object_or_404( Mumble, id=int(server) )
  299. if not srv.isUserAdmin( request.user ):
  300. raise Exception( 'Access denied' )
  301. srv.renameChannel(channelid, name, description)
  302. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  303. def sendMessage( request, server, sessionid, message ):
  304. srv = get_object_or_404( Mumble, id=int(server) )
  305. if not srv.isUserAdmin( request.user ):
  306. raise Exception( 'Access denied' )
  307. srv.sendMessage(sessionid, message)
  308. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  309. def sendMessageChannel( request, server, channelid, tree, message ):
  310. srv = get_object_or_404( Mumble, id=int(server) )
  311. if not srv.isUserAdmin( request.user ):
  312. raise Exception( 'Access denied' )
  313. srv.sendMessageChannel(channelid, tree, message)
  314. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  315. def users( request, server, resync=False ):
  316. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  317. If the request has a "data" field, evaluate that and update the user records.
  318. """
  319. srv = get_object_or_404( Mumble, id=int(server) )
  320. if resync:
  321. srv.readUsersFromMurmur()
  322. if not srv.isUserAdmin( request.user ):
  323. raise Exception( 'Access denied' )
  324. users = []
  325. for mu in srv.mumbleuser_set.all():
  326. owner = None
  327. if mu.owner is not None:
  328. owner = mu.owner.id
  329. users.append( {
  330. 'id': mu.id,
  331. 'name': mu.name,
  332. 'password': None,
  333. 'owner': owner,
  334. 'admin': mu.aclAdmin,
  335. } )
  336. return users
  337. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  338. def djangousers( request ):
  339. """ Return a list of all Django users' names and IDs. """
  340. users = [ { 'uid': '', 'uname': '------' } ]
  341. for du in User.objects.all().order_by( 'username' ):
  342. users.append( {
  343. 'uid': du.id,
  344. 'uname': unicode( du ),
  345. } )
  346. return users
  347. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  348. def update( request, server, data ):
  349. srv = get_object_or_404( Mumble, id=int(server) )
  350. for record in data:
  351. if record['id'] == -1:
  352. if record['delete']:
  353. continue
  354. mu = MumbleUser( server=srv )
  355. else:
  356. mu = MumbleUser.objects.get( id=record['id'] )
  357. if record['delete']:
  358. mu.delete()
  359. continue
  360. mu.name = record['name']
  361. mu.password = record['password']
  362. if record['owner']:
  363. mu.owner = User.objects.get( id=int(record['owner']) )
  364. mu.save()
  365. mu.aclAdmin = record['admin']
  366. return { 'success': True }
  367. @login_required
  368. @csrf_exempt
  369. def update_avatar( request, userid ):
  370. try:
  371. user = MumbleUser.objects.get( id=userid )
  372. except MumbleUser.DoesNotExist:
  373. return HttpResponse( "false", mimetype="text/html" )
  374. textureform = MumbleTextureForm( request.POST, request.FILES )
  375. if textureform.is_valid():
  376. if textureform.cleaned_data['usegravatar'] and user.gravatar:
  377. user.setTextureFromUrl( user.gravatar )
  378. else:
  379. user.setTexture( Image.open( textureform.cleaned_data['texturefile'] ) )
  380. return HttpResponse( "true", mimetype="text/html" )
  381. return HttpResponse( "false", mimetype="text/html" )
  382. def mmng_tree( request, server ):
  383. """ Return a JSON representation of the channel tree suitable for
  384. Murmur Manager:
  385. http://github.com/cheald/murmur-manager/tree/master/widget/
  386. To make the client widget query this view, set the URL attribute
  387. to "http://<mumble-django base URL>/mumble"
  388. """
  389. srv = get_object_or_404( Mumble, id=int(server) )
  390. chanlist = []
  391. userlist = []
  392. for chanid in srv.channels:
  393. channel = srv.channels[chanid]
  394. if channel.parent is not None:
  395. parent = channel.parent.chanid
  396. else:
  397. parent = -1
  398. chanlist.append({
  399. "type": "channel",
  400. "id": channel.chanid,
  401. "name": channel.name,
  402. "parent": parent,
  403. "position": channel.position,
  404. "state": channel.temporary and "temporary" or "permanent"
  405. })
  406. for sessionid in srv.players:
  407. user = srv.players[sessionid]
  408. userlist.append({
  409. "type": "player",
  410. "name": user.name,
  411. "channel": user.channel.chanid,
  412. "mute": user.mute or user.selfMute or user.suppress,
  413. "deaf": user.deaf or user.selfDeaf,
  414. "online": user.onlinesecs,
  415. "state": "online"
  416. })
  417. if "callback" in request.GET:
  418. prefix = request.GET["callback"]
  419. else:
  420. prefix = ""
  421. return HttpResponse(
  422. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  423. mimetype='text/javascript'
  424. )
  425. def cvp_checkauth( request, srv ):
  426. """ Check if the user is allowed to see private fields. """
  427. # http://www.djangosnippets.org/snippets/243/
  428. if srv.isUserAdmin( request.user ):
  429. return True
  430. if 'HTTP_AUTHORIZATION' in request.META:
  431. auth = request.META['HTTP_AUTHORIZATION'].split()
  432. if len(auth) == 2:
  433. # NOTE: We only support basic authentication for now.
  434. if auth[0].lower() == "basic":
  435. import base64
  436. from django.contrib.auth import authenticate
  437. uname, passwd = base64.b64decode(auth[1]).split(':')
  438. user = authenticate(username=uname, password=passwd)
  439. if user is not None and user.is_active and srv.isUserAdmin( user ):
  440. return True
  441. return False
  442. def cvp_json( request, server ):
  443. """ JSON reference implementation for the Channel Viewer Protocol.
  444. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  445. """
  446. srv = get_object_or_404( Mumble, id=int(server) )
  447. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  448. if "callback" in request.GET:
  449. ret = "%s(%s)" % ( request.GET["callback"], json )
  450. else:
  451. ret = json
  452. return HttpResponse( ret, mimetype='application/json' )
  453. def cvp_xml( request, server ):
  454. """ XML reference implementation for the Channel Viewer Protocol.
  455. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  456. """
  457. from xml.etree.cElementTree import tostring as xml_to_string
  458. srv = get_object_or_404( Mumble, id=int(server) )
  459. return HttpResponse(
  460. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  461. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  462. mimetype='text/xml'
  463. )
  464. def mumbleviewer_tree_xml( request, server ):
  465. """ Get the XML tree from the server and serialize it to the client. """
  466. from xml.etree.cElementTree import tostring as xml_to_string
  467. srv = get_object_or_404( Mumble, id=int(server) )
  468. return HttpResponse(
  469. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  470. mimetype='text/xml'
  471. )
  472. def mumbleviewer_tree_json( request, server ):
  473. """ Get the Dict from the server and serialize it as JSON to the client. """
  474. srv = get_object_or_404( Mumble, id=int(server) )
  475. if "jsonp_callback" in request.GET:
  476. prefix = request.GET["jsonp_callback"]
  477. else:
  478. prefix = ""
  479. return HttpResponse(
  480. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  481. mimetype='text/javascript'
  482. )