used typescript the way its supposed to be used

This commit is contained in:
Core 2022-02-01 05:31:19 +00:00
parent 4590e90037
commit a8dc524e6a
No known key found for this signature in database
GPG key ID: FE9BF1B547F8F3C6
7 changed files with 330 additions and 332 deletions

View file

@ -45,6 +45,7 @@
"mdns-js": "github:bitfocus/node-mdns-js", "mdns-js": "github:bitfocus/node-mdns-js",
"mpris-service": "^2.1.2", "mpris-service": "^2.1.2",
"music-metadata": "^7.11.4", "music-metadata": "^7.11.4",
"node-gyp": "^8.4.1",
"qrcode": "^1.5.0", "qrcode": "^1.5.0",
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"react": "^17.0.2", "react": "^17.0.2",
@ -59,6 +60,7 @@
"devDependencies": { "devDependencies": {
"@types/discord-rpc": "^4.0.0", "@types/discord-rpc": "^4.0.0",
"@types/express": "^4.17.13", "@types/express": "^4.17.13",
"@types/qrcode-terminal": "^0.12.0",
"@types/ws": "^8.2.2", "@types/ws": "^8.2.2",
"electron": "https://github.com/castlabs/electron-releases.git", "electron": "https://github.com/castlabs/electron-releases.git",
"electron-builder": "^22.14.5", "electron-builder": "^22.14.5",

View file

@ -1,5 +1,6 @@
import * as electron from 'electron'; import {app, Menu, nativeImage, Tray} from 'electron';
import * as path from 'path'; import * as path from 'path';
import {utils} from './utils'
export class AppEvents { export class AppEvents {
private protocols: string[] = [ private protocols: string[] = [
@ -11,79 +12,76 @@ export class AppEvents {
"music" "music"
] ]
private plugin: any = undefined; private plugin: any = undefined;
private store: any = undefined;
private win: any = undefined;
private tray: any = undefined; private tray: any = undefined;
private i18n: any = undefined; private i18n: any = undefined;
constructor(store: any) { constructor() {
this.store = store this.start();
this.start(store);
} }
/** /**
* Handles all actions that occur for the app on start (Mainly commandline arguments) * Handles all actions that occur for the app on start (Mainly commandline arguments)
* @returns {void} * @returns {void}
*/ */
private start(store: any): void { private start(): void {
console.info('[AppEvents] App started'); console.info('[AppEvents] App started');
/********************************************************************************************************************** /**********************************************************************************************************************
* Startup arguments handling * Startup arguments handling
**********************************************************************************************************************/ **********************************************************************************************************************/
if (electron.app.commandLine.hasSwitch('version') || electron.app.commandLine.hasSwitch('v')) { if (app.commandLine.hasSwitch('version') || app.commandLine.hasSwitch('v')) {
console.log(electron.app.getVersion()) console.log(app.getVersion())
electron.app.exit() app.exit()
} }
// Verbose Check // Verbose Check
if (electron.app.commandLine.hasSwitch('verbose')) { if (app.commandLine.hasSwitch('verbose')) {
console.log("[Cider] User has launched the application with --verbose"); console.log("[Cider] User has launched the application with --verbose");
} }
// Log File Location // Log File Location
if (electron.app.commandLine.hasSwitch('log') || electron.app.commandLine.hasSwitch('l')) { if (app.commandLine.hasSwitch('log') || app.commandLine.hasSwitch('l')) {
console.log(path.join(electron.app.getPath('userData'), 'logs')) console.log(path.join(app.getPath('userData'), 'logs'))
electron.app.exit() app.exit()
} }
// Expose GC // Expose GC
electron.app.commandLine.appendSwitch('js-flags', '--expose_gc') app.commandLine.appendSwitch('js-flags', '--expose_gc')
if (process.platform === "win32") { if (process.platform === "win32") {
electron.app.setAppUserModelId(electron.app.getName()) // For notification name app.setAppUserModelId(app.getName()) // For notification name
} }
/*********************************************************************************************************************** /***********************************************************************************************************************
* Commandline arguments * Commandline arguments
**********************************************************************************************************************/ **********************************************************************************************************************/
switch (store.visual.hw_acceleration) { switch (utils.getStoreValue('visual.hw_acceleration') as string) {
default: default:
case "default": case "default":
electron.app.commandLine.appendSwitch('enable-accelerated-mjpeg-decode') app.commandLine.appendSwitch('enable-accelerated-mjpeg-decode')
electron.app.commandLine.appendSwitch('enable-accelerated-video') app.commandLine.appendSwitch('enable-accelerated-video')
electron.app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds') app.commandLine.appendSwitch('disable-gpu-driver-bug-workarounds')
electron.app.commandLine.appendSwitch('ignore-gpu-blacklist') app.commandLine.appendSwitch('ignore-gpu-blacklist')
electron.app.commandLine.appendSwitch('enable-native-gpu-memory-buffers') app.commandLine.appendSwitch('enable-native-gpu-memory-buffers')
electron.app.commandLine.appendSwitch('enable-accelerated-video-decode'); app.commandLine.appendSwitch('enable-accelerated-video-decode');
electron.app.commandLine.appendSwitch('enable-gpu-rasterization'); app.commandLine.appendSwitch('enable-gpu-rasterization');
electron.app.commandLine.appendSwitch('enable-native-gpu-memory-buffers'); app.commandLine.appendSwitch('enable-native-gpu-memory-buffers');
electron.app.commandLine.appendSwitch('enable-oop-rasterization'); app.commandLine.appendSwitch('enable-oop-rasterization');
break; break;
case "webgpu": case "webgpu":
console.info("WebGPU is enabled."); console.info("WebGPU is enabled.");
electron.app.commandLine.appendSwitch('enable-unsafe-webgpu') app.commandLine.appendSwitch('enable-unsafe-webgpu')
break; break;
case "disabled": case "disabled":
console.info("Hardware acceleration is disabled."); console.info("Hardware acceleration is disabled.");
electron.app.commandLine.appendSwitch('disable-gpu') app.commandLine.appendSwitch('disable-gpu')
break; break;
} }
if (process.platform === "linux") { 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.defaultApp) {
if (process.argv.length >= 2) { if (process.argv.length >= 2) {
this.protocols.forEach((protocol: string) => { 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 { } else {
this.protocols.forEach((protocol: string) => { this.protocols.forEach((protocol: string) => {
electron.app.setAsDefaultProtocolClient(protocol) app.setAsDefaultProtocolClient(protocol)
}) })
} }
@ -113,11 +111,8 @@ export class AppEvents {
console.log('[AppEvents] App ready'); console.log('[AppEvents] App ready');
} }
public bwCreated(win: Electron.BrowserWindow, i18n: any) { public bwCreated() {
this.win = win app.on('open-url', (event, url) => {
this.i18n = i18n
electron.app.on('open-url', (event, url) => {
event.preventDefault() event.preventDefault()
if (this.protocols.some((protocol: string) => url.includes(protocol))) { if (this.protocols.some((protocol: string) => url.includes(protocol))) {
this.LinkHandler(url) this.LinkHandler(url)
@ -145,9 +140,9 @@ export class AppEvents {
let authURI = arg.split('/auth/')[1] let authURI = arg.split('/auth/')[1]
if (authURI.startsWith('lastfm')) { // If we wanted more auth options if (authURI.startsWith('lastfm')) { // If we wanted more auth options
const authKey = authURI.split('lastfm?token=')[1]; const authKey = authURI.split('lastfm?token=')[1];
this.store.set('lastfm.enabled', true); utils.setStoreValue('lastfm.enabled', true);
this.store.set('lastfm.auth_token', authKey); utils.setStoreValue('lastfm.auth_token', authKey);
this.win.webContents.send('LastfmAuthenticated', authKey); utils.getWindow().webContents.send('LastfmAuthenticated', authKey);
this.plugin.callPlugin('lastfm', 'authenticate', authKey); this.plugin.callPlugin('lastfm', 'authenticate', authKey);
} }
} }
@ -164,7 +159,7 @@ export class AppEvents {
for (const [key, value] of Object.entries(mediaType)) { for (const [key, value] of Object.entries(mediaType)) {
if (playParam.includes(key)) { if (playParam.includes(key)) {
const id = playParam.split(key)[1] 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}`) console.debug(`[LinkHandler] Attempting to load ${value} by id: ${id}`)
} }
} }
@ -173,7 +168,7 @@ export class AppEvents {
console.log(arg) console.log(arg)
let url = arg.split('//')[1] let url = arg.split('//')[1]
console.warn(`[LinkHandler] Attempting to load url: ${url}`); 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() { private InstanceHandler() {
// Detects of an existing instance is running (So if the lock has been achieved, no existing instance has been found) // 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 if (!gotTheLock) { // Runs on the new instance if another instance has been found
console.log('[Cider] Another instance has been found, quitting.') 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 } 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()) console.log("[InstanceHandler] (second-instance) Instance started with " + startArgs.toString())
startArgs.forEach(arg => { startArgs.forEach(arg => {
@ -199,10 +194,10 @@ export class AppEvents {
this.LinkHandler(arg) this.LinkHandler(arg)
} else if (arg.includes("--force-quit")) { } else if (arg.includes("--force-quit")) {
console.warn('[InstanceHandler] (second-instance) Force Quit found. Quitting App.'); console.warn('[InstanceHandler] (second-instance) Force Quit found. Quitting App.');
electron.app.quit() app.quit()
} else if (this.win) { } else if (utils.getWindow()) {
if (this.win.isMinimized()) this.win.restore() if (utils.getWindow().isMinimized()) utils.getWindow().restore()
this.win.focus() utils.getWindow().focus()
} }
}) })
}) })
@ -215,48 +210,50 @@ export class AppEvents {
*/ */
private InitTray() { private InitTray() {
const icons = { 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, width: 32,
height: 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, width: 32,
height: 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, width: 20,
height: 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 = new Tray(process.platform === 'win32' ? icons.win32 : (process.platform === 'darwin' ? icons.darwin : icons.linux))
this.tray.setToolTip(electron.app.getName()) this.tray.setToolTip(app.getName())
this.setTray(false) this.setTray(false)
this.tray.on('double-click', () => { this.tray.on('double-click', () => {
if (this.win) { if (utils.getWindow()) {
if (this.win.isVisible()) { if (utils.getWindow().isVisible()) {
this.win.focus() utils.getWindow().focus()
} else { } else {
this.win.show() utils.getWindow().show()
} }
} }
}) })
this.win.on('show', () => { console.log("THISHI ISFJDKIASKJDBKDJSFDLJ<KBSIJUBSDFKJBSKJDBFIKJSBDIHJNFSIHNB ")
console.log(utils.getWindow())
utils.getWindow().on('show', () => {
this.setTray(true) this.setTray(true)
}) })
this.win.on('restore', () => { utils.getWindow().on('restore', () => {
this.setTray(true) this.setTray(true)
}) })
this.win.on('hide', () => { utils.getWindow().on('hide', () => {
this.setTray(false) this.setTray(false)
}) })
this.win.on('minimize', () => { utils.getWindow().on('minimize', () => {
this.setTray(false) this.setTray(false)
}) })
} }
@ -265,17 +262,18 @@ export class AppEvents {
* Sets the tray context menu to a given state * Sets the tray context menu to a given state
* @param visible - BrowserWindow Visibility * @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: () => { click: () => {
if (this.win) { if (utils.getWindow()) {
if (visible) { if (visible) {
this.win.hide() utils.getWindow().hide()
} else { } else {
this.win.show() utils.getWindow().show()
} }
} }
} }
@ -283,7 +281,7 @@ export class AppEvents {
{ {
label: this.i18n['action.tray.quit'], label: this.i18n['action.tray.quit'],
click: () => { click: () => {
electron.app.quit() app.quit()
} }
} }
]) ])

View file

@ -1,6 +1,5 @@
// @ts-nocheck
import * as path from "path"; 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 windowStateKeeper from "electron-window-state";
import * as express from "express"; import * as express from "express";
import * as getPort from "get-port"; import * as getPort from "get-port";
@ -12,26 +11,20 @@ import * as os from "os";
import * as mm from 'music-metadata'; import * as mm from 'music-metadata';
import fetch from 'electron-fetch' import fetch from 'electron-fetch'
import {wsapi} from "./wsapi"; import {wsapi} from "./wsapi";
import * as jsonc from "jsonc"; import {jsonc} from "jsonc";
import { NsisUpdater, AppImageUpdater } from "electron-updater"; import {NsisUpdater} from "electron-updater";
export class Win { import {utils} from './utils'
private win: any | undefined = null;
private app: any | undefined = null;
private store: any | undefined = null;
private devMode: boolean = !electron.app.isPackaged;
public i18n: any = {};
constructor(app: electron.App, store: any) { export class BrowserWindow {
this.app = app; public static win: any | undefined = null;
this.store = store; private devMode: boolean = !app.isPackaged;
}
private paths: any = { private paths: any = {
srcPath: path.join(__dirname, "../../src"), srcPath: path.join(__dirname, "../../src"),
resourcePath: path.join(__dirname, "../../resources"), resourcePath: path.join(__dirname, "../../resources"),
ciderCache: path.resolve(electron.app.getPath("userData"), "CiderCache"), ciderCache: path.resolve(app.getPath("userData"), "CiderCache"),
themes: path.resolve(electron.app.getPath("userData"), "Themes"), themes: path.resolve(app.getPath("userData"), "Themes"),
plugins: path.resolve(electron.app.getPath("userData"), "Plugins"), plugins: path.resolve(app.getPath("userData"), "Plugins"),
}; };
private audioStream: any = new Stream.PassThrough(); private audioStream: any = new Stream.PassThrough();
private clientPort: number = 0; private clientPort: number = 0;
@ -39,7 +32,7 @@ export class Win {
private EnvironmentVariables: object = { private EnvironmentVariables: object = {
env: { env: {
platform: process.platform, platform: process.platform,
dev: electron.app.isPackaged, dev: app.isPackaged,
}, },
}; };
private options: any = { private options: any = {
@ -92,17 +85,17 @@ export class Win {
this.startWebServer(); this.startWebServer();
this.win = new electron.BrowserWindow(this.options); BrowserWindow.win = new bw(this.options);
const ws = new wsapi(this.win) const ws = new wsapi(BrowserWindow.win)
ws.InitWebSockets() ws.InitWebSockets()
// and load the renderer. // and load the renderer.
this.startSession(); this.startSession();
this.startHandlers(); this.startHandlers();
// Register listeners on Window to track size and position of the Window. // 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++) { for (let i = 0; i < expectedDirectories.length; i++) {
if ( if (
!fs.existsSync( !fs.existsSync(
path.join(electron.app.getPath("userData"), expectedDirectories[i]) path.join(app.getPath("userData"), expectedDirectories[i])
) )
) { ) {
fs.mkdirSync( 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"); app.set("view engine", "ejs");
let firstRequest = true; let firstRequest = true;
app.use((req, res, next) => { app.use((req, res, next) => {
// @ts-ignore if (!req || !req.headers || !req.headers.host || !req.headers["user-agent"]) {
if ( console.error('Req not defined')
req.url.includes("audio.webm") || return
(req.headers.host.includes("localhost") && }
(this.devMode || req.headers["user-agent"].includes("Electron"))) if (req.url.includes("audio.webm") || (req.headers.host.includes("localhost") && (this.devMode || req.headers["user-agent"].includes("Electron")))) {
) {
next(); next();
} else { } else {
res.redirect("https://discord.gg/applemusic"); res.redirect("https://discord.gg/applemusic");
} }
}); });
app.get("/", (req, res) => { app.get("/", (_req, res) => {
res.render("main", this.EnvironmentVariables); 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 * TODO: Broadcast the remote so that /web-remote/ can connect
* https://github.com/ciderapp/Apple-Music-Electron/blob/818ed18940ff600d76eb59d22016723a75885cd5/resources/functions/handler.js#L1173 * 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}`); qrcode.generate(`http://${os.hostname}:${this.remotePort}`);
console.log("---- Ignore Me ;) ---"); console.log("---- Ignore Me ;) ---");
/* /*
* *
* USING https://www.npmjs.com/package/qrcode-terminal for terminal * 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 * WE SHOULD USE https://www.npmjs.com/package/qrcode for the remote (or others) for showing to user via an in-app dialog
* -@quacksire * -@quacksire
*/ */
} }
firstRequest = false; firstRequest = false;
}) })
remote.get("/", (req, res) => { remote.get("/", (_req, res) => {
res.render("index", this.EnvironmentVariables); res.render("index", this.EnvironmentVariables);
}); });
}) })
@ -229,7 +221,7 @@ export class Win {
*/ */
private startSession(): void { 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 // 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"], urls: ["https://*/*.js"],
}, },
@ -249,7 +241,7 @@ export class Win {
} }
); );
this.win.webContents.session.webRequest.onBeforeSendHeaders( BrowserWindow.win.webContents.session.webRequest.onBeforeSendHeaders(
async ( async (
details: { url: string; requestHeaders: { [x: string]: string } }, details: { url: string; requestHeaders: { [x: string]: string } },
callback: (arg0: { requestHeaders: any }) => void callback: (arg0: { requestHeaders: any }) => void
@ -257,7 +249,7 @@ export class Win {
if (details.url === "https://buy.itunes.apple.com/account/web/info") { if (details.url === "https://buy.itunes.apple.com/account/web/info") {
details.requestHeaders["sec-fetch-site"] = "same-site"; details.requestHeaders["sec-fetch-site"] = "same-site";
details.requestHeaders["DNT"] = "1"; details.requestHeaders["DNT"] = "1";
let itspod = await this.win.webContents.executeJavaScript( let itspod = await BrowserWindow.win.webContents.executeJavaScript(
`window.localStorage.getItem("music.ampwebplay.itspod")` `window.localStorage.getItem("music.ampwebplay.itspod")`
); );
if (itspod != null) if (itspod != null)
@ -269,10 +261,10 @@ export class Win {
let location = `http://localhost:${this.clientPort}/`; let location = `http://localhost:${this.clientPort}/`;
if (electron.app.isPackaged) { if (app.isPackaged) {
this.win.loadURL(location); BrowserWindow.win.loadURL(location);
} else { } else {
this.win.loadURL(location, { BrowserWindow.win.loadURL(location, {
userAgent: "Cider Development Environment", userAgent: "Cider Development Environment",
}); });
} }
@ -285,44 +277,20 @@ export class Win {
/********************************************************************************************************************** /**********************************************************************************************************************
* ipcMain Events * ipcMain Events
****************************************************************************************************************** */ ****************************************************************************************************************** */
electron.ipcMain.on("cider-platform", (event) => { ipcMain.on("cider-platform", (event) => {
event.returnValue = process.platform; event.returnValue = process.platform;
}); });
let i18nBase = fs.readFileSync(path.join(__dirname, "../../src/i18n/en_US.jsonc"), "utf8"); ipcMain.on("get-i18n", (event, key) => {
i18nBase = jsonc.parse(i18nBase) event.returnValue = utils.getLocale(key);
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;
}); });
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")); let i18nFiles = fs.readdirSync(path.join(__dirname, "../../src/i18n")).filter(file => file.endsWith(".jsonc"));
// read all the files and parse them // read all the files and parse them
let i18nListing = [] let i18nListing = []
for (let i = 0; i < i18nFiles.length; i++) { for (let i = 0; i < i18nFiles.length; i++) {
let i18n = fs.readFileSync(path.join(__dirname, `../../src/i18n/${i18nFiles[i]}`), "utf8"); const i18n: { [index: string]: Object } = jsonc.parse(fs.readFileSync(path.join(__dirname, `../../src/i18n/${i18nFiles[i]}`), "utf8"));
i18n = jsonc.parse(i18n)
i18nListing.push({ i18nListing.push({
"code": i18nFiles[i].replace(".jsonc", ""), "code": i18nFiles[i].replace(".jsonc", ""),
"nameNative": i18n["i18n.languageName"] ?? i18nFiles[i].replace(".jsonc", ""), "nameNative": i18n["i18n.languageName"] ?? i18nFiles[i].replace(".jsonc", ""),
@ -334,50 +302,50 @@ export class Win {
event.returnValue = i18nListing; event.returnValue = i18nListing;
}) })
electron.ipcMain.on("get-gpu-mode", (event) => { ipcMain.on("get-gpu-mode", (event) => {
event.returnValue = process.platform; event.returnValue = process.platform;
}); });
electron.ipcMain.on("is-dev", (event) => { ipcMain.on("is-dev", (event) => {
event.returnValue = this.devMode; event.returnValue = this.devMode;
}); });
electron.ipcMain.on("put-library-songs", (event, arg) => { ipcMain.on("put-library-songs", (_event, arg) => {
fs.writeFileSync( fs.writeFileSync(
path.join(this.paths.ciderCache, "library-songs.json"), path.join(this.paths.ciderCache, "library-songs.json"),
JSON.stringify(arg) JSON.stringify(arg)
); );
}); });
electron.ipcMain.on("put-library-artists", (event, arg) => { ipcMain.on("put-library-artists", (_event, arg) => {
fs.writeFileSync( fs.writeFileSync(
path.join(this.paths.ciderCache, "library-artists.json"), path.join(this.paths.ciderCache, "library-artists.json"),
JSON.stringify(arg) JSON.stringify(arg)
); );
}); });
electron.ipcMain.on("put-library-albums", (event, arg) => { ipcMain.on("put-library-albums", (_event, arg) => {
fs.writeFileSync( fs.writeFileSync(
path.join(this.paths.ciderCache, "library-albums.json"), path.join(this.paths.ciderCache, "library-albums.json"),
JSON.stringify(arg) JSON.stringify(arg)
); );
}); });
electron.ipcMain.on("put-library-playlists", (event, arg) => { ipcMain.on("put-library-playlists", (_event, arg) => {
fs.writeFileSync( fs.writeFileSync(
path.join(this.paths.ciderCache, "library-playlists.json"), path.join(this.paths.ciderCache, "library-playlists.json"),
JSON.stringify(arg) JSON.stringify(arg)
); );
}); });
electron.ipcMain.on("put-library-recentlyAdded", (event, arg) => { ipcMain.on("put-library-recentlyAdded", (_event, arg) => {
fs.writeFileSync( fs.writeFileSync(
path.join(this.paths.ciderCache, "library-recentlyAdded.json"), path.join(this.paths.ciderCache, "library-recentlyAdded.json"),
JSON.stringify(arg) JSON.stringify(arg)
); );
}); });
electron.ipcMain.on("get-library-songs", (event) => { ipcMain.on("get-library-songs", (event) => {
let librarySongs = fs.readFileSync( let librarySongs = fs.readFileSync(
path.join(this.paths.ciderCache, "library-songs.json"), path.join(this.paths.ciderCache, "library-songs.json"),
"utf8" "utf8"
@ -385,7 +353,7 @@ export class Win {
event.returnValue = JSON.parse(librarySongs); event.returnValue = JSON.parse(librarySongs);
}); });
electron.ipcMain.on("get-library-artists", (event) => { ipcMain.on("get-library-artists", (event) => {
let libraryArtists = fs.readFileSync( let libraryArtists = fs.readFileSync(
path.join(this.paths.ciderCache, "library-artists.json"), path.join(this.paths.ciderCache, "library-artists.json"),
"utf8" "utf8"
@ -393,7 +361,7 @@ export class Win {
event.returnValue = JSON.parse(libraryArtists); event.returnValue = JSON.parse(libraryArtists);
}); });
electron.ipcMain.on("get-library-albums", (event) => { ipcMain.on("get-library-albums", (event) => {
let libraryAlbums = fs.readFileSync( let libraryAlbums = fs.readFileSync(
path.join(this.paths.ciderCache, "library-albums.json"), path.join(this.paths.ciderCache, "library-albums.json"),
"utf8" "utf8"
@ -401,7 +369,7 @@ export class Win {
event.returnValue = JSON.parse(libraryAlbums); event.returnValue = JSON.parse(libraryAlbums);
}); });
electron.ipcMain.on("get-library-playlists", (event) => { ipcMain.on("get-library-playlists", (event) => {
let libraryPlaylists = fs.readFileSync( let libraryPlaylists = fs.readFileSync(
path.join(this.paths.ciderCache, "library-playlists.json"), path.join(this.paths.ciderCache, "library-playlists.json"),
"utf8" "utf8"
@ -409,7 +377,7 @@ export class Win {
event.returnValue = JSON.parse(libraryPlaylists); event.returnValue = JSON.parse(libraryPlaylists);
}); });
electron.ipcMain.on("get-library-recentlyAdded", (event) => { ipcMain.on("get-library-recentlyAdded", (event) => {
let libraryRecentlyAdded = fs.readFileSync( let libraryRecentlyAdded = fs.readFileSync(
path.join(this.paths.ciderCache, "library-recentlyAdded.json"), path.join(this.paths.ciderCache, "library-recentlyAdded.json"),
"utf8" "utf8"
@ -417,125 +385,98 @@ export class Win {
event.returnValue = JSON.parse(libraryRecentlyAdded); 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"; const u = track + " " + artist + " official video";
return await yt.search(u); return await yt.search(u);
}); });
electron.ipcMain.on("close", () => { ipcMain.on("close", () => {
this.win.close(); BrowserWindow.win.close();
}); });
electron.ipcMain.on("maximize", () => { ipcMain.on("maximize", () => {
// listen for maximize event // listen for maximize event
if (this.win.isMaximized()) { if (BrowserWindow.win.isMaximized()) {
this.win.unmaximize(); BrowserWindow.win.unmaximize();
} else { } else {
this.win.maximize(); BrowserWindow.win.maximize();
} }
}); });
electron.ipcMain.on("unmaximize", () => { ipcMain.on("unmaximize", () => {
// listen for maximize event // listen for maximize event
this.win.unmaximize(); BrowserWindow.win.unmaximize();
}); });
electron.ipcMain.on("minimize", () => { ipcMain.on("minimize", () => {
// listen for minimize event // listen for minimize event
this.win.minimize(); BrowserWindow.win.minimize();
}); });
// Set scale // Set scale
electron.ipcMain.on("setScreenScale", (event, scale) => { ipcMain.on("setScreenScale", (_event, scale) => {
this.win.webContents.setZoomFactor(parseFloat(scale)); BrowserWindow.win.webContents.setZoomFactor(parseFloat(scale));
}); });
electron.ipcMain.on("windowmin", (event, width, height) => { ipcMain.on("windowmin", (_event, width, height) => {
this.win.setMinimumSize(width, height); BrowserWindow.win.setMinimumSize(width, height);
}) })
electron.ipcMain.on("windowontop", (event, ontop) => { ipcMain.on("windowontop", (_event, ontop) => {
this.win.setAlwaysOnTop(ontop); BrowserWindow.win.setAlwaysOnTop(ontop);
}); });
// Set scale // Set scale
electron.ipcMain.on("windowresize", (event, width, height, lock = false) => { ipcMain.on("windowresize", (_event, width, height, lock = false) => {
this.win.setContentSize(width, height); BrowserWindow.win.setContentSize(width, height);
this.win.setResizable(!lock); BrowserWindow.win.setResizable(!lock);
}); });
//Fullscreen //Fullscreen
electron.ipcMain.on('setFullScreen', (event, flag) => { ipcMain.on('setFullScreen', (_event, flag) => {
this.win.setFullScreen(flag) BrowserWindow.win.setFullScreen(flag)
}) })
//Fullscreen //Fullscreen
electron.ipcMain.on('detachDT', (event, _) => { ipcMain.on('detachDT', (_event, _) => {
this.win.webContents.openDevTools({mode: 'detach'}); BrowserWindow.win.webContents.openDevTools({mode: 'detach'});
}) })
electron.ipcMain.on('play', (event, type, id) => { ipcMain.on('play', (_event, type, id) => {
this.win.webContents.executeJavaScript(` BrowserWindow.win.webContents.executeJavaScript(`
MusicKit.getInstance().setQueue({ ${type}: '${id}'}).then(function(queue) { MusicKit.getInstance().setQueue({ ${type}: '${id}'}).then(function(queue) {
MusicKit.getInstance().play(); 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 //QR Code
electron.ipcMain.handle('showQR', async (event, _) => { ipcMain.handle('showQR', async (event, _) => {
let url = `http://${getIp()}:${this.remotePort}`; let url = `http://${BrowserWindow.getIP()}:${this.remotePort}`;
electron.shell.openExternal(`https://cider.sh/pair-remote?url=${btoa(encodeURI(url))}`); shell.openExternal(`https://cider.sh/pair-remote?url=${Buffer.from(encodeURI(url)).toString('base64')}`).catch(console.error);
/*
* Doing this because we can give them the link and let them send it via Pocket or another in-browser tool -q
*/
}) })
// Get previews for normalization // Get previews for normalization
electron.ipcMain.on("getPreviewURL", (_event, url) => { ipcMain.on("getPreviewURL", (_event, url) => {
'get url'
fetch(url) fetch(url)
.then(res => res.buffer()) .then(res => res.buffer())
.then(async (buffer) => { .then(async (buffer) => {
try { const metadata = await mm.parseBuffer(buffer, 'audio/x-m4a');
const metadata = await mm.parseBuffer(buffer, 'audio/x-m4a'); let SoundCheckTag = metadata.native.iTunes[1].value
let SoundCheckTag = metadata.native.iTunes[1].value console.log('sc', SoundCheckTag)
console.log('sc', SoundCheckTag) BrowserWindow.win.webContents.send('SoundCheckTag', SoundCheckTag)
this.win.webContents.send('SoundCheckTag', SoundCheckTag) }).catch(err => {
} catch (error) { console.log(err)
console.error(error.message); });
}
})
}); });
electron.ipcMain.on('check-for-update', async (_event, url) => { ipcMain.on('check-for-update', async (_event, url) => {
const options = { const options: any = {
provider: 'generic', provider: 'generic',
url: 'https://43-429851205-gh.circle-artifacts.com/0/%7E/Cider/dist/artifacts' //Base URL 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 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; let wndState = WND_STATE.NORMAL;
this.win.on("resize", (_: any) => { BrowserWindow.win.on("resize", (_: any) => {
const isMaximized = this.win.isMaximized(); const isMaximized = BrowserWindow.win.isMaximized();
const isMinimized = this.win.isMinimized(); const isMinimized = BrowserWindow.win.isMinimized();
const isFullScreen = this.win.isFullScreen(); const isFullScreen = BrowserWindow.win.isFullScreen();
const state = wndState; const state = wndState;
if (isMinimized && state !== WND_STATE.MINIMIZED) { if (isMinimized && state !== WND_STATE.MINIMIZED) {
wndState = WND_STATE.MINIMIZED; wndState = WND_STATE.MINIMIZED;
@ -561,10 +502,10 @@ export class Win {
wndState = WND_STATE.FULL_SCREEN; wndState = WND_STATE.FULL_SCREEN;
} else if (isMaximized && state !== WND_STATE.MAXIMIZED) { } else if (isMaximized && state !== WND_STATE.MAXIMIZED) {
wndState = 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) { } else if (state !== WND_STATE.NORMAL) {
wndState = WND_STATE.NORMAL; wndState = WND_STATE.NORMAL;
this.win.webContents.executeJavaScript( BrowserWindow.win.webContents.executeJavaScript(
`app.chrome.maximized = false` `app.chrome.maximized = false`
); );
} }
@ -573,65 +514,72 @@ export class Win {
let isQuiting = false let isQuiting = false
this.win.on("close", (event: Event) => { BrowserWindow.win.on("close", (event: Event) => {
if ((this.store.general.close_button_hide || process.platform === "darwin" )&& !isQuiting) { if ((utils.getStoreValue('general.close_button_hide') || process.platform === "darwin") && !isQuiting) {
event.preventDefault(); event.preventDefault();
this.win.hide(); BrowserWindow.win.hide();
} else { } else {
this.win.destroy(); BrowserWindow.win.destroy();
} }
}) })
electron.app.on('before-quit', () => { app.on('before-quit', () => {
isQuiting = true isQuiting = true
}); });
electron.app.on('window-all-closed', () => { app.on('window-all-closed', () => {
electron.app.quit() app.quit()
}) })
this.win.on("closed", () => { BrowserWindow.win.on("closed", () => {
this.win = null; BrowserWindow.win = null;
}); });
// Set window Handler // Set window Handler
this.win.webContents.setWindowOpenHandler((x: any) => { BrowserWindow.win.webContents.setWindowOpenHandler((x: any) => {
if (x.url.includes("apple") || x.url.includes("localhost")) { if (x.url.includes("apple") || x.url.includes("localhost")) {
return {action: "allow"}; return {action: "allow"};
} }
electron.shell.openExternal(x.url).catch(console.error); shell.openExternal(x.url).catch(console.error);
return {action: "deny"}; return {action: "deny"};
}); });
} }
private async broadcastRemote() { private static getIP(): string {
function getIp() { let ip: string = '';
let ip: any = false; let alias = 0;
let alias = 0; const ifaces: any = os.networkInterfaces();
const ifaces: any = os.networkInterfaces(); for (let dev in ifaces) {
for (var dev in ifaces) { console.log(dev)
ifaces[dev].forEach((details: any) => { console.log(ifaces)
if (details.family === 'IPv4') { console.log(ifaces[dev])
if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? ':' + alias : ''))) { // ifaces[dev].forEach((details: any) => {
if (details.address.substring(0, 8) === '192.168.' || // if (details.family === 'IPv4') {
details.address.substring(0, 7) === '172.16.' || // if (!/(loopback|vmware|internal|hamachi|vboxnet|virtualbox)/gi.test(dev + (alias ? ':' + alias : ''))) {
details.address.substring(0, 3) === '10.' // if (details.address.substring(0, 8) === '192.168.' ||
) { // details.address.substring(0, 7) === '172.16.' ||
ip = details.address; // details.address.substring(0, 3) === '10.'
++alias; // ) {
} // ip = details.address;
} // ++alias;
} // }
}); // }
} // }
return ip; // });
} }
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'); const encoded = new Buffer(myString).toString('base64');
var x = mdns.tcp('cider-remote'); const x = mdns.tcp('cider-remote');
var txt_record = { const txt_record = {
"Ver": "131077", "Ver": "131077",
'DvSv': '3689', 'DvSv': '3689',
'DbId': 'D41D8CD98F00B205', 'DbId': 'D41D8CD98F00B205',
@ -640,8 +588,11 @@ export class Win {
'txtvers': '1', 'txtvers': '1',
"CtlN": "Cider", "CtlN": "Cider",
"iV": "196623" "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(); server2.start();
console.log('remote broadcasted') console.log('remote broadcasted')
} }

View file

@ -1,15 +1,14 @@
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as electron from 'electron' import * as electron from 'electron'
import {utils} from './utils';
export default class PluginHandler { export class Plugins {
private basePluginsPath = path.join(__dirname, '../plugins'); private basePluginsPath = path.join(__dirname, '../plugins');
private userPluginsPath = path.join(electron.app.getPath('userData'), 'plugins'); private userPluginsPath = path.join(electron.app.getPath('userData'), 'plugins');
private readonly pluginsList: any = {}; private readonly pluginsList: any = {};
private readonly _store: any;
constructor(config: any) { constructor() {
this._store = config;
this.pluginsList = this.getPlugins(); this.pluginsList = this.getPlugins();
} }
@ -24,7 +23,7 @@ export default class PluginHandler {
if (plugins[file] || plugin.name in plugins) { if (plugins[file] || plugin.name in plugins) {
console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`); console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);
} else { } 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) { if (plugins[file] || plugin in plugins) {
console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`); console.log(`[${plugin.name}] Plugin already loaded / Duplicate Class Name`);
} else { } else {
plugins[file] = new plugin(electron.app, this._store); plugins[file] = new plugin(electron.app, utils.getStore());
} }
} }
}); });

View file

@ -1,8 +1,8 @@
import * as Store from 'electron-store'; import * as ElectronStore from 'electron-store';
import * as electron from "electron"; import * as electron from "electron";
export class ConfigStore { export class Store {
private _store: Store; static cfg: ElectronStore;
private defaults: any = { private defaults: any = {
"general": { "general": {
@ -54,7 +54,7 @@ export class ConfigStore {
"down": 'acoustic-ceiling-tiles', "down": 'acoustic-ceiling-tiles',
"up": 'acoustic-ceiling-tiles', "up": 'acoustic-ceiling-tiles',
} }
}, },
"equalizer": { "equalizer": {
'preset': "default", 'preset': "default",
'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000], 'frequencies': [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],
@ -107,26 +107,14 @@ export class ConfigStore {
private migrations: any = {} private migrations: any = {}
constructor() { constructor() {
this._store = new Store({ Store.cfg = new ElectronStore({
name: 'cider-config', name: 'cider-config',
defaults: this.defaults, defaults: this.defaults,
migrations: this.migrations, migrations: this.migrations,
}); });
this._store.set(this.mergeStore(this.defaults, this._store.store)) Store.cfg.set(this.mergeStore(this.defaults, Store.cfg.store))
this.ipcHandler(this._store); this.ipcHandler();
}
get store() {
return this._store.store;
}
get(key: string) {
return this._store.get(key);
}
set(key: string, value: any) {
this._store.set(key, value);
} }
/** /**
@ -140,7 +128,7 @@ export class ConfigStore {
if (key.includes('migrations')) { if (key.includes('migrations')) {
continue; continue;
} }
if(source[key] instanceof Array) { if (source[key] instanceof Array) {
continue continue
} }
if (source[key] instanceof Object) Object.assign(source[key], this.mergeStore(target[key], source[key])) if (source[key] instanceof Object) Object.assign(source[key], this.mergeStore(target[key], source[key]))
@ -153,21 +141,21 @@ export class ConfigStore {
/** /**
* IPC Handler * IPC Handler
*/ */
private ipcHandler(cfg: Store | any): void { private ipcHandler(): void {
electron.ipcMain.handle('getStoreValue', (event, key, defaultValue) => { 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) => { electron.ipcMain.handle('setStoreValue', (event, key, value) => {
cfg.set(key, value); Store.cfg.set(key, value);
}); });
electron.ipcMain.on('getStore', (event) => { electron.ipcMain.on('getStore', (event) => {
event.returnValue = cfg.store event.returnValue = Store.cfg.store
}) })
electron.ipcMain.on('setStore', (event, store) => { electron.ipcMain.on('setStore', (event, store) => {
cfg.store = store Store.cfg.store = store
}) })
} }

61
src/main/base/utils.ts Normal file
View file

@ -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
}
}

View file

@ -1,41 +1,40 @@
require('v8-compile-cache'); require('v8-compile-cache');
// Analytics for debugging fun yeah. // Analytics for debugging fun yeah.
import * as sentry from '@sentry/electron'; import {init as Sentry} from '@sentry/electron';
import * as electron from 'electron'; import {app, components, ipcMain} from 'electron';
import {Win} from "./base/win"; import {Store} from "./base/store";
import {ConfigStore} from "./base/store";
import {AppEvents} from "./base/app"; 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(); new Store();
const App = new AppEvents(config.store); const Cider = new AppEvents();
const Cider = new Win(electron.app, config.store) const CiderPlug = new Plugins();
const plug = new PluginHandler(config.store);
let win: Electron.BrowserWindow;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* App Event Handlers * App Event Handlers
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
electron.app.on('ready', () => { app.on('ready', () => {
App.ready(plug); Cider.ready(CiderPlug);
console.log('[Cider] Application is Ready. Creating Window.') console.log('[Cider] Application is Ready. Creating Window.')
if (!electron.app.isPackaged) { if (!app.isPackaged) {
console.info('[Cider] Running in development mode.') console.info('[Cider] Running in development mode.')
require('vue-devtools').install() require('vue-devtools').install()
} }
electron.components.whenReady().then(async () => { components.whenReady().then(async () => {
win = await Cider.createWindow() const bw = new BrowserWindow()
App.bwCreated(win, Cider.i18n); const win = await bw.createWindow()
/// please dont change this for plugins to get proper and fully initialized Win objects
plug.callPlugins('onReady', win);
win.on("ready-to-show", () => { win.on("ready-to-show", () => {
Cider.bwCreated();
CiderPlug.callPlugins('onReady', win);
win.show(); win.show();
}); });
}); });
@ -46,17 +45,17 @@ electron.app.on('ready', () => {
* Renderer Event Handlers * Renderer Event Handlers
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
electron.ipcMain.on('playbackStateDidChange', (event, attributes) => { ipcMain.on('playbackStateDidChange', (event, attributes) => {
plug.callPlugins('onPlaybackStateDidChange', attributes); CiderPlug.callPlugins('onPlaybackStateDidChange', attributes);
}); });
electron.ipcMain.on('nowPlayingItemDidChange', (event, attributes) => { ipcMain.on('nowPlayingItemDidChange', (event, attributes) => {
plug.callPlugins('onNowPlayingItemDidChange', attributes); CiderPlug.callPlugins('onNowPlayingItemDidChange', attributes);
}); });
electron.app.on('before-quit', () => { app.on('before-quit', () => {
plug.callPlugins('onBeforeQuit'); CiderPlug.callPlugins('onBeforeQuit');
console.warn(`${electron.app.getName()} exited.`); console.warn(`${app.getName()} exited.`);
}); });
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -64,7 +63,7 @@ electron.app.on('before-quit', () => {
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// @ts-ignore // @ts-ignore
electron.app.on('widevine-ready', (version, lastVersion) => { app.on('widevine-ready', (version, lastVersion) => {
if (null !== lastVersion) { if (null !== lastVersion) {
console.log('[Cider][Widevine] Widevine ' + version + ', upgraded from ' + lastVersion + ', is ready to be used!') console.log('[Cider][Widevine] Widevine ' + version + ', upgraded from ' + lastVersion + ', is ready to be used!')
} else { } else {
@ -73,12 +72,12 @@ electron.app.on('widevine-ready', (version, lastVersion) => {
}) })
// @ts-ignore // @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 + '!') console.log('[Cider][Widevine] Widevine ' + currentVersion + ' is ready to be upgraded to ' + pendingVersion + '!')
}) })
// @ts-ignore // @ts-ignore
electron.app.on('widevine-error', (error) => { app.on('widevine-error', (error) => {
console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error) console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error)
electron.app.exit() app.exit()
}) })