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.

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