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