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.contrib import admin
16 from django.core.cache import cache
17 from django.core.mail import send_mail
18 from django.http import HttpResponse
19 from django.template.loader import render_to_string
20 from django.utils import timezone
21 from django.utils.translation import get_language
22 from django.conf import settings
23 from django.utils.safestring import mark_safe
24 from django.utils.translation import gettext as _
27 tz = pytz.timezone(settings.TIME_ZONE)
30 def localtime_to_utc(localtime):
31 return timezone.utc.normalize(
32 tz.localize(localtime)
37 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
41 if not os.path.isdir(path):
45 def stringify_keys(dictionary):
46 return dict((keyword.encode('ascii'), value)
47 for keyword, value in dictionary.items())
50 def json_encode(obj, sort_keys=True, ensure_ascii=False):
51 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
55 return json.loads(obj)
58 def json_decode_fallback(value):
60 return json_decode(value)
65 class AjaxError(Exception):
69 def ajax(login_required=False, method=None, template=None, permission_required=None):
72 def ajax_view(request):
76 request_params = request.POST
78 request_params = request.GET
79 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
81 required_params = fun_params[1:-len(defaults)]
83 required_params = fun_params[1:]
84 missing_params = set(required_params) - set(request_params)
87 'result': 'missing params',
88 'missing': ', '.join(missing_params),
92 request_params = dict(
93 (key, json_decode_fallback(value))
94 for key, value in request_params.items()
95 if fun_kwargs or key in fun_params)
96 kwargs.update(stringify_keys(request_params))
98 if login_required and not request.user.is_authenticated:
99 res = {'result': 'logout'}
100 if (permission_required and
101 not request.user.has_perm(permission_required)):
102 res = {'result': 'access denied'}
105 res = fun(request, **kwargs)
107 res = {'html': render_to_string(template, res, request=request)}
108 except AjaxError as e:
109 res = {'result': e.args[0]}
110 if 'result' not in res:
112 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
113 status=200 if res['result'] == 'ok' else 400)
120 def send_noreply_mail(subject, message, recipient_list, **kwargs):
122 '[WolneLektury] ' + subject,
123 message + "\n\n-- \n" + _('Message sent automatically. Please do not reply.'),
124 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
127 # source: https://docs.python.org/2/library/csv.html#examples
128 class UnicodeCSVWriter(object):
130 A CSV writer which will write rows to CSV file "f",
131 which is encoded in the given encoding.
134 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
135 # Redirect output to a queue
136 self.queue = BytesIO()
137 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
139 self.encoder = codecs.getincrementalencoder(encoding)()
141 def writerow(self, row):
142 self.writer.writerow([s.encode("utf-8") for s in row])
143 # Fetch UTF-8 output from the queue ...
144 data = self.queue.getvalue()
145 data = data.decode("utf-8")
146 # ... and reencode it into the target encoding
147 data = self.encoder.encode(data)
148 # write to the target stream
149 self.stream.write(data)
151 self.queue.truncate(0)
153 def writerows(self, rows):
158 # the original re.escape messes with unicode
160 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
163 def get_cached_render_key(instance, property_name, language=None):
165 language = get_language()
166 return 'cached_render:%s.%s:%s:%s' % (
167 type(instance).__name__,
174 def cached_render(template_name, timeout=24 * 60 * 60):
175 def decorator(method):
178 key = get_cached_render_key(self, method.__name__)
179 content = cache.get(key)
181 context = method(self)
182 content = render_to_string(template_name, context)
183 cache.set(key, str(content), timeout=timeout)
185 content = mark_safe(content)
191 def clear_cached_renders(bound_method):
192 for lc, ln in settings.LANGUAGES:
194 get_cached_render_key(
195 bound_method.__self__,
196 bound_method.__name__,
202 class YesNoFilter(admin.SimpleListFilter):
203 def lookups(self, request, model_admin):
209 def queryset(self, request, queryset):
210 if self.value() == 'yes':
211 return queryset.filter(self.q)
212 elif self.value() == 'no':
213 return queryset.exclude(self.q)