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.

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