### Manage yt-dlp Binary Updates with JavaScript Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Manages the automatic detection, downloading, and updating of the yt-dlp binary from GitHub releases. It requires environment variables for paths and a window object. It provides methods to check for updates, get local and remote versions, check for pre-installed binaries, get download URLs, and perform manual downloads. ```javascript const BinaryUpdater = require("./modules/BinaryUpdater"); // Initialize updater const binaryUpdater = new BinaryUpdater(env.paths, win); // Check and install/update yt-dlp await binaryUpdater.checkUpdate(); // Get current installed version const localVersion = await binaryUpdater.getLocalVersion(); console.log("Installed version:", localVersion); // "2023.10.13" // Get latest version from GitHub const remoteVersion = await binaryUpdater.getRemoteVersion(); console.log("Latest version:", remoteVersion); // Check if yt-dlp is pre-installed on system const isPreInstalled = await binaryUpdater.checkPreInstalled(); if (isPreInstalled) { console.log("Using system yt-dlp"); } else { console.log("Using bundled yt-dlp"); } // Get platform-specific download URL const downloadUrl = binaryUpdater.getBinaryUrl(); console.log("Download URL:", downloadUrl); // Windows: "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe" // Linux: "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp" // macOS (modern): "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos" // macOS (legacy): "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos_legacy" // Manual download and install await binaryUpdater.downloadUpdate(downloadUrl, "2023.10.13"); console.log("Binary updated successfully"); ``` -------------------------------- ### Monitor System Clipboard for URLs with JavaScript Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt The ClipboardWatcher module monitors the system clipboard for video URLs. It automatically processes detected URLs, starting and stopping monitoring via polling. It can also manually read and validate clipboard content, avoiding duplicate processing. ```javascript const ClipboardWatcher = require("./modules/ClipboardWatcher"); // Initialize clipboard watcher const clipboardWatcher = new ClipboardWatcher(win, env); // Start monitoring clipboard (polls every 1000ms) clipboardWatcher.startPolling(); // Stop monitoring clipboardWatcher.stopPolling(); // Manual clipboard check const clipboardContent = clipboardWatcher.readClipboard(); if (clipboardWatcher.isValidUrl(clipboardContent)) { queryManager.manage(clipboardContent); } // Clipboard watcher automatically: // 1. Reads clipboard content periodically // 2. Detects if content is a valid URL // 3. Checks if URL is already being processed // 4. Sends URL to renderer for user confirmation // 5. Avoids duplicate processing // Controlled by settings if (env.settings.autoFillClipboard) { clipboardWatcher.startPolling(); } // Respects global shortcuts // Shift+Ctrl+V: Manually paste from clipboard // Shift+Ctrl+D: Start download ``` -------------------------------- ### Manage Application Configuration with Environment Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Handles application-wide settings, including version, download paths, Python detection, and rate limiting for concurrent operations. Initializes with Electron's app module and allows dynamic updates to settings and concurrency limits. ```javascript const Environment = require("./modules/Environment"); const { app } = require("electron"); // Initialize environment const env = new Environment(app); await env.initialize(); // Access configuration console.log("App version:", env.version); console.log("Python command:", env.pythonCommand); console.log("Download path:", env.settings.downloadPath); // Configure concurrent downloads env.changeMaxConcurrent(8); // Allow 8 simultaneous downloads // Access rate limiters (Bottleneck instances) // Download limiter controls simultaneous downloads await env.downloadLimiter.schedule(async () => { console.log("Starting download..."); // Download operation here }); // Metadata limiter controls simultaneous metadata fetches await env.metadataLimiter.schedule(async () => { console.log("Fetching metadata..."); // Metadata fetch operation here }); // Settings structure const settings = { outputFormat: "mp4", audioOutputFormat: "mp3", downloadPath: "/path/to/downloads", proxy: "http://proxy.example.com:8080", rateLimit: "500", // KB/s maxConcurrent: 4, autoFillClipboard: true, theme: "dark", nameFormat: "% (title).200s-(%(height)sp%(fps).0d).%(ext)s", sponsorblockMark: "all", downloadMetadata: true, downloadThumbnail: false, retries: 10 }; env.settings.update(settings); ``` -------------------------------- ### Execute yt-dlp Commands with Query Class (JavaScript) Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Implements a custom query class extending the base Query class to execute yt-dlp commands. It supports constructing arguments, managing processes, and handling live output via callbacks. Dependencies include the './modules/types/Query' module. Inputs are a URL and optional arguments, with outputs being the command result or live data. ```javascript const Query = require("./modules/types/Query"); // Extend Query class for custom operations class CustomQuery extends Query { constructor(environment, identifier) { super(environment, identifier); } async execute(url) { const args = [ "-J", // JSON output "--flat-playlist", // Flat playlist info "--no-cache-dir", // Disable caching "--ignore-config" // Ignore config files ]; // Start query with callback for live output return await this.start(url, args, (liveData) => { console.log("Output:", liveData); }); } } // Use the query const query = new CustomQuery(environment, "custom_id_123"); try { const result = await query.execute("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); console.log("Result:", result); } catch (error) { console.error("Query failed:", error); } // Cancel running query query.stop(); // Query automatically adds common arguments: // - User agent (random or empty based on settings) // - Proxy configuration // - Certificate validation settings // - Cookie file path // - Rate limiting // - Playlist/no-playlist flags // Example of direct usage with args const args = ["-F"]; // List all formats const output = await query.start(url, args); console.log("Available formats:", output); // With live callback await query.start(url, ["-f", "best", "-o", "/path/%(title)s.%(ext)s"], (line) => { if (line.includes("[download]")) { console.log("Download progress:", line); } }); ``` -------------------------------- ### QueryManager API for Video Download and Management (JavaScript) Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt The QueryManager acts as the central controller for managing video metadata, download operations, and coordinating between the UI and backend processes. It supports adding videos, downloading single or multiple videos, checking file sizes, stopping downloads, managing subtitles, and opening downloaded content. It requires Electron window and environment objects for initialization. ```javascript const QueryManager = require("./modules/QueryManager"); const Environment = require("./modules/Environment"); // Initialize with Electron window and environment const queryManager = new QueryManager(win, env); // Add a video URL for processing (auto-detects single/playlist) queryManager.manage("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); // Download a single video with specific format queryManager.downloadVideo({ identifier: "abc123def456", format: "1080p60", type: "video", encoding: "h264", audioEncoding: "aac" }); // Download multiple videos in batch queryManager.downloadAllVideos({ downloadType: "all", videos: [ { identifier: "video1", format: "1080p", type: "video", encoding: "none", audioEncoding: "none" }, { identifier: "video2", format: "720p", type: "audio", encoding: "none", audioEncoding: "mp3" } ] }); // Get file size before downloading const size = await queryManager.getSize( "abc123def456", // identifier "1080p60", // formatLabel false, // audioOnly false, // videoOnly true, // clicked "h264", // encoding "aac" // audioEncoding ); console.log(`Video size: ${size} bytes`); // Stop an active download queryManager.stopDownload("abc123def456"); // Get available subtitles const [subs, autoCaptions] = queryManager.getAvailableSubtitles("abc123def456", false); console.log("Available subtitles:", subs.map(s => s.name)); // Set subtitle preferences queryManager.setSubtitle({ identifier: "abc123def456", enabled: true, subs: ["en", "es"], autoGen: ["fr"], unified: false }); // Save video metadata to JSON await queryManager.saveInfo("abc123def456", true); // Open downloaded video or folder queryManager.openVideo({ identifier: "abc123def456", type: "item" // or "folder" }); ``` -------------------------------- ### Manage Persistent User Settings Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Provides functionality to load, validate, update, and save user preferences. It supports default fallbacks, serialization to JSON, and provides access to various settings like output formats, download paths, and name formatting. ```javascript const Settings = require("./modules/persistence/Settings"); // Load settings from file const settings = await Settings.loadFromFile(paths, env); // Access settings console.log("Output format:", settings.outputFormat); console.log("Audio format:", settings.audioOutputFormat); console.log("Max concurrent downloads:", settings.maxConcurrent); console.log("Default concurrent:", settings.getDefaultMaxConcurrent()); // Update settings settings.update({ outputFormat: "mkv", audioOutputFormat: "opus", downloadPath: "/new/path", maxConcurrent: 8, theme: "light", proxy: "socks5://127.0.0.1:1080", rateLimit: "1000", sponsorblockMark: "sponsor,intro,outro", sponsorblockRemove: "sponsor", enableEncoding: true, downloadThumbnail: true, compatFilename: true }); // Get serialized settings const serialized = settings.serialize(); console.log(JSON.stringify(serialized, null, 2)); // Save to disk settings.save(); // Writes to settings file asynchronously // Access specific settings if (settings.autoFillClipboard) { console.log("Clipboard monitoring enabled"); } if (settings.cookiePath) { console.log("Using cookies from:", settings.cookiePath); } // Name format examples settings.nameFormat = "% (title).200s-(%(height)sp%(fps).0d).%(ext)s"; // Result: "Video Title-(1080p60).mp4" settings.nameFormat = "% (title).200s.%(ext)s"; // Result: "Video Title.mp4" ``` -------------------------------- ### Video Metadata Model in JavaScript Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Represents a video entity with its metadata, format options, and download state. It takes a URL, type, and environment as input. It allows setting metadata, configuring download options (like audio/video only, quality, subtitles), selecting formats, serializing the object, and tracking download states. It also associates the video with a download query. ```javascript const Video = require("./modules/types/Video"); // Create new video instance const video = new Video( "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "single", // type: "single", "playlist", or "metadata" environment ); console.log("Video identifier:", video.identifier); // Random 32-char ID // Set metadata from InfoQuery result video.setMetadata({ title: "Rick Astley - Never Gonna Give You Up", duration: 213, uploader: "Rick Astley", thumbnail: "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg", like_count: 1500000, view_count: 1200000000, description: "Official video", formats: [ {height: 1080, fps: 60, filesize: 150000000, vcodec: "h264", acodec: "aac"}, {height: 1080, fps: 30, filesize: 80000000, vcodec: "h264", acodec: "aac"}, {height: 720, fps: 30, filesize: 50000000, vcodec: "h264", acodec: "aac"} ], subtitles: {en: [{ext: "vtt"}]}, en: [{ext: "vtt"}], automatic_captions: {fr: [{ext: "vtt"}]} }); console.log("Has metadata:", video.hasMetadata); // true console.log("Title:", video.title); console.log("Duration:", video.duration); // "03:33" console.log("Available formats:", video.formats.length); console.log("Selected format index:", video.selected_format_index); // 0 (highest quality) // Get filename for download const filename = video.getFilename(); console.log("Filename:", filename); // "Rick Astley - Never Gonna Give You Up-(1080p60)" // Configure download options video.audioOnly = false; video.videoOnly = false; video.audioQuality = "best"; video.downloadSubs = true; video.subLanguages = ["en", "es"]; video.selectedSubs = [["en"], ["fr"]]; video.selectedEncoding = "h264"; video.selectedAudioEncoding = "aac"; // Get format by label const format = video.getFormatFromLabel("1080p60"); console.log("Format:", format); // Serialize for export const serialized = video.serialize(); console.log(JSON.stringify(serialized, null, 2)); // Track download state video.downloaded = false; video.error = false; video.downloadingAudio = false; // Set associated query video.setQuery(downloadQuery); console.log("Download path:", video.downloadedPath); ``` -------------------------------- ### DownloadQuery API for Individual Video Download Execution (JavaScript) Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt The DownloadQuery class handles the actual download process for a single video, including format selection, progress tracking, and file management. It utilizes a ProgressBar for progress callbacks and requires video metadata, environment configuration, and playlist metadata. The connect method executes the download, and cancel stops an ongoing download. ```javascript const DownloadQuery = require("./modules/download/DownloadQuery"); const ProgressBar = require("./modules/types/ProgressBar"); // Create download query for a video const progressBar = new ProgressBar(queryManager, video); const downloadQuery = new DownloadQuery( "https://www.youtube.com/watch?v=dQw4w9WgXcQ", video, // Video object with metadata environment, // Environment configuration progressBar, // Progress callback handler playlistMeta // Playlist metadata array ); // Execute download with automatic format selection try { const result = await downloadQuery.connect(); if (result === "done") { console.log("Download completed successfully"); } } catch (error) { console.error("Download failed:", error); } // Cancel ongoing download downloadQuery.cancel(); // Video object configuration example const video = { url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ", identifier: "abc123", audioOnly: false, videoOnly: false, audioQuality: "best", formats: [ {height: 1080, fps: 60}, {height: 1080, fps: 30}, {height: 720, fps: 30} ], selected_format_index: 0, selectedEncoding: "h264", selectedAudioEncoding: "aac", downloadSubs: true, subLanguages: ["en", "es"] }; ``` -------------------------------- ### Fetch Video Metadata with InfoQuery Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Retrieves detailed metadata for a given video URL, including title, duration, uploader, available formats, and quality options. It can also detect and process playlist entries. Requires the InfoQuery module and an environment configuration. ```javascript const InfoQuery = require("./modules/info/InfoQuery"); // Create metadata query const infoQuery = new InfoQuery( "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "unique_identifier_123", environment ); // Fetch metadata const metadata = await infoQuery.connect(); if (metadata) { console.log("Title:", metadata.title); console.log("Duration:", metadata.duration); console.log("Uploader:", metadata.uploader); console.log("Available formats:", metadata.formats.length); // Access format details metadata.formats.forEach(format => { console.log(`Format: ${format.height}p @ ${format.fps}fps`); console.log(` Video codec: ${format.vcodec}`); console.log(` Audio codec: ${format.acodec}`); console.log(` File size: ${format.filesize}`); }); // Playlist detection if (metadata.entries && metadata.entries.length > 0) { console.log(`Playlist with ${metadata.entries.length} videos`); metadata.entries.forEach(entry => { console.log(` - ${entry.title} (${entry.url})`); }); } } ``` -------------------------------- ### Secure IPC Communication with Electron Context Bridge (JavaScript) Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt Establishes secure inter-process communication (IPC) between Electron's main and renderer processes using context isolation. It exposes specific IPC channels and handles invoking functions from the main process and receiving events. Dependencies include 'electron'. Inputs are channel names and data for invoking, outputs are invoked results or received event data. ```javascript // In preload.js (context bridge) const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld("main", { invoke: async (channel, data) => { const validChannels = [ "videoAction", "settingsAction", "downloadFolder", "iconProgress", "getSubtitles", "installUpdate" ]; if (validChannels.includes(channel)) { return await ipcRenderer.invoke(channel, data); } }, receive: (channel, callback) => { const validChannels = [ "videoAction", "updateGlobalButtons", "toast", "binaryLock", "log", "error" ]; if (validChannels.includes(channel)) { ipcRenderer.on(channel, (event, arg) => callback(arg)); } } }); // In renderer.js // Call main process functions const result = await window.main.invoke("videoAction", { action: "download", identifier: "abc123", downloadType: "single", format: "1080p", type: "video", encoding: "h264", audioEncoding: "aac" }); // Listen for main process events window.main.receive("videoAction", (data) => { if (data.action === "add") { console.log("Video added:", data.title); } else if (data.action === "progress") { console.log(`Progress: ${data.progress.percentage}`); } }); // In main.js const { ipcMain } = require('electron'); // Handle renderer requestsipcMain.handle('videoAction', async (event, args) => { switch (args.action) { case "download": if (args.downloadType === "single") { queryManager.downloadVideo(args); } else if (args.downloadType === "all") { queryManager.downloadAllVideos(args); } break; case "stop": queryManager.stopDownload(args.identifier); break; case "getSize": return await queryManager.getSize( args.identifier, args.formatLabel, args.audioOnly, args.videoOnly, args.clicked, args.encoding, args.audioEncoding ); } }); // Send to renderer win.webContents.send("videoAction", { action: "progress", identifier: "abc123", progress: { percentage: "45.2%", speed: "2.5MiB/s", eta: "00:45" } }); ``` -------------------------------- ### Manage and Persist Video URLs Across Sessions with JavaScript Source: https://context7.com/stefanlobbenmeier/youtube-dl-gui/llms.txt The TaskList module handles saving and restoring video URLs between application sessions. It loads saved tasks on startup and saves current tasks on application close, ensuring data persistence. It also deduplicates playlist videos and preserves playlist relationships. ```javascript const TaskList = require("./modules/persistence/TaskList"); // Initialize task list const taskList = new TaskList(env.paths, queryManager); // Load saved tasks from previous session task.load(); // Save current tasks await taskList.save(); // Restore tasks to QueryManager task.restore(); // Manually manage task list const currentTasks = queryManager.getTaskList(); console.log("Current URLs:", currentTasks); // ["https://youtube.com/watch?v=abc", "https://youtube.com/playlist?list=xyz"] // Task list automatically: // 1. Saves managed video URLs on app close // 2. Loads saved URLs on app start // 3. Deduplicates playlist videos // 4. Preserves playlist relationships // 5. Stores in JSON format // Disable task list persistence env.settings.taskList = false; env.settings.save(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.