files.py 24.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
import os
import shutil
import json
from datetime import datetime
from urllib.parse import quote
import logging

logger = logging.getLogger(__name__)

from fastapi import APIRouter, HTTPException, UploadFile, File, Body, Query, Depends
from fastapi.responses import FileResponse
from fastapi.concurrency import run_in_threadpool
from sqlalchemy import select, func, delete, false, or_

from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog, WikiKbInfo, WikiOaUser
from src.database.schemas import UploadInitRequest
from config import RAW_DIR, BASE_DIR
from src.services.identity.tokens import get_current_user, get_current_user_optional
from src.services.oa.deps import require_perm
from src.services.oa.kb_guard import assert_file_action, assert_kb_action, NEED_READ, NEED_WRITE
from src.services.oa.kb_paths import kb_raw_dir, kb_raw_rel
from src.services.oa.perms import assert_kb_writable, resolve_readable_kbs
from src.services.oa.kb_provision import get_base_kb
from src.tools.document_parser import (
    delete_office_preview_pdf,
    extract_text_from_file,
    get_existing_office_preview_pdf,
)

router = APIRouter()


async def _file_raw_base(session, db_file) -> str:
    """按文件归属库返回其 raw 根目录(kb_id 空=公共基础库 comm,回落 RAW_DIR)。"""
    if not getattr(db_file, "kb_id", None):
        return RAW_DIR
    kb = await session.get(WikiKbInfo, db_file.kb_id)
    if kb is None:
        return RAW_DIR
    return kb_raw_dir(kb)


async def _file_abs_path(session, db_file) -> str:
    """文件真实磁盘绝对路径:优先用持久化的 raw_path(含 uuid,允许同名),
    历史无 raw_path 的文件回落旧布局 <raw_base>/<format>/<name>。"""
    if getattr(db_file, "raw_path", None):
        return os.path.join(BASE_DIR, db_file.raw_path)
    raw_base = await _file_raw_base(session, db_file)
    return os.path.join(raw_base, db_file.format.lower(), db_file.name)

FILE_LIST_SORT_COLUMNS = {
    "time": WikiFile.created_at,
    "name": WikiFile.name,
    "size": WikiFile.size,
    "status": WikiFile.status,
    "format": WikiFile.format,
    "id": WikiFile.id,
    "word_count": func.coalesce(WikiFile.word_count, 0),
    # 「Token 消耗」按总消耗(LLM + VLM)排序,与列展示的 overall 口径一致;
    # coalesce 兜底 NULL,避免旧数据在 desc 排序时把空值顶到前面。
    "token": (func.coalesce(WikiFile.total_tokens, 0) + func.coalesce(WikiFile.vlm_total_tokens, 0)),
}
FILE_LIST_STATUSES = {"All", "Indexed", "Pending", "Ingesting", "Uploading", "Failed"}


def _normalize_file_list_options(
    sort_by: str = "time",
    sort_order: str = "desc",
    status: str = "All",
    file_format: str = "All",
) -> tuple[str, str, str, str]:
    normalized_sort_by = sort_by if sort_by in FILE_LIST_SORT_COLUMNS else "time"
    normalized_sort_order = sort_order.lower() if sort_order and sort_order.lower() in {"asc", "desc"} else "desc"
    normalized_status = status if status in FILE_LIST_STATUSES else "All"
    normalized_format = file_format.strip() if file_format and file_format.strip() else "All"
    return normalized_sort_by, normalized_sort_order, normalized_status, normalized_format


def _apply_file_list_filters(query, search: str = "", status: str = "All", file_format: str = "All"):
    if search:
        query = query.where(WikiFile.name.ilike(f"%{search}%"))
    if status != "All":
        query = query.where(WikiFile.status == status)
    if file_format != "All":
        query = query.where(WikiFile.format == file_format)
    return query


