steam-host.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import * as path from 'path'
  2. import { encodeBigInts, decodeBigInts, type SteamHostRequest, type SteamHostResponse } from './steam-host-protocol'
  3. type Koffi = typeof import('koffi')
  4. type SteamClient = ReturnType<typeof import('steamworks.js')['init']>
  5. let client: SteamClient | null = null
  6. function init(appId: number): void {
  7. // eslint-disable-next-line @typescript-eslint/no-require-imports
  8. const steamworks: typeof import('steamworks.js') = require('steamworks.js')
  9. client = steamworks.init(appId)
  10. }
  11. // not bound in steamworks.js, so called through the flat C API of the already loaded libsteam_api.so
  12. let steamLib: ReturnType<Koffi['load']> | null = null
  13. let ugc: {
  14. ptr: unknown
  15. setUserItemVote: (ugc: unknown, itemId: bigint, voteUp: boolean) => bigint
  16. addItemToFavorites: (ugc: unknown, appId: number, itemId: bigint) => bigint
  17. removeItemFromFavorites: (ugc: unknown, appId: number, itemId: bigint) => bigint
  18. } | null = null
  19. let isLoggedOn: (() => boolean) | null = null
  20. function getSteamLib(): ReturnType<Koffi['load']> {
  21. if (!steamLib) {
  22. // eslint-disable-next-line @typescript-eslint/no-require-imports
  23. const koffi: Koffi = require('koffi')
  24. const libPath = path.join(
  25. path.dirname(require.resolve('steamworks.js')),
  26. 'dist', 'linux64', 'libsteam_api.so'
  27. ).replace(/app\.asar(?!\.unpacked)/, 'app.asar.unpacked')
  28. steamLib = koffi.load(libPath)
  29. }
  30. return steamLib
  31. }
  32. function getUgc(): NonNullable<typeof ugc> {
  33. if (!ugc) {
  34. // eslint-disable-next-line @typescript-eslint/no-require-imports
  35. const koffi: Koffi = require('koffi')
  36. const lib = getSteamLib()
  37. const ugcPtrType = koffi.pointer(koffi.opaque('ISteamUGC'))
  38. ugc = {
  39. ptr: lib.func('SteamAPI_SteamUGC_v020', ugcPtrType, [])(),
  40. setUserItemVote: lib.func('SteamAPI_ISteamUGC_SetUserItemVote', 'uint64', [ugcPtrType, 'uint64', 'bool']),
  41. addItemToFavorites: lib.func('SteamAPI_ISteamUGC_AddItemToFavorites', 'uint64', [ugcPtrType, 'uint32', 'uint64']),
  42. removeItemFromFavorites: lib.func('SteamAPI_ISteamUGC_RemoveItemFromFavorites', 'uint64', [ugcPtrType, 'uint32', 'uint64'])
  43. }
  44. }
  45. return ugc
  46. }
  47. // 0 = k_uAPICallInvalid
  48. function voteRaw(itemId: bigint, voteUp: boolean): bigint {
  49. const api = getUgc()
  50. const handle = api.setUserItemVote(api.ptr, itemId, voteUp)
  51. if (handle === 0n) throw new Error('SetUserItemVote failed')
  52. return handle
  53. }
  54. function favoriteRaw(appId: number, itemId: bigint, add: boolean): bigint {
  55. const api = getUgc()
  56. const handle = add ? api.addItemToFavorites(api.ptr, appId, itemId) : api.removeItemFromFavorites(api.ptr, appId, itemId)
  57. if (handle === 0n) throw new Error(add ? 'AddItemToFavorites failed' : 'RemoveItemFromFavorites failed')
  58. return handle
  59. }
  60. function isOnline(): boolean {
  61. if (!isLoggedOn) {
  62. // eslint-disable-next-line @typescript-eslint/no-require-imports
  63. const koffi: Koffi = require('koffi')
  64. const lib = getSteamLib()
  65. const userPtrType = koffi.pointer(koffi.opaque('ISteamUser'))
  66. const userPtr = lib.func('SteamAPI_SteamUser_v023', userPtrType, [])()
  67. const bLoggedOn = lib.func('SteamAPI_ISteamUser_BLoggedOn', 'bool', [userPtrType])
  68. isLoggedOn = () => bLoggedOn(userPtr)
  69. }
  70. return isLoggedOn()
  71. }
  72. async function call(method: string, args: unknown[]): Promise<unknown> {
  73. if (method === 'init') {
  74. init(args[0] as number)
  75. return null
  76. }
  77. if (!client) throw new Error('Steam not initialized')
  78. if (method === 'voteRaw') return voteRaw(args[0] as bigint, args[1] as boolean)
  79. if (method === 'favoriteRaw') return favoriteRaw(args[0] as number, args[1] as bigint, args[2] as boolean)
  80. if (method === 'isOnline') return isOnline()
  81. if (method === 'hasMethod') {
  82. const [ns, fn] = (args[0] as string).split('.')
  83. return typeof (client as unknown as Record<string, Record<string, unknown>>)[ns]?.[fn] === 'function'
  84. }
  85. const [ns, fn] = method.split('.')
  86. const target = (client as unknown as Record<string, Record<string, unknown>>)[ns]
  87. const func = target?.[fn]
  88. if (typeof func !== 'function') throw new Error(`Unknown Steam method ${method}`)
  89. return await func.apply(target, args)
  90. }
  91. process.parentPort.on('message', (e) => {
  92. const req = decodeBigInts(e.data) as SteamHostRequest
  93. call(req.method, req.args).then(
  94. (result) => process.parentPort.postMessage(encodeBigInts({ id: req.id, result } satisfies SteamHostResponse)),
  95. (err) => process.parentPort.postMessage({ id: req.id, error: (err as Error)?.message ?? String(err) } satisfies SteamHostResponse)
  96. )
  97. })