refactor main and rendered ipc
This commit is contained in:
parent
17e4b06948
commit
ddb2f4df0f
28 changed files with 758 additions and 211 deletions
55
src/App.vue
55
src/App.vue
|
|
@ -35,12 +35,19 @@
|
|||
import { defineComponent, onMounted, onUnmounted, ref } from "vue";
|
||||
import { IpcRendererEvent } from "electron";
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
import { useProfile } from "@/modules/auth"
|
||||
import { invokeProfile } from "@/ipcRend/account";
|
||||
import { postInitSession, postMount } from "@/ipcRend/session";
|
||||
|
||||
import Splash from "@/components/splash.vue";
|
||||
import Messenger from "@/components/messenger.vue";
|
||||
import Login from "@/components/login.vue";
|
||||
|
||||
import { Profile } from "@/types";
|
||||
|
||||
|
||||
export default defineComponent({
|
||||
|
||||
components: {
|
||||
Splash,
|
||||
Messenger,
|
||||
|
|
@ -48,39 +55,38 @@ export default defineComponent({
|
|||
},
|
||||
|
||||
setup() {
|
||||
const { post } = useIpc();
|
||||
|
||||
const { post, invoke } = useIpc();
|
||||
|
||||
const { profile, setProfile, clearProfile } = useProfile();
|
||||
|
||||
// Whether browser has received user info yet.
|
||||
const ready = ref(false);
|
||||
|
||||
// Information about current user.
|
||||
const profile = ref(false);
|
||||
|
||||
// New messages that browser missed while closed.
|
||||
const newMessages = ref([])
|
||||
const newMessages = ref([]);
|
||||
|
||||
// Receive updated information about the session.
|
||||
const updateState = (_event: IpcRendererEvent, payload: any) => {
|
||||
console.log('YAYAYAYAYA');
|
||||
console.log("APP:Received updated profile and new messages: \n" +
|
||||
` profile: ${payload.message.profile}\n` +
|
||||
` new: ${payload.message.newMessages}`)
|
||||
` new: ${payload.message.newMessages}`);
|
||||
|
||||
if (payload.message.profile) {
|
||||
console.log(`APP:Logged-in, showing Messenger View.`)
|
||||
console.log(`APP:Logged-in, showing Messenger View.`);
|
||||
} else {
|
||||
console.log(`APP:Logged-out, showing Login View.`)
|
||||
console.log(`APP:Logged-out, showing Login View.`);
|
||||
}
|
||||
|
||||
// Set profile and newMessages.
|
||||
profile.value = payload.message.profile;
|
||||
newMessages.value = payload.message.newMessages;
|
||||
|
||||
ready.value = true;
|
||||
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
console.log("APP:mounted.")
|
||||
onMounted(async () => {
|
||||
console.log("APP:mounted.");
|
||||
window.ipcRenderer.on("update-state", updateState)
|
||||
window.ipcRenderer.on("update_available", () => {
|
||||
console.log('testing auto update');
|
||||
|
|
@ -89,18 +95,35 @@ export default defineComponent({
|
|||
window.ipcRenderer.on("update_downloaded", () => {
|
||||
console.log('testing update download');
|
||||
})
|
||||
post("app-mounted", "")
|
||||
|
||||
postMount();
|
||||
|
||||
try {
|
||||
|
||||
const profile = await invokeProfile() as Profile;
|
||||
setProfile(profile);
|
||||
} catch(e) {
|
||||
console.log('[AUTH]', e);
|
||||
clearProfile();
|
||||
} finally {
|
||||
ready.value = true;
|
||||
if (profile.value.crimataId) {
|
||||
// start session
|
||||
postInitSession(profile.value.crimataId);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.ipcRenderer.removeAllListeners("update-state")
|
||||
window.ipcRenderer.removeAllListeners("update-state");
|
||||
})
|
||||
|
||||
return {
|
||||
ready,
|
||||
profile,
|
||||
post,
|
||||
newMessages
|
||||
newMessages,
|
||||
profile
|
||||
}
|
||||
}
|
||||
})
|
||||
|
|
|
|||
36
src/api/account.ts
Normal file
36
src/api/account.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
|
||||
import { useHttp } from "@/modules/http";
|
||||
import axios from "axios";
|
||||
|
||||
const { post } = useHttp();
|
||||
|
||||
export const submit =
|
||||
async (email: string, password: string) => (
|
||||
|
||||
await post('/account/login', {
|
||||
email,
|
||||
password
|
||||
})
|
||||
|
||||
)
|
||||
|
||||
|
||||
export const logout =
|
||||
async (): Promise<null | Error> => (await post('/account/logout'));
|
||||
|
||||
|
||||
|
||||
export const fetchProfile = async(email: string, token: string) => (
|
||||
|
||||
await axios({
|
||||
url: "http://127.0.0.1:3000/api/account/profile",
|
||||
headers: {
|
||||
Cookie: `jwt=${token}`
|
||||
},
|
||||
method: 'GET',
|
||||
data: {
|
||||
email,
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
|
|
@ -7,6 +7,7 @@
|
|||
|
||||
import { initApp } from './background/init';
|
||||
import { protocol } from "electron";
|
||||
require('dotenv').config()
|
||||
|
||||
// Scheme must be registered before the app is ready
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
|
|
|
|||
|
|
@ -2,9 +2,7 @@
|
|||
|
||||
"use strict";
|
||||
|
||||
import { ipcMain } from "electron";
|
||||
import { backgroundMitt } from '@/modules/emitter';
|
||||
|
||||
const portAudio = require('naudiodon');
|
||||
|
||||
// Audio in and out stream objects.
|
||||
|
|
@ -26,27 +24,22 @@ const audioOptions = {
|
|||
closeOnError: false,
|
||||
}
|
||||
|
||||
// Toggles record to true to begin capturing chunks.
|
||||
const onRecordingStart = (_event: any, _payload: any) => {
|
||||
console.log("AUDIO: Beginning audio capture.")
|
||||
record = true;
|
||||
}
|
||||
export const toggleRecord = (): void => { record = !record };
|
||||
|
||||
// Returns recorded audio to frontend and sets record to false.
|
||||
const onRecordingEnd = async (_event: any, payload: any) => {
|
||||
console.log("AUDIO:Sending audio to browser.")
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
export const fetchAudioInput = (): Promise<Error | string> => (
|
||||
|
||||
new Promise((resolve, reject) => {
|
||||
|
||||
try {
|
||||
resolve(audioContainer.input);
|
||||
record = false;
|
||||
toggleRecord();
|
||||
} catch (e) {
|
||||
reject()
|
||||
reject(new Error('Failed to fetch the audio.'))
|
||||
}
|
||||
|
||||
});
|
||||
};
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
// Main audio function run by run.ts module.
|
||||
|
|
@ -86,15 +79,6 @@ export function initAudioIO(): void {
|
|||
ao.start();
|
||||
|
||||
}
|
||||
|
||||
// Listen to record.
|
||||
console.log("AUDIO:Adding recording listeners.")
|
||||
|
||||
ipcMain.removeAllListeners("start-recording");
|
||||
ipcMain.on("start-recording", onRecordingStart);
|
||||
|
||||
ipcMain.removeHandler("stop-recording");
|
||||
ipcMain.handle("stop-recording", onRecordingEnd);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -3,9 +3,10 @@
|
|||
|
||||
import { app, dialog } from "electron";
|
||||
import { createWindow } from './window';
|
||||
import { initSession } from './session';
|
||||
import { initAudioIO, stopStream } from './audio';
|
||||
import { stopStream } from './audio';
|
||||
import { backgroundMitt } from '@/modules/emitter';
|
||||
import useIpc from "@/background/ipc/index";
|
||||
const { autoUpdater } = require('electron-updater');
|
||||
|
||||
let win: boolean;
|
||||
|
||||
|
|
@ -15,7 +16,6 @@ backgroundMitt.on('window-active', (state: boolean) => {
|
|||
});
|
||||
|
||||
// Auto updating.
|
||||
const { autoUpdater } = require('electron-updater')
|
||||
autoUpdater.requestHeaders = { 'PRIVATE-TOKEN': 'mvvgWYwWnot4bisiQMh_' }
|
||||
|
||||
autoUpdater.on('update-available', (info: any) => {
|
||||
|
|
@ -38,19 +38,18 @@ autoUpdater.on('update-downloaded', (info: any) => {
|
|||
|
||||
})
|
||||
|
||||
|
||||
|
||||
// Run when electron app is initialized.
|
||||
async function main(dev: boolean) {
|
||||
console.log("MAIN:Initializing Electron App.")
|
||||
async function main(): Promise<void> {
|
||||
|
||||
console.log("MAIN:Initializing Electron App.");
|
||||
|
||||
useIpc();
|
||||
|
||||
// Must wait til window is created.
|
||||
await createWindow();
|
||||
|
||||
// Instantiate socket session with crimata-platorm.
|
||||
initSession(dev);
|
||||
|
||||
// Begin audio stream.
|
||||
initAudioIO();
|
||||
|
||||
}
|
||||
|
||||
// Root function of app.
|
||||
|
|
@ -58,8 +57,8 @@ export function initApp(dev: boolean): void {
|
|||
|
||||
// On initial startup.
|
||||
app.on("ready", () => {
|
||||
if (!dev) autoUpdater.checkForUpdates()
|
||||
main(dev)
|
||||
// autoUpdater.checkForUpdates()
|
||||
main();
|
||||
});
|
||||
|
||||
// Must keep to ensure app doesn't quit on close.
|
||||
|
|
|
|||
117
src/background/ipc/account.ts
Normal file
117
src/background/ipc/account.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
|
||||
"use strict";
|
||||
|
||||
import { Profile } from "@/types";
|
||||
import { submit, fetchProfile, logout } from "@/api/account";
|
||||
import { ipcMain, IpcMainInvokeEvent } from "electron";
|
||||
import { store } from "@/background/store";
|
||||
|
||||
|
||||
const parseAuthRes = (authRes: any) => {
|
||||
const token = authRes.headers['set-cookie'][0].split(";")[0].split("=")[1] as string;
|
||||
const profile = authRes.data as Profile;
|
||||
return {
|
||||
token,
|
||||
profile
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
const onProfile = async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
_payload: null
|
||||
): Promise<Profile | Error> => (
|
||||
|
||||
new Promise(async (resolve, reject) => {
|
||||
console.log('[IPC]: user-profile');
|
||||
|
||||
// get jwt token and crimataId from store
|
||||
const token = store.get('key');
|
||||
const crimataId = store.get('crimataId');
|
||||
|
||||
// authenticate and fetch profile
|
||||
try {
|
||||
|
||||
const res = await fetchProfile(
|
||||
crimataId,
|
||||
token
|
||||
);
|
||||
|
||||
const parsed = parseAuthRes(res);
|
||||
resolve(parsed.profile);
|
||||
|
||||
} catch(e) {
|
||||
reject(new Error('Failed to fetch profile.'));
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
const onLogin = async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
payload: string
|
||||
): Promise<Profile | Error> => (
|
||||
|
||||
new Promise(async (resolve, reject) => {
|
||||
console.log('[IPC]: user-login');
|
||||
|
||||
const account = JSON.parse(payload);
|
||||
|
||||
if ( account.password && account.email ) {
|
||||
try {
|
||||
const res = await submit(account.email, account.password);
|
||||
const parsed = parseAuthRes(res);
|
||||
|
||||
// save jwt token and profile
|
||||
store.set('key', parsed.token);
|
||||
store.set('crimataId', parsed.profile.crimataId);
|
||||
|
||||
// return profile to renderer
|
||||
resolve(parsed.profile);
|
||||
|
||||
} catch(e) {
|
||||
console.log('[API]', e.response);
|
||||
reject(new Error('Failed to authenticate'));
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const onLogout = async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
_payload: null
|
||||
): Promise<void> => (
|
||||
|
||||
new Promise(async (resolve, reject) => {
|
||||
console.log('[IPC]: user-logout');
|
||||
|
||||
try {
|
||||
// post logout to backend
|
||||
await logout();
|
||||
|
||||
// remove key and crimataId
|
||||
store.delete('key');
|
||||
store.delete('crimataId');
|
||||
|
||||
// TODO: kill crimata platform session
|
||||
|
||||
resolve();
|
||||
} catch(e) {
|
||||
reject(new Error('Failed to logout. Please try again.'));
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
export default function useAccountListeners(): void {
|
||||
|
||||
ipcMain.removeHandler("user-profile");
|
||||
ipcMain.handle("user-profile", onProfile);
|
||||
|
||||
ipcMain.removeHandler("user-login");
|
||||
ipcMain.handle("user-login", onLogin);
|
||||
|
||||
ipcMain.removeHandler("user-logout");
|
||||
ipcMain.handle("user-logout", onLogout);
|
||||
|
||||
}
|
||||
40
src/background/ipc/audio.ts
Normal file
40
src/background/ipc/audio.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
|
||||
"use strict";
|
||||
|
||||
import { ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron";
|
||||
import { fetchAudioInput, toggleRecord } from "@/background/audio";
|
||||
|
||||
|
||||
// Toggles record to true to begin capturing chunks.
|
||||
const onRecordingStart = (
|
||||
_event: IpcMainEvent,
|
||||
_payload: null
|
||||
): void => {
|
||||
|
||||
console.log('[IPC]: start-recording');
|
||||
|
||||
toggleRecord();
|
||||
};
|
||||
|
||||
|
||||
// Returns recorded audio to frontend and sets record to false.
|
||||
const onRecordingStop = async (
|
||||
_event: IpcMainInvokeEvent,
|
||||
_payload: null
|
||||
): Promise<Error | string> => {
|
||||
|
||||
console.log('[IPC]: stop-recording');
|
||||
|
||||
return await fetchAudioInput()
|
||||
};
|
||||
|
||||
|
||||
export default function useAudioListeners(): void {
|
||||
|
||||
ipcMain.removeAllListeners("start-recording");
|
||||
ipcMain.on("start-recording", onRecordingStart);
|
||||
|
||||
ipcMain.removeHandler("stop-recording");
|
||||
ipcMain.handle("stop-recording", onRecordingStop);
|
||||
|
||||
}
|
||||
17
src/background/ipc/index.ts
Normal file
17
src/background/ipc/index.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
|
||||
"use strict";
|
||||
|
||||
import useAccountListeners from "./account";
|
||||
import useSessionListeners from "./session";
|
||||
import useAudioListeners from "./audio";
|
||||
|
||||
|
||||
export default function useIpc(): void {
|
||||
|
||||
useAccountListeners();
|
||||
|
||||
useSessionListeners();
|
||||
|
||||
useAudioListeners();
|
||||
|
||||
}
|
||||
62
src/background/ipc/session.ts
Normal file
62
src/background/ipc/session.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
|
||||
"use strict";
|
||||
|
||||
import { initSession, emitNewMessages, sendMessage } from '@/background/session';
|
||||
import { ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron";
|
||||
import { initAudioIO } from "@/background/audio";
|
||||
import { ClientMessage } from "@/types";
|
||||
|
||||
|
||||
// Instantiate socket session with crimata-platorm.
|
||||
const onSessionInit = (
|
||||
_event: IpcMainInvokeEvent,
|
||||
cid: string
|
||||
): void => {
|
||||
|
||||
console.log('[IPC]: init-session');
|
||||
|
||||
initSession(cid);
|
||||
|
||||
initAudioIO();
|
||||
}
|
||||
|
||||
|
||||
const onAppMounted = (
|
||||
_event: IpcMainInvokeEvent,
|
||||
_payload: null
|
||||
): void => {
|
||||
|
||||
console.log('[IPC]: app-mounted');
|
||||
|
||||
emitNewMessages()
|
||||
};
|
||||
|
||||
|
||||
// Handle messages from window/client.
|
||||
const onClientMessage = (
|
||||
_event: IpcMainEvent,
|
||||
payload: ClientMessage
|
||||
): void => {
|
||||
|
||||
console.log('[IPC]: client-message');
|
||||
|
||||
sendMessage(payload);
|
||||
}
|
||||
|
||||
|
||||
export default function useSessionListeners(): void {
|
||||
|
||||
console.log('[IPC]: Init session listeners.');
|
||||
|
||||
// Attach listeners for frontend.
|
||||
ipcMain.removeAllListeners("client-message");
|
||||
ipcMain.on("client-message", onClientMessage);
|
||||
|
||||
// Attack browser window init listener.
|
||||
ipcMain.removeAllListeners("app-mounted");
|
||||
ipcMain.on("app-mounted", onAppMounted);
|
||||
|
||||
ipcMain.removeAllListeners("init-session");
|
||||
ipcMain.on("init-session", onSessionInit);
|
||||
|
||||
}
|
||||
|
|
@ -1,82 +1,35 @@
|
|||
/*
|
||||
* 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
|
||||
*
|
||||
* 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, saveToJson } from './helpers';
|
||||
import { ipcMain, IpcMainEvent, IpcMainInvokeEvent } from "electron";
|
||||
import { ipcEmit, loadState } from './helpers';
|
||||
|
||||
import useWebSockets from "@/modules/websockets";
|
||||
import useWebSockets from "./websockets";
|
||||
|
||||
import { play } from "./audio";
|
||||
import { renderMessage } from "@/modules/message";
|
||||
import { AuthProtocol, SessionState, Profile } from "@/types";
|
||||
import { SessionState } from "@/types";
|
||||
|
||||
let win = true;
|
||||
|
||||
// Info saved to json on quit (key, newMessages).
|
||||
let state: SessionState;
|
||||
|
||||
// Profile of current user.
|
||||
let profile: Profile | boolean;
|
||||
|
||||
// Called when server sends auth message.
|
||||
const updateState = (res: AuthProtocol) => {
|
||||
console.log("SESS:Auth message received: \n" +
|
||||
` key: ${res.key}\n` +
|
||||
` alias: ${res.profile}`)
|
||||
|
||||
if (state) {
|
||||
|
||||
// Update key.
|
||||
state.key = res.key;
|
||||
|
||||
// Update the user profile.
|
||||
profile = res.profile;
|
||||
|
||||
// Send upated profile to frontend.
|
||||
console.log("SESS:Sending updated user profile to browser.")
|
||||
ipcEmit("update-state", {
|
||||
profile: profile,
|
||||
newMessages: state.newMessages
|
||||
})
|
||||
|
||||
// Save the updated state to json.
|
||||
console.log("SESS:Saving session state.")
|
||||
saveToJson("session.json", state)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Send state on new window.
|
||||
const onNewBrowserWindow = (_event: IpcMainInvokeEvent, _payload: any) => {
|
||||
if (typeof profile !== 'undefined') {
|
||||
console.log("SESS:Sending user profile to browser.")
|
||||
ipcEmit("update-state", {
|
||||
profile: profile,
|
||||
newMessages: state.newMessages
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Calls appropriate endpoint for a server message.
|
||||
const onMessage = (data: string) => {
|
||||
let message = JSON.parse(data)
|
||||
|
||||
// AuthProtocol message.
|
||||
if (message.hasOwnProperty("key")) {
|
||||
updateState(message)
|
||||
}
|
||||
const onMessage = (data: string): void => {
|
||||
let message = JSON.parse(data);
|
||||
console.log('received new message', message);
|
||||
|
||||
// Standard message.
|
||||
else if (message.content) {
|
||||
if (message.content) {
|
||||
|
||||
// Convert to render message
|
||||
message = renderMessage(
|
||||
|
|
@ -93,7 +46,7 @@ const onMessage = (data: string) => {
|
|||
}
|
||||
ipcEmit("render-message", message)
|
||||
}
|
||||
|
||||
|
||||
else {
|
||||
console.log("SESS:No window: saving message.")
|
||||
state.newMessages.push(message);
|
||||
|
|
@ -108,57 +61,40 @@ const onMessage = (data: string) => {
|
|||
|
||||
};
|
||||
|
||||
// When socket connects, we update state.
|
||||
const onOpen = () => {
|
||||
console.log(`SESS:Sending key: ${state.key}`)
|
||||
|
||||
if (state) {
|
||||
sendMessage({
|
||||
"key": state.key,
|
||||
"usr": false,
|
||||
"pwd": false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Websockets module.
|
||||
const { createSocket, sendMessage } = useWebSockets(onMessage, onOpen);
|
||||
const { createSocket, send } = useWebSockets(onMessage);
|
||||
|
||||
// Handle messages from window/client.
|
||||
const onClientMessage = (_event: IpcMainEvent, payload: any) => {
|
||||
console.log("New client message")
|
||||
|
||||
const success = sendMessage(payload)
|
||||
|
||||
if (!success) {
|
||||
console.log("Unable to send message: ", payload)
|
||||
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 = (dev: boolean) => {
|
||||
export const initSession = (cid: string): void => {
|
||||
console.log("SESS:Creating new session.")
|
||||
|
||||
// Load Json or createState.
|
||||
state = loadState("session.json")
|
||||
|
||||
console.log("SESS:State loaded: \n" +
|
||||
` key: ${state.key}\n` +
|
||||
` new: ${state.newMessages}`)
|
||||
state = loadState("session.json");
|
||||
|
||||
// Open socket connection.
|
||||
let url = "ws://crimata.com:8760";
|
||||
if (dev) url = "ws://localhost:8760";
|
||||
createSocket(url)
|
||||
|
||||
// Attack browser window init listener.
|
||||
ipcMain.removeAllListeners("app-mounted")
|
||||
ipcMain.on("app-mounted", onNewBrowserWindow);
|
||||
|
||||
// Attach listeners for frontend.
|
||||
ipcMain.removeAllListeners("client-message")
|
||||
ipcMain.on("client-message", onClientMessage);
|
||||
createSocket();
|
||||
|
||||
// Keep win up-to-date.
|
||||
backgroundMitt.on('window-active', (state: boolean) => {
|
||||
|
|
|
|||
16
src/background/store.ts
Normal file
16
src/background/store.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
|
||||
const Store = require('electron-store');
|
||||
|
||||
const schema = {
|
||||
key: {
|
||||
type: 'string',
|
||||
},
|
||||
crimataId: {
|
||||
type: 'string'
|
||||
}
|
||||
};
|
||||
|
||||
export const store = new Store({
|
||||
schema,
|
||||
encryptionKey: "super user test"
|
||||
});
|
||||
|
|
@ -1,13 +1,16 @@
|
|||
"use strict";
|
||||
|
||||
import WebSocket from 'ws';
|
||||
import { ipcMain } from "electron";
|
||||
|
||||
let socket: WebSocket;
|
||||
|
||||
const socketUrl = process.env.PLATFORM_URL;
|
||||
|
||||
// Run every time we want to connect to backend.
|
||||
export default function useWebSockets(receiveCallback: (s: string) => any, openCallback: () => any) {
|
||||
export default function useWebSockets(
|
||||
receiveCallback: (s: string) => void,
|
||||
openCallback?: () => void
|
||||
) {
|
||||
|
||||
// Returns bool (sucess or fail).
|
||||
const sendMessage = (data: any) => {
|
||||
|
|
@ -24,11 +27,22 @@ export default function useWebSockets(receiveCallback: (s: string) => any, openC
|
|||
|
||||
}
|
||||
|
||||
const onOpen = (event: WebSocket.OpenEvent) => {
|
||||
const send = async (data: Record<string, any>): Promise<boolean> => (
|
||||
new Promise((resolve, reject) => {
|
||||
if (socket.readyState !== 1) {
|
||||
reject(false);
|
||||
}
|
||||
socket.send(JSON.stringify(data))
|
||||
resolve(true);
|
||||
|
||||
}))
|
||||
|
||||
|
||||
const onOpen = (_event: WebSocket.OpenEvent) => {
|
||||
|
||||
console.log("WS:Connected to WS Server!");
|
||||
|
||||
openCallback()
|
||||
if (openCallback) openCallback();
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -40,7 +54,7 @@ export default function useWebSockets(receiveCallback: (s: string) => any, openC
|
|||
|
||||
}
|
||||
|
||||
const onClose = (event: WebSocket.CloseEvent) => {
|
||||
const onClose = (_event: WebSocket.CloseEvent) => {
|
||||
console.log("WS:Socket closed normally.")
|
||||
}
|
||||
|
||||
|
|
@ -52,9 +66,9 @@ export default function useWebSockets(receiveCallback: (s: string) => any, openC
|
|||
setTimeout(createSocket, 1000)
|
||||
}
|
||||
|
||||
const createSocket = (url: string) => {
|
||||
|
||||
socket = new WebSocket(url)
|
||||
const createSocket = () => {
|
||||
if (socketUrl)
|
||||
socket = new WebSocket(socketUrl)
|
||||
|
||||
// Add listeners.
|
||||
socket.addEventListener("open", onOpen)
|
||||
|
|
@ -67,7 +81,8 @@ export default function useWebSockets(receiveCallback: (s: string) => any, openC
|
|||
|
||||
return {
|
||||
createSocket,
|
||||
sendMessage
|
||||
sendMessage,
|
||||
send
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -57,7 +57,6 @@ const saveWindowState = () => {
|
|||
|
||||
// Do this on window mount.
|
||||
const onWindowMount = (): void => {
|
||||
console.log("BW:Adding window listeners. ")
|
||||
|
||||
// Must tell initApp that window exists.
|
||||
backgroundMitt.emit('window-active', true);
|
||||
|
|
@ -70,12 +69,10 @@ const onWindowMount = (): void => {
|
|||
backgroundMitt.removeAllListeners("ipc-renderer")
|
||||
backgroundMitt.on("ipc-renderer", renderMessage);
|
||||
|
||||
console.log("BW:Listeners created.")
|
||||
}
|
||||
|
||||
// Do this on window dismount (close).
|
||||
const onWindowDismount = (): void => {
|
||||
console.log("BW:Window closed.")
|
||||
win = null;
|
||||
backgroundMitt.emit('window-active', false);
|
||||
}
|
||||
|
|
@ -89,7 +86,6 @@ export async function createWindow(): Promise<void> {
|
|||
|
||||
// Load the saved window state.
|
||||
winState = loadWinState("window.json")
|
||||
console.log(`BW:Creating window [${winState.width}, ${winState.height}].`)
|
||||
|
||||
// Define the browser window.
|
||||
win = new BrowserWindow({
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { useIpc } from '@/modules/ipc';
|
|||
import { onMounted, onUnmounted, ref, Ref } from "vue";
|
||||
import keyboardNameMap from "../keyBoardMaps/keyboardNameMap";
|
||||
import { renderMessage, clientMessage } from '@/modules/message';
|
||||
import { postMessage } from "@/ipcRend/session";
|
||||
import { invokeStopRecord } from "@/ipcRend/audio";
|
||||
|
||||
|
||||
function showRecIcon () {
|
||||
|
|
@ -13,7 +15,7 @@ function showRecIcon () {
|
|||
opacity: [0, 0.75],
|
||||
scale: [0.0, 1],
|
||||
duration: 250,
|
||||
easing: 'linear',
|
||||
easing: 'linear',
|
||||
})
|
||||
|
||||
}
|
||||
|
|
@ -25,7 +27,7 @@ function hideRecIcon () {
|
|||
opacity: [0.75, 0],
|
||||
scale: [1, 0],
|
||||
duration: 250,
|
||||
easing: 'linear',
|
||||
easing: 'linear',
|
||||
})
|
||||
|
||||
}
|
||||
|
|
@ -50,7 +52,7 @@ export default function useAudioInputController (typing: Ref) {
|
|||
if (cmd == "SPACE" && !recording.value && !typing.value) {
|
||||
|
||||
console.log("INPT:Starting record.")
|
||||
post("start-recording", "");
|
||||
post("start-recording", null);
|
||||
|
||||
showRecIcon()
|
||||
recording.value = true;
|
||||
|
|
@ -67,9 +69,9 @@ export default function useAudioInputController (typing: Ref) {
|
|||
|
||||
// Create a message.
|
||||
const message = renderMessage(
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"sf"
|
||||
)
|
||||
|
||||
|
|
@ -78,14 +80,19 @@ export default function useAudioInputController (typing: Ref) {
|
|||
|
||||
// Stop recording and get audio from recorder.
|
||||
console.log("INPT:Stopping record.")
|
||||
const audio = await invoke("stop-recording", "");
|
||||
|
||||
// Send message to the backend for processing.
|
||||
const clientM = clientMessage("", audio, message.uid);
|
||||
post('client-message', clientM);
|
||||
try {
|
||||
const audio = await invokeStopRecord() as string;
|
||||
// Send message to the backend for processing.
|
||||
const clientM = clientMessage("", audio, message.uid);
|
||||
postMessage(clientM);
|
||||
} catch(e) {
|
||||
console.log('Failed to fetch audio.')
|
||||
} finally {
|
||||
hideRecIcon();
|
||||
recording.value = false;
|
||||
}
|
||||
|
||||
|
||||
hideRecIcon()
|
||||
recording.value = false;
|
||||
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { useIpc } from '@/modules/ipc';
|
|||
import { Ref, ref, watch, onMounted, onUnmounted } from "vue";
|
||||
import keyboardNameMap from "../keyBoardMaps/keyboardNameMap";
|
||||
import { clientMessage, renderMessage } from '@/modules/message';
|
||||
import { postMessage } from "@/ipcRend/session";
|
||||
|
||||
|
||||
//---Animations-----------------------------------------------
|
||||
|
||||
|
|
@ -19,7 +21,7 @@ function showTextInput () {
|
|||
translateX: [t1, t2],
|
||||
scale: [0.3, 1],
|
||||
duration: 500,
|
||||
easing: 'easeOutExpo',
|
||||
easing: 'easeOutExpo',
|
||||
})
|
||||
|
||||
}
|
||||
|
|
@ -33,7 +35,7 @@ function hideTextInput() {
|
|||
translateX: t,
|
||||
scale: 0.3,
|
||||
duration: 500,
|
||||
easing: 'easeOutExpo',
|
||||
easing: 'easeOutExpo',
|
||||
})
|
||||
|
||||
}
|
||||
|
|
@ -45,7 +47,7 @@ function switchSide(currentSide: string) {
|
|||
targets: '#textInput',
|
||||
translateX: t,
|
||||
duration: 500,
|
||||
easing: 'easeOutExpo',
|
||||
easing: 'easeOutExpo',
|
||||
})
|
||||
|
||||
}
|
||||
|
|
@ -75,7 +77,7 @@ export default function useTextInputController(elementX: Ref) {
|
|||
textInput.value = "";
|
||||
textInput.blur();
|
||||
}
|
||||
|
||||
|
||||
hideTextInput()
|
||||
firstKey = true;
|
||||
typing.value = false;
|
||||
|
|
@ -87,9 +89,9 @@ export default function useTextInputController(elementX: Ref) {
|
|||
|
||||
// Create the message.
|
||||
const message = renderMessage(
|
||||
textInput.value,
|
||||
false,
|
||||
"",
|
||||
textInput.value,
|
||||
false,
|
||||
"",
|
||||
"sf"
|
||||
)
|
||||
|
||||
|
|
@ -97,7 +99,7 @@ export default function useTextInputController(elementX: Ref) {
|
|||
|
||||
// Send it to the backend for processing.
|
||||
const clientM = clientMessage(textInput.value, false, message.uid);
|
||||
post('client-message', clientM);
|
||||
postMessage(clientM);
|
||||
|
||||
clearInput()
|
||||
}
|
||||
|
|
@ -115,9 +117,9 @@ export default function useTextInputController(elementX: Ref) {
|
|||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
const key = keyboardNameMap[e.keyCode]
|
||||
|
||||
|
||||
if (textInput) {
|
||||
|
||||
|
||||
// Only runs on firstKey.
|
||||
if (firstKey) {
|
||||
|
||||
|
|
@ -165,7 +167,7 @@ export default function useTextInputController(elementX: Ref) {
|
|||
switchSide(side)
|
||||
side = "left"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
if (winW - elementX > 230) {
|
||||
|
|
@ -173,7 +175,7 @@ export default function useTextInputController(elementX: Ref) {
|
|||
side = "right"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@
|
|||
|
||||
<!-- submit button; position: fixed -->
|
||||
<button class="submitButton button" type="submit">Submit</button>
|
||||
|
||||
|
||||
</form>
|
||||
|
||||
<!-- back to login button: position: fixed -->
|
||||
|
|
@ -37,21 +37,34 @@
|
|||
import { defineComponent, ref } from "vue";
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
import { authRequest } from '@/modules/message';
|
||||
import { useProfile } from '@/modules/auth';
|
||||
import { invokeLogin } from "@/ipcRend/account";
|
||||
import { Profile } from "@/types";
|
||||
|
||||
export default defineComponent({
|
||||
name: "Login",
|
||||
|
||||
setup() {
|
||||
|
||||
const { post } = useIpc();
|
||||
const { setProfile } = useProfile();
|
||||
|
||||
const usr = ref("");
|
||||
const pwd = ref("");
|
||||
|
||||
// Submit login credentials to the backend.
|
||||
const submitForm = () => {
|
||||
console.log(`Submitting login form: ${usr.value}, ${pwd.value}`)
|
||||
post("client-message", authRequest(false, usr.value, pwd.value))
|
||||
const submitForm = async () => {
|
||||
|
||||
try {
|
||||
const profile = await invokeLogin({
|
||||
email: usr.value,
|
||||
password: pwd.value
|
||||
}) as Profile;
|
||||
|
||||
setProfile(profile);
|
||||
|
||||
} catch(e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@
|
|||
|
||||
<!-- List of message bubbles. -->
|
||||
<div id="messenger">
|
||||
<Message
|
||||
v-for="message in messages"
|
||||
:message="message[1]"
|
||||
<Message
|
||||
v-for="message in messages"
|
||||
:message="message[1]"
|
||||
:key="message[0]"
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -48,25 +48,24 @@ export default defineComponent({
|
|||
|
||||
// Load the message history.
|
||||
if (crimataId === window.localStorage.getItem("last_usr")) {
|
||||
prepMessageView(props.newMessages)
|
||||
prepMessageView(props.newMessages);
|
||||
} else {
|
||||
messages.value.clear()
|
||||
messages.value.clear();
|
||||
}
|
||||
|
||||
// New content listeners.
|
||||
emitter.on('self-message', (message) => updateMessageView(message));
|
||||
window.ipcRenderer.on("render-message", (_e: any, payload: any) => {
|
||||
updateMessageView(payload.message)
|
||||
updateMessageView(payload.message);
|
||||
});
|
||||
|
||||
// Save the usr for next time.
|
||||
window.localStorage.setItem("last_usr", crimataId)
|
||||
window.localStorage.setItem("last_usr", crimataId);
|
||||
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
window.ipcRenderer.removeAllListeners("render-message");
|
||||
window.ipcRenderer.removeAllListeners("annotate-message");
|
||||
emitter.all.clear();
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@
|
|||
import { defineComponent, ref } from "vue";
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
import { logoutRequest } from '@/modules/message';
|
||||
import { useProfile } from "@/modules/auth"
|
||||
import { invokeLogout } from "@/ipcRend/account";
|
||||
|
||||
export default defineComponent({
|
||||
name: "Settings",
|
||||
|
|
@ -37,7 +39,9 @@
|
|||
setup() {
|
||||
const toggleSettings = ref(false);
|
||||
|
||||
const { post } = useIpc();
|
||||
const { post, invoke } = useIpc();
|
||||
|
||||
const { clearProfile } = useProfile();
|
||||
|
||||
// Listen for escape key to close settings.
|
||||
const onEscape = (e: any) => {
|
||||
|
|
@ -54,9 +58,17 @@
|
|||
}
|
||||
|
||||
// We ask server to log us out.
|
||||
const onLogout = () => {
|
||||
console.log("Submitting logout request.")
|
||||
post("client-message", logoutRequest())
|
||||
const onLogout = async () => {
|
||||
|
||||
console.log("Submitting logout request.");
|
||||
|
||||
try {
|
||||
clearProfile();
|
||||
await invokeLogout();
|
||||
} catch(e) {
|
||||
console.log('error')
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
27
src/ipcRend/account.ts
Normal file
27
src/ipcRend/account.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
import { Profile } from "@/types";
|
||||
|
||||
const { invoke } = useIpc();
|
||||
|
||||
interface LoginPayload {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
|
||||
export const invokeProfile = async (): Promise<Profile | Error> => (
|
||||
await invoke('user-profile', null)
|
||||
);
|
||||
|
||||
|
||||
export const invokeLogin = async (
|
||||
payload: LoginPayload
|
||||
): Promise<Profile | Error> => (
|
||||
await invoke('user-login', JSON.stringify(payload))
|
||||
);
|
||||
|
||||
|
||||
export const invokeLogout = async (): Promise<void> => (
|
||||
await invoke("user-logout", null)
|
||||
);
|
||||
15
src/ipcRend/audio.ts
Normal file
15
src/ipcRend/audio.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
|
||||
|
||||
const { post, invoke } = useIpc();
|
||||
|
||||
|
||||
export const postStartRecord = (): void => (
|
||||
post("start-recording", null)
|
||||
);
|
||||
|
||||
|
||||
export const invokeStopRecord = async (): Promise<string | Error> => (
|
||||
await invoke("stop-recording", null)
|
||||
);
|
||||
21
src/ipcRend/session.ts
Normal file
21
src/ipcRend/session.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
|
||||
import { useIpc } from "@/modules/ipc";
|
||||
|
||||
import { ClientMessage } from "@/types";
|
||||
|
||||
const { post } = useIpc();
|
||||
|
||||
|
||||
export const postMount = (): void => (
|
||||
post("app-mounted", null)
|
||||
);
|
||||
|
||||
|
||||
export const postInitSession = (cid: string): void => (
|
||||
post("init-session", cid)
|
||||
);
|
||||
|
||||
|
||||
export const postMessage = (payload: ClientMessage): void => (
|
||||
post('client-message', payload)
|
||||
);
|
||||
23
src/modules/auth.ts
Normal file
23
src/modules/auth.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { ref } from "vue";
|
||||
import { Profile } from "@/types";
|
||||
|
||||
|
||||
const profile = ref();
|
||||
|
||||
export const useProfile = () => {
|
||||
|
||||
const setProfile = (payload: Profile) => {
|
||||
profile.value = payload;
|
||||
}
|
||||
|
||||
const clearProfile = () => {
|
||||
profile.value = null;
|
||||
}
|
||||
|
||||
return {
|
||||
setProfile,
|
||||
clearProfile,
|
||||
profile
|
||||
}
|
||||
|
||||
}
|
||||
54
src/modules/http.ts
Normal file
54
src/modules/http.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
|
||||
import axios, { AxiosRequestConfig } from 'axios';
|
||||
|
||||
const preFix = '/api';
|
||||
|
||||
const baseURL = process.env.BUSSINESS_URL + preFix;
|
||||
|
||||
|
||||
interface Request {
|
||||
endpoint: string;
|
||||
query?: Record<string, any>;
|
||||
config?: Record<string, any>;
|
||||
}
|
||||
|
||||
|
||||
const makeQuery = (reqQuery: Record<string, any>) => {
|
||||
|
||||
let result = '';
|
||||
|
||||
result = '?' + Object.entries(reqQuery)
|
||||
.map(([ key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
|
||||
.join('&')
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
export const useHttp = () => {
|
||||
|
||||
const api = axios.create({
|
||||
baseURL,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
|
||||
const post = async (endpoint: string, payload?: Record<string, any>): Promise<any> => (
|
||||
await api.post(endpoint, payload)
|
||||
)
|
||||
|
||||
|
||||
const get = async (req: Request) => {
|
||||
|
||||
if (req.query) {
|
||||
req.endpoint += makeQuery(req.query);
|
||||
}
|
||||
|
||||
const res = await api.get(req.endpoint, req.config);
|
||||
return res;
|
||||
};
|
||||
|
||||
return {
|
||||
get, post
|
||||
}
|
||||
}
|
||||
10
src/types.ts
10
src/types.ts
|
|
@ -19,7 +19,7 @@ export interface ClientMessage {
|
|||
}
|
||||
|
||||
export interface ClientRequest {
|
||||
intent: string;
|
||||
intent: string;
|
||||
params: object;
|
||||
epic: string | boolean;
|
||||
confidence: number;
|
||||
|
|
@ -50,8 +50,10 @@ export interface Profile {
|
|||
}
|
||||
|
||||
export interface AuthProtocol {
|
||||
key: boolean | string;
|
||||
profile: boolean | Profile;
|
||||
token: null | string;
|
||||
profile: null | Profile;
|
||||
password?: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export interface LogoutRequest {
|
||||
|
|
@ -71,4 +73,4 @@ export interface StandardMessage {
|
|||
};
|
||||
context: string;
|
||||
modifier: string;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue