missing file
[wolnelektury.git] / src / wolnelektury / utils.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import codecs
5 import csv
6 from functools import wraps
7 from inspect import getargspec
8 from io import BytesIO
9 import json
10 import os
11 import re
12
13 from django.conf import settings
14 from django.contrib import admin
15 from django.core.cache import cache
16 from django.core.mail import send_mail
17 from django.http import HttpResponse
18 from django.template.loader import render_to_string
19 from django.utils.translation import get_language
20 from django.conf import settings
21 from django.utils.safestring import mark_safe
22 from django.utils.translation import gettext as _
23
24
25 def utc_for_js(dt):
26     return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
27
28
29 def makedirs(path):
30     if not os.path.isdir(path):
31         os.makedirs(path)
32
33
34 def stringify_keys(dictionary):
35     return dict((keyword.encode('ascii'), value)
36                 for keyword, value in dictionary.items())
37
38
39 def json_encode(obj, sort_keys=True, ensure_ascii=False):
40     return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
41
42
43 def json_decode(obj):
44     return json.loads(obj)
45
46
47 def json_decode_fallback(value):
48     try:
49         return json_decode(value)
50     except ValueError:
51         return value
52
53
54 class AjaxError(Exception):
55     pass
56
57
58 def ajax(login_required=False, method=None, template=None, permission_required=None):
59     def decorator(fun):
60         @wraps(fun)
61         def ajax_view(request):
62             kwargs = {}
63             request_params = None
64             if method == 'post':
65                 request_params = request.POST
66             elif method == 'get':
67                 request_params = request.GET
68             fun_params, xx, fun_kwargs, defaults = getargspec(fun)
69             if defaults:
70                 required_params = fun_params[1:-len(defaults)]
71             else:
72                 required_params = fun_params[1:]
73             missing_params = set(required_params) - set(request_params)
74             if missing_params:
75                 res = {
76                     'result': 'missing params',
77                     'missing': ', '.join(missing_params),
78                 }
79             else:
80                 if request_params:
81                     request_params = dict(
82                         (key, json_decode_fallback(value))
83                         for key, value in request_params.items()
84                         if fun_kwargs or key in fun_params)
85                     kwargs.update(stringify_keys(request_params))
86                 res = None
87                 if login_required and not request.user.is_authenticated:
88                     res = {'result': 'logout'}
89                 if (permission_required and
90                         not request.user.has_perm(permission_required)):
91                     res = {'result': 'access denied'}
92             if not res:
93                 try:
94                     res = fun(request, **kwargs)
95                     if res and template:
96                         res = {'html': render_to_string(template, res, request=request)}
97                 except AjaxError as e:
98                     res = {'result': e.args[0]}
99             if 'result' not in res:
100                 res['result'] = 'ok'
101             return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
102                                 status=200 if res['result'] == 'ok' else 400)
103
104         return ajax_view
105
106     return decorator
107
108
109 def send_noreply_mail(subject, message, recipient_list, **kwargs):
110     send_mail(
111         '[WolneLektury] ' + subject,
112         message + "\n\n-- \n" + _('Message sent automatically. Please do not reply.'),
113         'no-reply@wolnelektury.pl', recipient_list, **kwargs)
114
115
116 # source: https://docs.python.org/2/library/csv.html#examples
117 class UnicodeCSVWriter(object):
118     """
119     A CSV writer which will write rows to CSV file "f",
120     which is encoded in the given encoding.
121     """
122
123     def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
124         # Redirect output to a queue
125         self.queue = BytesIO()
126         self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
127         self.stream = f
128         self.encoder = codecs.getincrementalencoder(encoding)()
129
130     def writerow(self, row):
131         self.writer.writerow([s.encode("utf-8") for s in row])
132         # Fetch UTF-8 output from the queue ...
133         data = self.queue.getvalue()
134         data = data.decode("utf-8")
135         # ... and reencode it into the target encoding
136         data = self.encoder.encode(data)
137         # write to the target stream
138         self.stream.write(data)
139         # empty queue
140         self.queue.truncate(0)
141
142     def writerows(self, rows):
143         for row in rows:
144             self.writerow(row)
145
146
147 # the original re.escape messes with unicode
148 def re_escape(s):
149     return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
150
151
152 def get_cached_render_key(instance, property_name, language=None):
153     if language is None:
154         language = get_language()
155     return 'cached_render:%s.%s:%s:%s' % (
156             type(instance).__name__,
157             property_name,
158             instance.pk,
159             language
160         )
161
162
163 def cached_render(template_name, timeout=24 * 60 * 60):
164     def decorator(method):
165         @wraps(method)
166         def wrapper(self):
167             key = get_cached_render_key(self, method.__name__)
168             content = cache.get(key)
169             if content is None:
170                 context = method(self)
171                 content = render_to_string(template_name, context)
172                 cache.set(key, str(content), timeout=timeout)
173             else:
174                 content = mark_safe(content)
175             return content
176         return wrapper
177     return decorator
178
179
180 def clear_cached_renders(bound_method):
181     for lc, ln in settings.LANGUAGES:
182         cache.delete(
183             get_cached_render_key(
184                 bound_method.__self__,
185                 bound_method.__name__,
186                 lc
187             )
188         )
189
190
191 class YesNoFilter(admin.SimpleListFilter):
192     def lookups(self, request, model_admin):
193         return (
194             ('yes', _('Yes')),
195             ('no', _('No')),
196         )
197
198     def queryset(self, request, queryset):
199         if self.value() == 'yes':
200             return queryset.filter(self.q)
201         elif self.value() == 'no':
202             return queryset.exclude(self.q)
203
204
205 def is_ajax(request):
206     return request.headers.get('x-requested-with') == 'XMLHttpRequest'