]> Repos - mime-chat/commitdiff
add useIpc hook auth_refactor
authorEnrique Hernandez <hernandeze2@xavier.edu>
Sun, 30 May 2021 15:06:10 +0000 (11:06 -0400)
committerEnrique Hernandez <hernandeze2@xavier.edu>
Sun, 30 May 2021 15:06:10 +0000 (11:06 -0400)
12 files changed:
.gitignore
package.json
src/api/account.ts
src/background/audio.ts
src/background/init.ts
src/background/ipc/account.ts
src/background/ipc/audio.ts [new file with mode: 0644]
src/background/ipc/index.ts
src/background/ipc/session.ts [new file with mode: 0644]
src/background/session.ts
src/modules/http.ts
yarn.lock

index 46762a2d8026977681654cc9be80bef640c4e2e5..20128fcb9af542bb1621c6eb55798b0cc5be56e0 100644 (file)
@@ -9,6 +9,7 @@ crash.log
 # local env files
 .env.local
 .env.*.local
+.env
 
 # Log files
 npm-debug.log*
index ec3ff75b3265263c948c2d6ac59938b7d66c2c82..04ce2ec2338666c9c1ba2eeb2a39440ffadec2e3 100644 (file)
@@ -24,6 +24,7 @@
     "animejs": "^3.2.0",
     "axios": "^0.21.1",
     "core-js": "^3.6.5",
+    "dotenv": "^10.0.0",
     "electron-is-dev": "^2.0.0",
     "electron-store": "^8.0.0",
     "electron-updater": "^4.3.8",
