107 lines
2.5 KiB
TypeScript
107 lines
2.5 KiB
TypeScript
/*
|
|
* Creates a websocket session with Crimata Servers.
|
|
*
|
|
* Connects to Servers and attempts key authentication. Server will respond
|
|
* with key and user profile. We send the profile to the browser. We also
|
|
* resend this information on new broser window. We then serve as a
|
|
* communication interface between the window and the servers. It will
|
|
* automatically try to reconnect on websocket disconnect.
|
|
*/
|
|
|
|
import { backgroundMitt } from "@/modules/emitter";
|
|
import { ipcEmit, loadState } from './helpers';
|
|
|
|
import useWebSockets from "./websockets";
|
|
|
|
import { play } from "./audio";
|
|
import { renderMessage } from "@/modules/message";
|
|
import { SessionState } from "@/types";
|
|
|
|
let win = true;
|
|
|
|
// Info saved to json on quit (key, newMessages).
|
|
let state: SessionState;
|
|
|
|
|
|
// Calls appropriate endpoint for a server message.
|
|
const onMessage = (data: string): void => {
|
|
let message = JSON.parse(data);
|
|
console.log('received new message', message);
|
|
|
|
// Standard message.
|
|
if (message.content) {
|
|
|
|
// Convert to render message
|
|
message = renderMessage(
|
|
message.content.text,
|
|
message.content.audio,
|
|
message.context,
|
|
message.modifier
|
|
);
|
|
|
|
if (win) {
|
|
console.log("SESS:Emitting standard message.")
|
|
if (message.audio) {
|
|
play(message.audio)
|
|
}
|
|
ipcEmit("render-message", message)
|
|
}
|
|
|
|
else {
|
|
console.log("SESS:No window: saving message.")
|
|
state.newMessages.push(message);
|
|
}
|
|
}
|
|
|
|
else {
|
|
if (win) {
|
|
ipcEmit("render-message", message)
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
|
|
// Websockets module.
|
|
const { createSocket, send } = useWebSockets(onMessage);
|
|
|
|
|
|
export const emitNewMessages = (): void => {
|
|
if (state) {
|
|
ipcEmit("update-state", {
|
|
newMessages: state.newMessages,
|
|
});
|
|
}
|
|
|
|
}
|
|
|
|
|
|
export const sendMessage = (payload: Record<string, any>): void => {
|
|
try {
|
|
send(payload)
|
|
} catch(e) {
|
|
console.log("Unable to send message: ", payload);
|
|
}
|
|
|
|
}
|
|
|
|
|
|
// Call this to initialize session with Crimata servers.
|
|
export const initSession = (authPayload: {
|
|
token: string;
|
|
crimataId: string;
|
|
}): void => {
|
|
console.log("SESS:Creating new session.")
|
|
|
|
// Load Json or createState.
|
|
state = loadState("session.json");
|
|
|
|
// Open socket connection.
|
|
createSocket(authPayload);
|
|
|
|
// Keep win up-to-date.
|
|
backgroundMitt.on('window-active', (state: boolean) => {
|
|
win = state;
|
|
});
|
|
|
|
}
|