Fundraising in PDF.
[wolnelektury.git] / src / stats / utils.py
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.
3 #
4 from django.conf import settings
5 from datetime import datetime
6 import logging
7 from functools import update_wrapper
8 from urllib.parse import urlencode
9 from random import random
10 from inspect import isclass
11
12 from django.utils.encoding import force_bytes
13
14 from .tasks import track_request
15
16 logger = logging.getLogger(__name__)
17
18
19 def piwik_url(request):
20     return urlencode(dict(
21         idsite=getattr(settings, 'PIWIK_SITE_ID', '0'),
22         rec=1,
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")
32     ))
33
34 PIWIK_API_VERSION = 1
35
36
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
40     """
41     if not getattr(settings, 'PIWIK_SITE_ID', 0):
42         return klass_or_method
43
44     # get target method
45     if isclass(klass_or_method):
46         klass = klass_or_method
47         call_func = klass.__call__
48     else:
49         call_func = klass_or_method
50
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)
55
56     # and wrap it
57     update_wrapper(wrap, call_func)
58
59     if isclass(klass_or_method):
60         klass.__call__ = wrap
61         return klass
62     else:
63         return wrap
64
65
66 def piwik_track_view(view):
67     if not getattr(settings, 'PIWIK_SITE_ID', 0):
68         return view
69
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)
74
75     update_wrapper(wrap, view)
76     return wrap