diff --git a/.gitignore b/.gitignore index 46762a2..20128fc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ crash.log # local env files .env.local .env.*.local +.env # Log files npm-debug.log* diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 01b0f33..2c0d22c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -21,7 +21,9 @@ build: dotenv: variables.env name: $CI_COMMIT_REF_SLUG paths: - - dist_electron/ + - dist_electron/*.dmg + - dist_electron/*.zip + - dist_electron/*.yml when: on_success only: - main diff --git a/build/config.gypi b/build/config.gypi deleted file mode 100644 index 6f84ed7..0000000 --- a/build/config.gypi +++ /dev/null @@ -1,79 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "asan": 0, - "build_v8_with_gn": "false", - "coverage": "false", - "dcheck_always_on": 0, - "debug_nghttp2": "false", - "debug_node": "false", - "enable_lto": "false", - "enable_pgo_generate": "false", - "enable_pgo_use": "false", - "error_on_warn": "false", - "force_dynamic_crt": 0, - "host_arch": "x64", - "icu_data_in": "../../deps/icu-tmp/icudt67l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_path": "deps/icu-small", - "icu_small": "false", - "icu_ver_major": "67", - "is_debug": 0, - "llvm_version": "0.0", - "napi_build_version": "6", - "node_byteorder": "little", - "node_debug_lib": "false", - "node_enable_d8": "false", - "node_install_npm": "true", - "node_module_version": 83, - "node_no_browser_globals": "false", - "node_prefix": "/", - "node_release_urlbase": "https://nodejs.org/download/release/", - "node_shared": "false", - "node_shared_brotli": "false", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_nghttp2": "false", - "node_shared_openssl": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_target_type": "executable", - "node_use_bundled_v8": "true", - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_node_code_cache": "true", - "node_use_node_snapshot": "true", - "node_use_openssl": "true", - "node_use_v8_platform": "true", - "node_with_ltcg": "false", - "node_without_node_options": "false", - "openssl_fips": "", - "openssl_is_fips": "false", - "shlib_suffix": "83.dylib", - "target_arch": "x64", - "v8_enable_31bit_smis_on_64bit_arch": 0, - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_enable_inspector": 1, - "v8_enable_pointer_compression": 0, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 1, - "v8_promise_internal_field_count": 1, - "v8_random_seed": 0, - "v8_trace_maps": 0, - "v8_use_siphash": 1, - "want_separate_host_toolset": 0, - "xcode_version": "11.0", - "nodedir": "/Users/Enrique/Library/Caches/node-gyp/14.4.0", - "standalone_static_library": 1 - } -} diff --git a/package.json b/package.json index 43ed620..24d13b1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "Crimata", - "version": "0.9.7", + "version": "0.9.9", "private": true, "description": "Cross-platform messenger application built with electron, vue3, and TS.", "author": { @@ -12,7 +12,7 @@ "postinstall": "electron-builder install-app-deps", "postuninstall": "electron-builder install-app-deps" }, - "main": "background.js", + "main": "init.js", "dependencies": { "@google-cloud/speech": "^4.2.0", "@types/animejs": "^3.1.2", @@ -22,8 +22,10 @@ "@types/uuid": "^8.3.0", "@types/ws": "^7.2.7", "animejs": "^3.2.0", + "axios": "^0.21.1", "core-js": "^3.6.5", "electron-is-dev": "^2.0.0", + "electron-store": "^8.0.0", "electron-updater": "^4.3.8", "mitt": "^2.1.0", "naudiodon": "^2.3.2", @@ -36,6 +38,7 @@ "ws": "^7.3.1" }, "devDependencies": { + "@types/axios": "^0.14.0", "@types/electron-devtools-installer": "^2.2.0", "@types/jest": "^24.0.19", "@typescript-eslint/eslint-plugin": "^2.33.0", @@ -69,13 +72,15 @@ "lintOnSave": false, "pluginOptions": { "electronBuilder": { - "preload": "src/preload.ts", + "mainProcessFile": "./src/init.ts", + "rendererProcessFile": "./src/render/main.ts", + "preload": "./src/render/preload.ts", "builderOptions": { "appId": "com.crimata.ElectronUpdaterApp", "artifactName": "${productName}-${version}.${ext}", "publish": { "provider": "generic", - "url": "https://gitlab.com/api/v4/projects/25637892/jobs/artifacts/master/dist_electron?job=build" + "url": "https://gitlab.com/api/v4/projects/25637892/jobs/artifacts/main/raw/dist_electron?job=build" } } } diff --git a/public/index.html b/public/index.html index 48809d8..8f79d27 100644 --- a/public/index.html +++ b/public/index.html @@ -11,11 +11,7 @@ - -
+
diff --git a/src/App.vue b/src/App.vue deleted file mode 100644 index 320b62f..0000000 --- a/src/App.vue +++ /dev/null @@ -1,183 +0,0 @@ - - - - - diff --git a/src/account.ts b/src/account.ts new file mode 100644 index 0000000..581da0e --- /dev/null +++ b/src/account.ts @@ -0,0 +1,95 @@ + +import { postAuth, postLogin, postLogout } from "@/api/account"; +import { endSession, launchSession } from "@/session"; +import { getToken, setToken, setProfile, getProfile, clearStore } from "./store"; +import { parseAuthRes } from "./auth"; +import { ipcEmit } from "@/composables/useEmitter"; + +export const accountAuth = async (): Promise => { + + /* attempt to get a login token from the store */ + const token = getToken(); + + /* try to login with it, returns platform secret and new token on success */ + if (token) { + try { + + const res = await postAuth(token); + + const parsed = parseAuthRes(res); + + setToken(parsed.token) + setProfile(parsed.profile); + + return { + profile: parsed.profile, + token: parsed.token + }; + + } catch(e) { + console.log('[ACCOUNT]', e); + clearStore(); + throw(new Error('Failed to authenticate.')); + + } + } else { + throw(new Error('Unable to authenticate.')); + } +}; + +export const accountLogin: IpcHandlerCallback = async (payload) => { + const account = payload as AccountCredentials; + try { + + // attempt login with email password + const res = await postLogin(account.email, account.password); + const parsed = parseAuthRes(res); + + // save jwt token and profile + setToken(parsed.token); + setProfile(parsed.profile); + + // launch session + launchSession(parsed.token); + + // return profile to renderer + return parsed.profile; + + } catch(e) { + clearStore(); + throw e; + } +} + + +export const accountLogout = async (): Promise => { + + try { + // post logout to backend + await postLogout(); + + // remove key and crimataId + clearStore(); + + // kill crimata platform session + endSession(); + + return; + + } catch(e) { + console.log('[ACCOUNT]', e); + return (new Error('Failed to logout. Please try again.')); + } + +} + +export const updateAppState = (): void => { + + const profile = getProfile(); + + ipcEmit("set-profile", profile); + + // ipcEmit('messages') etc + +} + diff --git a/src/api/account.ts b/src/api/account.ts new file mode 100644 index 0000000..45baca2 --- /dev/null +++ b/src/api/account.ts @@ -0,0 +1,31 @@ + +import useHttp from "@/composables/useHttp"; +import axios from "axios"; +import {config} from "@/config"; + +const { post } = useHttp(); + +export const postAuth = async (token: string) => ( + await axios({ + url: config.BUSINESS_URL + config.BUSINESS_PREFIX + '/account/authenticate', + headers: { + Cookie: `crimataCookie=${token}` + }, + method: 'POST', + }) +); + + +export const postLogin = async (email: string, password: string) => ( + await post('/account/login', { email, password }) +); + + +export const postLogout = + async (): Promise => (await post('/account/logout')); + + + + + + diff --git a/src/assets/crimata.svg b/src/assets/crimata.svg deleted file mode 100644 index 8bb28dc..0000000 --- a/src/assets/crimata.svg +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/audio.ts b/src/audio.ts new file mode 100644 index 0000000..7ae2562 --- /dev/null +++ b/src/audio.ts @@ -0,0 +1,187 @@ +/* eslint @typescript-eslint/no-var-requires: "off" */ + +"use strict"; + +// where the audio goes +let buffer: ArrayBuffer[] = []; + +// place audio data in buffer +export const collect: IpcListenerCallback = (chunk) => { + if (chunk) buffer.push(chunk); +} + +// return audio and clear buffer +export const flush = async () => { + const bufferCopy = buffer; + buffer = []; + return bufferCopy; +} + +// import { backgroundMitt } from '@/modules/emitter'; +// const portAudio = require('naudiodon'); + +// // Audio in and out stream objects. +// let ai: typeof portAudio.AudioIO | boolean = false; +// let ao: typeof portAudio.AudioIO | boolean = false; + +// // Whether activly recording. +// let record = false; + +// const audioContainer = { +// input: '', +// } + +// const audioOptions = { +// channelCount: 1, +// sampleFormat: 16, +// sampleRate: 16000, +// deviceId: -1, +// closeOnError: false, +// } + +// export const toggleRecord = (): void => { record = !record }; + + +// export const fetchAudioInput = (): Promise => ( + +// new Promise((resolve, reject) => { + +// try { +// resolve(audioContainer.input); +// toggleRecord(); +// } catch (e) { +// reject(new Error('Failed to fetch the audio.')) +// } + +// }) +// ) + + +// // Main audio function run by run.ts module. +// export function initAudioIO(): void { +// console.log("AUDIO:Starting io streams.") + +// if (!ai) { + +// // Initialize and start input stream. +// ai = new portAudio.AudioIO({ inOptions: audioOptions }); +// ai.setEncoding("hex"); +// ai.start(); + +// // On each data chunk... +// ai.on('data', (chunk: string) => { + +// // If recording, we capture the data. +// if (record) { +// console.log('AUDIO:Recording...') +// audioContainer.input += chunk; +// } + +// // Else, we don't capture and also clear audioContainer. +// else { +// if (audioContainer.input.length) { +// audioContainer.input = ""; +// } +// } + +// }); +// } + +// if (!ao) { + +// // Initialize and start input stream. +// ao = new portAudio.AudioIO({ outOptions: audioOptions }); +// ao.start(); + +// } +// } + + +// // ---Audio playback-------------------------------------------- + +// // Split Buffer into an array of len-sized Buffers. +// function bufSplit(buf: Buffer, len: number): Array { +// const chunks = []; +// let i = 0; +// let L = len; + +// while(i < buf.byteLength) { +// chunks.push(buf.slice(i, L)); +// i = L; +// L += len; +// } + +// return chunks; +// } + +// // Audio playback. +// export function play(input: string): void { + +// // Format the audio. +// const audio = bufSplit( +// Buffer.from(input as string, 'hex'), +// 8192 +// ); + +// // Called on end of write. +// const callback = () => { + +// // We stop audio playback anim. +// backgroundMitt.emit('ipc-renderer', { +// endpoint: 'stop-playback-anim' +// }); + +// } + +// write(); + +// // Iterate through audio array and write buffers to portAudio writable. +// function write() { +// let chunk: Buffer; +// let ok = true; +// let i = 0; + +// do { +// chunk = audio[i]; +// if (i === audio.length - 1) { +// // write last chunk. +// ao.write(chunk, null, callback); +// } else { +// // check for backpreassure. +// ok = ao.write(chunk, null); +// } +// i++; +// } while (i < audio.length && ok); + +// if (i < audio.length) { +// // Had to stop early! +// // Write some more once it drains. +// ao.once('drain', write); +// } +// } +// } + +// // ------------------------------------------------------------- + +// // Get's called on window close. +// export async function stopStream() { +// console.log("AUDIO:Stopping audio stream.") +// if (ai) { +// try { +// await ai.quit() +// } catch(e){ +// console.log('AUDIO: Failed to shutdown audio input.'); +// throw e; +// } +// } +// if (ao) { +// try { +// await ao.quit() +// } catch(e){ +// console.log('AUDIO: Failed to shutdown audio output.'); +// throw e; +// } +// } +// } + + diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..14ed36a --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,13 @@ + +export 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 + } +}; + + + + diff --git a/src/background.ts b/src/background.ts deleted file mode 100644 index 8fafb4f..0000000 --- a/src/background.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Entry point for Crimata electron app. - * "Look on my Works, ye Mighty, and despair!" - */ - -"use strict"; - -import { initApp } from './background/init'; -import { protocol } from "electron"; - -// Scheme must be registered before the app is ready -protocol.registerSchemesAsPrivileged([ - { scheme: "app", privileges: { secure: true, standard: true } } -]); - -// Load environment variable -const isDev = require('electron-is-dev'); - -// NOTE Program Begins Here -(async () => { - - console.log('Starting Crimata electron app.'); - await initApp(isDev); - -})(); diff --git a/src/background/audio.ts b/src/background/audio.ts deleted file mode 100644 index 6dd3bdd..0000000 --- a/src/background/audio.ts +++ /dev/null @@ -1,179 +0,0 @@ -/* eslint @typescript-eslint/no-var-requires: "off" */ - -"use strict"; - -import { ipcMain } from "electron"; -import { backgroundMitt } from '@/modules/emitter'; - -const portAudio = require('naudiodon'); - -// Audio in and out stream objects. -let ai: typeof portAudio.AudioIO | boolean = false; -let ao: typeof portAudio.AudioIO | boolean = false; - -// Whether activly recording. -let record = false; - -const audioContainer = { - input: '', -} - -const audioOptions = { - channelCount: 1, - sampleFormat: 16, - sampleRate: 16000, - deviceId: -1, - closeOnError: false, -} - -// Toggles record to true to begin capturing chunks. -const onRecordingStart = (_event: any, _payload: any) => { - console.log("AUDIO: Beginning audio capture.") - record = true; -} - -// 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) => { - - try { - resolve(audioContainer.input); - record = false; - } catch (e) { - reject() - } - - }); -}; - - -// Main audio function run by run.ts module. -export function initAudioIO(): void { - console.log("AUDIO:Starting io streams.") - - if (!ai) { - - // Initialize and start input stream. - ai = new portAudio.AudioIO({ inOptions: audioOptions }); - ai.setEncoding("hex"); - ai.start(); - - // On each data chunk... - ai.on('data', (chunk: string) => { - - // If recording, we capture the data. - if (record) { - console.log('AUDIO:Recording...') - audioContainer.input += chunk; - } - - // Else, we don't capture and also clear audioContainer. - else { - if (audioContainer.input.length) { - audioContainer.input = ""; - } - } - - }); - } - - if (!ao) { - - // Initialize and start input stream. - ao = new portAudio.AudioIO({ outOptions: audioOptions }); - 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); -} - - -// ---Audio playback-------------------------------------------- - -// Split Buffer into an array of len-sized Buffers. -function bufSplit(buf: Buffer, len: number): Array { - const chunks = []; - let i = 0; - let L = len; - - while(i < buf.byteLength) { - chunks.push(buf.slice(i, L)); - i = L; - L += len; - } - - return chunks; -} - -// Audio playback. -export function play(input: string): void { - - // Format the audio. - const audio = bufSplit( - Buffer.from(input as string, 'hex'), - 8192 - ); - - // Called on end of write. - const callback = () => { - - // We stop audio playback anim. - backgroundMitt.emit('ipc-renderer', { - endpoint: 'stop-playback-anim' - }); - - } - - write(); - - // Iterate through audio array and write buffers to portAudio writable. - function write() { - let chunk: Buffer; - let ok = true; - let i = 0; - - do { - chunk = audio[i]; - if (i === audio.length - 1) { - // write last chunk. - ao.write(chunk, null, callback); - } else { - // check for backpreassure. - ok = ao.write(chunk, null); - } - i++; - } while (i < audio.length && ok); - - if (i < audio.length) { - // Had to stop early! - // Write some more once it drains. - ao.once('drain', write); - } - } -} - -// ------------------------------------------------------------- - -// Get's called on window close. -// export function stopStream() { -// console.log("AUDIO:Stopping audio stream.") -// if (ai) { -// ai.quit() -// } -// if (ao) { -// ao.quit() -// } -// console.log("AUDIO:Audio closed.") -// } - - diff --git a/src/background/helpers.ts b/src/background/helpers.ts deleted file mode 100644 index bd3d279..0000000 --- a/src/background/helpers.ts +++ /dev/null @@ -1,60 +0,0 @@ -import fs from 'fs'; -import { backgroundMitt } from "@/modules/emitter"; -import { SessionState, WindowState } from "@/types"; - - -export const ipcEmit = (channel: string, payload: any) => { - backgroundMitt.emit('ipc-renderer', { - endpoint: channel, - message: payload - }); -} - -export const loadState = (fileName: string): SessionState => { - let state: SessionState; - - try { - state = JSON.parse(fs.readFileSync(fileName).toString()); - } - - catch (error) { - state = { - key: false, - newMessages: [] - } - } - - return state - -} - -export const loadWinState = (fileName: string): WindowState => { - let state: WindowState; - - try { - state = JSON.parse(fs.readFileSync(fileName).toString()); - } - - catch (error) { - state = { - width: 600, - height: 500, - x: null, - y: null, - } - } - - return state - -} - -// Save session or window state. -export const saveToJson = (fileName: string, data: any) => { - - fs.writeFile(fileName, JSON.stringify(data), (err) => { - if (err) { - console.log("Error when saving to json.") - } - }) - -} \ No newline at end of file diff --git a/src/background/init.ts b/src/background/init.ts deleted file mode 100644 index b4f1240..0000000 --- a/src/background/init.ts +++ /dev/null @@ -1,94 +0,0 @@ - -"use strict"; - -import { app, dialog } from "electron"; -import { createWindow } from './window'; -import { initSession } from './session'; -import { initAudioIO } from './audio'; -import { backgroundMitt } from '@/modules/emitter'; - -let win: boolean; - -// Listen for window creation. -backgroundMitt.on('window-active', (state: boolean) => { - win = state; -}); - -// Auto updating. -const { autoUpdater } = require('electron-updater') -autoUpdater.requestHeaders = { 'PRIVATE-TOKEN': 'mvvgWYwWnot4bisiQMh_' } - -autoUpdater.on('update-available', (info: any) => { - console.log(`Update available: ${info.version}`) -}) - -autoUpdater.on('update-downloaded', (info: any) => { - - const updateDialog = { - type: 'info', - buttons: ['Restart', 'Later'], - title: 'Application Update', - message: info.version, - detail: 'A new version has been downloaded. Restart the application to apply the updates.' - } - - dialog.showMessageBox(updateDialog).then((returnValue) => { - if (returnValue.response === 0) autoUpdater.quitAndInstall() - }) - -}) - -// Run when electron app is initialized. -async function main() { - console.log("MAIN:Initializing Electron App.") - - // Must wait til window is created. - await createWindow(); - - // Instantiate socket session with crimata-platorm. - initSession(); - - // Begin audio stream. - initAudioIO(); - -} - -// Root function of app. -export function initApp(dev: boolean): void { - - // On initial startup. - app.on("ready", () => { - - // Check for updates every 2min. - setInterval(() => { - autoUpdater.checkForUpdates() - }, 5000) // 5s for development. - - main() - }); - - // Must keep to ensure app doesn't quit on close. - app.on("before-quit", () => { - }); - - // Must keep to ensure app doesn't quit on close. - app.on("window-all-closed", () => { - }); - - // When user clicks app icon (re-open) - app.on("activate", () => { - - if (!win) { - createWindow(); - } - - }); - - // Exit cleanly on request from parent process in development mode. - if (dev) { - process.on("SIGTERM", () => { - app.quit(); - }); - } -} - diff --git a/src/background/session.ts b/src/background/session.ts deleted file mode 100644 index 35773c8..0000000 --- a/src/background/session.ts +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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, saveToJson } from './helpers'; -import { ipcMain, IpcMainEvent, IpcMainInvokeEvent } from "electron"; - -import useWebSockets from "@/modules/websockets"; - -import { play } from "./audio"; -import { renderMessage } from "@/modules/message"; -import { AuthProtocol, SessionState, Profile } 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) - } - - // Standard message. - else 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) - } - } - -}; - -// 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); - -// 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) - } - -} - -// Call this to initialize session with Crimata servers. -export const initSession = () => { - 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}`) - - // Open socket connection. - createSocket() - - // 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); - - // Keep win up-to-date. - backgroundMitt.on('window-active', (state: boolean) => { - win = state; - }); - -} diff --git a/src/components/controllers/audioCtrl.ts b/src/components/controllers/audioCtrl.ts deleted file mode 100644 index c9efaa9..0000000 --- a/src/components/controllers/audioCtrl.ts +++ /dev/null @@ -1,111 +0,0 @@ -import anime from "animejs"; -import useMitt from "@/modules/mitt"; -import { useIpc } from '@/modules/ipc'; -import { onMounted, onUnmounted, ref, Ref } from "vue"; -import keyboardNameMap from "../keyBoardMaps/keyboardNameMap"; -import { renderMessage, clientMessage } from '@/modules/message'; - - -function showRecIcon () { - - anime({ - targets: '#recIcon', - opacity: [0, 0.75], - scale: [0.0, 1], - duration: 250, - easing: 'linear', - }) - -} - -function hideRecIcon () { - - anime({ - targets: '#recIcon', - opacity: [0.75, 0], - scale: [1, 0], - duration: 250, - easing: 'linear', - }) - -} - - -export default function useAudioInputController (typing: Ref) { - - // For sending messages. - const { post, invoke } = useIpc(); - const { emitter } = useMitt(); - - // Keepp track of when we are recording. - const recording = ref(false); - - //---Callbacks----------------------------------------------- - - const onKeyDown = (e: KeyboardEvent) => { - const cmd = keyboardNameMap[e.keyCode]; - // console.log(cmd) - - // Start recording on space bar. - if (cmd == "SPACE" && !recording.value && !typing.value) { - - console.log("INPT:Starting record.") - post("start-recording", ""); - - showRecIcon() - recording.value = true; - - } - - } - - const onKeyUp = async (e: KeyboardEvent) => { - const cmd = keyboardNameMap[e.keyCode]; - - // Stop recording on space up. - if (cmd == "SPACE" && recording.value) { - - // Create a message. - const message = renderMessage( - "", - "", - "", - "sf" - ) - - // Render it immediately. - emitter.emit("self-message", message); - - // 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); - - hideRecIcon() - recording.value = false; - - } - - } - - //----------------------------------------------------------- - - onMounted(() => { - window.addEventListener("keydown", onKeyDown); - window.addEventListener("keyup", onKeyUp); - }) - - onUnmounted(() => { - window.removeEventListener("keydown", onKeyDown); - window.removeEventListener("keyup", onKeyUp); - }); - - - return { - recording - } - -} diff --git a/src/components/keyBoardMaps/keyboardCharMap.ts b/src/components/keyBoardMaps/keyboardCharMap.ts deleted file mode 100644 index 102e9c3..0000000 --- a/src/components/keyBoardMaps/keyboardCharMap.ts +++ /dev/null @@ -1,263 +0,0 @@ -// This has the UnShifted and Shifted characters that each key maps to -// Ones that are to be ignored for character input are empty. -const keyboardCharMap = [ - ["", ""], // [0] - ["", ""], // [1] - ["", ""], // [2] - ["", ""], // [3] - ["", ""], // [4] - ["", ""], // [5] - ["", ""], // [6] - ["", ""], // [7] - ["", ""], // [8] - ["", ""], // [9] - ["", ""], // [10] - ["", ""], // [11] - ["", ""], // [12] - ["\r", "\r"], // [13] - MOST control characters are ignored. This one (Carriage Return, or "Enter") is significant! - ["", ""], // [14] - ["", ""], // [15] - ["", ""], // [16] - ["", ""], // [17] - ["", ""], // [18] - ["", ""], // [19] - ["", ""], // [20] - ["", ""], // [21] - ["", ""], // [22] - ["", ""], // [23] - ["", ""], // [24] - ["", ""], // [25] - ["", ""], // [26] - ["", ""], // [27] - ["", ""], // [28] - ["", ""], // [29] - ["", ""], // [30] - ["", ""], // [31] - [" ", " "], // [32] // SPACE! Don't "clean it up" and remove the space! - ["", ""], // [33] - ["", ""], // [34] - ["", ""], // [35] - ["", ""], // [36] - ["", ""], // [37] - ["", ""], // [38] - ["", ""], // [39] - ["", ""], // [40] - ["", ""], // [41] - ["", ""], // [42] - ["", ""], // [43] - ["", ""], // [44] - ["", ""], // [45] - ["", ""], // [46] - ["", ""], // [47] - ["0", ")"], // [48] - ["1", "!"], // [49] - ["2", "@"], // [50] - ["3", "#"], // [51] - ["4", "$"], // [52] - ["5", "%"], // [53] - ["6", "^"], // [54] - ["7", "&"], // [55] - ["8", "*"], // [56] - ["9", "("], // [57] - ["", ""], // [58] - [";", ":"], // [59] - ["<", ""], // [60] - ["=", ""], // [61] - [">", ""], // [62] - ["?", ""], // [63] shifted; else "/" - ["", ""], // [64] - ["a", "A"], // [65] - ["b", "B"], // [66] - ["c", "C"], // [67] - ["d", "D"], // [68] - ["e", "E"], // [69] - ["f", "F"], // [70] - ["g", "G"], // [71] - ["h", "H"], // [72] - ["i", "I"], // [73] - ["j", "J"], // [74] - ["k", "K"], // [75] - ["l", "L"], // [76] - ["m", "M"], // [77] - ["n", "N"], // [78] - ["o", "O"], // [79] - ["p", "P"], // [80] - ["q", "Q"], // [81] - ["r", "R"], // [82] - ["s", "S"], // [83] - ["t", "T"], // [84] - ["u", "U"], // [85] - ["v", "V"], // [86] - ["w", "W"], // [87] - ["x", "X"], // [88] - ["y", "Y"], // [89] - ["z", "Z"], // [90] - ["", ""], // [91] Windows Key (Windows) or Command Key (Mac) - ["", ""], // [92] - ["", ""], // [93] - ["", ""], // [94] - ["", ""], // [95] - // Number Keypad Entries... - ["0", ""], // [96] - ["1", ""], // [97] - ["2", ""], // [98] - ["3", ""], // [99] - ["4", ""], // [100] - ["5", ""], // [101] - ["6", ""], // [102] - ["7", ""], // [103] - ["8", ""], // [104] - ["9", ""], // [105] - ["*", ""], // [106] - ["+", ""], // [107] - ["", ""], // [108] - ["-", ""], // [109] - [".", ""], // [110] - ["/", ""], // [111] - - ["", ""], // [112] - ["", ""], // [113] - ["", ""], // [114] - ["", ""], // [115] - ["", ""], // [116] - ["", ""], // [117] - ["", ""], // [118] - ["", ""], // [119] - ["", ""], // [120] - ["", ""], // [121] - ["", ""], // [122] - ["", ""], // [123] - ["", ""], // [124] - ["", ""], // [125] - ["", ""], // [126] - ["", ""], // [127] - ["", ""], // [128] - ["", ""], // [129] - ["", ""], // [130] - ["", ""], // [131] - ["", ""], // [132] - ["", ""], // [133] - ["", ""], // [134] - ["", ""], // [135] - ["", ""], // [136] - ["", ""], // [137] - ["", ""], // [138] - ["", ""], // [139] - ["", ""], // [140] - ["", ""], // [141] - ["", ""], // [142] - ["", ""], // [143] - ["", ""], // [144] - ["", ""], // [145] - ["", ""], // [146] - ["", ""], // [147] - ["", ""], // [148] - ["", ""], // [149] - ["", ""], // [150] - ["", ""], // [151] - ["", ""], // [152] - ["", ""], // [153] - ["", ""], // [154] - ["", ""], // [155] - ["", ""], // [156] - ["", ""], // [157] - ["", ""], // [158] - ["", ""], // [159] - ["", ""], // [160] - ["", ""], // [161] - ["", ""], // [162] - ["", ""], // [163] - ["", ""], // [164] - ["", ""], // [165] - ["", ""], // [166] - ["", ""], // [167] - ["", ""], // [168] - ["", ""], // [169] - ["", ""], // [170] - ["", ""], // [171] - ["", ""], // [172] - ["", ""], // [173] - ["", ""], // [174] - ["", ""], // [175] - ["", ""], // [176] - ["", ""], // [177] - ["", ""], // [178] - ["", ""], // [179] - ["", ""], // [180] - ["", ""], // [181] - ["", ""], // [182] - ["", ""], // [183] - ["", ""], // [184] - ["", ""], // [185] - [";", ":"], // [186] - ["=", "+"], // [187] - [",", "<"], // [188] - ["-", "_"], // [189] - [".", ">"], // [190] - ["/", "?"], // [191] - ["`", "~"], // [192] - ["", ""], // [193] - ["", ""], // [194] - ["", ""], // [195] - ["", ""], // [196] - ["", ""], // [197] - ["", ""], // [198] - ["", ""], // [199] - ["", ""], // [200] - ["", ""], // [201] - ["", ""], // [202] - ["", ""], // [203] - ["", ""], // [204] - ["", ""], // [205] - ["", ""], // [206] - ["", ""], // [207] - ["", ""], // [208] - ["", ""], // [209] - ["", ""], // [210] - ["", ""], // [211] - ["", ""], // [212] - ["", ""], // [213] - ["", ""], // [214] - ["", ""], // [215] - ["", ""], // [216] - ["", ""], // [217] - ["", ""], // [218] - ["[", "{"], // [219] - ["\\", "|"], // [220] - ["]", "}"], // [221] - ["'", '"'], // [222] - ["", ""], // [223] - ["", ""], // [224] - ["", ""], // [225] - ["", ""], // [226] - ["", ""], // [227] - ["", ""], // [228] - ["", ""], // [229] - ["", ""], // [230] - ["", ""], // [231] - ["", ""], // [232] - ["", ""], // [233] - ["", ""], // [234] - ["", ""], // [235] - ["", ""], // [236] - ["", ""], // [237] - ["", ""], // [238] - ["", ""], // [239] - ["", ""], // [240] - ["", ""], // [241] - ["", ""], // [242] - ["", ""], // [243] - ["", ""], // [244] - ["", ""], // [245] - ["", ""], // [246] - ["", ""], // [247] - ["", ""], // [248] - ["", ""], // [249] - ["", ""], // [250] - ["", ""], // [251] - ["", ""], // [252] - ["", ""], // [253] - ["", ""], // [254] - ["", ""] // [255] -]; -export default keyboardCharMap; diff --git a/src/components/keyBoardMaps/keyboardNameMap.ts b/src/components/keyBoardMaps/keyboardNameMap.ts deleted file mode 100644 index 8f385ae..0000000 --- a/src/components/keyBoardMaps/keyboardNameMap.ts +++ /dev/null @@ -1,261 +0,0 @@ -// names of known key codes (0-255) -const keyboardNameMap = [ - "", // [0] - "", // [1] - "", // [2] - "CANCEL", // [3] - "", // [4] - "", // [5] - "HELP", // [6] - "", // [7] - "BACK_SPACE", // [8] - "TAB", // [9] - "", // [10] - "", // [11] - "CLEAR", // [12] - "ENTER", // [13] - "ENTER_SPECIAL", // [14] - "", // [15] - "SHIFT", // [16] - "CONTROL", // [17] - "ALT", // [18] - "PAUSE", // [19] - "CAPS_LOCK", // [20] - "KANA", // [21] - "EISU", // [22] - "JUNJA", // [23] - "FINAL", // [24] - "HANJA", // [25] - "", // [26] - "ESCAPE", // [27] - "CONVERT", // [28] - "NONCONVERT", // [29] - "ACCEPT", // [30] - "MODECHANGE", // [31] - "SPACE", // [32] - "PAGE_UP", // [33] - "PAGE_DOWN", // [34] - "END", // [35] - "HOME", // [36] - "LEFT", // [37] - "UP", // [38] - "RIGHT", // [39] - "DOWN", // [40] - "SELECT", // [41] - "PRINT", // [42] - "EXECUTE", // [43] - "PRINTSCREEN", // [44] - "INSERT", // [45] - "DELETE", // [46] - "", // [47] - "0", // [48] - "1", // [49] - "2", // [50] - "3", // [51] - "4", // [52] - "5", // [53] - "6", // [54] - "7", // [55] - "8", // [56] - "9", // [57] - "COLON", // [58] - "SEMICOLON", // [59] - "LESS_THAN", // [60] - "EQUALS", // [61] - "GREATER_THAN", // [62] - "QUESTION_MARK", // [63] - "AT", // [64] - "A", // [65] - "B", // [66] - "C", // [67] - "D", // [68] - "E", // [69] - "F", // [70] - "G", // [71] - "H", // [72] - "I", // [73] - "J", // [74] - "K", // [75] - "L", // [76] - "M", // [77] - "N", // [78] - "O", // [79] - "P", // [80] - "Q", // [81] - "R", // [82] - "S", // [83] - "T", // [84] - "U", // [85] - "V", // [86] - "W", // [87] - "X", // [88] - "Y", // [89] - "Z", // [90] - "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac) - "", // [92] - "CONTEXT_MENU", // [93] - "", // [94] - "SLEEP", // [95] - "NUMPAD0", // [96] - "NUMPAD1", // [97] - "NUMPAD2", // [98] - "NUMPAD3", // [99] - "NUMPAD4", // [100] - "NUMPAD5", // [101] - "NUMPAD6", // [102] - "NUMPAD7", // [103] - "NUMPAD8", // [104] - "NUMPAD9", // [105] - "MULTIPLY", // [106] - "ADD", // [107] - "SEPARATOR", // [108] - "SUBTRACT", // [109] - "DECIMAL", // [110] - "DIVIDE", // [111] - "F1", // [112] - "F2", // [113] - "F3", // [114] - "F4", // [115] - "F5", // [116] - "F6", // [117] - "F7", // [118] - "F8", // [119] - "F9", // [120] - "F10", // [121] - "F11", // [122] - "F12", // [123] - "F13", // [124] - "F14", // [125] - "F15", // [126] - "F16", // [127] - "F17", // [128] - "F18", // [129] - "F19", // [130] - "F20", // [131] - "F21", // [132] - "F22", // [133] - "F23", // [134] - "F24", // [135] - "", // [136] - "", // [137] - "", // [138] - "", // [139] - "", // [140] - "", // [141] - "", // [142] - "", // [143] - "NUM_LOCK", // [144] - "SCROLL_LOCK", // [145] - "WIN_OEM_FJ_JISHO", // [146] - "WIN_OEM_FJ_MASSHOU", // [147] - "WIN_OEM_FJ_TOUROKU", // [148] - "WIN_OEM_FJ_LOYA", // [149] - "WIN_OEM_FJ_ROYA", // [150] - "", // [151] - "", // [152] - "", // [153] - "", // [154] - "", // [155] - "", // [156] - "", // [157] - "", // [158] - "", // [159] - "CIRCUMFLEX", // [160] - "EXCLAMATION", // [161] - "DOUBLE_QUOTE", // [162] - "HASH", // [163] - "DOLLAR", // [164] - "PERCENT", // [165] - "AMPERSAND", // [166] - "UNDERSCORE", // [167] - "OPEN_PAREN", // [168] - "CLOSE_PAREN", // [169] - "ASTERISK", // [170] - "PLUS", // [171] - "PIPE", // [172] - "HYPHEN_MINUS", // [173] - "OPEN_CURLY_BRACKET", // [174] - "CLOSE_CURLY_BRACKET", // [175] - "TILDE", // [176] - "", // [177] - "", // [178] - "", // [179] - "", // [180] - "VOLUME_MUTE", // [181] - "VOLUME_DOWN", // [182] - "VOLUME_UP", // [183] - "", // [184] - "", // [185] - "SEMICOLON", // [186] - "EQUALS", // [187] - "COMMA", // [188] - "MINUS", // [189] - "PERIOD", // [190] - "SLASH", // [191] - "BACK_QUOTE", // [192] - "", // [193] - "", // [194] - "", // [195] - "", // [196] - "", // [197] - "", // [198] - "", // [199] - "", // [200] - "", // [201] - "", // [202] - "", // [203] - "", // [204] - "", // [205] - "", // [206] - "", // [207] - "", // [208] - "", // [209] - "", // [210] - "", // [211] - "", // [212] - "", // [213] - "", // [214] - "", // [215] - "", // [216] - "", // [217] - "", // [218] - "OPEN_BRACKET", // [219] - "BACK_SLASH", // [220] - "CLOSE_BRACKET", // [221] - "QUOTE", // [222] - "", // [223] - "META", // [224] - "ALTGR", // [225] - "", // [226] - "WIN_ICO_HELP", // [227] - "WIN_ICO_00", // [228] - "", // [229] - "WIN_ICO_CLEAR", // [230] - "", // [231] - "", // [232] - "WIN_OEM_RESET", // [233] - "WIN_OEM_JUMP", // [234] - "WIN_OEM_PA1", // [235] - "WIN_OEM_PA2", // [236] - "WIN_OEM_PA3", // [237] - "WIN_OEM_WSCTRL", // [238] - "WIN_OEM_CUSEL", // [239] - "WIN_OEM_ATTN", // [240] - "WIN_OEM_FINISH", // [241] - "WIN_OEM_COPY", // [242] - "WIN_OEM_AUTO", // [243] - "WIN_OEM_ENLW", // [244] - "WIN_OEM_BACKTAB", // [245] - "ATTN", // [246] - "CRSEL", // [247] - "EXSEL", // [248] - "EREOF", // [249] - "PLAY", // [250] - "ZOOM", // [251] - "", // [252] - "PA1", // [253] - "WIN_OEM_CLEAR", // [254] - "" // [255] -]; - -export default keyboardNameMap; diff --git a/src/components/message.vue b/src/components/message.vue deleted file mode 100644 index e69f29c..0000000 --- a/src/components/message.vue +++ /dev/null @@ -1,419 +0,0 @@ - - - - - diff --git a/src/components/messenger.vue b/src/components/messenger.vue deleted file mode 100644 index edc50a1..0000000 --- a/src/components/messenger.vue +++ /dev/null @@ -1,115 +0,0 @@ - - - - - diff --git a/src/components/textInput.vue b/src/components/textInput.vue deleted file mode 100644 index 45e1af7..0000000 --- a/src/components/textInput.vue +++ /dev/null @@ -1,49 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/composables/autoUpdate.ts b/src/composables/autoUpdate.ts new file mode 100644 index 0000000..1a6b780 --- /dev/null +++ b/src/composables/autoUpdate.ts @@ -0,0 +1,31 @@ +const { autoUpdater } = require('electron-updater'); + +let win: boolean; + +// Listen for window creation. +backgroundMitt.on('window-active', (state: boolean) => { + win = state; +}); + +// Auto updating. +autoUpdater.requestHeaders = { 'PRIVATE-TOKEN': 'mvvgWYwWnot4bisiQMh_' } + +autoUpdater.on('update-available', (info: any) => { + console.log(`Update available: ${info.version}`) +}) + +autoUpdater.on('update-downloaded', (info: any) => { + + const updateDialog = { + type: 'info', + buttons: ['Restart', 'Later'], + title: 'Application Update', + message: info.version, + detail: 'A new version has been downloaded. Restart the application to apply the updates.' + } + + dialog.showMessageBox(updateDialog).then((returnValue) => { + if (returnValue.response === 0) autoUpdater.quitAndInstall() + }) + +}) \ No newline at end of file diff --git a/src/modules/emitter.ts b/src/composables/useEmitter.ts similarity index 51% rename from src/modules/emitter.ts rename to src/composables/useEmitter.ts index bc91693..f95f328 100644 --- a/src/modules/emitter.ts +++ b/src/composables/useEmitter.ts @@ -1,13 +1,16 @@ -/* eslint-disable */ - -import { Emitter } from "mitt"; // Backend emitter - -type Mitt = Emitter; - +// const EventEmitter = require('events'); - class BackgroundMitt extends EventEmitter { } export const backgroundMitt = new BackgroundMitt(); + +export const ipcEmit = (channel: string, payload: T) => { + backgroundMitt.emit('ipc-renderer', { + channel, + payload + }); +}; + + diff --git a/src/composables/useHttp.ts b/src/composables/useHttp.ts new file mode 100644 index 0000000..6b9ee56 --- /dev/null +++ b/src/composables/useHttp.ts @@ -0,0 +1,51 @@ + +import axios, { AxiosRequestConfig } from 'axios'; +import {config} from "@/config"; + +const baseURL = config.BUSINESS_URL + config.BUSINESS_PREFIX; + +interface Request { + endpoint: string; + query?: Record; + config?: Record; +} + +const makeQuery = (reqQuery: Record) => { + + let result = ''; + + result = '?' + Object.entries(reqQuery) + .map(([ key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) + .join('&') + + return result; +}; + + +export default function useHttp() { + + const api = axios.create({ + baseURL, + withCredentials: true, + }); + + + const post = async (endpoint: string, payload?: Record): Promise => ( + 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 + } +} diff --git a/src/composables/useIpcMain.ts b/src/composables/useIpcMain.ts new file mode 100644 index 0000000..ebfc4bc --- /dev/null +++ b/src/composables/useIpcMain.ts @@ -0,0 +1,82 @@ + +import { ipcMain, IpcMainInvokeEvent, IpcMainEvent } from "electron"; + +export class IpcHandler implements IIpcHandler { + + readonly channel: string; + + readonly _handlerCallback: IpcHandlerCallback; + + constructor(options: { + channel: string; + handlerCallback: IpcHandlerCallback; + }) { + this.channel = options.channel; + this._handlerCallback = options.handlerCallback; + } + + handle() { + this.remove(); + ipcMain.handle(this.channel, this._onInvoke); + } + + remove() { + ipcMain.removeHandler(this.channel); + } + + private _onInvoke = (_e: IpcMainInvokeEvent, payload?: string | null): Promise => { + + return new Promise(async (resolve, reject) => { + + console.log(`[IPC] Handle:${this.channel}`); + + try { + + const params = payload ? JSON.parse(payload) : null; + + const res = await this._handlerCallback(params); + + resolve(res as unknown as ReturnType); + + } catch(e) { + console.log(`[IPC] Error:${this.channel}`); + reject(e); + } + }); + } + +} + + +export class IpcListener implements IIpcListener { + + readonly channel: string; + + readonly _listenerCallback: IpcListenerCallback; + + constructor(options: { + channel: string; + listenerCallback: IpcListenerCallback; + }) { + this.channel = options.channel; + this._listenerCallback = options.listenerCallback; + } + + listen() { + this.remove(); + ipcMain.on(this.channel, this._onPost); + } + + remove() { + ipcMain.removeAllListeners(this.channel); + } + + private _onPost = (_e: IpcMainEvent, payload?: string | null): void => { + + console.log(`[IPC] Post: ${this.channel}`); + + const params = payload ? JSON.parse(payload) : null; + this._listenerCallback(params); + } + +} diff --git a/src/composables/useMessageCanvas.ts b/src/composables/useMessageCanvas.ts new file mode 100644 index 0000000..c85f7ed --- /dev/null +++ b/src/composables/useMessageCanvas.ts @@ -0,0 +1,36 @@ + + + +export default class Canvas { + + messages: Message[]; + + /* seed canvas with messages on init */ + constructor(messages: Message[]) { + this.messages = messages; + ipcEmit("seed-view", this.messages); + } + + /* add a new message to the canvas */ + add(message: Message) { + this.messages.push(message); + ipcEmit("update-view", message); + } + + /* update an existing message */ + update(message: Message) { + + /* get the target message */ + let target_message = this.messages.filter((m: Message) => { + return m.uid = message.uid; + })[0]; + + /* replace the target message */ + if (target_message) { + target_message = message; + ipcEmit("update-view", message); + } + + } + +} diff --git a/src/composables/useSaveToJSON.ts b/src/composables/useSaveToJSON.ts new file mode 100644 index 0000000..06ab4b9 --- /dev/null +++ b/src/composables/useSaveToJSON.ts @@ -0,0 +1,13 @@ + +import {config} from "@/config"; +import fs from 'fs'; + +export const saveToJson = (fileName: string, data: any) => { + + fs.writeFile(config.configPath + fileName, JSON.stringify(data), (err) => { + if (err) { + console.log("Error when saving to json.") + } + }) + +} diff --git a/src/composables/useWebsockets.ts b/src/composables/useWebsockets.ts new file mode 100644 index 0000000..d1cfc02 --- /dev/null +++ b/src/composables/useWebsockets.ts @@ -0,0 +1,89 @@ + +"use strict"; + +import WebSocket from 'ws'; + + +const _connectionCheckTimeout = 4000; +const _reconnectTimeout = 1000; +let _connectionCheckInterval: ReturnType; + + +export default function useWebSockets( + messageCallback: (message: string) => void, + connectionStatusCallback: (alive: boolean) => void, +) { + + let socket: WebSocket; + + const send = async (data: Record): Promise => { + return new Promise((resolve, reject) => { + if (socket) { + if (socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify(data)); + resolve(true); + } + } + reject(false); + }); + } + + const connect = (socketUrl: string, secret: string) => { + + // avoid setting multiple interval; + if (_connectionCheckInterval) clearInterval(_connectionCheckInterval); + + /* create a new socket */ + socket = new WebSocket(socketUrl); + + /* add event listeners */ + socket.on("open", () => { + + socket.send(JSON.stringify({key: secret})); + + // ping server + _connectionCheckInterval = setInterval(() => { + + socket.ping(null, true, (e: Error) => { + if (e) { + socket.close(); + connectionStatusCallback(false); + setTimeout(() => connect(socketUrl, secret), _reconnectTimeout); + } + }); + + }, _connectionCheckTimeout); + + }); + + socket.on("message", (event: WebSocket.MessageEvent) => { + console.log("message received", event); + messageCallback(event.toString()) + }); + + socket.on("close", (event: WebSocket.CloseEvent) => { + connectionStatusCallback(false); + clearInterval(_connectionCheckInterval); + if (!event.wasClean) { + setTimeout(() => connect(socketUrl, secret), _reconnectTimeout); + } + + }); + + socket.on("pong", () => connectionStatusCallback(true)); + + } + + const close = () => { + if (socket) { + socket.close(); + } + } + + return { + connect, + send, + close + }; + +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..855b1b2 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,17 @@ + +import { app } from "electron"; + +const env = process.env; + +const PLATFORM_PORT = env.PLATFORM_PORT || 8760; +const PLATFORM_IP = env.PLATFORM_IP || 'http://127.0.0.1'; + +const BUSINESS_PORT = env.BUSINESS_PORT || 3000; +const BUSINESS_IP = env.BUSINESS_IP || 'http://127.0.0.1'; + +export const config = { + PLATFORM_URL: `${PLATFORM_IP}:${PLATFORM_PORT}`, + BUSINESS_URL: `${BUSINESS_IP}:${BUSINESS_PORT}`, + BUSINESS_PREFIX: '/api', + configPath: app.getPath('userData') +} diff --git a/src/init.ts b/src/init.ts new file mode 100644 index 0000000..9a0fdf6 --- /dev/null +++ b/src/init.ts @@ -0,0 +1,52 @@ +/** + * Entry point for Crimata electron app. + * "Look on my Works, ye Mighty, and despair!" + */ + +"use strict"; + +import { app, protocol } from "electron"; +import createWindow from "./window"; +import main from "./main"; +import { backgroundMitt } from '@/composables/useEmitter'; + +console.log('Starting Crimata electron app.'); + +// Scheme must be registered before the app is ready +protocol.registerSchemesAsPrivileged([ + { scheme: "app", privileges: { secure: true, standard: true } } +]); + +const isDev = require('electron-is-dev'); + +let win: boolean; + +// Listen for window creation. +backgroundMitt.on('window-active', (state: boolean) => { + win = state; +}); + +/* Start main process on ready */ +app.on("ready", async () => { + await main(); +}); + +// Must keep to ensure app doesn't quit on close. +app.on("before-quit", async () => { +}); + +// Must keep to ensure app doesn't quit on close. +app.on("window-all-closed", () => { +}); + +// When user clicks app icon (re-open) +app.on("activate", () => { + if (!win) createWindow(); +}); + +// Exit cleanly on request from parent process in development mode. +if (isDev) { + process.on("SIGTERM", () => { + app.quit(); + }); +} diff --git a/src/ipc/handlers.ts b/src/ipc/handlers.ts new file mode 100644 index 0000000..5529662 --- /dev/null +++ b/src/ipc/handlers.ts @@ -0,0 +1,28 @@ + +"use strict"; + +import { accountLogin, accountLogout, accountProfile } from "@/account"; +import { IpcHandler } from "@/composables/useIpcMain"; +import { flush } from "@/audio"; + + +const LOGIN_CHANNEL = "invoke-account-login"; +const LOGOUT_CHANNEL = "invoke-account-logout"; +const GET_AUDIO_CHANNEL = "invoke-audio-flush"; + +export const loginHandler = new IpcHandler({ + channel: LOGIN_CHANNEL, + handlerCallback: accountLogin +}); + +export const logoutHandler = new IpcHandler({ + channel: LOGOUT_CHANNEL, + handlerCallback: accountLogout +}); + +export const getAudioHandler = new IpcHandler({ + channel: GET_AUDIO_CHANNEL, + handlerCallback: flush +}); + + diff --git a/src/ipc/index.ts b/src/ipc/index.ts new file mode 100644 index 0000000..e6eb90a --- /dev/null +++ b/src/ipc/index.ts @@ -0,0 +1,33 @@ + +"use strict"; + +import * as handlers from "./handlers"; +import * as listeners from "./listeners"; + +const ipcHandlers: IPCHandlers = {}; +const ipcListeners: IPCListeners = {}; + +const _initHandlers = (): void => { + for (const [key, handler] of Object.entries(handlers)) { + if (!(key in ipcHandlers)) { + ipcHandlers[key] = handler; + handler.handle(); + } + } +}; + +const _initListeners = (): void => { + for (const [key, listener] of Object.entries(listeners)) { + if (!(key in ipcListeners)) { + ipcListeners[key] = listener; + listener.listen(); + } + } +}; + +export default function initIpcMain(): void { + _initHandlers(); + _initListeners(); +} + + diff --git a/src/ipc/listeners.ts b/src/ipc/listeners.ts new file mode 100644 index 0000000..8ef5d45 --- /dev/null +++ b/src/ipc/listeners.ts @@ -0,0 +1,24 @@ + +import { IpcListener } from "@/composables/useIpcMain" +import { sendMessage } from '@/session'; +import { collect } from "@/audio"; +import { updateAppState } from "@/account"; + +const CLIENT_MESSAGE_CHANNEL = "post-session-send" +const GET_AUDIO_CHANNEL = "post-audio-collect"; +const APP_MOUNT_CHANNEL = "post-app-mount"; + +export const messageListener = new IpcListener({ + channel: CLIENT_MESSAGE_CHANNEL, + listenerCallback: sendMessage +}); + +export const audioChunkListener = new IpcListener({ + channel: GET_AUDIO_CHANNEL, + listenerCallback: collect +}); + +export const appMountListener = new IpcListener({ + channel: APP_MOUNT_CHANNEL, + listenerCallback: updateAppState +}); diff --git a/src/main.ts b/src/main.ts index 35774f7..a360835 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,15 +1,39 @@ -// src/main.ts +/** + * Where the background logic really begins, gets called by app.onReady(). + * + * Handles authentication. If profile is set, we launch a session, which consis + * of opening a connection with the platform, initializing the audio streams. + * + * The session is primarily an interface between the frontend and the platform, + * relaying messages from one to the other. + * + */ -import App from "./App.vue"; +import initIpcMain from "@/ipc/index"; +import { accountAuth, updateAppState } from "./account"; +import { launchSession } from "./session"; +import createWindow from "./window"; -import mitt from "mitt"; -import { createApp } from "vue"; +let authState: AuthState | null; +export default async function main() { -// Handle events. -const emitter = mitt(); + /* initiate controls for frontend to use when needed */ + initIpcMain(); -const app = createApp(App) + /* launch browser window */ + await createWindow(); -app.provide("mitt", emitter) -app.mount("#app"); + try { + authState = await accountAuth() as AuthState; + } catch(e) { + console.log('AUTH:', e); + authState = null; + } finally { + if (authState) { + launchSession(authState.token as string); + } + updateAppState(); + } + +} diff --git a/src/modules/ipc.ts b/src/modules/ipc.ts deleted file mode 100644 index 36658de..0000000 --- a/src/modules/ipc.ts +++ /dev/null @@ -1,21 +0,0 @@ - -export const useIpc = () => { - - const invoke = async (endpoint: string, payload: any) => { - try { - const res = await window.ipcRenderer.invoke(endpoint, payload); - return res; - } catch (e) { - throw e; - } - } - - const post = (endpoint: string, payload: any) => { - window.ipcRenderer.send(endpoint, payload); - }; - - return { - invoke, - post - } -} diff --git a/src/modules/message.ts b/src/modules/message.ts deleted file mode 100644 index 71beb70..0000000 --- a/src/modules/message.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { - RenderMessage, - ClientMessage, - ClientRequest, - AuthRequest, - LogoutRequest -} from "@/types"; - -import { v4 as uuidv4 } from 'uuid'; - -function getTimeStamp(): number { - const currentdate = new Date(); - return currentdate.getTime(); -} - -// Create a RenderMessage object. -export const renderMessage = (text: boolean | string, audio: boolean | string, context: string, modifier: string): RenderMessage => ( - { - content: { - text: text, - audio: audio - }, - context: context, - modifier: modifier, - time: getTimeStamp(), - uid: uuidv4(), - isChild: "none", - seen: false, - newMessage: false - } -) - -export const clientMessage = (text: string, audio: string | boolean, uid: string): ClientMessage => ( - { - audio, - text, - uid - } -) - -export const clientRequest = (intent: string, params: object, epic: string | boolean): ClientRequest => ( - { - intent: intent, - params: params, - epic: epic, - confidence: 1.0 - } -) - -export const authRequest = (key: boolean | string, usr: boolean | string, pwd: boolean | string): AuthRequest => ( - { - key, - usr, - pwd - } -) - -export const logoutRequest = (): LogoutRequest => ( - { - logout: true - } -) \ No newline at end of file diff --git a/src/modules/messages.ts b/src/modules/messages.ts deleted file mode 100644 index 1d2c4b4..0000000 --- a/src/modules/messages.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { ref } from 'vue'; -import useScroll from "@/modules/scroll"; -import { RenderMessage, Annotation } from "@/types"; - -const messages = ref(new Map()); - -const addMessage = (message: RenderMessage) => { - messages.value.set(message.uid, message) -} - -const updateMessage = (annotation: Annotation) => { - const message = messages.value.get(annotation.uid) - message.context = annotation.context - message.content.text = annotation.text -} - -const loadSavedMessages = () => { - const rawData = window.localStorage.getItem("crimata_messages"); - if (rawData) { - const messageData = JSON.parse(rawData) - messages.value = new Map(Object.entries(messageData)); - } -} - -const saveMessages = () => { - const messageData = Object.fromEntries(messages.value); - window.localStorage.setItem("crimata_messages", JSON.stringify(messageData)); -} - -const isSimmilar = (messageA: RenderMessage, messageB: RenderMessage) => { - if ((Math.abs(messageA.time - messageB.time) < 20000) && (messageA.modifier == messageB.modifier) && (messageA.context == messageB.context)) { - return true - } - return false -} - -const updateGrouping = () => { - console.log("updating grouping") - const refs = Array.from(messages.value.keys()) - - // Get the last three messages. - const first = messages.value.get(refs[refs.length - 1]) - const second = messages.value.get(refs[refs.length - 2]) - const third = messages.value.get(refs[refs.length - 3]) - - // If messages are simmilar, update the classes. - if ((first) && (second)) { - if (isSimmilar(first, second)) { - first.isChild = "last" // i.e. last in group. - second.isChild = "first" - - if (third) { - if ((third.isChild == "first") || (third.isChild == "middle")) { - second.isChild = "middle" - } - } - } - } -} - - -export default function useMessages() { - - // Scroll controller. - const { setScroll, updateScrollRef, adjustScroll } = useScroll("messenger"); - - // Main function for updating the message view. - const updateMessageView = (message: RenderMessage | Annotation) => { - - // Step 1: See if user is scrolled down. - updateScrollRef() - - // Step 2: Add the new content to the view. - if ("content" in message) { - addMessage(message) - } else { - updateMessage(message) - } - - // Step 3: Pop off oldest message (if > 200). - if (messages.value.size >= 200) { - const oldest = Array.from(messages.value.keys()).shift(); - messages.value.delete(oldest); - } - - // Step 4: Update grouping. - updateGrouping() - - // Setp 5: Scroll the view (if scrolled down). - setTimeout(adjustScroll, 20); - - // Step 6: Save the view data. - saveMessages() - - } - - // Seed message view with message history. - const prepMessageView = (newMessages: RenderMessage[]) => { - console.log("MSGR:Prepping messenger view.") - - // Load and render saved messages and immediately scroll to bottom. - loadSavedMessages() - setTimeout(setScroll.bind(false), 10); - - // Render new messages, then wait 1s to scroll. - if (newMessages.length) { - - console.log("MSGR:Adding new messages") - - newMessages.forEach(message => { - message.newMessage = true; - addMessage(message) - }) - - setTimeout(setScroll.bind(true), 1000); - - } - } - - return { - messages, - prepMessageView, - updateMessageView - } -} \ No newline at end of file diff --git a/src/modules/mitt.ts b/src/modules/mitt.ts deleted file mode 100644 index 4f3f448..0000000 --- a/src/modules/mitt.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { inject } from "vue"; -import { Emitter } from "mitt"; - -// Frontend emitter - -type Mitt = Emitter; - -let emitter: Mitt; - -export default function useMitt() { - - const emitterInject: Mitt | undefined = inject("mitt"); - if (emitterInject) { - emitter = emitterInject; - } - return { - emitter - } -} \ No newline at end of file diff --git a/src/modules/scroll.ts b/src/modules/scroll.ts deleted file mode 100644 index 58370f7..0000000 --- a/src/modules/scroll.ts +++ /dev/null @@ -1,50 +0,0 @@ - - -export default function useScroll(element: string) { - - let isScrolledToBottom: boolean; - - // Set the initial scroll position. - const setScroll = (smooth: boolean) => { - const view = document.getElementById(element) - - if (view) { - view.scrollTo({ - top: view.scrollHeight - view.clientHeight, - behavior: (smooth) ? 'smooth' : 'auto' - }); - } - } - - // Update isScrolledToBottom - const updateScrollRef = () => { - const view = document.getElementById(element) - - if (view) { - isScrolledToBottom = view.scrollHeight - view.clientHeight <= view.scrollTop + 1 - } - - } - - // Adjust scroll after we add content to the messenger. - const adjustScroll = () => { - const view = document.getElementById(element) - - if (view) { - if (isScrolledToBottom) { - view.scrollTo({ - top: view.scrollHeight - view.clientHeight, - behavior: 'smooth' - }); - } - } - - } - - return { - updateScrollRef, - adjustScroll, - setScroll, - } - -} diff --git a/src/modules/websockets.ts b/src/modules/websockets.ts deleted file mode 100644 index 9af0448..0000000 --- a/src/modules/websockets.ts +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -import WebSocket from 'ws'; -import { ipcMain } from "electron"; - -let socket: WebSocket; - - -// Run every time we want to connect to backend. -export default function useWebSockets(receiveCallback: (s: string) => any, openCallback: () => any) { - - // Returns bool (sucess or fail). - const sendMessage = (data: any) => { - console.log("WS:Sending message: ", data) - - if (socket.readyState !== 1) { - return false - } - - else { - socket.send(JSON.stringify(data)) - return true - } - - } - - const onOpen = (event: WebSocket.OpenEvent) => { - - console.log("WS:Connected to WS Server!"); - - openCallback() - - } - - const onServerMessage = (event: WebSocket.MessageEvent) => { - - console.log("WS:Message received: ", event.data); - - receiveCallback(event.data.toString()) - - } - - const onClose = (event: WebSocket.CloseEvent) => { - console.log("WS:Socket closed normally.") - } - - // Reconnect automatically on error. - const onError = (event: WebSocket.ErrorEvent) => { - console.log("WS:WebSocket error: ", event.message); - - console.log("Attempting reconnect in 1s.") - setTimeout(createSocket, 1000) - } - - const createSocket = () => { - socket = new WebSocket(`ws://127.0.0.1:8760`) - - // Add listeners. - socket.addEventListener("open", onOpen) - socket.addEventListener("message", onServerMessage) - socket.addEventListener("close", onClose) - socket.addEventListener("error", onError) - - console.log("WS:New socket created.") - } - - return { - createSocket, - sendMessage - } - -} \ No newline at end of file diff --git a/src/render/App.vue b/src/render/App.vue new file mode 100644 index 0000000..686591b --- /dev/null +++ b/src/render/App.vue @@ -0,0 +1,76 @@ + + + + + diff --git a/src/render/components/bubble.vue b/src/render/components/bubble.vue new file mode 100644 index 0000000..982cef3 --- /dev/null +++ b/src/render/components/bubble.vue @@ -0,0 +1,331 @@ + + + + + + + diff --git a/src/render/components/controllers/bubble.control.ts b/src/render/components/controllers/bubble.control.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/render/components/controllers/helpers.ts b/src/render/components/controllers/helpers.ts new file mode 100644 index 0000000..23976a8 --- /dev/null +++ b/src/render/components/controllers/helpers.ts @@ -0,0 +1,102 @@ +import { ref } from "vue"; +import anime from "animejs"; +import { v4 as uuidv4 } from 'uuid'; + + +export function animateTextInput () { + + const side = ref("right"); + + function show () { + const t1 = (side.value === "right") ? 50 : -70; + const t2 = (side.value === "right") ? 110 : -130; + + anime({ + targets: '#textInput', + opacity: [0, 1], + translateX: [t1, t2], + scale: [0.3, 1], + duration: 500, + easing: 'easeOutExpo', + }) + + } + + function hide () { + const t = (side.value === "right") ? 50 : -80; + + anime({ + targets: '#textInput', + opacity: [1, 0], + translateX: t, + scale: 0.3, + duration: 500, + easing: 'easeOutExpo', + }) + + } + + function switchSide () { + const t = (side.value === "right") ? -130 : 110; + + anime({ + targets: '#textInput', + translateX: t, + duration: 500, + easing: 'easeOutExpo', + }) + + } + + return { + side, + show, + hide, + switchSide + }; + +} + +export function animateAudioInput () { + + function show () { + anime({ + targets: '#recIcon', + opacity: [0, 0.75], + scale: [0.0, 1], + duration: 250, + easing: 'linear', + }) + } + + function hide () { + anime({ + targets: '#recIcon', + opacity: [0.75, 0], + scale: [1, 0], + duration: 250, + easing: 'linear', + }) + } + + return { + show, + hide + }; + +} + + +export function newMessage ({ + text=false, + audio=false, + context=false, + uid=uuidv4() +}) { + return { + text: text, + audio: audio, + context: context, + uid: uid + }; +} diff --git a/src/render/components/controllers/inputItem.control.audio.ts b/src/render/components/controllers/inputItem.control.audio.ts new file mode 100644 index 0000000..facf30c --- /dev/null +++ b/src/render/components/controllers/inputItem.control.audio.ts @@ -0,0 +1,77 @@ +import { onMounted, onUnmounted, ref, Ref } from "vue"; +import { postMessage } from "@/render/ipc"; +import { newMessage, animateAudioInput } from "./helpers"; +import { invokeReturnAudio, postAudioChunk } from "@/render/ipc"; + +export default function useAudioInputController (typing: Ref) { + + const recording = ref(false); + let mediaRecorder: MediaRecorder; + + const { show, hide } = animateAudioInput(); + + // initialize audio + const conf = {audio: true, video: false} + navigator.mediaDevices.getUserMedia(conf).then((stream: MediaStream) => { + + const options = {mimeType: 'audio/webm'}; + mediaRecorder = new MediaRecorder(stream, options); + + // post any mew audio to backend + mediaRecorder.addEventListener('dataavailable', (e: BlobEvent) => { + e.data.arrayBuffer().then((buff: ArrayBuffer) => { + postAudioChunk(buff); + }); + }); + + // get audio and post new message to backend + mediaRecorder.addEventListener('stop', (_e: Event) => { + invokeReturnAudio().then((audio: ArrayBuffer[] | Error) => { + console.log(audio); + // postMessage(newMessage({audio: audio})); + }); + }); + + }); + + // start recording on space bar + const record = () => { + console.log("INPT:Capturing audio...") + mediaRecorder.start(); + recording.value = true; + show() + } + + // stop recording and send on release + const stop = () => { + console.log("INPT:Stopping record.") + mediaRecorder.stop(); + recording.value = false; + hide(); + } + + const onKeyDown = (e: KeyboardEvent) => { + if (e.keyCode == 32 && !typing.value) record(); + } + + const onKeyUp = (e: KeyboardEvent) => { + if (e.keyCode == 32 && recording.value) stop(); + } + + //----------------------------------------------------------- + + onMounted(() => { + window.addEventListener("keydown", onKeyDown); + window.addEventListener("keyup", onKeyUp); + }); + + onUnmounted(() => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("keyup", onKeyUp); + }) + + return { + recording + } + +} diff --git a/src/components/controllers/textCtrl.ts b/src/render/components/controllers/inputItem.control.text.ts similarity index 52% rename from src/components/controllers/textCtrl.ts rename to src/render/components/controllers/inputItem.control.text.ts index 7a2e2e8..941ae89 100644 --- a/src/components/controllers/textCtrl.ts +++ b/src/render/components/controllers/inputItem.control.text.ts @@ -1,70 +1,20 @@ -import anime from "animejs"; -import useMitt from "@/modules/mitt"; -import { useIpc } from '@/modules/ipc'; import { Ref, ref, watch, onMounted, onUnmounted } from "vue"; -import keyboardNameMap from "../keyBoardMaps/keyboardNameMap"; -import { clientMessage, renderMessage } from '@/modules/message'; - -//---Animations----------------------------------------------- - -let side = "right"; // Side of parent we are on. - -function showTextInput () { - const t1 = (side === "right") ? 50 : -70; - const t2 = (side === "right") ? 110 : -130; - - anime({ - targets: '#textInput', - opacity: [0, 1], - translateX: [t1, t2], - scale: [0.3, 1], - duration: 500, - easing: 'easeOutExpo', - }) - -} - -function hideTextInput() { - const t = (side === "right") ? 50 : -80; - - anime({ - targets: '#textInput', - opacity: [1, 0], - translateX: t, - scale: 0.3, - duration: 500, - easing: 'easeOutExpo', - }) - -} - -function switchSide(currentSide: string) { - const t = (currentSide === "right") ? -130 : 110; - - anime({ - targets: '#textInput', - translateX: t, - duration: 500, - easing: 'easeOutExpo', - }) - -} - -//------------------------------------------------------------ +import { postMessage } from "@/render/ipc"; +import { newMessage, animateTextInput } from "./helpers"; export default function useTextInputController(elementX: Ref) { + let textInput: HTMLInputElement | null; - const { post } = useIpc(); - const { emitter } = useMitt(); + const { side, show, hide, switchSide } = animateTextInput(); let firstKey = true; const typing = ref(false); // Prep inputItem for typing. const prepInput = () => { - showTextInput() + show() typing.value = true } @@ -75,8 +25,8 @@ export default function useTextInputController(elementX: Ref) { textInput.value = ""; textInput.blur(); } - - hideTextInput() + + hide() firstKey = true; typing.value = false; } @@ -85,28 +35,20 @@ export default function useTextInputController(elementX: Ref) { const sendMessage = () => { if (textInput) { - // Create the message. - const message = renderMessage( - textInput.value, - false, - "", - "sf" - ) - - emitter.emit("self-message", message); - // Send it to the backend for processing. - const clientM = clientMessage(textInput.value, false, message.uid); - post('client-message', clientM); + const message = newMessage({ + text: false + }); + + // postMessage(message); clearInput() } } // Keys that are capable of opening the text input (numbers and letters). - const hotKeyRange = keyboardNameMap.slice(47, 91) - const isHotKey = (key: string) => { - if (hotKeyRange.includes(key)) { + const isHotKey = (key: number) => { + if (key >= 47 && key <= 91) { // a letter return true } } @@ -114,10 +56,10 @@ export default function useTextInputController(elementX: Ref) { //---Callbacks----------------------------------------------- const onKeyDown = (e: KeyboardEvent) => { - const key = keyboardNameMap[e.keyCode] - + const key = e.keyCode; + if (textInput) { - + // Only runs on firstKey. if (firstKey) { @@ -131,18 +73,18 @@ export default function useTextInputController(elementX: Ref) { textInput.focus(); // Close input when no text or on ESC. - if ((textInput.value == "") && (!firstKey) && (key === "BACK_SPACE")) { + if ((textInput.value == "") && (!firstKey) && (key === 8)) { // backspace clearInput() return } - if (key === "ESCAPE") { + if (key === 27) { // escape clearInput() return } // Close and send on enter. - if (key === "ENTER") { + if (key === 13) { if (textInput.value) { sendMessage() return @@ -160,20 +102,20 @@ export default function useTextInputController(elementX: Ref) { const winW = window.innerWidth // Logic depends on the side we are on. - if (side === "right") { + if (side.value === "right") { if (winW - elementX < 230) { - switchSide(side) - side = "left" + switchSide() + side.value = "left" } - } + } else { if (winW - elementX > 230) { - switchSide(side) - side = "right" + switchSide() + side.value = "right" } } - + }); onMounted(() => { diff --git a/src/render/components/controllers/messenger.control.ts b/src/render/components/controllers/messenger.control.ts new file mode 100644 index 0000000..b9c3a96 --- /dev/null +++ b/src/render/components/controllers/messenger.control.ts @@ -0,0 +1,38 @@ +import { ref } from 'vue'; +import useScroll from "@/render/composables/useScroll"; + +const messagesRef = ref(); + +/* seed the canvas with messages */ +const seedCanvas = (messages: Message[]) => { + messagesRef.value = messages; +} + +const addMessage = (message: Message) => { + messagesRef.value.push(message); +} + +const updateMessage = (message: Message) => { + + let target_message = messagesRef.value.filter((m: Message) => { + return m.uid = message.uid; + })[0]; + + if (target_message) { + target_message = message; + } + +} + +export default function useMessages() { + + const { updateScrollRef, adjustScroll } = useScroll("messenger"); + + return { + messagesRef, + seedCanvas, + addMessage, + updateMessage + }; + +} diff --git a/src/render/components/header.vue b/src/render/components/header.vue new file mode 100644 index 0000000..63716c8 --- /dev/null +++ b/src/render/components/header.vue @@ -0,0 +1,89 @@ + + + + + diff --git a/src/components/inputItem.vue b/src/render/components/inputItem.vue similarity index 84% rename from src/components/inputItem.vue rename to src/render/components/inputItem.vue index 861d7c1..edd844f 100644 --- a/src/components/inputItem.vue +++ b/src/render/components/inputItem.vue @@ -6,14 +6,17 @@ :style="{ top: `${elementY}px`, left: `${elementX}px` }" >
{{ initials }}
- + - + @@ -24,24 +27,19 @@ + + diff --git a/src/components/settings.vue b/src/render/components/settings.vue similarity index 80% rename from src/components/settings.vue rename to src/render/components/settings.vue index a70b797..cf881c3 100644 --- a/src/components/settings.vue +++ b/src/render/components/settings.vue @@ -1,8 +1,8 @@