Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
726 lines (620 loc) · 27.6 KB
/
Copy pathscript.js
File metadata and controls
726 lines (620 loc) · 27.6 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
/* ==========================================================================
SCRIPT.JS
Logic untuk index.html (upload) dan download.html (download).
File ini otomatis mendeteksi ada di halaman mana lewat elemen yang tersedia.
Membutuhkan config.js dan Firebase JS SDK (compat build) dimuat SEBELUM file ini.
========================================================================== */
/* --- Init Firebase app + Firestore --- */
firebase.initializeApp(CONFIG.FIREBASE_CONFIG);
const db = firebase.firestore();
/* --- Init App Check (opsional, hanya jalan kalau RECAPTCHA_SITE_KEY diisi) ---
App Check memastikan hanya request dari halaman web asli kamu yang bisa
menulis/membaca ke Firestore, ini pengganti "anti-bot/anti-DDoS" tanpa
perlu server sendiri. Kalau belum setup, baris ini otomatis dilewati. */
if (CONFIG.RECAPTCHA_SITE_KEY && typeof firebase.appCheck === "function") {
try {
firebase.appCheck().activate(CONFIG.RECAPTCHA_SITE_KEY, true);
} catch (err) {
console.warn("App Check gagal diaktifkan:", err);
}
}
/* ==========================================================================
UTIL: Toast Notification
========================================================================== */
function showToast(message, type = "info") {
const wrap = document.getElementById("toastWrap");
if (!wrap) return;
const el = document.createElement("div");
el.className = `toast ${type}`;
const dot = document.createElement("span");
dot.className = "dot";
const text = document.createElement("span");
text.textContent = message; // textContent -> aman dari XSS, tidak pakai innerHTML
el.appendChild(dot);
el.appendChild(text);
wrap.appendChild(el);
setTimeout(() => {
el.style.opacity = "0";
el.style.transition = "opacity .3s ease";
setTimeout(() => el.remove(), 300);
}, 3200);
}
/* ==========================================================================
UTIL: Format ukuran file jadi human-readable (KB/MB/GB)
========================================================================== */
function formatBytes(bytes) {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
}
/* ==========================================================================
THEME SWITCHER (dipakai di kedua halaman)
========================================================================== */
(function initTheme() {
const saved = localStorage.getItem("dropshare-theme") || "lime";
applyTheme(saved);
document.querySelectorAll("[data-theme-btn]").forEach((btn) => {
btn.addEventListener("click", () => {
const theme = btn.getAttribute("data-theme-btn");
applyTheme(theme);
localStorage.setItem("dropshare-theme", theme);
});
});
function applyTheme(theme) {
document.body.setAttribute("data-theme", theme);
document.querySelectorAll("[data-theme-btn]").forEach((b) => {
b.classList.toggle("active", b.getAttribute("data-theme-btn") === theme);
});
}
})();
/* ==========================================================================
Notifikasi status koneksi internet
========================================================================== */
window.addEventListener("offline", () => showToast("Koneksi internet terputus.", "error"));
window.addEventListener("online", () => showToast("Koneksi internet tersambung kembali.", "success"));
/* ==========================================================================
PWA: Registrasi Service Worker (untuk fitur Share Target)
========================================================================== */
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("sw.js").catch((err) => {
console.warn("Gagal mendaftarkan service worker:", err);
});
});
}
/* ==========================================================================
PWA: Banner "Instal Aplikasi" custom (dipakai di index.html)
Memakai event beforeinstallprompt bawaan browser, ditampilkan lewat
UI custom bertema DropShare (bukan bar bawaan browser).
========================================================================== */
(function initInstallBanner() {
const banner = document.getElementById("installBanner");
if (!banner) return; // halaman ini tidak punya banner install (mis. download.html)
const installBtn = document.getElementById("installBtn");
const dismissBtn = document.getElementById("installDismissBtn");
let deferredPrompt = null;
// Catatan: "ditutup" di sini SENGAJA cuma berlaku untuk sesi halaman ini saja
// (variabel biasa, bukan localStorage/sessionStorage). Begitu halaman
// di-refresh, banner akan muncul lagi dari awal kalau browser masih
// menganggap app ini installable.
let dismissedThisSession = false;
window.addEventListener("beforeinstallprompt", (e) => {
e.preventDefault();
deferredPrompt = e;
if (!dismissedThisSession) {
banner.style.display = "flex";
}
});
installBtn.addEventListener("click", async () => {
if (!deferredPrompt) return;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
if (outcome === "accepted") {
showToast("DropShare sedang diinstal...", "success");
}
deferredPrompt = null;
banner.style.display = "none";
});
dismissBtn.addEventListener("click", () => {
banner.style.display = "none";
dismissedThisSession = true;
});
window.addEventListener("appinstalled", () => {
banner.style.display = "none";
showToast("DropShare berhasil diinstal! Coba bagikan file JSON dari WhatsApp.", "success");
});
})();
/* ==========================================================================
TUTORIAL: Lightbox zoom untuk gambar step-by-step.
Berjalan aman di halaman manapun - kalau elemennya gak ada, gak ngapa-ngapain.
========================================================================== */
(function initTutorialImages() {
const images = document.querySelectorAll(".step-img");
if (images.length === 0) return;
const lightboxOverlay = document.getElementById("lightboxOverlay");
const lightboxImg = document.getElementById("lightboxImg");
const lightboxClose = document.getElementById("lightboxClose");
if (!lightboxOverlay) return;
function openLightbox(src, alt) {
lightboxImg.src = src;
lightboxImg.alt = alt || "";
lightboxOverlay.classList.add("show");
document.body.style.overflow = "hidden";
}
function closeLightbox() {
lightboxOverlay.classList.remove("show");
document.body.style.overflow = "";
}
images.forEach((img) => {
img.addEventListener("click", () => openLightbox(img.src, img.alt));
});
lightboxClose.addEventListener("click", closeLightbox);
lightboxOverlay.addEventListener("click", (e) => {
if (e.target === lightboxOverlay) closeLightbox();
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") closeLightbox();
});
})();
/* ==========================================================================
ROUTER SEDERHANA
index.html punya elemen #uploadView -> jalankan initUploadPage()
download.html punya elemen #downloadView -> jalankan initDownloadPage()
========================================================================== */
document.addEventListener("DOMContentLoaded", () => {
if (document.getElementById("uploadView")) initUploadPage();
if (document.getElementById("downloadView")) initDownloadPage();
});
/* ==========================================================================
HALAMAN UPLOAD (index.html)
========================================================================== */
function initUploadPage() {
const dropzone = document.getElementById("dropzone");
const fileInput = document.getElementById("fileInput");
const fileInfo = document.getElementById("fileInfo");
const fName = document.getElementById("fName");
const fSize = document.getElementById("fSize");
const fRemove = document.getElementById("fRemove");
const uploadBtn = document.getElementById("uploadBtn");
const uploadBtnText = document.getElementById("uploadBtnText");
const progressWrap = document.getElementById("progressWrap");
const progressFill = document.getElementById("progressFill");
const progressPct = document.getElementById("progressPct");
const progressLabel = document.getElementById("progressLabel");
const uploadForm = document.getElementById("uploadForm");
const resultView = document.getElementById("resultView");
const resultLink = document.getElementById("resultLink");
const copyBtn = document.getElementById("copyBtn");
const openBtn = document.getElementById("openBtn");
const resetBtn = document.getElementById("resetBtn");
const showInRecentToggle = document.getElementById("showInRecentToggle");
let selectedFile = null;
let isUploading = false;
// Tampilkan daftar "File Terbaru" saat halaman dibuka
loadRecentFiles();
// --- Terapkan batasan tipe file dari config.js ke UI secara otomatis ---
applyAllowedTypesToUI();
// --- Ambil file "titipan" dari share.html (kalau datang dari tombol
// "Ubah File Ini Jadi Link"). File TIDAK otomatis diunggah - cuma
// otomatis dipasang ke form, user tetap harus klik "Unggah File". ---
loadFileFromShareHandoff();
async function loadFileFromShareHandoff() {
const params = new URLSearchParams(window.location.search);
if (params.get("from-share") !== "1") return;
if (!("caches" in window)) return;
try {
const cache = await caches.open("dropshare-share-target-v1");
const res = await cache.match("shared-file");
if (!res) return;
const blob = await res.blob();
const rawName = res.headers.get("X-File-Name");
const fileName = rawName ? decodeURIComponent(rawName) : "shared.json";
await cache.delete("shared-file");
const file = new File([blob], fileName, { type: blob.type || "application/json" });
selectFile(file);
showToast("File dari WhatsApp siap diunggah. Tekan \"Unggah File\" untuk buat link.", "info");
// Bersihkan parameter URL biar rapi & gak ke-reload kalau user refresh
window.history.replaceState({}, "", window.location.pathname);
} catch (err) {
console.warn("Gagal memuat file titipan dari share.html:", err);
}
}
function applyAllowedTypesToUI() {
const exts = CONFIG.ALLOWED_EXTENSIONS || [];
if (exts.length === 0) {
fileInput.removeAttribute("accept");
document.getElementById("dzTitle").textContent = "Seret & lepas file di sini";
document.getElementById("dzSub").textContent = "atau klik untuk memilih file dari perangkatmu";
document.getElementById("tagline").textContent = "Unggah file, dapatkan link, bagikan ke siapa saja. Cepat dan tanpa ribet.";
return;
}
fileInput.setAttribute("accept", exts.join(","));
const labels = exts.map((e) => e.replace(".", "").toUpperCase());
const readable = labels.length === 1
? labels[0]
: labels.slice(0, -1).join(", ") + " atau " + labels[labels.length - 1];
document.getElementById("dzTitle").textContent = `Seret & lepas file ${readable} di sini`;
document.getElementById("dzSub").textContent = `atau klik untuk memilih file ${readable} dari perangkatmu`;
document.getElementById("tagline").textContent = `Unggah file ${readable}, dapatkan link, bagikan ke siapa saja. Cepat dan tanpa ribet.`;
}
// --- Klik dropzone -> buka file picker ---
dropzone.addEventListener("click", () => fileInput.click());
dropzone.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); fileInput.click(); }
});
// --- Drag & drop ---
["dragenter", "dragover"].forEach((evt) => {
dropzone.addEventListener(evt, (e) => {
e.preventDefault();
dropzone.classList.add("dragover");
});
});
["dragleave", "drop"].forEach((evt) => {
dropzone.addEventListener(evt, (e) => {
e.preventDefault();
dropzone.classList.remove("dragover");
});
});
dropzone.addEventListener("drop", (e) => {
const file = e.dataTransfer.files[0];
if (file) selectFile(file);
});
// --- Pilih file via input ---
fileInput.addEventListener("change", () => {
if (fileInput.files[0]) selectFile(fileInput.files[0]);
});
// --- Hapus file yang dipilih ---
fRemove.addEventListener("click", (e) => {
e.stopPropagation();
resetFileSelection();
});
function selectFile(file) {
if (!file || file.size === 0) {
showToast("File kosong tidak dapat diunggah.", "error");
return;
}
if (file.size > CONFIG.MAX_FILE_SIZE) {
showToast(`Ukuran file melebihi batas maksimum (${formatBytes(CONFIG.MAX_FILE_SIZE)}).`, "error");
return;
}
const exts = CONFIG.ALLOWED_EXTENSIONS || [];
if (exts.length > 0) {
const nameLower = file.name.toLowerCase();
const isAllowedExt = exts.some((ext) => nameLower.endsWith(ext.toLowerCase()));
if (!isAllowedExt) {
showToast(`Tipe file tidak didukung. Hanya ${exts.join(", ")} yang diizinkan.`, "error");
return;
}
}
selectedFile = file;
fName.textContent = file.name;
fSize.textContent = formatBytes(file.size);
fileInfo.classList.add("show");
uploadBtn.disabled = false;
uploadBtnText.textContent = "Unggah File";
}
function resetFileSelection() {
selectedFile = null;
fileInput.value = "";
fileInfo.classList.remove("show");
uploadBtn.disabled = true;
uploadBtnText.textContent = "Pilih file dahulu";
progressWrap.classList.remove("show");
progressFill.style.width = "0%";
progressFill.classList.remove("shimmer");
progressPct.textContent = "0%";
}
// --- Proses upload ---
uploadBtn.addEventListener("click", async () => {
if (!selectedFile || isUploading) return;
if (!navigator.onLine) {
showToast("Tidak ada koneksi internet. Coba lagi nanti.", "error");
return;
}
// --- Cooldown anti-spam klik berulang (proteksi ringan di sisi client) ---
const cooldownMs = CONFIG.UPLOAD_COOLDOWN_MS || 0;
const lastUpload = parseInt(localStorage.getItem("dropshare-last-upload") || "0", 10);
const sinceLast = Date.now() - lastUpload;
if (cooldownMs > 0 && sinceLast < cooldownMs) {
const waitSec = Math.ceil((cooldownMs - sinceLast) / 1000);
showToast(`Tunggu ${waitSec} detik sebelum mengunggah file lagi.`, "error");
return;
}
isUploading = true;
uploadBtn.disabled = true;
fRemove.style.pointerEvents = "none";
progressWrap.classList.add("show");
progressLabel.textContent = "Uploading...";
uploadBtnText.innerHTML = "";
const spinner = document.createElement("span");
spinner.className = "spinner";
uploadBtnText.appendChild(spinner);
uploadBtnText.appendChild(document.createTextNode(" Mengunggah..."));
// Progress bar palsu (Firestore write tidak punya event progress asli),
// supaya UX tetap terasa responsif untuk file kecil.
let fakePct = 0;
const fakeProgress = setInterval(() => {
fakePct = Math.min(fakePct + 15, 90);
progressFill.style.width = fakePct + "%";
progressPct.textContent = Math.round(fakePct) + "%";
}, 120);
try {
const result = await uploadToFirestore(selectedFile, showInRecentToggle && showInRecentToggle.checked);
clearInterval(fakeProgress);
progressFill.style.width = "100%";
progressPct.textContent = "100%";
localStorage.setItem("dropshare-last-upload", String(Date.now()));
const shareUrl = `${window.location.origin}${window.location.pathname.replace(/index\.html$/, "").replace(/\/$/, "")}/download.html?id=${encodeURIComponent(result.id)}`;
resultLink.value = shareUrl;
uploadForm.style.display = "none";
resultView.classList.add("show");
if (result.deduped) {
showToast("File yang sama sudah pernah diunggah — pakai link yang sudah ada (hemat kuota).", "info");
} else {
showToast("File berhasil diunggah!", "success");
}
loadRecentFiles();
} catch (err) {
clearInterval(fakeProgress);
console.error(err);
showToast(err.message || "Gagal mengunggah file. Coba lagi.", "error");
progressLabel.textContent = "Gagal mengunggah";
} finally {
isUploading = false;
uploadBtn.disabled = false;
fRemove.style.pointerEvents = "auto";
uploadBtnText.textContent = "Unggah File";
}
});
// --- Salin link ---
copyBtn.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(resultLink.value);
showToast("Link disalin ke clipboard!", "success");
} catch {
resultLink.select();
document.execCommand("copy");
showToast("Link disalin!", "success");
}
});
// --- Buka link ---
openBtn.addEventListener("click", () => {
window.open(resultLink.value, "_blank");
});
// --- Upload file lagi ---
resetBtn.addEventListener("click", () => {
resultView.classList.remove("show");
uploadForm.style.display = "block";
resetFileSelection();
});
}
/* ==========================================================================
FUNGSI: Baca file sebagai teks (Promise wrapper untuk FileReader)
========================================================================== */
function readFileAsText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error("Gagal membaca file."));
reader.readAsText(file);
});
}
/* ==========================================================================
FUNGSI: Hitung hash SHA-256 dari isi file (untuk deteksi duplikat).
Dua file dengan isi persis sama akan selalu menghasilkan hash yang sama,
walau nama filenya berbeda.
========================================================================== */
async function sha256Hex(text) {
const enc = new TextEncoder().encode(text);
const hashBuffer = await crypto.subtle.digest("SHA-256", enc);
return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
/* ==========================================================================
FUNGSI: Upload file ke Firestore.
Isi file disimpan sebagai field string di dalam 1 dokumen. Firestore
membatasi ukuran dokumen ~1MB, karena itu file divalidasi terhadap
CONFIG.MAX_FILE_SIZE (jauh di bawah limit itu) sebelum dikirim.
ANTI-DUPLIKAT: sebelum membuat dokumen baru, dicek dulu apakah sudah ada
file dengan isi (hash) yang sama di antara file-file publik. Kalau ada,
file baru TIDAK dibuat - cukup pakai link yang sudah ada, supaya storage
gratis tidak cepat habis karena file yang sama diupload berulang kali.
Pengecekan ini hanya berlaku untuk file publik (lihat catatan di rules).
========================================================================== */
async function uploadToFirestore(file, isPublic) {
const content = await readFileAsText(file);
// Validasi tambahan: pastikan isi file benar-benar JSON valid,
// bukan cuma mengandalkan ekstensi nama file.
try {
JSON.parse(content);
} catch (e) {
throw new Error("Isi file bukan JSON yang valid.");
}
const contentHash = await sha256Hex(content);
try {
// --- Cek duplikat (hanya di antara file publik) ---
if (isPublic) {
const dupSnap = await db.collection(CONFIG.FILES_COLLECTION)
.where("public", "==", true)
.where("contentHash", "==", contentHash)
.limit(1)
.get();
if (!dupSnap.empty) {
return { id: dupSnap.docs[0].id, deduped: true };
}
}
const docData = {
name: file.name,
content: content,
size: file.size,
type: file.type || "application/json",
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
public: !!isPublic,
contentHash: contentHash
};
const ref = await db.collection(CONFIG.FILES_COLLECTION).add(docData);
return { id: ref.id, deduped: false };
} catch (err) {
console.error(err);
if (err.code === "permission-denied") {
throw new Error("Upload ditolak oleh aturan keamanan (cek Firestore Rules / App Check).");
}
throw new Error("Upload gagal. Periksa koneksi atau konfigurasi Firebase.");
}
}
/* ==========================================================================
HALAMAN DOWNLOAD (download.html)
Alur:
1. Ambil parameter ?id=
2. Ambil dokumen dari Firestore berdasarkan id tsb
3. Bentuk file Blob dari isi dokumen -> trigger auto-download
4. Tampilkan error yang jelas jika gagal / offline
========================================================================== */
async function initDownloadPage() {
const dlLoading = document.getElementById("dlLoading");
const dlReady = document.getElementById("dlReady");
const dlReadyIcon = document.getElementById("dlReadyIcon");
const dlFileName = document.getElementById("dlFileName");
const dlFileSize = document.getElementById("dlFileSize");
const dlFileDate = document.getElementById("dlFileDate");
const dlReadyStatus = document.getElementById("dlReadyStatus");
const dlReadySpinner = document.getElementById("dlReadySpinner");
const dlManualWrap = document.getElementById("dlManualWrap");
const dlManualBtn = document.getElementById("dlManualBtn");
const dlError = document.getElementById("dlError");
const dlErrorMsg = document.getElementById("dlErrorMsg");
const params = new URLSearchParams(window.location.search);
const fileId = params.get("id");
if (!fileId) {
return showError("Link tidak valid. Parameter id tidak ditemukan.");
}
if (!navigator.onLine) {
return showError("Tidak ada koneksi internet. Periksa jaringanmu dan coba lagi.");
}
let objectUrl = null;
try {
const snap = await db.collection(CONFIG.FILES_COLLECTION).doc(fileId).get();
if (!snap.exists) {
return showError("File tidak ditemukan. Link mungkin sudah kedaluwarsa atau dihapus.");
}
const data = snap.data();
const fileName = data.name || `${fileId}.json`;
const fileSize = typeof data.size === "number" ? data.size : new Blob([data.content || ""]).size;
const createdAt = data.createdAt && data.createdAt.toDate ? data.createdAt.toDate() : null;
const blob = new Blob([data.content || ""], { type: data.type || "application/json" });
objectUrl = URL.createObjectURL(blob);
dlFileName.textContent = fileName;
dlFileSize.textContent = formatBytes(fileSize);
dlFileDate.textContent = createdAt ? formatUploadDate(createdAt) : "Tanggal tidak diketahui";
dlLoading.style.display = "none";
dlReady.style.display = "block";
dlReadyStatus.textContent = "Menyiapkan unduhan...";
await new Promise((resolve) => setTimeout(resolve, 1100));
triggerDownload(objectUrl, fileName);
dlReadySpinner.style.display = "none";
dlReadyStatus.textContent = "Unduhan dimulai. Jika tidak berjalan otomatis, klik tombol di bawah.";
dlReadyIcon.outerHTML = '<svg id="dlReadyIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>';
dlManualWrap.style.display = "block";
dlManualBtn.addEventListener("click", () => triggerDownload(objectUrl, fileName));
} catch (err) {
console.error(err);
if (err.code === "permission-denied") {
showError("Akses ditolak oleh aturan keamanan Firestore.");
} else {
showError("Terjadi kesalahan saat menyiapkan file. Coba lagi nanti.");
}
}
function triggerDownload(url, name) {
const a = document.createElement("a");
a.href = url;
a.download = name;
a.rel = "noopener";
document.body.appendChild(a);
a.click();
a.remove();
}
function showError(message) {
dlLoading.style.display = "none";
dlReady.style.display = "none";
dlError.classList.add("show");
dlErrorMsg.textContent = message;
showToast(message, "error");
}
}
/* ==========================================================================
FUNGSI: Muat & tampilkan file terbaru yang diunggah (publik, opt-in
lewat toggle privasi). Data diambil dari Firestore, field `public == true`.
Kalau collection kosong, kartu "File Terbaru" otomatis disembunyikan.
========================================================================== */
async function loadRecentFiles() {
const sectionEl = document.getElementById("recentFilesSection");
const listEl = document.getElementById("recentFilesList");
if (!sectionEl || !listEl) return;
try {
const snap = await db.collection(CONFIG.FILES_COLLECTION)
.where("public", "==", true)
.orderBy("createdAt", "desc")
.limit(CONFIG.RECENT_UPLOADS_LIMIT || 15)
.get();
if (snap.empty) {
sectionEl.style.display = "none";
return;
}
const basePath = window.location.pathname.replace(/index\.html$/, "").replace(/\/$/, "");
listEl.innerHTML = "";
snap.forEach((doc) => {
const row = doc.data();
const a = document.createElement("a");
a.className = "recent-item";
a.href = `${basePath}/download.html?id=${encodeURIComponent(doc.id)}`;
const icon = document.createElement("div");
icon.className = "recent-icon";
icon.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/></svg>';
const meta = document.createElement("div");
meta.className = "recent-meta";
const nameEl = document.createElement("div");
nameEl.className = "recent-name";
nameEl.textContent = row.name;
const subEl = document.createElement("div");
subEl.className = "recent-sub";
const createdAt = row.createdAt && row.createdAt.toDate ? row.createdAt.toDate() : null;
subEl.textContent = `${formatBytes(row.size || 0)} · ${createdAt ? formatRelativeTime(createdAt) : "-"}`;
meta.appendChild(nameEl);
meta.appendChild(subEl);
const arrow = document.createElement("div");
arrow.className = "recent-arrow";
arrow.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>';
a.appendChild(icon);
a.appendChild(meta);
a.appendChild(arrow);
listEl.appendChild(a);
});
sectionEl.style.display = "block";
} catch (err) {
console.error("Gagal memuat file terbaru:", err);
sectionEl.style.display = "none";
}
}
/* ==========================================================================
UTIL: Format waktu relatif (mis. "5 menit lalu") dari objek Date
========================================================================== */
function formatRelativeTime(date) {
const diffSec = Math.floor((Date.now() - date.getTime()) / 1000);
if (diffSec < 60) return "Baru saja";
if (diffSec < 3600) return `${Math.floor(diffSec / 60)} menit lalu`;
if (diffSec < 86400) return `${Math.floor(diffSec / 3600)} jam lalu`;
return `${Math.floor(diffSec / 86400)} hari lalu`;
}
/* ==========================================================================
UTIL: Format tanggal upload (dari objek Date) ke format Indonesia
========================================================================== */
function formatUploadDate(date) {
try {
return date.toLocaleDateString("id-ID", {
day: "numeric", month: "long", year: "numeric",
hour: "2-digit", minute: "2-digit"
});
} catch {
return "Tanggal tidak diketahui";
}
}