-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
321 lines (286 loc) · 9.32 KB
/
background.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
// upload related code
// globals
let isCanceled = false;
const MAX_CONCURRENT_UPLOADS = 5;
let activeUploads = 0;
let uploadQueue = [];
let uploadedChunks = 0;
let totalFileChunks = 0;
let isPaused = false;
let currentUpload = null;
let isRestarting = false;
let currentFileDetails = null;
// functions
function dataURLtoBlob(dataurl) {
const arr = dataurl.split(",");
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: "application/octet-stream" });
}
function uploadChunk(
chunkData,
fileName,
chunkIndex,
totalChunks,
fileSize,
serverUrl,
isCanceled
) {
return new Promise(async (resolve, reject) => {
const start = chunkIndex * chunkData.size;
const end =
start + chunkData.size < fileSize ? start + chunkData.size : fileSize;
const headers = new Headers();
headers.append("Content-Type", "application/octet-stream");
headers.append("Content-Range", `bytes ${start}-${end - 1}/${fileSize}`);
headers.append("X-File-Name", btoa(fileName));
headers.append("X-Chunk-Index", chunkIndex);
headers.append("X-Total-Chunks", totalChunks);
headers.append("X-Is-Canceled", isCanceled.toString());
try {
const response = await fetch(serverUrl, {
method: "POST",
headers: headers,
body: chunkData,
});
if (response.ok) {
const responseData = await response.json(); // Parse response as JSON
resolve(responseData);
} else {
reject(new Error("Upload failed: " + response.statusText));
}
} catch (error) {
reject(new Error("Network error"));
}
});
}
function handleFileUpload(fileUrl, fileName, fileSize) {
const chunkSize = 3 * 1024 * 1024; // 3MB chunks
totalFileChunks = Math.ceil(fileSize / chunkSize);
// Save initial state to local storage
saveUploadState(fileName, 0, totalFileChunks, fileSize);
fetch(fileUrl)
.then((response) => response.blob())
.then((blob) => {
for (let i = 0; i < totalFileChunks; i++) {
const start = i * chunkSize;
const end = Math.min(start + chunkSize, fileSize);
const chunkData = blob.slice(start, end);
const serverUrl = "http://localhost:5000/api/upload";
uploadQueue.push({
chunkData,
fileName,
chunkIndex: i,
totalChunks: totalFileChunks,
fileSize,
serverUrl,
isCanceled,
});
}
processQueue();
});
}
function processQueue() {
if (isPaused) {
console.log("Upload paused");
return; // Stop processing when paused
}
if (uploadQueue.length > 0) {
// Show the progress bar when starting the upload process
chrome.runtime.sendMessage({ type: "showProgressBar" });
}
while (activeUploads < MAX_CONCURRENT_UPLOADS && uploadQueue.length > 0) {
const {
chunkData,
fileName,
chunkIndex,
totalChunks,
fileSize,
serverUrl,
isCanceled,
} = uploadQueue.shift();
activeUploads++;
console.log("Active Uploads", activeUploads);
uploadChunk(
chunkData,
fileName,
chunkIndex,
totalChunks,
fileSize,
serverUrl,
isCanceled
)
.then((responseData) => {
if (responseData.fileAssembled) {
// send a message to the popup to refresh the file list
chrome.runtime.sendMessage({ type: "refreshFileList" });
}
activeUploads--;
uploadedChunks++;
updateProgress();
processQueue();
// Check if this was the last chunk
if (uploadedChunks === totalChunks) {
// Hide the progress bar when upload is complete
chrome.runtime.sendMessage({ type: "hideProgressBar" });
chrome.runtime.sendMessage({ type: "refreshFileList" });
chrome.runtime.sendMessage({ type: "uploadComplete" });
notifyUploadCompletion("uploadComplete");
resetUploadState();
}
})
.catch((error) => {
console.log("Upload Process Error: ", error);
activeUploads--;
processQueue();
});
}
}
function updateProgress() {
const progress = (uploadedChunks / totalFileChunks) * 100;
chrome.runtime.sendMessage({ type: "updateProgress", progress: progress });
}
// After an upload is complete or canceled, send a message to the popup script
function notifyUploadCompletion(status) {
chrome.runtime.sendMessage({ type: status });
chrome.runtime.sendMessage({ type: "refreshFileList" });
currentUpload = null;
isCanceled = false;
resetUploadState();
chrome.storage.local.remove("uploadState");
chrome.storage.local.remove("currentFile"); // Clear the current file data
}
function resetUploadState() {
// Reset all the state variables
uploadQueue = [];
activeUploads = 0;
uploadedChunks = 0;
totalFileChunks = 0;
isPaused = false;
isCanceled = false;
}
function saveUploadState(fileName, uploadedChunks, totalChunks, fileSize) {
const uploadState = {
fileName,
uploadedChunks,
totalChunks,
fileSize,
};
chrome.storage.local.set({ uploadState }, () => {
console.log("Upload state saved:", uploadState);
});
}
// Message Listeners (Chrome)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "restartUpload") {
isRestarting = true;
currentFileDetails = message.file;
isCanceled = true; // Set the cancel flag
// Clear the upload queue and reset active uploads
uploadQueue = [];
activeUploads = 0;
// Hide the progress bar and reset progress
chrome.runtime.sendMessage({ type: "hideProgressBar" });
chrome.runtime.sendMessage({ type: "resetProgress" });
// Call cancel on the server
fetch(`http://localhost:5000/api/upload/cancel`, {
method: "POST",
headers: { "X-File-Name": btoa(currentFileDetails.name) },
})
.then((response) => {
if (response.ok) {
// Hide the progress bar and reset progress
chrome.runtime.sendMessage({ type: "hideProgressBar" });
chrome.runtime.sendMessage({ type: "resetProgress" });
console.log("Canceled the uploading process successfully");
if (isRestarting) {
// Restart upload process after a brief delay to ensure cancellation is complete
handleFileUpload(
currentFileDetails.fileUrl,
currentFileDetails.name,
currentFileDetails.size
);
isRestarting = false;
}
}
})
.catch((error) =>
console.error("Error during upload cancellation:", error)
);
}
});
// Message listener for pause/resume
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "pauseResumeUpload") {
isPaused = !isPaused;
if (isPaused) {
// Save the current state to local storage
saveUploadState(
currentUpload.fileName,
uploadedChunks,
totalFileChunks,
currentUpload.fileSize
);
} else {
// Resume upload
// Do not remove the state here, as it's still needed for progress tracking
processQueue();
}
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "deleteAllFiles") {
fetch(`http://localhost:5000/api/upload/deleteAll`, {
method: "DELETE",
})
.then((response) => {
if (response.ok) {
console.log("All files deleted successfully");
// refresh the file list in the popup
chrome.runtime.sendMessage({ type: "refreshFileList" });
}
})
.catch((error) => console.error("Error deleting all files:", error));
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "startUpload") {
currentUpload = message;
handleFileUpload(message.fileUrl, message.fileName, message.fileSize);
} else if (message.type === "cancelCurrentUpload") {
// Cancel only the current upload
if (currentUpload && currentUpload.fileName === message.fileName) {
isCanceled = true;
console.log("clicked cancel");
const fileName = uploadQueue.length > 0 ? uploadQueue[0].fileName : null;
// Clear the upload queue and reset active uploads
uploadQueue = [];
activeUploads = 0;
// Hide the progress bar and refresh the file list in the popup
chrome.runtime.sendMessage({ type: "hideProgressBar" });
chrome.runtime.sendMessage({ type: "refreshFileList" });
if (fileName) {
// Send a request to the server to cancel the upload
fetch(`http://localhost:5000/api/upload/cancel`, {
method: "POST",
headers: { "X-File-Name": btoa(fileName) },
})
.then((response) => {
if (response.ok) {
console.log("Cancelled the Uploading process successfully");
// refresh the file list in the popup
chrome.runtime.sendMessage({ type: "refreshFileList" });
chrome.runtime.sendMessage({ type: "uploadCancelled" });
chrome.storage.local.remove("currentFile"); // Clear the current file data
notifyUploadCompletion("uploadCancelled");
}
})
.catch((error) => console.error("Cancellation error:", error));
}
}
}
});