-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress-manager.js
107 lines (83 loc) · 2.93 KB
/
express-manager.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
const express = require('express');
const path = require("path");
const bodyParser = require('body-parser');
const publicDir = path.join(__dirname + "/public");
const ipc = require('electron').ipcMain;
class ExpressManager {
app;
server;
running = false;
password = null;
connections = [];
fileList = [];
constructor() {
}
open(port, password, fileList) {
if (this.running === false) {
this.fileList = fileList;
this.app = express();
this.app.use(express.json());
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
if (password != null) {
this.password = password.trim();
this.app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "/publicHidden/login.html"));
});
this.app.post("/", (req, res) => {
if (req.body.password === this.password) {
this.showFileList(res);
} else {
res.redirect("/?error=true");
}
});
} else {
this.app.get("/", (req, res) => {
this.showFileList(res);
});
this.password = null;
}
this.app.get("/dlf*", (req, res) => {
let fileId = (req.url.match(/\d+$/) || []).pop();
this.fileList.forEach(function (file) {
if (file.id == fileId) {
res.download(file.path);
}
});
})
this.server = this.app.listen(port);
this.server.on('connection', connection => {
this.connections.push(connection);
connection.on('close', () => this.connections = this.connections.filter(curr => curr !== connection));
});
this.running = true;
this.app.use(express.static(publicDir));
}
}
close() {
if (this.running === true) {
this.connections.forEach(curr => curr.end());
this.server.close();
this.running = false;
}
}
showFileList(response) {
let tempSendFileList = [];
this.fileList.forEach(file => {
tempSendFileList.push({id: file.id, name: file.name, size: bytesToSize(file.size)});
});
response.render(path.join(__dirname, "/publicHidden/fileDisplay.ejs"), {
files: tempSendFileList
});
}
}
function bytesToSize(bytes) {
let sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function createInstance() {
return new ExpressManager();
}
module.exports = createInstance;