unis-oa/backend/app/service/attachment_bundle.py

109 lines
4.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""把一张单据的附件打成一个 ZIP 供界面「全部下载」。
流程详情右侧那块附件面板列的是 ``oa_attachment`` 里挂在某个 job 上、且不属于
批注 / 审批意见随附文件的那几条。这里按完全一样的口径取,避免"面板上有 6 份、
打出来 7 份"或漏掉某一份。
ZIP 在内存里拼好再回:OA 场景下这一面板按单据来,几十份几 MB 的附件是常态,
几百 MB 的单据不该为此把 worker 的内存吃穿。所以只要总字节超过 :data:`MAX_TOTAL_BYTES`
就回一条中文提示,让人改用逐份下载——这是"兜底"不是"常规路径"。
"""
from __future__ import annotations
import io
import zipfile
from typing import Iterable
from fastapi.responses import Response
from sqlalchemy import select
from sqlalchemy.orm import Session
from .. import models
from ..storage import StorageError, resolve_uri
from ..storage.http import content_disposition, storage_error
MAX_TOTAL_BYTES = 200 * 1024 * 1024
class BundleTooLarge(Exception):
"""这一单的附件合起来太大,不打整包。"""
def is_visible(db: Session, subject, user) -> bool:
"""这个人「看不看得见这一单」——与列表/关联字段那条口径同一套。
:func:`app.api.runtime._visible_work_filter` 把可见范围定成:自己发起的、
待办/已办里有这一单的、待阅/已阅里有这一单的,管理员全放。那是一条
SQLAlchemy 条件,留给列表拼 WHERE 用的;这里手上只有一行,用一条 UNION
拼出同一个并集,命中即停。
``creator_identity`` / ``identity`` 存的是登录账号,与 ``user.ref`` 同一口径。
"""
if user.is_admin:
return True
ref = user.ref
if str(getattr(subject, "creator_identity", "") or "") == ref or str(
getattr(subject, "creator", "") or ""
) == str(user.person_id):
return True
job = str(getattr(subject, "job", "") or "")
if not job:
return False
probe = (
select(models.Task.id).where(models.Task.job == job, models.Task.identity == ref)
.union_all(
select(models.TaskCompleted.id).where(
models.TaskCompleted.job == job, models.TaskCompleted.identity == ref
),
select(models.Read.id).where(models.Read.job == job, models.Read.identity == ref),
select(models.ReadCompleted.id).where(
models.ReadCompleted.job == job, models.ReadCompleted.identity == ref
),
)
)
return db.execute(probe.limit(1)).first() is not None
def safe_name(name: str, used: set[str]) -> str:
"""把附件名压成 ZIP 内的唯一条目名。
同名两份附件很常见(不同环节各传一版);ZIP 允许重名,但解包时会互相覆盖,
审批人就会以为少了一份。所以撞名时补 `` (2)``、`` (3)``。名字里的路径分隔符
也要去掉,免得解包时写出子目录。
"""
candidate = str(name or "attachment").replace("\\", "/").split("/")[-1].strip() or "attachment"
base, dot, extension = candidate.rpartition(".")
if not dot or not base:
base, extension = candidate, ""
suffix = f".{extension}" if extension else ""
index = 1
while candidate in used:
index += 1
candidate = f"{base} ({index}){suffix}"
used.add(candidate)
return candidate
def build(rows: Iterable[models.Attachment], title: str) -> Response:
"""从附件行建 ZIP 响应。只读存储、不改库、不留临时文件。"""
stream = io.BytesIO()
used: set[str] = set()
total = 0
with zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
for row in rows:
total += int(row.length or 0)
if total > MAX_TOTAL_BYTES:
raise BundleTooLarge()
try:
payload = resolve_uri(row.storage).read_bytes(row.storage)
except StorageError as exc:
raise storage_error(exc, "附件") from exc
archive.writestr(safe_name(row.name, used), payload)
filename = f"{title or '流程附件'}.zip"
return Response(
content=stream.getvalue(),
media_type="application/zip",
headers=content_disposition(filename),
)