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.
10 from functools import wraps
13 from inspect import getargspec
16 from django.core.mail import send_mail
17 from django.http import HttpResponse
18 from django.template import RequestContext
19 from django.template.loader import render_to_string
20 from django.utils import timezone
21 from django.conf import settings
22 from django.utils.translation import ugettext
24 tz = pytz.timezone(settings.TIME_ZONE)
27 def localtime_to_utc(localtime):
28 return timezone.utc.normalize(
29 tz.localize(localtime)
34 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
38 if not os.path.isdir(path):
42 def stringify_keys(dictionary):
43 return dict((keyword.encode('ascii'), value)
44 for keyword, value in dictionary.iteritems())
47 def json_encode(obj, sort_keys=True, ensure_ascii=False):
48 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
52 return json.loads(obj)
55 def json_decode_fallback(value):
57 return json_decode(value)
62 class AjaxError(Exception):
66 def ajax(login_required=False, method=None, template=None, permission_required=None):
69 def ajax_view(request):
73 request_params = request.POST
75 request_params = request.GET
76 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
78 required_params = fun_params[1:-len(defaults)]
80 required_params = fun_params[1:]
81 missing_params = set(required_params) - set(request_params)
84 'result': 'missing params',
85 'missing': ', '.join(missing_params),
89 request_params = dict(
90 (key, json_decode_fallback(value))
91 for key, value in request_params.iteritems()
92 if fun_kwargs or key in fun_params)
93 kwargs.update(stringify_keys(request_params))
95 if login_required and not request.user.is_authenticated():
96 res = {'result': 'logout'}
97 if (permission_required and
98 not request.user.has_perm(permission_required)):
99 res = {'result': 'access denied'}
102 res = fun(request, **kwargs)
104 res = {'html': render_to_string(template, res, RequestContext(request))}
105 except AjaxError as e:
106 res = {'result': e.args[0]}
107 if 'result' not in res:
109 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
110 status=200 if res['result'] == 'ok' else 400)
117 def send_noreply_mail(subject, message, recipient_list, **kwargs):
119 u'[WolneLektury] ' + subject,
120 message + u"\n\n-- \n" + ugettext(u'Message sent automatically. Please do not reply.'),
121 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
124 # source: https://docs.python.org/2/library/csv.html#examples
125 class UnicodeCSVWriter(object):
127 A CSV writer which will write rows to CSV file "f",
128 which is encoded in the given encoding.
131 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
132 # Redirect output to a queue
133 self.queue = cStringIO.StringIO()
134 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
136 self.encoder = codecs.getincrementalencoder(encoding)()
138 def writerow(self, row):
139 self.writer.writerow([s.encode("utf-8") for s in row])
140 # Fetch UTF-8 output from the queue ...
141 data = self.queue.getvalue()
142 data = data.decode("utf-8")
143 # ... and reencode it into the target encoding
144 data = self.encoder.encode(data)
145 # write to the target stream
146 self.stream.write(data)
148 self.queue.truncate(0)
150 def writerows(self, rows):
155 # the original re.escape messes with unicode
157 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
160 BOT_BITS = ['bot', 'slurp', 'spider', 'facebook', 'crawler', 'parser', 'http']
163 def is_crawler(request):
164 user_agent = request.META.get('HTTP_USER_AGENT')
167 user_agent = user_agent.lower()
168 return any(bot_bit in user_agent for bot_bit in BOT_BITS)