Files
history-collector/app/main.py
T

295 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import asyncio
import base64
import hmac
import logging
import os
import sqlite3
from contextlib import closing
from datetime import datetime, timezone
from html import escape
from pathlib import Path
from typing import Annotated
from urllib.parse import urlencode, urlparse
from zoneinfo import ZoneInfo
import httpx
from fastapi import FastAPI, Header, HTTPException, Query, Request, status
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field, HttpUrl
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("history-collector")
DATA_DIR = Path(os.getenv("DATA_DIR", "/data"))
DB_PATH = DATA_DIR / "history.sqlite3"
API_TOKEN = os.getenv("API_TOKEN", "")
VIEWER_USERNAME = os.getenv("VIEWER_USERNAME", "admin")
VIEWER_PASSWORD = os.getenv("VIEWER_PASSWORD", "")
DISCORD_WEBHOOK_URL = os.getenv("DISCORD_WEBHOOK_URL", "")
MAX_VISITS_PER_REQUEST = int(os.getenv("MAX_VISITS_PER_REQUEST", "100"))
PAGE_SIZE_CHOICES = (25, 50, 100, 250)
DEFAULT_PAGE_SIZE = 50
LOCAL_TIMEZONE = ZoneInfo("Europe/Ljubljana")
INGESTION_LOG_FILENAME = "history-collector.log"
_FILE_HANDLER_MARKER = "_history_collector_file_handler"
class Visit(BaseModel):
url: HttpUrl
title: str = Field(default="", max_length=1000)
visit_time: datetime
transition: str = Field(default="observed", max_length=100)
class VisitBatch(BaseModel):
device_id: str = Field(min_length=1, max_length=128, pattern=r"^[a-zA-Z0-9._-]+$")
visits: list[Visit] = Field(min_length=1, max_length=MAX_VISITS_PER_REQUEST)
app = FastAPI(title="Local History Collector", docs_url=None, redoc_url=None)
_VALIDATION_LOCATION_FIELDS = frozenset(
{"body", "device_id", "visits", "url", "title", "visit_time", "transition"}
)
def local_timestamp(value: datetime | None = None) -> str:
return (value or datetime.now(timezone.utc)).astimezone(LOCAL_TIMEZONE).isoformat(timespec="seconds")
class LocalLogFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
return local_timestamp(datetime.fromtimestamp(record.created, timezone.utc))
def ingestion_log_path() -> Path:
return DATA_DIR / INGESTION_LOG_FILENAME
def configure_file_logging() -> None:
log_path = ingestion_log_path()
log_path.resolve().parent.mkdir(parents=True, exist_ok=True)
for handler in list(logger.handlers):
if not getattr(handler, _FILE_HANDLER_MARKER, False):
continue
if Path(handler.baseFilename).resolve() == log_path.resolve():
return
logger.removeHandler(handler)
handler.close()
handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
try:
os.chmod(log_path, 0o600)
except OSError:
handler.close()
raise
handler.setLevel(logging.INFO)
handler.setFormatter(LocalLogFormatter("%(asctime)s %(levelname)s %(message)s"))
setattr(handler, _FILE_HANDLER_MARKER, True)
logger.addHandler(handler)
def validation_error_summary(exc: RequestValidationError) -> str:
summaries = []
errors = exc.errors()
for error in errors[:20]:
location = []
for part in error.get("loc", ()):
if isinstance(part, int):
location.append(f"index_{part}")
elif isinstance(part, str) and part in _VALIDATION_LOCATION_FIELDS:
location.append(part)
else:
location.append("field")
error_type = error.get("type")
if not isinstance(error_type, str) or not error_type:
error_type = "unknown"
error_type = "".join(char if char.isalnum() or char in "._-" else "_" for char in error_type)[:80]
summaries.append(f"{'.'.join(location) or 'unknown'}:{error_type or 'unknown'}")
if len(errors) > 20:
summaries.append(f"...+{len(errors) - 20}_more")
return ",".join(summaries) or "unknown"
@app.exception_handler(RequestValidationError)
async def log_visit_validation_error(request: Request, exc: RequestValidationError):
if request.url.path == "/v1/visits":
logger.warning(
"visit_ingestion_rejected ingestion_timestamp=%s timezone=Europe/Ljubljana status=422 "
"reason=request_validation_failed validation=%s",
local_timestamp(),
validation_error_summary(exc),
)
return await request_validation_exception_handler(request, exc)
def domain_from_url(url: str) -> str:
return (urlparse(url).hostname or "").lower()
def connect():
DATA_DIR.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY, device_id TEXT NOT NULL, url TEXT NOT NULL,
domain TEXT NOT NULL DEFAULT '', title TEXT NOT NULL DEFAULT '',
visit_time TEXT NOT NULL, transition TEXT NOT NULL, received_at TEXT NOT NULL,
UNIQUE(device_id, url, visit_time))""")
# Migration for databases created by collector v1.
columns = {row[1] for row in conn.execute("PRAGMA table_info(visits)")}
if "domain" not in columns:
conn.execute("ALTER TABLE visits ADD COLUMN domain TEXT NOT NULL DEFAULT ''")
missing = conn.execute("SELECT id, url FROM visits WHERE domain = ''").fetchall()
conn.executemany("UPDATE visits SET domain = ? WHERE id = ?", [(domain_from_url(row["url"]), row["id"]) for row in missing])
conn.execute("CREATE INDEX IF NOT EXISTS idx_visits_device_time ON visits(device_id, visit_time DESC)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_visits_domain ON visits(domain)")
conn.commit()
return conn
@app.on_event("startup")
def startup():
try:
DATA_DIR.mkdir(parents=True, exist_ok=True)
configure_file_logging()
except Exception as exc:
raise RuntimeError(f"Unable to configure application log file at {ingestion_log_path()}: {exc}") from exc
if len(API_TOKEN) < 24:
raise RuntimeError("API_TOKEN must contain at least 24 characters")
if len(VIEWER_PASSWORD) < 12:
raise RuntimeError("VIEWER_PASSWORD must contain at least 12 characters")
with closing(connect()):
pass
def require_token(authorization: str | None):
if not hmac.compare_digest(authorization or "", f"Bearer {API_TOKEN}"):
logger.warning(
"visit_ingestion_rejected ingestion_timestamp=%s timezone=Europe/Ljubljana status=401 reason=invalid_api_token",
local_timestamp(),
)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid API token")
def require_viewer(request: Request):
header = request.headers.get("authorization", "")
try:
scheme, encoded = header.split(" ", 1)
username, password = base64.b64decode(encoded).decode("utf-8").split(":", 1)
except Exception:
scheme = username = password = ""
if scheme.lower() != "basic" or not (hmac.compare_digest(username, VIEWER_USERNAME) and hmac.compare_digest(password, VIEWER_PASSWORD)):
raise HTTPException(status_code=401, detail="Authentication required", headers={"WWW-Authenticate": 'Basic realm="History Collector"'})
def save_batch(batch: VisitBatch) -> int:
received_at = datetime.now(timezone.utc).isoformat()
rows = [(batch.device_id, str(v.url), domain_from_url(str(v.url)), v.title,
v.visit_time.astimezone(timezone.utc).isoformat(), v.transition, received_at) for v in batch.visits]
with closing(connect()) as conn:
before = conn.total_changes
conn.executemany("""INSERT OR IGNORE INTO visits
(device_id, url, domain, title, visit_time, transition, received_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""", rows)
inserted = conn.total_changes - before
conn.commit()
return inserted
async def post_discord(batch: VisitBatch):
if not DISCORD_WEBHOOK_URL:
return
lines = [f"• {v.visit_time.astimezone(timezone.utc):%Y-%m-%d %H:%M UTC} — {v.title or '(brez naslova)'}\n <{v.url}>" for v in batch.visits]
chunks, current = [], f"**Zgodovina brskanja · {batch.device_id}**\n"
for line in lines:
candidate = current + line + "\n"
if len(candidate) > 1900 and current.strip():
chunks.append(current)
current = f"**Zgodovina brskanja · {batch.device_id} (nadaljevanje)**\n{line}\n"
else:
current = candidate
if current.strip(): chunks.append(current)
try:
async with httpx.AsyncClient(timeout=10) as client:
for content in chunks:
response = await client.post(DISCORD_WEBHOOK_URL, json={"content": content})
response.raise_for_status()
except Exception:
logger.exception("Discord relay failed")
@app.get("/healthz")
def healthz():
return {"ok": True}
@app.post("/v1/visits", status_code=status.HTTP_202_ACCEPTED)
async def receive_visits(batch: VisitBatch, authorization: Annotated[str | None, Header()] = None):
require_token(authorization)
try:
stored = save_batch(batch)
except Exception:
logger.exception(
"visit_batch_save_failed ingestion_timestamp=%s timezone=Europe/Ljubljana status=500 "
"reason=database_save_failed validated_visits=%d",
local_timestamp(),
len(batch.visits),
)
raise
ingestion_timestamp = local_timestamp()
logger.info(
"visit_batch_ingested ingestion_timestamp=%s timezone=Europe/Ljubljana device_id=%s accepted=%d stored=%d",
ingestion_timestamp,
batch.device_id,
len(batch.visits),
stored,
)
asyncio.create_task(post_discord(batch))
return {"accepted": len(batch.visits), "stored": stored}
def iso_from_local(value: str | None) -> str | None:
if not value:
return None
try:
return datetime.fromisoformat(value).replace(tzinfo=timezone.utc).isoformat()
except ValueError:
return None
def viewer_timestamp(value: str) -> str:
try:
normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
timestamp = datetime.fromisoformat(normalized)
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
return timestamp.astimezone(LOCAL_TIMEZONE).strftime("%m. %d. %H:%M")
except (AttributeError, TypeError, ValueError):
return str(value)
def viewer_page(rows, domains, devices, start, end, device, search, page, per_page, total_visits, total_pages):
opts = ['<option value="">Vse naprave</option>'] + [f'<option value="{escape(d, quote=True)}" {"selected" if d == device else ""}>{escape(d)}</option>' for d in devices]
visit_rows = "".join(f"<tr><td>{escape(viewer_timestamp(r['visit_time']))}</td><td>{escape(r['device_id'])}</td><td>{escape(r['domain'])}</td><td>{escape(r['title'])}</td><td><a href=\"{escape(r['url'], quote=True)}\" target=\"_blank\" rel=\"noreferrer\">{escape(r['url'])}</a></td></tr>" for r in rows) or '<tr><td colspan="5">Ni zadetkov.</td></tr>'
domain_rows = "".join(f"<tr><td>{escape(r['domain'])}</td><td>{r['visits']}</td><td>{escape(viewer_timestamp(r['last_seen']))}</td></tr>" for r in domains) or '<tr><td colspan="3">Ni zadetkov.</td></tr>'
def hidden_input(name, value):
return f'<input type="hidden" name="{name}" value="{escape(str(value), quote=True)}">'
def page_url(target_page):
values = [(name, value) for name, value in (("start", start), ("end", end), ("device", device), ("q", search)) if value is not None]
values.extend([("page", target_page), ("per_page", per_page)])
return "?" + urlencode(values)
result_start = (page - 1) * per_page + 1 if total_visits else 0
result_end = min(page * per_page, total_visits) if total_visits else 0
previous = f'<a href="{escape(page_url(page - 1), quote=True)}" rel="prev">Prejšnja</a>' if page > 1 else '<span aria-disabled="true">Prejšnja</span>'
next_page = f'<a href="{escape(page_url(page + 1), quote=True)}" rel="next">Naslednja</a>' if page < total_pages else '<span aria-disabled="true">Naslednja</span>'
pagination_controls = f'{previous}<span aria-current="page">Stran {page if total_pages else 0} od {total_pages}</span>{next_page}'
page_size_options = "".join(f'<option value="{size}" {"selected" if size == per_page else ""}>{size}</option>' for size in PAGE_SIZE_CHOICES)
filter_fields = "".join(hidden_input(name, value) for name, value in (("start", start), ("end", end), ("device", device), ("q", search)) if value is not None)
return f'''<!doctype html><html lang="sl"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Zgodovina brskanja</title><style>body{{font:14px system-ui,sans-serif;margin:2rem;background:#111827;color:#e5e7eb}}main{{margin:auto}}form,.box{{background:#1f2937;padding:1rem;border-radius:10px;margin:1rem 0}}input,select,button{{padding:.5rem;margin:.25rem;border-radius:5px;border:1px solid #4b5563}}input,select{{background:#111827;color:#e5e7eb}}button{{background:#2563eb;color:white}}table{{border-collapse:collapse;width:100%;background:#fff;color:#111827}}th,td{{padding:.55rem;border:1px solid #d1d5db;text-align:left;vertical-align:top}}th{{background:#e5e7eb}}a{{color:#075985;word-break:break-all}}.pagination{{display:flex;align-items:center;gap:1rem;justify-content:center;flex-wrap:wrap}}.pagination a{{display:inline-block;padding:.5rem;border:1px solid #4b5563;border-radius:5px;background:#2563eb;color:white;text-decoration:none}}.pagination span[aria-disabled="true"]{{display:inline-block;padding:.5rem;border:1px solid #4b5563;border-radius:5px;background:#374151;color:#9ca3af}}.pagination-toolbar{{display:flex;align-items:center;gap:1rem;flex-wrap:wrap}}.pagination-toolbar form{{flex:1 1 20rem;min-width:0;margin:0}}.pagination-toolbar .pagination{{flex:1 1 20rem}}.grid{{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,400px);gap:1rem}}.unique-domains{{width:100%;max-width:400px;box-sizing:border-box;min-width:0;overflow-wrap:anywhere}}@media(max-width:900px){{.grid{{grid-template-columns:1fr}}}}</style><main><h1>Zgodovina brskanja</h1><form method="get"><label>Od <input type="datetime-local" name="start" value="{escape(start or '', quote=True)}"></label><label>Do <input type="datetime-local" name="end" value="{escape(end or '', quote=True)}"></label><label>Naprava <select name="device">{''.join(opts)}</select></label><label>Išči <input name="q" value="{escape(search or '', quote=True)}" placeholder="domena, naslov ali URL"></label>{hidden_input("per_page", per_page)}<button>Filtriraj</button></form><div class="grid"><section class="box"><h2>Obiski ({result_start}–{result_end} od {total_visits})</h2><div class="pagination-toolbar"><form method="get"><label for="per-page">Obiskov na stran</label><select id="per-page" name="per_page">{page_size_options}</select>{filter_fields}<button type="submit">Uporabi</button></form><nav class="pagination" aria-label="Strani obiskov">{pagination_controls}</nav></div><table><thead><tr><th>Čas (Europe/Ljubljana)</th><th>Naprava</th><th>Domena</th><th>Naslov</th><th>URL</th></tr></thead><tbody>{visit_rows}</tbody></table><nav class="pagination" style="margin-top:1rem" aria-label="Spodnja navigacija strani obiskov">{pagination_controls}</nav></section><section class="box unique-domains"><h2>Unikatne domene</h2><table><thead><tr><th>Domena</th><th>Obiski</th><th>Zadnji obisk</th></tr></thead><tbody>{domain_rows}</tbody></table></section></div></main></html>'''
@app.get("/", response_class=HTMLResponse)
def viewer(request: Request, start: str | None = Query(None), end: str | None = Query(None), device: str | None = Query(None), q: str | None = Query(None), page: int = Query(1, ge=1), per_page: int = Query(DEFAULT_PAGE_SIZE)):
require_viewer(request)
if per_page not in PAGE_SIZE_CHOICES:
raise HTTPException(status_code=422, detail="per_page must be one of 25, 50, 100, or 250")
filters, params = [], []
if value := iso_from_local(start): filters.append("visit_time >= ?"); params.append(value)
if value := iso_from_local(end): filters.append("visit_time <= ?"); params.append(value)
if device: filters.append("device_id = ?"); params.append(device)
if q: filters.append("(domain LIKE ? OR title LIKE ? OR url LIKE ?)"); params.extend([f"%{q}%"] * 3)
where = (" WHERE " + " AND ".join(filters)) if filters else ""
with closing(connect()) as conn:
total_visits = conn.execute(f"SELECT COUNT(*) FROM visits{where}", params).fetchone()[0]
total_pages = (total_visits + per_page - 1) // per_page if total_visits else 0
page = min(page, total_pages) if total_pages else 1
offset = (page - 1) * per_page
rows = conn.execute(f"SELECT visit_time, device_id, domain, title, url FROM visits{where} ORDER BY visit_time DESC, id DESC LIMIT ? OFFSET ?", params + [per_page, offset]).fetchall()
domains = conn.execute(f"SELECT domain, COUNT(*) visits, MAX(visit_time) last_seen FROM visits{where} GROUP BY domain ORDER BY visits DESC, last_seen DESC LIMIT 200", params).fetchall()
devices = [r[0] for r in conn.execute("SELECT DISTINCT device_id FROM visits ORDER BY device_id")]
return viewer_page(rows, domains, devices, start, end, device, q, page, per_page, total_visits, total_pages)