Code layout change.
[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 from .tasks import track_request
13
14 logger = logging.getLogger(__name__)
15
16
17 def piwik_url(request):
18     return urllib.urlencode(dict(
19         idsite=getattr(settings, 'PIWIK_SITE_ID', '0'),
20         rec=1,
21         url='http://%s%s' % (request.META['HTTP_HOST'], request.path),
22         rand=int(random() * 0x10000),
23         apiv=PIWIK_API_VERSION,
24         urlref=request.META.get('HTTP_REFERER', ''),
25         ua=request.META.get('HTTP_USER_AGENT', ''),
26         lang=request.META.get('HTTP_ACCEPT_LANGUAGE', ''),
27         token_auth=getattr(settings, 'PIWIK_TOKEN', ''),
28         cip=request.META['REMOTE_ADDR'],
29         cdt=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
30     ))
31
32 PIWIK_API_VERSION = 1
33
34
35 def piwik_track(klass_or_method):
36     """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
37     Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
38     """
39     if not getattr(settings, 'PIWIK_SITE_ID', 0):
40         return klass_or_method
41
42     # get target method
43     if isclass(klass_or_method):
44         klass = klass_or_method
45         call_func = klass.__call__
46     else:
47         call_func = klass_or_method
48
49     def wrap(self, request, *args, **kw):
50         if getattr(request, 'piwik_track', True):
51             track_request.delay(piwik_url(request))
52         return call_func(self, request, *args, **kw)
53
54     # and wrap it
55     update_wrapper(wrap, call_func)
56
57     if isclass(klass_or_method):
58         klass.__call__ = wrap
59         return klass
60     else:
61         return wrap