From 9b8c2026ea2f64b6c8b2edd8bdfe2633583fd39a Mon Sep 17 00:00:00 2001 From: xhgit Date: Fri, 13 Nov 2026 19:23:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E7=AE=A1=E7=90=86=E5=92=8C=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Desktop/browser/index.html | 7 ++++- Desktop/browser/style.css | 5 +++ Desktop/browser/ui.js | 54 +++++++++++++++++++++++++++++++-- Desktop/src/browser-library.ts | 19 ++++++++++-- Desktop/src/browser.ts | 52 +++++++++++++++++++++++++++++-- README.md | 2 +- docs/progress.md | 6 +++- tests/contacts-browser.test.mjs | 23 +++++++++++++- 8 files changed, 155 insertions(+), 13 deletions(-) diff --git a/Desktop/browser/index.html b/Desktop/browser/index.html index 09a17c6..3eb12fd 100644 --- a/Desktop/browser/index.html +++ b/Desktop/browser/index.html @@ -9,7 +9,7 @@
-
+
@@ -30,5 +30,10 @@

书签

    浏览历史

      + diff --git a/Desktop/browser/style.css b/Desktop/browser/style.css index b78977c..8d76870 100644 --- a/Desktop/browser/style.css +++ b/Desktop/browser/style.css @@ -23,4 +23,9 @@ input { flex: 1; min-width: 0; } #library li { display: flex; gap: 6px; align-items: start; margin-bottom: 6px; } #library li button:first-child { display: grid; flex: 1; text-align: left; white-space: normal; overflow-wrap: anywhere; } #library li span { font-size: 11px; opacity: .78; } +#download-panel { padding: 18px; } +#download-panel h1 { margin: 0 0 10px; font-size: 18px; } +#download-list { list-style: none; padding: 0; } +#download-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 8px; } +#download-list strong { overflow-wrap: anywhere; } @media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } } diff --git a/Desktop/browser/ui.js b/Desktop/browser/ui.js index ae279dd..6c5b175 100644 --- a/Desktop/browser/ui.js +++ b/Desktop/browser/ui.js @@ -4,6 +4,37 @@ const address = document.querySelector('#address') const status = document.querySelector('#status') const button = (action) => document.querySelector(`[data-action="${action}"]`) let current +let panel = 'library' + +function renderDownloads(entries) { + const rows = entries.map((item) => { + const row = document.createElement('li') + const name = document.createElement('strong') + const state = document.createElement('span') + name.textContent = item.name + const labels = { progressing: '下载中', paused: '已暂停', completed: '已完成', cancelled: '已取消', interrupted: '已中断' } + state.textContent = labels[item.state] ?? item.state + if (item.total > 0 && item.state === 'progressing') state.textContent += ' · ' + Math.floor(100 * item.received / item.total) + '%' + row.append(name, state) + function add(label, action) { + const button = document.createElement('button') + button.textContent = label + button.onclick = () => void command(action, item.id) + row.append(button) + } + if (item.state === 'progressing') add('暂停', 'downloadPause') + if (item.resumable) add('继续', 'downloadResume') + if (['progressing', 'paused'].includes(item.state)) add('取消', 'downloadCancel') + if (item.state === 'completed') add('在文件夹中显示', 'showDownload') + return row + }) + if (!rows.length) { + const empty = document.createElement('li') + empty.textContent = '暂无下载记录' + rows.push(empty) + } + document.querySelector('#download-list').replaceChildren(...rows) +} function renderEntries(selector, entries, removable) { const container = document.querySelector(selector) @@ -60,12 +91,16 @@ function render(state) { button('bookmark').disabled = !state.url button('bookmark').textContent = state.bookmarked ? '取消书签' : '添加书签' button('library').hidden = state.privateMode - button('library').setAttribute('aria-pressed', String(state.libraryMode)) - document.querySelector('#library').hidden = !state.libraryMode - if (state.libraryMode) { + document.querySelector('#show-downloads').hidden = state.privateMode + button('library').setAttribute('aria-pressed', String(state.libraryMode && panel === 'library')) + document.querySelector('#show-downloads').setAttribute('aria-pressed', String(state.libraryMode && panel === 'downloads')) + document.querySelector('#library').hidden = !(state.libraryMode && panel === 'library') + document.querySelector('#download-panel').hidden = !(state.libraryMode && panel === 'downloads') + if (state.libraryMode && panel === 'library') { renderEntries('#bookmarks', state.bookmarks, true) renderEntries('#history', state.history, false) } + if (state.libraryMode && panel === 'downloads') renderDownloads(state.downloads) status.textContent = state.error } @@ -84,6 +119,19 @@ for (const element of document.querySelectorAll('[data-action]')) { } } +function showPanel(next) { + if (current?.libraryMode && panel !== next) { + panel = next + render(current) + } else { + panel = next + void command('library') + } +} + +button('library').onclick = () => showPanel('library') +document.querySelector('#show-downloads').onclick = () => showPanel('downloads') + document.querySelector('#address-form').onsubmit = (event) => { event.preventDefault() const value = address.value diff --git a/Desktop/src/browser-library.ts b/Desktop/src/browser-library.ts index cb6042a..41d8b2d 100644 --- a/Desktop/src/browser-library.ts +++ b/Desktop/src/browser-library.ts @@ -4,7 +4,8 @@ import { readFileSync, renameSync, writeFileSync } from 'node:fs' import { join } from 'node:path' export type Entry = { id: string; url: string; title: string; time: number } -type Library = { bookmarks: Entry[]; history: Entry[] } +export type DownloadRecord = { id: string; name: string; path: string; state: 'completed' | 'cancelled' | 'interrupted'; time: number } +type Library = { bookmarks: Entry[]; history: Entry[]; downloads: DownloadRecord[] } let cache: Library | undefined const file = () => join(app.getPath('userData'), 'browser-library.json') @@ -13,9 +14,12 @@ export function library(): Library { if (cache) return cache try { const saved = JSON.parse(readFileSync(file(), 'utf8')) as Partial - cache = { bookmarks: parseEntries(saved.bookmarks), history: parseEntries(saved.history) } + cache = { bookmarks: parseEntries(saved.bookmarks), history: parseEntries(saved.history), + downloads: Array.isArray(saved.downloads) ? saved.downloads.slice(0, 150).filter((item) => + typeof item?.id === 'string' && typeof item.name === 'string' && typeof item.path === 'string' && + typeof item.time === 'number' && ['completed', 'cancelled', 'interrupted'].includes(item.state)) : [] } } catch { - cache = { bookmarks: [], history: [] } + cache = { bookmarks: [], history: [], downloads: [] } } return cache } @@ -64,3 +68,12 @@ export function removeBookmark(id: string) { export function clearHistory() { persist({ ...library(), history: [] }) } + +export function recordDownload(record: DownloadRecord) { + const previous = library() + persist({ ...previous, downloads: [record, ...previous.downloads].slice(0, 150) }) +} + +export function clearDownloads() { + persist({ ...library(), downloads: [] }) +} diff --git a/Desktop/src/browser.ts b/Desktop/src/browser.ts index 23907cd..e329713 100644 --- a/Desktop/src/browser.ts +++ b/Desktop/src/browser.ts @@ -1,8 +1,8 @@ import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, WebContentsView } from 'electron' -import type { Session } from 'electron' +import type { DownloadItem, Session } from 'electron' import { randomUUID } from 'node:crypto' import { join } from 'node:path' -import { clearHistory, library, removeBookmark, toggleBookmark, visit } from './browser-library' +import { clearDownloads, clearHistory, library, recordDownload, removeBookmark, toggleBookmark, visit } from './browser-library' const browserURL = 'xhchat://app/browser' const height = 102 @@ -19,6 +19,7 @@ type BrowserWindowState = { } const windows = new Map() +const downloads = new Map() export function website(value: string): URL | undefined { try { @@ -41,7 +42,7 @@ function address(value: string): URL | undefined { function state(browser: BrowserWindowState) { const contents = browser.active?.view.webContents - const collection = browser.privateMode ? { bookmarks: [], history: [] } : library() + const collection = browser.privateMode ? { bookmarks: [], history: [], downloads: [] } : library() return { privateMode: browser.privateMode, active: browser.active?.id, @@ -54,6 +55,13 @@ function state(browser: BrowserWindowState) { libraryMode: browser.libraryMode, bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()), ...collection, + downloads: browser.privateMode ? [] : [ + ...[...downloads].map(([id, item]) => ({ + id, name: item.getFilename(), state: item.isPaused() ? 'paused' : item.getState(), + received: item.getReceivedBytes(), total: item.getTotalBytes(), resumable: item.canResume(), + })), + ...collection.downloads, + ], } } @@ -188,6 +196,21 @@ function configureSites(sites: Session, privateMode: boolean) { return } item.setSaveDialogOptions({ title: '保存网页下载', buttonLabel: '保存' }) + const id = randomUUID() + downloads.set(id, item) + item.on('updated', updateNormalWindows) + item.once('done', (_event, result) => { + downloads.delete(id) + if (result === 'completed' || result === 'cancelled' || result === 'interrupted') { + try { + recordDownload({ id, name: item.getFilename(), path: item.getSavePath(), state: result, time: Date.now() }) + } catch { + if (browser.active) browser.active.error = '无法保存下载记录' + } + } + updateNormalWindows() + }) + updateNormalWindows() }) } @@ -280,6 +303,29 @@ export function registerBrowserHandlers(trusted: Session) { updateNormalWindows() break } + case 'downloadPause': + case 'downloadResume': + case 'downloadCancel': { + if (browser.privateMode || typeof value !== 'string') break + const item = downloads.get(value) + if (action === 'downloadPause' && item?.getState() === 'progressing') item.pause() + if (action === 'downloadResume' && item?.canResume()) item.resume() + if (action === 'downloadCancel') item?.cancel() + updateNormalWindows() + break + } + case 'showDownload': { + if (browser.privateMode || typeof value !== 'string') break + const item = library().downloads.find((entry) => entry.id === value && entry.state === 'completed') + if (item?.path) shell.showItemInFolder(item.path) + break + } + case 'clearDownloads': { + if (browser.privateMode) break + clearDownloads() + updateNormalWindows() + break + } case 'openEntry': { if (browser.privateMode || typeof value !== 'string') break const { bookmarks, history } = library() diff --git a/README.md b/README.md index 179207a..28f3e98 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ | 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | | 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 | | 消息管理 | 支持引用回复、搜索本机历史、收藏和本机删除。 | -| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史和隐私窗口,网页运行在独立会话中。 | +| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 | 当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) diff --git a/docs/progress.md b/docs/progress.md index fe39ca9..b80b314 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -21,7 +21,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg - 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。 - 阶段二与三还需分片附件、消息操作、群聊、多设备可信授权、加密备份与跨设备历史同步。两设备文字和小附件私聊已进入开发预览。 - 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。 -- 阶段五还需下载记录、逐站授权、反钓鱼及聊天联动。 +- 阶段五还需逐站授权、反钓鱼及聊天联动。 - 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。 ## 联系人和 Chromium 浏览器 @@ -62,3 +62,7 @@ Windows 与 Web 可发送带引用摘要的 MLS 文字消息。两端支持按 ## 浏览器书签和历史 Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多 250 条。书签支持添加、打开和移除。清除站点数据会同时清除历史。隐私窗口不读写书签或历史,隔离测试验证其访问不会出现在普通窗口。 + +## 浏览器下载管理 + +普通窗口下载支持保存对话框、进度、暂停、可恢复时继续、取消和完成后定位文件。最多保存 150 条记录,清除记录不删除已下载文件。Electron 集成测试确认真实文件写入、状态记录和清除。 diff --git a/tests/contacts-browser.test.mjs b/tests/contacts-browser.test.mjs index 9e8cf7e..9d14779 100644 --- a/tests/contacts-browser.test.mjs +++ b/tests/contacts-browser.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict' import { randomBytes } from 'node:crypto' -import { mkdtemp, rm } from 'node:fs/promises' +import { mkdtemp, readFile, rm } from 'node:fs/promises' import { createServer } from 'node:http' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -28,6 +28,12 @@ test('双端联系人实时同步,桌面浏览器独立分区与 UA', { timeou const requests = [] const local = createServer((request, response) => { requests.push({ path: request.url, userAgent: request.headers['user-agent'] }) + if (request.url === '/download') { + response.setHeader('Content-Type', 'application/octet-stream') + response.setHeader('Content-Disposition', 'attachment; filename=download-check.txt') + response.end('download-check') + return + } response.setHeader('Content-Type', 'text/html; charset=utf-8') response.end('隔离测试站

      OK

      ') }) @@ -93,6 +99,21 @@ test('双端联系人实时同步,桌面浏览器独立分区与 UA', { timeou await toolbar.getByRole('button', { name: '添加书签', exact: true }).click() await toolbar.getByRole('button', { name: '取消书签', exact: true }).waitFor() await toolbar.getByRole('button', { name: '书签与历史', exact: true }).click() + const savedFile = join(profile, 'download-check.txt') + await app.evaluate(({ session, webContents }, { url, savedFile }) => { + const sites = session.fromPartition('persist:xhchat-sites') + sites.once('will-download', (_event, item) => item.setSavePath(savedFile)) + const page = webContents.getAllWebContents().find((entry) => entry.getURL() === url + '/first') + if (!page) throw new Error('找不到下载来源标签页') + page.downloadURL(url + '/download') + }, { url, savedFile }) + await toolbar.getByRole('button', { name: '下载', exact: true }).click() + await toolbar.getByText('download-check.txt', { exact: true }).waitFor() + await toolbar.getByText('已完成', { exact: true }).waitFor() + assert.equal(await readFile(savedFile, 'utf8'), 'download-check') + await toolbar.getByRole('button', { name: '清除下载记录' }).click() + await toolbar.getByText('暂无下载记录').waitFor() + await toolbar.getByRole('button', { name: '书签与历史', exact: true }).click() await toolbar.locator('#bookmarks').getByText(url + '/first', { exact: true }).waitFor() await toolbar.locator('#history').getByText(url + '/first', { exact: true }).waitFor() const openedPrivate = app.waitForEvent('window') -- 2.54.0