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.
5 from django.contrib.sites.models import Site
6 from piwik.django.models import PiwikSite
7 from django.conf import settings
9 from functools import update_wrapper
13 from random import random
14 from inspect import isclass
16 logger = logging.getLogger(__name__)
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)
28 # Retrieve piwik information
30 _host = urlparse.urlsplit(settings.PIWIK_URL).netloc
31 except AttributeError:
32 logger.debug("PIWIK_URL not configured.")
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.")
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
45 return klass_or_method
48 if isclass(klass_or_method):
49 klass = klass_or_method
50 call_func = klass.__call__
52 call_func = klass_or_method
54 def wrap(self, request, *args, **kw):
55 conn = httplib.HTTPConnection(_host)
56 conn.request('GET', piwik_url(
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 '',
67 return call_func(self, request, *args, **kw)
70 update_wrapper(wrap, call_func)
72 if isclass(klass_or_method):