feat: implement multi-part/playlist support and fix IPC crashes

This commit is contained in:
2026-02-16 00:33:52 +02:00
parent 19905a75e8
commit 18f04143ea
5 changed files with 5403 additions and 0 deletions

896
index.html Normal file
View File

@@ -0,0 +1,896 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' https: data:">
<title>madapes Media Downloader</title>
<style>
:root {
--bg-base: #0f0f0f;
--bg-elevated: #1e1e1e;
--bg-card: #282828;
--yt-red: #ff0000;
--text-primary: #ffffff;
--text-secondary: #aaaaaa;
--border-color: #3f3f3f;
--input-bg: #121212;
--accent-glow: rgba(255, 0, 0, 0.2);
--transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background-color: var(--bg-base);
color: var(--text-primary);
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
user-select: none;
}
/* Custom Title Bar / Header */
header {
padding: 30px 40px 30px;
background: linear-gradient(to bottom, rgba(255, 0, 0, 0.08) 0%, transparent 100%);
flex-shrink: 0;
text-align: center;
-webkit-app-region: drag;
/* Window can be dragged by clicking and dragging the header */
}
/* Adjust for traffic lights on macOS */
.title-bar-spacer {
height: 28px;
-webkit-app-region: drag;
}
.logo {
font-size: 26px;
font-weight: 800;
margin-bottom: 24px;
color: var(--text-primary);
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
letter-spacing: -0.5px;
pointer-events: none;
/* Let drag pass through if not interacting */
}
.logo span {
color: var(--yt-red);
}
.search-container {
max-width: 700px;
margin: 0 auto;
position: relative;
-webkit-app-region: no-drag;
/* Inputs shouldn't be draggable */
}
.input-wrapper {
position: relative;
display: flex;
align-items: center;
background: var(--input-bg);
border: 1px solid var(--border-color);
border-radius: 40px;
padding: 2px 2px 2px 20px;
transition: var(--transition);
}
.input-wrapper:focus-within {
border-color: var(--yt-red);
box-shadow: 0 0 0 4px var(--accent-glow);
}
input[type="text"] {
flex: 1;
background: transparent;
border: none;
color: white;
font-size: 15px;
padding: 12px 0;
outline: none;
font-family: inherit;
}
.detect-btn {
background: var(--bg-card);
color: white;
border: none;
padding: 10px 24px;
border-radius: 30px;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 8px;
margin-left: 10px;
}
.detect-btn:hover:not(:disabled) {
background: var(--border-color);
}
.detect-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Main Content */
main {
flex: 1;
padding: 0 40px 40px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 24px;
}
/* Result Card */
#videoResult {
display: none;
background: var(--bg-elevated);
border-radius: 16px;
overflow: hidden;
border: 1px solid var(--border-color);
animation: slideUp 0.4s var(--transition);
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.card-content {
display: flex;
padding: 24px;
gap: 24px;
}
.thumbnail-wrapper {
width: 280px;
flex-shrink: 0;
}
.thumbnail {
width: 100%;
aspect-ratio: 16/9;
background: #000;
border-radius: 12px;
object-fit: cover;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.4);
}
.info-wrapper {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
}
.video-title {
font-size: 20px;
font-weight: 700;
margin-bottom: 8px;
line-height: 1.4;
user-select: text;
}
.video-meta {
color: var(--text-secondary);
font-size: 14px;
margin-bottom: 20px;
display: flex;
gap: 15px;
}
/* Format Selection */
.format-selection {
margin-top: auto;
}
.format-group {
display: flex;
gap: 8px;
margin-bottom: 12px;
}
.format-chip {
padding: 6px 18px;
border-radius: 20px;
background: var(--bg-card);
border: 1px solid var(--border-color);
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: var(--transition);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.format-chip.active {
background: white;
color: black;
border-color: white;
}
.select-wrapper {
background: var(--input-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
margin-bottom: 20px;
}
select {
width: 100%;
background: transparent;
border: none;
color: var(--text-primary);
padding: 12px;
font-family: 'Courier New', monospace;
font-size: 13px;
outline: none;
cursor: pointer;
}
/* Action Bar */
.action-bar {
display: flex;
gap: 12px;
}
.btn-main {
padding: 12px 28px;
border-radius: 40px;
border: none;
font-weight: 700;
font-size: 14px;
cursor: pointer;
transition: var(--transition);
display: flex;
align-items: center;
gap: 10px;
}
.btn-red {
background: var(--yt-red);
color: white;
}
.btn-red:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(255, 0, 0, 0.3);
}
.btn-outline {
background: transparent;
border: 1px solid var(--border-color);
color: white;
}
.btn-outline:hover:not(:disabled) {
background: var(--border-color);
}
.btn-main:disabled {
opacity: 0.5;
transform: none;
box-shadow: none;
cursor: not-allowed;
}
.playlist-option {
display: none;
align-items: center;
padding: 12px 16px;
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
margin-bottom: 20px;
border: 1px solid var(--border-color);
transition: var(--transition);
}
.playlist-option:hover {
border-color: var(--yt-red);
background: rgba(255, 0, 0, 0.05);
}
.playlist-option label {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
width: 100%;
user-select: none;
}
.playlist-option input {
cursor: pointer;
width: 18px;
height: 18px;
accent-color: var(--yt-red);
}
.playlist-text {
font-size: 14px;
font-weight: 500;
}
/* Progress Area */
#progressArea {
display: none;
padding: 24px;
background: var(--bg-elevated);
border-top: 1px solid var(--border-color);
}
.progress-header {
display: flex;
justify-content: space-between;
margin-bottom: 12px;
font-size: 13px;
font-weight: 600;
}
.progress-track {
height: 6px;
background: var(--bg-card);
border-radius: 3px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: var(--yt-red);
width: 0%;
transition: width 0.3s ease;
box-shadow: 0 0 10px rgba(255, 0, 0, 0.4);
}
.progress-stats {
margin-top: 10px;
display: flex;
gap: 20px;
font-size: 12px;
color: var(--text-secondary);
}
/* Notification Overlay */
#notification-overlay {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0.9);
background: rgba(0, 0, 0, 0.85);
backdrop-filter: blur(20px);
padding: 24px 40px;
border-radius: 24px;
border: 1px solid var(--border-color);
z-index: 1000;
display: none;
flex-direction: column;
align-items: center;
gap: 16px;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.6);
border: 1px solid rgba(255, 255, 255, 0.1);
transition: var(--transition);
opacity: 0;
pointer-events: none;
}
#notification-overlay.active {
display: flex;
opacity: 1;
transform: translate(-50%, -50%) scale(1);
pointer-events: all;
}
.notification-icon {
font-size: 32px;
}
.notification-text {
font-weight: 600;
font-size: 16px;
letter-spacing: 0.2px;
text-align: center;
max-width: 300px;
}
/* Spinner Animation */
.spinner {
width: 32px;
height: 32px;
border: 3px solid rgba(255, 255, 255, 0.1);
border-top-color: var(--yt-red);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Empty State */
.empty-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--text-secondary);
text-align: center;
gap: 16px;
}
.empty-state svg {
width: 80px;
height: 80px;
opacity: 0.2;
color: white;
}
.empty-state h2 {
color: var(--text-primary);
}
/* Responsive Design */
@media (max-width: 900px) {
.card-content {
flex-direction: column;
align-items: center;
text-align: center;
}
.thumbnail-wrapper {
width: 100%;
max-width: 400px;
}
.video-meta {
justify-content: center;
}
.format-group {
justify-content: center;
}
.action-bar {
justify-content: center;
}
}
@media (max-width: 600px) {
header {
padding: 20px 20px;
}
main {
padding: 0 20px 20px;
}
.logo {
font-size: 20px;
}
.video-title {
font-size: 18px;
}
}
</style>
</head>
<body>
<header>
<div class="title-bar-spacer"></div>
<div class="logo">
<svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">
<path
d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 4-8 4z"
fill="#ff0000" />
</svg>
<span>Media Downloader</span>
</div>
<div class="search-container">
<div class="input-wrapper">
<input type="text" id="url" placeholder="Paste link from YouTube, Vimeo, Twitter, or any site..."
autofocus>
<button id="detectBtn" class="detect-btn">
<span>🔍</span> Detect
</button>
</div>
</div>
</header>
<main>
<div id="emptyState" class="empty-state">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
stroke-linejoin="round">
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
<line x1="8" y1="21" x2="16" y2="21"></line>
<line x1="12" y1="17" x2="12" y2="21"></line>
</svg>
<h2>Ready to download?</h2>
<p>Paste a link above to fetch video details and formats.</p>
</div>
<div id="videoResult">
<div class="card-content">
<div class="thumbnail-wrapper">
<img id="thumbnail" class="thumbnail" src="" alt="Thumbnail">
</div>
<div class="info-wrapper">
<h2 id="videoTitle" class="video-title">Video Title</h2>
<div class="video-meta">
<span id="uploader">Uploader</span>
<span id="duration">--:--</span>
</div>
<div class="format-selection">
<div class="format-group">
<div class="format-chip active" id="chipVideo">Video + Audio</div>
<div class="format-chip" id="chipAudio">Audio Only</div>
</div>
<div class="select-wrapper">
<select id="formatSelect">
<option value="best">Quality: High (Auto)</option>
</select>
</div>
<div id="playlistOption" class="playlist-option" style="display: none;">
<label class="container">
<input type="checkbox" id="playlistCheckbox">
<span class="checkmark"></span>
<span class="playlist-text">Download entire playlist (<span id="playlistCount">0</span>
items)</span>
</label>
</div>
<div class="action-bar">
<button id="actionBtn" class="btn-main btn-red" disabled>⬇️ Download Video + Audio</button>
<button id="cancelBtn" class="btn-main btn-outline" disabled>✖ Stop</button>
</div>
</div>
</div>
</div>
<div id="progressArea">
<div class="progress-header">
<span id="progressStatus">Downloading...</span>
<span id="progressPercent">0%</span>
</div>
<div class="progress-track">
<div id="progressFill" class="progress-fill"></div>
</div>
<div class="progress-stats">
<span id="speed"></span>
<span id="eta"></span>
</div>
</div>
</div>
</main>
<!-- Central Notification Overlay -->
<div id="notification-overlay">
<div id="notification-icon" class="notification-icon"></div>
<div id="notification-text" class="notification-text"></div>
</div>
<script>
const urlInput = document.getElementById('url');
const detectBtn = document.getElementById('detectBtn');
const actionBtn = document.getElementById('actionBtn');
const cancelBtn = document.getElementById('cancelBtn');
const formatSelect = document.getElementById('formatSelect');
const progressFill = document.getElementById('progressFill');
const progressPercent = document.getElementById('progressPercent');
const progressStatus = document.getElementById('progressStatus');
const progressArea = document.getElementById('progressArea');
const speedEl = document.getElementById('speed');
const etaEl = document.getElementById('eta');
const statusText = document.getElementById('notification-text');
const statusIcon = document.getElementById('notification-icon');
const statusOverlay = document.getElementById('notification-overlay');
const videoResult = document.getElementById('videoResult');
const emptyState = document.getElementById('emptyState');
const videoTitle = document.getElementById('videoTitle');
const uploader = document.getElementById('uploader');
const duration = document.getElementById('duration');
const thumbnail = document.getElementById('thumbnail');
const chipVideo = document.getElementById('chipVideo');
const chipAudio = document.getElementById('chipAudio');
let isDownloading = false;
let detectedData = null;
let allFormats = [];
let currentFilter = 'video'; // 'video', 'audio'
// Utility
function formatBytes(bytes) {
if (!bytes || bytes === 0) return '';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0;
let size = bytes;
while (size >= 1024 && i < units.length - 1) {
size /= 1024;
i++;
}
return `${size.toFixed(1)} ${units[i]}`;
}
function formatDuration(seconds) {
if (!seconds) return '';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
return `${m}:${s.toString().padStart(2, '0')}`;
}
let statusTimeout = null;
function setStatus(text, type = 'ready') {
if (statusTimeout) clearTimeout(statusTimeout);
// Only show popover overlay for loading and error states
if (type === 'loading' || type === 'error') {
statusText.textContent = text;
statusIcon.innerHTML = '';
statusIcon.className = 'notification-icon';
statusOverlay.classList.add('active');
if (type === 'loading') {
const spinner = document.createElement('div');
spinner.className = 'spinner';
statusIcon.appendChild(spinner);
} else if (type === 'error') {
statusIcon.textContent = '❌';
}
} else {
// Hide for success, ready, or cancelled states
statusOverlay.classList.remove('active');
}
// Auto-hide error after a delay
if (type === 'error') {
statusTimeout = setTimeout(() => {
statusOverlay.classList.remove('active');
}, 5000); // Errors stay visible longer
}
}
function buildFormatLabel(format) {
const parts = [];
const typeEmoji = (format.has_video && format.has_audio) ? '📹' : (format.has_video ? '📺' : '🎵');
parts.push(typeEmoji);
parts.push(format.resolution || 'unknown');
parts.push(format.ext.toUpperCase());
if (format.fps) parts.push(`${format.fps}fps`);
if (format.filesize) parts.push(formatBytes(format.filesize));
parts.push(`[${format.format_id}]`);
return parts.join(' • ');
}
function applyFilters() {
formatSelect.innerHTML = ''; // Start clean
// Always add the "Best" option first as a safe fallback for all sites
const autoOption = document.createElement('option');
autoOption.value = 'best';
autoOption.textContent = '⭐ Best Quality (Recommended Auto)';
formatSelect.appendChild(autoOption);
const filtered = allFormats.filter(format => {
const isAudioOnly = !format.has_video && format.has_audio;
if (currentFilter === 'video' && format.has_video) return true;
if (currentFilter === 'audio' && isAudioOnly) return true;
return false;
});
// Re-sort (height > tbr > fps)
filtered.sort((a, b) => {
const aVal = (a.height || 0) * 1000000 + (a.tbr || 0) * 1000 + (a.fps || 0);
const bVal = (b.height || 0) * 1000000 + (b.tbr || 0) * 1000 + (b.fps || 0);
return bVal - aVal;
});
filtered.forEach(format => {
const option = document.createElement('option');
option.value = format.format_id;
option.textContent = buildFormatLabel(format);
formatSelect.appendChild(option);
});
// Preselect Best Quality (Auto) by default for robustness
formatSelect.selectedIndex = 0;
}
// Chip logic
[chipVideo, chipAudio].forEach(chip => {
chip.addEventListener('click', () => {
if (isDownloading) return;
[chipVideo, chipAudio].forEach(c => c.classList.remove('active'));
chip.classList.add('active');
currentFilter = chip.id === 'chipVideo' ? 'video' : 'audio';
// Update button text
const itemCount = detectedData && detectedData.length > 1 ? ` All ${detectedData.length} Items` : '';
if (currentFilter === 'video') {
actionBtn.innerHTML = `⬇️ Download Video + Audio${itemCount}`;
} else {
actionBtn.innerHTML = `🎵 Download Audio (MP3)${itemCount}`;
}
applyFilters();
});
});
// Detect
detectBtn.addEventListener('click', async () => {
const url = urlInput.value.trim();
if (!url) return setStatus('Enter a URL first', 'error');
detectBtn.disabled = true;
setStatus('Detecting media...', 'loading');
try {
const result = await window.electronAPI.detectVideos(url);
if (!result.success) throw new Error(result.message || 'Detection failed');
detectedData = result.items;
if (!detectedData?.length) throw new Error('No formats found');
const video = detectedData[0];
allFormats = video.formats || [];
// UI Update
videoTitle.textContent = video.title;
uploader.textContent = `👤 ${video.uploader || 'Unknown'}`;
duration.textContent = `⏱️ ${formatDuration(video.duration)}`;
thumbnail.src = video.thumbnail || '';
// Handle playlist UI
const playlistOption = document.getElementById('playlistOption');
const playlistCheckbox = document.getElementById('playlistCheckbox');
const playlistCountSpan = document.getElementById('playlistCount');
if (result.isPlaylist && result.playlistCount > 1) {
playlistOption.style.display = 'flex';
playlistCountSpan.textContent = result.playlistCount;
playlistCheckbox.checked = false; // Default to single video
} else {
playlistOption.style.display = 'none';
}
emptyState.style.display = 'none';
videoResult.style.display = 'block';
progressArea.style.display = 'none';
applyFilters();
statusOverlay.classList.remove('active');
actionBtn.disabled = false;
// Trigger button text update
if (currentFilter === 'video') {
actionBtn.innerHTML = `⬇️ Download Video + Audio`;
} else {
actionBtn.innerHTML = `🎵 Download Audio (MP3)`;
}
} catch (error) {
setStatus(error.message, 'error');
} finally {
detectBtn.disabled = false;
}
});
// Action Button (Dynamic)
actionBtn.addEventListener('click', async () => {
const url = urlInput.value.trim();
const formatId = formatSelect.value || 'best';
const downloadPlaylist = document.getElementById('playlistCheckbox').checked;
isDownloading = true;
toggleControls(true);
progressArea.style.display = 'block';
const title = videoTitle.textContent;
let result;
if (currentFilter === 'video') {
setStatus('Initializing download...', 'loading');
result = await window.electronAPI.startDownload(url, formatId, false, null, title, downloadPlaylist);
} else {
setStatus('Initializing audio extraction...', 'loading');
result = await window.electronAPI.startDownload(url, formatId, true, 'mp3', title, downloadPlaylist);
}
if (result && !result.success) {
setStatus(result.message, 'ready'); // This will now hide overlay
resetUI();
}
});
// Cancel
cancelBtn.addEventListener('click', async () => {
await window.electronAPI.cancelDownload();
setStatus('Cancelled', 'ready'); // This will now hide overlay
resetUI();
});
function toggleControls(active) {
actionBtn.disabled = active;
detectBtn.disabled = active;
cancelBtn.disabled = !active;
urlInput.disabled = active;
// Disable chips during download
[chipVideo, chipAudio].forEach(chip => {
chip.style.opacity = active ? 0.4 : 1;
chip.style.cursor = active ? 'not-allowed' : 'pointer';
});
}
function resetUI() {
isDownloading = false;
toggleControls(false);
actionBtn.disabled = !detectedData;
progressArea.style.display = 'none';
}
// IPC Handlers
window.electronAPI.onProgress((data) => {
const percent = Math.min(100, Math.max(0, data.percent || 0));
progressFill.style.width = percent + '%';
progressPercent.textContent = percent.toFixed(1) + '%';
progressStatus.textContent = data.status || 'Downloading...';
speedEl.textContent = data.speed ? `${data.speed}` : '';
etaEl.textContent = data.eta ? `⏱️ ETA: ${data.eta}` : '';
});
window.electronAPI.onComplete((data) => {
if (data.success) {
// Remove popover, just update progress text
statusOverlay.classList.remove('active');
progressStatus.textContent = 'Download Complete!';
progressPercent.textContent = '100%';
progressFill.style.width = '100%';
}
resetUI();
});
window.electronAPI.onError((message) => {
setStatus(message, 'error');
resetUI();
});
urlInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !isDownloading && !detectBtn.disabled) detectBtn.click();
});
</script>
</body>
</html>

