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.

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