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.

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