2024-07-19 17:56:25 +02:00
|
|
|
// this file is responsible for managing UDN connections.
|
|
|
|
|
|
|
|
|
|
import UDNFrontend, { Message } from "udn-frontend";
|
|
|
|
|
|
|
|
|
|
import { ChatMessage } from "./chatTypes";
|
|
|
|
|
import { stringify } from "../utility";
|
|
|
|
|
|
|
|
|
|
export default class ConnectionModel {
|
|
|
|
|
// basic
|
|
|
|
|
udn: UDNFrontend;
|
|
|
|
|
|
|
|
|
|
// data
|
|
|
|
|
get isConnected(): boolean {
|
|
|
|
|
return this.udn.ws != undefined && this.udn.ws.readyState == 1;
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-19 18:02:23 +02:00
|
|
|
get address(): string | undefined {
|
2024-07-19 17:56:25 +02:00
|
|
|
return this.udn.ws?.url;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// connection
|
2024-07-19 18:02:23 +02:00
|
|
|
connect = (address: string): void => {
|
2024-07-19 17:56:25 +02:00
|
|
|
this.udn.connect(address);
|
2024-07-19 18:02:23 +02:00
|
|
|
};
|
2024-07-19 17:56:25 +02:00
|
|
|
|
2024-07-19 18:02:23 +02:00
|
|
|
disconnect = (): void => {
|
2024-07-19 17:56:25 +02:00
|
|
|
this.udn.disconnect();
|
2024-07-19 18:02:23 +02:00
|
|
|
};
|
2024-07-19 17:56:25 +02:00
|
|
|
|
2024-07-19 18:02:23 +02:00
|
|
|
handleConnectionChange = () => {
|
|
|
|
|
console.log("connection status:", this.isConnected, this.address);
|
|
|
|
|
};
|
2024-07-19 17:56:25 +02:00
|
|
|
|
|
|
|
|
// messaging
|
2024-07-19 18:02:23 +02:00
|
|
|
sendChatMessage = (chatMessage: ChatMessage): boolean => {
|
2024-07-19 17:56:25 +02:00
|
|
|
const stringifiedBody = stringify(chatMessage);
|
|
|
|
|
return this.udn.sendMessage(chatMessage.channel, stringifiedBody);
|
2024-07-19 18:02:23 +02:00
|
|
|
};
|
2024-07-19 17:56:25 +02:00
|
|
|
|
2024-07-19 18:02:23 +02:00
|
|
|
handleMessage = (data: Message) => {};
|
2024-07-19 17:56:25 +02:00
|
|
|
|
|
|
|
|
// setup
|
|
|
|
|
constructor() {
|
|
|
|
|
this.udn = new UDNFrontend();
|
|
|
|
|
this.udn.onmessage = this.handleMessage;
|
2024-07-19 18:02:23 +02:00
|
|
|
this.udn.onconnect = this.handleConnectionChange;
|
|
|
|
|
this.udn.ondisconnect = this.handleConnectionChange;
|
2024-07-19 17:56:25 +02:00
|
|
|
}
|
|
|
|
|
}
|