d20039cd2aa1bbe1444913bcba4c63878043bce0
[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 codecs
6 import csv
7 import cStringIO
8 import json
9 import os
10 from functools import wraps
11
12 import pytz
13 from inspect import getargspec
14
15 import re
16 from django.core.mail import send_mail
17 from django.http import HttpResponse
18 from django.template import RequestContext
19 from django.template.loader import render_to_string
20 from django.utils import timezone
21 from django.conf import settings
22 from django.utils.translation import ugettext
23
24 tz = pytz.timezone(settings.TIME_ZONE)
25
26
27 def localtime_to_utc(localtime):
28     return timezone.utc.normalize(
29         tz.localize(localtime)
30     )
31
32
33 def utc_for_js(dt):
34     return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
35
36
37 def makedirs(path):
38     if not os.path.isdir(path):
39         os.makedirs(path)
40
41
42 def stringify_keys(dictionary):
43     return dict((keyword.encode('ascii'), value)
44                 for keyword, value in dictionary.iteritems())
45
46
47 def json_encode(obj, sort_keys=True, ensure_ascii=False):
48     return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
49
50
51 def json_decode(obj):
52     return json.loads(obj)
53
54
55 def json_decode_fallback(value):
56     try:
57         return json_decode(value)
58     except ValueError:
59         return value
60
61
62 class AjaxError(Exception):
63     pass
64
65
66 def ajax(login_required=False, method=None, template=None, permission_required=None):
67     def decorator(fun):
68         @wraps(fun)
69         def ajax_view(request):
70             kwargs = {}
71             request_params = None
72             if method == 'post':
73                 request_params = request.POST
74             elif method == 'get':
75                 request_params = request.GET
76             fun_params, xx, fun_kwargs, defaults = getargspec(fun)
77             if defaults:
78                 required_params = fun_params[1:-len(defaults)]
79             else:
80                 required_params = fun_params[1:]
81             missing_params = set(required_params) - set(request_params)
82             if missing_params:
83                 res = {
84                     'result': 'missing params',
85                     'missing': ', '.join(missing_params),
86                 }
87             else:
88                 if request_params:
89                     request_params = dict(
90                         (key, json_decode_fallback(value))
91                         for key, value in request_params.iteritems()
92                         if fun_kwargs or key in fun_params)
93                     kwargs.update(stringify_keys(request_params))
94                 res = None
95                 if login_required and not request.user.is_authenticated():
96                     res = {'result': 'logout'}
97                 if (permission_required and
98                         not request.user.has_perm(permission_required)):
99                     res = {'result': 'access denied'}
100             if not res:
101                 try:
102                     res = fun(request, **kwargs)
103                     if res and template:
104                         res = {'html': render_to_string(template, res, RequestContext(request))}
105                 except AjaxError as e:
106                     res = {'result': e.args[0]}
107             if 'result' not in res:
108                 res['result'] = 'ok'
109             return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
110                                 status=200 if res['result'] == 'ok' else 400)
111
112         return ajax_view
113
114     return decorator
115
116
117 def send_noreply_mail(subject, message, recipient_list, **kwargs):
118     send_mail(
119         u'[WolneLektury] ' + subject,
120         message + u"\n\n-- \n" + ugettext(u'Message sent automatically. Please do not reply.'),
121         'no-reply@wolnelektury.pl', recipient_list, **kwargs)
122
123
124 # source: https://docs.python.org/2/library/csv.html#examples
125 class UnicodeCSVWriter(object):
126     """
127     A CSV writer which will write rows to CSV file "f",
128     which is encoded in the given encoding.
129     """
130
131     def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
132         # Redirect output to a queue
133         self.queue = cStringIO.StringIO()
134         self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
135         self.stream = f
136         self.encoder = codecs.getincrementalencoder(encoding)()
137
138     def writerow(self, row):
139         self.writer.writerow([s.encode("utf-8") for s in row])
140         # Fetch UTF-8 output from the queue ...
141         data = self.queue.getvalue()
142         data = data.decode("utf-8")
143         # ... and reencode it into the target encoding
144         data = self.encoder.encode(data)
145         # write to the target stream
146         self.stream.write(data)
147         # empty queue
148         self.queue.truncate(0)
149
150     def writerows(self, rows):
151         for row in rows:
152             self.writerow(row)
153
154
155 # the original re.escape messes with unicode
156 def re_escape(s):
157     return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)