412
main.js Normal file
View File

@@ -0,0 +1,412 @@
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const YTDlpWrap = require('yt-dlp-wrap').default;
const fs = require('fs');
const os = require('os');
const { promisify } = require('util');
const rename = promisify(fs.rename);
const copyFile = promisify(fs.copyFile);
const unlink = promisify(fs.unlink);
const rm = promisify(fs.rm);
let mainWindow;
let currentDownload = null;
// Resolve binary paths
const isDev = !app.isPackaged;
const binDir = isDev
? path.join(__dirname, 'resources', 'bin')
: path.join(process.resourcesPath, 'bin');
const ytDlpPath = path.join(binDir, 'yt-dlp');
const ffmpegPath = path.join(binDir, 'ffmpeg');
// Initialize yt-dlp with local binary
const ytDlpWrap = new YTDlpWrap(ytDlpPath);
// Set ffmpeg path for yt-dlp-wrap and child processes
process.env.PATH = binDir + path.delimiter + process.env.PATH;
async function createWindow() {
mainWindow = new BrowserWindow({
width: 1000,
height: 750,
minWidth: 800,
minHeight: 600,
resizable: true,
title: 'madapes Media Downloader',
icon: path.join(binDir, '..', 'icon.png'), // Point to icon.png in resources
titleBarStyle: 'hidden',
trafficLightPosition: { x: 15, y: 15 },
backgroundColor: '#0f0f0f',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
mainWindow.loadFile('index.html');
mainWindow.on('closed', () => {
if (currentDownload) {
try {
currentDownload.kill();
} catch (e) {
console.error('Failed to kill download on window close:', e);
}
currentDownload = null;
}
mainWindow = null;
});
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
// Helper to safely send messages to renderer
function sendToRenderer(channel, data) {
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents) {
mainWindow.webContents.send(channel, data);
}
}
// Detect videos and formats
ipcMain.handle('detect-videos', async (event, url) => {
console.log(`[Main] Starting video detection for URL: ${url}`);
try {
// Get video info in JSON format. Using --no-playlist for MUCH faster initial detection.
console.log('[Main] Calling ytDlpWrap.getVideoInfo with --no-playlist...');
const info = await ytDlpWrap.getVideoInfo([
url,
'--no-playlist',
'--extractor-args', 'generic:impersonate'
]);
console.log('[Main] ytDlpWrap.getVideoInfo success');
console.log(`[Main] Info keys: ${Object.keys(info).join(', ')}`);
// Handle both single videos and playlists/multi-parts
const entries = Array.isArray(info.entries) ? info.entries.filter(Boolean) : [info];
console.log(`[Main] Found ${entries.length} entries`);
// Detect if it's a playlist or part of one
const isPlaylist = !!info.playlist_count || !!info.entries || url.includes('list=') || !!info.playlist_id || !!info._type === 'playlist';
const playlistCount = info.playlist_count || (Array.isArray(info.entries) ? info.entries.length : (url.includes('list=') ? '?' : 1));
console.log(`[Main] Detection Details - isPlaylist: ${isPlaylist}, playlistCount: ${playlistCount}, info._type: ${info._type}, has_entries: ${!!info.entries}`);
const detected = entries.map((entry) => {
const formats = (entry.formats || [])
.filter((f) => f.url || f.format_id) // Some manifests might not have direct URLs yet
.map((f) => ({
format_id: f.format_id,
ext: f.ext || 'unknown',
resolution: f.resolution || (f.width && f.height ? `${f.width}x${f.height}` : 'audio only'),
width: f.width,
height: f.height,
vcodec: f.vcodec,
acodec: f.acodec,
fps: f.fps,
tbr: f.tbr, // Total bitrate
vbr: f.vbr, // Video bitrate
abr: f.abr, // Audio bitrate
filesize: f.filesize || f.filesize_approx || null,
protocol: f.protocol,
format_note: f.format_note,
quality: f.quality,
has_video: f.vcodec && f.vcodec !== 'none',
has_audio: f.acodec && f.acodec !== 'none'
}))
// Sort: combined (video+audio) first, then by quality
.sort((a, b) => {
const typeScore = (x) => {
if (x.has_video && x.has_audio) return 3;
if (x.has_video) return 2;
if (x.has_audio) return 1;
return 0;
};
const aScore = typeScore(a) * 1e9 + (a.height || 0) * 1e6 + (a.tbr || 0);
const bScore = typeScore(b) * 1e9 + (b.height || 0) * 1e6 + (b.tbr || 0);
return bScore - aScore;
});
return {
id: entry.id,
title: entry.title || 'Unknown Title',
webpage_url: entry.webpage_url || url,
uploader: entry.uploader || entry.channel || 'Generic Site',
duration: entry.duration || 0,
thumbnail: entry.thumbnail || entry.thumbnails?.[0]?.url || '',
description: entry.description || '',
formats: formats
};
});
console.log(`[Main] Detection complete. Returning ${detected.length} items. Playlist: ${isPlaylist} (${playlistCount})`);
return {
success: true,
items: detected,
isPlaylist: isPlaylist,
playlistCount: playlistCount
};
} catch (error) {
console.error('Detection error:', error);
return {
success: false,
message: error.message || 'Failed to detect videos'
};
}
});
// Sanitize filename for safe saving
function sanitizeFilename(name) {
return name
.replace(/[<>:"/\\|?*]/g, '_')
.replace(/\s+/g, ' ')
.trim();
}
// Handle download request
ipcMain.handle('start-download', async (event, payload) => {
const { url, formatId, extractAudio, audioFormat, title, downloadPlaylist } = payload;
console.log(`[Main] Starting download for URL: ${url}, Format: ${formatId}, AudioOnly: ${extractAudio}, Title: ${title}, Playlist: ${downloadPlaylist}`);
let tempDir = null;
try {
// Show save dialog
const defaultExt = extractAudio ? (audioFormat || 'mp3') : 'mp4';
const sanitizedTitle = title ? sanitizeFilename(title).substring(0, 50) : 'download';
if (!mainWindow || mainWindow.isDestroyed()) {
return { success: false, message: 'Window closed' };
}
const result = await dialog.showSaveDialog(mainWindow, {
title: extractAudio ? 'Save audio as' : 'Save video as',
defaultPath: `${sanitizedTitle}.${defaultExt}`,
filters: extractAudio ? [
{ name: 'Audio Files', extensions: ['mp3', 'm4a', 'opus', 'wav'] },
{ name: 'All Files', extensions: ['*'] }
] : [
{ name: 'Video Files', extensions: ['mp4', 'mkv', 'webm', 'mov', 'avi', 'flv'] },
{ name: 'Audio Files', extensions: ['mp3', 'm4a', 'opus', 'wav'] },
{ name: 'All Files', extensions: ['*'] }
]
});
if (result.canceled) {
return { success: false, message: 'Cancelled' };
}
const savePath = result.filePath;
// Create a unique temp directory
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'madapes-downloader-'));
const tempOutputFile = path.join(tempDir, `processed.${defaultExt}`);
// Build download arguments
const args = [
url,
'--newline',
'--extractor-args', 'generic:impersonate'
];
if (!downloadPlaylist) {
args.push('--no-playlist');
}
// Use a simple template for output to be robust across environments
const outputTemplate = path.join(tempDir, 'media-%(autonumber)03d.%(ext)s');
args.push('-o', outputTemplate);
console.log(`[Main] Executing yt-dlp with command: ${ytDlpPath} ${args.join(' ')}`);
// Add format selection
if (extractAudio) {
args.push('--extract-audio');
args.push('--audio-format', audioFormat || 'mp3');
args.push('--postprocessor-args', `ffmpeg:-y`);
args.push('-o', tempOutputFile);
if (formatId && formatId !== 'best') {
args.push('-f', formatId);
} else {
args.push('-f', 'bestaudio/best');
}
} else if (formatId && formatId !== 'best') {
args.push('-f', formatId);
} else {
// Default to best quality with video+audio
args.push('-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best');
}
let lastProgress = 0;
let isConverting = false;
let totalItems = 1;
let currentItem = 1;
// Wrap download in a Promise to correctly await process completion
const downloadPromise = new Promise((resolve, reject) => {
currentDownload = ytDlpWrap.exec(args);
currentDownload.on('progress', (progress) => {
try {
let percent = 0;
if (progress.percent) {
const percentStr = String(progress.percent).replace('%', '');
percent = parseFloat(percentStr);
}
// If progress reaches 100 but the process is still running, it's likely converting
if (percent >= 100 && extractAudio && !isConverting) {
isConverting = true;
}
// Aggregate progress for multi-item downloads
const aggregatePercent = ((currentItem - 1) * 100 + percent) / totalItems;
if (Math.abs(aggregatePercent - lastProgress) > 0.1 || percent === 100) {
lastProgress = aggregatePercent;
let statusMsg = isConverting ? 'Converting to MP3...' : `Downloading... ${percent.toFixed(1)}%`;
if (totalItems > 1) {
statusMsg = `Downloading item ${currentItem} of ${totalItems}... (${percent.toFixed(1)}%)`;
}
sendToRenderer('download-progress', {
percent: aggregatePercent,
itemPercent: percent,
currentItem: currentItem,
totalItems: totalItems,
speed: progress.currentSpeed || '',
eta: progress.eta || '',
totalSize: progress.totalSize || '',
status: statusMsg
});
}
} catch (err) {
console.error('Progress parsing error:', err);
}
});
currentDownload.on('ytDlpEvent', (eventType, eventData) => {
console.log(`[Main] ytDlpEvent: ${eventType} | Data: ${eventData}`);
// Check for multi-item info in logs
if (eventType === 'download') {
const itemMatch = eventData.match(/Downloading item (\d+) of (\d+)/);
if (itemMatch) {
currentItem = parseInt(itemMatch[1]);
totalItems = parseInt(itemMatch[2]);
}
sendToRenderer('download-status', eventData);
}
});
currentDownload.on('close', (code) => {
console.log(`[Main] yt-dlp process closed with code: ${code}`);
if (code === 0) {
resolve();
} else {
reject(new Error(`yt-dlp exited with code ${code}`));
}
});
currentDownload.on('error', (error) => {
console.error('[Main] yt-dlp process error:', error);
sendToRenderer('download-error', error.message);
reject(error);
});
});
await downloadPromise;
console.log('[Main] Download promise resolved.');
// Verify and move files from temp to final destination
const files = fs.readdirSync(tempDir).sort();
console.log(`[Main] Files in tempDir: ${JSON.stringify(files)}`);
if (files.length === 0) {
console.error(`[Main] Error: No files found in ${tempDir}`);
throw new Error('No files were downloaded');
}
sendToRenderer('download-progress', {
percent: 100,
status: 'Finishing up...'
});
if (files.length === 1) {
// Single file: move to the exact savePath the user chose
const actualFile = path.join(tempDir, files[0]);
try {
await rename(actualFile, savePath);
} catch (moveErr) {
await copyFile(actualFile, savePath);
await unlink(actualFile);
}
} else {
// Multiple files: creates a folder if savePath was a file, or puts them in the Dir
// Actually, dialog.showSaveDialog returns a FILE path.
// We'll create a folder at savePath (minus extension) and put all files there.
const targetFolder = savePath.replace(/\.[^/.]+$/, "");
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder, { recursive: true });
}
for (const file of files) {
const src = path.join(tempDir, file);
const dest = path.join(targetFolder, file);
try {
await rename(src, dest);
} catch (moveErr) {
await copyFile(src, dest);
await unlink(src);
}
}
}
sendToRenderer('download-complete', {
success: true,
path: files.length === 1 ? savePath : savePath.replace(/\.[^/.]+$/, "")
});
return { success: true, path: files.length === 1 ? savePath : savePath.replace(/\.[^/.]+$/, "") };
} catch (error) {
console.error('Download error:', error);
sendToRenderer('download-error', error.message);
return { success: false, message: error.message };
} finally {
currentDownload = null;
if (tempDir && fs.existsSync(tempDir)) {
try {
await rm(tempDir, { recursive: true, force: true });
} catch (err) {
console.error('Temp cleanup error:', err);
}
}
}
});
// Handle cancel request
ipcMain.handle('cancel-download', async () => {
if (currentDownload) {
try {
currentDownload.kill();
currentDownload = null;
return { success: true };
} catch (err) {
return { success: false, message: err.message };
}
}
return { success: false, message: 'No active download' };
});

