Link handling should be working

This commit is contained in:
Core 2022-01-24 00:25:43 +00:00
parent 64f646e123
commit 5c7a05ff61
5 changed files with 155 additions and 147 deletions

View file

@ -9,7 +9,7 @@ export class AppEvents {
"musics", "musics",
"music" "music"
] ]
private static plugin: any = null;
private static store: any = null; private static store: any = null;
constructor(store: any) { constructor(store: any) {
@ -88,27 +88,34 @@ export class AppEvents {
}) })
} }
electron.app.on('open-url', (event, url) => {
event.preventDefault()
if (this.protocols.some((protocol: string) => url.includes(protocol))) {
AppEvents.LinkHandler(url)
}
})
} }
public quit() { public quit() {
console.log('App stopped'); console.log('App stopped');
} }
public ready() { public ready(plug: any) {
AppEvents.plugin = plug
console.log('App ready'); console.log('App ready');
} }
public bwCreated(win: Electron.BrowserWindow) {
electron.app.on('open-url', (event, url) => {
event.preventDefault()
if (AppEvents.protocols.some((protocol: string) => url.includes(protocol))) {
AppEvents.LinkHandler(url, win)
}
})
AppEvents.InstanceHandler(win)
}
/*********************************************************************************************************************** /***********************************************************************************************************************
* Private methods * Private methods
**********************************************************************************************************************/ **********************************************************************************************************************/
private static LinkHandler(arg: string) { private static LinkHandler(arg: any, win: Electron.BrowserWindow) {
if (!arg) return; if (!arg) return;
// LastFM Auth URL // LastFM Auth URL
@ -118,8 +125,8 @@ export class AppEvents {
const authKey = authURI.split('lastfm?token=')[1]; const authKey = authURI.split('lastfm?token=')[1];
AppEvents.store.set('lastfm.enabled', true); AppEvents.store.set('lastfm.enabled', true);
AppEvents.store.set('lastfm.auth_token', authKey); AppEvents.store.set('lastfm.auth_token', authKey);
// AppEvents.window.webContents.send('LastfmAuthenticated', authKey); win.webContents.send('LastfmAuthenticated', authKey);
// lastfm.authenticate() AppEvents.plugin.callPlugin('lastfm', 'authenticate', authKey);
} }
} }
// Play // Play
@ -148,4 +155,28 @@ export class AppEvents {
electron.ipcRenderer.send('play', 'url', url) electron.ipcRenderer.send('play', 'url', url)
} }
} }
private static InstanceHandler(win: Electron.BrowserWindow) {
// 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()
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()
} else { // Runs on the first instance if no other instance has been found
electron.app.on('second-instance', (_event, startArgs) => {
if (startArgs.includes("--force-quit")) {
console.warn('[InstanceHandler][SecondInstanceHandler] Force Quit found. Quitting App.');
electron.app.quit()
} else if (startArgs.includes("cider://")) {
AppEvents.LinkHandler(startArgs, win)
} else if (win) {
if (win.isMinimized()) win.restore()
win.focus()
}
})
}
}
} }

View file

