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