mime-chat/src/background/session.ts
2021-03-23 10:24:06 -05:00

54 lines
No EOL
1.2 KiB
TypeScript

import { backgroundMitt } from './emitter';
import { ipcMain, IpcMainEvent } from "electron";
import useWebSockets from "@/modules/ws";
import { handleAuthMessage, handleStandardMessage, handleProfileMessage, handleAnnotation } from "./handlers";
// Calls appropriate endpoint for a server message.
const onServerMessage = (data: string): void => {
const message = JSON.parse(data)
if (message.key) {
backgroundMitt.emit('auth-response', message);
}
else if (message.content) {
handleStandardMessage(message)
}
else if (message.first) {
handleProfileMessage(message)
}
else {
handleAnnotation(message)
}
};
const { createSocket, sendMessage } = useWebSockets(onServerMessage);
// Handle messages from client.
const onClientMessage = (_event: IpcMainEvent, payload: any) {
sendMessage(JSON.stringify(payload))
}
// Routes messages to and from Crimata Servers.
export default function agentInterface() {
const initSession = () => {
ipcMain.removeAllListeners()
ipcMain.on("client-message", onClientMessage);
createSocket()
}
return {
initSession
}
}