Files
2026-11-14 17:05:01 +00:00

519 lines
18 KiB
Python

"""Visitor analytics — parse request metadata and persist visits/visitors.
This module holds the pure logic behind the tracking middleware so it can be
unit-tested without spinning up Flask or faking HTTP headers. The app factory
(`blog/__init__.py`) wires `record_visit()` into the request cycle; the UA and
referrer parsing are deliberately dependency-free (stdlib only).
What we capture for every public-page visit:
- browser / os / device -> from the User-Agent header
- referrer + source -> from the Referer header (where they found us)
- page path + title -> from the request URL + a lightweight lookup
- approximate location -> from the client IP (country/region/city + coords)
Only an opaque `visitor_id` cookie is used to correlate visits. The IP address
itself is never stored: geolocation lookups are cached under a SHA-256 hash and
only the resolved place is kept.
"""
import hashlib
import ipaddress
import json
import os
import re
import time
import urllib.request
from urllib.parse import quote, urlparse
from .db import get_db
# --- User-Agent parsing ----------------------------------------------------- #
# Ordered most-specific-first. Each entry is (token, browser-name); the first
# matching token wins. Chrome-on-iOS masquerades as Safari, so it is checked
# before the generic Safari rule.
_BROWSER_TOKENS = [
("Edg", "Edge"), # catches Edg / EdgE / EdgiOS / EdgA (Chromium-based Edge)
("Firefox", "Firefox"),
("Opera", "Opera"),
("SamsungBrowser", "Samsung Internet"),
("CriOS", "Safari"), # Chrome on iOS reports itself as Safari
("Chrome", "Chrome"),
("Vivaldi", "Vivaldi"),
("Brave", "Brave"),
("Edge", "Edge"), # legacy Edge (rare, pre-Chromium)
("KaiaOS", "KaiaOS"),
("Coast", "Firefox OS"),
("Safari", "Safari"),
]
# Ordered most-specific-first. iOS tokens MUST precede "Mac OS X"/"Darwin"
# because every Apple UA also contains "Mac OS X".
_OS_TOKENS = [
("iPhone", "iOS"),
("iPad", "iOS"),
("iPod", "iOS"),
("Windows", "Windows"),
("Mac OS X", "macOS"),
("Darwin", "macOS"),
("Android", "Android"),
("Linux", "Linux"),
]
_DEVICE_TOKENS = (
"Mobile iPad Tablet XBOX ONE PLAYSTATION Vita PS4 PS5 Baidu"
)
def parse_user_agent(ua):
"""Return a (browser, os, device) tuple from a User-Agent string.
Any field we cannot confidently identify is returned as an empty string so
the stored row stays clean rather than falling back to a wrong default.
"""
ua = (ua or "").strip()
if not ua:
return "", "", ""
browser = _first_match(ua, _BROWSER_TOKENS)
os_name = _first_match(ua, _OS_TOKENS)
device = "mobile" if any(tok in ua for tok in _DEVICE_TOKENS.split()) else "desktop"
# iPad is frequently a desktop-class device; downgrade only when the UA is
# an iOS Safari build (real touch/iPhone-style browsing).
if os_name == "iOS" and "Mobile" not in ua:
device = "desktop"
return browser, os_name, device
def _first_match(ua, tokens):
for token, name in tokens:
if token in ua:
return name
return ""
# Substrings that mark an automated client. Analytics used to record crawlers,
# uptime monitors and CLI fetchers as if they were readers, which inflated every
# number on the dashboard.
_BOT_TOKENS = (
"bot", "crawl", "spider", "slurp", "scrapy", "curl/", "wget",
"python-requests", "python-urllib", "httpx", "httpclient", "go-http-client",
"headlesschrome", "phantomjs", "monitor", "uptime", "pingdom", "feedfetcher",
"preview", "facebookexternalhit", "whatsapp", "telegrambot",
)
def is_bot(user_agent):
"""True when the User-Agent looks automated (or is missing entirely)."""
ua = (user_agent or "").strip().lower()
if not ua:
return True
return any(token in ua for token in _BOT_TOKENS)
# --- Referrer / source classification --------------------------------------- #
# Where the visitor came from. The raw referrer and its domain are always kept
# (for detail); `source` is a coarse category shown prominently in the UI.
_SEARCH_DOMAINS = {
"google", "bing", "duckduckgo", "yahoo", "brave", "startpage", "mojeek",
"ecosia", "qwant", "yandex", "search.marginalia.nu",
}
_SOCIAL_DOMAINS = {
"twitter", "x.com", "facebook", "fb.com", "instagram", "linkedin",
"reddit", "pinterest", "tumblr", "youtube", "tiktok", "vimeo", "mastodon",
}
def _matches_any(host, domain_set):
"""True if any label of `host` (excluding the TLD) is in `domain_set`."""
host = host.lower()
if host in domain_set:
return True
for label in host.split(".")[:-1]: # drop the top-level domain
if label in domain_set:
return True
return False
def classify_source(referer):
"""Return a (referrer, domain, source) tuple.
`source` is one of: 'direct', 'search', 'social', 'referral', 'external'.
"""
if not referer:
return "", "", "direct"
referer = referer.strip()
parsed = urlparse(referer)
domain = (parsed.netloc or "").lower()
host = domain.split(":")[0] # drop any port
if not host:
return referer, "", "external"
# Match on the bare domain name appearing as any label (so "www.google.com",
# "mobile.twitter.com" etc. are still recognised), then collapse a leading
# subdomain (www./m./mobile.) to the registrable domain for clean grouping.
host = host.lower()
if _matches_any(host, _SEARCH_DOMAINS):
source = "search"
elif _matches_any(host, _SOCIAL_DOMAINS):
source = "social"
else:
source = "referral" # any other known web origin
labels = host.split(".")
domain = ".".join(labels[1:]) if len(labels) > 2 else host
return referer, domain, source
# --- Location (IP geolocation) ---------------------------------------------- #
# The dashboard shows where readers are, so each visitor's approximate location
# is resolved from their IP address: country/region/city plus map coordinates.
#
# Lookups are best-effort and cached per *hashed* IP (geo_cache), so repeat
# visits cost one indexed read and a flaky/unreachable service never blocks a
# page: the visit is still recorded, just without a location. Set BLOG_GEOIP=0
# to turn all outbound lookups off.
GEO_API_TEMPLATE = os.environ.get("BLOG_GEOIP_URL", "https://ipwho.is/{ip}")
GEO_POSITIVE_TTL = 60 * 60 * 24 * 30 # re-check a resolved address after 30 days
GEO_NEGATIVE_TTL = 60 * 60 * 24 # retry a failed lookup after a day
def _env_float(name, default):
try:
return float(os.environ.get(name, default))
except (TypeError, ValueError):
return default
def geo_enabled():
"""Geo lookups default to on; BLOG_GEOIP=0 opts out entirely."""
return os.environ.get("BLOG_GEOIP", "1").strip().lower() not in (
"0", "false", "no", "off",
)
def _blank_location():
return {
"country": "",
"country_code": "",
"region": "",
"city": "",
"latitude": None,
"longitude": None,
}
def hash_ip(ip):
"""Stable pseudonymous cache key; the raw IP never reaches the database."""
return hashlib.sha256((ip or "").strip().encode("utf-8", "replace")).hexdigest()
def _row_location(row):
return {
"country": row["country"] or "",
"country_code": row["country_code"] or "",
"region": row["region"] or "",
"city": row["city"] or "",
"latitude": row["latitude"],
"longitude": row["longitude"],
}
def _coordinate(value, limit):
try:
number = float(value)
except (TypeError, ValueError):
return None
if -limit <= number <= limit:
return round(number, 4)
return None
GEO_SELF_KEY = "__server__" # cache key for this host's own public location
def local_fallback_enabled():
"""Whether LAN/local visitors fall back to the server's own location."""
return os.environ.get("BLOG_GEOIP_LOCAL", "1").strip().lower() not in (
"0", "false", "no", "off",
)
def _public_ip(value):
"""Return `value` as a normalised public IP string, or ''."""
try:
address = ipaddress.ip_address((value or "").strip())
except ValueError:
return ""
return str(address) if address.is_global else ""
def client_ip(remote_addr, headers, trust_proxy=False):
"""Resolve the reader's address, looking through a local proxy if needed.
Docker's port publishing and LAN reverse proxies make every request appear
to come from a private address (172.20.0.1, 192.168.2.2, ...), which used to
switch geolocation off entirely. When the direct peer is private/loopback the
real address is only available in the forwarding headers, so the first public
address they name is used. Headers from a direct internet peer are ignored
(unless BLOG_TRUST_PROXY is set) so clients cannot spoof their own location.
"""
peer = (remote_addr or "").strip()
try:
peer_is_local = not ipaddress.ip_address(peer).is_global
except ValueError:
peer_is_local = True
if not (peer_is_local or trust_proxy):
return peer
for name in ("CF-Connecting-IP", "True-Client-IP", "X-Real-IP"):
candidate = _public_ip(headers.get(name, ""))
if candidate:
return candidate
for part in (headers.get("X-Forwarded-For", "") or "").split(","):
candidate = _public_ip(part)
if candidate:
return candidate
return peer
def _cache_location(db, ip_hash, location, ok):
db.execute(
"""
INSERT INTO geo_cache
(ip_hash, ok, country, country_code, region, city, latitude,
longitude, checked_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(ip_hash) DO UPDATE SET
ok = excluded.ok,
country = excluded.country,
country_code = excluded.country_code,
region = excluded.region,
city = excluded.city,
latitude = excluded.latitude,
longitude = excluded.longitude,
checked_at = excluded.checked_at
""",
(
ip_hash,
1 if ok else 0,
location["country"],
location["country_code"],
location["region"],
location["city"],
location["latitude"],
location["longitude"],
time.time(),
),
)
db.commit()
def lookup_location(ip):
"""Return an approximate location dict for a visitor's IP address.
Public addresses are resolved directly. Private/loopback addresses (LAN
readers, or every request behind Docker's port mapping when nothing forwards
the real address) have no location of their own, so they fall back to this
server's own public location — the closest sensible guess for a self-hosted
blog. Set BLOG_GEOIP_LOCAL=0 to disable that fallback. Any network/API
problem degrades to an empty location rather than an error.
"""
location = _blank_location()
if not geo_enabled():
return location
ip = (ip or "").strip()
if ip:
try:
if not ipaddress.ip_address(ip).is_global:
ip = ""
except ValueError:
return location
if not ip and not local_fallback_enabled():
return location
db = get_db()
key = hash_ip(ip or GEO_SELF_KEY)
row = db.execute("SELECT * FROM geo_cache WHERE ip_hash = ?", (key,)).fetchone()
if row is not None:
ttl = GEO_POSITIVE_TTL if row["ok"] else GEO_NEGATIVE_TTL
if time.time() - (row["checked_at"] or 0) < ttl:
return _row_location(row)
try:
# An empty {ip} resolves the caller, i.e. this server's egress address.
api_request = urllib.request.Request(
GEO_API_TEMPLATE.format(ip=quote(ip)),
headers={"User-Agent": "SimpleBlogAnalytics/1.0"},
)
with urllib.request.urlopen(
api_request, timeout=_env_float("BLOG_GEOIP_TIMEOUT", 2.5)
) as response:
payload = json.loads(response.read(65536).decode("utf-8", "replace"))
if not payload.get("success", True):
raise ValueError("geolocation lookup failed")
location = {
"country": (payload.get("country") or "").strip(),
"country_code": (payload.get("country_code") or "").strip().upper(),
"region": (payload.get("region") or "").strip(),
"city": (payload.get("city") or "").strip(),
"latitude": _coordinate(payload.get("latitude"), 90),
"longitude": _coordinate(payload.get("longitude"), 180),
}
except Exception:
# Offline, rate-limited or malformed: remember the failure for a day so
# every page view does not pay for another timeout.
try:
_cache_location(db, key, location, ok=False)
except Exception:
pass
return _blank_location()
try:
_cache_location(db, key, location, ok=True)
except Exception:
pass
return location
def country_flag(code):
"""Turn an ISO 3166-1 alpha-2 code into a flag emoji ('' when unknown)."""
code = (code or "").strip().upper()
if len(code) != 2 or not code.isalpha():
return ""
return "".join(chr(0x1F1E6 + ord(ch) - ord("A")) for ch in code)
# --- Persistence ------------------------------------------------------------- #
def record_visit(visitor, page_path, title, ip=""):
"""Upsert the visitor row and append a visit for `page_path`.
`visitor` is a dict of the mutable fields (browser, os, device, referrer,
referrer_domain, source, country, ...). `ip` is used once to resolve the
visitor's approximate location when they are new or still have none.
Returns the visitor row.
"""
db = get_db()
# Upsert: match on visitor_id, update the mutable fields + last_seen.
row = db.execute(
"SELECT * FROM visitors WHERE visitor_id = ?", (visitor["visitor_id"],)
).fetchone()
# Resolve the location only when it is still missing (cached per hashed IP),
# so returning readers never trigger another lookup.
visitor = dict(visitor)
if row is None or not (row["country"] or row["city"]):
visitor.update(lookup_location(ip))
if row is None:
now = _utcnow()
first_seen = now
db.execute(
"""
INSERT INTO visitors
(visitor_id, browser, os, device, referrer, referrer_domain,
source, country, country_code, region, city, latitude,
longitude, first_seen, last_seen, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
visitor["visitor_id"],
visitor.get("browser") or "",
visitor.get("os") or "",
visitor.get("device") or "",
visitor.get("referrer") or "",
visitor.get("referrer_domain") or "",
visitor.get("source") or "direct",
visitor.get("country") or "",
visitor.get("country_code") or "",
visitor.get("region") or "",
visitor.get("city") or "",
visitor.get("latitude"),
visitor.get("longitude"),
first_seen,
first_seen,
now,
),
)
else:
# Keep the first-ever referrer/source (do not overwrite with a later
# empty/changed value), but always refresh last_seen.
keep_referrer = visitor.get("referrer") or row["referrer"]
keep_domain = visitor.get("referrer_domain") or row["referrer_domain"]
keep_source = visitor.get("source") or row["source"]
# Never erase a location we already resolved with a later empty lookup.
keep_country = visitor.get("country") or row["country"]
keep_code = visitor.get("country_code") or row["country_code"]
keep_region = visitor.get("region") or row["region"]
keep_city = visitor.get("city") or row["city"]
keep_lat = (
visitor.get("latitude")
if visitor.get("latitude") is not None
else row["latitude"]
)
keep_lon = (
visitor.get("longitude")
if visitor.get("longitude") is not None
else row["longitude"]
)
db.execute(
"""
UPDATE visitors
SET browser = COALESCE(?, browser),
os = COALESCE(? , os),
device = COALESCE(? , device),
referrer = COALESCE(? , referrer),
referrer_domain = COALESCE(? , referrer_domain),
source = COALESCE(? , source),
country = COALESCE(? , country),
country_code = COALESCE(? , country_code),
region = COALESCE(? , region),
city = COALESCE(? , city),
latitude = COALESCE(? , latitude),
longitude = COALESCE(? , longitude),
last_seen = ?
WHERE visitor_id = ?
""",
(
visitor.get("browser") or "",
visitor.get("os") or "",
visitor.get("device") or "",
keep_referrer,
keep_domain,
keep_source,
keep_country,
keep_code,
keep_region,
keep_city,
keep_lat,
keep_lon,
_utcnow(),
visitor["visitor_id"],
),
)
db.execute(
"""
INSERT INTO visits (visitor_id, page_path, title, timestamp)
VALUES (?, ?, ?, ?)
""",
(
visitor["visitor_id"],
page_path,
title or "",
_utcnow(),
),
)
db.commit()
return row
def _utcnow():
from datetime import datetime, timezone
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")