-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileSplitter.tsx
245 lines (214 loc) · 8.11 KB
/
FileSplitter.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
import { definePlugin, webpack } from "@utils/webpack";
import { Button, Text, Forms } from "@webpack/common";
import { useCallback, useState, useEffect } from "@webpack/common";
const CHUNK_SIZE = 7.9 * 1024 * 1024;
const CHUNK_TIMEOUT = 5 * 60 * 1000;
interface FileChunk {
index: number;
total: number;
data: string;
originalName: string;
originalSize: number;
timestamp: number;
}
interface ChunkStorage {
[key: string]: {
chunks: FileChunk[];
lastUpdated: number;
};
}
const FileUploadStore = webpack.getModule(m => m?.upload && m?.instantBatchUpload);
const MessageActions = webpack.getModule(m => m?.sendMessage);
class ChunkManager {
private static storage: ChunkStorage = {};
static addChunk(chunk: FileChunk): void {
const key = chunk.originalName;
if (!this.storage[key]) {
this.storage[key] = {
chunks: [],
lastUpdated: Date.now()
};
}
this.storage[key].chunks.push(chunk);
this.storage[key].lastUpdated = Date.now();
}
static getChunks(fileName: string): FileChunk[] | null {
return this.storage[fileName]?.chunks || null;
}
static cleanOldChunks(): void {
const now = Date.now();
Object.keys(this.storage).forEach(key => {
if (now - this.storage[key].lastUpdated > CHUNK_TIMEOUT) {
delete this.storage[key];
}
});
}
}
const SplitFileComponent = () => {
const [status, setStatus] = useState("");
const [isUploading, setIsUploading] = useState(false);
const [progress, setProgress] = useState(0);
useEffect(() => {
const cleanup = setInterval(() => {
ChunkManager.cleanOldChunks();
}, 60000);
return () => clearInterval(cleanup);
}, []);
const handleFileSplit = useCallback(async (file: File) => {
try {
setIsUploading(true);
const chunks: FileChunk[] = [];
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
for (let i = 0; i < totalChunks; i++) {
const start = i * CHUNK_SIZE;
const end = Math.min(start + CHUNK_SIZE, file.size);
const chunk = file.slice(start, end);
const base64Data = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(chunk);
});
chunks.push({
index: i,
total: totalChunks,
data: base64Data,
originalName: file.name,
originalSize: file.size,
timestamp: Date.now()
});
}
await Promise.all(chunks.map(async (chunk, index) => {
try {
const chunkBlob = await fetch(chunk.data).then(r => r.blob());
const chunkFile = new File(
[chunkBlob],
`${file.name}.part${chunk.index + 1}of${chunk.total}`,
{ type: 'application/octet-stream' }
);
await FileUploadStore.upload({
file: chunkFile,
message: JSON.stringify(chunk),
channelId: webpack.getModule(m => m?.getChannelId)?.getChannelId()
});
setProgress(Math.round(((index + 1) / totalChunks) * 100));
} catch (error) {
throw new Error(`Failed to upload chunk ${index + 1}: ${error.message}`);
}
}));
setStatus(`Successfully split and uploaded file into ${totalChunks} parts`);
} catch (error) {
setStatus(`Error: ${error.message}`);
} finally {
setIsUploading(false);
setProgress(0);
}
}, []);
const handleFileSelect = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (file.size > CHUNK_SIZE) {
setStatus(`Preparing to split ${file.name} into chunks...`);
await handleFileSplit(file);
} else {
setStatus("File is small enough to send directly");
}
}, [handleFileSplit]);
const handleFileMerge = useCallback(async (chunks: FileChunk[]) => {
try {
chunks.sort((a, b) => a.index - b.index);
const blobParts: Blob[] = [];
for (const chunk of chunks) {
const response = await fetch(chunk.data);
const blob = await response.blob();
blobParts.push(blob);
}
const finalBlob = new Blob(blobParts);
const finalFile = new File([finalBlob], chunks[0].originalName);
const url = URL.createObjectURL(finalFile);
const a = document.createElement('a');
a.href = url;
a.download = finalFile.name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Error merging file chunks:', error);
}
}, []);
return (
<Forms.FormSection>
<input
type="file"
onChange={handleFileSelect}
style={{ display: 'none' }}
id="file-input"
/>
<Button
onClick={() => document.getElementById('file-input')?.click()}
disabled={isUploading}
>
{isUploading ? 'Uploading...' : 'Select Large File'}
</Button>
{progress > 0 && <Text variant="text-sm/normal">{`Progress: ${progress}%`}</Text>}
{status && <Text variant="text-sm/normal">{status}</Text>}
</Forms.FormSection>
);
};
export default definePlugin({
name: "FileSplitter",
description: "Split large files to bypass Discord's 8MB limit",
authors: [
{
id: 1234567890n,
name: "Your Name",
},
],
patches: [
{
find: "uploadFiles,",
replacement: {
match: /(.{1,}\.uploadFiles,)/,
replace: "$1,FileSplitter:()=><SplitFileComponent/>,"
}
}
],
start() {
const originalSendMessage = MessageActions.sendMessage;
MessageActions.sendMessage = async (...args) => {
try {
const content = args[1]?.content;
if (content && typeof content === 'string' && content.startsWith("{")) {
const chunkData = JSON.parse(content) as FileChunk;
if (this.isValidChunk(chunkData)) {
ChunkManager.addChunk(chunkData);
const chunks = ChunkManager.getChunks(chunkData.originalName);
if (chunks && chunks.length === chunkData.total) {
await this.handleFileMerge(chunks);
}
}
}
} catch (e) {
// Not a chunk message, proceed normally
}
return originalSendMessage.apply(this, args);
};
},
stop() {
if (MessageActions.sendMessage.__original) {
MessageActions.sendMessage = MessageActions.sendMessage.__original;
}
},
isValidChunk(chunk: any): chunk is FileChunk {
return (
typeof chunk === 'object' &&
typeof chunk.index === 'number' &&
typeof chunk.total === 'number' &&
typeof chunk.data === 'string' &&
typeof chunk.originalName === 'string' &&
typeof chunk.originalSize === 'number' &&
typeof chunk.timestamp === 'number'
);
}
});