def _file_list_order_by(sort_by: str = "time", sort_order: str = "desc"):
    sort_column = FILE_LIST_SORT_COLUMNS.get(sort_by, WikiFile.created_at)
    if sort_order == "asc":
        order_by = [sort_column.asc()]
        stability_order = WikiFile.id.asc()
    else:
        order_by = [sort_column.desc()]
        stability_order = WikiFile.id.desc()
    if sort_by != "id":
        order_by.append(stability_order)
    return order_by


@router.get("/files")
async def list_files(
    page: int = 1,
    page_size: int = 10,
    search: str = "",
    sort_by: str = "time",
    sort_order: str = "desc",
    status: str = "All",
    file_format: str = Query("All", alias="format"),
    kb_id: str = Query("", alias="kbId"),
    kb_ids: str = Query("", alias="kbIds"),
    me: WikiOaUser = Depends(get_current_user_optional),
):
    """从数据库获取原始文件列表及其状态(按当前用户可读知识库收窄)。
    状态包括:Pending(待处理)、Ingesting(摄入中)、Indexed(已完成索引)、Failed(失败)。
    kbId 为空=可读库全集;指定则只看该库。kbIds(逗号分隔)=只看这批库(选某中心=其下全部库)。
    """
    sort_by, sort_order, status, file_format = _normalize_file_list_options(
        sort_by=sort_by,
        sort_order=sort_order,
        status=status,
        file_format=file_format,
    )
    logger.info(
        "获取文件列表: page=%s, page_size=%s, search='%s', sort_by=%s, sort_order=%s, status=%s, format=%s, kbId=%s",
        page, page_size, search, sort_by, sort_order, status, file_format, kb_id,
    )
    async with AsyncSessionLocal() as session:
        # 可读知识库收窄:base 文件 kb_id 为 NULL;登录用户按 resolve_readable_kbs,匿名仅 base。
        base_kb = await get_base_kb(session)
        base_id = base_kb.id if base_kb else None
        kb_name_map: dict[str, str] = {base_id: base_kb.kb_name} if base_kb else {}
        if me is not None:
            readable = await resolve_readable_kbs(me)
            readable_ids = {k.id for k in readable}
            kb_name_map.update({k.id: k.kb_name for k in readable})
            allow = []
            # base 文件 kb_id 为 NULL:解耦后仅在用户被授权公共基础库时可见(与授权模型一致)
            if base_id is not None and base_id in readable_ids:
                allow.append(WikiFile.kb_id.is_(None))
            if readable_ids:
                allow.append(WikiFile.kb_id.in_(readable_ids))
            kb_scope_cond = or_(*allow) if allow else false()
        else:
            readable_ids = set()
            kb_scope_cond = WikiFile.kb_id.is_(None)

        # 指定库过滤:kbIds(多库,选某中心=其下全部库)优先,其次 kbId(单库);base 需同时匹配 NULL
        explicit_cond = None
        target_ids = [i for i in (kb_ids.split(",") if kb_ids else []) if i.strip()]
        if not target_ids and kb_id:
            target_ids = [kb_id]
        if target_ids:
            conds = []
            include_base = base_id is not None and base_id in target_ids
            if include_base:
                conds.append(WikiFile.kb_id.is_(None))
            other_ids = [i for i in target_ids if i != base_id]
            if other_ids:
                conds.append(WikiFile.kb_id.in_(other_ids))
            explicit_cond = or_(*conds) if conds else false()

        def _scoped(stmt):
            stmt = stmt.where(kb_scope_cond)
            if explicit_cond is not None:
                stmt = stmt.where(explicit_cond)
            return stmt

        query = _scoped(_apply_file_list_filters(select(WikiFile), search, status, file_format))

        count_query = select(func.count()).select_from(query.subquery())
        total_result = await session.execute(count_query)
        total_count = total_result.scalar() or 0

        formats_query = _scoped(_apply_file_list_filters(
            select(WikiFile.format).distinct(),
            search=search,
            status=status,
            file_format="All",
        )).order_by(WikiFile.format.asc())
        formats_result = await session.execute(formats_query)
        format_options = [fmt for fmt in formats_result.scalars().all() if fmt]

        query = query.order_by(*_file_list_order_by(sort_by, sort_order)).offset((page - 1) * page_size).limit(page_size)
        result = await session.execute(query)
        db_files = result.scalars().all()

        # 上传用户名映射(本页文件的 uploaded_by → 姓名)
        uploader_ids = {f.uploaded_by for f in db_files if f.uploaded_by}
        uploader_map: dict[str, str] = {}
        if uploader_ids:
            urows = (
                await session.execute(
                    select(WikiOaUser.id, WikiOaUser.display_name).where(WikiOaUser.id.in_(uploader_ids))
                )
            ).all()
            uploader_map = {uid: dn for uid, dn in urows}

    files_list = []
    for db_file in db_files:
        name = db_file.name
        ext = db_file.format or (os.path.splitext(name)[1].lstrip(".").upper() or "TXT")

        size_raw = db_file.size or 0
        if size_raw < 1024 * 1024:
            size_str = f"{size_raw / 1024:.1f} KB"
        else:
            size_str = f"{size_raw / (1024*1024):.1f} MB"

        frontend_meta = {}
        if db_file.status == "Indexed" and db_file.ingest_time:
            frontend_meta = {
                "total_tokens": db_file.total_tokens or 0,
                "input_tokens": db_file.input_tokens or 0,
                "output_tokens": db_file.output_tokens or 0,
                "cached_input_tokens": db_file.cached_input_tokens or 0,
                "vlm_total_tokens": db_file.vlm_total_tokens or 0,
                # 前端「Token 消耗」列展示口径:LLM + VLM 总消耗。
                "overall_total_tokens": (db_file.total_tokens or 0) + (db_file.vlm_total_tokens or 0),
                "ingest_mode": db_file.ingest_mode or "",
                "ingest_duration": str(db_file.ingest_duration or "0"),
                "ingest_time": db_file.ingest_time.strftime("%Y-%m-%d %H:%M:%S") if db_file.ingest_time else ""
            }

        created_at = db_file.created_at or datetime.now()
        file_kb_id = db_file.kb_id or base_id
        files_list.append({
            "id": db_file.id,
            "name": name,
            "time": created_at.strftime("%Y-%m-%d"),
            "full_time": created_at.strftime("%Y-%m-%d %H:%M:%S"),
            "format": ext,
            "size": size_str,
            "size_raw": size_raw,
            "word_count": db_file.word_count or 0,
            "status": db_file.status,
            "error_message": db_file.error_message,
            "kb_id": file_kb_id,
            "kb_name": kb_name_map.get(file_kb_id, ""),
            "uploaded_by_name": uploader_map.get(db_file.uploaded_by, "") if db_file.uploaded_by else "",
            "meta": frontend_meta,
        })
    return {
        "files": files_list,
        "total": total_count,
        "page": page,
        "page_size": page_size,
        "filter_options": {
            "formats": format_options,
        },
    }


