steamutils 1.3.75 → 1.3.77

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. package/SteamClient.js +2426 -2418
  2. package/index.js +14 -4
  3. package/package.json +1 -1
package/SteamClient.js CHANGED
@@ -1,2418 +1,2426 @@
1
- import NodeSteamUser from "steam-user";
2
- import _ from "lodash";
3
- import fs from "fs";
4
- import { protoDecode, protoEncode } from "./helpers/util.js";
5
- import SteamID from "steamid";
6
- import FriendCode from "csgo-friendcode";
7
- import axios from "axios";
8
- import helpers, { loadProfos } from "./helpers/protos.js";
9
- import { fileURLToPath } from "url";
10
- import path from "path";
11
- import SteamUser from "./index.js";
12
- import { v4 as uuidv4 } from "uuid";
13
- import EFriendRelationship from "steam-user/enums/EFriendRelationship.js";
14
- import SteamCommunity from "steamcommunity";
15
- import moment from "moment-timezone";
16
- import { encode, encodeUids } from "./bufferHelpers.js";
17
-
18
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
-
20
- const Protos = helpers([
21
- {
22
- name: "csgo",
23
- protos: loadProfos(`${__dirname}/protos/`),
24
- },
25
- ]);
26
-
27
- export const RANKS = {
28
- 0: "Unranked",
29
- 1: "Silver I",
30
- 2: "Silver II",
31
- 3: "Silver III",
32
- 4: "Silver IV",
33
- 5: "Silver Elite",
34
- 6: "Silver Elite Master",
35
- 7: "Gold Nova I",
36
- 8: "Gold Nova II",
37
- 9: "Gold Nova III",
38
- 10: "Gold Nova Master",
39
- 11: "Master Guardian I",
40
- 12: "Master Guardian II",
41
- 13: "Master Guardian Elite",
42
- 14: "Distinguished Master Guardian",
43
- 15: "Legendary Eagle",
44
- 16: "Legendary Eagle Master",
45
- 17: "Supreme Master First Class",
46
- 18: "The Global Elite",
47
- };
48
- export const LOCS = {
49
- 20054: "VN",
50
- 23115: "KZ",
51
- 20041: "IN",
52
- 20035: "CN",
53
- 17474: "BD",
54
- 17481: "ID",
55
- 22861: "MY",
56
- 18516: "TH",
57
- 22356: "TW",
58
- 21067: "KR",
59
- 19272: "HK",
60
- 18512: "PH",
61
- 21842: "RU",
62
- 16716: "LA",
63
- 20558: "NP",
64
- 18259: "SG",
65
- 19789: "MM",
66
- 20045: "MN",
67
- 18251: "KG",
68
- 18507: "KH",
69
- 22605: "MX",
70
- 19280: "PK",
71
- 20301: "HK/MO", //hongkong or macau
72
- 21333: "Unknown",
73
- 21825: "AU",
74
- 20034: "Unkown",
75
- };
76
-
77
- const AppID = 730;
78
- export let CSGO_VER = 13960;
79
- export const FreeAppList = JSON.parse(fs.readFileSync(path.join(__dirname, "free_packages.json"))).packages;
80
-
81
- SteamUser.getAppVersion(AppID).then(function (ver) {
82
- CSGO_VER = ver;
83
- });
84
-
85
- const PersonasCache = [];
86
- let isSendingFriendMessages = false;
87
-
88
- function SteamClient({ username, password, cookie, clientJsToken, isAutoRequestFreeLicense = true, isFakeGameScore = true, isPartyRegister = true, isAutoPlay = false, isInvisible = false, autoAcceptTradeRequest = false, autoReconnect = true, MAX_GAME_PLAY = 10, games = null }) {
89
- const steamClient = new NodeSteamUser();
90
- let prime = null;
91
- let state = "Offline"; //InGame, Online, Invisible
92
- let isLogOff = false;
93
- let playingBlocked = null;
94
- const richPresence = {};
95
- let sendMessageTimestamp = 0;
96
- let lastTimePartyRegister = 0;
97
- let lastTimePartySearch = 0;
98
- const ownedApps = [];
99
- let logOffEvent = null;
100
-
101
- const currentLobby = {
102
- lobbyID: null,
103
- timestamp: 0,
104
- };
105
-
106
- const onAnyCallbacks = [];
107
-
108
- const events = {
109
- user: [],
110
- loggedOn: [],
111
- csgoOnline: [],
112
- csgoClientHello: [],
113
- webSession: [],
114
- friendMessage: [],
115
- friendTyping: [],
116
- disconnected: [],
117
- error: [],
118
- playersProfile: [],
119
- fatalError: [],
120
- partyInvite: [],
121
- friendRelationship: [],
122
- tradeOffers: [],
123
- offlineMessages: [],
124
- friendsList: [],
125
- gifts: [],
126
- playingState: [],
127
- emailInfo: [],
128
- accountLimitations: [],
129
- };
130
-
131
- const gcCallback = {};
132
-
133
- function pushGCCallback(name, cb, timeout) {
134
- if (!gcCallback[name]) {
135
- gcCallback[name] = {};
136
- }
137
- let t = null;
138
- let id = uuidv4();
139
-
140
- function callback(...arg) {
141
- if (t) {
142
- clearTimeout(t);
143
- }
144
- delete gcCallback[name][id];
145
- cb?.apply(null, arg);
146
- }
147
-
148
- if (timeout) {
149
- t = setTimeout(callback, timeout);
150
- }
151
- gcCallback[name][id] = callback;
152
- }
153
-
154
- function callGCCallback(name, ...arg) {
155
- if (gcCallback[name]) {
156
- for (const id in gcCallback[name]) {
157
- gcCallback[name][id]?.(...arg);
158
- }
159
- }
160
- }
161
-
162
- function callEvent(_events, data) {
163
- const eventName = Object.keys(events).find((eventName) => events[eventName] === _events);
164
- eventName && onAnyCallbacks.forEach((cb) => cb?.({ eventName, data }));
165
-
166
- _events?.forEach?.((e) => {
167
- e.callback?.(data);
168
- e.timeout && clearTimeout(e.timeout);
169
- delete e.timeout;
170
- if (e.once) {
171
- delete e.callback;
172
- }
173
- });
174
- _.remove(_events, (e) => !e || e?.once);
175
- }
176
-
177
- function onEvent(name, callback, once, timeout) {
178
- if (!events[name]) {
179
- events[name] = [];
180
- }
181
- const t = timeout ? setTimeout(callback, timeout) : null;
182
- events[name].push({
183
- once,
184
- callback,
185
- timeout: t,
186
- });
187
- }
188
-
189
- function offEvent(name) {
190
- if (Array.isArray(events[name])) {
191
- for (const eventElement of events[name]) {
192
- if (eventElement.timeout) {
193
- clearTimeout(eventElement.timeout);
194
- }
195
- }
196
- }
197
-
198
- delete events[name];
199
- }
200
-
201
- function onAnyEvent(callback) {
202
- onAnyCallbacks.push(callback);
203
- }
204
-
205
- function offAllEvent() {
206
- for (const name in events) {
207
- for (const event of events[name]) {
208
- if (event.timeout) {
209
- try {
210
- clearTimeout(event.timeout);
211
- } catch (e) {}
212
- delete event.timeout;
213
- }
214
- }
215
- delete events[name];
216
- }
217
- onAnyCallbacks.length = 0;
218
- }
219
-
220
- const intervals = {};
221
- const intervalRandoms = {};
222
-
223
- function doSetInterval(cb, timeout, key) {
224
- const isRandom = Array.isArray(timeout);
225
- if (!key) {
226
- key = uuidv4();
227
- }
228
- if (isRandom) {
229
- if (intervalRandoms[key] !== undefined) {
230
- try {
231
- clearTimeout(intervalRandoms[key]);
232
- } catch (e) {}
233
- }
234
- intervalRandoms[key] = setTimeout(
235
- function () {
236
- doSetInterval(cb, timeout, key);
237
- if (state !== "Offline") {
238
- cb();
239
- }
240
- },
241
- _.random(timeout[0], timeout[1]),
242
- );
243
- } else {
244
- if (intervals[key] !== undefined) {
245
- try {
246
- clearInterval(intervals[key]);
247
- } catch (e) {}
248
- }
249
-
250
- intervals[key] = setInterval(function () {
251
- if (state !== "Offline") {
252
- cb();
253
- }
254
- }, timeout);
255
- }
256
-
257
- return key;
258
- }
259
-
260
- function doClearIntervals() {
261
- for (const key in intervals) {
262
- clearInterval(intervals[key]);
263
- delete intervals[key];
264
- }
265
- for (const key in intervalRandoms) {
266
- clearTimeout(intervalRandoms[key]);
267
- delete intervalRandoms[key];
268
- }
269
- }
270
-
271
- function doClearInterval(key) {
272
- try {
273
- clearInterval(intervals[key]);
274
- } catch (e) {}
275
- delete intervals[key];
276
-
277
- try {
278
- clearTimeout(intervalRandoms[key]);
279
- } catch (e) {}
280
- delete intervalRandoms[key];
281
- }
282
-
283
- function getAccountInfoName() {
284
- return [steamClient?.accountInfo?.name, steamClient?._logOnDetails?.account_name].filter(Boolean).join(" - ");
285
- }
286
-
287
- function getPersonaName() {
288
- return steamClient?.accountInfo?.name;
289
- }
290
-
291
- function log(...msg) {
292
- const now = moment().tz("Asia/Ho_Chi_Minh").format("DD/MM/YYYY HH:mm:ss");
293
- console.log(`[${now}] [${getAccountInfoName()}]`, ...msg);
294
- }
295
-
296
- async function getPersonas(steamIDs) {
297
- steamIDs = steamIDs.map((steamId) => (steamId instanceof SteamID ? steamId.getSteamID64() : steamId));
298
- const notCachesteamIDs = steamIDs.filter((id) => !PersonasCache.some((p) => p.id == id));
299
- const cachedPersonas = PersonasCache.filter((p) => steamIDs.includes(p.id));
300
-
301
- if (notCachesteamIDs.length) {
302
- let personas = null;
303
- try {
304
- personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
305
- } catch (e) {}
306
- if (!personas || !Object.keys(personas).length) {
307
- try {
308
- personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
309
- } catch (e) {}
310
- }
311
- if (!personas || !Object.keys(personas).length) {
312
- try {
313
- personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
314
- } catch (e) {}
315
- }
316
- if (personas && Object.keys(personas).length) {
317
- for (let sid64 in personas) {
318
- personas[sid64].id = sid64;
319
- personas[sid64].avatar_hash = Buffer.from(personas[sid64].avatar_hash).toString("hex");
320
- PersonasCache.push(personas[sid64]);
321
- cachedPersonas.push(personas[sid64]);
322
- }
323
- }
324
- }
325
-
326
- while (PersonasCache.length > 500) {
327
- PersonasCache.shift();
328
- }
329
- return cachedPersonas;
330
- }
331
-
332
- function sleep(ms) {
333
- return new Promise((resolve) => {
334
- setTimeout(resolve, ms);
335
- });
336
- }
337
-
338
- function getCookies() {
339
- return cookie || steamClient?.webSession?.cookies?.join?.(";");
340
- }
341
-
342
- async function getCookiesWait() {
343
- return (
344
- getCookies() ||
345
- new Promise((resolve) => {
346
- onEvent(
347
- "webSession",
348
- function (webSession) {
349
- resolve(webSession?.cookies);
350
- },
351
- true,
352
- 30000,
353
- );
354
- })
355
- );
356
- }
357
-
358
- async function gamePlay() {
359
- if ((Array.isArray(games) && games.length) || (games && (typeof games === "number" || typeof games === "string"))) {
360
- return gamesPlayed(games);
361
- }
362
-
363
- let ownedApps = [];
364
- for (let i = 0; i < 5; i++) {
365
- ownedApps = await getUserOwnedApps();
366
- if (ownedApps?.length) {
367
- break;
368
- }
369
- }
370
- if (!ownedApps?.length) {
371
- gamesPlayed(730);
372
- } else {
373
- ownedApps = ownedApps.map(({ appid }) => appid);
374
- ownedApps = _.shuffle(ownedApps);
375
- ownedApps.length = Math.min(ownedApps.length, MAX_GAME_PLAY - 1);
376
- _.remove(ownedApps, (app) => app == 730);
377
- gamesPlayed([...ownedApps, 730]);
378
- }
379
- }
380
-
381
- async function autoGamePlay() {
382
- await gamePlay();
383
- doSetInterval(gamePlay, [15 * 60000, 30 * 60000], "autoGamePlay");
384
- }
385
-
386
- async function offAutoGamePlay() {
387
- steamClient.gamesPlayed([]);
388
- doClearInterval("autoGamePlay");
389
- }
390
-
391
- async function updateAutoGamePlay() {
392
- if (isAutoPlay) {
393
- autoGamePlay();
394
- } else {
395
- offAutoGamePlay();
396
- }
397
- }
398
-
399
- /**
400
- * Get a list of lobbies (* = Unsure description could be wrong)
401
- * @param {Number} ver Game version we are searching for
402
- * @param {Boolean} apr Prime or not*
403
- * @param {Number} ark Rank multiplied by 10*
404
- * @param {Array.<Number>} grps *
405
- * @param {Number} launcher If we are using the China CSGO launcher or not*
406
- * @param {Number} game_type Game type, 8 Competitive, 10 Wingman
407
- * @returns {Promise.<Object>}
408
- */
409
- async function partySearch({ prime = false, game_type = "Competitive", rank = "Silver Elite", timeout = 5000 } = {}) {
410
- const players = await new Promise((resolve) => {
411
- steamClient.sendToGC(
412
- AppID,
413
- Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Search,
414
- {},
415
- protoEncode(Protos.csgo.CMsgGCCStrike15_v2_Party_Search, {
416
- ver: CSGO_VER,
417
- apr: prime ? 1 : 0,
418
- ark: parseInt(Object.keys(RANKS).find((k) => RANKS[k] === rank)) * 10,
419
- grps: [],
420
- launcher: 0,
421
- game_type: game_type === "Competitive" ? 8 : 10,
422
- }),
423
- );
424
- lastTimePartySearch = new Date().getTime();
425
- pushGCCallback("partySearch", resolve, timeout);
426
- });
427
- if (Array.isArray(players) && players.length) {
428
- const personas = await getPersonas(players.map((p) => p.steamId));
429
- for (const player of players) {
430
- const persona = personas.find((p) => p.id == player.steamId);
431
- if (persona) {
432
- player.player_name = persona.player_name;
433
- player.avatar_hash = persona.avatar_hash;
434
- }
435
- }
436
- }
437
- return players;
438
- }
439
-
440
- async function createLobby() {
441
- if (!steamClient.steamID) {
442
- return;
443
- }
444
-
445
- return new Promise((resolve) => {
446
- const timeout = setTimeout(function () {
447
- resolve();
448
- }, 30000);
449
-
450
- steamClient._send(
451
- {
452
- msg: Protos.csgo.EMsg.k_EMsgClientMMSCreateLobby,
453
- proto: {
454
- steamid: steamClient.steamID.getSteamID64(),
455
- routing_appid: 730,
456
- },
457
- },
458
- protoEncode(Protos.csgo.CMsgClientMMSCreateLobby, {
459
- app_id: 730,
460
- max_members: 1,
461
- lobby_type: 1,
462
- lobby_flags: 1,
463
- }),
464
- function (payload) {
465
- clearTimeout(timeout);
466
- const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload.toBuffer());
467
- const steam_id_lobby = result.steam_id_lobby.toString();
468
- currentLobby.lobbyID = steam_id_lobby;
469
- currentLobby.timestamp = new Date().getTime();
470
- resolve(steam_id_lobby);
471
- },
472
- );
473
- });
474
-
475
- // return await getHandlerResult(Protos.csgo.EMsg.k_EMsgClientMMSCreateLobbyResponse, function (payload) {
476
- // const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload.toBuffer())
477
- // return result.steam_id_lobby.toString()
478
- // })
479
-
480
- // steamClient.sendToGC(730, Protos.csgo.EMsg.k_EMsgClientMMSCreateLobby, {
481
- // steamid: steamClient.steamID,
482
- // routing_appid: 730,
483
- // }, protoEncode(Protos.csgo.CMsgClientMMSCreateLobby, {
484
- // app_id: 730,
485
- // max_members: 1,
486
- // lobby_type: 1,
487
- // lobby_flags: 1
488
- // }))
489
- }
490
-
491
- async function updateLobby(lobbyID) {
492
- if (!steamClient.steamID) {
493
- return;
494
- }
495
-
496
- return new Promise((resolve) => {
497
- const timeout = setTimeout(function () {
498
- resolve();
499
- }, 30000);
500
-
501
- steamClient._send(
502
- {
503
- msg: Protos.csgo.EMsg.k_EMsgClientMMSSetLobbyData,
504
- proto: {
505
- steamid: steamClient.steamID.getSteamID64(),
506
- routing_appid: 730,
507
- },
508
- },
509
- protoEncode(Protos.csgo.CMsgClientMMSSetLobbyData, {
510
- app_id: 730,
511
- steam_id_lobby: lobbyID,
512
- steam_id_member: "0",
513
- max_members: 10,
514
- lobby_type: 1,
515
- lobby_flags: 1,
516
- metadata: encode(
517
- {
518
- "game:ark": "0",
519
- // Country/Message
520
- "game:loc": "",
521
- "game:mapgroupname": "mg_de_mirage",
522
- "game:mode": "competitive",
523
- "game:prime": "1",
524
- "game:type": "classic",
525
- "members:numPlayers": "1",
526
- "options:action": "custommatch",
527
- "options:anytypemode": "0",
528
- "system:access": "private",
529
- "system:network": "LIVE",
530
- uids: [steamClient.steamID],
531
- },
532
- [0x00, 0x00],
533
- [0x08],
534
- { uids: encodeUids },
535
- ).toBuffer(),
536
- }),
537
- function (payload) {
538
- clearTimeout(timeout);
539
- const result = protoDecode(Protos.csgo.CMsgClientMMSSetLobbyDataResponse, payload.toBuffer());
540
- const steam_id_lobby = result.steam_id_lobby.toString();
541
- currentLobby.lobbyID = steam_id_lobby;
542
- currentLobby.timestamp = new Date().getTime();
543
- resolve(steam_id_lobby);
544
- },
545
- );
546
- });
547
-
548
- // return await getHandlerResult(Protos.csgo.EMsg.k_EMsgClientMMSSetLobbyDataResponse, function (payload) {
549
- // const result = protoDecode(Protos.csgo.CMsgClientMMSSetLobbyDataResponse, payload.toBuffer())
550
- // return result.steam_id_lobby.toString()
551
- // })
552
- }
553
-
554
- async function invite2Lobby(lobbyID, steamId) {
555
- if (!steamClient.steamID) {
556
- return;
557
- }
558
-
559
- steamClient._send(
560
- {
561
- msg: Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby,
562
- proto: {
563
- steamid: steamClient.steamID.getSteamID64(),
564
- routing_appid: 730,
565
- },
566
- },
567
- protoEncode(Protos.csgo.CMsgClientMMSInviteToLobby, {
568
- app_id: 730,
569
- steam_id_lobby: lobbyID,
570
- steam_id_user_invited: steamId,
571
- }),
572
- );
573
-
574
- // lobbyID = new SteamID(lobbyID).accountid;
575
-
576
- // Protos.csgo.EMsg.k_EMsgGCHInviteUserToLobby
577
- // Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby
578
- // steamClient.sendToGC(730, Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby, {}, protoEncode(Protos.csgo.CMsgClientMMSInviteToLobby, {
579
- // app_id: 730,
580
- // steam_id_lobby: lobbyID,
581
- // steam_id_user_invited: accountid,
582
- // }), function (...args) {
583
- // console.log("invite2Lobby response", args)
584
- // })
585
- }
586
-
587
- async function createThenInvite2Lobby(steamIds, onInvite) {
588
- if (!steamClient.steamID) {
589
- return;
590
- }
591
-
592
- if (!Array.isArray(steamIds)) {
593
- steamIds = [steamIds];
594
- }
595
-
596
- let lobbyID = null;
597
- if (currentLobby.lobbyID && currentLobby.timestamp > new Date().getTime() - 30000) {
598
- //30 seconds
599
- lobbyID = currentLobby.lobbyID;
600
- } else {
601
- lobbyID = await createLobby();
602
- lobbyID = await updateLobby(lobbyID);
603
- }
604
-
605
- for (const steamId of steamIds) {
606
- onInvite?.(lobbyID, steamId);
607
- await invite2Lobby(lobbyID, steamId);
608
- }
609
-
610
- return lobbyID;
611
- }
612
-
613
- async function getLobbyData(lobbyID) {
614
- if (!steamClient.steamID) {
615
- return;
616
- }
617
-
618
- return new Promise((resolve) => {
619
- const timeout = setTimeout(function () {
620
- resolve();
621
- }, 30000);
622
-
623
- steamClient._send(
624
- {
625
- msg: Protos.csgo.EMsg.k_EMsgClientMMSGetLobbyData,
626
- proto: {
627
- steamid: steamClient.steamID.getSteamID64(),
628
- routing_appid: 730,
629
- },
630
- },
631
- protoEncode(Protos.csgo.CMsgClientMMSGetLobbyData, {
632
- app_id: 730,
633
- steam_id_lobby: lobbyID.toString(),
634
- }),
635
- function (payload) {
636
- clearTimeout(timeout);
637
- const result = protoDecode(Protos.csgo.CMsgClientMMSLobbyData, payload.toBuffer());
638
- result.steam_id_lobby = result.steam_id_lobby.toString();
639
- resolve(result);
640
- },
641
- );
642
- });
643
- }
644
-
645
- async function joinLobby(lobbyID) {
646
- log("joinLobby", lobbyID); //SteamID.fromIndividualAccountID(lobbyId).accountid
647
-
648
- steamClient._send(
649
- {
650
- msg: Protos.csgo.EMsg.k_EMsgClientMMSJoinLobby,
651
- proto: {
652
- steamid: steamClient.steamID.getSteamID64(),
653
- routing_appid: 730,
654
- },
655
- }, //CMsgClientMMSUserJoinedLobby CMsgClientMMSJoinLobby
656
- protoEncode(Protos.csgo.CMsgClientMMSJoinLobby, {
657
- app_id: 730,
658
- steam_id_lobby: lobbyID,
659
- persona_name: steamClient.accountInfo.name,
660
- }),
661
- function (payload) {
662
- const result = protoDecode(Protos.csgo.CMsgClientMMSJoinLobbyResponse, payload.toBuffer());
663
- result.steam_id_lobby = result.steam_id_lobby.toString();
664
- result.steam_id_owner = result.steam_id_owner.toString();
665
- console.log(result);
666
- const resultExample = {
667
- members: [],
668
- app_id: 730,
669
- steam_id_lobby: "3641224920",
670
- chat_room_enter_response: 2,
671
- max_members: 0,
672
- lobby_type: 0,
673
- lobby_flags: 0,
674
- steam_id_owner: "0",
675
- metadata: null, //Buffer
676
- };
677
- },
678
- );
679
- }
680
-
681
- async function sendHello() {
682
- steamClient.sendToGC(AppID, Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello, {}, Buffer.alloc(0));
683
- // steamClient.sendToGC(AppID, Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientHello, {}, Buffer.alloc(0));
684
-
685
- steamClient.sendToGC(
686
- AppID,
687
- Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientHello,
688
- {},
689
- protoEncode(Protos.csgo.CMsgClientHello, {
690
- version: 2000258, //get from https://github.com/SteamDatabase/GameTracking-CS2/commits
691
- client_session_need: 0,
692
- client_launcher: 0,
693
- steam_launcher: 0,
694
- }),
695
- );
696
- }
697
-
698
- async function requestCoPlays() {
699
- return new Promise((resolve) => {
700
- steamClient.sendToGC(AppID, Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Account_RequestCoPlays, {}, Buffer.alloc(0));
701
- pushGCCallback("RequestCoPlays", resolve, 30000);
702
- });
703
- }
704
-
705
- function bindEvent() {
706
- const _events = {
707
- async disconnected(eresult, msg) {
708
- state = "Offline";
709
- log("disconnected", eresult, msg);
710
-
711
- callEvent(events.disconnected, { eresult, msg });
712
-
713
- if (["ServiceUnavailable", "NoConnection"].includes(msg) && autoReconnect && !isLogOff) {
714
- async function relogin(retry) {
715
- if (isLogOff) {
716
- console.error("Cannot relogin (logoff)");
717
- return false;
718
- } else if (retry <= 0) {
719
- console.error("Cannot relogin");
720
- return false;
721
- } else {
722
- const isSuccess = await login(true);
723
- if (isSuccess) {
724
- const loggedOnResponse = await new Promise((resolve) => {
725
- onEvent("loggedOn", resolve, true, 180000);
726
- });
727
- if (loggedOnResponse) {
728
- console.log("Relogin success");
729
- return true;
730
- } else {
731
- const isLogOff = await new Promise((resolve, reject) => {
732
- logOffEvent = resolve;
733
- setTimeout(resolve, 120000);
734
- });
735
- logOffEvent = null;
736
- if (isLogOff === true) {
737
- return false;
738
- }
739
- return await relogin(retry - 1);
740
- }
741
- } else {
742
- const isLogOff = await new Promise((resolve, reject) => {
743
- logOffEvent = resolve;
744
- setTimeout(resolve, 120000);
745
- });
746
- logOffEvent = null;
747
- if (isLogOff === true) {
748
- return false;
749
- }
750
- return await relogin(retry - 1);
751
- }
752
- }
753
- }
754
-
755
- const isLogOff = await new Promise((resolve, reject) => {
756
- logOffEvent = resolve;
757
- setTimeout(resolve, 60000);
758
- });
759
- logOffEvent = null;
760
- if (isLogOff === true) {
761
- offAllEvent();
762
- doClearIntervals();
763
- } else {
764
- const isSuccess = await relogin(50);
765
- if (!isSuccess) {
766
- offAllEvent();
767
- doClearIntervals();
768
- }
769
- }
770
- } else {
771
- offAllEvent();
772
- doClearIntervals();
773
- }
774
- },
775
- async error(e) {
776
- let errorStr = "";
777
- switch (e.eresult) {
778
- case 5:
779
- errorStr = "Invalid Password";
780
- break;
781
- case 6:
782
- case 34:
783
- errorStr = "Logged In Elsewhere";
784
- break;
785
- case 84:
786
- errorStr = "Rate Limit Exceeded";
787
- break;
788
- case 65:
789
- errorStr = "steam guard is invalid";
790
- break;
791
- default:
792
- errorStr = `Unknown: ${e.eresult}`;
793
- break;
794
- }
795
- log(`error [isLogOff: ${isLogOff}]`, e?.message);
796
- doClearIntervals();
797
- callEvent(events.error, { eresult: e.eresult, msg: e.message, error: errorStr });
798
- },
799
- async webSession(sessionID, cookies) {
800
- const webSession = { sessionID, cookies };
801
- steamClient.webSession = webSession;
802
- callEvent(events.webSession, webSession);
803
- },
804
- async receivedFromGC(appid, msgType, payload) {
805
- const key = getECsgoGCMsgKey(msgType);
806
- switch (msgType) {
807
- case Protos.csgo.EMsg.k_EMsgClientChatInvite: {
808
- log(payload);
809
- break;
810
- }
811
- case Protos.csgo.ECsgoGCMsg.k_EMsgClientMMSJoinLobbyResponse: {
812
- const msg = protoDecode(Protos.csgo.CMsgClientMMSJoinLobbyResponse, payload);
813
- log(msg);
814
- break;
815
- }
816
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Invite: {
817
- const msg = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Party_Invite, payload);
818
- const sid64 = SteamID.fromIndividualAccountID(msg.accountid).getSteamID64();
819
- if (events.partyInvite?.length) {
820
- const personas = await getPersonas([sid64]);
821
- const player_name = personas.find((p) => p.id == sid64)?.player_name;
822
- if (player_name === undefined) {
823
- log(sid64, personas);
824
- }
825
- callEvent(events.partyInvite, { player_name, steamId: sid64, lobbyId: msg.lobbyid });
826
- }
827
- // log(player_name, `https://steamcommunity.com/profiles/${sid64}`);
828
- // joinLobby(msg.lobbyid, msg.accountid)
829
- break;
830
- }
831
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Account_RequestCoPlays: {
832
- const msg = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Account_RequestCoPlays, payload);
833
- const personas = msg.players.map((p) => SteamID.fromIndividualAccountID(p.accountid));
834
- callGCCallback("RequestCoPlays", personas);
835
- break;
836
- }
837
- case Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientWelcome: {
838
- prime = false;
839
- const CMsgClientWelcome = protoDecode(Protos.csgo.CMsgClientWelcome, payload);
840
- const obj = {};
841
- for (const outofdate_cache of CMsgClientWelcome.outofdate_subscribed_caches) {
842
- for (const cache_object of outofdate_cache.objects) {
843
- for (const object_data of cache_object.object_data) {
844
- switch (cache_object.type_id) {
845
- case 1: {
846
- const result = protoDecode(Protos.csgo.CSOEconItem, object_data);
847
- result.id = result.id.toNumber();
848
- break;
849
- }
850
- case 2: {
851
- const result = protoDecode(Protos.csgo.CSOPersonaDataPublic, object_data);
852
- obj.PersonaDataPublic = result;
853
- const example = {
854
- player_level: 4, //CSGO_Profile_Rank
855
- commendation: {
856
- cmd_friendly: 149,
857
- cmd_teaching: 108,
858
- cmd_leader: 115,
859
- },
860
- elevated_state: true,
861
- };
862
- break;
863
- }
864
- case 5: {
865
- const result = protoDecode(Protos.csgo.CSOItemRecipe, object_data);
866
- break;
867
- }
868
- case 7: {
869
- const CSOEconGameAccountClient = protoDecode(Protos.csgo.CSOEconGameAccountClient, object_data);
870
- const CSOEconGameAccountClientExample = {
871
- additional_backpack_slots: 0,
872
- bonus_xp_timestamp_refresh: 1688518800, //Wednesday 1:00:00 AM every week
873
- bonus_xp_usedflags: 19,
874
- elevated_state: 5,
875
- elevated_timestamp: 5,
876
- }; //1688518800
877
- if ((CSOEconGameAccountClient.bonus_xp_usedflags & 16) != 0) {
878
- // EXPBonusFlag::PrestigeEarned
879
- prime = true;
880
- CSOEconGameAccountClient.prime = true;
881
- }
882
- if (CSOEconGameAccountClient.elevated_state === 5) {
883
- // bought prime
884
- prime = true;
885
- CSOEconGameAccountClient.prime = true;
886
- }
887
- obj.GameAccountClient = CSOEconGameAccountClient;
888
- break;
889
- }
890
-
891
- case 35: {
892
- // const result =protoDecode(Protos.csgo.CSOSelectedItemPreset, object_data);
893
- break;
894
- }
895
-
896
- case 36: {
897
- // const result =protoDecode(Protos.csgo.CSOEconItemPresetInstance, object_data);
898
- break;
899
- }
900
- case 38: {
901
- const result = protoDecode(Protos.csgo.CSOEconItemDropRateBonus, object_data);
902
- break;
903
- }
904
- case 39: {
905
- const result = protoDecode(Protos.csgo.CSOEconItemLeagueViewPass, object_data);
906
- break;
907
- }
908
- case 40: {
909
- const result = protoDecode(Protos.csgo.CSOEconItemEventTicket, object_data);
910
- break;
911
- }
912
- case 41: {
913
- const result = protoDecode(Protos.csgo.CSOAccountSeasonalOperation, object_data);
914
- break;
915
- }
916
- case 42: {
917
- // const result =protoDecode(Protos.csgo.CSOEconItemTournamentPassport, object_data);
918
- break;
919
- }
920
- case 43: {
921
- const result = protoDecode(Protos.csgo.CSOEconDefaultEquippedDefinitionInstanceClient, object_data);
922
- const example = {
923
- account_id: 1080136620,
924
- item_definition: 61,
925
- class_id: 3,
926
- slot_id: 2,
927
- };
928
- break;
929
- }
930
- case 45: {
931
- const result = protoDecode(Protos.csgo.CSOEconCoupon, object_data);
932
- break;
933
- }
934
- case 46: {
935
- const result = protoDecode(Protos.csgo.CSOQuestProgress, object_data);
936
- break;
937
- }
938
- case 4: {
939
- const result = protoDecode(Protos.csgo.CSOAccountItemPersonalStore, object_data);
940
- result.generation_time = result.generation_time * 1000;
941
- if (Array.isArray(result.items)) {
942
- result.items = result.items.map((item) => item.toNumber());
943
- }
944
- obj.personalStore = result;
945
- break;
946
- }
947
-
948
- default: {
949
- log("cache_object.type_id", cache_object.type_id);
950
- }
951
- }
952
- }
953
- }
954
- }
955
- callEvent(events.csgoOnline, obj);
956
-
957
- if (isPartyRegister) {
958
- partyRegister();
959
- doSetInterval(
960
- function () {
961
- partyRegister();
962
- },
963
- [60000, 120000],
964
- "autoPartyRegister",
965
- );
966
- }
967
- break;
968
- }
969
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingGC2ClientUpdate: {
970
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchmakingGC2ClientUpdate, payload);
971
- break;
972
- }
973
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GC2ClientGlobalStats: {
974
- const result = protoDecode(Protos.csgo.CMsgClientUGSGetGlobalStatsResponse, payload);
975
- break;
976
- }
977
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientReportPlayer: {
978
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientReportPlayer, payload);
979
- break;
980
- }
981
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GC2ClientTextMsg: {
982
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_GC2ClientTextMsg, payload);
983
- break;
984
- }
985
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello: {
986
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchmakingGC2ClientHello, payload);
987
- const example = {
988
- my_current_event_teams: [],
989
- my_current_event_stages: [],
990
- rankings: [],
991
- account_id: 1080136620,
992
- ongoingmatch: null,
993
- global_stats: {
994
- search_statistics: [
995
- {
996
- game_type: 520,
997
- search_time_avg: 0,
998
- players_searching: 5141,
999
- },
1000
- {
1001
- game_type: 32776,
1002
- search_time_avg: 0,
1003
- players_searching: 6561,
1004
- },
1005
- ],
1006
- players_online: 617207,
1007
- servers_online: 230638,
1008
- players_searching: 13550,
1009
- servers_available: 126352,
1010
- ongoing_matches: 23264,
1011
- search_time_avg: 95993,
1012
- main_post_url: "*XA=https://blast.tv/live*XT=https://www.twitch.tv/blastpremier*XB=https://live.bilibili.com/35*XG=playcast://https://gotv.blast.tv/major-a*T=SGTAB*L=2@https://steamcommunity.com/broadcast/watch/76561199492362089",
1013
- required_appid_version: 13879,
1014
- pricesheet_version: 1688084844,
1015
- twitch_streams_version: 2,
1016
- active_tournament_eventid: 21,
1017
- active_survey_id: 0,
1018
- rtime32_cur: 0,
1019
- rtime32_event_start: 0,
1020
- },
1021
- penalty_seconds: 0,
1022
- penalty_reason: 0,
1023
- vac_banned: 0,
1024
- ranking: {
1025
- account_id: 1080136620,
1026
- rank_id: 10,
1027
- wins: 209,
1028
- rank_change: 0,
1029
- rank_type_id: 6,
1030
- tv_control: 0,
1031
- },
1032
- commendation: {
1033
- cmd_friendly: 149,
1034
- cmd_teaching: 108,
1035
- cmd_leader: 115,
1036
- },
1037
- medals: null,
1038
- my_current_event: null,
1039
- my_current_team: null,
1040
- survey_vote: 0,
1041
- activity: null,
1042
- player_level: 4,
1043
- player_cur_xp: 327684501,
1044
- player_xp_bonus_flags: 0,
1045
- };
1046
- if (result?.global_stats?.required_appid_version && (!CSGO_VER || result.global_stats.required_appid_version > CSGO_VER)) {
1047
- CSGO_VER = result.global_stats.required_appid_version;
1048
- }
1049
- callEvent(events.csgoClientHello, result);
1050
- break;
1051
- }
1052
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientReportResponse: {
1053
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientReportResponse, payload);
1054
- break;
1055
- }
1056
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientCommendPlayerQueryResponse: {
1057
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientCommendPlayer, payload);
1058
- break;
1059
- }
1060
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_PlayerOverwatchCaseAssignment: {
1061
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_PlayerOverwatchCaseAssignment, payload);
1062
- break;
1063
- }
1064
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchList: {
1065
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchList, payload);
1066
- break;
1067
- }
1068
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GetEventFavorites_Response: {
1069
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_GetEventFavorites_Response, payload);
1070
- break;
1071
- }
1072
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_StartAgreementSessionInGame: {
1073
- break;
1074
- }
1075
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_ClientDeepStats: {
1076
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_ClientDeepStats, payload);
1077
- break;
1078
- }
1079
- case Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientConnectionStatus: {
1080
- const result = protoDecode(Protos.csgo.CMsgConnectionStatus, payload);
1081
- break;
1082
- }
1083
- case Protos.csgo.EGCItemMsg.k_EMsgGCStoreGetUserDataResponse: {
1084
- const result = protoDecode(Protos.csgo.CMsgStoreGetUserDataResponse, payload);
1085
- break;
1086
- }
1087
- case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseFinalizeResponse: {
1088
- const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseFinalizeResponse, payload);
1089
- break;
1090
- }
1091
- case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseCancelResponse: {
1092
- const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseCancelResponse, payload);
1093
- break;
1094
- }
1095
- case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseInitResponse: {
1096
- const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseInitResponse, payload);
1097
- break;
1098
- }
1099
- case Protos.csgo.EMsg.k_EMsgClientMMSCreateLobbyResponse: {
1100
- const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload);
1101
- console.log("k_EMsgClientMMSCreateLobbyResponse", result);
1102
- break;
1103
- }
1104
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientGCRankUpdate: {
1105
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientGCRankUpdate, payload);
1106
- break;
1107
- }
1108
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Search: {
1109
- const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Party_SearchResults, payload);
1110
- const entries = _.uniqBy(result.entries, "id");
1111
- //{
1112
- // id: 144900402,
1113
- // grp: 0,
1114
- // game_type: 8,
1115
- // apr: 1,
1116
- // ark: 17,
1117
- // loc: 20041,
1118
- // accountid: 0
1119
- // }
1120
-
1121
- //{
1122
- // id: "76561199265943339",
1123
- // rich_presence: [],
1124
- // persona_state: null,
1125
- // game_played_app_id: null,
1126
- // game_server_ip: null,
1127
- // game_server_port: null,
1128
- // persona_state_flags: null,
1129
- // online_session_instances: null,
1130
- // persona_set_by_user: null,
1131
- // player_name: "杀人不见血",
1132
- // query_port: null,
1133
- // steamid_source: null,
1134
- // avatar_hash: "33994e26f1fe7e2093f8c7dee66c1ac91531050d",
1135
- // last_logoff: null,
1136
- // last_logon: null,
1137
- // last_seen_online: null,
1138
- // clan_rank: null,
1139
- // game_name: null,
1140
- // gameid: null,
1141
- // game_data_blob: null,
1142
- // clan_data: null,
1143
- // clan_tag: null,
1144
- // broadcast_id: null,
1145
- // game_lobby_id: null,
1146
- // watching_broadcast_accountid: null,
1147
- // watching_broadcast_appid: null,
1148
- // watching_broadcast_viewers: null,
1149
- // watching_broadcast_title: null,
1150
- // is_community_banned: null,
1151
- // player_name_pending_review: null,
1152
- // avatar_pending_review: null,
1153
- // avatar_url_icon: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d.jpg",
1154
- // avatar_url_medium: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d_medium.jpg",
1155
- // avatar_url_full: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d_full.jpg"
1156
- // }
1157
-
1158
- const players = [];
1159
- for (const player of entries) {
1160
- try {
1161
- const prime = player.apr === 1 ? "PRIME" : "NON-PRIME";
1162
- const loc = LOCS[player.loc] || player.loc;
1163
- const steamId = SteamID.fromIndividualAccountID(player.id).getSteamID64();
1164
- const friendCode = FriendCode.encode(steamId);
1165
-
1166
- // if ((LOCS[player.loc] == 'VN' || !LOCS[player.loc])) {
1167
- players.push({
1168
- prime,
1169
- rank: RANKS[player.ark] !== undefined ? RANKS[player.ark] : player.ark,
1170
- loc,
1171
- steamId,
1172
- friendCode,
1173
- });
1174
- // }
1175
- } catch (e) {}
1176
- }
1177
-
1178
- callGCCallback("partySearch", players);
1179
- break;
1180
- }
1181
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_PlayersProfile: {
1182
- let data = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_PlayersProfile, payload)?.account_profiles;
1183
- const dataExample = [
1184
- {
1185
- my_current_event_teams: [],
1186
- my_current_event_stages: [],
1187
- rankings: [
1188
- {
1189
- account_id: 1225887169,
1190
- rank_id: 0,
1191
- wins: 6,
1192
- rank_change: 0,
1193
- rank_type_id: 7,
1194
- tv_control: 0,
1195
- },
1196
- {
1197
- account_id: 1225887169,
1198
- rank_id: 0,
1199
- wins: 0,
1200
- rank_change: 0,
1201
- rank_type_id: 10,
1202
- tv_control: 0,
1203
- },
1204
- ],
1205
- account_id: 1225887169,
1206
- ongoingmatch: null,
1207
- global_stats: null,
1208
- penalty_seconds: 0,
1209
- penalty_reason: 0,
1210
- vac_banned: 0,
1211
- ranking: {
1212
- account_id: 1225887169,
1213
- rank_id: 8,
1214
- wins: 469,
1215
- rank_change: 0,
1216
- rank_type_id: 6,
1217
- tv_control: 0,
1218
- },
1219
- commendation: {
1220
- cmd_friendly: 51,
1221
- cmd_teaching: 40,
1222
- cmd_leader: 40,
1223
- },
1224
- medals: {
1225
- display_items_defidx: [4819, 4737],
1226
- featured_display_item_defidx: 4819,
1227
- },
1228
- my_current_event: null,
1229
- my_current_team: null,
1230
- survey_vote: 0,
1231
- activity: null,
1232
- player_level: 32,
1233
- player_cur_xp: 327682846,
1234
- player_xp_bonus_flags: 0,
1235
- },
1236
- ];
1237
-
1238
- const player = data?.[0];
1239
- if (player) {
1240
- player.prime = !!(player.ranking?.account_id || player.player_level || player.player_cur_xp);
1241
- player.steamId = SteamID.fromIndividualAccountID(player.account_id).getSteamID64();
1242
- callGCCallback(`PlayersProfile_${player.account_id}`, player);
1243
- }
1244
- callEvent(events.playersProfile, player);
1245
- break;
1246
- }
1247
- case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientLogonFatalError: {
1248
- const data = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientLogonFatalError, payload);
1249
- const dataExample = {
1250
- errorcode: 4,
1251
- message: "",
1252
- country: "VN",
1253
- };
1254
- callEvent(events.fatalError, data);
1255
- break;
1256
- }
1257
- default:
1258
- log(`receivedFromGC ${msgType} ${key}`);
1259
- const results = Object.values(Protos.csgo)
1260
- .map(function (p) {
1261
- try {
1262
- return protoDecode(p, payload);
1263
- } catch (e) {}
1264
- })
1265
- .filter(function (result) {
1266
- return result && Object.keys(result).length;
1267
- });
1268
- log(key, results);
1269
- }
1270
- },
1271
- async loggedOn(loggedOnResponse) {
1272
- callEvent(events.loggedOn, loggedOnResponse);
1273
- updateInvisible();
1274
- updateAutoRequestFreeLicense();
1275
- updateAutoGamePlay();
1276
- },
1277
- async user(steamId, data) {
1278
- callEvent(events.user, { steamId: steamId.getSteamID64(), data });
1279
- const dataExample = {
1280
- rich_presence: [
1281
- {
1282
- key: "status",
1283
- value: "Competitive Mirage [ 3 : 6 ]",
1284
- },
1285
- {
1286
- key: "version",
1287
- value: "13875",
1288
- },
1289
- {
1290
- key: "game:state",
1291
- value: "game",
1292
- },
1293
- {
1294
- key: "steam_display",
1295
- value: "#display_GameKnownMapScore",
1296
- },
1297
- {
1298
- key: "game:mode",
1299
- value: "competitive",
1300
- },
1301
- {
1302
- key: "game:mapgroupname",
1303
- value: "mg_de_mirage",
1304
- },
1305
- {
1306
- key: "game:map",
1307
- value: "de_mirage",
1308
- },
1309
- {
1310
- key: "game:server",
1311
- value: "kv",
1312
- },
1313
- {
1314
- key: "watch",
1315
- value: "1",
1316
- },
1317
- {
1318
- key: "steam_player_group",
1319
- value: "2134948645",
1320
- },
1321
- {
1322
- key: "game:score",
1323
- value: "[ 3 : 6 ]",
1324
- },
1325
- ],
1326
- friendid: "76561199405834425",
1327
- persona_state: 1,
1328
- game_played_app_id: 730,
1329
- game_server_ip: null,
1330
- game_server_port: null,
1331
- persona_state_flags: 1,
1332
- online_session_instances: 1,
1333
- persona_set_by_user: null,
1334
- player_name: "quỷ súng",
1335
- query_port: null,
1336
- steamid_source: "0",
1337
- avatar_hash: {
1338
- type: "Buffer",
1339
- data: [23, 163, 216, 209, 236, 179, 73, 228, 225, 30, 48, 190, 192, 170, 177, 246, 139, 71, 122, 205],
1340
- },
1341
- last_logoff: 1683950268,
1342
- last_logon: 1683950281,
1343
- last_seen_online: 1683950268,
1344
- clan_rank: null,
1345
- game_name: "",
1346
- gameid: "730",
1347
- game_data_blob: {
1348
- type: "Buffer",
1349
- data: [],
1350
- },
1351
- clan_data: null,
1352
- clan_tag: null,
1353
- broadcast_id: "0",
1354
- game_lobby_id: "0",
1355
- watching_broadcast_accountid: null,
1356
- watching_broadcast_appid: null,
1357
- watching_broadcast_viewers: null,
1358
- watching_broadcast_title: null,
1359
- is_community_banned: null,
1360
- player_name_pending_review: null,
1361
- avatar_pending_review: null,
1362
- };
1363
- },
1364
- async playingState(playing_blocked, playing_app) {
1365
- playingBlocked = playing_blocked;
1366
- if (playing_app === 0) {
1367
- playing_app = null;
1368
- }
1369
- if (playing_blocked) {
1370
- //true, false
1371
- console.log("Playing else where");
1372
- }
1373
- log("playingState", playing_blocked, playing_app);
1374
- callEvent(events.playingState, { playing_blocked, playing_app });
1375
- },
1376
- async friendRelationship(sid, relationship, previousRelationship) {
1377
- callEvent(events.friendRelationship, {
1378
- steamId: sid.getSteamID64(),
1379
- relationship,
1380
- previousRelationship,
1381
- });
1382
- switch (relationship) {
1383
- case EFriendRelationship.None: {
1384
- //we got unfriended.
1385
- break;
1386
- }
1387
- case EFriendRelationship.RequestRecipient: {
1388
- //we got invited as a friend
1389
- break;
1390
- }
1391
- case EFriendRelationship.Friend: {
1392
- //we got added as a friend
1393
- break;
1394
- }
1395
- }
1396
- },
1397
- async tradeOffers(count) {
1398
- callEvent(events.tradeOffers, count);
1399
- },
1400
- async offlineMessages(count, friends) {
1401
- callEvent(events.offlineMessages, { count, steamIdList: friends });
1402
- },
1403
- async tradeRequest(steamID, respond) {
1404
- if (autoAcceptTradeRequest) {
1405
- log(`Incoming trade request from ${steamID.getSteam3RenderedID()}, accepting`);
1406
- respond(true);
1407
- } else {
1408
- log(`Incoming trade request from ${steamID.getSteam3RenderedID()}, wating`);
1409
- }
1410
- },
1411
- async friendsList() {
1412
- callEvent(events.friendsList, getFriendList());
1413
- },
1414
- async gifts(gid, packageid, TimeCreated, TimeExpiration, TimeSent, TimeAcked, TimeRedeemed, RecipientAddress, SenderAddress, SenderName) {
1415
- callEvent(events.gifts, {
1416
- gid,
1417
- packageid,
1418
- TimeCreated,
1419
- TimeExpiration,
1420
- TimeSent,
1421
- TimeAcked,
1422
- TimeRedeemed,
1423
- RecipientAddress,
1424
- SenderAddress,
1425
- SenderName,
1426
- });
1427
- },
1428
- async emailInfo(address, validated) {
1429
- callEvent(events.emailInfo, { address, validated });
1430
- },
1431
- async appLaunched() {
1432
- setTimeout(function () {
1433
- state = getPlayingAppIds().length ? "InGame" : isInvisible ? "Invisible" : "Online";
1434
- }, 1000);
1435
- },
1436
- async appQuit() {
1437
- setTimeout(function () {
1438
- state = getPlayingAppIds().length ? "InGame" : isInvisible ? "Invisible" : "Online";
1439
- }, 1000);
1440
- },
1441
- async accountLimitations(bis_limited_account, bis_community_banned, bis_locked_account, bis_limited_account_allowed_to_invite_friends) {
1442
- callEvent(events.accountLimitations, {
1443
- limited: bis_limited_account,
1444
- communityBanned: bis_community_banned,
1445
- locked: bis_locked_account,
1446
- canInviteFriends: bis_limited_account_allowed_to_invite_friends,
1447
- });
1448
- },
1449
- };
1450
-
1451
- const _chatEvents = {
1452
- async friendMessage(data) {
1453
- if (!data) return;
1454
- data.message_no_bbcode = data.message_no_bbcode?.replaceAll("ː", ":");
1455
- data.message = data.message?.replaceAll("ː", ":");
1456
- const example = {
1457
- steamid_friend: {
1458
- universe: 1,
1459
- type: 1,
1460
- instance: 1,
1461
- accountid: 1080136620,
1462
- },
1463
- chat_entry_type: 1,
1464
- from_limited_account: false,
1465
- message: "xxx",
1466
- ordinal: 0,
1467
- local_echo: false,
1468
- message_no_bbcode: "xxx",
1469
- low_priority: false,
1470
- server_timestamp: "2023-05-14T09:26:25.000Z",
1471
- message_bbcode_parsed: ["xxx"],
1472
- };
1473
- const timestamp = new Date(data.server_timestamp).getTime();
1474
- const steamId = data.steamid_friend.getSteamID64();
1475
- const invite = ["Invited you to play a game!", "Đã mời bạn chơi một trò chơi!"].includes(data.message_no_bbcode || data.message);
1476
- const emotion = (data.message_no_bbcode || "").split(" ").find((m) => m.startsWith(":") && m.endsWith(":"));
1477
-
1478
- callEvent(events.friendMessage, {
1479
- ...data,
1480
- message: data.message_no_bbcode,
1481
- invite,
1482
- steamId,
1483
- timestamp,
1484
- emotion,
1485
- });
1486
- },
1487
- async friendTyping(steamId, message) {
1488
- callEvent(events.friendTyping, {
1489
- steamId,
1490
- message,
1491
- });
1492
- },
1493
- };
1494
-
1495
- // steamClient.on('lobbyInvite', (inviterID, lobbyID ) => {
1496
- // joinLobby(lobbyID)
1497
- // })
1498
-
1499
- // steamClient.on('debug', (msg) => {
1500
- // if (!["ClientPersonaState","ClientClanState"].some(c => msg.includes(c))) {
1501
- // if(msg.startsWith("Received")){
1502
- // console.log(`------- ${msg}`)
1503
- // } else {
1504
- // console.log(msg)
1505
- // }
1506
- // }
1507
- // })
1508
-
1509
- function getECsgoGCMsgKey(_key) {
1510
- for (let key in Protos.csgo.ECsgoGCMsg) {
1511
- if (Protos.csgo.ECsgoGCMsg[key] == _key) {
1512
- return key;
1513
- }
1514
- }
1515
- for (let key in Protos.csgo.EGCBaseClientMsg) {
1516
- if (Protos.csgo.EGCBaseClientMsg[key] == _key) {
1517
- return key;
1518
- }
1519
- }
1520
- for (let key in Protos.csgo.EMsg) {
1521
- if (Protos.csgo.EMsg[key] == _key) {
1522
- return key;
1523
- }
1524
- }
1525
- for (let key in Protos.csgo.EGCItemMsg) {
1526
- if (Protos.csgo.EGCItemMsg[key] == _key) {
1527
- return key;
1528
- }
1529
- }
1530
- }
1531
-
1532
- for (const [name, _event] of Object.entries(_events)) {
1533
- steamClient.on(name, _event);
1534
- }
1535
-
1536
- for (const [name, _event] of Object.entries(_chatEvents)) {
1537
- steamClient.chat.on(name, _event);
1538
- }
1539
- }
1540
-
1541
- function getHandlerResult(msg, handler) {
1542
- const timeout = { current: null };
1543
- return new Promise((resolve) => {
1544
- function myhandler(...args) {
1545
- timeout.current && clearTimeout(timeout.current);
1546
- removeHandler();
1547
- resolve(handler?.(...args));
1548
- }
1549
-
1550
- function removeHandler() {
1551
- if (Array.isArray(steamClient._handlerManager._handlers[msg])) {
1552
- const index = steamClient._handlerManager._handlers[msg].findIndex((_handler) => _handler === myhandler);
1553
- if (index > -1) {
1554
- steamClient._handlerManager._handlers[msg].splice(index, 1);
1555
- }
1556
- }
1557
- }
1558
-
1559
- timeout.current = setTimeout(function () {
1560
- removeHandler();
1561
- resolve();
1562
- }, 60000);
1563
- steamClient._handlerManager.add(msg, myhandler);
1564
- });
1565
- }
1566
-
1567
- function getFriendList() {
1568
- return Object.keys(steamClient.myFriends).filter((steamId) => steamClient.myFriends[steamId] === NodeSteamUser.EFriendRelationship.Friend);
1569
- }
1570
-
1571
- function sendFriendTyping(steamId, callback) {
1572
- steamClient.chat.sendFriendTyping(steamId, callback);
1573
- }
1574
-
1575
- /*
1576
- * usually take 400 -> 800 miliseconds
1577
- * */
1578
- function getPlayersProfile(steamId) {
1579
- const accountid = new SteamID(steamId).accountid;
1580
- steamClient.sendToGC(
1581
- 730,
1582
- Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientRequestPlayersProfile,
1583
- {},
1584
- protoEncode(Protos.csgo.CMsgGCCStrike15_v2_ClientRequestPlayersProfile, {
1585
- account_id: accountid, // account_id: new SteamID('76561199184696945').accountid,
1586
- request_level: 32,
1587
- }),
1588
- );
1589
- return new Promise((resolve) => {
1590
- pushGCCallback(`PlayersProfile_${accountid}`, resolve, 2000);
1591
- });
1592
- }
1593
-
1594
- async function checkPlayerPrimeStatus(steamId) {
1595
- const profile = await getPlayersProfile(steamId);
1596
- if (!profile) return false;
1597
-
1598
- if (profile.ranking?.account_id) {
1599
- return true;
1600
- }
1601
-
1602
- if (profile.player_level || profile.player_cur_xp) {
1603
- return true;
1604
- }
1605
- return false;
1606
- }
1607
-
1608
- async function _getStoreSteamPoweredResponse(cookie) {
1609
- let response = null;
1610
- for (let i = 0; i < 50; i++) {
1611
- if (!response) {
1612
- try {
1613
- response = await axios.request({
1614
- url: "https://store.steampowered.com/",
1615
- headers: {
1616
- cookie,
1617
- accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.75",
1618
- },
1619
- });
1620
- } catch (e) {
1621
- await sleep(1000);
1622
- }
1623
- }
1624
- }
1625
- return response;
1626
- }
1627
-
1628
- async function getNewCookie(cookie) {
1629
- if (!cookie) {
1630
- return;
1631
- }
1632
- let response = await _getStoreSteamPoweredResponse(cookie);
1633
- if (!response) {
1634
- return;
1635
- }
1636
- while (Array.isArray(response?.headers?.["set-cookie"])) {
1637
- console.log(cookie);
1638
- const cookieObj = cookie.split(";").reduce(function (accumulator, currentValue) {
1639
- accumulator[currentValue.trim().split("=")[0].trim()] = currentValue.trim().split("=")[1].trim();
1640
- return accumulator;
1641
- }, {});
1642
- for (const mcookie of response.headers["set-cookie"]) {
1643
- const name = mcookie.split("=")[0].trim();
1644
- const value = mcookie.split("=")[1].split(";")[0].trim();
1645
- cookieObj[name] = value;
1646
- }
1647
- cookie = Object.keys(cookieObj)
1648
- .map((name) => `${name}=${cookieObj[name]}`)
1649
- .join(";");
1650
- response = await _getStoreSteamPoweredResponse(cookie);
1651
- }
1652
- return cookie;
1653
- }
1654
-
1655
- async function loginWithCookie(cookie, tryNewCookie = false) {
1656
- let response;
1657
- for (let i = 0; i < 20; i++) {
1658
- try {
1659
- response = await axios.request({
1660
- url: "https://steamcommunity.com/chat/clientjstoken",
1661
- headers: {
1662
- cookie,
1663
- },
1664
- });
1665
- } catch (e) {
1666
- await sleep(1000);
1667
- }
1668
- if (response) {
1669
- break;
1670
- }
1671
- }
1672
-
1673
- const result = response?.data;
1674
- if (result?.logged_in) {
1675
- Object.assign(result, {
1676
- steamID: new SteamID(result.steamid),
1677
- accountName: result.account_name,
1678
- webLogonToken: result.token,
1679
- });
1680
- steamClient.logOn(result);
1681
- return cookie;
1682
- } else {
1683
- if (tryNewCookie) {
1684
- log("You are not logged in", cookie);
1685
- return null;
1686
- } else {
1687
- const newCookie = await getNewCookie(cookie);
1688
- if (!newCookie) {
1689
- console.error("Cannot get new cookie");
1690
- return null;
1691
- } else {
1692
- return await loginWithCookie(newCookie, true);
1693
- }
1694
- }
1695
- }
1696
- }
1697
-
1698
- async function login(reconnect = false) {
1699
- function logOn(clientJsToken) {
1700
- try {
1701
- steamClient.logOn({
1702
- ...clientJsToken,
1703
- steamId: new SteamID(clientJsToken.steamid),
1704
- steamID: new SteamID(clientJsToken.steamid),
1705
- accountName: clientJsToken.account_name,
1706
- webLogonToken: clientJsToken.token,
1707
- });
1708
- return true;
1709
- } catch (e) {
1710
- console.error(e);
1711
- return false;
1712
- }
1713
- }
1714
-
1715
- if (clientJsToken?.logged_in === true) {
1716
- log(reconnect ? "reconnect with clientJsToken" : "login with clientJsToken");
1717
- setTimeout(function () {
1718
- clientJsToken = null;
1719
- }, 1000);
1720
- return logOn(clientJsToken);
1721
- } else if (cookie) {
1722
- log(reconnect ? "reconnect with cookie" : "login with cookie");
1723
- const steamUser = new SteamUser(typeof cookie === "function" ? await cookie() : cookie);
1724
- const _clientJsToken = await steamUser.getClientJsToken();
1725
- if (_clientJsToken?.logged_in === true) {
1726
- return logOn(_clientJsToken);
1727
- } else {
1728
- log(`Account not logged in ${clientJsToken?.account_name || steamUser.getSteamIdUser() || ""}`);
1729
- console.log(clientJsToken);
1730
- return false;
1731
- }
1732
- } else if (username && password) {
1733
- log(reconnect ? `reconnect with username ${username}` : `login with username ${username}`);
1734
- steamClient.logOn({
1735
- accountName: username,
1736
- password: password,
1737
- rememberPassword: true,
1738
- machineName: "Natri",
1739
- });
1740
- return true;
1741
- } else {
1742
- log(`Account not logged in ${clientJsToken?.account_name || ""}`);
1743
- return false;
1744
- }
1745
- }
1746
-
1747
- function logOff() {
1748
- isLogOff = true;
1749
- logOffEvent?.(true);
1750
- steamClient.logOff();
1751
- }
1752
-
1753
- function onCookie(callback) {
1754
- if (getCookies()) {
1755
- callback(getCookies());
1756
- } else {
1757
- onEvent(
1758
- "webSession",
1759
- function (webSession) {
1760
- callback(webSession?.cookies?.join?.(";"));
1761
- },
1762
- true,
1763
- );
1764
- }
1765
- }
1766
-
1767
- async function init() {
1768
- bindEvent();
1769
- if (await login()) {
1770
- steamClient._handlerManager.add(Protos.csgo.EMsg.k_EMsgClientRequestedClientStats, function (payload) {
1771
- const result = protoDecode(Protos.csgo.CMsgClientRequestedClientStats, payload.toBuffer());
1772
- // console.log("CMsgClientRequestedClientStats", result);
1773
- });
1774
- steamClient._handlerManager.add(Protos.csgo.EMsg.k_EMsgClientMMSLobbyData, function (payload) {
1775
- const result = protoDecode(Protos.csgo.CMsgClientMMSLobbyData, payload.toBuffer());
1776
- // console.log("CMsgClientMMSLobbyData", result, result.metadata);
1777
- });
1778
- }
1779
- }
1780
-
1781
- function partyRegister() {
1782
- if (prime === null) {
1783
- _partyRegister(true);
1784
- _partyRegister(false);
1785
- } else {
1786
- _partyRegister(prime);
1787
- }
1788
- }
1789
-
1790
- function _partyRegister(prime) {
1791
- log("partyRegister", prime);
1792
- lastTimePartyRegister = new Date().getTime();
1793
- steamClient.sendToGC(
1794
- 730,
1795
- Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Register,
1796
- {},
1797
- protoEncode(Protos.csgo.CMsgGCCStrike15_v2_Party_Register, {
1798
- // id : 0,
1799
- ver: CSGO_VER,
1800
- apr: prime ? 1 : 0, //prime
1801
- ark: prime ? 180 : 0,
1802
- grps: [],
1803
- launcher: 0,
1804
- game_type: 8,
1805
- }),
1806
- );
1807
- }
1808
-
1809
- async function sendFriendMessage(steamId, message) {
1810
- while (sendMessageTimestamp && new Date().getTime() - sendMessageTimestamp < 2000) {
1811
- await sleep(1000);
1812
- }
1813
-
1814
- while (isSendingFriendMessages) {
1815
- await sleep(5000);
1816
- }
1817
-
1818
- isSendingFriendMessages = true;
1819
- const now = new Date().getTime();
1820
- while (new Date().getTime() - now < 2 * 60000) {
1821
- //2 minutes
1822
- const result = await new Promise((resolve) => {
1823
- steamClient.chat.sendFriendMessage(steamId, message, undefined, function (...arg) {
1824
- sendMessageTimestamp = new Date().getTime();
1825
- resolve(arg);
1826
- });
1827
- });
1828
-
1829
- if (result?.[1]?.server_timestamp) {
1830
- isSendingFriendMessages = false;
1831
- return result?.[1];
1832
- } else if (result?.[0]?.message?.includes?.("RateLimitExceeded")) {
1833
- await sleep(5000);
1834
- } else {
1835
- isSendingFriendMessages = false;
1836
- return result;
1837
- }
1838
- }
1839
- isSendingFriendMessages = false;
1840
- }
1841
-
1842
- async function autoRequestFreeLicense(shouldLog = false, max = 10) {
1843
- return;
1844
- // const mCookies = await getCookiesWait()
1845
- // if (!mCookies) return
1846
- // let freeAppList = Array.isArray(steamClient.licenses) ? FreeAppList.filter(appId => steamClient.licenses.every(({package_id}) => package_id !== appId)) : FreeAppList;
1847
- const freeAppList = freeAppList.filter((appId) => ownedApps.some((app) => app.appid == appId));
1848
- const recommendedApps = _.shuffle(freeAppList);
1849
- if (max) {
1850
- recommendedApps.length = Math.min(recommendedApps.length, max);
1851
- }
1852
- try {
1853
- const response = await steamClient.requestFreeLicense(recommendedApps);
1854
- if (shouldLog) {
1855
- log(response);
1856
- }
1857
- } catch (e) {
1858
- log(e);
1859
- }
1860
- // if (Math.random() > 0.7) {
1861
- // for (const recommendedApp of recommendedApps) {
1862
- // try {
1863
- // await steamUtils.requestFreeLicense(recommendedApp)
1864
- // } catch (e) {
1865
- // }
1866
- // await sleep(2000)
1867
- // }
1868
- // } else {
1869
- // try {
1870
- // await steamClient.requestFreeLicense(recommendedApps)
1871
- // } catch (e) {
1872
- // log(e);
1873
- // }
1874
- // }
1875
-
1876
- // if (shouldLog) {
1877
- // await sleep(20000)
1878
- // const ownedAppsCount2 = (await steamUtils.getDynamicStoreUserData())?.rgOwnedApps?.length || 0
1879
- // const increaseNumber = ownedAppsCount2 - ownedAppsCount;
1880
- // log(`OwnedApps length ${ownedAppsCount2}, increase ${increaseNumber}`)
1881
- // }
1882
- }
1883
-
1884
- async function playCSGO() {
1885
- try {
1886
- await steamClient.requestFreeLicense(AppID);
1887
- await sleep(5000);
1888
- } catch (e) {}
1889
- gamesPlayed(AppID);
1890
- }
1891
-
1892
- function doFakeGameScore() {
1893
- const maxRound = Math.random() > 0.7 ? 16 : 12;
1894
- const maps = [
1895
- "ar_baggage",
1896
- "ar_dizzy",
1897
- "ar_monastery",
1898
- "ar_shoots",
1899
- "cs_agency",
1900
- "cs_assault",
1901
- "cs_italy",
1902
- "cs_militia",
1903
- "cs_office",
1904
- "de_ancient",
1905
- "de_anubis",
1906
- "de_bank",
1907
- "de_boyard",
1908
- "de_cache",
1909
- "de_canals",
1910
- "de_cbble",
1911
- "de_chalice",
1912
- "de_dust2",
1913
- "de_inferno",
1914
- "de_lake",
1915
- "de_mirage",
1916
- "de_nuke",
1917
- "de_overpass",
1918
- "de_safehouse",
1919
- // "de_shortnuke",
1920
- "de_stmarc",
1921
- "de_sugarcane",
1922
- "de_train",
1923
- "de_tuscan",
1924
- "de_vertigo",
1925
- "dz_ember",
1926
- "dz_vineyard",
1927
- "gd_cbble",
1928
- "training1",
1929
- ];
1930
-
1931
- if (richPresence.myScore === undefined) {
1932
- richPresence.myScore = _.random(0, maxRound);
1933
- }
1934
- if (richPresence.theirScore === undefined) {
1935
- richPresence.theirScore = _.random(0, maxRound);
1936
- }
1937
- if (richPresence.map === undefined) {
1938
- richPresence.map = maps[Math.floor(Math.random() * maps.length)];
1939
- }
1940
- if (richPresence.myScore === maxRound || richPresence.theirScore === maxRound) {
1941
- richPresence.myScore = 0;
1942
- richPresence.theirScore = 0;
1943
- richPresence.map = maps[Math.floor(Math.random() * maps.length)];
1944
- } else {
1945
- const isMyTeamWin = Math.random() > 0.5;
1946
- if (isMyTeamWin) {
1947
- richPresence.myScore++;
1948
- } else {
1949
- richPresence.theirScore++;
1950
- }
1951
- }
1952
-
1953
- const score = richPresence.myScore === 0 && richPresence.theirScore === 0 ? "" : `[ ${richPresence.myScore} : ${richPresence.theirScore} ]`;
1954
- steamClient.uploadRichPresence(730, {
1955
- "game:state": "game",
1956
- steam_display: "#display_GameKnownMapScore",
1957
- connect: "+gcconnectG082AA752",
1958
- version: CSGO_VER.toString(),
1959
- "game:mode": "competitive",
1960
- "game:map": richPresence.map,
1961
- "game:server": "kv",
1962
- watch: _.random(1, 5).toString(),
1963
- "game:score": score,
1964
- });
1965
- }
1966
-
1967
- function updateFakeGameScore() {
1968
- if (isFakeGameScore && getPlayingAppIds().some((a) => a == 730)) {
1969
- doSetInterval(doFakeGameScore, [60000, 180000], "uploadRichPresenceCSGO");
1970
- } else {
1971
- doClearInterval("uploadRichPresenceCSGO");
1972
- }
1973
- }
1974
-
1975
- function updateAutoRequestFreeLicense() {
1976
- if (isAutoRequestFreeLicense) {
1977
- doSetInterval(
1978
- function () {
1979
- autoRequestFreeLicense(false, 50);
1980
- },
1981
- [5 * 60000, 10 * 60000],
1982
- "autoRequestFreeLicense",
1983
- );
1984
- } else {
1985
- doClearInterval("autoRequestFreeLicense");
1986
- }
1987
- }
1988
-
1989
- function updateInvisible() {
1990
- if (isInvisible) {
1991
- steamClient.setPersona(NodeSteamUser.EPersonaState.Invisible);
1992
- state = "Invisible";
1993
- } else {
1994
- steamClient.setPersona(NodeSteamUser.EPersonaState.Online);
1995
- state = "Online";
1996
- }
1997
- }
1998
-
1999
- async function gamesPlayed(apps) {
2000
- if (!Array.isArray(apps)) {
2001
- apps = [apps];
2002
- }
2003
-
2004
- const processedApps = apps.map((app) => {
2005
- if (typeof app == "string") {
2006
- app = { game_id: "15190414816125648896", game_extra_info: app };
2007
- } else if (typeof app === "number" || typeof app != "object") {
2008
- app = { game_id: app };
2009
- }
2010
-
2011
- if (typeof app.game_ip_address == "number") {
2012
- app.game_ip_address = { v4: app.game_ip_address };
2013
- }
2014
-
2015
- return app;
2016
- });
2017
-
2018
- steamClient.gamesPlayed(processedApps);
2019
- if (processedApps.some((app) => parseInt(app.game_id) === 730)) {
2020
- await sleep(500);
2021
- await sendHello();
2022
- }
2023
- updateFakeGameScore();
2024
-
2025
- // await sleep(10000)
2026
- // self.steamUser.uploadRichPresence(730, {
2027
- // status: 'bussssss',
2028
- // 'game:state': 'lobby',
2029
- // steam_display: '#display_watch',
2030
- // currentmap: '#gamemap_de_empire',
2031
- // connect: '+gcconnectG082AA752',
2032
- // 'game:mode': 'competitive'
2033
- // })
2034
- }
2035
-
2036
- function getFriendsList() {
2037
- const methodName = "FriendsList.GetFriendsList#1";
2038
- const { users, myFriends } = steamClient; //object
2039
- /*
2040
- users
2041
- * {
2042
- rich_presence: [],
2043
- player_name: "Kei #SkinsMonkey",
2044
- avatar_hash: [123,4543],
2045
- last_logoff: "2023-05-20T05:00:42.000Z",
2046
- last_logon: "2023-05-20T05:02:16.000Z",
2047
- last_seen_online: "2023-05-20T05:00:42.000Z",
2048
- avatar_url_icon: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a.jpg",
2049
- avatar_url_medium: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a_medium.jpg",
2050
- avatar_url_full: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a_full.jpg"
2051
- }
2052
- *
2053
-
2054
- myFriends
2055
- {
2056
- 76561198365087582: 3,
2057
- 76561199490395123: 3
2058
- }
2059
- * */
2060
- /*steamClient._send({
2061
- msg: 151,
2062
- proto: {
2063
- target_job_name: methodName
2064
- }
2065
- }, Buffer.alloc(0), function (body, hdr) {
2066
- const result = hdr.proto.eresult
2067
- const errorMessage = hdr.proto.error_message
2068
- const responseData = body.toBuffer()
2069
- console.log(`xxx`, result)
2070
- })*/
2071
-
2072
- steamClient.sendToGC(730, 767, {}, Buffer.alloc(0));
2073
- }
2074
-
2075
- async function getUserOwnedApps(steamId = steamClient.steamID) {
2076
- if (!steamId) {
2077
- return [];
2078
- }
2079
- if (typeof steamId?.getSteamID64 === "function") {
2080
- steamId = steamId.getSteamID64();
2081
- }
2082
- const isMe = steamId === steamClient.steamID.getSteamID64();
2083
- if (isMe && ownedApps.length) {
2084
- return ownedApps;
2085
- }
2086
- let result = {};
2087
- try {
2088
- result = await steamClient.getUserOwnedApps(steamId);
2089
- } catch (e) {
2090
- try {
2091
- result = await steamClient.getUserOwnedApps(steamId);
2092
- } catch (e) {
2093
- result = {};
2094
- }
2095
- }
2096
- if (isMe && Array.isArray(result.apps)) {
2097
- ownedApps.length = 0;
2098
- ownedApps.push(...result.apps);
2099
- }
2100
- return result.apps || [];
2101
- const resultExample = {
2102
- app_count: 22,
2103
- apps: [
2104
- {
2105
- content_descriptorids: [],
2106
- appid: 208030,
2107
- name: "Moon Breakers",
2108
- playtime_2weeks: null,
2109
- playtime_forever: 0,
2110
- img_icon_url: "",
2111
- has_community_visible_stats: null,
2112
- playtime_windows_forever: 0,
2113
- playtime_mac_forever: 0,
2114
- playtime_linux_forever: 0,
2115
- rtime_last_played: 0,
2116
- capsule_filename: null,
2117
- sort_as: null,
2118
- has_workshop: null,
2119
- has_market: null,
2120
- has_dlc: null,
2121
- has_leaderboards: null,
2122
- },
2123
- ],
2124
- };
2125
- }
2126
-
2127
- function getPlayingAppIds() {
2128
- return steamClient._playingAppIds || [];
2129
- }
2130
-
2131
- return {
2132
- init,
2133
- partySearch,
2134
- invite2Lobby,
2135
- createLobby,
2136
- updateLobby,
2137
- createThenInvite2Lobby,
2138
- joinLobby,
2139
- getLobbyData,
2140
- partyRegister,
2141
- requestCoPlays,
2142
- getPersonas,
2143
- getUsername() {
2144
- return username;
2145
- },
2146
- getCookies,
2147
- getCookiesWait,
2148
- getLogOnDetails() {
2149
- return steamClient?._logOnDetails;
2150
- },
2151
- onEvent,
2152
- offEvent,
2153
- offAllEvent,
2154
- setPersona(state, name) {
2155
- steamClient.setPersona(state, name);
2156
- },
2157
- sendFriendMessage,
2158
- sendFriendTyping,
2159
- getSteamClient() {
2160
- return steamClient;
2161
- },
2162
- getAccountInfoName,
2163
- getPersonaName,
2164
- async getPlayersProfile(steamId, retry = 3) {
2165
- for (let i = 0; i < retry; i++) {
2166
- const profile = await getPlayersProfile(steamId);
2167
- if (profile) {
2168
- return profile;
2169
- }
2170
- }
2171
- return null;
2172
- },
2173
- autoRequestFreeLicense,
2174
- playCSGO,
2175
- doSetInterval,
2176
- doClearIntervals,
2177
- gamesPlayed,
2178
- sendHello,
2179
- checkPlayerPrimeStatus,
2180
- doClearInterval,
2181
- gamePlay,
2182
- autoGamePlay,
2183
- offAutoGamePlay,
2184
- updateAutoGamePlay,
2185
- getFriendsList,
2186
- setIsPartyRegister(change) {
2187
- change = !!change;
2188
- if (isPartyRegister !== change) {
2189
- isPartyRegister = change;
2190
- if (!isPartyRegister) {
2191
- doClearInterval("autoPartyRegister");
2192
- } else {
2193
- sendHello();
2194
- }
2195
- }
2196
- },
2197
- setAutoPlay(change) {
2198
- change = !!change;
2199
- if (isAutoPlay !== change) {
2200
- isAutoPlay = change;
2201
- updateAutoGamePlay();
2202
- }
2203
- },
2204
- setIsInvisible(change) {
2205
- change = !!change;
2206
- if (isInvisible !== change) {
2207
- isInvisible = change;
2208
- updateInvisible();
2209
- }
2210
- },
2211
- setFakeGameScore(change) {
2212
- change = !!change;
2213
- if (isFakeGameScore !== change) {
2214
- isFakeGameScore = change;
2215
- updateFakeGameScore();
2216
- }
2217
- },
2218
- setAutoRequestFreeLicense(change) {
2219
- change = !!change;
2220
- if (isAutoRequestFreeLicense !== change) {
2221
- isAutoRequestFreeLicense = change;
2222
- updateAutoRequestFreeLicense();
2223
- }
2224
- },
2225
- getState() {
2226
- return state;
2227
- },
2228
- log,
2229
- isPrime() {
2230
- return prime === true;
2231
- },
2232
- getFriendList,
2233
- logOff,
2234
- isPlayingBlocked() {
2235
- return playingBlocked;
2236
- },
2237
- async getChatHistory(steamId) {
2238
- if (!steamClient.steamID) return [];
2239
- const mySteamId = typeof steamClient.steamID.getSteamID64 === "function" ? steamClient.steamID.getSteamID64() : steamClient.steamID;
2240
- return new Promise((resolve) => {
2241
- setTimeout(resolve, 90000);
2242
- steamClient.getChatHistory(steamId, async function (error, result) {
2243
- const messages = (result || []).map(function (msg) {
2244
- const fromSteamId = typeof msg.steamID?.getSteamID64 === "function" ? msg.steamID.getSteamID64() : msg.steamID;
2245
- return {
2246
- message: msg.message,
2247
- from: fromSteamId,
2248
- to: fromSteamId == mySteamId ? steamId : mySteamId,
2249
- _id: new Date(msg.timestamp).getTime().toString(),
2250
- timestamp: new Date(msg.timestamp).getTime(),
2251
- isMe: fromSteamId !== steamId,
2252
- };
2253
- });
2254
- resolve(messages);
2255
- });
2256
- });
2257
- },
2258
- onAnyEvent,
2259
- async redeemGift(gid) {
2260
- try {
2261
- const community = new SteamCommunity();
2262
- let cookies = await getCookiesWait();
2263
- community.setCookies(typeof cookies === "string" ? cookies.split(";") : cookies);
2264
- community.redeemGift(gid);
2265
- } catch (e) {}
2266
- },
2267
- async requestFreeLicense(...args) {
2268
- try {
2269
- return await steamClient.requestFreeLicense(...args);
2270
- } catch (e) {}
2271
- },
2272
- getSteamId() {
2273
- try {
2274
- return steamClient.steamID.getSteamID64();
2275
- } catch (e) {}
2276
- },
2277
- getLastTimePartyRegister() {
2278
- return lastTimePartyRegister;
2279
- },
2280
- getLastTimePartySearch() {
2281
- return lastTimePartySearch;
2282
- },
2283
- getLicenses() {
2284
- return steamClient.licenses;
2285
- const exampleLicenses = [
2286
- {
2287
- package_id: 303386,
2288
- time_created: 1680491335,
2289
- time_next_process: 0,
2290
- minute_limit: 0,
2291
- minutes_used: 0,
2292
- payment_method: 1024,
2293
- flags: 512,
2294
- purchase_country_code: "VN",
2295
- license_type: 1,
2296
- territory_code: 0,
2297
- change_number: 20615891,
2298
- owner_id: 1530068060,
2299
- initial_period: 0,
2300
- initial_time_unit: 0,
2301
- renewal_period: 0,
2302
- renewal_time_unit: 0,
2303
- access_token: "8049398090486337961",
2304
- master_package_id: null,
2305
- },
2306
- ];
2307
- },
2308
- uploadRichPresence(appid, richPresence) {
2309
- const _richPresence = Array.isArray(richPresence)
2310
- ? richPresence.reduce(function (previousValue, currentValue, currentIndex, array) {
2311
- if (currentValue.key) {
2312
- previousValue[currentValue.key] = currentValue.value?.toString() || "";
2313
- }
2314
- return previousValue;
2315
- }, {})
2316
- : richPresence;
2317
- steamClient.uploadRichPresence(appid, _richPresence);
2318
- },
2319
- getUserOwnedApps,
2320
- getPlayingAppIds,
2321
- getCurrentLobby() {
2322
- return currentLobby;
2323
- },
2324
- setGame(_games) {
2325
- games = _games;
2326
- },
2327
- };
2328
- }
2329
-
2330
- export default SteamClient;
2331
-
2332
- export function increaseCSGO_VER() {
2333
- return ++CSGO_VER;
2334
- }
2335
-
2336
- SteamClient.isAccountPlayable = async function isAccountPlayable({ cookie, clientJsToken, timeoutMs, onPlayable, onNotPlayable, ...rest }) {
2337
- if (!clientJsToken && cookie) {
2338
- clientJsToken = await new SteamUser(typeof cookie === "function" ? await cookie() : cookie).getClientJsToken();
2339
- }
2340
- if (clientJsToken?.logged_in !== true) {
2341
- if (typeof onNotPlayable === "function") {
2342
- await onNotPlayable(null);
2343
- }
2344
- return { invalidClientJsToken: true };
2345
- }
2346
- return await new Promise((resolve) => {
2347
- const timeouts = [
2348
- setTimeout(() => {
2349
- doResolve({ timedOut: true });
2350
- }, timeoutMs || 30000),
2351
- ];
2352
-
2353
- const steamClient = new SteamClient({
2354
- isFakeGameScore: false,
2355
- isAutoPlay: true,
2356
- isPartyRegister: false,
2357
- isInvisible: true,
2358
- MAX_GAME_PLAY: 10,
2359
- games: 730,
2360
- clientJsToken,
2361
- ...rest,
2362
- });
2363
-
2364
- steamClient.onEvent("error", ({ eresult, msg, error }) => {
2365
- doResolve({ eresult, msg, error });
2366
- });
2367
-
2368
- steamClient.onEvent("csgoOnline", (ClientWelcome) => {
2369
- doResolve({ playable: true });
2370
- });
2371
-
2372
- steamClient.onEvent("csgoClientHello", (ClientHello) => {
2373
- doResolve({ playable: true });
2374
- });
2375
-
2376
- steamClient.onEvent("playingState", ({ playing_blocked, playing_app }) => {
2377
- if (playing_blocked) {
2378
- doResolve({ playable: false });
2379
- } else {
2380
- timeouts.push(
2381
- setTimeout(function () {
2382
- const isBlocked = steamClient.isPlayingBlocked();
2383
- doResolve({ playable: !isBlocked });
2384
- }, 5000),
2385
- );
2386
- }
2387
- });
2388
-
2389
- // steamClient.onEvent("fatalError", () => {
2390
- // doResolve();
2391
- // });
2392
-
2393
- steamClient.init();
2394
-
2395
- async function doResolve(data) {
2396
- timeouts.forEach((timeout) => clearTimeout(timeout));
2397
- steamClient.doClearIntervals();
2398
- steamClient.offAllEvent();
2399
-
2400
- if (data?.playable === true) {
2401
- if (typeof onPlayable === "function") {
2402
- try {
2403
- await onPlayable(steamClient);
2404
- } catch (e) {}
2405
- }
2406
- } else {
2407
- if (typeof onNotPlayable === "function") {
2408
- try {
2409
- await onNotPlayable(steamClient);
2410
- } catch (e) {}
2411
- }
2412
- }
2413
-
2414
- steamClient.logOff();
2415
- return resolve(data);
2416
- }
2417
- });
2418
- };
1
+ import NodeSteamUser from "steam-user";
2
+ import _ from "lodash";
3
+ import fs from "fs";
4
+ import { protoDecode, protoEncode } from "./helpers/util.js";
5
+ import SteamID from "steamid";
6
+ import FriendCode from "csgo-friendcode";
7
+ import axios from "axios";
8
+ import helpers, { loadProfos } from "./helpers/protos.js";
9
+ import { fileURLToPath } from "url";
10
+ import path from "path";
11
+ import SteamUser from "./index.js";
12
+ import { v4 as uuidv4 } from "uuid";
13
+ import EFriendRelationship from "steam-user/enums/EFriendRelationship.js";
14
+ import SteamCommunity from "steamcommunity";
15
+ import moment from "moment-timezone";
16
+ import { encode, encodeUids } from "./bufferHelpers.js";
17
+
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ const Protos = helpers([
21
+ {
22
+ name: "csgo",
23
+ protos: loadProfos(`${__dirname}/protos/`),
24
+ },
25
+ ]);
26
+
27
+ export const RANKS = {
28
+ 0: "Unranked",
29
+ 1: "Silver I",
30
+ 2: "Silver II",
31
+ 3: "Silver III",
32
+ 4: "Silver IV",
33
+ 5: "Silver Elite",
34
+ 6: "Silver Elite Master",
35
+ 7: "Gold Nova I",
36
+ 8: "Gold Nova II",
37
+ 9: "Gold Nova III",
38
+ 10: "Gold Nova Master",
39
+ 11: "Master Guardian I",
40
+ 12: "Master Guardian II",
41
+ 13: "Master Guardian Elite",
42
+ 14: "Distinguished Master Guardian",
43
+ 15: "Legendary Eagle",
44
+ 16: "Legendary Eagle Master",
45
+ 17: "Supreme Master First Class",
46
+ 18: "The Global Elite",
47
+ };
48
+ export const LOCS = {
49
+ 20054: "VN",
50
+ 23115: "KZ",
51
+ 20041: "IN",
52
+ 20035: "CN",
53
+ 17474: "BD",
54
+ 17481: "ID",
55
+ 22861: "MY",
56
+ 18516: "TH",
57
+ 22356: "TW",
58
+ 21067: "KR",
59
+ 19272: "HK",
60
+ 18512: "PH",
61
+ 21842: "RU",
62
+ 16716: "LA",
63
+ 20558: "NP",
64
+ 18259: "SG",
65
+ 19789: "MM",
66
+ 20045: "MN",
67
+ 18251: "KG",
68
+ 18507: "KH",
69
+ 22605: "MX",
70
+ 19280: "PK",
71
+ 20301: "HK/MO", //hongkong or macau
72
+ 21333: "Unknown",
73
+ 21825: "AU",
74
+ 20034: "Unkown",
75
+ };
76
+
77
+ const AppID = 730;
78
+ export let CSGO_VER = 13960;
79
+ export const FreeAppList = JSON.parse(fs.readFileSync(path.join(__dirname, "free_packages.json"))).packages;
80
+
81
+ SteamUser.getAppVersion(AppID).then(function (ver) {
82
+ CSGO_VER = ver;
83
+ });
84
+
85
+ const PersonasCache = [];
86
+ let isSendingFriendMessages = false;
87
+
88
+ function SteamClient({ username, password, cookie, clientJsToken, isAutoRequestFreeLicense = true, isFakeGameScore = true, isPartyRegister = true, isAutoPlay = false, isInvisible = false, autoAcceptTradeRequest = false, autoReconnect = true, MAX_GAME_PLAY = 10, games = null }) {
89
+ const steamClient = new NodeSteamUser();
90
+ let prime = null;
91
+ let state = "Offline"; //InGame, Online, Invisible
92
+ let isLogOff = false;
93
+ let playingBlocked = null;
94
+ const richPresence = {};
95
+ let sendMessageTimestamp = 0;
96
+ let lastTimePartyRegister = 0;
97
+ let lastTimePartySearch = 0;
98
+ const ownedApps = [];
99
+ let logOffEvent = null;
100
+
101
+ const currentLobby = {
102
+ lobbyID: null,
103
+ timestamp: 0,
104
+ };
105
+
106
+ const onAnyCallbacks = [];
107
+
108
+ const events = {
109
+ user: [],
110
+ loggedOn: [],
111
+ csgoOnline: [],
112
+ csgoClientHello: [],
113
+ webSession: [],
114
+ friendMessage: [],
115
+ friendTyping: [],
116
+ disconnected: [],
117
+ error: [],
118
+ playersProfile: [],
119
+ fatalError: [],
120
+ partyInvite: [],
121
+ friendRelationship: [],
122
+ tradeOffers: [],
123
+ offlineMessages: [],
124
+ friendsList: [],
125
+ gifts: [],
126
+ playingState: [],
127
+ emailInfo: [],
128
+ accountLimitations: [],
129
+ };
130
+
131
+ const gcCallback = {};
132
+
133
+ function pushGCCallback(name, cb, timeout) {
134
+ if (!gcCallback[name]) {
135
+ gcCallback[name] = {};
136
+ }
137
+ let t = null;
138
+ let id = uuidv4();
139
+
140
+ function callback(...arg) {
141
+ if (t) {
142
+ clearTimeout(t);
143
+ }
144
+ delete gcCallback[name][id];
145
+ cb?.apply(null, arg);
146
+ }
147
+
148
+ if (timeout) {
149
+ t = setTimeout(callback, timeout);
150
+ }
151
+ gcCallback[name][id] = callback;
152
+ }
153
+
154
+ function callGCCallback(name, ...arg) {
155
+ if (gcCallback[name]) {
156
+ for (const id in gcCallback[name]) {
157
+ gcCallback[name][id]?.(...arg);
158
+ }
159
+ }
160
+ }
161
+
162
+ function callEvent(_events, data) {
163
+ const eventName = Object.keys(events).find((eventName) => events[eventName] === _events);
164
+ eventName && onAnyCallbacks.forEach((cb) => cb?.({ eventName, data }));
165
+
166
+ _events?.forEach?.((e) => {
167
+ e.callback?.(data);
168
+ e.timeout && clearTimeout(e.timeout);
169
+ delete e.timeout;
170
+ if (e.once) {
171
+ delete e.callback;
172
+ }
173
+ });
174
+ _.remove(_events, (e) => !e || e?.once);
175
+ }
176
+
177
+ function onEvent(name, callback, once, timeout) {
178
+ if (!events[name]) {
179
+ events[name] = [];
180
+ }
181
+ const t = timeout ? setTimeout(callback, timeout) : null;
182
+ events[name].push({
183
+ once,
184
+ callback,
185
+ timeout: t,
186
+ });
187
+ }
188
+
189
+ function offEvent(name) {
190
+ if (Array.isArray(events[name])) {
191
+ for (const eventElement of events[name]) {
192
+ if (eventElement.timeout) {
193
+ clearTimeout(eventElement.timeout);
194
+ }
195
+ }
196
+ }
197
+
198
+ delete events[name];
199
+ }
200
+
201
+ function onAnyEvent(callback) {
202
+ onAnyCallbacks.push(callback);
203
+ }
204
+
205
+ function offAllEvent() {
206
+ for (const name in events) {
207
+ for (const event of events[name]) {
208
+ if (event.timeout) {
209
+ try {
210
+ clearTimeout(event.timeout);
211
+ } catch (e) {}
212
+ delete event.timeout;
213
+ }
214
+ }
215
+ delete events[name];
216
+ }
217
+ onAnyCallbacks.length = 0;
218
+ }
219
+
220
+ const intervals = {};
221
+ const intervalRandoms = {};
222
+
223
+ function doSetInterval(cb, timeout, key) {
224
+ const isRandom = Array.isArray(timeout);
225
+ if (!key) {
226
+ key = uuidv4();
227
+ }
228
+ if (isRandom) {
229
+ if (intervalRandoms[key] !== undefined) {
230
+ try {
231
+ clearTimeout(intervalRandoms[key]);
232
+ } catch (e) {}
233
+ }
234
+ intervalRandoms[key] = setTimeout(
235
+ function () {
236
+ doSetInterval(cb, timeout, key);
237
+ if (state !== "Offline") {
238
+ cb();
239
+ }
240
+ },
241
+ _.random(timeout[0], timeout[1]),
242
+ );
243
+ } else {
244
+ if (intervals[key] !== undefined) {
245
+ try {
246
+ clearInterval(intervals[key]);
247
+ } catch (e) {}
248
+ }
249
+
250
+ intervals[key] = setInterval(function () {
251
+ if (state !== "Offline") {
252
+ cb();
253
+ }
254
+ }, timeout);
255
+ }
256
+
257
+ return key;
258
+ }
259
+
260
+ function doClearIntervals() {
261
+ for (const key in intervals) {
262
+ clearInterval(intervals[key]);
263
+ delete intervals[key];
264
+ }
265
+ for (const key in intervalRandoms) {
266
+ clearTimeout(intervalRandoms[key]);
267
+ delete intervalRandoms[key];
268
+ }
269
+ }
270
+
271
+ function doClearInterval(key) {
272
+ try {
273
+ clearInterval(intervals[key]);
274
+ } catch (e) {}
275
+ delete intervals[key];
276
+
277
+ try {
278
+ clearTimeout(intervalRandoms[key]);
279
+ } catch (e) {}
280
+ delete intervalRandoms[key];
281
+ }
282
+
283
+ function getAccountInfoName() {
284
+ return [steamClient?.accountInfo?.name, steamClient?._logOnDetails?.account_name].filter(Boolean).join(" - ");
285
+ }
286
+
287
+ function getPersonaName() {
288
+ return steamClient?.accountInfo?.name;
289
+ }
290
+
291
+ function log(...msg) {
292
+ const now = moment().tz("Asia/Ho_Chi_Minh").format("DD/MM/YYYY HH:mm:ss");
293
+ console.log(`[${now}] [${getAccountInfoName()}]`, ...msg);
294
+ }
295
+
296
+ async function getPersonas(steamIDs) {
297
+ steamIDs = steamIDs.map((steamId) => (steamId instanceof SteamID ? steamId.getSteamID64() : steamId));
298
+ const notCachesteamIDs = steamIDs.filter((id) => !PersonasCache.some((p) => p.id == id));
299
+ const cachedPersonas = PersonasCache.filter((p) => steamIDs.includes(p.id));
300
+
301
+ if (notCachesteamIDs.length) {
302
+ let personas = null;
303
+ try {
304
+ personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
305
+ } catch (e) {}
306
+ if (!personas || !Object.keys(personas).length) {
307
+ try {
308
+ personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
309
+ } catch (e) {}
310
+ }
311
+ if (!personas || !Object.keys(personas).length) {
312
+ try {
313
+ personas = (await steamClient.getPersonas(notCachesteamIDs))?.personas;
314
+ } catch (e) {}
315
+ }
316
+ if (personas && Object.keys(personas).length) {
317
+ for (let sid64 in personas) {
318
+ personas[sid64].id = sid64;
319
+ personas[sid64].avatar_hash = Buffer.from(personas[sid64].avatar_hash).toString("hex");
320
+ PersonasCache.push(personas[sid64]);
321
+ cachedPersonas.push(personas[sid64]);
322
+ }
323
+ }
324
+ }
325
+
326
+ while (PersonasCache.length > 500) {
327
+ PersonasCache.shift();
328
+ }
329
+ return cachedPersonas;
330
+ }
331
+
332
+ function sleep(ms) {
333
+ return new Promise((resolve) => {
334
+ setTimeout(resolve, ms);
335
+ });
336
+ }
337
+
338
+ function getCookies() {
339
+ return cookie || steamClient?.webSession?.cookies?.join?.(";");
340
+ }
341
+
342
+ async function getCookiesWait() {
343
+ return (
344
+ getCookies() ||
345
+ new Promise((resolve) => {
346
+ onEvent(
347
+ "webSession",
348
+ function (webSession) {
349
+ resolve(webSession?.cookies);
350
+ },
351
+ true,
352
+ 30000,
353
+ );
354
+ })
355
+ );
356
+ }
357
+
358
+ async function gamePlay() {
359
+ if ((Array.isArray(games) && games.length) || (games && (typeof games === "number" || typeof games === "string"))) {
360
+ return gamesPlayed(games);
361
+ }
362
+
363
+ let ownedApps = [];
364
+ for (let i = 0; i < 5; i++) {
365
+ ownedApps = await getUserOwnedApps();
366
+ if (ownedApps?.length) {
367
+ break;
368
+ }
369
+ }
370
+ if (!ownedApps?.length) {
371
+ gamesPlayed(730);
372
+ } else {
373
+ ownedApps = ownedApps.map(({ appid }) => appid);
374
+ ownedApps = _.shuffle(ownedApps);
375
+ ownedApps.length = Math.min(ownedApps.length, MAX_GAME_PLAY - 1);
376
+ _.remove(ownedApps, (app) => app == 730);
377
+ gamesPlayed([...ownedApps, 730]);
378
+ }
379
+ }
380
+
381
+ async function autoGamePlay() {
382
+ await gamePlay();
383
+ doSetInterval(gamePlay, [15 * 60000, 30 * 60000], "autoGamePlay");
384
+ }
385
+
386
+ async function offAutoGamePlay() {
387
+ steamClient.gamesPlayed([]);
388
+ doClearInterval("autoGamePlay");
389
+ }
390
+
391
+ async function updateAutoGamePlay() {
392
+ if (isAutoPlay) {
393
+ autoGamePlay();
394
+ } else {
395
+ offAutoGamePlay();
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Get a list of lobbies (* = Unsure description could be wrong)
401
+ * @param {Number} ver Game version we are searching for
402
+ * @param {Boolean} apr Prime or not*
403
+ * @param {Number} ark Rank multiplied by 10*
404
+ * @param {Array.<Number>} grps *
405
+ * @param {Number} launcher If we are using the China CSGO launcher or not*
406
+ * @param {Number} game_type Game type, 8 Competitive, 10 Wingman
407
+ * @returns {Promise.<Object>}
408
+ */
409
+ async function partySearch({ prime = false, game_type = "Competitive", rank = "Silver Elite", timeout = 5000 } = {}) {
410
+ const players = await new Promise((resolve) => {
411
+ steamClient.sendToGC(
412
+ AppID,
413
+ Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Search,
414
+ {},
415
+ protoEncode(Protos.csgo.CMsgGCCStrike15_v2_Party_Search, {
416
+ ver: CSGO_VER,
417
+ apr: prime ? 1 : 0,
418
+ ark: parseInt(Object.keys(RANKS).find((k) => RANKS[k] === rank)) * 10,
419
+ grps: [],
420
+ launcher: 0,
421
+ game_type: game_type === "Competitive" ? 8 : 10,
422
+ }),
423
+ );
424
+ lastTimePartySearch = new Date().getTime();
425
+ pushGCCallback("partySearch", resolve, timeout);
426
+ });
427
+ if (Array.isArray(players) && players.length) {
428
+ const personas = await getPersonas(players.map((p) => p.steamId));
429
+ for (const player of players) {
430
+ const persona = personas.find((p) => p.id == player.steamId);
431
+ if (persona) {
432
+ player.player_name = persona.player_name;
433
+ player.avatar_hash = persona.avatar_hash;
434
+ }
435
+ }
436
+ }
437
+ return players;
438
+ }
439
+
440
+ async function createLobby() {
441
+ if (!steamClient.steamID) {
442
+ return;
443
+ }
444
+
445
+ return new Promise((resolve) => {
446
+ const timeout = setTimeout(function () {
447
+ resolve();
448
+ }, 30000);
449
+
450
+ steamClient._send(
451
+ {
452
+ msg: Protos.csgo.EMsg.k_EMsgClientMMSCreateLobby,
453
+ proto: {
454
+ steamid: steamClient.steamID.getSteamID64(),
455
+ routing_appid: 730,
456
+ },
457
+ },
458
+ protoEncode(Protos.csgo.CMsgClientMMSCreateLobby, {
459
+ app_id: 730,
460
+ max_members: 1,
461
+ lobby_type: 1,
462
+ lobby_flags: 1,
463
+ }),
464
+ function (payload) {
465
+ clearTimeout(timeout);
466
+ const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload.toBuffer());
467
+ const steam_id_lobby = result.steam_id_lobby.toString();
468
+ currentLobby.lobbyID = steam_id_lobby;
469
+ currentLobby.timestamp = new Date().getTime();
470
+ resolve(steam_id_lobby);
471
+ },
472
+ );
473
+ });
474
+
475
+ // return await getHandlerResult(Protos.csgo.EMsg.k_EMsgClientMMSCreateLobbyResponse, function (payload) {
476
+ // const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload.toBuffer())
477
+ // return result.steam_id_lobby.toString()
478
+ // })
479
+
480
+ // steamClient.sendToGC(730, Protos.csgo.EMsg.k_EMsgClientMMSCreateLobby, {
481
+ // steamid: steamClient.steamID,
482
+ // routing_appid: 730,
483
+ // }, protoEncode(Protos.csgo.CMsgClientMMSCreateLobby, {
484
+ // app_id: 730,
485
+ // max_members: 1,
486
+ // lobby_type: 1,
487
+ // lobby_flags: 1
488
+ // }))
489
+ }
490
+
491
+ async function updateLobby(lobbyID) {
492
+ if (!steamClient.steamID) {
493
+ return;
494
+ }
495
+
496
+ return new Promise((resolve) => {
497
+ const timeout = setTimeout(function () {
498
+ resolve();
499
+ }, 30000);
500
+
501
+ steamClient._send(
502
+ {
503
+ msg: Protos.csgo.EMsg.k_EMsgClientMMSSetLobbyData,
504
+ proto: {
505
+ steamid: steamClient.steamID.getSteamID64(),
506
+ routing_appid: 730,
507
+ },
508
+ },
509
+ protoEncode(Protos.csgo.CMsgClientMMSSetLobbyData, {
510
+ app_id: 730,
511
+ steam_id_lobby: lobbyID,
512
+ steam_id_member: "0",
513
+ max_members: 10,
514
+ lobby_type: 1,
515
+ lobby_flags: 1,
516
+ metadata: encode(
517
+ {
518
+ "game:ark": "0",
519
+ // Country/Message
520
+ "game:loc": "",
521
+ "game:mapgroupname": "mg_de_mirage",
522
+ "game:mode": "competitive",
523
+ "game:prime": "1",
524
+ "game:type": "classic",
525
+ "members:numPlayers": "1",
526
+ "options:action": "custommatch",
527
+ "options:anytypemode": "0",
528
+ "system:access": "private",
529
+ "system:network": "LIVE",
530
+ uids: [steamClient.steamID],
531
+ },
532
+ [0x00, 0x00],
533
+ [0x08],
534
+ { uids: encodeUids },
535
+ ).toBuffer(),
536
+ }),
537
+ function (payload) {
538
+ clearTimeout(timeout);
539
+ const result = protoDecode(Protos.csgo.CMsgClientMMSSetLobbyDataResponse, payload.toBuffer());
540
+ const steam_id_lobby = result.steam_id_lobby.toString();
541
+ currentLobby.lobbyID = steam_id_lobby;
542
+ currentLobby.timestamp = new Date().getTime();
543
+ resolve(steam_id_lobby);
544
+ },
545
+ );
546
+ });
547
+
548
+ // return await getHandlerResult(Protos.csgo.EMsg.k_EMsgClientMMSSetLobbyDataResponse, function (payload) {
549
+ // const result = protoDecode(Protos.csgo.CMsgClientMMSSetLobbyDataResponse, payload.toBuffer())
550
+ // return result.steam_id_lobby.toString()
551
+ // })
552
+ }
553
+
554
+ async function invite2Lobby(lobbyID, steamId) {
555
+ if (!steamClient.steamID) {
556
+ return;
557
+ }
558
+
559
+ steamClient._send(
560
+ {
561
+ msg: Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby,
562
+ proto: {
563
+ steamid: steamClient.steamID.getSteamID64(),
564
+ routing_appid: 730,
565
+ },
566
+ },
567
+ protoEncode(Protos.csgo.CMsgClientMMSInviteToLobby, {
568
+ app_id: 730,
569
+ steam_id_lobby: lobbyID,
570
+ steam_id_user_invited: steamId,
571
+ }),
572
+ );
573
+
574
+ // lobbyID = new SteamID(lobbyID).accountid;
575
+
576
+ // Protos.csgo.EMsg.k_EMsgGCHInviteUserToLobby
577
+ // Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby
578
+ // steamClient.sendToGC(730, Protos.csgo.EMsg.k_EMsgClientMMSInviteToLobby, {}, protoEncode(Protos.csgo.CMsgClientMMSInviteToLobby, {
579
+ // app_id: 730,
580
+ // steam_id_lobby: lobbyID,
581
+ // steam_id_user_invited: accountid,
582
+ // }), function (...args) {
583
+ // console.log("invite2Lobby response", args)
584
+ // })
585
+ }
586
+
587
+ async function createThenInvite2Lobby(steamIds, onInvite) {
588
+ if (!steamClient.steamID) {
589
+ return;
590
+ }
591
+
592
+ if (!Array.isArray(steamIds)) {
593
+ steamIds = [steamIds];
594
+ }
595
+
596
+ let lobbyID = null;
597
+ if (currentLobby.lobbyID && currentLobby.timestamp > new Date().getTime() - 30000) {
598
+ //30 seconds
599
+ lobbyID = currentLobby.lobbyID;
600
+ } else {
601
+ lobbyID = await createLobby();
602
+ lobbyID = await updateLobby(lobbyID);
603
+ }
604
+
605
+ for (const steamId of steamIds) {
606
+ onInvite?.(lobbyID, steamId);
607
+ await invite2Lobby(lobbyID, steamId);
608
+ }
609
+
610
+ return lobbyID;
611
+ }
612
+
613
+ async function getLobbyData(lobbyID) {
614
+ if (!steamClient.steamID) {
615
+ return;
616
+ }
617
+
618
+ return new Promise((resolve) => {
619
+ const timeout = setTimeout(function () {
620
+ resolve();
621
+ }, 30000);
622
+
623
+ steamClient._send(
624
+ {
625
+ msg: Protos.csgo.EMsg.k_EMsgClientMMSGetLobbyData,
626
+ proto: {
627
+ steamid: steamClient.steamID.getSteamID64(),
628
+ routing_appid: 730,
629
+ },
630
+ },
631
+ protoEncode(Protos.csgo.CMsgClientMMSGetLobbyData, {
632
+ app_id: 730,
633
+ steam_id_lobby: lobbyID.toString(),
634
+ }),
635
+ function (payload) {
636
+ clearTimeout(timeout);
637
+ const result = protoDecode(Protos.csgo.CMsgClientMMSLobbyData, payload.toBuffer());
638
+ result.steam_id_lobby = result.steam_id_lobby.toString();
639
+ resolve(result);
640
+ },
641
+ );
642
+ });
643
+ }
644
+
645
+ async function joinLobby(lobbyID) {
646
+ log("joinLobby", lobbyID); //SteamID.fromIndividualAccountID(lobbyId).accountid
647
+
648
+ steamClient._send(
649
+ {
650
+ msg: Protos.csgo.EMsg.k_EMsgClientMMSJoinLobby,
651
+ proto: {
652
+ steamid: steamClient.steamID.getSteamID64(),
653
+ routing_appid: 730,
654
+ },
655
+ }, //CMsgClientMMSUserJoinedLobby CMsgClientMMSJoinLobby
656
+ protoEncode(Protos.csgo.CMsgClientMMSJoinLobby, {
657
+ app_id: 730,
658
+ steam_id_lobby: lobbyID,
659
+ persona_name: steamClient.accountInfo.name,
660
+ }),
661
+ function (payload) {
662
+ const result = protoDecode(Protos.csgo.CMsgClientMMSJoinLobbyResponse, payload.toBuffer());
663
+ result.steam_id_lobby = result.steam_id_lobby.toString();
664
+ result.steam_id_owner = result.steam_id_owner.toString();
665
+ console.log(result);
666
+ const resultExample = {
667
+ members: [],
668
+ app_id: 730,
669
+ steam_id_lobby: "3641224920",
670
+ chat_room_enter_response: 2,
671
+ max_members: 0,
672
+ lobby_type: 0,
673
+ lobby_flags: 0,
674
+ steam_id_owner: "0",
675
+ metadata: null, //Buffer
676
+ };
677
+ },
678
+ );
679
+ }
680
+
681
+ async function sendHello() {
682
+ steamClient.sendToGC(AppID, Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello, {}, Buffer.alloc(0));
683
+ // steamClient.sendToGC(AppID, Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientHello, {}, Buffer.alloc(0));
684
+
685
+ steamClient.sendToGC(
686
+ AppID,
687
+ Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientHello,
688
+ {},
689
+ protoEncode(Protos.csgo.CMsgClientHello, {
690
+ version: 2000258, //get from https://github.com/SteamDatabase/GameTracking-CS2/commits
691
+ client_session_need: 0,
692
+ client_launcher: 0,
693
+ steam_launcher: 0,
694
+ }),
695
+ );
696
+ }
697
+
698
+ async function requestCoPlays() {
699
+ return new Promise((resolve) => {
700
+ steamClient.sendToGC(AppID, Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Account_RequestCoPlays, {}, Buffer.alloc(0));
701
+ pushGCCallback("RequestCoPlays", resolve, 30000);
702
+ });
703
+ }
704
+
705
+ function bindEvent() {
706
+ const _events = {
707
+ async disconnected(eresult, msg) {
708
+ state = "Offline";
709
+ log("disconnected", eresult, msg);
710
+
711
+ callEvent(events.disconnected, { eresult, msg });
712
+
713
+ if (["ServiceUnavailable", "NoConnection"].includes(msg) && autoReconnect && !isLogOff) {
714
+ async function relogin(retry) {
715
+ if (isLogOff) {
716
+ console.error("Cannot relogin (logoff)");
717
+ return false;
718
+ } else if (retry <= 0) {
719
+ console.error("Cannot relogin");
720
+ return false;
721
+ } else {
722
+ const isSuccess = await login(true);
723
+ if (isSuccess) {
724
+ const loggedOnResponse = await new Promise((resolve) => {
725
+ onEvent("loggedOn", resolve, true, 180000);
726
+ });
727
+ if (loggedOnResponse) {
728
+ console.log("Relogin success");
729
+ return true;
730
+ } else {
731
+ const isLogOff = await new Promise((resolve, reject) => {
732
+ logOffEvent = resolve;
733
+ setTimeout(resolve, 120000);
734
+ });
735
+ logOffEvent = null;
736
+ if (isLogOff === true) {
737
+ return false;
738
+ }
739
+ return await relogin(retry - 1);
740
+ }
741
+ } else {
742
+ const isLogOff = await new Promise((resolve, reject) => {
743
+ logOffEvent = resolve;
744
+ setTimeout(resolve, 120000);
745
+ });
746
+ logOffEvent = null;
747
+ if (isLogOff === true) {
748
+ return false;
749
+ }
750
+ return await relogin(retry - 1);
751
+ }
752
+ }
753
+ }
754
+
755
+ const isLogOff = await new Promise((resolve, reject) => {
756
+ logOffEvent = resolve;
757
+ setTimeout(resolve, 60000);
758
+ });
759
+ logOffEvent = null;
760
+ if (isLogOff === true) {
761
+ offAllEvent();
762
+ doClearIntervals();
763
+ } else {
764
+ const isSuccess = await relogin(50);
765
+ if (!isSuccess) {
766
+ offAllEvent();
767
+ doClearIntervals();
768
+ }
769
+ }
770
+ } else {
771
+ offAllEvent();
772
+ doClearIntervals();
773
+ }
774
+ },
775
+ async error(e) {
776
+ let errorStr = "";
777
+ switch (e.eresult) {
778
+ case 5:
779
+ errorStr = "Invalid Password";
780
+ break;
781
+ case 6:
782
+ case 34:
783
+ errorStr = "Logged In Elsewhere";
784
+ break;
785
+ case 84:
786
+ errorStr = "Rate Limit Exceeded";
787
+ break;
788
+ case 65:
789
+ errorStr = "steam guard is invalid";
790
+ break;
791
+ default:
792
+ errorStr = `Unknown: ${e.eresult}`;
793
+ break;
794
+ }
795
+ log(`error [isLogOff: ${isLogOff}]`, e?.message);
796
+ doClearIntervals();
797
+ callEvent(events.error, { eresult: e.eresult, msg: e.message, error: errorStr });
798
+ },
799
+ async webSession(sessionID, cookies) {
800
+ const webSession = { sessionID, cookies };
801
+ steamClient.webSession = webSession;
802
+ callEvent(events.webSession, webSession);
803
+ },
804
+ async receivedFromGC(appid, msgType, payload) {
805
+ const key = getECsgoGCMsgKey(msgType);
806
+ switch (msgType) {
807
+ case Protos.csgo.EMsg.k_EMsgClientChatInvite: {
808
+ log(payload);
809
+ break;
810
+ }
811
+ case Protos.csgo.ECsgoGCMsg.k_EMsgClientMMSJoinLobbyResponse: {
812
+ const msg = protoDecode(Protos.csgo.CMsgClientMMSJoinLobbyResponse, payload);
813
+ log(msg);
814
+ break;
815
+ }
816
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Invite: {
817
+ const msg = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Party_Invite, payload);
818
+ const sid64 = SteamID.fromIndividualAccountID(msg.accountid).getSteamID64();
819
+ if (events.partyInvite?.length) {
820
+ const personas = await getPersonas([sid64]);
821
+ const player_name = personas.find((p) => p.id == sid64)?.player_name;
822
+ if (player_name === undefined) {
823
+ log(sid64, personas);
824
+ }
825
+ callEvent(events.partyInvite, { player_name, steamId: sid64, lobbyId: msg.lobbyid });
826
+ }
827
+ // log(player_name, `https://steamcommunity.com/profiles/${sid64}`);
828
+ // joinLobby(msg.lobbyid, msg.accountid)
829
+ break;
830
+ }
831
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Account_RequestCoPlays: {
832
+ const msg = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Account_RequestCoPlays, payload);
833
+ const personas = msg.players.map((p) => SteamID.fromIndividualAccountID(p.accountid));
834
+ callGCCallback("RequestCoPlays", personas);
835
+ break;
836
+ }
837
+ case Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientWelcome: {
838
+ prime = false;
839
+ const CMsgClientWelcome = protoDecode(Protos.csgo.CMsgClientWelcome, payload);
840
+ const obj = {};
841
+ for (const outofdate_cache of CMsgClientWelcome.outofdate_subscribed_caches) {
842
+ for (const cache_object of outofdate_cache.objects) {
843
+ for (const object_data of cache_object.object_data) {
844
+ switch (cache_object.type_id) {
845
+ case 1: {
846
+ const result = protoDecode(Protos.csgo.CSOEconItem, object_data);
847
+ result.id = result.id.toNumber();
848
+ result.original_id = result.original_id.toNumber();
849
+ if (!obj.items) {
850
+ obj.items = {};
851
+ }
852
+ obj.items[result.id] = result;
853
+ break;
854
+ }
855
+ case 2: {
856
+ const result = protoDecode(Protos.csgo.CSOPersonaDataPublic, object_data);
857
+ obj.PersonaDataPublic = result;
858
+ const example = {
859
+ player_level: 4, //CSGO_Profile_Rank
860
+ commendation: {
861
+ cmd_friendly: 149,
862
+ cmd_teaching: 108,
863
+ cmd_leader: 115,
864
+ },
865
+ elevated_state: true,
866
+ };
867
+ break;
868
+ }
869
+ case 5: {
870
+ const result = protoDecode(Protos.csgo.CSOItemRecipe, object_data);
871
+ break;
872
+ }
873
+ case 7: {
874
+ const CSOEconGameAccountClient = protoDecode(Protos.csgo.CSOEconGameAccountClient, object_data);
875
+ const CSOEconGameAccountClientExample = {
876
+ additional_backpack_slots: 0,
877
+ bonus_xp_timestamp_refresh: 1688518800, //Wednesday 1:00:00 AM every week
878
+ bonus_xp_usedflags: 19,
879
+ elevated_state: 5,
880
+ elevated_timestamp: 5,
881
+ }; //1688518800
882
+ if ((CSOEconGameAccountClient.bonus_xp_usedflags & 16) != 0) {
883
+ // EXPBonusFlag::PrestigeEarned
884
+ prime = true;
885
+ CSOEconGameAccountClient.prime = true;
886
+ }
887
+ if (CSOEconGameAccountClient.elevated_state === 5) {
888
+ // bought prime
889
+ prime = true;
890
+ CSOEconGameAccountClient.prime = true;
891
+ }
892
+ obj.GameAccountClient = CSOEconGameAccountClient;
893
+ break;
894
+ }
895
+
896
+ case 35: {
897
+ // const result =protoDecode(Protos.csgo.CSOSelectedItemPreset, object_data);
898
+ break;
899
+ }
900
+
901
+ case 36: {
902
+ // const result =protoDecode(Protos.csgo.CSOEconItemPresetInstance, object_data);
903
+ break;
904
+ }
905
+ case 38: {
906
+ const result = protoDecode(Protos.csgo.CSOEconItemDropRateBonus, object_data);
907
+ break;
908
+ }
909
+ case 39: {
910
+ const result = protoDecode(Protos.csgo.CSOEconItemLeagueViewPass, object_data);
911
+ break;
912
+ }
913
+ case 40: {
914
+ const result = protoDecode(Protos.csgo.CSOEconItemEventTicket, object_data);
915
+ break;
916
+ }
917
+ case 41: {
918
+ const result = protoDecode(Protos.csgo.CSOAccountSeasonalOperation, object_data);
919
+ break;
920
+ }
921
+ case 42: {
922
+ // const result =protoDecode(Protos.csgo.CSOEconItemTournamentPassport, object_data);
923
+ break;
924
+ }
925
+ case 43: {
926
+ const result = protoDecode(Protos.csgo.CSOEconDefaultEquippedDefinitionInstanceClient, object_data);
927
+ const example = {
928
+ account_id: 1080136620,
929
+ item_definition: 61,
930
+ class_id: 3,
931
+ slot_id: 2,
932
+ };
933
+ break;
934
+ }
935
+ case 45: {
936
+ const result = protoDecode(Protos.csgo.CSOEconCoupon, object_data);
937
+ break;
938
+ }
939
+ case 46: {
940
+ const result = protoDecode(Protos.csgo.CSOQuestProgress, object_data);
941
+ break;
942
+ }
943
+ case 4: {
944
+ const result = protoDecode(Protos.csgo.CSOAccountItemPersonalStore, object_data);
945
+ result.generation_time = result.generation_time * 1000;
946
+ if (Array.isArray(result.items)) {
947
+ result.items = result.items.map((item) => item.toNumber());
948
+ }
949
+ obj.personalStore = result;
950
+ const redeemable_balance = result.redeemable_balance; //2, 0
951
+ //redeemable_balance 2: not yet claim
952
+ //redeemable_balance 0: claimed
953
+ break;
954
+ }
955
+
956
+ default: {
957
+ log("cache_object.type_id", cache_object.type_id);
958
+ }
959
+ }
960
+ }
961
+ }
962
+ }
963
+ callEvent(events.csgoOnline, obj);
964
+
965
+ if (isPartyRegister) {
966
+ partyRegister();
967
+ doSetInterval(
968
+ function () {
969
+ partyRegister();
970
+ },
971
+ [60000, 120000],
972
+ "autoPartyRegister",
973
+ );
974
+ }
975
+ break;
976
+ }
977
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingGC2ClientUpdate: {
978
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchmakingGC2ClientUpdate, payload);
979
+ break;
980
+ }
981
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GC2ClientGlobalStats: {
982
+ const result = protoDecode(Protos.csgo.CMsgClientUGSGetGlobalStatsResponse, payload);
983
+ break;
984
+ }
985
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientReportPlayer: {
986
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientReportPlayer, payload);
987
+ break;
988
+ }
989
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GC2ClientTextMsg: {
990
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_GC2ClientTextMsg, payload);
991
+ break;
992
+ }
993
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello: {
994
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchmakingGC2ClientHello, payload);
995
+ const example = {
996
+ my_current_event_teams: [],
997
+ my_current_event_stages: [],
998
+ rankings: [],
999
+ account_id: 1080136620,
1000
+ ongoingmatch: null,
1001
+ global_stats: {
1002
+ search_statistics: [
1003
+ {
1004
+ game_type: 520,
1005
+ search_time_avg: 0,
1006
+ players_searching: 5141,
1007
+ },
1008
+ {
1009
+ game_type: 32776,
1010
+ search_time_avg: 0,
1011
+ players_searching: 6561,
1012
+ },
1013
+ ],
1014
+ players_online: 617207,
1015
+ servers_online: 230638,
1016
+ players_searching: 13550,
1017
+ servers_available: 126352,
1018
+ ongoing_matches: 23264,
1019
+ search_time_avg: 95993,
1020
+ main_post_url: "*XA=https://blast.tv/live*XT=https://www.twitch.tv/blastpremier*XB=https://live.bilibili.com/35*XG=playcast://https://gotv.blast.tv/major-a*T=SGTAB*L=2@https://steamcommunity.com/broadcast/watch/76561199492362089",
1021
+ required_appid_version: 13879,
1022
+ pricesheet_version: 1688084844,
1023
+ twitch_streams_version: 2,
1024
+ active_tournament_eventid: 21,
1025
+ active_survey_id: 0,
1026
+ rtime32_cur: 0,
1027
+ rtime32_event_start: 0,
1028
+ },
1029
+ penalty_seconds: 0,
1030
+ penalty_reason: 0,
1031
+ vac_banned: 0,
1032
+ ranking: {
1033
+ account_id: 1080136620,
1034
+ rank_id: 10,
1035
+ wins: 209,
1036
+ rank_change: 0,
1037
+ rank_type_id: 6,
1038
+ tv_control: 0,
1039
+ },
1040
+ commendation: {
1041
+ cmd_friendly: 149,
1042
+ cmd_teaching: 108,
1043
+ cmd_leader: 115,
1044
+ },
1045
+ medals: null,
1046
+ my_current_event: null,
1047
+ my_current_team: null,
1048
+ survey_vote: 0,
1049
+ activity: null,
1050
+ player_level: 4,
1051
+ player_cur_xp: 327684501,
1052
+ player_xp_bonus_flags: 0,
1053
+ };
1054
+ if (result?.global_stats?.required_appid_version && (!CSGO_VER || result.global_stats.required_appid_version > CSGO_VER)) {
1055
+ CSGO_VER = result.global_stats.required_appid_version;
1056
+ }
1057
+ callEvent(events.csgoClientHello, result);
1058
+ break;
1059
+ }
1060
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientReportResponse: {
1061
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientReportResponse, payload);
1062
+ break;
1063
+ }
1064
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientCommendPlayerQueryResponse: {
1065
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientCommendPlayer, payload);
1066
+ break;
1067
+ }
1068
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_PlayerOverwatchCaseAssignment: {
1069
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_PlayerOverwatchCaseAssignment, payload);
1070
+ break;
1071
+ }
1072
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_MatchList: {
1073
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_MatchList, payload);
1074
+ break;
1075
+ }
1076
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_GetEventFavorites_Response: {
1077
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_GetEventFavorites_Response, payload);
1078
+ break;
1079
+ }
1080
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_StartAgreementSessionInGame: {
1081
+ break;
1082
+ }
1083
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_ClientDeepStats: {
1084
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_ClientDeepStats, payload);
1085
+ break;
1086
+ }
1087
+ case Protos.csgo.EGCBaseClientMsg.k_EMsgGCClientConnectionStatus: {
1088
+ const result = protoDecode(Protos.csgo.CMsgConnectionStatus, payload);
1089
+ break;
1090
+ }
1091
+ case Protos.csgo.EGCItemMsg.k_EMsgGCStoreGetUserDataResponse: {
1092
+ const result = protoDecode(Protos.csgo.CMsgStoreGetUserDataResponse, payload);
1093
+ break;
1094
+ }
1095
+ case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseFinalizeResponse: {
1096
+ const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseFinalizeResponse, payload);
1097
+ break;
1098
+ }
1099
+ case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseCancelResponse: {
1100
+ const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseCancelResponse, payload);
1101
+ break;
1102
+ }
1103
+ case Protos.csgo.EGCItemMsg.k_EMsgGCStorePurchaseInitResponse: {
1104
+ const result = protoDecode(Protos.csgo.CMsgGCStorePurchaseInitResponse, payload);
1105
+ break;
1106
+ }
1107
+ case Protos.csgo.EMsg.k_EMsgClientMMSCreateLobbyResponse: {
1108
+ const result = protoDecode(Protos.csgo.CMsgClientMMSCreateLobbyResponse, payload);
1109
+ console.log("k_EMsgClientMMSCreateLobbyResponse", result);
1110
+ break;
1111
+ }
1112
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientGCRankUpdate: {
1113
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientGCRankUpdate, payload);
1114
+ break;
1115
+ }
1116
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Search: {
1117
+ const result = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_Party_SearchResults, payload);
1118
+ const entries = _.uniqBy(result.entries, "id");
1119
+ //{
1120
+ // id: 144900402,
1121
+ // grp: 0,
1122
+ // game_type: 8,
1123
+ // apr: 1,
1124
+ // ark: 17,
1125
+ // loc: 20041,
1126
+ // accountid: 0
1127
+ // }
1128
+
1129
+ //{
1130
+ // id: "76561199265943339",
1131
+ // rich_presence: [],
1132
+ // persona_state: null,
1133
+ // game_played_app_id: null,
1134
+ // game_server_ip: null,
1135
+ // game_server_port: null,
1136
+ // persona_state_flags: null,
1137
+ // online_session_instances: null,
1138
+ // persona_set_by_user: null,
1139
+ // player_name: "杀人不见血",
1140
+ // query_port: null,
1141
+ // steamid_source: null,
1142
+ // avatar_hash: "33994e26f1fe7e2093f8c7dee66c1ac91531050d",
1143
+ // last_logoff: null,
1144
+ // last_logon: null,
1145
+ // last_seen_online: null,
1146
+ // clan_rank: null,
1147
+ // game_name: null,
1148
+ // gameid: null,
1149
+ // game_data_blob: null,
1150
+ // clan_data: null,
1151
+ // clan_tag: null,
1152
+ // broadcast_id: null,
1153
+ // game_lobby_id: null,
1154
+ // watching_broadcast_accountid: null,
1155
+ // watching_broadcast_appid: null,
1156
+ // watching_broadcast_viewers: null,
1157
+ // watching_broadcast_title: null,
1158
+ // is_community_banned: null,
1159
+ // player_name_pending_review: null,
1160
+ // avatar_pending_review: null,
1161
+ // avatar_url_icon: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d.jpg",
1162
+ // avatar_url_medium: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d_medium.jpg",
1163
+ // avatar_url_full: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/33/33994e26f1fe7e2093f8c7dee66c1ac91531050d_full.jpg"
1164
+ // }
1165
+
1166
+ const players = [];
1167
+ for (const player of entries) {
1168
+ try {
1169
+ const prime = player.apr === 1 ? "PRIME" : "NON-PRIME";
1170
+ const loc = LOCS[player.loc] || player.loc;
1171
+ const steamId = SteamID.fromIndividualAccountID(player.id).getSteamID64();
1172
+ const friendCode = FriendCode.encode(steamId);
1173
+
1174
+ // if ((LOCS[player.loc] == 'VN' || !LOCS[player.loc])) {
1175
+ players.push({
1176
+ prime,
1177
+ rank: RANKS[player.ark] !== undefined ? RANKS[player.ark] : player.ark,
1178
+ loc,
1179
+ steamId,
1180
+ friendCode,
1181
+ });
1182
+ // }
1183
+ } catch (e) {}
1184
+ }
1185
+
1186
+ callGCCallback("partySearch", players);
1187
+ break;
1188
+ }
1189
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_PlayersProfile: {
1190
+ let data = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_PlayersProfile, payload)?.account_profiles;
1191
+ const dataExample = [
1192
+ {
1193
+ my_current_event_teams: [],
1194
+ my_current_event_stages: [],
1195
+ rankings: [
1196
+ {
1197
+ account_id: 1225887169,
1198
+ rank_id: 0,
1199
+ wins: 6,
1200
+ rank_change: 0,
1201
+ rank_type_id: 7,
1202
+ tv_control: 0,
1203
+ },
1204
+ {
1205
+ account_id: 1225887169,
1206
+ rank_id: 0,
1207
+ wins: 0,
1208
+ rank_change: 0,
1209
+ rank_type_id: 10,
1210
+ tv_control: 0,
1211
+ },
1212
+ ],
1213
+ account_id: 1225887169,
1214
+ ongoingmatch: null,
1215
+ global_stats: null,
1216
+ penalty_seconds: 0,
1217
+ penalty_reason: 0,
1218
+ vac_banned: 0,
1219
+ ranking: {
1220
+ account_id: 1225887169,
1221
+ rank_id: 8,
1222
+ wins: 469,
1223
+ rank_change: 0,
1224
+ rank_type_id: 6,
1225
+ tv_control: 0,
1226
+ },
1227
+ commendation: {
1228
+ cmd_friendly: 51,
1229
+ cmd_teaching: 40,
1230
+ cmd_leader: 40,
1231
+ },
1232
+ medals: {
1233
+ display_items_defidx: [4819, 4737],
1234
+ featured_display_item_defidx: 4819,
1235
+ },
1236
+ my_current_event: null,
1237
+ my_current_team: null,
1238
+ survey_vote: 0,
1239
+ activity: null,
1240
+ player_level: 32,
1241
+ player_cur_xp: 327682846,
1242
+ player_xp_bonus_flags: 0,
1243
+ },
1244
+ ];
1245
+
1246
+ const player = data?.[0];
1247
+ if (player) {
1248
+ player.prime = !!(player.ranking?.account_id || player.player_level || player.player_cur_xp);
1249
+ player.steamId = SteamID.fromIndividualAccountID(player.account_id).getSteamID64();
1250
+ callGCCallback(`PlayersProfile_${player.account_id}`, player);
1251
+ }
1252
+ callEvent(events.playersProfile, player);
1253
+ break;
1254
+ }
1255
+ case Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientLogonFatalError: {
1256
+ const data = protoDecode(Protos.csgo.CMsgGCCStrike15_v2_ClientLogonFatalError, payload);
1257
+ const dataExample = {
1258
+ errorcode: 4,
1259
+ message: "",
1260
+ country: "VN",
1261
+ };
1262
+ callEvent(events.fatalError, data);
1263
+ break;
1264
+ }
1265
+ default:
1266
+ log(`receivedFromGC ${msgType} ${key}`);
1267
+ const results = Object.values(Protos.csgo)
1268
+ .map(function (p) {
1269
+ try {
1270
+ return protoDecode(p, payload);
1271
+ } catch (e) {}
1272
+ })
1273
+ .filter(function (result) {
1274
+ return result && Object.keys(result).length;
1275
+ });
1276
+ log(key, results);
1277
+ }
1278
+ },
1279
+ async loggedOn(loggedOnResponse) {
1280
+ callEvent(events.loggedOn, loggedOnResponse);
1281
+ updateInvisible();
1282
+ updateAutoRequestFreeLicense();
1283
+ updateAutoGamePlay();
1284
+ },
1285
+ async user(steamId, data) {
1286
+ callEvent(events.user, { steamId: steamId.getSteamID64(), data });
1287
+ const dataExample = {
1288
+ rich_presence: [
1289
+ {
1290
+ key: "status",
1291
+ value: "Competitive Mirage [ 3 : 6 ]",
1292
+ },
1293
+ {
1294
+ key: "version",
1295
+ value: "13875",
1296
+ },
1297
+ {
1298
+ key: "game:state",
1299
+ value: "game",
1300
+ },
1301
+ {
1302
+ key: "steam_display",
1303
+ value: "#display_GameKnownMapScore",
1304
+ },
1305
+ {
1306
+ key: "game:mode",
1307
+ value: "competitive",
1308
+ },
1309
+ {
1310
+ key: "game:mapgroupname",
1311
+ value: "mg_de_mirage",
1312
+ },
1313
+ {
1314
+ key: "game:map",
1315
+ value: "de_mirage",
1316
+ },
1317
+ {
1318
+ key: "game:server",
1319
+ value: "kv",
1320
+ },
1321
+ {
1322
+ key: "watch",
1323
+ value: "1",
1324
+ },
1325
+ {
1326
+ key: "steam_player_group",
1327
+ value: "2134948645",
1328
+ },
1329
+ {
1330
+ key: "game:score",
1331
+ value: "[ 3 : 6 ]",
1332
+ },
1333
+ ],
1334
+ friendid: "76561199405834425",
1335
+ persona_state: 1,
1336
+ game_played_app_id: 730,
1337
+ game_server_ip: null,
1338
+ game_server_port: null,
1339
+ persona_state_flags: 1,
1340
+ online_session_instances: 1,
1341
+ persona_set_by_user: null,
1342
+ player_name: "quỷ súng",
1343
+ query_port: null,
1344
+ steamid_source: "0",
1345
+ avatar_hash: {
1346
+ type: "Buffer",
1347
+ data: [23, 163, 216, 209, 236, 179, 73, 228, 225, 30, 48, 190, 192, 170, 177, 246, 139, 71, 122, 205],
1348
+ },
1349
+ last_logoff: 1683950268,
1350
+ last_logon: 1683950281,
1351
+ last_seen_online: 1683950268,
1352
+ clan_rank: null,
1353
+ game_name: "",
1354
+ gameid: "730",
1355
+ game_data_blob: {
1356
+ type: "Buffer",
1357
+ data: [],
1358
+ },
1359
+ clan_data: null,
1360
+ clan_tag: null,
1361
+ broadcast_id: "0",
1362
+ game_lobby_id: "0",
1363
+ watching_broadcast_accountid: null,
1364
+ watching_broadcast_appid: null,
1365
+ watching_broadcast_viewers: null,
1366
+ watching_broadcast_title: null,
1367
+ is_community_banned: null,
1368
+ player_name_pending_review: null,
1369
+ avatar_pending_review: null,
1370
+ };
1371
+ },
1372
+ async playingState(playing_blocked, playing_app) {
1373
+ playingBlocked = playing_blocked;
1374
+ if (playing_app === 0) {
1375
+ playing_app = null;
1376
+ }
1377
+ if (playing_blocked) {
1378
+ //true, false
1379
+ console.log("Playing else where");
1380
+ }
1381
+ log("playingState", playing_blocked, playing_app);
1382
+ callEvent(events.playingState, { playing_blocked, playing_app });
1383
+ },
1384
+ async friendRelationship(sid, relationship, previousRelationship) {
1385
+ callEvent(events.friendRelationship, {
1386
+ steamId: sid.getSteamID64(),
1387
+ relationship,
1388
+ previousRelationship,
1389
+ });
1390
+ switch (relationship) {
1391
+ case EFriendRelationship.None: {
1392
+ //we got unfriended.
1393
+ break;
1394
+ }
1395
+ case EFriendRelationship.RequestRecipient: {
1396
+ //we got invited as a friend
1397
+ break;
1398
+ }
1399
+ case EFriendRelationship.Friend: {
1400
+ //we got added as a friend
1401
+ break;
1402
+ }
1403
+ }
1404
+ },
1405
+ async tradeOffers(count) {
1406
+ callEvent(events.tradeOffers, count);
1407
+ },
1408
+ async offlineMessages(count, friends) {
1409
+ callEvent(events.offlineMessages, { count, steamIdList: friends });
1410
+ },
1411
+ async tradeRequest(steamID, respond) {
1412
+ if (autoAcceptTradeRequest) {
1413
+ log(`Incoming trade request from ${steamID.getSteam3RenderedID()}, accepting`);
1414
+ respond(true);
1415
+ } else {
1416
+ log(`Incoming trade request from ${steamID.getSteam3RenderedID()}, wating`);
1417
+ }
1418
+ },
1419
+ async friendsList() {
1420
+ callEvent(events.friendsList, getFriendList());
1421
+ },
1422
+ async gifts(gid, packageid, TimeCreated, TimeExpiration, TimeSent, TimeAcked, TimeRedeemed, RecipientAddress, SenderAddress, SenderName) {
1423
+ callEvent(events.gifts, {
1424
+ gid,
1425
+ packageid,
1426
+ TimeCreated,
1427
+ TimeExpiration,
1428
+ TimeSent,
1429
+ TimeAcked,
1430
+ TimeRedeemed,
1431
+ RecipientAddress,
1432
+ SenderAddress,
1433
+ SenderName,
1434
+ });
1435
+ },
1436
+ async emailInfo(address, validated) {
1437
+ callEvent(events.emailInfo, { address, validated });
1438
+ },
1439
+ async appLaunched() {
1440
+ setTimeout(function () {
1441
+ state = getPlayingAppIds().length ? "InGame" : isInvisible ? "Invisible" : "Online";
1442
+ }, 1000);
1443
+ },
1444
+ async appQuit() {
1445
+ setTimeout(function () {
1446
+ state = getPlayingAppIds().length ? "InGame" : isInvisible ? "Invisible" : "Online";
1447
+ }, 1000);
1448
+ },
1449
+ async accountLimitations(bis_limited_account, bis_community_banned, bis_locked_account, bis_limited_account_allowed_to_invite_friends) {
1450
+ callEvent(events.accountLimitations, {
1451
+ limited: bis_limited_account,
1452
+ communityBanned: bis_community_banned,
1453
+ locked: bis_locked_account,
1454
+ canInviteFriends: bis_limited_account_allowed_to_invite_friends,
1455
+ });
1456
+ },
1457
+ };
1458
+
1459
+ const _chatEvents = {
1460
+ async friendMessage(data) {
1461
+ if (!data) return;
1462
+ data.message_no_bbcode = data.message_no_bbcode?.replaceAll("ː", ":");
1463
+ data.message = data.message?.replaceAll("ː", ":");
1464
+ const example = {
1465
+ steamid_friend: {
1466
+ universe: 1,
1467
+ type: 1,
1468
+ instance: 1,
1469
+ accountid: 1080136620,
1470
+ },
1471
+ chat_entry_type: 1,
1472
+ from_limited_account: false,
1473
+ message: "xxx",
1474
+ ordinal: 0,
1475
+ local_echo: false,
1476
+ message_no_bbcode: "xxx",
1477
+ low_priority: false,
1478
+ server_timestamp: "2023-05-14T09:26:25.000Z",
1479
+ message_bbcode_parsed: ["xxx"],
1480
+ };
1481
+ const timestamp = new Date(data.server_timestamp).getTime();
1482
+ const steamId = data.steamid_friend.getSteamID64();
1483
+ const invite = ["Invited you to play a game!", "Đã mời bạn chơi một trò chơi!"].includes(data.message_no_bbcode || data.message);
1484
+ const emotion = (data.message_no_bbcode || "").split(" ").find((m) => m.startsWith(":") && m.endsWith(":"));
1485
+
1486
+ callEvent(events.friendMessage, {
1487
+ ...data,
1488
+ message: data.message_no_bbcode,
1489
+ invite,
1490
+ steamId,
1491
+ timestamp,
1492
+ emotion,
1493
+ });
1494
+ },
1495
+ async friendTyping(steamId, message) {
1496
+ callEvent(events.friendTyping, {
1497
+ steamId,
1498
+ message,
1499
+ });
1500
+ },
1501
+ };
1502
+
1503
+ // steamClient.on('lobbyInvite', (inviterID, lobbyID ) => {
1504
+ // joinLobby(lobbyID)
1505
+ // })
1506
+
1507
+ // steamClient.on('debug', (msg) => {
1508
+ // if (!["ClientPersonaState","ClientClanState"].some(c => msg.includes(c))) {
1509
+ // if(msg.startsWith("Received")){
1510
+ // console.log(`------- ${msg}`)
1511
+ // } else {
1512
+ // console.log(msg)
1513
+ // }
1514
+ // }
1515
+ // })
1516
+
1517
+ function getECsgoGCMsgKey(_key) {
1518
+ for (let key in Protos.csgo.ECsgoGCMsg) {
1519
+ if (Protos.csgo.ECsgoGCMsg[key] == _key) {
1520
+ return key;
1521
+ }
1522
+ }
1523
+ for (let key in Protos.csgo.EGCBaseClientMsg) {
1524
+ if (Protos.csgo.EGCBaseClientMsg[key] == _key) {
1525
+ return key;
1526
+ }
1527
+ }
1528
+ for (let key in Protos.csgo.EMsg) {
1529
+ if (Protos.csgo.EMsg[key] == _key) {
1530
+ return key;
1531
+ }
1532
+ }
1533
+ for (let key in Protos.csgo.EGCItemMsg) {
1534
+ if (Protos.csgo.EGCItemMsg[key] == _key) {
1535
+ return key;
1536
+ }
1537
+ }
1538
+ }
1539
+
1540
+ for (const [name, _event] of Object.entries(_events)) {
1541
+ steamClient.on(name, _event);
1542
+ }
1543
+
1544
+ for (const [name, _event] of Object.entries(_chatEvents)) {
1545
+ steamClient.chat.on(name, _event);
1546
+ }
1547
+ }
1548
+
1549
+ function getHandlerResult(msg, handler) {
1550
+ const timeout = { current: null };
1551
+ return new Promise((resolve) => {
1552
+ function myhandler(...args) {
1553
+ timeout.current && clearTimeout(timeout.current);
1554
+ removeHandler();
1555
+ resolve(handler?.(...args));
1556
+ }
1557
+
1558
+ function removeHandler() {
1559
+ if (Array.isArray(steamClient._handlerManager._handlers[msg])) {
1560
+ const index = steamClient._handlerManager._handlers[msg].findIndex((_handler) => _handler === myhandler);
1561
+ if (index > -1) {
1562
+ steamClient._handlerManager._handlers[msg].splice(index, 1);
1563
+ }
1564
+ }
1565
+ }
1566
+
1567
+ timeout.current = setTimeout(function () {
1568
+ removeHandler();
1569
+ resolve();
1570
+ }, 60000);
1571
+ steamClient._handlerManager.add(msg, myhandler);
1572
+ });
1573
+ }
1574
+
1575
+ function getFriendList() {
1576
+ return Object.keys(steamClient.myFriends).filter((steamId) => steamClient.myFriends[steamId] === NodeSteamUser.EFriendRelationship.Friend);
1577
+ }
1578
+
1579
+ function sendFriendTyping(steamId, callback) {
1580
+ steamClient.chat.sendFriendTyping(steamId, callback);
1581
+ }
1582
+
1583
+ /*
1584
+ * usually take 400 -> 800 miliseconds
1585
+ * */
1586
+ function getPlayersProfile(steamId) {
1587
+ const accountid = new SteamID(steamId).accountid;
1588
+ steamClient.sendToGC(
1589
+ 730,
1590
+ Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_ClientRequestPlayersProfile,
1591
+ {},
1592
+ protoEncode(Protos.csgo.CMsgGCCStrike15_v2_ClientRequestPlayersProfile, {
1593
+ account_id: accountid, // account_id: new SteamID('76561199184696945').accountid,
1594
+ request_level: 32,
1595
+ }),
1596
+ );
1597
+ return new Promise((resolve) => {
1598
+ pushGCCallback(`PlayersProfile_${accountid}`, resolve, 2000);
1599
+ });
1600
+ }
1601
+
1602
+ async function checkPlayerPrimeStatus(steamId) {
1603
+ const profile = await getPlayersProfile(steamId);
1604
+ if (!profile) return false;
1605
+
1606
+ if (profile.ranking?.account_id) {
1607
+ return true;
1608
+ }
1609
+
1610
+ if (profile.player_level || profile.player_cur_xp) {
1611
+ return true;
1612
+ }
1613
+ return false;
1614
+ }
1615
+
1616
+ async function _getStoreSteamPoweredResponse(cookie) {
1617
+ let response = null;
1618
+ for (let i = 0; i < 50; i++) {
1619
+ if (!response) {
1620
+ try {
1621
+ response = await axios.request({
1622
+ url: "https://store.steampowered.com/",
1623
+ headers: {
1624
+ cookie,
1625
+ accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.75",
1626
+ },
1627
+ });
1628
+ } catch (e) {
1629
+ await sleep(1000);
1630
+ }
1631
+ }
1632
+ }
1633
+ return response;
1634
+ }
1635
+
1636
+ async function getNewCookie(cookie) {
1637
+ if (!cookie) {
1638
+ return;
1639
+ }
1640
+ let response = await _getStoreSteamPoweredResponse(cookie);
1641
+ if (!response) {
1642
+ return;
1643
+ }
1644
+ while (Array.isArray(response?.headers?.["set-cookie"])) {
1645
+ console.log(cookie);
1646
+ const cookieObj = cookie.split(";").reduce(function (accumulator, currentValue) {
1647
+ accumulator[currentValue.trim().split("=")[0].trim()] = currentValue.trim().split("=")[1].trim();
1648
+ return accumulator;
1649
+ }, {});
1650
+ for (const mcookie of response.headers["set-cookie"]) {
1651
+ const name = mcookie.split("=")[0].trim();
1652
+ const value = mcookie.split("=")[1].split(";")[0].trim();
1653
+ cookieObj[name] = value;
1654
+ }
1655
+ cookie = Object.keys(cookieObj)
1656
+ .map((name) => `${name}=${cookieObj[name]}`)
1657
+ .join(";");
1658
+ response = await _getStoreSteamPoweredResponse(cookie);
1659
+ }
1660
+ return cookie;
1661
+ }
1662
+
1663
+ async function loginWithCookie(cookie, tryNewCookie = false) {
1664
+ let response;
1665
+ for (let i = 0; i < 20; i++) {
1666
+ try {
1667
+ response = await axios.request({
1668
+ url: "https://steamcommunity.com/chat/clientjstoken",
1669
+ headers: {
1670
+ cookie,
1671
+ },
1672
+ });
1673
+ } catch (e) {
1674
+ await sleep(1000);
1675
+ }
1676
+ if (response) {
1677
+ break;
1678
+ }
1679
+ }
1680
+
1681
+ const result = response?.data;
1682
+ if (result?.logged_in) {
1683
+ Object.assign(result, {
1684
+ steamID: new SteamID(result.steamid),
1685
+ accountName: result.account_name,
1686
+ webLogonToken: result.token,
1687
+ });
1688
+ steamClient.logOn(result);
1689
+ return cookie;
1690
+ } else {
1691
+ if (tryNewCookie) {
1692
+ log("You are not logged in", cookie);
1693
+ return null;
1694
+ } else {
1695
+ const newCookie = await getNewCookie(cookie);
1696
+ if (!newCookie) {
1697
+ console.error("Cannot get new cookie");
1698
+ return null;
1699
+ } else {
1700
+ return await loginWithCookie(newCookie, true);
1701
+ }
1702
+ }
1703
+ }
1704
+ }
1705
+
1706
+ async function login(reconnect = false) {
1707
+ function logOn(clientJsToken) {
1708
+ try {
1709
+ steamClient.logOn({
1710
+ ...clientJsToken,
1711
+ steamId: new SteamID(clientJsToken.steamid),
1712
+ steamID: new SteamID(clientJsToken.steamid),
1713
+ accountName: clientJsToken.account_name,
1714
+ webLogonToken: clientJsToken.token,
1715
+ });
1716
+ return true;
1717
+ } catch (e) {
1718
+ console.error(e);
1719
+ return false;
1720
+ }
1721
+ }
1722
+
1723
+ if (clientJsToken?.logged_in === true) {
1724
+ log(reconnect ? "reconnect with clientJsToken" : "login with clientJsToken");
1725
+ setTimeout(function () {
1726
+ clientJsToken = null;
1727
+ }, 1000);
1728
+ return logOn(clientJsToken);
1729
+ } else if (cookie) {
1730
+ log(reconnect ? "reconnect with cookie" : "login with cookie");
1731
+ const steamUser = new SteamUser(typeof cookie === "function" ? await cookie() : cookie);
1732
+ const _clientJsToken = await steamUser.getClientJsToken();
1733
+ if (_clientJsToken?.logged_in === true) {
1734
+ return logOn(_clientJsToken);
1735
+ } else {
1736
+ log(`Account not logged in ${clientJsToken?.account_name || steamUser.getSteamIdUser() || ""}`);
1737
+ console.log(clientJsToken);
1738
+ return false;
1739
+ }
1740
+ } else if (username && password) {
1741
+ log(reconnect ? `reconnect with username ${username}` : `login with username ${username}`);
1742
+ steamClient.logOn({
1743
+ accountName: username,
1744
+ password: password,
1745
+ rememberPassword: true,
1746
+ machineName: "Natri",
1747
+ });
1748
+ return true;
1749
+ } else {
1750
+ log(`Account not logged in ${clientJsToken?.account_name || ""}`);
1751
+ return false;
1752
+ }
1753
+ }
1754
+
1755
+ function logOff() {
1756
+ isLogOff = true;
1757
+ logOffEvent?.(true);
1758
+ steamClient.logOff();
1759
+ }
1760
+
1761
+ function onCookie(callback) {
1762
+ if (getCookies()) {
1763
+ callback(getCookies());
1764
+ } else {
1765
+ onEvent(
1766
+ "webSession",
1767
+ function (webSession) {
1768
+ callback(webSession?.cookies?.join?.(";"));
1769
+ },
1770
+ true,
1771
+ );
1772
+ }
1773
+ }
1774
+
1775
+ async function init() {
1776
+ bindEvent();
1777
+ if (await login()) {
1778
+ steamClient._handlerManager.add(Protos.csgo.EMsg.k_EMsgClientRequestedClientStats, function (payload) {
1779
+ const result = protoDecode(Protos.csgo.CMsgClientRequestedClientStats, payload.toBuffer());
1780
+ // console.log("CMsgClientRequestedClientStats", result);
1781
+ });
1782
+ steamClient._handlerManager.add(Protos.csgo.EMsg.k_EMsgClientMMSLobbyData, function (payload) {
1783
+ const result = protoDecode(Protos.csgo.CMsgClientMMSLobbyData, payload.toBuffer());
1784
+ // console.log("CMsgClientMMSLobbyData", result, result.metadata);
1785
+ });
1786
+ }
1787
+ }
1788
+
1789
+ function partyRegister() {
1790
+ if (prime === null) {
1791
+ _partyRegister(true);
1792
+ _partyRegister(false);
1793
+ } else {
1794
+ _partyRegister(prime);
1795
+ }
1796
+ }
1797
+
1798
+ function _partyRegister(prime) {
1799
+ log("partyRegister", prime);
1800
+ lastTimePartyRegister = new Date().getTime();
1801
+ steamClient.sendToGC(
1802
+ 730,
1803
+ Protos.csgo.ECsgoGCMsg.k_EMsgGCCStrike15_v2_Party_Register,
1804
+ {},
1805
+ protoEncode(Protos.csgo.CMsgGCCStrike15_v2_Party_Register, {
1806
+ // id : 0,
1807
+ ver: CSGO_VER,
1808
+ apr: prime ? 1 : 0, //prime
1809
+ ark: prime ? 180 : 0,
1810
+ grps: [],
1811
+ launcher: 0,
1812
+ game_type: 8,
1813
+ }),
1814
+ );
1815
+ }
1816
+
1817
+ async function sendFriendMessage(steamId, message) {
1818
+ while (sendMessageTimestamp && new Date().getTime() - sendMessageTimestamp < 2000) {
1819
+ await sleep(1000);
1820
+ }
1821
+
1822
+ while (isSendingFriendMessages) {
1823
+ await sleep(5000);
1824
+ }
1825
+
1826
+ isSendingFriendMessages = true;
1827
+ const now = new Date().getTime();
1828
+ while (new Date().getTime() - now < 2 * 60000) {
1829
+ //2 minutes
1830
+ const result = await new Promise((resolve) => {
1831
+ steamClient.chat.sendFriendMessage(steamId, message, undefined, function (...arg) {
1832
+ sendMessageTimestamp = new Date().getTime();
1833
+ resolve(arg);
1834
+ });
1835
+ });
1836
+
1837
+ if (result?.[1]?.server_timestamp) {
1838
+ isSendingFriendMessages = false;
1839
+ return result?.[1];
1840
+ } else if (result?.[0]?.message?.includes?.("RateLimitExceeded")) {
1841
+ await sleep(5000);
1842
+ } else {
1843
+ isSendingFriendMessages = false;
1844
+ return result;
1845
+ }
1846
+ }
1847
+ isSendingFriendMessages = false;
1848
+ }
1849
+
1850
+ async function autoRequestFreeLicense(shouldLog = false, max = 10) {
1851
+ return;
1852
+ // const mCookies = await getCookiesWait()
1853
+ // if (!mCookies) return
1854
+ // let freeAppList = Array.isArray(steamClient.licenses) ? FreeAppList.filter(appId => steamClient.licenses.every(({package_id}) => package_id !== appId)) : FreeAppList;
1855
+ const freeAppList = freeAppList.filter((appId) => ownedApps.some((app) => app.appid == appId));
1856
+ const recommendedApps = _.shuffle(freeAppList);
1857
+ if (max) {
1858
+ recommendedApps.length = Math.min(recommendedApps.length, max);
1859
+ }
1860
+ try {
1861
+ const response = await steamClient.requestFreeLicense(recommendedApps);
1862
+ if (shouldLog) {
1863
+ log(response);
1864
+ }
1865
+ } catch (e) {
1866
+ log(e);
1867
+ }
1868
+ // if (Math.random() > 0.7) {
1869
+ // for (const recommendedApp of recommendedApps) {
1870
+ // try {
1871
+ // await steamUtils.requestFreeLicense(recommendedApp)
1872
+ // } catch (e) {
1873
+ // }
1874
+ // await sleep(2000)
1875
+ // }
1876
+ // } else {
1877
+ // try {
1878
+ // await steamClient.requestFreeLicense(recommendedApps)
1879
+ // } catch (e) {
1880
+ // log(e);
1881
+ // }
1882
+ // }
1883
+
1884
+ // if (shouldLog) {
1885
+ // await sleep(20000)
1886
+ // const ownedAppsCount2 = (await steamUtils.getDynamicStoreUserData())?.rgOwnedApps?.length || 0
1887
+ // const increaseNumber = ownedAppsCount2 - ownedAppsCount;
1888
+ // log(`OwnedApps length ${ownedAppsCount2}, increase ${increaseNumber}`)
1889
+ // }
1890
+ }
1891
+
1892
+ async function playCSGO() {
1893
+ try {
1894
+ await steamClient.requestFreeLicense(AppID);
1895
+ await sleep(5000);
1896
+ } catch (e) {}
1897
+ gamesPlayed(AppID);
1898
+ }
1899
+
1900
+ function doFakeGameScore() {
1901
+ const maxRound = Math.random() > 0.7 ? 16 : 12;
1902
+ const maps = [
1903
+ "ar_baggage",
1904
+ "ar_dizzy",
1905
+ "ar_monastery",
1906
+ "ar_shoots",
1907
+ "cs_agency",
1908
+ "cs_assault",
1909
+ "cs_italy",
1910
+ "cs_militia",
1911
+ "cs_office",
1912
+ "de_ancient",
1913
+ "de_anubis",
1914
+ "de_bank",
1915
+ "de_boyard",
1916
+ "de_cache",
1917
+ "de_canals",
1918
+ "de_cbble",
1919
+ "de_chalice",
1920
+ "de_dust2",
1921
+ "de_inferno",
1922
+ "de_lake",
1923
+ "de_mirage",
1924
+ "de_nuke",
1925
+ "de_overpass",
1926
+ "de_safehouse",
1927
+ // "de_shortnuke",
1928
+ "de_stmarc",
1929
+ "de_sugarcane",
1930
+ "de_train",
1931
+ "de_tuscan",
1932
+ "de_vertigo",
1933
+ "dz_ember",
1934
+ "dz_vineyard",
1935
+ "gd_cbble",
1936
+ "training1",
1937
+ ];
1938
+
1939
+ if (richPresence.myScore === undefined) {
1940
+ richPresence.myScore = _.random(0, maxRound);
1941
+ }
1942
+ if (richPresence.theirScore === undefined) {
1943
+ richPresence.theirScore = _.random(0, maxRound);
1944
+ }
1945
+ if (richPresence.map === undefined) {
1946
+ richPresence.map = maps[Math.floor(Math.random() * maps.length)];
1947
+ }
1948
+ if (richPresence.myScore === maxRound || richPresence.theirScore === maxRound) {
1949
+ richPresence.myScore = 0;
1950
+ richPresence.theirScore = 0;
1951
+ richPresence.map = maps[Math.floor(Math.random() * maps.length)];
1952
+ } else {
1953
+ const isMyTeamWin = Math.random() > 0.5;
1954
+ if (isMyTeamWin) {
1955
+ richPresence.myScore++;
1956
+ } else {
1957
+ richPresence.theirScore++;
1958
+ }
1959
+ }
1960
+
1961
+ const score = richPresence.myScore === 0 && richPresence.theirScore === 0 ? "" : `[ ${richPresence.myScore} : ${richPresence.theirScore} ]`;
1962
+ steamClient.uploadRichPresence(730, {
1963
+ "game:state": "game",
1964
+ steam_display: "#display_GameKnownMapScore",
1965
+ connect: "+gcconnectG082AA752",
1966
+ version: CSGO_VER.toString(),
1967
+ "game:mode": "competitive",
1968
+ "game:map": richPresence.map,
1969
+ "game:server": "kv",
1970
+ watch: _.random(1, 5).toString(),
1971
+ "game:score": score,
1972
+ });
1973
+ }
1974
+
1975
+ function updateFakeGameScore() {
1976
+ if (isFakeGameScore && getPlayingAppIds().some((a) => a == 730)) {
1977
+ doSetInterval(doFakeGameScore, [60000, 180000], "uploadRichPresenceCSGO");
1978
+ } else {
1979
+ doClearInterval("uploadRichPresenceCSGO");
1980
+ }
1981
+ }
1982
+
1983
+ function updateAutoRequestFreeLicense() {
1984
+ if (isAutoRequestFreeLicense) {
1985
+ doSetInterval(
1986
+ function () {
1987
+ autoRequestFreeLicense(false, 50);
1988
+ },
1989
+ [5 * 60000, 10 * 60000],
1990
+ "autoRequestFreeLicense",
1991
+ );
1992
+ } else {
1993
+ doClearInterval("autoRequestFreeLicense");
1994
+ }
1995
+ }
1996
+
1997
+ function updateInvisible() {
1998
+ if (isInvisible) {
1999
+ steamClient.setPersona(NodeSteamUser.EPersonaState.Invisible);
2000
+ state = "Invisible";
2001
+ } else {
2002
+ steamClient.setPersona(NodeSteamUser.EPersonaState.Online);
2003
+ state = "Online";
2004
+ }
2005
+ }
2006
+
2007
+ async function gamesPlayed(apps) {
2008
+ if (!Array.isArray(apps)) {
2009
+ apps = [apps];
2010
+ }
2011
+
2012
+ const processedApps = apps.map((app) => {
2013
+ if (typeof app == "string") {
2014
+ app = { game_id: "15190414816125648896", game_extra_info: app };
2015
+ } else if (typeof app === "number" || typeof app != "object") {
2016
+ app = { game_id: app };
2017
+ }
2018
+
2019
+ if (typeof app.game_ip_address == "number") {
2020
+ app.game_ip_address = { v4: app.game_ip_address };
2021
+ }
2022
+
2023
+ return app;
2024
+ });
2025
+
2026
+ steamClient.gamesPlayed(processedApps);
2027
+ if (processedApps.some((app) => parseInt(app.game_id) === 730)) {
2028
+ await sleep(500);
2029
+ await sendHello();
2030
+ }
2031
+ updateFakeGameScore();
2032
+
2033
+ // await sleep(10000)
2034
+ // self.steamUser.uploadRichPresence(730, {
2035
+ // status: 'bussssss',
2036
+ // 'game:state': 'lobby',
2037
+ // steam_display: '#display_watch',
2038
+ // currentmap: '#gamemap_de_empire',
2039
+ // connect: '+gcconnectG082AA752',
2040
+ // 'game:mode': 'competitive'
2041
+ // })
2042
+ }
2043
+
2044
+ function getFriendsList() {
2045
+ const methodName = "FriendsList.GetFriendsList#1";
2046
+ const { users, myFriends } = steamClient; //object
2047
+ /*
2048
+ users
2049
+ * {
2050
+ rich_presence: [],
2051
+ player_name: "Kei #SkinsMonkey",
2052
+ avatar_hash: [123,4543],
2053
+ last_logoff: "2023-05-20T05:00:42.000Z",
2054
+ last_logon: "2023-05-20T05:02:16.000Z",
2055
+ last_seen_online: "2023-05-20T05:00:42.000Z",
2056
+ avatar_url_icon: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a.jpg",
2057
+ avatar_url_medium: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a_medium.jpg",
2058
+ avatar_url_full: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/3e/3e9da0b107ac2ec384759544368a8a977359537a_full.jpg"
2059
+ }
2060
+ *
2061
+
2062
+ myFriends
2063
+ {
2064
+ 76561198365087582: 3,
2065
+ 76561199490395123: 3
2066
+ }
2067
+ * */
2068
+ /*steamClient._send({
2069
+ msg: 151,
2070
+ proto: {
2071
+ target_job_name: methodName
2072
+ }
2073
+ }, Buffer.alloc(0), function (body, hdr) {
2074
+ const result = hdr.proto.eresult
2075
+ const errorMessage = hdr.proto.error_message
2076
+ const responseData = body.toBuffer()
2077
+ console.log(`xxx`, result)
2078
+ })*/
2079
+
2080
+ steamClient.sendToGC(730, 767, {}, Buffer.alloc(0));
2081
+ }
2082
+
2083
+ async function getUserOwnedApps(steamId = steamClient.steamID) {
2084
+ if (!steamId) {
2085
+ return [];
2086
+ }
2087
+ if (typeof steamId?.getSteamID64 === "function") {
2088
+ steamId = steamId.getSteamID64();
2089
+ }
2090
+ const isMe = steamId === steamClient.steamID.getSteamID64();
2091
+ if (isMe && ownedApps.length) {
2092
+ return ownedApps;
2093
+ }
2094
+ let result = {};
2095
+ try {
2096
+ result = await steamClient.getUserOwnedApps(steamId);
2097
+ } catch (e) {
2098
+ try {
2099
+ result = await steamClient.getUserOwnedApps(steamId);
2100
+ } catch (e) {
2101
+ result = {};
2102
+ }
2103
+ }
2104
+ if (isMe && Array.isArray(result.apps)) {
2105
+ ownedApps.length = 0;
2106
+ ownedApps.push(...result.apps);
2107
+ }
2108
+ return result.apps || [];
2109
+ const resultExample = {
2110
+ app_count: 22,
2111
+ apps: [
2112
+ {
2113
+ content_descriptorids: [],
2114
+ appid: 208030,
2115
+ name: "Moon Breakers",
2116
+ playtime_2weeks: null,
2117
+ playtime_forever: 0,
2118
+ img_icon_url: "",
2119
+ has_community_visible_stats: null,
2120
+ playtime_windows_forever: 0,
2121
+ playtime_mac_forever: 0,
2122
+ playtime_linux_forever: 0,
2123
+ rtime_last_played: 0,
2124
+ capsule_filename: null,
2125
+ sort_as: null,
2126
+ has_workshop: null,
2127
+ has_market: null,
2128
+ has_dlc: null,
2129
+ has_leaderboards: null,
2130
+ },
2131
+ ],
2132
+ };
2133
+ }
2134
+
2135
+ function getPlayingAppIds() {
2136
+ return steamClient._playingAppIds || [];
2137
+ }
2138
+
2139
+ return {
2140
+ init,
2141
+ partySearch,
2142
+ invite2Lobby,
2143
+ createLobby,
2144
+ updateLobby,
2145
+ createThenInvite2Lobby,
2146
+ joinLobby,
2147
+ getLobbyData,
2148
+ partyRegister,
2149
+ requestCoPlays,
2150
+ getPersonas,
2151
+ getUsername() {
2152
+ return username;
2153
+ },
2154
+ getCookies,
2155
+ getCookiesWait,
2156
+ getLogOnDetails() {
2157
+ return steamClient?._logOnDetails;
2158
+ },
2159
+ onEvent,
2160
+ offEvent,
2161
+ offAllEvent,
2162
+ setPersona(state, name) {
2163
+ steamClient.setPersona(state, name);
2164
+ },
2165
+ sendFriendMessage,
2166
+ sendFriendTyping,
2167
+ getSteamClient() {
2168
+ return steamClient;
2169
+ },
2170
+ getAccountInfoName,
2171
+ getPersonaName,
2172
+ async getPlayersProfile(steamId, retry = 3) {
2173
+ for (let i = 0; i < retry; i++) {
2174
+ const profile = await getPlayersProfile(steamId);
2175
+ if (profile) {
2176
+ return profile;
2177
+ }
2178
+ }
2179
+ return null;
2180
+ },
2181
+ autoRequestFreeLicense,
2182
+ playCSGO,
2183
+ doSetInterval,
2184
+ doClearIntervals,
2185
+ gamesPlayed,
2186
+ sendHello,
2187
+ checkPlayerPrimeStatus,
2188
+ doClearInterval,
2189
+ gamePlay,
2190
+ autoGamePlay,
2191
+ offAutoGamePlay,
2192
+ updateAutoGamePlay,
2193
+ getFriendsList,
2194
+ setIsPartyRegister(change) {
2195
+ change = !!change;
2196
+ if (isPartyRegister !== change) {
2197
+ isPartyRegister = change;
2198
+ if (!isPartyRegister) {
2199
+ doClearInterval("autoPartyRegister");
2200
+ } else {
2201
+ sendHello();
2202
+ }
2203
+ }
2204
+ },
2205
+ setAutoPlay(change) {
2206
+ change = !!change;
2207
+ if (isAutoPlay !== change) {
2208
+ isAutoPlay = change;
2209
+ updateAutoGamePlay();
2210
+ }
2211
+ },
2212
+ setIsInvisible(change) {
2213
+ change = !!change;
2214
+ if (isInvisible !== change) {
2215
+ isInvisible = change;
2216
+ updateInvisible();
2217
+ }
2218
+ },
2219
+ setFakeGameScore(change) {
2220
+ change = !!change;
2221
+ if (isFakeGameScore !== change) {
2222
+ isFakeGameScore = change;
2223
+ updateFakeGameScore();
2224
+ }
2225
+ },
2226
+ setAutoRequestFreeLicense(change) {
2227
+ change = !!change;
2228
+ if (isAutoRequestFreeLicense !== change) {
2229
+ isAutoRequestFreeLicense = change;
2230
+ updateAutoRequestFreeLicense();
2231
+ }
2232
+ },
2233
+ getState() {
2234
+ return state;
2235
+ },
2236
+ log,
2237
+ isPrime() {
2238
+ return prime === true;
2239
+ },
2240
+ getFriendList,
2241
+ logOff,
2242
+ isPlayingBlocked() {
2243
+ return playingBlocked;
2244
+ },
2245
+ async getChatHistory(steamId) {
2246
+ if (!steamClient.steamID) return [];
2247
+ const mySteamId = typeof steamClient.steamID.getSteamID64 === "function" ? steamClient.steamID.getSteamID64() : steamClient.steamID;
2248
+ return new Promise((resolve) => {
2249
+ setTimeout(resolve, 90000);
2250
+ steamClient.getChatHistory(steamId, async function (error, result) {
2251
+ const messages = (result || []).map(function (msg) {
2252
+ const fromSteamId = typeof msg.steamID?.getSteamID64 === "function" ? msg.steamID.getSteamID64() : msg.steamID;
2253
+ return {
2254
+ message: msg.message,
2255
+ from: fromSteamId,
2256
+ to: fromSteamId == mySteamId ? steamId : mySteamId,
2257
+ _id: new Date(msg.timestamp).getTime().toString(),
2258
+ timestamp: new Date(msg.timestamp).getTime(),
2259
+ isMe: fromSteamId !== steamId,
2260
+ };
2261
+ });
2262
+ resolve(messages);
2263
+ });
2264
+ });
2265
+ },
2266
+ onAnyEvent,
2267
+ async redeemGift(gid) {
2268
+ try {
2269
+ const community = new SteamCommunity();
2270
+ let cookies = await getCookiesWait();
2271
+ community.setCookies(typeof cookies === "string" ? cookies.split(";") : cookies);
2272
+ community.redeemGift(gid);
2273
+ } catch (e) {}
2274
+ },
2275
+ async requestFreeLicense(...args) {
2276
+ try {
2277
+ return await steamClient.requestFreeLicense(...args);
2278
+ } catch (e) {}
2279
+ },
2280
+ getSteamId() {
2281
+ try {
2282
+ return steamClient.steamID.getSteamID64();
2283
+ } catch (e) {}
2284
+ },
2285
+ getLastTimePartyRegister() {
2286
+ return lastTimePartyRegister;
2287
+ },
2288
+ getLastTimePartySearch() {
2289
+ return lastTimePartySearch;
2290
+ },
2291
+ getLicenses() {
2292
+ return steamClient.licenses;
2293
+ const exampleLicenses = [
2294
+ {
2295
+ package_id: 303386,
2296
+ time_created: 1680491335,
2297
+ time_next_process: 0,
2298
+ minute_limit: 0,
2299
+ minutes_used: 0,
2300
+ payment_method: 1024,
2301
+ flags: 512,
2302
+ purchase_country_code: "VN",
2303
+ license_type: 1,
2304
+ territory_code: 0,
2305
+ change_number: 20615891,
2306
+ owner_id: 1530068060,
2307
+ initial_period: 0,
2308
+ initial_time_unit: 0,
2309
+ renewal_period: 0,
2310
+ renewal_time_unit: 0,
2311
+ access_token: "8049398090486337961",
2312
+ master_package_id: null,
2313
+ },
2314
+ ];
2315
+ },
2316
+ uploadRichPresence(appid, richPresence) {
2317
+ const _richPresence = Array.isArray(richPresence)
2318
+ ? richPresence.reduce(function (previousValue, currentValue, currentIndex, array) {
2319
+ if (currentValue.key) {
2320
+ previousValue[currentValue.key] = currentValue.value?.toString() || "";
2321
+ }
2322
+ return previousValue;
2323
+ }, {})
2324
+ : richPresence;
2325
+ steamClient.uploadRichPresence(appid, _richPresence);
2326
+ },
2327
+ getUserOwnedApps,
2328
+ getPlayingAppIds,
2329
+ getCurrentLobby() {
2330
+ return currentLobby;
2331
+ },
2332
+ setGame(_games) {
2333
+ games = _games;
2334
+ },
2335
+ };
2336
+ }
2337
+
2338
+ export default SteamClient;
2339
+
2340
+ export function increaseCSGO_VER() {
2341
+ return ++CSGO_VER;
2342
+ }
2343
+
2344
+ SteamClient.isAccountPlayable = async function isAccountPlayable({ cookie, clientJsToken, timeoutMs, onPlayable, onNotPlayable, ...rest }) {
2345
+ if (!clientJsToken && cookie) {
2346
+ clientJsToken = await new SteamUser(typeof cookie === "function" ? await cookie() : cookie).getClientJsToken();
2347
+ }
2348
+ if (clientJsToken?.logged_in !== true) {
2349
+ if (typeof onNotPlayable === "function") {
2350
+ await onNotPlayable(null);
2351
+ }
2352
+ return { invalidClientJsToken: true };
2353
+ }
2354
+ return await new Promise((resolve) => {
2355
+ const timeouts = [
2356
+ setTimeout(() => {
2357
+ doResolve({ timedOut: true });
2358
+ }, timeoutMs || 30000),
2359
+ ];
2360
+
2361
+ const steamClient = new SteamClient({
2362
+ isFakeGameScore: false,
2363
+ isAutoPlay: true,
2364
+ isPartyRegister: false,
2365
+ isInvisible: true,
2366
+ MAX_GAME_PLAY: 10,
2367
+ games: 730,
2368
+ clientJsToken,
2369
+ ...rest,
2370
+ });
2371
+
2372
+ steamClient.onEvent("error", ({ eresult, msg, error }) => {
2373
+ doResolve({ eresult, msg, error });
2374
+ });
2375
+
2376
+ steamClient.onEvent("csgoOnline", (ClientWelcome) => {
2377
+ doResolve({ playable: true });
2378
+ });
2379
+
2380
+ steamClient.onEvent("csgoClientHello", (ClientHello) => {
2381
+ doResolve({ playable: true });
2382
+ });
2383
+
2384
+ steamClient.onEvent("playingState", ({ playing_blocked, playing_app }) => {
2385
+ if (playing_blocked) {
2386
+ doResolve({ playable: false });
2387
+ } else {
2388
+ timeouts.push(
2389
+ setTimeout(function () {
2390
+ const isBlocked = steamClient.isPlayingBlocked();
2391
+ doResolve({ playable: !isBlocked });
2392
+ }, 5000),
2393
+ );
2394
+ }
2395
+ });
2396
+
2397
+ // steamClient.onEvent("fatalError", () => {
2398
+ // doResolve();
2399
+ // });
2400
+
2401
+ steamClient.init();
2402
+
2403
+ async function doResolve(data) {
2404
+ timeouts.forEach((timeout) => clearTimeout(timeout));
2405
+ steamClient.doClearIntervals();
2406
+ steamClient.offAllEvent();
2407
+
2408
+ if (data?.playable === true) {
2409
+ if (typeof onPlayable === "function") {
2410
+ try {
2411
+ await onPlayable(steamClient);
2412
+ } catch (e) {}
2413
+ }
2414
+ } else {
2415
+ if (typeof onNotPlayable === "function") {
2416
+ try {
2417
+ await onNotPlayable(steamClient);
2418
+ } catch (e) {}
2419
+ }
2420
+ }
2421
+
2422
+ steamClient.logOff();
2423
+ return resolve(data);
2424
+ }
2425
+ });
2426
+ };