materialCache.js
24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
const md5 = require('../lib/md5.js')
// 基础缓存与图片文件缓存分开版本,图片缓存只在 storage 中保存轻量文件路径。
const SOURCE_PREFIX = 'source_v2_'
const IMAGE_PREFIX = 'material_file_v1_'
const LEGACY_IMAGE_PREFIX = 'material_base64_'
const URL_PREFIX = 'material_file_url_v1_'
const LEGACY_URL_PREFIX = 'material_url_'
const imageGenerations = new Map()
const activeImageTargets = new Map()
const writeQueues = new Map()
// 同一张图片(素材 ID + 位置 + URL 指纹)只下载保存一次,首屏补齐与后台批量缓存共用一个 Promise。
const pendingConversions = new Map()
const downloadQueue = []
let activeDownloads = 0
const imageReadQueue = []
const pendingImageReads = new Map()
let activeImageReads = 0
const imageMemory = new Map()
const IMAGE_MEMORY_LIMIT = 16 * 1024 * 1024
let imageMemoryBytes = 0
let imageMemoryEpoch = 0
const isRemote = value => typeof value === 'string' && /^https?:\/\//i.test(value)
const isLocalImage = value => typeof value === 'string' && value.trim() !== '' &&
!isRemote(value) && !/^data:/i.test(value)
const hasId = id => (typeof id === 'string' && id.trim() !== '') || (typeof id === 'number' && Number.isFinite(id))
const isSource = data => data && Array.isArray(data.moduleList) && Array.isArray(data.toolList)
function getSourceKey(shopMerchantId, sceneType, params = {}) {
let key = `${SOURCE_PREFIX}${sceneType}_${shopMerchantId}`
if (hasId(params.brandId) && hasId(params.subBrandId)) key += `_${params.brandId}_${params.subBrandId}`
return key
}
function imageKey(sourceKey, id, slotKey) {
// 素材 ID 下按图片位置和 URL 指纹分槽;每条记录的 value 只有本地文件路径。
// 门店、场景和车型作为命名空间,避免不同配置串图。
return `${IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}`
}
function legacyImageKey(sourceKey, id, slotKey) {
return `${LEGACY_IMAGE_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}_${id}_${slotKey}`
}
// 位置 => 该位置上次成功转换时使用的 URL,用于判断接口地址是否变化。
function urlKey(sourceKey) {
return `${URL_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}`
}
function legacyUrlKey(sourceKey) {
return `${LEGACY_URL_PREFIX}${sourceKey.slice(SOURCE_PREFIX.length)}`
}
function getNetworkStatus() {
return new Promise(resolve => {
uni.getNetworkType({
success: res => resolve(!!res.networkType && res.networkType !== 'none'),
fail: () => resolve(false)
})
})
}
function read(key) {
return new Promise(resolve => {
uni.getStorage({ key, success: res => resolve(res.data), fail: () => resolve(null) })
})
}
function remove(key) {
if (key.startsWith(IMAGE_PREFIX)) forgetImage(key)
return new Promise(resolve => {
uni.removeStorage({ key, success: resolve, fail: resolve })
})
}
function removeSavedFile(filePath) {
if (!isLocalImage(filePath) || typeof uni.removeSavedFile !== 'function') return Promise.resolve()
return new Promise(resolve => {
uni.removeSavedFile({ filePath, success: resolve, fail: resolve })
})
}
// 文件路径记录不等于文件仍存在:App 可能因系统清理而丢失保存的素材文件。
function savedFileExists(filePath) {
if (!isLocalImage(filePath)) return Promise.resolve(false)
if (typeof plus !== 'undefined' && plus.io?.resolveLocalFileSystemURL) {
return new Promise(resolve => {
try {
plus.io.resolveLocalFileSystemURL(filePath, () => resolve(true), () => resolve(false))
} catch (error) {
resolve(false)
}
})
}
if (typeof uni.getFileInfo === 'function') {
return new Promise(resolve => {
uni.getFileInfo({ filePath, success: () => resolve(true), fail: () => resolve(false) })
})
}
// 不支持文件查询的运行环境沿用路径缓存,避免影响非 App 端原有行为。
return Promise.resolve(true)
}
function forgetImage(key) {
const cached = imageMemory.get(key)
if (cached) imageMemoryBytes -= cached.length * 2
imageMemory.delete(key)
// 写入与读取重叠时,旧读取结果不能重新放回内存。
const pending = pendingImageReads.get(key)
if (pending) {
pending.invalidated = true
pendingImageReads.delete(key)
}
}
function clearImageMemory() {
imageMemory.clear()
imageMemoryBytes = 0
imageMemoryEpoch++
}
function rememberImage(key, image) {
const bytes = image.length * 2
if (bytes > IMAGE_MEMORY_LIMIT) return
const cached = imageMemory.get(key)
if (cached) imageMemoryBytes -= cached.length * 2
imageMemory.delete(key)
while (imageMemoryBytes + bytes > IMAGE_MEMORY_LIMIT && imageMemory.size) {
const oldest = imageMemory.keys().next().value
imageMemoryBytes -= imageMemory.get(oldest).length * 2
imageMemory.delete(oldest)
}
imageMemory.set(key, image)
imageMemoryBytes += bytes
}
function retryInvalidatedRead(job) {
if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
// 成功写入已使旧读取失效,仍在显示的素材直接重读同一 key。
// 复用读取队列以保持并发上限,过期页面不再参与新一轮读取。
job.subscribers.forEach(subscriber => {
if (!subscriber.isCurrent()) subscriber.resolve(null)
else readImage(job.key, subscriber.isCurrent, subscriber.metrics).then(subscriber.resolve)
})
}
function drainImageReads() {
while (activeImageReads < 3 && imageReadQueue.length) {
const job = imageReadQueue.shift()
const subscribers = job.subscribers.filter(subscriber => subscriber.isCurrent())
if (!subscribers.length) {
job.subscribers.forEach(subscriber => subscriber.resolve(null))
if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
continue
}
if (job.invalidated) { retryInvalidatedRead(job); continue }
activeImageReads++
subscribers[0].metrics.storageReads++
read(job.key).catch(() => null).then(async value => {
if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
if (job.invalidated) { retryInvalidatedRead(job); return }
let image = isLocalImage(value) ? value : null
if (image && !await savedFileExists(image)) {
image = null
// 删除无效路径,后续在线读取和后台缓存都可重新下载。
await remove(job.key)
}
if (image && job.epoch === imageMemoryEpoch && job.subscribers.some(subscriber => subscriber.isCurrent())) {
rememberImage(job.key, image)
}
job.subscribers.forEach(subscriber => subscriber.resolve(subscriber.isCurrent() ? image : null))
}).finally(() => {
if (pendingImageReads.get(job.key) === job) pendingImageReads.delete(job.key)
activeImageReads--
drainImageReads()
})
}
}
function readImage(key, isCurrent, metrics) {
if (!isCurrent()) return Promise.resolve(null)
const image = imageMemory.get(key)
if (image) {
return savedFileExists(image).then(exists => {
if (!exists) {
forgetImage(key)
return null
}
imageMemory.delete(key)
imageMemory.set(key, image)
metrics.memoryHits++
return image
})
}
return new Promise(resolve => {
let job = pendingImageReads.get(key)
if (!job) {
job = { key, subscribers: [], epoch: imageMemoryEpoch, invalidated: false }
pendingImageReads.set(key, job)
imageReadQueue.push(job)
} else metrics.sharedReads++
job.subscribers.push({ resolve, isCurrent, metrics })
drainImageReads()
})
}
// 同一个 key 的异步写入串行执行,避免较早发起的写入较晚完成。
function write(key, data, shouldWrite = () => true) {
const previous = writeQueues.get(key) || Promise.resolve()
const pending = previous.catch(() => { }).then(() => {
if (!shouldWrite()) return
return new Promise((resolve, reject) => uni.setStorage({
key, data,
success: result => {
if (key.startsWith(IMAGE_PREFIX)) forgetImage(key)
resolve(result)
},
fail: reject
}))
})
writeQueues.set(key, pending)
const cleanup = () => { if (writeQueues.get(key) === pending) writeQueues.delete(key) }
pending.then(cleanup, cleanup)
return pending
}
function withoutBase64(value) {
if (typeof value === 'string') return /^data:image\//i.test(value) ? '' : value
if (Array.isArray(value)) return value.map(withoutBase64)
if (!value || typeof value !== 'object') return value
return Object.fromEntries(Object.keys(value).map(key => [key, withoutBase64(value[key])]))
}
async function saveSourceCache(key, data) {
const base = withoutBase64({ id: data.id, moduleList: data.moduleList || [], toolList: data.toolList || [] })
// 新基础数据一旦提交,旧图片任务不得继续覆盖该配置。
const generation = (imageGenerations.get(key) || 0) + 1
imageGenerations.set(key, generation)
const targets = [...materialGroups(base)].flatMap(([id, entries]) =>
entries.flatMap(entry => entry.slots).map(slot => imageKey(key, id, slot.key)))
activeImageTargets.set(key, { generation, targets: new Set(targets) })
await write(key, base)
return base
}
// 只枚举页面使用的图片字段,业务文本、视频、跳转地址不参与图片缓存。
function imageSlots(item, kind, options = {}) {
const slots = []
const hasCarKey = Object.prototype.hasOwnProperty.call(options, 'carKey')
const matchesCar = entry => !hasCarKey || (
entry && hasId(options.carKey) && (
String(entry.relVehicleSeriesId) === String(options.carKey) ||
String(entry.relVehicleModelId) === String(options.carKey)
)
)
function add(path, value) {
if (Array.isArray(options.fields) && (path.length !== 1 || !options.fields.includes(path[0]))) return
if (isRemote(value)) slots.push({
kind, path, url: value,
// key 含 URL 指纹,用于定位图片;name 只标识位置,用于比对接口 URL 与缓存 URL。
key: md5(JSON.stringify([kind, path, value])),
name: md5(JSON.stringify([kind, path]))
})
}
function fields(value, path, names) {
if (!value || typeof value !== 'object') return
names.forEach(name => add([...path, name], value[name]))
}
fields(item, [], ['thumbnail', 'homeEntranceCover', 'contentPicUrl', 'shortTitleUrl', 'carIcon', 'productPoster'])
if (Array.isArray(options.fields)) return slots
const views = item.receptionSourceDetailList
// ThreeGuarantees 按 tab 位置取图(views[activeIndex] / views[tabIndex]),
// 这个位置无法由车系推断,必须枚举全部键;其余组件只取当前车系或 detailUrl / bgUrl。
const restrictViewKeys = hasCarKey &&
!/^threeguarantee/i.test(String(item.componentName || '').replace(/[^a-z]/gi, ''))
if (Array.isArray(views)) {
views.forEach((view, index) => {
const path = ['receptionSourceDetailList', index]
// 位置直接存图片地址时同样要缓存,否则组件读到的仍是在线地址。
if (isRemote(view)) add(path, view)
else fields(view, path, ['detailUrl', 'bgUrl'])
})
} else if (views && typeof views === 'object') {
const keys = restrictViewKeys ? [...new Set(['detailUrl', 'bgUrl', String(options.carKey)])] : Object.keys(views)
keys.forEach(key => add(['receptionSourceDetailList', key], views[key]))
} else add(['receptionSourceDetailList'], views)
;['screenList', 'materialDetailList'].forEach(name => {
if (Array.isArray(item[name])) item[name].forEach((entry, index) => {
if (name === 'materialDetailList' && !matchesCar(entry)) return
fields(entry, [name, index], ['url', 'detailUrl', 'bgUrl', 'contentPicUrl', 'homeEntranceCover', 'thumbnail'])
})
})
function caseImages(value, path) {
if (!value || typeof value !== 'object') return
Object.keys(value).forEach(key => {
if (key === 'imageUrl') add([...path, key], value[key])
else if (typeof value[key] === 'object') caseImages(value[key], [...path, key])
})
}
caseImages(item.receptionpriproCusCaseList, ['receptionpriproCusCaseList'])
return slots
}
function materialGroups(data) {
const groups = new Map()
;['moduleList', 'toolList'].forEach(kind => {
; (data[kind] || []).forEach(item => {
if (!item || !hasId(item.id)) return
const id = String(item.id)
if (!groups.has(id)) groups.set(id, [])
groups.get(id).push({ item, slots: imageSlots(item, kind) })
})
})
return groups
}
// 诊断用:枚举补齐后仍是在线图片地址的字段路径,确认还有哪些图片位置没被缓存覆盖。
function remoteImagePaths(items) {
const found = []
const walk = (value, path) => {
if (typeof value === 'string') {
if (/(^https?:\/\/).+\.(png|jpe?g|webp|gif|bmp|svg|avif)([?#]|$)/i.test(value)) found.push(path.join('.'))
return
}
if (!value || typeof value !== 'object') return
Object.keys(value).forEach(key => walk(value[key], [...path, key]))
}
items.forEach((item, index) => walk(item, [index]))
return [...new Set(found)]
}
// 直接根据当前素材 ID、图片位置和 URL 算出 key,不枚举 storage 或读取其他素材图片。
async function hydrateSourceImages(key, base, options = {}) {
const isCurrent = options.isCurrent || (() => true)
const maxImages = Number.isFinite(options.maxImages) ? Math.max(0, options.maxImages) : Infinity
let remainingImages = maxImages
const start = Date.now()
const metrics = { storageReads: 0, memoryHits: 0, sharedReads: 0, imageHits: 0, missingImages: 0, downloadedImages: 0, requestedImages: 0, pathBytes: 0, leftoverUrls: [] }
if (!isCurrent() || !isSource(base)) return null
const display = { ...base }
const hydrated = []
const pending = []
;['moduleList', 'toolList'].forEach(kind => {
const ids = options[kind === 'moduleList' ? 'moduleIds' : 'toolIds']
const selected = Array.isArray(ids) ? new Set(ids.map(String)) : null
display[kind] = base[kind].map(item => {
if (!item || !hasId(item.id) || (selected && !selected.has(String(item.id)))) return item
const allSlots = imageSlots(item, kind, options)
// 首屏只等待最能代表当前素材的图片;其余图片由后续后台读取补齐。
const slots = remainingImages === Infinity ? allSlots : allSlots
.sort((a, b) => {
const priority = ['detailUrl', 'contentPicUrl', 'bgUrl', 'homeEntranceCover', 'thumbnail', 'shortTitleUrl']
const getPriority = slot => {
const index = priority.indexOf(slot.path[slot.path.length - 1])
return index < 0 ? priority.length : index
}
return getPriority(a) - getPriority(b)
})
.slice(0, remainingImages)
remainingImages -= slots.length
if (!slots.length) return item
// 只复制本次要展示的素材,其他条目保留轻量基础数据。
const clone = JSON.parse(JSON.stringify(item))
// 首屏渐进加载时,未准备好的网络图片不能直接交给组件,避免组件绕过文件缓存自行发起请求。
if (options.hideUnloadedImages) {
const selectedKeys = new Set(slots.map(slot => slot.key))
allSlots.filter(slot => !selectedKeys.has(slot.key)).forEach(slot => {
let target = clone
slot.path.slice(0, -1).forEach(part => { target = target[part] })
target[slot.path[slot.path.length - 1]] = ''
})
}
hydrated.push(clone)
slots.forEach(slot => {
metrics.requestedImages++
pending.push(readImage(imageKey(key, item.id, slot.key), isCurrent, metrics).then(async image => {
if (!isCurrent()) return
// 首屏可能早于后台文件保存完成:缺失的位置按需补齐,优先渲染持久化文件。
if (!image && options.allowDownload) {
metrics.downloadedImages++
image = await convertSlotImage(key, item.id, slot)
if (!isCurrent()) return
}
if (!image) { metrics.missingImages++; return }
metrics.imageHits++
metrics.pathBytes += image.length * 2
let target = clone
slot.path.slice(0, -1).forEach(part => { target = target[part] })
target[slot.path[slot.path.length - 1]] = image
}))
})
return clone
})
})
await Promise.all(pending)
metrics.leftoverUrls = remoteImagePaths(hydrated).slice(0, 10)
metrics.durationMs = Date.now() - start
metrics.cancelled = !isCurrent()
if (typeof options.onMetrics === 'function') options.onMetrics(metrics)
return isCurrent() ? display : null
}
async function readSourceCache(key, online = true, options = {}) {
const isCurrent = options.isCurrent || (() => true)
if (!isCurrent()) return null
const base = await read(key)
if (!isCurrent()) return null
if (!isSource(base)) {
if (online) return null
const legacy = await read(key.replace(SOURCE_PREFIX, 'source_'))
return isCurrent() && isSource(legacy) ? legacy : null
}
if (online || options.baseOnly) return base
let incomplete = false
const display = await hydrateSourceImages(key, base, {
...options,
onMetrics: metrics => {
incomplete = metrics.missingImages > 0
if (typeof options.onMetrics === 'function') options.onMetrics(metrics)
}
})
if (!isCurrent()) return null
if (incomplete) {
// 迁移中途断网时使用完整旧快照,不能把来源不明的旧图拼到新素材上。
const legacy = await read(key.replace(SOURCE_PREFIX, 'source_'))
if (!isCurrent()) return null
if (isSource(legacy)) return legacy
}
return display
}
function downloadImageFile(url) {
return new Promise(resolve => {
const fail = reason => {
console.warn('素材图片下载失败', { url, reason })
return ''
}
if (typeof uni.downloadFile !== 'function' || typeof uni.saveFile !== 'function') {
resolve(fail('file-api-unavailable'))
return
}
uni.downloadFile({
url, timeout: 15000,
success: res => {
if (res.statusCode < 200 || res.statusCode >= 300) return resolve(fail(`status:${res.statusCode}`))
const header = res.header || {}
const typeKey = Object.keys(header).find(key => key.toLowerCase() === 'content-type')
const declaredType = typeKey ? String(header[typeKey]).split(';')[0].trim().toLowerCase() : ''
const extension = url.split(/[?#]/)[0].match(/\.(png|jpe?g|webp|gif|bmp|svg|avif)$/i)?.[1].toLowerCase()
const fallbackType = extension ? `image/${({ jpg: 'jpeg', svg: 'svg+xml' })[extension] || extension}` : ''
const mime = declaredType || fallbackType
if (!/^image\/[\w.+-]+$/.test(mime)) return resolve(fail(`type:${mime || 'unknown'}`))
if (!res.tempFilePath) return resolve(fail('empty-path'))
uni.saveFile({
tempFilePath: res.tempFilePath,
success: saved => resolve(isLocalImage(saved.savedFilePath) ? saved.savedFilePath : fail('empty-saved-path')),
fail: error => resolve(fail(error?.errMsg || 'save-file'))
})
},
fail: error => resolve(fail(error?.errMsg || 'request'))
})
})
}
function drainDownloads() {
while (activeDownloads < 3 && downloadQueue.length) {
const job = downloadQueue.shift()
if (!job.isCurrent()) { job.resolve(''); continue }
activeDownloads++
downloadImageFile(job.url).catch(() => '').then(job.resolve).finally(() => {
activeDownloads--
drainDownloads()
})
}
}
function enqueueImage(url, isCurrent) {
return new Promise(resolve => {
downloadQueue.push({ url, isCurrent, resolve })
drainDownloads()
})
}
// 下载并持久化单个槽位,storage 只保存文件路径;失败时不写成功标记,确保下次可重试。
// key 由素材 ID、图片位置和 URL 指纹共同决定,同一次下载的调用方共享结果,不会重复请求。
function convertSlotImage(key, id, slot) {
const target = imageKey(key, id, slot.key)
const pending = pendingConversions.get(target)
if (pending) return pending
const task = enqueueImage(slot.url, () => true).then(async image => {
if (!isLocalImage(image)) {
console.warn('素材图片文件保存失败', slot.url)
return ''
}
try {
await write(target, image, () => true)
} catch (error) {
await removeSavedFile(image)
console.warn('素材图片路径写入缓存失败,已清理孤立文件', target)
return ''
}
// 同一 URL 的旧 Base64 只在新文件成功后删除,迁移失败时仍保留原缓存。
remove(legacyImageKey(key, id, slot.key))
rememberImage(target, image)
return image
}).catch(() => '')
pendingConversions.set(target, task)
const cleanup = () => { if (pendingConversions.get(target) === task) pendingConversions.delete(target) }
task.then(cleanup, cleanup)
return task
}
async function cacheMaterialImages(key, base) {
const generation = (imageGenerations.get(key) || 0) + 1
imageGenerations.set(key, generation)
const isCurrent = () => imageGenerations.get(key) === generation
const slots = [...materialGroups(base)].flatMap(([id, entries]) =>
entries.flatMap(entry => entry.slots).map(slot => ({ id, slot })))
activeImageTargets.set(key, {
generation,
targets: new Set(slots.map(({ id, slot }) => imageKey(key, id, slot.key)))
})
// 只读取位置、URL 与文件路径的轻量记录,不读取图片内容。
const cachedUrls = await read(urlKey(key))
const urls = cachedUrls && typeof cachedUrls === 'object' ? { ...cachedUrls } : {}
const activeSlotNames = new Set()
let urlsChanged = false
const results = await Promise.all(slots.map(async ({ id, slot }) => {
// 素材 ID + 位置,才是本次要比对 URL 的槽位。
const slotName = `${id}_${slot.name}`
activeSlotNames.add(slotName)
const target = imageKey(key, id, slot.key)
const previous = urls[slotName]
const storedPath = await read(target)
const storedFilePath = isLocalImage(storedPath) && await savedFileExists(storedPath) ? storedPath : ''
if (isLocalImage(storedPath) && !storedFilePath) await remove(target)
const recorded = previous && previous.url === slot.url && previous.key === target &&
isLocalImage(previous.path) && storedFilePath === previous.path
// 同一素材位置上 URL 与已保存文件一致时,跳过重复下载。
if (recorded || storedFilePath) {
// 首屏补齐过的位置补记到 storage,下次冷启动同样能跳过。
if (!recorded) {
urls[slotName] = { url: slot.url, path: storedFilePath, key: target }
urlsChanged = true
}
return true
}
const image = await convertSlotImage(key, id, slot)
if (!image) return false
if (!isCurrent()) {
// 新一轮缓存或当前页面可能正在复用同一个下载结果。过期调用不能删除共享文件,
// 当前配置不再使用这个目标时才清理,避免留下旧品牌切换过程中的孤立文件。
const latest = activeImageTargets.get(key)
if (!latest?.targets.has(target)) {
await remove(target)
await removeSavedFile(image)
}
return false
}
// 新文件落盘后再清理同一位置的旧文件与旧路径记录。
if (previous && previous.url && previous.url !== slot.url) {
const previousSlotKey = md5(JSON.stringify([slot.kind, slot.path, previous.url]))
await remove(previous.key || imageKey(key, id, previousSlotKey))
await remove(legacyImageKey(key, id, previousSlotKey))
}
if (previous?.path && previous.path !== image) await removeSavedFile(previous.path)
// 文件保存及路径写入都成功后才记录 URL,失败时下次仍会重试。
urls[slotName] = { url: slot.url, path: image, key: target }
urlsChanged = true
return true
}))
// 接口已删除的图片位置不再保留文件,避免长期切换品牌后缓存只增不减。
await Promise.all(Object.keys(urls).filter(slotName => !activeSlotNames.has(slotName)).map(async slotName => {
const obsolete = urls[slotName]
if (obsolete?.key) await remove(obsolete.key)
if (obsolete?.path) await removeSavedFile(obsolete.path)
delete urls[slotName]
urlsChanged = true
}))
if (urlsChanged && isCurrent()) {
try {
await write(urlKey(key), urls, isCurrent)
} catch (error) {
console.warn('素材图片 URL 记录写入失败', key)
}
}
if (isCurrent() && results.every(Boolean)) {
// 图片全部落盘后才能结束迁移,基础缓存写入成功不代表离线图片已就绪。
await Promise.all([
remove(key.replace(SOURCE_PREFIX, 'source_')),
remove(legacyUrlKey(key))
])
}
}
module.exports = { getSourceKey, getNetworkStatus, readSourceCache, hydrateSourceImages, clearImageMemory, saveSourceCache, cacheMaterialImages }