Files
hermes c95213e172
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 28s
feat(tasks): ответственный, пресеты, свимлейны, утренний дайджест на почту
- radicale: X-RESPONSIBLE/-NAME/-EMAIL, set_responsible; починена правка задач,
  у которых имя файла ≠ UID (кэш перечитывается при 404, _resource_url помнит href)
- board: просрочка после 18:00 МСК, пресеты resp=, группировка по ответственному
- tasktracker: правило «вне бэклога только с ответственным», set_responsible
- UI доски: бейдж/поповер ответственного, пресеты, переключатель «По ответственным»
- контакты: is_employee (звёздочка, пресет «Сотрудники»), 9 сотрудников отмечены,
  Жигульский/Ферулёв/Чикуров созданы заготовками
- scripts/backfill_responsible.py: владелец проставлен 73 задачам
- scripts/tasks_digest.py + cron 08:00 daily: письмо с разделами, himalaya -a hermes
- tests: test_task_responsible.py (15), test_tasks_digest.py (6)
- openspec changes task-responsible и tasks-digest заархивированы
2026-11-14 01:22:53 +00:00

376 lines
17 KiB
Python
Raw Permalink 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.
"""
contacts.py — доступ к базе контактов для веб-интерфейса.
Источник истины — `/opt/hermes/email/contacts/contacts.json` (его пишет
`scripts/contacts_extractor.py`, читают `contacts_caldav_sync.py` и генератор
`contacts.vcf`). Формат файла не меняется: `version` / `contacts` / `by_email`,
где `by_email` хранит ИНДЕКСЫ позиций в списке.
Правка из интерфейса:
1. под flock перечитываем файл (экстрактор мог его переписать),
2. меняем одно поле, добавляем его в `manual_fields` (экстрактор такие поля
не перезаписывает),
3. пишем атомарно (tmp + os.replace), пересобираем `by_email` и `index.json`,
4. сразу пушим vCard в CardDAV: локальное изменение с чужим etag иначе
откатится двусторонним синком (там приоритет у телефона).
"""
from __future__ import annotations
import fcntl
import json
import os
import re
import unicodedata
from pathlib import Path
from typing import Any
from urllib.parse import quote
CONTACTS_DIR = Path(os.environ.get("CONTACTS_DIR", "/opt/hermes/email/contacts"))
CONTACTS_JSON = CONTACTS_DIR / "contacts.json"
INDEX_JSON = CONTACTS_DIR / "index.json"
RADICALE_BASE = os.environ.get("RADICALE_BASE", "http://127.0.0.1:5232")
RADICALE_USER = "estorozhenko"
ADDRESSBOOK = "Контакты"
RADICALE_ENV = Path(os.environ.get("RADICALE_ENV", "/opt/hermes/email-assistant/radicale/.env"))
# поля, которые отдаются в таблицу и редактируются
NAME_FIELDS = ("last_name", "first_name", "middle_name")
EDITABLE = NAME_FIELDS + ("company", "position", "phone", "phone_secondary", "email", "address")
FILTER_FIELDS = ("company", "last_name", "first_name", "middle_name", "phone", "email", "position")
SORT_FIELDS = ("last_name", "first_name", "company", "position", "email")
ALPHABET = list("АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ") + list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + ["#"]
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
_PHONE_OK_RE = re.compile(r"^[0-9+()\-\s.,доб.]*$", re.I)
LETTER_RE = re.compile(r"[А-ЯЁA-Z]")
_cache: dict[str, Any] = {"key": None, "db": None, "mtime": 0.0}
# ─── чтение ──────────────────────────────────────────────────────────────────
def load(path: Path | str | None = None, force: bool = False) -> dict[str, Any]:
"""Прочитать базу (кэш по mtime). Отсутствующий файл → пустая база."""
p = Path(path or CONTACTS_JSON)
try:
mtime = p.stat().st_mtime
except FileNotFoundError:
return {"version": 1, "contacts": [], "by_email": {}}
if not force and _cache["key"] == str(p) and _cache["mtime"] == mtime:
return _cache["db"]
db = json.loads(p.read_text(encoding="utf-8"))
db.setdefault("contacts", [])
db.setdefault("by_email", {})
_cache.update(key=str(p), db=db, mtime=mtime)
return db
def visible(db: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Контакты для показа: без soft-deleted (удалённых на телефоне)."""
db = db if db is not None else load()
return [c for c in db.get("contacts", []) if not c.get("deleted")]
def by_id(contact_id: str, db: dict[str, Any] | None = None) -> dict[str, Any] | None:
db = db if db is not None else load()
for c in db.get("contacts", []):
if c.get("id") == contact_id:
return c
return None
def display_name(contact: dict[str, Any]) -> str:
parts = [contact.get(k) or "" for k in NAME_FIELDS]
name = " ".join(p for p in parts if p).strip()
return name or (contact.get("full_name") or "").strip() or "(без имени)"
# ─── нормализация и фильтры ──────────────────────────────────────────────────
def norm(value: Any) -> str:
"""casefold + «ё»→«е» + сжатые пробелы (сравнение текстовых фильтров)."""
text = unicodedata.normalize("NFC", str(value or "")).casefold().replace("ё", "е")
return re.sub(r"\s+", " ", text).strip()
def digits(value: Any) -> str:
return re.sub(r"\D+", "", str(value or ""))
def letter_of(contact: dict[str, Any]) -> str:
"""Буква алфавитного указателя по фамилии (fallback — полное имя)."""
for raw in (contact.get("last_name"), contact.get("full_name"),
contact.get("first_name")):
text = (raw or "").strip()
if not text:
continue
ch = text[0].upper()
return ch if LETTER_RE.match(ch) else "#"
return "#"
def _match(contact: dict[str, Any], field: str, needle: str) -> bool:
if field == "phone":
nd = digits(needle)
if not nd:
return True
return nd in digits(contact.get("phone")) or nd in digits(contact.get("phone_secondary"))
if field == "email":
return norm(needle) in norm(contact.get("email"))
return norm(needle) in norm(contact.get(field))
def search(contacts: list[dict[str, Any]], *, q: str = "", letter: str = "",
emp: str = "", **filters: str) -> list[dict[str, Any]]:
"""Отфильтровать список контактов (регистронезависимо, телефон — по цифрам).
`emp` — пресет «Сотрудники»: непустое значение оставляет только контакты
с `is_employee: true`.
"""
qn = norm(q)
only_employees = bool((emp or "").strip())
result = []
for c in contacts:
if only_employees and not c.get("is_employee"):
continue
if letter and letter_of(c) != letter.upper():
continue
if qn:
haystack = " ".join(norm(c.get(f)) for f in EDITABLE)
# телефон в запросе может быть в любом формате — сверяем и по цифрам
q_digits = digits(q)
if qn not in haystack and not (q_digits and q_digits in digits(
f"{c.get('phone') or ''} {c.get('phone_secondary') or ''}")):
continue
ok = True
for field in FILTER_FIELDS:
value = (filters.get(field) or "").strip()
if value and not _match(c, field, value):
ok = False
break
if ok:
result.append(c)
return result
def sort_contacts(contacts: list[dict[str, Any]], sort: str = "last_name",
reverse: bool = False) -> list[dict[str, Any]]:
key = sort if sort in SORT_FIELDS else "last_name"
def sort_key(c: dict[str, Any]) -> tuple:
if key == "last_name":
return (norm(c.get("last_name") or c.get("full_name")),
norm(c.get("first_name")), norm(c.get("middle_name")))
return (norm(c.get(key)), norm(c.get("last_name") or c.get("full_name")))
return sorted(contacts, key=sort_key, reverse=reverse)
def alphabet(contacts: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Указатель: буква → количество контактов (0 = буква неактивна)."""
counts: dict[str, int] = {}
for c in contacts:
counts[letter_of(c)] = counts.get(letter_of(c), 0) + 1
return [{"letter": ch, "count": counts.get(ch, 0)} for ch in ALPHABET]
def filter_options(contacts: list[dict[str, Any]], field: str) -> list[str]:
"""Уникальные значения поля для автодополнения (компания, должность)."""
values = {(c.get(field) or "").strip() for c in contacts}
return sorted(v for v in values if v)
# ─── валидация и правка ──────────────────────────────────────────────────────
def validate_field(field: str, value: str) -> str | None:
"""Мягкая проверка значения: возвращает текст ошибки или None."""
if field not in EDITABLE:
return f"поле «{field}» не редактируется"
value = (value or "").strip()
if len(value) > 300:
return "слишком длинное значение (максимум 300 символов)"
if field == "email" and value and not _EMAIL_RE.match(value):
return "некорректный email"
if field in ("phone", "phone_secondary") and value and not _PHONE_OK_RE.match(value):
return "в телефоне допустимы цифры, +, скобки, дефис и «доб.»"
return None
def rebuild(db: dict[str, Any]) -> dict[str, Any]:
"""Пересобрать производные поля: full_name и by_email (хранит индексы)."""
for c in db.get("contacts", []):
parts = [(c.get(k) or "").strip() for k in NAME_FIELDS]
if any(parts):
c["full_name"] = " ".join(p for p in parts if p)
db["by_email"] = {(c.get("email") or "").lower(): i
for i, c in enumerate(db.get("contacts", []))}
return db
def save(db: dict[str, Any], path: Path | str | None = None,
index_path: Path | str | None = None) -> None:
"""Атомарная запись базы + index.json (вызывать под блокировкой)."""
p = Path(path or CONTACTS_JSON)
idx = Path(index_path or (p.parent / "index.json"))
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(p.suffix + ".tmp")
tmp.write_text(json.dumps(db, ensure_ascii=False, indent=1), encoding="utf-8")
os.replace(tmp, p)
idx.write_text(json.dumps(db.get("by_email", {}), ensure_ascii=False, indent=1),
encoding="utf-8")
_cache.update(key=str(p), db=db, mtime=p.stat().st_mtime)
def set_employee(contact_id: str, value: bool, *,
path: Path | str | None = None) -> dict[str, Any]:
"""Включить/выключить признак «сотрудник» (звёздочка в карточке).
Признак живёт только в `contacts.json`: в vCard он не пишется (клиенты его
не понимают), поэтому CardDAV не трогаем. Поле добавляется в
`manual_fields`, чтобы экстрактор его не перетирал.
"""
p = Path(path or CONTACTS_JSON)
lock_path = p.with_suffix(".lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
with open(lock_path, "w", encoding="utf-8") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
db = load(p, force=True)
contact = by_id(contact_id, db)
if contact is None:
return {"error": f"контакт {contact_id} не найден"}
contact["is_employee"] = bool(value)
manual = contact.setdefault("manual_fields", [])
if "is_employee" not in manual:
manual.append("is_employee")
save(db, p)
fcntl.flock(lock_file, fcntl.LOCK_UN)
return {"ok": True, "is_employee": bool(value), "contact": contact}
def update_field(contact_id: str, field: str, value: str, *,
path: Path | str | None = None, push: bool = True) -> dict[str, Any]:
"""Изменить одно поле контакта: валидация → файл под flock → CardDAV."""
p = Path(path or CONTACTS_JSON)
error = validate_field(field, value)
if error:
return {"error": error}
value = (value or "").strip()
lock_path = p.with_suffix(".lock")
lock_path.parent.mkdir(parents=True, exist_ok=True)
with open(lock_path, "w", encoding="utf-8") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
db = load(p, force=True) # перечитываем: экстрактор мог записать файл
contact = by_id(contact_id, db)
if contact is None:
return {"error": f"контакт {contact_id} не найден"}
old = contact.get(field)
contact[field] = value
manual = contact.setdefault("manual_fields", [])
if field not in manual:
manual.append(field)
rebuild(db)
save(db, p)
result: dict[str, Any] = {"ok": True, "contact": contact, "old": old,
"full_name": contact.get("full_name", "")}
if push:
result["caldav"] = _sync_carddav(contact, db, p)
fcntl.flock(lock_file, fcntl.LOCK_UN)
return result
def _sync_carddav(contact: dict[str, Any], db: dict[str, Any], path: Path) -> dict[str, Any]:
"""Толкнуть карточку в CardDAV и записать etag/dirty в базу (под тем же flock)."""
pushed = push_to_caldav(contact)
caldav = dict(contact.get("caldav") or {})
caldav["uid"] = caldav.get("uid") or contact.get("id")
if pushed.get("error"):
caldav["dirty"] = True
contact["caldav"] = caldav
rebuild(db)
save(db, path)
return {"error": pushed["error"], "dirty": True}
caldav["etag"] = pushed.get("etag")
caldav.pop("dirty", None)
contact["caldav"] = caldav
rebuild(db)
save(db, path)
return {"etag": pushed.get("etag")}
# ─── CardDAV ─────────────────────────────────────────────────────────────────
def radicale_password() -> str:
env = os.environ.get("CALDAV_PASS") or os.environ.get("RADICALE_PASS")
if env:
return env
try:
for line in RADICALE_ENV.read_text(encoding="utf-8").splitlines():
if line.startswith("RADICALE_PASS="):
return line.split("=", 1)[1].strip()
except OSError:
pass
return ""
def to_vcard(contact: dict[str, Any]) -> str:
"""vCard 4.0 контакта. N собирается из явных частей ФИО (Family;Given;Additional)."""
last = (contact.get("last_name") or "").strip()
first = (contact.get("first_name") or "").strip()
middle = (contact.get("middle_name") or "").strip()
full_name = display_name(contact)
if last or first or middle:
n_line = f"N:{last};{first};{middle};;"
else:
parts = full_name.split(maxsplit=2)
n_line = (f"N:{parts[-1]};{parts[0]};{' '.join(parts[1:-1])};;"
if len(parts) >= 2 else f"N:{full_name};;;;")
lines = ["BEGIN:VCARD", "VERSION:4.0"]
uid = (contact.get("caldav") or {}).get("uid") or contact.get("id") or ""
if uid:
lines.append(f"UID:{uid}")
lines += [f"FN:{full_name}", n_line]
if contact.get("email"):
lines.append(f"EMAIL;TYPE=WORK:{contact['email']}")
if contact.get("phone"):
lines.append(f"TEL;TYPE=WORK:{str(contact['phone']).replace(',', ' ')}")
if contact.get("phone_secondary"):
lines.append(f"TEL;TYPE=CELL:{str(contact['phone_secondary']).replace(',', ' ')}")
if contact.get("position"):
lines.append(f"TITLE:{contact['position']}")
if contact.get("company"):
lines.append(f"ORG:{contact['company']}")
if contact.get("address"):
lines.append(f"ADR;TYPE=WORK:;;{contact['address']};;;")
if contact.get("source_uids"):
lines.append("X-SOURCES:" + " | ".join(contact["source_uids"]))
lines.append("END:VCARD")
return "\r\n".join(lines) + "\r\n"
def card_url(uid: str) -> str:
return f"{RADICALE_BASE}/{RADICALE_USER}/{quote(ADDRESSBOOK)}/{quote(uid)}.vcf"
def push_to_caldav(contact: dict[str, Any]) -> dict[str, Any]:
"""PUT vCard в Radicale. Возвращает {'etag': ...} или {'error': ...}."""
import httpx
uid = (contact.get("caldav") or {}).get("uid") or contact.get("id")
if not uid:
return {"error": "у контакта нет id — нечего синхронизировать"}
headers = {"Content-Type": "text/vcard; charset=utf-8"}
etag = (contact.get("caldav") or {}).get("etag")
if etag:
headers["If-Match"] = etag
try:
with httpx.Client(auth=(RADICALE_USER, radicale_password()), timeout=5.0) as client:
r = client.put(card_url(uid), content=to_vcard(contact), headers=headers)
if r.status_code == 412: # карточку изменили на телефоне
return {"error": "конфликт версий (412): карточка изменена на телефоне"}
r.raise_for_status()
return {"etag": (r.headers.get("etag") or "").strip('"')}
except Exception as exc: # noqa: BLE001 — сеть/авторизация: правка остаётся локальной
return {"error": str(exc)}