You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9 KiB

// Firefox does randomized exponential backoff for failed websocket requests
// This means we can't have [1. long downtime] and [2. fast reconnect] at the sime time
//
// We abuse the fact that HTTP requests are NOT backoffed, and use those to monitor
// the server. When we see that the server is up - we attempt an actual websocket connection
//
// Details best described here: https://github.com/kee-org/KeeFox/issues/189
function ws_connect(first_connect = false) {
2 years ago
const session_id = ls.getItem('sessionId') || '0';
const desk_id = storage.desk_id;
ws = new WebSocket(`${config.ws_url}?deskId=${desk_id}&sessionId=${session_id}`);
ws.addEventListener('open', on_open);
ws.addEventListener('message', on_message);
ws.addEventListener('error', on_error);
ws.addEventListener('close', on_close);
}
function on_open() {
clearTimeout(storage.timers.ws_reconnect);
if (config.debug_print) console.debug('open')
2 years ago
}
async function on_message(event) {
const data = event.data;
let message_data = null;
2 years ago
if ('arrayBuffer' in data) {
message_data = await data.arrayBuffer();
const view = new DataView(message_data);
const d = deserializer_create(message_data, view);
await handle_message(d);
} else {
/* For all my Safari < 14 bros out there */
const reader = new FileReader();
reader.onload = async (e) => {
message_data = e.target.result;
const view = new DataView(message_data);
const d = deserializer_create(message_data, view);
await handle_message(d);
};
reader.readAsArrayBuffer(data);
}
2 years ago
}
function on_close() {
ws = null;
if (config.debug_print) console.debug('close');
2 years ago
storage.timers.ws_reconnect = setTimeout(ws_connect, config.ws_reconnect_timeout);
}
function on_error() {
ws.close();
}