@router.post("/upload/init")
async def upload_init(payload: UploadInitRequest, me: WikiOaUser = Depends(require_perm("wiki:file:upload"))):
    """分步上传第一步:批量分配 UUID(允许同名上传)。

    需指定目标知识库 kbId(空=公共基础库 comm)。落库前双层校验:
    角色须有 wiki:file:upload 按钮权限(require_perm),且当前用户对该库为 owner(可写)。
    同名文件不再拦截——每个文件分配独立 uuid,落盘名含 uuid 后缀,天然不撞。
    """
    logger.info(f"初始化文件上传,共 {len(payload.files)} 个文件, kbId={payload.kbId}")
    mapping = {}
    errors = {}
    async with AsyncSessionLocal() as session:
        # 解析目标库(空=comm 公共基础库),并做 owner 写权限校验
        if payload.kbId:
            kb = await session.get(WikiKbInfo, payload.kbId)
            if kb is None or kb.del_flag != 0:
                raise HTTPException(status_code=404, detail="目标知识库不存在")
        else:
            kb = await get_base_kb(session)
        if kb is None:
            raise HTTPException(status_code=400, detail="知识库未初始化,请联系管理员")
        await assert_kb_action(me, kb, NEED_WRITE)  # Reader/无权 → 403 权限不足
        target_kb_id = kb.id

        for f in payload.files:
            ext = os.path.splitext(f.name)[1].lstrip(".").upper() or "TXT"
            db_file = WikiFile(
                name=f.name,
                format=ext,
                size=0,
                word_count=0,
                status="Uploading",
                kb_id=target_kb_id,
                uploaded_by=me.id,
            )
            session.add(db_file)
            await session.flush()
            mapping[f.name] = db_file.id
        await session.commit()
    return {"mapping": mapping, "errors": errors}


