"""Umwandlung von Office-Dateien (Word, Excel, OpenDocument …) in PDF über Gotenberg."""
import logging
from pathlib import Path
import httpx
from .config import settings
log = logging.getLogger("praxis.convert")
OFFICE_EXT = {".doc", ".docx", ".docm", ".dot", ".dotx", ".odt", ".ott", ".rtf",
".xls", ".xlsx", ".xlsm", ".xlt", ".xltx", ".ods", ".ots",
".ppt", ".pptx", ".pps", ".ppsx", ".odp"}
class ConversionError(Exception):
pass
def enabled() -> bool:
return bool(settings.gotenberg_url)
def convertible(path: str | None) -> bool:
return bool(path) and Path(path).suffix.lower() in OFFICE_EXT
def pdf_name(original: str | None) -> str:
return (Path(original).stem if original else "dokument") + ".pdf"
async def office_to_pdf(rel_path: str) -> str:
"""Wandelt eine hochgeladene Office-Datei um und speichert das PDF daneben.
Gibt den relativen Pfad des PDFs zurück oder wirft ConversionError."""
if not enabled():
raise ConversionError("PDF-Umwandlung ist nicht eingerichtet (GOTENBERG_URL fehlt).")
src = settings.upload_dir / rel_path
ext = src.suffix.lower()
if ext not in OFFICE_EXT:
raise ConversionError(f"Dateityp {ext} kann nicht umgewandelt werden.")
data = {"pdfa": settings.pdf_a} if settings.pdf_a else {}
try:
async with httpx.AsyncClient(timeout=settings.convert_timeout) as client:
with open(src, "rb") as fh:
resp = await client.post(f"{settings.gotenberg_url}/forms/libreoffice/convert",
files={"files": (f"dokument{ext}", fh, "application/octet-stream")},
data=data)
except httpx.HTTPError as e:
raise ConversionError(f"Konverter nicht erreichbar ({settings.gotenberg_url}): {e}") from e
except OSError as e:
raise ConversionError(f"Datei nicht lesbar: {e}") from e
if resp.status_code != 200 or not resp.content.startswith(b"%PDF"):
raise ConversionError(f"Konverter-Fehler HTTP {resp.status_code}: {resp.text[:200]}")
rel_pdf = str(Path(rel_path).with_suffix(".pdf"))
try:
(settings.upload_dir / rel_pdf).write_bytes(resp.content)
except OSError as e:
raise ConversionError(f"PDF konnte nicht gespeichert werden: {e}") from e
log.info("In PDF umgewandelt: %s -> %s (%d KB)", rel_path, rel_pdf, len(resp.content) // 1024)
return rel_pdf
async def health() -> bool | None:
"""None = nicht eingerichtet, True/False = erreichbar."""
if not enabled():
return None
try:
async with httpx.AsyncClient(timeout=5) as client:
return (await client.get(f"{settings.gotenberg_url}/health")).status_code == 200
except httpx.HTTPError:
return False
async def convert_backlog(wait_seconds: int = 300) -> None:
"""Nach dem Start: alle Office-Dateien ohne PDF im Hintergrund umwandeln.
Wartet, bis der Konverter erreichbar ist (er startet meist langsamer als die App)."""
import asyncio
from sqlalchemy import select
from .db import SessionLocal
from .models import DocumentVersion
from .search import index_version
if not enabled():
return
waited = 0
while not await health():
if waited >= wait_seconds:
log.warning("Konverter nach %ds nicht erreichbar – vorhandene Dateien werden nicht umgewandelt", waited)
return
await asyncio.sleep(10)
waited += 10
with SessionLocal() as db:
todo = [v for v in db.scalars(select(DocumentVersion).where(DocumentVersion.file_path.is_not(None),
DocumentVersion.pdf_path.is_(None))).all()
if convertible(v.file_path)]
if not todo:
return
log.info("Wandle %d vorhandene Office-Datei(en) in PDF um …", len(todo))
ok = 0
for v in todo:
try:
v.pdf_path = await office_to_pdf(v.file_path)
await asyncio.to_thread(index_version, v)
db.commit()
ok += 1
except ConversionError as e:
db.rollback()
log.warning("Umwandlung von %s fehlgeschlagen: %s", v.file_name, e)
log.info("Hintergrund-Umwandlung fertig: %d von %d", ok, len(todo))
# ---------- Hintergrund-Job (Start, nach Importen) ----------
_job = None
def job_running() -> bool:
return _job is not None and not _job.done()
def start_background_processing() -> None:
"""Suchindex und PDF-Umwandlung im Hintergrund nachziehen (läuft höchstens einmal gleichzeitig)."""
import asyncio
global _job
if job_running():
return
async def run():
from .search import index_backlog
await index_backlog()
await convert_backlog()
_job = asyncio.create_task(run())
def pending_conversions(db) -> int:
from sqlalchemy import select
from .models import DocumentVersion
if not enabled():
return 0
paths = db.scalars(select(DocumentVersion.file_path).where(DocumentVersion.file_path.is_not(None),
DocumentVersion.pdf_path.is_(None))).all()
return sum(1 for p in paths if convertible(p))