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.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
22 tz = pytz.timezone(settings.TIME_ZONE)
25 def localtime_to_utc(localtime):
26 return timezone.utc.normalize(
27 tz.localize(localtime)
32 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
36 if not os.path.isdir(path):
40 def stringify_keys(dictionary):
41 return dict((keyword.encode('ascii'), value)
42 for keyword, value in dictionary.items())
45 def json_encode(obj, sort_keys=True, ensure_ascii=False):
46 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
50 return json.loads(obj)
53 def json_decode_fallback(value):
55 return json_decode(value)
60 class AjaxError(Exception):
64 def ajax(login_required=False, method=None, template=None, permission_required=None):
67 def ajax_view(request):
71 request_params = request.POST
73 request_params = request.GET
74 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
76 required_params = fun_params[1:-len(defaults)]
78 required_params = fun_params[1:]
79 missing_params = set(required_params) - set(request_params)
82 'result': 'missing params',
83 'missing': ', '.join(missing_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))
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'}
100 res = fun(request, **kwargs)
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:
107 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
108 status=200 if res['result'] == 'ok' else 400)
115 def send_noreply_mail(subject, message, recipient_list, **kwargs):
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)
122 # source: https://docs.python.org/2/library/csv.html#examples
123 class UnicodeCSVWriter(object):
125 A CSV writer which will write rows to CSV file "f",
126 which is encoded in the given encoding.
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)
134 self.encoder = codecs.getincrementalencoder(encoding)()
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)
146 self.queue.truncate(0)
148 def writerows(self, rows):
153 # the original re.escape messes with unicode
155 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
158 BOT_BITS = ['bot', 'slurp', 'spider', 'facebook', 'crawler', 'parser', 'http']
161 def is_crawler(request):
162 user_agent = request.META.get('HTTP_USER_AGENT')
165 user_agent = user_agent.lower()
166 return any(bot_bit in user_agent for bot_bit in BOT_BITS)