2022-06-25 15:44:17 +00:00
|
|
|
import { EVENT_WS_MESSAGE } from "@goauthentik/web/constants";
|
|
|
|
import { MessageLevel } from "@goauthentik/web/elements/messages/Message";
|
|
|
|
import { showMessage } from "@goauthentik/web/elements/messages/MessageContainer";
|
2021-09-21 09:31:37 +00:00
|
|
|
|
2022-06-25 15:44:17 +00:00
|
|
|
import { t } from "@lingui/macro";
|
2021-07-22 11:47:27 +00:00
|
|
|
|
|
|
|
export interface WSMessage {
|
2021-07-22 12:15:54 +00:00
|
|
|
message_type: string;
|
2021-07-22 11:47:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export class WebsocketClient {
|
|
|
|
messageSocket?: WebSocket;
|
|
|
|
retryDelay = 200;
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
try {
|
|
|
|
this.connect();
|
|
|
|
} catch (error) {
|
|
|
|
console.warn(`authentik/ws: failed to connect to ws ${error}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(): void {
|
|
|
|
if (navigator.webdriver) return;
|
2021-08-03 15:52:21 +00:00
|
|
|
const wsUrl = `${window.location.protocol.replace("http", "ws")}//${
|
|
|
|
window.location.host
|
|
|
|
}/ws/client/`;
|
2021-07-22 11:47:27 +00:00
|
|
|
this.messageSocket = new WebSocket(wsUrl);
|
|
|
|
this.messageSocket.addEventListener("open", () => {
|
|
|
|
console.debug(`authentik/ws: connected to ${wsUrl}`);
|
|
|
|
this.retryDelay = 200;
|
|
|
|
});
|
|
|
|
this.messageSocket.addEventListener("close", (e) => {
|
|
|
|
console.debug(`authentik/ws: closed ws connection: ${e}`);
|
2022-06-25 22:46:40 +00:00
|
|
|
if (this.retryDelay > 6000) {
|
2021-11-16 10:21:30 +00:00
|
|
|
showMessage(
|
|
|
|
{
|
|
|
|
level: MessageLevel.error,
|
|
|
|
message: t`Connection error, reconnecting...`,
|
|
|
|
},
|
|
|
|
true,
|
|
|
|
);
|
2021-07-22 11:47:27 +00:00
|
|
|
}
|
|
|
|
setTimeout(() => {
|
|
|
|
console.debug(`authentik/ws: reconnecting ws in ${this.retryDelay}ms`);
|
|
|
|
this.connect();
|
|
|
|
}, this.retryDelay);
|
|
|
|
this.retryDelay = this.retryDelay * 2;
|
|
|
|
});
|
|
|
|
this.messageSocket.addEventListener("message", (e) => {
|
|
|
|
const data = JSON.parse(e.data);
|
|
|
|
window.dispatchEvent(
|
|
|
|
new CustomEvent(EVENT_WS_MESSAGE, {
|
|
|
|
bubbles: true,
|
|
|
|
composed: true,
|
|
|
|
detail: data as WSMessage,
|
2021-08-03 15:52:21 +00:00
|
|
|
}),
|
2021-07-22 11:47:27 +00:00
|
|
|
);
|
|
|
|
});
|
|
|
|
this.messageSocket.addEventListener("error", () => {
|
|
|
|
this.retryDelay = this.retryDelay * 2;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|