93 lines
2.7 KiB
Python
93 lines
2.7 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import mimetypes
|
|
import re
|
|
import shutil
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
from app.config import get_settings
|
|
|
|
|
|
settings = get_settings()
|
|
|
|
DATA_IMAGE_RE = re.compile(
|
|
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
|
|
re.IGNORECASE | re.DOTALL,
|
|
)
|
|
|
|
|
|
def sha256_file(path: Path) -> str:
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as handle:
|
|
while True:
|
|
chunk = handle.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def group_dir(group_id: int, category: str) -> Path:
|
|
return settings.data_root / category / f"group_{group_id:04d}"
|
|
|
|
|
|
def version_dir(category: str, group_id: int, document_id: int, version_no: int) -> Path:
|
|
return group_dir(group_id, category) / f"document_{document_id:06d}" / f"v{version_no:03d}"
|
|
|
|
|
|
def public_storage_url(path: Path) -> str:
|
|
relative = path.relative_to(settings.data_root).as_posix()
|
|
return f"{settings.public_base_url.rstrip('/')}/storage/{relative}"
|
|
|
|
|
|
def guess_image_ext(fmt: str) -> str:
|
|
fmt = fmt.lower().strip()
|
|
if fmt in {"jpeg", "jpg"}:
|
|
return "jpg"
|
|
if fmt in {"png", "gif", "bmp", "webp"}:
|
|
return fmt
|
|
return "png"
|
|
|
|
|
|
def rewrite_embedded_images(markdown_text: str, assets_dir: Path) -> tuple[str, int]:
|
|
assets_dir.mkdir(parents=True, exist_ok=True)
|
|
seen: dict[str, str] = {}
|
|
count = 0
|
|
|
|
def repl(match: re.Match[str]) -> str:
|
|
nonlocal count
|
|
alt = match.group("alt") or "image"
|
|
fmt = guess_image_ext(match.group("fmt") or "png")
|
|
raw = base64.b64decode(match.group("b64"))
|
|
digest = hashlib.sha256(raw).hexdigest()
|
|
existing = seen.get(digest)
|
|
if existing is None:
|
|
count += 1
|
|
filename = f"img_{count:03d}_{digest[:8]}.{fmt}"
|
|
target = assets_dir / filename
|
|
target.write_bytes(raw)
|
|
existing = filename
|
|
seen[digest] = existing
|
|
return f""
|
|
|
|
return DATA_IMAGE_RE.sub(repl, markdown_text), len(seen)
|
|
|
|
|
|
def remove_path_if_exists(path: Path) -> None:
|
|
if path.is_dir():
|
|
shutil.rmtree(path, ignore_errors=True)
|
|
elif path.exists():
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
def build_zip(source_paths: list[tuple[Path, str]], output_path: Path) -> Path:
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
for path, archive_name in source_paths:
|
|
if path.exists():
|
|
archive.write(path, arcname=archive_name)
|
|
return output_path
|