Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate from remote to ipc + fix restart in portable app #605

Merged
merged 15 commits into from
Jun 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 4 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
const path = require("path");

const electron = require("electron");
const remote = require('@electron/remote/main');
remote.initialize();
const enhanceWebRequest = require("electron-better-web-request").default;
const is = require("electron-is");
const unhandled = require("electron-unhandled");
Expand All @@ -15,6 +13,7 @@ const { fileExists, injectCSS } = require("./plugins/utils");
const { isTesting } = require("./utils/testing");
const { setUpTray } = require("./tray");
const { setupSongInfo } = require("./providers/song-info");
const { setupAppControls, restart } = require("./providers/app-controls");

// Catch errors and log them
unhandled({
Expand Down Expand Up @@ -120,7 +119,6 @@ function createMainWindow() {
contextIsolation: false,
preload: path.join(__dirname, "preload.js"),
nodeIntegrationInSubFrames: true,
nativeWindowOpen: true, // window.open return Window object(like in regular browsers), not BrowserWindowProxy
affinity: "main-window", // main window, and addition windows should work in one process
...(isTesting()
? {
Expand All @@ -138,7 +136,6 @@ function createMainWindow() {
: "default",
autoHideMenuBar: config.get("options.hideMenu"),
});
remote.enable(win.webContents);

if (windowPosition) {
const { x, y } = windowPosition;
Expand Down Expand Up @@ -261,6 +258,7 @@ app.once("browser-window-created", (event, win) => {

setupSongInfo(win);
loadPlugins(win);
setupAppControls();

win.webContents.on("did-fail-load", (
_event,
Expand Down Expand Up @@ -448,13 +446,8 @@ function showUnresponsiveDialog(win, details) {
cancelId: 0
}).then( result => {
switch (result.response) {
case 1: //if relaunch - relaunch+exit
app.relaunch();
case 2:
app.quit();
break;
default:
break;
case 1: restart(); break;
case 2: app.quit(); break;
}
});
}
Expand Down
6 changes: 2 additions & 4 deletions menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const path = require("path");

const { app, Menu, dialog } = require("electron");
const is = require("electron-is");
const { restart } = require("./providers/app-controls");

const { getAllPlugins } = require("./plugins/utils");
const config = require("./config");
Expand Down Expand Up @@ -302,10 +303,7 @@ const mainMenuTemplate = (win) => {
},
{
label: "Restart App",
click: () => {
app.relaunch();
app.quit();
},
click: restart
},
{ role: "quit" },
],
Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@
},
"dependencies": {
"@cliqz/adblocker-electron": "^1.23.7",
"@electron/remote": "^2.0.8",
"@ffmpeg/core": "^0.10.0",
"@ffmpeg/ffmpeg": "^0.10.1",
"Simple-YouTube-Age-Restriction-Bypass": "https://gitpkg.now.sh/zerodytrash/Simple-YouTube-Age-Restriction-Bypass/dist?v2.4.6",
Expand All @@ -108,7 +107,7 @@
"electron-is": "^3.0.0",
"electron-localshortcut": "^3.2.1",
"electron-store": "^8.0.1",
"electron-unhandled": "^3.0.2",
"electron-unhandled": "^4.0.1",
"electron-updater": "^4.6.3",
"filenamify": "^4.3.0",
"hark": "^1.2.3",
Expand All @@ -122,7 +121,7 @@
},
"devDependencies": {
"auto-changelog": "^2.4.0",
"electron": "^17.0.0",
"electron": "^18.2.3",
"electron-builder": "^23.0.3",
"electron-devtools-installer": "^3.1.1",
"electron-icon-maker": "0.0.5",
Expand Down
3 changes: 1 addition & 2 deletions plugins/downloader/youtube-dl.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const { join } = require("path");

const Mutex = require("async-mutex").Mutex;
const { ipcRenderer } = require("electron");
const remote = require('@electron/remote');
const is = require("electron-is");
const filenamify = require("filenamify");

Expand Down Expand Up @@ -137,7 +136,7 @@ const toMP3 = async (
safeVideoName + "." + extension
);

const folder = options.downloadFolder || remote.app.getPath("downloads");
const folder = options.downloadFolder || await ipcRenderer.invoke('getDownloadsFolder');
const name = metadata.title
? `${metadata.artist ? `${metadata.artist} - ` : ""}${metadata.title}`
: videoName;
Expand Down
11 changes: 10 additions & 1 deletion plugins/precise-volume/back.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,18 @@ This is used to determine if plugin is actually active
*/
let enabled = false;

module.exports = (win) => {
const { globalShortcut } = require('electron');

module.exports = (win, options) => {
enabled = true;
injectCSS(win.webContents, path.join(__dirname, "volume-hud.css"));

if (options.globalShortcuts?.volumeUp) {
globalShortcut.register((options.globalShortcuts.volumeUp), () => win.webContents.send('changeVolume', true));
}
if (options.globalShortcuts?.volumeDown) {
globalShortcut.register((options.globalShortcuts.volumeDown), () => win.webContents.send('changeVolume', false));
}
}

module.exports.enabled = () => enabled;
63 changes: 27 additions & 36 deletions plugins/precise-volume/front.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
const { ipcRenderer } = require("electron");
const { globalShortcut } = require('@electron/remote');

const { setOptions, setMenuOptions, isEnabled } = require("../../config/plugins");

function $(selector) { return document.querySelector(selector); }
let api;

module.exports = (options) => {
let api, options;

module.exports = (_options) => {
options = _options;
document.addEventListener('apiLoaded', e => {
api = e.detail;
firstRun(options);
ipcRenderer.on('changeVolume', (_, toIncrease) => changeVolume(toIncrease));
firstRun();
}, { once: true, passive: true })
};

module.exports.moveVolumeHud = moveVolumeHud;

/** Restore saved volume and setup tooltip */
function firstRun(options) {
function firstRun() {
if (typeof options.savedVolume === "number") {
// Set saved volume as tooltip
setTooltip(options.savedVolume);
Expand All @@ -26,16 +28,14 @@ function firstRun(options) {
}
}

setupPlaybar(options);

setupLocalArrowShortcuts(options);
setupPlaybar();

setupGlobalShortcuts(options);
setupLocalArrowShortcuts();

const noVid = $("#main-panel")?.computedStyleMap().get("display").value === "none";
injectVolumeHud(noVid);
if (!noVid) {
setupVideoPlayerOnwheel(options);
setupVideoPlayerOnwheel();
if (!isEnabled('video-toggle')) {
//video-toggle handles hud positioning on its own
const videoMode = () => api.getPlayerResponse().videoDetails?.musicVideoType !== 'MUSIC_VIDEO_TYPE_ATV';
Expand Down Expand Up @@ -96,22 +96,22 @@ function showVolumeHud(volume) {
}

/** Add onwheel event to video player */
function setupVideoPlayerOnwheel(options) {
function setupVideoPlayerOnwheel() {
$("#main-panel").addEventListener("wheel", event => {
event.preventDefault();
// Event.deltaY < 0 means wheel-up
changeVolume(event.deltaY < 0, options);
changeVolume(event.deltaY < 0);
});
}

function saveVolume(volume, options) {
function saveVolume(volume) {
options.savedVolume = volume;
writeOptions(options);
writeOptions();
}

//without this function it would rewrite config 20 time when volume change by 20
let writeTimeout;
function writeOptions(options) {
function writeOptions() {
if (writeTimeout) clearTimeout(writeTimeout);

writeTimeout = setTimeout(() => {
Expand All @@ -121,13 +121,13 @@ function writeOptions(options) {
}

/** Add onwheel event to play bar and also track if play bar is hovered*/
function setupPlaybar(options) {
function setupPlaybar() {
const playerbar = $("ytmusic-player-bar");

playerbar.addEventListener("wheel", event => {
event.preventDefault();
// Event.deltaY < 0 means wheel-up
changeVolume(event.deltaY < 0, options);
changeVolume(event.deltaY < 0);
});

// Keep track of mouse position for showVolumeSlider()
Expand All @@ -139,19 +139,19 @@ function setupPlaybar(options) {
playerbar.classList.remove("on-hover");
});

setupSliderObserver(options);
setupSliderObserver();
}

/** Save volume + Update the volume tooltip when volume-slider is manually changed */
function setupSliderObserver(options) {
function setupSliderObserver() {
const sliderObserver = new MutationObserver(mutations => {
for (const mutation of mutations) {
// This checks that volume-slider was manually set
if (mutation.oldValue !== mutation.target.value &&
(typeof options.savedVolume !== "number" || Math.abs(options.savedVolume - mutation.target.value) > 4)) {
// Diff>4 means it was manually set
setTooltip(mutation.target.value);
saveVolume(mutation.target.value, options);
saveVolume(mutation.target.value);
}
}
});
Expand All @@ -164,18 +164,18 @@ function setupSliderObserver(options) {
}

/** if (toIncrease = false) then volume decrease */
function changeVolume(toIncrease, options) {
function changeVolume(toIncrease) {
// Apply volume change if valid
const steps = Number(options.steps || 1);
api.setVolume(toIncrease ?
Math.min(api.getVolume() + steps, 100) :
Math.max(api.getVolume() - steps, 0));

// Save the new volume
saveVolume(api.getVolume(), options);
saveVolume(api.getVolume());

// change slider position (important)
updateVolumeSlider(options);
updateVolumeSlider();

// Change tooltips to new value
setTooltip(options.savedVolume);
Expand All @@ -185,7 +185,7 @@ function changeVolume(toIncrease, options) {
showVolumeHud(options.savedVolume);
}

function updateVolumeSlider(options) {
function updateVolumeSlider() {
// Slider value automatically rounds to multiples of 5
for (const slider of ["#volume-slider", "#expand-volume-slider"]) {
$(slider).value =
Expand Down Expand Up @@ -228,26 +228,17 @@ function setTooltip(volume) {
}
}

function setupGlobalShortcuts(options) {
if (options.globalShortcuts.volumeUp) {
globalShortcut.register((options.globalShortcuts.volumeUp), () => changeVolume(true, options));
}
if (options.globalShortcuts.volumeDown) {
globalShortcut.register((options.globalShortcuts.volumeDown), () => changeVolume(false, options));
}
}

function setupLocalArrowShortcuts(options) {
function setupLocalArrowShortcuts() {
if (options.arrowsShortcut) {
window.addEventListener('keydown', (event) => {
switch (event.code) {
case "ArrowUp":
event.preventDefault();
changeVolume(true, options);
changeVolume(true);
break;
case "ArrowDown":
event.preventDefault();
changeVolume(false, options);
changeVolume(false);
break;
}
});
Expand Down
15 changes: 15 additions & 0 deletions plugins/quality-changer/back.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { ipcMain, dialog } = require("electron");

module.exports = () => {
ipcMain.handle('qualityChanger', async (_, qualityLabels, currentIndex) => {
return await dialog.showMessageBox({
type: "question",
buttons: qualityLabels,
defaultId: currentIndex,
title: "Choose Video Quality",
message: "Choose Video Quality:",
detail: `Current Quality: ${qualityLabels[currentIndex]}`,
cancelId: -1
})
})
};
22 changes: 8 additions & 14 deletions plugins/quality-changer/front.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { ElementFromFile, templatePath } = require("../utils");
const { dialog } = require('@electron/remote');
const { ipcRenderer } = require("electron");

function $(selector) { return document.querySelector(selector); }

Expand All @@ -21,21 +21,15 @@ function setup(event) {
if (api.getPlayerState() === 2) api.playVideo();
else if (api.getPlayerState() === 1) api.pauseVideo();

const currentIndex = api.getAvailableQualityLevels().indexOf(api.getPlaybackQuality())

dialog.showMessageBox({
type: "question",
buttons: api.getAvailableQualityLabels(),
defaultId: currentIndex,
title: "Choose Video Quality",
message: "Choose Video Quality:",
detail: `Current Quality: ${api.getAvailableQualityLabels()[currentIndex]}`,
cancelId: -1
}).then((promise) => {
const qualityLevels = api.getAvailableQualityLevels();

const currentIndex = qualityLevels.indexOf(api.getPlaybackQuality());

ipcRenderer.invoke('qualityChanger', api.getAvailableQualityLabels(), currentIndex).then(promise => {
if (promise.response === -1) return;
const newQuality = api.getAvailableQualityLevels()[promise.response];
const newQuality = qualityLevels[promise.response];
api.setPlaybackQualityRange(newQuality);
api.setPlaybackQuality(newQuality)
})
});
}
}
12 changes: 3 additions & 9 deletions preload.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
const path = require("path");

const remote = require('@electron/remote');

require("./providers/front-logger")();
const config = require("./config");
const { fileExists } = require("./plugins/utils");
const setupFrontLogger = require("./providers/front-logger");
const setupSongInfo = require("./providers/song-info-front");
const { setupSongControls } = require("./providers/song-controls-front");
const { ipcRenderer } = require("electron");

const plugins = config.plugins.getEnabled();

Expand Down Expand Up @@ -49,12 +47,8 @@ document.addEventListener("DOMContentLoaded", () => {
// inject song-controls
setupSongControls();

// inject front logger
setupFrontLogger();

// Add action for reloading
global.reload = () =>
remote.getCurrentWindow().webContents.loadURL(config.get("url"));
global.reload = () => ipcRenderer.send('reload');

// Blocks the "Are You Still There?" popup by setting the last active time to Date.now every 15min
setInterval(() => window._lact = Date.now(), 900000);
Expand Down
Loading