-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
2049 lines (1807 loc) · 68.4 KB
/
index.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
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const multer = require('multer');
const path = require('path');
const bcrypt = require('bcrypt');
const fs = require('fs');
const sharp = require('sharp');
const { v4: uuidv4 } = require('uuid');
const Vibrant = require('node-vibrant');
const { removeMetadata, base64StringToArrayBuffer } = require('@qoocollections/content-metadata-remover');
const axios = require('axios');
const jwt = require('jsonwebtoken');
const sqlite3 = require('sqlite3').verbose();
const { DateTime } = require('luxon');
const now = DateTime.now().setZone('Europe/Berlin');
const currentHour = now.hour;
const os = require('os');
const clc = require('cli-color');
const ffprobe = require('ffprobe');
const ffprobeStatic = require('ffprobe-static');
const ffmpeg = require("fluent-ffmpeg");
const ffmpegInstaller = require("@ffmpeg-installer/ffmpeg");
const hls = require('hls-server');
const nocache = require('nocache');
const cookieParser = require('cookie-parser');
const sanitize = require('sanitize');
require('dotenv').config();
const { BASE_URL, PORT, JWT_TOKEN, SITE_TITLE, SITE_FAVICON, OG_TITLE, OG_DESCRIPTION, THEME_COLOR, FONT_COLOR, AUTHOR_URL, AUTHOR_NAME, PROVIDER_NAME, PROVIDER_URL, DOMINANT_COLOR_STATIC, BOX_SHADOW_COLOR, COPYRIGHT_TEXT, DISCORD_WEBHOOK_NAME, DISCORD_WEBHOOK_URL, DISCORD_WEBHOOK_SUCCESS_COLOR, DISCORD_WEBHOOK_ERROR_COLOR, REDIRECT_URL } = process.env
const AUDIO_FORMATS = process.env.AUDIO_FORMATS.split(',');
const VIDEO_FORMATS = process.env.VIDEO_FORMATS.split(',');
const IMAGE_FORMATS = process.env.IMAGE_FORMATS.split(',');
const USE_DOMINANT_COLOR = process.env.USE_DOMINANT_COLOR === 'true';
const REMOVE_METADATA = process.env.REMOVE_METADATA === 'true';
const USE_PREVIEW = process.env.USE_PREVIEW === 'true';
const USE_HLS = process.env.USE_HLS === 'true';
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(sanitize.middleware);
if (process.env.ALLOW_METRICS === 'true') {
const Sentry = require("@sentry/node");
const { CaptureConsole } = require('@sentry/integrations');
Sentry.init({
dsn: "https://[email protected]/4505795835658240",
tracesSampleRate: 0.4,
integrations: [
new CaptureConsole({
levels: ['error']
})
],
});
}
const localVersionPath = path.join(__dirname, 'package.json');
const localVersion = require(localVersionPath);
async function checkLatestVersion() {
try {
const response = await axios.get('https://raw.githubusercontent.com/maxsrl/moeshare/main/package.json');
const remotePackageJson = response.data;
const latestVersion = remotePackageJson.version;
if (latestVersion !== localVersion.version) {
console.log(clc.bold.magenta(`\n--------------------------------------------------------------------------------`));
console.log(clc.magenta(`\n[UPDATE] | » Eine neue Version (${latestVersion}) von MoeShare ist verfügbar!`));
console.log(clc.magenta(` Die derzeitige Version lautet: ${localVersion.version}`));
console.log(clc.bold.magenta(` Prüfe auf neue Variable in der docker-compose.yml bzw. example.env!`));
console.log(clc.bold.magenta(`\n--------------------------------------------------------------------------------`));
} else {
console.log(clc.magenta('[UPDATE] | » MoeShare ist auf dem neusten Stand!'));
}
} catch (error) {
console.log(clc.red('[ERROR] | » Fehler beim Abrufen von package.json von GitHub:', error.message));
}
}
checkLatestVersion();
app.get('/', (req, res) => {
res.status(302).location(REDIRECT_URL).json({});
});
function parseColor(hexColor) {
return parseInt(hexColor, 16);
}
const db = new sqlite3.Database('./db/datenbank.sqlite', (sqliteError) => {
if (sqliteError) {
console.error(clc.red('[ERROR] | » Fehler bei der Verbindung zur SQLite-Datenbank:', sqliteError));
} else {
console.log(clc.green('[INFO] | » Die Verbindung zur SQLite-Datenbank wurde erfolgreich hergestellt.'));
const createTableQuery = `CREATE TABLE IF NOT EXISTS file_data (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
filename TEXT NOT NULL,
creation_date TEXT NOT NULL,
size_mb REAL NOT NULL,
size_bytes INTEGER NOT NULL,
dominant_color TEXT NOT NULL,
resolution_width INTEGER NOT NULL,
resolution_height INTEGER NOT NULL
)`;
db.run(createTableQuery, (error) => {
if (error) {
console.error(clc.red('[ERROR] | » Fehler beim Erstellen der Tabelle "file_data":', error.message));
} else {
console.log(clc.yellow('[INFO] | » Tabelle "file_data" erfolgreich erstellt oder bereits vorhanden.'));
}
});
}
});
let greeting;
if (currentHour >= 5 && currentHour < 12) {
greeting = "Guten Morgen";
} else if (currentHour >= 12 && currentHour < 18) {
greeting = "Guten Tag";
} else if (currentHour >= 18 && currentHour < 22) {
greeting = "Guten Abend";
} else {
greeting = "Gute Nacht";
}
function getFolderSizeAndFileCount(folderPath) {
let folderSizeBytes = 0;
let fileCount = 0;
const calculateSize = (itemPath) => {
const stats = fs.statSync(itemPath);
if (stats.isFile()) {
folderSizeBytes += stats.size;
fileCount++;
} else if (stats.isDirectory()) {
const items = fs.readdirSync(itemPath);
items.forEach((item) => {
calculateSize(path.join(itemPath, item));
});
}
};
calculateSize(folderPath);
return { folderSizeBytes, fileCount };
}
const folderPath = './uploads';
const { folderSizeBytes, fileCount } = getFolderSizeAndFileCount(folderPath);
const folderSizeKb = folderSizeBytes / 1024;
const folderSizeMb = folderSizeKb / 1024;
const formatMemory = (bytes) => {
const megabytes = bytes / (1024 * 1024);
return megabytes.toFixed(2);
};
const freeMemory = os.freemem();
const totalMemory = os.totalmem();
const formattedFreeMemory = formatMemory(freeMemory);
const formattedTotalMemory = formatMemory(totalMemory);
console.log(clc.whiteBright(`\n`))
console.log(clc.bold.whiteBright(`-----------------------------------------------------------------------------------------------------`))
console.log(clc.bold.whiteBright(`${greeting}, Nutzer.`))
console.log(clc.bold.whiteBright(`Vielen Dank, dass du MoeShare (${localVersion.version}) nutzt!\n`))
console.log(clc.bold.whiteBright(`Hier kannst du die aktuellen Einstellungen sehen:`))
console.log(clc.whiteBright(` - Diese Farbe wird anstelle der Dominanten Farbe genutzt: ${DOMINANT_COLOR_STATIC}`))
console.log(clc.whiteBright(` - Wird Angewand, wenn die Datei kein Bild ist: ${BOX_SHADOW_COLOR}`))
console.log(clc.whiteBright(` - Schriftfarbe: ${FONT_COLOR}\n`))
console.log(clc.whiteBright(` - Erlaubte Audio-Formate:${AUDIO_FORMATS}`))
console.log(clc.whiteBright(` - Erlaubte Video-Formate: ${VIDEO_FORMATS}`))
console.log(clc.whiteBright(` - Erlaubte Bilder-Formate: ${IMAGE_FORMATS}\n`))
console.log(clc.whiteBright(` - Soll die Dominante Farbe des Bildes genutzt werden? ${USE_DOMINANT_COLOR ? "✅" : "❌"}`))
console.log(clc.whiteBright(` - Sollen die Metadaten der Datei gelöscht werden? ${REMOVE_METADATA ? "✅" : "❌"}`))
console.log(clc.whiteBright(` - Soll ein Preview erstellt und genutzt werden? ${USE_PREVIEW ? "✅" : "❌"}`))
console.log(clc.whiteBright(` - Sollen Logs an die Discord-Webhook gesendet werden? ${process.env.LOGS ? "✅" : "❌"}`))
console.log(clc.whiteBright(` - Dürfen Fehler an Sentry für die Fehlerbehebung gesendet werden? ${process.env.ALLOW_METRICS ? "✅" : "❌"}\n`))
console.log(clc.whiteBright(` - Soll HLS für das Videostreaming verwendet werden? ${process.env.USE_HLS ? "✅" : "❌"}\n`))
console.log(clc.bold.whiteBright(`Systemeigenschaften:`))
console.log(clc.whiteBright(` - Hostname: ${os.hostname()}`))
console.log(clc.whiteBright(` - Kernel-Typ: ${os.type()}`))
console.log(clc.whiteBright(` - Kernel-Version: ${os.release()}\n`))
console.log(clc.whiteBright(` - CPU-Architektur: ${os.arch()}`))
console.log(clc.whiteBright(` - Anzahl der CPU-Kerne: ${os.cpus().length}\n`))
console.log(clc.whiteBright(` - Arbeitsspeicher: ${formattedFreeMemory} MB / ${formattedTotalMemory} MB\n`))
console.log(clc.bold.whiteBright(`Uploadereigenschaften:`))
console.log(clc.whiteBright(` - Domain: ${BASE_URL}`))
console.log(clc.whiteBright(` - Speicherplatz verwendet: ${folderSizeKb.toFixed(2)} KB (${folderSizeMb.toFixed(2)} MB)`))
console.log(clc.whiteBright(` - Insgesamte Dateien: ${fileCount}\n`))
console.log(clc.bold.whiteBright(`Wenn du Hilfe oder Probleme hast, melde sie unter https://github.com/maxsrl/moeshare/issues.`))
console.log(clc.bold.whiteBright(`-----------------------------------------------------------------------------------------------------\n\n`))
const createDirectoriesForAllUsers = async () => {
try {
const users = await getAllUsers();
users.forEach(users => {
const uploadPath = path.join(__dirname, 'uploads', users);
fs.mkdirSync(uploadPath, { recursive: true });
const userPreviewPath = path.join(uploadPath, 'preview');
fs.mkdirSync(userPreviewPath, { recursive: true });
const m3u8Path = path.join(uploadPath, 'm3u8');
fs.mkdirSync(m3u8Path, { recursive: true });
const prefix = 'conversionStarted-';
fs.readdir(m3u8Path, (err, files) => {
if (err) {
console.error(clc.red('[INFO > Cleanup] | » Fehler beim Löschen der Unbeendete Aufgabe:', err));
return;
}
for (const file of files) {
if (file.startsWith(prefix)) {
const baseName = file.slice(prefix.length);
const matchingFiles = files.filter((f) => f.startsWith(baseName));
matchingFiles.forEach((matchingFile) => {
const filePath = path.join(m3u8Path, matchingFile);
fs.unlink(filePath, (unlinkErr) => {
if (unlinkErr) {
console.error(clc.red('[INFO > Cleanup] | » Fehler beim Löschen der Unbeendete Aufgabe:', filePathStarted, unlinkErr));
} else {
console.log(clc.green('[INFO > Cleanup] | » Unbeendete Aufgabe wird gelöscht:', filePathStarted));
}
});
});
const filePathStarted = path.join(`${m3u8Path}/conversionStarted-${baseName}`);
fs.unlink(filePathStarted, (unlinkErr) => {
if (unlinkErr) {
console.error(clc.red('[INFO > Cleanup] | » Fehler beim Löschen der Unbeendete Aufgabe:', filePathStarted, unlinkErr));
} else {
console.log(clc.green('[INFO > Cleanup] | » Unbeendete Aufgabe wird gelöscht:', filePathStarted));
}
});
}
}
});
});
console.log(clc.yellow('[INFO] | » Alle Benutzerordner wurden erstellt oder bereits vorhanden.'));
const webhookData = {
embeds: [
{
title: 'System',
description: 'Alle Benutzerordner wurden erfolgreich erstellt.',
color: parseColor(DISCORD_WEBHOOK_SUCCESS_COLOR),
}
],
username: DISCORD_WEBHOOK_NAME,
};
if (process.env.LOGS !== 'false') {
try {
await axios.post(DISCORD_WEBHOOK_URL, webhookData);
} catch (error) {
console.error(clc.red('[DISCORD > ERROR] | » Nachricht konnte nicht gesendet werden:', error.message));
}
}
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler beim Erstellen der Benutzerordner:' + error.message));
const webhookData = {
embeds: [
{
title: 'System',
description: 'Fehler beim Erstellen der Benutzerordner\n' + error.message,
color: parseColor(DISCORD_WEBHOOK_ERROR_COLOR),
}
],
username: DISCORD_WEBHOOK_NAME,
};
if (process.env.LOGS !== 'false') {
try {
await axios.post(DISCORD_WEBHOOK_URL, webhookData);
} catch (error) {
console.error(clc.red('[DISCORD > ERROR] | » Nachricht konnte nicht gesendet werden:', error.message));
}
}
}
};
const getAllUsers = () => {
return new Promise((resolve, reject) => {
const query = 'SELECT username FROM users';
db.all(query, [], (error, rows) => {
if (error) {
reject(error);
} else {
const usernames = rows.map(row => row.username);
resolve(usernames);
}
});
});
};
createDirectoriesForAllUsers();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const username = req.user.username;
const uploadPath = path.join(__dirname, 'uploads', username);
fs.mkdirSync(uploadPath, { recursive: true });
const userPreviewPath = path.join(__dirname, 'uploads', username, 'preview');
fs.mkdirSync(userPreviewPath, { recursive: true });
cb(null, uploadPath);
},
filename: function (req, file, cb) {
const uniqueSuffix = uuidv4();
const fileExtension = path.extname(file.originalname);
const fileName = `${uniqueSuffix}${fileExtension}`;
cb(null, fileName);
},
});
const fileFilter = (req, file, cb) => {
cb(null, true);
};
const upload = multer({
storage: storage,
fileFilter: fileFilter,
}).single('file');
const getUserByUsername = (username) => {
return new Promise((resolve, reject) => {
const query = 'SELECT * FROM users WHERE username = ?';
const values = [username];
db.get(query, values, (error, row) => {
if (error) {
reject(error);
} else {
resolve(row);
}
});
});
};
const getUserByToken = (token) => {
return new Promise((resolve, reject) => {
const query = 'SELECT * FROM users WHERE token = ?';
const values = [token];
db.get(query, values, (error, row) => {
if (error) {
console.error(clc.red('[ERROR] | » Fehler beim Abrufen des Benutzers aus der Datenbank:', error.message));
reject(error);
} else {
resolve(row);
}
});
});
};
const authenticate = async (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Authentifizierungstoken fehlt!' });
}
try {
const decoded = jwt.verify(token, JWT_TOKEN);
req.user = decoded;
const user = await getUserByUsername(decoded.username);
if (!user || user.token !== token) {
return res.status(401).json({ error: 'Ungültiges Token!' });
}
next();
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler bei der Authentifizierung:', error.message));
res.status(401).json({ error: 'Ungültiges Token!' });
}
};
const isAdmin = async (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ error: 'Authentifizierung fehlgeschlagen' });
}
try {
const user = await getUserByToken(token);
if (!user) {
return res.status(401).json({ error: 'Ungültiges Token' });
}
if (user.role !== 'admin') {
return res.redirect('/login');
}
next();
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler bei der Authentifizierung:', error.message));
return res.status(500).json({ error: 'Serverfehler bei der Authentifizierung' });
}
};
const TokenUsername = async (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Authentifizierung fehlgeschlagen' });
}
try {
const user = await getUserByToken(token);
if (!user) {
return res.status(401).json({ error: 'Ungültiges Token' });
}
const username = user.username;
req.TokenUsername = username;
next();
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler bei der Authentifizierung:', error.message));
return res.status(500).json({ error: 'Serverfehler bei der Authentifizierung' });
}
};
const checkToken = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.redirect('/login');
}
db.get('SELECT * FROM users WHERE token = ?', [token], (err, row) => {
if (err || !row) {
return res.redirect('/login');
}
req.username = row.username;
next();
});
};
if (process.env.USE_DASHBOARD === 'true') {
const comparePasswords = (password, hash) => {
return bcrypt.compareSync(password, hash);
};
const checkAuthentication = (req, res, next) => {
const token = req.cookies.token;
if (token) {
return res.redirect("/dashboard");
}
next();
};
app.get("/login", checkAuthentication, (req, res) => {
res.render("login", {
SITE_FAVICON,
OG_DESCRIPTION,
OG_TITLE,
SITE_TITLE,
localVersion,
});
});
app.get("/logout", (req, res) => {
res.clearCookie("token");
res.redirect("/login");
});
app.post("/login", (req, res) => {
const token = req.bodyString('token'); // Sanitize the token as a string
// Set the sanitized token in the "token" cookie
res.cookie("token", token);
db.get("SELECT * FROM users WHERE token = ?", [token], (err, row) => {
if (err || !row) {
return res.status(401).json({ message: "Ungültiger Token" });
}
res.redirect("/dashboard");
});
});
app.get("/dashboard", checkToken, (req, res) => {
const username = req.username;
const directoryPath = `uploads/${username}/`;
const getUsersCountQuery = "SELECT COUNT(*) as userCount FROM users";
db.get(getUsersCountQuery, [], (err, row) => {
if (err) {
console.error(clc.red("[ERROR] | » Fehler bei der Abfrage der Nutzeranzahl:", err));
return res.status(500).json({ error: "Interner Serverfehler" });
}
const numberOfUsers = row.userCount;
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error(clc.red("\n[ERROR] | » Fehler beim Lesen des Verzeichnisses:", err));
return res.status(500).json({ error: "Interner Serverfehler" });
}
const fileNames = files.filter((file) =>
fs.statSync(`${directoryPath}/${file}`).isFile()
);
const numberOfFiles = fileNames.length;
let totalSpaceUsed = 0;
fileNames.forEach((file) => {
const stats = fs.statSync(`${directoryPath}/${file}`);
totalSpaceUsed += stats.size;
});
totalSpaceUsed = (totalSpaceUsed / (1024 * 1024)).toFixed(2);
res.render("dashboard", {
username,
files: fileNames,
greeting,
numberOfFiles,
totalSpaceUsed,
numberOfUsers,
BASE_URL,
SITE_FAVICON,
OG_DESCRIPTION,
OG_TITLE,
SITE_TITLE,
localVersion,
});
});
});
});
app.get("/api/data", checkToken, (req, res) => {
const username = req.username;
const directoryPath = `uploads/${username}/`;
const page = req.query.page || 1;
const itemsPerPage = 20;
const startIndex = (page - 1) * itemsPerPage;
const endIndex = page * itemsPerPage;
function listFileNames() {
const filesAndDirs = fs.readdirSync(directoryPath);
const fileNames = [];
for (const item of filesAndDirs) {
const itemPath = path.join(directoryPath, item);
if (fs.statSync(itemPath).isFile()) {
fileNames.push(item);
}
}
return fileNames.slice(startIndex, endIndex);
}
function countFilesWithoutFolders(directoryPath) {
const filesAndDirs = fs.readdirSync(directoryPath);
let fileCount = 0;
for (const item of filesAndDirs) {
const itemPath = path.join(directoryPath, item);
if (fs.statSync(itemPath).isFile()) {
fileCount++;
}
}
return fileCount;
}
const fileNames = listFileNames();
const totalItems = countFilesWithoutFolders(directoryPath);
const totalPages = Math.ceil(totalItems / itemsPerPage);
const hasNextPage = page < totalPages;
res.json({
totalItems: totalItems,
itemsPerPage: itemsPerPage,
currentPage: page,
totalPages: totalPages,
hasNextPage: hasNextPage,
data: fileNames,
});
});
app.get("/admin", checkToken, isAdmin, (req, res) => {
const username = req.username;
const searchUserTerm = req.query.searchUser;
const searchFileTerm = req.query.searchFile;
let queryUser = "SELECT * FROM users";
let queryFile = "SELECT * FROM file_data";
if (searchUserTerm) {
queryUser += ` WHERE username LIKE '%${searchUserTerm}%'`;
}
if (searchFileTerm) {
queryFile += ` WHERE filename LIKE '%${searchFileTerm}%'`;
}
function getFolderSizeAndFileCount(folderPath) {
let folderSizeBytes = 0;
let numberOfFiles = 0;
const calculateSize = (itemPath) => {
const stats = fs.statSync(itemPath);
if (stats.isFile()) {
folderSizeBytes += stats.size;
numberOfFiles++;
} else if (stats.isDirectory()) {
const items = fs.readdirSync(itemPath);
items.forEach((item) => {
calculateSize(path.join(itemPath, item));
});
}
};
calculateSize(folderPath);
return { folderSizeBytes, numberOfFiles };
}
const folderPath = "./uploads";
const { folderSizeBytes, numberOfFiles } =
getFolderSizeAndFileCount(folderPath);
const folderSizeKb = folderSizeBytes / 1024;
const folderSizeMb = folderSizeKb / 1024;
const uploadDirectory = path.join(__dirname, "uploads");
fs.readdir(uploadDirectory, (err, files) => {
if (err) {
return res.status(500).send(err);
}
const getUsersCountQuery = "SELECT COUNT(*) as userCount FROM users";
db.get(getUsersCountQuery, [], (err, row) => {
if (err) {
console.error(clc.red("\n[ERROR] | » Fehler bei der Abfrage der Nutzeranzahl:", err));
return res.status(500).json({ error: "Interner Serverfehler" });
}
const numberOfUsers = row.userCount;
db.all(queryUser, (err, userRows) => {
if (err) {
return res.status(500).send(err);
}
db.all(queryFile, (err, fileRows) => {
if (err) {
return res.status(500).send(err);
}
res.render("admin", {
username,
users: userRows,
file_data: fileRows,
greeting,
numberOfFiles,
folderSizeMb,
numberOfUsers,
SITE_FAVICON,
OG_DESCRIPTION,
OG_TITLE,
SITE_TITLE,
localVersion,
});
});
});
});
});
});
}
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const notFoundPage = `<!DOCTYPE HTML>
<html lang="de-DE">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>404 » ${SITE_TITLE} </title>
<meta property="og:title" content="${OG_TITLE}">
<meta property="og:description" content="${OG_DESCRIPTION}">
<meta name="og:locale" content="de_DE" />
<link rel="icon" href="${SITE_FAVICON}" type="image/png" />
<style>
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: #0e0e0e;
margin: 0;
font-family: Arial, sans-serif;
animation: bgAnimation 5s infinite alternate;
}
.button-container {
display: flex;
gap: 10px;
margin-top: 20px;
}
.button {
width: 220px;
height: 50px;
font-size: 15px;
font-family: Arial, sans-serif;
font-weight: bold;
border: none;
outline: none;
color: #fff;
background: #111;
cursor: pointer;
position: relative;
z-index: 0;
border-radius: 10px;
}
.button:before {
content: '';
background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000);
position: absolute;
top: -2px;
left:-2px;
background-size: 400%;
z-index: -1;
filter: blur(5px);
width: calc(100% + 4px);
height: calc(100% + 4px);
animation: glowing 20s linear infinite;
opacity: 0;
transition: opacity .3s ease-in-out;
border-radius: 10px;
}
.button:active {
color: #000
}
.button:active:after {
background: transparent;
}
.button:hover:before {
opacity: 1;
}
.button:after {
z-index: -1;
content: '';
position: absolute;
width: 100%;
height: 100%;
background: #111;
left: 0;
top: 0;
border-radius: 10px;
}
@keyframes glowing {
0% { background-position: 0 0; }
50% { background-position: 400% 0; }
100% { background-position: 0 0; }
}
.text {
font-size: 2rem;
font-family: Arial, sans-serif;
font-weight: bold;
color: transparent;
text-align: center;
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right, #3B82F6, #A855F7, #F43F5E);
}
.copyright {
position: absolute;
bottom: 10px;
font-size: 15px;
font-family: Arial, sans-serif;
font-weight: bold;
color: ${FONT_COLOR};
text-align: center;
}
.version {
position: absolute;
top: 10px;
left: 10px;
font-size: 15px;
font-family: Arial, sans-serif;
font-weight: bold;
color: ${FONT_COLOR};
}
a {
color: ${FONT_COLOR};
}
</style>
</head>
<body>
<h1 class="text">Diese Datei existiert nicht!</h1>
<br>
<div class="button-container">
<button class="button" type="button" onclick="javascript:history.back()">Zurück</button>
</div>
<div class="copyright">
${COPYRIGHT_TEXT}
</div>
<div class="version">
V. ${localVersion.version}</br>
</div>
</body>
</html>`;
app.post('/upload', authenticate, upload, TokenUsername, async (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'Keine Datei hochgeladen!' });
}
const filename = req.file.filename;
const userUploadsPath = path.join(__dirname, 'uploads', req.TokenUsername);
const filePath = path.join(userUploadsPath, filename);
const previewPath = path.join(userUploadsPath, 'preview', filename);
const m3u8Path = path.join(userUploadsPath, 'm3u8', filename.split('.')[0]);
const m3u8PathWithoutFilename = path.join(userUploadsPath, 'm3u8');
if (USE_PREVIEW && IMAGE_FORMATS.some(format => filename.endsWith(format))) {
await sharp(filePath)
.webp({ quality: 50 })
.toFile(previewPath);
}
if (REMOVE_METADATA) {
await removeMetadataFromImage(filePath);
} else {
console.log(clc.yellow('[INFO] | » Metadatenentfernung deaktiviert.'));
}
res.json({
success: true,
file: `${process.env.BASE_URL}/uploads/${req.TokenUsername}/${filename}`,
view: `${process.env.BASE_URL}/view/${filename}`,
preview: (USE_PREVIEW && IMAGE_FORMATS.some(format => filename.endsWith(format)))
? `${process.env.BASE_URL}/uploads/${req.TokenUsername}/preview/${filename}`
: `${process.env.BASE_URL}/uploads/${req.TokenUsername}/${filename}`,
delete: `${process.env.BASE_URL}/delete/${filename}`,
});
const COLOR_COUNT = 256;
const QUALITY = 3;
const extractDominantColor = (filePath) => {
return new Promise((resolve, reject) => {
const imageMimeType = getMimeType(filePath);
if (!isImageMimeType(imageMimeType)) {
resolve('#ffffff');
return;
}
Vibrant.from(filePath)
.maxColorCount(COLOR_COUNT)
.quality(QUALITY)
.getPalette()
.then(palette => {
const dominantColor = palette.Vibrant.hex;
resolve(dominantColor);
})
.catch(error => {
console.error(clc.red('[ERROR] | » Fehler beim Extrahieren der Farbe:', error.message));
reject(error);
});
});
};
function isImageMimeType(mimeType) {
return mimeType.startsWith('image/png', 'image/jpeg', 'image/gif', 'image/tiff', 'image/bmp', 'image/tiff');
}
const getMimeType = (filePath) => {
const mime = require('mime-types');
const mimeType = mime.lookup(filePath);
return mimeType;
};
let dominantColor;
if (USE_DOMINANT_COLOR === true) {
dominantColor = await extractDominantColor(filePath);
} else {
dominantColor = DOMINANT_COLOR_STATIC;
}
const fileStats = fs.statSync(filePath);
const creationDate = fileStats.birthtime.toLocaleString('de-DE', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: 'Europe/Berlin'
});
const isImage = IMAGE_FORMATS.some(format => filename.endsWith(format)) || filename.endsWith('.gif');
const isVideo = VIDEO_FORMATS.some(format => filename.endsWith(format));
let resolution;
if (isImage) {
try {
resolution = await getImageResolution(filePath);
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler beim Ermitteln der Bildauflösung:', error.message));
resolution = { width: 0, height: 0 };
}
} else if (isVideo) {
try {
resolution = await getVideoResolution(filePath);
} catch (error) {
console.error(clc.red('[ERROR] | » Fehler beim Ermitteln der Videoauflösung:', error.message));
resolution = { width: 0, height: 0 };
}
} else {
resolution = { width: 0, height: 0 };
}
if (isVideo && USE_HLS) {
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
fs.writeFileSync(`${m3u8PathWithoutFilename}/conversionStarted-${filename.split('.')[0]}`, '');
const ffmpegProcess = ffmpeg(filePath, { timeout: 432000 })
.addOptions([
'-profile:v baseline',
'-level 3.0',
'-start_number 0',
'-hls_time 10',
'-hls_list_size 0',
'-f hls',
])
.output(m3u8Path + '.m3u8')
.on('end', () => {
console.log(clc.green('[INFO] | » Video wurde erfolgreich umgewandelt.'));
fs.unlink(`${m3u8PathWithoutFilename}/conversionStarted-${filename.split('.')[0]}`, (err) => {
if (err) {
console.error(clc.red('[ERROR] | » Fehler beim Löschen der conversionStarted-Datei:', err));
} else {}
});
fs.writeFileSync(`${m3u8PathWithoutFilename}/conversionComplete-${filename.split('.')[0]}`, '');
})
.on('error', (err, stdout, stderr) => {
console.error(clc.red('[ERROR] | » FFmpeg Fehler:', err));
console.error(clc.red('[ERROR] | » FFmpeg STDERR:', stderr));
});
ffmpegProcess.run();
}
function getVideoResolution(filePath) {
return new Promise((resolve, reject) => {
ffprobe(filePath, { path: ffprobeStatic.path }, (error, info) => {
if (error) {
reject(error);
} else {
const videoStream = info.streams.find(stream => stream.codec_type === 'video');
if (!videoStream) {
reject(new Error(clc.red('[ERROR] | » Kein Video-Stream gefunden!')));
} else {
const { width, height } = videoStream;
resolve({ width, height });
}
}
});
});
}
async function getImageResolution(filePath) {
const metadata = await sharp(filePath).metadata();
return { width: metadata.width, height: metadata.height };
}
const sizeInBytes = fileStats.size;
const sizeInMB = parseFloat((sizeInBytes / (1024 * 1024)).toFixed(3));
const saveFileDataToDatabase = async (username, filename, creationDate, sizeInMB, sizeInBytes, dominantColor, resolution) => {
const query = 'INSERT INTO file_data (username, filename, creation_date, size_mb, size_bytes, dominant_color, resolution_width, resolution_height) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
const values = [username, filename, creationDate, sizeInMB, sizeInBytes, dominantColor, resolution.width, resolution.height];
db.run(query, values, async (error) => {