import ipaddress import logging import re from functools import lru_cache from urllib.parse import urlsplit from django.conf import settings from django.db import DatabaseError from django.db.models import F, OuterRef, Subquery, Sum, Value from django.db.models.functions import Coalesce from django.utils import timezone from .models import TrafficDaily logger = logging.getLogger(__name__) PUBLIC = { 'home', 'chapters', 'chapter', 'chapter-discussion', 'slx-series-reviews', 'slx-series-review', 'slx-reviews', 'slx-review', 'blog', 'blog-post', 'entries', 'entry', 'upcoming', 'stream', 'slx-community', 'search', 'books', 'coming-soon', } BOT = re.compile(r'bot\b|spider|crawler|preview|facebookexternalhit|headless|curl/|python-requests', re.I) HOST = re.compile(r'(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\Z') def source_origin(request): try: remote = urlsplit(request.META.get('HTTP_REFERER', '')[:4096]) name = remote.hostname if remote.scheme not in ('https', 'http') or not name or not HOST.fullmatch(name): return '' own = urlsplit('//' + request.get_host()).hostname if name == own: return 'internal' value = f'{remote.scheme}://{name}' return value if len(value) <= 255 else '' except ValueError: return '' @lru_cache(maxsize=1) def geo_reader(path): import maxminddb try: return maxminddb.open_database(path) except maxminddb.InvalidDatabaseError as exc: raise ValueError('Invalid country database') from exc def location_for(request): empty = {'country': '', 'region': '', 'city': ''} if not settings.SLX_GEOIP_DB: return empty header = ( 'HTTP_X_SLX_CLIENT_IP' if settings.SLX_TRUST_CADDY_IP else 'REMOTE_ADDR' ) try: ip = ipaddress.ip_address(request.META.get(header, '')) if not ip.is_global: return empty row = geo_reader(settings.SLX_GEOIP_DB).get(str(ip)) or {} country = row.get('country', {}).get('iso_code', '') subdivisions = row.get('subdivisions') or [] region = '' if subdivisions: region = subdivisions[0].get('names', {}).get('en', '') city = row.get('city', {}).get('names', {}).get('en', '') return { 'country': country if re.fullmatch(r'[A-Z]{2}', country) else '', 'region': region[:120], 'city': city[:120], } except (ValueError, OSError, ImportError, RuntimeError): return empty def view_total(kind, ident): return TrafficDaily.objects.filter(kind=kind, target_id=ident).aggregate(total=Sum('views'))['total'] or 0 def with_views(qs, kind): totals = TrafficDaily.objects.filter(kind=kind, target_id=OuterRef('pk')).order_by().values('target_id').annotate( total=Sum('views')).values('total') return qs.annotate(public_views=Coalesce(Subquery(totals), Value(0), output_field=TrafficDaily._meta.get_field('views'))) class TrafficMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) match = getattr(request, 'resolver_match', None) if (not settings.SLX_ANALYTICS or request.method != 'GET' or response.status_code != 200 or not response.get('Content-Type', '').startswith('text/html') or not match or match.namespace or match.url_name not in PUBLIC or getattr(request.user, 'is_staff', False) or request.META.get('HTTP_DNT') == '1' or request.META.get('HTTP_SEC_GPC') == '1' or any('prefetch' in request.META.get(header, '').lower() for header in ('HTTP_SEC_PURPOSE', 'HTTP_PURPOSE')) or not request.META.get('HTTP_USER_AGENT') or BOT.search(request.META['HTTP_USER_AGENT'])): return response kind, target = getattr(request, 'slx_view_target', ('site', 0)) try: location = location_for(request) row, created = TrafficDaily.objects.get_or_create( day=timezone.localdate(), kind=kind, target_id=target, route=match.url_name, country=location['country'], region=location['region'], city=location['city'], source=source_origin(request), ) if not created: TrafficDaily.objects.filter(pk=row.pk).update(views=F('views') + 1) except DatabaseError: logger.warning('SLX traffic could not be recorded.') return response