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