@router.post("/upload/{file_id}")
async def upload_file_chunk(
    file_id: str,
    file: UploadFile = File(...),
    me: WikiOaUser = Depends(require_perm("wiki:file:upload")),
):
    """分步上传第二步:根据 UUID 传输具体文件,异步流式落盘(落盘名含 uuid,允许同名)。"""
    logger.info(f"接收文件上传: file_id={file_id}, filename={file.filename}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()

        if not db_file:
            raise HTTPException(status_code=404, detail="File init record not found.")
        if db_file.status != "Uploading":
            raise HTTPException(status_code=400, detail="File is not in Uploading state.")
        # owner 写权限(Reader/无权 → 403 权限不足)
        await assert_file_action(session, me, db_file, NEED_WRITE)

        # 归属库的 raw 根(绝对 + 项目根相对),落盘名加 uuid 后缀避免同名互相覆盖
        kb = await session.get(WikiKbInfo, db_file.kb_id) if db_file.kb_id else await get_base_kb(session)
        raw_base = kb_raw_dir(kb) if kb else RAW_DIR
        raw_rel_base = kb_raw_rel(kb) if kb else os.path.relpath(RAW_DIR, BASE_DIR).replace("\\", "/")
        fmt = db_file.format.lower()
        stem, ext = os.path.splitext(db_file.name)
        disk_name = f"{stem}_{db_file.id}{ext}"
        file_dir = os.path.join(raw_base, fmt)
        os.makedirs(file_dir, exist_ok=True)
        file_path = os.path.join(file_dir, disk_name)
        # 持久化真实落盘路径(项目根相对,POSIX),预览/下载/删除/摄入摄出唯一真相源
        db_file.raw_path = f"{raw_rel_base}/{fmt}/{disk_name}"

        def save_upload_file(upload_file, path):
            with open(path, "wb") as buffer:
                shutil.copyfileobj(upload_file.file, buffer)

        await run_in_threadpool(save_upload_file, file, file_path)

        file_size = os.path.getsize(file_path)
        word_count = 0
        logger.info(
            "[Upload] File saved; skip upload-time text extraction: file_id=%s, name=%s, size=%s",
            file_id,
            file.filename,
            file_size,
        )

        db_file.size = file_size
        db_file.word_count = word_count
        db_file.status = "Pending"

        log = WikiOperationLog(
            file_id=file_id,
            file_name=file.filename,
            operation="UPLOAD_COMPLETED",
            details=json.dumps({"size": file_size, "word_count": word_count}, ensure_ascii=False)
        )
        session.add(log)
        await session.commit()

    logger.info(f"文件上传完成: {file.filename}, size={file_size}, word_count={word_count}")
    return {
        "status": "success",
        "file_id": file_id,
        "file_status": "Pending",
        "size": file_size,
        "word_count": word_count,
    }


@router.delete("/files/{file_id}")
async def delete_file(file_id: str, me: WikiOaUser = Depends(require_perm("wiki:file:remove"))):
    """根据 ID 从数据库和磁盘彻底删除文件(owner 可写库才允许)。"""
    logger.info(f"请求删除文件: file_id={file_id}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()
        if not db_file:
            raise HTTPException(status_code=404, detail="File not found")
        await assert_file_action(session, me, db_file, NEED_WRITE)  # Reader/无权 → 403
        if db_file.status not in ["Pending", "Failed"]:
            raise HTTPException(status_code=400, detail="只有待处理或失败的文件才能删除!")

        name = db_file.name
        file_path = await _file_abs_path(session, db_file)
        file_dir = os.path.dirname(file_path)
        if os.path.exists(file_path):
            os.remove(file_path)
        if os.path.splitext(name)[1].lower() in (".ppt", ".pptx"):
            delete_office_preview_pdf(file_path, file_id)
        if os.path.exists(file_dir) and not os.listdir(file_dir):
            os.rmdir(file_dir)

        # 先写入 DELETE 日志(WikiFile 删除后 ON DELETE SET NULL 会将日志的 file_id 置为 NULL)
        log = WikiOperationLog(
            file_id=file_id,
            file_name=name,
            operation="DELETE",
            details=json.dumps({"deleted_from": "disk and db"}, ensure_ascii=False)
        )
        session.add(log)
        # 显式删除关联 pages(ForeignKey CASCADE 会处理,显式删除保证兼容性)
        await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == file_id))
        await session.delete(db_file)
        await session.commit()

    logger.info(f"文件已删除: {name} (id={file_id})")
    return {"status": "success"}


