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 def piwik_track(klass_or_method):
29 """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
30 Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
32 # Retrieve piwik information
33 current_site = Site.objects.get_current()
34 piwik_site = PiwikSite.objects.filter(site=current_site.id)
36 if len(piwik_site) == 0:
37 logger.debug("No PiwikSite is configured for Site " + current_site.name)
38 return klass_or_method
40 id_piwik = piwik_site[0].id_site
41 host = urlparse.urlsplit(settings.PIWIK_URL).netloc
44 if isclass(klass_or_method):
45 klass = klass_or_method
46 call_func = klass.__call__
48 call_func = klass_or_method
50 def wrap(self, request, *args, **kw):
51 conn = httplib.HTTPConnection(host)
52 conn.request('GET', piwik_url(
54 apiv=PIWIK_API_VERSION,
55 rand=int(random() * 0x10000),
56 token_auth=urllib.quote(settings.PIWIK_TOKEN),
57 cip=urllib.quote(request.META['REMOTE_ADDR']),
58 url=urllib.quote('http://' + request.META['HTTP_HOST'] + request.path),
59 urlref=urllib.quote(request.META['HTTP_REFERER']) if 'HTTP_REFERER' in request.META else '',
63 return call_func(self, request, *args, **kw)
66 update_wrapper(wrap, call_func)
68 if isclass(klass_or_method):