backup.service.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  2. import * as fs from 'fs'
  3. import * as os from 'os'
  4. import * as path from 'path'
  5. import type { WallpaperMeta } from '@shared/types'
  6. let backupRoot = ''
  7. const wallpapers = new Map<string, WallpaperMeta>()
  8. vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir() } }))
  9. vi.mock('./config.service', () => ({ getConfiguredBackupPath: () => backupRoot }))
  10. vi.mock('./library.service', () => ({
  11. getWallpaper: (id: string) => wallpapers.get(id) ?? null,
  12. getAllWallpapers: () => [...wallpapers.values()],
  13. updateWallpaper: (id: string, patch: Partial<WallpaperMeta>) =>
  14. wallpapers.set(id, { ...wallpapers.get(id)!, ...patch }),
  15. upsertWallpaper: (meta: WallpaperMeta) => wallpapers.set(meta.id, meta),
  16. deleteWallpaper: (id: string) => wallpapers.delete(id),
  17. applyWallpaperChanges: (c: {
  18. upserts?: WallpaperMeta[]
  19. patches?: { id: string; patch: Partial<WallpaperMeta> }[]
  20. deletes?: string[]
  21. }) => {
  22. for (const m of c.upserts ?? []) wallpapers.set(m.id, m)
  23. for (const { id, patch } of c.patches ?? []) wallpapers.set(id, { ...wallpapers.get(id)!, ...patch })
  24. for (const id of c.deletes ?? []) wallpapers.delete(id)
  25. },
  26. normalizeType: (t?: string) => t ?? 'scene',
  27. normalizeRating: () => 'everyone',
  28. }))
  29. const backup = await import('./backup.service')
  30. const win = { isDestroyed: () => false, webContents: { send: vi.fn<() => void>() } } as never
  31. let tmp = ''
  32. let source = ''
  33. function writeFiles(dir: string, files: Record<string, string>): void {
  34. for (const [rel, content] of Object.entries(files)) {
  35. fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true })
  36. fs.writeFileSync(path.join(dir, rel), content)
  37. }
  38. }
  39. beforeEach(() => {
  40. tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-backup-'))
  41. backupRoot = path.join(tmp, 'backups')
  42. source = path.join(tmp, 'workshop', '123')
  43. writeFiles(source, { 'project.json': '{}', 'materials/a.tex': 'aaaa', 'scene.pkg': 'pkg' })
  44. wallpapers.clear()
  45. })
  46. afterEach(() => fs.rmSync(tmp, { recursive: true, force: true }))
  47. describe('backupWallpaper', () => {
  48. it('copies, verifies and leaves no staging folder behind', async () => {
  49. const dir = await backup.backupWallpaper('123', source, win)
  50. expect(dir).toBe(path.join(backupRoot, '123'))
  51. expect(await backup.backupMatchesSource(source, dir)).toBe(true)
  52. expect(fs.readdirSync(backupRoot)).toEqual(['123'])
  53. })
  54. it('refuses a folder without project.json', async () => {
  55. fs.rmSync(path.join(source, 'project.json'))
  56. await expect(backup.backupWallpaper('123', source, win)).rejects.toThrow(/project.json/)
  57. expect(fs.existsSync(path.join(backupRoot, '123'))).toBe(false)
  58. })
  59. it('ignores the shader cache Wallpaper Engine writes into the wallpaper', async () => {
  60. writeFiles(source, { 'shaders/blobsSM40/abc.dxs': 'blob', 'shaders/custom.frag': 'void main() {}' })
  61. const dir = await backup.backupWallpaper('123', source, win)
  62. expect(fs.existsSync(path.join(dir, 'shaders/blobsSM40'))).toBe(false)
  63. expect(fs.existsSync(path.join(dir, 'shaders/custom.frag'))).toBe(true)
  64. writeFiles(source, { 'shaders/blobsSM40/def.dxs': 'another blob' })
  65. expect(await backup.backupMatchesSource(source, dir)).toBe(true)
  66. })
  67. it('replaces a corrupted backup', async () => {
  68. const dir = await backup.backupWallpaper('123', source, win)
  69. fs.writeFileSync(path.join(dir, 'materials/a.tex'), 'aaab')
  70. expect(await backup.backupMatchesSource(source, dir)).toBe(false)
  71. fs.writeFileSync(path.join(dir, 'stray'), 'x')
  72. await backup.backupWallpaper('123', source, win)
  73. expect(await backup.backupMatchesSource(source, dir)).toBe(true)
  74. expect(fs.readdirSync(backupRoot)).toEqual(['123'])
  75. })
  76. })
  77. describe('backupMatchesSource', () => {
  78. it('detects missing files and size changes', async () => {
  79. const dir = await backup.backupWallpaper('123', source, win)
  80. fs.rmSync(path.join(dir, 'scene.pkg'))
  81. expect(await backup.backupMatchesSource(source, dir)).toBe(false)
  82. expect(await backup.backupMatchesSource(source, path.join(tmp, 'nope'))).toBe(false)
  83. })
  84. })
  85. const base = { title: 't', type: 'scene', contentRating: 'everyone', createdAt: 0, updatedAt: 0, subscribed: false, appliedCount: 0, tags: [], categories: [] } as unknown as WallpaperMeta
  86. describe('removeBackup', () => {
  87. it('drops a backup entry whose folder no longer exists', async () => {
  88. wallpapers.set('9', { ...base, id: '9', source: 'backup', localPath: path.join(tmp, 'gone', '9'), backedUp: true })
  89. await backup.removeBackup('9')
  90. expect(wallpapers.has('9')).toBe(false)
  91. })
  92. it('deletes the backup of a workshop entry and keeps the workshop copy', async () => {
  93. const dir = await backup.backupWallpaper('123', source, win)
  94. wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
  95. await backup.removeBackup('123')
  96. expect(fs.existsSync(dir)).toBe(false)
  97. expect(fs.existsSync(source)).toBe(true)
  98. expect(wallpapers.get('123')?.backedUp).toBe(false)
  99. })
  100. it('never deletes a folder outside the backup folder', async () => {
  101. const outside = path.join(tmp, 'elsewhere')
  102. writeFiles(outside, { 'project.json': '{}' })
  103. wallpapers.set('7', { ...base, id: '7', source: 'backup', localPath: outside, backedUp: true })
  104. const { keptDir } = await backup.removeBackup('7')
  105. expect(keptDir).toBe(outside)
  106. expect(fs.existsSync(outside)).toBe(true)
  107. expect(wallpapers.has('7')).toBe(false)
  108. })
  109. })
  110. describe('scanBackupFolder', () => {
  111. it('drops missing and corrupted backup entries and skips corrupted folders', async () => {
  112. writeFiles(path.join(backupRoot, 'good'), { 'project.json': '{"type":"video","file":"a.mp4"}', 'a.mp4': 'v' })
  113. writeFiles(path.join(backupRoot, 'nofile'), { 'project.json': '{"type":"video","file":"a.mp4"}' })
  114. writeFiles(path.join(backupRoot, 'badjson'), { 'project.json': '{nope' })
  115. writeFiles(path.join(backupRoot, 'scene'), { 'project.json': '{"type":"scene","file":"scene.json"}', 'scene.pkg': 'p' })
  116. writeFiles(path.join(backupRoot, 'preset'), { 'project.json': '{"dependency":"1"}' })
  117. wallpapers.set('gone', { ...base, id: 'gone', source: 'backup', localPath: path.join(backupRoot, 'gone'), backedUp: true })
  118. wallpapers.set('nofile', { ...base, id: 'nofile', source: 'backup', localPath: path.join(backupRoot, 'nofile'), backedUp: true })
  119. wallpapers.set('offline', { ...base, id: 'offline', source: 'backup', localPath: path.join(tmp, 'unmounted', 'offline'), backedUp: true })
  120. const result = (await backup.scanBackupFolder())
  121. expect(result.removed).toBe(2)
  122. expect(result.corrupted.sort()).toEqual(['badjson', 'nofile'])
  123. expect([...wallpapers.keys()].sort()).toEqual(['good', 'offline', 'preset', 'scene'])
  124. expect(wallpapers.get('good')?.fileSize).toBe(fs.statSync(path.join(backupRoot, 'good', 'project.json')).size + 1)
  125. const again = await backup.scanBackupFolder()
  126. expect(again.imported).toBe(0)
  127. expect(again.skipped).toBe(3)
  128. })
  129. it('re-imports a backup entry that pointed at a folder in the old backup location', async () => {
  130. writeFiles(path.join(backupRoot, 'moved'), { 'project.json': '{}' })
  131. fs.mkdirSync(path.join(tmp, 'old-backups'))
  132. wallpapers.set('moved', { ...base, id: 'moved', source: 'backup', localPath: path.join(tmp, 'old-backups', 'moved'), backedUp: true, fileSize: 1 })
  133. const result = await backup.scanBackupFolder()
  134. expect(result.removed).toBe(0)
  135. expect(result.imported).toBe(1)
  136. expect(wallpapers.get('moved')?.localPath).toBe(path.join(backupRoot, 'moved'))
  137. })
  138. it('keeps a workshop entry linked when its backup differs from the workshop copy', async () => {
  139. const dir = await backup.backupWallpaper('123', source, win)
  140. wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
  141. writeFiles(source, { 'scene.pkg': 'updated-by-the-author', 'materials/b.tex': 'bbbb' })
  142. const result = await backup.scanBackupFolder()
  143. expect(result.unlinked).toBe(0)
  144. expect(result.corrupted).toEqual([])
  145. expect(wallpapers.get('123')?.backedUp).toBe(true)
  146. })
  147. it('links an unlinked workshop entry to an older backup', async () => {
  148. const dir = await backup.backupWallpaper('123', source, win)
  149. wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: false })
  150. writeFiles(source, { 'scene.pkg': 'updated-by-the-author' })
  151. const result = await backup.scanBackupFolder()
  152. expect(result.linked).toBe(1)
  153. expect(wallpapers.get('123')).toMatchObject({ backedUp: true, backupDir: dir })
  154. })
  155. it('flags a backup that is older than the workshop copy', async () => {
  156. const dir = await backup.backupWallpaper('123', source, win)
  157. wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
  158. writeFiles(source, { 'shaders/blobsSM40/abc.dxs': 'blob' })
  159. await backup.checkOutdatedBackups()
  160. expect(wallpapers.get('123')?.backupOutdated).toBeFalsy()
  161. writeFiles(source, { 'scene.pkg': 'updated-by-the-author' })
  162. fs.utimesSync(source, new Date(), new Date(Date.now() + 5000))
  163. expect(await backup.checkOutdatedBackups()).toBe(true)
  164. expect(wallpapers.get('123')?.backupOutdated).toBe(true)
  165. await backup.backupWallpaper('123', source, win)
  166. fs.utimesSync(source, new Date(), new Date(Date.now() + 10000))
  167. await backup.checkOutdatedBackups()
  168. expect(wallpapers.get('123')?.backupOutdated).toBe(false)
  169. })
  170. it('unlinks a workshop entry whose backup lost its project.json', async () => {
  171. const dir = await backup.backupWallpaper('123', source, win)
  172. wallpapers.set('123', { ...base, id: '123', source: 'workshop', localPath: source, backedUp: true, backupDir: dir })
  173. fs.rmSync(path.join(dir, 'project.json'))
  174. const result = await backup.scanBackupFolder()
  175. expect(result.unlinked).toBe(1)
  176. expect(result.corrupted).toEqual(['123'])
  177. expect(wallpapers.get('123')?.backedUp).toBe(false)
  178. })
  179. })