-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
296 lines (246 loc) · 10.2 KB
/
app.js
File metadata and controls
296 lines (246 loc) · 10.2 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
// Elements
const themeToggle = document.getElementById('themeToggle');
const sunIcon = document.getElementById('sunIcon');
const moonIcon = document.getElementById('moonIcon');
const uploadView = document.getElementById('uploadView');
const accessView = document.getElementById('accessView');
const uploadForm = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const dropzone = document.getElementById('dropzone');
const fileNameDisplay = document.getElementById('fileNameDisplay');
const uploadBtn = document.getElementById('uploadBtn');
const uploadError = document.getElementById('uploadError');
const uploadSuccess = document.getElementById('uploadSuccess');
const resultUrl = document.getElementById('resultUrl');
const resultPin = document.getElementById('resultPin');
const customUrlInput = document.getElementById('customUrl');
const resetBtn = document.getElementById('resetBtn');
const accessForm = document.getElementById('accessForm');
const pinInput = document.getElementById('pinInput');
const accessUrlDisplay = document.getElementById('accessUrlDisplay');
const accessError = document.getElementById('accessError');
const downloadBtn = document.getElementById('downloadBtn');
const nukeBtn = document.getElementById('nukeBtn');
let turnstileToken = null;
let currentFile = null;
const MAX_FILE_SIZE = 1 * 1024 * 1024; // 1MB
const HOSTNAME = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' ? window.location.host : 'temp-pdf.pages.dev';
// Theme toggling
function toggleTheme() {
const isDark = document.body.classList.toggle('dark-mode');
document.body.classList.toggle('light-mode', !isDark);
sunIcon.classList.toggle('hidden', !isDark);
moonIcon.classList.toggle('hidden', isDark);
localStorage.setItem('theme', isDark ? 'dark' : 'light');
}
// Initialize theme
if (localStorage.getItem('theme') === 'dark' || (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
toggleTheme();
}
themeToggle.addEventListener('click', toggleTheme);
// Turnstile Callback
window.onTurnstileSuccess = function (token) {
turnstileToken = token;
validateUploadForm();
};
// Form Validation
function validateUploadForm() {
const isFileValid = currentFile && currentFile.size <= MAX_FILE_SIZE;
const isUrlValid = customUrlInput.value.trim().length > 0;
// We only require turnstile token if there is one configured
const isTokenValid = document.querySelector('.cf-turnstile') ? !!turnstileToken : true;
uploadBtn.disabled = !(isFileValid && isUrlValid && isTokenValid);
}
// File Drag & Drop logic
dropzone.addEventListener('dragover', (e) => {
e.preventDefault();
dropzone.classList.add('dragover');
});
dropzone.addEventListener('dragleave', () => dropzone.classList.remove('dragover'));
dropzone.addEventListener('drop', (e) => {
e.preventDefault();
dropzone.classList.remove('dragover');
if (e.dataTransfer.files.length) handleFileSelection(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length) handleFileSelection(e.target.files[0]);
});
function handleFileSelection(file) {
if (file.size > MAX_FILE_SIZE) {
showError(uploadError, "File exceeds 1MB limit.");
currentFile = null;
fileNameDisplay.textContent = "Click or drag a file to upload";
dropzone.classList.remove('success');
customUrlInput.parentElement.classList.remove('url-ready');
} else if (!['application/pdf', 'text/plain'].includes(file.type)) {
showError(uploadError, "Only PDF and TXT files are allowed.");
currentFile = null;
fileNameDisplay.textContent = "Click or drag a file to upload";
dropzone.classList.remove('success');
customUrlInput.parentElement.classList.remove('url-ready');
} else {
uploadError.textContent = "";
currentFile = file;
fileNameDisplay.textContent = file.name;
dropzone.classList.add('success');
customUrlInput.parentElement.classList.add('url-ready');
}
// Reset input so `change` event fires even if the same file is chosen again
fileInput.value = '';
validateUploadForm();
}
customUrlInput.addEventListener('input', validateUploadForm);
function showError(el, msg) {
el.textContent = msg;
setTimeout(() => el.textContent = "", 5000);
}
// Upload Submission
uploadForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (uploadBtn.disabled) return;
uploadBtn.disabled = true;
uploadBtn.textContent = "Uploading...";
uploadError.textContent = "";
try {
const formData = new FormData();
formData.append('file', currentFile);
formData.append('url', customUrlInput.value.trim());
const selectedTtl = document.querySelector('input[name="ttl"]:checked').value;
formData.append('ttl', selectedTtl);
if (turnstileToken) formData.append('cf-turnstile-response', turnstileToken);
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Upload failed');
}
// Show Success
uploadForm.classList.add('hidden');
uploadSuccess.classList.remove('hidden');
resultUrl.textContent = `${HOSTNAME}/${data.url}`;
resultPin.textContent = data.pin;
} catch (err) {
showError(uploadError, err.message);
uploadBtn.disabled = false;
uploadBtn.textContent = "Upload File";
}
});
function resetUpload() {
currentFile = null;
fileNameDisplay.textContent = "Click or drag a file to upload";
dropzone.classList.remove('success');
customUrlInput.parentElement.classList.remove('url-ready');
customUrlInput.value = "";
turnstileToken = null;
if (window.turnstile) turnstile.reset();
uploadForm.classList.remove('hidden');
uploadSuccess.classList.add('hidden');
uploadBtn.disabled = true;
uploadBtn.textContent = "Upload File";
}
resetBtn.addEventListener('click', resetUpload);
// Routing logic
async function checkRoute() {
const path = window.location.pathname.substring(1).split('/')[0];
if (path && path !== "api" && path !== "index.html") {
// We are on a custom URL
uploadView.classList.add('hidden');
accessView.classList.remove('hidden');
accessUrlDisplay.textContent = path;
// Check if URL actually exists
try {
const res = await fetch(`/api/check/${path}`);
if (res.status === 404) {
accessSubtitle.textContent = "File not found or expired.";
accessForm.classList.add('hidden');
}
} catch (e) { /* ignore network errors here, let user try pin */ }
}
}
checkRoute();
// Access & Download Logic
accessForm.addEventListener('submit', async (e) => {
e.preventDefault();
downloadBtn.disabled = true;
accessError.textContent = "";
const url = accessUrlDisplay.textContent;
const pin = pinInput.value;
if (pin.length !== 2) {
showError(accessError, "Enter 2-digit PIN.");
downloadBtn.disabled = false;
return;
}
try {
downloadBtn.textContent = "Verifying...";
// Step 1: Synchronously open a blank window (critical for Safari popup blocker)
// This must remain in the same execution cycle as the button click event
const newWindow = window.open('', '_blank');
// Step 2: Verify PIN via secure POST and get a one-time token
const res = await fetch(`/api/verify/${url}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin })
});
const data = await res.json();
if (!res.ok) {
// Close the blank window if verification fails
if (newWindow) newWindow.close();
throw new Error(data.error || "Access Denied");
}
// Step 3: Use the pre-opened window to navigate to the file
// Adding download=1 will hint the browser (especially iOS Safari) to download the file directly on mobile
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const downloadUrl = `/api/get/${url}?token=${data.token}${isMobile ? '&download=1' : ''}`;
downloadBtn.textContent = "Opening...";
if (newWindow) {
newWindow.location.href = downloadUrl;
} else {
// Fallback if the popup blocker somehow still blocked it (e.g. strict settings)
window.location.href = downloadUrl;
}
setTimeout(() => {
downloadBtn.textContent = "Download / View";
downloadBtn.disabled = false;
}, 2000);
} catch (err) {
pinInput.classList.remove('pin-error');
void pinInput.offsetWidth; // trigger reflow
pinInput.classList.add('pin-error');
showError(accessError, err.message);
downloadBtn.disabled = false;
downloadBtn.textContent = "Download / View";
}
});
nukeBtn.addEventListener('click', async () => {
const url = accessUrlDisplay.textContent;
const pin = pinInput.value;
if (pin.length !== 2) {
showError(accessError, "Enter PIN to delete.");
return;
}
if (!confirm("Are you sure you want to instantly delete this file?")) return;
nukeBtn.disabled = true;
nukeBtn.textContent = "Deleting...";
try {
const res = await fetch(`/api/delete/${url}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ pin })
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || "Failed to delete");
}
accessSubtitle.textContent = "File has been deleted.";
accessForm.classList.add('hidden');
} catch (err) {
pinInput.classList.remove('pin-error');
void pinInput.offsetWidth; // trigger reflow
pinInput.classList.add('pin-error');
showError(accessError, err.message);
nukeBtn.disabled = false;
nukeBtn.textContent = "Delete Now";
}
});