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.

384 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
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 = get_list_or_404( Mumble );
  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. isAdmin = srv.isUserAdmin( request.user );
  79. # The tab to start on.
  80. displayTab = 0;
  81. if isAdmin:
  82. if request.method == 'POST' and "mode" in request.POST and request.POST['mode'] == 'admin':
  83. adminform = MumbleForm( request.POST, instance=srv );
  84. if adminform.is_valid():
  85. adminform.save();
  86. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  87. else:
  88. displayTab = 2;
  89. else:
  90. adminform = MumbleForm( instance=srv );
  91. else:
  92. adminform = None;
  93. registered = False;
  94. user = None;
  95. if request.user.is_authenticated():
  96. # Unregistered users may or may not need a password to register.
  97. if settings.PROTECTED_MODE and srv.passwd:
  98. unregged_user_form = MumbleUserPasswordForm;
  99. # Unregistered users may or may not want to link an existing account
  100. elif settings.ALLOW_ACCOUNT_LINKING:
  101. unregged_user_form = MumbleUserLinkForm;
  102. else:
  103. unregged_user_form = MumbleUserForm;
  104. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'reg':
  105. try:
  106. user = MumbleUser.objects.get( server=srv, owner=request.user );
  107. except MumbleUser.DoesNotExist:
  108. regform = unregged_user_form( request.POST );
  109. regform.server = srv;
  110. if regform.is_valid():
  111. model = regform.save( commit=False );
  112. model.owner = request.user;
  113. model.server = srv;
  114. # If we're linking accounts, the change is local only.
  115. model.save( dontConfigureMurmur=( "linkacc" in regform.data ) );
  116. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  117. else:
  118. displayTab = 1;
  119. else:
  120. regform = MumbleUserForm( request.POST, instance=user );
  121. regform.server = srv;
  122. if regform.is_valid():
  123. regform.save();
  124. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  125. else:
  126. displayTab = 1;
  127. else:
  128. try:
  129. user = MumbleUser.objects.get( server=srv, owner=request.user );
  130. except MumbleUser.DoesNotExist:
  131. regform = unregged_user_form();
  132. else:
  133. regform = MumbleUserForm( instance=user );
  134. registered = True;
  135. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'texture' and registered:
  136. textureform = MumbleTextureForm( request.POST, request.FILES );
  137. if textureform.is_valid():
  138. user.setTexture( Image.open( request.FILES['texturefile'] ) );
  139. return HttpResponseRedirect( reverse( show, kwargs={ 'server': int(server), } ) );
  140. else:
  141. textureform = MumbleTextureForm();
  142. else:
  143. regform = None;
  144. textureform = None;
  145. if isAdmin:
  146. if request.method == 'POST' and 'mode' in request.POST and request.POST['mode'] == 'kick':
  147. kickform = MumbleKickForm( request.POST );
  148. if kickform.is_valid():
  149. if kickform.cleaned_data["ban"]:
  150. srv.banUser( kickform.cleaned_data['session'], kickform.cleaned_data['reason'] );
  151. srv.kickUser( kickform.cleaned_data['session'], kickform.cleaned_data['reason'] );
  152. # ChannelTable is a somewhat misleading name, as it actually contains channels and players.
  153. channelTable = [];
  154. for cid in srv.channels:
  155. if cid != 0 and srv.channels[cid].show:
  156. channelTable.append( srv.channels[cid] );
  157. for pid in srv.players:
  158. channelTable.append( srv.players[pid] );
  159. show_url = reverse( show, kwargs={ 'server': srv.id } );
  160. login_url = reverse( auth_views.login );
  161. return render_to_response(
  162. 'mumble/mumble.html',
  163. {
  164. 'login_url': "%s?next=%s" % ( login_url, show_url ),
  165. 'DBaseObject': srv,
  166. 'ChannelTable': channelTable,
  167. 'CurrentUserIsAdmin': isAdmin,
  168. 'AdminForm': adminform,
  169. 'RegForm': regform,
  170. 'TextureForm': textureform,
  171. 'Registered': registered,
  172. 'DisplayTab': displayTab,
  173. 'MumbleActive': True,
  174. 'MumbleAccount':user,
  175. },
  176. context_instance = RequestContext(request)
  177. );
  178. def mobile_show( request, server ):
  179. """ Display the channel list for the given Server ID. """
  180. srv = get_object_or_404( Mumble, id=server );
  181. user = None;
  182. if request.user.is_authenticated():
  183. try:
  184. user = MumbleUser.objects.get( server=srv, owner=request.user );
  185. except MumbleUser.DoesNotExist:
  186. pass;
  187. return render_to_response(
  188. 'mumble/mobile_mumble.html',
  189. {
  190. 'DBaseObject': srv,
  191. 'MumbleActive': True,
  192. 'MumbleAccount':user,
  193. },
  194. context_instance = RequestContext(request)
  195. );
  196. def showTexture( request, server, userid = None ):
  197. """ Pack the given user's texture into an HttpResponse.
  198. If userid is none, use the currently logged in User.
  199. """
  200. srv = get_object_or_404( Mumble, id=int(server) );
  201. if userid is None:
  202. if request.user.is_authenticated():
  203. user = get_object_or_404( MumbleUser, server=srv, owner=request.user );
  204. else:
  205. raise Http404();
  206. else:
  207. user = get_object_or_404( MumbleUser, server=srv, id=int(userid) );
  208. try:
  209. img = user.getTexture();
  210. except ValueError:
  211. raise Http404();
  212. else:
  213. buf = StringIO();
  214. img.save( buf, "PNG" );
  215. return HttpResponse( buf.getvalue(), "image/png" );
  216. @login_required
  217. def users( request, server ):
  218. """ Create a list of MumbleUsers for a given server serialized as a JSON object.
  219. If the request has a "data" field, evaluate that and update the user records.
  220. """
  221. srv = get_object_or_404( Mumble, id=int(server) );
  222. if "resync" in request.POST and request.POST['resync'] == "true":
  223. srv.readUsersFromMurmur();
  224. if not srv.isUserAdmin( request.user ):
  225. return HttpResponse(
  226. simplejson.dumps({ 'success': False, 'objects': [], 'errormsg': 'Access denied' }),
  227. mimetype='text/javascript'
  228. );
  229. if request.method == 'POST':
  230. data = simplejson.loads( request.POST['data'] );
  231. for record in data:
  232. if record['id'] == -1:
  233. if record['delete']:
  234. continue;
  235. mu = MumbleUser( server=srv );
  236. else:
  237. mu = MumbleUser.objects.get( id=record['id'] );
  238. if record['delete']:
  239. mu.delete();
  240. continue;
  241. mu.name = record['name'];
  242. mu.password = record['password'];
  243. if record['owner']:
  244. mu.owner = User.objects.get( id=int(record['owner']) );
  245. mu.save();
  246. mu.aclAdmin = record['admin'];
  247. users = [];
  248. for mu in srv.mumbleuser_set.all():
  249. owner = None;
  250. if mu.owner is not None:
  251. owner = mu.owner.id
  252. users.append( {
  253. 'id': mu.id,
  254. 'name': mu.name,
  255. 'password': None,
  256. 'owner': owner,
  257. 'admin': mu.aclAdmin,
  258. } );
  259. return HttpResponse(
  260. simplejson.dumps( { 'success': True, 'objects': users } ),
  261. mimetype='text/javascript'
  262. );
  263. @login_required
  264. def djangousers( request ):
  265. """ Return a list of all Django users' names and IDs. """
  266. users = [ { 'uid': '', 'uname': '------' } ];
  267. for du in User.objects.all().order_by( 'username' ):
  268. users.append( {
  269. 'uid': du.id,
  270. 'uname': unicode( du ),
  271. } );
  272. return HttpResponse(
  273. simplejson.dumps( { 'success': True, 'objects': users } ),
  274. mimetype='text/javascript'
  275. );
  276. def mmng_tree( request, server ):
  277. """ Return a JSON representation of the channel tree suitable for
  278. Murmur Manager:
  279. http://github.com/cheald/murmur-manager/tree/master/widget/
  280. To make the client widget query this view, set the URL attribute
  281. to "http://<mumble-django base URL>/mumble"
  282. """
  283. srv = get_object_or_404( Mumble, id=int(server) );
  284. chanlist = []
  285. userlist = []
  286. for chanid in srv.channels:
  287. channel = srv.channels[chanid]
  288. if channel.parent is not None:
  289. parent = channel.parent.chanid
  290. else:
  291. parent = -1
  292. chanlist.append({
  293. "type": "channel",
  294. "id": channel.chanid,
  295. "name": channel.name,
  296. "parent": parent,
  297. "position": channel.position,
  298. "state": channel.temporary and "temporary" or "permanent"
  299. })
  300. for sessionid in srv.players:
  301. user = srv.players[sessionid]
  302. userlist.append({
  303. "type": "player",
  304. "name": user.name,
  305. "channel": user.channel.chanid,
  306. "mute": user.mute or user.selfMute or user.suppress,
  307. "deaf": user.deaf or user.selfDeaf or user.suppress,
  308. "online": user.onlinesecs,
  309. "state": "online"
  310. })
  311. if "callback" in request.GET:
  312. prefix = request.GET["callback"]
  313. else:
  314. prefix = ""
  315. return HttpResponse(
  316. prefix + "(" + simplejson.dumps( { 'channels': chanlist, 'users': userlist } ) + ")",
  317. mimetype='text/javascript'
  318. );