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.

402 lines
14 KiB

16 years ago
16 years ago
16 years ago
15 years ago
16 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 models import Mumble, MumbleUser
  28. from forms import MumbleForm, MumbleUserForm, MumbleUserPasswordForm
  29. from forms import MumbleUserLinkForm, MumbleTextureForm, MumbleKickForm
  30. def redir( request ):
  31. """ Redirect to the servers list. """
  32. if request.META['HTTP_USER_AGENT'].startswith( 'BlackBerry' ) or \
  33. "Opera Mobi" in request.META['HTTP_USER_AGENT'] or \
  34. "Opera Mini" in request.META['HTTP_USER_AGENT'] or \
  35. "Windows CE" in request.META['HTTP_USER_AGENT'] or \
  36. "MIDP" in request.META['HTTP_USER_AGENT'] or \
  37. "Palm" in request.META['HTTP_USER_AGENT'] or \
  38. "NetFront" in request.META['HTTP_USER_AGENT'] or \
  39. "Nokia" in request.META['HTTP_USER_AGENT'] or \
  40. "Symbian" in request.META['HTTP_USER_AGENT'] or \
  41. "UP.Browser" in request.META['HTTP_USER_AGENT'] or \
  42. "UP.Link" in request.META['HTTP_USER_AGENT'] or \
  43. "WinWAP" in request.META['HTTP_USER_AGENT'] or \
  44. "Android" in request.META['HTTP_USER_AGENT'] or \
  45. "DoCoMo" in request.META['HTTP_USER_AGENT'] or \
  46. "KDDI-" in request.META['HTTP_USER_AGENT'] or \
  47. "Softbank" in request.META['HTTP_USER_AGENT'] or \
  48. "J-Phone" in request.META['HTTP_USER_AGENT'] or \
  49. "IEMobile" in request.META['HTTP_USER_AGENT'] or \
  50. "iPod" in request.META['HTTP_USER_AGENT'] or \
  51. "iPhone" in request.META['HTTP_USER_AGENT']:
  52. return HttpResponseRedirect( reverse( mobile_mumbles ) )
  53. else:
  54. return HttpResponseRedirect( reverse( mumbles ) )
  55. def mobile_mumbles( request ):
  56. return mumbles( request, mobile=True )
  57. def mumbles( request, mobile=False ):
  58. """ Display a list of all configured Mumble servers, or redirect if only one configured. """
  59. mms = Mumble.objects.all().order_by( "name" )
  60. if len(mms) == 1:
  61. return HttpResponseRedirect( reverse(
  62. { False: show, True: mobile_show }[mobile],
  63. kwargs={ 'server': mms[0].id, }
  64. ) )
  65. return render_to_response(
  66. 'mumble/%s.html' % { False: 'list', True: 'mobile_list' }[mobile],
  67. { 'MumbleObjects': mms,
  68. 'MumbleActive': True,
  69. },
  70. context_instance = RequestContext(request)
  71. )
  72. def show( request, server ):
  73. """ Display the channel list for the given Server ID.
  74. This includes not only the channel list itself, but indeed the user registration,
  75. server admin and user texture form as well. The template then uses JavaScript
  76. to display these forms integrated into the Channel viewer.
  77. """
  78. srv = get_object_or_404( Mumble, id=server )
  79. if not srv.booted:
  80. return render_to_response(
  81. 'mumble/offline.html',
  82. { 'DBaseObject': srv,
  83. 'MumbleActive': True,
  84. }, context_instance = RequestContext(request) )
  85. isAdmin = srv.isUserAdmin( request.user )
  86. # The tab to start on.
  87. displayTab = 0
  88. if isAdmin:
  89. if request.method == 'POST' and "mode" in request.POST and request.POST['mode'] == 'admin':
  90. adminform = MumbleForm( request.POST, instance=srv )
  91. if adminform.is_valid():
  92. adminform.save()
  93. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) )
  94. else:
  95. displayTab = 2
  96. else:
  97. adminform = MumbleForm( instance=srv )
  98. else:
  99. adminform = None
  100. registered = False
  101. user = None
  102. if request.user.is_authenticated():
  103. # Unregistered users may or may not need a password to register.
  104. if settings.PROTECTED_MODE and srv.passwd:
  105. unregged_user_form = MumbleUserPasswordForm
  106. # Unregistered users may or may not want to link an existing account
  107. elif settings.ALLOW_ACCOUNT_LINKING:
  108. unregged_user_form = MumbleUserLinkForm
  109. else:
  110. unregged_user_form = MumbleUserForm
  111. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'reg':
  112. try:
  113. user = MumbleUser.objects.get( server=srv, owner=request.user )
  114. except MumbleUser.DoesNotExist:
  115. regform = unregged_user_form( request.POST )
  116. regform.server = srv
  117. if regform.is_valid():
  118. model = regform.save( commit=False )
  119. model.owner = request.user
  120. model.server = srv
  121. # If we're linking accounts, the change is local only.
  122. model.save( dontConfigureMurmur=( "linkacc" in regform.data ) )
  123. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) )
  124. else:
  125. displayTab = 1
  126. else:
  127. regform = MumbleUserForm( request.POST, instance=user )
  128. regform.server = srv
  129. if regform.is_valid():
  130. regform.save()
  131. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) )
  132. else:
  133. displayTab = 1
  134. else:
  135. try:
  136. user = MumbleUser.objects.get( server=srv, owner=request.user )
  137. except MumbleUser.DoesNotExist:
  138. regform = unregged_user_form()
  139. else:
  140. regform = MumbleUserForm( instance=user )
  141. registered = True
  142. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'texture' and registered:
  143. textureform = MumbleTextureForm( request.POST, request.FILES )
  144. if textureform.is_valid():
  145. if 'usegravatar' in textureform.cleaned_data and textureform.cleaned_data['usegravatar'] and user.gravatar:
  146. user.setTextureFromUrl( user.gravatar )
  147. elif 'texturefile' in request.FILES:
  148. user.setTexture( Image.open( request.FILES['texturefile'] ) )
  149. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) )
  150. else:
  151. textureform = MumbleTextureForm()
  152. else:
  153. regform = None
  154. textureform = None
  155. if isAdmin:
  156. if request.method == 'POST' and 'mode' in request.POST:
  157. if request.POST['mode'] == 'kick':
  158. kickform = MumbleKickForm( request.POST )
  159. if kickform.is_valid():
  160. if kickform.cleaned_data["ban"]:
  161. srv.banUser( kickform.cleaned_data['session'], kickform.cleaned_data['reason'] )
  162. srv.kickUser( kickform.cleaned_data['session'], kickform.cleaned_data['reason'] )
  163. # ChannelTable is a somewhat misleading name, as it actually contains channels and players.
  164. channelTable = []
  165. for cid in srv.channels:
  166. if cid != 0 and srv.channels[cid].show:
  167. channelTable.append( srv.channels[cid] )
  168. for pid in srv.players:
  169. channelTable.append( srv.players[pid] )
  170. show_url = reverse( show, kwargs={ 'server': srv.id } )
  171. login_url = reverse( auth_views.login )
  172. return render_to_response( 'mumble/mumble.html', {
  173. 'login_url': "%s?next=%s" % ( login_url, show_url ),
  174. 'DBaseObject': srv,
  175. 'ChannelTable': channelTable,
  176. 'CurrentUserIsAdmin': isAdmin,
  177. 'AdminForm': adminform,
  178. 'RegForm': regform,
  179. 'TextureForm': textureform,
  180. 'Registered': registered,
  181. 'DisplayTab': displayTab,
  182. 'MumbleActive': True,
  183. 'MumbleAccount':user,
  184. }, context_instance = RequestContext(request) )
  185. def mobile_show( request, server ):
  186. """ Display the channel list for the given Server ID. """
  187. srv = get_object_or_404( Mumble, id=server )
  188. user = None
  189. if request.user.is_authenticated():
  190. try:
  191. user = MumbleUser.objects.get( server=srv, owner=request.user )
  192. except MumbleUser.DoesNotExist:
  193. pass
  194. return render_to_response( 'mumble/mobile_mumble.html', {
  195. 'DBaseObject': srv,
  196. 'MumbleActive': True,
  197. 'MumbleAccount':user,
  198. }, context_instance = RequestContext(request) )
  199. def showTexture( request, server, userid ):
  200. """ Pack the given user's texture into an HttpResponse.
  201. If userid is none, use the currently logged in User.
  202. """
  203. srv = get_object_or_404( Mumble, id=int(server) )
  204. user = get_object_or_404( MumbleUser, server=srv, id=int(userid) )
  205. try:
  206. img = user.getTexture()
  207. except ValueError:
  208. raise Http404()
  209. else:
  210. buf = StringIO()
  211. img.save( buf, "PNG" )
  212. return HttpResponse( buf.getvalue(), "image/png" )
  213. @login_required
  214. def users( request, server ):
  215. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  216. If the request has a "data" field, evaluate that and update the user records.
  217. """
  218. srv = get_object_or_404( Mumble, id=int(server) )
  219. if "resync" in request.POST and request.POST['resync'] == "true":
  220. srv.readUsersFromMurmur()
  221. if not srv.isUserAdmin( request.user ):
  222. return HttpResponse(
  223. simplejson.dumps({ 'success': False, 'objects': [], 'errormsg': 'Access denied' }),
  224. mimetype='text/javascript'
  225. )
  226. if request.method == 'POST':
  227. data = simplejson.loads( request.POST['data'] )
  228. for record in data:
  229. if record['id'] == -1:
  230. if record['delete']:
  231. continue
  232. mu = MumbleUser( server=srv )
  233. else:
  234. mu = MumbleUser.objects.get( id=record['id'] )
  235. if record['delete']:
  236. mu.delete()
  237. continue
  238. mu.name = record['name']
  239. mu.password = record['password']
  240. if record['owner']:
  241. mu.owner = User.objects.get( id=int(record['owner']) )
  242. mu.save()
  243. mu.aclAdmin = record['admin']
  244. users = []
  245. for mu in srv.mumbleuser_set.all():
  246. owner = None
  247. if mu.owner is not None:
  248. owner = mu.owner.id
  249. users.append( {
  250. 'id': mu.id,
  251. 'name': mu.name,
  252. 'password': None,
  253. 'owner': owner,
  254. 'admin': mu.aclAdmin,
  255. } )
  256. return HttpResponse(
  257. simplejson.dumps( { 'success': True, 'objects': users } ),
  258. mimetype='text/javascript'
  259. )
  260. @login_required
  261. def djangousers( request ):
  262. """ Return a list of all Django users' names and IDs. """
  263. users = [ { 'uid': '', 'uname': '------' } ]
  264. for du in User.objects.all().order_by( 'username' ):
  265. users.append( {
  266. 'uid': du.id,
  267. 'uname': unicode( du ),
  268. } )
  269. return HttpResponse(
  270. simplejson.dumps( { 'success': True, 'objects': users } ),
  271. mimetype='text/javascript'
  272. )
  273. def mmng_tree( request, server ):
  274. """ Return a JSON representation of the channel tree suitable for
  275. Murmur Manager:
  276. http://github.com/cheald/murmur-manager/tree/master/widget/
  277. To make the client widget query this view, set the URL attribute
  278. to "http://<mumble-django base URL>/mumble"
  279. """
  280. srv = get_object_or_404( Mumble, id=int(server) )
  281. chanlist = []
  282. userlist = []
  283. for chanid in srv.channels:
  284. channel = srv.channels[chanid]
  285. if channel.parent is not None:
  286. parent = channel.parent.chanid
  287. else:
  288. parent = -1
  289. chanlist.append({
  290. "type": "channel",
  291. "id": channel.chanid,
  292. "name": channel.name,
  293. "parent": parent,
  294. "position": channel.position,
  295. "state": channel.temporary and "temporary" or "permanent"
  296. })
  297. for sessionid in srv.players:
  298. user = srv.players[sessionid]
  299. userlist.append({
  300. "type": "player",
  301. "name": user.name,
  302. "channel": user.channel.chanid,
  303. "mute": user.mute or user.selfMute or user.suppress,
  304. "deaf": user.deaf or user.selfDeaf,
  305. "online": user.onlinesecs,
  306. "state": "online"
  307. })
  308. if "callback" in request.GET:
  309. prefix = request.GET["callback"]
  310. else:
  311. prefix = ""
  312. return HttpResponse(
  313. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  314. mimetype='text/javascript'
  315. )
  316. def mumbleviewer_tree_xml( request, server ):
  317. """ Get the XML tree from the server and serialize it to the client. """
  318. from xml.etree.cElementTree import tostring as xml_to_string
  319. srv = get_object_or_404( Mumble, id=int(server) )
  320. return HttpResponse(
  321. xml_to_string( srv.asMvXml(), encoding='utf-8' ),
  322. mimetype='text/xml'
  323. )
  324. def mumbleviewer_tree_json( request, server ):
  325. """ Get the Dict from the server and serialize it as JSON to the client. """
  326. srv = get_object_or_404( Mumble, id=int(server) )
  327. if "jsonp_callback" in request.GET:
  328. prefix = request.GET["jsonp_callback"]
  329. else:
  330. prefix = ""
  331. return HttpResponse(
  332. prefix + "(" + simplejson.dumps( srv.asMvJson() ) + ")",
  333. mimetype='text/javascript'
  334. )