Merge pull request '实现浏览器下载管理和本地下载记录' (#11) from xhgit/browser-downloads into main
Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/11
This commit was merged in pull request #11.
This commit is contained in:
commit
69db334aae
8 files changed
+155
-13
No files matched your search
@@ -9,7 +9,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button></div>
|
||||
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button><button id="show-downloads">下载</button></div>
|
||||
<form id="address-form">
|
||||
<button type="button" data-action="back" aria-label="后退">←</button>
|
||||
<button type="button" data-action="forward" aria-label="前进">→</button>
|
||||
@@ -30,5 +30,10 @@
|
||||
<section><h1>书签</h1><ul id="bookmarks"></ul></section>
|
||||
<section><h1>浏览历史</h1><ul id="history"></ul></section>
|
||||
</main>
|
||||
<section id="download-panel" hidden>
|
||||
<h1>下载记录</h1>
|
||||
<button data-action="clearDownloads">清除下载记录</button>
|
||||
<ul id="download-list"></ul>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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; } }
|
||||
+51
-3
@@ -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
|
||||
|
||||
@@ -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<Library>
|
||||
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: [] })
|
||||
}
|
||||
+49
-3
@@ -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<number, BrowserWindowState>()
|
||||
const downloads = new Map<string, DownloadItem>()
|
||||
|
||||
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()
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 |
|
||||
| 消息管理 | 支持引用回复、搜索本机历史、收藏和本机删除。 |
|
||||
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史和隐私窗口,网页运行在独立会话中。 |
|
||||
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索、书签、历史、下载和隐私窗口,网页运行在独立会话中。 |
|
||||
|
||||
当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
|
||||
|
||||
|
||||
+5
-1
@@ -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 集成测试确认真实文件写入、状态记录和清除。
|
||||
@@ -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('<title>隔离测试站</title><h1>OK</h1>')
|
||||
})
|
||||
@@ -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')
|
||||
|
||||
Reference in new issue
Block a user