mime-chat/src/background/session.ts
2021-02-08 23:13:43 -06:00

109 lines
2.5 KiB
TypeScript

import WebSocket from 'ws';
import { windowEmitter } from './windowEmitter';
type Message = {
type: string;
id: string;
}
interface RenderMessage extends Message {
content: string;
context: string;
subContext: string;
modifiers: string;
time: string;
}
interface AuthMessage extends Message {
email: string;
firstName: string;
lastName: string;
access_token: string;
}
interface AuthRequest {
token: string;
}
interface PostLogin {
email: string;
password: string;
}
interface PostMessage {
content: string;
}
const ip = 'ws://localhost';
const port = 8080;
const username = '[email protected]';
let socket: WebSocket;
const receiveMessage = (message: string): void => {
// NOTE assuming message is JSON string
const parsed: RenderMessage | AuthMessage = JSON.parse(message);
if (parsed.type === "render") {
windowEmitter.emit('ipc-renderer', {
endpoint: 'render-message',
message: parsed
});
} else if (parsed.type === "auth") {
windowEmitter.emit('auth-resp', parsed);
}
}
export function initSession() {
let success = false;
socket = new WebSocket(`${ip}:${port}`);
socket.binaryType = 'arraybuffer';
socket.on('open', () => {
console.log('Connected to crimata-platform');
socket.send(username);
success = true;
})
socket.on("message", receiveMessage);
setTimeout(()=> {
if (!success) {
throw new Error('Unable to connect to crimata-platform')
}
}, 3000)
}
export const authUser = (event: any, arg: AuthRequest) => {
console.log('sending token to socket', arg)
try {
sendMessage({
content: arg.token
});
windowEmitter.on('auth-resp', (payload: AuthMessage) => {
event.reply('auth-user-reply', payload);
})
} catch(e){
console.log('Error authenticating user! ' + e);
event.reply('auth-user-reply', e);
}
}
export const authLogin = (event: any, arg: PostLogin) => {
try {
sendMessage(arg)
windowEmitter.on('auth-resp', (payload: AuthMessage) => {
event.reply('auth-login-reply', payload);
})
} catch(e) {
console.log('Error loging in' + e);
event.reply('auth-login-reply', e);
}
}
export const sendMessage = (content: PostMessage | Buffer | PostLogin) => {
if (content instanceof Buffer) {
socket.send(content);
} else {
socket.send(JSON.stringify(content));
}
}