@router.post("/files/batch_delete")
async def batch_delete_files(data: dict = Body(...), me: WikiOaUser = Depends(require_perm("wiki:file:batchRemove"))):
    """根据 ids 批量从数据库和磁盘彻底删除文件(逐个校验对所属库的 owner 写权限)。"""
    ids = data.get("ids", [])
    if not ids:
        raise HTTPException(status_code=400, detail="ids 不能为空")
    logger.info(f"请求批量删除文件: ids={ids}")

    deleted_count = 0
    errors = []
    async with AsyncSessionLocal() as session:
        for fid in ids:
            result = await session.execute(select(WikiFile).where(WikiFile.id == fid))
            db_file = result.scalar_one_or_none()
            if not db_file:
                errors.append(f"id={fid}: 未找到")
                continue
            try:
                await assert_file_action(session, me, db_file, NEED_WRITE)
            except HTTPException as he:
                errors.append(f"{db_file.name}: {he.detail}")
                continue
            if db_file.status not in ["Pending", "Failed"]:
                errors.append(f"{db_file.name}: 只有待处理或失败的文件才能删除")
                continue
            try:
                file_path = await _file_abs_path(session, db_file)
                file_dir = os.path.dirname(file_path)
                if os.path.exists(file_path):
                    os.remove(file_path)
                if os.path.splitext(db_file.name)[1].lower() in (".ppt", ".pptx"):
                    delete_office_preview_pdf(file_path, fid)
                if os.path.exists(file_dir) and not os.listdir(file_dir):
                    os.rmdir(file_dir)

                log = WikiOperationLog(
                    file_id=fid,
                    file_name=db_file.name,
                    operation="DELETE",
                    details=json.dumps({"batch": True}, ensure_ascii=False)
                )
                session.add(log)
                await session.execute(delete(WikiFilePage).where(WikiFilePage.file_id == fid))
                await session.delete(db_file)
                deleted_count += 1
                logger.info(f"批量删除: 已删除文件 {db_file.name} (id={fid})")
            except Exception as e:
                logger.error(f"批量删除文件失败 [{db_file.name}]: {e}")
                errors.append(f"{db_file.name}: 删除失败 {str(e)}")
        await session.commit()

    if errors and deleted_count == 0:
        raise HTTPException(status_code=400, detail="批量删除失败: " + "; ".join(errors))
    return {"status": "success", "deleted_count": deleted_count, "errors": errors or None}


