trilium/src/public/javascripts/services/messaging.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

import utils from './utils.js';
2018-03-26 09:29:35 +08:00
import infoService from "./info.js";
const $outstandingSyncsCount = $("#outstanding-syncs-count");
const syncMessageHandlers = [];
const messageHandlers = [];
let ws;
let lastSyncId;
let lastPingTs;
function logError(message) {
console.log(utils.now(), message); // needs to be separate from .trace()
console.trace();
if (ws && ws.readyState === 1) {
ws.send(JSON.stringify({
type: 'log-error',
error: message
}));
}
}
2017-12-18 02:46:18 +08:00
function subscribeToMessages(messageHandler) {
messageHandlers.push(messageHandler);
}
function subscribeToSyncMessages(messageHandler) {
syncMessageHandlers.push(messageHandler);
}
function handleMessage(event) {
const message = JSON.parse(event.data);
for (const messageHandler of messageHandlers) {
messageHandler(message);
}
if (message.type === 'sync') {
2019-02-10 23:36:25 +08:00
lastPingTs = Date.now();
if (message.data.length > 0) {
2018-10-21 16:26:14 +08:00
console.debug(utils.now(), "Sync data: ", message.data);
lastSyncId = message.data[message.data.length - 1].id;
}
const syncData = message.data.filter(sync => sync.sourceId !== glob.sourceId);
for (const syncMessageHandler of syncMessageHandlers) {
syncMessageHandler(syncData);
}
$outstandingSyncsCount.html(message.outstandingSyncs);
}
else if (message.type === 'sync-hash-check-failed') {
2018-03-26 09:29:35 +08:00
infoService.showError("Sync check failed!", 60000);
}
else if (message.type === 'consistency-checks-failed') {
2018-03-26 09:29:35 +08:00
infoService.showError("Consistency checks failed! See logs for details.", 50 * 60000);
}
}
function connectWebSocket() {
const protocol = document.location.protocol === 'https:' ? 'wss' : 'ws';
// use wss for secure messaging
const ws = new WebSocket(protocol + "://" + location.host);
2019-07-06 18:03:51 +08:00
ws.onopen = () => console.debug(utils.now(), "Connected to server with WebSocket");
ws.onmessage = handleMessage;
2019-07-06 18:03:51 +08:00
// we're not handling ws.onclose here because reconnection is done in sendPing()
return ws;
}
setTimeout(() => {
ws = connectWebSocket();
lastSyncId = glob.maxSyncIdAtLoad;
2019-02-10 23:36:25 +08:00
lastPingTs = Date.now();
setInterval(async () => {
2019-02-10 23:36:25 +08:00
if (Date.now() - lastPingTs > 30000) {
console.log("Lost connection to server");
}
2019-07-06 18:03:51 +08:00
if (ws.readyState === ws.OPEN) {
2019-06-27 02:49:17 +08:00
ws.send(JSON.stringify({
type: 'ping',
lastSyncId: lastSyncId
}));
}
2019-07-06 18:03:51 +08:00
else if (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING) {
console.log("WS closed or closing, trying to reconnect");
ws = connectWebSocket();
}
}, 1000);
2018-04-06 11:17:19 +08:00
}, 0);
2017-12-02 11:28:22 +08:00
export default {
logError,
subscribeToMessages,
subscribeToSyncMessages
};