4046
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
package.json Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "video-downloader",
"version": "1.0.0",
"description": "Video stream downloader with format detection",
"main": "main.js",
"scripts": {
"start": "electron .",
"postinstall": "electron-builder install-app-deps"
},
"build": {
"appId": "com.madapes.mediadownloader",
"productName": "madapes Media Downloader",
"directories": {
"output": "dist"
},
"extraResources": [
"resources/**"
],
"mac": {}
},
"keywords": [
"video",
"downloader",
"stream",
"hls",
"dash"
],
"author": "",
"license": "MIT",
"dependencies": {
"electron": "^28.0.0",
"yt-dlp-wrap": "^2.3.8"
},
"devDependencies": {
"electron-builder": "^24.9.1"
}
}

12
preload.js Normal file
View File

@@ -0,0 +1,12 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
detectVideos: (url) => ipcRenderer.invoke('detect-videos', url),
startDownload: (url, formatId, extractAudio, audioFormat, title, downloadPlaylist) => ipcRenderer.invoke('start-download', { url, formatId, extractAudio, audioFormat, title, downloadPlaylist }),
cancelDownload: () => ipcRenderer.invoke('cancel-download'),
onProgress: (callback) => ipcRenderer.on('download-progress', (event, data) => callback(data)),
onComplete: (callback) => ipcRenderer.on('download-complete', (event, data) => callback(data)),
onError: (callback) => ipcRenderer.on('download-error', (event, message) => callback(message)),
onStatus: (callback) => ipcRenderer.on('download-status', (event, data) => callback(data))
});