@ -34,6 +34,7 @@ export default class PluginHandler {
fs.readdirSync(this.userPluginsPath).forEach(file => { fs.readdirSync(this.userPluginsPath).forEach(file => {
if (file.endsWith('.ts') || file.endsWith('.js')) { if (file.endsWith('.ts') || file.endsWith('.js')) {
const plugin = require(path.join(this.userPluginsPath, file)).default; const plugin = require(path.join(this.userPluginsPath, file)).default;
file = file.replace('.ts', '').replace('.js', '');
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 {
@ -54,4 +55,10 @@ export default class PluginHandler {
} }
} }
public callPlugin(plugin: string, event: string, ...args: any[]) {
if (this.pluginsList[plugin][event]) {
this.pluginsList[plugin][event](...args);
}
}
} }

View file

@ -8,7 +8,6 @@ import * as yt from "youtube-search-without-api-key";
import * as fs from "fs"; import * as fs from "fs";
import { Stream } from "stream"; import { Stream } from "stream";
import * as qrcode from "qrcode-terminal"; import * as qrcode from "qrcode-terminal";
import * as qrcode2 from "qrcode";
import * as os from "os"; import * as os from "os";
import {wsapi} from "./wsapi"; import {wsapi} from "./wsapi";
@ -62,7 +61,6 @@ export class Win {
sandbox: true, sandbox: true,
allowRunningInsecureContent: true, allowRunningInsecureContent: true,
contextIsolation: false, contextIsolation: false,
webviewTag: true, webviewTag: true,
plugins: true, plugins: true,
nodeIntegrationInWorker: false, nodeIntegrationInWorker: false,
@ -74,7 +72,7 @@ export class Win {
/** /**
* Creates the browser window * Creates the browser window
*/ */
async createWindow(): Promise<void> { async createWindow(): Promise<Electron.BrowserWindow> {
this.clientPort = await getPort({ port: 9000 }); this.clientPort = await getPort({ port: 9000 });
this.verifyFiles(); this.verifyFiles();
@ -91,9 +89,6 @@ export class Win {
this.startWebServer(); this.startWebServer();
this.win = new electron.BrowserWindow(this.options); this.win = new electron.BrowserWindow(this.options);
this.win.on("ready-to-show", () => {
this.win.show();
});
const ws = new wsapi(this.win) const ws = new wsapi(this.win)
ws.InitWebSockets() ws.InitWebSockets()
// and load the renderer. // and load the renderer.

View file

@ -1,8 +1,8 @@
require('v8-compile-cache'); require('v8-compile-cache');
// Analytics for debugging fun yeah. // Analytics for debugging fun yeah.
const ElectronSentry = require("@sentry/electron"); import * as sentry from '@sentry/electron';
ElectronSentry.init({dsn: "https://68c422bfaaf44dea880b86aad5a820d2@o954055.ingest.sentry.io/6112214"}); sentry.init({dsn: "https://68c422bfaaf44dea880b86aad5a820d2@o954055.ingest.sentry.io/6112214"});
import * as electron from 'electron'; import * as electron from 'electron';
import {Win} from "./base/win"; import {Win} from "./base/win";
@ -10,18 +10,19 @@ import {ConfigStore} from "./base/store";
import {AppEvents} from "./base/app"; import {AppEvents} from "./base/app";
import PluginHandler from "./base/plugins"; import PluginHandler from "./base/plugins";
// const test = new PluginHandler();
const config = new ConfigStore(); const config = new ConfigStore();
const App = new AppEvents(config.store); const App = new AppEvents(config.store);
const Cider = new Win(electron.app, config.store) const Cider = new Win(electron.app, config.store)
const plug = new PluginHandler(); const plug = new PluginHandler();
let win: Electron.BrowserWindow;
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* App Event Handlers * App Event Handlers
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
electron.app.on('ready', () => { electron.app.on('ready', () => {
App.ready(); App.ready(plug);
console.log('[Cider] Application is Ready. Creating Window.') console.log('[Cider] Application is Ready. Creating Window.')
if (!electron.app.isPackaged) { if (!electron.app.isPackaged) {
@ -30,13 +31,13 @@ electron.app.on('ready', () => {
} }
electron.components.whenReady().then(async () => { electron.components.whenReady().then(async () => {
await Cider.createWindow() win = await Cider.createWindow()
plug.callPlugins('onReady', Cider); App.bwCreated(win);
win.on("ready-to-show", () => {
win.show();
}) });
});
plug.callPlugins('onReady', win);
}); });
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -51,57 +52,31 @@ electron.ipcMain.on('nowPlayingItemDidChange', (event, attributes) => {
plug.callPlugins('onNowPlayingItemDidChange', attributes); plug.callPlugins('onNowPlayingItemDidChange', attributes);
}); });
//
electron.app.on('before-quit', () => { electron.app.on('before-quit', () => {
plug.callPlugins('onBeforeQuit'); plug.callPlugins('onBeforeQuit');
console.warn(`${electron.app.getName()} exited.`); console.warn(`${electron.app.getName()} exited.`);
}); });
//
// // @ts-ignore
// // Widevine Stuff
// electron.app.on('widevine-ready', (version, lastVersion) => {
// if (null !== lastVersion) {
// console.log('[Cider][Widevine] Widevine ' + version + ', upgraded from ' + lastVersion + ', is ready to be used!')
// } else {
// console.log('[Cider][Widevine] Widevine ' + version + ' is ready to be used!')
// }
// })
// // @ts-ignore /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// electron.app.on('widevine-update-pending', (currentVersion, pendingVersion) => { * Widevine Event Handlers
// console.log('[Cider][Widevine] Widevine ' + currentVersion + ' is ready to be upgraded to ' + pendingVersion + '!') * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// })
// // @ts-ignore // @ts-ignore
// electron.app.on('widevine-error', (error) => { electron.app.on('widevine-ready', (version, lastVersion) => {
// console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error) if (null !== lastVersion) {
// electron.app.exit() console.log('[Cider][Widevine] Widevine ' + version + ', upgraded from ' + lastVersion + ', is ready to be used!')
// }) } else {
console.log('[Cider][Widevine] Widevine ' + version + ' is ready to be used!')
//
//
// app.on('open-url', (event, url) => {
// event.preventDefault()
// if (url.includes('ame://') || url.includes('itms://') || url.includes('itmss://') || url.includes('musics://') || url.includes('music://')) {
// CiderBase.LinkHandler(url)
// }
// })
//
electron.app.on('second-instance', (_e, argv) => {
console.warn(`[InstanceHandler][SecondInstanceHandler] Second Instance Started with args: [${argv.join(', ')}]`)
// Checks if first instance is authorized and if second instance has protocol args
if (argv.includes("--force-quit")) {
console.warn('[InstanceHandler][SecondInstanceHandler] Force Quit found. Quitting App.');
electron.app.quit()
} else if (Cider.win) { // If a Second Instance has Been Started
console.warn('[InstanceHandler][SecondInstanceHandler] Showing window.');
Cider.win.show()
Cider.win.focus()
} }
}) })
if (!electron.app.requestSingleInstanceLock()) { // @ts-ignore
console.warn("[InstanceHandler] Existing Instance is Blocking Second Instance."); electron.app.on('widevine-update-pending', (currentVersion, pendingVersion) => {
electron.app.quit(); console.log('[Cider][Widevine] Widevine ' + currentVersion + ' is ready to be upgraded to ' + pendingVersion + '!')
} })
// @ts-ignore
electron.app.on('widevine-error', (error) => {
console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error)
electron.app.exit()
})

View file

@ -1,4 +1,3 @@
import * as electron from 'electron'; import * as electron from 'electron';
import * as fs from 'fs'; import * as fs from 'fs';
import {resolve} from 'path'; import {resolve} from 'path';
@ -16,6 +15,7 @@ export default class LastFMPlugin {
private _win: any; private _win: any;
private _app: any; private _app: any;
private _lastfm: any; private _lastfm: any;
private authenticateFromFile() { private authenticateFromFile() {
let sessionData = require(this.sessionPath) let sessionData = require(this.sessionPath)
console.log("[LastFM][authenticateFromFile] Logging in with Session Info.") console.log("[LastFM][authenticateFromFile] Logging in with Session Info.")
@ -24,8 +24,8 @@ export default class LastFMPlugin {
} }
private authenticate() { authenticate() {
try{ try {
if (this._win.store.store.lastfm.auth_token) { if (this._win.store.store.lastfm.auth_token) {
this._win.store.store.lastfm.enabled = true; this._win.store.store.lastfm.enabled = true;
} }
@ -43,7 +43,7 @@ export default class LastFMPlugin {
this._lastfm = Object.assign(lfmAPI, {cachedAttributes: false, cachedNowPlayingAttributes: false}); this._lastfm = Object.assign(lfmAPI, {cachedAttributes: false, cachedNowPlayingAttributes: false});
fs.stat(this.sessionPath, (err : any) => { fs.stat(this.sessionPath, (err: any) => {
if (err) { if (err) {
console.error("[LastFM][Session] Session file couldn't be opened or doesn't exist,", err) console.error("[LastFM][Session] Session file couldn't be opened or doesn't exist,", err)
console.log("[LastFM][Auth] Beginning authentication from configuration") console.log("[LastFM][Auth] Beginning authentication from configuration")
@ -77,11 +77,11 @@ export default class LastFMPlugin {
} }
} }
private async scrobbleSong(attributes : any) { private async scrobbleSong(attributes: any) {
await new Promise(resolve => setTimeout(resolve, Math.round(attributes.durationInMillis * (this._win.store.store.lastfm.scrobble_after / 100)))); await new Promise(resolve => setTimeout(resolve, Math.round(attributes.durationInMillis * (this._win.store.store.lastfm.scrobble_after / 100))));
const currentAttributes = attributes; const currentAttributes = attributes;
if (!this._lastfm || this._lastfm.cachedAttributes === attributes ) { if (!this._lastfm || this._lastfm.cachedAttributes === attributes) {
return return
} }
@ -112,11 +112,11 @@ export default class LastFMPlugin {
this.authenticate(); this.authenticate();
} }
} else { } else {
return console.log('[LastFM] Did not add ', attributes.name , '—' , this.filterArtistName(attributes.artistName), 'because now playing a other song.'); return console.log('[LastFM] Did not add ', attributes.name, '—', this.filterArtistName(attributes.artistName), 'because now playing a other song.');
} }
} }
private filterArtistName(artist :any) { private filterArtistName(artist: any) {
if (!this._win.store.store.lastfm.enabledRemoveFeaturingArtists) return artist; if (!this._win.store.store.lastfm.enabledRemoveFeaturingArtists) return artist;
artist = artist.split(' '); artist = artist.split(' ');
@ -134,8 +134,8 @@ export default class LastFMPlugin {
return artist.charAt(0).toUpperCase() + artist.slice(1); return artist.charAt(0).toUpperCase() + artist.slice(1);
} }
private updateNowPlayingSong(attributes : any) { private updateNowPlayingSong(attributes: any) {
if (!this._lastfm ||this._lastfm.cachedNowPlayingAttributes === attributes || !this._win.store.store.lastfm.NowPlaying) { if (!this._lastfm || this._lastfm.cachedNowPlayingAttributes === attributes || !this._win.store.store.lastfm.NowPlaying) {
return return
} }
@ -151,7 +151,7 @@ export default class LastFMPlugin {
'track': attributes.name, 'track': attributes.name,
'album': attributes.albumName, 'album': attributes.albumName,
'albumArtist': this.filterArtistName(attributes.artistName) 'albumArtist': this.filterArtistName(attributes.artistName)
}, function (err : any, nowPlaying :any) { }, function (err: any, nowPlaying: any) {
if (err) { if (err) {
return console.error('[LastFM] An error occurred while updating nowPlayingSong', err); return console.error('[LastFM] An error occurred while updating nowPlayingSong', err);
} }
@ -179,7 +179,7 @@ export default class LastFMPlugin {
*/ */
constructor(app: any) { constructor(app: any) {
this._app = app; this._app = app;
electron.app.on('second-instance', (_e:any, argv:any) => { electron.app.on('second-instance', (_e: any, argv: any) => {
// Checks if first instance is authorized and if second instance has protocol args // Checks if first instance is authorized and if second instance has protocol args
argv.forEach((value: any) => { argv.forEach((value: any) => {
if (value.includes('auth')) { if (value.includes('auth')) {
@ -196,7 +196,7 @@ export default class LastFMPlugin {
} }
}) })
}) })
electron.app.on('open-url', (event :any, arg:any) => { electron.app.on('open-url', (event: any, arg: any) => {
console.log('[LastFMPlugin] yes') console.log('[LastFMPlugin] yes')
event.preventDefault(); event.preventDefault();
if (arg.includes('auth')) { if (arg.includes('auth')) {