forked from ScattrdBlade/bigFileUpload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
809 lines (729 loc) · 32.4 KB
/
index.tsx
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
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { ApplicationCommandInputType, ApplicationCommandOptionType, Argument, CommandContext, sendBotMessage } from "@api/Commands";
import { NavContextMenuPatchCallback } from "@api/ContextMenu";
import { definePluginSettings } from "@api/Settings";
import { Flex } from "@components/Flex";
import { OpenExternalIcon } from "@components/Icons";
import { Devs } from "@utils/constants";
import { insertTextIntoChatInputBox, sendMessage } from "@utils/discord";
import { Margins } from "@utils/margins";
import definePlugin, { OptionType, PluginNative } from "@utils/types";
import { findByPropsLazy } from "@webpack";
import { Button, DraftType, Forms, Menu, PermissionsBits, PermissionStore, React, Select, SelectedChannelStore, showToast, TextInput, UploadManager, useEffect, useState } from "@webpack/common";
const Native = VencordNative.pluginHelpers.BigFileUpload as PluginNative<typeof import("./native")>;
const UploadStore = findByPropsLazy("getUploads");
const OptionClasses = findByPropsLazy("optionName", "optionIcon", "optionLabel");
function createCloneableStore(initialState: any) {
const store = { ...initialState };
const listeners: (() => void)[] = [];
function get() {
return { ...store };
}
function set(newState: Partial<typeof store>) {
Object.assign(store, newState);
listeners.forEach(listener => listener());
}
function subscribe(listener: () => void) {
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
if (index > -1) {
listeners.splice(index, 1);
}
};
}
return {
get,
set,
subscribe
};
}
function SettingsComponent(props: { setValue(v: any): void; }) {
const [fileUploader, setFileUploader] = useState(settings.store.fileUploader || "GoFile");
const [customUploaderStore] = useState(() => createCloneableStore({
name: settings.store.customUploaderName || "",
requestURL: settings.store.customUploaderRequestURL || "",
fileFormName: settings.store.customUploaderFileFormName || "",
responseType: settings.store.customUploaderResponseType || "",
url: settings.store.customUploaderURL || "",
thumbnailURL: settings.store.customUploaderThumbnailURL || "",
headers: (() => {
const parsedHeaders = JSON.parse(settings.store.customUploaderHeaders || "{}");
if (Object.keys(parsedHeaders).length === 0) {
parsedHeaders[""] = "";
}
return parsedHeaders;
})(),
args: (() => {
const parsedArgs = JSON.parse(settings.store.customUploaderArgs || "{}");
if (Object.keys(parsedArgs).length === 0) {
parsedArgs[""] = "";
}
return parsedArgs;
})(),
}));
const fileInputRef = React.useRef<HTMLInputElement>(null);
useEffect(() => {
const unsubscribe = customUploaderStore.subscribe(() => {
const state = customUploaderStore.get();
updateSetting("customUploaderName", state.name);
updateSetting("customUploaderRequestURL", state.requestURL);
updateSetting("customUploaderFileFormName", state.fileFormName);
updateSetting("customUploaderResponseType", state.responseType);
updateSetting("customUploaderURL", state.url);
updateSetting("customUploaderThumbnailURL", state.thumbnailURL);
updateSetting("customUploaderHeaders", JSON.stringify(state.headers));
updateSetting("customUploaderArgs", JSON.stringify(state.args));
});
return unsubscribe;
}, []);
function updateSetting(key: keyof typeof settings.store, value: any) {
if (key in settings.store) {
settings.store[key] = value;
} else {
console.error(`Invalid setting key: ${key}`);
}
}
function handleShareXConfigUpload(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e: ProgressEvent<FileReader>) => {
try {
const config = JSON.parse(e.target?.result as string);
customUploaderStore.set({
name: "",
requestURL: "",
fileFormName: "",
responseType: "Text",
url: "",
thumbnailURL: "",
headers: { "": "" },
args: { "": "" }
});
customUploaderStore.set({
name: config.Name || "",
requestURL: config.RequestURL || "",
fileFormName: config.FileFormName || "",
responseType: config.ResponseType || "Text",
url: config.URL || "",
thumbnailURL: config.ThumbnailURL || "",
headers: config.Headers || { "": "" },
args: config.Arguments || { "": "" }
});
updateSetting("customUploaderName", config.Name || "");
updateSetting("customUploaderRequestURL", config.RequestURL || "");
updateSetting("customUploaderFileFormName", config.FileFormName || "");
updateSetting("customUploaderResponseType", config.ResponseType || "Text");
updateSetting("customUploaderURL", config.URL || "");
updateSetting("customUploaderThumbnailURL", config.ThumbnailURL || "");
updateSetting("customUploaderHeaders", JSON.stringify(config.Headers || { "": "" }));
updateSetting("customUploaderArgs", JSON.stringify(config.Arguments || { "": "" }));
setFileUploader("Custom");
updateSetting("fileUploader", "Custom");
showToast("ShareX config imported successfully!");
} catch (error) {
console.error("Error parsing ShareX config:", error);
showToast("Error importing ShareX config. Check console for details.");
}
};
reader.readAsText(file);
event.target.value = "";
}
}
const validateCustomUploaderSettings = () => {
if (fileUploader === "Custom") {
if (!settings.store.customUploaderRequestURL) {
showToast("Custom uploader request URL is required.");
return false;
}
if (!settings.store.customUploaderFileFormName) {
showToast("Custom uploader file form name is required.");
return false;
}
if (!settings.store.customUploaderURL) {
showToast("Custom uploader URL (JSON path) is required.");
return false;
}
}
return true;
};
const handleFileUploaderChange = (v: string) => {
if (v === "Custom" && !validateCustomUploaderSettings()) {
return;
}
setFileUploader(v);
updateSetting("fileUploader", v);
};
const handleArgChange = (oldKey: string, newKey: string, value: any) => {
const state = customUploaderStore.get();
const newArgs = { ...state.args };
if (oldKey !== newKey) {
delete newArgs[oldKey];
}
if (value === "" && newKey === "") {
delete newArgs[oldKey];
} else {
newArgs[newKey] = value;
}
customUploaderStore.set({ args: newArgs });
if (Object.values(newArgs).every(v => v !== "") && Object.keys(newArgs).every(k => k !== "")) {
newArgs[""] = "";
}
customUploaderStore.set({ args: newArgs });
};
const handleHeaderChange = (oldKey: string, newKey: string, value: string) => {
const state = customUploaderStore.get();
const newHeaders = { ...state.headers };
if (oldKey !== newKey) {
delete newHeaders[oldKey];
}
if (value === "" && newKey === "") {
delete newHeaders[oldKey];
} else {
newHeaders[newKey] = value;
}
customUploaderStore.set({ headers: newHeaders });
if (Object.values(newHeaders).every(v => v !== "") && Object.keys(newHeaders).every(k => k !== "")) {
newHeaders[""] = "";
}
customUploaderStore.set({ headers: newHeaders });
};
const triggerFileUpload = () => {
if (fileInputRef.current) {
fileInputRef.current.click();
}
};
return (
<Flex flexDirection="column">
{/* File Uploader Selection */}
<Forms.FormSection title="Select the file uploader service">
<Select
options={[
{ label: "Custom Uploader", value: "Custom" },
{ label: "Catbox", value: "Catbox" },
{ label: "Litterbox", value: "Litterbox" },
{ label: "GoFile", value: "GoFile" },
]}
placeholder="Select the file uploader service"
className={Margins.bottom16}
select={handleFileUploaderChange}
isSelected={v => v === fileUploader}
serialize={v => v}
/>
</Forms.FormSection>
{/* GoFile Settings */}
{fileUploader === "GoFile" && (
<>
<Forms.FormDivider />
<Forms.FormTitle>GoFile Settings</Forms.FormTitle>
<Forms.FormSection title="GoFile Token (optional)">
<TextInput
type="text"
value={settings.store.gofileToken || ""}
placeholder="Insert GoFile Token"
onChange={newValue => updateSetting("gofileToken", newValue)}
className={Margins.bottom16}
/>
</Forms.FormSection>
</>
)}
{/* Auto-Send Settings */}
<Forms.FormSection title="Auto-Send">
<Select
options={[
{ label: "Yes", value: "Yes" },
{ label: "No", value: "No" },
]}
placeholder="Select Auto-Send"
className={Margins.bottom16}
select={newValue => updateSetting("autoSend", newValue)}
isSelected={v => v === settings.store.autoSend}
serialize={v => v}
/>
</Forms.FormSection>
{/* Catbox Settings */}
{fileUploader === "Catbox" && (
<>
<Forms.FormDivider />
<Forms.FormTitle>Catbox Settings</Forms.FormTitle>
<Forms.FormSection title="Catbox User hash (optional)">
<TextInput
type="text"
value={settings.store.catboxUserHash || ""}
placeholder="Insert User Hash"
onChange={newValue => updateSetting("catboxUserHash", newValue)}
className={Margins.bottom16}
/>
</Forms.FormSection>
</>
)}
{/* Litterbox Settings */}
{fileUploader === "Litterbox" && (
<>
<Forms.FormDivider />
<Forms.FormTitle>Litterbox Settings</Forms.FormTitle>
<Forms.FormSection title="Select the file expiration time">
<Select
options={[
{ label: "1 hour", value: "1h" },
{ label: "12 hours", value: "12h" },
{ label: "24 hours", value: "24h" },
{ label: "72 hours", value: "72h" },
]}
placeholder="Select Duration"
className={Margins.bottom16}
select={newValue => updateSetting("litterboxTime", newValue)}
isSelected={v => v === settings.store.litterboxTime}
serialize={v => v}
/>
</Forms.FormSection>
</>
)}
{/* Custom Uploader Settings */}
{fileUploader === "Custom" && (
<>
<Forms.FormSection title="Name of the custom uploader">
<TextInput
type="text"
value={customUploaderStore.get().name}
placeholder="Name"
onChange={(newValue: string) => customUploaderStore.set({ name: newValue })}
className={Margins.bottom16}
/>
</Forms.FormSection>
<Forms.FormSection title="Request URL for the custom uploader">
<TextInput
type="text"
value={customUploaderStore.get().requestURL}
placeholder="Request URL"
onChange={(newValue: string) => customUploaderStore.set({ requestURL: newValue })}
className={Margins.bottom16}
/>
</Forms.FormSection>
<Forms.FormSection title="File form name for the custom uploader">
<TextInput
type="text"
value={customUploaderStore.get().fileFormName}
placeholder="File Form Name"
onChange={(newValue: string) => customUploaderStore.set({ fileFormName: newValue })}
className={Margins.bottom16}
/>
</Forms.FormSection>
<Forms.FormSection title="Response type for the custom uploader">
<Select
options={[
{ label: "Text", value: "Text" },
{ label: "JSON", value: "JSON" },
]}
placeholder="Select Response Type"
className={Margins.bottom16}
select={(newValue: string) => customUploaderStore.set({ responseType: newValue })}
isSelected={(v: string) => v === customUploaderStore.get().responseType}
serialize={(v: string) => v}
/>
</Forms.FormSection>
<Forms.FormSection title="URL (JSON path) for the custom uploader">
<TextInput
type="text"
value={customUploaderStore.get().url}
placeholder="URL (JSON path)"
onChange={(newValue: string) => customUploaderStore.set({ url: newValue })}
className={Margins.bottom16}
/>
</Forms.FormSection>
<Forms.FormSection title="Thumbnail URL (JSON path) for the custom uploader">
<TextInput
type="text"
value={customUploaderStore.get().thumbnailURL}
placeholder="Thumbnail URL (JSON path)"
onChange={(newValue: string) => customUploaderStore.set({ thumbnailURL: newValue })}
className={Margins.bottom16}
/>
</Forms.FormSection>
<Forms.FormDivider />
<Forms.FormTitle>Custom Uploader Arguments</Forms.FormTitle>
{Object.entries(customUploaderStore.get().args).map(([key, value], index) => (
<div key={index}>
<TextInput
type="text"
value={key}
placeholder="Argument Key"
onChange={(newKey: string) => handleArgChange(key, newKey, value as string)}
className={Margins.bottom16}
/>
<TextInput
type="text"
value={value as string}
placeholder="Argument Value"
onChange={(newValue: string) => handleArgChange(key, key, newValue)}
className={Margins.bottom16}
/>
</div>
))}
<Forms.FormDivider />
<Forms.FormTitle>Headers</Forms.FormTitle>
{Object.entries(customUploaderStore.get().headers).map(([key, value], index) => (
<div key={index}>
<TextInput
type="text"
value={key}
placeholder="Header Key"
onChange={(newKey: string) => handleHeaderChange(key, newKey, value as string)}
className={Margins.bottom16}
/>
<TextInput
type="text"
value={value as string}
placeholder="Header Value"
onChange={(newValue: string) => handleHeaderChange(key, key, newValue)}
className={Margins.bottom16}
/>
</div>
))}
<Forms.FormDivider />
<Forms.FormTitle>Import ShareX Config</Forms.FormTitle>
<Button
onClick={triggerFileUpload}
color={Button.Colors.BRAND}
size={Button.Sizes.XLARGE}
className={Margins.bottom16}
>
Select File
</Button>
<input
ref={fileInputRef}
type="file"
accept=".sxcu"
style={{ display: "none" }}
onChange={handleShareXConfigUpload}
/>
</>
)}
</Flex>
);
}
const settings = definePluginSettings({
fileUploader: {
type: OptionType.SELECT,
options: [
{ label: "Custom Uploader", value: "Custom" },
{ label: "Catbox", value: "Catbox", default: true },
{ label: "Litterbox", value: "Litterbox" },
{ label: "GoFile", value: "GoFile" },
],
description: "Select the file uploader service",
hidden: true
},
gofileToken: {
type: OptionType.STRING,
default: "",
description: "GoFile Token (optional)",
hidden: true
},
autoSend: {
type: OptionType.SELECT,
options: [
{ label: "Yes", value: "Yes"},
{ label: "No", value: "No", default: true },
],
description: "Auto-Send",
hidden: true
},
catboxUserHash: {
type: OptionType.STRING,
default: "",
description: "User hash for Catbox uploader (optional)",
hidden: true
},
litterboxTime: {
type: OptionType.SELECT,
options: [
{ label: "1 hour", value: "1h", default: true },
{ label: "12 hours", value: "12h" },
{ label: "24 hours", value: "24h" },
{ label: "72 hours", value: "72h" },
],
description: "Duration for files on Litterbox before they are deleted",
hidden: true
},
customUploaderName: {
type: OptionType.STRING,
default: "",
description: "Name of the custom uploader",
hidden: true
},
customUploaderRequestURL: {
type: OptionType.STRING,
default: "",
description: "Request URL for the custom uploader",
hidden: true
},
customUploaderFileFormName: {
type: OptionType.STRING,
default: "",
description: "File form name for the custom uploader",
hidden: true
},
customUploaderResponseType: {
type: OptionType.SELECT,
options: [
{ label: "Text", value: "Text", default: true },
{ label: "JSON", value: "JSON" },
],
description: "Response type for the custom uploader",
hidden: true
},
customUploaderURL: {
type: OptionType.STRING,
default: "",
description: "URL (JSON path) for the custom uploader",
hidden: true
},
customUploaderThumbnailURL: {
type: OptionType.STRING,
default: "",
description: "Thumbnail URL (JSON path) for the custom uploader",
hidden: true
},
customUploaderHeaders: {
type: OptionType.STRING,
default: JSON.stringify({}),
description: "Headers for the custom uploader (JSON string)",
hidden: true
},
customUploaderArgs: {
type: OptionType.STRING,
default: JSON.stringify({}),
description: "Arguments for the custom uploader (JSON string)",
hidden: true
},
customSettings: {
type: OptionType.COMPONENT,
component: SettingsComponent,
description: "Configure custom uploader settings",
hidden: false
},
}).withPrivateSettings<{
customUploaderArgs?: Record<string, string>;
customUploaderHeaders?: Record<string, string>;
}>();
function sendTextToChat(text: string) {
if (settings.store.autoSend === "No") {
insertTextIntoChatInputBox(text);
} else {
const channelId = SelectedChannelStore.getChannelId();
sendMessage(channelId, { content: text });
}
}
async function resolveFile(options: Argument[], ctx: CommandContext): Promise<File | null> {
for (const opt of options) {
if (opt.name === "file") {
const upload = UploadStore.getUpload(ctx.channel.id, opt.name, DraftType.SlashCommand);
return upload.item.file;
}
}
return null;
}
async function uploadFileToGofile(file: File, channelId: string) {
try {
const arrayBuffer = await file.arrayBuffer();
const fileName = file.name;
const fileType = file.type;
const serverResponse = await fetch("https://api.gofile.io/servers");
const serverData = await serverResponse.json();
const server = serverData.data.servers[Math.floor(Math.random() * serverData.data.servers.length)].name;
const uploadResult = await Native.uploadFileToGofileNative(`https://${server}.gofile.io/uploadFile`, arrayBuffer, fileName, fileType);
if (uploadResult.status === "ok") {
const { downloadPage } = uploadResult.data;
setTimeout(() => sendTextToChat(`${downloadPage} `), 10);
UploadManager.clearAll(channelId, DraftType.SlashCommand);
} else {
console.error("Error uploading file:", uploadResult);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
} catch (error) {
console.error("Error uploading file:", error);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
}
async function uploadFileToCatbox(file: File, channelId: string) {
try {
const url = "https://catbox.moe/user/api.php";
const userHash = settings.store.catboxUserHash;
const fileSizeMB = file.size / (1024 * 1024);
const arrayBuffer = await file.arrayBuffer();
const fileName = file.name;
const uploadResult = await Native.uploadFileToCatboxNative(url, arrayBuffer, fileName, file.type, userHash);
if (uploadResult.startsWith("https://") || uploadResult.startsWith("http://")) {
const videoExtensions = [".mp4", ".mkv", ".webm", ".avi", ".mov", ".flv", ".wmv", ".m4v", ".mpg", ".mpeg", ".3gp", ".ogv"];
let finalUrl = uploadResult;
if (fileSizeMB >= 150 && videoExtensions.some(ext => finalUrl.endsWith(ext))) {
finalUrl = `https://embeds.video/${finalUrl}`;
}
setTimeout(() => sendTextToChat(`${finalUrl} `), 10);
UploadManager.clearAll(channelId, DraftType.SlashCommand);
} else {
console.error("Error uploading file:", uploadResult);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
} catch (error) {
console.error("Error uploading file:", error);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
}
async function uploadFileToLitterbox(file: File, channelId: string) {
try {
const arrayBuffer = await file.arrayBuffer();
const fileName = file.name;
const fileType = file.type;
const fileSizeMB = file.size / (1024 * 1024);
const time = settings.store.litterboxTime;
const uploadResult = await Native.uploadFileToLitterboxNative(arrayBuffer, fileName, fileType, time);
if (uploadResult.startsWith("https://") || uploadResult.startsWith("http://")) {
const videoExtensions = [".mp4", ".mkv", ".webm", ".avi", ".mov", ".flv", ".wmv", ".m4v", ".mpg", ".mpeg", ".3gp", ".ogv"];
let finalUrl = uploadResult;
if (fileSizeMB >= 150 && videoExtensions.some(ext => finalUrl.endsWith(ext))) {
finalUrl = `https://embeds.video/${finalUrl}`;
}
setTimeout(() => sendTextToChat(`${finalUrl}`), 10);
UploadManager.clearAll(channelId, DraftType.SlashCommand);
} else {
console.error("Error uploading file:", uploadResult);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
} catch (error) {
console.error("Error uploading file:", error);
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
}
async function uploadFileCustom(file: File, channelId: string) {
try {
const arrayBuffer = await file.arrayBuffer();
const fileName = file.name;
const fileType = file.type;
const fileFormName = settings.store.customUploaderFileFormName || "file[]";
const customArgs = JSON.parse(settings.store.customUploaderArgs || "{}");
const customHeaders = JSON.parse(settings.store.customUploaderHeaders || "{}");
const responseType = settings.store.customUploaderResponseType;
const urlPath = settings.store.customUploaderURL.split(".");
const finalUrl = await Native.uploadFileCustomNative(settings.store.customUploaderRequestURL, arrayBuffer, fileName, fileType, fileFormName, customArgs, customHeaders, responseType, urlPath);
if (finalUrl.startsWith("https://") || finalUrl.startsWith("http://")) {
const videoExtensions = [".mp4", ".mkv", ".webm", ".avi", ".mov", ".flv", ".wmv", ".m4v", ".mpg", ".mpeg", ".3gp", ".ogv"];
let finalUrlModified = finalUrl;
if (videoExtensions.some(ext => finalUrlModified.endsWith(ext))) {
finalUrlModified = `https://embeds.video/${finalUrlModified}`;
}
setTimeout(() => sendTextToChat(`${finalUrlModified} `), 10);
UploadManager.clearAll(channelId, DraftType.SlashCommand);
} else {
console.error("Error uploading file: Invalid URL returned");
sendBotMessage(channelId, { content: "Error uploading file. Check the console for more info." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
} catch (error) {
console.error("Error uploading file:", error);
sendBotMessage(channelId, { content: `Error uploading file: ${error}. Check the console for more info.` });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
}
async function uploadFile(file: File, channelId: string) {
const uploader = settings.store.fileUploader;
switch (uploader) {
case "GoFile":
await uploadFileToGofile(file, channelId);
break;
case "Catbox":
await uploadFileToCatbox(file, channelId);
break;
case "Litterbox":
await uploadFileToLitterbox(file, channelId);
break;
case "Custom":
await uploadFileCustom(file, channelId);
break;
default:
console.error("Unknown uploader:", uploader);
sendBotMessage(channelId, { content: "Error: Unknown uploader selected." });
UploadManager.clearAll(channelId, DraftType.SlashCommand);
}
}
function triggerFileUpload() {
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.style.display = "none";
fileInput.onchange = async event => {
const target = event.target as HTMLInputElement;
if (target && target.files && target.files.length > 0) {
const file = target.files[0];
if (file) {
const channelId = SelectedChannelStore.getChannelId();
await uploadFile(file, channelId);
} else {
showToast("No file selected");
}
}
};
document.body.appendChild(fileInput);
fileInput.click();
document.body.removeChild(fileInput);
}
const ctxMenuPatch: NavContextMenuPatchCallback = (children, props) => {
if (props.channel.guild_id && !PermissionStore.can(PermissionsBits.SEND_MESSAGES, props.channel)) return;
children.splice(1, 0,
<Menu.MenuItem
id="upload-big-file"
label={
<div className={OptionClasses.optionLabel}>
<OpenExternalIcon className={OptionClasses.optionIcon} height={24} width={24} />
<div className={OptionClasses.optionName}>Upload a Big File</div>
</div>
}
action={triggerFileUpload}
/>
);
};
export default definePlugin({
name: "BigFileUpload",
description: "Bypass Discord's upload limit by uploading files using the 'Upload a Big File' button or /fileupload and they'll get uploaded as links into chat via file uploaders.",
authors: [Devs.ScattrdBlade],
settings,
dependencies: ["CommandsAPI"],
contextMenus: {
"channel-attach": ctxMenuPatch,
},
commands: [
{
inputType: ApplicationCommandInputType.BUILT_IN,
name: "fileupload",
description: "Upload a file",
options: [
{
name: "file",
description: "The file to upload",
type: ApplicationCommandOptionType.ATTACHMENT,
required: true,
},
],
execute: async (opts, cmdCtx) => {
const file = await resolveFile(opts, cmdCtx);
if (file) {
await uploadFile(file, cmdCtx.channel.id);
} else {
sendBotMessage(cmdCtx.channel.id, { content: "No file specified!" });
UploadManager.clearAll(cmdCtx.channel.id, DraftType.SlashCommand);
}
},
},
],
});