Merge branch 'upcoming' of https://github.com/CiderApp/Cider into upcoming
This commit is contained in:
commit
a51dc79a94
23 changed files with 1835 additions and 1078 deletions
|
@ -1,3 +1,4 @@
|
|||
// @ts-nocheck
|
||||
import * as path from "path";
|
||||
import * as electron from "electron";
|
||||
import * as windowStateKeeper from "electron-window-state";
|
||||
|
@ -5,7 +6,10 @@ import * as express from "express";
|
|||
import * as getPort from "get-port";
|
||||
import * as yt from "youtube-search-without-api-key";
|
||||
import * as fs from "fs";
|
||||
import {Stream} from "stream";
|
||||
import { Stream } from "stream";
|
||||
import * as qrcode from "qrcode-terminal";
|
||||
import * as os from "os";
|
||||
import {wsapi} from "./wsapi";
|
||||
|
||||
export class Win {
|
||||
win: any | undefined = null;
|
||||
|
@ -24,17 +28,21 @@ export class Win {
|
|||
ciderCache: path.resolve(electron.app.getPath("userData"), "CiderCache"),
|
||||
themes: path.resolve(electron.app.getPath("userData"), "Themes"),
|
||||
plugins: path.resolve(electron.app.getPath("userData"), "Plugins"),
|
||||
}
|
||||
};
|
||||
private audioStream: any = new Stream.PassThrough();
|
||||
private clientPort: number = 0;
|
||||
private remotePort: number = 6942;
|
||||
private EnvironmentVariables: object = {
|
||||
"env": {
|
||||
env: {
|
||||
platform: process.platform,
|
||||
dev: electron.app.isPackaged
|
||||
}
|
||||
dev: electron.app.isPackaged,
|
||||
},
|
||||
};
|
||||
private options: any = {
|
||||
icon: path.join(this.paths.resourcePath, `icons/icon.` + (process.platform === "win32" ? "ico" : "png")),
|
||||
icon: path.join(
|
||||
this.paths.resourcePath,
|
||||
`icons/icon.` + (process.platform === "win32" ? "ico" : "png")
|
||||
),
|
||||
width: 1024,
|
||||
height: 600,
|
||||
x: undefined,
|
||||
|
@ -43,8 +51,8 @@ export class Win {
|
|||
minHeight: 410,
|
||||
frame: false,
|
||||
title: "Cider",
|
||||
vibrancy: 'dark',
|
||||
transparent: (process.platform === "darwin"),
|
||||
vibrancy: "dark",
|
||||
transparent: process.platform === "darwin",
|
||||
hasShadow: false,
|
||||
webPreferences: {
|
||||
nodeIntegration: true,
|
||||
|
@ -57,27 +65,29 @@ export class Win {
|
|||
nodeIntegrationInWorker: false,
|
||||
webSecurity: false,
|
||||
|
||||
preload: path.join(this.paths.srcPath, './preload/cider-preload.js')
|
||||
}
|
||||
preload: path.join(this.paths.srcPath, "./preload/cider-preload.js"),
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates the browser window
|
||||
*/
|
||||
async createWindow(): Promise<void> {
|
||||
this.clientPort = await getPort({port: 9000});
|
||||
this.clientPort = await getPort({ port: 9000 });
|
||||
this.verifyFiles();
|
||||
|
||||
// Load the previous state with fallback to defaults
|
||||
const windowState = windowStateKeeper({
|
||||
defaultWidth: 1024,
|
||||
defaultHeight: 600
|
||||
defaultHeight: 600,
|
||||
});
|
||||
this.options.width = windowState.width;
|
||||
this.options.height = windowState.height;
|
||||
|
||||
// Start the webserver for the browser window to load
|
||||
this.startWebServer()
|
||||
const ws = new wsapi()
|
||||
ws.InitWebSockets()
|
||||
this.startWebServer();
|
||||
|
||||
this.win = new electron.BrowserWindow(this.options);
|
||||
|
||||
|
@ -88,7 +98,6 @@ export class Win {
|
|||
// Register listeners on Window to track size and position of the Window.
|
||||
windowState.manage(this.win);
|
||||
|
||||
|
||||
return this.win;
|
||||
}
|
||||
|
||||
|
@ -96,25 +105,29 @@ export class Win {
|
|||
* Verifies the files for the renderer to use (Cache, library info, etc.)
|
||||
*/
|
||||
private verifyFiles(): void {
|
||||
const expectedDirectories = [
|
||||
"CiderCache"
|
||||
]
|
||||
const expectedDirectories = ["CiderCache"];
|
||||
const expectedFiles = [
|
||||
"library-songs.json",
|
||||
"library-artists.json",
|
||||
"library-albums.json",
|
||||
"library-playlists.json",
|
||||
"library-recentlyAdded.json",
|
||||
]
|
||||
];
|
||||
for (let i = 0; i < expectedDirectories.length; i++) {
|
||||
if (!fs.existsSync(path.join(electron.app.getPath("userData"), expectedDirectories[i]))) {
|
||||
fs.mkdirSync(path.join(electron.app.getPath("userData"), expectedDirectories[i]))
|
||||
if (
|
||||
!fs.existsSync(
|
||||
path.join(electron.app.getPath("userData"), expectedDirectories[i])
|
||||
)
|
||||
) {
|
||||
fs.mkdirSync(
|
||||
path.join(electron.app.getPath("userData"), expectedDirectories[i])
|
||||
);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < expectedFiles.length; i++) {
|
||||
const file = path.join(this.paths.ciderCache, expectedFiles[i])
|
||||
const file = path.join(this.paths.ciderCache, expectedFiles[i]);
|
||||
if (!fs.existsSync(file)) {
|
||||
fs.writeFileSync(file, JSON.stringify([]))
|
||||
fs.writeFileSync(file, JSON.stringify([]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -124,23 +137,31 @@ export class Win {
|
|||
*/
|
||||
private startWebServer(): void {
|
||||
const app = express();
|
||||
|
||||
app.use(express.static(path.join(this.paths.srcPath, './renderer/')));
|
||||
app.set("views", path.join(this.paths.srcPath, './renderer/views'));
|
||||
|
||||
app.use(express.static(path.join(this.paths.srcPath, "./renderer/")));
|
||||
app.set("views", path.join(this.paths.srcPath, "./renderer/views"));
|
||||
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.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)
|
||||
|
||||
res.render("main", this.EnvironmentVariables);
|
||||
});
|
||||
|
||||
app.get('/audio.webm', (req, res) => {
|
||||
app.get("/audio.webm", (req, res) => {
|
||||
try {
|
||||
req.socket.setTimeout(Number.MAX_SAFE_INTEGER);
|
||||
// CiderBase.requests.push({req: req, res: res});
|
||||
|
@ -150,21 +171,45 @@ export class Win {
|
|||
// requests.splice(pos, 1);
|
||||
// console.info("CLOSED", CiderBase.requests.length);
|
||||
// });
|
||||
this.audioStream.on('data', (data: any) => {
|
||||
this.audioStream.on("data", (data: any) => {
|
||||
try {
|
||||
res.write(data);
|
||||
} catch (ex) {
|
||||
console.log(ex)
|
||||
console.log(ex);
|
||||
}
|
||||
})
|
||||
});
|
||||
} catch (ex) {
|
||||
console.log(ex)
|
||||
console.log(ex);
|
||||
}
|
||||
});
|
||||
//app.use(express.static())
|
||||
|
||||
app.listen(this.clientPort, () => {
|
||||
console.log(`Cider client port: ${this.clientPort}`);
|
||||
});
|
||||
|
||||
/*
|
||||
* 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
|
||||
*/
|
||||
const remote = express();
|
||||
remote.use(express.static(path.join(this.paths.srcPath, "./web-remote/")))
|
||||
remote.listen(this.remotePort, () => {
|
||||
console.log(`Cider remote port: ${this.remotePort}`);
|
||||
if (firstRequest) {
|
||||
console.log("---- Ignore Me ;) ---");
|
||||
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
|
||||
*/
|
||||
}
|
||||
firstRequest = false;
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -174,181 +219,234 @@ export class Win {
|
|||
// intercept "https://js-cdn.music.apple.com/hls.js/2.141.0/hls.js/hls.js" and redirect to local file "./apple-hls.js" instead
|
||||
this.win.webContents.session.webRequest.onBeforeRequest(
|
||||
{
|
||||
urls: ["https://*/*.js"]
|
||||
urls: ["https://*/*.js"],
|
||||
},
|
||||
(details: { url: string | string[]; }, callback: (arg0: { redirectURL?: string; cancel?: boolean; }) => void) => {
|
||||
(
|
||||
details: { url: string | string[] },
|
||||
callback: (arg0: { redirectURL?: string; cancel?: boolean }) => void
|
||||
) => {
|
||||
if (details.url.includes("hls.js")) {
|
||||
callback({
|
||||
redirectURL: `http://localhost:${this.clientPort}/apple-hls.js`
|
||||
})
|
||||
redirectURL: `http://localhost:${this.clientPort}/apple-hls.js`,
|
||||
});
|
||||
} else {
|
||||
callback({
|
||||
cancel: false
|
||||
})
|
||||
cancel: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
this.win.webContents.session.webRequest.onBeforeSendHeaders(async (details: { url: string; requestHeaders: { [x: string]: string; }; }, callback: (arg0: { requestHeaders: any; }) => void) => {
|
||||
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(`window.localStorage.getItem("music.ampwebplay.itspod")`)
|
||||
if (itspod != null)
|
||||
details.requestHeaders['Cookie'] = `itspod=${itspod}`
|
||||
this.win.webContents.session.webRequest.onBeforeSendHeaders(
|
||||
async (
|
||||
details: { url: string; requestHeaders: { [x: string]: string } },
|
||||
callback: (arg0: { requestHeaders: any }) => void
|
||||
) => {
|
||||
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(
|
||||
`window.localStorage.getItem("music.ampwebplay.itspod")`
|
||||
);
|
||||
if (itspod != null)
|
||||
details.requestHeaders["Cookie"] = `itspod=${itspod}`;
|
||||
}
|
||||
callback({ requestHeaders: details.requestHeaders });
|
||||
}
|
||||
callback({requestHeaders: details.requestHeaders})
|
||||
})
|
||||
);
|
||||
|
||||
let location = `http://localhost:${this.clientPort}/`
|
||||
let location = `http://localhost:${this.clientPort}/`;
|
||||
|
||||
if (electron.app.isPackaged) {
|
||||
this.win.loadURL(location)
|
||||
this.win.loadURL(location);
|
||||
} else {
|
||||
this.win.loadURL(location, {userAgent: 'Cider Development Environment'})
|
||||
this.win.loadURL(location, {
|
||||
userAgent: "Cider Development Environment",
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the window handlers
|
||||
*/
|
||||
private startHandlers(): void {
|
||||
|
||||
/**********************************************************************************************************************
|
||||
* ipcMain Events
|
||||
****************************************************************************************************************** */
|
||||
electron.ipcMain.on("cider-platform", (event) => {
|
||||
event.returnValue = process.platform
|
||||
})
|
||||
|
||||
electron.ipcMain.on("get-gpu-mode", (event) => {
|
||||
event.returnValue = process.platform
|
||||
})
|
||||
|
||||
electron.ipcMain.on("is-dev", (event) => {
|
||||
event.returnValue = this.devMode
|
||||
})
|
||||
|
||||
electron.ipcMain.on('close', () => { // listen for close event
|
||||
this.win.close();
|
||||
})
|
||||
|
||||
electron.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) => {
|
||||
fs.writeFileSync(path.join(this.paths.ciderCache, "library-artists.json"), JSON.stringify(arg))
|
||||
})
|
||||
|
||||
electron.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) => {
|
||||
fs.writeFileSync(path.join(this.paths.ciderCache, "library-playlists.json"), JSON.stringify(arg))
|
||||
})
|
||||
|
||||
electron.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) => {
|
||||
let librarySongs = fs.readFileSync(path.join(this.paths.ciderCache, "library-songs.json"), "utf8")
|
||||
event.returnValue = JSON.parse(librarySongs)
|
||||
})
|
||||
|
||||
electron.ipcMain.on('get-library-artists', (event) => {
|
||||
let libraryArtists = fs.readFileSync(path.join(this.paths.ciderCache, "library-artists.json"), "utf8")
|
||||
event.returnValue = JSON.parse(libraryArtists)
|
||||
})
|
||||
|
||||
electron.ipcMain.on('get-library-albums', (event) => {
|
||||
let libraryAlbums = fs.readFileSync(path.join(this.paths.ciderCache, "library-albums.json"), "utf8")
|
||||
event.returnValue = JSON.parse(libraryAlbums)
|
||||
})
|
||||
|
||||
electron.ipcMain.on('get-library-playlists', (event) => {
|
||||
let libraryPlaylists = fs.readFileSync(path.join(this.paths.ciderCache, "library-playlists.json"), "utf8")
|
||||
event.returnValue = JSON.parse(libraryPlaylists)
|
||||
})
|
||||
|
||||
electron.ipcMain.on('get-library-recentlyAdded', (event) => {
|
||||
let libraryRecentlyAdded = fs.readFileSync(path.join(this.paths.ciderCache, "library-recentlyAdded.json"), "utf8")
|
||||
event.returnValue = JSON.parse(libraryRecentlyAdded)
|
||||
})
|
||||
|
||||
electron.ipcMain.handle('getYTLyrics', async (event, track, artist) => {
|
||||
const u = track + " " + artist + " official video";
|
||||
return await yt.search(u)
|
||||
})
|
||||
|
||||
electron.ipcMain.handle('setVibrancy', (event, key, value) => {
|
||||
this.win.setVibrancy(value)
|
||||
event.returnValue = process.platform;
|
||||
});
|
||||
|
||||
electron.ipcMain.on('maximize', () => { // listen for maximize event
|
||||
if (this.win.isMaximized()) {
|
||||
this.win.unmaximize()
|
||||
} else {
|
||||
this.win.maximize()
|
||||
}
|
||||
})
|
||||
electron.ipcMain.on("get-gpu-mode", (event) => {
|
||||
event.returnValue = process.platform;
|
||||
});
|
||||
|
||||
electron.ipcMain.on('minimize', () => { // listen for minimize event
|
||||
electron.ipcMain.on("is-dev", (event) => {
|
||||
event.returnValue = this.devMode;
|
||||
});
|
||||
|
||||
electron.ipcMain.on("close", () => {
|
||||
// listen for close event
|
||||
this.win.close();
|
||||
});
|
||||
|
||||
electron.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) => {
|
||||
fs.writeFileSync(
|
||||
path.join(this.paths.ciderCache, "library-artists.json"),
|
||||
JSON.stringify(arg)
|
||||
);
|
||||
});
|
||||
|
||||
electron.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) => {
|
||||
fs.writeFileSync(
|
||||
path.join(this.paths.ciderCache, "library-playlists.json"),
|
||||
JSON.stringify(arg)
|
||||
);
|
||||
});
|
||||
|
||||
electron.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) => {
|
||||
let librarySongs = fs.readFileSync(
|
||||
path.join(this.paths.ciderCache, "library-songs.json"),
|
||||
"utf8"
|
||||
);
|
||||
event.returnValue = JSON.parse(librarySongs);
|
||||
});
|
||||
|
||||
electron.ipcMain.on("get-library-artists", (event) => {
|
||||
let libraryArtists = fs.readFileSync(
|
||||
path.join(this.paths.ciderCache, "library-artists.json"),
|
||||
"utf8"
|
||||
);
|
||||
event.returnValue = JSON.parse(libraryArtists);
|
||||
});
|
||||
|
||||
electron.ipcMain.on("get-library-albums", (event) => {
|
||||
let libraryAlbums = fs.readFileSync(
|
||||
path.join(this.paths.ciderCache, "library-albums.json"),
|
||||
"utf8"
|
||||
);
|
||||
event.returnValue = JSON.parse(libraryAlbums);
|
||||
});
|
||||
|
||||
electron.ipcMain.on("get-library-playlists", (event) => {
|
||||
let libraryPlaylists = fs.readFileSync(
|
||||
path.join(this.paths.ciderCache, "library-playlists.json"),
|
||||
"utf8"
|
||||
);
|
||||
event.returnValue = JSON.parse(libraryPlaylists);
|
||||
});
|
||||
|
||||
electron.ipcMain.on("get-library-recentlyAdded", (event) => {
|
||||
let libraryRecentlyAdded = fs.readFileSync(
|
||||
path.join(this.paths.ciderCache, "library-recentlyAdded.json"),
|
||||
"utf8"
|
||||
);
|
||||
event.returnValue = JSON.parse(libraryRecentlyAdded);
|
||||
});
|
||||
|
||||
electron.ipcMain.handle("getYTLyrics", async (event, track, artist) => {
|
||||
const u = track + " " + artist + " official video";
|
||||
return await yt.search(u);
|
||||
});
|
||||
|
||||
electron.ipcMain.handle("setVibrancy", (event, key, value) => {
|
||||
this.win.setVibrancy(value);
|
||||
});
|
||||
|
||||
electron.ipcMain.on("maximize", () => {
|
||||
// listen for maximize event
|
||||
if (this.win.isMaximized()) {
|
||||
this.win.unmaximize();
|
||||
} else {
|
||||
this.win.maximize();
|
||||
}
|
||||
});
|
||||
|
||||
electron.ipcMain.on("minimize", () => {
|
||||
// listen for minimize event
|
||||
this.win.minimize();
|
||||
})
|
||||
});
|
||||
|
||||
// Set scale
|
||||
electron.ipcMain.on('setScreenScale', (event, scale) => {
|
||||
this.win.webContents.setZoomFactor(parseFloat(scale))
|
||||
electron.ipcMain.on("setScreenScale", (event, scale) => {
|
||||
this.win.webContents.setZoomFactor(parseFloat(scale));
|
||||
});
|
||||
|
||||
|
||||
// Titlebar #147 - Implemented as plugin
|
||||
electron.ipcMain.on('set-titlebar', (e, titlebar) => {
|
||||
this.win.title = `${titlebar} - Cider`
|
||||
})
|
||||
electron.ipcMain.on('reset-titlebar', () => {
|
||||
this.win.title = `Cider`
|
||||
})
|
||||
|
||||
/* *********************************************************************************************
|
||||
* Window Events
|
||||
* **********************************************************************************************/
|
||||
* Window Events
|
||||
* **********************************************************************************************/
|
||||
|
||||
if (process.platform === "win32") {
|
||||
let WND_STATE = {
|
||||
MINIMIZED: 0,
|
||||
NORMAL: 1,
|
||||
MAXIMIZED: 2,
|
||||
FULL_SCREEN: 3
|
||||
}
|
||||
let wndState = WND_STATE.NORMAL
|
||||
FULL_SCREEN: 3,
|
||||
};
|
||||
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()
|
||||
const isMaximized = this.win.isMaximized();
|
||||
const isMinimized = this.win.isMinimized();
|
||||
const isFullScreen = this.win.isFullScreen();
|
||||
const state = wndState;
|
||||
if (isMinimized && state !== WND_STATE.MINIMIZED) {
|
||||
wndState = WND_STATE.MINIMIZED
|
||||
wndState = WND_STATE.MINIMIZED;
|
||||
} else if (isFullScreen && state !== WND_STATE.FULL_SCREEN) {
|
||||
wndState = WND_STATE.FULL_SCREEN
|
||||
wndState = WND_STATE.FULL_SCREEN;
|
||||
} else if (isMaximized && state !== WND_STATE.MAXIMIZED) {
|
||||
wndState = WND_STATE.MAXIMIZED
|
||||
this.win.webContents.executeJavaScript(`app.chrome.maximized = true`)
|
||||
wndState = WND_STATE.MAXIMIZED;
|
||||
this.win.webContents.executeJavaScript(`app.chrome.maximized = true`);
|
||||
} else if (state !== WND_STATE.NORMAL) {
|
||||
wndState = WND_STATE.NORMAL
|
||||
this.win.webContents.executeJavaScript(`app.chrome.maximized = false`)
|
||||
wndState = WND_STATE.NORMAL;
|
||||
this.win.webContents.executeJavaScript(
|
||||
`app.chrome.maximized = false`
|
||||
);
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
this.win.on("closed", () => {
|
||||
this.win = null
|
||||
})
|
||||
this.win = null;
|
||||
});
|
||||
|
||||
// Set window Handler
|
||||
this.win.webContents.setWindowOpenHandler((x: any) => {
|
||||
if (x.url.includes("apple") || x.url.includes("localhost")) {
|
||||
return {action: "allow"}
|
||||
return { action: "allow" };
|
||||
}
|
||||
electron.shell.openExternal(x.url).catch(console.error)
|
||||
return {action: 'deny'}
|
||||
})
|
||||
|
||||
electron.shell.openExternal(x.url).catch(console.error);
|
||||
return { action: "deny" };
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
284
src/main/base/wsapi.ts
Normal file
284
src/main/base/wsapi.ts
Normal file
|
@ -0,0 +1,284 @@
|
|||
// @ts-nocheck
|
||||
|
||||
import * as ws from "ws";
|
||||
import * as http from "http";
|
||||
import * as https from "https";
|
||||
import * as url from "url";
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
import * as electron from "electron";
|
||||
const WebSocket = ws;
|
||||
const WebSocketServer = ws.Server;
|
||||
|
||||
private class standardResponse {
|
||||
status: number;
|
||||
message: string;
|
||||
data: any;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export class wsapi {
|
||||
port: any = 26369
|
||||
wss: any = null
|
||||
clients: []
|
||||
createId() {
|
||||
// create random guid
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
||||
var r = Math.random() * 16 | 0,
|
||||
v = c == 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
public async InitWebSockets () {
|
||||
electron.ipcMain.on('wsapi-updatePlaybackState', (event, arg) => {
|
||||
wsapi.updatePlaybackState(arg);
|
||||
})
|
||||
|
||||
electron.ipcMain.on('wsapi-returnQueue', (event, arg) => {
|
||||
wsapi.returnQueue(JSON.parse(arg));
|
||||
});
|
||||
|
||||
electron.ipcMain.on('wsapi-returnSearch', (event, arg) => {
|
||||
console.log("SEARCH")
|
||||
wsapi.returnSearch(JSON.parse(arg));
|
||||
});
|
||||
|
||||
electron.ipcMain.on('wsapi-returnSearchLibrary', (event, arg) => {
|
||||
wsapi.returnSearchLibrary(JSON.parse(arg));
|
||||
});
|
||||
|
||||
electron.ipcMain.on('wsapi-returnDynamic', (event, arg, type) => {
|
||||
wsapi.returnDynamic(JSON.parse(arg), type);
|
||||
});
|
||||
|
||||
electron.ipcMain.on('wsapi-returnMusicKitApi', (event, arg, method) => {
|
||||
wsapi.returnMusicKitApi(JSON.parse(arg), method);
|
||||
});
|
||||
|
||||
electron.ipcMain.on('wsapi-returnLyrics', (event, arg) => {
|
||||
wsapi.returnLyrics(JSON.parse(arg));
|
||||
});
|
||||
this.wss = new WebSocketServer({
|
||||
port: this.port,
|
||||
perMessageDeflate: {
|
||||
zlibDeflateOptions: {
|
||||
// See zlib defaults.
|
||||
chunkSize: 1024,
|
||||
memLevel: 7,
|
||||
level: 3
|
||||
},
|
||||
zlibInflateOptions: {
|
||||
chunkSize: 10 * 1024
|
||||
},
|
||||
// Other options settable:
|
||||
clientNoContextTakeover: true, // Defaults to negotiated value.
|
||||
serverNoContextTakeover: true, // Defaults to negotiated value.
|
||||
serverMaxWindowBits: 10, // Defaults to negotiated value.
|
||||
// Below options specified as default values.
|
||||
concurrencyLimit: 10, // Limits zlib concurrency for perf.
|
||||
threshold: 1024 // Size (in bytes) below which messages
|
||||
// should not be compressed if context takeover is disabled.
|
||||
}
|
||||
})
|
||||
console.log(`WebSocketServer started on port: ${this.port}`);
|
||||
|
||||
const defaultResponse = new standardResponse(0, {}, "OK");
|
||||
|
||||
|
||||
this.wss.on('connection', function connection(ws) {
|
||||
ws.id = wsapi.createId();
|
||||
console.log(`Client ${ws.id} connected`)
|
||||
wsapi.clients.push(ws);
|
||||
ws.on('message', function incoming(message) {
|
||||
|
||||
});
|
||||
// ws on message
|
||||
ws.on('message', function incoming(message) {
|
||||
let data = JSON.parse(message);
|
||||
let response = new standardResponse(0, {}, "OK");;
|
||||
if (data.action) {
|
||||
data.action.toLowerCase();
|
||||
}
|
||||
switch (data.action) {
|
||||
default:
|
||||
response.message = "Action not found";
|
||||
break;
|
||||
case "identify":
|
||||
response.message = "Thanks for identifying!"
|
||||
response.data = {
|
||||
id: ws.id
|
||||
}
|
||||
ws.identity = {
|
||||
name: data.name,
|
||||
author: data.author,
|
||||
description: data.description,
|
||||
version: data.version
|
||||
}
|
||||
break;
|
||||
case "play-next":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.playNext(\`${data.type}\`,\`${data.id}\`)`);
|
||||
response.message = "Play Next";
|
||||
break;
|
||||
case "play-later":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.playLater(\`${data.type}\`,\`${data.id}\`)`);
|
||||
response.message = "Play Later";
|
||||
break;
|
||||
case "quick-play":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.quickPlay(\`${data.term}\`)`);
|
||||
response.message = "Quick Play";
|
||||
break;
|
||||
case "get-lyrics":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.getLyrics()`);
|
||||
break;
|
||||
case "shuffle":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.toggleShuffle()`);
|
||||
break;
|
||||
case "set-shuffle":
|
||||
if(data.shuffle == true) {
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().shuffleMode = 1`);
|
||||
}else{
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().shuffleMode = 0`);
|
||||
}
|
||||
break;
|
||||
case "repeat":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.toggleRepeat()`);
|
||||
break;
|
||||
case "seek":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().seekToTime(${parseFloat(data.time)})`);
|
||||
response.message = "Seek";
|
||||
break;
|
||||
case "pause":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().pause()`);
|
||||
response.message = "Paused";
|
||||
break;
|
||||
case "play":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().play()`);
|
||||
response.message = "Playing";
|
||||
break;
|
||||
case "stop":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().stop()`);
|
||||
response.message = "Stopped";
|
||||
break;
|
||||
case "volume":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().volume = ${parseFloat(data.volume)}`);
|
||||
response.message = "Volume";
|
||||
break;
|
||||
case "mute":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().mute()`);
|
||||
response.message = "Muted";
|
||||
break;
|
||||
case "unmute":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().unmute()`);
|
||||
response.message = "Unmuted";
|
||||
break;
|
||||
case "next":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().skipToNextItem()`);
|
||||
response.message = "Next";
|
||||
break;
|
||||
case "previous":
|
||||
electron.app.win.webContents.executeJavaScript(`MusicKit.getInstance().skipToPreviousItem()`);
|
||||
response.message = "Previous";
|
||||
break;
|
||||
case "musickit-api":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.musickitApi(\`${data.method}\`, \`${data.id}\`, ${JSON.stringify(data.params)})`);
|
||||
break;
|
||||
case "musickit-library-api":
|
||||
break;
|
||||
case "set-autoplay":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.setAutoplay(${data.autoplay})`);
|
||||
break;
|
||||
case "queue-move":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.moveQueueItem(${data.from},${data.to})`);
|
||||
break;
|
||||
case "get-queue":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.getQueue()`);
|
||||
break;
|
||||
case "search":
|
||||
if (!data.limit) {
|
||||
data.limit = 10;
|
||||
}
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.search(\`${data.term}\`, \`${data.limit}\`)`);
|
||||
break;
|
||||
case "library-search":
|
||||
if (!data.limit) {
|
||||
data.limit = 10;
|
||||
}
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.searchLibrary(\`${data.term}\`, \`${data.limit}\`)`);
|
||||
break;
|
||||
case "show-window":
|
||||
electron.app.win.show()
|
||||
break;
|
||||
case "hide-window":
|
||||
electron.app.win.hide()
|
||||
break;
|
||||
case "play-mediaitem":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.playTrackById(${data.id}, \`${data.kind}\`)`);
|
||||
response.message = "Playing track";
|
||||
break;
|
||||
case "get-status":
|
||||
response.data = {
|
||||
isAuthorized: true
|
||||
};
|
||||
response.message = "Status";
|
||||
break;
|
||||
case "get-currentmediaitem":
|
||||
electron.app.win.webContents.executeJavaScript(`wsapi.getPlaybackState()`);
|
||||
break;
|
||||
}
|
||||
ws.send(JSON.stringify(response));
|
||||
});
|
||||
|
||||
ws.on('close', function close() {
|
||||
// remove client from list
|
||||
wsapi.clients.splice(wsapi.clients.indexOf(ws), 1);
|
||||
console.log(`Client ${ws.id} disconnected`);
|
||||
});
|
||||
ws.send(JSON.stringify(defaultResponse));
|
||||
});
|
||||
}
|
||||
sendToClient(id) {
|
||||
// replace the clients.forEach with a filter to find the client that requested
|
||||
}
|
||||
updatePlaybackState(attr) {
|
||||
const response = new standardResponse(0, attr, "OK", "playbackStateUpdate");
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnMusicKitApi(results, method) {
|
||||
const response = new standardResponse(0, results, "OK", `musickitapi.${method}`);
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnDynamic(results, type) {
|
||||
const response = new standardResponse(0, results, "OK", type);
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnLyrics(results) {
|
||||
const response = new standardResponse(0, results, "OK", "lyrics");
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnSearch(results) {
|
||||
const response = new standardResponse(0, results, "OK", "searchResults");
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnSearchLibrary(results) {
|
||||
const response = new standardResponse(0, results, "OK", "searchResultsLibrary");
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
returnQueue(queue) {
|
||||
const response = new standardResponse(0, queue, "OK", "queue");
|
||||
wsapi.clients.forEach(function each(client) {
|
||||
client.send(JSON.stringify(response));
|
||||
});
|
||||
}
|
||||
}
|
|
@ -11,7 +11,7 @@ import {AppEvents} from "./base/app";
|
|||
import PluginHandler from "./base/plugins";
|
||||
|
||||
// const test = new PluginHandler();
|
||||
let win = null;
|
||||
let win: Promise<void> | null = null;
|
||||
const config = new ConfigStore();
|
||||
const App = new AppEvents(config.store);
|
||||
const Cider = new Win(electron.app, config.store)
|
||||
|
@ -30,8 +30,12 @@ electron.app.on('ready', () => {
|
|||
require('vue-devtools').install()
|
||||
}
|
||||
|
||||
win = Cider.createWindow();
|
||||
plug.callPlugins('onReady', win);
|
||||
electron.components.whenReady().then(() => {
|
||||
win = Cider.createWindow();
|
||||
plug.callPlugins('onReady', win);
|
||||
})
|
||||
|
||||
|
||||
});
|
||||
|
||||
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
@ -52,23 +56,27 @@ electron.app.on('before-quit', () => {
|
|||
console.warn(`${electron.app.getName()} exited.`);
|
||||
});
|
||||
//
|
||||
// // @ts-ignore
|
||||
// // Widevine Stuff
|
||||
// app.on('widevine-ready', (version, lastVersion) => {
|
||||
// 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!')
|
||||
// }
|
||||
// })
|
||||
//
|
||||
// app.on('widevine-update-pending', (currentVersion, pendingVersion) => {
|
||||
|
||||
// // @ts-ignore
|
||||
// electron.app.on('widevine-update-pending', (currentVersion, pendingVersion) => {
|
||||
// console.log('[Cider][Widevine] Widevine ' + currentVersion + ' is ready to be upgraded to ' + pendingVersion + '!')
|
||||
// })
|
||||
//
|
||||
// app.on('widevine-error', (error) => {
|
||||
|
||||
// // @ts-ignore
|
||||
// electron.app.on('widevine-error', (error) => {
|
||||
// console.log('[Cider][Widevine] Widevine installation encountered an error: ' + error)
|
||||
// app.exit()
|
||||
// electron.app.exit()
|
||||
// })
|
||||
|
||||
//
|
||||
//
|
||||
// app.on('open-url', (event, url) => {
|
||||
|
|
35
src/main/plugins/Extras/sendSongToTitlebar.ts
Normal file
35
src/main/plugins/Extras/sendSongToTitlebar.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
import * as electron from "electron";
|
||||
|
||||
export default class sendSongToTitlebar {
|
||||
/**
|
||||
* Base Plugin Details (Eventually implemented into a GUI in settings)
|
||||
*/
|
||||
public name: string = 'sendSongToTitlebar';
|
||||
public description: string = 'Sets the app\'s titlebar to the Song title';
|
||||
public version: string = '0.0.1';
|
||||
public author: string = 'Cider Collective (credit to 8times9 via #147)';
|
||||
/**
|
||||
* Runs on plugin load (Currently run on application start)
|
||||
*/
|
||||
constructor() {}
|
||||
/**
|
||||
* Runs on app ready
|
||||
*/
|
||||
onReady(): void {}
|
||||
/**
|
||||
* Runs on app stop
|
||||
*/
|
||||
onBeforeQuit(): void {}
|
||||
/**
|
||||
* Runs on playback State Change
|
||||
* @param attributes Music Attributes (attributes.state = current state)
|
||||
*/
|
||||
onPlaybackStateDidChange(attributes: any): void {
|
||||
electron.ipcRenderer.send('set-titlebar', attributes.name)
|
||||
}
|
||||
/**
|
||||
* Runs on song change
|
||||
* @param attributes Music Attributes
|
||||
*/
|
||||
onNowPlayingItemDidChange(attributes: object): void {}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue