This repository has been archived by the owner on Feb 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 93
/
app.js
146 lines (124 loc) · 3.72 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
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
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser'); // 获取 req.body
const history = require('connect-history-api-fallback');
const http = require('http');
const jwtAuth = require('socketio-jwt-auth'); // 用于 JWT 验证的 socket.io 中间件
const child_process = require('child_process'); // 子进程
const { getConfig } = require('./config');
const config = getConfig();
const api = require('./api');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// connect-history-api-fallback 中间件后所有的 GET 请求都会变成 index (default: './index.html').
app.use(history({
// 将所有带 api 的 GET 请求都代理到 parsedUrl.path, 其实就是原来的路径
rewrites: [
{
from: /^\/api\/.*$/,
to: context => context.parsedUrl.path
}
]
}));
// Expose API routes
api(app);
// Serve WebApp routes
app.use(express.static(path.join(__dirname, './dist')));
const server = http.createServer(app);
// websocket 握手依赖 http 服务
const io = require('socket.io')(server);
if (config.auth) {
io.use(jwtAuth.authenticate({
secret: config.jwtsecret
}, (payload, done) => {
const user = {
name: payload.name,
group: payload.group
};
if (user.name === 'admin') {
done(null, user);
} else {
done(null, false, '只有 admin 账号能登录管理后台.');
}
}));
}
let scanner = null;
// 有新的客户端连接时触发
io.on('connection', function (socket) {
// console.log('connection');
socket.emit('success', {
message: '成功登录管理后台.',
user: socket.request.user
});
// socket.on('disconnect', () => {
// console.log('disconnect');
// });
socket.on('ON_SCANNER_PAGE', () => {
if (scanner) {
// 防止用户在扫描过程中刷新页面
scanner.send({
emit: 'SCAN_INIT_STATE'
});
}
});
socket.on('PERFORM_SCAN', () => {
if (!scanner) {
scanner = child_process.fork(path.join(__dirname, './filesystem/scanner.js'), { silent: false }); // 子进程
scanner.on('exit', (code) => {
scanner = null;
if (code) {
io.emit('SCAN_ERROR');
}
});
scanner.on('message', (m) => {
if (m.event) {
io.emit(m.event, m.payload);
}
});
}
});
socket.on('KILL_SCAN_PROCESS', () => {
scanner.send({
exit: 1
});
});
// 发生错误时触发
socket.on('error', (err) => {
console.error(err);
});
});
// 返回错误响应
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
// 验证错误
res.status(401).send({ error: err.message });
} else if (err.code === 'SQLITE_ERROR') {
if (err.message.indexOf('no such table') !== -1) {
res.status(500).send({ error: '数据库结构尚未建立,请先执行扫描.'});
}
} else {
res.status(500).send({ error: err.message || err });
}
});
// 获取本机IP地址
const getIPAddress = () => {
const interfaces = require('os').networkInterfaces();
for(let devName in interfaces){
const iface = interfaces[devName];
for (let i=0; i<iface.length; i++) {
const alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
return alias.address;
}
}
}
};
const LOCAL_IP = getIPAddress();
// Start server
server.listen(process.env.PORT || 8888, () => {
console.log(`使用浏览器在本机访问 http://localhost:${process.env.PORT || 8888}`);
console.log(`或在局域网访问 http://${LOCAL_IP}:${process.env.PORT || 8888}`);
});