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.

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