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.
7 from functools import wraps
10 from inspect import getargspec
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
20 tz = pytz.timezone(settings.TIME_ZONE)
23 def localtime_to_utc(localtime):
24 return timezone.utc.normalize(
25 tz.localize(localtime)
30 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
34 if not os.path.isdir(path):
38 def stringify_keys(dictionary):
39 return dict((keyword.encode('ascii'), value)
40 for keyword, value in dictionary.iteritems())
43 def json_encode(obj, sort_keys=True, ensure_ascii=False):
44 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
48 return json.loads(obj)
51 def json_decode_fallback(value):
53 return json_decode(value)
58 class AjaxError(Exception):
62 def ajax(login_required=False, method=None, template=None, permission_required=None):
65 def ajax_view(request):
69 request_params = request.POST
71 request_params = request.GET
72 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
74 required_params = fun_params[1:-len(defaults)]
76 required_params = fun_params[1:]
77 missing_params = set(required_params) - set(request_params)
80 'result': 'missing params',
81 'missing': ', '.join(missing_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))
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'}
98 res = fun(request, **kwargs)
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:
105 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
106 status=200 if res['result'] == 'ok' else 400)
113 def send_noreply_mail(subject, message, recipient_list, **kwargs):
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)