Skip to content

Commit

Permalink
Add some much needed resiliency
Browse files Browse the repository at this point in the history
  • Loading branch information
iiPythonx committed Feb 19, 2024
1 parent 103b678 commit 059ee85
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 19 deletions.
18 changes: 9 additions & 9 deletions nightwatch/desktop/src/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,23 @@ $("#connect-form").on("submit", (e) => {

// Establish connection
const nw = new NightwatchServer($("#connect-address").val());
nw.connected(() => {
const ws_error = (m) => { nw.close(); notifier.alert(m); delete nw; delete window.nightwatch; } // Cleanest way I could come up with

// Handle callbacks
nw.on_error = () => ws_error("Connection to server failed.");
nw.connected = () => {
nw.identify($("#connect-username").val(), window._usercolor || "#fefefe", (d) => {
if (d.type == "error") {
nw.close();
delete nw;
return notifier.alert(d.data.text);
}
if (d.type == "error") ws_error(d.data.text);
$("#server-name").text(d.data.name);
ui.switch("messages");
});
});
};

// Handle messages
nw.on_message((message) => {
nw.on_message = (message) => {
message = message.data;
if ((message.user && message.user.name !== nw.user?.name) || !message.user) process_message(message);
});
};

// Expose our API
window.nightwatch = nw;
Expand Down
13 changes: 3 additions & 10 deletions nightwatch/desktop/src/js/nightwatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,13 @@ class NightwatchServer {
delete this._callbacks[data.callback];
return callback(data);
}
if (data.type == "message" && this._onmessage) this._onmessage(data);
if (data.type == "message" && this.on_message) this.on_message(data);
});
this.socket.addEventListener("open", () => { if (this._connected) this._connected(); });
this.socket.addEventListener("error", () => { if (this.on_error) this.on_error(); });
this.socket.addEventListener("open", () => { if (this.connected) this.connected(); });
this._interval = setInterval(() => { this.send_payload("ping"); }, 10000);
}

connected(callback) {
this._connected = callback;
}

on_message(callback) {
this._onmessage = callback;
}

send_payload(type, data, callback) {
if (!this.socket) throw new Error("Current Nightwatch websocket is not connected!");
let payload = { data: data };
Expand Down

0 comments on commit 059ee85

Please sign in to comment.