backup.service.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import { BrowserWindow } from 'electron'
  2. import { spawn } from 'child_process'
  3. import * as crypto from 'crypto'
  4. import * as fs from 'fs'
  5. import * as path from 'path'
  6. import { IpcChannels } from '@shared/ipc-channels'
  7. import type { BackupProgressEvent, WallpaperMeta } from '@shared/types'
  8. import { getConfiguredBackupPath } from './config.service'
  9. import * as library from './library.service'
  10. import { containedPath } from '../utils/contained'
  11. import { normalizeType, normalizeRating, type ProjectJson } from './library.service'
  12. function getBackupDir(id: string): string {
  13. const backupPath = getConfiguredBackupPath()
  14. if (!backupPath) throw new Error('Backup path must be configured before backing up')
  15. return path.join(backupPath, id)
  16. }
  17. export function resolveBackupDir(wallpaper: WallpaperMeta): string | null {
  18. if (wallpaper.source === 'backup' && wallpaper.localPath) return wallpaper.localPath
  19. if (wallpaper.backupDir) return wallpaper.backupDir
  20. try {
  21. return getBackupDir(wallpaper.id)
  22. } catch {
  23. return null
  24. }
  25. }
  26. async function isDir(p: string): Promise<boolean> {
  27. try {
  28. return (await fs.promises.stat(p)).isDirectory()
  29. } catch {
  30. return false
  31. }
  32. }
  33. export async function exists(p: string): Promise<boolean> {
  34. try {
  35. await fs.promises.access(p)
  36. return true
  37. } catch {
  38. return false
  39. }
  40. }
  41. async function readProjectJson(dir: string): Promise<ProjectJson | null> {
  42. try {
  43. return JSON.parse(await fs.promises.readFile(path.join(dir, 'project.json'), 'utf8')) as ProjectJson
  44. } catch {
  45. return null
  46. }
  47. }
  48. // project.json names come from Windows, where "Preview.JPG" finds preview.jpg
  49. async function findFileIgnoringCase(dir: string, rel: string): Promise<string | undefined> {
  50. const exact = containedPath(dir, rel)
  51. if (!exact) return undefined
  52. if (await exists(exact)) return exact
  53. const parent = path.dirname(exact)
  54. const name = path.basename(exact).toLowerCase()
  55. try {
  56. const match = (await fs.promises.readdir(parent)).find((f) => f.toLowerCase() === name)
  57. return match ? path.join(parent, match) : undefined
  58. } catch {
  59. return undefined
  60. }
  61. }
  62. export async function previewInBackup(wallpaper: WallpaperMeta, dir: string): Promise<string | undefined> {
  63. if (wallpaper.previewLocal && wallpaper.localPath) {
  64. const rel = path.relative(wallpaper.localPath, wallpaper.previewLocal)
  65. if (rel && !rel.startsWith('..') && !path.isAbsolute(rel) && (await exists(path.join(dir, rel)))) {
  66. return path.join(dir, rel)
  67. }
  68. }
  69. const pj = await readProjectJson(dir)
  70. const named = pj?.preview ? await findFileIgnoringCase(dir, pj.preview) : undefined
  71. if (named) return named
  72. try {
  73. const any = (await fs.promises.readdir(dir)).find((f) => /^preview\.(png|jpe?g|gif|webp|bmp)$/i.test(f))
  74. return any ? path.join(dir, any) : undefined
  75. } catch {
  76. return undefined
  77. }
  78. }
  79. export async function hasBackupFiles(dir: string | null): Promise<boolean> {
  80. return !!dir && (await isDir(dir)) && (await exists(path.join(dir, 'project.json')))
  81. }
  82. export type FolderProblem = 'missingFolder' | 'brokenProject' | 'missingMainFile'
  83. export async function findFolderProblem(dir: string): Promise<{ code: FolderProblem; detail: string } | null> {
  84. if (!(await isDir(dir))) return { code: 'missingFolder', detail: 'folder is missing' }
  85. const pj = await readProjectJson(dir)
  86. if (!pj) return { code: 'brokenProject', detail: 'project.json is missing or unreadable' }
  87. if (!pj.file) return null
  88. if (await exists(path.join(dir, pj.file))) return null
  89. if (normalizeType(pj.type) === 'scene' && (await fs.promises.readdir(dir)).some((f) => f.endsWith('.pkg'))) {
  90. return null
  91. }
  92. return { code: 'missingMainFile', detail: `${pj.file} is missing` }
  93. }
  94. async function findBackupProblem(dir: string): Promise<string | null> {
  95. return (await findFolderProblem(dir))?.detail ?? null
  96. }
  97. export async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
  98. const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
  99. const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
  100. return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
  101. }
  102. function hashFile(filePath: string): Promise<string> {
  103. return new Promise((resolve, reject) => {
  104. const hash = crypto.createHash('sha256')
  105. const stream = fs.createReadStream(filePath)
  106. stream.on('error', reject)
  107. stream.on('data', (chunk) => hash.update(chunk))
  108. stream.on('end', () => { resolve(hash.digest('hex')) })
  109. })
  110. }
  111. // WE writes compiled shaders into the folder
  112. function isShaderCache(relPath: string): boolean {
  113. return /^shaders[\\/]blobs/i.test(relPath)
  114. }
  115. async function walkFiles(dirPath: string, baseDir = dirPath): Promise<{ relPath: string; size: number }[]> {
  116. const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
  117. const nested = await Promise.all(
  118. entries.map(async (entry) => {
  119. const full = path.join(dirPath, entry.name)
  120. if (entry.isDirectory()) return isShaderCache(path.relative(baseDir, full)) ? [] : walkFiles(full, baseDir)
  121. if (!entry.isFile()) return []
  122. return [{ relPath: path.relative(baseDir, full), size: (await fs.promises.stat(full)).size }]
  123. })
  124. )
  125. return nested.flat()
  126. }
  127. async function walkDirs(dirPath: string): Promise<string[]> {
  128. const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
  129. const nested = await Promise.all(
  130. entries.filter((e) => e.isDirectory()).map((e) => walkDirs(path.join(dirPath, e.name)))
  131. )
  132. return [dirPath, ...nested.flat()]
  133. }
  134. export async function forEachLimit<T>(items: T[], limit: number, fn: (item: T) => Promise<void>): Promise<void> {
  135. let next = 0
  136. const worker = async (): Promise<void> => {
  137. while (next < items.length) await fn(items[next++])
  138. }
  139. await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
  140. }
  141. async function fsyncPath(p: string): Promise<void> {
  142. const handle = await fs.promises.open(p, 'r')
  143. try {
  144. await handle.sync()
  145. } finally {
  146. await handle.close()
  147. }
  148. }
  149. // fsynced pages are clean, so iflag=nocache can evict them and the hash check reads the disk
  150. function dropPageCache(dir: string): Promise<void> {
  151. return new Promise((resolve) => {
  152. const child = spawn(
  153. 'find',
  154. [dir, '-type', 'f', '-exec', 'sh', '-c',
  155. 'for f do dd if="$f" iflag=nocache count=0 status=none; done', 'sh', '{}', '+'],
  156. { stdio: 'ignore' }
  157. )
  158. child.on('error', () => { resolve() })
  159. child.on('close', () => { resolve() })
  160. })
  161. }
  162. function sendProgress(win: BrowserWindow, progress: BackupProgressEvent): void {
  163. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_BACKUP_PROGRESS, progress)
  164. }
  165. function percent(done: number, total: number): number {
  166. return total > 0 ? Math.round((done / total) * 100) : 100
  167. }
  168. export async function backupMatchesSource(sourcePath: string, backupDir: string): Promise<boolean> {
  169. let src: { relPath: string; size: number }[]
  170. let dst: { relPath: string; size: number }[]
  171. try {
  172. ;[src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
  173. } catch {
  174. return false
  175. }
  176. if (src.length !== dst.length) return false
  177. const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
  178. if (src.some((f) => dstSizes.get(f.relPath) !== f.size)) return false
  179. for (const file of src) {
  180. const [a, b] = await Promise.all([
  181. hashFile(path.join(sourcePath, file.relPath)),
  182. hashFile(path.join(backupDir, file.relPath))
  183. ])
  184. if (a !== b) return false
  185. }
  186. return true
  187. }
  188. export async function verifyOnDisk(sourcePath: string, destDir: string): Promise<boolean> {
  189. try {
  190. for (const file of await walkFiles(destDir)) await fsyncPath(path.join(destDir, file.relPath))
  191. for (const dir of await walkDirs(destDir)) await fsyncPath(dir)
  192. } catch {
  193. return false
  194. }
  195. await dropPageCache(destDir)
  196. return backupMatchesSource(sourcePath, destDir)
  197. }
  198. export async function syncDir(dir: string): Promise<void> {
  199. await fsyncPath(dir)
  200. }
  201. function swapPaths(destDir: string): { stagingDir: string; oldDir: string; verifiedMark: string } {
  202. const root = path.dirname(destDir)
  203. const name = path.basename(destDir)
  204. return {
  205. stagingDir: path.join(root, `.${name}.partial`),
  206. oldDir: path.join(root, `.${name}.old`),
  207. verifiedMark: path.join(root, `.${name}.verified`)
  208. }
  209. }
  210. const SWAP_SUFFIX = /^\.(.+)\.(partial|old|verified)$/
  211. const activeCopies = new Set<string>()
  212. export async function recoverInterruptedCopy(destDir: string): Promise<void> {
  213. if (activeCopies.has(path.resolve(destDir))) return
  214. await recoverSwap(destDir)
  215. }
  216. function removeTree(p: string): Promise<void> {
  217. return fs.promises.rm(p, { recursive: true, force: true })
  218. }
  219. async function recoverSwap(destDir: string): Promise<void> {
  220. const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
  221. const [hasDest, hasOld, hasStaging, isVerified] = await Promise.all([
  222. exists(destDir),
  223. exists(oldDir),
  224. exists(stagingDir),
  225. exists(verifiedMark)
  226. ])
  227. if (!hasOld && !hasStaging && !isVerified) return
  228. if (!hasDest && isVerified && hasStaging) {
  229. await fs.promises.rename(stagingDir, destDir)
  230. console.warn(`[Backup] Finished an interrupted copy of ${destDir}`)
  231. } else if (!hasDest && hasOld) {
  232. await fs.promises.rename(oldDir, destDir)
  233. console.warn(`[Backup] Restored ${destDir} from the copy an interrupted update had set aside`)
  234. }
  235. await fsyncPath(path.dirname(destDir)).catch(() => {})
  236. await Promise.all([removeTree(oldDir), removeTree(stagingDir), removeTree(verifiedMark)])
  237. }
  238. export async function recoverInterruptedCopies(root: string): Promise<void> {
  239. let names: Set<string>
  240. try {
  241. names = new Set((await fs.promises.readdir(root)).flatMap((entry) => SWAP_SUFFIX.exec(entry)?.[1] ?? []))
  242. } catch {
  243. return
  244. }
  245. for (const name of names) {
  246. await recoverInterruptedCopy(path.join(root, name)).catch((err: unknown) => { console.error(`[Backup] Could not recover ${name} in ${root}:`, err) }
  247. )
  248. }
  249. }
  250. export async function recoverInterruptedCopiesIn(roots: string[]): Promise<void> {
  251. for (const root of new Set(roots)) await recoverInterruptedCopies(root)
  252. }
  253. export async function backupWallpaper(
  254. id: string,
  255. sourcePath: string,
  256. win: BrowserWindow
  257. ): Promise<string> {
  258. const destDir = getBackupDir(id)
  259. if (path.resolve(sourcePath) === path.resolve(destDir)) {
  260. throw new Error('Wallpaper already lives in the backup folder')
  261. }
  262. return copyWallpaperFolder(id, sourcePath, destDir, win, 'backup')
  263. }
  264. // staged, fsynced copy, hash-checked against the source before it replaces destDir
  265. export async function copyWallpaperFolder(
  266. id: string,
  267. sourcePath: string,
  268. destDir: string,
  269. win: BrowserWindow,
  270. action: BackupProgressEvent['action']
  271. ): Promise<string> {
  272. const key = path.resolve(destDir)
  273. if (activeCopies.has(key)) throw new Error(`${destDir} is already being written`)
  274. activeCopies.add(key)
  275. try {
  276. return await stageAndSwap(id, sourcePath, destDir, win, action)
  277. } finally {
  278. activeCopies.delete(key)
  279. }
  280. }
  281. async function stageAndSwap(
  282. id: string,
  283. sourcePath: string,
  284. destDir: string,
  285. win: BrowserWindow,
  286. action: BackupProgressEvent['action']
  287. ): Promise<string> {
  288. const destRoot = path.dirname(destDir)
  289. const { stagingDir, oldDir, verifiedMark } = swapPaths(destDir)
  290. const files = await walkFiles(sourcePath)
  291. if (!files.some((f) => f.relPath === 'project.json')) {
  292. throw new Error('Source folder has no project.json, refusing to copy an incomplete wallpaper')
  293. }
  294. const bytesTotal = files.reduce((sum, f) => sum + f.size, 0)
  295. await fs.promises.mkdir(destRoot, { recursive: true })
  296. await recoverSwap(destDir)
  297. await fs.promises.mkdir(stagingDir)
  298. let bytesDone = 0
  299. try {
  300. for (const file of files) {
  301. const srcFile = path.join(sourcePath, file.relPath)
  302. const destFile = path.join(stagingDir, file.relPath)
  303. let srcStat: fs.Stats
  304. try {
  305. srcStat = await fs.promises.stat(srcFile)
  306. } catch {
  307. throw new Error(`Source file is gone, refusing to copy: ${file.relPath}`)
  308. }
  309. if (!srcStat.isFile() || srcStat.size !== file.size) {
  310. throw new Error(`Source file changed since it was scanned, refusing to copy: ${file.relPath}`)
  311. }
  312. await fs.promises.mkdir(path.dirname(destFile), { recursive: true })
  313. await fs.promises.copyFile(srcFile, destFile)
  314. await fsyncPath(destFile)
  315. bytesDone += file.size
  316. sendProgress(win, {
  317. itemId: id,
  318. action,
  319. bytesCopied: bytesDone,
  320. bytesTotal,
  321. percentage: percent(bytesDone, bytesTotal),
  322. status: 'copying'
  323. })
  324. }
  325. for (const dir of await walkDirs(stagingDir)) await fsyncPath(dir)
  326. await dropPageCache(stagingDir)
  327. bytesDone = 0
  328. for (const file of files) {
  329. const destFile = path.join(stagingDir, file.relPath)
  330. const destSize = (await fs.promises.stat(destFile)).size
  331. if (destSize !== file.size) {
  332. throw new Error(
  333. `Verification failed for ${file.relPath}: expected ${file.size} bytes, got ${destSize}`
  334. )
  335. }
  336. const [srcHash, destHash] = await Promise.all([
  337. hashFile(path.join(sourcePath, file.relPath)),
  338. hashFile(destFile)
  339. ])
  340. if (srcHash !== destHash) {
  341. throw new Error(`Verification failed for ${file.relPath}: hash mismatch`)
  342. }
  343. bytesDone += file.size
  344. sendProgress(win, {
  345. itemId: id,
  346. action,
  347. bytesCopied: bytesDone,
  348. bytesTotal,
  349. percentage: percent(bytesDone, bytesTotal),
  350. status: 'verifying'
  351. })
  352. }
  353. await fs.promises.writeFile(verifiedMark, '')
  354. await fsyncPath(verifiedMark)
  355. await fsyncPath(destRoot)
  356. const hadOld = await exists(destDir)
  357. if (hadOld) await fs.promises.rename(destDir, oldDir)
  358. try {
  359. await fs.promises.rename(stagingDir, destDir)
  360. } catch (err) {
  361. if (hadOld) await fs.promises.rename(oldDir, destDir)
  362. throw err
  363. }
  364. await fsyncPath(destRoot)
  365. await Promise.all([removeTree(oldDir), removeTree(verifiedMark)])
  366. } catch (err) {
  367. await Promise.all([removeTree(stagingDir), removeTree(verifiedMark)].map((removal) => removal.catch(() => {})))
  368. sendProgress(win, {
  369. itemId: id,
  370. action,
  371. bytesCopied: bytesDone,
  372. bytesTotal,
  373. percentage: 0,
  374. status: 'error',
  375. message: (err as Error).message
  376. })
  377. throw err
  378. }
  379. sendProgress(win, { itemId: id, action, bytesCopied: bytesTotal, bytesTotal, percentage: 100, status: 'completed' })
  380. return destDir
  381. }
  382. function isDeletableBackupDir(wallpaper: WallpaperMeta, dir: string): boolean {
  383. const resolved = path.resolve(dir)
  384. if (wallpaper.backupDir && path.resolve(wallpaper.backupDir) === resolved) return true
  385. if (wallpaper.source === 'backup' && path.basename(resolved) === wallpaper.id) return true
  386. const backupPath = getConfiguredBackupPath()
  387. return !!backupPath && path.dirname(resolved) === path.resolve(backupPath)
  388. }
  389. export async function removeBackup(id: string): Promise<{ keptDir: string | null }> {
  390. const wallpaper = library.getWallpaper(id)
  391. if (!wallpaper) return { keptDir: null }
  392. const dir = resolveBackupDir(wallpaper)
  393. let keptDir: string | null = null
  394. if (dir && (await exists(dir))) {
  395. const isWorkshopCopy =
  396. wallpaper.source !== 'backup' && !!wallpaper.localPath && path.resolve(wallpaper.localPath) === path.resolve(dir)
  397. if (isWorkshopCopy || !isDeletableBackupDir(wallpaper, dir)) {
  398. keptDir = dir
  399. console.warn(`[Backup] Not deleting ${dir} for ${id}, only dropping the reference`)
  400. } else {
  401. await fs.promises.rm(dir, { recursive: true, force: true })
  402. }
  403. }
  404. if (wallpaper.source === 'backup') {
  405. library.deleteWallpaper(id)
  406. } else {
  407. library.updateWallpaper(id, { backedUp: false, backupDir: undefined })
  408. }
  409. return { keptDir }
  410. }
  411. async function buildBackupMeta(id: string, localPath: string, existing?: WallpaperMeta): Promise<WallpaperMeta> {
  412. const [pj, files] = await Promise.all([readProjectJson(localPath), walkFiles(localPath)])
  413. const now = Date.now()
  414. return {
  415. id,
  416. title: pj?.title ?? existing?.title ?? `Wallpaper ${id}`,
  417. type: normalizeType(pj?.type),
  418. contentRating: normalizeRating(pj?.contentrating),
  419. description: pj?.description ?? existing?.description,
  420. previewLocal: containedPath(localPath, pj?.preview),
  421. localPath,
  422. file: pj?.file,
  423. fileSize: files.reduce((sum, f) => sum + f.size, 0),
  424. createdAt: existing?.createdAt ?? now,
  425. updatedAt: now,
  426. subscribed: false,
  427. appliedCount: existing?.appliedCount ?? 0,
  428. source: 'backup',
  429. tags: pj?.tags ?? existing?.tags ?? [],
  430. resolutions: existing?.resolutions,
  431. categories: existing?.categories ?? [],
  432. backedUp: true,
  433. backupDir: localPath
  434. }
  435. }
  436. const SCAN_CONCURRENCY = 4
  437. async function previewRepair(w: WallpaperMeta): Promise<Partial<WallpaperMeta> | null> {
  438. const patch: Partial<WallpaperMeta> = {}
  439. if (w.customPreview && !(await exists(w.customPreview))) {
  440. patch.customPreview = undefined
  441. patch.useOriginalPreview = false
  442. }
  443. if (!w.previewLocal || !(await exists(w.previewLocal))) {
  444. const dirs = [w.localPath, resolveBackupDir(w)].filter((d): d is string => !!d)
  445. let mounted = false
  446. for (const dir of new Set(dirs.map((d) => path.resolve(d)))) {
  447. if (!(await isDir(dir))) continue
  448. mounted = true
  449. const found = await previewInBackup(w, dir)
  450. if (found) {
  451. patch.previewLocal = found
  452. break
  453. }
  454. }
  455. if (!patch.previewLocal && mounted && w.previewLocal) patch.previewLocal = undefined
  456. }
  457. return Object.keys(patch).length > 0 ? patch : null
  458. }
  459. async function previewRepairs(wallpapers: WallpaperMeta[]): Promise<{ id: string; patch: Partial<WallpaperMeta> }[]> {
  460. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  461. await forEachLimit(
  462. wallpapers.filter((w) => !w.downloading),
  463. SCAN_CONCURRENCY,
  464. async (w) => {
  465. const patch = await previewRepair(w)
  466. if (patch) patches.push({ id: w.id, patch })
  467. }
  468. )
  469. return patches
  470. }
  471. export async function scanBackupFolder(): Promise<{
  472. imported: number
  473. skipped: number
  474. linked: number
  475. removed: number
  476. unlinked: number
  477. previewsFixed: number
  478. corrupted: string[]
  479. }> {
  480. const result = {
  481. imported: 0,
  482. skipped: 0,
  483. linked: 0,
  484. removed: 0,
  485. unlinked: 0,
  486. previewsFixed: 0,
  487. corrupted: [] as string[]
  488. }
  489. const backupPath = getConfiguredBackupPath()
  490. const wallpapers = new Map(library.getAllWallpapers().map((w) => [w.id, w]))
  491. if (!backupPath || !(await isDir(backupPath))) {
  492. const patches = await previewRepairs([...wallpapers.values()])
  493. library.applyWallpaperChanges({ patches })
  494. result.previewsFixed = patches.length
  495. return result
  496. }
  497. await recoverInterruptedCopies(backupPath)
  498. const folderIds = (await fs.promises.readdir(backupPath, { withFileTypes: true }))
  499. // dot folders are staging copies of an in-progress backup
  500. .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
  501. .map((e) => e.name)
  502. const problems = new Map<string, Promise<string | null>>()
  503. const problemOf = (dir: string): Promise<string | null> => {
  504. const key = path.resolve(dir)
  505. if (!problems.has(key)) problems.set(key, findBackupProblem(dir))
  506. return problems.get(key)!
  507. }
  508. const upserts: WallpaperMeta[] = []
  509. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  510. const deletes: string[] = []
  511. const referenced = [...wallpapers.values()].filter((w) => (w.source === 'backup' || w.backedUp) && !w.downloading)
  512. await forEachLimit(referenced, SCAN_CONCURRENCY, async (w) => {
  513. const dir = resolveBackupDir(w)
  514. // the drive holding it is not mounted
  515. if (dir && !(await isDir(path.dirname(dir)))) return
  516. const reason = dir ? await problemOf(dir) : 'no backup folder'
  517. if (!reason) return
  518. console.warn(`[Backup] Dropping broken backup of ${w.id} at ${dir}: ${reason}`)
  519. if (w.source === 'backup') {
  520. deletes.push(w.id)
  521. result.removed++
  522. } else {
  523. patches.push({ id: w.id, patch: { backedUp: false, backupDir: undefined } })
  524. result.unlinked++
  525. }
  526. })
  527. const dropped = new Set([...deletes, ...patches.map((p) => p.id)])
  528. await forEachLimit(folderIds, SCAN_CONCURRENCY, async (id) => {
  529. const dir = path.join(backupPath, id)
  530. const problem = await problemOf(dir)
  531. if (problem) {
  532. console.warn(`[Backup] Skipping corrupted backup ${dir}: ${problem}`)
  533. result.corrupted.push(id)
  534. return
  535. }
  536. const existing = wallpapers.get(id)
  537. if (existing?.source === 'workshop' || existing?.source === 'local') {
  538. if ((existing.backedUp && !dropped.has(id)) || existing.downloading) {
  539. result.skipped++
  540. } else {
  541. // outdated is still a backup
  542. patches.push({ id, patch: { backedUp: true, backupDir: dir } })
  543. result.linked++
  544. }
  545. return
  546. }
  547. if (
  548. existing?.source === 'backup' &&
  549. !dropped.has(id) &&
  550. existing.fileSize !== undefined &&
  551. path.resolve(existing.localPath ?? '') === path.resolve(dir)
  552. ) {
  553. result.skipped++
  554. return
  555. }
  556. upserts.push(await buildBackupMeta(id, dir, existing))
  557. result.imported++
  558. })
  559. const reimported = new Set(upserts.map((m) => m.id))
  560. const previewPatches = await previewRepairs(
  561. [...wallpapers.values()].filter((w) => !reimported.has(w.id) && !deletes.includes(w.id))
  562. )
  563. patches.push(...previewPatches)
  564. result.previewsFixed = previewPatches.length
  565. library.applyWallpaperChanges({
  566. upserts,
  567. patches,
  568. deletes: deletes.filter((id) => !reimported.has(id))
  569. })
  570. result.removed -= deletes.filter((id) => reimported.has(id)).length
  571. result.corrupted.sort()
  572. return result
  573. }
  574. // only changed workshop folders get re-walked
  575. const outdatedCheckedAt = new Map<string, string>()
  576. export async function checkOutdatedBackups(): Promise<boolean> {
  577. const candidates = library
  578. .getAllWallpapers()
  579. .filter((w) => w.source === 'workshop' && w.backedUp && !w.downloading && w.localPath)
  580. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  581. await forEachLimit(candidates, SCAN_CONCURRENCY, async (w) => {
  582. const dir = resolveBackupDir(w)
  583. if (!dir) return
  584. let key: string
  585. try {
  586. const stat = await fs.promises.stat(w.localPath!)
  587. key = `${w.updatedAt}|${dir}|${stat.mtimeMs}`
  588. } catch {
  589. return
  590. }
  591. if (outdatedCheckedAt.get(w.id) === key) return
  592. let outdated: boolean
  593. try {
  594. outdated = !(await sameFileList(w.localPath!, dir))
  595. } catch {
  596. // backup drive not mounted, or the folder is being replaced right now
  597. return
  598. }
  599. outdatedCheckedAt.set(w.id, key)
  600. if (!!w.backupOutdated !== outdated) patches.push({ id: w.id, patch: { backupOutdated: outdated } })
  601. })
  602. if (patches.length > 0) library.applyWallpaperChanges({ patches })
  603. return patches.length > 0
  604. }