Files
image-workbench-desktop/src/storage-file.js
T

296 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* storage-file.js —— 桌面端「资料目录」存储底座(2026-11-16)
*
* 目标:数据不再只躺在 WebView 私有存储里,而是落在一个你指定的普通目录:
* <资料目录>/data.json 所有 localStorage 键(设置/提示词/画布/图库索引…)
* <资料目录>/images/<hash>.<ext> 所有图片字节(按内容哈希去重,真实二进制,无 base64)
*
* 实现要点(为什么能不加异步改造就跑起来):
* localStorage 是同步 API,文件 IO 是异步的 ⇒ 启动时一次性把 data.json 读进内存,
* 之后读写都是同步的内存操作,写盘走 debounce(800ms)异步刷盘;关窗前 flush 一次。
*
* 只在 Tauri 里启用;网页版 enabled() 恒为 false,调用方原样走浏览器存储。
*/
;(function (global) {
'use strict'
const PTR_KEY = 'iwb.dataDir' // 资料目录指针:必须住在 WebView 存储里(否则找不到 data.json)
const DATA_FILE = 'data.json'
const IMG_DIR = 'images'
const SCHEMA = 1
let tauri = null
let dir = ''
let mem = {} // key -> 原始字符串(与 localStorage 一一对应)
let assets = {} // key -> { f: 'images/xxx.png', k: 'blob' | 'dataurl' }
let small = {} // 小文本 KV(日志等):key -> 字符串
let loaded = false
let timer = null
let writing = null
// 惰性取 __TAURI__:模块加载时它未必已注入,但每个调用点都要能拿到
const tk = () => { if (!tauri) { try { tauri = global.__TAURI__ || null } catch (e) { tauri = null } } return tauri }
const fs = () => { const T = tk(); return (T && T.fs) || null }
const path = () => { const T = tk(); return (T && T.path) || null }
const core = () => { const T = tk(); return (T && T.core) || null }
const enabled = () => { const T = tk(); return !!(T && T.core && T.fs && T.path) }
const join = async (...p) => {
const P = path()
if (!P || !P.join) return p.join('/')
return await P.join.apply(null, p.map(String))
}
const bytes = () => {
let n = 0
try { for (const k of Object.keys(mem)) n += (k.length + String(mem[k] || '').length) * 2 } catch (e) { /* ignore */ }
return n
}
const schedule = () => {
if (!enabled()) return
if (timer) clearTimeout(timer)
timer = setTimeout(() => { timer = null; flush().catch(() => {}) }, 800)
}
const snapshot = () => JSON.stringify({ v: SCHEMA, at: Date.now(), keys: mem, assets, small })
// 原子写:先写 .tmp 再 rename,避免断电/崩溃留下半个 JSON
const flush = async () => {
if (!enabled() || !dir) return Promise.resolve(false)
if (writing) return writing
const body = snapshot()
const target = await join(dir, DATA_FILE)
writing = (async () => {
try {
const tmp = await join(dir, DATA_FILE + '.tmp')
await fs().writeTextFile(tmp, body)
await fs().rename(tmp, target)
return true
} catch (e) {
try { await fs().writeTextFile(target, body) } catch (e2) { /* ignore */ }
return false
} finally { writing = null }
})()
return writing
}
// 图片:内容哈希(SHA-256 前 16 位)→ images/<hash>.<ext>,同图只存一份
const extOf = (mime) => {
const m = String(mime || '').toLowerCase()
if (m.indexOf('jpeg') >= 0 || m.indexOf('jpg') >= 0) return 'jpg'
if (m.indexOf('webp') >= 0) return 'webp'
if (m.indexOf('gif') >= 0) return 'gif'
if (m.indexOf('svg') >= 0) return 'svg'
if (m.indexOf('avif') >= 0) return 'avif'
return 'png'
}
const sha16 = async (buf) => {
try {
const d = await global.crypto.subtle.digest('SHA-256', buf)
return Array.from(new Uint8Array(d)).slice(0, 8).map((b) => b.toString(16).padStart(2, '0')).join('')
} catch (e) {
let h = 2166136261
const u = new Uint8Array(buf)
for (let i = 0; i < u.length; i++) { h ^= u[i]; h = Math.imul(h, 16777619) >>> 0 }
return 'f' + (h >>> 0).toString(16)
}
}
const dataUrlToBytes = (s) => {
const m = /^data:([^;,]+)?(;base64)?,/i.exec(String(s || ''))
if (!m) return null
const bin = global.atob(String(s).slice(m[0].length))
const u = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i)
return { mime: m[1] || 'image/png', bytes: u }
}
const bytesToDataUrl = (mime, u8) => {
let bin = ''
const CH = 0x8000
for (let i = 0; i < u8.length; i += CH) bin += String.fromCharCode.apply(null, u8.subarray(i, i + CH))
return 'data:' + (mime || 'image/png') + ';base64,' + global.btoa(bin)
}
// ── 对外:legacy IndexedDB 同形接口(app.js 的 IDB 就是拿这个)──
const kv = {
async put(key, value) {
try {
if (!enabled() || !dir) return false
if (value && typeof value === 'object' && typeof value.size === 'number' && value.type !== undefined) {
// Blob:直接取二进制落盘
const buf = await value.arrayBuffer()
const hash = await sha16(buf)
const rel = IMG_DIR + '/' + hash + '.' + extOf(value.type)
const abs = await join(dir, rel)
await fs().writeFile(abs, new Uint8Array(buf))
assets[String(key)] = { f: rel, k: 'blob', m: value.type || 'application/octet-stream' }
schedule()
return true
}
const s = String(value)
if (s.indexOf('data:') === 0) {
const dec = dataUrlToBytes(s)
if (dec) {
const hash = await sha16(dec.bytes)
const rel = IMG_DIR + '/' + hash + '.' + extOf(dec.mime)
const abs = await join(dir, rel)
await fs().writeFile(abs, dec.bytes)
assets[String(key)] = { f: rel, k: 'dataurl', m: dec.mime }
schedule()
return true
}
}
small[String(key)] = s
schedule()
return true
} catch (e) {
try { global.IWBMetricsSwallow && global.IWBMetricsSwallow('file-kv-put', e) } catch (e2) { /* ignore */ }
return false
}
},
async get(key) {
try {
const a = assets[String(key)]
if (a) {
const abs = await join(dir, a.f)
const u8 = await fs().readFile(abs)
if (a.k === 'dataurl') return bytesToDataUrl(a.m, u8)
return new Blob([u8], { type: a.m || 'application/octet-stream' })
}
return Object.prototype.hasOwnProperty.call(small, String(key)) ? small[String(key)] : null
} catch (e) { return null }
},
async getBlob(key) {
try {
const a = assets[String(key)]
if (!a) return null
const abs = await join(dir, a.f)
const u8 = await fs().readFile(abs)
return new Blob([u8], { type: a.m || 'application/octet-stream' })
} catch (e) { return null }
},
async del(key) {
try {
const k = String(key)
const had = !!assets[k] || Object.prototype.hasOwnProperty.call(small, k)
delete assets[k]; delete small[k]
schedule()
return had
} catch (e) { return false }
},
async keys() { try { return Object.keys(assets).concat(Object.keys(small)) } catch (e) { return [] } },
async logPut(id, entry) { return kv.put('log:' + id, JSON.stringify(entry)) },
async logAll() {
const out = []
for (const k of Object.keys(small)) if (k.indexOf('log:') === 0) { try { out.push(JSON.parse(small[k])) } catch (e) { /* ignore */ } }
return out
},
async kvGet(key) { return kv.get(key) },
async kvPut(key, value) { return kv.put(key, typeof value === 'string' ? value : JSON.stringify(value)) },
}
// ── 对外:localStorage 同形的内存表(供 IWBStorageLocal / lsGet 使用)──
const storage = {
getItem(k) { return Object.prototype.hasOwnProperty.call(mem, String(k)) ? mem[String(k)] : null },
setItem(k, v) { mem[String(k)] = String(v); schedule() },
removeItem(k) { delete mem[String(k)]; schedule() },
clear() { mem = {}; schedule() },
key(i) { return Object.keys(mem)[i] || null },
get length() { return Object.keys(mem).length },
}
const runtime = {
get(key, fallback) { try { const v = storage.getItem(key); return v === null ? fallback : JSON.parse(v) } catch (e) { return fallback } },
set(key, value) { try { storage.setItem(key, JSON.stringify(value)); return true } catch (e) { return false } },
remove(key) { try { storage.removeItem(key); return true } catch (e) { return false } },
rawGet(key, fallback) { const v = storage.getItem(key); return v === null ? fallback : v },
rawSet(key, value) { try { storage.setItem(key, String(value)); return true } catch (e) { return false } },
bytes,
indexedDb: kv,
}
async function loadInto() {
// data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次)
const target = await join(dir, DATA_FILE)
let parsed = null
try { const txt = await fs().readTextFile(target); parsed = JSON.parse(txt) } catch (e) { parsed = null }
if (parsed && parsed.keys) {
mem = parsed.keys || {}
assets = parsed.assets || {}
small = parsed.small || {}
return 'loaded'
}
mem = {}
try {
for (let i = 0; i < global.localStorage.length; i++) {
const k = global.localStorage.key(i)
if (k) mem[k] = global.localStorage.getItem(k)
}
} catch (e) { /* ignore */ }
return 'migrated'
}
// 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件)
const blog = async (m) => { try { await fs().writeTextFile(await join(dir, '_boot.log'), new Date().toISOString() + ' ' + m + '\n', { append: true }) } catch (e) { /* ignore */ } }
async function migrateBlobs() {
try {
await blog('migrate:start dir=' + dir)
// 注意:Tauri fs 默认禁dotfile(.xxx),标记文件用普通名字
const marker = await join(dir, 'migrated.flag')
const has = await fs().exists(marker)
await blog('migrate:marker exists=' + has)
if (has) return 0
const C = global.IWBStorageContract || {}
const store = (global.IWBStorageIndexedDB && global.IWBStorageIndexedDB.create)
? global.IWBStorageIndexedDB.create({ contract: C.indexedDb })
: null
await blog('migrate:store=' + !!store + ' imagesAll=' + !!(store && store.imagesAll))
if (!store || typeof store.imagesAll !== 'function') { await fs().writeTextFile(marker, 'no-idb'); return 0 }
const r = await store.imagesAll()
await blog('migrate:result ok=' + (r && r.ok) + ' n=' + (r && r.value && r.value.length))
const list = (r && r.ok && Array.isArray(r.value)) ? r.value : []
let n = 0
for (const it of list) {
if (!it || it.key === undefined) continue
try { if (await kv.put(it.key, it.value)) n++ } catch (e) { /* 单条失败不影响其它 */ }
}
await flush()
await fs().writeTextFile(marker, String(n))
await blog('migrate:done n=' + n)
return n
} catch (e) { await blog('migrate:ERR ' + (e && (e.message || e))); return 0 }
}
async function init(opts) {
const o = opts || {}
tauri = global.__TAURI__ || null
if (!enabled()) return false
if (loaded) return true
let want = o.dir || ''
try { want = want || global.localStorage.getItem(PTR_KEY) || '' } catch (e) { /* ignore */ }
if (!want) {
// 默认目录:~/Documents/ImageWorkbench
try { const doc = await path().documentDir(); want = await join(doc, 'ImageWorkbench') } catch (e) { want = '' }
}
if (!want) return false
// 授权(fs scope 是运行时授权,重启后由这里补一次)
try { await core().invoke('grant_dir', { dir: want }) } catch (e) { console.error('[iwb][file-store] 授权失败', e); return false }
dir = want
try { global.localStorage.setItem(PTR_KEY, dir) } catch (e) { /* ignore */ }
try { await fs().mkdir(await join(dir, IMG_DIR), { recursive: true }) } catch (e) { /* 已存在 */ }
await loadInto()
loaded = true
// 首次迁移要立刻落盘,别等 debounce
await flush()
// 老版本图片在 IndexedDB 里 ⇒ 搬到 images/(带标记,只跑一次)
try { await migrateBlobs() } catch (e) { /* 迁移失败不阻塞启动 */ }
return true
}
global.IWBStorageFile = {
enabled, ready: init, flush, runtime,
storage: () => storage,
kv: () => kv,
dir: () => dir,
setDir: async (next) => { dir = String(next || ''); await flush();},
stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length }),
__internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl },
}
// 关窗/收托盘前强制刷盘(beforeunload 在桌面端不保证,但能救一次是一次)
try { global.addEventListener('beforeunload', () => { try { flush() } catch (e) { /* ignore */ } }) } catch (e) { /* ignore */ }
})(typeof window !== 'undefined' ? window : globalThis)