-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
340 lines (296 loc) · 9.72 KB
/
script.js
File metadata and controls
340 lines (296 loc) · 9.72 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
// Simple browser ZIP extractor using zip.js
// - Supports password-protected ZIPs (WinZIP AES + ZipCrypto)
// - Works fully client-side in modern browsers
// Grab DOM elements
const fileInput = document.getElementById("zipFileInput");
const dropZone = document.getElementById("dropZone");
const passwordInput = document.getElementById("passwordInput");
const extractBtn = document.getElementById("extractBtn");
const fileInfo = document.getElementById("fileInfo");
const progressContainer = document.getElementById("progressContainer");
const progressBar = document.getElementById("progressBar");
const progressText = document.getElementById("progressText");
const messageBox = document.getElementById("message");
const fileList = document.getElementById("fileList");
const resultsCard = document.getElementById("resultsCard");
// Keep state in memory
let selectedFile = null;
let extractedFiles = []; // { name, size, blob, url }
// Utility: format bytes to human readable size
function formatBytes(bytes) {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const value = bytes / Math.pow(1024, i);
return `${value.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}
// Utility: show a message (type = "error" | "success" | "warning")
function showMessage(text, type = "success") {
messageBox.className = "message"; // reset
if (!text) {
messageBox.classList.remove("show");
return;
}
messageBox.textContent = text;
messageBox.classList.add("show");
messageBox.classList.add(type);
}
// Utility: set loading state (disable button, show spinner text)
function setLoading(isLoading) {
if (isLoading) {
extractBtn.disabled = true;
extractBtn.textContent = "Extracting…";
} else {
extractBtn.disabled = false;
extractBtn.textContent = "Extract ZIP";
}
}
// Utility: clear previous results and URLs
function resetResults() {
// Revoke old object URLs to free memory
extractedFiles.forEach((f) => {
if (f.url) URL.revokeObjectURL(f.url);
});
extractedFiles = [];
fileList.innerHTML = "";
resultsCard.style.display = "none";
progressBar.style.width = "0%";
progressText.textContent = "Preparing…";
progressContainer.style.display = "none";
}
// Handle file selection from input
fileInput.addEventListener("change", (event) => {
const file = event.target.files[0];
handleNewFile(file);
});
// Handle drag & drop selection
["dragenter", "dragover"].forEach((evtName) => {
dropZone.addEventListener(evtName, (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.add("drag-over");
});
});
["dragleave", "drop"].forEach((evtName) => {
dropZone.addEventListener(evtName, (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.remove("drag-over");
});
});
dropZone.addEventListener("drop", (e) => {
const file = e.dataTransfer.files[0];
handleNewFile(file);
});
// Handle selecting a new zip file
function handleNewFile(file) {
resetResults();
showMessage("");
if (!file) {
selectedFile = null;
fileInfo.textContent = "No file selected";
return;
}
// Basic type check (not perfect but helps)
if (
!file.name.toLowerCase().endsWith(".zip") &&
file.type !== "application/zip"
) {
selectedFile = null;
fileInfo.textContent = "No file selected";
showMessage("Please choose a .zip file.", "error");
return;
}
selectedFile = file;
fileInfo.textContent = `${file.name} (${formatBytes(file.size)})`;
// Optional warning for very large files on mobile
const largeBytes = 150 * 1024 * 1024; // 150 MB
if (file.size > largeBytes) {
showMessage(
"Large archive detected. On some mobile devices this may be slow or fail due to limited memory.",
"warning"
);
}
}
// Main extract button handler
extractBtn.addEventListener("click", async () => {
if (!selectedFile) {
showMessage("Please select a ZIP file first.", "error");
return;
}
if (typeof zip === "undefined") {
showMessage(
"zip.js library did not load. Check your internet connection and reload the page.",
"error"
);
return;
}
resetResults();
setLoading(true);
showMessage("");
const password = passwordInput.value || undefined;
try {
// Create a ZipReader for the selected file
// Passing { password } allows reading password-protected zips
const readerOptions = {};
if (password) {
readerOptions.password = password;
}
const zipReader = new zip.ZipReader(
new zip.BlobReader(selectedFile),
readerOptions
);
// Try to get entries; invalid password or unsupported encryption
// can throw here or later when reading file data.
let entries;
try {
entries = await zipReader.getEntries();
} catch (error) {
// Wrong or missing password for an encrypted archive
if (
error.message === zip.ERR_INVALID_PASSWORD ||
error.message === zip.ERR_ENCRYPTED
) {
await zipReader.close();
showMessage("Incorrect password or encrypted with unsupported method.", "error");
setLoading(false);
return;
}
// Other unexpected error
console.error(error);
await zipReader.close();
showMessage("Could not read ZIP file: " + error.message, "error");
setLoading(false);
return;
}
if (!entries || entries.length === 0) {
await zipReader.close();
showMessage("ZIP file is empty or could not be read.", "error");
setLoading(false);
return;
}
// Filter out directory entries
const fileEntries = entries.filter((entry) => !entry.directory);
if (fileEntries.length === 0) {
await zipReader.close();
showMessage("ZIP contains only folders, no files to extract.", "warning");
setLoading(false);
return;
}
let processedCount = 0;
const totalCount = fileEntries.length;
progressContainer.style.display = "block";
progressBar.style.width = "0%";
progressText.textContent = "Starting extraction…";
// Extract files one by one
for (const entry of fileEntries) {
const writer = new zip.BlobWriter();
try {
await entry.getData(writer, {
// Progress for this single file
onprogress: (index, max) => {
if (max) {
const percentFile = Math.round((index / max) * 100);
progressText.textContent = `Extracting: ${entry.filename} (${percentFile}%)`;
} else {
progressText.textContent = `Extracting: ${entry.filename}`;
}
},
});
} catch (error) {
// Wrong or missing password when actually decrypting data
if (
error.message === zip.ERR_INVALID_PASSWORD ||
error.message === zip.ERR_ENCRYPTED
) {
console.error(error);
await zipReader.close();
showMessage(
password
? "Password is incorrect for this ZIP."
: "This ZIP is password‑protected. Please enter the password and try again.",
"error"
);
setLoading(false);
progressContainer.style.display = "none";
resetResults();
return;
}
// For other errors, log and skip this file
console.error("Error extracting entry", entry.filename, error);
showMessage(
`Some files could not be extracted: ${entry.filename}`,
"warning"
);
continue;
}
const blob = await writer.getData();
const url = URL.createObjectURL(blob);
extractedFiles.push({
name: entry.filename,
size: blob.size,
blob,
url,
});
processedCount += 1;
const percentAll = Math.round((processedCount / totalCount) * 100);
progressBar.style.width = `${percentAll}%`;
}
await zipReader.close();
if (extractedFiles.length === 0) {
showMessage(
"No files were extracted. The archive may be corrupted or fully encrypted with an unsupported method.",
"error"
);
setLoading(false);
progressContainer.style.display = "none";
return;
}
renderFileList();
showMessage("Extraction completed successfully.", "success");
} catch (err) {
console.error(err);
showMessage("Unexpected error while extracting ZIP: " + err.message, "error");
} finally {
setLoading(false);
}
});
// Render the extracted files list with download buttons
function renderFileList() {
fileList.innerHTML = "";
extractedFiles.forEach((file, index) => {
const row = document.createElement("div");
row.className = "file-row";
const main = document.createElement("div");
main.className = "file-main";
const nameEl = document.createElement("div");
nameEl.className = "file-name";
nameEl.textContent = file.name;
const sizeEl = document.createElement("div");
sizeEl.className = "file-size";
sizeEl.textContent = formatBytes(file.size);
main.appendChild(nameEl);
main.appendChild(sizeEl);
const downloadBtn = document.createElement("button");
downloadBtn.className = "btn primary";
downloadBtn.textContent = "Download";
downloadBtn.addEventListener("click", () => {
downloadFile(file, index);
});
row.appendChild(main);
row.appendChild(downloadBtn);
fileList.appendChild(row);
});
resultsCard.style.display = "block";
}
// Trigger browser download for a single extracted file
function downloadFile(file, index) {
const a = document.createElement("a");
a.href = file.url;
// Use last path segment as filename
const parts = file.name.split("/");
a.download = parts[parts.length - 1] || "file";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}