-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1040 lines (873 loc) · 39.4 KB
/
Copy pathscript.js
File metadata and controls
1040 lines (873 loc) · 39.4 KB
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
class DiscordUploader {
constructor() {
// UI Elements
this.fileInput = document.getElementById('fileInput');
this.progressText = document.querySelector('.progress-text');
this.progressFill = document.querySelector('.progress-fill');
this.statusMessage = document.querySelector('.status-message');
this.errorMessage = document.querySelector('.error-message');
this.webhookUrlInput = document.getElementById('webhookUrl');
// Upload configuration
this.CHUNK_SIZE = 10 * 1024 * 1024; // 10MB in bytes
this.MAX_RETRIES = 3; // Maximum number of retry attempts
this.RETRY_DELAY = 2000; // Delay between retries in ms
this.RATE_LIMIT_DELAY = 1500; // Delay between chunk uploads to avoid rate limiting
this.MAX_FILE_SIZE = 1024 * 1024 * 1024; // 1GB max file size
this.MAX_STORED_UPLOADS = 25; // Maximum number of uploads to store in local storage
this.STORAGE_CLEANUP_THRESHOLD = 10 * 1024 * 1024; // 10MB of localStorage threshold
this.URL_CHECK_INTERVAL = 300000; // Check download URLs every 5 minutes (300000 ms)
// Upload state
this.isUploading = false;
this.isPaused = false;
this.uploadQueue = [];
this.currentChunkIndex = 0;
this.uploadedChunks = 0;
this.totalChunks = 0;
this.chunkUploadResults = [];
this.urlCheckTimer = null;
// Event listeners
this.fileInput.addEventListener('change', this.handleFileSelect.bind(this));
// Add listeners for buttons if they exist
const startButton = document.getElementById('startUpload');
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
const cancelButton = document.getElementById('cancelUpload');
if (startButton) startButton.addEventListener('click', this.startUpload.bind(this));
if (pauseButton) pauseButton.addEventListener('click', this.pauseUpload.bind(this));
if (resumeButton) resumeButton.addEventListener('click', this.resumeUpload.bind(this));
if (cancelButton) cancelButton.addEventListener('click', this.cancelUpload.bind(this));
// Start URL checking timer
this.startUrlCheckTimer();
}
// Generate a random filename with mixed case letters and numbers
generateRandomFilename(originalFilename, chunkIndex, totalChunks) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < 8; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
// Get file extension
const extension = originalFilename.match(/\.[0-9a-z]+$/i)?.[0] || '';
const baseName = originalFilename.replace(/\.[^/.]+$/, "");
// Add chunk information to filename
return `${baseName}_${result}_part${String(chunkIndex).padStart(3, '0')}_of_${totalChunks}${extension}`;
}
// Calculate a simple checksum for a file
async calculateChecksum(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function(e) {
const data = e.target.result;
let hash = 0;
// Simple hash function for demo purposes
// In production, use a proper hashing algorithm like SHA-256
for (let i = 0; i < data.byteLength; i++) {
hash = ((hash << 5) - hash) + (new Uint8Array(data)[i]);
hash |= 0; // Convert to 32bit integer
}
resolve(Math.abs(hash).toString(16));
};
reader.readAsArrayBuffer(file.slice(0, Math.min(file.size, 5 * 1024 * 1024))); // Read first 5MB for checksum
});
}
// Validate webhook URL
validateWebhookUrl(url) {
if (!url) return false;
// Check if URL is valid and matches Discord webhook format
// Accept both discord.com and discordapp.com domains
const discordWebhookRegex = /^https:\/\/(discord\.com|discordapp\.com)\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+$/;
// Add visual indicator for validation result
const webhookUrlInput = document.getElementById('webhookUrl');
const validationMessage = document.querySelector('.validation-message');
if (url && discordWebhookRegex.test(url)) {
if (webhookUrlInput) webhookUrlInput.classList.remove('input-error');
if (validationMessage) {
validationMessage.classList.remove('visible');
}
return true;
} else {
if (webhookUrlInput) webhookUrlInput.classList.add('input-error');
if (validationMessage) {
validationMessage.textContent = 'Please enter a valid Discord webhook URL';
validationMessage.classList.add('visible');
}
return false;
}
}
// Check if file size is within limits
validateFileSize(file) {
if (!file) return false;
const fileSizeWarning = document.querySelector('.file-size-warning');
if (file.size > this.MAX_FILE_SIZE) {
this.showStatus(`File is too large. Maximum size is ${this.formatFileSize(this.MAX_FILE_SIZE)}.`, true);
if (fileSizeWarning) {
fileSizeWarning.textContent = `File is too large. Maximum size is ${this.formatFileSize(this.MAX_FILE_SIZE)}.`;
fileSizeWarning.classList.add('visible');
}
return false;
} else {
if (fileSizeWarning) {
fileSizeWarning.classList.remove('visible');
}
return true;
}
}
// Update progress display
updateProgress(percent) {
this.progressText.textContent = `${Math.round(percent)}%`;
this.progressFill.style.width = `${percent}%`;
// Update chunk indicator if available
const chunkIndicator = document.querySelector('.chunk-indicator');
if (chunkIndicator && this.totalChunks > 0) {
chunkIndicator.textContent = `Chunk: ${this.uploadedChunks}/${this.totalChunks}`;
}
}
// Update chunk progress display
updateChunkProgress(percent) {
const chunkProgressText = document.querySelector('.chunk-progress-text');
const chunkProgressFill = document.querySelector('.chunk-progress-fill');
if (chunkProgressText) {
chunkProgressText.textContent = `Current chunk: ${Math.round(percent)}%`;
}
if (chunkProgressFill) {
chunkProgressFill.style.width = `${percent}%`;
}
}
// Show status message
showStatus(message, isError = false) {
if (!this.statusMessage) return;
this.statusMessage.textContent = message;
if (isError) {
if (this.errorMessage) {
this.errorMessage.textContent = message;
this.errorMessage.style.display = 'block';
this.statusMessage.textContent = 'Error occurred. See details below.';
} else {
this.statusMessage.style.color = '#ff4444';
}
console.error('DiscordUploader Error:', message);
} else {
this.statusMessage.style.color = '#ffffff';
if (this.errorMessage) {
this.errorMessage.style.display = 'none';
this.errorMessage.textContent = '';
}
}
}
// Check available localStorage space
checkStorageSpace() {
let totalSize = 0;
try {
for (let key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
totalSize += localStorage[key].length * 2; // Approximate size in bytes
}
}
} catch (e) {
console.error('Error checking storage space', e);
return true; // Continue anyway
}
// If we're approaching storage limits, clean up old uploads
if (totalSize > this.STORAGE_CLEANUP_THRESHOLD) {
this.cleanupOldUploads();
}
return true;
}
// Clean up old uploads from localStorage
cleanupOldUploads() {
try {
const stored = localStorage.getItem('discordUploads');
if (!stored) return;
let uploads = JSON.parse(stored);
// If we have too many uploads, sort by date and remove oldest
if (uploads.length > this.MAX_STORED_UPLOADS) {
uploads.sort((a, b) => {
return new Date(b.uploadDate) - new Date(a.uploadDate);
});
// Keep only the most recent uploads
uploads = uploads.slice(0, this.MAX_STORED_UPLOADS);
// Save back to localStorage
localStorage.setItem('discordUploads', JSON.stringify(uploads));
console.log(`Cleaned up uploads, now storing ${uploads.length} items`);
}
} catch (e) {
console.error('Error cleaning up uploads', e);
}
}
// Split file into chunks
splitFileIntoChunks(file) {
const chunks = [];
let start = 0;
while (start < file.size) {
const end = Math.min(start + this.CHUNK_SIZE, file.size);
chunks.push(file.slice(start, end));
start = end;
}
return chunks;
}
// Upload a single chunk with retry logic
async uploadChunk(chunk, filename, webhookUrl, chunkIndex, retryCount = 0) {
const formData = new FormData();
formData.append('file', chunk, filename);
try {
const response = await fetch(webhookUrl, {
method: 'POST',
body: formData
});
// Handle various HTTP status codes
if (response.status === 429) {
// Rate limited - retry after a delay
const retryAfter = response.headers.get('Retry-After') || 5;
this.showStatus(`Rate limited. Retrying in ${retryAfter} seconds...`);
if (retryCount < this.MAX_RETRIES) {
// Wait for the specified time and retry
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
return this.uploadChunk(chunk, filename, webhookUrl, chunkIndex, retryCount + 1);
} else {
throw new Error('Max retries exceeded for rate limit');
}
} else if (response.status === 413) {
// Entity too large - the chunk size needs to be reduced
this.showStatus('File chunk too large for Discord. Reducing chunk size...', true);
// If we can retry with a smaller chunk
if (chunk.size > 4 * 1024 * 1024 && retryCount < this.MAX_RETRIES) {
// Reduce the chunk size for future uploads
this.CHUNK_SIZE = Math.floor(this.CHUNK_SIZE * 0.75);
// Split this chunk into smaller chunks
const smallerChunks = [];
let start = 0;
const newChunkSize = Math.floor(this.CHUNK_SIZE * 0.75);
while (start < chunk.size) {
const end = Math.min(start + newChunkSize, chunk.size);
smallerChunks.push(chunk.slice(start, end));
start = end;
}
// Upload the first smaller chunk and return
const newFilename = this.generateRandomFilename(filename, chunkIndex, this.totalChunks);
return this.uploadChunk(smallerChunks[0], newFilename, webhookUrl, chunkIndex, retryCount + 1);
} else {
throw new Error('File chunk too large and could not be reduced further');
}
} else if (!response.ok) {
// Other HTTP errors
if (retryCount < this.MAX_RETRIES) {
this.showStatus(`HTTP error ${response.status}. Retrying (${retryCount + 1}/${this.MAX_RETRIES})...`);
await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY));
return this.uploadChunk(chunk, filename, webhookUrl, chunkIndex, retryCount + 1);
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
// If we reach here, the upload was successful
const result = await response.json();
return result;
} catch (error) {
// Network errors or other exceptions
if (retryCount < this.MAX_RETRIES) {
this.showStatus(`Upload failed: ${error.message}. Retrying (${retryCount + 1}/${this.MAX_RETRIES})...`);
await new Promise(resolve => setTimeout(resolve, this.RETRY_DELAY));
return this.uploadChunk(chunk, filename, webhookUrl, chunkIndex, retryCount + 1);
} else {
throw new Error(`Upload failed: ${error.message}`);
}
}
}
// Process the upload queue
async processQueue() {
if (this.isPaused || this.uploadQueue.length === 0 || !this.isUploading) {
return;
}
const item = this.uploadQueue.shift();
this.currentChunkIndex = item.index;
try {
this.showStatus(`Uploading part ${item.index + 1} of ${this.totalChunks}...`);
// Generate a meaningful filename for the chunk
const chunkFilename = this.generateRandomFilename(
item.originalFilename,
item.index + 1,
this.totalChunks
);
// Upload the chunk
const result = await this.uploadChunk(
item.chunk,
chunkFilename,
item.webhookUrl,
item.index
);
// Store the result for later reassembly
this.chunkUploadResults[item.index] = {
url: result.attachments?.[0]?.url || '',
filename: chunkFilename,
size: item.chunk.size,
index: item.index,
messageId: result.id
};
// Update progress
this.uploadedChunks++;
const progress = (this.uploadedChunks / this.totalChunks) * 100;
this.updateProgress(progress);
// Add delay between uploads to avoid rate limiting
await new Promise(resolve => setTimeout(resolve, this.RATE_LIMIT_DELAY));
// Process next chunk
if (this.uploadQueue.length > 0) {
this.processQueue();
} else if (this.uploadedChunks === this.totalChunks) {
// All chunks uploaded successfully
this.showStatus('Upload complete!');
this.isUploading = false;
// Update UI buttons if available
const startButton = document.getElementById('startUpload');
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
const cancelButton = document.getElementById('cancelUpload');
if (startButton) startButton.disabled = false;
if (pauseButton) pauseButton.disabled = true;
if (resumeButton) resumeButton.disabled = true;
if (cancelButton) cancelButton.disabled = true;
// Store the upload information for later download/management
this.saveUploadInfo();
}
} catch (error) {
this.showStatus(`Error: ${error.message}`, true);
this.isUploading = false;
// Update UI buttons
const startButton = document.getElementById('startUpload');
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
const cancelButton = document.getElementById('cancelUpload');
if (startButton) startButton.disabled = false;
if (pauseButton) pauseButton.disabled = true;
if (resumeButton) resumeButton.disabled = true;
if (cancelButton) cancelButton.disabled = true;
}
}
// Save upload information for later retrieval
saveUploadInfo() {
if (this.chunkUploadResults.length === 0) return;
// Get the file information
const file = this.fileInput.files[0];
if (!file) return;
// Create metadata for the upload
const uploadInfo = {
originalFilename: file.name,
size: file.size,
type: file.type,
chunks: this.chunkUploadResults,
uploadDate: new Date().toISOString(),
checksum: this.fileChecksum,
totalChunks: this.totalChunks
};
// Get existing uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads', e);
}
// Add this upload and save back to localStorage
uploads.push(uploadInfo);
localStorage.setItem('discordUploads', JSON.stringify(uploads));
// Refresh the file list if available
this.loadUploadedFiles();
}
// Load and display uploaded files
loadUploadedFiles() {
const fileTableBody = document.getElementById('fileTableBody');
const noFilesMessage = document.getElementById('noFilesMessage');
if (!fileTableBody) return;
// Clear existing entries
fileTableBody.innerHTML = '';
// Get uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads', e);
}
// Show/hide no files message
if (noFilesMessage) {
noFilesMessage.style.display = uploads.length === 0 ? 'block' : 'none';
}
// If no uploads, return
if (uploads.length === 0) return;
// Add each upload to the table
uploads.forEach((upload, index) => {
const row = document.createElement('tr');
// Format file size
const formattedSize = this.formatFileSize(upload.size);
// Format date
const uploadDate = new Date(upload.uploadDate);
const formattedDate = uploadDate.toLocaleDateString() + ' ' + uploadDate.toLocaleTimeString();
// Check URL status
const urlStatus = this.checkUrlStatus(upload);
const statusClass = urlStatus === 'valid' ? 'url-status-valid' : 'url-status-invalid';
const statusText = urlStatus === 'valid' ? 'Active' : 'Needs refresh';
row.innerHTML = `
<td>${upload.originalFilename}</td>
<td>${formattedSize}</td>
<td>${upload.totalChunks}</td>
<td>${formattedDate}</td>
<td><span class="url-status ${statusClass}">${statusText}</span></td>
<td>
<div class="actions-dropdown">
<button class="button actions-btn">Actions</button>
<div class="actions-content">
<button class="action-item download-btn" data-index="${index}">Download</button>
<button class="action-item refresh-url-btn" data-index="${index}">Refresh URL</button>
<button class="action-item delete-btn" data-index="${index}">Delete</button>
</div>
</div>
</td>
`;
fileTableBody.appendChild(row);
});
// Add event listeners to the actions button to toggle dropdown
document.querySelectorAll('.actions-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
// Close all other dropdowns
document.querySelectorAll('.actions-content').forEach(content => {
if (content !== e.currentTarget.nextElementSibling) {
content.classList.remove('show');
}
});
// Toggle this dropdown
const dropdown = e.currentTarget.nextElementSibling;
dropdown.classList.toggle('show');
});
});
// Close dropdowns when clicking outside
document.addEventListener('click', () => {
document.querySelectorAll('.actions-content').forEach(content => {
content.classList.remove('show');
});
});
// Add event listeners to the action buttons
document.querySelectorAll('.download-btn').forEach(btn => {
btn.addEventListener('click', this.handleDownload.bind(this));
});
document.querySelectorAll('.refresh-url-btn').forEach(btn => {
btn.addEventListener('click', this.handleRefreshUrl.bind(this));
});
document.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', this.handleDelete.bind(this));
});
}
// Format file size for display
formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// Handle file selection
async handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
// Validate file size
if (!this.validateFileSize(file)) {
return;
}
// Reset progress and state
this.updateProgress(0);
this.updateChunkProgress(0);
this.showStatus('File selected. Ready to upload.');
this.uploadQueue = [];
this.chunkUploadResults = [];
this.uploadedChunks = 0;
this.currentChunkIndex = 0;
// Calculate chunks
const chunks = this.splitFileIntoChunks(file);
this.totalChunks = chunks.length;
// Calculate checksum
this.fileChecksum = await this.calculateChecksum(file);
// Update UI with file information
const selectedFileName = document.getElementById('selectedFileName');
const selectedFileSize = document.getElementById('selectedFileSize');
const fileChunks = document.getElementById('fileChunks');
if (selectedFileName) selectedFileName.textContent = file.name;
if (selectedFileSize) selectedFileSize.textContent = this.formatFileSize(file.size);
if (fileChunks) fileChunks.textContent = chunks.length.toString();
// Enable start upload button if available
const startButton = document.getElementById('startUpload');
if (startButton) startButton.disabled = false;
}
// Start the upload process
async startUpload() {
const file = this.fileInput.files[0];
if (!file) {
this.showStatus('No file selected', true);
return;
}
// Validate file size
if (!this.validateFileSize(file)) {
return;
}
// Check available storage space
if (!this.checkStorageSpace()) {
this.showStatus('Local storage is nearly full. Please clear some space before uploading.', true);
return;
}
// Get webhook URL
let webhookUrl = this.webhookUrlInput ? this.webhookUrlInput.value : '';
// If no webhook URL in input, prompt for it
if (!webhookUrl) {
webhookUrl = prompt('Please enter your Discord webhook URL:');
}
// Validate webhook URL
if (!this.validateWebhookUrl(webhookUrl)) {
this.showStatus('Invalid Discord webhook URL. Please check and try again.', true);
return;
}
// Reset upload state
this.isUploading = true;
this.isPaused = false;
this.uploadQueue = [];
this.chunkUploadResults = [];
this.uploadedChunks = 0;
this.currentChunkIndex = 0;
// Update UI
this.updateProgress(0);
this.showStatus('Preparing file for upload...');
// Update UI buttons
const startButton = document.getElementById('startUpload');
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
const cancelButton = document.getElementById('cancelUpload');
if (startButton) startButton.disabled = true;
if (pauseButton) pauseButton.disabled = false;
if (resumeButton) resumeButton.disabled = true;
if (cancelButton) cancelButton.disabled = false;
try {
// Split file into chunks
const chunks = this.splitFileIntoChunks(file);
this.totalChunks = chunks.length;
// Prepare upload queue
for (let i = 0; i < chunks.length; i++) {
this.uploadQueue.push({
chunk: chunks[i],
index: i,
webhookUrl,
originalFilename: file.name
});
}
// Start processing the queue
this.processQueue();
} catch (error) {
this.showStatus(`Error: ${error.message}`, true);
this.isUploading = false;
// Update UI buttons
if (startButton) startButton.disabled = false;
if (pauseButton) pauseButton.disabled = true;
if (resumeButton) resumeButton.disabled = true;
if (cancelButton) cancelButton.disabled = true;
}
}
// Pause the upload
pauseUpload() {
if (!this.isUploading) return;
this.isPaused = true;
this.showStatus('Upload paused. Click Resume to continue.');
// Update UI buttons
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
if (pauseButton) pauseButton.disabled = true;
if (resumeButton) resumeButton.disabled = false;
}
// Resume the upload
resumeUpload() {
if (!this.isUploading) return;
this.isPaused = false;
this.showStatus('Resuming upload...');
// Update UI buttons
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
if (pauseButton) pauseButton.disabled = false;
if (resumeButton) resumeButton.disabled = true;
// Continue processing the queue
this.processQueue();
}
// Cancel the upload
cancelUpload() {
this.isUploading = false;
this.isPaused = false;
this.uploadQueue = [];
this.showStatus('Upload cancelled.');
// Update UI buttons
const startButton = document.getElementById('startUpload');
const pauseButton = document.getElementById('pauseUpload');
const resumeButton = document.getElementById('resumeUpload');
const cancelButton = document.getElementById('cancelUpload');
if (startButton) startButton.disabled = false;
if (pauseButton) pauseButton.disabled = true;
if (resumeButton) resumeButton.disabled = true;
if (cancelButton) cancelButton.disabled = true;
}
// Handle download button click
handleDownload(event) {
const index = event.target.dataset.index;
if (index === undefined) return;
// Get uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads', e);
return;
}
// Get the selected upload
const upload = uploads[index];
if (!upload) {
this.showStatus('Upload not found', true);
return;
}
// Show the download section
const downloadSection = document.getElementById('downloadSection');
if (downloadSection) downloadSection.style.display = 'block';
// Update download information
const downloadFileName = document.getElementById('downloadFileName');
const downloadFileSize = document.getElementById('downloadFileSize');
const downloadChunks = document.getElementById('downloadChunks');
if (downloadFileName) downloadFileName.textContent = upload.originalFilename;
if (downloadFileSize) downloadFileSize.textContent = this.formatFileSize(upload.size);
if (downloadChunks) downloadChunks.textContent = upload.totalChunks.toString();
// Store the current download index
this.currentDownloadIndex = index;
// Enable download button
const startDownloadButton = document.getElementById('startDownload');
if (startDownloadButton) startDownloadButton.disabled = false;
}
// Handle delete button click
handleDelete(event) {
const index = event.target.dataset.index;
if (index === undefined) return;
// Get uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads', e);
return;
}
// Get the selected upload
const upload = uploads[index];
if (!upload) {
this.showStatus('Upload not found', true);
return;
}
// Show delete confirmation modal
const deleteModal = document.getElementById('deleteModal');
const deleteFileName = document.getElementById('deleteFileName');
const confirmDeleteButton = document.getElementById('confirmDelete');
const cancelDeleteButton = document.getElementById('cancelDelete');
if (deleteModal) {
// Set filename and show modal
if (deleteFileName) deleteFileName.textContent = upload.originalFilename;
deleteModal.style.display = 'block';
// Set up event listeners for buttons
if (confirmDeleteButton) {
confirmDeleteButton.onclick = () => {
// Remove the upload from localStorage
uploads.splice(index, 1);
localStorage.setItem('discordUploads', JSON.stringify(uploads));
// Hide modal and refresh file list
deleteModal.style.display = 'none';
this.loadUploadedFiles();
this.showStatus('File deleted successfully.');
};
}
if (cancelDeleteButton) {
cancelDeleteButton.onclick = () => {
// Just hide the modal
deleteModal.style.display = 'none';
};
}
}
}
// Handle URL refresh button click
handleRefreshUrl(event) {
const index = event.target.dataset.index;
if (index === undefined) return;
this.refreshUploadUrl(index);
}
// Check if URLs in an upload are still valid
checkUrlStatus(upload) {
if (!upload || !upload.chunks || upload.chunks.length === 0) {
return 'invalid';
}
// Check if upload was recent (within last 24 hours)
const uploadTime = new Date(upload.uploadDate).getTime();
const now = new Date().getTime();
const hoursSinceUpload = (now - uploadTime) / (1000 * 60 * 60);
// Discord URLs typically expire after 24 hours
if (hoursSinceUpload > 24) {
return 'invalid';
}
return 'valid';
}
// Start timer to periodically check URLs
startUrlCheckTimer() {
// Clear any existing timer
if (this.urlCheckTimer) {
clearInterval(this.urlCheckTimer);
}
// Set up a new timer to check URLs periodically
this.urlCheckTimer = setInterval(() => {
this.checkAllUrls();
}, this.URL_CHECK_INTERVAL);
// Run an initial check
this.checkAllUrls();
}
// Check all stored URLs for validity
checkAllUrls() {
// Get uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads for URL check', e);
return;
}
if (uploads.length === 0) return;
// Check each upload
let urlsNeedingRefresh = 0;
uploads.forEach(upload => {
if (this.checkUrlStatus(upload) === 'invalid') {
urlsNeedingRefresh++;
}
});
// If any URLs need refreshing, update the UI
if (urlsNeedingRefresh > 0) {
const refreshNotice = document.getElementById('refreshNotice');
if (refreshNotice) {
refreshNotice.textContent = `${urlsNeedingRefresh} file(s) need URL refresh`;
refreshNotice.style.display = 'block';
}
}
// Refresh the file list to show updated status
this.loadUploadedFiles();
}
// Attempt to refresh URLs for a specific upload
refreshUploadUrl(index) {
// Get uploads from localStorage
let uploads = [];
try {
const stored = localStorage.getItem('discordUploads');
if (stored) {
uploads = JSON.parse(stored);
}
} catch (e) {
console.error('Error loading stored uploads for URL refresh', e);
return;
}
// Get the selected upload
const upload = uploads[index];
if (!upload) {
this.showStatus('Upload not found for URL refresh', true);
return;
}
// Show status message
this.showStatus('Attempting to refresh download URLs...');
// In a real implementation, you would re-upload the file or use an API to refresh the URLs
// For this demo, we'll just update the timestamp to simulate a refresh
upload.uploadDate = new Date().toISOString();
// Save back to localStorage
localStorage.setItem('discordUploads', JSON.stringify(uploads));
// Update the UI
this.loadUploadedFiles();
this.showStatus('Download URLs refreshed successfully!');
}
}
// Initialize the uploader when the document is ready
document.addEventListener('DOMContentLoaded', () => {
// Add preload element for background image
const preloader = document.createElement('div');
preloader.className = 'preload-images';
const preloadImg = document.createElement('img');
preloadImg.src = 'assets/edit-341776933.gif';
preloader.appendChild(preloadImg);
document.body.appendChild(preloader);
// Add loading spinner
const loader = document.createElement('div');
loader.className = 'loader';
loader.innerHTML = '<div class="spinner"></div>';
document.body.appendChild(loader);
// Hide loader when background image and page are loaded
window.addEventListener('load', () => {
setTimeout(() => {
loader.classList.add('hidden');
setTimeout(() => {
loader.remove();
}, 500);
}, 500);
});
const uploader = new DiscordUploader();
// Load saved webhook URL if available
const webhookUrlInput = document.getElementById('webhookUrl');
if (webhookUrlInput) {
const savedWebhookUrl = localStorage.getItem('discordWebhookUrl');
if (savedWebhookUrl) {
webhookUrlInput.value = savedWebhookUrl;
uploader.validateWebhookUrl(savedWebhookUrl);
}
// Add validation message element if it doesn't exist
const inputGroup = webhookUrlInput.closest('.input-group');
if (inputGroup && !inputGroup.querySelector('.validation-message')) {
const validationMessage = document.createElement('div');
validationMessage.className = 'validation-message';
inputGroup.appendChild(validationMessage);
}
}
// Add file size warning container if it doesn't exist