forked from scotow/sendrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
81 lines (69 loc) · 2.33 KB
/
app.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
#!/usr/bin/env node
// Imports.
// Config.
const config = require('./lib/config.js');
// Basic modules.
const path = require('path');
const fs = require('fs');
// Utils.
const moment = require('moment');
// Database.
const database = require('./lib/database.js');
// Web server.
const express = require('express');
const cookieParser = require('cookie-parser');
const download = require('./routes/download.js');
const upload = require('./routes/upload.js');
const revoke = require('./routes/revoke.js');
const info = require('./routes/info.js');
const utils = require('./lib/utils.js');
const error = require('./lib/error.js');
const app = express();
app.set('trust proxy', true);
app.set('x-powered-by', false);
app.set('json spaces', '\t');
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use('/', download);
app.use('/', upload);
app.use('/', revoke);
app.use('/', info);
app.all('*', (req, res) => {
utils.displayError(req, res, error.fromCode(404), 404);
});
start();
async function start() {
try {
await database.ping();
console.log(`Connected to mySQL server.`);
await initUploadsFolder();
app.listen(config.site.port, () => {
console.log(`Server started on port ${config.site.port}.`);
});
} catch(error) {
console.error(`Error starting Sendrop: ${error.stack}`);
}
}
async function initUploadsFolder() {
if(fs.existsSync(config.storage.path)) {
const fileRegex = /^\d+$/;
let files = fs.readdirSync(config.storage.path).filter(file => fileRegex.test(file));
if(files.length) {
files = await database.getExpiration(files);
const now = moment().unix();
files.forEach(file => {
if(file.expiration < now) {
utils.deleteFile(file).catch(error => console.error('Error while deleting expired file on start-up.', error));
} else {
setTimeout(() => {
utils.deleteFile(file).catch(error => console.error('Error while deleting expired file.', error));
}, (file.expiration - now) * 1e3);
}
});
}
} else {
fs.mkdirSync(config.storage.path);
}
}