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 django.conf import settings
7 from datetime import datetime
9 from functools import update_wrapper
11 from random import random
12 from inspect import isclass
13 from .tasks import track_request
15 logger = logging.getLogger(__name__)
18 def piwik_url(request):
19 return urllib.urlencode(dict(
20 idsite=getattr(settings, 'PIWIK_SITE_ID', '0'),
22 url='http://%s%s' % (request.META['HTTP_HOST'], request.path),
23 rand=int(random() * 0x10000),
24 apiv=PIWIK_API_VERSION,
25 urlref=request.META.get('HTTP_REFERER', ''),
26 ua=request.META.get('HTTP_USER_AGENT', ''),
27 lang=request.META.get('HTTP_ACCEPT_LANGUAGE', ''),
28 token_auth=getattr(settings, 'PIWIK_TOKEN', ''),
29 cip=request.META['REMOTE_ADDR'],
30 cdt=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
36 def piwik_track(klass_or_method):
37 """Track decorated class or method using Piwik (according to configuration in settings and django-piwik)
38 Works for handler classes (executed by __call__) or handler methods. Expects request to be the first parameter
40 if not getattr(settings, 'PIWIK_SITE_ID', 0):
41 return klass_or_method
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 track_request.delay(piwik_url(request))
52 return call_func(self, request, *args, **kw)
55 update_wrapper(wrap, call_func)
57 if isclass(klass_or_method):