-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
493 lines (427 loc) · 14.2 KB
/
popup.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
// Tab switching functionality
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
// Load files if Download tab is opened
if (tabName === "Download") {
fetchFileListForDownload();
}
if (tabName === "Upload") {
fetchFileList();
}
}
// upload related code
// globals
let isPaused = false;
let fileQueue = [];
serverUrl = "http://localhost:5000/api/upload";
// functions
function setFileInputEnabled(enabled) {
document.getElementById("fileInput").disabled = !enabled;
}
// Function to upload the next file in the queue
function uploadNextFile() {
if (fileQueue.length === 0) {
setFileInputEnabled(true); // Enable file input again when all files are processed
return;
}
const file = fileQueue.shift(); // Get the next file from the queue
currentFile = file;
// Save current file details to local storage
chrome.storage.local.set({
currentFile: { name: file.name, size: file.size },
});
const fileUrl = URL.createObjectURL(file);
chrome.runtime.sendMessage({
type: "startUpload",
fileUrl: fileUrl,
fileName: file.name,
fileSize: file.size,
});
}
function resetProgressBar() {
const progressBar = document.getElementById("progressBar");
progressBar.style.width = "0%";
progressBar.textContent = "0%";
}
function fetchFileList() {
fetch("http://localhost:5000/api/upload")
.then((response) => response.text())
.then((data) => {
document.getElementById("filesList").innerHTML = data;
});
}
function updateProgressBar(progress) {
if (progress == null || isNaN(progress)) {
// Skip the update or set a default value if progress is null or not a number
return;
}
const progressBar = document.getElementById("progressBar");
progressBar.style.width = progress + "%";
progressBar.textContent = progress.toFixed(0) + "%";
}
// Event Listeners (Document)
// Add event listeners for tab switching
document
.getElementById("uploadTab")
.addEventListener("click", function (event) {
openTab(event, "Upload");
});
// Modify the file input change event to handle multiple files
document.getElementById("fileInput").addEventListener("change", function () {
if (this.files.length === 0) return;
fileQueue = Array.from(this.files); // Store all selected files in the queue
uploadNextFile(); // Start uploading the first file
});
document.getElementById("restartButton").addEventListener("click", function () {
if (currentFile) {
chrome.runtime.sendMessage({
type: "restartUpload",
file: {
fileUrl: URL.createObjectURL(currentFile),
name: currentFile.name,
size: currentFile.size,
},
});
setFileInputEnabled(false);
}
});
document.addEventListener("DOMContentLoaded", function () {
fetch("http://localhost:5000/api/upload")
.then((response) => response.text())
.then((data) => {
document.getElementById("filesList").innerHTML = data;
});
});
document
.getElementById("filesList")
.addEventListener("click", function (event) {
if (event.target.classList.contains("delete-button")) {
const fileName = event.target.getAttribute("data-filename");
fetch(`http://localhost:5000/api/upload/delete/${fileName}`, {
method: "DELETE",
})
.then((response) => {
if (response.ok) {
event.target.parentNode.remove(); // Remove the file item from the list
}
})
.catch((error) => {
console.error("Error deleting file:", error);
});
}
});
document.getElementById("cancelButton").addEventListener("click", function () {
chrome.storage.local.get("currentFile", function (data) {
if (data.currentFile) {
chrome.runtime.sendMessage({
type: "cancelCurrentUpload",
fileName: data.currentFile.name,
});
} else {
console.error("No current file data found");
}
});
});
document
.getElementById("pauseResumeButton")
.addEventListener("click", function () {
chrome.runtime.sendMessage({ type: "pauseResumeUpload" });
this.textContent = isPaused ? "Pause" : "Resume";
isPaused = !isPaused;
});
// Call fetchFileList on DOMContentLoaded to load the initial file list
document.addEventListener("DOMContentLoaded", function () {
chrome.storage.local.get("uploadState", function (data) {
if (data.uploadState) {
// Update UI for the stored state
setupUIForResumedUpload(data.uploadState);
} else {
fetchFileList();
}
});
document.getElementsByClassName("tablinks")[0].click();
});
function setupUIForResumedUpload(uploadState) {
updateProgressBar(
(uploadState.uploadedChunks / uploadState.totalChunks) * 100
);
document.getElementById("progressBarContainer").style.display = "block";
document.getElementById("pauseResumeButton").textContent = "Resume";
// Update isPaused state
isPaused = true;
}
document
.getElementById("deleteAllButton")
.addEventListener("click", function () {
chrome.runtime.sendMessage({ type: "deleteAllFiles" });
});
// Event Listeners (Chrome)
// Listener for upload completion or cancellation message from background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "uploadComplete" || message.type === "uploadCancelled") {
fetchFileList();
uploadNextFile(); // Trigger next file upload
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "updateProgress") {
updateProgressBar(message.progress);
} else if (message.type === "resetProgress") {
resetProgressBar();
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "showProgressBar") {
document.getElementById("progressBarContainer").style.display = "block";
} else if (message.type === "hideProgressBar") {
document.getElementById("progressBarContainer").style.display = "none";
}
if (message.type === "refreshFileList") {
fetchFileList();
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "refreshFileList") {
console.log(
"Received refreshFileList message, waiting 3 seconds before fetching file list"
);
// Delay the fetchFileList call by 3000 milliseconds (3 seconds)
setTimeout(fetchFileList, 3000);
}
});
// download related code
// globals
let isDownloadPaused = false;
let isDownloading = false;
let downloadQueue = [];
let downloadAbortController = null;
let currentDownloadAbortController = null;
let downloadAborted = false;
let currentFile = null;
let currentFileName = null;
let currentChunkCount = null;
let currentChunkIndex = 0;
let currentChunks = [];
// functions
function assembleAndDownloadFile(chunks, fileName) {
// Create a new blob from the array of chunks
const fileBlob = new Blob(chunks);
// Create a URL for the blob
const url = window.URL.createObjectURL(fileBlob);
// Create a temporary anchor element and trigger a download
const a = document.createElement("a");
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
// Clean up by revoking the blob URL and removing the anchor element
window.URL.revokeObjectURL(url);
a.remove();
}
// Function to update the queue display
function updateDownloadQueueDisplay() {
const queueDisplayElement = document.getElementById("downloadQueueDisplay");
const queueCount = downloadQueue.length;
if (queueCount > 0) {
queueDisplayElement.textContent = `${queueCount} more file(s) in queue`;
} else {
queueDisplayElement.textContent = "No files in queue";
}
}
// Function to download a file
function downloadFile(fileName, chunkCount) {
// Reset download state for a new file
currentFileName = fileName;
currentChunkCount = chunkCount;
currentChunkIndex = 0;
currentChunks = [];
downloadAborted = false; // Reset flag at the start of a new download
// Show the download progress bar
document.getElementById("downloadProgressBarContainer").style.display =
"block";
updateDownloadProgressBar(0);
isDownloading = true; // Set the flag to true when download starts
downloadAbortController = new AbortController(); // Create a new controller for each download
const { signal } = downloadAbortController;
currentDownloadAbortController = new AbortController();
continueDownload();
}
function continueDownload() {
if (
currentChunkIndex < currentChunkCount &&
!downloadAborted &&
isDownloading &&
!isDownloadPaused
) {
fetch(
`http://localhost:5000/api/upload/download/${currentFileName}/${currentChunkIndex}`,
{ signal: currentDownloadAbortController.signal }
)
.then((response) => response.blob())
.then((blob) => {
if (downloadAborted) {
console.log("Download was aborted, stopping further processing.");
return;
}
currentChunks.push(blob);
currentChunkIndex++;
updateDownloadProgressBar(
(currentChunkIndex / currentChunkCount) * 100
);
if (currentChunkIndex < currentChunkCount) {
continueDownload(); // Fetch the next chunk
} else {
// All chunks downloaded
assembleAndDownloadFile(currentChunks, currentFileName);
downloadQueue.shift();
updateDownloadQueueDisplay();
resetProgressBarAndHide();
if (downloadQueue.length > 0) {
startNextDownload();
}
}
})
.catch((error) => {
if (error.name === "AbortError") {
console.log("Download aborted: ", currentFileName);
} else {
console.error("Error downloading chunk: ", error);
}
});
}
}
function resetProgressBarAndHide() {
document.getElementById("downloadProgressBarContainer").style.display =
"none";
updateDownloadProgressBar(0);
}
function toggleDownloadPause() {
isDownloadPaused = !isDownloadPaused;
document.getElementById("pauseResumeDownloadButton").textContent =
isDownloadPaused ? "Resume" : "Pause";
if (!isDownloadPaused && isDownloading) {
// Resume the download process
continueDownload();
}
}
function cancelCurrentDownload() {
if (currentDownloadAbortController) {
currentDownloadAbortController.abort();
downloadAborted = true;
currentDownloadAbortController = null;
isDownloading = false;
updateDownloadProgressBar(0);
if (downloadQueue.length > 0) {
downloadQueue.shift(); // Remove the cancelled file from the queue
updateDownloadQueueDisplay();
startNextDownload(); // Immediately start next download
} else {
resetDownloadState();
}
}
}
function resetDownloadState() {
document.getElementById("downloadProgressBarContainer").style.display =
"none";
updateDownloadProgressBar(0);
isDownloading = false; // Ensure downloading flag is reset
downloadQueue = []; // Clear the download queue
updateDownloadQueueDisplay();
}
function updateDownloadProgressBar(progress) {
const progressBar = document.getElementById("downloadProgressBar");
progressBar.style.width = progress + "%";
progressBar.textContent = progress.toFixed(0) + "%";
}
// Function to fetch and display available files for download
function fetchFileListForDownload() {
fetch("http://localhost:5000/api/uploadfiles")
.then((response) => response.text())
.then((data) => {
document.getElementById("filesDownloadList").innerHTML = data;
});
}
function initiateFileDownload(fileName) {
fetch(`http://localhost:5000/api/upload/metadata/${fileName}`)
.then((response) => response.json())
.then((metadata) => {
downloadQueue.push({ fileName, chunkCount: metadata.chunkCount });
updateDownloadQueueDisplay(); // Update the queue display
if (downloadQueue.length === 1) {
startNextDownload();
}
})
.catch((error) => {
console.error("Error fetching file metadata:", error);
});
}
function startNextDownload() {
if (downloadQueue.length > 0) {
const { fileName, chunkCount } = downloadQueue[0];
downloadFile(fileName, chunkCount);
} else {
resetDownloadState(); // Reset state if no more files to download
}
}
function restartCurrentDownload() {
if (currentDownloadAbortController) {
currentDownloadAbortController.abort(); // Abort the current download
downloadAborted = true;
currentDownloadAbortController = null;
if (isDownloading) {
isDownloading = false; // Reset downloading flag
updateDownloadProgressBar(0); // Reset progress bar
if (downloadQueue.length > 0) {
const currentDownload = downloadQueue.shift(); // Remove and get the current download details
downloadQueue.unshift(currentDownload); // Add it back to the start of the queue
startNextDownload(); // Immediately start the download
}
}
}
}
// Event Listeners (Document)
document
.getElementById("downloadTab")
.addEventListener("click", function (event) {
openTab(event, "Download");
});
document
.getElementById("pauseResumeDownloadButton")
.addEventListener("click", function () {
toggleDownloadPause();
});
document
.getElementById("cancelCurrentDownloadButton")
.addEventListener("click", cancelCurrentDownload);
document
.getElementById("cancelDownloadButton")
.addEventListener("click", function () {
if (downloadAbortController) {
downloadAbortController.abort(); // Abort all downloads
downloadAbortController = null;
}
resetDownloadState();
downloadQueue = []; // Clear the queue
updateDownloadQueueDisplay();
});
document
.getElementById("filesDownloadList")
.addEventListener("click", function (event) {
if (event.target.classList.contains("download-button")) {
const fileName = event.target.getAttribute("data-filename");
initiateFileDownload(fileName);
}
});
document
.getElementById("restartDownloadButton")
.addEventListener("click", restartCurrentDownload);