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.

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