From bf68e8dded3961a69c1c8be8fe8ab8e77c0c1569 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 7 Aug 2026 11:23:44 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8D=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E7=AE=A1=E7=90=86=E5=85=B1=E4=BA=AB=E5=89=AA=E8=B4=B4?= =?UTF-8?q?=E6=9D=BF=E6=A8=A1=E5=9D=97=E8=AF=AD=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/patch_admin_timeline_ui.py | 32 +++++++++------------------ tests/test_patch_admin_timeline_ui.py | 15 ++++++++++++- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/scripts/patch_admin_timeline_ui.py b/scripts/patch_admin_timeline_ui.py index 1e6d6f2..2ac4689 100644 --- a/scripts/patch_admin_timeline_ui.py +++ b/scripts/patch_admin_timeline_ui.py @@ -15,25 +15,13 @@ def rewrite(path: Path, text: str) -> None: def patch_file_manage(path: Path) -> bool: - text = path.read_text(encoding='utf-8') - old = text - if 'detailTimeline:It(s.timeline||[])' in text and 'fcbxTimelineCollapsed' not in text: - text = text.replace( - 'detailTimeline:It(s.timeline||[])}},nt=t=>', - 'detailTimeline:It(s.timeline||[]),fcbxTimelineCollapsed:!0}},nt=t=>', - 1, - ) - render_old = 'N(e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}' - render_new = 'N((e(b).fcbxTimelineCollapsed&&e(b).detailTimeline.filter(ga=>ga.key==="retrieved_event").length>3)?e(b).detailTimeline.filter((ga,Qa)=>ga.key!=="retrieved_event"||e(b).detailTimeline.filter(Ja=>Ja.key==="retrieved_event").indexOf(ga)<3):e(b).detailTimeline,(n,K)=>(p(),f("div",{key:`${n.key}-${K}`,class:"grid grid-cols-[auto_minmax(0,1fr)] gap-3"}' - if render_old in text and 'ga.key==="retrieved_event"' not in text: - text = text.replace(render_old, render_new, 1) - close_old = ']))),128))],2)])):j("",!0),l("section",kn,' - close_new = ']))),128)),e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length>3?(p(),f("button",{key:0,type:"button",class:o(["mt-3 rounded-lg border px-3 py-2 text-sm font-medium transition",[e(u)?"border-gray-600 text-gray-200 hover:bg-gray-700":"border-gray-200 text-gray-700 hover:bg-gray-50"]]),onClick:m[99]||(m[99]=n=>e(b).fcbxTimelineCollapsed=!e(b).fcbxTimelineCollapsed)},r(e(b).fcbxTimelineCollapsed?`展开全部取件记录(共 ${e(b).detailTimeline.filter(n=>n.key==="retrieved_event").length} 次)":"收起取件记录"),3)):j("",!0)],2)])):j("",!0),l("section",kn,' - if close_old in text and '展开全部取件记录' not in text: - text = text.replace(close_old, close_new, 1) - if text != old: - rewrite(path, text) - return True + """Do not mutate Vite's shared file-management bundle. + + It imports the clipboard chunk, which is also shared by the upload/download + service. Structural text replacement in a minified bundle is unsafe and can + invalidate the module graph. Lifecycle presentation is handled by the + standalone DOM script below instead. + """ return False @@ -49,7 +37,7 @@ def patch_clipboard(path: Path) -> bool: if not match: return False name = match.group('name') - replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}}''' + replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}},''' text = text[:match.start()] + replacement + text[match.end():] if text != old: rewrite(path, text) @@ -169,7 +157,9 @@ def main() -> None: if write_detail_collapse_script(theme): changed.append(str((assets / 'fcb-lifecycle-collapse-v3.js').relative_to(ASSETS_ROOT))) if not changed: - raise SystemExit('admin timeline/clipboard patch markers not found or already patched') + # The standalone lifecycle script is idempotently regenerated even when + # the clipboard bundle was already patched in a cached build layer. + return print('patched admin assets:', ', '.join(changed)) diff --git a/tests/test_patch_admin_timeline_ui.py b/tests/test_patch_admin_timeline_ui.py index d3baa41..b1f9cfa 100644 --- a/tests/test_patch_admin_timeline_ui.py +++ b/tests/test_patch_admin_timeline_ui.py @@ -1,6 +1,8 @@ +import tempfile import unittest +from pathlib import Path -from scripts.patch_admin_timeline_ui import build_lifecycle_script +from scripts.patch_admin_timeline_ui import build_lifecycle_script, patch_clipboard class AdminTimelinePatchTests(unittest.TestCase): @@ -11,6 +13,17 @@ class AdminTimelinePatchTests(unittest.TestCase): self.assertIn("展开全部取件记录", script) self.assertIn("row.style.overflow = 'visible'", script) + def test_clipboard_rewrite_keeps_module_declaration_separator(self): + source = '''const m=async(a,e={})=>{try{return!0}catch(r){return!1}},R=async(a,e={})=>{return a};export{m};''' + with tempfile.TemporaryDirectory() as temp_dir: + path = Path(temp_dir) / "clipboard-test.js" + path.write_text(source, encoding="utf-8") + + self.assertTrue(patch_clipboard(path)) + patched = path.read_text(encoding="utf-8") + + self.assertIn("}},R=async", patched) + if __name__ == "__main__": unittest.main() From 5427c187d4c0ea6effca540a0555546f9e0b7146 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 7 Aug 2026 11:33:27 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=90=9B=20=E5=81=9C=E6=AD=A2=E6=94=B9?= =?UTF-8?q?=E5=86=99=E5=85=B1=E4=BA=AB=E5=89=8D=E7=AB=AF=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/patch_admin_timeline_ui.py | 22 ++++++---------------- tests/test_patch_admin_timeline_ui.py | 19 ++++++------------- 2 files changed, 12 insertions(+), 29 deletions(-) diff --git a/scripts/patch_admin_timeline_ui.py b/scripts/patch_admin_timeline_ui.py index 2ac4689..3bebff0 100644 --- a/scripts/patch_admin_timeline_ui.py +++ b/scripts/patch_admin_timeline_ui.py @@ -26,22 +26,12 @@ def patch_file_manage(path: Path) -> bool: def patch_clipboard(path: Path) -> bool: - text = path.read_text(encoding='utf-8') - old = text - pattern = re.compile( - r'const (?P[A-Za-z_$][\w$]*)=async\(a,e=\{\}\)=>\{.*?\},' - r'(?=[A-Za-z_$][\w$]*=async\(a,e=\{\}\)=>\{)', - re.S, - ) - match = pattern.search(text) - if not match: - return False - name = match.group('name') - replacement = f'''const {name}=async(a,e={{}})=>{{const{{successMsg:t="复制成功",errorMsg:n="复制失败,请手动复制",showMsg:s=!0,notify:c}}=e,l=(r,d)=>{{s&&c?.(r,d)}},q=()=>{{try{{window.prompt("复制下面内容",a)}}catch{{}}}};try{{if(navigator.clipboard&&window.isSecureContext)try{{await navigator.clipboard.writeText(a);return l(t,"success"),!0}}catch{{}}const r=document.createElement("textarea");r.value=a,r.setAttribute("readonly","");r.className="fcbx-copy-fallback";r.style.cssText="position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1";document.body.appendChild(r);r.focus();r.select();r.setSelectionRange(0,r.value.length);let d=!1;try{{d=document.execCommand("copy")}}finally{{document.body.removeChild(r)}}if(d)return l(t,"success"),!0;q();l("已打开手动复制窗口","warning");return!1}}catch(r){{return console.error("复制失败:",r),q(),l(n,"error"),!1}}}},''' - text = text[:match.start()] + replacement + text[match.end():] - if text != old: - rewrite(path, text) - return True + """Never rewrite Vite's shared clipboard chunk after compilation. + + The source utility already implements Clipboard API, DOM and manual-copy + fallbacks. Rewriting a minified ESM module can invalidate every page that + imports it, including FileManageView. + """ return False diff --git a/tests/test_patch_admin_timeline_ui.py b/tests/test_patch_admin_timeline_ui.py index b1f9cfa..df2030c 100644 --- a/tests/test_patch_admin_timeline_ui.py +++ b/tests/test_patch_admin_timeline_ui.py @@ -1,8 +1,7 @@ -import tempfile -import unittest from pathlib import Path +import unittest -from scripts.patch_admin_timeline_ui import build_lifecycle_script, patch_clipboard +from scripts.patch_admin_timeline_ui import build_lifecycle_script, patch_clipboard, patch_file_manage class AdminTimelinePatchTests(unittest.TestCase): @@ -13,16 +12,10 @@ class AdminTimelinePatchTests(unittest.TestCase): self.assertIn("展开全部取件记录", script) self.assertIn("row.style.overflow = 'visible'", script) - def test_clipboard_rewrite_keeps_module_declaration_separator(self): - source = '''const m=async(a,e={})=>{try{return!0}catch(r){return!1}},R=async(a,e={})=>{return a};export{m};''' - with tempfile.TemporaryDirectory() as temp_dir: - path = Path(temp_dir) / "clipboard-test.js" - path.write_text(source, encoding="utf-8") - - self.assertTrue(patch_clipboard(path)) - patched = path.read_text(encoding="utf-8") - - self.assertIn("}},R=async", patched) + def test_shared_compiled_modules_are_not_rewritten(self): + placeholder = Path("unused.js") + self.assertFalse(patch_file_manage(placeholder)) + self.assertFalse(patch_clipboard(placeholder)) if __name__ == "__main__": From 07e362d341ae5b10d3f69f949f98d529ccc3e709 Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 7 Aug 2026 15:02:23 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E2=9C=A8=20=E9=85=8D=E7=BD=AE=E5=9B=9E?= =?UTF-8?q?=E6=94=B6=E7=AB=99=E9=BB=98=E8=AE=A4=E4=BF=9D=E7=95=99=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/admin/services.py | 38 +++++++++++++++++++++++++++++++-- core/config.py | 1 + core/settings.py | 1 + tests/test_recycle_bin.py | 44 +++++++++++++++++++++++++++++++++------ 4 files changed, 76 insertions(+), 8 deletions(-) diff --git a/apps/admin/services.py b/apps/admin/services.py index 7a61aae..51096bf 100644 --- a/apps/admin/services.py +++ b/apps/admin/services.py @@ -80,7 +80,7 @@ class FileService: "code", } - TRASH_DEFAULT_RETENTION_DAYS = 7 + TRASH_DEFAULT_RETENTION_DAYS = 30 TRASH_MAX_RETENTION_DAYS = 365 def __init__(self): @@ -118,7 +118,9 @@ class FileService: @classmethod def _trash_expiry(cls, now: datetime, retention_days: Optional[int]): if retention_days is None: - retention_days = cls.TRASH_DEFAULT_RETENTION_DAYS + retention_days = int( + getattr(settings, "trashRetentionDays", cls.TRASH_DEFAULT_RETENTION_DAYS) + ) if retention_days == 0: return None if not 1 <= retention_days <= cls.TRASH_MAX_RETENTION_DAYS: @@ -1726,6 +1728,7 @@ class FileService: class ConfigService: INT_FIELDS = { "adminSessionExpire", + "trashRetentionDays", "enableChunk", "errorCount", "errorMinute", @@ -1804,6 +1807,28 @@ class ConfigService: ) next_config["adminSessionExpire"] = session_expire + try: + trash_retention_days = int( + next_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS) + ) + except (TypeError, ValueError): + raise HTTPException( + status_code=400, + detail="trashRetentionDays 配置值格式错误", + ) + if not 1 <= trash_retention_days <= FileService.TRASH_MAX_RETENTION_DAYS: + raise HTTPException( + status_code=400, + detail="trashRetentionDays 必须是 1 到 365 个整天", + ) + next_config["trashRetentionDays"] = trash_retention_days + retention_changed = ( + "trashRetentionDays" in update_data + and trash_retention_days != int( + current_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS) + ) + ) + if int(next_config.get("storageLimit", 0)) < 0: raise HTTPException( status_code=400, @@ -1816,6 +1841,15 @@ class ConfigService: await KeyValue.update_or_create(key="settings", defaults={"value": next_config}) await refresh_settings() + if retention_changed: + retention_now = await get_now() + retention_expiry = FileService._trash_expiry(retention_now, trash_retention_days) + await FileCodes.filter( + is_trashed=True, + trash_purged_at__isnull=True, + trash_expires_at__isnull=False, + ).update(trash_expires_at=retention_expiry) + class LocalFileService: async def list_files(self): diff --git a/core/config.py b/core/config.py index 4c13f53..c7fe873 100644 --- a/core/config.py +++ b/core/config.py @@ -25,6 +25,7 @@ SETUP_CONFIG_FIELDS = { "max_save_seconds", "name", "openUpload", + "trashRetentionDays", "uploadCount", "uploadMinute", "uploadSize", diff --git a/core/settings.py b/core/settings.py index cf7b242..f7f7480 100644 --- a/core/settings.py +++ b/core/settings.py @@ -46,6 +46,7 @@ DEFAULT_CONFIG = { "admin_token": "", "jwt_secret": "", "adminSessionExpire": ADMIN_SESSION_EXPIRE_DEFAULT, + "trashRetentionDays": 30, "openUpload": 1, "uploadSize": 1024 * 1024 * 10, "allowed_file_types": ["*"], diff --git a/tests/test_recycle_bin.py b/tests/test_recycle_bin.py index f10a744..637450c 100644 --- a/tests/test_recycle_bin.py +++ b/tests/test_recycle_bin.py @@ -7,8 +7,9 @@ from tortoise import Tortoise from apps.base.models import FileCodes, ShareCodeReservations from apps.base.utils import CODE_LENGTH, get_random_code -from apps.admin.services import FileService +from apps.admin.services import ConfigService, FileService from core.settings import settings +from core.utils import get_now class FakeStorage: @@ -40,13 +41,44 @@ class RecycleBinTests(unittest.TestCase): item = await FileCodes.create(code="old", prefix="demo", suffix=".txt", file_path="share/data/demo", uuid_file_name="demo.txt", expired_count=-1) service = FileService() service._file_storage = FakeStorage() - trashed = await service.move_to_trash(item, reason="manual", retention_days=7) - self.assertTrue(trashed.is_trashed) - self.assertEqual(trashed.trash_reason, "manual") - self.assertIsNotNone(trashed.trash_expires_at) + settings.trashRetentionDays = 30 + default_now = await get_now() + trashed_default = await service.move_to_trash(item, reason="manual") + self.assertTrue(trashed_default.is_trashed) + self.assertEqual(trashed_default.trash_reason, "manual") + self.assertIsNotNone(trashed_default.trash_expires_at) + self.assertAlmostEqual( + (trashed_default.trash_expires_at - default_now).total_seconds(), + 30 * 86400, + delta=5, + ) self.assertTrue(FakeStorage.moved) - await service.purge_trashed_file(trashed) + permanent = await FileCodes.create(code="perm", prefix="perm", suffix=".txt", file_path="share/data/perm", uuid_file_name="perm.txt", expired_count=-1) + await service.move_to_trash(permanent, reason="manual", retention_days=0) + purged = await FileCodes.create(code="purged", prefix="purged", suffix=".txt", file_path="share/data/purged", uuid_file_name="purged.txt", expired_count=-1, is_trashed=True, trash_purged_at=await get_now()) + + original_refresh = __import__("apps.admin.services", fromlist=["refresh_settings"]).refresh_settings + async def fake_refresh(): + return None + module = __import__("apps.admin.services", fromlist=["refresh_settings"]) + module.refresh_settings = fake_refresh + try: + await ConfigService().update_config({"trashRetentionDays": 14}) + finally: + module.refresh_settings = original_refresh + + await trashed_default.refresh_from_db() + await permanent.refresh_from_db() + await purged.refresh_from_db() + self.assertAlmostEqual( + (trashed_default.trash_expires_at - await get_now()).total_seconds(), + 14 * 86400, + delta=5, + ) + self.assertIsNone(permanent.trash_expires_at) + self.assertIsNotNone(purged.trash_purged_at) + await service.purge_trashed_file(trashed_default) audit_record = await FileCodes.get(id=item.id) self.assertTrue(audit_record.is_trashed) self.assertIsNotNone(audit_record.trash_purged_at) From d21f39af9d8ebc2f38135b2667755cd9e96b312f Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 7 Aug 2026 15:13:53 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=90=9B=20=E8=A1=A5=E9=BD=90=E7=94=9F?= =?UTF-8?q?=E5=91=BD=E5=91=A8=E6=9C=9F=E6=82=AC=E6=B5=AE=E8=BE=B9=E6=A1=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/patch_admin_timeline_ui.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/patch_admin_timeline_ui.py b/scripts/patch_admin_timeline_ui.py index 3bebff0..e119c41 100644 --- a/scripts/patch_admin_timeline_ui.py +++ b/scripts/patch_admin_timeline_ui.py @@ -95,6 +95,7 @@ def build_lifecycle_script() -> str: if (card) { card.style.overflow = 'visible'; card.style.position = 'relative'; + card.style.borderTopWidth = '1px'; } row.onmouseenter = () => { row.style.zIndex = '2'; }; row.onmouseleave = () => { row.style.zIndex = '0'; };