Files
email-assistant/webui/entities.py
T
Hermes Agent 8ca4c4a7c8 feat(entities): метки классификации в детализации письма + автосозданные событие/задача
- db.split_tags(): метки делятся по запятой и пробелу (был один чип «meeting,task»)
- webui/entities.py: связь письмо↔сущность в frontmatter (entity_<kind>_uid/state),
  ensure/disable/enable/create_task_control; disable event = DELETE VEVENT,
  disable task = STATUS:CANCELLED+X-DELETED; task-control только по кнопке
- блок «Отметки» + «Автоматически создано» в детализации, роут POST /api/email/entity
- handlers: общий UID и ICS-билдеры, запись entity_*, пропуск state: disabled,
  --backfill --days/--limit, dry-run больше не пишет в Radicale
- fix: UID ресурса теперь уникален (транслит-слаг + sha1[:8]) — кириллица выпадала
  из регулярки, письма из разных подпапок затирали один ресурс (1121 письмо с
  task/meeting, 554 handled_*, в Radicale 50 задач и 52 события)
- fix: DUE в VTODO пишется в UTC — Radicale отклонял плавающее время (400)
- tests: test_entities.py 10/10, test_email_entities_ui.py 7/7
2026-10-30 09:50:11 +00:00

363 lines
16 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.
"""
entities.py — связь письма с автоматически созданными сущностями (событие/задача).
Обработчики классификации создают по меткам VEVENT в «Рабочем» и VTODO в
«Задачах». Здесь:
- связь письмо ↔ сущности хранится в frontmatter (`entity_<kind>_uid/state`),
- создание/включение, отключение и проверка состояния сущностей,
- «задача-контроль» по письму-встрече (когда на встречу идут подчинённые).
Правила (решения пользователя 2026-10-30):
- отключение события = удаление ресурса VEVENT (событие исчезает из календаря);
- отключение задачи = мягкая отмена (STATUS:CANCELLED + X-DELETED:1);
- сущность с `state: disabled` не пересоздаётся автоматической классификацией;
- задача-контроль создаётся только по кнопке.
UID ресурса = путь письма, приведённый к `[a-zA-Z0-9-]` (как в scripts/email_handlers.py),
поэтому автоматически созданные ранее сущности находятся по тому же адресу.
"""
from __future__ import annotations
import fcntl
import hashlib
import os
import re
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from urllib.parse import quote
import httpx
from .radicale import RADICALE_BASE, RADICALE_USER, _password, _set_prop
EMAIL_ROOT = Path("/opt/hermes/email")
# реальный каталог архива (EMAIL_ROOT — симлинк) и точки, от которых считается
# относительный путь письма: от него строится UID ресурса
EMAIL_ROOTS = (EMAIL_ROOT, Path("/mnt/raid1/email"))
COLLECTION_BY_KIND = {"event": "Рабочий", "task": "Задачи"}
KINDS = ("event", "task")
# признак того, что по письму уже отработал автоматический обработчик
HANDLED_KEY = {"event": "handled_meeting", "task": "handled_task"}
_FM_RE = re.compile(r"^(---\s*\n)(.*?)(\n---)", re.S)
# ─── frontmatter ─────────────────────────────────────────────────────────────
def _unquote(value: str) -> str:
value = (value or "").strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
return value[1:-1]
return value
def headers_of(text: str) -> dict[str, str]:
"""Поля frontmatter письма (плоский key: value, кавычки снимаются)."""
match = _FM_RE.match(text)
if not match:
return {}
fields: dict[str, str] = {}
for line in match.group(2).splitlines():
if ":" not in line or line.lstrip().startswith("#"):
continue
key, _, value = line.partition(":")
fields[key.strip()] = _unquote(value)
return fields
def read_email(path: Path | str) -> str:
return Path(path).read_text(encoding="utf-8", errors="replace")
def update_frontmatter(path: Path | str, fields: dict[str, Any]) -> None:
"""Обновить/добавить поля frontmatter атомарно и под flock."""
target = Path(path)
lock_path = target.with_suffix(target.suffix + ".lock")
with open(lock_path, "w", encoding="utf-8") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
text = read_email(target)
match = _FM_RE.match(text)
if not match:
raise ValueError(f"нет frontmatter: {target}")
head, body, tail = match.group(1), match.group(2), match.group(3)
lines = body.splitlines()
for key, value in fields.items():
rendered = f"{key}: {value}"
replaced = False
for i, line in enumerate(lines):
if line.split(":", 1)[0].strip() == key:
lines[i] = rendered
replaced = True
break
if not replaced:
lines.append(rendered)
new_text = text[:match.start()] + head + "\n".join(lines) + tail + text[match.end():]
tmp = target.with_suffix(target.suffix + ".tmp")
tmp.write_text(new_text, encoding="utf-8")
os.replace(tmp, target)
fcntl.flock(lock_file, fcntl.LOCK_UN)
def rel_path_of(email_file: Path | str) -> str:
"""Путь письма относительно архива (в UID идёт именно он, как в обработчиках)."""
path = Path(email_file)
for root in EMAIL_ROOTS:
try:
return path.relative_to(root).as_posix()
except ValueError:
continue
except OSError: # pragma: no cover — битый симлинк
continue
return path.as_posix().lstrip("/")
# Транслитерация для читаемого UID (кириллица в UID раньше просто выпадала —
# письма из разных подпапок получали ОДИН UID и затирали друг друга)
_TRANSLIT = {
"а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "e",
"ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m",
"н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u",
"ф": "f", "х": "h", "ц": "c", "ч": "ch", "ш": "sh", "щ": "sch", "ъ": "",
"ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya",
}
def _translit(text: str) -> str:
return "".join(_TRANSLIT.get(ch, ch) for ch in text.lower())
def email_uid(rel_path: Path | str) -> str:
"""UID ресурса: читаемый слаг пути письма + короткий хэш (гарантия уникальности).
Раньше UID собирался как `re.sub(r"[^a-zA-Z0-9]+", "-", rel)` — кириллица
выпадала, и письма из разных подпапок («INBOX/Контрагенты/ИП/2026/04/6» и
«INBOX/2026/04/6») получали одинаковый UID и перезаписывали ресурс.
"""
rel = rel_path if isinstance(rel_path, str) and not rel_path.startswith("/") \
else rel_path_of(str(rel_path))
slug = re.sub(r"[^a-zA-Z0-9]+", "-", _translit(rel)).strip("-")[:80]
digest = hashlib.sha1(rel.encode("utf-8")).hexdigest()[:8]
return f"{slug}-{digest}" if slug else digest
# ─── iCalendar ───────────────────────────────────────────────────────────────
def ics_escape(value: Any) -> str:
text = str(value).replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,")
return text.replace("\r\n", "\\n").replace("\n", "\\n")
MSK_OFFSET = 3 # Москва, без перехода на летнее время с 2014
def to_utc_ics(local_dt: str) -> str:
"""'YYYY-MM-DD HH:MM' (московское) → 'YYYYMMDDTHHMMSSZ'.
Radicale отклоняет VTODO с «плавающим» DUE (400 Bad Request): без DTSTART
значение должно быть UTC или датой.
"""
moment = datetime.strptime(local_dt[:16], "%Y-%m-%d %H:%M") - timedelta(hours=MSK_OFFSET)
return moment.strftime("%Y%m%dT%H%M%SZ")
def _vtodo_ics(uid: str, summary: str, description: str, due_dt: str | None = None) -> str:
now = datetime.now().strftime("%Y%m%dT%H%M%S")
lines = [
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//email-assistant//VTODO//RU",
"BEGIN:VTODO", f"UID:{uid}@email-assistant", f"DTSTAMP:{now}",
f"SUMMARY:{ics_escape(summary)}", f"DESCRIPTION:{ics_escape(description)}",
]
if due_dt:
try:
lines.append(f"DUE:{to_utc_ics(due_dt)}")
except ValueError:
pass
lines += ["STATUS:NEEDS-ACTION", "END:VTODO", "END:VCALENDAR"]
return "\r\n".join(lines)
def _vevent_ics(uid: str, summary: str, description: str, start_dt: str,
duration_min: int = 60) -> str:
now = datetime.now().strftime("%Y%m%dT%H%M%S")
start = datetime.strptime(start_dt, "%Y-%m-%d %H:%M")
end = start + timedelta(minutes=duration_min)
lines = [
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//email-assistant//VEVENT//RU",
"BEGIN:VEVENT", f"UID:{uid}@email-assistant", f"DTSTAMP:{now}",
f"SUMMARY:{ics_escape(summary)}", f"DESCRIPTION:{ics_escape(description)}",
f"DTSTART:{start.strftime('%Y%m%dT%H%M%S')}",
f"DTEND:{end.strftime('%Y%m%dT%H%M%S')}",
"END:VEVENT", "END:VCALENDAR",
]
return "\r\n".join(lines)
def build_vtodo(uid: str, summary: str, description: str, due_dt: str | None = None) -> str:
return _vtodo_ics(uid, summary, description, due_dt)
def build_vevent(uid: str, summary: str, description: str, start_dt: str,
duration_min: int = 60) -> str:
return _vevent_ics(uid, summary, description, start_dt, duration_min)
def next_workday_1100(now: datetime | None = None) -> str:
"""Ближайший будний день в 11:00 (для заданий без явного времени)."""
moment = now or datetime.now()
date = moment + timedelta(days=1)
while date.weekday() >= 5: # сб/вс
date += timedelta(days=1)
return date.strftime("%Y-%m-%d") + " 11:00"
def meeting_start(headers: dict[str, str]) -> str | None:
"""'YYYY-MM-DD HH:MM' из meeting_datetime; None, если не задано/битое."""
raw = (headers.get("meeting_datetime") or "").replace("T", " ").strip()
if re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$", raw[:16]):
return raw[:16]
return None
# ─── CalDAV ──────────────────────────────────────────────────────────────────
def resource_url(kind: str, uid: str) -> str:
collection = COLLECTION_BY_KIND[kind]
return f"{RADICALE_BASE}/{RADICALE_USER}/{quote(collection)}/{quote(uid)}.ics"
def _client() -> httpx.Client:
return httpx.Client(auth=(RADICALE_USER, _password()), timeout=10.0)
def resource_exists(kind: str, uid: str) -> bool:
try:
with _client() as client:
return client.get(resource_url(kind, uid)).status_code == 200
except Exception: # noqa: BLE001 — недоступный Radicale = «не знаем», считаем нет
return False
def _put(kind: str, uid: str, body: str) -> dict[str, Any]:
try:
with _client() as client:
response = client.put(resource_url(kind, uid), content=body,
headers={"Content-Type": "text/calendar; charset=utf-8"})
if response.status_code not in (200, 201, 204):
return {"error": f"PUT {response.status_code}: {response.text[:200]}"}
return {"ok": True, "etag": response.headers.get("etag", "").strip('"')}
except Exception as exc: # noqa: BLE001
return {"error": str(exc)}
def _cancel_task(uid: str) -> dict[str, Any]:
"""Мягкая отмена VTODO: STATUS:CANCELLED + X-DELETED (ресурс остаётся)."""
try:
with _client() as client:
response = client.get(resource_url("task", uid))
if response.status_code == 404:
return {"ok": True, "note": "задачи уже нет"}
response.raise_for_status()
etag = response.headers.get("etag", "").strip()
body = _set_prop(response.text, "STATUS", "CANCELLED")
body = _set_prop(body, "X-DELETED", "1")
put = client.put(resource_url("task", uid), content=body,
headers={"Content-Type": "text/calendar; charset=utf-8",
"If-Match": etag})
if put.status_code not in (200, 204):
return {"error": f"PUT {put.status_code}: {put.text[:200]}"}
return {"ok": True}
except Exception as exc: # noqa: BLE001
return {"error": str(exc)}
def _delete_resource(kind: str, uid: str) -> dict[str, Any]:
try:
with _client() as client:
response = client.delete(resource_url(kind, uid))
if response.status_code in (200, 204, 404):
return {"ok": True}
return {"error": f"DELETE {response.status_code}: {response.text[:200]}"}
except Exception as exc: # noqa: BLE001
return {"error": str(exc)}
# ─── сущности письма ─────────────────────────────────────────────────────────
def state_fields(kind: str) -> tuple[str, str]:
return (f"entity_{kind}_uid", f"entity_{kind}_state")
def describe(email_file: Path | str) -> dict[str, Any]:
"""Состояние сущностей письма: uid/state/exists для события и задачи."""
headers = headers_of(read_email(email_file))
out: dict[str, Any] = {}
for kind in KINDS:
uid_key, state_key = state_fields(kind)
uid = headers.get(uid_key) or email_uid(rel_path_of(email_file))
state = headers.get(state_key) or ""
out[kind] = {"uid": uid, "state": state,
"exists": resource_exists(kind, uid) if uid else False,
"handled": headers.get(HANDLED_KEY[kind]) == "true"}
return out
def ensure(kind: str, email_file: Path | str, *, force: bool = False) -> dict[str, Any]:
"""Создать сущность по письму, если её нет и она не отключена пользователем."""
headers = headers_of(read_email(email_file))
uid = email_uid(rel_path_of(email_file))
_, state_key = state_fields(kind)
if headers.get(state_key) == "disabled" and not force:
return {"ok": True, "skipped": "disabled"}
summary = (headers.get("subject") or "(без темы)").strip()
description = f"Из письма: {email_file}"
start = meeting_start(headers)
if kind == "event":
body = _vevent_ics(uid, summary, description, start or next_workday_1100())
else:
body = _vtodo_ics(uid, summary, description, (start or headers.get("date") or "")[:16] or None)
result = _put(kind, uid, body)
if result.get("error"):
return result
uid_key, state_key = state_fields(kind)
fields = {uid_key: uid, state_key: "created"}
if kind == "event":
fields["entity_event_start"] = start or ""
update_frontmatter(email_file, fields)
return {"ok": True, "uid": uid, "start": start}
def disable(kind: str, email_file: Path | str) -> dict[str, Any]:
"""Отключить сущность: событие удаляется, задача мягко отменяется."""
headers = headers_of(read_email(email_file))
uid = headers.get(state_fields(kind)[0]) or email_uid(rel_path_of(email_file))
result = _delete_resource("event", uid) if kind == "event" else _cancel_task(uid)
if result.get("error"):
return result
update_frontmatter(email_file, {state_fields(kind)[1]: "disabled"})
return {"ok": True, "uid": uid}
def enable(kind: str, email_file: Path | str) -> dict[str, Any]:
"""Включить сущность обратно — создать ресурс заново по данным письма."""
return ensure(kind, email_file, force=True)
def create_task_control(email_file: Path | str) -> dict[str, Any]:
"""«Задача-контроль» по письму-встрече: срок — дата встречи (или +1 рабочий день)."""
headers = headers_of(read_email(email_file))
uid = email_uid(rel_path_of(email_file))
summary = "Контроль: " + (headers.get("subject") or "(без темы)").strip()
description = f"Из письма: {email_file}"
due = meeting_start(headers) or (headers.get("date") or "")[:16] or None
body = _vtodo_ics(uid, summary, description, due)
result = _put("task", uid, body)
if result.get("error"):
return result
update_frontmatter(email_file, {state_fields("task")[0]: uid,
state_fields("task")[1]: "created"})
return {"ok": True, "uid": uid, "due": due}