fix(board): путь ресурса брать из href (UID из писем не совпадает с именем файла → 'Task not found')
- _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
This commit is contained in:
+59
-14
@@ -20,6 +20,8 @@ _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:
|
||||
@@ -120,18 +122,29 @@ def _fetch_items(name: str, kind: str) -> list[dict[str, Any]]:
|
||||
<C:filter><C:comp-filter name="VCALENDAR"><C:comp-filter name="VTODO" /></C:comp-filter></C:filter>
|
||||
</C:calendar-query>""")
|
||||
r.raise_for_status()
|
||||
# ответ c C:calendar-data или c:calendar-data
|
||||
for m in re.finditer(
|
||||
r"<(?:[^:]+:)?getetag>([^<]+)</(?:[^:]+:)?getetag>\s*"
|
||||
r"<[^:]+:calendar-data[^>]*>(.*?)</[^:]+:calendar-data>",
|
||||
r.text, re.S | re.I):
|
||||
etag, data = m.group(1), m.group(2)
|
||||
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:
|
||||
items.append(_parse_vtodo(data, etag))
|
||||
item = _parse_vtodo(data, etag)
|
||||
elif kind == "VEVENT" and "BEGIN:VEVENT" in data:
|
||||
items.append(_parse_vevent(data, etag))
|
||||
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 недоступен
|
||||
@@ -184,16 +197,40 @@ def create_task(summary: str, description: str = "", due_str: str | None = None,
|
||||
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 = c.get(_task_url(uid))
|
||||
if r.status_code == 404:
|
||||
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('" ')
|
||||
return _parse_vtodo(r.text, etag)
|
||||
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
|
||||
|
||||
@@ -202,10 +239,17 @@ 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 = c.get(_task_url(uid))
|
||||
if r.status_code == 404:
|
||||
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)}
|
||||
@@ -213,9 +257,10 @@ def _load_for_update(uid: str) -> tuple[str, str] | dict:
|
||||
|
||||
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(_task_url(uid), content=body,
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user