-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
518 lines (450 loc) · 17.5 KB
/
script.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
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
let captchaText = '';
let mouseMovements = [];
function generateCaptcha() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 150;
canvas.height = 50;
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const captchaLength = 6;
captchaText = '';
for (let i = 0; i < captchaLength; i++) {
captchaText += characters.charAt(Math.floor(Math.random() * characters.length));
}
ctx.fillStyle = '#f2f2f2';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = getRandomColor();
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
for (let i = 0; i < 30; i++) {
ctx.fillStyle = getRandomColor();
ctx.beginPath();
ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2);
ctx.fill();
}
ctx.font = 'bold 24px Comic Sans MS';
ctx.fillStyle = '#000';
ctx.setTransform(
Math.cos(0.1), -Math.sin(0.1),
Math.sin(0.1), Math.cos(0.1),
20, 25
);
ctx.fillText(captchaText, 10, 30);
ctx.setTransform(1, 0, 0, 1, 0, 0);
document.getElementById('captcha').innerHTML = '';
document.getElementById('captcha').appendChild(canvas);
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
}
generateCaptcha();
function trackMouseMovement(event) {
mouseMovements.push({ x: event.clientX, y: event.clientY });
}
function analyzeMovements() {
// Check if there are enough recorded movements
if (mouseMovements.length < 10) {
return false; // Not enough data to analyze, assume it's not suspicious
}
let suspicious = false;
// Iterate through the recorded movements
for (let i = 1; i < mouseMovements.length; i++) {
// Calculate the difference in x and y coordinates between consecutive points
const dx = mouseMovements[i].x - mouseMovements[i - 1].x;
const dy = mouseMovements[i].y - mouseMovements[i - 1].y;
// If the differences are too small, mark as suspicious
if (Math.abs(dx) < 2 && Math.abs(dy) < 2) {
suspicious = true;
break; // Stop further checks if suspicious behavior is detected
}
}
return suspicious; // Return the result of the analysis
}
let currentUser;
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
async function login() {
document.addEventListener('mousemove', trackMouseMovement);
const suspicious = analyzeMovements();
if (suspicious) {
alert('Suspicious activity detected. Please login again.');
document.removeEventListener('mousemove', trackMouseMovement);
return;
}
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captchaInput = document.getElementById('captchaInput').value;
if (captchaInput.toLowerCase() !== captchaText.toLowerCase()) {
alert('Invalid captcha');
generateCaptcha();
return;
}
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
currentUser = username;
document.getElementById('loggedInUser').textContent = currentUser;
document.getElementById('loginSection').style.display = 'none';
document.getElementById('contentSection').style.display = 'block';
setCookie('username', username, 30);
setCookie('password', password, 30);
listUserFiles();
listStarredFiles()
} else {
alert('Login failed');
}
} catch (error) {
console.error('Error:', error);
alert('Login failed');
}
generateCaptcha();
}
async function autoLogin() {
const username = getCookie('username');
const password = getCookie('password');
if (username && password) {
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
currentUser = username;
document.getElementById('loggedInUser').textContent = currentUser;
document.getElementById('loginSection').style.display = 'none';
document.getElementById('contentSection').style.display = 'block';
listUserFiles();
listStarredFiles()
} else {
alert('Auto-login failed');
}
} catch (error) {
console.error('Error:', error);
alert('Auto-login failed');
}
}
}
async function register() {
document.addEventListener('mousemove', trackMouseMovement);
const suspicious = analyzeMovements();
if (suspicious) {
alert('Suspicious activity detected. Please register again.');
document.removeEventListener('mousemove', trackMouseMovement);
return;
}
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const captchaInput = document.getElementById('captchaInput').value;
if (captchaInput.toLowerCase() !== captchaText.toLowerCase()) {
alert('Invalid captcha');
generateCaptcha();
return;
}
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
alert('Registration successful. Please login.');
} else {
alert('Registration failed');
}
} catch (error) {
console.error('Error:', error);
alert('Registration failed');
}
generateCaptcha();
}
function logout() {
currentUser = '';
document.getElementById('loginSection').style.display = 'block';
document.getElementById('contentSection').style.display = 'none';
document.getElementById('username').value = '';
document.getElementById('password').value = '';
document.getElementById('captchaInput').value = '';
document.getElementById('userFiles').innerHTML = '';
generateCaptcha();
deleteCookie('username');
deleteCookie('password');
}
function deleteCookie(name) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}
async function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const description = document.getElementById('fileDescription').value;
const password = document.getElementById('filePassword').value;
if (!file) {
alert('Please select a file');
return;
}
if (!file.name.endsWith('.bin')) {
alert('Only .bin files are allowed');
return;
}
if (!password) { // Add this check
alert('Please enter your password');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('description', description);
formData.append('username', currentUser);
formData.append('password', password); // Add this line
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/upload', {
method: 'POST',
body: formData
});
if (response.ok) {
const result = await response.text();
document.getElementById('uploadResult').innerHTML = `File uploaded successfully. URL: ${result}`;
listUserFiles();
} else {
document.getElementById('uploadResult').innerHTML = 'Upload failed: ' + await response.text();
}
} catch (error) {
console.error('Error:', error);
document.getElementById('uploadResult').innerHTML = 'Upload failed';
}
}
async function searchFiles() {
const searchTerm = document.getElementById('searchInput').value;
try {
const response = await fetch(`https://osxiec-file-server-1.onrender.com/search?term=${encodeURIComponent(searchTerm)}&username=${encodeURIComponent(currentUser)}`);
if (response.ok) {
const results = await response.json();
let htmlResult = '<ul>';
results.forEach(file => {
const starAction = file.isStarred ? 'unstar' : 'star';
htmlResult += `<li>
<a href="${file.url}" target="_blank">${file.name}</a>
<br>Uploaded by: ${file.username}
<br>Description: ${file.description}
<br>Stars: ${file.starCount}
<br><button onclick="toggleStar('${file.name}', '${starAction}')">${file.isStarred ? 'Unstar' : 'Star'}</button>
</li>`;
});
htmlResult += '</ul>';
document.getElementById('searchResult').innerHTML = htmlResult;
openModal();
} else {
document.getElementById('searchResult').innerHTML = 'Search failed: ' + await response.text();
openModal();
}
} catch (error) {
console.error('Error:', error);
document.getElementById('searchResult').innerHTML = 'Search failed';
openModal();
}
}
async function listUserFiles() {
try {
const response = await fetch(`https://osxiec-file-server-1.onrender.com/user-files?username=${encodeURIComponent(currentUser)}¤tUser=${encodeURIComponent(currentUser)}`);
if (response.ok) {
const files = await response.json();
let htmlResult = '<ul>';
files.forEach(file => {
const starAction = file.isStarred ? 'unstar' : 'star';
htmlResult += `<li>
<a href="${file.url}" target="_blank">${file.name}</a>
<br>Description: ${file.description}
<br>Stars: ${file.starCount}
<br><button onclick="toggleStar('${file.name}', '${starAction}')">${file.isStarred ? 'Unstar' : 'Star'}</button>
<br><button onclick="removeFile('${file.name}')">Remove</button>
</li>`;
});
htmlResult += '</ul>';
document.getElementById('userFiles').innerHTML = htmlResult;
} else {
document.getElementById('userFiles').innerHTML = 'Failed to fetch user files: ' + await response.text();
}
} catch (error) {
console.error('Error:', error);
document.getElementById('userFiles').innerHTML = 'Failed to fetch user files';
}
}
async function removeFile(fileName) {
if (!confirm('Are you sure you want to remove this container, this action cannot be undone?')) {
return;
}
const password = document.getElementById('filePassword').value;
if (!password) {
alert('Password is required to remove the file');
return;
}
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/remove', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: currentUser,
password: password,
filename: fileName
}),
});
if (response.ok) {
alert('File removed successfully');
listUserFiles();
} else {
alert('Failed to remove file: ' + await response.text());
}
} catch (error) {
console.error('Error:', error);
alert('Failed to remove file');
}
}
function openModal() {
document.getElementById('searchModal').style.display = 'block';
}
function closeModal() {
document.getElementById('searchModal').style.display = 'none';
}
document.querySelector('.close').addEventListener('click', closeModal);
window.onclick = function(event) {
const modal = document.getElementById('searchModal');
if (event.target == modal) {
closeModal();
}
}
function upload(){
document.getElementById('uploadSection').style.display = 'block';
document.getElementById('contentSection').style.display = 'none';
}
function closeUpload(){
document.getElementById('uploadSection').style.display = 'none';
document.getElementById('contentSection').style.display = 'block';
}
window.onload = function() {
autoLogin();
}
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
searchFiles();
}
});
async function toggleStar(filename, action) {
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/star', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: currentUser, filename, action }),
});
if (response.ok) {
// Refresh the file list to show updated star status
listUserFiles();
// If we're in the search results, refresh those too
if (document.getElementById('searchModal').style.display === 'block') {
searchFiles();
}
} else {
alert(`Failed to ${action} file: ` + await response.text());
}
} catch (error) {
console.error('Error:', error);
alert(`Failed to ${action} file`);
}
}
async function listStarredFiles() {
try {
const response = await fetch(`https://osxiec-file-server-1.onrender.com/starred-files?username=${encodeURIComponent(currentUser)}`);
if (response.ok) {
const files = await response.json();
let htmlResult = '<h3>Starred Files</h3><ul>';
files.forEach(file => {
htmlResult += `<li>
<a href="${file.url}" target="_blank">${file.name}</a>
<br>Uploaded by: ${file.username}
<br>Description: ${file.description}
<br>Stars: ${file.starCount}
<br><button onclick="toggleStar('${file.name}', 'unstar')">Unstar</button>
</li>`;
});
htmlResult += '</ul>';
document.getElementById('starredFiles').innerHTML = htmlResult;
} else {
document.getElementById('starredFiles').innerHTML = 'Failed to fetch starred files: ' + await response.text();
}
} catch (error) {
console.error('Error:', error);
document.getElementById('starredFiles').innerHTML = 'Failed to fetch starred files';
}
}
async function resetPassword() {
const currentPassword = document.getElementById('currentPassword').value;
const newPassword = document.getElementById('newPassword').value;
const confirmPassword = document.getElementById('confirmPassword').value;
const username = currentUser; // Assuming currentUser is globally accessible
// Basic client-side validation
if (!currentPassword || !newPassword || !confirmPassword) {
alert('Please fill in all fields');
return;
}
if (newPassword !== confirmPassword) {
alert('Passwords do not match');
return;
}
try {
const response = await fetch('https://osxiec-file-server-1.onrender.com/reset', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
current_password: currentPassword,
new_password: newPassword // Send the new password
})
});
if (response.ok) {
alert('Password reset successful');
document.getElementById('passwordResetForm').reset(); // Reset form fields
} else {
const errorMessage = await response.text();
alert('Password reset failed: ' + errorMessage);
}
} catch (error) {
console.error('Error:', error);
alert('Password reset failed');
}
}
function reset(){
document.getElementById('resetSection').style.display = 'block';
document.getElementById('contentSection').style.display = 'none';
}
function closeReset(){
document.getElementById('resetSection').style.display = 'none';
document.getElementById('contentSection').style.display = 'block';
}