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.

412 lines
12 KiB

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