docs: session close 2026-10-22 — Docker, metrics, auth-log, Task 6 (VTODO-create). feat: webui/radicale.py create/toggle_task, CalDAV REPORT, api endpoints. fix: login cookie (HTMX, method=post, stale cleanup). fix: SQLite WAL read-only mount.

This commit is contained in:
2026-10-23 18:49:13 +00:00
parent b34993402f
commit d52cb89098
47 changed files with 3992 additions and 5 deletions
+386
View File
@@ -0,0 +1,386 @@
"""
app.py — FastAPI приложение веб-интерфейса Email Assistant.
Запуск (dev):
.venv/bin/uvicorn webui.app:app --host 127.0.0.1 --port 8085
Маршруты:
GET /login, POST /login — вход по паролю (WEBUI_PASSWORD из .env)
GET /logout — выход
GET / — главная (поиск + карточки)
GET /emails — список писем (3 колонки)
GET /emails/<path> — деталка письма (htmx-фрагмент или страница)
GET /attachments/<path> — скачивание вложения
GET /search — поиск (htmx-фрагмент результатов)
POST /api/ai/ask — вопрос к локальной модели
"""
from __future__ import annotations
import os
import secrets
import sys
from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI, Form, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from . import ai, db, metrics, radicale
ROOT = Path(__file__).parent
EMAIL_ROOT = db.EMAIL_ROOT
# --- настройки ---
def _load_env() -> None:
"""Прочитать .env проекта (WEBUI_PASSWORD) без python-dotenv-зависимости."""
env_file = ROOT.parent / ".env"
if not env_file.exists():
return
for line in env_file.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
k, v = line.split("=", 1)
os.environ.setdefault(k.strip(), v.strip())
_load_env()
WEBUI_PASSWORD = os.environ.get("WEBUI_PASSWORD", "")
# --- лог авторизации (webui_auth.log, рядом с imap_client.log) ---
AUTH_LOG_PATH = Path("/opt/hermes/email/logs/webui_auth.log")
# при read-only volume mkdir может не пройти — не ошибка, запишет в fallback
try:
AUTH_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
except OSError:
pass
if not AUTH_LOG_PATH.parent.is_dir() or not os.access(AUTH_LOG_PATH.parent, os.W_OK):
AUTH_LOG_PATH = None # в stdout через logging
def _log_auth(event: str, request: Request, note: str = "") -> None:
"""JSON-строка в лог авторизации (stdout, видно в docker logs)."""
import json
import datetime
import logging
log = logging.getLogger("webui.auth")
rec = {
"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"),
"event": event,
"remote_addr": request.client.host if request.client else "?",
"user_agent": request.headers.get("user-agent", ""),
"note": note,
}
msg = json.dumps(rec, ensure_ascii=False)
if AUTH_LOG_PATH:
try:
with AUTH_LOG_PATH.open("a", encoding="utf-8") as f:
f.write(msg + "\n")
except OSError:
pass
log.info("AUTH %s %s", rec["ts"], msg)
# --- сессии (в памяти процесса) ---
_sessions: set[str] = set()
app = FastAPI(title="Email Assistant WebUI")
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")
templates = Jinja2Templates(directory=ROOT / "templates")
templates.env.globals["TAG_COLORS"] = db.TAG_COLORS
templates.env.globals["current_path"] = lambda req: req.url.path
templates.env.filters["filesize"] = db._hr_size
# --- auth ---
def is_htmx(request: Request) -> bool:
return request.headers.get("HX-Request") == "true"
def _auth_cookie(request: Request) -> str | None:
return request.cookies.get("webui_auth")
def require_auth(request: Request):
token = _auth_cookie(request)
if not token or token not in _sessions:
raise HTTPException(status_code=401, detail="Not authenticated")
return None
AuthDep = Annotated[None, Depends(require_auth)]
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
"""Глобальная проверка авторизации: всё, кроме /login и /static, требует cookie."""
path = request.url.path
if path.startswith("/login") or path.startswith("/static") or path == "/metrics":
response = await call_next(request)
metrics.set_sessions(len(_sessions))
return response
token = _auth_cookie(request)
if not token or token not in _sessions:
metrics.set_sessions(len(_sessions))
_log_auth("auth_denied", request, note=f"token_exists={bool(token)} sessions_cnt={len(_sessions)}")
# удалить невалидную куку навсегда
resp_denied = RedirectResponse(url="/login", status_code=303)
if token:
resp_denied.delete_cookie("webui_auth", path="/")
if is_htmx(request) or path.startswith("/api/"):
return JSONResponse({"detail": "Not authenticated"}, status_code=401)
return resp_denied
response = await call_next(request)
metrics.set_sessions(len(_sessions))
if path not in ("/metrics", "/favicon.ico") and not path.startswith("/static"):
metrics.observe_request(request.method, path, response.status_code)
return response
# --- helpers ---
def render(request: Request, template: str, ctx: dict | None = None):
c = {"request": request, **(ctx or {})}
return templates.TemplateResponse(request, template, c)
def fragment(request: Request, template: str, ctx: dict | None = None):
c = {"request": request, **(ctx or {})}
return templates.TemplateResponse(request, template, c)
# --- страницы ---
@app.get("/login", response_class=HTMLResponse)
def login_page(request: Request):
tk = _auth_cookie(request)
if tk and tk in _sessions and tk:
return RedirectResponse(url="/", status_code=303)
# если кука невалидна — удалить
if tk and tk not in _sessions:
resp = render(request, "login.html", {"error": None})
resp.delete_cookie("webui_auth", path="/")
return resp
return render(request, "login.html", {"error": None})
@app.post("/login")
def login_post(request: Request, password: str = Form(...)):
import secrets as _secrets
ok = WEBUI_PASSWORD and _secrets.compare_digest(password, WEBUI_PASSWORD)
if not ok:
_log_auth("login_failed", request, note="wrong password")
if is_htmx(request):
return fragment(request, "partials/login_frag.html", {"error": "Неверный пароль"})
return render(request, "login.html", {"error": "Неверный пароль"})
token = secrets.token_urlsafe(32)
_sessions.add(token)
secure = request.url.scheme == "https" or request.headers.get("x-forwarded-proto", "") == "https"
_log_auth("login_ok", request, note=f"token={token[:8]}...")
if is_htmx(request):
resp = fragment(request, "partials/login_ok.html")
resp.headers["HX-Redirect"] = "/"
else:
resp = RedirectResponse(url="/", status_code=303)
resp.set_cookie("webui_auth", token, httponly=True, samesite="lax",
secure=secure, max_age=60 * 60 * 24 * 30)
return resp
@app.get("/logout")
def logout(request: Request):
token = _auth_cookie(request)
if token:
_sessions.discard(token)
resp = RedirectResponse(url="/login", status_code=303)
resp.delete_cookie("webui_auth")
return resp
@app.get("/", response_class=HTMLResponse)
def index(request: Request, _: AuthDep):
# карточки
tasks = radicale.get_tasks()
events = radicale.get_events()
# письма к исполнению: classification task/urgent из кэша → последние 3
todo_emails: list[dict] = []
for rel_path, cls in db.classified_paths_cache():
if cls in ("task", "urgent") and rel_path.startswith("INBOX/"):
em = db.get_email(rel_path)
if em:
em["classification"] = cls
todo_emails.append(em)
if len(todo_emails) >= 5:
break
return render(request, "index.html", {
"tasks": tasks, "events": events, "todo_emails": todo_emails,
"stat_emails": _count_emails(), "page": "home",
})
@app.get("/emails", response_class=HTMLResponse)
def emails(request: Request, _: AuthDep, folder: str = "INBOX", path: str | None = None,
q: str = "", limit: int = 50):
import time
t0 = time.monotonic()
folders = db.list_folders()
if q.strip():
rows = db.search(q, folder=folder, limit=limit)
if not rows:
rows = db.search(q, folder=folder, limit=limit, in_body=True)
is_search = True
else:
rows = db.list_folder(folder, limit=limit)
is_search = False
# обогащаем классификацией (тэги) из кэша
cls_map = {p: c for p, c in db.classified_paths_cache()}
for r in rows:
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
if q.strip():
metrics.observe_search(time.monotonic() - t0)
current = db.get_email(path) if path else None
if current is None and rows:
current = db.get_email(rows[0]["path"])
path = rows[0]["path"] if rows else None
ctx = {
"folders": folders, "folder": folder, "rows": rows, "q": q,
"current": current, "current_path": path, "is_search": is_search,
"page": "emails",
}
if is_htmx(request):
return fragment(request, "partials/emails_content.html", ctx)
return render(request, "emails.html", ctx)
@app.get("/emails/{relpath:path}", response_class=HTMLResponse)
def email_detail(request: Request, relpath: str, _: AuthDep):
"""Деталка письма как htmx-фрагмент (для превью-панели)."""
em = db.get_email(relpath)
if em is None:
raise HTTPException(status_code=404)
if is_htmx(request):
ctx = {"current": em, "current_path": relpath}
return fragment(request, "partials/email_detail.html", ctx)
# полная страница (прямой переход)
folders = db.list_folders()
# ищем папку письма
folder = em["meta"].get("folder") or ("INBOX" if relpath.startswith("INBOX/") else "")
rows = db.list_folder(folder, limit=100)
cls_map = {p: c for p, c in db.classified_paths_cache()}
for r in rows:
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
return render(request, "emails.html", {
"folders": folders, "folder": folder, "rows": rows, "q": "",
"current": em, "current_path": relpath, "is_search": False,
"page": "emails",
})
@app.get("/attachments/{relpath:path}")
def attachment(relpath: str, _: AuthDep):
"""Скачивание вложения: relpath = INBOX/2026/10/15499/attachments/file.pdf."""
fpath = (EMAIL_ROOT / relpath).resolve()
if not str(fpath).startswith(str(EMAIL_ROOT.resolve())) or not fpath.is_file():
raise HTTPException(status_code=404)
return FileResponse(fpath, filename=fpath.name)
@app.get("/search")
def search_page(request: Request, _: AuthDep, q: str = "", folder: str = "",
tag: str = "", df: str = "", dt: str = "", att: bool = False,
body: bool = False, limit: int = 50):
rows = db.search(q, folder=folder or None, tag=tag or None,
date_from=df or None, date_to=dt or None,
only_attachments=att, in_body=body, limit=limit)
body_fallback = False
t0 = __import__("time").monotonic()
if q.strip() and not rows and not body:
# FTS не нашёл (индексируется только превью 500 симв.) — ищем в теле
rows = db.search(q, folder=folder or None, tag=tag or None,
date_from=df or None, date_to=dt or None,
only_attachments=att, in_body=True, limit=limit)
body_fallback = bool(rows)
metrics.observe_search(__import__("time").monotonic() - t0)
cls_map = {p: c for p, c in db.classified_paths_cache()}
for r in rows:
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
ctx = {"rows": rows, "q": q, "folder": folder, "tag": tag,
"df": df, "dt": dt, "att": att, "body": body,
"body_fallback": body_fallback, "page": "search"}
if is_htmx(request):
return fragment(request, "partials/search_results.html", ctx)
ctx["folders"] = db.list_folders()
return render(request, "search.html", ctx)
# --- ИИ-панель ---
@app.post("/api/ai/ask")
async def ai_ask(request: Request, _: AuthDep):
import json
import time
body = json.loads(await request.body())
q = (body.get("question") or "").strip()
ctx = (body.get("context") or "").strip()
if not q:
raise HTTPException(status_code=400, detail="question required")
t0 = time.monotonic()
res = ai.ask(q, ctx)
metrics.observe_ai(time.monotonic() - t0)
if res.get("error"):
return {"text": "", "error": res["error"]}
return {"text": ai.linkify(res["text"])}
# --- Задачи (Radicale VTODO) ---
@app.post("/api/tasks/create")
async def task_create(request: Request, _: AuthDep):
"""Создать VTODO из письма (или произвольного текста)."""
import json
raw = await request.body()
try:
data = json.loads(raw)
except Exception:
return {"error": "invalid JSON"}
summary = (data.get("subject") or data.get("summary") or "Без темы")[:120]
description = data.get("body", "")[:500]
sender = data.get("from", "")
if sender:
description = f"От: {sender}\n{description}"
due_str = data.get("due")
res = radicale.create_task(summary, description.strip(), due_str)
if res.get("error"):
return {"error": res["error"]}
return {"ok": True, "uid": res.get("uid", ""), "etag": res.get("etag", "")}
@app.post("/api/task/{uid}/toggle")
def task_toggle(uid: str, request: Request, _: AuthDep):
"""Переключить COMPLETED ↔ NEEDS-ACTION."""
import httpx
res = radicale.toggle_task(uid)
if res.get("error"):
return {"error": res["error"]}
return {"ok": True, "status": res["status"]}
# --- метрики (Prometheus) ---
@app.get("/metrics")
def metrics_endpoint():
body, ctype = metrics.render_metrics()
from fastapi.responses import Response
return Response(content=body, media_type=ctype)
# --- misc ---
def _count_emails() -> int:
con = db.connect()
try:
row = con.execute("SELECT COUNT(*) AS c FROM emails").fetchone()
return row["c"] if row else 0
finally:
con.close()
if not WEBUI_PASSWORD:
print("WARNING: WEBUI_PASSWORD не задан в .env — вход по паролю отключён "
"(разрешается любой пароль). Добавьте WEBUI_PASSWORD=... в .env",
file=sys.stderr)