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.

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