workshop-verify.service.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import * as fs from 'fs'
  2. import * as path from 'path'
  3. import type { VerifyProblem, VerifyResult, WallpaperMeta } from '@shared/types'
  4. import * as library from './library.service'
  5. import * as steam from './steam.service'
  6. import { exists, findFolderProblem, forEachLimit } from './backup.service'
  7. import { getWorkshopPath } from '../utils/paths'
  8. // the workshop folder is often on a HDD
  9. const VERIFY_CONCURRENCY = 4
  10. export interface ItemCheck {
  11. problem: VerifyProblem | null
  12. detail?: string
  13. busy?: boolean
  14. }
  15. export function presetDependency(pj: { dependency?: string | number }): string | null {
  16. const id = pj.dependency == null ? '' : String(pj.dependency)
  17. return /^\d+$/.test(id) ? id : null
  18. }
  19. // EItemState and install size vs the folder; a failed Steam call throws instead of reporting "not installed"
  20. export async function checkItem(wallpaper: WallpaperMeta): Promise<ItemCheck> {
  21. const id = BigInt(wallpaper.id)
  22. const state = await steam.fetchItemState(id)
  23. if (state & (steam.ITEM_STATE_DOWNLOADING | steam.ITEM_STATE_DOWNLOAD_PENDING)) return { problem: null, busy: true }
  24. if (!(state & steam.ITEM_STATE_INSTALLED)) return { problem: 'notInstalled' }
  25. if (state & steam.ITEM_STATE_NEEDS_UPDATE) return { problem: 'needsUpdate' }
  26. const info = await steam.getInstallInfo(id)
  27. const dir = info?.folder || wallpaper.localPath
  28. if (!dir) return { problem: 'missingFolder' }
  29. const folderProblem = await findFolderProblem(dir)
  30. if (folderProblem) return { problem: folderProblem.code, detail: folderProblem.detail }
  31. // a preset's wallpaper is its dependency
  32. const pj = library.readProjectJson(dir)
  33. if (pj && !pj.file) {
  34. const dependency = presetDependency(pj)
  35. if (!dependency) return { problem: 'missingMainFile', detail: 'project.json names no file and no dependency' }
  36. if (!library.readProjectJson(path.join(path.dirname(dir), dependency))) {
  37. return { problem: 'missingDependency', detail: `dependency ${dependency} is not installed` }
  38. }
  39. }
  40. // WE adds its shader cache later, so only smaller means missing
  41. if (info && info.sizeOnDisk > 0) {
  42. const actual = await library.getDirSizeAsync(dir)
  43. if (actual < info.sizeOnDisk) {
  44. return { problem: 'missingData', detail: `${actual} of ${info.sizeOnDisk} bytes on disk` }
  45. }
  46. }
  47. return { problem: null }
  48. }
  49. /** dot names are skipped by the scan and watcher */
  50. export function repairStashOf(dir: string, itemId: string): string {
  51. return path.join(path.dirname(dir), `.reverify-${itemId}`)
  52. }
  53. const STASH_NAME = /^\.reverify-(\d+)$/
  54. const STATE_CHECK_TIMEOUT_MS = 3000
  55. const HOST_START_TIMEOUT_MS = 15_000
  56. async function within<T>(promise: Promise<T>, ms: number): Promise<T> {
  57. let timer: ReturnType<typeof setTimeout> | undefined
  58. try {
  59. return await Promise.race([
  60. promise,
  61. new Promise<never>((_, reject) => {
  62. timer = setTimeout(() => reject(new Error('Steam did not answer')), ms)
  63. })
  64. ])
  65. } finally {
  66. clearTimeout(timer)
  67. }
  68. }
  69. async function steamIsFetching(itemId: string): Promise<boolean> {
  70. try {
  71. await within(steam.whenHostReady(), HOST_START_TIMEOUT_MS)
  72. const state = await within(steam.fetchItemState(BigInt(itemId)), STATE_CHECK_TIMEOUT_MS)
  73. return (state & (steam.ITEM_STATE_DOWNLOADING | steam.ITEM_STATE_DOWNLOAD_PENDING)) !== 0
  74. } catch {
  75. return false
  76. }
  77. }
  78. /**
  79. * After an interrupted repair, restores the old copy (true) unless Steam's folder is complete. While Steam is still
  80. * fetching the item neither folder is touched, the old copy may be all there is
  81. */
  82. export async function settleRepairStash(dir: string, stash: string): Promise<boolean> {
  83. if (!(await exists(stash))) return false
  84. const itemId = STASH_NAME.exec(path.basename(stash))?.[1]
  85. if (itemId && (await steamIsFetching(itemId))) return false
  86. if (!(await findFolderProblem(dir))) {
  87. await fs.promises.rm(stash, { recursive: true, force: true })
  88. return false
  89. }
  90. console.log(`[Verify] Putting back the old copy from ${stash}`)
  91. await fs.promises.rm(dir, { recursive: true, force: true })
  92. await fs.promises.rename(stash, dir)
  93. return true
  94. }
  95. let stashesRestored: Promise<void> | null = null
  96. /** Before the first scan, which would drop stashed items */
  97. export function restoreRepairStashes(): Promise<void> {
  98. stashesRestored ??= (async () => {
  99. const root = getWorkshopPath()
  100. let names: string[]
  101. try {
  102. names = await fs.promises.readdir(root)
  103. } catch {
  104. return
  105. }
  106. for (const name of names) {
  107. const id = STASH_NAME.exec(name)?.[1]
  108. if (!id) continue
  109. try {
  110. await settleRepairStash(path.join(root, id), path.join(root, name))
  111. } catch (err) {
  112. console.warn(`[Verify] Could not settle ${name}:`, err)
  113. }
  114. }
  115. })()
  116. return stashesRestored
  117. }
  118. // subscriptions too, which may have no workshop entry yet
  119. async function verifiableItems(ids?: string[]): Promise<{ wallpaper: WallpaperMeta; inLibrary: boolean }[]> {
  120. const wanted = ids ? new Set(ids) : null
  121. const all = library.getAllWallpapers()
  122. const byId = new Map(all.map((w) => [w.id, w]))
  123. const items = all
  124. .filter((w) => w.source === 'workshop' && (!wanted || wanted.has(w.id)))
  125. .map((wallpaper) => ({ wallpaper, inLibrary: true }))
  126. const subscribed = await steam.getSubscribedItems()
  127. for (const id of subscribed) {
  128. const existing = byId.get(id)
  129. if (existing?.source === 'workshop' || (wanted && !wanted.has(id))) continue
  130. console.log(`[Verify] ${id} is subscribed but ${existing ? `a ${existing.source} entry` : 'not in the library'}`)
  131. items.push({
  132. wallpaper: {
  133. id,
  134. title: existing?.title ?? id,
  135. type: existing?.type ?? 'scene',
  136. source: 'workshop',
  137. localPath: path.join(getWorkshopPath(), id),
  138. subscribed: true,
  139. createdAt: 0,
  140. updatedAt: 0,
  141. appliedCount: 0,
  142. tags: [],
  143. categories: []
  144. },
  145. inLibrary: false
  146. })
  147. }
  148. return items
  149. }
  150. export async function verifyItems(
  151. ids: string[] | undefined,
  152. onProgress: (done: number, total: number) => void
  153. ): Promise<VerifyResult> {
  154. if (!steam.isSteamRunning()) throw new Error('Steam is not running')
  155. const items = await verifiableItems(ids)
  156. const patches: { id: string; patch: Partial<WallpaperMeta> }[] = []
  157. const damaged: string[] = []
  158. let skipped = 0
  159. let done = 0
  160. onProgress(0, items.length)
  161. await forEachLimit(items, VERIFY_CONCURRENCY, async ({ wallpaper: w, inLibrary }) => {
  162. try {
  163. if (w.downloading) {
  164. skipped++
  165. return
  166. }
  167. const check = await checkItem(w)
  168. if (check.busy) {
  169. skipped++
  170. return
  171. }
  172. if (check.problem) {
  173. console.warn(`[Verify] ${w.id} (${w.title}): ${check.problem}${check.detail ? ` - ${check.detail}` : ''}`)
  174. damaged.push(w.id)
  175. }
  176. if (inLibrary && check.problem !== (w.verifyProblem ?? null)) {
  177. patches.push({ id: w.id, patch: { verifyProblem: check.problem ?? undefined } })
  178. }
  179. } catch (err) {
  180. console.warn(`[Verify] ${w.id}:`, err)
  181. skipped++
  182. } finally {
  183. onProgress(++done, items.length)
  184. }
  185. })
  186. if (patches.length > 0) library.applyWallpaperChanges({ patches })
  187. return { checked: items.length - skipped, skipped, damaged }
  188. }