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.

601 lines
22 KiB

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