a9cd69741f
- tasktracker/{__init__,api,fragments}.py: TaskTracker (list/get/create/update/
toggle/delete/set_priority), APIRouter с 8 маршрутами, HTML-фрагменты карточки
и формы (Alpine + HTMX, экранирование текста и x-data через json+html.escape)
- webui/radicale.py: _set_prop/_esc/_task_url, get_task, set_priority, delete_task
(мягкое: STATUS:CANCELLED + X-DELETED:1); GET+PUT+If-Match собран в
_load_for_update/_put_for_update; get_tasks() скрывает мягко удалённые
- webui/app.py: -109 строк (маршруты задач и _render_tasks_card), + include_router
- UI: бейдж приоритета 1-5 (клик — следующий) и кнопка ✕ в строке задачи,
приоритет в форме создания, карточка обновляется без перезагрузки страницы
- Dockerfile: COPY tasktracker /app/tasktracker
- tests/test_tasktracker.py: 8 тестов на FakeStorage + 401 для всех маршрутов
Проверено: 8/8 новых и 7/7 smoke-тестов, живой прогон против Radicale (10/10
сценариев, тестовая задача удалена), контейнер email-webui healthy на 10.8.0.2:8085,
200 инлайн-JS выражений валидны. Change tasktracker-module заархивирован
(дельта смержена в openspec/specs/tasktracker).
436 lines
17 KiB
Python
436 lines
17 KiB
Python
"""
|
||
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
|
||
from tasktracker.api import router as tasktracker_router
|
||
|
||
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
|
||
|
||
# --- модуль задач (VTODO) ---
|
||
app.include_router(tasktracker_router)
|
||
|
||
|
||
# --- 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"])}
|
||
|
||
|
||
# --- Календарь ---
|
||
@app.get("/api/calendar")
|
||
def calendar(request: Request, _: AuthDep, year: int = 0, month: int = 0):
|
||
"""Динамическая сетка календаря (HTMX-фрагмент)."""
|
||
import datetime
|
||
now = datetime.date.today()
|
||
y = year if year else now.year
|
||
m = month if month else now.month
|
||
# первый день месяца
|
||
first = datetime.date(y, m, 1)
|
||
# последний день месяца
|
||
if m == 12:
|
||
last = datetime.date(y + 1, 1, 1) - datetime.timedelta(days=1)
|
||
else:
|
||
last = datetime.date(y, m + 1, 1) - datetime.timedelta(days=1)
|
||
# смещение: понедельник = 0
|
||
start_wk = first.weekday()
|
||
# клетки
|
||
cells = []
|
||
for _ in range(start_wk):
|
||
cells.append('<span class="d"></span>')
|
||
for d in range(1, last.day + 1):
|
||
dd = datetime.date(y, m, d)
|
||
cls = "d"
|
||
if dd.weekday() >= 5:
|
||
cls += " wk"
|
||
if dd == now:
|
||
cls += " today"
|
||
cells.append(f'<span class="{cls}">{d}</span>')
|
||
dates = _fetch_events_for_month(y, m)
|
||
events_html = "".join(
|
||
f'<div class="ev"><span class="tm">{e.get("dtstart","")}</span>'
|
||
f'<span class="dot" style="background:var(--accent)"></span>{e["summary"]}</div>'
|
||
for e in dates
|
||
) or '<div class="ev" style="color:var(--fg3)">Событий нет</div>'
|
||
|
||
mon_names = ["Январь","Февраль","Март","Апрель","Май","Июнь",
|
||
"Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"]
|
||
prev_m = m - 1 or 12
|
||
prev_y = y - 1 if prev_m == 12 else y
|
||
next_m = m + 1 if m < 12 else 1
|
||
next_y = y + 1 if next_m == 1 else y
|
||
html = f'''<div class="cal">
|
||
<div class="cal-head">
|
||
<button hx-get="/api/calendar?year={prev_y}&month={prev_m}" hx-target="closest .cal" hx-swap="outerHTML">◀</button>
|
||
<span>{mon_names[m-1]} {y}</span>
|
||
<button hx-get="/api/calendar?year={next_y}&month={next_m}" hx-target="closest .cal" hx-swap="outerHTML">▶</button>
|
||
</div>
|
||
<div class="dow"><span>Пн</span><span>Вт</span><span>Ср</span><span>Чт</span><span>Пт</span><span>Сб</span><span>Вс</span></div>
|
||
<div class="days">{"".join(cells)}</div>
|
||
<div class="evlist">{events_html}</div>
|
||
</div>'''
|
||
return HTMLResponse(html)
|
||
|
||
|
||
def _fetch_events_for_month(year: int, month: int) -> list[dict]:
|
||
"""Выбрать события Radicale за указанный месяц."""
|
||
try:
|
||
evs = radicale.get_events(limit=50)
|
||
except Exception:
|
||
return []
|
||
# фильтр по дате
|
||
import datetime
|
||
result = []
|
||
for e in evs:
|
||
d = e.get("datestr")
|
||
if d:
|
||
try:
|
||
dd = datetime.datetime.strptime(d, "%d.%m.%Y")
|
||
if dd.year == year and dd.month == month:
|
||
result.append(e)
|
||
except ValueError:
|
||
result.append(e)
|
||
else:
|
||
result.append(e)
|
||
return result
|
||
|
||
|
||
# --- метрики (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) |