workshop.service.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import { WE_APP_ID } from '@shared/constants'
  2. import type {
  3. WorkshopQueryParams,
  4. WorkshopQueryResult,
  5. WorkshopItem,
  6. CreatorWorkshopQueryParams
  7. } from '@shared/types'
  8. import type { workshop } from 'steamworks.js/client'
  9. import { workshopCall, getSubscribedItems } from './steam.service'
  10. type SteamWorkshopItem = workshop.WorkshopItem
  11. type WorkshopPage = workshop.WorkshopPaginatedResult
  12. const QUERY_TYPE_MAP: Record<string, number> = {
  13. RankedByVote: 0,
  14. RankedByPublicationDate: 1,
  15. RankedByTrend: 3,
  16. RankedByTotalUniqueSubscriptions: 12,
  17. RankedByTextSearch: 11,
  18. RankedByLastUpdatedDate: 19
  19. }
  20. const USER_LIST_ORDER_MAP: Record<string, number> = {
  21. RankedByVote: 5, // VoteScoreDesc
  22. RankedByPublicationDate: 1, // CreationOrderDesc
  23. RankedByTrend: 1, // no trend equivalent, falls back to newest
  24. RankedByTotalUniqueSubscriptions: 4, // SubscriptionDateDesc, closest analog
  25. RankedByTextSearch: 1,
  26. RankedByLastUpdatedDate: 3 // LastUpdatedDesc
  27. }
  28. export async function queryWorkshop(params: WorkshopQueryParams): Promise<WorkshopQueryResult> {
  29. const appId = params.appId ?? WE_APP_ID
  30. const page = params.page ?? 1
  31. const queryType = QUERY_TYPE_MAP[params.queryType ?? 'RankedByPublicationDate'] ?? 1
  32. const result = await workshopCall<WorkshopPage>(
  33. 'getAllItems',
  34. page,
  35. queryType,
  36. 13, // UGCType.All, since WE items span multiple subtypes
  37. appId,
  38. appId,
  39. queryConfig(params)
  40. )
  41. return toQueryResult(result, page)
  42. }
  43. export async function getWorkshopItem(publishedFileId: string): Promise<WorkshopItem | null> {
  44. let item: SteamWorkshopItem | null
  45. try {
  46. item = await workshopCall<SteamWorkshopItem | null>('getItem', BigInt(publishedFileId), {
  47. includeLongDescription: true
  48. })
  49. } catch {
  50. // an id Steam can no longer resolve (taken down, banned) throws here instead of returning null like getItems()
  51. return null
  52. }
  53. if (!item) return null
  54. const subscribedSet = new Set(await getSubscribedItems())
  55. const transformed = transformItem(item, subscribedSet)
  56. await attachFileSizes([transformed])
  57. return transformed
  58. }
  59. export async function queryWorkshopByCreator(
  60. creatorSteamId: string,
  61. params: CreatorWorkshopQueryParams = {}
  62. ): Promise<WorkshopQueryResult> {
  63. const accountId = Number(BigInt(creatorSteamId) & 0xffffffffn)
  64. const page = params.page ?? 1
  65. const sortOrder = USER_LIST_ORDER_MAP[params.queryType ?? 'RankedByPublicationDate'] ?? 1
  66. const result = await workshopCall<WorkshopPage>(
  67. 'getUserItems',
  68. page,
  69. accountId,
  70. 0, // UserListType.Published
  71. 13, // UGCType.All
  72. sortOrder,
  73. { consumer: WE_APP_ID },
  74. queryConfig(params)
  75. )
  76. return toQueryResult(result, page)
  77. }
  78. function queryConfig(params: CreatorWorkshopQueryParams): workshop.WorkshopItemQueryConfig {
  79. return {
  80. searchText: params.searchText,
  81. requiredTags: params.tags,
  82. excludedTags: params.excludedTags,
  83. includeLongDescription: true
  84. }
  85. }
  86. async function toQueryResult(result: WorkshopPage, page: number): Promise<WorkshopQueryResult> {
  87. const subscribedSet = new Set(await getSubscribedItems())
  88. const items = result.items.filter(Boolean).map((item) => transformItem(item!, subscribedSet))
  89. await attachFileSizes(items)
  90. return { items, page, totalResults: result.totalResults }
  91. }
  92. // A details query only fetches its first result page, and Steam pages those at 50 items -
  93. // anything past that in a single getItems() call silently comes back missing.
  94. const DETAILS_QUERY_BATCH = 50
  95. async function getItemsBatched(publishedFileIds: string[]) {
  96. const items: SteamWorkshopItem[] = []
  97. for (let i = 0; i < publishedFileIds.length; i += DETAILS_QUERY_BATCH) {
  98. const batch = publishedFileIds.slice(i, i + DETAILS_QUERY_BATCH)
  99. const result = await workshopCall<workshop.WorkshopItemsResult>('getItems', batch.map((id) => BigInt(id)))
  100. for (const item of result.items) {
  101. if (item) items.push(item)
  102. }
  103. }
  104. return items
  105. }
  106. export async function isWallpaperEngineItem(publishedFileId: string): Promise<boolean> {
  107. const [item] = await getItemsBatched([publishedFileId])
  108. return !!item && (item.consumerAppId === undefined || item.consumerAppId === WE_APP_ID)
  109. }
  110. export interface WorkshopDetails {
  111. timeUpdated: number
  112. // includes type and age rating, so items without a local project.json can still be classified
  113. tags: string[]
  114. authorSteamId: string
  115. }
  116. // One details query serves everything the library backfills (update time, live tags, author),
  117. // ids Steam no longer resolves are simply missing from the map
  118. export async function getWorkshopDetails(publishedFileIds: string[]): Promise<Map<string, WorkshopDetails>> {
  119. const map = new Map<string, WorkshopDetails>()
  120. if (publishedFileIds.length === 0) return map
  121. for (const item of await getItemsBatched(publishedFileIds)) {
  122. map.set(item.publishedFileId.toString(), {
  123. timeUpdated: item.timeUpdated,
  124. tags: item.tags ?? [],
  125. authorSteamId: item.owner.steamId64.toString()
  126. })
  127. }
  128. return map
  129. }
  130. // ids missing from the result are unavailable; a request error propagates so the caller doesn't read it as "all clear"
  131. export async function getUnavailableWorkshopItems(publishedFileIds: string[]): Promise<Set<string>> {
  132. const details = await getWorkshopDetails(publishedFileIds)
  133. return new Set(publishedFileIds.filter((id) => !details.has(id)))
  134. }
  135. // steamworks.js doesn't map the file size field; Steam's public web API has the figure shown on the Workshop page
  136. const fileSizeCache = new Map<string, number>()
  137. const FILE_SIZE_BATCH = 100
  138. const FILE_SIZE_TIMEOUT_MS = 15_000
  139. async function fetchFileSizesBatch(ids: string[]): Promise<void> {
  140. if (ids.length === 0) return
  141. const body = new URLSearchParams({ itemcount: String(ids.length) })
  142. ids.forEach((id, i) => { body.set(`publishedfileids[${i}]`, id) })
  143. const res = await fetch('https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/', {
  144. method: 'POST',
  145. body,
  146. signal: AbortSignal.timeout(FILE_SIZE_TIMEOUT_MS)
  147. })
  148. const data = (await res.json()) as { response?: { publishedfiledetails?: ({ publishedfileid?: string; file_size?: string | number | null } | null)[] } } | null
  149. const details = data?.response?.publishedfiledetails ?? []
  150. for (const d of details) {
  151. if (d?.publishedfileid && d.file_size != null) {
  152. fileSizeCache.set(d.publishedfileid, Number(d.file_size))
  153. }
  154. }
  155. }
  156. async function attachFileSizes(items: WorkshopItem[]): Promise<void> {
  157. const uncached = [...new Set(items.map((i) => i.publishedFileId).filter((id) => !fileSizeCache.has(id)))]
  158. if (uncached.length > 0) {
  159. try {
  160. for (let i = 0; i < uncached.length; i += FILE_SIZE_BATCH) {
  161. await fetchFileSizesBatch(uncached.slice(i, i + FILE_SIZE_BATCH))
  162. }
  163. } catch (err) {
  164. console.warn('[Workshop] Failed to fetch file sizes:', err)
  165. }
  166. }
  167. for (const item of items) {
  168. const size = fileSizeCache.get(item.publishedFileId)
  169. if (size != null) item.fileSize = size
  170. }
  171. }
  172. function transformItem(
  173. item: SteamWorkshopItem,
  174. subscribedSet: Set<string>
  175. ): WorkshopItem {
  176. return {
  177. publishedFileId: item.publishedFileId.toString(),
  178. title: item.title,
  179. description: item.description,
  180. previewUrl: item.previewUrl ?? '',
  181. creatorSteamId: item.owner.steamId64.toString(),
  182. tags: item.tags ?? [],
  183. timeCreated: item.timeCreated,
  184. timeUpdated: item.timeUpdated,
  185. subscriptions: Number(item.statistics?.numSubscriptions ?? 0),
  186. upvotes: item.numUpvotes,
  187. downvotes: item.numDownvotes,
  188. isSubscribed: subscribedSet.has(item.publishedFileId.toString())
  189. }
  190. }