Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(config): 桌面快捷方式由配置页开关

longmeidaodd5dc21761df
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 94ea645eb..0d5819ab3 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -168,7 +168,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt
```
验收四项:菜单栏只出现一个 Peach 图标且 `status` 报「已加载」;`launchctl print` 的 pid 就是那个菜单栏进程;`pfctl -s nat` 列出 80 → 8900、443 → 8443 两条 rdr;两条 `/healthz` 都回 200。`peach.local` 换成本机 `[server].mdns_name` 的值。
-- 发布入口是 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 生成方形 Logo 与多尺寸 `.ico`,再构建单一 `dist/Peach/Peach.exe`;无参数运行托盘,`serve`/`migrate` 运行 CLI。桌面快捷方式由 `scripts/create_desktop_shortcut.ps1` 创建,自启动只由 `scripts/manage_tray_startup.ps1` 管理。
+- 发布入口是 `scripts/build_windows.ps1`:先用 `scripts/generate_brand_assets.py` 生成方形 Logo 与多尺寸 `.ico`,再构建单一 `dist/Peach/Peach.exe`;无参数运行托盘,`serve`/`migrate` 运行 CLI。桌面快捷方式和开机自启都在配置页的「开机自启」一组里开关,由 `src/peach/desktop_startup.py` 落盘;`scripts/manage_tray_startup.ps1` 只作发布包的排障入口。
- 对外测试包由 `.github/workflows/release.yml` 承担:`build_windows.ps1 -Standalone` 用 PyInstaller onedir 生成完整 Windows 程序目录,压缩后由不检出源码的消费任务运行 `scripts/smoke_desktop.py`。`v<__version__>` tag 与版本不一致会失败,通过制品验收才创建 GitHub 预发布并附 SHA256;`workflow_dispatch` 只生成和验收 artifact。macOS 独立包另列待办,源码菜单栏构建入口仍为 `build_macos_app.py`。
- 刷新源码运行态不要用 Computer Use 点托盘:`python scripts/restart_windows_tray.py` 按精确 EXE 路径找到 pystray 隐藏窗口、发送正常停止消息、等托盘自行关闭子服务,再静默启动并核对新托盘重新拥有两个服务;找不到唯一窗口或退出超时就拒绝,绝不强杀后另启。`--swap-from <暂存包>` 让它在旧托盘退出后、新托盘启动前顺手换掉二进制,那是整条链路上唯一一个目标文件没有进程持有的窗口;换生产二进制用下面那条入口,不要单独调它。
- 换掉生产托盘二进制走 `python scripts/deploy_windows_tray.py`,在主检出里用项目 venv 的 Python 跑:拒绝脏检出 → 按 HEAD 提交号在 `<数据根>/state/source-sync-build/<commit>/` 构建 → 让暂存包自己跑一次 `migrate status` → 停旧托盘、原地换 `dist/Peach/Peach.exe`(旧的留成 `Peach.pre-source-sync-<时间>.exe`)、起新托盘 → 用项目 CA 严格校验读生产 HTTPS 口的 `/healthz` 并核对版本号。结果打印成一份 JSON,`step` 说明停在哪一步。新托盘起不来或拿不到两个子服务时自动换回备份并重开旧托盘;`--staged <路径>` 复用已经打好的包、跳过构建。不要就地构建 `dist/Peach/`:运行中的托盘持有那个文件,PyInstaller 清目录会撞上 WinError 5。换生产入口本身仍要当场授权,脚本不代替那次授权。
diff --git a/frontend/src/islands/desktop-settings.tsx b/frontend/src/islands/desktop-settings.tsx
index 1201b639a..40fed4cbf 100644
--- a/frontend/src/islands/desktop-settings.tsx
+++ b/frontend/src/islands/desktop-settings.tsx
@@ -3,7 +3,7 @@ import { fieldsetTitle, setActionBusy, confirmModal, wireCollapse } from '@peach
import { icon } from '@peach/legacy/core';
import { apiSend, errorMessage } from '../api';
-export interface StartupState { available: boolean; enabled: boolean; silent: boolean; message: string }
+export interface StartupState { available: boolean; enabled: boolean; silent: boolean; message: string; desktop: boolean; desktop_message: string }
export interface UninstallState { available: boolean; full_available: boolean; message: string; data_root: string; directories: string[] }
function SettingCheck({ label, checked, disabled, change }: { label:string; checked:boolean; disabled:boolean; change(value:boolean):void }) {
@@ -18,13 +18,17 @@ function SettingToggle({ label, checked, disabled, change }: { label:string; che
export function StartupSettings({ startup, receipt }: { startup: StartupState; receipt(message: string): void }) {
const [enabled,setEnabled] = useState(startup.enabled);
const [silent,setSilent] = useState(startup.silent);
+ const [desktop,setDesktop] = useState(startup.desktop);
const [error,setError] = useState('');
const busy = useRef(false);
const button = useRef<HTMLButtonElement>(null);
+ // 桌面快捷方式只有 Windows 有,桌面上已经摆着另一份安装的图标时也不给动;两种情况后端
+ // 都在 desktop_message 里说了原因,所以这里按它有没有内容判禁用,不再自己判平台。
+ const desktopReady = startup.available && !startup.desktop_message;
async function save() {
if (busy.current) return;
busy.current = true; setActionBusy(button.current,true); setError('');
- try { await apiSend('/api/configuration/startup',{enabled,silent}); receipt('已保存开机自启'); }
+ try { await apiSend('/api/configuration/startup',{enabled,silent,desktop}); receipt('已保存开机自启'); }
catch (cause) { setError(errorMessage(cause)); }
finally { busy.current = false; setActionBusy(button.current,false); }
}
@@ -36,6 +40,8 @@ export function StartupSettings({ startup, receipt }: { startup: StartupState; r
<SettingToggle label="开机后启动 Peach" checked={enabled} disabled={!startup.available} change={setEnabled} />
<div class="configoption"><SettingToggle label="静默启动" checked={silent} disabled={!startup.available || !enabled} change={setSilent} />
<p class="confighelp">静默启动仅显示托盘,开机后启动 Peach 打开时生效。</p></div>
+ <div class="configoption"><SettingToggle label="在桌面创建快捷方式" checked={desktop} disabled={!desktopReady} change={setDesktop} />
+ <p class="confighelp">{startup.desktop_message || '双击图标打开 Peach 网页;卸载时一并移除。'}</p></div>
</div>
{startup.message && <p class="confighelp">{startup.message}</p>}
{error && <p class="configbad" role="alert">{error}</p>}
@@ -66,8 +72,8 @@ export function UninstallSettings({ uninstall }: { uninstall: UninstallState })
const [accepted,setAccepted] = useState('');
async function remove() {
await confirmModal({title:'卸载 Peach',danger:true,body:removeData
- ? '将退出 Peach,移除程序、开机自启、设置、本地数据库、观看记录、凭据和缓存。原始媒体文件保留。'
- : '将退出 Peach 并移除程序和开机自启。设置、本地数据库、观看记录与缓存保留。',
+ ? '将退出 Peach,移除程序、开机自启、桌面图标、设置、本地数据库、观看记录、凭据和缓存。原始媒体文件保留。'
+ : '将退出 Peach 并移除程序、开机自启和桌面图标。设置、本地数据库、观看记录与缓存保留。',
confirmLabel:'卸载 Peach',onConfirm:async () => {
const result = await apiSend<{message:string}>('/api/configuration/uninstall',{delete_data:removeData,confirmation:'卸载 Peach'});
setAccepted(result.message);
@@ -77,7 +83,7 @@ export function UninstallSettings({ uninstall }: { uninstall: UninstallState })
<div class="geist-fieldset-content">
<div class="configfieldset-heading">
<div dangerouslySetInnerHTML={{__html:fieldsetTitle('uninstallTitle','卸载 Peach')}} />
- {uninstall.available && <p class="confighelp">卸载会退出 Peach、移除程序和开机自启。原始媒体文件保留。</p>}
+ {uninstall.available && <p class="confighelp">卸载会退出 Peach、移除程序、开机自启和桌面图标。原始媒体文件保留。</p>}
</div>
<SettingCheck label="完全卸载:同时删除设置、本地数据库、观看记录、凭据和缓存" checked={removeData} disabled={!uninstall.full_available || !!accepted} change={setRemoveData} />
<DataDirectories data={uninstall} />
diff --git a/frontend/test/configuration.test.tsx b/frontend/test/configuration.test.tsx
index e2e157b1e..5ec06dbb9 100644
--- a/frontend/test/configuration.test.tsx
+++ b/frontend/test/configuration.test.tsx
@@ -34,7 +34,7 @@ const settle = async () => {
};
it('配置以通用媒体网络和维护分组,缺少通用选项时省略标题', () => {
- const {el}=mount({startup:{available:true,enabled:false,silent:true,message:''},peach_proxy:{mode:'direct',proxy_saved:false,needs_selection:false}});
+ const {el}=mount({startup:{available:true,enabled:false,silent:true,message:'',desktop:false,desktop_message:''},peach_proxy:{mode:'direct',proxy_saved:false,needs_selection:false}});
expect([...el.querySelectorAll('.configgroup')].map(e=>e.textContent)).toEqual(['通用','媒体','网络与访问','更新与维护']);
expect(el.querySelector('#peachProxy .configfieldset-heading #peachProxyTitle')).not.toBeNull();
expect(el.querySelector('#peachProxy .configfieldset-heading > .confighelp')?.textContent).toContain('共用此设置');
diff --git a/frontend/test/desktop-settings.test.tsx b/frontend/test/desktop-settings.test.tsx
index ff115e5fc..759d8963e 100644
--- a/frontend/test/desktop-settings.test.tsx
+++ b/frontend/test/desktop-settings.test.tsx
@@ -14,15 +14,17 @@ afterEach(()=>{document.body.replaceChildren();vi.unstubAllGlobals();});
it('自启保存实际选项,卸载默认保留数据',async()=>{
const fetch = vi.fn(async(_url:string,_init:RequestInit)=>({ok:true,json:async()=>({})}));vi.stubGlobal('fetch',fetch);
const host=document.createElement('div');document.body.append(host);
- await act(async()=>render(<><StartupSettings startup={{available:true,enabled:false,silent:true,message:''}} receipt={()=>{}} />
+ await act(async()=>render(<><StartupSettings startup={{available:true,enabled:false,silent:true,message:'',desktop:false,desktop_message:''}} receipt={()=>{}} />
<UninstallSettings uninstall={{available:true,full_available:true,message:'',data_root:'fixture',directories:[]}} /></>,host));
expect(host.querySelector('#uninstallPeach .configfieldset-heading #uninstallTitle')).not.toBeNull();
expect(host.querySelector('#uninstallPeach .configfieldset-heading > .confighelp')?.textContent).toContain('原始媒体文件保留');
const boxes=host.querySelectorAll<HTMLInputElement>('input');
- expect(host.querySelectorAll('[role="switch"]')).toHaveLength(2);
+ expect(host.querySelectorAll('[role="switch"]')).toHaveLength(3);
expect(host.querySelector('form button')?.textContent).toBe('保存配置');
expect(fetch).not.toHaveBeenCalled();
- expect(boxes[2]!.checked).toBe(false);
+ // 桌面快捷方式那颗开关排在静默启动之后,卸载的复选框因此退到第 4 个。
+ expect(boxes[3]!.checked).toBe(false);
+ expect(boxes[2]!.disabled).toBe(false);
expect(boxes[1]!.disabled).toBe(true);
expect(host.querySelector('[data-fieldset-type=error]')).not.toBeNull();
const summary=host.querySelector('summary')!;
@@ -33,7 +35,20 @@ it('自启保存实际选项,卸载默认保留数据',async()=>{
await act(async()=>{boxes[0]!.checked=true;boxes[0]!.dispatchEvent(new Event('change',{bubbles:true}));});
expect(boxes[1]!.disabled).toBe(false);
await act(async()=>{host.querySelector('form')!.dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));});
- expect(JSON.parse(String(fetch.mock.calls[0]![1].body))).toEqual({enabled:true,silent:true});
+ expect(JSON.parse(String(fetch.mock.calls[0]![1].body))).toEqual({enabled:true,silent:true,desktop:false});
+ render(null,host);
+});
+it('桌面快捷方式被别的安装占着时,那颗开关锁住并说出原因',async()=>{
+ // 只锁住这一颗。桌面上摆着另一份 Peach 的图标不该连开机自启都不让改,那一格自己还是好的。
+ const host=document.createElement('div');document.body.append(host);
+ const startup={available:true,enabled:true,silent:true,message:'',desktop:false,desktop_message:'桌面快捷方式属于另一份 Peach 安装'};
+ await act(async()=>render(<StartupSettings startup={startup} receipt={()=>{}} />,host));
+ const switches=host.querySelectorAll<HTMLInputElement>('[role="switch"]');
+ expect(switches[2]!.disabled).toBe(true);
+ expect(switches[0]!.disabled).toBe(false);
+ expect(host.querySelector('form button')?.hasAttribute('disabled')).toBe(false);
+ expect([...host.querySelectorAll('.confighelp')].map(node=>node.textContent))
+ .toContain('桌面快捷方式属于另一份 Peach 安装');
render(null,host);
});
it('随机无方向,首页偏好与其他排序分别解析',()=>{
diff --git a/scripts/create_desktop_shortcut.ps1 b/scripts/create_desktop_shortcut.ps1
deleted file mode 100644
index ff970726f..000000000
--- a/scripts/create_desktop_shortcut.ps1
+++ /dev/null
@@ -1,25 +0,0 @@
-$ErrorActionPreference = 'Stop'
-$ProjectRoot = Split-Path -Parent $PSScriptRoot
-$TrayExecutable = Join-Path $ProjectRoot 'dist\Peach\Peach.exe'
-$Desktop = [Environment]::GetFolderPath('Desktop')
-$ShortcutPath = Join-Path $Desktop 'Peach.lnk'
-
-if (-not (Test-Path -LiteralPath $TrayExecutable -PathType Leaf)) {
- throw "Built tray executable not found: $TrayExecutable"
-}
-
-$Shell = New-Object -ComObject WScript.Shell
-$Shortcut = $Shell.CreateShortcut($ShortcutPath)
-$Shortcut.TargetPath = $TrayExecutable
-$Shortcut.WorkingDirectory = Split-Path -Parent $TrayExecutable
-$Shortcut.Description = 'Peach'
-$Shortcut.IconLocation = "$TrayExecutable,0"
-$Shortcut.WindowStyle = 7
-$Shortcut.Save()
-
-[pscustomobject]@{
- Shortcut = $ShortcutPath
- Target = $Shortcut.TargetPath
- WorkingDirectory = $Shortcut.WorkingDirectory
- Icon = $Shortcut.IconLocation
-}
diff --git a/src/peach/desktop_startup.py b/src/peach/desktop_startup.py
index 003fd5a03..9927f9a56 100644
--- a/src/peach/desktop_startup.py
+++ b/src/peach/desktop_startup.py
@@ -116,6 +116,46 @@ def startup_directory() -> Path:
return Path(os.environ["APPDATA"]) / "Microsoft/Windows/Start Menu/Programs/Startup"
+#: 桌面的 known folder ID(`FOLDERID_Desktop`)。
+_DESKTOP_FOLDER_ID = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}"
+
+
+def desktop_directory() -> Path:
+ """本机桌面目录。Windows 走 known folder,不拼 `%USERPROFILE%\\Desktop`。
+
+ Windows 11 上启用 OneDrive 备份的机器把桌面重定向到
+ `%USERPROFILE%\\OneDrive\\Desktop`,`~/Desktop` 那个目录要么不存在,要么是个
+ 没人看的空壳——快捷方式放进去,用户在自己桌面上看不到任何东西。
+ """
+ if sys.platform != "win32":
+ return Path.home() / "Desktop"
+ import ctypes
+ buffer = ctypes.c_wchar_p()
+ guid = ctypes.create_string_buffer(16)
+ if ctypes.windll.ole32.CLSIDFromString(_DESKTOP_FOLDER_ID, guid) == 0 and \
+ ctypes.windll.shell32.SHGetKnownFolderPath(
+ guid, 0, None, ctypes.byref(buffer)) == 0:
+ try:
+ return Path(buffer.value)
+ finally:
+ ctypes.windll.ole32.CoTaskMemFree(buffer)
+ return Path(os.environ.get("USERPROFILE", Path.home())) / "Desktop"
+
+
+def desktop_entry(program: Path) -> tuple[Path, dict]:
+ """桌面快捷方式的路径与当前状态;属于另一份安装时不认领。
+
+ 文件名是给人看的 `Peach.lnk`,不带启动项那串安装身份哈希:桌面上并排两个
+ `Peach-3f2a…lnk` 谁也分不清哪个是哪个。代价是同一台机器上的第二份安装认不到这个
+ 图标,它会照实报「属于另一份 Peach 安装」,不覆盖。
+ """
+ path = desktop_directory() / "Peach.lnk"
+ current = shortcut("read", path)
+ if current["enabled"] and Path(current["target"]).resolve() != program.resolve():
+ raise ValueError("桌面快捷方式属于另一份 Peach 安装")
+ return path, current
+
+
def windows_entry(config, program: Path) -> tuple[Path, dict]:
directory = startup_directory()
legacy = directory / "Peach.lnk"
@@ -133,10 +173,34 @@ def windows_entry(config, program: Path) -> tuple[Path, dict]:
return path, current
+#: 桌面快捷方式只有 Windows 有。macOS 的等价物是 Finder 别名,得靠 osascript 造,
+#: 而 Dock 已经是那个平台放常用程序的地方。
+_NO_DESKTOP = "此系统未提供桌面快捷方式"
+
+
+def desktop_snapshot(config) -> dict:
+ """桌面快捷方式那一格的状态,自己一个 try。
+
+ 不跟启动项共用异常出口:桌面上摆着另一份安装的 `Peach.lnk` 只该让这个开关关掉并
+ 说出原因,不该把整个「开机自启」面板打成「状态未取得」,把还好着的两个开关一起锁住。
+ """
+ if sys.platform != "win32":
+ return {"desktop": False, "desktop_message": _NO_DESKTOP}
+ try:
+ program, _, _ = target(config)
+ _, entry = desktop_entry(program)
+ return {"desktop": entry["enabled"], "desktop_message": ""}
+ except (OSError, ValueError) as exc:
+ return {"desktop": False, "desktop_message": str(exc)}
+ except (KeyError, subprocess.TimeoutExpired):
+ return {"desktop": False, "desktop_message": "桌面快捷方式状态未取得"}
+
+
def snapshot(config=None) -> dict:
config = config or settings_file.load_config()
if sys.platform not in {"win32", "darwin"}:
- return {"available": False, "enabled": False, "silent": True, "message": "此系统未提供登录自启入口"}
+ return {"available": False, "enabled": False, "silent": True,
+ "message": "此系统未提供登录自启入口", **desktop_snapshot(config)}
try:
preference = json.loads((config.directory("state") / "desktop-startup.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
@@ -155,23 +219,41 @@ def snapshot(config=None) -> dict:
enabled = bool(entry.get("RunAtLoad", False))
silent = "--show" not in entry.get("ProgramArguments", []) if enabled else bool(preference.get("silent", True))
return {"available": program.is_file(), "enabled": enabled, "silent": silent,
- "message": "" if program.is_file() else "未找到本机托盘入口"}
+ "message": "" if program.is_file() else "未找到本机托盘入口", **desktop_snapshot(config)}
except (OSError, ValueError, KeyError, subprocess.TimeoutExpired):
- return {"available": False, "enabled": False, "silent": True, "message": "启动项状态未取得"}
+ return {"available": False, "enabled": False, "silent": True,
+ "message": "启动项状态未取得", **desktop_snapshot(config)}
-def save(config, *, enabled: bool, silent: bool, executable: Path | None = None) -> dict:
- if type(enabled) is not bool or type(silent) is not bool:
+def save(config, *, enabled: bool, silent: bool, desktop: bool, executable: Path | None = None) -> dict:
+ if type(enabled) is not bool or type(silent) is not bool or type(desktop) is not bool:
raise ValueError("启动选项必须为开或关")
+ if desktop and sys.platform != "win32":
+ raise ValueError(_NO_DESKTOP)
program, args, directory = target(config, executable=executable)
- if enabled and not program.is_file():
+ if (enabled or desktop) and not program.is_file():
raise ValueError("未找到本机托盘入口")
- args = [*args, "--silent" if silent else "--show"]
if sys.platform == "win32":
+ # 桌面图标固定 `--show`,跟登录自启的静默选项无关:用户是特意去点它的。托盘已经
+ # 在跑时 `main()` 拿不到单实例锁,`--show` 那一支正好打开网页,这跟点桌面图标该
+ # 发生的事是同一件。
+ try:
+ icon, existing = desktop_entry(program)
+ except ValueError:
+ # 桌面上的 `Peach.lnk` 是另一份安装的。要求开启就照实拒绝;要求关闭时它本来
+ # 就不是我们放的,跳过——不能因为它挡在那儿连「开机自启」这一格都存不下。
+ if desktop:
+ raise
+ else:
+ shortcut("write" if desktop else "remove", icon, target=str(program),
+ arguments=subprocess.list2cmdline([*args, "--show"]),
+ directory=str(directory), expected=existing.get("target", ""))
+ args = [*args, "--silent" if silent else "--show"]
path, existing = windows_entry(config, program)
shortcut("write" if enabled else "remove", path, target=str(program), arguments=subprocess.list2cmdline(args),
directory=str(directory), expected=existing.get("target", ""))
elif sys.platform == "darwin":
+ args = [*args, "--silent" if silent else "--show"]
path = Path.home() / "Library/LaunchAgents" / f"{MACOS_LAUNCH_AGENT_LABEL}.plist"
entry = plistlib.loads(path.read_bytes()) if path.is_file() else {}
if entry.get("ProgramArguments") and Path(entry["ProgramArguments"][0]).resolve() != program.resolve():
@@ -184,4 +266,5 @@ def save(config, *, enabled: bool, silent: bool, executable: Path | None = None)
else:
raise ValueError("此系统未提供登录自启入口")
atomic_write_text(config.directory("state") / "desktop-startup.json", json.dumps({"silent": silent}))
- return {"available": True, "enabled": enabled, "silent": silent, "message": ""}
+ return {"available": True, "enabled": enabled, "silent": silent, "message": "",
+ "desktop": desktop, "desktop_message": "" if sys.platform == "win32" else _NO_DESKTOP}
diff --git a/src/peach/desktop_uninstall.py b/src/peach/desktop_uninstall.py
index e8dbd1509..2a452cf01 100644
--- a/src/peach/desktop_uninstall.py
+++ b/src/peach/desktop_uninstall.py
@@ -129,7 +129,9 @@ def poll(tray) -> None:
if any(data.get(key) != value for key, value in checked.items()):
raise ValueError("配置已变更,请重新确认卸载")
shell = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32/WindowsPowerShell/v1.0/powershell.exe"
- desktop_startup.save(config, enabled=False, silent=True)
+ # 桌面图标和启动项都在数据根之外,`_SCRIPT` 的路径校验只认数据根里的东西,
+ # 列进 `files` 会被它 `exit 2`。卸载前先由这一步把两个 `.lnk` 都撤掉。
+ desktop_startup.save(config, enabled=False, silent=True, desktop=False)
process = subprocess.Popen([str(shell), "-NoProfile", "-NonInteractive", "-EncodedCommand",
base64.b64encode(_SCRIPT.encode("utf-16-le")).decode("ascii")],
stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index faeb26c78..de714df95 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -126,7 +126,8 @@ def save_startup(request: Request, body: dict = Body(...), _args=Depends(require
local_only(request)
same_origin(request)
try:
- return desktop_startup.save(settings_file.load_config(), enabled=body.get("enabled"), silent=body.get("silent"))
+ return desktop_startup.save(settings_file.load_config(), enabled=body.get("enabled"), silent=body.get("silent"),
+ desktop=body.get("desktop"))
except (ValueError, OSError) as exc:
raise HTTPException(400, str(exc)) from exc
diff --git a/tests/test_desktop_settings.py b/tests/test_desktop_settings.py
index 4a0d57f8a..66b081979 100644
--- a/tests/test_desktop_settings.py
+++ b/tests/test_desktop_settings.py
@@ -102,7 +102,11 @@ class DesktopSettingsTests(unittest.TestCase):
self.assertEqual(args, ['--data-root', str(self.data)])
self.assertEqual(program.parent, self.program)
with self.assertRaises(ValueError):
- desktop_startup.save(self.config, enabled='false', silent=True)
+ desktop_startup.save(self.config, enabled='false', silent=True, desktop=False)
+ # 三个开关一视同仁。`desktop` 缺省会静默删掉桌面图标,所以它不给默认值,
+ # 路由漏传就在这里变成 400,而不是替用户做决定。
+ with self.assertRaises(ValueError):
+ desktop_startup.save(self.config, enabled=False, silent=True, desktop=None)
def test_configuration_actions_require_local_origin_and_uninstall_confirmation(self):
from fastapi import FastAPI
@@ -131,6 +135,57 @@ class DesktopSettingsTests(unittest.TestCase):
{'enabled':False}, {'enabled':True,'target':str(self.root / 'Other.exe')}]), self.assertRaisesRegex(ValueError, '另一份'):
desktop_startup.windows_entry(self.config, self.program / 'Peach.exe')
+ @unittest.skipUnless(os.name == 'nt', 'Windows known folder')
+ def test_desktop_directory_comes_from_the_known_folder_not_the_home_path(self):
+ """桌面目录问 shell 要,不拼 `%USERPROFILE%\\Desktop`。
+
+ 开了 OneDrive 备份的 Windows 11 把桌面重定向到 `%USERPROFILE%\\OneDrive\\Desktop`,
+ 拼出来那个目录用户根本看不到。判据取 shell 自己的答案:`SHGetKnownFolderPath`
+ 一旦失败,函数会静默退回拼路径,只断言「返回了个存在的目录」是看不出来的。
+ """
+ shell = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/WindowsPowerShell/v1.0/powershell.exe'
+ result = subprocess.run(
+ [str(shell), '-NoProfile', '-NonInteractive', '-Command',
+ "[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);[Environment]::GetFolderPath('Desktop')"],
+ capture_output=True, text=True, encoding='utf-8', timeout=25,
+ creationflags=subprocess.CREATE_NO_WINDOW, check=True)
+ self.assertEqual(desktop_startup.desktop_directory(), Path(result.stdout.strip()))
+
+ @unittest.skipUnless(os.name == 'nt', 'Windows 原生快捷方式')
+ def test_desktop_shortcut_has_its_own_switch_and_yields_to_another_installation(self):
+ """桌面图标由第三个开关单独管,参数固定 `--show`,遇到别人的图标不覆盖。
+
+ `--show` 跟「静默启动」无关:静默只管开机那一次,桌面图标是用户特意去点的。托盘
+ 已经在跑时 `tray.main()` 拿不到单实例锁,`--show` 那一支正好打开网页。
+
+ 桌面上摆着另一份安装的 `Peach.lnk` 时,要求开启照实拒绝,要求关闭则跳过它——那个
+ 图标本来就不是这份安装放的,不能因为它挡在那儿连「开机自启」都存不下。
+ """
+ startup = self.root / 'startup'
+ startup.mkdir()
+ program = self.program / 'Peach.exe'
+ icon = self.root / 'Peach.lnk'
+ with patch.object(desktop_startup, 'desktop_directory', return_value=self.root), \
+ patch.object(desktop_startup, 'startup_directory', return_value=startup), \
+ patch.object(desktop_startup, 'target', return_value=(program, ['--data-root', str(self.data)], self.program)):
+ state = desktop_startup.save(self.config, enabled=False, silent=True, desktop=True)
+ self.assertTrue(state['desktop'])
+ self.assertTrue(icon.is_file(), sorted(item.name for item in self.root.iterdir()))
+ self.assertIn('--show', desktop_startup.shortcut('read', icon)['arguments'])
+ self.assertEqual(sorted(item.name for item in startup.iterdir()), [])
+ self.assertTrue(desktop_startup.desktop_snapshot(self.config)['desktop'])
+
+ other = self.program / 'Other.exe'
+ other.touch()
+ desktop_startup.shortcut('write', icon, target=str(other), directory=str(self.program), expected=str(program))
+ with self.assertRaisesRegex(ValueError, '另一份'):
+ desktop_startup.save(self.config, enabled=False, silent=True, desktop=True)
+ self.assertEqual(desktop_startup.desktop_snapshot(self.config),
+ {'desktop': False, 'desktop_message': '桌面快捷方式属于另一份 Peach 安装'})
+ desktop_startup.save(self.config, enabled=True, silent=True, desktop=False)
+ self.assertEqual(len(list(startup.iterdir())), 1)
+ self.assertTrue(icon.is_file())
+
def _shortcut_round_trip(self, name):
path = self.root / name
program = str(self.program / 'Peach.exe')
diff --git a/tests/test_frontend_build.py b/tests/test_frontend_build.py
index 6ba6a7268..75d09c7bb 100644
--- a/tests/test_frontend_build.py
+++ b/tests/test_frontend_build.py
@@ -61,6 +61,19 @@ class IslandBundleTests(unittest.TestCase):
self.assertTrue((ROOT / "web" / name.lstrip("/")).is_file(),
f"产物 import 的 {name} 在仓库里不存在")
+ def test_the_startup_switches_and_their_payload_are_in_the_shipped_bundle(self):
+ """「开机自启」那三颗开关的标签和它们发出去的键,判据落在产物上。
+
+ `web/dist/peach-ui.js` 是提交进 Git 的产物。改了 `frontend/src` 不重建,浏览器拿到
+ 的仍是旧的那一份,而 tsc 和 vitest 都只看源码,谁都不会红——只有扫产物这一条会。
+ """
+ for label in ("开机后启动 Peach", "静默启动", "在桌面创建快捷方式"):
+ self.assertIn(label, self.bundle,
+ f"产物里没有「{label}」,先跑 npm --prefix frontend run build")
+ payload = self.bundle[self.bundle.index('"/api/configuration/startup"'):][:240]
+ for key in ("enabled:", "silent:", "desktop:"):
+ self.assertIn(key, payload, f"保存开机自启没带上 {key}")
+
def test_the_route_that_serves_it_is_registered(self):
# 扫整个包而不是 `api.py` 一个文件:这条路由现在住在 `routes_pages.py`,
# 而它属于哪个模块是内部事,前端只关心它被注册了。
diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.js
index 1d72aa6c8..ee2dd32a4 100644
--- a/web/dist/peach-ui.js
+++ b/web/dist/peach-ui.js
@@ -923,19 +923,20 @@ function at({ label: e, checked: t, disabled: n, change: r }) {
});
}
function ot({ startup: e, receipt: t }) {
- let [n, r] = W(e.enabled), [i, a] = W(e.silent), [o, s] = W(""), c = q(!1), l = q(null);
- async function u() {
- if (!c.current) {
- c.current = !0, v(l.current, !0), s("");
+ let [n, r] = W(e.enabled), [i, a] = W(e.silent), [o, s] = W(e.desktop), [c, l] = W(""), u = q(!1), f = q(null), p = e.available && !e.desktop_message;
+ async function m() {
+ if (!u.current) {
+ u.current = !0, v(f.current, !0), l("");
try {
await B("/api/configuration/startup", {
enabled: n,
- silent: i
+ silent: i,
+ desktop: o
}), t("已保存开机自启");
} catch (e) {
- s(R(e));
+ l(R(e));
} finally {
- c.current = !1, v(l.current, !1);
+ u.current = !1, v(f.current, !1);
}
}
}
@@ -943,7 +944,7 @@ function ot({ startup: e, receipt: t }) {
class: "configfieldset",
"data-geist-fieldset": !0,
onSubmit: (e) => {
- e.preventDefault(), u();
+ e.preventDefault(), m();
},
children: [/* @__PURE__ */ J("div", {
class: "geist-fieldset-content",
@@ -953,39 +954,54 @@ function ot({ startup: e, receipt: t }) {
class: "configoptions",
role: "group",
"aria-labelledby": "startupTitle",
- children: [/* @__PURE__ */ J(at, {
- label: "开机后启动 Peach",
- checked: n,
- disabled: !e.available,
- change: r
- }), /* @__PURE__ */ J("div", {
- class: "configoption",
- children: [/* @__PURE__ */ J(at, {
- label: "静默启动",
- checked: i,
- disabled: !e.available || !n,
- change: a
- }), /* @__PURE__ */ J("p", {
- class: "confighelp",
- children: "静默启动仅显示托盘,开机后启动 Peach 打开时生效。"
- })]
- })]
+ children: [
+ /* @__PURE__ */ J(at, {
+ label: "开机后启动 Peach",
+ checked: n,
+ disabled: !e.available,
+ change: r
+ }),
+ /* @__PURE__ */ J("div", {
+ class: "configoption",
+ children: [/* @__PURE__ */ J(at, {
+ label: "静默启动",
+ checked: i,
+ disabled: !e.available || !n,
+ change: a
+ }), /* @__PURE__ */ J("p", {
+ class: "confighelp",
+ children: "静默启动仅显示托盘,开机后启动 Peach 打开时生效。"
+ })]
+ }),
+ /* @__PURE__ */ J("div", {
+ class: "configoption",
+ children: [/* @__PURE__ */ J(at, {
+ label: "在桌面创建快捷方式",
+ checked: o,
+ disabled: !p,
+ change: s
+ }), /* @__PURE__ */ J("p", {
+ class: "confighelp",
+ children: e.desktop_message || "双击图标打开 Peach 网页;卸载时一并移除。"
+ })]
+ })
+ ]
}),
e.message && /* @__PURE__ */ J("p", {
class: "confighelp",
children: e.message
}),
- o && /* @__PURE__ */ J("p", {
+ c && /* @__PURE__ */ J("p", {
class: "configbad",
role: "alert",
- children: o
+ children: c
})
]
}), /* @__PURE__ */ J("footer", {
class: "geist-fieldset-footer",
"data-geist-fieldset-footer": !0,
children: /* @__PURE__ */ J("button", {
- ref: l,
+ ref: f,
type: "submit",
class: "geist-button primary",
disabled: !e.available,
@@ -1014,7 +1030,7 @@ function ct({ uninstall: e }) {
await l({
title: "卸载 Peach",
danger: !0,
- body: t ? "将退出 Peach,移除程序、开机自启、设置、本地数据库、观看记录、凭据和缓存。原始媒体文件保留。" : "将退出 Peach 并移除程序和开机自启。设置、本地数据库、观看记录与缓存保留。",
+ body: t ? "将退出 Peach,移除程序、开机自启、桌面图标、设置、本地数据库、观看记录、凭据和缓存。原始媒体文件保留。" : "将退出 Peach 并移除程序、开机自启和桌面图标。设置、本地数据库、观看记录与缓存保留。",
confirmLabel: "卸载 Peach",
onConfirm: async () => {
let e = await B("/api/configuration/uninstall", {
@@ -1037,7 +1053,7 @@ function ct({ uninstall: e }) {
class: "configfieldset-heading",
children: [/* @__PURE__ */ J("div", { dangerouslySetInnerHTML: { __html: d("uninstallTitle", "卸载 Peach") } }), e.available && /* @__PURE__ */ J("p", {
class: "confighelp",
- children: "卸载会退出 Peach、移除程序和开机自启。原始媒体文件保留。"
+ children: "卸载会退出 Peach、移除程序、开机自启和桌面图标。原始媒体文件保留。"
})]
}),
/* @__PURE__ */ J(it, {