diff --git a/main.py b/main.py index 10bf308..cb41553 100644 --- a/main.py +++ b/main.py @@ -1112,7 +1112,7 @@ def music_download(): if not url: return jsonify({"status": "error", "error": "Missing 'url' in request body."}), 400 - cookies = str(data.get('cookies') or '').strip() + cookies = str(data.get('cookies') or '').strip('\r\n') forward_payload = {"url": url, "cookies": cookies} if cookies else {"url": url} # Another service downloads music from YouTube and converts it to mp3. diff --git a/templates/video.html b/templates/video.html index 56a6146..d1fedb1 100644 --- a/templates/video.html +++ b/templates/video.html @@ -1692,6 +1692,20 @@

} } + function normalizeMusicCookies(contents) { + const lines = contents.replace(/^\uFEFF/, '').split(/\r\n|\r|\n/); + const rows = lines.filter(line => line.trim() && (!line.startsWith('#') || line.startsWith('#HttpOnly_'))); + if (!rows.length || rows.some(line => { + const fields = line.split('\t'); + return fields.length !== 7 || !fields[0] || !/^(TRUE|FALSE)$/.test(fields[1]) + || !/^(TRUE|FALSE)$/.test(fields[3]) || !/^\d*$/.test(fields[4]); + })) { + throw new Error('Please export cookies in Netscape cookies.txt format (not JSON or a Cookie request header).'); + } + // yt-dlp requires this header. Preserve tabs, including empty cookie values. + return '# Netscape HTTP Cookie File\n' + rows.join('\n') + '\n'; + } + async function handleMusicCookiesUpload(input) { const file = input.files[0]; if (!file) return; @@ -1703,16 +1717,12 @@

status.textContent = 'Reading cookies file...'; try { if (file.size > 1024 * 1024) throw new Error('Cookies file must be smaller than 1 MB.'); - const contents = (await file.text()).replace(/^\uFEFF/, '').trim(); - const rows = contents.split(/\r?\n/).filter(line => line.trim() && (!line.startsWith('#') || line.startsWith('#HttpOnly_'))); - if (!rows.length || rows.some(line => line.split('\t').length !== 7)) { - throw new Error('Please export cookies in Netscape cookies.txt format.'); - } + const contents = normalizeMusicCookies(await file.text()); const textarea = document.getElementById('musicCookiesInput'); textarea.value = contents; textarea.dispatchEvent(new Event('input', { bubbles: true })); saveVideoSettings(); - status.textContent = `Loaded ${file.name}. Cookies are ready for the next download.`; + status.textContent = `Loaded ${file.name}. File format checked; YouTube will verify the session during download.`; } catch (error) { status.textContent = error.message || 'Could not read the cookies file.'; showToast(status.textContent, 'warn'); @@ -1742,6 +1752,7 @@

btn.disabled = true; document.getElementById('musicFileInput').disabled = true; + document.getElementById('musicCookiesFileInput').disabled = true; audioSelectionVersion++; btn.classList.add('opacity-70'); btnText.textContent = "Downloading..."; @@ -1752,7 +1763,8 @@

logToConsole(`[Music] POST /api/music_download ${url}`, 'cmd'); try { - const cookies = (document.getElementById('musicCookiesInput')?.value || '').trim(); + const rawCookies = document.getElementById('musicCookiesInput').value; + const cookies = rawCookies.trim() ? normalizeMusicCookies(rawCookies) : ''; // Single request: backend downloads + converts and returns the audio directly. const response = await fetch('/api/music_download', { method: 'POST', @@ -1780,12 +1792,16 @@

showToast("Music downloaded! Click Save to store the MP3.", "success"); } catch (error) { logToConsole(`[API Error] ${error.message}`, 'error'); + const cookieStatus = document.getElementById('musicCookiesFileStatus'); + cookieStatus.textContent = error.message; + cookieStatus.closest('details').open = true; showToast("Music download failed. Check console logs.", "error"); metaBadge.textContent = "Error"; setEqualizerActive(false, 'Download Failed'); } finally { btn.disabled = false; document.getElementById('musicFileInput').disabled = false; + document.getElementById('musicCookiesFileInput').disabled = false; btn.classList.remove('opacity-70'); btnText.textContent = "Download MP3"; btnIcon.className = "fa-solid fa-download"; diff --git a/tests/browser/test_cookie_file_upload.py b/tests/browser/test_cookie_file_upload.py new file mode 100644 index 0000000..5aa243e --- /dev/null +++ b/tests/browser/test_cookie_file_upload.py @@ -0,0 +1,54 @@ +"""Cookies remain parseable across file import, browser storage and both APIs.""" +from http.cookiejar import MozillaCookieJar +from pathlib import Path + +import pytest + +from test_video_studio import studio, reopen_studio + +pytestmark = pytest.mark.browser + + +def test_cookie_file_reaches_ytdlp_without_losing_empty_values(studio, worker, monkeypatch): + page, _ = studio + page.evaluate('async () => await window.videoStudioReady') + # An export without a header, Windows newlines, BOM, HttpOnly and empty value. + rows = '#HttpOnly_.youtube.com\tTRUE\t/\tTRUE\t0\tSID\tfake-test-value\r\n.youtube.com\tTRUE\t/\tFALSE\t0\tEMPTY\t\r\n' + page.locator('#musicCookiesFileInput').set_input_files({ + 'name': 'cookies.txt', 'mimeType': 'text/plain', 'buffer': ('\ufeff' + rows).encode(), + }) + page.wait_for_function("document.getElementById('musicCookiesFileStatus').textContent.startsWith('Loaded cookies.txt')") + normalized = '# Netscape HTTP Cookie File\n' + rows.replace('\r\n', '\n') + assert page.locator('#musicCookiesInput').input_value() == normalized + reopen_studio(page) + assert page.locator('#musicCookiesInput').input_value() == normalized + received = [] + + def download(command, **kwargs): + cookie_path = command[command.index('--cookies') + 1] + jar = MozillaCookieJar(cookie_path) + jar.load(ignore_discard=True, ignore_expires=True) + received.append({cookie.name: cookie.value for cookie in jar}) + output = command[command.index('-o') + 1].replace('%(ext)s', 'mp3') + Path(output).write_bytes(b'test-mp3') + + monkeypatch.setattr(worker.subprocess, 'run', download) + monkeypatch.setattr(worker, '_get_song_title', lambda url: 'Test song') + page.locator('#musicUrlInput').fill('https://www.youtube.com/watch?v=test') + page.evaluate('handleMusicDownload({preventDefault(){}})') + page.wait_for_function("!document.getElementById('musicBtn').disabled") + assert received == [{'SID': 'fake-test-value', 'EMPTY': ''}] + assert page.locator('#studioMetaBadge').inner_text().startswith('Done') + + +def test_invalid_cookie_file_keeps_previous_cookies(studio): + page, _ = studio + page.evaluate('async () => await window.videoStudioReady') + page.locator('summary').filter(has_text='YouTube Cookies').click() + page.locator('#musicCookiesInput').fill('previous cookies') + page.locator('#musicCookiesFileInput').set_input_files({ + 'name': 'cookies.txt', 'mimeType': 'text/plain', 'buffer': b'{"cookies": []}', + }) + page.wait_for_function("document.getElementById('musicCookiesFileStatus').textContent.startsWith('Please export')") + assert page.locator('#musicCookiesInput').input_value() == 'previous cookies' + assert page.locator('#musicBtn').is_enabled() diff --git a/tests/test_worker.py b/tests/test_worker.py index 222694f..dbcb137 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -81,6 +81,18 @@ def test_download_requires_url(worker, payload): assert worker.app.test_client().post('/api/music_download', json=payload).status_code == 400 +@pytest.mark.parametrize('stderr, expected', [ + (b'The provided YouTube account cookies are no longer valid.', 'session is no longer valid'), + (b'Sign in to confirm you\xe2\x80\x99re not a bot.', 'server connection'), +]) +def test_download_explains_youtube_authentication_failure(worker, monkeypatch, stderr, expected): + failure = subprocess.CalledProcessError(1, 'yt-dlp', stderr=stderr) + monkeypatch.setattr(worker.subprocess, 'run', Mock(side_effect=failure)) + response = worker.app.test_client().post('/api/music_download', json={'url': 'https://www.youtube.com/watch?v=test'}) + assert response.status_code == 500 + assert expected in response.json['error'] + + def test_download_moves_audio_across_filesystems(worker, monkeypatch, tmp_path): import errno diff --git a/yt-dlp_serv.py b/yt-dlp_serv.py index 3247852..48d0ca3 100644 --- a/yt-dlp_serv.py +++ b/yt-dlp_serv.py @@ -230,7 +230,7 @@ def music_download(): # yt-dlp with `-x` writes to a temp file, so pipe through the temp dir and # read the produced .mp3 back. `-o -` is unreliable when extracting audio. - cookies = str(data.get('cookies') or '').strip() + cookies = str(data.get('cookies') or '').strip('\r\n') download_dir = tempfile.mkdtemp(prefix="automap_download_") cookie_args = [] if cookies: @@ -296,6 +296,15 @@ def music_download(): except subprocess.CalledProcessError as e: error_message = (e.stderr or b'').decode("utf-8", errors="ignore").strip() + if 'cookies are no longer valid' in error_message: + error_message = ('YouTube rejected the account cookies because the session is no longer valid. ' + 'Export fresh youtube.com cookies from a new private/incognito session, ' + 'close that window, then upload the new cookies.txt file.') + elif 'Sign in to confirm' in error_message and 'bot' in error_message: + error_message = ('YouTube requires a sign-in/bot check for this request. ' + 'Upload fresh YouTube account cookies. If they are already fresh, ' + 'YouTube may also be challenging the server connection; ' + 'a correctly formatted cookies file alone cannot guarantee access.') return jsonify({"status": "error", "error": f"yt-dlp ERROR: {error_message}"}), 500