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.

605 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. }, context_instance = RequestContext(request) )
  174. def mobile_show( request, server ):
  175. """ Display the channel list for the given Server ID. """
  176. srv = get_object_or_404( Mumble, id=server )
  177. user = None
  178. if request.user.is_authenticated():
  179. try:
  180. user = MumbleUser.objects.get( server=srv, owner=request.user )
  181. except MumbleUser.DoesNotExist:
  182. pass
  183. return render_to_response( 'mumble/mobile_mumble.html', {
  184. 'DBaseObject': srv,
  185. 'MumbleActive': True,
  186. 'MumbleAccount':user,
  187. }, context_instance = RequestContext(request) )
  188. def embed( request, server ):
  189. """ Display the channel viewer for the given Server ID. """
  190. srv = get_object_or_404( Mumble, id=server )
  191. return render_to_response( 'mumble/embed.html', {
  192. 'MumbleServer': srv,
  193. 'MumbleActive': True,
  194. }, context_instance = RequestContext(request) )
  195. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  196. def hasTexture( request, server, userid ):
  197. srv = get_object_or_404( Mumble, id=int(server) )
  198. if srv.hasUserTexture(int(userid)):
  199. return {
  200. 'has': True,
  201. 'url': reverse( showTexture, kwargs={ 'server': server, 'userid': userid } )
  202. }
  203. else:
  204. return { 'has': False, 'url': None }
  205. def showTexture( request, server, userid ):
  206. """ Pack the given user's texture into an HttpResponse. """
  207. srv = get_object_or_404( Mumble, id=int(server) )
  208. try:
  209. img = srv.getUserTexture(int(userid))
  210. except ValueError:
  211. raise Http404()
  212. else:
  213. buf = StringIO()
  214. img.save( buf, "PNG" )
  215. return HttpResponse( buf.getvalue(), "image/png" )
  216. def qrcode( request, server ):
  217. """ Show a QR Coce image that links to the server's embedded page. """
  218. try:
  219. import qrencode
  220. except ImportError:
  221. return HttpResponse( "oh noez" )
  222. else:
  223. from django.contrib.sites.models import Site
  224. version, size, img = qrencode.encode_scaled( "%s://%s%s" % (
  225. { False: "http", True: "https" }[request.is_secure()],
  226. Site.objects.get_current().domain,
  227. reverse( embed, kwargs={ 'server': server } )
  228. ), 82 )
  229. buf = StringIO()
  230. img.save( buf, "PNG" )
  231. return HttpResponse( buf.getvalue(), "image/png" )
  232. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  233. def get_admin( request, server ):
  234. srv = get_object_or_404( Mumble, id=int(server) )
  235. if not srv.isUserAdmin( request.user ):
  236. raise Exception( 'Access denied' )
  237. adminform = MumbleForm( request.POST, instance=srv )
  238. data = {}
  239. for fld in adminform.fields:
  240. data[fld] = getattr( srv, fld )
  241. return { 'data': data, 'success': True }
  242. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  243. def log( request, server, start, limit, filter ):
  244. """ Retrieve log messages. """
  245. srv = get_object_or_404( Mumble, id=int(server) )
  246. if not srv.isUserAdmin( request.user ):
  247. raise Exception( "Access denied" )
  248. return { 'data': [
  249. { 'timestamp': ent.timestamp, 'txt': ent.txt }
  250. for ent in srv.getLog( start, (start + limit), filter )
  251. ], 'success': True }
  252. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  253. def bans( request, server ):
  254. """ Retrieve bans. """
  255. srv = get_object_or_404( Mumble, id=int(server) )
  256. if not srv.isUserAdmin( request.user ):
  257. raise Exception( "Access denied" )
  258. return { 'data': [
  259. { 'start': ent.start, 'address': ent.address, 'bits': ent.bits,
  260. 'duration': ent.duration, 'reason': ent.reason, 'name': ent.name,
  261. 'addrstr': iptostring(ent.address) }
  262. for ent in srv.getBans()
  263. ], 'success': True }
  264. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  265. def removeBan( request, server, bandata ):
  266. """ Retrieve bans. """
  267. srv = get_object_or_404( Mumble, id=int(server) )
  268. if not srv.isUserAdmin( request.user ):
  269. raise Exception( "Access denied" )
  270. if "addrstr" in bandata:
  271. del bandata["addrstr"]
  272. bandata["address"] = tuple(bandata["address"])
  273. cleanargs = {}
  274. for kw in bandata:
  275. cleanargs[str(kw)] = bandata[kw]
  276. return srv.removeBan( **cleanargs )
  277. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  278. def moveUser( request, server, sessionid, channelid ):
  279. srv = get_object_or_404( Mumble, id=int(server) )
  280. if not srv.isUserAdmin( request.user ):
  281. raise Exception( 'Access denied' )
  282. srv.moveUser( sessionid, channelid )
  283. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  284. def moveChannel( request, server, channelid, parentid ):
  285. srv = get_object_or_404( Mumble, id=int(server) )
  286. if not srv.isUserAdmin( request.user ):
  287. raise Exception( 'Access denied' )
  288. srv.moveChannel( channelid, parentid )
  289. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  290. def kickUser( request, server, sessionid, reason, ban, duration ):
  291. srv = get_object_or_404( Mumble, id=int(server) )
  292. if not srv.isUserAdmin( request.user ):
  293. raise Exception( 'Access denied' )
  294. if ban:
  295. srv.banUser( sessionid, reason, duration )
  296. srv.kickUser( sessionid, reason )
  297. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  298. def muteUser( request, server, sessionid, mute ):
  299. srv = get_object_or_404( Mumble, id=int(server) )
  300. if not srv.isUserAdmin( request.user ):
  301. raise Exception( 'Access denied' )
  302. srv.muteUser(sessionid, mute)
  303. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  304. def deafenUser( request, server, sessionid, deaf ):
  305. srv = get_object_or_404( Mumble, id=int(server) )
  306. if not srv.isUserAdmin( request.user ):
  307. raise Exception( 'Access denied' )
  308. srv.deafenUser(sessionid, deaf)
  309. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  310. def addChannel( request, server, name, parentid ):
  311. srv = get_object_or_404( Mumble, id=int(server) )
  312. if not srv.isUserAdmin( request.user ):
  313. raise Exception( 'Access denied' )
  314. srv.addChannel(name, parentid)
  315. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  316. def removeChannel( request, server, channelid ):
  317. srv = get_object_or_404( Mumble, id=int(server) )
  318. if not srv.isUserAdmin( request.user ):
  319. raise Exception( 'Access denied' )
  320. srv.removeChannel(channelid)
  321. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  322. def renameChannel( request, server, channelid, name, description ):
  323. srv = get_object_or_404( Mumble, id=int(server) )
  324. if not srv.isUserAdmin( request.user ):
  325. raise Exception( 'Access denied' )
  326. srv.renameChannel(channelid, name, description)
  327. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  328. def sendMessage( request, server, sessionid, message ):
  329. srv = get_object_or_404( Mumble, id=int(server) )
  330. if not srv.isUserAdmin( request.user ):
  331. raise Exception( 'Access denied' )
  332. srv.sendMessage(sessionid, message)
  333. @EXT_DIRECT_PROVIDER.register_method( "Mumble" )
  334. def sendMessageChannel( request, server, channelid, tree, message ):
  335. srv = get_object_or_404( Mumble, id=int(server) )
  336. if not srv.isUserAdmin( request.user ):
  337. raise Exception( 'Access denied' )
  338. srv.sendMessageChannel(channelid, tree, message)
  339. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  340. def users( request, server, resync=False ):
  341. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  342. If the request has a "data" field, evaluate that and update the user records.
  343. """
  344. srv = get_object_or_404( Mumble, id=int(server) )
  345. if resync:
  346. srv.readUsersFromMurmur()
  347. if not srv.isUserAdmin( request.user ):
  348. raise Exception( 'Access denied' )
  349. users = []
  350. for mu in srv.mumbleuser_set.all():
  351. owner = None
  352. if mu.owner is not None:
  353. owner = mu.owner.id
  354. users.append( {
  355. 'id': mu.id,
  356. 'name': mu.name,
  357. 'password': None,
  358. 'owner': owner,
  359. 'admin': mu.aclAdmin,
  360. } )
  361. return users
  362. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  363. def djangousers( request ):
  364. """ Return a list of all Django users' names and IDs. """
  365. users = [ { 'uid': '', 'uname': '------' } ]
  366. for du in User.objects.all().order_by( 'username' ):
  367. users.append( {
  368. 'uid': du.id,
  369. 'uname': unicode( du ),
  370. } )
  371. return users
  372. @EXT_DIRECT_PROVIDER.register_method( "MumbleUserAdmin" )
  373. def update( request, server, data ):
  374. srv = get_object_or_404( Mumble, id=int(server) )
  375. for record in data:
  376. if record['id'] == -1:
  377. if record['delete']:
  378. continue
  379. mu = MumbleUser( server=srv )
  380. else:
  381. mu = MumbleUser.objects.get( id=record['id'] )
  382. if record['delete']:
  383. mu.delete()
  384. continue
  385. mu.name = record['name']
  386. mu.password = record['password']
  387. if record['owner']:
  388. mu.owner = User.objects.get( id=int(record['owner']) )
  389. mu.save()
  390. mu.aclAdmin = record['admin']
  391. return { 'success': True }
  392. @login_required
  393. @csrf_exempt
  394. def update_avatar( request, userid ):
  395. try:
  396. user = MumbleUser.objects.get( id=userid )
  397. except MumbleUser.DoesNotExist:
  398. return HttpResponse( "false", mimetype="text/html" )
  399. textureform = MumbleTextureForm( request.POST, request.FILES )
  400. if textureform.is_valid():
  401. if textureform.cleaned_data['usegravatar'] and user.gravatar:
  402. user.setTextureFromUrl( user.gravatar )
  403. else:
  404. user.setTexture( Image.open( textureform.cleaned_data['texturefile'] ) )
  405. return HttpResponse( "true", mimetype="text/html" )
  406. return HttpResponse( "false", mimetype="text/html" )
  407. def mmng_tree( request, server ):
  408. """ Return a JSON representation of the channel tree suitable for
  409. Murmur Manager:
  410. http://github.com/cheald/murmur-manager/tree/master/widget/
  411. To make the client widget query this view, set the URL attribute
  412. to "http://<mumble-django base URL>/mumble"
  413. """
  414. srv = get_object_or_404( Mumble, id=int(server) )
  415. chanlist = []
  416. userlist = []
  417. for chanid in srv.channels:
  418. channel = srv.channels[chanid]
  419. if channel.parent is not None:
  420. parent = channel.parent.chanid
  421. else:
  422. parent = -1
  423. chanlist.append({
  424. "type": "channel",
  425. "id": channel.chanid,
  426. "name": channel.name,
  427. "parent": parent,
  428. "position": channel.position,
  429. "state": channel.temporary and "temporary" or "permanent"
  430. })
  431. for sessionid in srv.players:
  432. user = srv.players[sessionid]
  433. userlist.append({
  434. "type": "player",
  435. "name": user.name,
  436. "channel": user.channel.chanid,
  437. "mute": user.mute or user.selfMute or user.suppress,
  438. "deaf": user.deaf or user.selfDeaf,
  439. "online": user.onlinesecs,
  440. "state": "online"
  441. })
  442. if "callback" in request.GET:
  443. prefix = request.GET["callback"]
  444. validate_jsonp_callback(prefix)
  445. else:
  446. prefix = ""
  447. return HttpResponse(
  448. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  449. mimetype='text/javascript'
  450. )
  451. def cvp_checkauth( request, srv ):
  452. """ Check if the user is allowed to see private fields. """
  453. # http://www.djangosnippets.org/snippets/243/
  454. if srv.isUserAdmin( request.user ):
  455. return True
  456. if 'HTTP_AUTHORIZATION' in request.META:
  457. auth = request.META['HTTP_AUTHORIZATION'].split()
  458. if len(auth) == 2:
  459. # NOTE: We only support basic authentication for now.
  460. if auth[0].lower() == "basic":
  461. import base64
  462. from django.contrib.auth import authenticate
  463. uname, passwd = base64.b64decode(auth[1]).split(':')
  464. user = authenticate(username=uname, password=passwd)
  465. if user is not None and user.is_active and srv.isUserAdmin( user ):
  466. return True
  467. return False
  468. def cvp_json( request, server ):
  469. """ JSON reference implementation for the Channel Viewer Protocol.
  470. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  471. """
  472. srv = get_object_or_404( Mumble, id=int(server) )
  473. json = simplejson.dumps( srv.asDict( cvp_checkauth( request, srv ) ) )
  474. if "callback" in request.GET:
  475. validate_jsonp_callback(request.GET["callback"])
  476. ret = "%s(%s)" % ( request.GET["callback"], json )
  477. else:
  478. ret = json
  479. return HttpResponse( ret, mimetype='application/json' )
  480. def cvp_xml( request, server ):
  481. """ XML reference implementation for the Channel Viewer Protocol.
  482. See <http://mumble.sourceforge.net/Channel_Viewer_Protocol>
  483. """
  484. from xml.etree.cElementTree import tostring as xml_to_string
  485. srv = get_object_or_404( Mumble, id=int(server) )
  486. return HttpResponse(
  487. '<?xml version="1.0" encoding="UTF-8" ?>'+\
  488. xml_to_string( srv.asXml( cvp_checkauth( request, srv ) ), encoding='utf-8' ),
  489. mimetype='text/xml'
  490. )
  491. def mumbleviewer_tree_xml( request, server ):
  492. """ Get the XML tree from the server and serialize it to the client. """
  493. from xml.etree.cElementTree import tostring as xml_to_string
  494. srv = get_object_or_404( Mumble, id=int(server) )
  495. return HttpResponse(
  496. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  497. mimetype='text/xml'
  498. )
  499. def mumbleviewer_tree_json( request, server ):
  500. """ Get the Dict from the server and serialize it as JSON to the client. """
  501. srv = get_object_or_404( Mumble, id=int(server) )
  502. if "jsonp_callback" in request.GET:
  503. prefix = request.GET["jsonp_callback"]
  504. validate_jsonp_callback(prefix)
  505. else:
  506. prefix = ""
  507. return HttpResponse(
  508. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  509. mimetype='text/javascript'
  510. )