mirror of
https://github.com/MasterAcnolo/Freedom-Loader.git
synced 2026-07-29 18:25:47 +02:00
refactor: add full documentation and fix theme loading robustness
- Add JSDoc comments across frontend and backend modules - Improve code readability and maintainability with consistent documentation style - Document Electron IPC handlers, UI utilities, and theme system - Add missing function/class documentation in theme loader and app services - Minor structural improvements and cleanup across Electron main process modules - Minor fixes on variable names
This commit is contained in:
@@ -1,11 +1,42 @@
|
||||
/**
|
||||
* Electron auto-update system using electron-updater.
|
||||
*
|
||||
* Handles:
|
||||
* - update detection
|
||||
* - user confirmation dialogs
|
||||
* - download progress streaming to renderer
|
||||
* - application restart and installation
|
||||
*/
|
||||
|
||||
const { autoUpdater } = require("electron-updater");
|
||||
const { dialog } = require("electron");
|
||||
const { logger } = require("../server/logger");
|
||||
|
||||
/**
|
||||
* Configures autoUpdater behavior:
|
||||
* - disables automatic download
|
||||
* - disables automatic install on quit
|
||||
* (manual user-controlled update flow)
|
||||
*/
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
|
||||
/**
|
||||
* Initializes application auto-update lifecycle.
|
||||
*
|
||||
* Registers update event listeners and binds them to:
|
||||
* - UI dialogs (Electron dialog)
|
||||
* - renderer communication (webContents)
|
||||
* - download/install flow control
|
||||
*
|
||||
* @param {BrowserWindow} mainWindow - main Electron window instance
|
||||
*/
|
||||
function initAutoUpdater(mainWindow) {
|
||||
|
||||
/**
|
||||
* Triggered when a new version is detected.
|
||||
* Prompts user to install or defer update.
|
||||
*/
|
||||
autoUpdater.on("update-available", async (info) => {
|
||||
logger.info(`Update available: ${info.version}`);
|
||||
|
||||
@@ -28,6 +59,10 @@ function initAutoUpdater(mainWindow) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Streams update download progress to renderer process.
|
||||
* Used to update UI progress bar and status indicators.
|
||||
*/
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
logger.info(`Download progress: ${Math.round(progress.percent)}%`);
|
||||
mainWindow?.webContents.send("update-progress", {
|
||||
@@ -36,6 +71,10 @@ function initAutoUpdater(mainWindow) {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Triggered when update has been fully downloaded.
|
||||
* Prompts user to restart application and install update.
|
||||
*/
|
||||
autoUpdater.on("update-downloaded", async (info) => {
|
||||
logger.info(`Update downloaded: ${info.version}`);
|
||||
|
||||
@@ -52,6 +91,10 @@ function initAutoUpdater(mainWindow) {
|
||||
if (response === 0) autoUpdater.quitAndInstall();
|
||||
});
|
||||
|
||||
/**
|
||||
* Handles update system errors.
|
||||
* Logs failure and displays an error dialog to user.
|
||||
*/
|
||||
autoUpdater.on("error", (err) => {
|
||||
logger.error("Auto update error:", err.message);
|
||||
dialog.showErrorBox("Update Error", err.message);
|
||||
@@ -60,6 +103,10 @@ function initAutoUpdater(mainWindow) {
|
||||
checkForUpdates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually triggers update check on startup.
|
||||
* Separated from init for reusability and testability.
|
||||
*/
|
||||
async function checkForUpdates() {
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
@@ -68,6 +115,10 @@ async function checkForUpdates() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually triggers update download.
|
||||
* Used when user accepts update prompt.
|
||||
*/
|
||||
async function downloadUpdate() {
|
||||
try {
|
||||
await autoUpdater.downloadUpdate();
|
||||
@@ -76,6 +127,9 @@ async function downloadUpdate() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediately quits application and installs downloaded update.
|
||||
*/
|
||||
function installUpdate() {
|
||||
autoUpdater.quitAndInstall();
|
||||
}
|
||||
|
||||
@@ -2,9 +2,33 @@ const fs = require("fs");
|
||||
const { app, dialog } = require("electron");
|
||||
const { logger } = require("../server/logger");
|
||||
|
||||
/**
|
||||
* Verifies that all required native binaries exist before the app starts.
|
||||
*
|
||||
* This includes:
|
||||
* - yt-dlp (download engine)
|
||||
* - ffmpeg (media processing)
|
||||
* - ffprobe (media inspection)
|
||||
* - deno (JS runtime used by yt-dlp hooks)
|
||||
*
|
||||
* If any dependency is missing:
|
||||
* - logs the error
|
||||
* - shows a blocking Electron error dialog
|
||||
* - exits the application
|
||||
*
|
||||
* @returns {boolean} true if all dependencies are present, false otherwise
|
||||
*/
|
||||
function checkNativeDependencies() {
|
||||
/**
|
||||
* Native dependency paths are resolved at runtime from the server helpers.
|
||||
* This ensures correct resolution in both dev and packaged builds.
|
||||
*/
|
||||
const { binaryPaths } = require("../server/helpers/path.helpers");
|
||||
|
||||
/**
|
||||
* List of required external executables used by the application runtime.
|
||||
* Each entry defines a binary name and its resolved absolute path.
|
||||
*/
|
||||
const deps = [
|
||||
{ name: "yt-dlp.exe", path: binaryPaths.ytDlp },
|
||||
{ name: "ffmpeg.exe", path: binaryPaths.ffmpeg },
|
||||
@@ -15,9 +39,16 @@ function checkNativeDependencies() {
|
||||
const missing = deps.filter(d => !fs.existsSync(d.path));
|
||||
if (missing.length === 0) return true;
|
||||
|
||||
/**
|
||||
* Human-readable list of missing binaries for logging and user dialog display.
|
||||
*/
|
||||
const list = missing.map(d => d.name).join(", ");
|
||||
logger.error(`Missing dependencies: ${list}`);
|
||||
|
||||
/**
|
||||
* Defers error dialog until Electron app is fully initialized.
|
||||
* Required to safely display modal dialogs before quit.
|
||||
*/
|
||||
app.whenReady().then(() => {
|
||||
dialog.showErrorBox(
|
||||
"Missing dependencies",
|
||||
|
||||
@@ -2,12 +2,40 @@ const config = require('../config');
|
||||
const RPC = require("discord-rpc");
|
||||
const { logger } = require("../server/logger");
|
||||
|
||||
/**
|
||||
* Discord Application Client ID used to authenticate the RPC connection.
|
||||
* Comes from the application configuration.
|
||||
*/
|
||||
const clientId = `${config.DiscordRPCID}`;
|
||||
|
||||
/**
|
||||
* Discord RPC client instance using IPC transport.
|
||||
* Maintains a persistent connection with Discord desktop client.
|
||||
*/
|
||||
const rpc = new RPC.Client({ transport: "ipc" });
|
||||
|
||||
/**
|
||||
* Optional interval reference used for future RPC refresh logic.
|
||||
* Currently reserved for potential periodic activity updates.
|
||||
*/
|
||||
let intervalId;
|
||||
|
||||
/**
|
||||
* Initializes Discord Rich Presence (RPC) connection.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Connect to Discord via IPC transport
|
||||
* - Set application presence (title, state, timestamps, assets)
|
||||
* - Handle connection errors gracefully via logger
|
||||
*
|
||||
* Triggered once during application startup.
|
||||
*/
|
||||
function startRPC() {
|
||||
|
||||
/**
|
||||
* Rich Presence payload describing current application state
|
||||
* shown in Discord user profile.
|
||||
*/
|
||||
rpc.on("ready", () => {
|
||||
const presence = {
|
||||
largeImageKey: "icon",
|
||||
@@ -27,10 +55,22 @@ function startRPC() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gracefully stops Discord Rich Presence connection.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Clear any running intervals
|
||||
* - Remove current activity from Discord
|
||||
* - Destroy RPC transport connection
|
||||
* - Handle cleanup errors safely
|
||||
*/
|
||||
async function stopRPC(){
|
||||
try {
|
||||
if (intervalId) clearInterval(intervalId);
|
||||
|
||||
/**
|
||||
* Ensures RPC connection exists before attempting cleanup.
|
||||
*/
|
||||
if (rpc && rpc.transport) {
|
||||
await rpc.clearActivity()
|
||||
await rpc.destroy();
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
/**
|
||||
* Electron IPC main process registry.
|
||||
*
|
||||
* Centralizes all IPC channels exposed to renderer process:
|
||||
* - Application info (version, features)
|
||||
* - Window controls (topbar actions)
|
||||
* - File system interactions (theme, config, download paths)
|
||||
* - UI state synchronization (progress bar)
|
||||
*
|
||||
* Acts as the bridge between renderer and privileged Node/Electron APIs.
|
||||
*/
|
||||
|
||||
const { ipcMain, dialog, shell } = require("electron");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
@@ -8,6 +20,12 @@ const config = require("../config");
|
||||
const { validateDownloadPath, getDefaultDownloadPath } = require("./pathValidator");
|
||||
const { userThemesPath } = require("../server/helpers/path.helpers");
|
||||
|
||||
/**
|
||||
* Security whitelist for feature flags that can be modified at runtime.
|
||||
*
|
||||
* Prevents unauthorized or unexpected configuration keys from being persisted.
|
||||
* Acts as a basic validation layer for IPC "set-feature".
|
||||
*/
|
||||
const FEATURE_WHITELIST = new Set([
|
||||
"autoUpdate",
|
||||
"discordRPC",
|
||||
@@ -23,17 +41,45 @@ const FEATURE_WHITELIST = new Set([
|
||||
"notifySystem"
|
||||
]);
|
||||
|
||||
/**
|
||||
* Absolute path to the configuration file storing feature flags.
|
||||
*/
|
||||
const configFolderPath = featuresPath;
|
||||
|
||||
/**
|
||||
* Directory containing user-installed themes.
|
||||
*/
|
||||
const themeFolderPath = userThemesPath;
|
||||
|
||||
/**
|
||||
* Registers all IPC handlers and event listeners for Electron main process.
|
||||
*
|
||||
* This function wires renderer → main communication channels:
|
||||
* - synchronous queries (handle)
|
||||
* - fire-and-forget events (on)
|
||||
*
|
||||
* @param {Function} getMainWindow - Function returning current BrowserWindow instance
|
||||
*/
|
||||
function registerIpcHandlers(getMainWindow) {
|
||||
|
||||
// Infos générales
|
||||
ipcMain.handle("version", () => config.version);
|
||||
/**
|
||||
* Returns application version from config.
|
||||
*/
|
||||
ipcMain.handle("version", () => config.version);
|
||||
|
||||
/**
|
||||
* Returns runtime feature configuration object.
|
||||
*/
|
||||
ipcMain.handle("features", () => configFeatures);
|
||||
|
||||
// Sélection et validation de dossier
|
||||
/**
|
||||
* Opens native folder selection dialog and validates selected path.
|
||||
*
|
||||
* Ensures:
|
||||
* - user cancellation is handled safely
|
||||
* - selected path is validated against security rules
|
||||
* - unsafe directories are rejected
|
||||
*/
|
||||
ipcMain.handle("select-download-folder", async () => {
|
||||
const result = await dialog.showOpenDialog({ properties: ["openDirectory"] });
|
||||
if (result.canceled) {
|
||||
@@ -53,48 +99,108 @@ function registerIpcHandlers(getMainWindow) {
|
||||
ipcMain.handle("validate-download-path", (_, userPath) => validateDownloadPath(userPath));
|
||||
ipcMain.handle("get-default-download-path", () => getDefaultDownloadPath());
|
||||
|
||||
// Progression dans la taskbar
|
||||
/**
|
||||
* Updates Windows/macOS taskbar progress indicator.
|
||||
*
|
||||
* @param {number} percent - Progress value (0–100)
|
||||
*/
|
||||
ipcMain.on("set-progress", (_, percent) => {
|
||||
getMainWindow()?.setProgressBar(percent / 100);
|
||||
});
|
||||
|
||||
// TOPBAR ACTION
|
||||
/**
|
||||
* Window minimize request from renderer.
|
||||
*/
|
||||
ipcMain.on("window-minimize", () => getMainWindow()?.minimize());
|
||||
|
||||
/**
|
||||
* Toggles maximize/unmaximize state of main window.
|
||||
*/
|
||||
ipcMain.on("window-maximize", () => {
|
||||
const win = getMainWindow();
|
||||
if (!win) return;
|
||||
win.isMaximized() ? win.unmaximize() : win.maximize();
|
||||
});
|
||||
|
||||
/**
|
||||
* Closes the main application window.
|
||||
*/
|
||||
ipcMain.on("window-close", () => getMainWindow()?.close());
|
||||
|
||||
|
||||
/**
|
||||
* Opens Chromium DevTools in detached mode.
|
||||
*/
|
||||
ipcMain.on("open-devtools", () =>
|
||||
getMainWindow()?.webContents.openDevTools({ mode: "detach" })
|
||||
);
|
||||
|
||||
/**
|
||||
* Opens application logs directory in system file explorer.
|
||||
*/
|
||||
ipcMain.on("open-logs", () => logDir && shell.openPath(logDir));
|
||||
|
||||
/**
|
||||
* Opens external website in default browser.
|
||||
*/
|
||||
ipcMain.on("open-website", () =>
|
||||
shell.openExternal("https://masteracnolo.github.io/Freedom-Loader-Site/")
|
||||
);
|
||||
|
||||
/**
|
||||
* Opens official wiki page in external browser.
|
||||
*/
|
||||
ipcMain.on("open-wiki", () =>
|
||||
shell.openExternal("https://masteracnolo.github.io/Freedom-Loader-Site/wiki")
|
||||
);
|
||||
|
||||
/**
|
||||
* Opens workshop page in external browser.
|
||||
*/
|
||||
ipcMain.on("open-workshop", () =>
|
||||
shell.openExternal("https://masteracnolo.github.io/Freedom-Loader-Workshop")
|
||||
);
|
||||
|
||||
/**
|
||||
* Opens configuration folder in system file explorer.
|
||||
*/
|
||||
ipcMain.on("open-config", () => shell.openPath(configFolderPath));
|
||||
|
||||
|
||||
|
||||
// THEME
|
||||
/**
|
||||
* Retrieves available themes from filesystem.
|
||||
*/
|
||||
ipcMain.handle("get-themes", () => getThemes());
|
||||
|
||||
/**
|
||||
* Opens theme directory in file explorer.
|
||||
*/
|
||||
ipcMain.on("open-theme", () => shell.openPath(themeFolderPath));
|
||||
|
||||
/**
|
||||
* Reloads themes from disk dynamically.
|
||||
*/
|
||||
ipcMain.handle("reload-themes", async () => {
|
||||
return await reloadThemes();
|
||||
});
|
||||
|
||||
// Modification des features
|
||||
/**
|
||||
* Updates a runtime feature flag and persists it to disk.
|
||||
*
|
||||
* Flow:
|
||||
* - Validates key against whitelist
|
||||
* - Prevents unnecessary writes if value is unchanged
|
||||
* - Updates in-memory config object
|
||||
* - Persists to configuration file
|
||||
*
|
||||
* Security note:
|
||||
* Only whitelisted keys can be modified via IPC to prevent config injection.
|
||||
*
|
||||
* @param {Electron.IpcMainEvent} event
|
||||
* @param {{key: string, value: any}} payload
|
||||
* @returns {boolean} success state
|
||||
*/
|
||||
ipcMain.handle("set-feature", (event, { key, value }) => {
|
||||
try {
|
||||
if (!FEATURE_WHITELIST.has(key)) {
|
||||
|
||||
@@ -2,28 +2,77 @@ const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { logger } = require("../server/logger");
|
||||
|
||||
/**
|
||||
* Cached resolved default download path.
|
||||
* Initialized lazily on first access to avoid unnecessary imports.
|
||||
*/
|
||||
let _defaultPath = null;
|
||||
|
||||
/**
|
||||
* Returns the application's default download directory.
|
||||
*
|
||||
* This value is lazily loaded and cached after first call.
|
||||
* The path originates from server configuration helpers.
|
||||
*
|
||||
* @returns {string} Absolute default download path
|
||||
*/
|
||||
function getDefaultDownloadPath() {
|
||||
|
||||
if (!_defaultPath) {
|
||||
|
||||
/**
|
||||
* Lazy-loaded dependency providing the configured default download folder.
|
||||
* Required only when function is executed to reduce startup cost.
|
||||
*/
|
||||
const { defaultDownloadFolder } = require("../server/helpers/path.helpers");
|
||||
|
||||
_defaultPath = defaultDownloadFolder;
|
||||
|
||||
}
|
||||
return _defaultPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and sanitizes a user-provided download path.
|
||||
*
|
||||
* Steps performed:
|
||||
* - Resolves absolute real filesystem path
|
||||
* - Normalizes symbolic links via realpathSync
|
||||
* - Checks path safety rules (blocks system-critical directories)
|
||||
* - Falls back to default path if input is empty
|
||||
*
|
||||
* @param {string} userPath - User-provided directory path
|
||||
* @returns {string} Sanitized absolute path
|
||||
* @throws Error If path is invalid, unsafe, or inaccessible
|
||||
*/
|
||||
function validateDownloadPath(userPath) {
|
||||
|
||||
/**
|
||||
* Lazy-loaded helper used to enforce safe directory constraints.
|
||||
* Prevents writes to protected system folders.
|
||||
*/
|
||||
const { isSafePath } = require("../server/helpers/validation.helpers");
|
||||
|
||||
if (!userPath) return getDefaultDownloadPath();
|
||||
|
||||
try {
|
||||
|
||||
/**
|
||||
* Resolves filesystem symlinks to ensure canonical absolute path.
|
||||
* Required to prevent path traversal or alias bypass.
|
||||
*/
|
||||
const resolved = fs.realpathSync(path.resolve(userPath));
|
||||
if (!isSafePath(resolved)) {
|
||||
throw new Error("Path not allowed: system folders are blocked!");
|
||||
}
|
||||
return resolved;
|
||||
} catch (err) {
|
||||
}
|
||||
catch (err) {
|
||||
|
||||
/**
|
||||
* Handles invalid filesystem paths, permissions issues, or resolution failures.
|
||||
* Logs diagnostic information before propagating a sanitized error.
|
||||
*/
|
||||
logger.error(`Invalid download path: ${userPath} — ${err.message}`);
|
||||
throw new Error(`Invalid or inaccessible path: ${err.message}`);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
const { BrowserWindow, app } = require("electron");
|
||||
const path = require("path");
|
||||
|
||||
/**
|
||||
* Reference to the splash screen BrowserWindow instance.
|
||||
* Used during application startup before main window is ready.
|
||||
*/
|
||||
let splashWindow = null;
|
||||
|
||||
/**
|
||||
* Creates and displays the splash screen window.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Initializes a frameless, always-on-top splash window
|
||||
* - Loads splash HTML UI
|
||||
* - Dynamically injects banner image depending on dev/production mode
|
||||
* - Acts as startup visual feedback before main window loads
|
||||
*/
|
||||
function createSplashWindow() {
|
||||
|
||||
const splashOptions = {
|
||||
/**
|
||||
* Configuration for splash screen BrowserWindow.
|
||||
* Optimized for minimal UI and fast startup display.
|
||||
*/
|
||||
const splashOptions = {
|
||||
width: 400,
|
||||
height: 300,
|
||||
frame: false,
|
||||
@@ -19,13 +36,29 @@ const splashOptions = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Instantiates the splash screen window.
|
||||
*/
|
||||
splashWindow = new BrowserWindow(splashOptions);
|
||||
|
||||
/**
|
||||
* Absolute path to splash HTML file used as initial UI.
|
||||
* Loaded locally from application bundle or project folder.
|
||||
*/
|
||||
const splashPath = path.join(__dirname, "../public/splash.html");
|
||||
splashWindow.loadFile(splashPath);
|
||||
|
||||
// Inject banner path for both dev and packaged app
|
||||
/**
|
||||
* Executes once splash HTML is fully loaded.
|
||||
* Used here to inject dynamic assets (banner image path).
|
||||
*/
|
||||
splashWindow.webContents.on('did-finish-load', () => {
|
||||
|
||||
/**
|
||||
* Resolves splash banner image path depending on runtime mode:
|
||||
* - Production: bundled resources directory
|
||||
* - Development: local build directory
|
||||
*/
|
||||
let bannerPath;
|
||||
|
||||
// Check if app is packaged
|
||||
@@ -36,12 +69,21 @@ const splashOptions = {
|
||||
bannerPath = path.join(__dirname, '../build/banner.png');
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects runtime image source into splash DOM.
|
||||
* Uses file:// protocol to load local image safely in Electron context.
|
||||
*/
|
||||
splashWindow.webContents.executeJavaScript(`
|
||||
document.querySelector('img[alt="Freedom Loader"]').src = 'file:///${bannerPath.replace(/\\/g, '/')}';
|
||||
`);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes and cleans up the splash screen window.
|
||||
*
|
||||
* Should be called once main window is ready to display.
|
||||
*/
|
||||
function closeSplashWindow() {
|
||||
if (splashWindow) {
|
||||
splashWindow.close();
|
||||
@@ -49,6 +91,13 @@ function closeSplashWindow() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates splash screen progress indicator from main process.
|
||||
*
|
||||
* Sends a step value to renderer via injected JS function.
|
||||
*
|
||||
* @param {number} step - Current initialization step or progress value
|
||||
*/
|
||||
function setSplashProgress(step) {
|
||||
if (splashWindow) {
|
||||
splashWindow.webContents.executeJavaScript(`window.setProgress(${step})`);
|
||||
|
||||
@@ -1,14 +1,48 @@
|
||||
/**
|
||||
* Theme loading and parsing system.
|
||||
*
|
||||
* Supports:
|
||||
* - Folder-based themes
|
||||
* - ZIP-based themes
|
||||
* - Theme validation against required schema
|
||||
* - Image embedding as base64 data URIs
|
||||
* - Cached theme registry with sorted priority order
|
||||
*
|
||||
* Acts as the core theme ingestion pipeline for the application UI.
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { logger } = require("../server/logger");
|
||||
const JSZip = require("jszip");
|
||||
|
||||
/**
|
||||
* Maximum allowed size (in bytes) for theme images.
|
||||
* Prevents memory abuse from large embedded assets.
|
||||
*/
|
||||
const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* List of supported image file extensions for theme assets.
|
||||
*/
|
||||
const ALLOWED_IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".gif", ".avif"];
|
||||
|
||||
/**
|
||||
* Allowed base filenames for theme background/cover images.
|
||||
* Restricts theme asset resolution to known conventions.
|
||||
*/
|
||||
const ALLOWED_IMAGE_NAMES = ["cover", "background"];
|
||||
|
||||
/**
|
||||
* Priority order used to sort themes in UI.
|
||||
* Themes not listed are placed at the end.
|
||||
*/
|
||||
const THEME_ORDER = ["dark", "light"];
|
||||
|
||||
/**
|
||||
* Required JSON schema paths for a valid theme definition.
|
||||
* Each entry represents a nested property path that must exist.
|
||||
*/
|
||||
const REQUIRED_KEYS = [
|
||||
["meta", "name"],
|
||||
["meta", "author"],
|
||||
@@ -20,10 +54,25 @@ const REQUIRED_KEYS = [
|
||||
["style", "progressBar", "fill"],
|
||||
];
|
||||
|
||||
/**
|
||||
* Safely retrieves a deeply nested value from an object using a key path array.
|
||||
*
|
||||
* @param {object} obj - Target object
|
||||
* @param {string[]} keys - Property path segments
|
||||
* @returns {*} value or undefined if path is invalid
|
||||
*/
|
||||
function getNestedValue(obj, keys) {
|
||||
return keys.reduce((acc, key) => acc?.[key], obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates theme JSON structure against required schema.
|
||||
*
|
||||
* Ensures all mandatory configuration keys exist before theme is accepted.
|
||||
*
|
||||
* @param {object} json - Parsed theme JSON
|
||||
* @returns {{valid: boolean, reason?: string}}
|
||||
*/
|
||||
function validateThemeJson(json) {
|
||||
for (const keyPath of REQUIRED_KEYS) {
|
||||
if (getNestedValue(json, keyPath) === undefined) {
|
||||
@@ -33,6 +82,14 @@ function validateThemeJson(json) {
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes raw theme JSON into application-ready theme object.
|
||||
*
|
||||
* @param {string} themeId
|
||||
* @param {object} themeJson
|
||||
* @param {string|null} imageData - Base64 encoded theme image
|
||||
* @returns {object} normalized theme object
|
||||
*/
|
||||
function buildThemeObject(themeId, themeJson, imageData) {
|
||||
return {
|
||||
id: themeId.toLowerCase(),
|
||||
@@ -45,6 +102,17 @@ function buildThemeObject(themeId, themeJson, imageData) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts and encodes an image from theme archive into base64 data URI.
|
||||
*
|
||||
* Applies safety checks:
|
||||
* - Rejects images exceeding MAX_IMAGE_SIZE
|
||||
* - Converts file extension into valid MIME type
|
||||
*
|
||||
* @param {Buffer} buffer
|
||||
* @param {string} filename
|
||||
* @returns {string|null} data URI or null if invalid
|
||||
*/
|
||||
function extractImage(buffer, filename) {
|
||||
if (buffer.length > MAX_IMAGE_SIZE) {
|
||||
logger.warn(`Image too large, ignoring`);
|
||||
@@ -55,6 +123,20 @@ function extractImage(buffer, filename) {
|
||||
return `data:image/${mime};base64,${buffer.toString("base64")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a theme from a ZIP archive.
|
||||
*
|
||||
* Steps:
|
||||
* - Extract ZIP content
|
||||
* - Locate .theme.json file
|
||||
* - Validate JSON structure
|
||||
* - Extract optional image asset
|
||||
* - Build normalized theme object
|
||||
*
|
||||
* @param {string} zipPath
|
||||
* @param {string} themeId
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function loadThemeFromZip(zipPath, themeId) {
|
||||
try {
|
||||
const zipBuffer = fs.readFileSync(zipPath);
|
||||
@@ -91,6 +173,15 @@ async function loadThemeFromZip(zipPath, themeId) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a theme from a directory structure.
|
||||
*
|
||||
* Equivalent to ZIP loader but works on filesystem directly.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
* @param {string} themeId
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function loadThemeFromFolder(folderPath, themeId) {
|
||||
try {
|
||||
const jsonFile = fs.readdirSync(folderPath).find(f => f.endsWith(".theme.json"));
|
||||
@@ -124,13 +215,38 @@ async function loadThemeFromFolder(folderPath, themeId) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory cache of loaded themes.
|
||||
* Avoids re-parsing filesystem on every request.
|
||||
*/
|
||||
let cachedThemes = null;
|
||||
|
||||
/**
|
||||
* Active theme directory path used as source of truth.
|
||||
*/
|
||||
let themeFolderPath = null;
|
||||
|
||||
/**
|
||||
* Sets the active theme directory path.
|
||||
*
|
||||
* @param {string} folderPath
|
||||
*/
|
||||
function setThemeFolderPath(folderPath) {
|
||||
themeFolderPath = folderPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads all themes from the configured theme directory.
|
||||
*
|
||||
* Supports:
|
||||
* - ZIP themes (.zip)
|
||||
* - Folder themes (directory-based)
|
||||
*
|
||||
* Iterates through filesystem entries and delegates parsing
|
||||
* to the appropriate loader (ZIP or folder).
|
||||
*
|
||||
* @returns {Promise<object[]>} List of valid theme objects
|
||||
*/
|
||||
async function loadThemesFromFolder() {
|
||||
const themes = [];
|
||||
|
||||
@@ -161,11 +277,31 @@ async function loadThemesFromFolder() {
|
||||
return themes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns sorting priority for a theme ID.
|
||||
*
|
||||
* Lower index = higher priority.
|
||||
* Themes not in THEME_ORDER are placed at the end.
|
||||
*
|
||||
* @param {string} id
|
||||
* @returns {number}
|
||||
*/
|
||||
function getThemeOrder(id) {
|
||||
const index = THEME_ORDER.indexOf(id);
|
||||
return index === -1 ? Infinity : index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the theme system.
|
||||
*
|
||||
* Steps:
|
||||
* - Sets theme folder path
|
||||
* - Loads all themes from disk
|
||||
* - Sorts themes by priority order
|
||||
* - Caches result in memory
|
||||
*
|
||||
* @param {string} folderPath
|
||||
*/
|
||||
async function initThemes(folderPath) {
|
||||
setThemeFolderPath(folderPath);
|
||||
const themes = await loadThemesFromFolder();
|
||||
@@ -174,10 +310,24 @@ async function initThemes(folderPath) {
|
||||
logger.info(`Themes after sort: ${cachedThemes.map(t => t.id).join(", ")}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns cached themes.
|
||||
*
|
||||
* If themes are not loaded yet, returns empty array.
|
||||
*
|
||||
* @returns {object[]}
|
||||
*/
|
||||
function getThemes() {
|
||||
return cachedThemes ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads themes from disk and refreshes cache.
|
||||
*
|
||||
* Used when themes are modified at runtime without restart.
|
||||
*
|
||||
* @returns {Promise<object[]>}
|
||||
*/
|
||||
async function reloadThemes() {
|
||||
const themes = await loadThemesFromFolder();
|
||||
cachedThemes = themes.sort((a, b) => getThemeOrder(a.id) - getThemeOrder(b.id));
|
||||
|
||||
@@ -1,21 +1,55 @@
|
||||
/**
|
||||
* Electron main window module dependencies.
|
||||
* Handles BrowserWindow lifecycle and application UI shell.
|
||||
*/
|
||||
|
||||
const { BrowserWindow, app } = require("electron");
|
||||
const path = require("path");
|
||||
const { logger } = require("../server/logger");
|
||||
const { configFeatures } = require("../config");
|
||||
const config = require("../config");
|
||||
|
||||
/**
|
||||
* Singleton reference to the main Electron BrowserWindow instance.
|
||||
* Ensures only one application window exists at runtime.
|
||||
*/
|
||||
let mainWindow = null;
|
||||
|
||||
/**
|
||||
* Creates and initializes the main Electron application window.
|
||||
*
|
||||
* Responsibilities:
|
||||
* - Ensures singleton window instance (prevents duplicates)
|
||||
* - Configures window options (size, icon, preload, security settings)
|
||||
* - Loads frontend application from local dev server
|
||||
* - Handles lifecycle events (close, errors)
|
||||
*
|
||||
* @returns {Promise<BrowserWindow>} The created or existing window instance
|
||||
*/
|
||||
async function createMainWindow() {
|
||||
|
||||
/**
|
||||
* Prevents multiple instances of the main window.
|
||||
* Returns existing instance if already created.
|
||||
*/
|
||||
if (mainWindow) {
|
||||
logger.warn("Window already exists, no new creation!");
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves application icon path depending on runtime mode:
|
||||
* - Development: local build folder
|
||||
* - Production: packaged Electron resources
|
||||
*/
|
||||
const iconPath = config.devMode
|
||||
? path.join(__dirname, "../build/app-icon.ico")
|
||||
: path.join(process.resourcesPath, "build/app-icon.ico");
|
||||
|
||||
/**
|
||||
* Electron BrowserWindow configuration object.
|
||||
* Defines UI behavior, security settings, and preload bridge.
|
||||
*/
|
||||
const windowOptions = {
|
||||
title: `Freedom Loader ${config.version}`,
|
||||
icon: iconPath,
|
||||
@@ -35,6 +69,10 @@ async function createMainWindow() {
|
||||
|
||||
mainWindow = new BrowserWindow(windowOptions);
|
||||
|
||||
/**
|
||||
* Loads the frontend application served by the local dev server.
|
||||
* In production, this could be replaced with a file:// build.
|
||||
*/
|
||||
try {
|
||||
await mainWindow.loadURL(`http://localhost:${config.applicationPort}`);
|
||||
logger.info("Window loaded");
|
||||
@@ -43,6 +81,10 @@ async function createMainWindow() {
|
||||
throw err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up window reference when the main window is closed.
|
||||
* Prevents memory leaks and allows recreation if needed.
|
||||
*/
|
||||
mainWindow.on("closed", () => {
|
||||
logger.info("Main window closed");
|
||||
mainWindow = null;
|
||||
@@ -51,6 +93,14 @@ async function createMainWindow() {
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current main window instance.
|
||||
*
|
||||
* Useful for IPC handlers and background services
|
||||
* needing access to the renderer process.
|
||||
*
|
||||
* @returns {BrowserWindow | null}
|
||||
*/
|
||||
function getMainWindow() {
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
const { execFile } = require("child_process");
|
||||
const { logger } = require("../server/logger");
|
||||
|
||||
/**
|
||||
* Attempts to update the local yt-dlp binary using its built-in update command.
|
||||
*
|
||||
* This function:
|
||||
* - Executes yt-dlp with the `-U` flag
|
||||
* - Logs update output or warnings if update fails
|
||||
* - Never throws: update failure is non-blocking by design
|
||||
*
|
||||
* @param {string} ytDlpPath - Absolute path to the yt-dlp executable
|
||||
*/
|
||||
function updateYtDlp(ytDlpPath) {
|
||||
|
||||
logger.info("yt-dlp update check starting...");
|
||||
|
||||
/**
|
||||
* Executes yt-dlp CLI process in a non-interactive mode.
|
||||
* Used here specifically for self-update via `-U` flag.
|
||||
*/
|
||||
execFile(ytDlpPath, ["-U"], (err, stdout) => {
|
||||
|
||||
/**
|
||||
* Handles yt-dlp update result:
|
||||
* - Logs warning if update fails (network, binary issues, permissions)
|
||||
* - Logs stdout output when update succeeds
|
||||
*/
|
||||
if (err) logger.warn("yt-dlp update failed (continuing):", err.message);
|
||||
|
||||
else logger.info(`yt-dlp update: ${stdout.trim()}`);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user