index de5783720c70e6b212b69e4c12a75037b49dbaac..0fd14973172ed94b5ba4c524da2b708d9e67c2c5 100644 (file)
@@ -23,7 +23,7 @@ export const logout =
 export const fetchProfile = async(email: string, token: string) => (
 
     await axios({
-      url: "http://127.0.0.1:3010/api/account/profile",
+      url: "http://127.0.0.1:3000/api/account/profile",
       headers: {
           Cookie: `jwt=${token}`
       },
index 0a98206086013a9eb2c7e98e498b81c55e234040..fa6efb2eff06ef42c08aa3f07d8dc206cc31a344 100644 (file)
@@ -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.")
+export const fetchAudioInput = (): Promise<Error | string> => (
 
-    return new Promise((resolve, reject) => {
+    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);
 }
 
 
index 21f9c45efe5dfdf0ccd885ef1d275b307d1baf4e..0936e81fd02832f5ed1773eef5e0ba7201cb43b4 100644 (file)
@@ -1,12 +1,12 @@
 
 "use strict";
 
-import { app, dialog, ipcMain, IpcMainInvokeEvent } from "electron";
+import { app, dialog } from "electron";
 import { createWindow } from './window';
-import { initSession, onAppMounted } from './session';
-import { initAudioIO, stopStream } from './audio';
+import { stopStream } from './audio';
 import { backgroundMitt } from '@/modules/emitter';
-import { initAccountListener } from "@/background/ipc/account";
+import useIpc from "@/background/ipc/index";
+const { autoUpdater } = require('electron-updater');
 
 let win: boolean;
 
@@ -16,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) => {
@@ -40,29 +39,13 @@ autoUpdater.on('update-downloaded', (info: any) => {
 })
 
 
-const onSessionInit = (_event: IpcMainInvokeEvent, cid: string) => {
-    // Instantiate socket session with crimata-platorm.
-    initSession(cid);
-
-    // Begin audio stream.
-    initAudioIO();
-}
-
 
 // Run when electron app is initialized.
 async function main(): Promise<void> {
 
     console.log("MAIN:Initializing Electron App.");
 
-    // Attack browser window init listener.
-    ipcMain.removeAllListeners("app-mounted");
-    ipcMain.on("app-mounted", onAppMounted);
-
-    ipcMain.removeAllListeners("init-session");
-    ipcMain.on("init-session", onSessionInit);
-
-    // handler user auth, login, and logout asynchrounously
-    initAccountListener();
+    useIpc();
 
     // Must wait til window is created.
     await createWindow();
@@ -74,7 +57,7 @@ export function initApp(dev: boolean): void {
 
     // On initial startup.
     app.on("ready", () => {
-        autoUpdater.checkForUpdates()
+        // autoUpdater.checkForUpdates()
         main()
     });
 
index 932c2b28b3776932b7b54090f52ef9ed5f8cfcd4..e6e9795e1f8dc1e7f15496bcd2781d411190aa97 100644 (file)
@@ -3,7 +3,7 @@
 
 import { Profile } from "@/types";
 import { submit, fetchProfile, logout } from "@/api/account";
-import { ipcMain } from "electron";
+import { ipcMain, IpcMainInvokeEvent } from "electron";
 import { store } from "@/background/store";
 
 
@@ -17,9 +17,10 @@ const parseAuthRes = (authRes: any) => {
 };
 
 
-const onProfile = async (_event: any, _payload: string) => (
+const onProfile = async (_event: IpcMainInvokeEvent, _payload: string) => (
 
     new Promise(async (resolve, reject) => {
+        console.log('[IPC]: user-profile');
 
         // get jwt token and crimataId from store
         const token = store.get('key');
@@ -43,9 +44,10 @@ const onProfile = async (_event: any, _payload: string) => (
 )
 
 
-const onLogin = async (_event: any, payload: string) => (
+const onLogin = async (_event: IpcMainInvokeEvent, payload: string) => (
 
     new Promise(async (resolve, reject) => {
+        console.log('[IPC]: user-login');
 
         const account = JSON.parse(payload);
 
@@ -69,9 +71,10 @@ const onLogin = async (_event: any, payload: string) => (
     })
 )
 
-const onLogout = async (_event: any, _payload: string) => (
+const onLogout = async (_event: IpcMainInvokeEvent, _payload: string) => (
 
     new Promise(async (resolve, reject) => {
+        console.log('[IPC]: user-logout');
 
         try {
             // post logout to backend
@@ -91,7 +94,7 @@ const onLogout = async (_event: any, _payload: string) => (
 )
 
 
-export const initAccountListener = () => {
+export default function useAccountListeners(): void {
 
     ipcMain.removeHandler("user-profile");
     ipcMain.handle("user-profile", onProfile);
diff --git a/src/background/ipc/audio.ts b/src/background/ipc/audio.ts
new file mode 100644 (file)
index 0000000..e6a63d0
--- /dev/null
@@ -0,0 +1,39 @@
+
+"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);
+
+};
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..933bda1d7deef014748fad953ff4dd10d699658d 100644 (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();
+
+}
diff --git a/src/background/ipc/session.ts b/src/background/ipc/session.ts
new file mode 100644 (file)
index 0000000..3eaacbf
--- /dev/null
@@ -0,0 +1,61 @@
+
+"use strict";
+
+import { initSession, emitNewMessages, sendMessage } from '@/background/session';
+import { ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron";
+import { initAudioIO } from "@/background/audio";
+
+
+// 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: any
+): void => {
+
+    console.log('[IPC]: app-mounted');
+
+    emitNewMessages()
+};
+
+
+// Handle messages from window/client.
+const onClientMessage = async (
+    _event: IpcMainEvent,
+    payload: Record<string, any>
+): Promise<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);
+
+}
index a619f334fb48c8e6f8f5bbc35ff6567c6e7d05a5..fc3e4fdf76b95e45b6158a95303536e67f53d61b 100644 (file)
@@ -9,8 +9,7 @@
  */
 
 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 "./websockets";
 
@@ -23,17 +22,9 @@ let win = true;
 // Info saved to json on quit (key, newMessages).
 let state: SessionState;
 
-// Send state on new window.
-export const onAppMounted = (_event: IpcMainInvokeEvent, _payload: any) => {
-
-    ipcEmit("update-state", {
-        newMessages: state.newMessages,
-    });
-
-}
 
 // Calls appropriate endpoint for a server message.
-const onMessage = (data: string) => {
+const onMessage = (data: string): void => {
     let message = JSON.parse(data);
     console.log('received new message', message);
 
@@ -74,13 +65,18 @@ const onMessage = (data: string) => {
 // Websockets module.
 const { createSocket, send } = useWebSockets(onMessage);
 
-// Handle messages from window/client.
-const onClientMessage = async (_event: IpcMainEvent, payload: any): Promise<void> => {
-    console.log("New client message")
 
-    if (payload.hasOwnProperty("key")) {
-        return
+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) {
@@ -91,7 +87,7 @@ const onClientMessage = async (_event: IpcMainEvent, payload: any): Promise<void
 
 
 // Call this to initialize session with Crimata servers.
-export const initSession = (cid: string) => {
+export const initSession = (cid: string): void => {
     console.log("SESS:Creating new session.")
 
     // Load Json or createState.
@@ -100,10 +96,6 @@ export const initSession = (cid: string) => {
     // Open socket connection.
     createSocket();
 
-    // Attach listeners for frontend.
-    ipcMain.removeAllListeners("client-message");
-    ipcMain.on("client-message", onClientMessage);
-
     // Keep win up-to-date.
     backgroundMitt.on('window-active', (state: boolean) => {
         win = state;
index 7ec423d09ceb5314d877405e5c17deeeda191fa8..326b6756c3507506319ab0d6ceac98aead0422ca 100644 (file)
@@ -1,7 +1,7 @@
 
 import axios, { AxiosRequestConfig } from 'axios';
 
-const baseURL = 'http://127.0.0.1:3010/api';
+const baseURL = 'http://127.0.0.1:3000/api';
 
 
 interface Request {
index e79f19f4206b26a835d230a4d20b7b4993018baf..465adc92b1561f2f99ed954c208ccf343d9ac1b0 100644 (file)
--- a/yarn.lock
+++ b/yarn.lock
@@ -4898,6 +4898,11 @@ dotenv-expand@^5.1.0:
   resolved "https://registry.yarnpkg.com/dotenv-expand/-/dotenv-expand-5.1.0.tgz#3fbaf020bfd794884072ea26b1e9791d45a629f0"
   integrity sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==
 
+dotenv@^10.0.0:
+  version "10.0.0"
+  resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-10.0.0.tgz#3d4227b8fb95f81096cdd2b66653fb2c7085ba81"
+  integrity sha512-rlBi9d8jpv9Sf1klPjNfFAuWDjKLwTIJJ/VxtoTwIR6hnZxcEOQCZg2oIL3MWBYw5GpUDKOEnND7LXTbIpQ03Q==
+
 dotenv@^8.2.0:
   version "8.2.0"
   resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.2.0.tgz#97e619259ada750eea3e4ea3e26bceea5424b16a"