From 0c059865e23807079a2ab05a8cf4485f03b99628 Mon Sep 17 00:00:00 2001 From: Roland Date: Fri, 20 Feb 2026 14:37:58 -0700 Subject: [PATCH] Updating download process to prevent rate limiting. * Added encrypted cookies feature for use with yt-dlp. Decrypted cookies never touch the disk. * Adding sleep between all downloads to prevent rapid requests. * Channels are fully refreshed before downloading. * Removing superseded video browser profile. --- app/src/DashboardPage.js | 2 + app/src/api.js | 84 ++++- app/src/components/Common.js | 21 ++ app/src/components/Download.js | 39 -- app/src/components/Theme.tsx | 24 +- app/src/components/Videos.js | 358 +++++++++++++++---- app/src/components/admin/Downloads.js | 3 + app/src/components/admin/Settings.js | 14 + docker-compose.yml | 6 +- docker/api/Dockerfile | 14 +- main.py | 8 +- modules/videos/api.py | 71 +++- modules/videos/cookies.py | 474 +++++++++++++++++++++++++ modules/videos/downloader.py | 162 ++++----- modules/videos/lib.py | 214 ++++------- modules/videos/models.py | 14 +- modules/videos/schema.py | 30 ++ modules/videos/test/test_cookies.py | 402 +++++++++++++++++++++ modules/videos/test/test_downloader.py | 63 +--- modules/videos/test/test_lib.py | 91 ----- modules/videos/video/lib.py | 43 +-- requirements.txt | 3 +- wrolpi/common.py | 10 + wrolpi/conftest.py | 6 +- wrolpi/contexts.py | 11 + wrolpi/downloader.py | 38 ++ wrolpi/flags.py | 13 + wrolpi/root_api.py | 1 + wrolpi/schema.py | 6 +- wrolpi/test/test_downloader.py | 5 +- 30 files changed, 1678 insertions(+), 552 deletions(-) create mode 100644 modules/videos/cookies.py create mode 100644 modules/videos/test/test_cookies.py diff --git a/app/src/DashboardPage.js b/app/src/DashboardPage.js index fceb4e3a..d23e9afb 100644 --- a/app/src/DashboardPage.js +++ b/app/src/DashboardPage.js @@ -1,4 +1,5 @@ import { + CookiesLockedMessage, ErrorMessage, LoadStatistic, PageContainer, @@ -91,6 +92,7 @@ function FlagsMessages() { {settings && settings['ignore_outdated_zims'] === false && flags.outdated_zims ? : null} {internetDownMessage} + } diff --git a/app/src/api.js b/app/src/api.js index d5aa6943..6b53c594 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -301,6 +301,7 @@ export async function getSettings() { download_manager_stopped: content.download_manager_stopped, download_on_startup: content.download_on_startup, download_timeout: content.download_timeout, + download_wait: content.download_wait, hotspot_device: content.hotspot_device, hotspot_on_startup: content.hotspot_on_startup, hotspot_password: content.hotspot_password, @@ -469,22 +470,6 @@ export async function getArchiveStatistics() { return response } -export async function fetchBrowserProfiles() { - const response = await apiGet(`${API_URI}/videos/browser-profiles`); - if (response.status === 200) { - return await response.json(); - } else { - const message = await getErrorMessage(response, 'Failed to get browser profiles.'); - toast({ - type: 'error', - title: 'Fetching Browser Profiles Failed', - description: message, - time: 5000, - }); - return {} - } -} - export async function updateVideoDownloaderSettings(settings) { const response = await apiPut(`${API_URI}/videos/settings`, settings); if (response.status === 200) { @@ -1931,3 +1916,70 @@ export async function getBulkTagProgress() { // Not toasting because this happens often during polling. return null; } + +// Encrypted Cookies API + +export async function getCookiesStatus() { + const response = await apiGet(`${VIDEOS_API}/cookies/status`); + if (response.ok) { + return await response.json(); + } + const message = await getErrorMessage(response, 'Failed to get cookies status.'); + toast({type: 'error', title: 'Cookies Error', description: message, time: 5000}); + return null; +} + +export async function uploadCookies(cookiesContent, password) { + const body = {cookies_content: cookiesContent, password}; + const response = await apiPost(`${VIDEOS_API}/cookies`, body); + if (response.ok) { + toast({type: 'success', title: 'Cookies Saved', description: 'Cookies encrypted and saved successfully.', time: 3000}); + return {success: true}; + } + const message = await getErrorMessage(response, 'Failed to save cookies.'); + toast({type: 'error', title: 'Cookies Error', description: message, time: 5000}); + return {success: false, error: message}; +} + +export async function deleteCookies() { + const response = await apiDelete(`${VIDEOS_API}/cookies`); + if (response.status === 204) { + toast({type: 'success', title: 'Cookies Deleted', description: 'Encrypted cookies file deleted.', time: 3000}); + return {success: true}; + } + const message = await getErrorMessage(response, 'Failed to delete cookies.'); + toast({type: 'error', title: 'Cookies Error', description: message, time: 5000}); + return {success: false, error: message}; +} + +export async function unlockCookies(password) { + const body = {password}; + const response = await apiPost(`${VIDEOS_API}/cookies/unlock`, body); + if (response.ok) { + toast({type: 'success', title: 'Cookies Unlocked', description: 'Cookies decrypted and ready for downloads.', time: 3000}); + return {success: true}; + } + const message = await getErrorMessage(response, 'Failed to unlock cookies.'); + toast({type: 'error', title: 'Cookies Error', description: message, time: 5000}); + return {success: false, error: message}; +} + +export async function lockCookies() { + const response = await apiPost(`${VIDEOS_API}/cookies/lock`); + if (response.ok) { + toast({type: 'success', title: 'Cookies Locked', description: 'Cookies cleared from memory.', time: 3000}); + return {success: true}; + } + const message = await getErrorMessage(response, 'Failed to lock cookies.'); + toast({type: 'error', title: 'Cookies Error', description: message, time: 5000}); + return {success: false, error: message}; +} + +export async function fetchSuggestedUserAgent() { + const response = await apiGet(`${VIDEOS_API}/suggested-user-agent`); + if (response.ok) { + const data = await response.json(); + return data?.user_agent || ''; + } + return ''; +} diff --git a/app/src/components/Common.js b/app/src/components/Common.js index 5d4971a6..ab0d91d1 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -589,6 +589,27 @@ export function WROLModeMessage({content}) { return null; } +export function CookiesLockedMessage() { + const {settings} = React.useContext(SettingsContext); + const {status} = React.useContext(StatusContext); + const flags = status?.flags || {}; + + if (!flags.cookies_exist || flags.cookies_unlocked || settings?.wrol_mode) { + return null; + } + + return + + + Cookies Locked + You have encrypted cookies stored, but they are currently locked. + + Unlock in Video Settings + + + ; +} + // Thanks https://www.npmjs.com/package/text-ellipsis export function textEllipsis(str, maxLength = 100, {side = "end", ellipsis = "..."} = {}) { if (str && str.length > maxLength) { diff --git a/app/src/components/Download.js b/app/src/components/Download.js index 0395d61d..c8ca73d1 100644 --- a/app/src/components/Download.js +++ b/app/src/components/Download.js @@ -359,38 +359,6 @@ export function ChannelTagNameForm({form}) { } -export function UseBrowserProfile({form}) { - const [config, setConfig] = useState(null); - - const localFetchConfig = async () => { - const result = await fetchVideoDownloaderConfig(); - setConfig(result); - if (result?.always_use_browser_profile === true) { - // Enable the toggle if "always_use_browser_profile" is set. - form.setValue('settings.use_browser_profile', true); - } - } - - React.useEffect(() => { - localFetchConfig(); - }, []); - - const popupContent = <>Use the browser profile to download videos. - This is useful for downloading videos that require a login. See: Videos > Settings; - const label = ; - return -} - export function VideosDownloadForm({ singleDownload = true, onCancel, @@ -415,7 +383,6 @@ export function VideosDownloadForm({ tag_names: [], downloader: Downloaders.Video, settings: { - use_browser_profile: false, video_format: defaultVideoFormat, video_resolutions: configResolutions, } @@ -523,11 +490,6 @@ export function VideosDownloadForm({ - - - - - @@ -659,7 +621,6 @@ export function ChannelDownloadForm({ minimum_duration: null, title_exclude: null, title_include: null, - use_browser_profile: false, video_count_limit: null, video_format: defaultVideoFormat, video_resolutions: configResolutions, diff --git a/app/src/components/Theme.tsx b/app/src/components/Theme.tsx index 45b03be8..8fac67cd 100644 --- a/app/src/components/Theme.tsx +++ b/app/src/components/Theme.tsx @@ -4,6 +4,7 @@ import { Accordion as SAccordion, Breadcrumb as SBreadcrumb, Button as SButton, + ButtonGroup as SButtonGroup, Card as SCard, Divider as SDivider, Form as SForm, @@ -38,6 +39,7 @@ import { AccordionProps, BreadcrumbProps, ButtonProps, + ButtonGroupProps, CardProps as SCardProps, DividerProps, FormProps, @@ -222,12 +224,30 @@ export function Accordion(props: AccordionProps) { return } -export const Button = forwardRef((props, ref) => { +// ---------------------------------------------------------------------------- +// Button Compound Component +// ---------------------------------------------------------------------------- + +type ButtonGroupComponent = React.FC; + +interface ButtonComponent extends React.ForwardRefExoticComponent> { + Group: ButtonGroupComponent; +} + +const ButtonGroup: ButtonGroupComponent = (props) => { + return +}; + +const ButtonBase = forwardRef((props, ref) => { const {i, inverted} = useContext(ThemeContext); const mergedProps = defaultGrey({...i, ...props}, !!inverted); return }); -Button.displayName = 'Button'; +ButtonBase.displayName = 'ButtonBase'; + +export const Button: ButtonComponent = Object.assign(ButtonBase, { + Group: ButtonGroup, +}); export function Divider(props: DividerProps) { const {i} = useContext(ThemeContext); diff --git a/app/src/components/Videos.js b/app/src/components/Videos.js index 5b7d782a..06e7182b 100644 --- a/app/src/components/Videos.js +++ b/app/src/components/Videos.js @@ -32,7 +32,10 @@ import { Container, Form, FormDropdown, + FormInput, + FormTextArea, Image, + Label, PlaceholderHeader, PlaceholderLine, StatisticLabel, @@ -44,14 +47,19 @@ import {useChannel, useSearchOrder, useSearchVideos, useVideo, useVideoStatistic import {FileRowTagIcon, FilesView} from "./Files"; import Grid from "semantic-ui-react/dist/commonjs/collections/Grid"; import Icon from "semantic-ui-react/dist/commonjs/elements/Icon"; -import {Button, Card, Header, Loader, Placeholder, Popup, Segment, Statistic} from "./Theme"; +import {Button, Card, Header, Loader, Modal, Placeholder, Popup, Segment, Statistic} from "./Theme"; import { deleteVideos, - fetchBrowserProfiles, + deleteCookies, + fetchSuggestedUserAgent, fetchVideoDownloaderConfig, + getCookiesStatus, + lockCookies, postVideoFileFormat, previewBatchReorganization, - updateVideoDownloaderConfig + unlockCookies, + updateVideoDownloaderConfig, + uploadCookies, } from "../api"; import {Media, QueryContext, ThemeContext} from "../contexts/contexts"; import _ from "lodash"; @@ -319,10 +327,10 @@ function VideosSettingsPage() { writesubtitles: true, writethumbnail: true, }, - always_use_browser_profile: false, yt_dlp_extra_args: '', - browser_profile: '', download_missing_video_comments: false, + user_agent: '', + sleep_requests: 0.75, }; const configSubmitter = async () => { @@ -335,47 +343,16 @@ function VideosSettingsPage() { emptyFormData, }); - const emptyProfilesOptions = [{key: null, text: 'No profiles found'}]; - const loadingProfilesOptions = [{key: null, text: 'Loading profiles, please wait...'}]; - const [browserProfilesOptions, setBrowserProfilesOptions] = useState(loadingProfilesOptions); - - const localFetchBrowserProfiles = async () => { - let tempProfiles = []; - let localBrowserProfiles = await fetchBrowserProfiles(); - - for (const [browserKey, profilePaths] of Object.entries(localBrowserProfiles)) { - if (!profilePaths || profilePaths.length === 0) continue; - - // Extract browser display name from key (e.g., "chromium_profiles" -> "Chromium") - const browserName = browserKey.replace('_profiles', '') - .replace(/_/g, ' ') - .replace(/\b\w/g, c => c.toUpperCase()); - - for (const profilePath of profilePaths) { - const profileName = profilePath.split('/').pop(); - tempProfiles.push({ - value: profilePath, - text: `${browserName}: ${profileName}`, - }); - } - } - - if (_.isEmpty(tempProfiles)) { - tempProfiles = emptyProfilesOptions; - } - console.debug('VideosSettingsPage: Got browser profiles:', tempProfiles); - setBrowserProfilesOptions(tempProfiles); - }; + const [suggestedUserAgent, setSuggestedUserAgent] = useState(''); React.useEffect(() => { - localFetchBrowserProfiles(); + const fetchSuggested = async () => { + const ua = await fetchSuggestedUserAgent(); + setSuggestedUserAgent(ua); + }; + fetchSuggested(); }, []); - const alwaysUseBrowserProfileLabel = ; const downloadMissingVideoCommentsLabel = + + + + + + configForm.setValue('user_agent', e.target.value)} + placeholder='Leave empty to use yt-dlp default' + action={{ + content: 'Use Current Browser', + onClick: () => configForm.setValue('user_agent', suggestedUserAgent), + }} + /> + + + + - + + + configForm.setValue('sleep_requests', parseFloat(e.target.value) || 0)} + placeholder='0.75' + label={{basic: true, content: 'seconds'}} + labelPosition='right' + /> + @@ -465,15 +481,6 @@ function VideosSettingsPage() { icon='comments' /> - - - @@ -515,6 +522,8 @@ function VideosSettingsPage() { + + setBatchModalOpen(false)} @@ -527,37 +536,230 @@ function VideosSettingsPage() { } +function CookiesSettingsSection() { + const [status, setStatus] = useState({cookies_exist: false, cookies_unlocked: false}); + const [loading, setLoading] = useState(true); + const [uploadModalOpen, setUploadModalOpen] = useState(false); + const [unlockModalOpen, setUnlockModalOpen] = useState(false); + const [cookiesContent, setCookiesContent] = useState(''); + const [password, setPassword] = useState(''); + const [unlockPassword, setUnlockPassword] = useState(''); + const [submitting, setSubmitting] = useState(false); -export function VideoBrowserCookiesSelector({ - form, - options, - name = 'browser_profile', - path = 'browser_profile', - }) { - const [inputProps, inputAttrs] = form.getSelectionProps({name, path}); + const fetchStatus = async () => { + setLoading(true); + const result = await getCookiesStatus(); + if (result) { + setStatus(result); + } + setLoading(false); + }; + + useEffect(() => { + fetchStatus(); + }, []); + + const handleUpload = async () => { + if (password.length < 8) { + return; + } + setSubmitting(true); + const result = await uploadCookies(cookiesContent, password); + setSubmitting(false); + if (result.success) { + setUploadModalOpen(false); + setCookiesContent(''); + setPassword(''); + fetchStatus(); + } + }; + + const handleUnlock = async () => { + setSubmitting(true); + const result = await unlockCookies(unlockPassword); + setSubmitting(false); + if (result.success) { + setUnlockModalOpen(false); + setUnlockPassword(''); + fetchStatus(); + } + }; + + const handleLock = async () => { + setSubmitting(true); + await lockCookies(); + setSubmitting(false); + fetchStatus(); + }; + + const handleDelete = async () => { + setSubmitting(true); + await deleteCookies(); + setSubmitting(false); + fetchStatus(); + }; + + const getStatusLabel = () => { + if (loading) return ; + if (!status.cookies_exist) return ; + if (status.cookies_unlocked) return ; + return ; + }; const popupContent =
- Select a browser profile to use for cookies. This is useful for sites that require login to download videos. -
-
-

Help page

+

Upload cookies exported from your browser to allow yt-dlp to download videos that require authentication.

+

Browser extensions for exporting cookies:

+ +

Cookies are encrypted with AES-128 and stored securely. You'll need to unlock them with your password after each restart.

; - return <> - - - + return +
+ +
+ +

Use this feature at your own risk! You may be suspended or blocked if abused! +

+ +
+ Status: {getStatusLabel()} +
+ + + {!status.cookies_exist && ( + + )} + + {status.cookies_exist && !status.cookies_unlocked && ( + + )} + + {status.cookies_exist && status.cookies_unlocked && ( + + )} + + {status.cookies_exist && ( + <> + + + Delete + + + )} + + + {/* Upload Modal */} + setUploadModalOpen(false)} + size='small' + > + Upload Cookies + +
+ setCookiesContent(e.target.value)} + rows={10} + /> + setPassword(e.target.value)} + error={password.length > 0 && password.length < 8 ? 'Password must be at least 8 characters' : null} + /> +

+ Remember this password - you'll need it to unlock cookies after each restart. +

+ +
+ + + + +
+ + {/* Unlock Modal */} + setUnlockModalOpen(false)} + size='tiny' + > + Unlock Cookies + +
+ setUnlockPassword(e.target.value)} + onKeyPress={(e) => e.key === 'Enter' && handleUnlock()} + /> + +
+ + + + +
+
; } function VideosStatistics() { diff --git a/app/src/components/admin/Downloads.js b/app/src/components/admin/Downloads.js index b2dc6bb6..88644843 100644 --- a/app/src/components/admin/Downloads.js +++ b/app/src/components/admin/Downloads.js @@ -13,6 +13,7 @@ import { import {Link} from "react-router"; import { APIButton, + CookiesLockedMessage, DisableDownloadsToggle, ErrorMessage, formatFrequency, @@ -24,6 +25,7 @@ import { Button as SButton, ButtonGroup, Checkbox, + Icon, Label, Loader, PlaceholderLine, @@ -625,6 +627,7 @@ export function DownloadsPage() { return <> +
Downloads {pendingOnceDownloadsSpan}
diff --git a/app/src/components/admin/Settings.js b/app/src/components/admin/Settings.js index 78a4b9e8..95eee6a9 100644 --- a/app/src/components/admin/Settings.js +++ b/app/src/components/admin/Settings.js @@ -362,6 +362,7 @@ export function SettingsPage() { setDisabled(true); setPendingSave(true); newSettings.download_timeout = parseInt(newSettings.download_timeout); + newSettings.download_wait = parseInt(newSettings.download_wait); newSettings.log_level = toApiLogLevel(newSettings.log_level); try { await saveSettings(newSettings); @@ -448,6 +449,7 @@ export function SettingsPage() { archive_destination: settings.archive_destination, download_on_startup: settings.download_on_startup, download_timeout: settings.download_timeout, + download_wait: settings.download_wait, hotspot_device: settings.hotspot_device, hotspot_on_startup: settings.hotspot_on_startup, hotspot_password: settings.hotspot_password, @@ -564,6 +566,18 @@ export function SettingsPage() { /> + + + Wait Between Downloads + + } + value={state.download_wait} + disabled={disabled || state.download_wait === null} + onChange={(e, i) => handleTimeoutChange(e, 'download_wait', i.value)} + /> + + diff --git a/docker-compose.yml b/docker-compose.yml index 16fbd4e8..5ad931de 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -45,8 +45,10 @@ services: api: depends_on: - - db - - controller + db: + condition: service_healthy + controller: + condition: service_started build: context: . dockerfile: docker/api/Dockerfile diff --git a/docker/api/Dockerfile b/docker/api/Dockerfile index 59084124..43bc1aec 100644 --- a/docker/api/Dockerfile +++ b/docker/api/Dockerfile @@ -3,8 +3,20 @@ ENV DOCKER=true WORKDIR /opt/wrolpi # Update dependencies for the services install. -RUN apt-get update && apt-get install -y ffmpeg catdoc sysstat aria2 iputils-ping +RUN apt-get update && apt-get install -y ffmpeg catdoc sysstat aria2 iputils-ping unzip RUN ffmpeg -version + +# Install Deno runtime for yt-dlp +RUN ARCH=$(uname -m) && \ + if [ "$ARCH" = "aarch64" ]; then DENO_ARCH="aarch64-unknown-linux-gnu"; \ + elif [ "$ARCH" = "x86_64" ]; then DENO_ARCH="x86_64-unknown-linux-gnu"; \ + else echo "Unsupported architecture: $ARCH" && exit 1; fi && \ + curl -fsSL "https://github.com/denoland/deno/releases/download/v2.2.4/deno-${DENO_ARCH}.zip" -o /tmp/deno.zip \ + && unzip /tmp/deno.zip -d /usr/local/bin/ \ + && chmod +x /usr/local/bin/deno \ + && rm /tmp/deno.zip \ + && deno --version + # yt-dlp needs cache directory RUN mkdir /.cache && chown -R 1000:1000 /.cache diff --git a/main.py b/main.py index d42ab80c..97ad5e88 100755 --- a/main.py +++ b/main.py @@ -18,6 +18,7 @@ from wrolpi.common import logger, check_media_directory, set_log_level, limit_co create_empty_config_files, TRACE_LEVEL from wrolpi.contexts import attach_shared_contexts, reset_shared_contexts, initialize_configs_contexts from wrolpi.dates import Seconds +from modules.videos.cookies import lock_cookies from wrolpi.downloader import download_manager, get_download_manager_config from wrolpi.errors import WROLModeEnabled from wrolpi.files.worker import file_worker @@ -210,7 +211,7 @@ async def initialize_configs(app: Sanic): @api_app.listener('reload_process_stop') @limit_concurrent(1) async def handle_server_shutdown(*args, **kwargs): - """Stop downloads when server is shutting down.""" + """Stop downloads and securely clear sensitive data when server is shutting down.""" logger.warning('Shutting down') try: download_manager.stop() @@ -225,6 +226,11 @@ async def handle_server_shutdown(*args, **kwargs): await cancel_background_tasks() except Exception as e: logger.error('cancel_background_tasks failed. This is probably fine', exc_info=e) + # Securely zero cookies memory before shutdown + try: + lock_cookies() + except Exception as e: + logger.error('Failed to securely zero cookies memory', exc_info=e) @api_app.signal(Event.SERVER_SHUTDOWN_AFTER) diff --git a/modules/videos/api.py b/modules/videos/api.py index c94db48b..7b51cba9 100644 --- a/modules/videos/api.py +++ b/modules/videos/api.py @@ -8,6 +8,7 @@ from sanic_ext.extensions.openapi import openapi from wrolpi.api_utils import json_response from wrolpi.common import logger from . import lib, schema +from . import cookies from .channel.api import channel_bp from .downloader import preview_filename from .lib import format_videos_destination @@ -69,7 +70,69 @@ async def post_file_format(_: Request, body: schema.VideoFileFormatRequest): ), status=HTTPStatus.BAD_REQUEST) -@content_bp.get('/browser-profiles') -async def get_browser_profiles(_: Request): - browser_profiles = lib.get_browser_profiles() - return json_response(browser_profiles) +@content_bp.post('/cookies') +@openapi.definition( + description='Upload and encrypt cookies for yt-dlp', + body=schema.CookiesUploadRequest, +) +@validate(schema.CookiesUploadRequest) +async def upload_cookies(_: Request, body: schema.CookiesUploadRequest): + """Upload cookies content, encrypt with password, and save.""" + try: + cookies.save_encrypted_cookies(body.cookies_content, body.password) + return json_response({'success': True}, HTTPStatus.CREATED) + except ValueError as e: + return json_response({'error': str(e)}, HTTPStatus.BAD_REQUEST) + + +@content_bp.get('/cookies/status') +@openapi.response(HTTPStatus.OK, schema.CookiesStatusResponse) +async def get_cookies_status(_: Request): + """Get cookies status (exist? unlocked?).""" + status = cookies.get_cookies_status() + return json_response(status) + + +@content_bp.delete('/cookies') +async def delete_cookies(_: Request): + """Delete stored encrypted cookies.""" + deleted = cookies.delete_cookies() + if deleted: + return json_response({'success': True}, HTTPStatus.NO_CONTENT) + else: + return json_response({'error': 'No cookies file found'}, HTTPStatus.NOT_FOUND) + + +@content_bp.post('/cookies/unlock') +@openapi.definition( + description='Decrypt cookies to memory for session use', + body=schema.CookiesUnlockRequest, +) +@validate(schema.CookiesUnlockRequest) +async def unlock_cookies(_: Request, body: schema.CookiesUnlockRequest): + """Unlock cookies by decrypting to memory.""" + try: + cookies.unlock_cookies(body.password) + return json_response({'success': True}) + except FileNotFoundError: + return json_response({'error': 'No cookies file found'}, HTTPStatus.NOT_FOUND) + except ValueError as e: + return json_response({'error': str(e)}, HTTPStatus.BAD_REQUEST) + + +@content_bp.post('/cookies/lock') +async def lock_cookies(_: Request): + """Lock cookies by clearing from memory.""" + cookies.lock_cookies() + return json_response({'success': True}) + + +@content_bp.get('/suggested-user-agent') +async def get_suggested_user_agent(request: Request): + """Return the user-agent of the browser making this request. + + This is useful for pre-filling the user_agent field in Video Settings + with the browser's user-agent, which should match the browser used to + export cookies.""" + user_agent = request.headers.get('User-Agent', '') + return json_response({'user_agent': user_agent}) diff --git a/modules/videos/cookies.py b/modules/videos/cookies.py new file mode 100644 index 00000000..390d973b --- /dev/null +++ b/modules/videos/cookies.py @@ -0,0 +1,474 @@ +""" +Encrypted cookies management for yt-dlp video downloads. + +This module provides secure storage and retrieval of browser cookies for use with yt-dlp. +Cookies are encrypted using Fernet (AES-128-CBC + HMAC-SHA256) with PBKDF2 key derivation. + +Security features: +- Encryption: Fernet (AES-128-CBC + HMAC-SHA256) +- Key derivation: PBKDF2-SHA256 with 480k iterations (OWASP 2024 minimum) +- Password handling: Decrypt once to memory, forget password immediately +- In-memory storage: Decrypted cookies only in Python memory, not on disk +- Per-download temp files: Unique file per download, deleted immediately after +- Temp file permissions: chmod 600 (owner only) +- Secure deletion: Overwrite temp file with zeros before unlinking +- Memory zeroing: Secure clearing of decrypted cookies using ctypes memset +""" +import base64 +import ctypes +import os +import pathlib +import secrets +import tempfile +from contextlib import contextmanager +from typing import Optional, Tuple + +from cryptography.fernet import Fernet, InvalidToken +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC + +from wrolpi import flags +from wrolpi.common import get_media_directory, logger + +logger = logger.getChild(__name__) + +# OWASP 2024 minimum iterations for PBKDF2-SHA256 +PBKDF2_ITERATIONS = 480_000 +SALT_SIZE = 16 +MIN_PASSWORD_LENGTH = 8 + +# Encrypted cookies file path relative to config directory +COOKIES_FILENAME = 'cookies.txt.enc' + +# Module-level session state (in-memory only) +# Uses bytearray for mutable storage that can be securely zeroed +_session_cookies_content: Optional[bytearray] = None + + +def _get_shared_cookies() -> Optional[bytes]: + """Get cookies from shared context (set by another worker).""" + try: + from wrolpi.root_api import api_app + return api_app.shared_ctx.secure_cookies.get('content') + except (AttributeError, RuntimeError): + # shared_ctx not initialized (during testing or startup) + return None + + +def _set_shared_cookies(content: bytes) -> None: + """Store cookies in shared context for cross-worker access.""" + try: + from wrolpi.root_api import api_app + with api_app.shared_ctx.secure_cookies_lock: + api_app.shared_ctx.secure_cookies['content'] = content + except (AttributeError, RuntimeError): + # shared_ctx not initialized (during testing or startup) + pass + + +def _clear_shared_cookies() -> None: + """Clear cookies from shared context.""" + try: + from wrolpi.root_api import api_app + with api_app.shared_ctx.secure_cookies_lock: + api_app.shared_ctx.secure_cookies.clear() + except (AttributeError, RuntimeError): + pass + + +def _get_memset(): + """Get the memset function from the C library.""" + # Linux (including Raspberry Pi), macOS, Docker - all Unix-like + return ctypes.CDLL(None).memset + + +def _secure_zero_memory(data: bytearray) -> None: + """ + Securely zero memory containing sensitive data. + + Uses ctypes to call C's memset, ensuring the memory is actually + overwritten rather than just dereferenced. + """ + if data is None or len(data) == 0: + return + + try: + memset = _get_memset() + # Get the address of the bytearray's buffer + # bytearray objects expose their buffer via ctypes + buftype = ctypes.c_char * len(data) + buf = buftype.from_buffer(data) + memset(buf, 0, len(data)) + except Exception as e: + # Fallback: overwrite with zeros using Python + # Less secure but better than nothing + logger.warning(f'ctypes memset failed, using fallback: {e}') + for i in range(len(data)): + data[i] = 0 + + +def get_cookies_file_path() -> pathlib.Path: + """Get the path to the encrypted cookies file.""" + config_dir = get_media_directory() / 'config' + config_dir.mkdir(parents=True, exist_ok=True) + return config_dir / COOKIES_FILENAME + + +def _derive_key(password: str, salt: bytes) -> bytes: + """Derive a Fernet key from password and salt using PBKDF2.""" + kdf = PBKDF2HMAC( + algorithm=hashes.SHA256(), + length=32, + salt=salt, + iterations=PBKDF2_ITERATIONS, + ) + key = base64.urlsafe_b64encode(kdf.derive(password.encode('utf-8'))) + return key + + +def encrypt_cookies(content: str, password: str) -> bytes: + """ + Encrypt cookies content with password. + + Args: + content: The plain text cookies content (Netscape format) + password: User-provided password (min 8 chars) + + Returns: + Encrypted bytes: [16 bytes salt][Fernet encrypted content] + + Raises: + ValueError: If password is too short + """ + if len(password) < MIN_PASSWORD_LENGTH: + raise ValueError(f'Password must be at least {MIN_PASSWORD_LENGTH} characters') + + # Generate random salt + salt = secrets.token_bytes(SALT_SIZE) + + # Derive key from password + key = _derive_key(password, salt) + + # Encrypt content + fernet = Fernet(key) + encrypted = fernet.encrypt(content.encode('utf-8')) + + # Prepend salt to encrypted content + return salt + encrypted + + +def decrypt_cookies(encrypted: bytes, password: str) -> str: + """ + Decrypt cookies content with password. + + Args: + encrypted: Encrypted bytes from encrypt_cookies() + password: User-provided password + + Returns: + Decrypted cookies content string + + Raises: + ValueError: If data is corrupted or password is wrong + """ + if len(encrypted) < SALT_SIZE: + raise ValueError('Encrypted data is too short') + + # Extract salt and encrypted content + salt = encrypted[:SALT_SIZE] + ciphertext = encrypted[SALT_SIZE:] + + # Derive key from password + key = _derive_key(password, salt) + + # Decrypt content + fernet = Fernet(key) + try: + decrypted = fernet.decrypt(ciphertext) + return decrypted.decode('utf-8') + except InvalidToken: + raise ValueError('Invalid password or corrupted data') + + +def validate_cookies_format(content: str) -> Tuple[bool, Optional[str]]: + """ + Validate that the content appears to be valid Netscape cookies format. + + Args: + content: The cookies content to validate + + Returns: + Tuple of (is_valid, error_message) + """ + if not content or not content.strip(): + return False, 'Cookies content is empty' + + lines = content.strip().split('\n') + + # Check for Netscape header (optional but common) + has_header = False + valid_cookie_lines = 0 + + for line in lines: + line = line.strip() + + # Skip empty lines + if not line: + continue + + # Skip comments (lines starting with #) + if line.startswith('#'): + # Check for Netscape header + if 'Netscape' in line or 'HTTP Cookie File' in line: + has_header = True + continue + + # Each cookie line should have at least 7 tab-separated fields: + # domain, flag, path, secure, expiration, name, value + fields = line.split('\t') + if len(fields) >= 7: + valid_cookie_lines += 1 + else: + # Allow some flexibility - some formats use fewer fields + # But should have at least domain and name + if len(fields) < 2: + return False, f'Invalid cookie line format: {line[:50]}...' + + if valid_cookie_lines == 0: + return False, 'No valid cookie lines found. Expected Netscape/Mozilla cookies.txt format.' + + return True, None + + +def save_encrypted_cookies(content: str, password: str) -> pathlib.Path: + """ + Validate, encrypt, and save cookies to the config directory. + + Auto-unlocks cookies after saving (user just provided password). + + Args: + content: Plain text cookies content + password: User-provided password + + Returns: + Path to the saved encrypted file + + Raises: + ValueError: If cookies format is invalid or password is too short + """ + global _session_cookies_content + + # Validate format + is_valid, error = validate_cookies_format(content) + if not is_valid: + raise ValueError(error) + + # Encrypt + encrypted = encrypt_cookies(content, password) + + # Save to file + cookies_path = get_cookies_file_path() + cookies_path.write_bytes(encrypted) + + # Set restrictive permissions (owner only) + os.chmod(cookies_path, 0o600) + + # Set flags and auto-unlock (user just provided the password) + # Store as bytearray for secure clearing later + flags.cookies_exist.set() + _session_cookies_content = bytearray(content.encode('utf-8')) + _set_shared_cookies(content.encode('utf-8')) # Share with other workers + flags.cookies_unlocked.set() + + logger.info(f'Saved encrypted cookies to {cookies_path}') + return cookies_path + + +def cookies_exist() -> bool: + """Check if encrypted cookies file exists.""" + return get_cookies_file_path().is_file() + + +def delete_cookies() -> bool: + """ + Securely delete the encrypted cookies file. + + Returns: + True if file was deleted, False if it didn't exist + """ + cookies_path = get_cookies_file_path() + if not cookies_path.is_file(): + return False + + # Overwrite with zeros before deletion + size = cookies_path.stat().st_size + cookies_path.write_bytes(b'\x00' * size) + cookies_path.unlink() + + # Clear flags + flags.cookies_exist.clear() + flags.cookies_unlocked.clear() + + # Also clear session if unlocked + lock_cookies() + + logger.info('Deleted encrypted cookies file') + return True + + +def unlock_cookies(password: str) -> None: + """ + Decrypt cookies to memory for session use. + + The password is NOT stored - it goes out of scope after this function returns. + + Args: + password: User-provided password + + Raises: + FileNotFoundError: If no encrypted cookies file exists + ValueError: If password is wrong or data is corrupted + """ + global _session_cookies_content + + cookies_path = get_cookies_file_path() + if not cookies_path.is_file(): + raise FileNotFoundError('No encrypted cookies file found') + + encrypted = cookies_path.read_bytes() + decrypted = decrypt_cookies(encrypted, password) + + # Store in shared context for cross-worker access + _set_shared_cookies(decrypted.encode('utf-8')) + + # Store locally for this worker (as bytearray for secure clearing later) + _session_cookies_content = bytearray(decrypted.encode('utf-8')) + flags.cookies_unlocked.set() + logger.info('Cookies unlocked to memory (shared)') + + +def lock_cookies() -> None: + """Clear session - securely remove decrypted cookies from memory.""" + global _session_cookies_content + + if _session_cookies_content is not None: + _secure_zero_memory(_session_cookies_content) + _session_cookies_content = None + + # Clear shared context + _clear_shared_cookies() + + flags.cookies_unlocked.clear() + logger.info('Cookies locked (memory securely cleared)') + + +def cookies_unlocked() -> bool: + """Check if cookies are decrypted in memory (local or shared).""" + global _session_cookies_content + + # Check local first (fast path) + if _session_cookies_content is not None and len(_session_cookies_content) > 0: + return True + + # Check shared context (other worker may have unlocked) + shared_content = _get_shared_cookies() + if shared_content: + # Copy to local for this worker + _session_cookies_content = bytearray(shared_content) + return True + + return False + + +def _get_secure_temp_dir() -> Optional[str]: + """ + Get the most secure temporary directory available. + + Prefers /dev/shm (RAM-based) over /tmp (disk-based) to prevent + decrypted cookies from ever touching persistent storage. + + Returns: + Path to /dev/shm if available and writable, None otherwise + (None causes tempfile to use system default). + """ + shm_path = pathlib.Path('/dev/shm') + if shm_path.is_dir() and os.access(shm_path, os.W_OK): + return str(shm_path) + # Fall back to system default (typically /tmp) + return None + + +@contextmanager +def cookies_for_download(): + """ + Context manager providing a unique temp file for one download. + + Writes in-memory cookies to a unique temp file, yields the path for yt-dlp, + then securely deletes the temp file. + + Uses /dev/shm (RAM-based tmpfs) when available to prevent cookies from + ever touching persistent storage. Falls back to system temp directory. + + Usage: + with cookies_for_download() as cookies_path: + cmd = (*cmd, '--cookies', str(cookies_path)) + await run_download(cmd) + # Temp file is securely deleted here + + Yields: + pathlib.Path: Path to temporary cookies file + + Raises: + RuntimeError: If cookies are not unlocked + """ + if not cookies_unlocked(): + raise RuntimeError('Cookies not unlocked') + + # Create unique temp file, prefer /dev/shm (RAM) over /tmp (disk) + # Use opaque prefix to avoid revealing file purpose + fd, temp_path = tempfile.mkstemp( + suffix='.tmp', + prefix='w_', + dir=_get_secure_temp_dir() + ) + temp_file = pathlib.Path(temp_path) + logger.trace(f'Created temp cookies file at {temp_path}') + + try: + # Set restrictive permissions + os.chmod(temp_path, 0o600) + + # Write cookies content (decode bytearray to string) + with os.fdopen(fd, 'w') as f: + f.write(_session_cookies_content.decode('utf-8')) + + yield temp_file + finally: + # Securely delete temp file + if temp_file.exists(): + try: + size = temp_file.stat().st_size + temp_file.write_bytes(b'\x00' * size) + temp_file.unlink() + except Exception as e: + logger.warning(f'Failed to securely delete temp cookies file: {e}') + # Try to delete anyway + try: + temp_file.unlink() + except Exception: + pass + + +def get_cookies_status() -> dict: + """ + Get the current status of cookies. + + Returns: + Dict with keys: + - cookies_exist: bool - Whether encrypted file exists + - cookies_unlocked: bool - Whether cookies are decrypted in memory + """ + return { + 'cookies_exist': cookies_exist(), + 'cookies_unlocked': cookies_unlocked(), + } diff --git a/modules/videos/downloader.py b/modules/videos/downloader.py index 04e63260..892912de 100755 --- a/modules/videos/downloader.py +++ b/modules/videos/downloader.py @@ -12,7 +12,6 @@ from typing import Tuple, List, Dict, Optional from urllib.parse import urlparse, parse_qs import cachetools -import requests import yt_dlp.utils from cachetools.keys import hashkey from sqlalchemy.orm import Session @@ -21,20 +20,22 @@ from yt_dlp.extractor import YoutubeTabIE # noqa from wrolpi.cmd import YT_DLP_BIN from wrolpi.common import logger, get_media_directory, escape_file_name, resolve_generators, background_task, \ - trim_file_name, cached_multiprocessing_result, get_absolute_media_path + trim_file_name, cached_multiprocessing_result, get_absolute_media_path, aiohttp_post from wrolpi.dates import now from wrolpi.db import get_db_session from wrolpi.downloader import Downloader, Download, DownloadResult from wrolpi.errors import UnrecoverableDownloadError from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix from wrolpi.files.models import FileGroup +from wrolpi.files.worker import file_worker from wrolpi.vars import PYTEST, YTDLP_CACHE_DIR from .channel.lib import create_channel, get_channel from .common import get_no_channel_directory, update_view_counts_and_censored, \ ffmpeg_video_complete from .errors import UnknownChannel -from .lib import get_videos_downloader_config, YDL, ydl_logger, format_videos_destination, browser_profile_to_yt_dlp_arg, \ - browser_profile_to_yt_dlp_tuple +from .cookies import cookies_unlocked, cookies_for_download +from .lib import get_videos_downloader_config, YDL, ydl_logger, format_videos_destination, get_yt_dlp_http_headers, \ + get_yt_dlp_sleep_opts from .models import Video, Channel from .normalize_video_url import normalize_video_url from .schema import ChannelPostRequest @@ -120,7 +121,7 @@ def get_youtube_video_id(url: str) -> Optional[str]: return None -def get_youtube_duration(video_url: str) -> Optional[int]: +async def get_youtube_duration(video_url: str) -> Optional[int]: """Get video duration using YouTube's internal API. Returns None if URL is not YouTube or API fails.""" video_id = get_youtube_video_id(video_url) if not video_id: @@ -138,68 +139,71 @@ def get_youtube_duration(video_url: str) -> Optional[int]: } try: - response = requests.post( - "https://www.youtube.com/youtubei/v1/player", - json=payload, - timeout=10 - ) - response.raise_for_status() - data = response.json() - length_seconds = data.get("videoDetails", {}).get("lengthSeconds") - if length_seconds is not None: - return int(length_seconds) - else: - # Log why we couldn't get duration - status = data.get("playabilityStatus", {}).get("status", "UNKNOWN") - reason = data.get("playabilityStatus", {}).get("reason", "") - logger.warning(f'YouTube API returned no duration for {video_url}: status={status} reason={reason}') + async with aiohttp_post("https://www.youtube.com/youtubei/v1/player", payload, timeout=10) as response: + response.raise_for_status() + data = await response.json() + length_seconds = data.get("videoDetails", {}).get("lengthSeconds") + if length_seconds is not None: + return int(length_seconds) + else: + # Log why we couldn't get duration + status = data.get("playabilityStatus", {}).get("status", "UNKNOWN") + reason = data.get("playabilityStatus", {}).get("reason", "") + logger.warning(f'YouTube API returned no duration for {video_url}: status={status} reason={reason}') except Exception as e: logger.debug(f'YouTube API request failed for {video_url}: {e}') return None -def extract_info_key(url: str, ydl: YoutubeDL = YDL, process: bool = False, - browser_profile: pathlib.Path = None): - # Include browser_profile presence in cache key (not the path itself, just whether it's used) - return hashkey(url, process=process, use_browser_profile=browser_profile is not None) +def extract_info_key(url: str, ydl: YoutubeDL = YDL, process: bool = False): + return hashkey(url, process=process) extract_info_cache = cachetools.TTLCache(maxsize=1_000, ttl=timedelta(minutes=5).total_seconds()) -def get_browser_profile_from_config() -> Optional[pathlib.Path]: - """Get browser profile path if configured and always_use_browser_profile is enabled.""" - config = get_videos_downloader_config() - if config.browser_profile and config.always_use_browser_profile: - profile = pathlib.Path(config.browser_profile) - if profile.exists(): - return profile - return None - - # Cache results for each URL for a few minutes. @cachetools.cached(cache=extract_info_cache, key=extract_info_key) -def extract_info(url: str, ydl: YoutubeDL = YDL, process: bool = False, - browser_profile: pathlib.Path = None) -> dict: +def extract_info(url: str, ydl: YoutubeDL = YDL, process: bool = False) -> dict: """Get info about a video, channel, or playlist. Separated for testing.""" if PYTEST: raise RuntimeError(f'Refusing to download {url} during testing! {ydl}') - if browser_profile and browser_profile.exists(): - # Create a new YDL instance with browser profile, preserving custom ydl options if provided - ydl_opts = dict( - cachedir=YTDLP_CACHE_DIR, - cookiesfrombrowser=browser_profile_to_yt_dlp_tuple(browser_profile), - ) - # If a custom ydl was passed, copy its relevant options for format selection and output - if ydl != YDL: - for key in ['outtmpl', 'format', 'merge_output_format']: - if key in ydl.params: - ydl_opts[key] = ydl.params[key] - ydl = YoutubeDL(ydl_opts) - ydl.params['logger'] = logger.getChild('youtube-dl') - ydl.add_default_info_extractors() + if cookies_unlocked(): + logger.info(f'Using encrypted cookies for extract_info: {url}') + with cookies_for_download() as cookies_path: + ydl_opts = dict( + cachedir=YTDLP_CACHE_DIR, + cookiefile=str(cookies_path), + **get_yt_dlp_sleep_opts(), + ) + http_headers = get_yt_dlp_http_headers() + if http_headers: + ydl_opts['http_headers'] = http_headers + # If a custom ydl was passed, copy its relevant options for format selection and output + if ydl != YDL: + for key in ['outtmpl', 'format', 'merge_output_format']: + if key in ydl.params: + ydl_opts[key] = ydl.params[key] + ydl_with_cookies = YoutubeDL(ydl_opts) + ydl_with_cookies.params['logger'] = logger.getChild('youtube-dl') + ydl_with_cookies.add_default_info_extractors() + return ydl_with_cookies.extract_info(url, download=False, process=process) + + logger.info(f'No cookies available for extract_info: {url}') + # Create a new YDL instance with sleep options + ydl_opts = dict( + cachedir=YTDLP_CACHE_DIR, + **get_yt_dlp_sleep_opts(), + ) + if ydl != YDL: + for key in ['outtmpl', 'format', 'merge_output_format']: + if key in ydl.params: + ydl_opts[key] = ydl.params[key] + ydl = YoutubeDL(ydl_opts) + ydl.params['logger'] = logger.getChild('youtube-dl') + ydl.add_default_info_extractors() return ydl.extract_info(url, download=False, process=process) @@ -288,14 +292,14 @@ async def fetch_video_duration(url: str) -> int: return duration # Try YouTube API first (faster than yt-dlp) - duration = get_youtube_duration(url) + duration = await get_youtube_duration(url) if duration is not None: logger.info(f'Fetched video duration of {duration} from {url} using YouTube API') return duration # Fall back to yt-dlp for non-YouTube URLs or API failures logger.debug(f'Fetching video duration from {url} using yt-dlp') - info = extract_info(url, process=False, browser_profile=get_browser_profile_from_config()) + info = extract_info(url, process=False) duration = info['duration'] logger.info(f'Fetched video duration of {duration} from {url}') return duration @@ -317,7 +321,7 @@ class ChannelDownloader(Downloader, ABC): async def do_download(self, download: Download) -> DownloadResult: """Update a Channel's catalog, then schedule downloads of every missing video.""" - info = extract_info(download.url, process=False, browser_profile=get_browser_profile_from_config()) + info = extract_info(download.url, process=False) # Resolve the "entries" generator. info: dict = resolve_generators(info) entries = info.get('entries') @@ -402,8 +406,9 @@ class ChannelDownloader(Downloader, ABC): with get_db_session() as session: channel = get_channel(session, channel_id=channel_id, return_dict=False) if not channel.videos or not channel.refreshed: - logger.warning(f'Refreshing videos in {channel.directory} because {channel} has no video records!') - channel.refresh_files(channel.id, send_events=False) + logger.warning(f'Refreshing videos in {channel.directory} for channel {channel}') + job_id = channel.refresh_files(channel.id, send_events=False) + await file_worker.wait_for_job(job_id) # Wait for files to be indexed session.refresh(channel) @staticmethod @@ -511,8 +516,7 @@ class VideoDownloader(Downloader, ABC): location = video_.location if video_ else None try: - download.info_json = download.info_json or extract_info( - url, browser_profile=get_browser_profile_from_config()) + download.info_json = download.info_json or extract_info(url) except yt_dlp.utils.DownloadError as e: # Video may be private. try: @@ -592,24 +596,23 @@ class VideoDownloader(Downloader, ABC): cmd = (*cmd, '--write-info-json') if config.yt_dlp_extra_args: cmd = (*cmd, *config.yt_dlp_extra_args.split(' ')) - if config.browser_profile and ( - (i := settings.get('use_browser_profile')) or (config.always_use_browser_profile and i != False)): - # Use the browser profile to get cookies, but only if "always_use_browser_profile" is set and - # "use_browser_profile" is not False, or if "use_browser_profile" is set. - browser_profile = pathlib.Path(config.browser_profile) - if browser_profile.exists(): - browser_profile = browser_profile_to_yt_dlp_arg(browser_profile) - cmd = (*cmd, '--cookies-from-browser', browser_profile) - else: - logger.error(f'Browser profile {config.browser_profile} does not exist') + if config.sleep_requests > 0: + cmd = (*cmd, '--sleep-requests', str(config.sleep_requests)) - # Add destination and the video's URL to the command. - cmd = (*cmd, - '-o', video_path, - url, - ) - # Do the real download. - result = await self.process_runner(download, cmd, out_dir, debug=True) + if cookies_unlocked(): + # Use encrypted cookies file + logger.info(f'Using encrypted cookies for video download: {url}') + with cookies_for_download() as cookies_path: + cmd = (*cmd, '--cookies', str(cookies_path)) + if config.user_agent: + cmd = (*cmd, '--add-headers', f'User-Agent:{config.user_agent}') + cmd = (*cmd, '-o', video_path, url) + result = await self.process_runner(download, cmd, out_dir, debug=True) + else: + # No cookies available + logger.info(f'No cookies available for video download: {url}') + cmd = (*cmd, '-o', video_path, url) + result = await self.process_runner(download, cmd, out_dir, debug=True) stdout = result.stdout.decode() stderr = result.stderr.decode() @@ -838,8 +841,7 @@ class VideoDownloader(Downloader, ABC): # Get the path where the video will be saved. try: - entry = extract_info(url, ydl=ydl, process=True, - browser_profile=get_browser_profile_from_config()) + entry = extract_info(url, ydl=ydl, process=True) final_filename = pathlib.Path(prepare_filename(entry, ydl=ydl)).absolute() except DownloadError as e: if ' Cannot write ' in str(e): @@ -868,8 +870,7 @@ class VideoDownloader(Downloader, ABC): ydl = YoutubeDL(copy.deepcopy(options)) ydl.params['logger'] = ydl_logger ydl.add_default_info_extractors() - entry = extract_info(url, ydl=ydl, process=True, - browser_profile=get_browser_profile_from_config()) + entry = extract_info(url, ydl=ydl, process=True) logger.debug(f'Downloading {url} to {repr(str(final_filename))}') return final_filename, entry @@ -897,8 +898,7 @@ class VideoDownloader(Downloader, ABC): # Download video info json directly using yt-dlp. try: - browser_profile = get_browser_profile_from_config() - info_json = download_video_info_json(url, browser_profile=browser_profile) + info_json = download_video_info_json(url) except Exception as e: logger.error('Failed to download video info json', exc_info=e) return DownloadResult(success=False, error='Failed to download video info json') @@ -1030,7 +1030,7 @@ def update_channel_catalog(channel: Channel, info: dict): for entry in entries: if entry['title'] == 'Uploads': logger.info('Youtube-DL gave back a list of URLs, found the "Uploads" URL and using it.') - info = extract_info(entry['url'], browser_profile=get_browser_profile_from_config()) + info = extract_info(entry['url']) break with get_db_session(commit=True) as session: diff --git a/modules/videos/lib.py b/modules/videos/lib.py index a55ea2b4..5ed0be21 100644 --- a/modules/videos/lib.py +++ b/modules/videos/lib.py @@ -24,10 +24,11 @@ from wrolpi.errors import UnknownDirectory from wrolpi.events import Events from wrolpi.files.lib import split_path_stem_and_suffix from wrolpi.switches import register_switch_handler, ActivateSwitchMethod -from wrolpi.vars import YTDLP_CACHE_DIR, PYTEST, WROLPI_HOME +from wrolpi.vars import YTDLP_CACHE_DIR, PYTEST from .common import is_valid_poster, convert_image, \ generate_video_poster, ConfigError, \ extract_video_duration, ffprobe_json_sync, read_ffprobe_json_file, write_ffprobe_json_file +from .cookies import cookies_unlocked, cookies_for_download from .errors import UnknownChannel from .models import Channel @@ -37,32 +38,6 @@ DEFAULT_DOWNLOAD_FREQUENCY = Seconds.week REQUIRED_OPTIONS = ['name', 'directory'] -# Browser profile discovery configuration. -# Maps browser identifiers to their config paths and yt-dlp names. -BROWSER_CONFIGS = { - 'brave': { - 'yt_dlp_name': 'brave', - 'config_path': '.config/BraveSoftware/Brave-Browser', - 'profile_key': 'brave_profiles', - }, - 'chrome': { - 'yt_dlp_name': 'chrome', - 'config_path': '.config/google-chrome', - 'profile_key': 'chrome_profiles', - }, - 'chromium': { - 'yt_dlp_name': 'chromium', - 'config_path': '.config/chromium', - 'profile_key': 'chromium_profiles', - }, - 'firefox': { - 'yt_dlp_name': 'firefox', - 'config_path': '.mozilla/firefox', - 'profile_key': 'firefox_profiles', - }, -} - - @dataclasses.dataclass class VideoInfoJSON: channel_source_id: str | None = None @@ -531,9 +506,9 @@ class VideoDownloaderConfigValidator: version: int = None yt_dlp_options: VideoDownloaderConfigYtDlpOptionsValidator = field(default_factory=dict) yt_dlp_extra_args: str = '' - always_use_browser_profile: bool = False - browser_profile: str = '' download_missing_video_comments: bool = False + user_agent: str = '' + sleep_requests: float = 0.75 def __post_init__(self): allowed_fields = {i.name for i in dataclasses.fields(VideoDownloaderConfigYtDlpOptionsValidator)} @@ -560,9 +535,9 @@ class VideoDownloaderConfig(ConfigFile): youtube_include_dash_manifest=False, ), yt_dlp_extra_args='', - always_use_browser_profile=False, - browser_profile='', download_missing_video_comments=False, + user_agent='', + sleep_requests=0.75, ) validator = VideoDownloaderConfigValidator @@ -630,22 +605,6 @@ class VideoDownloaderConfig(ConfigFile): def yt_dlp_extra_args(self, value: str): self.update({**self._config, 'yt_dlp_extra_args': value}) - @property - def browser_profile(self) -> str: - return self._config['browser_profile'] - - @browser_profile.setter - def browser_profile(self, value: str): - self.update({**self._config, 'browser_profile': value}) - - @property - def always_use_browser_profile(self) -> bool: - return self._config['always_use_browser_profile'] - - @always_use_browser_profile.setter - def always_use_browser_profile(self, value: bool): - self.update({**self._config, 'always_use_browser_profile': value}) - @property def download_missing_video_comments(self) -> bool: return self._config['download_missing_video_comments'] @@ -654,6 +613,22 @@ class VideoDownloaderConfig(ConfigFile): def download_missing_video_comments(self, value: bool): self.update({**self._config, 'download_missing_video_comments': value}) + @property + def user_agent(self) -> str: + return self._config.get('user_agent', '') + + @user_agent.setter + def user_agent(self, value: str): + self.update({**self._config, 'user_agent': value}) + + @property + def sleep_requests(self) -> float: + return self._config.get('sleep_requests', 0.75) + + @sleep_requests.setter + def sleep_requests(self, value: float): + self.update({**self._config, 'sleep_requests': value}) + def import_config(self, file: pathlib.Path = None, send_events=False): super().import_config(file, send_events) self.successful_import = True @@ -677,6 +652,28 @@ def set_test_downloader_config(enabled: bool): TEST_VIDEOS_DOWNLOADER_CONFIG = VideoDownloaderConfig() if enabled else None +def get_yt_dlp_http_headers() -> dict: + """Get HTTP headers for yt-dlp, including user-agent if configured. + + This should be used when cookies are being used to ensure the user-agent + matches the browser that exported the cookies.""" + config = get_videos_downloader_config() + if config.user_agent: + return {'User-Agent': config.user_agent} + return {} + + +def get_yt_dlp_sleep_opts() -> dict: + """Get sleep options for yt-dlp to avoid rate limiting. + + This adds a delay between HTTP requests during metadata extraction, + helping avoid bot detection. Does not affect video file download speed.""" + config = get_videos_downloader_config() + if config.sleep_requests > 0: + return {'sleep_requests': config.sleep_requests} + return {} + + def get_channels_config_from_db(session: Session) -> dict: """Create a dictionary that contains all the Channels from the DB.""" from wrolpi.collections import Collection @@ -712,13 +709,7 @@ async def fetch_channel_source_id(channel_id: int): from modules.videos.channel.lib import get_channel channel = Channel.find_by_id(session, channel_id) - # Get browser profile from config - config = get_videos_downloader_config() - browser_profile = None - if config.browser_profile and config.always_use_browser_profile: - browser_profile = pathlib.Path(config.browser_profile) - - channel.source_id = channel.source_id or get_channel_source_id(channel.url, browser_profile=browser_profile) + channel.source_id = channel.source_id or get_channel_source_id(channel.url) if not channel.source_id: channel_import_logger.warning(f'Unable to fetch source_id for {channel.url}') else: @@ -808,17 +799,33 @@ ydl_logger = YDL.params['logger'] = logger.getChild('youtube-dl') YDL.add_default_info_extractors() -def get_channel_source_id(url: str, browser_profile: pathlib.Path = None) -> str: +def get_channel_source_id(url: str) -> str: """Get the source ID for a channel URL.""" - ydl = YDL - if browser_profile and browser_profile.exists(): - ydl_opts = dict( - cachedir=YTDLP_CACHE_DIR, - cookiesfrombrowser=browser_profile_to_yt_dlp_tuple(browser_profile), - ) - ydl = YoutubeDL(ydl_opts) - ydl.params['logger'] = logger.getChild('youtube-dl') - ydl.add_default_info_extractors() + if cookies_unlocked(): + logger.info(f'Using encrypted cookies for channel source id: {url}') + with cookies_for_download() as cookies_path: + ydl_opts = dict( + cachedir=YTDLP_CACHE_DIR, + cookiefile=str(cookies_path), + **get_yt_dlp_sleep_opts(), + ) + http_headers = get_yt_dlp_http_headers() + if http_headers: + ydl_opts['http_headers'] = http_headers + ydl = YoutubeDL(ydl_opts) + ydl.params['logger'] = logger.getChild('youtube-dl') + ydl.add_default_info_extractors() + channel_info = ydl.extract_info(url, download=False, process=False) + return channel_info.get('channel_id') or channel_info['uploader_id'] + + logger.info(f'No cookies available for channel source id: {url}') + ydl_opts = dict( + cachedir=YTDLP_CACHE_DIR, + **get_yt_dlp_sleep_opts(), + ) + ydl = YoutubeDL(ydl_opts) + ydl.params['logger'] = logger.getChild('youtube-dl') + ydl.add_default_info_extractors() channel_info = ydl.extract_info(url, download=False, process=False) return channel_info.get('channel_id') or channel_info['uploader_id'] @@ -1056,85 +1063,6 @@ def format_videos_destination(channel_name: str = None, channel_tag: str = None, return videos_destination -def _discover_chromium_profiles(browser_dir: pathlib.Path, profile_list: list): - """Discover profiles for Chromium-based browsers (Chromium, Chrome, Brave).""" - if not browser_dir.is_dir(): - return - default_profile = browser_dir / 'Default' - if default_profile.is_dir(): - profile_list.append(default_profile) - for profile in browser_dir.glob('Profile *'): - if profile.is_dir(): - profile_list.append(profile) - - -def _discover_firefox_profiles(browser_dir: pathlib.Path, profile_list: list): - """Discover profiles for Firefox using profiles.ini.""" - profiles_file = browser_dir / 'profiles.ini' - if not profiles_file.is_file(): - return - profiles_content = profiles_file.read_text() - default_profiles = re.findall(r'Default=(.*)', profiles_content) - for profile_path in default_profiles: - full_path = browser_dir / profile_path - if full_path.is_dir(): - profile_list.append(full_path) - - -def get_browser_profiles(home: pathlib.Path = WROLPI_HOME) -> dict: - """Searches the provided home directory for browser profiles from all supported browsers.""" - logger.debug(f'Searching for browser profiles in {home}') - - profiles = {config['profile_key']: [] for config in BROWSER_CONFIGS.values()} - - for browser_key, config in BROWSER_CONFIGS.items(): - browser_dir = home / config['config_path'] - if browser_key == 'firefox': - _discover_firefox_profiles(browser_dir, profiles[config['profile_key']]) - else: - _discover_chromium_profiles(browser_dir, profiles[config['profile_key']]) - - return profiles - - -def browser_profile_to_yt_dlp_arg(profile: pathlib.Path) -> str: - """Takes a Path and returns a string that can be used as a yt-dlp `--cookies-from-browser` argument. - - Format: BROWSER+KEYRING:PROFILE - - We explicitly specify GNOMEKEYRING because yt-dlp's auto-detection relies on desktop environment - variables which are not available when running as a systemd service. - """ - profile_str = str(profile) - - for browser_key, config in BROWSER_CONFIGS.items(): - if config['config_path'] in profile_str: - return f"{config['yt_dlp_name']}+GNOMEKEYRING:{profile.name}" - - # Fallback to original behavior for unknown browsers - *_, browser, profile_name = profile_str.split('/') - return f'{browser}+GNOMEKEYRING:{profile_name}' - - -def browser_profile_to_yt_dlp_tuple(profile: pathlib.Path) -> tuple: - """Takes a Path and returns a tuple that can be used as yt-dlp `cookiesfrombrowser` option in Python API. - - The yt-dlp Python API expects cookiesfrombrowser as a tuple: (browser, profile, keyring, container) - - We explicitly specify GNOMEKEYRING because yt-dlp's auto-detection relies on desktop environment - variables which are not available when running as a systemd service. - """ - profile_str = str(profile) - - for browser_key, config in BROWSER_CONFIGS.items(): - if config['config_path'] in profile_str: - return (config['yt_dlp_name'], profile.name, 'GNOMEKEYRING', None) - - # Fallback for unknown browsers - *_, browser, profile_name = profile_str.split('/') - return (browser, profile_name, 'GNOMEKEYRING', None) - - def format_video_filename( video: Video, file_name_format: str = None, diff --git a/modules/videos/models.py b/modules/videos/models.py index e352f143..b5130284 100644 --- a/modules/videos/models.py +++ b/modules/videos/models.py @@ -965,16 +965,19 @@ class Channel(ModelHelper, Base): return self.tag @classmethod - def refresh_files(cls, id_: int, send_events: bool = True): - """Refresh all files within this Channel's directory. Mark this channel as refreshed.""" + def refresh_files(cls, id_: int, send_events: bool = True) -> str: + """Refresh all files within this Channel's directory. Returns job_id for awaiting. + + The channel is marked as refreshed after the background task completes post-processing.""" # Get this Channel's info for later. Refresh may take a long time. with get_db_session() as session: directory = cls.find_by_id(session, id_).directory - # Perform info_json in background task. Channel will be marked as refreshed after this completes. + # Queue refresh immediately so caller can await the job. + job_id = file_worker.queue_refresh([directory]) + + # Background task handles post-processing after job completes. async def _(): - # Refresh all files within this channel's directory first. - job_id = file_worker.queue_refresh([directory]) await file_worker.wait_for_job(job_id) # Update view count second. from modules.videos.common import update_view_counts_and_censored @@ -984,6 +987,7 @@ class Channel(ModelHelper, Base): channel_.refreshed = True background_task(_()) + return job_id @staticmethod def get_by_id(session: Session, id_: int) -> Optional['Channel']: diff --git a/modules/videos/schema.py b/modules/videos/schema.py index daefd381..d46ffd77 100644 --- a/modules/videos/schema.py +++ b/modules/videos/schema.py @@ -246,3 +246,33 @@ class ChannelSearchRequest: @dataclass class VideoFileFormatRequest: video_file_format: str + + +@dataclass +class CookiesUploadRequest: + """Request to upload and encrypt cookies.""" + cookies_content: str + password: str + + def __post_init__(self): + if not self.cookies_content: + raise ValidationError('cookies_content cannot be empty') + if not self.password or len(self.password) < 8: + raise ValidationError('password must be at least 8 characters') + + +@dataclass +class CookiesUnlockRequest: + """Request to unlock cookies with password.""" + password: str + + def __post_init__(self): + if not self.password: + raise ValidationError('password cannot be empty') + + +@dataclass +class CookiesStatusResponse: + """Response with cookies status.""" + cookies_exist: bool + cookies_unlocked: bool diff --git a/modules/videos/test/test_cookies.py b/modules/videos/test/test_cookies.py new file mode 100644 index 00000000..2a036ebe --- /dev/null +++ b/modules/videos/test/test_cookies.py @@ -0,0 +1,402 @@ +"""Tests for the encrypted cookies module.""" +import os +import pathlib +import tempfile + +import pytest + +from modules.videos import cookies +from modules.videos.cookies import ( + encrypt_cookies, + decrypt_cookies, + validate_cookies_format, + save_encrypted_cookies, + delete_cookies, + cookies_exist, + unlock_cookies, + lock_cookies, + cookies_unlocked, + cookies_for_download, + get_cookies_status, + get_cookies_file_path, + MIN_PASSWORD_LENGTH, +) + + +# Sample valid Netscape format cookies +VALID_COOKIES_CONTENT = """# Netscape HTTP Cookie File +# This is a generated file! Do not edit. + +.youtube.com\tTRUE\t/\tTRUE\t1735689600\tLOGIN_INFO\tABC123 +.youtube.com\tTRUE\t/\tFALSE\t0\tSID\txyz789 +.google.com\tTRUE\t/\tTRUE\t1735689600\tNID\tdef456 +""" + +VALID_COOKIES_SIMPLE = """.example.com\tTRUE\t/\tFALSE\t0\tsession_id\tabc123""" + + +class TestEncryptDecrypt: + """Tests for basic encryption and decryption.""" + + def test_encrypt_decrypt_roundtrip(self): + """Content can be encrypted and decrypted back to original.""" + password = 'testpassword123' + content = VALID_COOKIES_CONTENT + + encrypted = encrypt_cookies(content, password) + decrypted = decrypt_cookies(encrypted, password) + + assert decrypted == content + + def test_encrypt_produces_different_output_each_time(self): + """Each encryption uses a unique salt, producing different ciphertext.""" + password = 'testpassword123' + content = VALID_COOKIES_CONTENT + + encrypted1 = encrypt_cookies(content, password) + encrypted2 = encrypt_cookies(content, password) + + assert encrypted1 != encrypted2 + + def test_password_too_short(self): + """Password must be at least MIN_PASSWORD_LENGTH characters.""" + short_password = 'a' * (MIN_PASSWORD_LENGTH - 1) + content = VALID_COOKIES_CONTENT + + with pytest.raises(ValueError, match='at least'): + encrypt_cookies(content, short_password) + + def test_wrong_password_fails(self): + """Decryption with wrong password raises ValueError.""" + password = 'testpassword123' + wrong_password = 'wrongpassword456' + content = VALID_COOKIES_CONTENT + + encrypted = encrypt_cookies(content, password) + + with pytest.raises(ValueError, match='Invalid password'): + decrypt_cookies(encrypted, wrong_password) + + def test_corrupted_data_fails(self): + """Decryption of corrupted data raises ValueError.""" + password = 'testpassword123' + + # Random bytes that aren't valid encrypted data + corrupted = os.urandom(100) + + with pytest.raises(ValueError): + decrypt_cookies(corrupted, password) + + def test_truncated_data_fails(self): + """Decryption of truncated data raises ValueError.""" + password = 'testpassword123' + + # Data too short to contain salt + truncated = b'short' + + with pytest.raises(ValueError, match='too short'): + decrypt_cookies(truncated, password) + + +class TestValidateCookiesFormat: + """Tests for cookies format validation.""" + + def test_valid_netscape_format(self): + """Valid Netscape format cookies pass validation.""" + is_valid, error = validate_cookies_format(VALID_COOKIES_CONTENT) + assert is_valid is True + assert error is None + + def test_valid_simple_format(self): + """Simple single-line cookies pass validation.""" + is_valid, error = validate_cookies_format(VALID_COOKIES_SIMPLE) + assert is_valid is True + assert error is None + + def test_empty_content_fails(self): + """Empty content fails validation.""" + is_valid, error = validate_cookies_format('') + assert is_valid is False + assert 'empty' in error.lower() + + def test_whitespace_only_fails(self): + """Whitespace-only content fails validation.""" + is_valid, error = validate_cookies_format(' \n\t \n ') + assert is_valid is False + assert 'empty' in error.lower() + + def test_comments_only_fails(self): + """Content with only comments fails validation.""" + content = """# This is a comment +# Another comment +# Netscape HTTP Cookie File +""" + is_valid, error = validate_cookies_format(content) + assert is_valid is False + assert 'No valid cookie lines' in error + + def test_invalid_format_fails(self): + """Content without proper tab-separated format fails.""" + content = """This is not a valid cookies file +Just some random text +""" + is_valid, error = validate_cookies_format(content) + assert is_valid is False + + +class TestSaveAndDelete: + """Tests for saving and deleting encrypted cookies.""" + + def test_save_and_exists(self, test_directory): + """Saving cookies creates the encrypted file.""" + password = 'testpassword123' + + # Initially no cookies exist + assert not cookies_exist() + + # Save cookies + path = save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + assert cookies_exist() + assert path.is_file() + assert path.name == 'cookies.txt.enc' + + def test_save_sets_restrictive_permissions(self, test_directory): + """Saved cookies file has restrictive permissions (owner only).""" + password = 'testpassword123' + + path = save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + # Check file permissions (should be 0o600 - owner read/write only) + mode = path.stat().st_mode & 0o777 + assert mode == 0o600 + + def test_save_invalid_format_fails(self, test_directory): + """Saving invalid cookies format raises ValueError.""" + password = 'testpassword123' + invalid_content = 'not valid cookies format' + + with pytest.raises(ValueError): + save_encrypted_cookies(invalid_content, password) + + def test_delete_removes_file(self, test_directory): + """Delete removes the encrypted cookies file.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + assert cookies_exist() + + result = delete_cookies() + + assert result is True + assert not cookies_exist() + + def test_delete_nonexistent_returns_false(self, test_directory): + """Delete returns False when no file exists.""" + assert not cookies_exist() + + result = delete_cookies() + + assert result is False + + def test_delete_clears_session(self, test_directory): + """Deleting cookies also clears the session.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + # save_encrypted_cookies auto-unlocks, but call unlock_cookies for clarity + unlock_cookies(password) + + assert cookies_unlocked() + + delete_cookies() + + assert not cookies_unlocked() + + def test_save_auto_unlocks(self, test_directory): + """Saving cookies automatically unlocks them (user just provided password).""" + password = 'testpassword123' + + assert not cookies_unlocked() + + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + # Cookies should be auto-unlocked after save + assert cookies_unlocked() + + +class TestUnlockLock: + """Tests for session unlock/lock functionality.""" + + def test_unlock_success(self, test_directory): + """Unlock decrypts cookies to memory.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + # save_encrypted_cookies auto-unlocks, so lock first to test unlock + lock_cookies() + assert not cookies_unlocked() + + unlock_cookies(password) + + assert cookies_unlocked() + + def test_unlock_no_file_fails(self, test_directory): + """Unlock fails when no encrypted file exists.""" + with pytest.raises(FileNotFoundError): + unlock_cookies('anypassword1') + + def test_unlock_wrong_password_fails(self, test_directory): + """Unlock with wrong password raises ValueError.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + with pytest.raises(ValueError, match='Invalid password'): + unlock_cookies('wrongpassword') + + def test_lock_clears_memory(self, test_directory): + """Lock clears decrypted cookies from memory.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + assert cookies_unlocked() + + lock_cookies() + + assert not cookies_unlocked() + + def test_lock_idempotent(self, test_directory): + """Lock can be called multiple times without error.""" + lock_cookies() + lock_cookies() + lock_cookies() + + assert not cookies_unlocked() + + +class TestCookiesForDownload: + """Tests for the per-download temp file context manager.""" + + def test_provides_temp_file(self, test_directory): + """Context manager provides a readable temp file.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + with cookies_for_download() as cookies_path: + assert cookies_path.is_file() + content = cookies_path.read_text() + assert content == VALID_COOKIES_CONTENT + + def test_temp_file_deleted_after(self, test_directory): + """Temp file is deleted after context manager exits.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + with cookies_for_download() as cookies_path: + temp_path = cookies_path # Save reference + + assert not temp_path.exists() + + def test_temp_file_deleted_on_exception(self, test_directory): + """Temp file is deleted even if exception occurs.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + temp_path = None + try: + with cookies_for_download() as cookies_path: + temp_path = cookies_path + raise RuntimeError('Test exception') + except RuntimeError: + pass + + assert temp_path is not None + assert not temp_path.exists() + + def test_fails_when_not_unlocked(self, test_directory): + """Raises RuntimeError when cookies not unlocked.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + # save_encrypted_cookies auto-unlocks, so lock first + lock_cookies() + + with pytest.raises(RuntimeError, match='not unlocked'): + with cookies_for_download(): + pass + + def test_unique_files_for_concurrent_downloads(self, test_directory): + """Each call creates a unique temp file.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + paths = [] + + # Start multiple contexts + with cookies_for_download() as path1: + paths.append(str(path1)) + with cookies_for_download() as path2: + paths.append(str(path2)) + with cookies_for_download() as path3: + paths.append(str(path3)) + + # All paths should be unique + assert len(paths) == len(set(paths)) + + def test_temp_file_has_restrictive_permissions(self, test_directory): + """Temp file has restrictive permissions.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + with cookies_for_download() as cookies_path: + mode = cookies_path.stat().st_mode & 0o777 + assert mode == 0o600 + + +class TestGetCookiesStatus: + """Tests for status reporting.""" + + def test_status_no_cookies(self, test_directory): + """Status shows no cookies when file doesn't exist.""" + status = get_cookies_status() + + assert status['cookies_exist'] is False + assert status['cookies_unlocked'] is False + + def test_status_locked(self, test_directory): + """Status shows locked when cookies exist but not unlocked.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + + # save_encrypted_cookies auto-unlocks, so lock first + lock_cookies() + + status = get_cookies_status() + + assert status['cookies_exist'] is True + assert status['cookies_unlocked'] is False + + def test_status_unlocked(self, test_directory): + """Status shows unlocked when cookies are in memory.""" + password = 'testpassword123' + save_encrypted_cookies(VALID_COOKIES_CONTENT, password) + unlock_cookies(password) + + status = get_cookies_status() + + assert status['cookies_exist'] is True + assert status['cookies_unlocked'] is True + + +# Fixture to reset module state between tests +@pytest.fixture(autouse=True) +def reset_cookies_state(): + """Reset cookies module state before and after each test.""" + lock_cookies() + yield + lock_cookies() diff --git a/modules/videos/test/test_downloader.py b/modules/videos/test/test_downloader.py index 4c128e23..d77c8a8c 100644 --- a/modules/videos/test/test_downloader.py +++ b/modules/videos/test/test_downloader.py @@ -654,64 +654,6 @@ def test_normalize_video_file_names(test_directory, video_download_manager): assert not vtt.exists() -@pytest.mark.asyncio -async def test_video_download_cookies(test_session, test_directory, mock_video_extract_info, await_switches, - video_download_manager, mock_video_process_runner, image_file, - test_videos_downloader_config): - config = get_videos_downloader_config() - - config.browser_profile = str(test_directory / 'firefox/some directory') - (test_directory / 'firefox/some directory').mkdir(parents=True) - - video_path = test_directory / 'a video.mp4' - shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', video_path) - - # Request video download with cookies. - settings = {'use_browser_profile': True} - - url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' - with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename: - mock_video_extract_info.return_value = example_video_json - mock_prepare_filename.return_value = (video_path, {'id': 'foo'}) - - video_download_manager.create_download(test_session, url, video_downloader.name, settings=settings) - await video_download_manager.wait_for_all_downloads() - - download, cmd, out_dir = mock_video_process_runner.call_args[0] - - assert '--cookies-from-browser' in cmd - # Format: BROWSER+KEYRING:PROFILE - assert 'firefox+GNOMEKEYRING:some directory' in cmd - - -@pytest.mark.asyncio -async def test_video_download_always_use_cookies(test_session, test_directory, mock_video_extract_info, await_switches, - video_download_manager, mock_video_process_runner, image_file, - test_videos_downloader_config): - config = get_videos_downloader_config() - - config.always_use_browser_profile = True - config.browser_profile = str(test_directory / 'chromium/some directory') - (test_directory / 'chromium/some directory').mkdir(parents=True) - - video_path = test_directory / 'a video.mp4' - shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', video_path) - - url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' - with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename: - mock_video_extract_info.return_value = example_video_json - mock_prepare_filename.return_value = (video_path, {'id': 'foo'}) - - video_download_manager.create_download(test_session, url, video_downloader.name) - await video_download_manager.wait_for_all_downloads() - - download, cmd, out_dir = mock_video_process_runner.call_args[0] - - assert '--cookies-from-browser' in cmd - # Format: BROWSER+KEYRING:PROFILE - assert 'chromium+GNOMEKEYRING:some directory' in cmd - - @pytest.mark.asyncio async def test_channel_downloader_sets_collection_id(test_session, channel_factory, mock_video_extract_info, video_download_manager, await_switches): @@ -741,9 +683,10 @@ async def test_channel_downloader_sets_collection_id(test_session, channel_facto } mock_video_extract_info.return_value = mock_info - # Mock Channel.refresh_files to avoid background tasks + # Mock Channel.refresh_files and file_worker.wait_for_job to avoid background tasks with mock.patch('modules.videos.downloader.VideoDownloader.do_download') as mock_video_do_download, \ - mock.patch.object(Channel, 'refresh_files'): + mock.patch.object(Channel, 'refresh_files', return_value='test-job-id'), \ + mock.patch('modules.videos.downloader.file_worker.wait_for_job', new_callable=mock.AsyncMock): mock_video_do_download.return_value = DownloadResult(success=True) await channel_downloader.do_download(download) diff --git a/modules/videos/test/test_lib.py b/modules/videos/test/test_lib.py index 1828e2b8..6c8ba151 100644 --- a/modules/videos/test/test_lib.py +++ b/modules/videos/test/test_lib.py @@ -369,97 +369,6 @@ async def test_videos_downloader_config_api(async_client, test_directory, test_v assert 'Invalid config' in response.json.get('error') -@pytest.mark.parametrize('file_name,expected', [ - ('/home/wrolpi/.config/chromium/Default', 'chromium+GNOMEKEYRING:Default'), - ('/home/wrolpi/.config/chromium/Profile 1', 'chromium+GNOMEKEYRING:Profile 1'), - ('/home/wrolpi/.mozilla/firefox/29el0wk0.default-release', 'firefox+GNOMEKEYRING:29el0wk0.default-release'), - ('/home/wrolpi/.config/BraveSoftware/Brave-Browser/Default', 'brave+GNOMEKEYRING:Default'), - ('/home/wrolpi/.config/BraveSoftware/Brave-Browser/Profile 1', 'brave+GNOMEKEYRING:Profile 1'), - ('/home/wrolpi/.config/google-chrome/Default', 'chrome+GNOMEKEYRING:Default'), - ('/home/wrolpi/.config/google-chrome/Profile 1', 'chrome+GNOMEKEYRING:Profile 1'), -]) -def test_browser_profile_to_yt_dlp_arg(file_name, expected): - """ - Test the conversion of a browser profile to yt-dlp arguments. - Format: BROWSER+KEYRING:PROFILE - Explicitly uses GNOMEKEYRING because yt-dlp auto-detection doesn't work in systemd services. - """ - file_name = pathlib.Path(file_name) - assert lib.browser_profile_to_yt_dlp_arg(file_name) == expected - - -@pytest.mark.parametrize('file_name,expected', [ - ('/home/wrolpi/.config/chromium/Default', ('chromium', 'Default', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.config/chromium/Profile 1', ('chromium', 'Profile 1', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.mozilla/firefox/29el0wk0.default-release', ('firefox', '29el0wk0.default-release', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.config/BraveSoftware/Brave-Browser/Default', ('brave', 'Default', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.config/BraveSoftware/Brave-Browser/Profile 1', ('brave', 'Profile 1', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.config/google-chrome/Default', ('chrome', 'Default', 'GNOMEKEYRING', None)), - ('/home/wrolpi/.config/google-chrome/Profile 1', ('chrome', 'Profile 1', 'GNOMEKEYRING', None)), -]) -def test_browser_profile_to_yt_dlp_tuple(file_name, expected): - """ - Test the conversion of a browser profile to yt-dlp cookiesfrombrowser tuple. - Explicitly uses GNOMEKEYRING because yt-dlp auto-detection doesn't work in systemd services. - """ - file_name = pathlib.Path(file_name) - assert lib.browser_profile_to_yt_dlp_tuple(file_name) == expected - - -def test_get_browser_profiles(test_directory): - """Test discovery of browser profiles for all supported browsers.""" - # Create a mock home directory with browser profiles - home = test_directory / 'home' - - # Chromium profiles - chromium_dir = home / '.config/chromium' - (chromium_dir / 'Default').mkdir(parents=True) - (chromium_dir / 'Profile 1').mkdir(parents=True) - - # Chrome profiles - chrome_dir = home / '.config/google-chrome' - (chrome_dir / 'Default').mkdir(parents=True) - (chrome_dir / 'Profile 2').mkdir(parents=True) - - # Brave profiles - brave_dir = home / '.config/BraveSoftware/Brave-Browser' - (brave_dir / 'Default').mkdir(parents=True) - - # Firefox profiles - firefox_dir = home / '.mozilla/firefox' - firefox_dir.mkdir(parents=True) - firefox_profile_dir = firefox_dir / 'abc123.default-release' - firefox_profile_dir.mkdir() - profiles_ini = firefox_dir / 'profiles.ini' - profiles_ini.write_text('[Profile0]\nDefault=abc123.default-release\n') - - profiles = lib.get_browser_profiles(home) - - # Verify all browser profile keys exist - assert 'chromium_profiles' in profiles - assert 'chrome_profiles' in profiles - assert 'brave_profiles' in profiles - assert 'firefox_profiles' in profiles - - # Verify Chromium profiles discovered - chromium_names = [p.name for p in profiles['chromium_profiles']] - assert 'Default' in chromium_names - assert 'Profile 1' in chromium_names - - # Verify Chrome profiles discovered - chrome_names = [p.name for p in profiles['chrome_profiles']] - assert 'Default' in chrome_names - assert 'Profile 2' in chrome_names - - # Verify Brave profiles discovered - brave_names = [p.name for p in profiles['brave_profiles']] - assert 'Default' in brave_names - - # Verify Firefox profiles discovered - firefox_names = [p.name for p in profiles['firefox_profiles']] - assert 'abc123.default-release' in firefox_names - - def test_video_location(test_session, video_factory, channel_factory, async_client): # Video location without a channel, it opens the preview. video1 = video_factory(title='vid1') diff --git a/modules/videos/video/lib.py b/modules/videos/video/lib.py index bcc1a35a..ddd37dff 100644 --- a/modules/videos/video/lib.py +++ b/modules/videos/video/lib.py @@ -1,5 +1,4 @@ import asyncio -import pathlib import random from datetime import timedelta from typing import Tuple, Optional, List @@ -17,7 +16,9 @@ from wrolpi.files.lib import handle_file_group_search_results from wrolpi.files.models import FileGroup from wrolpi.tags import tag_append_sub_select_where from wrolpi.vars import VIDEO_COMMENTS_FETCH_COUNT, YTDLP_CACHE_DIR +from ..cookies import cookies_unlocked, cookies_for_download from ..errors import UnknownVideo +from ..lib import get_yt_dlp_http_headers, get_yt_dlp_sleep_opts logger.getChild(__name__) @@ -174,26 +175,33 @@ def delete_videos(session: Session, *video_ids: int): session.commit() -def download_video_info_json(url: str, browser_profile: 'pathlib.Path' = None) -> dict: - """Download video info JSON, optionally using browser cookies for authentication. - - Args: - url: The video URL to fetch info for. - browser_profile: Optional path to browser profile for cookie-based authentication. - """ +def download_video_info_json(url: str) -> dict: + """Download video info JSON, using encrypted cookies for authentication if available.""" ydl_opts = dict( getcomments=True, skip_download=True, extractor_args={'youtube': {'max_comments': ['all', '20', 'all', '10'], 'comment_sort': ['top']}}, cachedir=YTDLP_CACHE_DIR, + **get_yt_dlp_sleep_opts(), ) - if browser_profile and browser_profile.exists(): - from modules.videos.lib import browser_profile_to_yt_dlp_tuple - ydl_opts['cookiesfrombrowser'] = browser_profile_to_yt_dlp_tuple(browser_profile) - ydl_logger = logger.getChild('youtube-dl') + if cookies_unlocked(): + logger.info(f'Using encrypted cookies for video info: {url}') + with cookies_for_download() as cookies_path: + ydl_opts['cookiefile'] = str(cookies_path) + http_headers = get_yt_dlp_http_headers() + if http_headers: + ydl_opts['http_headers'] = http_headers + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + ydl.params['logger'] = ydl_logger + info = ydl.extract_info(url, download=False) + ydl.sanitize_info(info) + return info + + logger.info(f'No cookies available for video info: {url}') + with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.params['logger'] = ydl_logger info = ydl.extract_info(url, download=False) @@ -206,15 +214,8 @@ def download_video_info_json(url: str, browser_profile: 'pathlib.Path' = None) - async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT): """ Fetches Video info json for videos without comments, if comments are found then the info json file is replaced. - Uses browser profile for authentication if configured. + Uses encrypted cookies for authentication if available. """ - from modules.videos.lib import get_videos_downloader_config - - config = get_videos_downloader_config() - browser_profile = None - if config.browser_profile and config.always_use_browser_profile: - browser_profile = pathlib.Path(config.browser_profile) - one_month_ago = now() - timedelta(days=30) # Get any videos over a month old that do not have comments. @@ -281,7 +282,7 @@ async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT): try: # Get info json about the video. - info = download_video_info_json(url, browser_profile=browser_profile) + info = download_video_info_json(url) if not info or not isinstance(info.get('comments'), list): logger.error(f'Unable to get comments for video: {url=}') diff --git a/requirements.txt b/requirements.txt index 8b8d732b..215e60be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,6 +6,7 @@ aiohttp==3.13.3 alembic==1.10.4 beautifulsoup4==4.12.3 cachetools==5.5.0 +cryptography==45.0.3 ebooklib==0.18 feedparser==6.0.11 jc==1.25.3 @@ -31,4 +32,4 @@ srt==3.5.3 tqdm==4.67.1 vininfo[cli]==1.8.0 webvtt-py==0.5.1 -yt-dlp[default,curl-cffi]==2026.02.04 +yt-dlp[default,curl-cffi]==2026.02.21 diff --git a/wrolpi/common.py b/wrolpi/common.py index 1d188434..ec920b54 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -723,6 +723,7 @@ class WROLPiConfigValidator: check_for_upgrades: bool = None download_on_startup: bool = None download_timeout: int = None + download_wait: int = None hotspot_device: str = None hotspot_on_startup: bool = None hotspot_password: str = None @@ -862,6 +863,7 @@ class WROLPiConfig(ConfigFile): archive_destination='archive/%(domain_tag)s/%(domain)s', download_on_startup=True, download_timeout=0, + download_wait=60, hotspot_device='wlan0', hotspot_on_startup=True, hotspot_password='wrolpi hotspot', @@ -940,6 +942,14 @@ class WROLPiConfig(ConfigFile): def download_timeout(self, value: int): self.update({'download_timeout': value}) + @property + def download_wait(self) -> int: + return self._config.get('download_wait', 60) + + @download_wait.setter + def download_wait(self, value: int): + self.update({'download_wait': value}) + @property def hotspot_device(self) -> str: return self._config['hotspot_device'] diff --git a/wrolpi/conftest.py b/wrolpi/conftest.py index 9a704301..f205ec5c 100644 --- a/wrolpi/conftest.py +++ b/wrolpi/conftest.py @@ -36,7 +36,8 @@ import wrolpi.root_api # noqa from wrolpi import flags from wrolpi.api_utils import api_app from wrolpi.cmd import CommandResult -from wrolpi.common import iterify, log_level_context, enable_wrol_mode, disable_wrol_mode, timer, TRACE_LEVEL +from wrolpi.common import iterify, log_level_context, enable_wrol_mode, disable_wrol_mode, timer, TRACE_LEVEL, \ + get_wrolpi_config from wrolpi.common import logger, await_background_tasks as await_background_tasks_, BACKGROUND_TASKS from wrolpi.common import set_test_media_directory, Base, set_test_config from wrolpi.contexts import attach_shared_contexts, initialize_configs_contexts @@ -315,6 +316,9 @@ async def test_download_manager( manager = DownloadManager() await manager.enable() + # Disable per-domain rate limiting during tests to avoid timeouts. + get_wrolpi_config().download_wait = 0 + yield manager manager.stop() diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py index 7af8350f..4901a2d8 100644 --- a/wrolpi/contexts.py +++ b/wrolpi/contexts.py @@ -37,9 +37,15 @@ def attach_shared_contexts(app: Sanic): app.shared_ctx.status = manager.dict() app.shared_ctx.map_importing = manager.dict() app.shared_ctx.cache = manager.dict() + # Secure cookies shared storage + app.shared_ctx.secure_cookies = manager.dict() + app.shared_ctx.secure_cookies_lock = multiprocessing.Lock() # Shared ints app.shared_ctx.log_level = multiprocessing.Value(ctypes.c_int, LOG_LEVEL_INT) + # Download timing for per-domain rate limiting + app.shared_ctx.domain_last_download = manager.dict() + # Download Manager app.shared_ctx.download_manager_data = manager.dict() app.shared_ctx.download_manager_disabled = multiprocessing.Event() @@ -115,9 +121,14 @@ def reset_shared_contexts(app: Sanic): )) app.shared_ctx.map_importing.clear() app.shared_ctx.cache.clear() + # Secure cookies + app.shared_ctx.secure_cookies.clear() # Shared ints app.shared_ctx.log_level.value = LOG_LEVEL_INT + # Download timing + app.shared_ctx.domain_last_download.clear() + # Download Manager app.shared_ctx.download_manager_data.clear() app.shared_ctx.download_manager_data.update(dict( diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index c8ce7ede..dc38d99c 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -5,7 +5,9 @@ import logging import multiprocessing import os import pathlib +import random import tempfile +import time import traceback import xml.etree.ElementTree as ET from dataclasses import dataclass, field @@ -726,16 +728,40 @@ class DownloadManager: Download.frequency, Download.id)) count = 0 + download_wait = get_wrolpi_config().download_wait + rate_limited_domains = {} # Track domains we've already checked for rate limiting for download in new_downloads: domain = download.domain if domain not in self.processing_domains and len( self.processing_domains) < SIMULTANEOUS_DOWNLOAD_DOMAINS: + # Per-domain rate limiting. + if download_wait and download_wait > 0: + try: + last_completed = api_app.shared_ctx.domain_last_download.get(domain, 0) + if last_completed > 0: + elapsed = time.time() - last_completed + if elapsed < download_wait: + # Track this domain as rate-limited (count pending downloads) + rate_limited_domains[domain] = rate_limited_domains.get(domain, 0) + 1 + continue # Skip this domain, try next + except (AttributeError, RuntimeError): + pass # shared_ctx not initialized + self._add_processing_domain(domain) context = dict(download_id=download.id, download_url=download.url) await api_app.dispatch('wrolpi.download.download', context=context) count += 1 if count: self.log_debug(f'Added {count} downloads to queue.') + # Log rate-limited domains once per dispatch cycle. + for domain, pending_count in rate_limited_domains.items(): + try: + last_completed = api_app.shared_ctx.domain_last_download.get(domain, 0) + elapsed = time.time() - last_completed + remaining = download_wait - elapsed + self.log_debug(f'Rate limiting {domain}: {remaining:.1f}s remaining ({pending_count} pending)') + except (AttributeError, RuntimeError): + pass async def do_downloads(self): """Schedule any downloads that are new. @@ -1284,6 +1310,13 @@ async def signal_download_download(download_id: int, download_url: str): download_manager.unkill_download(download_id) # Save the config now that the Download has finished. save_downloads_config.activate_switch() + + # Record completion time for per-domain rate limiting. + if download_domain: + try: + api_app.shared_ctx.domain_last_download[download_domain] = time.time() + except (AttributeError, RuntimeError): + pass # shared_ctx not initialized except asyncio.CancelledError as e: worker_logger.warning('Canceled!', exc_info=e) return @@ -1577,6 +1610,9 @@ class RSSDownloader(Downloader): # Only download new URLs. with get_db_session() as session: urls = [i for i in urls if i not in [i.url for i in sub_downloader.already_downloaded(session, *urls)]] + # Filter out URLs already in the Download table (pending downloads). + existing_download_urls = {d[0] for d in session.query(Download.url).filter(Download.url.in_(urls))} + urls = [url for url in urls if url not in existing_download_urls] # Remove skipped URLs before duration checks. (Typically done after this by the download worker). urls = [i for i in urls if not download_manager.is_skipped(i)] @@ -1632,6 +1668,8 @@ class RSSDownloader(Downloader): logger.error(f'Failed to fetch duration: {url}', exc_info=e) # Download videos even if we fail to fetch their duration. new_urls.append(url) + # Sleep between fetches to prevent rate limiting. + await asyncio.sleep(random.randint(1, 3)) urls = new_urls if urls_before != urls: logger.info(f'Filtered videos using min/maximum_duration from {len(urls_before)} to {len(urls)}') diff --git a/wrolpi/flags.py b/wrolpi/flags.py index 7e19dfcb..424581ba 100644 --- a/wrolpi/flags.py +++ b/wrolpi/flags.py @@ -128,10 +128,16 @@ global_refresh_active = Flag('global_refresh_active') # The global refresh has been performed. This is False on a fresh instance of WROLPi. refresh_complete = Flag('refresh_complete', store_db=True) +# Cookies flags for yt-dlp. +cookies_exist = Flag('cookies_exist') +cookies_unlocked = Flag('cookies_unlocked') + def get_flags() -> dict: """Return a list of all Flags which are set.""" flags = dict( + cookies_exist=cookies_exist.is_set(), + cookies_unlocked=cookies_unlocked.is_set(), db_up=db_up.is_set(), file_worker_busy=file_worker_busy.is_set(), file_worker_cleanup=file_worker_cleanup.is_set(), @@ -213,6 +219,13 @@ def init_flags(): else: outdated_zims.clear() + # Initialize cookies flags from cookies module state. + from modules.videos.cookies import cookies_exist as check_cookies_exist, cookies_unlocked as check_cookies_unlocked + if check_cookies_exist(): + cookies_exist.set() + if check_cookies_unlocked(): + cookies_unlocked.set() + logger.debug('Initialized flags') diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index a47c7cc8..44ffe54c 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -156,6 +156,7 @@ def get_settings(_: Request): 'download_manager_stopped': download_manager.is_stopped, 'download_on_startup': wrolpi_config.download_on_startup, 'download_timeout': wrolpi_config.download_timeout, + 'download_wait': wrolpi_config.download_wait, 'hotspot_device': wrolpi_config.hotspot_device, 'hotspot_on_startup': wrolpi_config.hotspot_on_startup, 'hotspot_password': wrolpi_config.hotspot_password, diff --git a/wrolpi/schema.py b/wrolpi/schema.py index 5b3948d1..ca4e7986 100644 --- a/wrolpi/schema.py +++ b/wrolpi/schema.py @@ -18,6 +18,7 @@ class SettingsResponse: download_manager_stopped: bool download_on_startup: bool download_timeout: int + download_wait: int hotspot_device: str hotspot_on_startup: bool hotspot_password: str @@ -59,6 +60,7 @@ class SettingsRequest: archive_destination: Optional[str] = None download_on_startup: Optional[bool] = None download_timeout: Optional[int] = None + download_wait: Optional[int] = None hotspot_device: Optional[str] = None hotspot_on_startup: Optional[bool] = None hotspot_password: Optional[str] = None @@ -226,7 +228,6 @@ class DownloadSettings: suffix: Optional[str] = None title_exclude: Optional[str] = None title_include: Optional[str] = None - use_browser_profile: Optional[bool] = False video_count_limit: Optional[int] = None video_format: Optional[str] = None video_resolutions: List[str] = field(default_factory=list) @@ -245,9 +246,6 @@ class DownloadSettings: if not self.download_metadata_only: del self.download_metadata_only - if not self.use_browser_profile: - del self.use_browser_profile - if self.download_order not in (None, 'newest', 'oldest', 'views'): raise ValidationError(f'Download order must be one of newest, oldest, views, or null.') diff --git a/wrolpi/test/test_downloader.py b/wrolpi/test/test_downloader.py index dff7d540..b7aa9c4c 100644 --- a/wrolpi/test/test_downloader.py +++ b/wrolpi/test/test_downloader.py @@ -781,8 +781,9 @@ async def test_batch_api_endpoints(async_client, test_session, test_download_man assert response.status_code == HTTPStatus.OK assert response.json['retried_count'] == 1 test_session.refresh(d1) - # Status may be 'new' or 'pending' depending on whether the download worker picked it up - assert d1.status in ('new', 'pending') + # Status may be 'new', 'pending', or 'complete' depending on whether the download worker + # picked it up and completed before the assertion is checked. + assert d1.status in ('new', 'pending', 'complete') # Test batch clear endpoint body = dict(download_ids=[d2_id])