Files
tsumugu/backend/tests/sample_source.py
T
LarsandCursor 7e39fbb2bd
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Failing after 2m55s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 23s
Mache große IMAP-Fächer, die Paperless-Suche und die interne Markdown-Notiz über die gemeinsamen Schnittstellen benutzbar.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 07:34:14 +02:00

162 lines
5.0 KiB
Python

"""Third source used only to prove that registration is enough.
This module is not a product connector and is not imported by the application.
"""
from __future__ import annotations
from uuid import UUID
from app.core.errors import not_found, unprocessable
from app.retrieval import FilePayload, RetrievalFailure
from app.sourcebind import resolve_for_read
from app.sourceregistry import SourceModule, register_source, unregister_source
from app.sourceaccess import borrow_original, complete_borrow
KIND = "sample"
CATALOG = {
"alpha": {
"brief": {
"id": "brief",
"title": "Probenbrief",
"text": "Der Probenbrief bleibt lesbar.",
},
"notiz": {
"id": "notiz",
"title": "Randnotiz",
"text": "Die Randnotiz bleibt in der Quelle.",
},
}
}
CAPABILITIES = {
"kind": KIND,
"navigate": False,
"read_original": True,
"read_preview": True,
"read_attachment": False,
"edit_content": False,
"edit_metadata": False,
"search": {
"query": True,
"title": False,
"correspondent": False,
"document_type": False,
"tags": False,
"document_range": False,
"sort": False,
"continuation": False,
},
}
def parse_config(payload: dict) -> tuple[str, dict, str]:
config = payload.get("config") or {}
catalog = str(config.get("catalog") or "").strip()
name = str(payload.get("name") or "").strip() or catalog
if catalog not in CATALOG:
raise unprocessable("Der Katalog dieser Beispielquelle ist unbekannt.")
return name, {"catalog": catalog}, ""
def probe(row) -> dict:
items = _items(row)
return {"ok": True, "detail": f"Beispielquelle antwortet. {len(items)} Einträge sichtbar."}
def find(conn, owner_id: UUID, connector_id: UUID | None, query: str, options: dict) -> dict:
del options
row = _connector(conn, owner_id, connector_id)
needle = query.casefold()
items = list(_items(row).values())
if needle:
items = [
item for item in items
if needle in item["title"].casefold() or needle in item["text"].casefold()
]
return {"items": items, "connector_id": str(row["id"])}
def preview(conn, owner_id: UUID, connector_id: UUID, options: dict) -> dict:
row = _connector(conn, owner_id, connector_id)
item = _items(row).get(str(options.get("item") or ""))
if item is None:
raise unprocessable("Dieser Eintrag ist in der Beispielquelle nicht vorhanden.")
return {"id": item["id"], "title": item["title"], "text": item["text"], "media": "text"}
def open_original(conn, actor_id: UUID, element: dict, context, ref) -> tuple[bytes, str, str]:
borrowed = borrow_original(conn, actor_id, element, context, ref, KIND)
return complete_borrow(conn, borrowed, lambda row: _bytes(row, borrowed.external_id))
def export_original(conn, actor_id: UUID, external_id: str, detail: dict, assigned, ref):
del detail
result = resolve_for_read(conn, actor_id, KIND, ref, assigned)
if result.row is None:
return RetrievalFailure(result.code, result.message, result.choices)
try:
data, media, name = _bytes(result.row, str(external_id))
except Exception as exc:
return RetrievalFailure("missing", str(getattr(exc, "detail", exc)))
return FilePayload(name, media, data, "")
def install_sample_source() -> None:
register_source(SourceModule(
kind=KIND,
label="Beispielquelle",
representation="text",
capabilities=CAPABILITIES,
parse_config=parse_config,
probe=probe,
find=find,
open_original=open_original,
export_original=export_original,
navigate=None,
preview=preview,
))
def remove_sample_source() -> None:
unregister_source(KIND)
def _connector(conn, owner_id: UUID, connector_id: UUID | None):
if connector_id is not None:
row = conn.execute(
"""
SELECT id, owner_id, kind, name, settings, secret
FROM connectors WHERE id = %s AND owner_id = %s
""",
(connector_id, owner_id),
).fetchone()
if row is None or row["kind"] != KIND:
raise not_found()
return row
rows = conn.execute(
"""
SELECT id, owner_id, kind, name, settings, secret
FROM connectors
WHERE owner_id = %s AND kind = %s
ORDER BY name, id
""",
(owner_id, KIND),
).fetchall()
if len(rows) != 1:
raise unprocessable("Für diese Quelle ist kein eindeutiger Zugang zugeordnet.")
return rows[0]
def _items(row) -> dict:
catalog = (row["settings"] or {}).get("catalog")
return CATALOG.get(catalog) or {}
def _bytes(row, external_id: str) -> tuple[bytes, str, str]:
item = _items(row).get(external_id)
if item is None:
raise unprocessable("Dieser Eintrag ist in der Beispielquelle nicht vorhanden.")
return item["text"].encode("utf-8"), "text/plain", f"{item['id']}.txt"