tighter sponsor columns
[wolnelektury.git] / src / wolnelektury / utils.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import json
6 import os
7 from functools import wraps
8
9 import pytz
10 from inspect import getargspec
11
12 from django.core.mail import send_mail
13 from django.http import HttpResponse
14 from django.template import RequestContext
15 from django.template.loader import render_to_string
16 from django.utils import timezone
17 from django.conf import settings
18 from django.utils.translation import ugettext
19
20 tz = pytz.timezone(settings.TIME_ZONE)
21
22
23 def localtime_to_utc(localtime):
24     return timezone.utc.normalize(
25         tz.localize(localtime)
26     )
27
28
29 def utc_for_js(dt):
30     return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
31
32
33 def makedirs(path):
34     if not os.path.isdir(path):
35         os.makedirs(path)
36
37
38 def stringify_keys(dictionary):
39     return dict((keyword.encode('ascii'), value)
40                 for keyword, value in dictionary.iteritems())
41
42
43 def json_encode(obj, sort_keys=True, ensure_ascii=False):
44     return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
45
46
47 def json_decode(obj):
48     return json.loads(obj)
49
50
51 def json_decode_fallback(value):
52     try:
53         return json_decode(value)
54     except ValueError:
55         return value
56
57
58 class AjaxError(Exception):
59     pass
60
61
62 def ajax(login_required=False, method=None, template=None, permission_required=None):
63     def decorator(fun):
64         @wraps(fun)
65         def ajax_view(request):
66             kwargs = {}
67             request_params = None
68             if method == 'post':
69                 request_params = request.POST
70             elif method == 'get':
71                 request_params = request.GET
72             fun_params, xx, fun_kwargs, defaults = getargspec(fun)
73             if defaults:
74                 required_params = fun_params[1:-len(defaults)]
75             else:
76                 required_params = fun_params[1:]
77             missing_params = set(required_params) - set(request_params)
78             if missing_params:
79                 res = {
80                     'result': 'missing params',
81                     'missing': ', '.join(missing_params),
82                 }
83             else:
84                 if request_params:
85                     request_params = dict(
86                         (key, json_decode_fallback(value))
87                         for key, value in request_params.iteritems()
88                         if fun_kwargs or key in fun_params)
89                     kwargs.update(stringify_keys(request_params))
90                 res = None
91                 if login_required and not request.user.is_authenticated():
92                     res = {'result': 'logout'}
93                 if (permission_required and
94                         not request.user.has_perm(permission_required)):
95                     res = {'result': 'access denied'}
96             if not res:
97                 try:
98                     res = fun(request, **kwargs)
99                     if res and template:
100                         res = {'html': render_to_string(template, res, RequestContext(request))}
101                 except AjaxError as e:
102                     res = {'result': e.args[0]}
103             if 'result' not in res:
104                 res['result'] = 'ok'
105             return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
106                                 status=200 if res['result'] == 'ok' else 400)
107
108         return ajax_view
109
110     return decorator
111
112
113 def send_noreply_mail(subject, message, recipient_list, **kwargs):
114     send_mail(
115         u'[WolneLektury] ' + subject,
116         message + u"\n\n-- \n" + ugettext(u'Message sent automatically. Please do not reply.'),
117         'no-reply@wolnelektury.pl', recipient_list, **kwargs)