实现浏览器下载管理和本地下载记录

This commit is contained in:
xhgit committed 2026-11-13 19:23:20 +08:00
1 parent ae04cc9494
commit 9b8c2026ea
8 files changed
+155 -13

No files matched your search

+16 -3
View File
@@ -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: [] })
}