library.service.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. import { openStore } from '../utils/safeStore'
  2. import type { WallpaperMeta, WallpaperType, ContentRating, LibraryFilters, WallpaperFolder } from '@shared/types'
  3. import { getExtraLibraryRoots, getThumbnailsPath, getWorkshopPath } from '../utils/paths'
  4. import { findLocalWallpapers, localWallpaperId } from '../utils/localLibrary'
  5. import { containedPath } from '../utils/contained'
  6. import * as path from 'path'
  7. import * as fs from 'fs'
  8. import { randomUUID } from 'crypto'
  9. import { cleanupPlaylists } from './playlist.service'
  10. import { getWorkshopDetails, getUnavailableWorkshopItems, type WorkshopDetails } from './workshop.service'
  11. import { findAndMutate } from '../utils/collections'
  12. import { resolutionsFromTags } from '@shared/resolutions'
  13. import { detectFeatures, type WallpaperFeatures } from '../utils/hdr'
  14. import {
  15. isSteamRunning,
  16. getItemDownloadStatus,
  17. getSubscribedItems,
  18. isItemStuckNeverDownloaded,
  19. downloadItem
  20. } from './steam.service'
  21. interface LibraryStore {
  22. wallpapers: Record<string, WallpaperMeta>
  23. tags: string[]
  24. folders: WallpaperFolder[]
  25. resolutionsVersion: number
  26. }
  27. const fileStore = openStore<LibraryStore>({
  28. name: 'library',
  29. defaults: {
  30. wallpapers: {},
  31. tags: [],
  32. folders: [],
  33. resolutionsVersion: 0
  34. }
  35. })
  36. // electron-store re-reads and parses the whole file on every get, and the wallpaper map is megabytes
  37. let wallpapersCache: LibraryStore['wallpapers'] | null = null
  38. const store = {
  39. get path(): string {
  40. return fileStore.path
  41. },
  42. get<K extends keyof LibraryStore>(key: K): LibraryStore[K] {
  43. if (key !== 'wallpapers') return fileStore.get(key)
  44. wallpapersCache ??= fileStore.get('wallpapers')
  45. return wallpapersCache as LibraryStore[K]
  46. },
  47. set<K extends keyof LibraryStore>(key: K, value: LibraryStore[K]): void {
  48. if (key === 'wallpapers') wallpapersCache = null
  49. fileStore.set(key, value)
  50. if (key === 'wallpapers') wallpapersCache = value as LibraryStore['wallpapers']
  51. }
  52. }
  53. export function initLibrary(): void {
  54. console.log('[Library] Store initialized at', store.path)
  55. repairStaleDownloadFlags()
  56. }
  57. function repairStaleDownloadFlags(): void {
  58. const wallpapers = store.get('wallpapers')
  59. let changed = false
  60. for (const wallpaper of Object.values(wallpapers)) {
  61. if (!wallpaper.subscribed && (wallpaper.downloading || wallpaper.downloadFailed)) {
  62. wallpaper.downloading = false
  63. wallpaper.downloadFailed = false
  64. changed = true
  65. }
  66. }
  67. if (changed) store.set('wallpapers', wallpapers)
  68. }
  69. export function getAllWallpapers(filters?: LibraryFilters): WallpaperMeta[] {
  70. const all = Object.values(store.get('wallpapers'))
  71. let results = all
  72. if (filters?.type) {
  73. results = results.filter((w) => w.type === filters.type)
  74. }
  75. if (filters?.searchText) {
  76. const q = filters.searchText.toLowerCase()
  77. results = results.filter(
  78. (w) => w.title.toLowerCase().includes(q) || w.description?.toLowerCase().includes(q)
  79. )
  80. }
  81. if (filters?.contentRating) {
  82. results = results.filter((w) => w.contentRating === filters.contentRating)
  83. }
  84. if (filters?.tags && filters.tags.length > 0) {
  85. results = results.filter((w) => filters.tags!.every((tag) => w.tags.includes(tag)))
  86. }
  87. if (filters?.categories && filters.categories.length > 0) {
  88. results = results.filter((w) => filters.categories!.some((cat) => w.categories.includes(cat)))
  89. }
  90. const sortBy = filters?.sortBy ?? 'updatedAt'
  91. const dir = filters?.sortDir === 'asc' ? 1 : -1
  92. results = [...results].sort((a, b) => {
  93. switch (sortBy) {
  94. case 'title':
  95. return dir * a.title.localeCompare(b.title)
  96. case 'createdAt':
  97. return dir * (a.createdAt - b.createdAt)
  98. case 'updatedAt':
  99. return dir * (a.updatedAt - b.updatedAt)
  100. case 'lastApplied':
  101. return dir * ((a.lastAppliedAt ?? 0) - (b.lastAppliedAt ?? 0))
  102. case 'appliedCount':
  103. return dir * (a.appliedCount - b.appliedCount)
  104. case 'fileSize':
  105. return dir * ((a.fileSize ?? 0) - (b.fileSize ?? 0))
  106. default:
  107. return dir * (a.updatedAt - b.updatedAt)
  108. }
  109. })
  110. return results
  111. }
  112. export function getWallpaper(id: string): WallpaperMeta | null {
  113. const wallpapers = store.get('wallpapers')
  114. return wallpapers[id] ?? null
  115. }
  116. export function upsertWallpaper(meta: WallpaperMeta): void {
  117. const wallpapers = store.get('wallpapers')
  118. wallpapers[meta.id] = meta
  119. store.set('wallpapers', wallpapers)
  120. }
  121. // updatedAt is the workshop item's timestamp, not local edits
  122. export function updateWallpaper(id: string, patch: Partial<WallpaperMeta>): void {
  123. const current = getWallpaper(id)
  124. if (!current) throw new Error(`Wallpaper ${id} not found`)
  125. upsertWallpaper({ ...current, ...patch, updatedAt: current.updatedAt })
  126. }
  127. export function resetAllCompat(): number {
  128. const wallpapers = store.get('wallpapers')
  129. let reset = 0
  130. for (const wallpaper of Object.values(wallpapers)) {
  131. const compat = wallpaper.compat
  132. if (!compat || (!compat.freshLaunch && !compat.hotswapCrash && !compat.runtimeCrashes && !compat.lastCrash)) continue
  133. wallpaper.compat = compat.note ? { note: compat.note } : undefined
  134. reset++
  135. }
  136. if (reset > 0) store.set('wallpapers', wallpapers)
  137. return reset
  138. }
  139. export function deleteWallpaper(id: string): void {
  140. const wallpapers = store.get('wallpapers')
  141. const thumbnail = wallpapers[id]?.customPreview
  142. if (thumbnail && path.dirname(thumbnail) === getThumbnailsPath()) fs.rmSync(thumbnail, { force: true })
  143. delete wallpapers[id]
  144. store.set('wallpapers', wallpapers)
  145. }
  146. // reads the store fresh so changes made during a long scan aren't overwritten
  147. export function applyWallpaperChanges(changes: {
  148. upserts?: WallpaperMeta[]
  149. patches?: { id: string; patch: Partial<WallpaperMeta> }[]
  150. deletes?: string[]
  151. }): void {
  152. const wallpapers = store.get('wallpapers')
  153. for (const meta of changes.upserts ?? []) wallpapers[meta.id] = meta
  154. for (const { id, patch } of changes.patches ?? []) {
  155. if (wallpapers[id]) wallpapers[id] = { ...wallpapers[id], ...patch, updatedAt: wallpapers[id].updatedAt }
  156. }
  157. for (const id of changes.deletes ?? []) {
  158. const thumbnail = wallpapers[id]?.customPreview
  159. if (thumbnail && path.dirname(thumbnail) === getThumbnailsPath()) fs.rmSync(thumbnail, { force: true })
  160. delete wallpapers[id]
  161. }
  162. store.set('wallpapers', wallpapers)
  163. }
  164. export function resetAllFpsOverrides(): { count: number } {
  165. const wallpapers = store.get('wallpapers')
  166. let count = 0
  167. for (const id of Object.keys(wallpapers)) {
  168. if (wallpapers[id].fpsOverride !== undefined) {
  169. delete wallpapers[id].fpsOverride
  170. count++
  171. }
  172. }
  173. store.set('wallpapers', wallpapers)
  174. return { count }
  175. }
  176. export function addTag(wallpaperId: string, tagName: string): void {
  177. const wallpaper = getWallpaper(wallpaperId)
  178. if (!wallpaper) return
  179. if (!wallpaper.tags.includes(tagName)) {
  180. wallpaper.tags.push(tagName)
  181. upsertWallpaper(wallpaper)
  182. }
  183. const tags = store.get('tags')
  184. if (!tags.includes(tagName)) {
  185. tags.push(tagName)
  186. store.set('tags', tags.sort())
  187. }
  188. }
  189. export function removeTag(wallpaperId: string, tagName: string): void {
  190. const wallpaper = getWallpaper(wallpaperId)
  191. if (!wallpaper) return
  192. wallpaper.tags = wallpaper.tags.filter((t) => t !== tagName)
  193. upsertWallpaper(wallpaper)
  194. }
  195. export function getAllTags(): string[] {
  196. return store.get('tags')
  197. }
  198. export function getDistinctTags(): string[] {
  199. const all = Object.values(store.get('wallpapers'))
  200. const set = new Set<string>()
  201. for (const w of all) {
  202. for (const t of w.tags) set.add(t)
  203. }
  204. return [...set].sort()
  205. }
  206. export interface ProjectJson {
  207. title?: string
  208. type?: string
  209. file?: string
  210. tags?: string[]
  211. description?: string
  212. preview?: string
  213. contentrating?: string
  214. workshopid?: string
  215. dependency?: string | number
  216. }
  217. export function readProjectJson(localPath: string): ProjectJson | null {
  218. try {
  219. const raw = fs.readFileSync(path.join(localPath, 'project.json'), 'utf8')
  220. return JSON.parse(raw) as ProjectJson
  221. } catch {
  222. return null
  223. }
  224. }
  225. export function normalizeType(raw?: string): WallpaperType {
  226. switch (raw?.toLowerCase()) {
  227. case 'video': return 'video'
  228. case 'web': return 'web'
  229. case 'application': return 'application'
  230. default: return 'scene'
  231. }
  232. }
  233. export function normalizeRating(raw?: string): ContentRating {
  234. switch (raw?.toLowerCase()) {
  235. case 'everyone': return 'everyone'
  236. case 'questionable': return 'questionable'
  237. case 'mature': return 'mature'
  238. default: return 'uncategorized'
  239. }
  240. }
  241. // lets failed downloads without a project.json land in the right filters
  242. function deriveTypeFromTags(tags: string[]): WallpaperType | undefined {
  243. const match = tags.find((t) => ['Video', 'Web', 'Application', 'Scene'].includes(t))
  244. return match ? normalizeType(match) : undefined
  245. }
  246. function deriveRatingFromTags(tags: string[]): ContentRating | undefined {
  247. const match = tags.find((t) => ['Everyone', 'Questionable', 'Mature'].includes(t))
  248. return match ? normalizeRating(match) : undefined
  249. }
  250. function sameTags(a: string[] | undefined, b: string[] | undefined): boolean {
  251. if (!a || !b) return a === b
  252. return a.length === b.length && a.every((t) => b.includes(t))
  253. }
  254. const RATING_RESTRICTIVENESS: Record<ContentRating, number> = {
  255. uncategorized: 0,
  256. everyone: 1,
  257. questionable: 2,
  258. mature: 3
  259. }
  260. // contentrating and the tags can disagree, the stricter one wins
  261. function stricterRating(a: ContentRating, b?: ContentRating): ContentRating {
  262. if (!b) return a
  263. return RATING_RESTRICTIVENESS[b] > RATING_RESTRICTIVENESS[a] ? b : a
  264. }
  265. async function safeGetWorkshopDetails(ids: string[]): Promise<Map<string, WorkshopDetails>> {
  266. try {
  267. return await getWorkshopDetails(ids)
  268. } catch {
  269. return new Map()
  270. }
  271. }
  272. export function getDirSize(dirPath: string): number {
  273. let total = 0
  274. try {
  275. for (const entry of fs.readdirSync(dirPath, { withFileTypes: true })) {
  276. const full = path.join(dirPath, entry.name)
  277. if (entry.isDirectory()) {
  278. total += getDirSize(full)
  279. } else if (entry.isFile()) {
  280. try { total += fs.statSync(full).size } catch { }
  281. }
  282. }
  283. } catch { }
  284. return total
  285. }
  286. // extra folders are often on HDDs, don't block the main process
  287. export async function getDirSizeAsync(dirPath: string): Promise<number> {
  288. let total = 0
  289. let entries: fs.Dirent[]
  290. try {
  291. entries = await fs.promises.readdir(dirPath, { withFileTypes: true })
  292. } catch {
  293. return 0
  294. }
  295. for (const entry of entries) {
  296. const full = path.join(dirPath, entry.name)
  297. if (entry.isDirectory()) {
  298. total += await getDirSizeAsync(full)
  299. } else if (entry.isFile()) {
  300. try { total += (await fs.promises.stat(full)).size } catch { }
  301. }
  302. }
  303. return total
  304. }
  305. function buildMeta(
  306. workshopId: string,
  307. localPath: string,
  308. pj: ProjectJson | null,
  309. existing?: WallpaperMeta,
  310. workshopTimeUpdated?: number,
  311. authorSteamId?: string,
  312. liveWorkshopTags?: string[],
  313. fileSize?: number
  314. ): WallpaperMeta {
  315. const now = Date.now()
  316. const { downloading: _d, downloadFailed: _df, ...existingRest } = existing ?? { appliedCount: 0, categories: [] }
  317. // the preview can still be downloading, the next scan picks it up
  318. const previewPath = containedPath(localPath, pj?.preview)
  319. // Steam can flag an item Mature later, only the live tags show that
  320. const fromProject = stricterRating(normalizeRating(pj?.contentrating), deriveRatingFromTags(pj?.tags ?? []))
  321. const contentRating = stricterRating(fromProject, deriveRatingFromTags(liveWorkshopTags ?? []))
  322. return {
  323. ...existingRest,
  324. id: workshopId,
  325. title: pj?.title ?? `Wallpaper ${workshopId}`,
  326. type: normalizeType(pj?.type),
  327. contentRating,
  328. description: pj?.description,
  329. previewLocal: previewPath && fs.existsSync(previewPath) ? previewPath : undefined,
  330. previewUrl: undefined,
  331. localPath,
  332. file: pj?.file,
  333. fileSize: fileSize ?? getDirSize(localPath),
  334. createdAt: existing?.createdAt ?? now,
  335. updatedAt: workshopTimeUpdated ? workshopTimeUpdated * 1000 : (existing?.updatedAt ?? now),
  336. subscribed: true,
  337. source: 'workshop',
  338. backupDir: existing?.backupDir ?? (existing?.source === 'backup' ? existing.localPath : undefined),
  339. tags: pj?.tags ?? existing?.tags ?? [],
  340. resolutions: liveWorkshopTags ? resolutionsFromTags(liveWorkshopTags) : existing?.resolutions,
  341. authorSteamId: authorSteamId ?? existing?.authorSteamId,
  342. // content may have changed, detect features and verify again
  343. hdr: undefined,
  344. hrtf: undefined,
  345. verifyProblem: undefined
  346. }
  347. }
  348. async function buildIncompleteMeta(
  349. workshopId: string,
  350. localPath: string,
  351. existing?: WallpaperMeta,
  352. workshopTags?: string[],
  353. authorSteamId?: string
  354. ): Promise<WallpaperMeta> {
  355. const now = Date.now()
  356. const { downloading, failed } = isSteamRunning()
  357. ? await getItemDownloadStatus(BigInt(workshopId))
  358. : { downloading: true, failed: false }
  359. const tags = workshopTags
  360. ? [...new Set([...(existing?.tags ?? []), ...workshopTags])]
  361. : (existing?.tags ?? [])
  362. return {
  363. id: workshopId,
  364. title: existing?.title ?? `Wallpaper ${workshopId}`,
  365. type: (workshopTags && deriveTypeFromTags(workshopTags)) ?? existing?.type ?? 'scene',
  366. contentRating:
  367. (workshopTags && deriveRatingFromTags(workshopTags)) ?? existing?.contentRating ?? 'uncategorized',
  368. localPath,
  369. createdAt: existing?.createdAt ?? now,
  370. updatedAt: now,
  371. subscribed: true,
  372. appliedCount: existing?.appliedCount ?? 0,
  373. source: 'workshop',
  374. tags,
  375. resolutions: workshopTags ? resolutionsFromTags(workshopTags) : existing?.resolutions,
  376. categories: existing?.categories ?? [],
  377. downloading,
  378. downloadFailed: failed,
  379. authorSteamId: authorSteamId ?? existing?.authorSteamId,
  380. backedUp: existing?.backedUp,
  381. backupOutdated: existing?.backupOutdated,
  382. backupDir: existing?.backupDir ?? (existing?.source === 'backup' ? existing.localPath : undefined)
  383. }
  384. }
  385. export async function importWallpaperById(workshopId: string): Promise<WallpaperMeta | null> {
  386. const localPath = path.join(getWorkshopPath(), workshopId)
  387. if (!fs.existsSync(localPath)) return null
  388. const existing = getWallpaper(workshopId) ?? undefined
  389. const details = (await safeGetWorkshopDetails([workshopId])).get(workshopId)
  390. const authorSteamId = existing?.authorSteamId ?? details?.authorSteamId
  391. const pj = readProjectJson(localPath)
  392. if (!pj) {
  393. const meta = await buildIncompleteMeta(workshopId, localPath, existing, details?.tags, authorSteamId)
  394. upsertWallpaper(meta)
  395. return meta
  396. }
  397. const meta = buildMeta(workshopId, localPath, pj, existing, details?.timeUpdated, authorSteamId, details?.tags)
  398. upsertWallpaper(meta)
  399. // a preset waiting on this item as its dependency can be decided now
  400. hdrUndecided.clear()
  401. queueHdrCheck()
  402. return meta
  403. }
  404. async function buildLocalMeta(
  405. id: string,
  406. localPath: string,
  407. existing?: WallpaperMeta,
  408. details?: WorkshopDetails
  409. ): Promise<WallpaperMeta | null> {
  410. const pj = readProjectJson(localPath)
  411. if (!pj) return null
  412. const fileSize = await getDirSizeAsync(localPath)
  413. const authorSteamId = existing?.authorSteamId ?? details?.authorSteamId
  414. return {
  415. ...buildMeta(id, localPath, pj, existing, details?.timeUpdated, authorSteamId, details?.tags, fileSize),
  416. subscribed: false,
  417. source: 'local'
  418. }
  419. }
  420. export async function importLocalWallpaper(localPath: string): Promise<WallpaperMeta | null> {
  421. const id = await localWallpaperId(localPath)
  422. if (!id) return null
  423. const existing = getWallpaper(id) ?? undefined
  424. if (existing && existing.source !== 'local') return null
  425. // the first library holding an id wins
  426. if (existing?.localPath && existing.localPath !== localPath && fs.existsSync(path.join(existing.localPath, 'project.json'))) {
  427. const roots = getExtraLibraryRoots()
  428. const rank = (p: string): number => roots.indexOf(path.dirname(path.resolve(p)))
  429. if (rank(existing.localPath) !== -1 && rank(existing.localPath) <= rank(localPath)) return null
  430. }
  431. const details = /^\d+$/.test(id) ? (await safeGetWorkshopDetails([id])).get(id) : undefined
  432. const meta = await buildLocalMeta(id, localPath, existing, details)
  433. if (!meta) return null
  434. upsertWallpaper(meta)
  435. queueHdrCheck()
  436. return meta
  437. }
  438. export async function scanLibrary(): Promise<{ imported: number; skipped: number; removed: number }> {
  439. const workshopPath = getWorkshopPath()
  440. // unmounted drive must not empty the library
  441. const workshopMounted = fs.existsSync(workshopPath)
  442. // dot folders are copies moved aside during a repair
  443. const entries = workshopMounted
  444. ? fs.readdirSync(workshopPath, { withFileTypes: true }).filter((e) => !e.name.startsWith('.'))
  445. : []
  446. const onDisk = new Set(entries.filter(e => e.isDirectory()).map(e => e.name))
  447. const subscribedIds = isSteamRunning()
  448. ? new Set(await getSubscribedItems().catch(() => []))
  449. : new Set<string>()
  450. const wallpapers = { ...store.get('wallpapers') }
  451. let imported = 0
  452. let skipped = 0
  453. let removed = 0
  454. let resynced = false
  455. // drop workshop items whose folder is gone, unless still subscribed (tracked below)
  456. for (const id of Object.keys(wallpapers)) {
  457. if (wallpapers[id].source !== 'workshop' || !workshopMounted) continue
  458. if (!onDisk.has(id) && !subscribedIds.has(id)) {
  459. delete wallpapers[id]
  460. removed++
  461. }
  462. }
  463. const incomplete: { id: string; localPath: string }[] = []
  464. const toRebuild: { entry: fs.Dirent; localPath: string; pj: ProjectJson }[] = []
  465. const cacheHits: string[] = []
  466. for (const entry of entries) {
  467. if (!entry.isDirectory()) continue
  468. const localPath = path.join(workshopPath, entry.name)
  469. const pj = readProjectJson(localPath)
  470. if (!pj) {
  471. incomplete.push({ id: entry.name, localPath })
  472. continue
  473. }
  474. const existing = wallpapers[entry.name]
  475. if (existing?.localPath === localPath && !existing.downloading && existing.previewLocal !== undefined && fs.existsSync(existing.previewLocal) && existing?.contentRating !== undefined && existing?.fileSize !== undefined) {
  476. cacheHits.push(entry.name)
  477. skipped++
  478. continue
  479. }
  480. toRebuild.push({ entry, localPath, pj })
  481. }
  482. // subscribed items that never got a folder, see isItemStuckNeverDownloaded
  483. for (const id of subscribedIds) {
  484. if (onDisk.has(id)) continue
  485. if (isSteamRunning() && (await isItemStuckNeverDownloaded(BigInt(id)))) {
  486. await downloadItem(BigInt(id))
  487. }
  488. incomplete.push({ id, localPath: path.join(workshopPath, id) })
  489. }
  490. const roots = getExtraLibraryRoots()
  491. const { found, mounted } = await findLocalWallpapers(roots)
  492. const claimed = new Set([...onDisk, ...subscribedIds])
  493. for (const w of Object.values(wallpapers)) {
  494. if (w.source !== 'local') claimed.add(w.id)
  495. }
  496. const localFound = found.filter((f) => !claimed.has(f.id))
  497. const localIds = new Set(localFound.map((f) => f.id))
  498. for (const [id, w] of Object.entries(wallpapers)) {
  499. if (w.source !== 'local' || localIds.has(id) || claimed.has(id)) continue
  500. const root = path.dirname(path.resolve(w.localPath ?? ''))
  501. if (roots.includes(root) && !mounted.includes(root)) continue
  502. delete wallpapers[id]
  503. removed++
  504. }
  505. const localToBuild = localFound.filter((f) => {
  506. const existing = wallpapers[f.id]
  507. return !(existing?.source === 'local' && existing.localPath === f.localPath && existing.fileSize !== undefined)
  508. })
  509. skipped += localFound.length - localToBuild.length
  510. const details = await safeGetWorkshopDetails([
  511. ...incomplete.map((i) => i.id),
  512. ...toRebuild.map(({ entry }) => entry.name),
  513. ...cacheHits,
  514. ...localToBuild.map((f) => f.id).filter((id) => /^\d+$/.test(id))
  515. ])
  516. const authors = new Map<string, string>()
  517. for (const [id, d] of details) {
  518. if (!wallpapers[id]?.authorSteamId) authors.set(id, d.authorSteamId)
  519. }
  520. for (const { id, localPath } of incomplete) {
  521. const existing = wallpapers[id]
  522. const meta = await buildIncompleteMeta(id, localPath, existing, details.get(id)?.tags, authors.get(id))
  523. if (!existing) {
  524. wallpapers[id] = meta
  525. imported++
  526. } else if (
  527. existing.downloading !== meta.downloading ||
  528. existing.downloadFailed !== meta.downloadFailed ||
  529. existing.type !== meta.type ||
  530. existing.contentRating !== meta.contentRating ||
  531. existing.authorSteamId !== meta.authorSteamId ||
  532. !sameTags(existing.resolutions, meta.resolutions)
  533. ) {
  534. wallpapers[id] = {
  535. ...existing,
  536. downloading: meta.downloading,
  537. downloadFailed: meta.downloadFailed,
  538. type: meta.type,
  539. contentRating: meta.contentRating,
  540. tags: meta.tags,
  541. resolutions: meta.resolutions,
  542. authorSteamId: meta.authorSteamId
  543. }
  544. resynced = true
  545. skipped++
  546. } else {
  547. skipped++
  548. }
  549. }
  550. for (const { entry, localPath, pj } of toRebuild) {
  551. wallpapers[entry.name] = buildMeta(
  552. entry.name,
  553. localPath,
  554. pj,
  555. wallpapers[entry.name] ?? undefined,
  556. details.get(entry.name)?.timeUpdated,
  557. authors.get(entry.name),
  558. details.get(entry.name)?.tags
  559. )
  560. imported++
  561. }
  562. for (const { id, localPath } of localToBuild) {
  563. const meta = await buildLocalMeta(id, localPath, wallpapers[id], details.get(id))
  564. if (!meta) continue
  565. wallpapers[id] = meta
  566. imported++
  567. }
  568. for (const id of cacheHits) {
  569. const seconds = details.get(id)?.timeUpdated
  570. const authorId = authors.get(id)
  571. const live = details.get(id)?.tags
  572. // the author changed something, re-read project.json so a corrected rating sticks
  573. const localPath = wallpapers[id].localPath
  574. if (seconds !== undefined && wallpapers[id].updatedAt !== seconds * 1000 && localPath) {
  575. const pj = readProjectJson(localPath)
  576. if (pj) {
  577. wallpapers[id] = buildMeta(
  578. id,
  579. localPath,
  580. pj,
  581. wallpapers[id],
  582. seconds,
  583. authorId ?? wallpapers[id].authorSteamId,
  584. live
  585. )
  586. resynced = true
  587. continue
  588. }
  589. }
  590. const patch: Partial<WallpaperMeta> = {}
  591. if (seconds !== undefined && wallpapers[id].updatedAt !== seconds * 1000) {
  592. patch.updatedAt = seconds * 1000
  593. }
  594. if (authorId && wallpapers[id].authorSteamId !== authorId) {
  595. patch.authorSteamId = authorId
  596. }
  597. // only tighten, a failed tag fetch must not lower a rating
  598. const liveRating = live ? deriveRatingFromTags(live) : undefined
  599. if (liveRating) {
  600. const stricter = stricterRating(wallpapers[id].contentRating ?? 'uncategorized', liveRating)
  601. if (stricter !== wallpapers[id].contentRating) {
  602. patch.contentRating = stricter
  603. }
  604. }
  605. if (live) {
  606. const resolutions = resolutionsFromTags(live)
  607. if (!sameTags(wallpapers[id].resolutions, resolutions)) {
  608. patch.resolutions = resolutions
  609. }
  610. }
  611. if (Object.keys(patch).length > 0) {
  612. wallpapers[id] = { ...wallpapers[id], ...patch }
  613. resynced = true
  614. }
  615. }
  616. if (imported > 0 || removed > 0 || resynced) {
  617. store.set('wallpapers', wallpapers)
  618. }
  619. console.log(`[Library] Scan complete: ${imported} imported, ${skipped} skipped, ${removed} removed`)
  620. cleanupFolders()
  621. cleanupPlaylists(new Set(Object.keys(wallpapers)))
  622. queueHdrCheck()
  623. return { imported, skipped, removed }
  624. }
  625. // flags workshop items whose listing was taken down, they can't be downloaded again
  626. export async function checkUnavailableWallpapers(): Promise<{
  627. checked: number
  628. unavailable: number
  629. changed: boolean
  630. }> {
  631. if (!isSteamRunning()) return { checked: 0, unavailable: 0, changed: false }
  632. const wallpapers = store.get('wallpapers')
  633. const candidates = Object.values(wallpapers).filter(
  634. (w) => w.source === 'workshop' && !!w.localPath && !w.downloading
  635. )
  636. if (candidates.length === 0) return { checked: 0, unavailable: 0, changed: false }
  637. let unavailableIds: Set<string>
  638. try {
  639. unavailableIds = await getUnavailableWorkshopItems(candidates.map((w) => w.id))
  640. } catch {
  641. return { checked: 0, unavailable: 0, changed: false }
  642. }
  643. let changed = false
  644. for (const w of candidates) {
  645. const flag = unavailableIds.has(w.id)
  646. if (!!w.unavailable !== flag) {
  647. wallpapers[w.id] = { ...w, unavailable: flag }
  648. changed = true
  649. }
  650. }
  651. if (changed) store.set('wallpapers', wallpapers)
  652. return { checked: candidates.length, unavailable: unavailableIds.size, changed }
  653. }
  654. function isFromWorkshop(w: WallpaperMeta): boolean {
  655. return w.source === 'workshop' || (w.source === 'local' && /^\d+$/.test(w.id))
  656. }
  657. // bump when resolutionsFromTags() changes
  658. const RESOLUTIONS_VERSION = 2
  659. // resolution comes only from live tags, older or offline imports need this pass
  660. export async function backfillResolutions(): Promise<boolean> {
  661. if (!isSteamRunning()) return false
  662. const rederive = store.get('resolutionsVersion') !== RESOLUTIONS_VERSION
  663. const ids = Object.values(store.get('wallpapers'))
  664. .filter((w) => isFromWorkshop(w) && (rederive || w.resolutions === undefined))
  665. .map((w) => w.id)
  666. let details = new Map<string, WorkshopDetails>()
  667. if (ids.length > 0) {
  668. try {
  669. details = await getWorkshopDetails(ids)
  670. } catch {
  671. return false
  672. }
  673. }
  674. // other writes may have landed during the fetch
  675. const wallpapers = store.get('wallpapers')
  676. let changed = false
  677. for (const id of ids) {
  678. const w = wallpapers[id]
  679. if (!w) continue
  680. const live = details.get(id)?.tags
  681. // removed or private items get "none" instead of being asked every tick
  682. const resolutions = live ? resolutionsFromTags(live) : (w.resolutions ?? [])
  683. if (sameTags(w.resolutions, resolutions)) continue
  684. wallpapers[id] = { ...w, resolutions }
  685. changed = true
  686. }
  687. if (changed) store.set('wallpapers', wallpapers)
  688. store.set('resolutionsVersion', RESOLUTIONS_VERSION)
  689. if (ids.length > 0) {
  690. console.log(`[Library] Resolution tags fetched for ${details.size} of ${ids.length} items`)
  691. }
  692. return changed
  693. }
  694. // undecided this session (no ffprobe, unreadable files), not re-read every tick
  695. const hdrUndecided = new Set<string>()
  696. let hdrPassRunning = false
  697. let hdrPassQueued = false
  698. let hdrListener: (() => void) | undefined
  699. export function onHdrDetected(listener: () => void): void {
  700. hdrListener = listener
  701. }
  702. export function queueHdrCheck(): void {
  703. void backfillHdr().then((changed) => {
  704. if (changed) hdrListener?.()
  705. })
  706. }
  707. // HDR and HRTF share one scene read
  708. export async function backfillHdr(): Promise<boolean> {
  709. if (hdrPassRunning) {
  710. hdrPassQueued = true
  711. return false
  712. }
  713. hdrPassRunning = true
  714. try {
  715. const pending = Object.values(store.get('wallpapers')).filter(
  716. (w) => (w.hdr === undefined || w.hrtf === undefined) && !!w.localPath && !w.downloading && !hdrUndecided.has(w.id)
  717. )
  718. if (pending.length === 0) return false
  719. let changed = false
  720. let results = new Map<string, WallpaperFeatures>()
  721. const flush = (): void => {
  722. if (results.size === 0) return
  723. const wallpapers = store.get('wallpapers')
  724. for (const [id, features] of results) {
  725. if (wallpapers[id]) wallpapers[id] = { ...wallpapers[id], ...features }
  726. }
  727. store.set('wallpapers', wallpapers)
  728. results = new Map()
  729. changed = true
  730. }
  731. // enough for SSDs without making HDDs seek back and forth
  732. let next = 0
  733. const worker = async (): Promise<void> => {
  734. while (next < pending.length) {
  735. const w = pending[next++]
  736. const features = await detectFeatures(w).catch((): WallpaperFeatures => ({}))
  737. const known = Object.fromEntries(
  738. Object.entries(features).filter(([, value]) => value !== undefined)
  739. ) as WallpaperFeatures
  740. if (features.hdr === undefined || features.hrtf === undefined) hdrUndecided.add(w.id)
  741. if (Object.keys(known).length > 0) {
  742. results.set(w.id, known)
  743. if (results.size >= 500) flush()
  744. }
  745. }
  746. }
  747. await Promise.all(Array.from({ length: 4 }, worker))
  748. flush()
  749. console.log(`[Library] HDR/HRTF check: ${pending.length} items read, ${hdrUndecided.size} undecided`)
  750. return changed
  751. } finally {
  752. hdrPassRunning = false
  753. if (hdrPassQueued) {
  754. hdrPassQueued = false
  755. queueHdrCheck()
  756. }
  757. }
  758. }
  759. export function getAllFolders(): WallpaperFolder[] {
  760. return store.get('folders')
  761. }
  762. export function createFolder(title: string): WallpaperFolder {
  763. const folder: WallpaperFolder = { id: randomUUID(), title, items: [] }
  764. const folders = store.get('folders')
  765. folders.push(folder)
  766. store.set('folders', folders)
  767. return folder
  768. }
  769. function updateFolder(id: string, mutate: (folder: WallpaperFolder) => void): WallpaperFolder | null {
  770. const folders = store.get('folders')
  771. const folder = findAndMutate(folders, id, mutate)
  772. if (folder) store.set('folders', folders)
  773. return folder
  774. }
  775. export function renameFolder(id: string, title: string): WallpaperFolder | null {
  776. return updateFolder(id, (folder) => {
  777. folder.title = title
  778. })
  779. }
  780. export function deleteFolder(id: string): void {
  781. const folders = store.get('folders').filter((f) => f.id !== id)
  782. store.set('folders', folders)
  783. }
  784. export function addItemsToFolder(folderId: string, itemIds: string[]): WallpaperFolder | null {
  785. const folders = store.get('folders')
  786. const moving = new Set(itemIds)
  787. for (const folder of folders) {
  788. if (folder.id === folderId) continue
  789. folder.items = folder.items.filter((id) => !moving.has(id))
  790. }
  791. const target = findAndMutate(folders, folderId, (folder) => {
  792. const set = new Set(folder.items)
  793. for (const id of itemIds) set.add(id)
  794. folder.items = [...set]
  795. })
  796. if (target) store.set('folders', folders)
  797. return target
  798. }
  799. export function removeItemsFromFolder(folderId: string, itemIds: string[]): WallpaperFolder | null {
  800. return updateFolder(folderId, (folder) => {
  801. const remove = new Set(itemIds)
  802. folder.items = folder.items.filter((id) => !remove.has(id))
  803. })
  804. }
  805. /** Drops unknown ids and ids already claimed by an earlier folder, returns how many */
  806. export function cleanupFolders(): number {
  807. const wallpapers = store.get('wallpapers')
  808. const validIds = new Set(Object.keys(wallpapers))
  809. const folders = store.get('folders')
  810. const seen = new Set<string>()
  811. let removed = 0
  812. for (const folder of folders) {
  813. const before = folder.items.length
  814. folder.items = folder.items.filter((id) => {
  815. if (!validIds.has(id) || seen.has(id)) return false
  816. seen.add(id)
  817. return true
  818. })
  819. removed += before - folder.items.length
  820. }
  821. if (removed > 0) {
  822. store.set('folders', folders)
  823. console.log(`[Library] Folder cleanup: removed ${removed} stale item(s)`)
  824. }
  825. return removed
  826. }
  827. export function importWEConfig(configPath: string): { folders: number; playlists: number } {
  828. const raw = fs.readFileSync(configPath, 'utf8')
  829. const data = JSON.parse(raw)
  830. const imported: WallpaperFolder[] = []
  831. const existingTitles = new Set(store.get('folders').map((f) => f.title))
  832. // the profile with the most folders, usually '~'
  833. let bestProfile: { folders: any[]; playlists: any[] } = { folders: [], playlists: [] }
  834. for (const key of Object.keys(data)) {
  835. const val = data[key]
  836. if (!val || typeof val !== 'object') continue
  837. const general = val.general
  838. if (!general || typeof general !== 'object') continue
  839. const browser = general.browser
  840. const folders = browser?.folders ?? []
  841. const playlists = general.playlists ?? []
  842. const total = folders.length + playlists.length
  843. if (total > bestProfile.folders.length + bestProfile.playlists.length) {
  844. bestProfile = { folders, playlists }
  845. }
  846. }
  847. for (const f of bestProfile.folders) {
  848. const title = f.title ?? 'Untitled'
  849. if (existingTitles.has(title)) continue
  850. const items = Object.keys(f.items ?? {}).filter((k) => /^\d+$/.test(k))
  851. imported.push({ id: randomUUID(), title, items })
  852. existingTitles.add(title)
  853. }
  854. // playlist items are full file paths
  855. for (const p of bestProfile.playlists) {
  856. const title = p.name ?? 'Untitled Playlist'
  857. if (existingTitles.has(title)) continue
  858. const items: string[] = []
  859. for (const filePath of p.items ?? []) {
  860. const match = filePath.match(/\/431960\/(\d+)\//)
  861. if (match) items.push(match[1])
  862. }
  863. if (items.length > 0) {
  864. imported.push({ id: randomUUID(), title, items })
  865. existingTitles.add(title)
  866. }
  867. }
  868. if (imported.length > 0) {
  869. const folders = store.get('folders')
  870. folders.push(...imported)
  871. store.set('folders', folders)
  872. }
  873. const fCount = bestProfile.folders.length
  874. const pCount = bestProfile.playlists.length
  875. console.log(`[Library] WE config imported: ${imported.length} folders/playlists from ${fCount} folders + ${pCount} playlists`)
  876. return { folders: fCount, playlists: pCount }
  877. }