backup.service.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 { normalizeType, normalizeRating, type ProjectJson } from './library.service'
  11. export function getBackupDir(id: string): string {
  12. const backupPath = getConfiguredBackupPath()
  13. if (!backupPath) throw new Error('Backup path must be configured before backing up')
  14. return path.join(backupPath, id)
  15. }
  16. export function resolveBackupDir(wallpaper: WallpaperMeta): string | null {
  17. if (wallpaper.source === 'backup' && wallpaper.localPath) return wallpaper.localPath
  18. if (wallpaper.backupDir) return wallpaper.backupDir
  19. try {
  20. return getBackupDir(wallpaper.id)
  21. } catch {
  22. return null
  23. }
  24. }
  25. async function isDir(p: string): Promise<boolean> {
  26. try {
  27. return (await fs.promises.stat(p)).isDirectory()
  28. } catch {
  29. return false
  30. }
  31. }
  32. async function exists(p: string): Promise<boolean> {
  33. try {
  34. await fs.promises.access(p)
  35. return true
  36. } catch {
  37. return false
  38. }
  39. }
  40. async function readProjectJson(dir: string): Promise<ProjectJson | null> {
  41. try {
  42. return JSON.parse(await fs.promises.readFile(path.join(dir, 'project.json'), 'utf8')) as ProjectJson
  43. } catch {
  44. return null
  45. }
  46. }
  47. export async function hasBackupFiles(dir: string | null): Promise<boolean> {
  48. return !!dir && (await isDir(dir)) && (await exists(path.join(dir, 'project.json')))
  49. }
  50. export async function findBackupProblem(dir: string): Promise<string | null> {
  51. if (!(await isDir(dir))) return 'folder is missing'
  52. const pj = await readProjectJson(dir)
  53. if (!pj) return 'project.json is missing or unreadable'
  54. if (!pj.file) return null
  55. if (await exists(path.join(dir, pj.file))) return null
  56. if (normalizeType(pj.type) === 'scene' && (await fs.promises.readdir(dir)).some((f) => f.endsWith('.pkg'))) {
  57. return null
  58. }
  59. return `${pj.file} is missing`
  60. }
  61. async function sameFileList(sourcePath: string, backupDir: string): Promise<boolean> {
  62. const [src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
  63. const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
  64. return src.length === dst.length && src.every((f) => dstSizes.get(f.relPath) === f.size)
  65. }
  66. function hashFile(filePath: string): Promise<string> {
  67. return new Promise((resolve, reject) => {
  68. const hash = crypto.createHash('sha256')
  69. const stream = fs.createReadStream(filePath)
  70. stream.on('error', reject)
  71. stream.on('data', (chunk) => hash.update(chunk))
  72. stream.on('end', () => resolve(hash.digest('hex')))
  73. })
  74. }
  75. // Wallpaper Engine writes its compiled shaders (shaders/blobsSM40/*.dxs) into the wallpaper folder
  76. function isShaderCache(relPath: string): boolean {
  77. return /^shaders[\\/]blobs/i.test(relPath)
  78. }
  79. async function walkFiles(dirPath: string, baseDir = dirPath): Promise<{ relPath: string; size: number }[]> {
  80. const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
  81. const nested = await Promise.all(
  82. entries.map(async (entry) => {
  83. const full = path.join(dirPath, entry.name)
  84. if (entry.isDirectory()) return isShaderCache(path.relative(baseDir, full)) ? [] : walkFiles(full, baseDir)
  85. if (!entry.isFile()) return []
  86. return [{ relPath: path.relative(baseDir, full), size: (await fs.promises.stat(full)).size }]
  87. })
  88. )
  89. return nested.flat()
  90. }
  91. async function walkDirs(dirPath: string): Promise<string[]> {
  92. const entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
  93. const nested = await Promise.all(
  94. entries.filter((e) => e.isDirectory()).map((e) => walkDirs(path.join(dirPath, e.name)))
  95. )
  96. return [dirPath, ...nested.flat()]
  97. }
  98. async function forEachLimit<T>(items: T[], limit: number, fn: (item: T) => Promise<void>): Promise<void> {
  99. let next = 0
  100. const worker = async (): Promise<void> => {
  101. while (next < items.length) await fn(items[next++])
  102. }
  103. await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
  104. }
  105. async function fsyncPath(p: string): Promise<void> {
  106. const handle = await fs.promises.open(p, 'r')
  107. try {
  108. await handle.sync()
  109. } finally {
  110. await handle.close()
  111. }
  112. }
  113. // fsynced pages are clean, so iflag=nocache can evict them and the hash check reads the disk
  114. function dropPageCache(dir: string): Promise<void> {
  115. return new Promise((resolve) => {
  116. const child = spawn(
  117. 'find',
  118. [dir, '-type', 'f', '-exec', 'sh', '-c',
  119. 'for f do dd if="$f" iflag=nocache count=0 status=none; done', 'sh', '{}', '+'],
  120. { stdio: 'ignore' }
  121. )
  122. child.on('error', () => resolve())
  123. child.on('close', () => resolve())
  124. })
  125. }
  126. function sendProgress(win: BrowserWindow, progress: BackupProgressEvent): void {
  127. if (!win.isDestroyed()) win.webContents.send(IpcChannels.EVENT_BACKUP_PROGRESS, progress)
  128. }
  129. function percent(done: number, total: number): number {
  130. return total > 0 ? Math.round((done / total) * 100) : 100
  131. }
  132. export async function backupMatchesSource(sourcePath: string, backupDir: string): Promise<boolean> {
  133. let src: { relPath: string; size: number }[]
  134. let dst: { relPath: string; size: number }[]
  135. try {
  136. ;[src, dst] = await Promise.all([walkFiles(sourcePath), walkFiles(backupDir)])
  137. } catch {
  138. return false
  139. }
  140. if (src.length !== dst.length) return false
  141. const dstSizes = new Map(dst.map((f) => [f.relPath, f.size]))
  142. if (src.some((f) => dstSizes.get(f.relPath) !== f.size)) return false
  143. for (const file of src) {
  144. const [a, b] = await Promise.all([
  145. hashFile(path.join(sourcePath, file.relPath)),
  146. hashFile(path.join(backupDir, file.relPath))
  147. ])
  148. if (a !== b) return false
  149. }
  150. return true
  151. }
  152. export async function backupWallpaper(
  153. id: string,
  154. sourcePath: string,
  155. win: BrowserWindow
  156. ): Promise<string> {
  157. const destDir = getBackupDir(id)
  158. const backupRoot = path.dirname(destDir)
  159. if (path.resolve(sourcePath) === path.resolve(destDir)) {
  160. throw new Error('Wallpaper already lives in the backup folder')
  161. }
  162. const files = await walkFiles(sourcePath)
  163. if (!files.some((f) => f.relPath === 'project.json')) {
  164. throw new Error('Source folder has no project.json, refusing to back up an incomplete wallpaper')
  165. }
  166. const bytesTotal = files.reduce((sum, f) => sum + f.size, 0)
  167. await fs.promises.mkdir(backupRoot, { recursive: true })
  168. const stagingDir = path.join(backupRoot, `.${id}.partial`)
  169. const oldDir = path.join(backupRoot, `.${id}.old`)
  170. await fs.promises.rm(stagingDir, { recursive: true, force: true })
  171. await fs.promises.mkdir(stagingDir)
  172. let bytesDone = 0
  173. try {
  174. for (const file of files) {
  175. const srcFile = path.join(sourcePath, file.relPath)
  176. const destFile = path.join(stagingDir, file.relPath)
  177. let srcStat: fs.Stats
  178. try {
  179. srcStat = await fs.promises.stat(srcFile)
  180. } catch {
  181. throw new Error(`Source file is gone, refusing to back up: ${file.relPath}`)
  182. }
  183. if (!srcStat.isFile() || srcStat.size !== file.size) {
  184. throw new Error(`Source file changed since it was scanned, refusing to back up: ${file.relPath}`)
  185. }
  186. await fs.promises.mkdir(path.dirname(destFile), { recursive: true })
  187. await fs.promises.copyFile(srcFile, destFile)
  188. await fsyncPath(destFile)
  189. bytesDone += file.size
  190. sendProgress(win, {
  191. itemId: id,
  192. bytesCopied: bytesDone,
  193. bytesTotal,
  194. percentage: percent(bytesDone, bytesTotal),
  195. status: 'copying'
  196. })
  197. }
  198. for (const dir of await walkDirs(stagingDir)) await fsyncPath(dir)
  199. await dropPageCache(stagingDir)
  200. bytesDone = 0
  201. for (const file of files) {
  202. const destFile = path.join(stagingDir, file.relPath)
  203. const destSize = (await fs.promises.stat(destFile)).size
  204. if (destSize !== file.size) {
  205. throw new Error(
  206. `Backup verification failed for ${file.relPath}: expected ${file.size} bytes, got ${destSize}`
  207. )
  208. }
  209. const [srcHash, destHash] = await Promise.all([
  210. hashFile(path.join(sourcePath, file.relPath)),
  211. hashFile(destFile)
  212. ])
  213. if (srcHash !== destHash) {
  214. throw new Error(`Backup verification failed for ${file.relPath}: hash mismatch`)
  215. }
  216. bytesDone += file.size
  217. sendProgress(win, {
  218. itemId: id,
  219. bytesCopied: bytesDone,
  220. bytesTotal,
  221. percentage: percent(bytesDone, bytesTotal),
  222. status: 'verifying'
  223. })
  224. }
  225. await fs.promises.rm(oldDir, { recursive: true, force: true })
  226. const hadOld = await exists(destDir)
  227. if (hadOld) await fs.promises.rename(destDir, oldDir)
  228. await fs.promises.rename(stagingDir, destDir)
  229. await fsyncPath(backupRoot)
  230. if (hadOld) await fs.promises.rm(oldDir, { recursive: true, force: true })
  231. } catch (err) {
  232. await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {})
  233. sendProgress(win, {
  234. itemId: id,
  235. bytesCopied: bytesDone,
  236. bytesTotal,
  237. percentage: 0,
  238. status: 'error',
  239. message: (err as Error).message
  240. })
  241. throw err
  242. }
  243. sendProgress(win, { itemId: id, bytesCopied: bytesTotal, bytesTotal, percentage: 100, status: 'completed' })
  244. return destDir
  245. }
  246. function isDeletableBackupDir(wallpaper: WallpaperMeta, dir: string): boolean {
  247. const resolved = path.resolve(dir)
  248. if (wallpaper.backupDir && path.resolve(wallpaper.backupDir) === resolved) return true
  249. if (wallpaper.source === 'backup' && path.basename(resolved) === wallpaper.id) return true
  250. const backupPath = getConfiguredBackupPath()
  251. return !!backupPath && path.dirname(resolved) === path.resolve(backupPath)
  252. }
  253. export async function removeBackup(id: string): Promise<{ keptDir: string | null }> {
  254. const wallpaper = library.getWallpaper(id)
  255. if (!wallpaper) return { keptDir: null }
  256. const dir = resolveBackupDir(wallpaper)
  257. let keptDir: string | null = null
  258. if (dir && (await exists(dir))) {
  259. const isWorkshopCopy =
  260. wallpaper.source === 'workshop' && !!wallpaper.localPath && path.resolve(wallpaper.localPath) === path.resolve(dir)
  261. if (isWorkshopCopy || !isDeletableBackupDir(wallpaper, dir)) {
  262. keptDir = dir
  263. console.warn(`[Backup] Not deleting ${dir} for ${id}, only dropping the reference`)
  264. } else {
  265. await fs.promises.rm(dir, { recursive: true, force: true })
  266. }
  267. }
  268. if (wallpaper.source === 'backup') {
  269. library.deleteWallpaper(id)
  270. } else {
  271. library.updateWallpaper(id, { backedUp: false, backupDir: undefined })
  272. }
  273. return { keptDir }
  274. }
  275. async function buildBackupMeta(id: string, localPath: string, existing?: WallpaperMeta): Promise<WallpaperMeta> {
  276. const [pj, files] = await Promise.all([readProjectJson(localPath), walkFiles(localPath)])
  277. const now = Date.now()
  278. return {
  279. id,
  280. title: pj?.title ?? existing?.title ?? `Wallpaper ${id}`,
  281. type: normalizeType(pj?.type),
  282. contentRating: normalizeRating(pj?.contentrating),
  283. description: pj?.description ?? existing?.description,
  284. previewLocal: pj?.preview ? path.join(localPath, pj.preview) : undefined,
  285. localPath,
  286. file: pj?.file,
  287. fileSize: files.reduce((sum, f) => sum + f.size, 0),
  288. createdAt: existing?.createdAt ?? now,
  289. updatedAt: now,
  290. subscribed: false,
  291. appliedCount: existing?.appliedCount ?? 0,
  292. source: 'backup',
  293. tags: pj?.tags ?? existing?.tags ?? [],
  294. resolutions: existing?.resolutions,
  295. categories: existing?.categories ?? [],
  296. backedUp: true,
  297. backupDir: localPath
  298. }
  299. }
  300. const SCAN_CONCURRENCY = 4
  301. export async function scanBackupFolder(): Promise<{
  302. imported: number
  303. skipped: number
  304. linked: number
  305. removed: number
  306. unlinked: number
  307. corrupted: string[]
  308. }> {
  309. const result = { imported: 0, skipped: 0, linked: 0, removed: 0, unlinked: 0, corrupted: [] as string[] }
  310. const backupPath = getConfiguredBackupPath()
  311. if (!backupPath || !(await isDir(backupPath))) return result
  312. const wallpapers = new Map(library.getAllWallpapers().map((w) => [w.id, w]))
  313. const folderIds = (await fs.promises.readdir(backupPath, { withFileTypes: true }))
  314. // dot folders are staging copies of an in-progress backup
  315. .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
  316. .map((e) => e.name)
  317. const problems = new Map<string, Promise<string | null>>()
  318. const problemOf = (dir: string): Promise<string | null> => {
  319. const key = path.resolve(dir)
  320. if (!problems.has(key)) problems.set(key, findBackupProblem(dir))
  321. return problems.get(key)!
  322. }
  323. const upserts: WallpaperMeta[] = []
  324. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  325. const deletes: string[] = []
  326. const referenced = [...wallpapers.values()].filter((w) => (w.source === 'backup' || w.backedUp) && !w.downloading)
  327. await forEachLimit(referenced, SCAN_CONCURRENCY, async (w) => {
  328. const dir = resolveBackupDir(w)
  329. // the drive holding it is not mounted
  330. if (dir && !(await isDir(path.dirname(dir)))) return
  331. const reason = dir ? await problemOf(dir) : 'no backup folder'
  332. if (!reason) return
  333. console.warn(`[Backup] Dropping broken backup of ${w.id} at ${dir}: ${reason}`)
  334. if (w.source === 'backup') {
  335. deletes.push(w.id)
  336. result.removed++
  337. } else {
  338. patches.push({ id: w.id, patch: { backedUp: false, backupDir: undefined } })
  339. result.unlinked++
  340. }
  341. })
  342. const dropped = new Set([...deletes, ...patches.map((p) => p.id)])
  343. await forEachLimit(folderIds, SCAN_CONCURRENCY, async (id) => {
  344. const dir = path.join(backupPath, id)
  345. const problem = await problemOf(dir)
  346. if (problem) {
  347. console.warn(`[Backup] Skipping corrupted backup ${dir}: ${problem}`)
  348. result.corrupted.push(id)
  349. return
  350. }
  351. const existing = wallpapers.get(id)
  352. if (existing?.source === 'workshop') {
  353. if ((existing.backedUp && !dropped.has(id)) || existing.downloading) {
  354. result.skipped++
  355. } else {
  356. // an older version than the workshop copy is still a backup, backing up again refreshes it
  357. patches.push({ id, patch: { backedUp: true, backupDir: dir } })
  358. result.linked++
  359. }
  360. return
  361. }
  362. if (
  363. existing?.source === 'backup' &&
  364. !dropped.has(id) &&
  365. existing.fileSize !== undefined &&
  366. path.resolve(existing.localPath ?? '') === path.resolve(dir)
  367. ) {
  368. result.skipped++
  369. return
  370. }
  371. upserts.push(await buildBackupMeta(id, dir, existing))
  372. result.imported++
  373. })
  374. const reimported = new Set(upserts.map((m) => m.id))
  375. library.applyWallpaperChanges({
  376. upserts,
  377. patches,
  378. deletes: deletes.filter((id) => !reimported.has(id))
  379. })
  380. result.removed -= deletes.filter((id) => reimported.has(id)).length
  381. result.corrupted.sort()
  382. return result
  383. }
  384. // what each entry was last compared at, so only items whose workshop folder changed get re-walked
  385. const outdatedCheckedAt = new Map<string, string>()
  386. export async function checkOutdatedBackups(): Promise<boolean> {
  387. const candidates = library
  388. .getAllWallpapers()
  389. .filter((w) => w.source === 'workshop' && w.backedUp && !w.downloading && w.localPath)
  390. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  391. await forEachLimit(candidates, SCAN_CONCURRENCY, async (w) => {
  392. const dir = resolveBackupDir(w)
  393. if (!dir) return
  394. let key: string
  395. try {
  396. const stat = await fs.promises.stat(w.localPath!)
  397. key = `${w.updatedAt}|${dir}|${stat.mtimeMs}`
  398. } catch {
  399. return
  400. }
  401. if (outdatedCheckedAt.get(w.id) === key) return
  402. let outdated: boolean
  403. try {
  404. outdated = !(await sameFileList(w.localPath!, dir))
  405. } catch {
  406. // backup drive not mounted, or the folder is being replaced right now
  407. return
  408. }
  409. outdatedCheckedAt.set(w.id, key)
  410. if (!!w.backupOutdated !== outdated) patches.push({ id: w.id, patch: { backupOutdated: outdated } })
  411. })
  412. if (patches.length > 0) library.applyWallpaperChanges({ patches })
  413. return patches.length > 0
  414. }