@router.get("/files/view/{file_id}")
async def view_file(file_id: str, me: WikiOaUser = Depends(get_current_user)):
    """根据 ID 预览本地原始文件内容(需对所属库有访问权限,Reader 可预览)。"""
    logger.info(f"请求预览本地原始文件: file_id={file_id}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()
        if not db_file:
            raise HTTPException(status_code=404, detail="File not found")
        await assert_file_action(session, me, db_file, NEED_READ)  # 无权 → 403
        file_path = await _file_abs_path(session, db_file)

    logger.info(
        "[Preview] 原始文件预览请求: file_id=%s, name=%s, path=%s",
        file_id,
        db_file.name,
        file_path,
    )
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found on disk")

    ext = os.path.splitext(db_file.name)[1].lower()
    if ext == '.pdf':
        logger.info("[Preview] 返回 PDF 原文件: file_id=%s, media_type=application/pdf", file_id)
        return FileResponse(file_path, media_type='application/pdf')
    if ext in ('.ppt', '.pptx'):
        preview_pdf_path = get_existing_office_preview_pdf(file_path, file_id)
        if not preview_pdf_path:
            logger.info(
                "[Preview] PPT/PPTX preview PDF missing: file_id=%s, name=%s, path=%s",
                file_id,
                db_file.name,
                file_path,
            )
            raise HTTPException(
                status_code=202,
                detail={
                    "type": "preview_status",
                    "preview_status": "missing",
                    "message": "预览 PDF 尚未生成,请稍后刷新或先发起摄入。",
                },
            )
        logger.info(
            "[Preview] Return cached PPT/PPTX PDF preview: file_id=%s, cache_path=%s, media_type=application/pdf",
            file_id,
            preview_pdf_path,
        )
        return FileResponse(preview_pdf_path, media_type='application/pdf')

    if ext in ('.xlsx', '.xls'):
        media_type = (
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            if ext == '.xlsx' else 'application/vnd.ms-excel'
        )
        logger.info("[Preview] 返回 Excel 原文件: file_id=%s, media_type=%s", file_id, media_type)
        return FileResponse(file_path, media_type=media_type)

    try:
        content = extract_text_from_file(file_path)
        return {"type": "text_preview", "content": content}
    except Exception as e:
        logger.error(f"提取文件内容失败 [{db_file.name}]: {e}")
        return {"type": "text_preview", "content": f"无法提取文件内容: {str(e)}"}


@router.get("/files/download/{file_id}")
async def download_file(file_id: str, me: WikiOaUser = Depends(require_perm("wiki:file:download"))):
    """根据 ID 下载本地原始文件(需对所属库有访问权限,Reader 可下载)。"""
    logger.info(f"请求下载本地原始文件: file_id={file_id}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(WikiFile).where(WikiFile.id == file_id))
        db_file = result.scalar_one_or_none()
        if not db_file:
            raise HTTPException(status_code=404, detail="File not found")
        await assert_file_action(session, me, db_file, NEED_READ)  # 无权 → 403
        file_path = await _file_abs_path(session, db_file)

    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found on disk")

    headers = {
        "Content-Disposition": f"attachment; filename={quote(db_file.name)}; filename*=utf-8''{quote(db_file.name)}"
    }
    return FileResponse(file_path, headers=headers)


@router.get("/files/{file_id}/wiki_links")
async def get_file_wiki_links(file_id: str):
    """查询指定文件生成的 Wiki 页面路径列表。"""
    logger.info(f"查询文件关联的 Wiki 链接: file_id={file_id}")
    async with AsyncSessionLocal() as session:
        result = await session.execute(
            select(WikiFilePage).where(WikiFilePage.file_id == file_id)
        )
        pages = result.scalars().all()
    links = [p.page_path for p in pages]
    return {"links": links}