From 9ffcacc158f77d5d7023ba9fad29de6910502a6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=92=96=E5=95=A1=E5=85=AB=E6=9D=AF?= <2062008467@qq.com> Date: Thu, 3 Dec 2026 10:39:06 +0800 Subject: [PATCH] 1.0.2 --- plugins/cafe-notice/CHANGELOG.md | 10 + plugins/cafe-notice/README.md | 11 +- plugins/cafe-notice/package.json | 2 +- plugins/cafe-notice/src-ztools/plugin.json | 2 +- .../src-ztools/preload/services.js | 516 +++++++++++++----- .../src-ztools/preload/sqlite-lite.js | 301 ++++++++++ 6 files changed, 712 insertions(+), 130 deletions(-) create mode 100644 plugins/cafe-notice/src-ztools/preload/sqlite-lite.js diff --git a/plugins/cafe-notice/CHANGELOG.md b/plugins/cafe-notice/CHANGELOG.md index e40d3133f..a2f7d5c83 100644 --- a/plugins/cafe-notice/CHANGELOG.md +++ b/plugins/cafe-notice/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.0.2 - 2026-12-03 + +### 修复 + +- 修复升级到 ZTools 3.3.0 后插件页报 `TypeError: Cannot read properties of undefined (reading 'notice')`:新版宿主把 Electron 固定到 35.0.0-alpha.2,该版本没有内置 `node:sqlite`,preload 顶层 `require('node:sqlite')` 抛 `No such built-in module` 后 `window.services` 从未赋值。通知库改由新增的纯 JS 只读读取器 `preload/sqlite-lite.js` 解析(支持 WAL 快照、溢出页、64 位整型) +- 兼容未升级的旧版 ZTools:宿主带 `node:sqlite`(Electron 36.7.3+,如 3.2.x 的 Electron 41)时仍优先走原生实现,缺失或打开失败才启用纯 JS 兜底,且只降级一次不会每轮抛错;三种引擎(原生 / 兜底 / 原生失败降级)对同一份真实通知库的解析结果已逐条比对一致 +- 本地存储由 SQLite 改为 JSON / JSONL:`history.jsonl` 追加写、`config.json` / `state.json` 分文件避免采集写入覆盖用户设置、`apps.json` 按 mtime 缓存;旧 `history.db` 自动并入新存储(只补缺失项,不覆盖),迁移不再依赖宿主是否有 sqlite +- 采集、旧库迁移、横幅接管恢复等启动副作用移入 `init()`,排在 `window.services` 赋值之后并逐段 try/catch:任一步失败只降级对应功能,不再让整个插件页拿到 undefined +- `getStatus()` 增加 `dbEngine` 字段(`native` / `lite`),排障时可直接看出当前用的是哪个读取引擎 + ## 1.0.1 - 2026-11-12 ### 修复 diff --git a/plugins/cafe-notice/README.md b/plugins/cafe-notice/README.md index 5c1650554..7ef948e85 100644 --- a/plugins/cafe-notice/README.md +++ b/plugins/cafe-notice/README.md @@ -8,6 +8,12 @@ ## 更新日志 +### v1.0.2 - 2026-12-03 +- 修复 ZTools 3.3.0 下打不开、控制台报 `Cannot read properties of undefined (reading 'notice')`:新版宿主把 Electron 固定到 35,`node:sqlite` 已不是内置模块,preload 顶层 `require` 失败导致 `window.services` 从未赋值。现在通知库改由内置的纯 JS 只读 SQLite 读取器解析(支持 WAL 快照与溢出页) +- 两版宿主都兼容:ZTools 3.2.x / 更早(Electron 41,自带 `node:sqlite`)仍走原生实现,3.3.0(Electron 35,无该模块)或原生打开失败时自动改用纯 JS 兜底,降级只发生一次;三种走法对同一份通知库的解析结果已逐条比对一致(`getStatus().dbEngine` 可看出当前引擎) +- 本地存储由 SQLite 改为 JSON / JSONL(`history.jsonl` 只追加),旧 `history.db` 自动并入新存储,只补缺失项、不覆盖新数据;迁移不依赖宿主是否有 sqlite +- 采集、迁移等启动副作用挪到 `window.services` 赋值之后并逐段兜底:任一步失败只降级对应功能,不再让整个插件页拿到 undefined + ### v1.0.1 - 2026-11-12 - 修复卡片通知的透明区域挡住鼠标点击的问题:卡片窗默认整窗穿透,只有卡片区域接收点击,卡片间隙、内边距与无卡片时的空窗都不再挡下方操作 @@ -52,14 +58,15 @@ npm run build # 产物输出到 src-ztools/dist(含浮层 overlay.html) ## 数据存储 -- 历史与配置存于本地 SQLite:`/cafe-notice/history.db`(notice / app_config / config 三张表) +- 数据存于 `/cafe-notice/`:`history.jsonl`(通知历史,只追加写)、`config.json`(用户配置)、`state.json`(采集游标/统计/选主锁)、`apps.json`(按应用设置) +- 旧版 SQLite 库 `history.db` 原样保留,首次启动新版本时无论宿主有没有 `node:sqlite` 都会自动并入新存储(只补缺失项、不覆盖) - 默认留存 30 天、上限 5000 条,可在配置页调整或一键清空 - 导出文件落在系统下载目录 - 除读取本机通知库与注册表外不联网 ## 技术栈 -Vue 3 + Vite + TypeScript、Element Plus(按需引入)、node:sqlite、Electron 浮层窗口(createBrowserWindow) +Vue 3 + Vite + TypeScript、Element Plus(按需引入)、纯 JS 只读 SQLite 读取器(`preload/sqlite-lite.js`,支持 WAL 快照与溢出页)、Electron 浮层窗口(createBrowserWindow) ## 许可证 diff --git a/plugins/cafe-notice/package.json b/plugins/cafe-notice/package.json index 634f2f50f..1857f9fda 100644 --- a/plugins/cafe-notice/package.json +++ b/plugins/cafe-notice/package.json @@ -1,6 +1,6 @@ { "name": "cafe-notice", - "version": "1.0.1", + "version": "1.0.2", "description": "A ZTools plugin", "type": "module", "scripts": { diff --git a/plugins/cafe-notice/src-ztools/plugin.json b/plugins/cafe-notice/src-ztools/plugin.json index abc36ad2e..32ba917e0 100644 --- a/plugins/cafe-notice/src-ztools/plugin.json +++ b/plugins/cafe-notice/src-ztools/plugin.json @@ -4,7 +4,7 @@ "title": "通知美化(弹幕/卡片)", "description": "把 Windows 系统通知重新展示为跨屏弹幕或角落卡片,支持按应用静音/接管原生横幅、历史留存与导出", "author": "咖啡八杯", - "version": "1.0.1", + "version": "1.0.2", "categories": ["productivity", "system"], "main": "dist/index.html", "preload": "preload/services.js", diff --git a/plugins/cafe-notice/src-ztools/preload/services.js b/plugins/cafe-notice/src-ztools/preload/services.js index d2f56e961..6ebf4e795 100644 --- a/plugins/cafe-notice/src-ztools/preload/services.js +++ b/plugins/cafe-notice/src-ztools/preload/services.js @@ -1,7 +1,6 @@ const fs = require('node:fs') const path = require('node:path') const os = require('node:os') -const { DatabaseSync } = require('node:sqlite') const CHANNEL = 'cafe-notice:notice' const INSTANCE = Math.random().toString(36).slice(2, 8) @@ -16,6 +15,16 @@ try { /* 无 IPC 时浮层收不到推送,历史与主窗口仍可用 */ } +// 读 Windows 通知库需要 SQLite。ZTools 3.3.0 的 Electron 35 没把 sqlite 编进内置模块 +// (require('node:sqlite') 直接抛 No such built-in module),所以优先用原生、不可用退回纯 JS。 +let DatabaseSync = null +try { + DatabaseSync = require('node:sqlite').DatabaseSync +} catch (e) { + DatabaseSync = null +} +const sqliteLite = require('./sqlite-lite') + const KNOWN_APPS = { 'com.qoder.app': 'Qoder', 'top.z-tools': 'ZTools', @@ -59,69 +68,91 @@ const DEFAULT_CONFIG = { listText: '' } -let db = null -function getDb() { - if (db) return db - const dir = path.join(window.ztools.getPath('userData'), 'cafe-notice') - fs.mkdirSync(dir, { recursive: true }) - db = new DatabaseSync(path.join(dir, 'history.db')) - db.exec(` - CREATE TABLE IF NOT EXISTS notice( - id INTEGER PRIMARY KEY, - aumid TEXT NOT NULL DEFAULT '', - title TEXT NOT NULL DEFAULT '', - body TEXT NOT NULL DEFAULT '', - logo TEXT NOT NULL DEFAULT '', - arrived_at INTEGER NOT NULL - ); - CREATE TABLE IF NOT EXISTS app_config( - aumid TEXT PRIMARY KEY, - name TEXT, - color TEXT, - mode TEXT, - muted INTEGER NOT NULL DEFAULT 0 - ); - CREATE TABLE IF NOT EXISTS config(key TEXT PRIMARY KEY, value TEXT); - `) +// —— 本地存储 —— +// 不要用 require('node:sqlite'):ZTools 3.3.0 把 Electron 固定到 35.0.0-alpha.2 +// (Node 22.9,且这版 Electron 没有把 sqlite 内置模块编进去),preload 一 require +// 就抛 "No such built-in module: node:sqlite",后面的 window.services 根本不会赋值, +// 渲染层于是报 Cannot read properties of undefined (reading 'notice')。 +// 这里改成纯 JS 存储:配置/应用设置写小 JSON,通知历史写只追加的 JSONL。 +const DATA_DIR = path.join(window.ztools.getPath('userData'), 'cafe-notice') +const CONFIG_FILE = path.join(DATA_DIR, 'config.json') +const STATE_FILE = path.join(DATA_DIR, 'state.json') +const APPS_FILE = path.join(DATA_DIR, 'apps.json') +const HISTORY_FILE = path.join(DATA_DIR, 'history.jsonl') +const LEGACY_DB = path.join(DATA_DIR, 'history.db') +const LEGACY_FLAG = path.join(DATA_DIR, '.legacy-imported') + +let dataDirReady = false +function ensureDataDir() { + if (dataDirReady) return + fs.mkdirSync(DATA_DIR, { recursive: true }) + dataDirReady = true +} + +function readJson(file, fallback) { try { - db.exec('alter table app_config add column suppress_banner INTEGER NOT NULL DEFAULT 0') + return JSON.parse(fs.readFileSync(file, 'utf-8')) } catch (e) { - /* 列已存在 */ + return fallback } - return db } -// Statement 不缓存会每次查询泄漏一个原生句柄(内存持续增长的来源) -const stmtCache = new Map() -function prep(sql) { - let s = stmtCache.get(sql) - if (!s) { - s = getDb().prepare(sql) - stmtCache.set(sql, s) +function writeJson(file, value) { + const text = JSON.stringify(value) + try { + fs.writeFileSync(file + '.tmp', text, 'utf-8') + fs.renameSync(file + '.tmp', file) + } catch (e) { + try { + fs.writeFileSync(file, text, 'utf-8') + } catch (e2) { + /* 磁盘异常时只保留内存态,不阻断通知采集 */ + } } - return s } +// 运行期状态(采集游标、统计、选主锁、横幅原值)与用户配置分文件存放, +// 避免每 1.5s 一次的采集写入顺手覆盖掉用户刚改的设置 +const STATE_KEYS = new Set(['lastFiletime', 'stats', 'collectorLock']) + function getConfig() { - const cfg = Object.assign({}, DEFAULT_CONFIG) - for (const row of prep('select key, value from config').all()) cfg[row.key] = row.value - return cfg + return Object.assign({}, DEFAULT_CONFIG, readJson(CONFIG_FILE, {}), readJson(STATE_FILE, {})) } function setConfig(patch) { - const stmt = prep( - 'insert into config(key, value) values(?, ?) on conflict(key) do update set value = excluded.value' - ) - for (const [key, value] of Object.entries(patch || {})) stmt.run(key, String(value)) + ensureDataDir() + const config = {} + const state = {} + for (const [key, value] of Object.entries(patch || {})) { + if (STATE_KEYS.has(key) || key.startsWith('bannerOrig:')) state[key] = String(value) + else config[key] = String(value) + } + if (Object.keys(config).length) writeJson(CONFIG_FILE, Object.assign(readJson(CONFIG_FILE, {}), config)) + if (Object.keys(state).length) writeJson(STATE_FILE, Object.assign(readJson(STATE_FILE, {}), state)) +} + +// apps.json 很小但被 resolveApp 高频读取:按 mtime 缓存,文件一改就失效 +let appsCache = { at: -1, map: {} } +function readApps() { + let mtime = 0 + try { + mtime = fs.statSync(APPS_FILE).mtimeMs + } catch (e) { + /* 还没生成 */ + } + if (appsCache.at !== mtime) appsCache = { at: mtime, map: readJson(APPS_FILE, {}) } + return appsCache.map } function getAppConfig(aumid) { - return prep('select * from app_config where aumid = ?').get(aumid) || null + return readApps()[aumid] || null } function setAppConfig(aumid, patch) { - const cur = getAppConfig(aumid) || {} - const next = { + ensureDataDir() + const map = readJson(APPS_FILE, {}) + const cur = map[aumid] || {} + map[aumid] = { name: patch.name !== undefined ? patch.name : cur.name || null, color: patch.color !== undefined ? patch.color : cur.color || null, mode: patch.mode !== undefined ? patch.mode : cur.mode || null, @@ -129,12 +160,160 @@ function setAppConfig(aumid, patch) { suppress_banner: patch.suppressBanner !== undefined ? (patch.suppressBanner ? 1 : 0) : cur.suppress_banner || 0 } - prep( - `insert into app_config(aumid, name, color, mode, muted, suppress_banner) values(?, ?, ?, ?, ?, ?) - on conflict(aumid) do update set name = excluded.name, color = excluded.color, - mode = excluded.mode, muted = excluded.muted, suppress_banner = excluded.suppress_banner` - ) - .run(aumid, next.name, next.color, next.mode, next.muted, next.suppress_banner) + writeJson(APPS_FILE, map) +} + +// 历史记录存 JSONL:新通知只追加一行,只有裁剪/清空时才整体重写 +let histRows = [] +let histIds = new Set() +let histMtime = -1 + +function loadHistory() { + let mtime = 0 + try { + mtime = fs.statSync(HISTORY_FILE).mtimeMs + } catch (e) { + /* 还没生成 */ + } + if (mtime === histMtime) return + const rows = [] + const ids = new Set() + let text = '' + if (mtime) { + try { + text = fs.readFileSync(HISTORY_FILE, 'utf-8') + } catch (e) { + text = '' + } + } + for (const line of text.split('\n')) { + if (!line) continue + try { + const row = JSON.parse(line) + if (row && row.id != null) { + rows.push(row) + ids.add(Number(row.id)) + } + } catch (e) { + /* 跳过损坏行 */ + } + } + histRows = rows + histIds = ids + histMtime = mtime +} + +function saveHistory() { + ensureDataDir() + try { + const text = histRows.map((row) => JSON.stringify(row)).join('\n') + fs.writeFileSync(HISTORY_FILE + '.tmp', histRows.length ? text + '\n' : '', 'utf-8') + fs.renameSync(HISTORY_FILE + '.tmp', HISTORY_FILE) + histMtime = fs.statSync(HISTORY_FILE).mtimeMs + } catch (e) { + /* 磁盘异常时只保留内存态 */ + } +} + +function appendHistory(row) { + ensureDataDir() + try { + fs.appendFileSync(HISTORY_FILE, JSON.stringify(row) + '\n', 'utf-8') + } catch (e) { + return false + } + histRows.push(row) + histIds.add(Number(row.id)) + try { + histMtime = fs.statSync(HISTORY_FILE).mtimeMs + } catch (e) { + histMtime = -1 + } + return true +} + +/** + * 旧版把数据存在 history.db(node:sqlite)。宿主若能加载 node:sqlite, + * 就把旧配置/应用设置/历史并进新存储(只补缺失项),并落标记避免重复迁移。 + * 当前 ZTools 3.3.0 的 Electron 35 没有该模块,这里会直接跳过。 + */ +function importLegacyStore() { + if (fs.existsSync(LEGACY_FLAG) || !fs.existsSync(LEGACY_DB)) return + // 用自带的只读实现,不依赖宿主是否有 node:sqlite, + // 这样升级到 Electron 35 的宿主也能把旧 history.db 迁进新存储 + const db = sqliteLite.open(LEGACY_DB) + if (!db) return + try { + const index = (table, name) => + table ? table.columns.findIndex((c) => c.toLowerCase() === name.toLowerCase()) : -1 + + const configTable = db.table('config') + if (configTable) { + const iKey = index(configTable, 'key') + const iValue = index(configTable, 'value') + const known = Object.assign({}, readJson(CONFIG_FILE, {}), readJson(STATE_FILE, {})) + if (iKey >= 0 && iValue >= 0) { + for (const row of configTable.rows) { + const key = String(row[iKey]) + if (known[key] === undefined && row[iValue] != null) setConfig({ [key]: String(row[iValue]) }) + } + } + } + + const appsTable = db.table('app_config') + if (appsTable) { + const map = readJson(APPS_FILE, {}) + const iAumid = index(appsTable, 'aumid') + const iName = index(appsTable, 'name') + const iColor = index(appsTable, 'color') + const iMode = index(appsTable, 'mode') + const iMuted = index(appsTable, 'muted') + const iBanner = index(appsTable, 'suppress_banner') + for (const row of appsTable.rows) { + const aumid = String(row[iAumid]) + if (!aumid || map[aumid]) continue + map[aumid] = { + name: (iName >= 0 && row[iName]) || null, + color: (iColor >= 0 && row[iColor]) || null, + mode: (iMode >= 0 && row[iMode]) || null, + muted: (iMuted >= 0 && Number(row[iMuted])) || 0, + suppress_banner: (iBanner >= 0 && Number(row[iBanner])) || 0 + } + } + writeJson(APPS_FILE, map) + } + + const noticeTable = db.table('notice') + if (noticeTable) { + const iId = index(noticeTable, 'id') + const iAumid = index(noticeTable, 'aumid') + const iTitle = index(noticeTable, 'title') + const iBody = index(noticeTable, 'body') + const iLogo = index(noticeTable, 'logo') + const iAt = index(noticeTable, 'arrived_at') + loadHistory() + const legacy = noticeTable.rows + .map((row) => ({ + id: Number(row[iId]), + aumid: String(row[iAumid] || ''), + title: String(row[iTitle] || ''), + body: String(row[iBody] || ''), + logo: String(row[iLogo] || ''), + arrived_at: Number(row[iAt]) + })) + .filter((row) => Number.isFinite(row.id) && Number.isFinite(row.arrived_at)) + .sort((a, b) => a.arrived_at - b.arrived_at) + for (const row of legacy) { + if (histIds.has(row.id)) continue + appendHistory(row) + } + } + + ensureDataDir() + fs.writeFileSync(LEGACY_FLAG, new Date().toISOString(), 'utf-8') + } catch (e) { + /* 迁移失败不影响新存储,下次启动再试 */ + } } function hashText(text) { @@ -176,10 +355,15 @@ function deriveName(aumid) { const { execFile } = require('node:child_process') function run(file, args) { return new Promise((resolve) => { - execFile(file, args, { windowsHide: true, timeout: 25000, encoding: 'buffer' }, (err, stdout, stderr) => { - const buf = stdout || Buffer.alloc(0) - resolve({ err, text: new TextDecoder('gbk').decode(buf), stderr: String(stderr || '') }) - }) + try { + execFile(file, args, { windowsHide: true, timeout: 25000, encoding: 'buffer' }, (err, stdout, stderr) => { + const buf = stdout || Buffer.alloc(0) + resolve({ err, text: new TextDecoder('gbk').decode(buf), stderr: String(stderr || '') }) + }) + } catch (e) { + // 沙箱/策略拦截时 execFile 会同步抛 EPERM,按「命令失败」处理,别让调用方拿到 rejected promise + resolve({ err: e, text: '', stderr: String((e && e.message) || e) }) + } }) } @@ -702,6 +886,76 @@ function toView(row) { }) } +const WPN_QUERY = `select n.Id as id, cast(n.ArrivalTime as TEXT) as arrival, n.Payload as payload, + h.PrimaryId as aumid + from Notification n left join NotificationHandler h on h.RecordId = n.HandlerId + where printf('%020d', n.ArrivalTime) > ? + order by n.ArrivalTime` + +/** + * 读出 ArrivalTime 大于 since 的通知。 + * + * 读取引擎双轨,兼容各版本 ZTools: + * · 'native' —— 宿主带 node:sqlite(Electron 36.7.3+,即 ZTools 3.2.x 及更早那批 Electron 41); + * · 'lite' —— 宿主没有该模块(ZTools 3.3.0 锁的 Electron 35.0.0-alpha.2),用自带的纯 JS 只读实现, + * 自己拼出同样的结果集(左连接 + 过滤 + 按到达时间升序)。 + * native 只有在真正打开失败时才降级(比如某个 Electron 版本的 DatabaseSync 不接受 readOnly), + * 降级是一次性的,不会每 1.5s 重复抛错。 + */ +let dbEngine = null + +function pickEngine() { + if (!dbEngine) dbEngine = DatabaseSync ? 'native' : 'lite' + return dbEngine +} + +function readNotifications(file, since) { + if (pickEngine() === 'native') { + try { + const snap = new DatabaseSync(file, { readOnly: true }) + try { + return snap.prepare(WPN_QUERY).all(since) + } finally { + snap.close() + } + } catch (e) { + dbEngine = 'lite' + } + } + + const db = sqliteLite.open(file) + if (!db) throw new Error('无法打开通知库:' + file) + const notification = db.table('Notification') + if (!notification) throw new Error('通知库缺少 Notification 表') + const column = (t, name) => (t ? t.columns.findIndex((c) => c.toLowerCase() === name.toLowerCase()) : -1) + const iId = column(notification, 'Id') + const iArrival = column(notification, 'ArrivalTime') + const iPayload = column(notification, 'Payload') + const iHandler = column(notification, 'HandlerId') + const handlers = db.table('NotificationHandler') + const iRecord = column(handlers, 'RecordId') + const iPrimary = column(handlers, 'PrimaryId') + const handlerNames = new Map() + if (handlers && iRecord >= 0 && iPrimary >= 0) { + for (const row of handlers.rows) handlerNames.set(String(row[iRecord]), row[iPrimary]) + } + + const floor = BigInt(since || '0') + const rows = [] + for (const row of notification.rows) { + const arrival = BigInt(String(row[iArrival] == null ? 0 : row[iArrival])) + if (arrival <= floor) continue + rows.push({ + id: row[iId], + arrival: arrival.toString(), + payload: row[iPayload], + aumid: handlerNames.get(String(row[iHandler])) || null + }) + } + rows.sort((a, b) => (BigInt(a.arrival) < BigInt(b.arrival) ? -1 : BigInt(a.arrival) > BigInt(b.arrival) ? 1 : 0)) + return rows +} + async function pollOnce() { const out = { rows: 0, entries: [], error: null } fs.mkdirSync(WPN_COPY_DIR, { recursive: true }) @@ -713,63 +967,37 @@ async function pollOnce() { } } - let snap - try { - snap = new DatabaseSync(path.join(WPN_COPY_DIR, 'wpndatabase.db'), { readOnly: true }) - } catch (e) { - out.error = String((e && e.message) || e) - return out - } - let rows try { const since = String(getConfig().lastFiletime || '0').padStart(20, '0') - rows = snap - .prepare( - `select n.Id as id, cast(n.ArrivalTime as TEXT) as arrival, n.Payload as payload, - h.PrimaryId as aumid - from Notification n left join NotificationHandler h on h.RecordId = n.HandlerId - where printf('%020d', n.ArrivalTime) > ? - order by n.ArrivalTime` - ) - .all(since) + rows = readNotifications(path.join(WPN_COPY_DIR, 'wpndatabase.db'), since) } catch (e) { out.error = String((e && e.message) || e) return out - } finally { - snap.close() } await warmNames(rows.map((r) => r.aumid || '')) - const insert = prep( - 'insert or ignore into notice(id, aumid, title, body, logo, arrived_at) values(?, ?, ?, ?, ?, ?)' - ) + loadHistory() let maxFiletime = 0n for (const row of rows) { const filetime = BigInt(row.arrival || '0') if (filetime > maxFiletime) maxFiletime = filetime + const id = Number(row.id) + if (histIds.has(id)) continue const parsed = parseToast(row.payload || new Uint8Array(0)) - const changed = insert.run( - Number(row.id), - row.aumid || '', - parsed.title, - parsed.body, - parsed.logo, - filetimeToMs(row.arrival) - ) - if (changed.changes > 0) { - const entry = toView({ - id: row.id, - aumid: row.aumid, - title: parsed.title, - body: parsed.body, - logo: parsed.logo, - arrived_at: filetimeToMs(row.arrival) - }) - out.entries.push(entry) - broadcast(entry) + const notice = { + id, + aumid: row.aumid || '', + title: parsed.title, + body: parsed.body, + logo: parsed.logo, + arrived_at: filetimeToMs(row.arrival) } + if (!appendHistory(notice)) continue + const entry = toView(notice) + out.entries.push(entry) + broadcast(entry) } out.rows = rows.length if (maxFiletime > 0n) setConfig({ lastFiletime: String(maxFiletime) }) @@ -777,11 +1005,19 @@ async function pollOnce() { } function prune() { + loadHistory() const cfg = getConfig() const cutoff = Date.now() - Number(cfg.keepDays || 30) * 86400000 - prep('delete from notice where arrived_at < ?').run(cutoff) - prep('delete from notice where id not in (select id from notice order by arrived_at desc limit ?)') - .run(Number(cfg.keepMax || 5000)) + const keepMax = Math.max(1, Number(cfg.keepMax || 5000)) + const kept = histRows + .filter((row) => Number(row.arrived_at) >= cutoff) + .sort((a, b) => Number(b.arrived_at) - Number(a.arrived_at)) + .slice(0, keepMax) + .sort((a, b) => Number(a.arrived_at) - Number(b.arrived_at)) + if (kept.length === histRows.length) return + histRows = kept + histIds = new Set(kept.map((row) => Number(row.id))) + saveHistory() } let timer = null @@ -811,26 +1047,36 @@ function startCollector() { }, POLL_MS) } -if (!getConfig().lastFiletime) setConfig({ lastFiletime: String(nowFiletime()) }) // 采集依赖 wpndatabase / 注册表 / WinRT,仅 Windows 有意义;被侧载到其他平台时静默待命 const IS_WIN = process.platform === 'win32' -if (IS_WIN) { - ensureTestIdentity() - startCollector() - for (const row of prep('select aumid from app_config where suppress_banner = 1').all()) { - writeBanner(row.aumid, 0) + +/** + * 启动副作用统一挪到这里、等 window.services 赋值之后再执行: + * 任何一步抛错都只是功能降级,不会再像过去那样让渲染层拿到 undefined services。 + */ +function init() { + try { + if (IS_WIN && window.ztools.getWindowType() === 'main') importLegacyStore() + if (!getConfig().lastFiletime) setConfig({ lastFiletime: String(nowFiletime()) }) + if (IS_WIN) { + ensureTestIdentity() + startCollector() + const apps = readJson(APPS_FILE, {}) + for (const [aumid, cfg] of Object.entries(apps)) { + if (cfg && cfg.suppress_banner) writeBanner(aumid, 0) + } + } + // 僵尸浮层自检:leader 死后无人回 pong,8s 自关,避免孤儿窗越积越多 + if (ipcRenderer && window.ztools.getWindowType() === 'browser') { + setInterval(() => { + if (Date.now() - lastPong > 8000) window.close() + }, 2000) + } + if (IS_WIN) setTimeout(ensureOverlays, 300) + } catch (e) { + console.error('[cafe-notice] init failed', e) } } -// 僵尸浮层自检:leader 死后无人回 pong,8s 自关,避免孤儿窗越积越多 -if (ipcRenderer && window.ztools.getWindowType() === 'browser') { - setInterval(() => { - if (Date.now() - lastPong > 8000) window.close() - }, 2000) -} - -setTimeout(() => { - if (IS_WIN) ensureOverlays() -}, 300) window.services = { notice: { @@ -841,10 +1087,12 @@ window.services = { } catch (e) { /* 无统计 */ } + loadHistory() return Object.assign({}, status, shared, { enabled: getConfig().enabled === '1', overlayCount: shared.overlayCount || overlayIds.size, - historyCount: prep('select count(*) as c from notice').get().c + historyCount: histRows.length, + dbEngine: pickEngine() }) }, setEnabled(on) { @@ -918,20 +1166,30 @@ window.services = { ensureOverlays, collectOnce: pollOnce, getRecent(limit) { - return prep('select * from notice order by arrived_at desc limit ?') - .all(Number(limit) || 60) + loadHistory() + return histRows + .slice() + .sort((a, b) => Number(b.arrived_at) - Number(a.arrived_at)) + .slice(0, Number(limit) || 60) .map(toView) }, search(keyword, limit) { - const like = '%' + String(keyword || '') + '%' - return prep('select * from notice where title like ? or body like ? order by arrived_at desc limit ?') - .all(like, like, Number(limit) || 200) + loadHistory() + const k = String(keyword || '').toLowerCase() + return histRows + .filter((row) => (String(row.title || '') + String(row.body || '')).toLowerCase().includes(k)) + .sort((a, b) => Number(b.arrived_at) - Number(a.arrived_at)) + .slice(0, Number(limit) || 200) .map(toView) }, async getApps() { + loadHistory() const map = new Map() - for (const row of prep('select aumid, count(*) as count, max(arrived_at) as lastAt from notice group by aumid').all()) { - map.set(row.aumid, { count: row.count, lastAt: row.lastAt }) + for (const row of histRows) { + const cur = map.get(row.aumid) || { count: 0, lastAt: 0 } + cur.count += 1 + if (Number(row.arrived_at) > cur.lastAt) cur.lastAt = Number(row.arrived_at) + map.set(row.aumid, cur) } // 系统通知设置里登记过的应用 ⊇ 已采集应用,含从未被我们采到的 for (const aumid of await registryAppList()) { @@ -945,7 +1203,8 @@ window.services = { setAppConfig, sendTestNotification, exportHistory(format, keyword, aumid) { - let rows = prep('select * from notice order by arrived_at desc').all() + loadHistory() + let rows = histRows.slice().sort((a, b) => Number(b.arrived_at) - Number(a.arrived_at)) if (aumid) rows = rows.filter((r) => r.aumid === aumid) if (keyword) { const k = String(keyword).toLowerCase() @@ -969,7 +1228,12 @@ window.services = { return file }, clearHistory() { - prep('delete from notice').run() + histRows = [] + histIds = new Set() + saveHistory() } } } + +// services 先就位,再做采集、迁移等副作用 +init() diff --git a/plugins/cafe-notice/src-ztools/preload/sqlite-lite.js b/plugins/cafe-notice/src-ztools/preload/sqlite-lite.js new file mode 100644 index 000000000..5a16f165a --- /dev/null +++ b/plugins/cafe-notice/src-ztools/preload/sqlite-lite.js @@ -0,0 +1,301 @@ +'use strict' +/** + * 极简只读 SQLite 读取器(纯 JS,不依赖 node:sqlite 或任何原生模块)。 + * + * 为什么要自己写:ZTools 3.3.0 把 Electron 固定到 35.0.0-alpha.2,这版 Electron + * 没有把 sqlite 内置模块编进 node(require('node:sqlite') 直接抛 + * "No such built-in module"),而采集 Windows 通知必须读 + * %LOCALAPPDATA%\Microsoft\Windows\Notifications\wpndatabase.db。 + * + * 能力边界(够用即止,不做多余的事): + * · 只读,支持 WAL 快照(数据库已连同 -wal 一起复制到临时目录); + * · 只读普通 rowid 表(本项目只查 Notification / NotificationHandler), + * 不支持 WITH ROWID 表、索引树、视图、触发器; + * · 支持溢出页(通知 Payload 可达数 KB)、64 位整数(超过 2^53 转十进制字符串)。 + */ + +const fs = require('node:fs') + +const WAL_MAGIC = 0x377f0682 // 低位置 1 时校验和按小端计算 +const SQLITE_MAGIC = 'SQLite format 3\u0000' +const MAX_SAFE_BIG = BigInt(Number.MAX_SAFE_INTEGER) +const MIN_SAFE_BIG = -MAX_SAFE_BIG + +function readVarint(buf, pos) { + let value = 0n + for (let i = 0; i < 9; i += 1) { + const b = buf[pos + i] + if (b === undefined) return [0n, pos + 9] + if (i === 8) return [value * 256n + BigInt(b), pos + 9] + if (b < 0x80) return [value * 128n + BigInt(b), pos + i + 1] + value = value * 128n + BigInt(b & 0x7f) + } + return [0n, pos + 9] +} + +function toJs(big) { + return big >= MIN_SAFE_BIG && big <= MAX_SAFE_BIG ? Number(big) : big.toString() +} + +function readInt(buf, pos, size) { + let value = 0n + for (let i = 0; i < size; i += 1) value = (value << 8n) | BigInt(buf[pos + i]) + const bits = BigInt(size * 8) + if (value >= 1n << (bits - 1n)) value -= 1n << bits + return value +} + +/** serial type → [值, 占用字节数];BLOB 返回 Buffer,TEXT 返回字符串 */ +function decodeValue(buf, type, pos) { + if (type === 0) return [null, 0] + if (type >= 1 && type <= 6) { + const size = [0, 1, 2, 3, 4, 6, 8][type] + return [toJs(readInt(buf, pos, size)), size] + } + if (type === 7) return [buf.readDoubleBE(pos), 8] + if (type === 8) return [0, 0] + if (type === 9) return [1, 0] + if (type >= 12) { + const size = (type - 12) >> 1 + const raw = buf.subarray(pos, pos + size) + return [type % 2 === 0 ? Buffer.from(raw) : new TextDecoder('utf-8').decode(raw), size] + } + return [null, 0] // 10/11 是内部保留类型 +} + +function decodeRecord(buf) { + const [headerLen, headerEnd] = readVarint(buf, 0) + const types = [] + let pos = headerEnd + while (pos < Number(headerLen)) { + const [t, next] = readVarint(buf, pos) + types.push(Number(t)) + pos = next + } + let body = Number(headerLen) + const values = [] + for (const type of types) { + const [value, size] = decodeValue(buf, type, body) + values.push(value) + body += size + } + return values +} + +const CONSTRAINT_RE = /^(constraint|primary\s+key|unique|check|foreign)\b/i + +/** 从 CREATE TABLE 文本里取列名,并标出是 rowid 别名的 INTEGER PRIMARY KEY */ +function parseColumns(sql) { + const open = sql.indexOf('(') + const close = sql.lastIndexOf(')') + if (open < 0 || close <= open) return { names: [], rowidAlias: -1 } + const body = sql.slice(open + 1, close) + + const parts = [] + let cur = '' + let depth = 0 + let quote = null + for (const ch of body) { + if (quote) { + cur += ch + if (ch === quote) quote = null + continue + } + if (ch === '"' || ch === "'" || ch === '`') { + quote = ch + cur += ch + continue + } + if (ch === '[') { + quote = ']' + cur += ch + continue + } + if (ch === '(') depth += 1 + if (ch === ')') depth -= 1 + if (ch === ',' && depth === 0) { + parts.push(cur) + cur = '' + continue + } + cur += ch + } + if (cur.trim()) parts.push(cur) + + const names = [] + let rowidAlias = -1 + for (const part of parts) { + const def = part.trim() + if (!def || CONSTRAINT_RE.test(def)) continue + const m = /^(?:"([^"]*)"|'([^']*)'|`([^`]*)`|\[([^\]]*)\]|([^\s(]+))/.exec(def) + if (!m) continue + const name = m[1] || m[2] || m[3] || m[4] || m[5] + if (/^integer\s+primary\s+key\b/i.test(def.slice(m[0].length).trim()) && rowidAlias < 0) { + rowidAlias = names.length + } + names.push(name) + } + return { names, rowidAlias } +} + +function cksum(buf, start, len, little, s0, s1) { + for (let i = 0; i < len; i += 8) { + const x0 = little ? buf.readUInt32LE(start + i) : buf.readUInt32BE(start + i) + const x1 = little ? buf.readUInt32LE(start + i + 4) : buf.readUInt32BE(start + i + 4) + s0 = (s0 + x0 + s1) >>> 0 + s1 = (s1 + x1 + s0) >>> 0 + } + return [s0, s1] +} + +/** + * 打开一个 SQLite 文件(只读)。 + * @returns {null | { pageSize: number, table(name: string): { columns: string[], rows: any[][] } }} + */ +function open(file) { + let main + try { + main = fs.readFileSync(file) + } catch (e) { + return null + } + if (main.length < 512 || main.toString('latin1', 0, 16) !== SQLITE_MAGIC) return null + + let pageSize = main.readUInt16BE(16) + if (pageSize === 1) pageSize = 65536 + if (!(pageSize >= 512)) return null + const usable = pageSize - (main[20] || 0) + const overlay = new Map() + let pageCount = main.readUInt32BE(28) + + // WAL:快照连同 -wal 一起复制,未 checkpoint 的页在这里才看得到 + try { + const wal = fs.readFileSync(file + '-wal') + if (wal.length >= 32 && (wal.readUInt32BE(0) & 0xfffffffe) === WAL_MAGIC) { + const salt1 = wal.readUInt32BE(16) + const salt2 = wal.readUInt32BE(20) + const stored0 = wal.readUInt32BE(24) + const stored1 = wal.readUInt32BE(28) + // 校验和的字节序约定各家实现不一致,直接拿 WAL 头自校验来定: + // 哪种字节序能对上就用哪种,都对不上说明 WAL 头已损坏,忽略 WAL。 + let little = null + for (const candidate of [true, false]) { + const [c0, c1] = cksum(wal, 0, 24, candidate, 0, 0) + if (c0 === stored0 && c1 === stored1) { + little = candidate + break + } + } + if (little !== null) { + let s0 = stored0 + let s1 = stored1 + const frameSize = 24 + pageSize + for (let off = 32; off + frameSize <= wal.length; off += frameSize) { + const pgno = wal.readUInt32BE(off) + const dbSize = wal.readUInt32BE(off + 4) + if (wal.readUInt32BE(off + 8) !== salt1 || wal.readUInt32BE(off + 12) !== salt2) break + ;[s0, s1] = cksum(wal, off, 8, little, s0, s1) + ;[s0, s1] = cksum(wal, off + 24, pageSize, little, s0, s1) + if (s0 !== wal.readUInt32BE(off + 16) || s1 !== wal.readUInt32BE(off + 20)) break + if (pgno > 0) overlay.set(pgno, wal.subarray(off + 24, off + frameSize)) + if (dbSize > 0) pageCount = dbSize + } + } + } + } catch (e) { + /* 没有 -wal 或已 checkpoint */ + } + + function page(pgno) { + const hit = overlay.get(pgno) + if (hit) return hit + const start = (pgno - 1) * pageSize + if (pgno < 1 || start + pageSize > main.length) return null + return main.subarray(start, start + pageSize) + } + + function leafCell(buf, off) { + const [payloadLen, afterLen] = readVarint(buf, off) + const [rowid, bodyPos] = readVarint(buf, afterLen) + const size = Number(payloadLen) + if (!(size >= 0)) return null + const maxLocal = usable - 35 + const minLocal = Math.floor(((usable - 12) * 32) / 255) - 23 + let local = size + if (size > maxLocal) { + const k = minLocal + ((size - minLocal) % (usable - 4)) + local = k <= maxLocal ? k : minLocal + } + const parts = [buf.subarray(bodyPos, bodyPos + local)] + let got = local + if (local < size) { + let next = buf.readUInt32BE(bodyPos + local) + while (next && got < size) { + const ob = page(next) + if (!ob) break + next = ob.readUInt32BE(0) + const chunk = Math.min(usable - 4, size - got) + parts.push(ob.subarray(4, 4 + chunk)) + got += chunk + } + } + return { rowid: toJs(rowid), values: decodeRecord(Buffer.concat(parts, Math.min(got, size))) } + } + + function tableRows(rootPage) { + const rows = [] + const seen = new Set() + const walk = (pgno) => { + if (!pgno || seen.has(pgno) || seen.size > Math.max(pageCount, 1)) return + seen.add(pgno) + const buf = page(pgno) + if (!buf) return + const base = pgno === 1 ? 100 : 0 + const type = buf[base] + const nCells = buf.readUInt16BE(base + 3) + const ptrBase = base + (type === 0x05 ? 12 : 8) + if (type === 0x0d) { + for (let i = 0; i < nCells; i += 1) { + const row = leafCell(buf, buf.readUInt16BE(ptrBase + i * 2)) + if (row) rows.push(row) + } + } else if (type === 0x05) { + for (let i = 0; i < nCells; i += 1) walk(buf.readUInt32BE(buf.readUInt16BE(ptrBase + i * 2))) + walk(buf.readUInt32BE(base + 8)) + } + } + walk(rootPage) + return rows + } + + let master = null + function masterTables() { + if (master) return master + master = new Map() + for (const row of tableRows(1)) { + const [type, name, , rootPage, sql] = row.values + if (String(type).toLowerCase() !== 'table') continue + master.set(String(name).toLowerCase(), { rootPage: Number(rootPage), sql: String(sql || '') }) + } + return master + } + + return { + pageSize, + table(name) { + const info = masterTables().get(String(name).toLowerCase()) + if (!info || !info.rootPage) return null + const { names, rowidAlias } = parseColumns(info.sql) + const rows = tableRows(info.rootPage).map((row) => { + const values = row.values + if (rowidAlias >= 0 && (values[rowidAlias] === null || values[rowidAlias] === undefined)) { + values[rowidAlias] = row.rowid + } + return values + }) + return { columns: names, rows } + } + } +} + +module.exports = { open } \ No newline at end of file