98 lines
4.0 KiB
Python
98 lines
4.0 KiB
Python
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 country_for(request):
|
|
if not settings.SLX_GEOIP_DB:
|
|
return ''
|
|
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 ''
|
|
row = geo_reader(settings.SLX_GEOIP_DB).get(str(ip)) or {}
|
|
code = row.get('country', {}).get('iso_code', '')
|
|
return code if re.fullmatch(r'[A-Z]{2}', code) else ''
|
|
except (ValueError, OSError, ImportError, RuntimeError):
|
|
return ''
|
|
|
|
|
|
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:
|
|
row, created = TrafficDaily.objects.get_or_create(day=timezone.localdate(), kind=kind, target_id=target,
|
|
route=match.url_name, country=country_for(request), 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
|