From a8dc524e6ad5b734d43053f2a51ba151d43af708 Mon Sep 17 00:00:00 2001 From: Core <64542347+coredev-uk@users.noreply.github.com> Date: Tue, 1 Feb 2022 05:31:19 +0000 Subject: [PATCH] used typescript the way its supposed to be used --- package.json | 2 + src/main/base/app.ts | 136 ++++---- src/main/base/{win.ts => browserwindow.ts} | 353 +++++++++------------ src/main/base/plugins.ts | 11 +- src/main/base/store.ts | 38 +-- src/main/base/utils.ts | 61 ++++ src/main/index.ts | 61 ++-- 7 files changed, 330 insertions(+), 332 deletions(-) rename src/main/base/{win.ts => browserwindow.ts} (59%) create mode 100644 src/main/base/utils.ts diff --git a/package.json b/package.json index bcefe980..fc3868c3 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,7 @@ "mdns-js": "github:bitfocus/node-mdns-js", "mpris-service": "^2.1.2", "music-metadata": "^7.11.4", + "node-gyp": "^8.4.1", "qrcode": "^1.5.0", "qrcode-terminal": "^0.12.0", "react": "^17.0.2", @@ -59,6 +60,7 @@ "devDependencies": { "@types/discord-rpc": "^4.0.0", "@types/express": "^4.17.13", + "@types/qrcode-terminal": "^0.12.0", "@types/ws": "^8.2.2", "electron": "https://github.com/castlabs/electron-releases.git", "electron-builder": "^22.14.5", diff --git a/src/main/base/app.ts b/src/main/base/app.ts index fb72d057..2a6d13a9 100644 --- a/src/main/base/app.ts +++ b/src/main/base/app.ts @@ -1,5 +1,6 @@ -import * as electron from 'electron'; +import {app, Menu, nativeImage, Tray} from 'electron'; import * as path from 'path'; +import {utils} from './utils' export class AppEvents { private protocols: string[] = [ @@ -11,79 +12,76 @@ export class AppEvents { "music" ] private plugin: any = undefined; - private store: any = undefined; - private win: any = undefined; private tray: any = undefined; private i18n: any = undefined; - constructor(store: any) { - this.store = store - this.start(store); + constructor() { + this.start(); } /** * Handles all actions that occur for the app on start (Mainly commandline arguments) * @returns {void} */ - private start(store: any): void { + private start(): void { console.info('[AppEvents] App started'); /********************************************************************************************************************** * Startup arguments handling **********************************************************************************************************************/ - if (electron.app.commandLine.hasSwitch('version') || electron.app.commandLine.hasSwitch('v')) { - console.log(electron.app.getVersion()) - electron.app.exit() + if (app.commandLine.hasSwitch('version') || app.commandLine.hasSwitch('v')) { + console.log(app.getVersion()) + app.exit() } // Verbose Check - if (electron.app.commandLine.hasSwitch('verbose')) { + if (app.commandLine.hasSwitch('verbose')) { console.log("[Cider] User has launched the application with --verbose"); } // Log File Location - if (electron.app.commandLine.hasSwitch('log') || electron.app.commandLine.hasSwitch('l')) { - console.log(path.join(electron.app.getPath('userData'), 'logs')) - electron.app.exit() + if (app.commandLine.hasSwitch('log') || app.commandLine.hasSwitch('l')) { + console.log(path.join(app.getPath('userData'), 'logs')) + app.exit() } // Expose GC - electron.app.commandLine.appendSwitch('js-flags', '--expose_gc') + app.commandLine.appendSwitch('js-flags', '--expose_gc') if (process.platform === "win32") { - electron.app.setAppUserModelId(electron.app.getName()) // For notification name + app.setAppUserModelId(app.getName()) // For notification name } /*********************************************************************************************************************** * Commandline arguments **********************************************************************************************************************/ - switch (store.visual.hw_acceleration) { + switch (utils.getStoreValue('visual.hw_acceleration') as string) { default: case "default": - electron.app.commandLine.appendSwitch('enable-accelerated-mjpeg-decode') - electron.app.commandLine.appendSwitch('enable-accelerated-video') - electron.app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds') - electron.app.commandLine.appendSwitch('ignore-gpu-blacklist') - electron.app.commandLine.appendSwitch('enable-native-gpu-memory-buffers') - electron.app.commandLine.appendSwitch('enable-accelerated-video-decode'); - electron.app.commandLine.appendSwitch('enable-gpu-rasterization'); - electron.app.commandLine.appendSwitch('enable-native-gpu-memory-buffers'); - electron.app.commandLine.appendSwitch('enable-oop-rasterization'); + app.commandLine.appendSwitch('enable-accelerated-mjpeg-decode') + app.commandLine.appendSwitch('enable-accelerated-video') + app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds') + app.commandLine.appendSwitch('ignore-gpu-blacklist') + app.commandLine.appendSwitch('enable-native-gpu-memory-buffers') + app.commandLine.appendSwitch('enable-accelerated-video-decode'); + app.commandLine.appendSwitch('enable-gpu-rasterization'); + app.commandLine.appendSwitch('enable-native-gpu-memory-buffers'); + app.commandLine.appendSwitch('enable-oop-rasterization'); break; case "webgpu": console.info("WebGPU is enabled."); - electron.app.commandLine.appendSwitch('enable-unsafe-webgpu') + app.commandLine.appendSwitch('enable-unsafe-webgpu') break; case "disabled": console.info("Hardware acceleration is disabled."); - electron.app.commandLine.appendSwitch('disable-gpu') + app.commandLine.appendSwitch('disable-gpu') break; } if (process.platform === "linux") { - electron.app.commandLine.appendSwitch('disable-features', 'MediaSessionService'); + app.commandLine.appendSwitch('disable-features', 'MediaSessionService'); } /*********************************************************************************************************************** @@ -92,12 +90,12 @@ export class AppEvents { if (process.defaultApp) { if (process.argv.length >= 2) { this.protocols.forEach((protocol: string) => { - electron.app.setAsDefaultProtocolClient(protocol, process.execPath, [path.resolve(process.argv[1])]) + app.setAsDefaultProtocolClient(protocol, process.execPath, [path.resolve(process.argv[1])]) }) } } else { this.protocols.forEach((protocol: string) => { - electron.app.setAsDefaultProtocolClient(protocol) + app.setAsDefaultProtocolClient(protocol) }) } @@ -113,11 +111,8 @@ export class AppEvents { console.log('[AppEvents] App ready'); } - public bwCreated(win: Electron.BrowserWindow, i18n: any) { - this.win = win - this.i18n = i18n - - electron.app.on('open-url', (event, url) => { + public bwCreated() { + app.on('open-url', (event, url) => { event.preventDefault() if (this.protocols.some((protocol: string) => url.includes(protocol))) { this.LinkHandler(url) @@ -145,9 +140,9 @@ export class AppEvents { let authURI = arg.split('/auth/')[1] if (authURI.startsWith('lastfm')) { // If we wanted more auth options const authKey = authURI.split('lastfm?token=')[1]; - this.store.set('lastfm.enabled', true); - this.store.set('lastfm.auth_token', authKey); - this.win.webContents.send('LastfmAuthenticated', authKey); + utils.setStoreValue('lastfm.enabled', true); + utils.setStoreValue('lastfm.auth_token', authKey); + utils.getWindow().webContents.send('LastfmAuthenticated', authKey); this.plugin.callPlugin('lastfm', 'authenticate', authKey); } } @@ -164,7 +159,7 @@ export class AppEvents { for (const [key, value] of Object.entries(mediaType)) { if (playParam.includes(key)) { const id = playParam.split(key)[1] - this.win.webContents.send('play', value, id) + utils.getWindow().webContents.send('play', value, id) console.debug(`[LinkHandler] Attempting to load ${value} by id: ${id}`) } } @@ -173,7 +168,7 @@ export class AppEvents { console.log(arg) let url = arg.split('//')[1] console.warn(`[LinkHandler] Attempting to load url: ${url}`); - this.win.webContents.send('play', 'url', url) + utils.getWindow().webContents.send('play', 'url', url) } } @@ -183,13 +178,13 @@ export class AppEvents { private InstanceHandler() { // Detects of an existing instance is running (So if the lock has been achieved, no existing instance has been found) - const gotTheLock = electron.app.requestSingleInstanceLock() + const gotTheLock = app.requestSingleInstanceLock() if (!gotTheLock) { // Runs on the new instance if another instance has been found console.log('[Cider] Another instance has been found, quitting.') - electron.app.quit() + app.quit() } else { // Runs on the first instance if no other instance has been found - electron.app.on('second-instance', (_event, startArgs) => { + app.on('second-instance', (_event, startArgs) => { console.log("[InstanceHandler] (second-instance) Instance started with " + startArgs.toString()) startArgs.forEach(arg => { @@ -199,10 +194,10 @@ export class AppEvents { this.LinkHandler(arg) } else if (arg.includes("--force-quit")) { console.warn('[InstanceHandler] (second-instance) Force Quit found. Quitting App.'); - electron.app.quit() - } else if (this.win) { - if (this.win.isMinimized()) this.win.restore() - this.win.focus() + app.quit() + } else if (utils.getWindow()) { + if (utils.getWindow().isMinimized()) utils.getWindow().restore() + utils.getWindow().focus() } }) }) @@ -215,48 +210,50 @@ export class AppEvents { */ private InitTray() { const icons = { - "win32": electron.nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.ico`)).resize({ + "win32": nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.ico`)).resize({ width: 32, height: 32 }), - "linux": electron.nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.png`)).resize({ + "linux": nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.png`)).resize({ width: 32, height: 32 }), - "darwin": electron.nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.png`)).resize({ + "darwin": nativeImage.createFromPath(path.join(__dirname, `../../resources/icons/icon.png`)).resize({ width: 20, height: 20 }), } - console.log(this.i18n) - this.tray = new electron.Tray(process.platform === 'win32' ? icons.win32 : (process.platform === 'darwin' ? icons.darwin : icons.linux)) - this.tray.setToolTip(electron.app.getName()) + this.tray = new Tray(process.platform === 'win32' ? icons.win32 : (process.platform === 'darwin' ? icons.darwin : icons.linux)) + this.tray.setToolTip(app.getName()) this.setTray(false) this.tray.on('double-click', () => { - if (this.win) { - if (this.win.isVisible()) { - this.win.focus() + if (utils.getWindow()) { + if (utils.getWindow().isVisible()) { + utils.getWindow().focus() } else { - this.win.show() + utils.getWindow().show() } } }) - this.win.on('show', () => { + console.log("THISHI ISFJDKIASKJDBKDJSFDLJ { this.setTray(true) }) - this.win.on('restore', () => { + utils.getWindow().on('restore', () => { this.setTray(true) }) - this.win.on('hide', () => { + utils.getWindow().on('hide', () => { this.setTray(false) }) - this.win.on('minimize', () => { + utils.getWindow().on('minimize', () => { this.setTray(false) }) } @@ -265,17 +262,18 @@ export class AppEvents { * Sets the tray context menu to a given state * @param visible - BrowserWindow Visibility */ - private setTray(visible: boolean = this.win.isVisible()) { + private setTray(visible: boolean = utils.getWindow().isVisible()) { + this.i18n = utils.getLocale(utils.getStoreValue('general.language')) - const menu = electron.Menu.buildFromTemplate([ + const menu = Menu.buildFromTemplate([ { - label: (visible ? this.i18n['action.tray.minimize'] : `${this.i18n['action.tray.show']} ${electron.app.getName()}`), + label: (visible ? this.i18n['action.tray.minimize'] : `${this.i18n['action.tray.show']} ${app.getName()}`), click: () => { - if (this.win) { + if (utils.getWindow()) { if (visible) { - this.win.hide() + utils.getWindow().hide() } else { - this.win.show() + utils.getWindow().show() } } } @@ -283,7 +281,7 @@ export class AppEvents { { label: this.i18n['action.tray.quit'], click: () => { - electron.app.quit() + app.quit() } } ]) diff --git a/src/main/base/win.ts b/src/main/base/browserwindow.ts similarity index 59% rename from src/main/base/win.ts rename to src/main/base/browserwindow.ts index 1d6b1fc9..996f3bd7 100644 --- a/src/main/base/win.ts +++ b/src/main/base/browserwindow.ts @@ -1,6 +1,5 @@ -// @ts-nocheck import * as path from "path"; -import * as electron from "electron"; +import {app, BrowserWindow as bw, ipcMain, shell} from "electron"; import * as windowStateKeeper from "electron-window-state"; import * as express from "express"; import * as getPort from "get-port"; @@ -12,26 +11,20 @@ import * as os from "os"; import * as mm from 'music-metadata'; import fetch from 'electron-fetch' import {wsapi} from "./wsapi"; -import * as jsonc from "jsonc"; -import { NsisUpdater, AppImageUpdater } from "electron-updater"; -export class Win { - private win: any | undefined = null; - private app: any | undefined = null; - private store: any | undefined = null; - private devMode: boolean = !electron.app.isPackaged; - public i18n: any = {}; +import {jsonc} from "jsonc"; +import {NsisUpdater} from "electron-updater"; +import {utils} from './utils' - constructor(app: electron.App, store: any) { - this.app = app; - this.store = store; - } +export class BrowserWindow { + public static win: any | undefined = null; + private devMode: boolean = !app.isPackaged; private paths: any = { srcPath: path.join(__dirname, "../../src"), resourcePath: path.join(__dirname, "../../resources"), - ciderCache: path.resolve(electron.app.getPath("userData"), "CiderCache"), - themes: path.resolve(electron.app.getPath("userData"), "Themes"), - plugins: path.resolve(electron.app.getPath("userData"), "Plugins"), + ciderCache: path.resolve(app.getPath("userData"), "CiderCache"), + themes: path.resolve(app.getPath("userData"), "Themes"), + plugins: path.resolve(app.getPath("userData"), "Plugins"), }; private audioStream: any = new Stream.PassThrough(); private clientPort: number = 0; @@ -39,7 +32,7 @@ export class Win { private EnvironmentVariables: object = { env: { platform: process.platform, - dev: electron.app.isPackaged, + dev: app.isPackaged, }, }; private options: any = { @@ -92,17 +85,17 @@ export class Win { this.startWebServer(); - this.win = new electron.BrowserWindow(this.options); - const ws = new wsapi(this.win) + BrowserWindow.win = new bw(this.options); + const ws = new wsapi(BrowserWindow.win) ws.InitWebSockets() // and load the renderer. this.startSession(); this.startHandlers(); // Register listeners on Window to track size and position of the Window. - windowState.manage(this.win); + windowState.manage(BrowserWindow.win); - return this.win; + return BrowserWindow.win } /** @@ -120,11 +113,11 @@ export class Win { for (let i = 0; i < expectedDirectories.length; i++) { if ( !fs.existsSync( - path.join(electron.app.getPath("userData"), expectedDirectories[i]) + path.join(app.getPath("userData"), expectedDirectories[i]) ) ) { fs.mkdirSync( - path.join(electron.app.getPath("userData"), expectedDirectories[i]) + path.join(app.getPath("userData"), expectedDirectories[i]) ); } } @@ -147,19 +140,18 @@ export class Win { app.set("view engine", "ejs"); let firstRequest = true; app.use((req, res, next) => { - // @ts-ignore - if ( - req.url.includes("audio.webm") || - (req.headers.host.includes("localhost") && - (this.devMode || req.headers["user-agent"].includes("Electron"))) - ) { + if (!req || !req.headers || !req.headers.host || !req.headers["user-agent"]) { + console.error('Req not defined') + return + } + if (req.url.includes("audio.webm") || (req.headers.host.includes("localhost") && (this.devMode || req.headers["user-agent"].includes("Electron")))) { next(); } else { res.redirect("https://discord.gg/applemusic"); } }); - app.get("/", (req, res) => { + app.get("/", (_req, res) => { res.render("main", this.EnvironmentVariables); }); @@ -191,7 +183,7 @@ export class Win { }); /* - * Remote Client (I had no idea how to add it to our existing express server, so I just made another one) -@quacksire + * Remote Client (I had no idea how to add it to our existing express server, so I just made another one) -@quacksire * TODO: Broadcast the remote so that /web-remote/ can connect * https://github.com/ciderapp/Apple-Music-Electron/blob/818ed18940ff600d76eb59d22016723a75885cd5/resources/functions/handler.js#L1173 */ @@ -210,15 +202,15 @@ export class Win { qrcode.generate(`http://${os.hostname}:${this.remotePort}`); console.log("---- Ignore Me ;) ---"); /* - * - * USING https://www.npmjs.com/package/qrcode-terminal for terminal - * WE SHOULD USE https://www.npmjs.com/package/qrcode for the remote (or others) for showing to user via an in-app dialog - * -@quacksire - */ + * + * USING https://www.npmjs.com/package/qrcode-terminal for terminal + * WE SHOULD USE https://www.npmjs.com/package/qrcode for the remote (or others) for showing to user via an in-app dialog + * -@quacksire + */ } firstRequest = false; }) - remote.get("/", (req, res) => { + remote.get("/", (_req, res) => { res.render("index", this.EnvironmentVariables); }); }) @@ -229,7 +221,7 @@ export class Win { */ private startSession(): void { // intercept "https://js-cdn.music.apple.com/hls.js/2.141.1/hls.js/hls.js" and redirect to local file "./apple-hls.js" instead - this.win.webContents.session.webRequest.onBeforeRequest( + BrowserWindow.win.webContents.session.webRequest.onBeforeRequest( { urls: ["https://*/*.js"], }, @@ -249,7 +241,7 @@ export class Win { } ); - this.win.webContents.session.webRequest.onBeforeSendHeaders( + BrowserWindow.win.webContents.session.webRequest.onBeforeSendHeaders( async ( details: { url: string; requestHeaders: { [x: string]: string } }, callback: (arg0: { requestHeaders: any }) => void @@ -257,7 +249,7 @@ export class Win { if (details.url === "https://buy.itunes.apple.com/account/web/info") { details.requestHeaders["sec-fetch-site"] = "same-site"; details.requestHeaders["DNT"] = "1"; - let itspod = await this.win.webContents.executeJavaScript( + let itspod = await BrowserWindow.win.webContents.executeJavaScript( `window.localStorage.getItem("music.ampwebplay.itspod")` ); if (itspod != null) @@ -269,10 +261,10 @@ export class Win { let location = `http://localhost:${this.clientPort}/`; - if (electron.app.isPackaged) { - this.win.loadURL(location); + if (app.isPackaged) { + BrowserWindow.win.loadURL(location); } else { - this.win.loadURL(location, { + BrowserWindow.win.loadURL(location, { userAgent: "Cider Development Environment", }); } @@ -285,44 +277,20 @@ export class Win { /********************************************************************************************************************** * ipcMain Events ****************************************************************************************************************** */ - electron.ipcMain.on("cider-platform", (event) => { + ipcMain.on("cider-platform", (event) => { event.returnValue = process.platform; }); - let i18nBase = fs.readFileSync(path.join(__dirname, "../../src/i18n/en_US.jsonc"), "utf8"); - i18nBase = jsonc.parse(i18nBase) - try { - let i18n = fs.readFileSync(path.join(__dirname, `../../src/i18n/${this.store.general.language}.jsonc`), "utf8"); - i18n = jsonc.parse(i18n) - this.i18n = Object.assign(i18nBase, i18n) - } catch (e) { - console.error(e); - } - - electron.ipcMain.on("get-i18n", (event, key) => { - let i18nBase = fs.readFileSync(path.join(__dirname, "../../src/i18n/en_US.jsonc"), "utf8"); - i18nBase = jsonc.parse(i18nBase) - try { - let i18n = fs.readFileSync(path.join(__dirname, `../../src/i18n/${key}.jsonc`), "utf8"); - i18n = jsonc.parse(i18n) - this.i18n = Object.assign(i18nBase, i18n) - } catch (e) { - console.error(e); - event.returnValue = e; - } - - this.i18n = i18nBase; - event.returnValue = i18nBase; - + ipcMain.on("get-i18n", (event, key) => { + event.returnValue = utils.getLocale(key); }); - electron.ipcMain.on("get-i18n-listing", event => { + ipcMain.on("get-i18n-listing", event => { let i18nFiles = fs.readdirSync(path.join(__dirname, "../../src/i18n")).filter(file => file.endsWith(".jsonc")); // read all the files and parse them let i18nListing = [] for (let i = 0; i < i18nFiles.length; i++) { - let i18n = fs.readFileSync(path.join(__dirname, `../../src/i18n/${i18nFiles[i]}`), "utf8"); - i18n = jsonc.parse(i18n) + const i18n: { [index: string]: Object } = jsonc.parse(fs.readFileSync(path.join(__dirname, `../../src/i18n/${i18nFiles[i]}`), "utf8")); i18nListing.push({ "code": i18nFiles[i].replace(".jsonc", ""), "nameNative": i18n["i18n.languageName"] ?? i18nFiles[i].replace(".jsonc", ""), @@ -334,50 +302,50 @@ export class Win { event.returnValue = i18nListing; }) - electron.ipcMain.on("get-gpu-mode", (event) => { + ipcMain.on("get-gpu-mode", (event) => { event.returnValue = process.platform; }); - electron.ipcMain.on("is-dev", (event) => { + ipcMain.on("is-dev", (event) => { event.returnValue = this.devMode; }); - electron.ipcMain.on("put-library-songs", (event, arg) => { + ipcMain.on("put-library-songs", (_event, arg) => { fs.writeFileSync( path.join(this.paths.ciderCache, "library-songs.json"), JSON.stringify(arg) ); }); - electron.ipcMain.on("put-library-artists", (event, arg) => { + ipcMain.on("put-library-artists", (_event, arg) => { fs.writeFileSync( path.join(this.paths.ciderCache, "library-artists.json"), JSON.stringify(arg) ); }); - electron.ipcMain.on("put-library-albums", (event, arg) => { + ipcMain.on("put-library-albums", (_event, arg) => { fs.writeFileSync( path.join(this.paths.ciderCache, "library-albums.json"), JSON.stringify(arg) ); }); - electron.ipcMain.on("put-library-playlists", (event, arg) => { + ipcMain.on("put-library-playlists", (_event, arg) => { fs.writeFileSync( path.join(this.paths.ciderCache, "library-playlists.json"), JSON.stringify(arg) ); }); - electron.ipcMain.on("put-library-recentlyAdded", (event, arg) => { + ipcMain.on("put-library-recentlyAdded", (_event, arg) => { fs.writeFileSync( path.join(this.paths.ciderCache, "library-recentlyAdded.json"), JSON.stringify(arg) ); }); - electron.ipcMain.on("get-library-songs", (event) => { + ipcMain.on("get-library-songs", (event) => { let librarySongs = fs.readFileSync( path.join(this.paths.ciderCache, "library-songs.json"), "utf8" @@ -385,7 +353,7 @@ export class Win { event.returnValue = JSON.parse(librarySongs); }); - electron.ipcMain.on("get-library-artists", (event) => { + ipcMain.on("get-library-artists", (event) => { let libraryArtists = fs.readFileSync( path.join(this.paths.ciderCache, "library-artists.json"), "utf8" @@ -393,7 +361,7 @@ export class Win { event.returnValue = JSON.parse(libraryArtists); }); - electron.ipcMain.on("get-library-albums", (event) => { + ipcMain.on("get-library-albums", (event) => { let libraryAlbums = fs.readFileSync( path.join(this.paths.ciderCache, "library-albums.json"), "utf8" @@ -401,7 +369,7 @@ export class Win { event.returnValue = JSON.parse(libraryAlbums); }); - electron.ipcMain.on("get-library-playlists", (event) => { + ipcMain.on("get-library-playlists", (event) => { let libraryPlaylists = fs.readFileSync( path.join(this.paths.ciderCache, "library-playlists.json"), "utf8" @@ -409,7 +377,7 @@ export class Win { event.returnValue = JSON.parse(libraryPlaylists); }); - electron.ipcMain.on("get-library-recentlyAdded", (event) => { + ipcMain.on("get-library-recentlyAdded", (event) => { let libraryRecentlyAdded = fs.readFileSync( path.join(this.paths.ciderCache, "library-recentlyAdded.json"), "utf8" @@ -417,125 +385,98 @@ export class Win { event.returnValue = JSON.parse(libraryRecentlyAdded); }); - electron.ipcMain.handle("getYTLyrics", async (event, track, artist) => { + ipcMain.handle("getYTLyrics", async (_event, track, artist) => { const u = track + " " + artist + " official video"; return await yt.search(u); }); - electron.ipcMain.on("close", () => { - this.win.close(); + ipcMain.on("close", () => { + BrowserWindow.win.close(); }); - electron.ipcMain.on("maximize", () => { + ipcMain.on("maximize", () => { // listen for maximize event - if (this.win.isMaximized()) { - this.win.unmaximize(); + if (BrowserWindow.win.isMaximized()) { + BrowserWindow.win.unmaximize(); } else { - this.win.maximize(); + BrowserWindow.win.maximize(); } }); - electron.ipcMain.on("unmaximize", () => { + ipcMain.on("unmaximize", () => { // listen for maximize event - this.win.unmaximize(); + BrowserWindow.win.unmaximize(); }); - electron.ipcMain.on("minimize", () => { + ipcMain.on("minimize", () => { // listen for minimize event - this.win.minimize(); + BrowserWindow.win.minimize(); }); // Set scale - electron.ipcMain.on("setScreenScale", (event, scale) => { - this.win.webContents.setZoomFactor(parseFloat(scale)); + ipcMain.on("setScreenScale", (_event, scale) => { + BrowserWindow.win.webContents.setZoomFactor(parseFloat(scale)); }); - electron.ipcMain.on("windowmin", (event, width, height) => { - this.win.setMinimumSize(width, height); + ipcMain.on("windowmin", (_event, width, height) => { + BrowserWindow.win.setMinimumSize(width, height); }) - electron.ipcMain.on("windowontop", (event, ontop) => { - this.win.setAlwaysOnTop(ontop); + ipcMain.on("windowontop", (_event, ontop) => { + BrowserWindow.win.setAlwaysOnTop(ontop); }); // Set scale - electron.ipcMain.on("windowresize", (event, width, height, lock = false) => { - this.win.setContentSize(width, height); - this.win.setResizable(!lock); + ipcMain.on("windowresize", (_event, width, height, lock = false) => { + BrowserWindow.win.setContentSize(width, height); + BrowserWindow.win.setResizable(!lock); }); //Fullscreen - electron.ipcMain.on('setFullScreen', (event, flag) => { - this.win.setFullScreen(flag) + ipcMain.on('setFullScreen', (_event, flag) => { + BrowserWindow.win.setFullScreen(flag) }) //Fullscreen - electron.ipcMain.on('detachDT', (event, _) => { - this.win.webContents.openDevTools({mode: 'detach'}); + ipcMain.on('detachDT', (_event, _) => { + BrowserWindow.win.webContents.openDevTools({mode: 'detach'}); }) - electron.ipcMain.on('play', (event, type, id) => { - this.win.webContents.executeJavaScript(` - MusicKit.getInstance().setQueue({ ${type}: '${id}'}).then(function(queue) { - MusicKit.getInstance().play(); - }); - `) + ipcMain.on('play', (_event, type, id) => { + BrowserWindow.win.webContents.executeJavaScript(` + MusicKit.getInstance().setQueue({ ${type}: '${id}'}).then(function(queue) { + MusicKit.getInstance().play(); + }); + `) }) - function getIp() { - let ip = false; - let alias = 0; - let ifaces = os.networkInterfaces(); - for (var dev in ifaces) { - ifaces[dev].forEach(details => { - if (details.family === 'IPv4') { - if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? ':' + alias : ''))) { - if (details.address.substring(0, 8) === '192.168.' || - details.address.substring(0, 7) === '172.16.' || - details.address.substring(0, 3) === '10.' - ) { - ip = details.address; - ++alias; - } - } - } - }); - } - return ip; - } - //QR Code - electron.ipcMain.handle('showQR', async (event, _) => { - let url = `http://${getIp()}:${this.remotePort}`; - electron.shell.openExternal(`https://cider.sh/pair-remote?url=${btoa(encodeURI(url))}`); - /* - * Doing this because we can give them the link and let them send it via Pocket or another in-browser tool -q - */ + ipcMain.handle('showQR', async (event, _) => { + let url = `http://${BrowserWindow.getIP()}:${this.remotePort}`; + shell.openExternal(`https://cider.sh/pair-remote?url=${Buffer.from(encodeURI(url)).toString('base64')}`).catch(console.error); }) // Get previews for normalization - electron.ipcMain.on("getPreviewURL", (_event, url) => { - 'get url' + ipcMain.on("getPreviewURL", (_event, url) => { + fetch(url) .then(res => res.buffer()) .then(async (buffer) => { - try { - const metadata = await mm.parseBuffer(buffer, 'audio/x-m4a'); - let SoundCheckTag = metadata.native.iTunes[1].value - console.log('sc', SoundCheckTag) - this.win.webContents.send('SoundCheckTag', SoundCheckTag) - } catch (error) { - console.error(error.message); - } - }) + const metadata = await mm.parseBuffer(buffer, 'audio/x-m4a'); + let SoundCheckTag = metadata.native.iTunes[1].value + console.log('sc', SoundCheckTag) + BrowserWindow.win.webContents.send('SoundCheckTag', SoundCheckTag) + }).catch(err => { + console.log(err) + }); }); - electron.ipcMain.on('check-for-update', async (_event, url) => { - const options = { + ipcMain.on('check-for-update', async (_event, url) => { + const options: any = { provider: 'generic', url: 'https://43-429851205-gh.circle-artifacts.com/0/%7E/Cider/dist/artifacts' //Base URL } const autoUpdater = new NsisUpdater(options) //Windows Only (for now) -q - autoUpdater.checkForUpdatesAndNotify() + await autoUpdater.checkForUpdatesAndNotify() }) /* ********************************************************************************************* @@ -550,10 +491,10 @@ export class Win { }; let wndState = WND_STATE.NORMAL; - this.win.on("resize", (_: any) => { - const isMaximized = this.win.isMaximized(); - const isMinimized = this.win.isMinimized(); - const isFullScreen = this.win.isFullScreen(); + BrowserWindow.win.on("resize", (_: any) => { + const isMaximized = BrowserWindow.win.isMaximized(); + const isMinimized = BrowserWindow.win.isMinimized(); + const isFullScreen = BrowserWindow.win.isFullScreen(); const state = wndState; if (isMinimized && state !== WND_STATE.MINIMIZED) { wndState = WND_STATE.MINIMIZED; @@ -561,10 +502,10 @@ export class Win { wndState = WND_STATE.FULL_SCREEN; } else if (isMaximized && state !== WND_STATE.MAXIMIZED) { wndState = WND_STATE.MAXIMIZED; - this.win.webContents.executeJavaScript(`app.chrome.maximized = true`); + BrowserWindow.win.webContents.executeJavaScript(`app.chrome.maximized = true`); } else if (state !== WND_STATE.NORMAL) { wndState = WND_STATE.NORMAL; - this.win.webContents.executeJavaScript( + BrowserWindow.win.webContents.executeJavaScript( `app.chrome.maximized = false` ); } @@ -573,65 +514,72 @@ export class Win { let isQuiting = false - this.win.on("close", (event: Event) => { - if ((this.store.general.close_button_hide || process.platform === "darwin" )&& !isQuiting) { + BrowserWindow.win.on("close", (event: Event) => { + if ((utils.getStoreValue('general.close_button_hide') || process.platform === "darwin") && !isQuiting) { event.preventDefault(); - this.win.hide(); + BrowserWindow.win.hide(); } else { - this.win.destroy(); + BrowserWindow.win.destroy(); } }) - electron.app.on('before-quit', () => { + app.on('before-quit', () => { isQuiting = true }); - electron.app.on('window-all-closed', () => { - electron.app.quit() + app.on('window-all-closed', () => { + app.quit() }) - this.win.on("closed", () => { - this.win = null; + BrowserWindow.win.on("closed", () => { + BrowserWindow.win = null; }); // Set window Handler - this.win.webContents.setWindowOpenHandler((x: any) => { + BrowserWindow.win.webContents.setWindowOpenHandler((x: any) => { if (x.url.includes("apple") || x.url.includes("localhost")) { return {action: "allow"}; } - electron.shell.openExternal(x.url).catch(console.error); + shell.openExternal(x.url).catch(console.error); return {action: "deny"}; }); } - private async broadcastRemote() { - function getIp() { - let ip: any = false; - let alias = 0; - const ifaces: any = os.networkInterfaces(); - for (var dev in ifaces) { - ifaces[dev].forEach((details: any) => { - if (details.family === 'IPv4') { - if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? ':' + alias : ''))) { - if (details.address.substring(0, 8) === '192.168.' || - details.address.substring(0, 7) === '172.16.' || - details.address.substring(0, 3) === '10.' - ) { - ip = details.address; - ++alias; - } - } - } - }); - } - return ip; + private static getIP(): string { + let ip: string = ''; + let alias = 0; + const ifaces: any = os.networkInterfaces(); + for (let dev in ifaces) { + console.log(dev) + console.log(ifaces) + console.log(ifaces[dev]) + // ifaces[dev].forEach((details: any) => { + // if (details.family === 'IPv4') { + // if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? ':' + alias : ''))) { + // if (details.address.substring(0, 8) === '192.168.' || + // details.address.substring(0, 7) === '172.16.' || + // details.address.substring(0, 3) === '10.' + // ) { + // ip = details.address; + // ++alias; + // } + // } + // } + // }); } + return ip; + } - const myString = `http://${getIp()}:${this.remotePort}`; - let mdns = require('mdns-js'); + /** + * Broadcast the remote to the IP + * @private + */ + private async broadcastRemote() { + const myString = `http://${BrowserWindow.getIP()}:${this.remotePort}`; + const mdns = require('mdns-js'); const encoded = new Buffer(myString).toString('base64'); - var x = mdns.tcp('cider-remote'); - var txt_record = { + const x = mdns.tcp('cider-remote'); + const txt_record = { "Ver": "131077", 'DvSv': '3689', 'DbId': 'D41D8CD98F00B205', @@ -640,8 +588,11 @@ export class Win { 'txtvers': '1', "CtlN": "Cider", "iV": "196623" - } - let server2 = mdns.createAdvertisement(x, `${await getPort({port: 3839})}`, {name: encoded, txt: txt_record}); + }; + let server2 = mdns.createAdvertisement(x, `${await getPort({port: 3839})}`, { + name: encoded, + txt: txt_record + }); server2.start(); console.log('remote broadcasted') } diff --git a/src/main/base/plugins.ts b/src/main/base/plugins.ts index 0262d447..4ffb1042 100644 --- a/src/main/base/plugins.ts +++ b/src/main/base/plugins.ts @@ -1,15 +1,14 @@ import * as fs from 'fs'; import * as path from 'path'; import * as electron from 'electron' +import {utils} from './utils'; -export default class PluginHandler { +export class Plugins { private basePluginsPath = path.join(__dirname, '../plugins'); private userPluginsPath = path.join(electron.app.getPath('userData'), 'plugins'); private readonly pluginsList: any = {}; - private readonly _store: any; - constructor(config: any) { - this._store = config; + constructor() { this.pluginsList = this.getPlugins(); } @@ -24,7 +23,7 @@ export default class PluginHandler { if (plugins[file] || plugin.name in plugins) { console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`); } else { - plugins[file] = new plugin(electron.app, this._store); + plugins[file] = new plugin(electron.app, utils.getStore()); } } }); @@ -39,7 +38,7 @@ export default class PluginHandler { if (plugins[file] || plugin in plugins) { console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`); } else { - plugins[file] = new plugin(electron.app, this._store); + plugins[file] = new plugin(electron.app, utils.getStore()); } } }); diff --git a/src/main/base/store.ts b/src/main/base/store.ts index c26f429a..54ca5ba9 100644 --- a/src/main/base/store.ts +++ b/src/main/base/store.ts @@ -1,8 +1,8 @@ -import * as Store from 'electron-store'; +import * as ElectronStore from 'electron-store'; import * as electron from "electron"; -export class ConfigStore { - private _store: Store; +export class Store { + static cfg: ElectronStore; private defaults: any = { "general": { @@ -54,7 +54,7 @@ export class ConfigStore { "down": 'acoustic-ceiling-tiles', "up": 'acoustic-ceiling-tiles', } - }, + }, "equalizer": { 'preset': "default", 'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000], @@ -107,26 +107,14 @@ export class ConfigStore { private migrations: any = {} constructor() { - this._store = new Store({ + Store.cfg = new ElectronStore({ name: 'cider-config', defaults: this.defaults, migrations: this.migrations, }); - this._store.set(this.mergeStore(this.defaults, this._store.store)) - this.ipcHandler(this._store); - } - - get store() { - return this._store.store; - } - - get(key: string) { - return this._store.get(key); - } - - set(key: string, value: any) { - this._store.set(key, value); + Store.cfg.set(this.mergeStore(this.defaults, Store.cfg.store)) + this.ipcHandler(); } /** @@ -140,7 +128,7 @@ export class ConfigStore { if (key.includes('migrations')) { continue; } - if(source[key] instanceof Array) { + if (source[key] instanceof Array) { continue } if (source[key] instanceof Object) Object.assign(source[key], this.mergeStore(target[key], source[key])) @@ -153,21 +141,21 @@ export class ConfigStore { /** * IPC Handler */ - private ipcHandler(cfg: Store | any): void { + private ipcHandler(): void { electron.ipcMain.handle('getStoreValue', (event, key, defaultValue) => { - return (defaultValue ? cfg.get(key, true) : cfg.get(key)); + return (defaultValue ? Store.cfg.get(key, true) : Store.cfg.get(key)); }); electron.ipcMain.handle('setStoreValue', (event, key, value) => { - cfg.set(key, value); + Store.cfg.set(key, value); }); electron.ipcMain.on('getStore', (event) => { - event.returnValue = cfg.store + event.returnValue = Store.cfg.store }) electron.ipcMain.on('setStore', (event, store) => { - cfg.store = store + Store.cfg.store = store }) } diff --git a/src/main/base/utils.ts b/src/main/base/utils.ts new file mode 100644 index 00000000..89301c0f --- /dev/null +++ b/src/main/base/utils.ts @@ -0,0 +1,61 @@ +import * as fs from "fs"; +import * as path from "path"; +import {jsonc} from "jsonc"; +import {Store} from "./store"; +import {BrowserWindow as bw} from "./browserwindow"; + +export class utils { + + /** + * Fetches the i18n locale for the given language. + * @param language {string} The language to fetch the locale for. + * @param key {string} The key to search for. + * @returns {string | Object} The locale value. + */ + static getLocale(language: string, key?: string): string | object { + let i18n: { [index: string]: Object } = jsonc.parse(fs.readFileSync(path.join(__dirname, "../../src/i18n/en_US.jsonc"), "utf8")); + + if (language !== "en_US" && fs.existsSync(path.join(__dirname, `../../src/i18n/${language}.jsonc`))) { + i18n = Object.assign(i18n, jsonc.parse(fs.readFileSync(path.join(__dirname, `../../src/i18n/${language}.jsonc`), "utf8"))); + } + + if (key) { + return i18n[key] + } else { + return i18n + } + } + + /** + * Gets a store value + * @param key + * @returns store value + */ + static getStoreValue(key: string): any { + return Store.cfg.get(key) + } + + /** + * Sets a store + * @returns store + */ + static getStore(): Object { + return Store.cfg.store + } + + /** + * Sets a store value + * @param key + * @param value + */ + static setStoreValue(key: string, value: any): void { + Store.cfg.set(key, value) + } + + /** + * Gets the browser window + */ + static getWindow(): Electron.BrowserWindow { + return bw.win + } +} \ No newline at end of file diff --git a/src/main/index.ts b/src/main/index.ts index e6557a4c..c3071d66 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,41 +1,40 @@ require('v8-compile-cache'); // Analytics for debugging fun yeah. -import * as sentry from '@sentry/electron'; -import * as electron from 'electron'; -import {Win} from "./base/win"; -import {ConfigStore} from "./base/store"; +import {init as Sentry} from '@sentry/electron'; +import {app, components, ipcMain} from 'electron'; +import {Store} from "./base/store"; import {AppEvents} from "./base/app"; -import PluginHandler from "./base/plugins"; +import {Plugins} from "./base/plugins"; +import {utils} from "./base/utils"; +import {BrowserWindow} from "./base/browserwindow"; -sentry.init({dsn: "https://68c422bfaaf44dea880b86aad5a820d2@o954055.ingest.sentry.io/6112214"}); +Sentry({dsn: "https://68c422bfaaf44dea880b86aad5a820d2@o954055.ingest.sentry.io/6112214"}); -const config = new ConfigStore(); -const App = new AppEvents(config.store); -const Cider = new Win(electron.app, config.store) -const plug = new PluginHandler(config.store); - -let win: Electron.BrowserWindow; +new Store(); +const Cider = new AppEvents(); +const CiderPlug = new Plugins(); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * App Event Handlers * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ -electron.app.on('ready', () => { - App.ready(plug); +app.on('ready', () => { + Cider.ready(CiderPlug); console.log('[Cider] Application is Ready. Creating Window.') - if (!electron.app.isPackaged) { + if (!app.isPackaged) { console.info('[Cider] Running in development mode.') require('vue-devtools').install() } - electron.components.whenReady().then(async () => { - win = await Cider.createWindow() - App.bwCreated(win, Cider.i18n); - /// please dont change this for plugins to get proper and fully initialized Win objects - plug.callPlugins('onReady', win); + components.whenReady().then(async () => { + const bw = new BrowserWindow() + const win = await bw.createWindow() + win.on("ready-to-show", () => { + Cider.bwCreated(); + CiderPlug.callPlugins('onReady', win); win.show(); }); }); @@ -46,17 +45,17 @@ electron.app.on('ready', () => { * Renderer Event Handlers * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ -electron.ipcMain.on('playbackStateDidChange', (event, attributes) => { - plug.callPlugins('onPlaybackStateDidChange', attributes); +ipcMain.on('playbackStateDidChange', (event, attributes) => { + CiderPlug.callPlugins('onPlaybackStateDidChange', attributes); }); -electron.ipcMain.on('nowPlayingItemDidChange', (event, attributes) => { - plug.callPlugins('onNowPlayingItemDidChange', attributes); +ipcMain.on('nowPlayingItemDidChange', (event, attributes) => { + CiderPlug.callPlugins('onNowPlayingItemDidChange', attributes); }); -electron.app.on('before-quit', () => { - plug.callPlugins('onBeforeQuit'); - console.warn(`${electron.app.getName()} exited.`); +app.on('before-quit', () => { + CiderPlug.callPlugins('onBeforeQuit'); + console.warn(`${app.getName()} exited.`); }); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -64,7 +63,7 @@ electron.app.on('before-quit', () => { * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // @ts-ignore -electron.app.on('widevine-ready', (version, lastVersion) => { +app.on('widevine-ready', (version, lastVersion) => { if (null !== lastVersion) { console.log('[Cider][Widevine] Widevine ' + version + ', upgraded from ' + lastVersion + ', is ready to be used!') } else { @@ -73,12 +72,12 @@ electron.app.on('widevine-ready', (version, lastVersion) => { }) // @ts-ignore -electron.app.on('widevine-update-pending', (currentVersion, pendingVersion) => { +app.on('widevine-update-pending', (currentVersion, pendingVersion) => { console.log('[Cider][Widevine] Widevine ' + currentVersion + ' is ready to be upgraded to ' + pendingVersion + '!') }) // @ts-ignore -electron.app.on('widevine-error', (error) => { +app.on('widevine-error', (error) => { console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error) - electron.app.exit() + app.exit() })