| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672 |
- import { BrowserWindow } from 'electron'
- import { spawn } from 'child_process'
- import * as crypto from 'crypto'
- import * as fs from 'fs'
- import * as path from 'path'
- import { IpcChannels } from '@shared/ipc-channels'
- import type { BackupProgressEvent, WallpaperMeta } from '@shared/types'
- import { getConfiguredBackupPath } from './config.service'
- import * as library from './library.service'
- import { containedPath } from '../utils/contained'
- import { normalizeType, normalizeRating, type ProjectJson } from './library.service'
- function getBackupDir(id: string): string {
- const backupPath = getConfiguredBackupPath()
- if (!backupPath) throw new Error('Backup path must be configured before backing up')
- return path.join(backupPath, id)
- }
- export function resolveBackupDir(wallpaper: WallpaperMeta): string | null {
- if (wallpaper.source === 'backup' && wallpaper.localPath) return wallpaper.localPath
- if (wallpaper.backupDir) return wallpaper.backupDir
- try {
- return getBackupDir(wallpaper.id)
- } catch {
- return null
- }
- }
- async function isDir(p: string): Promise<boolean> {
- try {
- return (await fs.promises.stat(p)).isDirectory()
- } catch {
- return false
- }
- }
- export async function exists(p: string): Promise<boolean> {
- try {
- await fs.promises.access(p)
- return true
- } catch {
- return false
- }
- }
- async function readProjectJson(dir: string): Promise<ProjectJson | null> {
- try {
- return JSON.parse(await fs.promises.readFile(path.join(dir, 'project.json'), 'utf8')) as ProjectJson
- } catch {
- return null
- }
- }
- // project.json names come from Windows, where "Preview.JPG" finds preview.jpg
- async function findFileIgnoringCase(dir: string, rel: string): Promise<string | undefined> {
- const exact = containedPath(dir, rel)
- if (!exact) return undefined
- if (await exists(exact)) return exact
- const parent = path.dirname(exact)
- const name = path.basename(exact).toLowerCase()
- try {
- const match = (await fs.promises.readdir(parent)).find((f) => f.toLowerCase() === name)
- return match ? path.join(parent, match) : undefined
- } catch {
- return undefined
- }
- }
- export async function previewInBackup(wallpaper: WallpaperMeta, dir: string): Promise<string | undefined> {
- if (wallpaper.previewLocal && wallpaper.localPath) {
- const rel = path.relative(wallpaper.localPath, wallpaper.previewLocal)
- if (rel && !rel.startsWith('..') && !path.isAbsolute(rel) && (await exists(path.join(dir, rel)))) {
- return path.join(dir, rel)
- }
- }
- const pj = await readProjectJson(dir)
- const named = pj?.preview ? await findFileIgnoringCase(dir, pj.preview) : undefined
- if (named) return named
- try {
- const any = (await fs.promises.readdir(dir)).find((f) => /^preview\.(png|jpe?g|gif|webp|bmp)$/i.test(f))
- return any ? path.join(dir, any) : undefined
- } catch {
- return undefined
- }
- }
- export async function hasBackupFiles(dir: string | null): Promise<boolean> {
- return !!dir && (await isDir(dir)) && (await exists(path.join(dir, 'project.json')))
- }
- export type FolderProblem = 'missingFolder' | 'brokenProject' | 'missingMainFile'
- export async function findFolderProblem(dir: string): Promise<{ code: FolderProblem; detail: string } | null> {
- if (!(await isDir(dir))) return { code: 'missingFolder', detail: 'folder is missing' }
- const pj = await readProjectJson(dir)
- if (!pj) return { code: 'brokenProject', detail: 'project.json is missing or unreadable' }
- if (!pj.file) return null
- if (await exists(path.join(dir, pj.file))) return null
- if (normalizeType(pj.type) === 'scene' && (await fs.promises.readdir(dir)).some((f) => f.endsWith('.pkg'))) {
- return null
- }
- return { code: 'missingMainFile', detail: `${pj.file} is missing` }
- }
- async function findBackupProblem(dir: string): Promise<string | null> {
- return (await findFolderProblem(dir))?.detail ?? null
- }
- export async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
- const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
- const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
- return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
- }
- function hashFile(filePath: string): Promise<string> {
- return new Promise((resolve, reject) => {
- const hash = crypto.createHash('sha256')
- const stream = fs.createReadStream(filePath)
- stream.on('error', reject)
- stream.on('data', (chunk) => hash.update(chunk))
- stream.on('end', () => { resolve(hash.digest('hex')) })
- })
- }
- // WE writes compiled shaders into the folder
- function isShaderCache(relPath: string): boolean {
- return /^shaders[\\/]blobs/i.test(relPath)
- }
- async function walkFiles(dirPath: string, baseDir = dirPath): Promise<{ relPath: string; size: number }[]> {
- const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
- const nested = await Promise.all(
- entries.map(async (entry) => {
- const full = path.join(dirPath, entry.name)
- if (entry.isDirectory()) return isShaderCache(path.relative(baseDir, full)) ? [] : walkFiles(full, baseDir)
- if (!entry.isFile()) return []
- return [{ relPath: path.relative(baseDir, full), size: (await fs.promises.stat(full)).size }]
- })
- )
- return nested.flat()
- }
- async function walkDirs(dirPath: string): Promise<string[]> {
- const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
- const nested = await Promise.all(
- entries.filter((e) => e.isDirectory()).map((e) => walkDirs(path.join(dirPath, e.name)))
- )
- return [dirPath, ...nested.flat()]
- }
- export async function forEachLimit<T>(items: T[], limit: number, fn: (item: T) => Promise<void>): Promise<void> {
- let next = 0
- const worker = async (): Promise<void> => {
- while (next < items.length) await fn(items[next++])
- }
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
- }
- async function fsyncPath(p: string): Promise<void> {
- const handle = await fs.promises.open(p, 'r')
- try {
- await handle.sync()
- } finally {
- await handle.close()
- }
- }
- // fsynced pages are clean, so iflag=nocache can evict them and the hash check reads the disk
- function dropPageCache(dir: string): Promise<void> {
- return new Promise((resolve) => {
- const child = spawn(
- 'find',
- [dir, '-type', 'f', '-exec', 'sh', '-c',
- 'for f do dd if="$f" iflag=nocache count=0 status=none; done', 'sh', '{}', '+'],
- { stdio: 'ignore' }
- )
- child.on('error', () => { resolve() })
- child.on('close', () => { resolve() })
- })
- }
- function sendProgress(win: BrowserWindow, progress: BackupProgressEvent): void {
- if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_BACKUP_PROGRESS, progress)
- }
- function percent(done: number, total: number): number {
- return total > 0 ? Math.round((done / total) * 100) : 100
- }
- export async function backupMatchesSource(sourcePath: string, backupDir: string): Promise<boolean> {
- let src: { relPath: string; size: number }[]
- let dst: { relPath: string; size: number }[]
- try {
- ;[src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
- } catch {
- return false
- }
- if (src.length !== dst.length) return false
- const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
- if (src.some((f) => dstSizes.get(f.relPath) !== f.size)) return false
- for (const file of src) {
- const [a, b] = await Promise.all([
- hashFile(path.join(sourcePath, file.relPath)),
- hashFile(path.join(backupDir, file.relPath))
- ])
- if (a !== b) return false
- }
- return true
- }
- export async function verifyOnDisk(sourcePath: string, destDir: string): Promise<boolean> {
- try {
- for (const file of await walkFiles(destDir)) await fsyncPath(path.join(destDir, file.relPath))
- for (const dir of await walkDirs(destDir)) await fsyncPath(dir)
- } catch {
- return false
- }
- await dropPageCache(destDir)
- return backupMatchesSource(sourcePath, destDir)
- }
- export async function syncDir(dir: string): Promise<void> {
- await fsyncPath(dir)
- }
- function swapPaths(destDir: string): { stagingDir: string; oldDir: string; verifiedMark: string } {
- const root = path.dirname(destDir)
- const name = path.basename(destDir)
- return {
- stagingDir: path.join(root, `.${name}.partial`),
- oldDir: path.join(root, `.${name}.old`),
- verifiedMark: path.join(root, `.${name}.verified`)
- }
- }
- const SWAP_SUFFIX = /^\.(.+)\.(partial|old|verified)$/
- const activeCopies = new Set<string>()
- export async function recoverInterruptedCopy(destDir: string): Promise<void> {
- if (activeCopies.has(path.resolve(destDir))) return
- await recoverSwap(destDir)
- }
- function removeTree(p: string): Promise<void> {
- return fs.promises.rm(p, { recursive: true, force: true })
- }
- async function recoverSwap(destDir: string): Promise<void> {
- const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
- const [hasDest, hasOld, hasStaging, isVerified] = await Promise.all([
- exists(destDir),
- exists(oldDir),
- exists(stagingDir),
- exists(verifiedMark)
- ])
- if (!hasOld && !hasStaging && !isVerified) return
- if (!hasDest && isVerified && hasStaging) {
- await fs.promises.rename(stagingDir, destDir)
- console.warn(`[Backup] Finished an interrupted copy of ${destDir}`)
- } else if (!hasDest && hasOld) {
- await fs.promises.rename(oldDir, destDir)
- console.warn(`[Backup] Restored ${destDir} from the copy an interrupted update had set aside`)
- }
- await fsyncPath(path.dirname(destDir)).catch(() => {})
- await Promise.all([removeTree(oldDir), removeTree(stagingDir), removeTree(verifiedMark)])
- }
- export async function recoverInterruptedCopies(root: string): Promise<void> {
- let names: Set<string>
- try {
- names = new Set((await fs.promises.readdir(root)).flatMap((entry) => SWAP_SUFFIX.exec(entry)?.[1] ?? []))
- } catch {
- return
- }
- for (const name of names) {
- await recoverInterruptedCopy(path.join(root, name)).catch((err: unknown) => { console.error(`[Backup] Could not recover ${name} in ${root}:`, err) }
- )
- }
- }
- export async function recoverInterruptedCopiesIn(roots: string[]): Promise<void> {
- for (const root of new Set(roots)) await recoverInterruptedCopies(root)
- }
- export async function backupWallpaper(
- id: string,
- sourcePath: string,
- win: BrowserWindow
- ): Promise<string> {
- const destDir = getBackupDir(id)
- if (path.resolve(sourcePath) === path.resolve(destDir)) {
- throw new Error('Wallpaper already lives in the backup folder')
- }
- return copyWallpaperFolder(id, sourcePath, destDir, win, 'backup')
- }
- // staged, fsynced copy, hash-checked against the source before it replaces destDir
- export async function copyWallpaperFolder(
- id: string,
- sourcePath: string,
- destDir: string,
- win: BrowserWindow,
- action: BackupProgressEvent['action']
- ): Promise<string> {
- const key = path.resolve(destDir)
- if (activeCopies.has(key)) throw new Error(`${destDir} is already being written`)
- activeCopies.add(key)
- try {
- return await stageAndSwap(id, sourcePath, destDir, win, action)
- } finally {
- activeCopies.delete(key)
- }
- }
- async function stageAndSwap(
- id: string,
- sourcePath: string,
- destDir: string,
- win: BrowserWindow,
- action: BackupProgressEvent['action']
- ): Promise<string> {
- const destRoot = path.dirname(destDir)
- const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
- const files = await walkFiles(sourcePath)
- if (!files.some((f) => f.relPath === 'project.json')) {
- throw new Error('Source folder has no project.json, refusing to copy an incomplete wallpaper')
- }
- const bytesTotal = files.reduce((sum, f) => sum + f.size, 0)
- await fs.promises.mkdir(destRoot, { recursive: true })
- await recoverSwap(destDir)
- await fs.promises.mkdir(stagingDir)
- let bytesDone = 0
- try {
- for (const file of files) {
- const srcFile = path.join(sourcePath, file.relPath)
- const destFile = path.join(stagingDir, file.relPath)
- let srcStat: fs.Stats
- try {
- srcStat = await fs.promises.stat(srcFile)
- } catch {
- throw new Error(`Source file is gone, refusing to copy: ${file.relPath}`)
- }
- if (!srcStat.isFile() || srcStat.size !== file.size) {
- throw new Error(`Source file changed since it was scanned, refusing to copy: ${file.relPath}`)
- }
- await fs.promises.mkdir(path.dirname(destFile), { recursive: true })
- await fs.promises.copyFile(srcFile, destFile)
- await fsyncPath(destFile)
- bytesDone += file.size
- sendProgress(win, {
- itemId: id,
- action,
- bytesCopied: bytesDone,
- bytesTotal,
- percentage: percent(bytesDone, bytesTotal),
- status: 'copying'
- })
- }
- for (const dir of await walkDirs(stagingDir)) await fsyncPath(dir)
- await dropPageCache(stagingDir)
- bytesDone = 0
- for (const file of files) {
- const destFile = path.join(stagingDir, file.relPath)
- const destSize = (await fs.promises.stat(destFile)).size
- if (destSize !== file.size) {
- throw new Error(
- `Verification failed for ${file.relPath}: expected ${file.size} bytes, got ${destSize}`
- )
- }
- const [srcHash, destHash] = await Promise.all([
- hashFile(path.join(sourcePath, file.relPath)),
- hashFile(destFile)
- ])
- if (srcHash !== destHash) {
- throw new Error(`Verification failed for ${file.relPath}: hash mismatch`)
- }
- bytesDone += file.size
- sendProgress(win, {
- itemId: id,
- action,
- bytesCopied: bytesDone,
- bytesTotal,
- percentage: percent(bytesDone, bytesTotal),
- status: 'verifying'
- })
- }
- await fs.promises.writeFile(verifiedMark, '')
- await fsyncPath(verifiedMark)
- await fsyncPath(destRoot)
- const hadOld = await exists(destDir)
- if (hadOld) await fs.promises.rename(destDir, oldDir)
- try {
- await fs.promises.rename(stagingDir, destDir)
- } catch (err) {
- if (hadOld) await fs.promises.rename(oldDir, destDir)
- throw err
- }
- await fsyncPath(destRoot)
- await Promise.all([removeTree(oldDir), removeTree(verifiedMark)])
- } catch (err) {
- await Promise.all([removeTree(stagingDir), removeTree(verifiedMark)].map((removal) => removal.catch(() => {})))
- sendProgress(win, {
- itemId: id,
- action,
- bytesCopied: bytesDone,
- bytesTotal,
- percentage: 0,
- status: 'error',
- message: (err as Error).message
- })
- throw err
- }
- sendProgress(win, { itemId: id, action, bytesCopied: bytesTotal, bytesTotal, percentage: 100, status: 'completed' })
- return destDir
- }
- function isDeletableBackupDir(wallpaper: WallpaperMeta, dir: string): boolean {
- const resolved = path.resolve(dir)
- if (wallpaper.backupDir && path.resolve(wallpaper.backupDir) === resolved) return true
- if (wallpaper.source === 'backup' && path.basename(resolved) === wallpaper.id) return true
- const backupPath = getConfiguredBackupPath()
- return !!backupPath && path.dirname(resolved) === path.resolve(backupPath)
- }
- export async function removeBackup(id: string): Promise<{ keptDir: string | null }> {
- const wallpaper = library.getWallpaper(id)
- if (!wallpaper) return { keptDir: null }
- const dir = resolveBackupDir(wallpaper)
- let keptDir: string | null = null
- if (dir && (await exists(dir))) {
- const isWorkshopCopy =
- wallpaper.source !== 'backup' && !!wallpaper.localPath && path.resolve(wallpaper.localPath) === path.resolve(dir)
- if (isWorkshopCopy || !isDeletableBackupDir(wallpaper, dir)) {
- keptDir = dir
- console.warn(`[Backup] Not deleting ${dir} for ${id}, only dropping the reference`)
- } else {
- await fs.promises.rm(dir, { recursive: true, force: true })
- }
- }
- if (wallpaper.source === 'backup') {
- library.deleteWallpaper(id)
- } else {
- library.updateWallpaper(id, { backedUp: false, backupDir: undefined })
- }
- return { keptDir }
- }
- async function buildBackupMeta(id: string, localPath: string, existing?: WallpaperMeta): Promise<WallpaperMeta> {
- const [pj, files] = await Promise.all([readProjectJson(localPath), walkFiles(localPath)])
- const now = Date.now()
- return {
- id,
- title: pj?.title ?? existing?.title ?? `Wallpaper ${id}`,
- type: normalizeType(pj?.type),
- contentRating: normalizeRating(pj?.contentrating),
- description: pj?.description ?? existing?.description,
- previewLocal: containedPath(localPath, pj?.preview),
- localPath,
- file: pj?.file,
- fileSize: files.reduce((sum, f) => sum + f.size, 0),
- createdAt: existing?.createdAt ?? now,
- updatedAt: now,
- subscribed: false,
- appliedCount: existing?.appliedCount ?? 0,
- source: 'backup',
- tags: pj?.tags ?? existing?.tags ?? [],
- resolutions: existing?.resolutions,
- categories: existing?.categories ?? [],
- backedUp: true,
- backupDir: localPath
- }
- }
- const SCAN_CONCURRENCY = 4
- async function previewRepair(w: WallpaperMeta): Promise<Partial<WallpaperMeta> | null> {
- const patch: Partial<WallpaperMeta> = {}
- if (w.customPreview && !(await exists(w.customPreview))) {
- patch.customPreview = undefined
- patch.useOriginalPreview = false
- }
- if (!w.previewLocal || !(await exists(w.previewLocal))) {
- const dirs = [w.localPath, resolveBackupDir(w)].filter((d): d is string => !!d)
- let mounted = false
- for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {
- if (!(await isDir(dir))) continue
- mounted = true
- const found = await previewInBackup(w, dir)
- if (found) {
- patch.previewLocal = found
- break
- }
- }
- if (!patch.previewLocal && mounted && w.previewLocal) patch.previewLocal = undefined
- }
- return Object.keys(patch).length > 0 ? patch : null
- }
- async function previewRepairs(wallpapers: WallpaperMeta[]): Promise<{ id: string; patch: Partial<WallpaperMeta> }[]> {
- const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
- await forEachLimit(
- wallpapers.filter((w) => !w.downloading),
- SCAN_CONCURRENCY,
- async (w) => {
- const patch = await previewRepair(w)
- if (patch) patches.push({ id: w.id, patch })
- }
- )
- return patches
- }
- export async function scanBackupFolder(): Promise<{
- imported: number
- skipped: number
- linked: number
- removed: number
- unlinked: number
- previewsFixed: number
- corrupted: string[]
- }> {
- const result = {
- imported: 0,
- skipped: 0,
- linked: 0,
- removed: 0,
- unlinked: 0,
- previewsFixed: 0,
- corrupted: [] as string[]
- }
- const backupPath = getConfiguredBackupPath()
- const wallpapers = new Map(library.getAllWallpapers().map((w) => [w.id, w]))
- if (!backupPath || !(await isDir(backupPath))) {
- const patches = await previewRepairs([...wallpapers.values()])
- library.applyWallpaperChanges({ patches })
- result.previewsFixed = patches.length
- return result
- }
- await recoverInterruptedCopies(backupPath)
- const folderIds = (await fs.promises.readdir(backupPath, { withFileTypes: true }))
- // dot folders are staging copies of an in-progress backup
- .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
- .map((e) => e.name)
- const problems = new Map<string, Promise<string | null>>()
- const problemOf = (dir: string): Promise<string | null> => {
- const key = path.resolve(dir)
- if (!problems.has(key)) problems.set(key, findBackupProblem(dir))
- return problems.get(key)!
- }
- const upserts: WallpaperMeta[] = []
- const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
- const deletes: string[] = []
- const referenced = [...wallpapers.values()].filter((w) => (w.source === 'backup' || w.backedUp) && !w.downloading)
- await forEachLimit(referenced, SCAN_CONCURRENCY, async (w) => {
- const dir = resolveBackupDir(w)
- // the drive holding it is not mounted
- if (dir && !(await isDir(path.dirname(dir)))) return
- const reason = dir ? await problemOf(dir) : 'no backup folder'
- if (!reason) return
- console.warn(`[Backup] Dropping broken backup of ${w.id} at ${dir}: ${reason}`)
- if (w.source === 'backup') {
- deletes.push(w.id)
- result.removed++
- } else {
- patches.push({ id: w.id, patch: { backedUp: false, backupDir: undefined } })
- result.unlinked++
- }
- })
- const dropped = new Set([...deletes, ...patches.map((p) => p.id)])
- await forEachLimit(folderIds, SCAN_CONCURRENCY, async (id) => {
- const dir = path.join(backupPath, id)
- const problem = await problemOf(dir)
- if (problem) {
- console.warn(`[Backup] Skipping corrupted backup ${dir}: ${problem}`)
- result.corrupted.push(id)
- return
- }
- const existing = wallpapers.get(id)
- if (existing?.source === 'workshop' || existing?.source === 'local') {
- if ((existing.backedUp && !dropped.has(id)) || existing.downloading) {
- result.skipped++
- } else {
- // outdated is still a backup
- patches.push({ id, patch: { backedUp: true, backupDir: dir } })
- result.linked++
- }
- return
- }
- if (
- existing?.source === 'backup' &&
- !dropped.has(id) &&
- existing.fileSize !== undefined &&
- path.resolve(existing.localPath ?? '') === path.resolve(dir)
- ) {
- result.skipped++
- return
- }
- upserts.push(await buildBackupMeta(id, dir, existing))
- result.imported++
- })
- const reimported = new Set(upserts.map((m) => m.id))
- const previewPatches = await previewRepairs(
- [...wallpapers.values()].filter((w) => !reimported.has(w.id) && !deletes.includes(w.id))
- )
- patches.push(...previewPatches)
- result.previewsFixed = previewPatches.length
- library.applyWallpaperChanges({
- upserts,
- patches,
- deletes: deletes.filter((id) => !reimported.has(id))
- })
- result.removed -= deletes.filter((id) => reimported.has(id)).length
- result.corrupted.sort()
- return result
- }
- // only changed workshop folders get re-walked
- const outdatedCheckedAt = new Map<string, string>()
- export async function checkOutdatedBackups(): Promise<boolean> {
- const candidates = library
- .getAllWallpapers()
- .filter((w) => w.source === 'workshop' && w.backedUp && !w.downloading && w.localPath)
- const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
- await forEachLimit(candidates, SCAN_CONCURRENCY, async (w) => {
- const dir = resolveBackupDir(w)
- if (!dir) return
- let key: string
- try {
- const stat = await fs.promises.stat(w.localPath!)
- key = `${w.updatedAt}|${dir}|${stat.mtimeMs}`
- } catch {
- return
- }
- if (outdatedCheckedAt.get(w.id) === key) return
- let outdated: boolean
- try {
- outdated = !(await sameFileList(w.localPath!, dir))
- } catch {
- // backup drive not mounted, or the folder is being replaced right now
- return
- }
- outdatedCheckedAt.set(w.id, key)
- if (!!w.backupOutdated !== outdated) patches.push({ id: w.id, patch: { backupOutdated: outdated } })
- })
- if (patches.length > 0) library.applyWallpaperChanges({ patches })
- return patches.length > 0
- }
|