ProxmoxAAS-Dashboard/scripts/clientsync.js

53 lines
1.4 KiB
JavaScript
Raw Normal View History

2023-07-12 22:37:08 +00:00
import { requestAPI } from "./utils.js";
import { API } from "../vars.js";
2023-07-12 22:37:08 +00:00
2023-07-12 22:46:59 +00:00
export async function setupClientSync (callback) {
let scheme = localStorage.getItem("sync-scheme");
let rate = Number(localStorage.getItem("sync-rate"));
if (!scheme) {
scheme = "always";
localStorage.setItem("sync-scheme", "always");
}
if (!rate) {
rate = "5";
2023-07-28 18:32:04 +00:00
localStorage.setItem("sync-rate", "5");
2023-07-12 22:46:59 +00:00
}
2023-07-12 22:37:08 +00:00
if (scheme === "always") {
callback();
2023-07-12 22:46:59 +00:00
window.setInterval(callback, rate * 1000);
2023-07-12 22:37:08 +00:00
}
else if (scheme === "hash") {
const newHash = (await requestAPI("/sync/hash")).data;
localStorage.setItem("sync-current-hash", newHash);
callback();
window.setInterval(async () => {
const newHash = (await requestAPI("/sync/hash")).data;
if (localStorage.getItem("sync-current-hash") !== newHash) {
localStorage.setItem("sync-current-hash", newHash);
callback();
}
2023-07-12 22:46:59 +00:00
}, rate * 1000);
2023-07-12 22:37:08 +00:00
}
else if (scheme === "interrupt") {
callback();
const socket = new WebSocket(`wss://${API.replace("https://", "")}/sync/interrupt`);
socket.addEventListener("open", (event) => {
socket.send(`rate ${rate}`);
});
socket.addEventListener("message", (event) => {
2023-07-28 18:32:04 +00:00
const message = event.data.toString();
if (message === "sync") {
callback();
}
else {
2023-07-28 18:32:04 +00:00
console.error("clientsync: recieved unexpected message from server, closing socket.");
socket.close();
}
});
2023-07-12 22:37:08 +00:00
}
else {
2023-07-28 18:32:04 +00:00
console.error(`clientsync: unsupported scheme ${scheme} selected.`);
2023-07-12 22:37:08 +00:00
}
2023-07-28 18:32:04 +00:00
}