a76b74752b
- _fetch_items: сохраняет href ресурса из ответа CalDAV REPORT - _resource_url/_lookup_urls: href → <uid>.ics → <uid без @суффикса>.ics; найденный URL запоминается в _RESOLVED и используется для PUT с If-Match - get_task/_load_for_update: перебор кандидатов вместо одного URL - entities: UID пишется без суффикса @email-assistant (совпадает с именем файла) - тесты: разворот складок, кандидаты URL — 18/18
463 lines
18 KiB
Python
463 lines
18 KiB
Python
"""
|
||
radicale.py — тонкий CalDAV-клиент для карточек главной страницы.
|
||
|
||
Читает задачи (VTODO) и события (VEVENT) из Radicale (HTTP Basic auth).
|
||
Пароль — из radicale/.env (RADICALE_PASS), пользователь — estorozhenko.
|
||
Любая ошибка сети/пароля → пустой результат (главная не падает).
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from urllib.parse import quote
|
||
|
||
import httpx
|
||
|
||
RADICALE_BASE = "http://127.0.0.1:5232"
|
||
RADICALE_USER = "estorozhenko"
|
||
_ENV_FILE = Path("/opt/hermes/email-assistant/radicale/.env")
|
||
|
||
_CACHE: dict[str, Any] = {}
|
||
_CACHE_TTL = 30.0 # сек
|
||
# фактический URL ресурса, найденный при чтении задачи (UID ≠ имя файла)
|
||
_RESOLVED: dict[str, str] = {}
|
||
|
||
|
||
def _password() -> str:
|
||
for line in _ENV_FILE.read_text(encoding="utf-8").splitlines():
|
||
if line.startswith("RADICALE_PASS="):
|
||
return line.split("=", 1)[1].strip()
|
||
return ""
|
||
|
||
|
||
def _client() -> httpx.Client:
|
||
return httpx.Client(
|
||
base_url=RADICALE_BASE,
|
||
auth=(RADICALE_USER, _password()),
|
||
timeout=5.0,
|
||
headers={"Depth": "1"},
|
||
)
|
||
|
||
|
||
def _collection_url(name: str) -> str:
|
||
return f"{RADICALE_BASE}/{RADICALE_USER}/{quote(name)}/"
|
||
|
||
|
||
TASKS_COLLECTION = "Задачи"
|
||
|
||
|
||
def _task_url(uid: str) -> str:
|
||
"""URL одного VTODO-ресурса: /estorozhenko/Задачи/<uid>.ics"""
|
||
return f"{_collection_url(TASKS_COLLECTION)}{quote(uid)}.ics"
|
||
|
||
|
||
def _esc(value: str) -> str:
|
||
"""Экранирование текстового значения для iCalendar."""
|
||
return (value.replace("\\", "\\\\").replace(";", "\\;")
|
||
.replace(",", "\\,").replace("\n", "\\n"))
|
||
|
||
|
||
def _unfold(data: str) -> str:
|
||
"""Развернуть складки iCalendar (RFC 5545): перенос строки + пробел/таб = продолжение.
|
||
|
||
Radicale отдаёт длинные значения (UID, DESCRIPTION, SUMMARY) сложенными по 75
|
||
байт. Без разворота UID обрезался на 75-м символе, и любой PUT по нему отвечал
|
||
404 — кнопки доски молча не работали («нажал →, ничего не произошло»).
|
||
"""
|
||
return re.sub(r"\r?\n[ \t]", "", data)
|
||
|
||
|
||
def _unescape(value: str) -> str:
|
||
"""Обратное к _esc: \\n → перевод строки, \\, → запятая, \\; → точка с запятой."""
|
||
return (value.replace("\\n", "\n").replace("\\N", "\n")
|
||
.replace("\\,", ",").replace("\\;", ";")
|
||
.replace("\\\\", "\\"))
|
||
|
||
|
||
def _del_prop(body: str, name: str) -> str:
|
||
"""Удалить все вхождения свойства (COMPLETED при возврате из «Выполнено»)."""
|
||
prefix = f"{name}:"
|
||
out = [line for line in body.splitlines() if not line.upper().startswith(prefix)]
|
||
return "\r\n".join(out)
|
||
|
||
|
||
def _set_prop(body: str, name: str, value: str) -> str:
|
||
"""Заменить или добавить свойство VTODO (лишние копии свойства убираются)."""
|
||
out: list[str] = []
|
||
replaced = False
|
||
for line in body.splitlines():
|
||
if line.upper().startswith(f"{name}:"):
|
||
if not replaced:
|
||
out.append(f"{name}:{value}")
|
||
replaced = True
|
||
continue
|
||
out.append(line)
|
||
if not replaced:
|
||
for i, line in enumerate(out):
|
||
if line.strip().upper() == "END:VTODO":
|
||
out.insert(i, f"{name}:{value}")
|
||
replaced = True
|
||
break
|
||
if not replaced:
|
||
out.append(f"{name}:{value}")
|
||
return "\r\n".join(out)
|
||
|
||
|
||
|
||
def _fetch_items(name: str, kind: str) -> list[dict[str, Any]]:
|
||
import time
|
||
now = time.monotonic()
|
||
key = f"{name}:{kind}"
|
||
if key in _CACHE and now - _CACHE[key]["ts"] < _CACHE_TTL:
|
||
return _CACHE[key]["items"]
|
||
|
||
items: list[dict[str, Any]] = []
|
||
try:
|
||
with _client() as c:
|
||
# CalDAV REPORT — Radicale не отдаёт calendar-data через PROPFIND
|
||
r = c.request("REPORT", _collection_url(name), content="""<?xml version="1.0"?>
|
||
<C:calendar-query xmlns:C="urn:ietf:params:xml:ns:caldav" xmlns:D="DAV:">
|
||
<D:prop><D:getetag /><C:calendar-data /></D:prop>
|
||
<C:filter><C:comp-filter name="VCALENDAR"><C:comp-filter name="VTODO" /></C:comp-filter></C:filter>
|
||
</C:calendar-query>""")
|
||
r.raise_for_status()
|
||
for block in re.split(r"<(?::?[A-Za-z]+:)?response[^>]*>", r.text)[1:]:
|
||
m_data = re.search(r"<[^:]+:calendar-data[^>]*>(.*?)</[^:]+:calendar-data>",
|
||
block, re.S | re.I)
|
||
if m_data is None:
|
||
continue
|
||
m_etag = re.search(r"<(?:[^:]+:)?getetag>([^<]+)</", block)
|
||
# href ресурса — ИСТИННЫЙ путь: имя файла в Radicale не обязано
|
||
# совпадать со свойством UID (задачи из писем пишутся в <uid>.ics,
|
||
# а UID внутри — <uid>@email-assistant)
|
||
m_href = re.search(r"<(?:[A-Za-z]+:)?href>([^<]+)</", block)
|
||
etag = m_etag.group(1) if m_etag else ""
|
||
data = m_data.group(1)
|
||
data = data.replace("<", "<").replace(">", ">") \
|
||
.replace("&", "&").replace(""", '"')
|
||
href = m_href.group(1) if m_href else ""
|
||
if kind == "VTODO" and "BEGIN:VTODO" in data:
|
||
item = _parse_vtodo(data, etag)
|
||
elif kind == "VEVENT" and "BEGIN:VEVENT" in data:
|
||
item = _parse_vevent(data, etag)
|
||
else:
|
||
continue
|
||
item["href"] = href
|
||
items.append(item)
|
||
items.sort(key=lambda i: i.get("due") or i.get("dtstart") or "", reverse=False)
|
||
except Exception:
|
||
items = [] # Radicale недоступен
|
||
|
||
_CACHE[key] = {"ts": now, "items": items}
|
||
return items
|
||
|
||
|
||
def create_task(summary: str, description: str = "", due_str: str | None = None,
|
||
priority: int | None = None, from_value: str | None = None,
|
||
tags: list[str] | None = None) -> dict:
|
||
"""Создать VTODO в Radicale (PUT). Возвращает uid/etag или {'error': ...}.
|
||
|
||
from_value → X-FROM (кто поставил заявку), tags → CATEGORIES (объекты).
|
||
"""
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
uid = str(uuid.uuid4())
|
||
now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||
lines = [
|
||
"BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Email Assistant//Hermes//RU",
|
||
"BEGIN:VTODO", f"UID:{uid}", f"DTSTAMP:{now}", f"CREATED:{now}",
|
||
f"SUMMARY:{_esc(summary)}", f"DESCRIPTION:{_esc(description)}",
|
||
"STATUS:NEEDS-ACTION",
|
||
]
|
||
if due_str:
|
||
try:
|
||
from datetime import datetime as _dt
|
||
lines.append("DUE:" + _dt.strptime(due_str, "%Y-%m-%d").strftime("%Y%m%dT235959Z"))
|
||
except ValueError:
|
||
pass
|
||
if priority:
|
||
lines.append(f"PRIORITY:{int(priority)}")
|
||
if from_value:
|
||
lines.append(f"X-FROM:{_esc(from_value)}")
|
||
clean_tags = [t.strip() for t in (tags or []) if t and t.strip()]
|
||
if clean_tags:
|
||
lines.append("CATEGORIES:" + ",".join(_esc(t) for t in clean_tags))
|
||
lines.append("X-STATUS:backlog")
|
||
lines += ["END:VTODO", "END:VCALENDAR"]
|
||
body = "\r\n".join(lines)
|
||
try:
|
||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||
r = c.put(_task_url(uid), content=body, headers={"Content-Type": "text/calendar"})
|
||
r.raise_for_status()
|
||
etag = r.headers.get("etag", "").strip('" ')
|
||
_CACHE.pop(f"{TASKS_COLLECTION}:VTODO", None) # сбросить кэш
|
||
return {"uid": uid, "etag": etag}
|
||
except Exception as e:
|
||
return {"error": str(e)}
|
||
|
||
|
||
def _resource_url(uid: str) -> str:
|
||
"""URL ресурса задачи: сначала href из последнего REPORT (истинный путь)."""
|
||
key = f"{TASKS_COLLECTION}:VTODO"
|
||
for item in (_CACHE.get(key) or {}).get("items") or []:
|
||
if item.get("uid") == uid and item.get("href"):
|
||
return RADICALE_BASE + item["href"]
|
||
return _task_url(uid)
|
||
|
||
|
||
def _lookup_urls(uid: str) -> list[str]:
|
||
"""Кандидаты URL: href из кэша → <uid>.ics → <uid без @суффикса>.ics."""
|
||
urls = [_resource_url(uid)]
|
||
plain = uid.split("@", 1)[0]
|
||
if plain != uid:
|
||
urls.append(_task_url(plain))
|
||
return urls
|
||
|
||
|
||
def get_task(uid: str) -> dict[str, Any] | None:
|
||
"""Прочитать одну задачу по UID (без кэша)."""
|
||
try:
|
||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||
r = None
|
||
for url in _lookup_urls(uid):
|
||
r = c.get(url)
|
||
if r.status_code != 404:
|
||
break
|
||
if r is None or r.status_code == 404:
|
||
return None
|
||
r.raise_for_status()
|
||
etag = r.headers.get("etag", "").strip('" ')
|
||
item = _parse_vtodo(r.text, etag)
|
||
item["href"] = r.url.raw_path.decode() if hasattr(r.url, "raw_path") else ""
|
||
return item
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _load_for_update(uid: str) -> tuple[str, str] | dict:
|
||
"""GET задачи → (body, etag) для последующего PUT с If-Match. При ошибке — {'error': ...}."""
|
||
try:
|
||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||
r, url = None, ""
|
||
for candidate in _lookup_urls(uid):
|
||
r = c.get(candidate)
|
||
if r.status_code != 404:
|
||
url = candidate
|
||
break
|
||
if r is None or r.status_code == 404:
|
||
return {"error": "Task not found"}
|
||
r.raise_for_status()
|
||
# запомнить фактический ресурс, чтобы PUT шёл туда же
|
||
_RESOLVED[uid] = url
|
||
return r.text, r.headers.get("etag", "").strip()
|
||
except Exception as e:
|
||
return {"error": str(e)}
|
||
|
||
|
||
def _put_for_update(uid: str, body: str, etag: str) -> dict:
|
||
"""PUT обновлённого VTODO с проверкой etag; сбрасывает кэш списка."""
|
||
url = _RESOLVED.pop(uid, None) or _resource_url(uid)
|
||
try:
|
||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||
put_r = c.put(url, content=body,
|
||
headers={"Content-Type": "text/calendar", "If-Match": etag})
|
||
if put_r.status_code == 412:
|
||
_CACHE.pop(f"{TASKS_COLLECTION}:VTODO", None)
|
||
return {"error": "conflict", "note": "etag mismatch; reload page"}
|
||
put_r.raise_for_status()
|
||
_CACHE.pop(f"{TASKS_COLLECTION}:VTODO", None)
|
||
return {"ok": True}
|
||
except Exception as e:
|
||
return {"error": str(e)}
|
||
|
||
|
||
def toggle_task(uid: str) -> dict:
|
||
"""Переключить STATUS VTODO: NEEDS-ACTION ↔ COMPLETED."""
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
new_status = "COMPLETED" if "STATUS:NEEDS-ACTION" in body else "NEEDS-ACTION"
|
||
res = _put_for_update(uid, _set_prop(body, "STATUS", new_status), etag)
|
||
if res.get("error"):
|
||
return res
|
||
return {"status": new_status, "ok": True}
|
||
|
||
|
||
def update_task(uid: str, summary: str, due_str: str = "") -> dict:
|
||
"""Обновить SUMMARY и/или DUE VTODO."""
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
new_body = _set_prop(body, "SUMMARY", _esc(summary))
|
||
if due_str:
|
||
from datetime import datetime
|
||
try:
|
||
dt = datetime.strptime(due_str, "%Y-%m-%d").strftime("%Y%m%dT235959Z")
|
||
new_body = _set_prop(new_body, "DUE", dt)
|
||
except ValueError:
|
||
pass # некорректная дата — оставляем DUE как есть
|
||
return _put_for_update(uid, new_body, etag)
|
||
|
||
|
||
def set_priority(uid: str, priority: int) -> dict:
|
||
"""Установить PRIORITY VTODO (1 — высший, 5 — низший)."""
|
||
try:
|
||
priority = int(priority)
|
||
except (TypeError, ValueError):
|
||
return {"error": "priority must be int 1-5"}
|
||
if not 1 <= priority <= 5:
|
||
return {"error": "priority must be int 1-5"}
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
return _put_for_update(uid, _set_prop(body, "PRIORITY", str(priority)), etag)
|
||
|
||
|
||
def delete_task(uid: str) -> dict:
|
||
"""Мягкое удаление: STATUS:CANCELLED + X-DELETED (ресурс остаётся в Radicale)."""
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
new_body = _set_prop(body, "STATUS", "CANCELLED")
|
||
new_body = _set_prop(new_body, "X-DELETED", "1")
|
||
return _put_for_update(uid, new_body, etag)
|
||
|
||
|
||
def _parse_vtodo(data: str, etag: str) -> dict[str, Any]:
|
||
data = _unfold(data)
|
||
props: dict[str, str] = {}
|
||
for line in data.splitlines():
|
||
if ":" in line:
|
||
k, v = line.split(":", 1)
|
||
props[k.strip().upper()] = v.strip()
|
||
summary = props.get("SUMMARY", "(без темы)")
|
||
due = props.get("DUE")
|
||
status = props.get("STATUS", "")
|
||
complete = status == "COMPLETED"
|
||
uid = props.get("UID", "")
|
||
try:
|
||
priority = int(props.get("PRIORITY", "") or 0)
|
||
except ValueError:
|
||
priority = 0
|
||
# DUE: 20261023T120000Z → 2026-10-23
|
||
due_fmt = _fmt_date(due)
|
||
description = _unescape(props.get("DESCRIPTION", ""))
|
||
# «От кого»: явное X-FROM, иначе первая строка описания «От: …» (старые задачи)
|
||
from_value = _unescape(props.get("X-FROM", "")).strip()
|
||
if not from_value:
|
||
for line in description.splitlines():
|
||
if line.strip().lower().startswith("от:"):
|
||
from_value = line.split(":", 1)[1].strip()
|
||
break
|
||
tags = [_unescape(t).strip() for t in props.get("CATEGORIES", "").split(",") if t.strip()]
|
||
return {"type": "vtodo", "summary": _unescape(summary), "due": due_fmt,
|
||
"completed": complete, "status": status, "priority": priority,
|
||
"description": description,
|
||
"x_status": props.get("X-STATUS", "").strip().lower(),
|
||
"from_value": from_value,
|
||
"tags": tags,
|
||
"due_raw": due or "",
|
||
"completed_raw": props.get("COMPLETED", ""),
|
||
"modified_raw": props.get("LAST-MODIFIED", ""),
|
||
"created_raw": props.get("CREATED") or props.get("DTSTAMP", ""),
|
||
"created": _fmt_date(props.get("CREATED") or props.get("DTSTAMP")),
|
||
"deleted": status == "CANCELLED" or props.get("X-DELETED") == "1",
|
||
"etag": etag, "uid": uid}
|
||
|
||
|
||
def _parse_vevent(data: str, etag: str) -> dict[str, Any]:
|
||
data = _unfold(data)
|
||
props: dict[str, str] = {}
|
||
for line in data.splitlines():
|
||
if ":" in line:
|
||
k, v = line.split(":", 1)
|
||
props[k.strip().upper()] = v.strip()
|
||
summary = props.get("SUMMARY", "(без темы)")
|
||
dtstart = props.get("DTSTART")
|
||
dtend = props.get("DTEND", props.get("DURATION"))
|
||
return {"type": "vevent", "summary": summary,
|
||
"dtstart": _hhmm(dtstart), "datestr": _fmt_date(dtstart),
|
||
"end": dtend, "etag": etag}
|
||
|
||
|
||
def _fmt_date(iso: str | None) -> str | None:
|
||
if not iso:
|
||
return None
|
||
m = re.match(r"(\d{4})(\d{2})(\d{2})", iso)
|
||
return f"{m.group(3)}.{m.group(2)}.{m.group(1)}" if m else iso
|
||
|
||
|
||
def _hhmm(iso: str | None) -> str | None:
|
||
if not iso:
|
||
return None
|
||
m = re.match(r"(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})", iso)
|
||
if m:
|
||
return f"{m.group(4)}:{m.group(5)}"
|
||
return _fmt_date(iso)
|
||
|
||
|
||
def get_tasks(limit: int = 8, include_deleted: bool = False) -> list[dict[str, Any]]:
|
||
"""Список задач; мягко удалённые (STATUS:CANCELLED / X-DELETED) скрыты."""
|
||
items = _fetch_items(TASKS_COLLECTION, "VTODO")
|
||
if not include_deleted:
|
||
items = [t for t in items if not t.get("deleted")]
|
||
return items[:limit]
|
||
|
||
|
||
def get_tasks_by_email(email: str, limit: int = 5) -> list[dict[str, Any]]:
|
||
"""Задачи, созданные из писем контакта (в DESCRIPTION строка «От: ...<адрес>»)."""
|
||
addr = (email or "").strip().lower()
|
||
if not addr:
|
||
return []
|
||
found = []
|
||
for task in _fetch_items(TASKS_COLLECTION, "VTODO"):
|
||
if task.get("deleted"):
|
||
continue
|
||
description = (task.get("description") or "").lower()
|
||
if addr in description:
|
||
found.append(task)
|
||
if len(found) >= limit:
|
||
break
|
||
return found
|
||
|
||
|
||
def set_task_state(uid: str, x_status: str, status: str,
|
||
completed_iso: str | None = None) -> dict:
|
||
"""Записать колонку доски: X-STATUS + STATUS + метку COMPLETED.
|
||
|
||
completed_iso=None — метка COMPLETED удаляется (возврат из «Выполнено»).
|
||
"""
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
new_body = _set_prop(body, "X-STATUS", x_status)
|
||
new_body = _set_prop(new_body, "STATUS", status)
|
||
if completed_iso:
|
||
new_body = _set_prop(new_body, "COMPLETED", completed_iso)
|
||
else:
|
||
new_body = _del_prop(new_body, "COMPLETED")
|
||
return _put_for_update(uid, new_body, etag)
|
||
|
||
|
||
def set_tags(uid: str, tags: list[str]) -> dict:
|
||
"""Заменить набор тегов объекта (CATEGORIES); пустой список — свойство удаляется."""
|
||
loaded = _load_for_update(uid)
|
||
if isinstance(loaded, dict):
|
||
return loaded
|
||
body, etag = loaded
|
||
clean = [t.strip() for t in (tags or []) if t and t.strip()]
|
||
if clean:
|
||
new_body = _set_prop(body, "CATEGORIES", ",".join(_esc(t) for t in clean))
|
||
else:
|
||
new_body = _del_prop(body, "CATEGORIES")
|
||
return _put_for_update(uid, new_body, etag)
|
||
|
||
|
||
def get_events(limit: int = 8) -> list[dict[str, Any]]:
|
||
return _fetch_items("Рабочий", "VEVENT")[:limit] |