This repository has been archived by the owner on Mar 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
1210 lines (1117 loc) Β· 52.4 KB
/
index.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
module.exports = (() => {
/* ========== Required Dependencies ========== */
const http = require('http');
const https = require('https');
const url = require('url');
const crypto = require('crypto');
const fs = require('fs');
const moduleDispatcher = global.BdApi.findModuleByProps('dispatch', 'subscribe');
const moduleUserActions = global.BdApi.findModuleByProps('getCurrentUser');
const moduleFileCheck = global.BdApi.findModuleByProps('anyFileTooLarge', 'maxFileSize');
const moduleFileUpload = global.BdApi.findModuleByProps('instantBatchUpload', 'upload');
const moduleMessageActions = global.BdApi.findModuleByProps('sendMessage');
const moduleButtonElement = global.BdApi.findModuleByProps('BorderColors');
const moduleSwitchElement = global.BdApi.findModuleByDisplayName('SwitchItem');
const moduleTextboxElement = global.BdApi.findModule((m) => m.defaultProps && m.defaultProps.type === 'text');
const moduleModalActions = global.BdApi.findModuleByProps('useModalsStore', 'closeModal');
const moduleAttachmentUpload = global.BdApi.findModule((m) => m.AttachmentUpload).AttachmentUpload;
const moduleMessageClasses = {
...global.BdApi.findModule((m) => m.avatar && m.messageContent && m.alt),
...global.BdApi.findModuleByProps('groupStart'),
};
const moduleMessageScrollerClasses = global.BdApi.findModuleByProps('scrollerSpacer');
const moduleDividerClasses = { ...global.BdApi.findModuleByProps('divider'), ...global.BdApi.findModuleByProps('dividerDefault') };
/* ========== Global Constants & Internal Config ========== */
const config = {
meta: {
version: '1.0.0',
name: 'MagicUpload',
description: 'π§ββοΈ A BetterDiscord plugin to automagically upload files over 8MB.',
authors: [{
name: 'mack',
discord_id: '365247132375973889',
github_username: 'mack',
}],
},
oauth: {
handler: {
port: 29842,
host: 'localhost',
},
clientId: '911268808772-r7sa3s88f2o36hdcu9g4tmih6dbo4n77.apps.googleusercontent.com',
clientSecret: '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',
},
storage: {
algorithm: 'aes-256-ctr',
secretKey: 'jXn2r5u8x/A?D*G-KaPdSgVkYp3s6v9y',
iv: crypto.randomBytes(16),
credentialsKey: '_magicupload_oa_creds_gd',
uploadsKey: '_magicupload_files_inprogress',
uploadHistoryKey: '_magicupload_files_completed',
settingsKey: '_magicupload_settings',
defaultSettings: {
autoUpload: true,
uploadEverything: false,
embed: true,
directLink: true,
verbose: false,
},
},
upload: {
// Google Drive requires chunks to be multiples of 256KB
chunkMultiplier: 10,
},
};
const HTTP_CODE_OK = 200;
const HTTP_CODE_UPLOAD_OK = 308;
const HTTP_CODE_UNAUTHORIZED = 401;
const HTTP_CODE_NOT_FOUND = 404;
const HTTP_CODE_INTERNAL_ERR = 500;
// eslint-disable-next-line max-len
const OAUTH_AUTH_URL = `https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/drive&redirect_uri=http://${config.oauth.handler.host}:${config.oauth.handler.port}&response_type=code&client_id=${config.oauth.clientId}`;
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
const OAUTH_REVOKE_URL = 'https://oauth2.googleapis.com/revoke';
const GOOGLE_DRIVE_UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable';
const GOOGLE_DRIVE_API_URL = 'https://www.googleapis.com/drive/v3/files';
const DRIVE_READ_ROLE = 'reader';
const DRIVE_ANYONE_GRANTEE = 'anyone';
const UPLOAD_CANCELLED = 'upload_cancelled';
// eslint-disable-next-line max-len
const SUCCESS_HTML = () => '<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&family=Staatliches&display=swap" rel="stylesheet"> <title>Magic Upload - Google Drive Connected</title> <script src="https://kit.fontawesome.com/9fd6d0c095.js" crossorigin="anonymous"></script> </head> <body> <style> * { box-sizing: border-box; } body { max-width: 870px; margin: 0 auto; } .container { text-align: center; font-family: "Roboto", sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 90vh; position: relative; color: #363636; padding-left: 5rem; padding-right: 5rem; } .header img { width: 80px; } .header { display: flex; align-items: center; font-family: "Staatliches", cursive; font-size: 48px; margin-bottom: 0; } .header i { font-size: 18px; margin: 0 0.5rem; } p { padding: 0 2rem; margin-top: 0; font-size: 18px; line-height: 24px; } .footer { position: absolute; bottom: 1rem; font-size: 14px; opacity: 0.4; } .magic { color: #5e2de5; text-shadow: 0 8px 24px rgb(94 45 229 / 25%); } .tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; } .tooltip .tooltiptext { font-size: 16px; line-height: 20px; visibility: hidden; width: 120px; bottom: 130%; left: 50%; margin-left: -60px; background-color: rgba(0,0,0,0.9); color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; opacity: 0; transition: .3s; position: absolute; z-index: 1; } .tooltip .tooltiptext::after { content: " "; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #363636 transparent transparent transparent; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } a { color: #363636; transition: .3s; } a:hover{ color: #5e2de5; text-shadow: 0 8px 24px rgb(94 45 229 / 25%); } hr { width: 50px; opacity: 0.5; } </style> <div class="container"> <h1 class="header"><span class="magic">MagicUpload</span> <i class="fa-solid fa-link"></i> <img src="https://upload.wikimedia.org/wikipedia/commons/1/12/Google_Drive_icon_%282020%29.svg" /></h1> <hr> <p class="about">β
You"ve successfully linked your Google Drive account! You can now upload files that exceed your discord limit and they"ll automatically uploaded to your drive.</p> <p class="help">Need any help? Checkout our <a href="https://github.com/mack/magic-upload" class="tooltip"> <i class="fa-brands fa-github"></i> <span class="tooltiptext">GitHub</span> </a> or <a href="" class="tooltip"> <i class="fa-brands fa-discord"></i> <span class="tooltiptext">Community Discord</span> </a> . </p> <span class="footer">© Mackenzie Boudreau</span> </div> <script src="https://unpkg.com/[email protected]/dist/scrollreveal.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js"></script> <script> const sr = ScrollReveal({ origin: "top", distance: "60px", duration: 2500, delay: 400, }); sr.reveal(".header", {delay: 700}); sr.reveal("hr", {delay: 500}); sr.reveal(".about", {delay: 900, origin: "bottom"}); sr.reveal(".help", {delay: 1000, origin: "bottom"}); sr.reveal(".footer", {delay: 800, origin: "bottom"}); const jsConfetti = new JSConfetti(); setTimeout(() => { jsConfetti.addConfetti() }, 2000); </script> </body></html>';
// eslint-disable-next-line max-len
const ERROR_HTML = (props) => `<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@300&family=Roboto:wght@300;400;500&family=Staatliches&display=swap" rel="stylesheet"> <title>Magic Upload - Error</title> <script src="https://kit.fontawesome.com/9fd6d0c095.js" crossorigin="anonymous"></script> </head> <body> <style> * { box-sizing: border-box; } body { max-width: 870px; margin: 0 auto; } .container { text-align: center; font-family: "Roboto", sans-serif; display: flex; justify-content: center; align-items: center; flex-direction: column; height: 90vh; position: relative; color: #363636; padding-left: 5rem; padding-right: 5rem; } h1 { font-family: "Staatliches", cursive; font-size: 48px; margin-bottom: 0; } p { padding: 0 2rem; margin-top: 0; font-size: 18px; line-height: 24px; } .footer { position: absolute; bottom: 1rem; font-size: 14px; opacity: 0.4; } .error, .header > i { color: rgb(229, 45, 45); text-shadow: 0 8px 24px rgb(229 45 45 / 25%); } .tooltip { position: relative; display: inline-block; border-bottom: 1px dotted black; } .tooltip .tooltiptext { font-size: 16px; line-height: 20px; visibility: hidden; width: 120px; bottom: 130%; left: 50%; margin-left: -60px; background-color: rgba(0,0,0,0.9); color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; opacity: 0; transition: .3s; position: absolute; z-index: 1; } .tooltip .tooltiptext::after { content: " "; position: absolute; top: 100%; left: 50%; margin-left: -5px; border-width: 5px; border-style: solid; border-color: #363636 transparent transparent transparent; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } a { color: #363636; transition: .3s; } a:hover{ color: #5e2de5; text-shadow: 0 8px 24px rgb(94 45 229 / 25%); } hr { width: 50px; opacity: 0.5; } .error_container { max-width: 100%; position: relative; } .error_container:hover .error_label { opacity: 0.3; } .error_code { font-size: 14px; background-color: rgba(0,0,0,0.92); border-radius: 6px; padding-top: 2rem; padding-bottom: 2rem; padding-right: 2rem; padding-left: 2rem; color: white; text-align: left; word-wrap: break-word; font-family: 'Roboto Mono', monospace; } .error_label { transition: .3s; cursor: default; font-size: 12px; text-transform: uppercase; opacity: 0; color: white; position: absolute; right: 2rem; top: 1rem; } </style> <div class="container"> <h1 class="header"><i class="fa-solid fa-triangle-exclamation"></i> Uh oh, something went <span class="error">wrong</span> <i class="fa-solid fa-triangle-exclamation"></i></h1> <hr> <p class="about">We weren't able to connect your Google Drive account with MagicUpload. Please try again or reach out to help in our community discord. </p> <p class="help">Need any help? Checkout our <a href="https://github.com/mack/magic-upload" class="tooltip"> <i class="fa-brands fa-github"></i> <span class="tooltiptext">GitHub</span> </a> or <a href="" class="tooltip"> <i class="fa-brands fa-discord"></i> <span class="tooltiptext">Community Discord</span> </a> . </p> <div class="error_container"> <span class="error_label">OAuth Response // JSON</span> <div class="error_code"> ${props.error_message} </div> </div> <span class="footer">© Mackenzie Boudreau</span> </div> <script src="https://unpkg.com/[email protected]/dist/scrollreveal.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js"></script> <script> const sr = ScrollReveal({ origin: "top", distance: "60px", duration: 2500, delay: 400, }); sr.reveal(".header", {delay: 700}); sr.reveal("hr", {delay: 500}); sr.reveal(".about", {delay: 900, origin: "bottom"}); sr.reveal(".help", {delay: 1000, origin: "bottom"}); sr.reveal(".error_code", {delay: 1000, origin: "bottom"}); sr.reveal(".footer", {delay: 800, origin: "bottom"}); </script> </body></html>`;
const XUtil = {
log(...message) {
// Forced to get settings manually here.
// Code should be refactored in the future to use getSettings()
const settings = global.BdApi.loadData(config.meta.name, config.storage.settingsKey) || {};
if (settings.verbose) {
XUtil.console(message, 'log');
}
},
info(message) {
XUtil.console(message, 'info');
},
warn(message) {
XUtil.console(message, 'warn');
},
err(message) {
XUtil.console(message, 'err');
},
console(message, type) {
const consoleTypes = {
log: 'log',
info: 'info',
dbg: 'debug',
debug: 'debug',
warn: 'warn',
err: 'error',
error: 'error',
};
const parsedType = Object.prototype.hasOwnProperty.call(consoleTypes, type) ? consoleTypes[type] : 'log';
let parsedMessage = message;
if (!Array.isArray(message)) parsedMessage = [parsedMessage];
console[parsedType](`%c[${config.meta.name}]%c`, 'color: #3a71c1; font-weight: 700;', '', ...parsedMessage);
},
successToast(content, overrides) {
global.BdApi.showToast(content, { type: 'success', ...overrides });
},
infoToast(content, overrides) {
global.BdApi.showToast(content, { type: 'info', ...overrides });
},
warnToast(content, overrides) {
global.BdApi.showToast(content, { type: 'warning', ...overrides });
},
errorToast(content, overrides) {
global.BdApi.showToast(content, { type: 'error', ...overrides });
},
optionsWithAuth(options, storage) {
const modifiedOptions = options;
const accessToken = storage.getAccessToken();
if (accessToken) {
modifiedOptions.headers = { ...options.headers, Authorization: `Bearer ${accessToken}` };
}
return options;
},
encrypt(plain) {
const { algorithm, secretKey, iv } = config.storage;
const cipher = crypto.createCipheriv(algorithm, secretKey, iv);
const encrypted = Buffer.concat([cipher.update(plain), cipher.final()]);
return {
iv: iv.toString('hex'),
content: encrypted.toString('hex'),
};
},
decrypt(hash) {
const { algorithm, secretKey } = config.storage;
const decipher = crypto.createDecipheriv(algorithm, secretKey, Buffer.from(hash.iv, 'hex'));
const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
return decrpyted.toString();
},
override(module, methodName, method, options) {
const cancel = global.BdApi.monkeyPatch(module, methodName, { ...options, instead: method });
if (window.magicUploadOverrides) {
window.magicUploadOverrides.push(cancel);
} else {
window.magicUploadOverrides = [cancel];
}
},
clearOverrides() {
if (Array.isArray(window.magicUploadOverrides)) {
window.magicUploadOverrides.forEach((cancel) => cancel());
}
},
prettifySize(size) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (size === 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)), 10);
return `${Math.round(size / 1024 ** i, 2)} ${sizes[i]}`;
},
prettifyType(type) {
const typeSplit = type.split('/');
if (typeSplit.length == 2) return typeSplit[0];
return undefined;
},
truncate(str, n = 35) {
return (str.length > n) ? `${str.substr(0, n - 1)}...` : str;
},
driveLink(driveId) {
return `https://drive.google.com/file/d/${driveId}`;
},
directDriveLink(driveId) {
return `https://drive.google.com/uc?export=download&id=${driveId}`;
},
discordAvatarLink(userId, avatarId) {
return `https://cdn.discordapp.com/avatars/${userId}/${avatarId}.webp?size=160`;
},
convertFileToMagicFile(file, destination, content) {
return ({
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
name: file.name,
path: file.path,
size: file.size,
type: file.type,
webkitRelativePath: file.webkitRelativePath,
mu_destination: destination,
mu_content: content,
});
},
parseRecievedRange(rangeHeader) {
const range = rangeHeader.split('-');
if (range.length === 2) {
return parseInt(range[1], 10);
}
return undefined;
},
closeLastModal() {
const lastModal = moduleModalActions.useModalsStore.getState().default[0];
if (lastModal) {
moduleModalActions.closeModal(lastModal.key);
}
},
};
class Message {
constructor(messageContent, channelId, timestamp, name, avatarUrl) {
this.channelId = channelId;
const messageContainer = document.createElement('li');
const messageWrapper = document.createElement('div');
const message = document.createElement('div');
message.className = `${moduleMessageClasses.cozy} ${moduleMessageClasses.groupStart} ${moduleMessageClasses.wrapper}`;
const avatar = document.createElement('img');
avatar.src = avatarUrl;
avatar.className = moduleMessageClasses.avatar;
message.appendChild(avatar);
const header = document.createElement('h2');
const username = document.createElement('span');
username.innerHTML = name;
username.className = `${moduleMessageClasses.headerText} ${moduleMessageClasses.username}`;
header.appendChild(username);
const time = document.createElement('span');
time.className = `${moduleMessageClasses.timestamp} ${moduleMessageClasses.timestampInline}`;
time.innerHTML = timestamp;
header.appendChild(time);
message.appendChild(header);
if (messageContent instanceof HTMLElement) {
message.appendChild(messageContent);
} else {
message.innerText += messageContent;
}
messageWrapper.appendChild(message);
messageContainer.appendChild(messageWrapper);
this.messageContainer = messageContainer;
}
element() {
return this.messageContainer;
}
destination() {
return this.channelId;
}
show() {
const scrollerInner = document.querySelector(`.${moduleMessageScrollerClasses.scrollerInner}`);
const scrollerSpacer = document.querySelector(`.${moduleMessageScrollerClasses.scrollerSpacer}`);
if (scrollerInner) scrollerInner.insertBefore(this.messageContainer, scrollerSpacer);
}
destroy() {
if (this.messageContainer) {
this.messageContainer.remove();
}
}
}
class UploadAttachment extends Message {
constructor(destination, fileName, fileSize, initalProgress, onCancelUpload) {
const container = document.createElement('div');
const attachment = global.BdApi.React.createElement(moduleAttachmentUpload, {
filename: fileName,
size: fileSize,
progress: initalProgress,
onCancelUpload,
});
global.BdApi.ReactDOM.render(attachment, container);
const user = moduleUserActions.getCurrentUser();
super(container, destination, 'Powered by MagicUpload', user.username, XUtil.discordAvatarLink(user.id, user.avatar));
this.attachment = attachment;
this.container = container;
}
setProgress(progress) {
const newProgress = Math.min(Math.max(progress, 0), 100);
this.attachment.props.progress = newProgress;
const progressBarClass = this.container.innerHTML.match(/class="(progressBar-[^\s"]*)/)[1];
const progressBar = this.container.querySelector(`.${progressBarClass}`);
progressBar.style.transform = `translate3d(-${100 - this.attachment.props.progress}%, 0px, 0px)`;
}
progress() {
return this.attachment.props.progress;
}
}
/* ========== File Uploader ========== */
class FileUploader {
static sendFileLinkMessage(file, link) {
XUtil.log(`Sending file share link to channel: ${file.mu_destination}.`);
const formattedMessage = file.mu_content !== '' ? `${file.mu_content}\n${link}` : link;
moduleMessageActions.sendMessage(
file.mu_destination,
{
content: formattedMessage,
validNonShortcutEmojis: [],
},
);
}
constructor(storage, oauther) {
this.storage = storage;
this.oauther = oauther;
this.uploadAttachments = {};
this.cancelationQueue = {};
this.handleChannelSelect = (e) => this.checkForAttachments(e.channelId);
moduleDispatcher.subscribe('CHANNEL_SELECT', this.handleChannelSelect);
this.continue();
}
cleanup() {
moduleDispatcher.unsubscribe('CHANNEL_SELECT', this.handleChannelSelect);
}
checkForAttachments(channelId) {
Object.keys(this.uploadAttachments).forEach((streamLocation) => {
if (this.uploadAttachments[streamLocation].destination() === channelId) {
// Add slight delay to account for DOM loading.
setTimeout(() => {
this.uploadAttachments[streamLocation].show();
}, 200);
}
});
}
cancelFileHandler(streamLocation) {
return () => {
this.cancelationQueue[streamLocation] = true;
};
}
continue() {
const registeredUploads = this.getRegisteredUploads();
Object.keys(registeredUploads).forEach((streamLocation) => {
if (Object.prototype.hasOwnProperty.call(registeredUploads, streamLocation)) {
this.getStreamStatus(streamLocation, (response) => {
switch (response.status) {
case HTTP_CODE_OK: {
// File has finished uploading, remove from registry
this.unregisterUpload(streamLocation);
break;
}
case HTTP_CODE_UPLOAD_OK: {
XUtil.log('Resuming inprogress upload.');
// Upload session active, resume upload
const cursor = XUtil.parseRecievedRange(response.headers.get('Range'));
this.streamChunks(
streamLocation,
registeredUploads[streamLocation],
cursor,
(driveItem, file, err) => {
// Completed upload. Remove from registry and
// handle successful and unsuccessful completed uploads.
this.uploadAttachments[streamLocation].destroy();
delete this.uploadAttachments[streamLocation];
this.unregisterUpload(streamLocation);
if (err === null && driveItem) {
// Upload was successful, add permissions and share!
this.storage.patchUploadHistory({ uploadedAt: new Date().toUTCString(), driveItem, file });
XUtil.info(`${file.name} has been successfully uploaded to Google Drive.`);
this.share(driveItem.id, () => {
XUtil.info(`${file.name} permissions have been updated to "anyone with link".`);
const shareLink = this.storage.getSettings().directLink
? XUtil.directDriveLink(driveItem.id) : XUtil.driveLink(driveItem.id);
FileUploader.sendFileLinkMessage(file, shareLink);
});
} else if (err.message && err.message === UPLOAD_CANCELLED) {
XUtil.warn('Upload has been cancelled.');
XUtil.infoToast(`Upload ${XUtil.truncate(file.name, 35)} has been cancelled`);
} else {
XUtil.err('Upload has failed.');
XUtil.errorToast(`Upload failed ${XUtil.truncate(file.name, 35)}`);
}
},
);
break;
}
case HTTP_CODE_NOT_FOUND: {
// Upload session has expired, restart upload
const file = registeredUploads[streamLocation];
this.unregisterUpload(streamLocation);
this.upload(file);
break;
}
default:
}
});
}
});
}
getRegisteredUploads() {
return this.storage.load(config.storage.uploadsKey) || {};
}
registerUpload(streamLocation, file) {
XUtil.log('Registering new file into upload registry.');
const fileCopy = JSON.parse(JSON.stringify(file));
const registry = this.getRegisteredUploads();
registry[streamLocation] = fileCopy;
this.storage.store(config.storage.uploadsKey, registry);
}
unregisterUpload(streamLocation) {
XUtil.log('Unregistering file from upload registry.');
const registry = this.getRegisteredUploads();
delete registry[streamLocation];
this.storage.store(config.storage.uploadsKey, registry);
}
getStreamStatus(streamLocation, callback) {
const options = XUtil.optionsWithAuth({
method: 'PUT',
headers: {
'Content-Length': 0,
'Content-Range': 'bytes 0-*/*',
},
}, this.storage);
fetch(streamLocation, options).then((response) => {
if (callback) callback(response);
});
}
streamChunks(streamLocation, file, from, callback) {
// Check to see if there is an existing message attachment.
// If none, create a new one.
if (!this.uploadAttachments[streamLocation]) {
this.uploadAttachments[streamLocation] = new UploadAttachment(
file.mu_destination,
file.name,
file.size,
0,
this.cancelFileHandler(streamLocation),
);
this.uploadAttachments[streamLocation].show();
}
const { uploadAttachments, cancelationQueue } = this;
const accessToken = this.storage.getAccessToken();
// const unregisterUpload = this.storage.unregisterUpload;
const CHUNK_SIZE = config.upload.chunkMultiplier * 256 * 1024;
const buffer = Buffer.alloc(CHUNK_SIZE);
fs.open(file.path, 'r', (err, fd) => {
if (err || !fd || typeof fd !== 'number') {
callback(null, file, err);
}
const readNextChunk = (cursor) => {
// Interupt a file from uploading if user cancels
if (cancelationQueue[streamLocation]) {
callback(null, file, new Error(UPLOAD_CANCELLED));
return;
}
fs.read(fd, buffer, 0, CHUNK_SIZE, cursor, (err, byteLength) => {
if (err) {
callback(null, file, err);
}
let chunk;
if (byteLength < CHUNK_SIZE) {
// Read bytes are smaller than the chunk size.
// This can occur when a file is smaller than the
// chunk size, or we are uploading the last portion
// of a file.
chunk = buffer.slice(0, byteLength);
} else {
chunk = buffer;
}
const start = cursor;
const end = cursor + (chunk.length - 1); // -1 start cuz zero index
const total = file.size;
const locaton = new URL(streamLocation);
const options = {
host: locaton.host,
path: locaton.pathname + locaton.search,
method: 'PUT',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Length': chunk.length,
'Content-Range': `bytes ${start}-${end}/${total}`,
},
};
XUtil.log(`[${((start / total) * 100).toFixed(2)}%] Uploading ${file.name} (${start}/${total})`);
uploadAttachments[streamLocation].setProgress((start / total) * 100);
// Fetch unfortunately does handle Buffer objects well
// so we're forced to use `https` to process our requests
const uploadChunk = https.request(options, (res) => {
if (res.statusCode === HTTP_CODE_UPLOAD_OK) {
readNextChunk(XUtil.parseRecievedRange(res.headers.range));
}
if (res.statusCode === HTTP_CODE_OK) {
// File has been uploaded
let responseData = '';
res.on('data', (chunk) => { responseData += chunk; });
res.on('close', () => {
fs.close(fd, () => {
XUtil.successToast(`Successfully uploaded ${XUtil.truncate(file.name, 35)}`);
callback(JSON.parse(responseData), file, null);
});
});
}
});
uploadChunk.write(chunk);
uploadChunk.end();
});
};
readNextChunk(from);
});
}
share(driveId, callback, retry) {
const body = {
role: DRIVE_READ_ROLE,
type: DRIVE_ANYONE_GRANTEE,
};
const options = XUtil.optionsWithAuth({
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(body),
}, this.storage);
fetch(`${GOOGLE_DRIVE_API_URL}/${driveId}/permissions`, options).then((response) => response.json())
.then((data) => {
if (data.error) {
if (data.error.code === HTTP_CODE_UNAUTHORIZED && !retry) {
this.oauther.refresh(() => {
this.share(driveId, callback, true);
});
}
} else if (callback) callback();
});
}
upload(file, retry) {
XUtil.info(`Beginning upload for: ${file.name}`);
const body = {
name: file.name,
mimeType: file.type,
};
const options = XUtil.optionsWithAuth({
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Content-Length': file.size,
},
body: JSON.stringify(body),
}, this.storage);
fetch(GOOGLE_DRIVE_UPLOAD_URL, options).then((response) => {
if (response.status === HTTP_CODE_OK) {
const streamLocation = response.headers.get('Location');
// Forced to copy the file reference.
this.registerUpload(streamLocation, file);
this.streamChunks(streamLocation, file, 0, (driveItem, file, err) => {
// Completed upload. Remove from registry and
// handle successful and unsuccessful completed uploads.
this.uploadAttachments[streamLocation].destroy();
delete this.uploadAttachments[streamLocation];
this.unregisterUpload(streamLocation);
if (err === null && driveItem) {
// Upload was successful, add permissions and share!
this.storage.patchUploadHistory({ uploadedAt: new Date().toUTCString(), driveItem, file });
XUtil.info(`${file.name} has been successfully uploaded to Google Drive.`);
this.share(driveItem.id, () => {
XUtil.info(`${file.name} permissions have been updated to "anyone with link.`);
const shareLink = this.storage.getSettings().directLink
? XUtil.directDriveLink(driveItem.id) : XUtil.driveLink(driveItem.id);
FileUploader.sendFileLinkMessage(file, shareLink);
});
} else if (err.message && err.message === UPLOAD_CANCELLED) {
XUtil.warn('Upload has been cancelled.');
XUtil.infoToast(`Upload ${XUtil.truncate(file.name, 35)} has been cancelled`);
} else {
XUtil.err('Upload has failed.');
XUtil.errorToast(`Upload failed ${XUtil.truncate(file.name, 35)}`);
}
});
} else if (response.status === HTTP_CODE_UNAUTHORIZED && !retry) {
// Access token may be expired, try to refresh
this.oauther.refresh(() => {
XUtil.log('OAuth tokens potentially expired. Retry upload');
this.upload(file, true);
});
}
});
}
}
/* ========== Persistant Storage ========== */
class StorageHandler {
constructor(pluginName) {
this.pluginName = pluginName;
/* Alias Functions */
const {
credentialsKey,
uploadHistoryKey,
settingsKey,
defaultSettings,
} = config.storage;
// OAuth Helpers
this.deleteCredentials = () => this.delete(credentialsKey);
this.getAccessToken = () => {
const credentials = this.load(credentialsKey, true);
return credentials && credentials.access_token;
};
this.patchAccessToken = (token) => {
const credentials = this.load(credentialsKey, true);
credentials.access_token = token;
this.store(credentialsKey, credentials, true);
return token;
};
// FileUploader Helpers
this.getUploadHistory = () => this.load(uploadHistoryKey, false) || [];
this.patchUploadHistory = (completedUpload) => {
const uploadHistory = this.getUploadHistory();
uploadHistory.push(completedUpload);
this.store(uploadHistoryKey, uploadHistory, false);
};
this.clearUploadHistory = () => {
XUtil.log('Clearing upload history...');
this.store(uploadHistoryKey, [], false);
};
// Setting Helpers
this.getSettings = () => this.load(settingsKey, false) || defaultSettings;
this.saveSettings = (settings) => this.store(settingsKey, settings, false);
this.patchSettings = (newSettings) => {
// eslint-disable-next-line no-undef
const combined = _.merge(this.getSettings(), newSettings);
this.saveSettings(combined);
};
}
load(key, decrypt) {
let data = global.BdApi.loadData(this.pluginName, key);
if (data && decrypt) {
// Base64 decode the hash
const hash = Buffer.from(data, 'base64').toString('ascii');
data = JSON.parse(XUtil.decrypt(JSON.parse(hash)));
}
return data;
}
store(key, obj, encrypt) {
let data;
if (encrypt) {
const hash = XUtil.encrypt(JSON.stringify(obj));
// Base64 encode the hash
data = Buffer.from(JSON.stringify(hash)).toString('base64');
} else {
data = obj;
}
global.BdApi.saveData(this.pluginName, key, data);
}
delete(key) {
global.BdApi.deleteData(this.pluginName, key);
}
}
/* ========== OAuth Logic ========== */
class OAuther {
static postAccessToken(authorizationCode, callback) {
const body = new URLSearchParams({
client_id: config.oauth.clientId,
client_secret: config.oauth.clientSecret,
code: authorizationCode,
grant_type: 'authorization_code',
redirect_uri: `http://${config.oauth.handler.host}:${config.oauth.handler.port}`,
}).toString();
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body,
};
fetch(OAUTH_TOKEN_URL, options).then((response) => response.json()).then((data) => {
if (callback) callback(data);
});
}
static postRefreshAccessToken(refreshToken, callback) {
const body = new URLSearchParams({
client_id: config.oauth.clientId,
client_secret: config.oauth.clientSecret,
refresh_token: refreshToken,
grant_type: 'refresh_token',
}).toString();
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body,
};
fetch(OAUTH_TOKEN_URL, options).then((response) => response.json()).then((data) => {
if (callback) callback(data);
});
}
static postRevokeToken(token) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
fetch(`${OAUTH_REVOKE_URL}?token=${token}`, options).then((response) => {
if (response.status === HTTP_CODE_OK) {
XUtil.info('OAuth Token has successfully been revoked.');
} else {
XUtil.warn('Unable to revoke OAuth token.');
}
});
}
constructor(storage, flowCompleted, originalThis) {
this.storage = storage;
this.server = http.createServer((req, res) => {
const { query } = url.parse(req.url, true);
if (query.code) {
XUtil.log('Recieved authorization code.');
OAuther.postAccessToken(query.code, (credentials) => {
if (credentials.access_token && credentials.refresh_token) {
XUtil.log('Exchanged authorization code for access and refresh tokens.');
this.storage.store(config.storage.credentialsKey, credentials, true);
res.writeHeader(HTTP_CODE_OK, { 'Content-Type': 'text/html' });
res.write(SUCCESS_HTML());
XUtil.successToast('Google Drive connected!', { timeout: 5500 });
XUtil.info('Google Drive successfully linked.');
if (flowCompleted) flowCompleted(originalThis);
} else {
XUtil.err('Failed to retrieve access and refresh tokens.');
res.writeHeader(HTTP_CODE_INTERNAL_ERR, { 'Content-Type': 'text/html' });
res.write(ERROR_HTML({ error_message: JSON.stringify(credentials) }));
XUtil.errorToast('An error occured connecting Google Drive', { timeout: 5500 });
}
res.end();
this.cleanup();
});
}
});
}
launch() {
this.activateHandler(() => {
XUtil.log('Sending user to OAuth consent flow.');
window.open(OAUTH_AUTH_URL);
});
}
activateHandler(callback) {
if (this.server.listening) {
callback();
return;
}
const { port, host } = config.oauth.handler;
this.server.listen(port, host, () => {
XUtil.log(`Listening for OAuth redirects on http://${host}:${port}...`);
if (callback) callback();
});
}
cleanup(callback) {
if (this.server.listening) {
this.server.close(callback);
}
}
refresh(callback) {
const credentials = this.storage.load(config.storage.credentialsKey, true);
const refreshToken = credentials.refresh_token;
if (refreshToken) {
OAuther.postRefreshAccessToken(refreshToken, (newCredentals) => {
const accessToken = newCredentals.access_token;
if (accessToken) {
// Access token has been refreshed.
XUtil.log('Successfully refreshed access token.');
this.storage.patchAccessToken(accessToken);
if (callback) callback(accessToken);
} else {
// Refresh token may have expired, force another oauth prompt
XUtil.warn('Refresh token may have expired. Please reconnect your Google account.');
this.storage.deleteCredentials();
this.launch();
}
});
} else {
XUtil.err('Something went wrong. Clearing OAuth credentials.');
this.storage.deleteCredentials();
}
}
}
/* ========== Magic Upload Plugin ========== */
return class MagicUpload {
getName() { return config.meta.name; }
getAuthor() { return config.meta.authors.map((a) => a.name).join(', '); }
getDescription() { return config.meta.description; }
getVersion() { return config.meta.version; }
openOAuthPrompt() {
global.BdApi.showConfirmationModal(
'π Connect your Google Drive',
'Magic Upload requires Google Drive. To use this plugin you must connect your Google account.',
{
confirmText: 'Connect Google Account',
cancelText: 'Disable Plugin',
onConfirm: () => {
this.oauther.launch();
},
onCancel: () => {
global.BdApi.Plugins.disable(this.getName());
},
},
);
}
// eslint-disable-next-line class-methods-use-this
openUploadPrompt(file, callback) {
const fileName = XUtil.truncate(file.name);
const fileType = XUtil.prettifyType(file.type);
const fileSize = XUtil.prettifySize(file.size);
global.BdApi.showConfirmationModal(fileName, [
`Are you sure you want to upload this ${fileType || 'file'} (${fileSize}) to Google Drive and share it?`,
], {
confirmText: 'Upload to Drive',
cancelText: 'Cancel',
onConfirm: () => {
callback();
},
});
}
/* ========== Plugin Lifecycle Methods ========== */
load() {
this.storage = new StorageHandler(this.getName());
this.oauther = new OAuther(this.storage, this.overrideDiscordUpload, this);
this.uploader = new FileUploader(this.storage, this.oauther);
}
overrideDiscordUpload(originalThis) {
/* Patch upload methods */
const { realUploadLimit, storage, uploader } = originalThis;
XUtil.log('Overriding default file upload functionality.');
XUtil.override(moduleFileCheck, 'maxFileSize', ({ methodArguments, callOriginalMethod }) => {
const useOriginal = methodArguments[1];
if (useOriginal === true) {
return callOriginalMethod();
}
return Number.MAX_VALUE;
});
XUtil.override(moduleFileCheck, 'anyFileTooLarge', () => false);
XUtil.override(moduleFileCheck, 'uploadSumTooLarge', () => false);
XUtil.override(moduleFileCheck, 'getUploadFileSizeSum', () => 0);
XUtil.override(moduleFileUpload, 'uploadFiles', ({ methodArguments, thisObject, originalMethod }) => {
const [originalArguments] = methodArguments;
const { channelId, uploads, parsedMessage } = originalArguments;
uploads.forEach((upload) => {
if (!storage.getSettings().uploadEverything
&& upload.item.file.size < realUploadLimit) {
// File is within discord upload limit, upload as normal
XUtil.info(`File "${upload.item.file.name}" is within discords upload limit, using default file uploader.`);
const argsCopy = { ...originalArguments };
argsCopy.uploads = [upload];
originalMethod.apply(thisObject, [argsCopy]);
} else {
XUtil.info(`File "${upload.item.file.name}" exceeds upload limit, using ${config.meta.name} uploader.`);
const magicFile = XUtil.convertFileToMagicFile(
upload.item.file,
channelId,
parsedMessage.content,
);
if (storage.getSettings().autoUpload) {
uploader.upload(magicFile);
} else {
this.openUploadPrompt(magicFile, () => this.uploader.upload(magicFile));
}
}
});
});
}
start() {
XUtil.info('MagicUpload has started.');
this.realUploadLimit = moduleFileCheck.maxFileSize('', true);
if (!this.storage.getAccessToken()) {
// No token found. Prompt user to connect Google Drive.
this.openOAuthPrompt();
} else {
this.overrideDiscordUpload(this);
}
}
stop() {
XUtil.info('MagicUpload has stopped.');
XUtil.clearOverrides();
this.oauther.cleanup();
this.uploader.cleanup();
}
createSettingsCategory(children) {
const category = document.createElement('div');
category.className = moduleDividerClasses.container;
category.appendChild(children);
const categoryDivider = document.createElement('div');
categoryDivider.className = `${moduleDividerClasses.divider} ${moduleDividerClasses.dividerDefault}`;
categoryDivider.style.borderTop = 'thin solid #4f545c7a';
categoryDivider.style.height = '1px';
category.appendChild(categoryDivider);
return category;
}
createSwitchControl(config) {
class SwitchWrapper extends global.BdApi.React.Component {
constructor(props) {
super(props);
this.state = { enabled: this.props.value };
}
render() {
return global.BdApi.React.createElement(moduleSwitchElement, {
...this.props,
value: this.state.enabled,
onChange: (e) => {
this.props.onChange(e);
this.setState({ enabled: e });
},
});
}
}
const switchContainer = document.createElement('div');
const reactSwitch = global.BdApi.React.createElement(SwitchWrapper, {
value: config.value,
children: config.name,
note: config.note,
disabled: config.disabled,
onChange: config.onChange,
});
global.BdApi.ReactDOM.render(reactSwitch, switchContainer);
return switchContainer;
}
createButtonControl(config) {
const buttonContainer = document.createElement('div');
buttonContainer.style.marginTop = '8px';
const reactButton = global.BdApi.React.createElement(moduleButtonElement, {
children: config.name,
onClick: config.onClick,
});
global.BdApi.ReactDOM.render(reactButton, buttonContainer);
return buttonContainer;
}
createTextBoxControl(config) {
const textBoxContainer = document.createElement('div');
textBoxContainer.style.marginTop = '8px';
textBoxContainer.style.marginBottom = '20px';
const reactButton = global.BdApi.React.createElement(moduleTextboxElement, {
value: config.value,
disabled: config.disabled,
placeholder: config.placeholder || '',
});
global.BdApi.ReactDOM.render(reactButton, textBoxContainer);