Bring Piwik for API back.
[wolnelektury.git] / src / stats / utils.py
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.
4 #
5 from django.conf import settings
6 from datetime import datetime
7 import logging
8 from functools import update_wrapper
9 import urllib
10 from random import random
11 from inspect import isclass
12
13 from django.utils.encoding import force_str
14
15 from .tasks import track_request
16
17 logger = logging.getLogger(__name__)
18
19
20 def piwik_url(request):
21     return urllib.urlencode(dict(
22         idsite=getattr(settings, 'PIWIK_SITE_ID', '0'),
23         rec=1,
24         url=force_str('http://%s%s' % (request.META['HTTP_HOST'], request.path)),
25         rand=int(random() * 0x10000),
26         apiv=PIWIK_API_VERSION,
27         urlref=force_str(request.META.get('HTTP_REFERER', '')),
28         ua=request.META.get('HTTP_USER_AGENT', ''),
29         lang=request.META.get('HTTP_ACCEPT_LANGUAGE', ''),
30         token_auth=getattr(settings, 'PIWIK_TOKEN', ''),
31         cip=request.META['REMOTE_ADDR'],
32         cdt=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
33     ))
34
35 PIWIK_API_VERSION = 1
36
37
38 def piwik_track(klass_or_method):
39     """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
40     Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
41     """
42     if not getattr(settings, 'PIWIK_SITE_ID', 0):
43         return klass_or_method
44
45     # get target method
46     if isclass(klass_or_method):
47         klass = klass_or_method
48         call_func = klass.__call__
49     else:
50         call_func = klass_or_method
51
52     def wrap(self, request, *args, **kw):
53         if getattr(request, 'piwik_track', True):
54             track_request.delay(piwik_url(request))
55         return call_func(self, request, *args, **kw)
56
57     # and wrap it
58     update_wrapper(wrap, call_func)
59
60     if isclass(klass_or_method):
61         klass.__call__ = wrap
62         return klass
63     else:
64         return wrap
65
66
67 def piwik_track_view(view):
68     if not getattr(settings, 'PIWIK_SITE_ID', 0):
69         return view
70
71     def wrap(request, *args, **kwargs):
72         if getattr(request, 'piwik_track', True):
73             track_request.delay(piwik_url(request))
74         return view(self, request, *args, **kwargs)
75
76     update_wrapper(wrap, view)
77     return wrap