mirror of
https://gitverse.ru/kpa39l/email-assistant.git
synced 2026-11-27 06:30:08 +00:00
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:
+355
@@ -0,0 +1,355 @@
|
||||
"""
|
||||
db.py — read-only доступ к индексу писем (SQLite FTS5).
|
||||
|
||||
Источник: /opt/hermes/email/mail_index.db (схема — таблицы emails + email_fts).
|
||||
Никаких записей: только mode=ro + PRAGMA query_only=ON.
|
||||
|
||||
Письма на диске: EMAIL_ROOT/<path>/email.md (+ attachments/ рядом).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
EMAIL_ROOT = Path("/opt/hermes/email")
|
||||
EMAIL_ROOT_REAL = EMAIL_ROOT.resolve() # /opt/hermes/email → /mnt/raid1/email
|
||||
MAIL_INDEX = EMAIL_ROOT / "mail_index.db"
|
||||
|
||||
# Тэги классификации, которые могут быть в frontmatter email.md
|
||||
TAG_COLORS = {
|
||||
"urgent": "u",
|
||||
"task": "t",
|
||||
"meeting": "m",
|
||||
"info": "i",
|
||||
}
|
||||
|
||||
|
||||
def connect() -> sqlite3.Connection:
|
||||
"""Открыть mail_index.db — read-only через PRAGMA query_only. WAL разрешён."""
|
||||
con = sqlite3.connect(f"file:{MAIL_INDEX}?mode=ro", uri=True)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA query_only=ON")
|
||||
return con
|
||||
|
||||
|
||||
def _escape_fts(query: str) -> str:
|
||||
"""Экранировать пользовательский ввод для FTS5 MATCH.
|
||||
|
||||
unicode61 tokenizer: кавычки разбивают фразы, спецсимволы — операторы.
|
||||
Для простоты: оборачиваем каждый токен в двойные кавычки (безопасно для
|
||||
MATCH, точное совпадение подстроки через префикс-оператор *).
|
||||
"""
|
||||
# убираем управляющие символы FTS5, оставляем буквы/цифры/кириллицу
|
||||
tokens = re.findall(r"[\wа-яёА-ЯЁ«»-]+", query, flags=re.UNICODE)
|
||||
if not tokens:
|
||||
return '""'
|
||||
return " AND ".join(f'"{t}"*' if len(t) > 2 else f'"{t}"' for t in tokens)
|
||||
|
||||
|
||||
def _has_attachments(rel_path: str) -> bool:
|
||||
"""Есть ли у письма каталог attachments/ с файлами (по пути от EMAIL_ROOT)."""
|
||||
d = EMAIL_ROOT_REAL / rel_path
|
||||
att = d.parent / "attachments"
|
||||
try:
|
||||
return att.is_dir() and any(att.iterdir())
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _body_scan(query: str, limit: int = 50) -> list[str]:
|
||||
"""Поиск по ПОЛНОМУ телу email.md (FTS индексирует только превью 500 симв.).
|
||||
Возвращает относительные пути писем, где встречаются все токены запроса."""
|
||||
import re as _re
|
||||
tokens = [t.lower() for t in _re.findall(r"[\wа-яёА-ЯЁ]+", query, flags=_re.U)]
|
||||
if not tokens:
|
||||
return []
|
||||
hits: list[str] = []
|
||||
for root, _dirs, files in os.walk(EMAIL_ROOT_REAL):
|
||||
if "email.md" not in files:
|
||||
continue
|
||||
fp = Path(root) / "email.md"
|
||||
try:
|
||||
text = fp.read_text(encoding="utf-8", errors="replace").lower()
|
||||
except OSError:
|
||||
continue
|
||||
if all(t in text for t in tokens):
|
||||
hits.append(fp.relative_to(EMAIL_ROOT_REAL).as_posix())
|
||||
if len(hits) >= limit * 5:
|
||||
break
|
||||
return hits
|
||||
|
||||
|
||||
def search(query: str, *, folder: str | None = None, tag: str | None = None,
|
||||
date_from: str | None = None, date_to: str | None = None,
|
||||
only_attachments: bool = False, in_body: bool = False,
|
||||
limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
|
||||
"""Полнотекстовый поиск с фильтрами. Возвращает список писем (dict).
|
||||
|
||||
in_body=True — поиск по полному телу email.md (медленнее, зато находит
|
||||
упоминания глубже первых 500 символов, которые видит FTS-индекс).
|
||||
"""
|
||||
con = connect()
|
||||
try:
|
||||
where: list[str] = []
|
||||
params: list[Any] = []
|
||||
|
||||
body_paths: list[str] = []
|
||||
if query.strip() and not in_body:
|
||||
where.append("e.rowid IN (SELECT rowid FROM email_fts WHERE email_fts MATCH ?)")
|
||||
params.append(_escape_fts(query))
|
||||
if query.strip() and in_body:
|
||||
body_paths = _body_scan(query, limit=limit)
|
||||
if not body_paths:
|
||||
return []
|
||||
ph = ",".join("?" * len(body_paths))
|
||||
where.append(f"e.path IN ({ph})")
|
||||
params.extend(body_paths)
|
||||
|
||||
if folder:
|
||||
where.append("e.folder = ?")
|
||||
params.append(folder)
|
||||
if tag:
|
||||
tag_paths = [p for p, c in classified_paths_cache() if c == tag]
|
||||
if not tag_paths:
|
||||
return []
|
||||
ph = ",".join("?" * min(len(tag_paths), 900))
|
||||
where.append(f"(e.path IN ({ph}))")
|
||||
params.extend(tag_paths[:900])
|
||||
if date_from:
|
||||
where.append("date(substr(e.date,1,10)) >= date(?)")
|
||||
params.append(date_from)
|
||||
if date_to:
|
||||
where.append("date(substr(e.date,1,10)) <= date(?)")
|
||||
params.append(date_to)
|
||||
|
||||
sql = f"""
|
||||
SELECT e.path, e.uid, e.folder, e.date, e.from_addr, e.to_addrs,
|
||||
e.subject, e.body_preview
|
||||
FROM emails e
|
||||
{'WHERE ' + ' AND '.join(where) if where else ''}
|
||||
ORDER BY e.date DESC
|
||||
LIMIT ? OFFSET ?
|
||||
"""
|
||||
params += [limit if not only_attachments else limit * 4, offset]
|
||||
rows = con.execute(sql, params).fetchall()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
out: list[dict[str, Any]] = []
|
||||
found: set[str] = set()
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
d["has_attachments"] = _has_attachments(d["path"])
|
||||
if only_attachments and not d["has_attachments"]:
|
||||
continue
|
||||
out.append(d)
|
||||
found.add(d["path"])
|
||||
if len(out) >= limit:
|
||||
break
|
||||
|
||||
# in_body: часть писем может отсутствовать в индексе (FTS отстаёт) —
|
||||
# добираем их из файлов на диске.
|
||||
if in_body:
|
||||
for relp in body_paths:
|
||||
if relp in found:
|
||||
continue
|
||||
em = get_email(relp)
|
||||
if not em:
|
||||
continue
|
||||
meta = em["meta"]
|
||||
d = {
|
||||
"path": relp,
|
||||
"uid": None,
|
||||
"folder": meta.get("folder") or relp.split("/")[0],
|
||||
"date": meta.get("date") or "",
|
||||
"from_addr": meta.get("from") or "",
|
||||
"to_addrs": meta.get("to") or "",
|
||||
"subject": meta.get("subject") or "",
|
||||
"body_preview": em["body"][:500],
|
||||
"has_attachments": bool(em["attachments"]),
|
||||
}
|
||||
if folder and d["folder"] != folder:
|
||||
continue
|
||||
if only_attachments and not d["has_attachments"]:
|
||||
continue
|
||||
out.append(d)
|
||||
found.add(relp)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def list_folder(folder: str, limit: int = 100, offset: int = 0) -> list[dict[str, Any]]:
|
||||
"""Последние письма папки. Папка — точное совпадение (INBOX, INBOX/!Scan...)."""
|
||||
con = connect()
|
||||
try:
|
||||
rows = con.execute(
|
||||
"""SELECT path, uid, folder, date, from_addr, to_addrs, subject, body_preview
|
||||
FROM emails WHERE folder = ? ORDER BY date DESC LIMIT ? OFFSET ?""",
|
||||
(folder, limit, offset)).fetchall()
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
d["has_attachments"] = _has_attachments(d["path"])
|
||||
out.append(d)
|
||||
return out
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def list_folders() -> list[dict[str, Any]]:
|
||||
"""Все папки с количеством писем. INBOX-подпапки — отдельными строками."""
|
||||
con = connect()
|
||||
try:
|
||||
rows = con.execute(
|
||||
"SELECT folder, COUNT(*) AS cnt FROM emails GROUP BY folder "
|
||||
"ORDER BY folder").fetchall()
|
||||
folders = [dict(r) for r in rows]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
tree: dict[str, dict] = {}
|
||||
for f in folders:
|
||||
parts = f["folder"].split("/")
|
||||
node = tree
|
||||
for i, p in enumerate(parts):
|
||||
if p not in node:
|
||||
node[p] = {
|
||||
"name": p,
|
||||
"path": "/".join(parts[: i + 1]),
|
||||
"children": {},
|
||||
"cnt": 0,
|
||||
}
|
||||
if i == len(parts) - 1:
|
||||
node[p]["cnt"] = f["cnt"]
|
||||
node = node[p]["children"]
|
||||
return _flatten_tree(tree)
|
||||
|
||||
|
||||
def _flatten_tree(tree: dict[str, dict], depth: int = 0) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for key in sorted(tree):
|
||||
node = tree[key]
|
||||
out.append({
|
||||
"name": node["name"], "path": node["path"],
|
||||
"cnt": node["cnt"], "depth": depth,
|
||||
"has_children": bool(node["children"]),
|
||||
})
|
||||
out.extend(_flatten_tree(node["children"], depth + 1))
|
||||
return out
|
||||
|
||||
|
||||
def get_email(path: str) -> dict[str, Any] | None:
|
||||
"""Письмо по относительному пути + полный текст из email.md на диске."""
|
||||
rel = path.lstrip("/")
|
||||
# защита от path traversal
|
||||
if not rel.endswith("email.md"):
|
||||
rel = rel.rstrip("/") + "/email.md"
|
||||
fpath = (EMAIL_ROOT / rel).resolve()
|
||||
if not str(fpath).startswith(str(EMAIL_ROOT_REAL)):
|
||||
return None
|
||||
if not fpath.is_file():
|
||||
return None
|
||||
text = fpath.read_text(encoding="utf-8", errors="replace")
|
||||
meta, body = _split_frontmatter(text)
|
||||
attachments = list_attachments(str(fpath.parent))
|
||||
return {
|
||||
"path": fpath.relative_to(EMAIL_ROOT_REAL).as_posix(),
|
||||
"dir": str(fpath.parent),
|
||||
"meta": meta,
|
||||
"body": body,
|
||||
"attachments": attachments,
|
||||
"tags": [t for t in (meta.get("classification") or "").split() if t],
|
||||
}
|
||||
|
||||
|
||||
def list_attachments(email_dir: str) -> list[dict[str, str]]:
|
||||
att_dir = Path(email_dir) / "attachments"
|
||||
if not att_dir.is_dir():
|
||||
return []
|
||||
out = []
|
||||
for f in sorted(att_dir.iterdir()):
|
||||
if f.is_file():
|
||||
out.append({
|
||||
"name": f.name,
|
||||
"size": f.stat().st_size,
|
||||
"size_hr": _hr_size(f.stat().st_size),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _hr_size(n: int | float) -> str:
|
||||
for unit in ("B", "KB", "MB", "GB"):
|
||||
if n < 1024:
|
||||
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
|
||||
n = n / 1024
|
||||
return f"{n:.1f} TB"
|
||||
|
||||
|
||||
_FM_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n?", re.S | re.M)
|
||||
|
||||
|
||||
def _split_frontmatter(text: str) -> tuple[dict[str, str], str]:
|
||||
m = _FM_RE.match(text)
|
||||
if not m:
|
||||
return {}, text
|
||||
meta: dict[str, str] = {}
|
||||
for line in m.group(1).splitlines():
|
||||
if ":" in line:
|
||||
k, v = line.split(":", 1)
|
||||
meta[k.strip().lower()] = v.strip().strip("'\"")
|
||||
return meta, text[m.end():]
|
||||
|
||||
|
||||
# --- классификация (frontmatter) — кэш-слой для тэгов ---
|
||||
_CLASSIFIED_CACHE: list[tuple[str, str]] | None = None
|
||||
_CLASSIFIED_TS: float = 0.0
|
||||
_CLASSIFIED_TTL = 60.0 # секунд
|
||||
|
||||
|
||||
def classified_paths_cache() -> list[tuple[str, str]]:
|
||||
"""Пути + classification из frontmatter. Кэш на 60с — для карточек
|
||||
«к исполнению» и фильтра по тэгу. При первом вызове проходит по годам
|
||||
INBOX и Отправленные; при большом архиве это ~секунды, далее из кэша."""
|
||||
global _CLASSIFIED_CACHE, _CLASSIFIED_TS
|
||||
import time
|
||||
now = time.monotonic()
|
||||
if _CLASSIFIED_CACHE is None or now - _CLASSIFIED_TS > _CLASSIFIED_TTL:
|
||||
_CLASSIFIED_CACHE = _scan_classified()
|
||||
_CLASSIFIED_TS = now
|
||||
return _CLASSIFIED_CACHE
|
||||
|
||||
|
||||
def _scan_classified() -> list[tuple[str, str]]:
|
||||
"""Сканирует frontmatter писем за последний год (INBOX, Отправленные)."""
|
||||
out: list[tuple[str, str]] = []
|
||||
for root in (EMAIL_ROOT / "INBOX", EMAIL_ROOT / "Отправленные"):
|
||||
if not root.is_dir():
|
||||
continue
|
||||
# глубина: INBOX/YYYY/MM/UID/email.md — достаточно 4 уровня
|
||||
for year in root.iterdir():
|
||||
if not year.is_dir():
|
||||
continue
|
||||
for month in year.iterdir():
|
||||
if not month.is_dir():
|
||||
continue
|
||||
for uid_dir in month.iterdir():
|
||||
em = uid_dir / "email.md"
|
||||
if not em.is_file():
|
||||
continue
|
||||
text = em.read_text(encoding="utf-8", errors="replace")[:4000]
|
||||
m = _FM_RE.match(text)
|
||||
if not m:
|
||||
continue
|
||||
cls = ""
|
||||
for line in m.group(1).splitlines():
|
||||
if line.lower().startswith("classification:"):
|
||||
cls = line.split(":", 1)[1].strip().strip("'\"")
|
||||
break
|
||||
if cls:
|
||||
rel = em.relative_to(EMAIL_ROOT).as_posix()
|
||||
out.append((rel, cls))
|
||||
return out
|
||||
Reference in New Issue
Block a user