allow no PIWIK conf, fix test reqs
[wolnelektury.git] / apps / 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.contrib.sites.models import Site
6 from piwik.django.models import PiwikSite
7 from django.conf import settings
8 import logging
9 from functools import update_wrapper
10 import httplib
11 import urlparse
12 import urllib
13 from random import random
14 from inspect import isclass
15
16 logger = logging.getLogger(__name__)
17
18
19 def piwik_url(**kw):
20     url = settings.PIWIK_URL + u"/piwik.php?"
21     url += u'&'.join([k + u"=" + str(v) for k, v in kw.items()])
22     logger.info("piwik url: %s" % url)
23     return url
24
25 PIWIK_API_VERSION = 1
26
27
28 # Retrieve piwik information
29 try:
30     _host = urlparse.urlsplit(settings.PIWIK_URL).netloc
31 except AttributeError:
32     logger.debug("PIWIK_URL not configured.")
33     _host = None
34 try:
35     _id_piwik = PiwikSite.objects.get(site=Site.objects.get_current().id).id_site
36 except PiwikSite.DoesNotExist:
37     logger.debug("No PiwikSite is configured.")
38     _id_piwik = None
39
40 def piwik_track(klass_or_method):
41     """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
42     Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
43     """
44     if _id_piwik is None:
45         return klass_or_method
46
47     # get target method
48     if isclass(klass_or_method):
49         klass = klass_or_method
50         call_func = klass.__call__
51     else:
52         call_func = klass_or_method
53
54     def wrap(self, request, *args, **kw):
55         conn = httplib.HTTPConnection(_host)
56         conn.request('GET', piwik_url(
57             rec=1,
58             apiv=PIWIK_API_VERSION,
59             rand=int(random() * 0x10000),
60             token_auth=urllib.quote(settings.PIWIK_TOKEN),
61             cip=urllib.quote(request.META['REMOTE_ADDR']),
62             url=urllib.quote('http://' + request.META['HTTP_HOST'] + request.path),
63             urlref=urllib.quote(request.META['HTTP_REFERER']) if 'HTTP_REFERER' in request.META else '',
64             idsite=_id_piwik))
65
66         conn.close()
67         return call_func(self, request, *args, **kw)
68
69     # and wrap it
70     update_wrapper(wrap, call_func)
71
72     if isclass(klass_or_method):
73         klass.__call__ = wrap
74         return klass
75     else:
76         return wrap