steam.service.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. import { execFileSync } from 'child_process'
  2. import * as fs from 'fs'
  3. import * as os from 'os'
  4. import * as path from 'path'
  5. import { setTimeout as sleep } from 'timers/promises'
  6. import { app, utilityProcess, type BrowserWindow, type UtilityProcess } from 'electron'
  7. import { WE_APP_ID, STANDALONE_APP_ID } from '@shared/constants'
  8. import type { DownloadProgressEvent, FavoriteFailure, FavoriteStatus, WorkshopAuthorInfo } from '@shared/types'
  9. import { getSteamIdentity } from './config.service'
  10. import { encodeBigInts, decodeBigInts, type SteamHostResponse } from '../steam-host-protocol'
  11. import { hostCommand, isFlatpak } from '../utils/flatpak'
  12. import { SteamListCache } from './steam-list-cache'
  13. // Steam counts a connected process as a running game, so like WE's ui32.exe connect only while shown
  14. let windowActive = false
  15. // Steam not running is normal: warn once per cooldown
  16. const RETRY_COOLDOWN_MS = 15000
  17. let lastInitFailure = 0
  18. let hasWarnedThisOutage = false
  19. let host: UtilityProcess | null = null
  20. let hostReady: Promise<void> | null = null
  21. let nextRequestId = 1
  22. const pendingRequests = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()
  23. let inFlight = 0
  24. const STEAM_PID_FILES = [
  25. path.join(os.homedir(), '.steam', 'steam.pid'),
  26. path.join(os.homedir(), '.var', 'app', 'com.valvesoftware.Steam', '.steam', 'steam.pid')
  27. ]
  28. const PROCESS_CHECK_TTL_MS = 5000
  29. let processCheck = { at: 0, alive: false }
  30. // Flatpak Steam's pid is from its own namespace, hence the /proc scan
  31. function steamProcessAlive(): boolean {
  32. if (Date.now() - processCheck.at < PROCESS_CHECK_TTL_MS) return processCheck.alive
  33. if (isFlatpak()) {
  34. let hostAlive = false
  35. try {
  36. const [file, args] = hostCommand('pgrep', ['-x', 'steam'])
  37. execFileSync(file, args, { stdio: 'ignore', timeout: 5000 })
  38. hostAlive = true
  39. } catch {
  40. hostAlive = false
  41. }
  42. processCheck = { at: Date.now(), alive: hostAlive }
  43. return hostAlive
  44. }
  45. let alive = false
  46. for (const file of STEAM_PID_FILES) {
  47. try {
  48. const pid = Number(fs.readFileSync(file, 'utf8').trim())
  49. if (pid > 0 && fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim() === 'steam') {
  50. alive = true
  51. break
  52. }
  53. } catch {
  54. // no pid file or the process is gone
  55. }
  56. }
  57. if (!alive) {
  58. try {
  59. alive = fs.readdirSync('/proc').some((entry) => {
  60. if (!/^\d+$/.test(entry)) return false
  61. try {
  62. return fs.readFileSync(`/proc/${entry}/comm`, 'utf8').trim() === 'steam'
  63. } catch {
  64. return false
  65. }
  66. })
  67. } catch {
  68. alive = false
  69. }
  70. }
  71. processCheck = { at: Date.now(), alive }
  72. return alive
  73. }
  74. function stopHost(): void {
  75. host?.kill()
  76. host = null
  77. hostReady = null
  78. }
  79. app.on('will-quit', stopHost)
  80. export function bindSteamToWindow(win: BrowserWindow): void {
  81. const update = (): void => {
  82. const active = !win.isDestroyed() && win.isVisible() && !win.isMinimized()
  83. if (active === windowActive) return
  84. windowActive = active
  85. // steamCall() disconnects after the last running call
  86. if (!active && host && inFlight === 0) {
  87. console.log('[Steam] Window hidden, disconnecting')
  88. stopHost()
  89. }
  90. }
  91. win.on('show', update)
  92. win.on('hide', update)
  93. win.on('minimize', update)
  94. win.on('restore', update)
  95. win.on('closed', update)
  96. update()
  97. }
  98. export function isSteamAllowed(): boolean {
  99. return windowActive
  100. }
  101. // steamworks.js calls have no timeout, a hung one would hold the connection
  102. const REQUEST_TIMEOUT_MS = 60 * 1000
  103. function send(proc: UtilityProcess, method: string, args: unknown[]): Promise<unknown> {
  104. const id = nextRequestId++
  105. return new Promise((resolve, reject) => {
  106. const timer = setTimeout(() => {
  107. pendingRequests.delete(id)
  108. reject(new Error(`Steam ${method} timed out`))
  109. }, REQUEST_TIMEOUT_MS)
  110. pendingRequests.set(id, {
  111. resolve: (v) => {
  112. clearTimeout(timer)
  113. resolve(v)
  114. },
  115. reject: (e) => {
  116. clearTimeout(timer)
  117. reject(e)
  118. }
  119. })
  120. proc.postMessage(encodeBigInts({ id, method, args }))
  121. })
  122. }
  123. function startHost(): Promise<void> {
  124. const proc = utilityProcess.fork(path.join(__dirname, 'steam-host.js'), [], {
  125. serviceName: 'we-manager-steam',
  126. stdio: 'inherit'
  127. })
  128. host = proc
  129. proc.on('message', (data) => {
  130. const res = decodeBigInts(data) as SteamHostResponse
  131. const pending = pendingRequests.get(res.id)
  132. if (!pending) return
  133. pendingRequests.delete(res.id)
  134. if (res.error !== undefined) pending.reject(new Error(res.error))
  135. else pending.resolve(res.result)
  136. })
  137. proc.on('exit', (code) => {
  138. if (host === proc) {
  139. host = null
  140. hostReady = null
  141. }
  142. if (pendingRequests.size > 0) {
  143. const err = new Error(`Steam host exited (code ${code})`)
  144. for (const pending of pendingRequests.values()) pending.reject(err)
  145. pendingRequests.clear()
  146. }
  147. })
  148. const appId = getSteamIdentity() === 'standalone' ? STANDALONE_APP_ID : WE_APP_ID
  149. return send(proc, 'init', [appId]).then(
  150. () => {
  151. hasWarnedThisOutage = false
  152. console.log(`[Steam] Connected (app id ${appId})`)
  153. },
  154. (err) => {
  155. if (host === proc) stopHost()
  156. lastInitFailure = Date.now()
  157. if (!hasWarnedThisOutage) {
  158. hasWarnedThisOutage = true
  159. console.warn('[Steam] Init failed (Steam may not be running):', err?.message ?? err)
  160. }
  161. throw err
  162. }
  163. )
  164. }
  165. async function steamCall<T>(method: string, ...args: unknown[]): Promise<T> {
  166. if (!windowActive) throw new Error('Steam is only used while the window is open')
  167. if (!isSteamRunning()) throw new Error('Steam not running')
  168. inFlight++
  169. try {
  170. if (!hostReady) hostReady = startHost()
  171. await hostReady
  172. return (await send(host!, method, args)) as T
  173. } finally {
  174. inFlight--
  175. if (inFlight === 0 && host && !windowActive) {
  176. console.log('[Steam] Window hidden, disconnecting')
  177. stopHost()
  178. }
  179. }
  180. }
  181. export function isSteamRunning(): boolean {
  182. if (!windowActive) return false
  183. if (Date.now() - lastInitFailure < RETRY_COOLDOWN_MS) return false
  184. return steamProcessAlive()
  185. }
  186. export async function getLocalAccountId(): Promise<number> {
  187. const id = await steamCall<{ accountId: number }>('localplayer.getSteamId')
  188. return id.accountId
  189. }
  190. export function getSubscribedIds(): Promise<bigint[]> {
  191. return steamCall<bigint[]>('workshop.getSubscribedItems')
  192. }
  193. export function workshopCall<T>(method: string, ...args: unknown[]): Promise<T> {
  194. return steamCall<T>(`workshop.${method}`, ...args)
  195. }
  196. export async function subscribeToItem(itemId: bigint): Promise<void> {
  197. await steamCall('workshop.subscribe', itemId)
  198. }
  199. // subscribing doesn't reliably start a download, no-op when already there
  200. export async function downloadItem(itemId: bigint, highPriority = true): Promise<boolean> {
  201. try {
  202. return await steamCall<boolean>('workshop.download', itemId, highPriority)
  203. } catch {
  204. return false
  205. }
  206. }
  207. export async function unsubscribeFromItem(itemId: bigint): Promise<void> {
  208. await steamCall('workshop.unsubscribe', itemId)
  209. }
  210. function isSteamOnline(): Promise<boolean> {
  211. return steamCall<boolean>('isOnline')
  212. }
  213. function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
  214. return new Promise((resolve, reject) => {
  215. const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
  216. promise.then(
  217. (value) => {
  218. clearTimeout(timer)
  219. resolve(value)
  220. },
  221. (err) => {
  222. clearTimeout(timer)
  223. reject(err)
  224. }
  225. )
  226. })
  227. }
  228. // vote bindings come from patches/steamworks-vote/, unpatched builds still work
  229. let hasPatchedVoteApi: boolean | null = null
  230. async function patchedVoteApiAvailable(): Promise<boolean> {
  231. if (hasPatchedVoteApi === null) {
  232. const [vote, check] = await Promise.all([
  233. steamCall<boolean>('hasMethod', 'workshop.voteItem'),
  234. steamCall<boolean>('hasMethod', 'workshop.getUserVote')
  235. ])
  236. hasPatchedVoteApi = vote && check
  237. }
  238. return hasPatchedVoteApi
  239. }
  240. export async function checkUserVote(
  241. itemId: bigint
  242. ): Promise<{ votedUp: boolean; votedDown: boolean } | null> {
  243. if (!(await patchedVoteApiAvailable())) return null
  244. const result = await steamCall<{ votedUp: boolean; votedDown: boolean }>('workshop.getUserVote', itemId)
  245. return { votedUp: result.votedUp, votedDown: result.votedDown }
  246. }
  247. export function voteOnItem(itemId: bigint, voteUp: boolean): Promise<bigint> {
  248. return steamCall<bigint>('voteRaw', itemId, voteUp)
  249. }
  250. export async function openWorkshopItemOverlay(itemId: bigint): Promise<void> {
  251. await steamCall('overlay.activateToWebPage', `https://steamcommunity.com/sharedfiles/filedetails/?id=${itemId}`)
  252. }
  253. const USER_ITEM_TYPE = 13 // UGCType.All
  254. const CREATION_ORDER_DESC = 1
  255. const VOTED_UP = 2
  256. const VOTED_DOWN = 3
  257. const FAVORITED = 4
  258. const PAGE_FETCH_TIMEOUT_MS = 8000
  259. const VOTE_TIMEOUT_MS = 15000
  260. interface UserItemsPage {
  261. items: Array<{ publishedFileId: bigint } | null | undefined>
  262. returnedResults: number
  263. totalResults: number
  264. }
  265. async function getUserItemsPage(
  266. accountId: number,
  267. listType: number,
  268. page: number,
  269. retries = 2
  270. ): Promise<UserItemsPage> {
  271. for (let attempt = 0; ; attempt++) {
  272. try {
  273. return await withTimeout(
  274. workshopCall<UserItemsPage>(
  275. 'getUserItems', page, accountId, listType, USER_ITEM_TYPE, CREATION_ORDER_DESC, { consumer: WE_APP_ID }
  276. ),
  277. PAGE_FETCH_TIMEOUT_MS,
  278. `getUserItems page ${page}`
  279. )
  280. } catch (err) {
  281. if (attempt >= retries) throw err
  282. await sleep(300 * (attempt + 1))
  283. }
  284. }
  285. }
  286. const VOTE_FETCH_CONCURRENCY = 3
  287. const PAGE_PACING_MS = 150
  288. // lists sort by publish date, not vote date, so a full list means crawling all of it
  289. async function fetchUserList(
  290. accountId: number,
  291. listType: number,
  292. onPage: (ids: string[]) => void
  293. ): Promise<Set<string>> {
  294. const ids = new Set<string>()
  295. const take = (items: Array<{ publishedFileId: bigint } | null | undefined>): void => {
  296. const pageIds: string[] = []
  297. for (const item of items) if (item) pageIds.push(item.publishedFileId.toString())
  298. for (const id of pageIds) ids.add(id)
  299. onPage(pageIds)
  300. }
  301. const first = await getUserItemsPage(accountId, listType, 1)
  302. take(first.items)
  303. const pageSize = first.returnedResults
  304. if (pageSize <= 0 || ids.size >= first.totalResults) return ids
  305. const totalPages = Math.ceil(first.totalResults / pageSize)
  306. const remainingPages = Array.from({ length: Math.max(0, totalPages - 1) }, (_, i) => i + 2)
  307. let cursor = 0
  308. async function worker(): Promise<void> {
  309. while (cursor < remainingPages.length) {
  310. const page = remainingPages[cursor++]
  311. const r = await getUserItemsPage(accountId, listType, page)
  312. take(r.items)
  313. await sleep(PAGE_PACING_MS)
  314. }
  315. }
  316. await Promise.all(
  317. Array.from({ length: Math.min(VOTE_FETCH_CONCURRENCY, remainingPages.length) }, worker)
  318. )
  319. return ids
  320. }
  321. function listSource(listType: number) {
  322. return {
  323. canSync: isSteamRunning,
  324. getAccountId: getLocalAccountId,
  325. crawl: (accountId: number, onPage: (ids: string[]) => void) => fetchUserList(accountId, listType, onPage)
  326. }
  327. }
  328. const likedList = new SteamListCache('Liked list', 'vote-cache', listSource(VOTED_UP))
  329. const dislikedList = new SteamListCache('Disliked list', 'dislike-cache', listSource(VOTED_DOWN))
  330. const favoriteList = new SteamListCache('Favorites', 'favorite-cache', listSource(FAVORITED))
  331. const WRITE_ATTEMPTS = 4
  332. const WRITE_RETRY_BASE_MS = 1500
  333. // Steam drops overlapping UGC writes
  334. const WRITE_GAP_MS = 400
  335. let writeQueue: Promise<unknown> = Promise.resolve()
  336. function queueSteamWrite<T>(run: () => Promise<T>): Promise<T> {
  337. const result = writeQueue.then(run)
  338. writeQueue = result.catch(() => {}).then(() => sleep(WRITE_GAP_MS))
  339. return result
  340. }
  341. async function withRetry(what: string, attempt: () => Promise<void>): Promise<void> {
  342. let lastErr: unknown
  343. for (let i = 0; i < WRITE_ATTEMPTS; i++) {
  344. if (i > 0) await sleep(WRITE_RETRY_BASE_MS * 2 ** (i - 1))
  345. if (!isSteamRunning()) throw new Error(`Steam is not running - start Steam to ${what}`)
  346. if (!(await isSteamOnline())) throw new Error('Steam is offline - check your internet connection and try again')
  347. try {
  348. await attempt()
  349. return
  350. } catch (err) {
  351. lastErr = err
  352. console.warn(`[Steam] Could not ${what} (attempt ${i + 1}/${WRITE_ATTEMPTS}):`, (err as Error)?.message ?? err)
  353. }
  354. }
  355. throw lastErr
  356. }
  357. // session only
  358. const failedVotes = new Map<string, { up: boolean; message: string }>()
  359. let failedVotesChangeListener: ((failed: Record<string, string>) => void) | null = null
  360. export function getFailedVotes(): Record<string, string> {
  361. const out: Record<string, string> = {}
  362. for (const [id, failure] of failedVotes) {
  363. // liked elsewhere since
  364. if ((failure.up ? likedList : dislikedList).has(id)) failedVotes.delete(id)
  365. else out[id] = failure.message
  366. }
  367. return out
  368. }
  369. export function onFailedVotesChange(cb: (failed: Record<string, string>) => void): void {
  370. failedVotesChangeListener = cb
  371. }
  372. function setVoteFailure(idStr: string, failure: { up: boolean; message: string } | null): void {
  373. if (failure === null) {
  374. if (!failedVotes.delete(idStr)) return
  375. } else {
  376. failedVotes.set(idStr, failure)
  377. }
  378. failedVotesChangeListener?.(getFailedVotes())
  379. }
  380. export function voteOnItemAndConfirm(itemId: bigint, voteUp: boolean): Promise<boolean> {
  381. const idStr = itemId.toString()
  382. return queueSteamWrite(async () => {
  383. try {
  384. await withRetry(voteUp ? 'like wallpapers' : 'dislike wallpapers', () => voteOnce(itemId, voteUp))
  385. } catch (err) {
  386. const msg = (err as Error)?.message ?? String(err)
  387. setVoteFailure(idStr, {
  388. up: voteUp,
  389. message: `${voteUp ? 'Like' : 'Dislike'} failed after ${WRITE_ATTEMPTS} attempts: ${msg}`
  390. })
  391. throw new Error(`Could not reach Steam to ${voteUp ? 'like' : 'dislike'} this wallpaper: ${msg}`)
  392. }
  393. setVoteFailure(idStr, null)
  394. likedList.record(idStr, voteUp)
  395. dislikedList.record(idStr, !voteUp)
  396. return true
  397. })
  398. }
  399. // unpatched: success once enqueued, steamworks.js consumes the call result first
  400. async function voteOnce(itemId: bigint, voteUp: boolean): Promise<void> {
  401. if (await patchedVoteApiAvailable()) {
  402. await withTimeout(steamCall('workshop.voteItem', itemId, voteUp), VOTE_TIMEOUT_MS, 'Vote')
  403. } else {
  404. await voteOnItem(itemId, voteUp)
  405. }
  406. }
  407. export async function getVotedUpItemIds(): Promise<string[]> {
  408. return likedList.list()
  409. }
  410. export function getVotedDownItemIds(): string[] {
  411. return dislikedList.list()
  412. }
  413. export async function refreshItemVote(itemId: bigint): Promise<boolean | null> {
  414. if (!isSteamRunning() || !(await isSteamOnline().catch(() => false))) return null
  415. const result = await withTimeout(checkUserVote(itemId), PAGE_FETCH_TIMEOUT_MS, 'getUserVote').catch((err) => {
  416. console.warn('[Steam] Per-item vote check failed:', err?.message ?? err)
  417. return null
  418. })
  419. if (!result) return null
  420. dislikedList.applyCheck(itemId.toString(), result.votedDown)
  421. return likedList.applyCheck(itemId.toString(), result.votedUp)
  422. }
  423. let hasPatchedFavoriteApi: boolean | null = null
  424. async function patchedFavoriteApiAvailable(): Promise<boolean> {
  425. if (hasPatchedFavoriteApi === null) {
  426. const [add, remove] = await Promise.all([
  427. steamCall<boolean>('hasMethod', 'workshop.addFavorite'),
  428. steamCall<boolean>('hasMethod', 'workshop.removeFavorite')
  429. ])
  430. hasPatchedFavoriteApi = add && remove
  431. }
  432. return hasPatchedFavoriteApi
  433. }
  434. // favorites belong to WE's app id, even when connected as Spacewar
  435. async function favoriteOnce(itemId: bigint, add: boolean): Promise<void> {
  436. if (await patchedFavoriteApiAvailable()) {
  437. const method = add ? 'workshop.addFavorite' : 'workshop.removeFavorite'
  438. await withTimeout(steamCall(method, WE_APP_ID, itemId), VOTE_TIMEOUT_MS, 'Favorite')
  439. } else {
  440. await steamCall<bigint>('favoriteRaw', WE_APP_ID, itemId, add)
  441. }
  442. }
  443. // session-only, like failedVotes
  444. const failedFavorites = new Map<string, FavoriteFailure>()
  445. let favoriteStatusListener: ((status: FavoriteStatus) => void) | null = null
  446. export function getFavoriteStatus(): FavoriteStatus {
  447. const failed: Record<string, FavoriteFailure> = {}
  448. for (const [id, failure] of failedFavorites) {
  449. // already as intended, e.g. changed on the website
  450. if (favoriteList.has(id) === failure.add) failedFavorites.delete(id)
  451. else failed[id] = failure
  452. }
  453. return { failed, checking: favoriteList.unverified() }
  454. }
  455. export function onFavoriteStatusChange(cb: (status: FavoriteStatus) => void): void {
  456. favoriteStatusListener = cb
  457. }
  458. function favoriteStatusChanged(): void {
  459. favoriteStatusListener?.(getFavoriteStatus())
  460. }
  461. favoriteList.onVerified((id, add, confirmed) => {
  462. if (confirmed) {
  463. failedFavorites.delete(id)
  464. } else {
  465. console.warn(`[Steam] Favorites list still ${add ? 'misses' : 'has'} ${id}, the change didn't stick`)
  466. failedFavorites.set(id, {
  467. add,
  468. readBack: true,
  469. message: `Steam accepted the ${add ? 'favorite' : 'removal'}, but your favorites list still ${add ? "doesn't show" : 'shows'} this wallpaper 15 minutes later`
  470. })
  471. }
  472. favoriteStatusChanged()
  473. })
  474. export function setFavorite(itemId: bigint, add: boolean): Promise<boolean> {
  475. const idStr = itemId.toString()
  476. return queueSteamWrite(async () => {
  477. try {
  478. await withRetry(add ? 'add favorites' : 'remove favorites', () => favoriteOnce(itemId, add))
  479. } catch (err) {
  480. const msg = (err as Error)?.message ?? String(err)
  481. failedFavorites.set(idStr, {
  482. add,
  483. readBack: false,
  484. message: `${add ? 'Adding to' : 'Removing from'} favorites failed after ${WRITE_ATTEMPTS} attempts: ${msg}`
  485. })
  486. favoriteStatusChanged()
  487. throw new Error(`Could not reach Steam to ${add ? 'favorite' : 'unfavorite'} this wallpaper: ${msg}`)
  488. }
  489. failedFavorites.delete(idStr)
  490. favoriteList.record(idStr, add)
  491. favoriteStatusChanged()
  492. return true
  493. })
  494. }
  495. export function getFavoriteItemIds(): string[] {
  496. return favoriteList.list()
  497. }
  498. const SYNC_CHECK_INTERVAL_MS = 10 * 60 * 1000
  499. const SYNC_STARTUP_DELAY_MS = 20 * 1000
  500. let listSyncTimer: ReturnType<typeof setInterval> | null = null
  501. export function startUserListSync(listeners: {
  502. onLikedChange: (ids: string[]) => void
  503. onDislikedChange: (ids: string[]) => void
  504. onFavoritesChange: (ids: string[]) => void
  505. }): void {
  506. likedList.onChange(listeners.onLikedChange)
  507. dislikedList.onChange(listeners.onDislikedChange)
  508. favoriteList.onChange((ids) => {
  509. listeners.onFavoritesChange(ids)
  510. if (failedFavorites.size > 0) favoriteStatusChanged()
  511. })
  512. if (listSyncTimer) return
  513. const tick = (): void => {
  514. likedList.maybeSync()
  515. dislikedList.maybeSync()
  516. favoriteList.maybeSync()
  517. }
  518. setTimeout(tick, SYNC_STARTUP_DELAY_MS)
  519. listSyncTimer = setInterval(tick, SYNC_CHECK_INTERVAL_MS)
  520. }
  521. export async function getSubscribedItems(): Promise<string[]> {
  522. return (await getSubscribedIds()).map((id) => id.toString())
  523. }
  524. export async function getDownloadInfo(itemId: bigint): Promise<DownloadProgressEvent | null> {
  525. try {
  526. const info = await workshopCall<{ current: bigint; total: bigint } | null>('downloadInfo', itemId)
  527. if (!info) return null
  528. const bytesTotal = Number(info.total)
  529. const bytesDownloaded = Number(info.current)
  530. return {
  531. itemId: itemId.toString(),
  532. bytesDownloaded,
  533. bytesTotal,
  534. percentage: bytesTotal > 0 ? Math.round((bytesDownloaded / bytesTotal) * 100) : 0,
  535. status: 'downloading'
  536. }
  537. } catch {
  538. return null
  539. }
  540. }
  541. export async function getInstallInfo(itemId: bigint): Promise<{ folder: string; sizeOnDisk: number } | null> {
  542. try {
  543. const info = await workshopCall<{ folder: string; sizeOnDisk: bigint } | null>('installInfo', itemId)
  544. if (!info) return null
  545. return { folder: info.folder, sizeOnDisk: Number(info.sizeOnDisk) }
  546. } catch {
  547. return null
  548. }
  549. }
  550. // steamworks.js only knows the player and friends, read the public profile XML
  551. const authorInfoCache = new Map<string, WorkshopAuthorInfo | null>()
  552. export async function getAuthorInfo(steamId: string): Promise<WorkshopAuthorInfo | null> {
  553. if (authorInfoCache.has(steamId)) return authorInfoCache.get(steamId) ?? null
  554. try {
  555. const res = await fetch(`https://steamcommunity.com/profiles/${steamId}?xml=1`)
  556. const xml = await res.text()
  557. const name = xml.match(/<steamID><!\[CDATA\[([\s\S]*?)\]\]><\/steamID>/)?.[1]
  558. const avatarUrl = xml.match(/<avatarFull><!\[CDATA\[([\s\S]*?)\]\]><\/avatarFull>/)?.[1]
  559. const info = name && avatarUrl ? { steamId, name, avatarUrl } : null
  560. authorInfoCache.set(steamId, info)
  561. return info
  562. } catch {
  563. authorInfoCache.set(steamId, null)
  564. return null
  565. }
  566. }
  567. /** EItemState, throws when Steam can't be asked */
  568. export function fetchItemState(itemId: bigint): Promise<number> {
  569. return workshopCall<number>('state', itemId)
  570. }
  571. /** EItemState, 0 when Steam can't be asked */
  572. export async function getItemState(itemId: bigint): Promise<number> {
  573. try {
  574. return await fetchItemState(itemId)
  575. } catch {
  576. return 0
  577. }
  578. }
  579. // EItemState flags from the Steamworks SDK (isteamugc.h)
  580. export const ITEM_STATE_INSTALLED = 4
  581. export const ITEM_STATE_NEEDS_UPDATE = 8
  582. export const ITEM_STATE_DOWNLOADING = 16
  583. export const ITEM_STATE_DOWNLOAD_PENDING = 32
  584. // subscribed but never fetched, not even flagged as needing an update
  585. function isStuckNeverDownloaded(state: number): boolean {
  586. const installed = (state & ITEM_STATE_INSTALLED) !== 0
  587. const inProgress = (state & (ITEM_STATE_DOWNLOADING | ITEM_STATE_DOWNLOAD_PENDING | ITEM_STATE_NEEDS_UPDATE)) !== 0
  588. return !installed && !inProgress
  589. }
  590. export async function isItemStuckNeverDownloaded(itemId: bigint): Promise<boolean> {
  591. return isStuckNeverDownloaded(await getItemState(itemId))
  592. }
  593. export async function isItemDownloading(itemId: bigint): Promise<boolean> {
  594. const state = await getItemState(itemId)
  595. return (state & (ITEM_STATE_DOWNLOADING | ITEM_STATE_DOWNLOAD_PENDING)) !== 0
  596. }
  597. // NeedsUpdate and not downloading = Steam gave up; never-downloaded counts as downloading
  598. export async function getItemDownloadStatus(itemId: bigint): Promise<{ downloading: boolean; failed: boolean }> {
  599. const state = await getItemState(itemId)
  600. const downloading =
  601. (state & (ITEM_STATE_DOWNLOADING | ITEM_STATE_DOWNLOAD_PENDING)) !== 0 || isStuckNeverDownloaded(state)
  602. const failed = !downloading && (state & ITEM_STATE_NEEDS_UPDATE) !== 0
  603. return { downloading, failed }
  604. }