2017-11-26 06:43:05 +08:00
|
|
|
const WebSocket = require('ws');
|
2017-12-01 12:50:42 +08:00
|
|
|
const utils = require('./utils');
|
|
|
|
const log = require('./log');
|
2017-11-26 06:43:05 +08:00
|
|
|
|
|
|
|
let webSocketServer;
|
|
|
|
|
2017-12-01 12:50:42 +08:00
|
|
|
function init(httpServer, sessionParser) {
|
|
|
|
webSocketServer = new WebSocket.Server({
|
|
|
|
verifyClient: (info, done) => {
|
|
|
|
sessionParser(info.req, {}, () => {
|
|
|
|
const allowed = utils.isElectron() || info.req.session.loggedIn;
|
|
|
|
|
|
|
|
if (!allowed) {
|
|
|
|
log.error("WebSocket connection not allowed because session is neither electron nor logged in.");
|
|
|
|
}
|
|
|
|
|
|
|
|
done(allowed)
|
|
|
|
});
|
|
|
|
},
|
|
|
|
server: httpServer
|
|
|
|
});
|
|
|
|
|
2017-12-02 11:28:22 +08:00
|
|
|
webSocketServer.on('connection', (ws, req) => {
|
2017-11-26 06:43:05 +08:00
|
|
|
console.log("websocket client connected");
|
2017-12-02 11:28:22 +08:00
|
|
|
|
|
|
|
ws.on('message', messageJson => {
|
|
|
|
const message = JSON.parse(messageJson);
|
|
|
|
|
|
|
|
if (message.type === 'log-error') {
|
|
|
|
log.error('JS Error: ' + message.error);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
log.error('Unrecognized message: ');
|
|
|
|
log.error(message);
|
|
|
|
}
|
|
|
|
});
|
2017-11-26 06:43:05 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-11-29 07:33:23 +08:00
|
|
|
async function sendMessage(message) {
|
2017-11-26 06:43:05 +08:00
|
|
|
const jsonStr = JSON.stringify(message);
|
|
|
|
|
|
|
|
webSocketServer.clients.forEach(function each(client) {
|
|
|
|
if (client.readyState === WebSocket.OPEN) {
|
|
|
|
client.send(jsonStr);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
init,
|
2017-11-29 07:33:23 +08:00
|
|
|
sendMessage
|
2017-11-26 06:43:05 +08:00
|
|
|
};
|