support text direct downloads (#490)

## 合入说明

- 修复 `GET /share/select/` 文本分享直链错误走存储层导致“已删除/过期”的问题
- 文本分享返回 UTF-8 plain text 附件下载
- 补充回归测试,不影响现有文件下载与次数扣减逻辑

## 评估结论

有必要合入:master 仍复现该缺陷,改动小、无冲突、测试通过。
This commit is contained in:
Lan authored and GitHub committed 2026-07-21 14:52:36 +08:00
commit 59ed733f3a
2 files changed
+38 -1

No files matched your search

+13 -1
View File
@@ -4,13 +4,14 @@ import hashlib
import os
import uuid
from datetime import timedelta
from urllib.parse import unquote
from urllib.parse import quote, unquote
from typing import Optional, Tuple, Union
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
from pydantic import BaseModel, ValidationError
from starlette import status
from starlette.responses import Response
from tortoise.expressions import Case, F, Q, When
from apps.admin.dependencies import share_required_login
@@ -334,6 +335,17 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
assert isinstance(file_code, FileCodes)
if not await consume_file_usage(file_code):
return APIResponse(code=404, detail="文件已过期")
if file_code.text is not None:
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
return Response(
content=file_code.text,
media_type="text/plain",
headers={
"Content-Disposition": (
f"attachment; filename*=UTF-8''{quote(filename, safe='')}"
)
},
)
return await file_storage.get_file_response(file_code)
+25
View File
@@ -71,6 +71,7 @@ class ShareUsageSecurityTests(unittest.TestCase):
await self._assert_count_consumption_is_atomic()
await self._assert_time_expiration_and_usage_are_atomic()
await self._assert_download_url_is_single_use()
await self._assert_text_share_downloads_as_txt()
await self._assert_limited_files_do_not_expose_direct_urls()
await self._assert_metadata_counts_all_attempts()
finally:
@@ -156,6 +157,30 @@ class ShareUsageSecurityTests(unittest.TestCase):
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_text_share_downloads_as_txt(self):
record = await FileCodes.create(
code="text-download",
prefix="TAG",
text="hello, 文本直链",
expired_count=-1,
expired_at=None,
)
with patch.dict(views.storages, {"local": FakeStorage}):
response = await views.get_code_file(
code=record.code, ip="127.0.0.1"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.body.decode("utf-8"), record.text)
self.assertEqual(response.media_type, "text/plain")
self.assertEqual(
response.headers["content-disposition"],
"attachment; filename*=UTF-8''TAG.txt",
)
await record.refresh_from_db()
self.assertEqual(record.used_count, 1)
async def _assert_limited_files_do_not_expose_direct_urls(self):
record = await FileCodes.create(
code="proxy-only",