From 1af86ae2575e4dd2b15eeba7314032893998dfcc Mon Sep 17 00:00:00 2001 From: Lan Date: Wed, 3 Jun 2026 04:05:52 +0800 Subject: [PATCH] feat: add admin text preview endpoint --- apps/admin/services.py | 28 ++++++++++++++++++++++++++++ apps/admin/views.py | 10 ++++++++++ 2 files changed, 38 insertions(+) diff --git a/apps/admin/services.py b/apps/admin/services.py index 9661263..be0986c 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -190,6 +190,34 @@ class FileService: else: return await self.file_storage.get_file_response(file_code) + async def preview_file(self, file_id: int, max_chars: int = 4000): + max_chars = min(max(max_chars, 1), 20000) + file_code = await FileCodes.filter(id=file_id).first() + if not file_code: + raise HTTPException(status_code=404, detail="文件不存在") + if file_code.text is None: + raise HTTPException(status_code=400, detail="仅文本分享支持预览") + + content = file_code.text + preview = content[:max_chars] + return { + "id": file_code.id, + "code": file_code.code, + "name": f"{file_code.prefix}{file_code.suffix}", + "type": "text", + "content": preview, + "length": len(content), + "previewLength": len(preview), + "preview_length": len(preview), + "truncated": len(content) > max_chars, + "maxChars": max_chars, + "max_chars": max_chars, + "createdAt": file_code.created_at, + "created_at": file_code.created_at, + "expiredAt": file_code.expired_at, + "expired_at": file_code.expired_at, + } + async def share_local_file(self, item): local_file = LocalFileClass(item.filename) if not await local_file.exists(): diff --git a/apps/admin/views.py b/apps/admin/views.py index f3242c7..5cdb01f 100644 --- a/apps/admin/views.py +++ b/apps/admin/views.py @@ -196,6 +196,16 @@ async def file_download( return file_content +@admin_api.get("/file/preview") +async def file_preview( + id: int, + maxChars: int = 4000, + file_service: FileService = Depends(get_file_service), +): + preview = await file_service.preview_file(id, maxChars) + return APIResponse(detail=preview) + + @admin_api.get("/local/lists") async def get_local_lists( local_file_service: LocalFileService = Depends(get_local_file_service),