This commit had some important milestones in it. The major update is that now I
[mediagoblin.git] / mediagoblin / tools / response.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import werkzeug.utils
18 from werkzeug.wrappers import Response as wz_Response
19 from mediagoblin.tools.template import render_template
20 from mediagoblin.tools.translate import (lazy_pass_to_ugettext as _,
21 pass_to_ugettext)
22 from mediagoblin.db.models import UserBan, User
23 from datetime import datetime
24
25 class Response(wz_Response):
26 """Set default response mimetype to HTML, otherwise we get text/plain"""
27 default_mimetype = u'text/html'
28
29
30 def render_to_response(request, template, context, status=200):
31 """Much like Django's shortcut.render()"""
32 return Response(
33 render_template(request, template, context),
34 status=status)
35
36
37 def render_error(request, status=500, title=_('Oops!'),
38 err_msg=_('An error occured')):
39 """Render any error page with a given error code, title and text body
40
41 Title and description are passed through as-is to allow html. Make
42 sure no user input is contained therein for security reasons. The
43 description will be wrapped in <p></p> tags.
44 """
45 return Response(render_template(request, 'mediagoblin/error.html',
46 {'err_code': status, 'title': title, 'err_msg': err_msg}),
47 status=status)
48
49
50 def render_403(request):
51 """Render a standard 403 page"""
52 _ = pass_to_ugettext
53 title = _('Operation not allowed')
54 err_msg = _("Sorry Dave, I can't let you do that!</p><p>You have tried "
55 " to perform a function that you are not allowed to. Have you "
56 "been trying to delete all user accounts again?")
57 return render_error(request, 403, title, err_msg)
58
59 def render_404(request):
60 """Render a standard 404 page."""
61 _ = pass_to_ugettext
62 err_msg = _("There doesn't seem to be a page at this address. Sorry!</p>"
63 "<p>If you're sure the address is correct, maybe the page "
64 "you're looking for has been moved or deleted.")
65 return render_error(request, 404, err_msg=err_msg)
66
67 def render_user_banned(request):
68 """Renders the page which tells a user they have been banned, for how long
69 and the reason why they have been banned"
70 """
71 user_ban = UserBan.query.get(request.user.id)
72 if datetime.now()>user_ban.expiration_date:
73 user_ban.delete()
74 redirect(request,
75 'mediagoblin.index')
76 return render_to_response(request,
77 'mediagoblin/banned.html',
78 {'reason':user_ban.reason,
79 'expiration_date':user_ban.expiration_date})
80
81 def render_http_exception(request, exc, description):
82 """Return Response() given a werkzeug.HTTPException
83
84 :param exc: werkzeug.HTTPException or subclass thereof
85 :description: message describing the error."""
86 # If we were passed the HTTPException stock description on
87 # exceptions where we have localized ones, use those:
88 stock_desc = (description == exc.__class__.description)
89
90 if stock_desc and exc.code == 403:
91 return render_403(request)
92 elif stock_desc and exc.code == 404:
93 return render_404(request)
94
95 return render_error(request, title=exc.args[0],
96 err_msg=description,
97 status=exc.code)
98
99
100 def redirect(request, *args, **kwargs):
101 """Redirects to an URL, using urlgen params or location string
102
103 :param querystring: querystring to be appended to the URL
104 :param location: If the location keyword is given, redirect to the URL
105 """
106 querystring = kwargs.pop('querystring', None)
107
108 # Redirect to URL if given by "location=..."
109 if 'location' in kwargs:
110 location = kwargs.pop('location')
111 else:
112 location = request.urlgen(*args, **kwargs)
113
114 if querystring:
115 location += querystring
116 return werkzeug.utils.redirect(location)
117
118
119 def redirect_obj(request, obj):
120 """Redirect to the page for the given object.
121
122 Requires obj to have a .url_for_self method."""
123 return redirect(request, location=obj.url_for_self(request.urlgen))