"""檔案預覽:Office 文件用 LibreOffice 轉成 PDF,試算表讀成表格。結果依內容雜湊快取。""" import asyncio import hashlib import os import shutil import tempfile from pathlib import Path from . import config OFFICE = {"doc", "docx", "odt", "rtf", "ppt", "pptx", "odp", "pps", "ppsx", "key", "pages", "wpd", "vsd", "vsdx"} SHEETS = {"xlsx", "xlsm", "xls", "ods"} CACHE = Path(config.WORKDIR) / ".preview" _lock = asyncio.Lock() # LibreOffice 同時只跑一個,避免設定檔互搶 def kind(path: str) -> str | None: ext = path.rsplit(".", 1)[-1].lower() if "." in path else "" if ext in OFFICE or ext == "pdf": return "pdf" if ext in SHEETS: return "sheets" return None async def to_pdf(data: bytes, name: str) -> bytes: if not shutil.which("soffice"): raise RuntimeError("沒有安裝 LibreOffice,無法預覽這種文件") CACHE.mkdir(parents=True, exist_ok=True) out = CACHE / (hashlib.sha1(data).hexdigest() + ".pdf") if out.exists(): return out.read_bytes() async with _lock: if out.exists(): return out.read_bytes() with tempfile.TemporaryDirectory() as tmp: src = Path(tmp) / ("in." + name.rsplit(".", 1)[-1].lower()) src.write_bytes(data) profile = Path(tmp) / "profile" proc = await asyncio.create_subprocess_exec( "soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--norestore", "--convert-to", "pdf", "--outdir", tmp, str(src), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env={**{k: v for k, v in os.environ.items() if k in ("PATH", "LANG")}, "HOME": tmp}) try: _, err = await asyncio.wait_for(proc.communicate(), 180) except asyncio.TimeoutError: proc.kill() raise RuntimeError("轉換逾時") pdf = Path(tmp) / "in.pdf" if not pdf.exists(): raise RuntimeError("轉換失敗:" + err.decode(errors="replace")[-300:]) shutil.move(pdf, out) return out.read_bytes() def _sheets(data: bytes, ext: str, max_rows: int = 2000, max_cols: int = 100) -> list[dict]: import io import pandas as pd engine = {"xls": "xlrd", "ods": "odf"}.get(ext, "openpyxl") books = pd.read_excel(io.BytesIO(data), sheet_name=None, header=None, nrows=max_rows + 1, engine=engine, dtype=object) out = [] for name, df in books.items(): df = df.iloc[:, :max_cols].dropna(how="all").dropna(axis=1, how="all") rows = [["" if (v is None or (isinstance(v, float) and v != v)) else str(v) for v in r] for r in df.itertuples(index=False)] out.append({"name": str(name), "rows": rows[:max_rows], "truncated": len(rows) > max_rows}) return out async def sheets(data: bytes, name: str) -> list[dict]: return await asyncio.to_thread(_sheets, data, name.rsplit(".", 1)[-1].lower()) async def as_pdf(data: bytes, name: str) -> bytes: return data if name.lower().endswith(".pdf") else await to_pdf(data, name) async def _run(*argv, timeout=120) -> tuple[int, bytes, bytes]: proc = await asyncio.create_subprocess_exec(*argv, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) try: out, err = await asyncio.wait_for(proc.communicate(), timeout) except asyncio.TimeoutError: proc.kill() raise RuntimeError("處理逾時") return proc.returncode, out, err def _cached_pdf(pdf: bytes) -> Path: CACHE.mkdir(parents=True, exist_ok=True) fp = CACHE / (hashlib.sha1(pdf).hexdigest() + ".src.pdf") if not fp.exists(): fp.write_bytes(pdf) return fp async def page_count(pdf: bytes) -> int: if not shutil.which("pdfinfo"): raise RuntimeError("沒有安裝 poppler-utils") code, out, err = await _run("pdfinfo", str(_cached_pdf(pdf))) for line in out.decode(errors="replace").splitlines(): if line.startswith("Pages:"): return int(line.split()[1]) raise RuntimeError("讀不到頁數:" + err.decode(errors="replace")[-200:]) async def page_png(pdf: bytes, page: int, dpi: int = 120) -> bytes: src = _cached_pdf(pdf) out = CACHE / f"{src.stem}.p{page}.d{dpi}.png" if not out.exists(): code, _, err = await _run("pdftoppm", "-png", "-r", str(dpi), "-f", str(page), "-l", str(page), "-singlefile", str(src), str(out)[:-4]) if code != 0 or not out.exists(): raise RuntimeError("轉圖片失敗:" + err.decode(errors="replace")[-200:]) return out.read_bytes()