This repository has been archived by the owner on Aug 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (81 loc) · 2.59 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
require('dotenv').config();
global.app_version = require("./package.json").version;
const fs = require('fs');
if (!fs.existsSync(__dirname + '/config.js')) {
console.error('Config file not found!');
process.exit(1);
}
const config = require('./config');
//Validate config
if (
!config.http_port
|| typeof config.http_port != 'number'
|| config.http_port % 1 != 0
|| !config.data_dir
|| config.data_dir.length == 0
|| !config.id_generator
|| !['random', 'phoenic'].includes(config.id_generator)
|| !config.id_bytes
|| typeof config.id_bytes != 'number'
|| config.id_bytes < 1
|| config.id_bytes % 1 != 0
|| !config.delete_after
|| typeof config.delete_after != 'number'
|| config.delete_after < 0
|| config.delete_after % 1 != 0
) {
console.error('Invalid config file! (Missing or invalid variables)');
process.exit(1);
}
const { log, logLevel } = require('./app/logger');
const utils = require('./app/utils');
const cleaner = require('./app/cleaner');
log(logLevel.INFO, `TextStash starting up...`);
/**
* Initialize data directory
*/
log(logLevel.INFO, `Initializing data directory...`);
utils.initializeDataDir(logLevel.INFO);
/**
* Initialize cleanup
*/
if (config.delete_after > 0) {
cleaner.deleteExpiredFiles(config.delete_after);
setInterval(() => cleaner.deleteExpiredFiles(config.delete_after), 60000);
}
/**
* Initialize Web server
*/
log(logLevel.INFO, `Initializing Web server (Express)`);
const express = require('express');
const webServer = express();
webServer.use(require('body-parser').urlencoded({ extended: true, limit: '150kb' }));
webServer.set('view engine', 'ejs');
webServer.use('/static', express.static('static'));
webServer.use(function(req, res, next) {
log(logLevel.DEBUG, `[HTTP] Request form ${req.ip} at ${req.path}`);
next();
});
webServer.use('/', require('./routes/main'));
webServer.use('/api', require('./routes/api'));
/* Catch all API URLs and show 404 */
webServer.all('/api/*', (req, res) => {
res.json({code: 404, error: 'API not found or invalid method.'});
});
/* Catch all URLs and redirect to homepage */
webServer.all('*', (req, res) => {
res.redirect('/');
});
/* Handle server errors in production mode (hide error details) */
if (process.env.NODE_ENV != 'development') {
webServer.use((err, req, res, next) => {
if (err) {
res.sendStatus(500);
return;
}
next();
});
}
webServer.listen(config.http_port, () => {
log(logLevel.INFO, `TextStash Web server listening on port ${config.http_port}`);
});