trilium/services/messaging.js

53 lines
1.4 KiB
JavaScript
Raw Normal View History

const WebSocket = require('ws');
const utils = require('./utils');
const log = require('./log');
let webSocketServer;
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) => {
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-29 07:33:23 +08:00
async function sendMessage(message) {
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
};