1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from functools import wraps
7 from inspect import getargspec
14 from django.conf import settings
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 import timezone
20 from django.utils.translation import get_language
21 from django.conf import settings
22 from django.utils.safestring import mark_safe
23 from django.utils.translation import ugettext
26 tz = pytz.timezone(settings.TIME_ZONE)
29 def localtime_to_utc(localtime):
30 return timezone.utc.normalize(
31 tz.localize(localtime)
36 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
40 if not os.path.isdir(path):
44 def stringify_keys(dictionary):
45 return dict((keyword.encode('ascii'), value)
46 for keyword, value in dictionary.items())
49 def json_encode(obj, sort_keys=True, ensure_ascii=False):
50 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
54 return json.loads(obj)
57 def json_decode_fallback(value):
59 return json_decode(value)
64 class AjaxError(Exception):
68 def ajax(login_required=False, method=None, template=None, permission_required=None):
71 def ajax_view(request):
75 request_params = request.POST
77 request_params = request.GET
78 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
80 required_params = fun_params[1:-len(defaults)]
82 required_params = fun_params[1:]
83 missing_params = set(required_params) - set(request_params)
86 'result': 'missing params',
87 'missing': ', '.join(missing_params),
91 request_params = dict(
92 (key, json_decode_fallback(value))
93 for key, value in request_params.items()
94 if fun_kwargs or key in fun_params)
95 kwargs.update(stringify_keys(request_params))
97 if login_required and not request.user.is_authenticated:
98 res = {'result': 'logout'}
99 if (permission_required and
100 not request.user.has_perm(permission_required)):
101 res = {'result': 'access denied'}
104 res = fun(request, **kwargs)
106 res = {'html': render_to_string(template, res, request=request)}
107 except AjaxError as e:
108 res = {'result': e.args[0]}
109 if 'result' not in res:
111 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
112 status=200 if res['result'] == 'ok' else 400)
119 def send_noreply_mail(subject, message, recipient_list, **kwargs):
121 u'[WolneLektury] ' + subject,
122 message + u"\n\n-- \n" + ugettext(u'Message sent automatically. Please do not reply.'),
123 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
126 # source: https://docs.python.org/2/library/csv.html#examples
127 class UnicodeCSVWriter(object):
129 A CSV writer which will write rows to CSV file "f",
130 which is encoded in the given encoding.
133 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
134 # Redirect output to a queue
135 self.queue = BytesIO()
136 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
138 self.encoder = codecs.getincrementalencoder(encoding)()
140 def writerow(self, row):
141 self.writer.writerow([s.encode("utf-8") for s in row])
142 # Fetch UTF-8 output from the queue ...
143 data = self.queue.getvalue()
144 data = data.decode("utf-8")
145 # ... and reencode it into the target encoding
146 data = self.encoder.encode(data)
147 # write to the target stream
148 self.stream.write(data)
150 self.queue.truncate(0)
152 def writerows(self, rows):
157 # the original re.escape messes with unicode
159 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
162 BOT_BITS = ['bot', 'slurp', 'spider', 'facebook', 'crawler', 'parser', 'http']
165 def is_crawler(request):
166 user_agent = request.META.get('HTTP_USER_AGENT')
169 user_agent = user_agent.lower()
170 return any(bot_bit in user_agent for bot_bit in BOT_BITS)
173 def get_cached_render_key(instance, property_name, language=None):
175 language = get_language()
176 return 'cached_render:%s.%s:%s:%s' % (
177 type(instance).__name__,
184 def cached_render(template_name, timeout=24 * 60 * 60):
185 def decorator(method):
188 key = get_cached_render_key(self, method.__name__)
189 content = cache.get(key)
191 context = method(self)
192 content = render_to_string(template_name, context)
193 cache.set(key, str(content), timeout=timeout)
195 content = mark_safe(content)
201 def clear_cached_renders(bound_method):
202 for lc, ln in settings.LANGUAGES:
204 get_cached_render_key(
205 bound_method.__self__,
206 bound_method.__name__,