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.

381 lines
11 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
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 django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
  18. from django.template import RequestContext
  19. from django.http import Http404, HttpResponse, HttpResponseRedirect
  20. from django.contrib.auth.decorators import login_required
  21. from django.contrib.auth.models import User
  22. from django.conf import settings
  23. from django.core.urlresolvers import reverse
  24. from django.contrib.auth import views as auth_views
  25. from models import Mumble, MumbleUser
  26. from forms import MumbleForm, MumbleUserForm, MumbleUserPasswordForm
  27. from forms import MumbleUserLinkForm, MumbleTextureForm, MumbleKickForm
  28. def redir( request ):
  29. """ Redirect to the servers list. """
  30. if request.META['HTTP_USER_AGENT'].startswith( 'BlackBerry' ) or \
  31. "Opera Mobi" in request.META['HTTP_USER_AGENT'] or \
  32. "Opera Mini" in request.META['HTTP_USER_AGENT'] or \
  33. "Windows CE" in request.META['HTTP_USER_AGENT'] or \
  34. "MIDP" in request.META['HTTP_USER_AGENT'] or \
  35. "Palm" in request.META['HTTP_USER_AGENT'] or \
  36. "NetFront" in request.META['HTTP_USER_AGENT'] or \
  37. "Nokia" in request.META['HTTP_USER_AGENT'] or \
  38. "Symbian" in request.META['HTTP_USER_AGENT'] or \
  39. "UP.Browser" in request.META['HTTP_USER_AGENT'] or \
  40. "UP.Link" in request.META['HTTP_USER_AGENT'] or \
  41. "WinWAP" in request.META['HTTP_USER_AGENT'] or \
  42. "Android" in request.META['HTTP_USER_AGENT'] or \
  43. "DoCoMo" in request.META['HTTP_USER_AGENT'] or \
  44. "KDDI-" in request.META['HTTP_USER_AGENT'] or \
  45. "Softbank" in request.META['HTTP_USER_AGENT'] or \
  46. "J-Phone" in request.META['HTTP_USER_AGENT'] or \
  47. "IEMobile" in request.META['HTTP_USER_AGENT'] or \
  48. "iPod" in request.META['HTTP_USER_AGENT'] or \
  49. "iPhone" in request.META['HTTP_USER_AGENT']:
  50. return HttpResponseRedirect( reverse( mobile_mumbles ) );
  51. else:
  52. return HttpResponseRedirect( reverse( mumbles ) );
  53. def mobile_mumbles( request ):
  54. return mumbles( request, mobile=True );
  55. def mumbles( request, mobile=False ):
  56. """ Display a list of all configured Mumble servers, or redirect if only one configured. """
  57. mms = get_list_or_404( Mumble );
  58. if len(mms) == 1:
  59. return HttpResponseRedirect( reverse(
  60. { False: show, True: mobile_show }[mobile],
  61. kwargs={ 'server': mms[0].id, }
  62. ) );
  63. return render_to_response(
  64. 'mumble/%s.html' % { False: 'list', True: 'mobile_list' }[mobile],
  65. { 'MumbleObjects': mms,
  66. 'MumbleActive': True,
  67. },
  68. context_instance = RequestContext(request)
  69. );
  70. def show( request, server ):
  71. """Display the channel list for the given Server ID.
  72. This includes not only the channel list itself, but indeed the user registration,
  73. server admin and user texture form as well. The template then uses JavaScript
  74. to display these forms integrated into the Channel viewer.
  75. """
  76. srv = get_object_or_404( Mumble, id=server );
  77. isAdmin = srv.isUserAdmin( request.user );
  78. # The tab to start on.
  79. displayTab = 0;
  80. if isAdmin:
  81. if request.method == 'POST' and "mode" in request.POST and request.POST['mode'] == 'admin':
  82. adminform = MumbleForm( request.POST, instance=srv );
  83. if adminform.is_valid():
  84. adminform.save();
  85. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  86. else:
  87. displayTab = 2;
  88. else:
  89. adminform = MumbleForm( instance=srv );
  90. else:
  91. adminform = None;
  92. registered = False;
  93. user = None;
  94. if request.user.is_authenticated():
  95. # Unregistered users may or may not need a password to register.
  96. if settings.PROTECTED_MODE and srv.passwd:
  97. unregged_user_form = MumbleUserPasswordForm;
  98. # Unregistered users may or may not want to link an existing account
  99. elif settings.ALLOW_ACCOUNT_LINKING:
  100. unregged_user_form = MumbleUserLinkForm;
  101. else:
  102. unregged_user_form = MumbleUserForm;
  103. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'reg':
  104. try:
  105. user = MumbleUser.objects.get( server=srv, owner=request.user );
  106. except MumbleUser.DoesNotExist:
  107. regform = unregged_user_form( request.POST );
  108. regform.server = srv;
  109. if regform.is_valid():
  110. model = regform.save( commit=False );
  111. model.owner = request.user;
  112. model.server = srv;
  113. # If we're linking accounts, the change is local only.
  114. model.save( dontConfigureMurmur=( "linkacc" in regform.data ) );
  115. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  116. else:
  117. displayTab = 1;
  118. else:
  119. regform = MumbleUserForm( request.POST, instance=user );
  120. regform.server = srv;
  121. if regform.is_valid():
  122. regform.save();
  123. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  124. else:
  125. displayTab = 1;
  126. else:
  127. try:
  128. user = MumbleUser.objects.get( server=srv, owner=request.user );
  129. except MumbleUser.DoesNotExist:
  130. regform = unregged_user_form();
  131. else:
  132. regform = MumbleUserForm( instance=user );
  133. registered = True;
  134. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'texture' and registered:
  135. textureform = MumbleTextureForm( request.POST, request.FILES );
  136. if textureform.is_valid():
  137. user.setTexture( request.FILES['texturefile'] );
  138. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  139. else:
  140. textureform = MumbleTextureForm();
  141. else:
  142. regform = None;
  143. textureform = None;
  144. if isAdmin:
  145. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'kick':
  146. kickform = MumbleKickForm( request.POST );
  147. if kickform.is_valid():
  148. srv.kickUser( kickform.cleaned_data['session'], kickform.cleaned_data['reason'] );
  149. # ChannelTable is a somewhat misleading name, as it actually contains channels and players.
  150. channelTable = [];
  151. for cid in srv.channels:
  152. if cid != 0 and srv.channels[cid].show:
  153. channelTable.append( srv.channels[cid] );
  154. for pid in srv.players:
  155. channelTable.append( srv.players[pid] );
  156. show_url = reverse( show, kwargs={ 'server': srv.id } );
  157. login_url = reverse( auth_views.login );
  158. return render_to_response(
  159. 'mumble/mumble.html',
  160. {
  161. 'login_url': "%s?next=%s" % ( login_url, show_url ),
  162. 'DBaseObject': srv,
  163. 'ChannelTable': channelTable,
  164. 'CurrentUserIsAdmin': isAdmin,
  165. 'AdminForm': adminform,
  166. 'RegForm': regform,
  167. 'TextureForm': textureform,
  168. 'Registered': registered,
  169. 'DisplayTab': displayTab,
  170. 'MumbleActive': True,
  171. 'MumbleAccount':user,
  172. },
  173. context_instance = RequestContext(request)
  174. );
  175. def mobile_show( request, server ):
  176. """ Display the channel list for the given Server ID. """
  177. srv = get_object_or_404( Mumble, id=server );
  178. user = None;
  179. if request.user.is_authenticated():
  180. try:
  181. user = MumbleUser.objects.get( server=srv, owner=request.user );
  182. except MumbleUser.DoesNotExist:
  183. pass;
  184. return render_to_response(
  185. 'mumble/mobile_mumble.html',
  186. {
  187. 'DBaseObject': srv,
  188. 'MumbleActive': True,
  189. 'MumbleAccount':user,
  190. },
  191. context_instance = RequestContext(request)
  192. );
  193. def showTexture( request, server, userid = None ):
  194. """ Pack the given user's texture into an HttpResponse.
  195. If userid is none, use the currently logged in User.
  196. """
  197. srv = get_object_or_404( Mumble, id=int(server) );
  198. if userid is None:
  199. if request.user.is_authenticated():
  200. user = get_object_or_404( MumbleUser, server=srv, owner=request.user );
  201. else:
  202. raise Http404();
  203. else:
  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 or user.suppress,
  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. );