forked from Murmiration/epapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepapi.js
878 lines (700 loc) · 32.5 KB
/
epapi.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
/*
EndPwn "API"
Copyright 2018 EndPwn Project
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
DO NOT EDIT THIS FILE! Your bootstrap may overwrite changes to it, and you will lose your work!
EndPwn3 users: You can prevent this by creating a file in the same directory named DONOTUPDATE
https://github.com/endpwn/
*/
/* below are internal functions and objects, please don't touch them */
// TODO: move all this shit into an object
const __tag = 'EPAPI'
var __silent;
var __brand;
var __lite;
function __print(t) {
console.log(`%c[${__tag}]%c ${t}`, 'font-weight:bold;color:#0cc', '');
}
function __warn(t, e) {
if (typeof (e) == 'undefined') e = ''; else e = ':\n\n' + e;
console.warn(`%c[${__tag}]%c ${t}`, 'font-weight:bold;color:#0cc', '', e);
}
function __error(e, t) {
if (typeof (t) == 'undefined') t = 'uncaught exception';
console.error(`%c[${__tag}]%c ${t}:\n\n`, 'font-weight:bold;color:#0cc', '', e);
}
function __alert(b, t) {
if (typeof (t) == 'undefined') t = 'EPAPI'; else t = 'EPAPI: ' + t;
try {
wc.findFunc('e.onConfirmSecondary')[1].exports.show({ title: t, body: b });
} catch (e2) {
__error(e2, "Error occurred while attempting to pop the standard dialog box, falling back to alert()");
alert(b, t);
}
}
var __crashed = 0;
function __crash(e) {
__error(e, 'Fatal error!');
if (!__crashed) {
__crashed = 1;
if (__brand) {
__setSigmaColor('#f00');
}
__alert('A fatal error occurred in EPAPI.\n\nThis usually means there is a bug in EPAPI or your bootstrap. It can also mean that Discord updated, breaking something important.\n\nCheck the console for details.\n\nIf you don\'t know what this means, contact your bootstrap maintainer.', 'Fatal error!');
}
}
function __setwordmark(html) {
try {
return document.querySelector('[class*="wordmark"]').innerHTML = html;
}
catch (e) { }
}
function __setSigmaColor(color) {
setTimeout(() => __setwordmark(`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill="${color}" d="M0,0L13,0L13,2L3,2L8,7.5L3,13L13,13L13,15L0,15L0,13L5,7.5L0,2L0,0Z"/></svg>`), 2000);
}
// document-level events (internal)
var __events = {
// dispatched whenever Discord's internal event system dispatches an event
discordNativeEvent: function (e) {
return new CustomEvent('ep-native', { detail: e });
},
// dispatched whenever EPAPI is done initializing and loading plugins
onReady: function () {
return new Event('ep-ready');
},
// dispatched during early init, to signal that at least the global namespace is ready
// intended for use by bootstraps
onPrepared: function () {
return new Event('ep-prepared');
},
// dispatched whenever the user changes channel/guild in the ui
onChannelChange: function (e) {
return new CustomEvent('ep-onchannelchange', { detail: e.detail });
},
// dispatched whenever any message is received by the client
onMessage: function (e) {
return new CustomEvent('ep-onmessage', { detail: e.detail });
},
// dispatched whenever a message is received in the channel that the user is currently viewing
onChannelMessage: function (e) {
return new CustomEvent('ep-onchannelmessage', { detail: e.detail });
}
};
// stuff asarpwn's i.js and main.js used to handle
function __prepare() {
// undefine config and settings if running in lite mode and dont deal with require()
if (__lite) {
exports.config = undefined;
}
else {
// mutant hybrid require() for maximum compatibility, always defined now because some bootstraps have bad implementations
__print('defining require...');
//if (typeof (require) == "undefined") {
var r = DiscordNative.nativeModules.requireModule("discord_/../electron").remote.require;
window.require = m => {
try {
return DiscordNative.nativeModules.requireModule("discord_/../" + m);
}
catch (e) {
return r(m);
}
};
//}
// here we import and define some stuff that usually gets defined by the bootstrap, just in case
__print('requiring necessary modules...');
window.electron = require('electron').remote;
window.app = electron.app;
window.fs = require("original-fs");
// kinclude executes a file directly in the context of the page
window.kinclude = function (p) {
return eval(fs.readFileSync(p, 'utf8').toString());
}
// krequire is a reimplementation of require(), only intended for loading plugins
window.krequire = function (p) {
var exports = {};
eval(fs.readFileSync($api.data + '/plugins/' + p + (p.endsWith('.js') ? '' : '.js'), 'utf8').toString());
return exports;
}
}
window.kparse = function (p) {
var exports = {};
eval(p);
return exports;
}
// this part sets up webcrack, which is a very important part of EPAPI -- credit to bootsy
__print('initializing webcrack...');
webpackJsonp([1e3], { webcrack_ver01_xyzzy: function (n, b, d) { mArr = d.m, mCac = d.c, mCar = [], Object.keys(mCac).forEach(function (n) { mCar[n] = mCac[n] }), findFunc = function (n) { results = []; if ("string" == typeof n) mArr.forEach(function (r, t) { -1 !== r.toString().indexOf(n) && results.push(mCac[t]) }); else { if ("function" != typeof n) throw new TypeError("findFunc can only find via string and function, " + typeof n + " was passed"); mArr.forEach(function (r, e) { n(r) && results.push(mCac[e]) }) } return results }, findCache = function (n) { if (results = [], "function" == typeof n) mCar.forEach(function (r, t) { n(r) && results.push(r) }); else { if ("string" != typeof n) throw new TypeError("findCache can only find via function or string, " + typeof n + " was passed"); mCar.forEach(function (r, t) { if ("object" == typeof r.exports) for (p in r.exports) if (p == n && results.push(r), "default" == p && "object" == typeof r.exports["default"]) for (p in r.exports["default"]) p == n && results.push(r) }) } return results }, window.wc = { get: d, modArr: mArr, modCache: mCac, modCArr: mCar, findFunc: findFunc, findCache: findCache } } }); webpackJsonp([1e3], "", ["webcrack_ver01_xyzzy"]);
__print('defining helper functions...');
// shorthand methods that are used internally and in many plugins, maintained for compatibility and convenience
window.$listen = (e, c) => {
var listener = {
name: e,
callback: function () {
try {
c.apply(null, arguments);
}
catch (e) {
__error(e, 'An event listener threw an exception');
}
},
unregister: function () {
document.removeEventListener(this.name, this.callback);
}
}
document.addEventListener(listener.name, listener.callback);
return listener;
};
window.$dispatch = e => document.dispatchEvent(e);
window.$ = s => document.querySelector(s);
window.$$ = s => document.querySelectorAll(s);
window.$purge = e => e.innerHTML = '';
window.$_ = function (e, c, t, i) {
var elm = document.createElement(e);
if (typeof (c) != 'undefined') {
elm.className = c;
if (typeof (t) != 'undefined') {
elm.innerText = t;
if (typeof (i) != 'undefined') {
elm.id = i;
}
}
}
return elm;
};
window.$chan = exports.ui.getCurrentChannel;
window.$guild = exports.ui.getCurrentGuild;
window.$me = exports.internal.getId;
// expose EPAPI as $api, which is what most plugins expect it to be known as
window.$api = exports;
// extension methods used in some older plugins, maintained for compatibility
String.prototype.replaceAll = function (search, replacement) { return this.split(search).join(replacement) };
Array.prototype.contains = function (s) { return this.indexOf(s) != -1 };
// derive the date of creation from a discord snowflake id
Date.fromSnowflake = (id) => new Date((id / 4194304) + 1420070400000);
}
// set everything up and load plugins
function __init() {
if ($(".guilds-wrapper .guilds") != null ? $(".guilds-wrapper .guilds").children.length > 0 : 0) {
try {
if ($api.localStorage.get('safemode')) {
__print('running in safe mode, aborting late-init and informing the user');
$api.localStorage.remove('safemode');
__setSigmaColor('#ff0');
__alert('EPAPI is running in safe mode. No plugins have been loaded and internal Discord data structures have been left unmodified.', 'Safe Mode');
return;
}
$api.localStorage.remove('safemode');
// actually start initializing...
__print('Discord ready, initializing...')
// number of broken plugins
var warning = 0;
// use the ep-native event to dispatch other events
$listen('ep-native', (e) => {
switch (e.detail.type) {
case 'MESSAGE_CREATE':
$dispatch(__events.onMessage(e));
break;
case 'CHANNEL_SELECT':
$dispatch(__events.onChannelChange(e));
break;
}
});
// ep-onchannelmessage is like ep-onmessage, except it only fires when the user is currently viewing the channel the message originates from
$listen('ep-onmessage', e => {
if (e.detail.channel_id == $chan()) {
$dispatch(__events.onChannelMessage(e));
}
});
// register an event with discord's internal event system
__print('registering Discord event handler...');
window.__logAllInternalEvents = false;
exports.internal.dispatcher.default.register(e => {
if (!__crashed) {
if (window.__logAllInternalEvents) {
console.log(e.type + '\n', e);
}
try {
$dispatch(__events.discordNativeEvent(e));
}
catch (e) {
__crash(e);
}
}
});
// hook the discord internal event system
// TODO: registering with the event system is no longer necessary, we should probably unify this with the above chunk of code
$api.internal.dispatcher.default.dispatch_original = $api.internal.dispatcher.default.dispatch;
$api.internal.dispatcher.default.dispatch = function (e) {
__hooks.filter(x => x.type == e.type).forEach(x => x.callback(e));
$api.internal.dispatcher.default.dispatch_original(e);
}
// add our avatar -- credit to block for finding this method
wc.findFunc("clyde")[0].exports.BOT_AVATARS.EndPwn = "https://cdn.discordapp.com/avatars/350987786037493773/ae0a2f95898cfd867c843c1290e2b917.png";
// dont try loading plugins in lite mode
if (__lite) {
}
else {
// load plugins...
if (fs.existsSync(exports.data + '/plugins')) {
fs.readdirSync(exports.data + '/plugins').forEach(x => {
if (x.endsWith('.js')) {
try {
var plugin = krequire(x);
if (plugin.start !== undefined) {
__print('loading /plugins/' + x);
plugin.start();
} else {
__print('/plugins/' + x + ' does not export start(), ignoring...');
}
}
catch (e) {
__error(e, x + ' failed to initialize properly');
warning++;
}
}
});
}
// execute autoruns...
if (fs.existsSync(exports.data + '/autorun')) {
fs.readdirSync(exports.data + '/autorun').forEach(x => {
if (x.endsWith('.js')) {
try {
__print('executing /autorun/' + x);
kinclude(exports.data + '/autorun/' + x);
}
catch (e) {
__error(e, x + ' failed to execute properly');
warning++;
}
}
});
}
}
// display a message if any plugins failed to load
if (warning) {
__alert(`${warning} file${warning > 1 ? 's' : ''} failed to load. Check the console for details.`, 'Plugin failure');
}
// print the about message to the console
if (!__silent)
exports.about();
// dispatch the ep-ready event, we're all done here
$dispatch(__events.onReady());
}
catch (ex) {
__crash(ex);
}
} else {
// discord isnt ready, wait a bit and try again
__print('Discord not ready, waiting 1 second...');
setTimeout(arguments.callee, 1000);
}
}
var __hooks = [];
/* above are internal functions and objects, please don't touch them */
exports = {
// new version data
version: {
major: 5,
minor: 5,
revision: 38, // TODO: find a better way of incrementing/calculating the revision; the current way is fucking ridiculous (manually editing)
toString: function () {
return `v${this.major}.${this.minor}.${this.revision}`;
}
},
// the first ever export added to epapi, originally as a test -- kept in mainline because i havent had the heart to remove it
xyzzy: 'Nothing happened.',
// display info
// ugly code, should probably be made prettier at some point
// oh no i made it even uglier
about: function () {
if (__lite) {
console.log('%cΣndPwnᴸᴵᵀᴱ', 'font-size:48px;font-family:sans-serif');
console.log(`EPAPI ${this.version}\nhttps://endpwn.github.io/\nhttps://discord.gg/8k3gEeE`);
}
else
console.log(`%cΣndPwn%c
EPAPI ${this.version}, ${window.crispr ? `CRISPR ${window.crispr.version}, ` : ''}using ${this.bootstrap.name ? this.bootstrap.name : 'unknown'}${this.bootstrap.version ? ` ${this.bootstrap.version}` : ''}${this.bootstrap.method ? ` (${this.bootstrap.method})` : ''}
https://endpwn.github.io/
https://discord.gg/8k3gEeE`,
'background:linear-gradient(to bottom right,#0ff,#f0f);-webkit-background-clip:text;-webkit-text-fill-color:transparent;font-size:48px;font-family:sans-serif', '');
},
// get the lite status
get lite() {
return __lite;
},
/*
entrypoint arguments:
bootstrap (object): bootstrap properties
keys:
name (string): name of bootstrap
version (string or object): version of bootstrap
method (string): name of stage 1 method in use
lite (bool): disables node dependence (for web browsers)
silent (bool): dont display about() after initialization
brand (bool): enables the sigma wordmark replacement
all keys are optional, boolean values are assumed false if not provided
please do not call this method unless you are a bootstrap
*/
go: function (bootstrap, silent, brand, lite) {
try {
__print('starting up...')
// figure out which calling convention is being used
switch (typeof bootstrap) {
// new bootstrap using bootstrap properties object instead of separate arguments
case 'object':
exports.bootstrap = bootstrap;
__lite = bootstrap.lite ? true : false;
__silent = bootstrap.silent ? true : false;
__brand = bootstrap.brand ? true : false;
break;
// older bootstrap
case 'string':
exports.bootstrap = {
name: bootstrap
};
__lite = lite ? true : false; // dont use node integration
__silent = silent ? true : false;
__brand = brand ? true : false;
break;
// really old bootstrap, or the bootstrap is doing something stupid we dont expect
default:
if (window._epmethod === undefined) {
exports.method = 'unknown';
} else {
exports.method = _epmethod;
}
break;
}
__print('detected calling convention');
// prepare the global namespace
__print('preparing the global namespace...');
__prepare();
// dispatch ep-prepared to let the bootstrap know that the global namespace is ready
$dispatch(__events.onPrepared());
if (!__lite) {
// determine the root path where plugins and files will be found
exports.data = app.getPath('userData').replace(/\\/g, "/") + '/';
__print('data path ' + exports.data);
// icon by toxoid49b, tweaked by me
if (__brand) {
__setSigmaColor('#0ff');
}
}
// start trying to init
__print('starting init loop...');
setTimeout(__init, 0);
// undefine the entrypoint to avoid getting double-called
exports.go = undefined;
}
catch (ex) {
// something bad happened, undefine $api and display a message
__crash(ex);
}
},
// methods for committing data to settings.json
settings: {
// get a value in the settings.json object
get: function (k) {
if (__lite)
__warn('Something tried retrieving data from settings.json, but we are running in lite mode! Returning undefined...');
else
return JSON.parse(fs.readFileSync(exports.data + '/settings.json', 'utf8'))[k];
},
// set a value in the settings.json object
set: function (k, v) {
if (__lite) {
__warn('Something tried putting data into settings.json, but we are running in lite mode! Doing nothing...');
}
else {
var o = JSON.parse(fs.readFileSync(exports.data + '/settings.json', 'utf8'));
o[k] = v;
fs.writeFileSync(exports.data + '/settings.json', JSON.stringify(o, null, 2));
return v;
}
}
},
// localStorage stuff
localStorage: {
// get a value from localStorage
get: function (k) {
return exports.internal.objectStorage.impl.get(k);
},
// set a value in localStorage
set: function (k, v) {
return exports.internal.objectStorage.impl.set(k, v);
},
// remove a value from localStorage
remove: function (k) {
return exports.internal.objectStorage.impl.remove(k);
}
},
// utility functions
util: {
// BUG: wrap and its sister function both fuck things up that use `this`
// i know exactly why this happens, but not the slightest clue how to fix it
// manual wrapping is necessary in some cases because of this
//
// trying to use these on any function that uses `this` will fuck that function
// dont do it
// intercept a function's arguments
wrap: function (target1, callback) {
// get the original function
var orig = eval(target1);
// the stub we will overwrite the function with
function stub() {
// what we will pass to the original function
var args;
try {
// call the wrapper and get our args
args = callback.apply(null, arguments);
}
catch (e) {
__error(e, 'A function wrapper threw an exception');
// dont completely break the function if there's a flaw in the wrapper
args = arguments;
}
// returning undefined results in the function call being suppressed
if (typeof (args) != 'undefined') {
// call the original function
return orig.apply(null, args)
}
}
stub.original = orig;
stub.callback = callback;
callback = callback.bind(stub);
// do the overwriting thing
eval(`${target1}=stub`);
},
// intercept a function's return value
wrapAfter: function (target1, callback) {
// get the original function
var orig = eval(target1);
// the stub we will overwrite the function with
function stub() {
// call the original argument
var r = orig.apply(null, arguments);
try {
// call the wrapper and return its return value
return callback(r);
}
catch (e) {
__error(e, 'A function wrapper threw an exception');
// again, dont fuck stuff up if there's a flaw in the wrapper
return r;
}
}
stub.original = orig;
stub.callback = callback;
callback = callback.bind(stub);
// overwrite that shit
eval(`${target1}=stub`);
},
// extended findFunc that automatically narrows down results
findFuncExports: function (s, e) {
if (e === undefined) e = s;
var results = wc.findFunc(s).filter(x => x !== undefined && x.exports !== undefined && x.exports[e] !== undefined);
if (results.length == 0)
throw Error('findFuncExports() found no matches');
if (results.length > 1)
__warn('findFuncExports() found more than one match');
return results[0].exports;
}
},
// discord internal modules exposed with webcrack, commented out lines' purposes have been forgotten
internal: {
get constants() { return wc.findCache('API_HOST')[0].exports; },
get dispatcher() { return wc.findCache('Dispatcher').filter(x => x.exports !== undefined && x.exports.Store === undefined && x.exports.default !== undefined)[0].exports; },
//get evnt() { wc.findFunc('MESSAGE_CREATE')[1].exports },
get messageUI() { return exports.util.findFuncExports('receiveMessage'); },
get messageCreation() { return exports.util.findFuncExports('createMessage'); },
get notification() { return exports.util.findFuncExports('showNotification', 'setTTSType'); },
//get hguild() { wc.findFunc('leaveGuild')[0].exports },
//get lguild() { wc.findFunc('markGuildAsRead')[0].exports },
get objectStorage() { return wc.findCache('ObjectStorage')[0].exports; },
get user() { return wc.findCache('getUser')[0].exports; },
getId: () => wc.findCache('getId')[0].exports.getId()
},
// discord internal events stuff
// $api.event.* is has no use outside of epapi internal things
// as such, it has been moved to an internal object
events: {
// $listen('ep-native') without all the fuss
listen: function (type, callback) {
if (type === undefined) throw Error('must provide an event type');
if (callback === undefined) throw Error('must provide a callback');
return $listen('ep-native', e => {
if (e.detail.type == type) {
callback(e.detail);
}
});
},
// forge an event and dispatch it
dispatch: function (event) {
if (event.type === undefined) throw Error('must provide an event type');
return $api.internal.dispatcher.default.dirtyDispatch(event);
},
// intercept and modify an event before it can go anywhere
hook: function (type, callback) {
if (type === undefined) throw Error('must provide an event type');
if (callback === undefined) throw Error('must provide a callback');
var newHook = {
type: type,
callback: callback,
unregister: () => {
var i = __hooks.indexOf(newHook);
if (i > -1)
__hooks.splice(i, 1);
}
};
__hooks.push(newHook);
return newHook;
}
},
// discord api stuff
discord: {
// take a wild guess
rest: async function (method, endpoint, body, c) {
// the url we will be making our request to
var url = "https://discordapp.com/api/v6" + endpoint;
// fetch() options
var options = {
headers: {
// get the token from localStorage as our auth header
'Authorization': exports.internal.objectStorage.impl.get('token'),
'Content-type': 'application/json'
},
method: method
};
// if the body isnt already a string go ahead and stringify it
if (typeof (body) !== 'string') body = JSON.stringify(body);
// probably not the best way to handle this
if (method !== 'GET') options.body = body;
// fetch
var r = await fetch(url, options);
if (!r.ok)
throw Error(await r.text());
// urgh, theyre using callbacks
if (c !== undefined) {
// warn the dev
__warn("Using callbacks in REST calls is deprecated and may be removed in a future release.");
// operate like EPAPI =<5.0
c(await r.text());
}
else {
return await r.json();
}
},
// mark a message read
ack: function (channel, id) {
return this.rest('POST', `/channels/${channel}/messages/${id}/ack`);
},
sendMessage: function (channel, text) {
return this.rest('POST', `/channels/${channel}/messages`, { content: text });
},
sendEmbed: function (channel, ebd) {
return this.rest('POST', `/channels/${channel}/messages`, { embed: ebd }
);
},
getGuild: function (id, c) {
return this.rest('GET', `/guilds/${id}`, '', c ? e => c(JSON.parse(e)) : undefined);
},
getChannel: function (id, c) {
return this.rest('GET', '/channels/' + id, '', c ? e => c(JSON.parse(e)) : undefined);
},
getUser: function (id) {
return exports.internal.user.getUser(id);
},
getCurrentUser: function () {
return exports.internal.user.getCurrentUser();
},
getGuildRoles: function (id, c) {
return this.rest('GET', `/guilds/${id}/roles`, '', c ? e => c(JSON.parse(e)) : undefined);
},
getGuildChannels: function (id, c) {
return this.rest('GET', `/guilds/${id}/channels`, '', c ? e => c(JSON.parse(e)) : undefined);
},
getGuildUser: function (guildid, userid, c) {
return this.rest('GET', `/guilds/${guildid}/members/${userid}`, '', c ? e => c(JSON.parse(e)) : undefined);
},
getGuildUsers: function (id, c) {
return this.rest('GET', `/guilds/${id}/members?limit=1000`, '', c ? e => c(JSON.parse(e)) : undefined);
}
},
// ui stuff, including pulling data from the path for some reason
ui: {
// navigate
transitionTo: function (path) {
wc.findCache('transitionTo')[0].exports.transitionTo(path);
},
// focus discord
focus: function () {
electron.getCurrentWindow().focus();
},
// pull the channel id from the url
getCurrentChannel: function () {
var p = window.location.pathname.split('/');
return p[p.length - 1];
},
// pull the guild id from the url
getCurrentGuild: function () {
var p = window.location.pathname.split('/');
return p[p.length - 2];
},
// creates a fake message in the current channel (like clyde)
fakeMsg: function (t, f) {
var msg = exports.internal.messageCreation.createMessage(this.getCurrentChannel(), t);
msg.author.avatar = 'EndPwn'
msg.author.bot = true;
msg.author.discriminator = '0000';
msg.author.id = '1';
msg.author.username = 'EndPwn';
msg.state = 'SENT';
if (typeof (f) != 'undefined') {
f(msg);
}
exports.internal.messageUI.receiveMessage(this.getCurrentChannel(), msg);
},
hideChannels: function () {
$('[class^="channels"]').style.display = 'none';
},
showChannels: function () {
$('[class^="channels"]').style.display = '';
},
hideServers: function () {
$('.guilds-wrapper').style.display = 'none';
},
showServers: function () {
$('.guilds-wrapper').style.display = '';
},
/*hideToolbar: function () {
$('.topic').style.display = 'none';
$('.header-toolbar').style.display = 'none';
},
showToolbar: function () {
$('.topic').style.display = '';
$('.header-toolbar').style.display = '';
},*/
toggleUsers: function () {
wc.findFunc('toggleSection')[1].exports.TOGGLE_USERS.action()
},
// display a dialog box
showDialog: function (x) { // for example, $api.ui.showDialog({title: 'Pwnt!', body: 'It works!'})
exports.util.findFuncExports('e.onConfirmSecondary', 'show').show(x);
},
// display a banner at the top of the app
showNotice: function (text, button) {
exports.util.findFuncExports('ActionTypes.NOTICE_SHOW', 'show').show("GENERIC", text, button, () => { }, 0);
},
// get profile notes for a user
getNote: function (id) {
return $api.util.findFuncExports('getNote', '_actionHandlers').getNote(id);
},
get focused() {
return electron.getCurrentWindow().isFocused();
}
},
// debug, dont touch
__eval: x => eval(x)
}