forked from kikoeru-project/kikoeru-express
-
Notifications
You must be signed in to change notification settings - Fork 1
/
socket.js
99 lines (86 loc) · 2.42 KB
/
socket.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
const path = require('path');
const socket = require('socket.io');
const jwtAuth = require('socketio-jwt-auth'); // 用于 JWT 验证的 socket.io 中间件
const child_process = require('child_process'); // 子进程
const { config } = require('./config');
const initSocket = (server) => {
const io = socket(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,
auth: config.auth
});
// 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('PERFORM_UPDATE', () => {
if (!scanner) {
scanner = child_process.fork(path.join(__dirname, './filesystem/updater.js'), ['--refreshAll'], { 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);
});
});
}
module.exports = initSocket;