-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCrossPlatformPlaying.plugin.js
4746 lines (4009 loc) · 191 KB
/
CrossPlatformPlaying.plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @name CrossPlatformPlaying
* @author Giorgio
* @description Show what friends are playing even if they have their game activity turned off
* @version 0.2.8
* @authorId 316978243716775947
* @source https://github.com/giorgi-o/CrossPlatformPlaying
*/
/*@cc_on
@if (@_jscript)
// Offer to self-install for clueless users that try to run this directly.
var shell = WScript.CreateObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\BetterDiscord\plugins");
var pathSelf = WScript.ScriptFullName;
// Put the user at ease by addressing them in the first person
shell.Popup("It looks like you've mistakenly tried to run me directly. \n(Don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30);
if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
shell.Popup("I'm in the correct folder already.", 0, "I'm already installed", 0x40);
} else if (!fs.FolderExists(pathPlugins)) {
shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10);
} else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) {
fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true);
// Show the user where to put plugins in the future
shell.Exec("explorer " + pathPlugins);
shell.Popup("I'm installed!", 0, "Successfully installed", 0x40);
}
WScript.Quit();
@else@*/
/**************
** HELPER **
**************/
const https = require("https")
const tls = require("tls");
const fs = require("fs");
const net = require("net");
const crypto = require("crypto");
// send an HTTP request to a URL, bypassing CORS policy
const fetch = (url, options={}) => {
return new Promise((resolve) => {
const req = https.request(url, {
method: options.method || "GET",
headers: options.headers || {}
}, resp => {
const res = {
statusCode: resp.statusCode,
headers: resp.headers
};
let chunks = [];
resp.on('data', (chunk) => chunks.push(chunk));
resp.on('end', () => {
res.body = Buffer.concat(chunks).toString(options.encoding || "utf8");
resolve(res);
});
})
req.write(options.body || "");
req.end();
});
}
// basic error handling
const err = e => {
console.error(e);
for(const errCode of ["ETIMEDOUT", "ECONNRESET", "ENOTFOUND", "ENOENT", "ECONNABORTED"]) {
if(e.code === errCode || e.errno === errCode) return; // steam & hypixel sometimes time out for no reason
}
debugger;
BdApi.alert("Error happened!\n" + e);
}
const pluginName = "CrossPlatformPlaying";
const customRpcAppId = "883483733875892264";
const config = {
"info": {
"name": pluginName,
"authors": [{
"name": "Giorgio",
"discord_id": "316978243716775947",
"github_username": "giorgi-o"
}],
"version": "0.2.8",
"description": "Lets you see what your friends are playing even if they turned off game activity",
"github": "https://github.com/giorgi-o/CrossPlatformPlaying",
"github_raw": "https://raw.githubusercontent.com/giorgi-o/CrossPlatformPlaying/main/CrossPlatformPlaying.plugin.js"
},
"changelog": [ // added: green, improved: blurple, fixed: red, progress: yellow
{
"title": "League of Legends",
"type": "added",
"items": [
"Added TFT Double Up",
"Added AFK in the lobby detection",
]
},
{
"title": "Valorant",
"type": "improved",
"items": [
"Added Pearl map",
]
},
]
};
// the discord id of the current user (once the plugin loads)
let discord_id = 0;
// update the user's status in the guild member list
// call this when the user changes game (not just the game state)
let updateUser = (id) => {};
// to implement a new platform, create a subclass of Platform
// and override constructor(), start(), serializeData(), deserializeData(), getPresence(), destroy() and getSettings()
class Platform {
// all platforms should call super() with their platformId
constructor(platformId) {
this.platformId = platformId; // used when storing the platform settings
}
// should be called in constructor if the platform is enabled
start() {}
// loads the plugin settings and calls deserializeData(). Should be called in constructor before start()
loadData() {
const data = BdApi.loadData(pluginName, this.platformId);
this.deserializeData(data || {});
this.saveData();
}
// save the data from serializeData() on disk
saveData() {
BdApi.saveData(pluginName, this.platformId, this.serializeData());
}
// returns a JSON serializable object containing the data to be saved on disk
serializeData() {};
// takes the JSON stored on disk and deserializes it to be used by the platform
deserializeData(data) {};
// helper method that can be used for simple platforms
// platforms should implement getPresence with only one argument, discord_id
getPresence(discord_id, discordToPlatformId, presenceCache) {
if(!discord_id || !presenceCache || !discordToPlatformId || !discordToPlatformId[discord_id]) return;
const presences = [];
for (const platform_id of discordToPlatformId[discord_id]) {
if(presenceCache[platform_id])
presences.push(presenceCache[platform_id]);
}
if(presences.length) return presences;
}
// helper method to call updateUser() on a user using their user id
// because typically the processPresence() functions only have the platform id, not discord id
updateUser(platformId, discordToPlatformId) {
const discordIds = [];
for(const [discordId, platformIds] of Object.entries(discordToPlatformId)) {
let matches;
if(Array.isArray(platformIds)) matches = platformIds.includes(platformId);
else matches = platformIds === platformId;
if(matches) discordIds.push(discordId);
}
for(const discordId of discordIds)
updateUser(discordId);
}
// called when the plugin is stopped or the platform is disabled
// pluginShutdown is true if the whole plugin is being disabled
destroy(pluginShutdown) {};
// helper function to restart the platform, for example to re-authenticate.
restart() {
this.destroy(false);
this.enabled = true;
this.saveData();
this.start();
}
// should return an HTML element containing the settings panel
// takes as argument an object containing a map of discord IDs to and from usernames
getSettings() {
const div = document.createElement("div");
div.innerText = "No settings panel for " + this.platformId;
return div;
}
log(s) {
if(!this.debug) return;
if(typeof s === "object") console.log(`[${this.platformId.toUpperCase()}]`, s);
else console.log(`[${this.platformId.toUpperCase()}] ${s}`);
}
}
const removeFromList = (list, value) => {
const index = list.indexOf(value);
if(index !== -1) list.splice(index, 1);
}
const timeouts = [];
const intervals = [];
const setTimeout = (fn, delay) => {
const id = window.setTimeout(() => {
removeFromList(timeouts, id);
try {fn()}
catch(e) {err(e)}
}, delay);
timeouts.push(id);
return id;
}
const setInterval = (fn, delay) => {
const id = window.setInterval(() => {
try {fn()}
catch(e) {err(e)}
}, delay);
intervals.push(id);
return id;
}
// custom websocket client adding support for HTTP headers and cookies
class SimpleSocket extends EventTarget {
constructor(url, options={}) {
super();
this.on = this.addEventListener;
this.emit = (e, d) => this.dispatchEvent(new CustomEvent(e, d));
this.url = new URL(url);
if(this.url.protocol !== "wss:") return console.error("Only wss WebSockets are supported!");
this.key = options.key || crypto.randomBytes(16).toString('base64');
this.status = SimpleSocket.states.CONNECTING;
const reqOptions = {
hostname: this.url.hostname,
host: this.url.host,
port: this.url.port || 443,
path: this.url.pathname + this.url.search,
rejectUnauthorized: false,
headers: {
"Connection": "Upgrade",
"Upgrade": "websocket",
"Sec-WebSocket-Key": this.key,
"Sec-WebSocket-Version": options.version || 13,
...options.headers
},
...options.requestOptions
}
if(options.protocol) reqOptions.headers["Sec-WebSocket-Protocol"] = options.protocol;
if(options.extensions) reqOptions.headers["Sec-WebSocket-Extensions"] = options.extensions;
this.req = https.request(reqOptions);
this.req.on('upgrade', (res, socket, head) => {
try { // check accept header
const expected = crypto.createHash('sha1').update(this.key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest('base64');
if(res.headers["sec-websocket-accept"] !== expected) return console.error("Something fishy is going on... sec-websocket-accept expected vs recieved:", expected, res.headers["sec-websocket-accept"]);
this.socket = socket;
socket.on('data', data => this.receive(data));
socket.on('close', () => this.closed());
socket.on('error', console.error);
this.status = SimpleSocket.states.READY;
if(this.onconnect) this.onconnect(socket, res);
if(head && head.length) this.receive(head);
} catch(e) {
err(e);
}
});
this.req.on("error", console.error);
this.req.end();
}
send(data, opcode) {
try {
if(!this.socket) return;
if(this.status !== SimpleSocket.states.READY) return console.error("Tried to send data on a closed WebSocket!");
let header;
if(Buffer.isBuffer(data)) header = 0x82;
else {
header = 0x81;
data = Buffer.from(new TextEncoder().encode(data.toString()));
}
if(opcode) header = 0x80 + opcode;
let lengthByte = 0x80; // mask set to 1
let extendedLength;
if(data.length > 65535) {
lengthByte += 127;
(extendedLength = Buffer.alloc(8)).writeBigUInt64BE(BigInt(data.length));
} else if(data.length > 125) {
lengthByte += 126;
(extendedLength = Buffer.alloc(2)).writeUInt16BE(data.length);
} else {
lengthByte += data.length;
extendedLength = Buffer.alloc(0);
}
const maskKey = crypto.randomBytes(4);
const maskedData = this.maskData(data, maskKey);
const buf = Buffer.concat([
Buffer.from([header, lengthByte]),
extendedLength, maskKey, maskedData
]);
this.socket.write(buf);
} catch(e) {
err(e);
}
}
receive(buf) {
try {
if(!this.onmessage) return;
const fin = buf[0] >> 7; // bit 0 is FIN
const opcode = buf[0] & 0x0F; // bits 4-7 is opcode
const mask = buf[1] >> 7; // bit 8 is mask
if(opcode === SimpleSocket.opcode.PING) {
return this.pong();
}
let length = buf[1] & 0x7F;
let lengthEnd = 2;
if(length === 126) {
length = buf.readUInt16BE(2);
lengthEnd = 4;
} else if(length === 127) {
length = buf.readBigUInt64BE(2);
lengthEnd = 10;
}
let data;
if(mask) {
const key = buf.readUInt32BE(lengthEnd);
lengthEnd += 4;
const masked = buf.subarray(lengthEnd, lengthEnd + length);
data = this.maskData(masked, key);
} else {
data = buf.subarray(lengthEnd, lengthEnd + length);
}
if(opcode === SimpleSocket.opcode.CLOSE) {
return this.closed(data);
} else if(this.status !== SimpleSocket.states.READY) {
return console.error("Data received on closed WebSocket!");
}
if(opcode === SimpleSocket.opcode.TEXT) data = data.toString('utf8');
this.onmessage(data, buf);
} catch(e) {
err(e);
}
}
close(statusCode, reason) {
if(!this.socket) return;
let data = [];
if(statusCode) {
data = new Buffer(2);
data.writeUInt16BE(statusCode);
if(reason) data = Buffer.concat([data, new TextEncoder().encode(reason.toString())]);
}
this.send(data, SimpleSocket.opcode.CLOSE);
this.status = SimpleSocket.states.CLOSING;
this.socket.end();
}
closed(data) {
try {
if(this.status === SimpleSocket.states.CLOSED) return;
this.status = SimpleSocket.states.CLOSED;
this.socket.destroy();
if(!this.onclose) return;
if(data) {
const statusCode = data.readUInt16BE();
const reason = data.toString('utf-8', 2);
this.onclose(statusCode, reason);
} else this.onclose();
} catch(e) {
err(e);
}
}
maskData(data, key) {
const masked = [];
for(let i = 0; i < data.length; i++)
masked.push(data[i] ^ key[i % 4]);
return Buffer.from(masked);
}
ping() {
this.send([], SimpleSocket.opcode.PING);
}
pong() {
this.send([], SimpleSocket.opcode.PONG);
}
static opcode = {
CONT: 0,
TEXT: 1, BIN: 2,
CLOSE: 8,
PING: 9, PONG: 10
}
static states = {
CONNECTING: 0,
READY: 1,
CLOSING: 2,
CLOSED: 3
}
}
// SimpleSocket todo:
// list of websockets to destroy
// support continuation frames
// support close codes
// support http status codes other than 101
const Priorities = {
PLAYING: 7, // user has game open & actively playing
IN_LOBBY: 6, // user has game open and is about to launch (in lobby)
DISCORD_RICH_PRESENCE: 5, // discord presence, with rich presence
IN_LOBBY_AFK: 4, // user has game open but is afk
NONPRIMARY_PLAYING: 3, // user has their game open, but this is not the primary presence (e.g. Steam)
DISCORD_NORMAL: 2, // discord presence, without rich presence
SECONDARY: 1 // secondary activity (e.g. Spotify/Twitch)
}
// helper functions for building the settings panel
const SettingsBuilder = {
enabledSwitch: (platform) => {
const onChange = (value) => {
const wasEnabled = platform.enabled;
platform.enabled = value;
if(!wasEnabled && value) platform.start();
if(wasEnabled && !value) platform.destroy();
platform.saveData();
}
return new ZeresPluginLibrary.Settings.Switch("Enabled", "Whether this platform is enabled", platform.enabled, onChange);
},
toggleEnabledSwitch: (enabledSwitch) => {
enabledSwitch.getElement().children[0].children[0].children[1].children[0].children[1].click();
},
debugSwitch: (platform) => {
const onChange = (value) => {
platform.debug = value;
if(value) platform.log("Debug enabled!");
}
return new ZeresPluginLibrary.Settings.Switch("Debug", "Whether to print debug info to the console", platform.debug, onChange);
},
getTextboxInput: (textbox) => {
return textbox.children[0].children[1].children[0];
},
textboxWithButton: (name, note, value, onChange, textboxOptions, buttonText, onClick, timeout=50) => {
if(!name) name = ""; // if name is null, button formatting doesn't work for some reason
const textbox = new ZeresPluginLibrary.Settings.Textbox(name, note, value, onChange, textboxOptions).getElement();
setTimeout(() => {
const button = document.createElement("button");
button.innerText = buttonText;
button.onclick = onClick;
button.classList.add("bd-button");
button.style.fontSize = "16px";
button.style.marginLeft = "10px";
button.style.whiteSpace = "nowrap";
const div = textbox.children[0].children[1];
div.style.flexDirection = "row";
div.append(button);
}, timeout);
return textbox;
},
settingsPanel: (platform, ...nodes) => {
const panel = new ZeresPluginLibrary.Settings.SettingPanel(() => platform.saveData(), ...nodes);
return panel.getElement();
},
createDatalist: (id, values) => {
const datalist = document.createElement("datalist");
datalist.id = id;
for(const value of values) {
const option = document.createElement("option");
option.value = value;
datalist.append(option);
}
return datalist;
},
userMapInterface: (platform, platformDatalist, discordDatalist, platformUserList, discordUserList, usersMap, description, platformHeaderValue, platformIdRegex=/./, discordIdRegex=/^\d{15,}$/) => {
/** userList format: {
* idToName: {
* 1234: "gary"
* },
* nameToId: {
* "gary": 1234
* }
* }
*/
// get a few class names from discord (can't find them in ZLibrary)
if(!SettingsBuilder.inputClassNames) SettingsBuilder.inputClassNames = BdApi.findModuleByProps("input", "inputMini", "inputWrapper");
if(!SettingsBuilder.descriptionClassNames) SettingsBuilder.descriptionClassNames = BdApi.findModuleByProps('labelBold', 'labelDescriptor', 'labelSelected');
const userMapDiv = document.createElement("div");
userMapDiv.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.container);
if(platformDatalist) userMapDiv.append(platformDatalist);
if(description) {
const descriptionDiv = document.createElement("div");
descriptionDiv.className = (SettingsBuilder.descriptionClassNames.description);
descriptionDiv.innerHTML = description;
descriptionDiv.style.marginBottom = "6px";
userMapDiv.append(descriptionDiv);
}
const table = document.createElement("table");
table.style.width = "100%";
userMapDiv.append(table);
// top row with + button and labels
const topRow = document.createElement("tr");
topRow.id = platform.platformId + "-row-top";
const addRowButton = document.createElement("button");
addRowButton.innerText = "+";
addRowButton.className = "bd-button";
const addRowButtonColumn = document.createElement("th");
addRowButtonColumn.append(addRowButton);
topRow.append(addRowButtonColumn);
const platformColumnTitle = document.createElement("th");
platformColumnTitle.innerText = platformHeaderValue || "Platform user";
platformColumnTitle.style.color = "var(--header-primary)";
topRow.append(platformColumnTitle);
const discordColumnTitle = document.createElement("th");
discordColumnTitle.innerText = "Discord user";
discordColumnTitle.style.color = "var(--header-primary)";
topRow.append(discordColumnTitle);
table.append(topRow);
// handle saving data to json
let saveTimeout;
const saveData = () => {
clearTimeout(saveTimeout);
// delete all entries in old usersMap
for(const user of Object.keys(usersMap)) delete usersMap[user];
for(const row of table.children) {
if(row.id === platform.platformId + "-row-top") continue;
const [, platformColumn, discordColumn] = row.children;
const platformInput = platformColumn.children[0];
const discordInput = discordColumn.children[0];
let platformValue = platformInput.value;
let discordValue = discordInput.value;
if(platformUserList && platformUserList.nameToId[platformValue]) {
platformValue = platformUserList.nameToId[platformValue];
} else if(platformIdRegex && !platformIdRegex.test(platformValue)) {
platformInput.style.color = "red";
continue;
}
platformInput.style.color = null;
if(discordUserList && discordUserList.nameToId[discordValue]) {
discordValue = discordUserList.nameToId[discordValue];
} else if(discordIdRegex && !discordIdRegex.test(discordValue)) {
discordInput.style.color = "red";
continue;
}
discordInput.style.color = null;
if(!platformValue || !discordValue) continue;
if(Array.isArray(usersMap[discordValue])) {
usersMap[discordValue].push(platformValue);
} else {
usersMap[discordValue] = [platformValue];
}
}
saveTimeout = setTimeout(() => {
platform.saveData();
}, 500);
}
let id = 0;
const addRow = (platformValue, discordValue, insertAtEnd=false) => {
const row = document.createElement("tr");
row.style.width = "100%";
row.id = platform.platformId + "-row-" + id.toString();
// X button
const removeButton = document.createElement("button");
removeButton.className = "bd-button";
removeButton.innerText = "X";
removeButton.onclick = () => removeRow(row.id);
const removeButtonColumn = document.createElement("th");
removeButtonColumn.append(removeButton);
row.append(removeButtonColumn);
// platform dropdown
const platformInput = document.createElement("input");
platformInput.className = SettingsBuilder.inputClassNames.input;
platformInput.style.width = "100%";
platformInput.oninput = saveData;
if(platformValue) platformInput.value = platformValue;
if(platformDatalist) platformInput.setAttribute("list", platformDatalist.id);
const platformInputColumn = document.createElement("th");
platformInputColumn.style.width = "50%";
platformInputColumn.append(platformInput);
row.append(platformInputColumn);
// discord dropdown
const discordInput = document.createElement("input");
discordInput.className = SettingsBuilder.inputClassNames.input;
discordInput.style.width = "100%";
discordInput.oninput = saveData;
if(discordValue) discordInput.value = discordValue;
if(discordDatalist) discordInput.setAttribute("list", discordDatalist.id);
const discordInputColumn = document.createElement("th");
discordInputColumn.style.width = "50%";
discordInputColumn.append(discordInput);
row.append(discordInputColumn);
if(insertAtEnd) table.append(row);
else table.insertBefore(row, table.children[1]);
id++;
}
addRowButton.onclick = () => addRow();
const removeRow = (id) => {
table.removeChild(document.getElementById(id));
if(table.children.length === 1) addRow();
saveData();
}
const userCount = Object.values(usersMap).flat().length;
if(userCount === 0) {
addRow("", "");
}
else if(userCount === 1) {
const [[discord_id, platform_ids]] = Object.entries(usersMap);
addRow(platform_ids[0], discord_id);
}
else {
for(const [discord_id, platform_ids] of Object.entries(usersMap)) {
for(const platform_id of platform_ids) {
addRow(platformUserList && platformUserList.idToName[platform_id] || platform_id,
discordUserList && discordUserList.idToName[discord_id] || discord_id, true);
}
}
}
// add divider
const divider = document.createElement("div");
divider.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.divider);
divider.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.dividerDefault);
userMapDiv.append(divider);
return userMapDiv;
},
list: (platform, theList, description, header, regex=/./) => {
// get a few class names from discord (can't find them in ZLibrary)
if(!SettingsBuilder.inputClassNames) SettingsBuilder.inputClassNames = BdApi.findModuleByProps("input", "inputMini", "inputWrapper");
if(!SettingsBuilder.descriptionClassNames) SettingsBuilder.descriptionClassNames = BdApi.findModuleByProps('labelBold', 'labelDescriptor', 'labelSelected');
const listDiv = document.createElement("div");
listDiv.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.container);
if(description) {
const descriptionDiv = document.createElement("div");
descriptionDiv.className = (SettingsBuilder.descriptionClassNames.description);
descriptionDiv.innerHTML = description;
descriptionDiv.style.marginBottom = "6px";
listDiv.append(descriptionDiv);
}
const table = document.createElement("table");
table.style.width = "100%";
listDiv.append(table);
// top row with + button and labels
const topRow = document.createElement("tr");
topRow.id = platform.platformId + "-list-row-top";
const addRowButton = document.createElement("button");
addRowButton.innerText = "+";
addRowButton.className = "bd-button";
const addRowButtonColumn = document.createElement("th");
addRowButtonColumn.append(addRowButton);
topRow.append(addRowButtonColumn);
const inputColumnTitle = document.createElement("th");
inputColumnTitle.innerText = header || "Value";
inputColumnTitle.style.color = "var(--header-primary)";
topRow.append(inputColumnTitle);
table.append(topRow);
// handle saving data to json
let saveTimeout;
const saveData = () => {
clearTimeout(saveTimeout);
// delete all entries in old list
theList.length = 0;
for(const row of table.children) {
if(row.id === platform.platformId + "-list-row-top") continue;
const inputElement = row.children[1].children[0];
const inputValue = inputElement.value;
if(regex && !regex.test(inputValue)) {
inputElement.style.color = "red";
continue;
}
inputElement.style.color = null;
if(!inputValue) continue;
theList.push(inputValue);
}
saveTimeout = setTimeout(() => {
platform.saveData();
}, 500);
}
let id = 0;
const addRow = (value, insertAtEnd=false) => {
const row = document.createElement("tr");
row.style.width = "100%";
row.id = platform.platformId + "-list-row-" + id.toString();
// X button
const removeButton = document.createElement("button");
removeButton.className = "bd-button";
removeButton.innerText = "X";
removeButton.onclick = () => removeRow(row.id);
const removeButtonColumn = document.createElement("th");
removeButtonColumn.append(removeButton);
row.append(removeButtonColumn);
// input
const platformInput = document.createElement("input");
platformInput.className = SettingsBuilder.inputClassNames.input;
platformInput.style.width = "100%";
platformInput.oninput = saveData;
if(value) platformInput.value = value;
const platformInputColumn = document.createElement("th");
platformInputColumn.style.width = "100%";
platformInputColumn.append(platformInput);
row.append(platformInputColumn);
if(insertAtEnd) table.append(row);
else table.insertBefore(row, table.children[1]);
id++;
}
addRowButton.onclick = () => addRow();
const removeRow = (id) => {
table.removeChild(document.getElementById(id));
if(table.children.length === 1) addRow();
saveData();
}
if(theList.length <= 1) {
addRow(theList[0]);
} else {
for(const item of theList) {
addRow(item, true);
}
}
// add divider
const divider = document.createElement("div");
divider.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.divider);
divider.classList.add(ZeresPluginLibrary.DiscordClassModules.Dividers.dividerDefault);
listDiv.append(divider);
return listDiv;
}
}
/*************
** STEAM **
*************/
class Steam extends Platform {
constructor() {
super("steam");
this.presenceCache = {};
this.loadData();
if(this.enabled) {
this.start();
}
}
start() {
if(this.apiKey) {
this.updateCache();
// we are allowed 100000 requests/day = 64/minute
this.cacheUpdateinterval = setInterval(this.updateCache.bind(this), 10_000);
}
}
serializeData() {
return {
enabled: this.enabled || false,
apiKey: this.apiKey || "",
usersMap: this.discordToSteamIDs || {},
debug: this.debug || false
}
}
deserializeData(data) {
this.enabled = data.enabled || false;
this.apiKey = data.apiKey || "";
this.discordToSteamIDs = data.usersMap || {};
this.debug = data.debug || false;
}
async getPlayerSummaries(ids) {
const url = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${this.apiKey}&steamids=${ids.join(',')}`;
const req = await fetch(url);
if(req.statusCode !== 200) {
console.error(req);
if(req.statusCode === 403) {
console.error(req);
if(this.apiKey) BdApi.alert("Your Steam API key is invalid! Steam has been disabled, reenable it in settings.");
else BdApi.alert("You haven't provided a Steam API key!");
this.destroy();
return;
}
console.error("HTTP error " + req.statusCode + " when fetching steam data");
return;
}
try {
const json_data = JSON.parse(req.body);
if (!json_data.response || !json_data.response.players) return;
this.log(json_data);
for (const playerSummary of json_data.response.players) {
this.processPlayerSummary(playerSummary);
}
} catch (e) {
console.error(e);
console.error(req);
err("Couldn't JSON Parse Steam response!");
}
}
processPlayerSummary(summary) {
// format: https://developer.valvesoftware.com/wiki/Steam_Web_API#GetPlayerSummaries_.28v0002.29
if(summary.gameextrainfo) {
const statuses = ["Offline", "Playing", "Busy", "Away", "Snoozed", "Looking to trade", "Looking to play"];
const previousPresence = this.presenceCache[summary.steamid];
const playingSameGame = previousPresence && summary.gameextrainfo === previousPresence.name;
const presence = {
application_id: customRpcAppId,
name: summary.gameextrainfo,
details: `${statuses[summary.personastate]} on Steam`,
type: 0,
timestamps: {start: playingSameGame ? previousPresence.timestamps.start : +new Date()},
assets: {
large_image: "883490890377756682",
large_text: "Playing as " + summary.personaname
},
username: summary.personaname,
priority: Priorities.NONPRIMARY_PLAYING
};
this.presenceCache[summary.steamid] = presence;
this.log(presence);
if(!playingSameGame) this.updateUser(summary.steamid, this.discordToSteamIDs);
} else {
this.deletePresence(summary.steamid);
}
}
deletePresence(id) {
if(this.presenceCache[id]) {
delete this.presenceCache[id];
this.updateUser(id, this.discordToSteamIDs);
}
}
updateCache() {
if(!this.enabled) return clearInterval(this.cacheUpdateinterval);
try {
const steam_ids = Object.values(this.discordToSteamIDs).flat();
// can only request 100 steam profiles at a time
for (let i = 0; i < steam_ids.length; i += 100) {
this.getPlayerSummaries(steam_ids.slice(i, i + 100));
}
} catch (e) {
err(e);
}
}
getPresence(discord_id) {
return super.getPresence(discord_id, this.discordToSteamIDs, this.presenceCache);
}
getSettings(discordUserList, discordUsersDatalist) {
// enabled switch
const enabledSwitch = SettingsBuilder.enabledSwitch(this);
// api key textbox
const textboxChange = (value) => {
this.apiKey = value;
if(this.enabled) {
SettingsBuilder.toggleEnabledSwitch(enabledSwitch);
}
}
const apiKeyTextbox = new ZeresPluginLibrary.Settings.Textbox("API Key", "Your Steam API key. Get one at https://steamcommunity.com/dev/apikey", this.apiKey, textboxChange);
setTimeout(() => {
apiKeyTextbox.getElement().children[0].children[2].innerHTML = `Your Steam API key. Get one at <a href="https://steamcommunity.com/dev/apikey" target="_blank">https://steamcommunity.com/dev/apikey</a>`
}, 50);
const userMapDiv = SettingsBuilder.userMapInterface(this, null, discordUsersDatalist, null, discordUserList, this.discordToSteamIDs,
"To get IDs, use a site such as <a href='https://www.steamidfinder.com/' target=\"_blank\">Steam ID Finder</a> and copy the SteamID64 (Dec).", "Steam ID", /^\d+$/);
const debugSwitch = SettingsBuilder.debugSwitch(this);
return SettingsBuilder.settingsPanel(this, enabledSwitch, apiKeyTextbox, userMapDiv, debugSwitch);
}
destroy(pluginShutdown) {
this.enabled = false;
for(const id in this.presenceCache) this.deletePresence(id);
clearInterval(this.cacheUpdateinterval);
if(!pluginShutdown) this.saveData();
}
}
/*****************
** MINECRAFT **
*****************/
class Minecraft extends Platform {
constructor() {
super("minecraft");
this.mcUUIDToUsername = {};