transitioning to ts

This commit is contained in:
2023-05-01 23:23:43 +02:00
parent 412f1ae3e3
commit 46d030cf8e
18 changed files with 302 additions and 171 deletions

View File

@@ -19,7 +19,7 @@ import {
import { addTray, refreshTray } from "./scripts/tray";
import { addMenu } from "./scripts/menu";
import path from "path";
import expressModule from "./scripts/express";
import { startExpress } from "./scripts/express";
import mediaKeys from "./constants/mediaKeys";
import mediaInfoModule from "./scripts/mediaInfo";
import discordModule from "./scripts/discord";
@@ -29,7 +29,7 @@ const tidalUrl = "https://listen.tidal.com";
initialize();
let mainWindow: any;
let mainWindow: BrowserWindow;
const icon = path.join(__dirname, "../assets/icon.png");
const PROTOCOL_PREFIX = "tidal";
@@ -59,7 +59,7 @@ function setFlags() {
*
*/
function syncMenuBarWithStore() {
const fixedMenuBar = store.get(settings.menuBar);
const fixedMenuBar = !!store.get(settings.menuBar);
mainWindow.autoHideMenuBar = !fixedMenuBar;
mainWindow.setMenuBarVisibility(fixedMenuBar);
@@ -111,7 +111,7 @@ function createWindow(options = { x: 0, y: 0, backgroundColor: "white" }) {
mainWindow.webContents.setBackgroundThrottling(false);
}
mainWindow.on("close", function (event: any) {
mainWindow.on("close", function (event: CloseEvent) {
if (store.get(settings.minimizeOnClose)) {
event.preventDefault();
mainWindow.hide();
@@ -169,9 +169,9 @@ app.on("ready", async () => {
addGlobalShortcuts();
if (store.get(settings.trayIcon)) {
addTray(mainWindow, { icon });
refreshTray();
refreshTray(mainWindow);
}
store.get(settings.api) && expressModule.run(mainWindow);
store.get(settings.api) && startExpress(mainWindow);
store.get(settings.enableDiscord) && discordModule.initRPC();
} else {
app.quit();

12
src/models/options.ts Normal file
View File

@@ -0,0 +1,12 @@
export interface Options {
title: string;
artists: string;
album: string;
status: string;
url: string;
current: string;
duration: string;
"app-name": string;
image: string;
icon: string;
}

View File

@@ -1,28 +1,29 @@
let adBlock,
api,
customCSS,
disableBackgroundThrottle,
disableHardwareMediaKeys,
enableCustomHotkeys,
enableDiscord,
gpuRasterization,
menuBar,
minimizeOnClose,
mpris,
notifications,
playBackControl,
port,
singleInstance,
skipArtists,
skippedArtists,
trayIcon,
updateFrequency;
let adBlock: HTMLInputElement,
api: HTMLInputElement,
customCSS: HTMLInputElement,
disableBackgroundThrottle: HTMLInputElement,
disableHardwareMediaKeys: HTMLInputElement,
enableCustomHotkeys: HTMLInputElement,
enableDiscord: HTMLInputElement,
gpuRasterization: HTMLInputElement,
menuBar: HTMLInputElement,
minimizeOnClose: HTMLInputElement,
mpris: HTMLInputElement,
notifications: HTMLInputElement,
playBackControl: HTMLInputElement,
port: HTMLInputElement,
singleInstance: HTMLInputElement,
skipArtists: HTMLInputElement,
skippedArtists: HTMLInputElement,
trayIcon: HTMLInputElement,
updateFrequency: HTMLInputElement;
const { store, settings } = require("../../scripts/settings");
const { ipcRenderer } = require("electron");
const globalEvents = require("../../constants/globalEvents");
const remote = require("@electron/remote");
const { app } = remote;
/**
* Sync the UI forms with the current settings
*/
@@ -30,7 +31,7 @@ function refreshSettings() {
adBlock.checked = store.get(settings.adBlock);
api.checked = store.get(settings.api);
customCSS.value = store.get(settings.customCSS);
disableBackgroundThrottle.checked = store.get("disableBackgroundThrottle");
disableBackgroundThrottle.checked = store.get(settings.disableBackgroundThrottle);
disableHardwareMediaKeys.checked = store.get(settings.flags.disableHardwareMediaKeys);
enableCustomHotkeys.checked = store.get(settings.enableCustomHotkeys);
enableDiscord.checked = store.get(settings.enableDiscord);
@@ -43,7 +44,7 @@ function refreshSettings() {
port.value = store.get(settings.apiSettings.port);
singleInstance.checked = store.get(settings.singleInstance);
skipArtists.checked = store.get(settings.skipArtists);
skippedArtists.value = store.get(settings.skippedArtists).join("\n");
skippedArtists.value = (store.get(settings.skippedArtists) as string[]).join("\n");
trayIcon.checked = store.get(settings.trayIcon);
updateFrequency.value = store.get(settings.updateFrequency);
}
@@ -51,7 +52,7 @@ function refreshSettings() {
/**
* Open an url in the default browsers
*/
function openExternal(url) {
function openExternal(url: string) {
const { shell } = require("electron");
shell.openExternal(url);
}
@@ -75,31 +76,31 @@ function restart() {
* Bind UI components to functions after DOMContentLoaded
*/
window.addEventListener("DOMContentLoaded", () => {
function get(id) {
return document.getElementById(id);
function get(id: string): HTMLInputElement {
return document.getElementById(id) as HTMLInputElement;
}
document.getElementById("close").addEventListener("click", hide);
document.getElementById("restart").addEventListener("click", restart);
document.querySelectorAll(".external-link").forEach((elem) =>
elem.addEventListener("click", function (event) {
openExternal(event.target.getAttribute("data-url"));
openExternal((event.target as HTMLElement).getAttribute("data-url"));
})
);
function addInputListener(source, key) {
source.addEventListener("input", function (_event, _data) {
if (this.value === "on") {
function addInputListener(source: HTMLInputElement, key: string) {
source.addEventListener("input", () => {
if (source.value === "on") {
store.set(key, source.checked);
} else {
store.set(key, this.value);
store.set(key, source.value);
}
ipcRenderer.send(globalEvents.storeChanged);
});
}
function addTextAreaListener(source, key) {
source.addEventListener("input", function (_event, _data) {
function addTextAreaListener(source: HTMLInputElement, key: string) {
source.addEventListener("input", () => {
store.set(key, source.value.split("\n"));
ipcRenderer.send(globalEvents.storeChanged);
});

View File

@@ -1,17 +1,17 @@
const { setTitle } = require("./scripts/window-functions");
const { dialog, process, Notification } = require("@electron/remote");
import { Notification, app, dialog } from "@electron/remote";
import { ipcRenderer } from "electron";
import { Options } from "./models/options";
import { downloadFile } from "./scripts/download";
import { addHotkey } from "./scripts/hotkeys";
import { setTitle } from "./scripts/window-functions";
const { store, settings } = require("./scripts/settings");
const { ipcRenderer } = require("electron");
const { app } = require("@electron/remote");
const { downloadFile } = require("./scripts/download");
const notificationPath = `${app.getPath("userData")}/notification.jpg`;
const statuses = require("./constants/statuses");
const hotkeys = require("./scripts/hotkeys");
const globalEvents = require("./constants/globalEvents");
const { skipArtists, updateFrequency, customCSS } = require("./constants/settings");
const notificationPath = `${app.getPath("userData")}/notification.jpg`;
const appName = "Tidal Hifi";
let currentSong = "";
let player;
let player: any;
let currentPlayStatus = statuses.paused;
const elements = {
@@ -45,7 +45,7 @@ const elements = {
* Get an element from the dom
* @param {*} key key in elements object to fetch
*/
get: function (key) {
get: function (key: string) {
return window.document.querySelector(this[key.toLowerCase()]);
},
@@ -74,7 +74,7 @@ const elements = {
if (footer) {
const artists = footer.querySelectorAll(this.artists);
if (artists) return Array.from(artists).map((artist) => artist.textContent);
if (artists) return Array.from(artists).map((artist) => (artist as HTMLElement).textContent);
}
return [];
},
@@ -84,7 +84,7 @@ const elements = {
* @param {Array} artistsArray
* @returns {String} artists
*/
getArtistsString: function (artistsArray) {
getArtistsString: function (artistsArray: string[]) {
if (artistsArray.length > 0) return artistsArray.join(", ");
return "unknown artist(s)";
},
@@ -120,7 +120,7 @@ const elements = {
* Shorthand function to get the text of a dom element
* @param {*} key key in elements object to fetch
*/
getText: function (key) {
getText: function (key: string) {
const element = this.get(key);
return element ? element.textContent : "";
},
@@ -129,7 +129,7 @@ const elements = {
* Shorthand function to click a dom element
* @param {*} key key in elements object to fetch
*/
click: function (key) {
click: function (key: string) {
this.get(key).click();
return this;
},
@@ -138,7 +138,7 @@ const elements = {
* Shorthand function to focus a dom element
* @param {*} key key in elements object to fetch
*/
focus: function (key) {
focus: function (key: string) {
return this.get(key).focus();
},
};
@@ -186,40 +186,40 @@ function playPause() {
*/
function addHotKeys() {
if (store.get(settings.enableCustomHotkeys)) {
hotkeys.add("Control+p", function () {
addHotkey("Control+p", function () {
elements.click("account").click("settings");
});
hotkeys.add("Control+l", function () {
addHotkey("Control+l", function () {
handleLogout();
});
hotkeys.add("Control+h", function () {
addHotkey("Control+h", function () {
elements.click("home");
});
hotkeys.add("backspace", function () {
addHotkey("backspace", function () {
elements.click("back");
});
hotkeys.add("shift+backspace", function () {
addHotkey("shift+backspace", function () {
elements.click("forward");
});
hotkeys.add("control+u", function () {
addHotkey("control+u", function () {
// reloading window without cache should show the update bar if applicable
window.location.reload(true);
window.location.reload();
});
hotkeys.add("control+r", function () {
addHotkey("control+r", function () {
elements.click("repeat");
});
}
// always add the hotkey for the settings window
hotkeys.add("control+=", function () {
addHotkey("control+=", function () {
ipcRenderer.send(globalEvents.showSettings);
});
hotkeys.add("control+0", function () {
addHotkey("control+0", function () {
ipcRenderer.send(globalEvents.showSettings);
});
}
@@ -231,28 +231,26 @@ function addHotKeys() {
function handleLogout() {
const logoutOptions = ["Cancel", "Yes, please", "No, thanks"];
dialog.showMessageBox(
null,
{
dialog
.showMessageBox(null, {
type: "question",
title: "Logging out",
message: "Are you sure you want to log out?",
buttons: logoutOptions,
defaultId: 2,
},
function (response) {
if (logoutOptions.indexOf("Yes, please") == response) {
})
.then((result: { response: number }) => {
if (logoutOptions.indexOf("Yes, please") == result.response) {
for (let i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);
if (key.startsWith("_TIDAL_activeSession")) {
window.localStorage.removeItem(key);
i = window.localStorage.length + 1;
break;
}
}
window.location.reload();
}
}
);
});
}
function addFullScreenListeners() {
@@ -309,7 +307,7 @@ function getCurrentlyPlayingStatus() {
* Convert the duration from MM:SS to seconds
* @param {*} duration
*/
function convertDuration(duration) {
function convertDuration(duration: string) {
const parts = duration.split(":");
return parseInt(parts[1]) + 60 * parseInt(parts[0]);
}
@@ -319,7 +317,7 @@ function convertDuration(duration) {
*
* @param {*} options
*/
function updateMediaInfo(options, notify) {
function updateMediaInfo(options: Options, notify: boolean) {
if (options) {
ipcRenderer.send(globalEvents.updateInfo, options);
if (store.get(settings.notifications) && notify) {
@@ -361,7 +359,7 @@ function getTrackID() {
return window.location;
}
function updateMediaSession(options) {
function updateMediaSession(options: Options) {
if ("mediaSession" in navigator) {
navigator.mediaSession.metadata = new MediaMetadata({
title: options.title,
@@ -401,6 +399,8 @@ setInterval(function () {
current,
duration,
"app-name": appName,
image: "",
icon: "",
};
const titleOrArtistsChanged = currentSong !== songDashArtistTitle;
@@ -413,7 +413,7 @@ setInterval(function () {
const image = elements.getSongIcon();
new Promise((resolve) => {
new Promise<void>((resolve) => {
if (image.startsWith("http")) {
options.image = image;
downloadFile(image, notificationPath).then(
@@ -444,9 +444,9 @@ setInterval(function () {
* automatically skip a song if the artists are found in the list of artists to skip
* @param {*} artists array of artists
*/
function skipArtistsIfFoundInSkippedArtistsList(artists) {
function skipArtistsIfFoundInSkippedArtistsList(artists: string[]) {
if (store.get(skipArtists)) {
const skippedArtists = store.get(settings.skippedArtists);
const skippedArtists = store.get(settings.skippedArtists) as string[];
if (skippedArtists.length > 0) {
const artistsToSkip = skippedArtists.map((artist) => artist);
const artistNames = Object.values(artists).map((artist) => artist);
@@ -478,7 +478,7 @@ if (process.platform === "linux" && store.get(settings.mpris)) {
});
// Events
var events = {
const events = {
next: "next",
previous: "previous",
pause: "pause",
@@ -488,7 +488,7 @@ if (process.platform === "linux" && store.get(settings.mpris)) {
loopStatus: "repeat",
shuffle: "shuffle",
seek: "seek",
};
} as { [key: string]: string };
Object.keys(events).forEach(function (eventName) {
player.on(eventName, function () {
const eventValue = events[eventName];

View File

@@ -1,26 +0,0 @@
const download = {};
const request = require("request");
const fs = require("fs");
/**
* download and save a file
* @param {*} fileUrl url to download
* @param {*} targetPath path to save it at
*/
download.downloadFile = function(fileUrl, targetPath) {
return new Promise((resolve, reject) => {
var req = request({
method: "GET",
uri: fileUrl,
});
var out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on("end", resolve);
req.on("error", reject);
});
};
module.exports = download;

23
src/scripts/download.ts Normal file
View File

@@ -0,0 +1,23 @@
import fs from "fs";
import request from "request";
/**
* download and save a file
* @param {string} fileUrl url to download
* @param {string} targetPath path to save it at
*/
export const downloadFile = function (fileUrl: string, targetPath: string) {
return new Promise((resolve, reject) => {
const req = request({
method: "GET",
uri: fileUrl,
});
const out = fs.createWriteStream(targetPath);
req.pipe(out);
req.on("end", resolve);
req.on("error", reject);
});
};

View File

@@ -1,23 +1,23 @@
const express = require("express");
import { BrowserWindow } from "electron";
import express, { Response } from "express";
import fs from "fs";
const { mediaInfo } = require("./mediaInfo");
const { store, settings } = require("./settings");
const globalEvents = require("./../constants/globalEvents");
const statuses = require("./../constants/statuses");
const expressModule = {};
const fs = require("fs");
let expressInstance;
/**
* Function to enable tidal-hifi's express api
*/
expressModule.run = function (mainWindow) {
// expressModule.run = function (mainWindow)
export const startExpress = (mainWindow: BrowserWindow) => {
/**
* Shorthand to handle a fire and forget global event
* @param {*} res
* @param {*} action
*/
function handleGlobalEvent(res, action) {
function handleGlobalEvent(res: Response, action: any) {
mainWindow.webContents.send("globalEvent", action);
res.sendStatus(200);
}
@@ -26,7 +26,7 @@ expressModule.run = function (mainWindow) {
expressApp.get("/", (req, res) => res.send("Hello World!"));
expressApp.get("/current", (req, res) => res.json({ ...mediaInfo, artist: mediaInfo.artists }));
expressApp.get("/image", (req, res) => {
var stream = fs.createReadStream(mediaInfo.icon);
const stream = fs.createReadStream(mediaInfo.icon);
stream.on("open", function () {
res.set("Content-Type", "image/png");
stream.pipe(res);
@@ -50,21 +50,16 @@ expressModule.run = function (mainWindow) {
}
});
}
if (store.get(settings.api)) {
let port = store.get(settings.apiSettings.port);
expressInstance = expressApp.listen(port, "127.0.0.1", () => {});
expressInstance.on("error", function (e) {
let message = e.code;
if (e.code === "EADDRINUSE") {
message = `Port ${port} in use.`;
}
const { dialog } = require("electron");
dialog.showErrorBox("Api failed to start.", message);
});
} else {
expressInstance = undefined;
}
let port = store.get(settings.apiSettings.port);
const expressInstance = expressApp.listen(port, "127.0.0.1", () => {});
expressInstance.on("error", function (e: { code: string }) {
let message = e.code;
if (e.code === "EADDRINUSE") {
message = `Port ${port} in use.`;
}
const { dialog } = require("electron");
dialog.showErrorBox("Api failed to start.", message);
});
};
module.exports = expressModule;

View File

@@ -1,11 +0,0 @@
const hotkeyjs = require("hotkeys-js");
const hotkeys = {};
hotkeys.add = function(keys, func) {
hotkeyjs(keys, function(event, args) {
event.preventDefault();
func(event, args);
});
};
module.exports = hotkeys;

11
src/scripts/hotkeys.ts Normal file
View File

@@ -0,0 +1,11 @@
import hotkeyjs, { HotkeysEvent } from "hotkeys-js";
export const addHotkey = function (
keys: string,
func: (event?: KeyboardEvent, args?: HotkeysEvent) => void
) {
hotkeyjs(keys, function (event, args) {
event.preventDefault();
func(event, args);
});
};

View File

@@ -1,4 +1,4 @@
const { Menu, app } = require("electron");
import { BrowserWindow, Menu, app } from "electron";
const { showSettingsWindow } = require("./settings");
const isMac = process.platform === "darwin";
const { name } = require("./../constants/values");
@@ -19,9 +19,7 @@ const quitMenuEntry = {
accelerator: "Control+Q",
};
const menuModule = {};
menuModule.getMenu = function (mainWindow) {
export const getMenu = function (mainWindow: BrowserWindow) {
const toggleWindow = {
label: "Toggle Window",
click: function () {
@@ -113,11 +111,9 @@ menuModule.getMenu = function (mainWindow) {
quitMenuEntry,
];
return Menu.buildFromTemplate(mainMenu);
return Menu.buildFromTemplate(mainMenu as any);
};
menuModule.addMenu = function (mainWindow) {
Menu.setApplicationMenu(menuModule.getMenu(mainWindow));
export const addMenu = function (mainWindow: BrowserWindow) {
Menu.setApplicationMenu(getMenu(mainWindow));
};
module.exports = menuModule;

View File

@@ -1,5 +1,6 @@
const Store = require("electron-store");
const settings = require("./../constants/settings");
const settings = require("../constants/settings");
const path = require("path");
const { BrowserWindow } = require("electron");

View File

@@ -1,9 +1,10 @@
const { Tray } = require("electron");
const { getMenu } = require("./menu");
const trayModule = {};
let tray;
import { BrowserWindow, Tray } from "electron";
trayModule.addTray = function (mainWindow, options = { icon: "" }) {
const { getMenu } = require("./menu");
let tray: Tray;
export const addTray = function (mainWindow: BrowserWindow, options = { icon: "" }) {
tray = new Tray(options.icon);
tray.setIgnoreDoubleClickEvents(true);
tray.setToolTip("Tidal-hifi");
@@ -25,10 +26,8 @@ trayModule.addTray = function (mainWindow, options = { icon: "" }) {
});
};
trayModule.refreshTray = function (mainWindow) {
export const refreshTray = function (mainWindow: BrowserWindow) {
if (!tray) {
trayModule.addTray(mainWindow);
addTray(mainWindow);
}
};
module.exports = trayModule;

View File

@@ -1,11 +0,0 @@
const windowFunctions = {};
windowFunctions.setTitle = function(title) {
window.document.title = title;
};
windowFunctions.getTitle = function() {
return window.document.title;
};
module.exports = windowFunctions;

View File

@@ -0,0 +1,7 @@
export const setTitle = function (title: string) {
window.document.title = title;
};
export const getTitle = function () {
return window.document.title;
};