1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from django.conf import settings
5 from datetime import datetime
7 from functools import update_wrapper
8 from urllib.parse import urlencode
9 from random import random
10 from inspect import isclass
12 from django.utils.encoding import force_bytes
14 from .tasks import track_request
16 logger = logging.getLogger(__name__)
19 def piwik_url(request):
20 return urlencode(dict(
21 idsite=getattr(settings, 'PIWIK_SITE_ID', '0'),
23 url=force_bytes('http://%s%s' % (request.META['HTTP_HOST'], request.path)),
24 rand=int(random() * 0x10000),
25 apiv=PIWIK_API_VERSION,
26 urlref=force_bytes(request.META.get('HTTP_REFERER', '')),
27 ua=request.META.get('HTTP_USER_AGENT', ''),
28 lang=request.META.get('HTTP_ACCEPT_LANGUAGE', ''),
29 token_auth=getattr(settings, 'PIWIK_TOKEN', ''),
30 cip=request.META['REMOTE_ADDR'],
31 cdt=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
37 def piwik_track(klass_or_method):
38 """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
39 Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
41 if not getattr(settings, 'PIWIK_SITE_ID', 0):
42 return klass_or_method
45 if isclass(klass_or_method):
46 klass = klass_or_method
47 call_func = klass.__call__
49 call_func = klass_or_method
51 def wrap(self, request, *args, **kw):
52 if getattr(request, 'piwik_track', True):
53 track_request.delay(piwik_url(request))
54 return call_func(self, request, *args, **kw)
57 update_wrapper(wrap, call_func)
59 if isclass(klass_or_method):
66 def piwik_track_view(view):
67 if not getattr(settings, 'PIWIK_SITE_ID', 0):
70 def wrap(request, *args, **kwargs):
71 if getattr(request, 'piwik_track', True):
72 track_request.delay(piwik_url(request))
73 return view(request, *args, **kwargs)
75 update_wrapper(wrap, view)