wrolpi/wrolpi/downloader.py

2090 lines
88 KiB
Python

import asyncio
import contextlib
import inspect
import logging
import multiprocessing
import os
import pathlib
import random
import re
import tempfile
import time
import traceback
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from datetime import timedelta, datetime
from enum import Enum
from http import HTTPStatus
from itertools import filterfalse
from typing import List, Dict, Generator, Iterable, Coroutine, Any
from typing import Tuple, Optional
from urllib.parse import urlparse
from zoneinfo import ZoneInfo
import feedparser
import pytz
from feedparser import FeedParserDict
from sqlalchemy import Column, Integer, String, Text, ForeignKey, ARRAY, Index
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Session, relationship
from sqlalchemy.sql import Delete
from wrolpi import flags
from wrolpi.api_utils import api_app, perpetual_signal
from wrolpi.cmd import which, run_command, CommandResult
from wrolpi.common import Base, ModelHelper, logger, wrol_mode_check, zig_zag, ConfigFile, \
wrol_mode_enabled, background_task, get_absolute_media_path, timer, aiohttp_get, \
get_download_info, trim_file_name, get_wrolpi_config, TRACE_LEVEL
from wrolpi.dates import TZDateTime, now, Seconds
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.errors import InvalidDownload, UnrecoverableDownloadError, BotBlockedDownloadError, UnknownDownload, \
ValidationError, DownloadError
from wrolpi.events import Events
from wrolpi.media_path import MediaPathType
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod, await_switches
from wrolpi.vars import PYTEST, SIMULTANEOUS_DOWNLOAD_DOMAINS
logger = logger.getChild(__name__)
ARIA2C_PATH = which('aria2c', '/usr/bin/aria2c')
ARIA2C_PROGRESS_RE = re.compile(
r'\[#\w+\s+'
r'([\d.]+\w+)/([\d.]+\w+)' # downloaded/total
r'\((\d+)%\)' # percent
r'.*?DL:([\d.]+\w+)' # speed
r'(?:.*?ETA:([^\s\]]+))?' # optional ETA
)
_SIZE_UNITS = [('TiB', 1024 ** 4), ('GiB', 1024 ** 3), ('MiB', 1024 ** 2), ('KiB', 1024), ('B', 1)]
def _parse_size(s: str) -> int:
"""Convert a size string like '4.5MiB' to bytes (int)."""
for suffix, multiplier in _SIZE_UNITS:
if s.endswith(suffix):
return int(float(s[:-len(suffix)]) * multiplier)
# Fallback: try parsing as pure number.
return int(float(s))
def parse_aria2c_progress(line: str) -> dict | None:
"""Parse an aria2c progress line and return a dict, or None if not a progress line."""
m = ARIA2C_PROGRESS_RE.search(line)
if not m:
return None
return dict(
bytes_downloaded=_parse_size(m.group(1)),
total_bytes=_parse_size(m.group(2)),
percent=int(m.group(3)),
speed=_parse_size(m.group(4)),
eta=m.group(5),
)
def set_download_progress(download_id: int, progress: dict):
"""Store download progress in shared_ctx."""
data = dict(api_app.shared_ctx.download_manager_data)
dp = dict(data.get('download_progress', {}))
dp[download_id] = progress
data['download_progress'] = dp
api_app.shared_ctx.download_manager_data.update(data)
def clear_download_progress(download_id: int):
"""Remove download progress from shared_ctx."""
data = dict(api_app.shared_ctx.download_manager_data)
dp = dict(data.get('download_progress', {}))
dp.pop(download_id, None)
data['download_progress'] = dp
api_app.shared_ctx.download_manager_data.update(data)
def make_progress_callback(download_id: int, parse_fn: callable) -> callable:
"""Create a stdout callback that parses progress lines and updates shared_ctx.
The callback throttles updates to at most once per second.
:param download_id: The download ID to update progress for.
:param parse_fn: A function that takes a line string and returns a progress dict or None.
"""
last_update = [0.0]
def on_stdout(line: str):
now_ = time.monotonic()
if now_ - last_update[0] < 1.0:
return
# Some tools (e.g., pmtiles) use \r for progress updates within a single line.
# Parse the last non-empty segment.
segments = [s.strip() for s in line.split('\r') if s.strip()]
for segment in reversed(segments):
progress = parse_fn(segment)
if progress:
last_update[0] = now_
set_download_progress(download_id, progress)
return
return on_stdout
@perpetual_signal(sleep=1 if PYTEST else 5)
async def perpetual_download_worker():
async with flags.db_up.wait_for():
pass
if not get_download_manager_config().successful_import:
logger.trace(f'Not starting perpetual download worker because config was not imported')
return
if download_manager.is_stopped:
logger.trace(f'Not starting perpetual download worker because download manager is stopped')
return
try:
async with flags.have_internet.wait_for(timeout=5):
pass
except TimeoutError:
# Internet is not up.
return
await download_manager.do_downloads()
class DownloadFrequency(int, Enum):
hourly = 3600
hours3 = hourly * 3
hours12 = hourly * 12
daily = hourly * 24
weekly = daily * 7
biweekly = weekly * 2
days30 = daily * 30
days90 = daily * 90
days180 = daily * 180
@dataclass
class DownloadResult:
downloads: List[str] = field(default_factory=list)
error: str = None
info_json: dict = field(default_factory=dict)
location: str = None
retry_seconds: int = None
success: bool = False
settings: dict = field(default_factory=dict)
class DownloadStatus(str, Enum):
new = 'new'
pending = 'pending'
complete = 'complete'
failed = 'failed'
deferred = 'deferred'
class Download(ModelHelper, Base): # noqa
"""Model that is used to schedule downloads."""
__tablename__ = 'download' # noqa
__table_args__ = (
Index('idx_download_collection_id', 'collection_id'),
)
id = Column(Integer, primary_key=True)
url = Column(String, nullable=False, unique=True)
attempts = Column(Integer, default=0)
destination: pathlib.Path = Column(MediaPathType) # '/media/wrolpi/videos/WROLPi'
downloader = Column(Text) # 'videos', 'archive', 'kiwix_zim', etc.
sub_downloader = Column(Text) # The downloader any returned downloads should be sent.
error = Column(Text) # traceback from an error during downloading.
frequency = Column(Integer) # seconds between re-downloading.
info_json = Column(JSONB) # information retrieved WHILE downloading (from yt-dlp)
last_successful_download = Column(TZDateTime)
location = Column(Text) # Relative App URL where the downloaded item can be viewed.
next_download = Column(TZDateTime)
settings = Column(JSONB) # information about how the download should happen (video_resolution, etc.)
status = Column(String, default=DownloadStatus.new) # `DownloadStatus` enum.
tag_names = Column(ARRAY(Text))
# A Download may be associated with a Collection (downloads for channels, domains, etc.).
collection_id = Column(Integer, ForeignKey('collection.id', ondelete='SET NULL'))
collection = relationship('Collection', primaryjoin='Download.collection_id==Collection.id',
back_populates='downloads')
def __repr__(self):
if self.next_download or self.frequency:
return f'<Download id={self.id} status={self.status} url={repr(self.url)} ' \
f'next_download={repr(self.next_download)} frequency={self.frequency} attempts={self.attempts} ' \
f'error={bool(self.error)}>'
return f'<Download id={self.id} status={self.status} url={repr(self.url)} attempts={self.attempts} ' \
f'error={bool(self.error)}>'
def __json__(self) -> dict:
d = dict(
attempts=self.attempts,
collection_id=self.collection_id,
downloader=self.downloader,
frequency=self.frequency,
destination=self.destination,
id=self.id,
last_successful_download=self.last_successful_download,
location=self.location,
next_download=self.next_download,
settings=self.settings,
status=self.status,
sub_downloader=self.sub_downloader,
tag_names=self.tag_names,
url=self.url,
)
return d
def renew(self, reset_attempts: bool = False):
"""Mark this Download as "new" so it will be retried."""
self.status = DownloadStatus.new
if reset_attempts:
self.attempts = 0
@property
def is_new(self) -> bool:
return self.status == DownloadStatus.new
def defer(self):
"""Download should be tried again after a time."""
self.status = DownloadStatus.deferred
@property
def is_deferred(self) -> bool:
return self.status == DownloadStatus.deferred
def fail(self):
"""Download should not be attempted again. A recurring Download will raise an error."""
if self.frequency:
raise ValueError('Recurring download should not be failed.')
self.status = DownloadStatus.failed
@property
def is_failed(self) -> bool:
return self.status == DownloadStatus.failed
def started(self):
"""Mark this Download as in progress."""
self.attempts += 1
self.status = DownloadStatus.pending
@property
def is_pending(self) -> bool:
return self.status == DownloadStatus.pending
def complete(self):
"""Mark this Download as successfully downloaded."""
self.status = DownloadStatus.complete
self.error = None # clear any old errors
self.last_successful_download = now()
@property
def is_complete(self) -> bool:
return self.status == DownloadStatus.complete
def get_downloader(self):
if self.downloader:
return download_manager.find_downloader_by_name(self.downloader)
raise UnrecoverableDownloadError(f'Cannot find downloader for {repr(str(self.url))}')
@property
def domain(self):
return urlparse(self.url).netloc
def filter_excluded(self, urls: List[str]) -> List[str]:
"""Return any URLs that do not match my excluded_urls."""
if self.settings and (excluded_urls := self.settings.get('excluded_urls')):
excluded_urls = excluded_urls.split(',')
def excluded(url: str):
return any(i in url for i in excluded_urls)
return list(filterfalse(excluded, urls))
return urls
def add_to_skip_list(self):
download_manager.add_to_skip_list(self.url)
def delete(self, add_to_skip_list: bool = True):
# Do not download this automatically again. This saves the config.
if add_to_skip_list:
self.add_to_skip_list()
session = Session.object_session(self)
# Get collection info before deleting
collection = self.collection
collection_kind = collection.kind if collection else None
session.delete(self)
session.commit()
# Save appropriate config based on collection kind
if collection_kind == 'channel':
from modules.videos.lib import save_channels_config
save_channels_config.activate_switch()
elif collection_kind == 'domain':
from modules.archive.lib import save_domains_config
save_domains_config.activate_switch()
elif collection_kind:
from wrolpi.collections.config import save_collections_config
save_collections_config.activate_switch()
# Save download config again because this download is now removed from the download lists.
save_downloads_config.activate_switch()
@staticmethod
def get_by_id(session: Session, id_: int) -> Optional['Download']:
download = session.query(Download).filter(Download.id == id_).one_or_none()
return download
@classmethod
def find_by_id(cls, session: Session, id_) -> 'Download':
if download := cls.get_by_id(session, id_):
return download
raise UnknownDownload(f'Cannot find Download with id: {id_}')
@staticmethod
def get_by_url(session: Session, url: str) -> Optional['Download']:
download = session.query(Download).filter(Download.url == url).one_or_none()
return download
@classmethod
def find_by_url(cls, session: Session, url: str) -> 'Download':
if download := cls.get_by_url(session, url):
return download
raise UnknownDownload(f'Cannot find Download with URL: {url}')
@classmethod
def get_all_by_destination(cls, session: Session, destination: str | pathlib.Path) -> List['Download']:
destination = str(destination)
downloads = session.query(Download).filter_by(destination=destination).all()
return downloads
class Downloader:
name: str = None
pretty_name: str = None
listable: bool = True
timeout: int = None
def __init__(self, name: str = None, timeout: int = None):
if not name and not self.name:
raise NotImplementedError('Downloader must have a name!')
self.name: str = self.name or name
self.timeout: int = timeout or self.timeout
self._manager: DownloadManager = None # noqa
download_manager.register_downloader(self)
def __json__(self) -> dict:
return dict(name=self.name, pretty_name=self.pretty_name)
def __repr__(self):
return f'<Downloader name={self.name}>'
async def do_download(self, download: Download) -> DownloadResult:
raise NotImplementedError()
def already_downloaded(self, session: Session, *urls: List[str]):
raise NotImplementedError()
async def process_runner(self, download: Download, cmd: Tuple[str | pathlib.Path, ...], cwd: pathlib.Path,
timeout: int = None, debug: bool = True,
stdout_callback: callable = None, env: dict = None) -> CommandResult:
"""
Run a subprocess using the provided arguments. This process can be killed by the Download Manager.
Global timeout takes precedence over the timeout argument, unless it is 0. (Smaller global timeout wins)
"""
if cwd and not cwd.is_dir():
raise RuntimeError('cwd directory does not exist')
config_timeout = get_wrolpi_config().download_timeout
# 0 means no timeout. Prefer config timeout, then argument, then class default.
if config_timeout:
timeout = config_timeout
elif timeout is None:
timeout = self.timeout
coro = run_command(cmd, cwd=cwd, timeout=timeout, log_command=debug,
stdout_callback=stdout_callback, env=env)
result = await self.cancel_wrapper(coro, download)
if __debug__ and logger.isEnabledFor(TRACE_LEVEL):
for line in result.stdout.decode().splitlines():
logger.trace(line)
for line in result.stderr.decode().splitlines():
logger.error(line)
return result
@staticmethod
async def cancel_wrapper(coro: Coroutine, download: Download):
"""
Converts an async coroutine to a task. If DownloadManager receives a kill request, this method will cancel
the task.
"""
download_id = download.id
task = asyncio.create_task(coro)
try:
while not task.done():
if download_manager.download_is_killed(download_id) or not download_manager.can_download:
outside_window = download_manager.outside_download_window
logger.warning(f'Cancel download of {download.url}')
task.cancel()
try:
await task
except asyncio.CancelledError as e:
logger.info(f'Successful cancel of {download.url}', exc_info=e)
error = 'Download paused: outside download window' if outside_window \
else 'Download was canceled'
return DownloadResult(
success=False,
error=error,
)
finally:
download_manager.unkill_download(download_id)
else:
# Wait for the download to complete. Cancel if requested.
await asyncio.sleep(0.1)
except asyncio.CancelledError:
# Outer cancellation (e.g. from a parent cancel_wrapper). Ensure the inner task is also cancelled.
if not task.done():
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
raise
# Return the result of the download attempt.
return task.result()
@staticmethod
async def get_meta4_contents(url: str) -> bytes | None:
try:
meta4_url = f'{url}.meta4'
async with aiohttp_get(meta4_url, timeout=60) as response:
if response.status == HTTPStatus.OK:
contents = await response.content.read()
try:
root = ET.fromstring(contents)
if root.tag == '{urn:ietf:params:xml:ns:metalink4}metalink':
return contents
if root.tag == '{urn:ietf:params:xml:ns:metalink}metalink':
return contents
logger.debug(f'meta4 file was not a metalink file: {meta4_url}')
except Exception as e:
logger.debug(f'Failed to parse XML {meta4_url}', exc_info=e)
except Exception as e:
logger.debug(f'Failed to fetch meta4 file {url}', exc_info=e)
return None
async def download_file(self, download: Download, url: str, destination: pathlib.Path,
check_for_meta4: bool = True, concurrent: int = 3,
meta4_xml: bytes = None) -> pathlib.Path:
from wrolpi.files.lib import glob_shared_stem
if not ARIA2C_PATH:
raise DownloadError('Cannot find aria2c executable')
# Log download time.
with timer('download_file', level='info'):
# Use caller-provided meta4 (pre-verified), or auto-discover from CDN.
meta4_contents = meta4_xml
if not meta4_contents and check_for_meta4:
meta4_contents = await self.get_meta4_contents(url)
info = await get_download_info(url)
# TODO verify that this output_path is exclusive.
output_path = destination / trim_file_name(info.name)
with tempfile.NamedTemporaryFile(suffix='.meta4') as meta4_path:
cmd = (
ARIA2C_PATH,
'-l', '-', # Log to stdout for progress parsing.
'--log-level=notice', # Only notice-level logs (skip debug spam).
'-c', # Continue downloading a partially downloaded file.
f'-j{concurrent}', # concurrent connections
f'-s{concurrent}', # split into segments
'-d', destination,
url
)
meta4_path = pathlib.Path(meta4_path.name)
if meta4_contents:
meta4_path.write_bytes(meta4_contents)
cmd = (*cmd,
'-M', meta4_path,
)
else:
# Force aria2c to use our predicted filename. This avoids mismatches when
# the URL redirects to a CDN path that doesn't match the original filename.
cmd = (*cmd, '-o', output_path.name)
on_stdout = make_progress_callback(download.id, parse_aria2c_progress)
try:
result = await self.process_runner(download, cmd, destination, stdout_callback=on_stdout)
finally:
clear_download_progress(download.id)
stderr = result.stderr.decode() if getattr(result, 'stderr', None) else ''
stdout = result.stdout.decode() if getattr(result, 'stdout', None) else ''
if result.return_code != 0:
output = stderr.strip() or stdout.strip() or '(no output captured)'
logger.error(f'FileDownloader failed (rc={result.return_code}):'
f'\nstderr: {stderr[-1000:]}'
f'\nstdout: {stdout[-1000:]}')
raise DownloadError(
f'{output}\n\nFileDownloader failed with return code {result.return_code}'
)
if not output_path.is_file():
raise DownloadError(f'{stderr}\n\nOutput file not found: {output_path}')
# Delete any trailing meta4 files.
matching_files = glob_shared_stem(output_path)
for file in matching_files:
if file.name.endswith('.meta4'):
logger.warning(f'Deleting meta4 file: {file}')
file.unlink()
if file.name.endswith('.aria2'):
logger.trace(f'Deleting aria2 file: {file}')
file.unlink()
return output_path
class DownloadManager:
"""
Runs a collection of workers which will download any URLs in the `download` table.
Only one download from each domain will be downloaded at a time. If we only have one domain (example.com) in the
URLs to be downloaded, then only one worker will be busy.
"""
manager = multiprocessing.Event()
def __init__(self):
self.instances: Tuple[Downloader] = tuple()
self._instances = dict()
def __repr__(self):
return f'<DownloadManager pid={os.getpid()}>'
@property
def disabled(self):
# Server is going to keep running, but downloads should stop.
return api_app.shared_ctx.download_manager_disabled
@property
def is_disabled(self) -> bool:
return self.disabled.is_set()
def disable(self):
"""Stop all downloads and downloaders."""
if not self.disabled.is_set():
self.disabled.set()
@property
def stopped(self):
# Server is stopping and perpetual download should stop.
return api_app.shared_ctx.download_manager_stopped
@property
def is_stopped(self) -> bool:
return self.stopped.is_set()
def stop(self):
"""Stop all downloads, downloaders and workers. This is called when the server is shutting down."""
if not self.is_stopped:
self.stopped.set()
self.disable()
async def enable(self):
"""Enable downloading.
perpetual_download_worker will start downloading.
"""
self.log_info('Enabling downloading')
self.stopped.clear()
self.disabled.clear()
@staticmethod
def _get_local_time():
"""Return the current local time, using configured timezone or system default."""
from wrolpi.common import get_wrolpi_config
config = get_wrolpi_config()
if config.timezone:
tz = ZoneInfo(config.timezone)
return now().astimezone(tz).time()
return now().astimezone().time()
def is_within_download_window(self) -> bool:
"""Returns True if current time is within the configured download window, or no window is configured."""
config = get_wrolpi_config()
start = config.download_window_start
end = config.download_window_end
if not start or not end:
return True
current = self._get_local_time()
start_time = datetime.strptime(start, "%H:%M").time()
end_time = datetime.strptime(end, "%H:%M").time()
if start_time <= end_time:
return start_time <= current < end_time
else:
# Overnight window (e.g., 22:00-06:00)
return current >= start_time or current < end_time
@property
def outside_download_window(self) -> bool:
return not self.is_within_download_window()
@property
def can_download(self) -> bool:
"""Returns True only if all steps necessary for downloading have been met."""
if PYTEST:
return True
if self.is_disabled:
# DownloadManager has been disabled and should not download.
return False
if self.is_stopped:
# DownloadManager has been stopped and system is probably restarting.
return False
if not flags.have_internet.is_set():
# Do not download without internet.
return False
if wrol_mode_enabled():
# Do not download with WROL Mode enabled.
return False
if get_wrolpi_config().require_cookies_unlocked \
and flags.cookies_exist.is_set() \
and not flags.cookies_unlocked.is_set():
# Do not download when cookies exist but are not unlocked.
return False
if not self.is_within_download_window():
# Do not download outside the configured time window.
return False
if get_download_manager_config().successful_import:
# Finally, allow downloading because config was valid and imported.
return True
# Do not download by default.
return False
@property
def processing_domains(self):
return api_app.shared_ctx.download_manager_data['processing_domains']
@processing_domains.setter
def processing_domains(self, value: list):
api_app.shared_ctx.download_manager_data.update({'processing_domains': value})
def _add_processing_domain(self, domain: str):
self.processing_domains = list(self.processing_domains) + [domain, ]
def _delete_processing_domain(self, domain: str):
self.processing_domains = [i for i in self.processing_domains if i != domain]
def register_downloader(self, instance: Downloader):
if not isinstance(instance, Downloader):
raise ValueError(f'Invalid downloader cannot be registered! {instance=}')
if instance in self.instances:
raise ValueError(f'Downloader already registered! {instance=}')
self.instances = (*self.instances, instance)
self._instances[instance.name] = instance
def log(self, message: str, level=logging.DEBUG, exc_info=None):
logger.log(level, f'{self} {message}', exc_info=exc_info)
def log_info(self, message: str):
return self.log(message, logging.INFO)
def log_debug(self, message: str):
return self.log(message, logging.DEBUG)
def log_error(self, message: str, exc_info=None):
return self.log(message, logging.ERROR, exc_info)
def log_warning(self, message: str):
return self.log(message, logging.WARNING)
def find_downloader_by_name(self, name: str) -> Optional[Downloader]:
"""Attempt to find a registered Downloader by its name. Raises error if it cannot be found."""
if downloader := self._instances.get(name):
return downloader
raise InvalidDownload(f'Cannot find downloader with name {name}')
def get_or_create_download(self, session: Session, url: str, reset_attempts: bool = False,
override_skip: bool = False) -> Download:
"""Get a Download by its URL, if it cannot be found create one."""
if not url:
raise ValueError('Download must have a URL')
if download := Download.get_by_url(session, url):
if reset_attempts:
download.attempts = 0
return download
if self.is_skipped(url):
if override_skip is True:
self.remove_from_skip_list(url)
else:
raise InvalidDownload(
f'Refusing to download {url} because it is in the download_manager.yaml skip list')
download = Download(url=url, status='new')
session.add(download)
return download
def create_downloads(self, session: Session, urls: List[str], downloader_name: str,
reset_attempts: bool = False, sub_downloader_name: str = None,
destination: str | pathlib.Path = None, tag_names: List[str] = None, settings: dict = None,
override_skip: bool = False) \
-> List[Download]:
"""Schedule all URLs for download. If one cannot be downloaded, none will be added."""
if not urls or not all(urls):
raise ValueError(f'Download must have a URL: {urls=}')
logger.debug(f'Attempting to create {len(urls)} new downloads')
# Ensure all Tags exist before creating downloads.
if tag_names:
with get_db_curs() as curs:
stmt = 'SELECT name FROM tag WHERE name = ANY(%(tag_names)s)'
curs.execute(stmt, dict(tag_names=tag_names))
existing_tag_names = {i[0] for i in curs.fetchall()}
missing_tag_names = set(tag_names) - existing_tag_names
if missing_tag_names:
raise ValidationError(f'Tag does not exist: {missing_tag_names.pop()}')
downloads = []
# Throws an error if no downloader is found.
self.find_downloader_by_name(downloader_name)
if destination:
destination = pathlib.Path(destination) if isinstance(destination, str) else destination
if not destination.is_absolute():
destination = get_absolute_media_path(destination)
for url in urls:
if url in get_download_manager_config().skip_urls and override_skip:
# User manually entered this download, remove it from the skip list.
self.remove_from_skip_list(url)
elif url in get_download_manager_config().skip_urls:
self.log_warning(f'Skipping {url} because it is in the download_manager.yaml skip list.')
continue
download = self.get_or_create_download(session, url, override_skip=override_skip)
# Download may have failed, try again.
download.renew(reset_attempts=reset_attempts)
download.destination = destination or None
download.downloader = downloader_name
download.sub_downloader = sub_downloader_name
download.tag_names = tag_names or None
# Preserve existing settings, unless new settings are provided.
download.settings = settings if settings is not None else download.settings
if download.frequency and download.settings and (collection_id := download.settings.get('collection_id')):
# Attach a recurring download to its Collection.
download.collection_id = download.collection_id or collection_id
downloads.append(download)
logger.debug(f'Created {len(downloads)} new downloads')
session.flush(downloads)
try:
# Start downloading ASAP.
background_task(self.dispatch_downloads())
# Save the config now that new Downloads exist.
save_downloads_config.activate_switch()
except RuntimeError:
# Event loop isn't running. Probably testing?
if not PYTEST:
self.log_info(f'Unable to queue downloads after creating {len(downloads)} download(s).')
return downloads
def create_download(self, session: Session, url: str, downloader_name: str, reset_attempts: bool = False,
sub_downloader_name: str = None, destination: str | pathlib.Path = None,
tag_names: List[str] = None, settings: Dict = None,
override_skip: bool = False) -> Download:
"""Schedule a URL for download. If the URL failed previously, it may be retried."""
downloads = self.create_downloads(session, [url], downloader_name=downloader_name,
reset_attempts=reset_attempts, sub_downloader_name=sub_downloader_name,
destination=destination, tag_names=tag_names, settings=settings,
override_skip=override_skip)
return downloads[0]
def recurring_download(self, session: Session, url: str, frequency: int, downloader_name: str,
sub_downloader_name: str = None, reset_attempts: bool = False,
destination: str | pathlib.Path = None, tag_names: List[str] = None,
settings: Dict = None, collection_id: int = None,
override_skip: bool = False) -> Download:
"""Schedule a recurring download."""
if not frequency or not isinstance(frequency, int):
raise ValueError('Recurring download must have a frequency!')
from wrolpi.scrape_downloader import ScrapeHTMLDownloader
if downloader_name == ScrapeHTMLDownloader.name and frequency:
raise InvalidDownload(f'Cannot schedule recurring download for {downloader_name=}')
download, = self.create_downloads(session, [url, ], downloader_name=downloader_name,
reset_attempts=reset_attempts, sub_downloader_name=sub_downloader_name,
destination=destination, tag_names=tag_names, settings=settings,
override_skip=override_skip)
download.frequency = frequency
if collection_id:
download.collection_id = collection_id
# Only recurring Downloads can be Collection Downloads - look up via Channel.
from modules.videos.models import Channel
if channel := Channel.get_by_url(session, url=download.url):
download.collection_id = channel.collection_id
session.commit()
return download
def update_download(self, session: Session, id_: int, url: str, downloader: str,
destination: str | pathlib.Path = None, tag_names: List[str] = None,
sub_downloader: str | None = None, frequency: int = None,
settings: Dict = None, collection_id: int = None) -> Download:
download = Download.find_by_id(session, id_)
if collection_id and not frequency:
raise InvalidDownload(f'A once-download cannot be associated with a Collection')
download.url = url
download.downloader = downloader
download.frequency = frequency
# Preserve existing settings, unless new settings are provided.
download.settings = settings if settings is not None else download.settings
# Use provided params even if empty.
download.destination = destination or None
download.tag_names = tag_names or None
download.sub_downloader = sub_downloader or None
# Update Collection relationship
download.collection_id = collection_id
save_downloads_config.activate_switch()
return download
@wrol_mode_check
async def dispatch_downloads(self):
"""Dispatch Sanic signals to start downloads. This only starts as many downloads as the
SIMULTANEOUS_DOWNLOAD_DOMAINS variable."""
if not self.can_download:
# Don't queue downloads when disabled.
return
if (domains := len(self.processing_domains)) > SIMULTANEOUS_DOWNLOAD_DOMAINS:
self.log_debug(
f'Unable to queue downloads because there are more domains than workers: {domains} >= 4')
return
# Find download whose domain isn't already being downloaded.
with get_db_session(commit=True) as session:
new_downloads = list(session.query(Download).filter(
Download.status == 'new',
Download.domain not in self.processing_domains,
).order_by(
Download.frequency.is_(None),
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.
Warning: Downloads will still be running even after this returns! See `wait_for_all_downloads`.
"""
if not self.can_download:
return
try:
self.renew_recurring_downloads()
except Exception as e:
self.log_error(f'Unable to renew downloads!', exc_info=e)
try:
self.delete_old_once_downloads()
except Exception as e:
self.log_error(f'Unable to delete old downloads!', exc_info=e)
await self.dispatch_downloads()
async def wait_for_all_downloads(self, timeout: int = 10):
"""Signals start of all pending Downloads, waits for all Downloads to be processed.
@param timeout: Give up waiting after this many seconds.
@raises TimeoutError: If timeout is exceeded.
@warning: THIS METHOD IS FOR TESTING.
"""
with timer('wait_for_all_downloads', level='trace'):
# Use real datetime.now to avoid `fake_now`.
start = datetime.now()
while (datetime.now() - start).total_seconds() < timeout:
# Send out download signals.
await self.dispatch_downloads()
# Wait for processes to start.
await asyncio.sleep(0.1)
await await_switches()
# Break out of loop only when all downloads have been processed.
with get_db_session() as session:
statuses = {i.status for i in self.get_downloads(session)}
if DownloadStatus.new not in statuses and DownloadStatus.pending not in statuses:
# All downloads must be complete/deferred/failed.
break
else:
raise TimeoutError('Downloads never finished!')
@staticmethod
def retry_downloads(reset_attempts: bool = False):
"""Set any incomplete Downloads to `new` so they will be retried.
@param reset_attempts: Will set `download.attempts` to 0 if True.
"""
with get_db_curs(commit=True) as curs:
if reset_attempts:
stmt = "UPDATE download SET status='new', attempts=0 WHERE status='pending' OR status='deferred' OR status='failed'"
else:
stmt = "UPDATE download SET status='new' WHERE status='pending' OR status='deferred' OR status='failed'"
curs.execute(stmt)
def get_new_downloads(self, session: Session) -> Generator[Download, None, None]:
"""
Get all "new" downloads. This method fetches the first download each iteration, so it will fetch downloads
that were created after calling it.
"""
last = None
while True:
download = session.query(Download).filter_by(status='new').order_by(Download.id).first()
if not download:
return
if download == last:
# Got the last download again. Is something wrong?
return
last = download
yield download
def get_recurring_downloads(self, session: Session, limit: int = None):
"""Get all Downloads that will be downloaded in the future."""
query = session.query(Download).filter(
Download.frequency != None # noqa
).order_by(
Download.next_download, # Sort recurring by which will occur first, then by frequency.
Download.frequency, # Sort by frequency if the next_download is the same.
)
if limit:
query = query.limit(limit)
downloads = query.all()
return downloads
def get_once_downloads(self, session: Session, limit: int = None):
"""Get all Downloads that will not reoccur."""
query = session.query(Download).filter(
Download.frequency == None # noqa
).order_by(
Download.last_successful_download.desc(),
Download.id,
)
if limit:
query = query.limit(limit)
downloads = query.all()
return downloads
def renew_recurring_downloads(self):
"""Mark any recurring downloads that are due for download as "new". Start a download."""
now_ = now()
with get_db_session() as session:
recurring = self.get_recurring_downloads(session)
renewed_count = 0
for download in recurring:
# A new download may not have a `next_download`, create it if necessary.
download.next_download = download.next_download or self.calculate_next_download(session, download)
if download.next_download < now_ and download.status not in (
DownloadStatus.new, DownloadStatus.pending):
download.renew()
renewed_count += 1
if renewed_count:
self.log_debug(f'Renewed {renewed_count} recurring downloads')
session.commit()
@staticmethod
def get_downloads(session: Session) -> List[Download]:
downloads = list(session.query(Download).all())
return downloads
def delete_download(self, session: Session, download_id: int):
"""Delete a Download. Returns True if a Download was deleted, otherwise return False."""
if download := Download.get_by_id(session, download_id):
# This saves the config twice.
download.delete()
return True
return False
def restart_download(self, session: Session, download_id: int) -> Download:
"""Renews a download and resets its download attempts."""
download = Download.find_by_id(session, download_id)
download.renew(reset_attempts=True)
session.commit()
return download
def kill_download(self, download_id: int):
"""Fail a Download. If it is pending, kill the Downloader so the download stops."""
logger.info(f'Killing Download: {download_id}')
download_manager_data = api_app.shared_ctx.download_manager_data.copy()
download_manager_data['killed_downloads'] = download_manager_data['killed_downloads'] + [download_id, ]
api_app.shared_ctx.download_manager_data.update(download_manager_data)
with get_db_session(commit=True) as session:
if download := Download.get_by_id(session, download_id):
download.error = 'User stopped this download'
download.fail()
@staticmethod
def unkill_download(download_id: int):
"""Remove a Download from the killed_downloads list. This allows it to be run again."""
download_manager_data = api_app.shared_ctx.download_manager_data.copy()
download_manager_data['killed_downloads'] = \
[i for i in download_manager_data['killed_downloads'] if i != download_id]
api_app.shared_ctx.download_manager_data.update(download_manager_data)
@staticmethod
def download_is_killed(download_id: int):
return download_id in api_app.shared_ctx.download_manager_data['killed_downloads']
FINISHED_STATUSES = (DownloadStatus.complete, DownloadStatus.failed)
def delete_old_once_downloads(self):
"""Delete all once-downloads that have expired.
Do not delete downloads that are new, or should be tried again."""
count = 0
with get_db_session(commit=True) as session:
downloads = self.get_once_downloads(session)
one_month = now() - timedelta(days=30)
for download in downloads:
if download.status in self.FINISHED_STATUSES and download.last_successful_download and \
download.last_successful_download < one_month:
session.delete(download)
count += 1
if count:
self.log_debug(f'Deleted {count} once downloads')
def list_downloaders(self) -> List[Downloader]:
"""Return a list of the Downloaders available on this Download Manager."""
return [i for i in self.instances if i.listable]
# Downloads should be sorted by their status in a particular order.
_status_order = '''CASE
WHEN (status = 'pending') THEN 0
WHEN (status = 'failed') THEN 1
WHEN (status = 'new') THEN 2
WHEN (status = 'deferred') THEN 3
WHEN (status = 'complete') THEN 4
END'''
def get_fe_downloads(self):
"""Get downloads for the Frontend. Uses raw SQL for faster result."""
# Use custom SQL because SQLAlchemy is slow.
with get_db_curs() as curs:
stmt = f'''
SELECT
collection_id,
destination,
downloader,
error,
frequency,
id,
last_successful_download,
location,
next_download,
settings,
status,
sub_downloader,
tag_names,
url
FROM download
WHERE frequency IS NOT NULL
ORDER BY
{self._status_order},
next_download,
frequency
'''
curs.execute(stmt)
recurring_downloads = list(map(dict, curs.fetchall()))
stmt = f'''
SELECT
destination,
downloader,
error,
frequency,
id,
last_successful_download,
location,
next_download,
settings,
status,
tag_names,
url
FROM download
WHERE frequency IS NULL
ORDER BY
{self._status_order},
last_successful_download DESC,
id
LIMIT 100
'''
curs.execute(stmt)
once_downloads = list(map(dict, curs.fetchall()))
stmt = '''
SELECT COUNT(id) FILTER (
WHERE frequency IS NULL
AND (status = 'pending' OR status = 'new')
)
FROM download \
'''
curs.execute(stmt)
pending_once_downloads = curs.fetchone()[0]
try:
progress_data = dict(api_app.shared_ctx.download_manager_data.get('download_progress', {}))
except Exception:
progress_data = {}
for download in once_downloads + recurring_downloads:
if download['id'] in progress_data:
download['progress'] = progress_data[download['id']]
data = dict(
recurring_downloads=recurring_downloads,
once_downloads=once_downloads,
pending_once_downloads=pending_once_downloads,
)
return data
def get_summary(self) -> dict:
"""
Get a summary of what Downloads are happening as well as the status of the DownloadManager.
"""
with get_db_curs() as curs:
stmt = """
SELECT COUNT(*) FILTER (WHERE status = 'pending') AS pending_downloads,
COUNT(*) FILTER (WHERE frequency IS NOT NULL) AS recurring_downloads
FROM download \
"""
curs.execute(stmt)
counts = list(map(dict, curs.fetchall()))[0]
summary = dict(
pending=counts['pending_downloads'],
recurring=counts['recurring_downloads'],
disabled=self.is_disabled,
stopped=self.is_stopped,
outside_download_window=self.outside_download_window,
)
return summary
@staticmethod
def calculate_next_download(session: Session, download: Download) -> Optional[datetime]:
"""
If the download is "deferred", download soon. But, slowly increase the time between attempts.
If the download is "complete" and the download has a frequency, schedule the download in it's next iteration.
(Next week, month, etc.)
When multiple same-frequency downloads are overdue (e.g., after service restart), they are spread
dynamically from NOW using zig_zag. The most overdue download (by last_successful_download) runs
immediately, others are spread across the frequency period.
"""
if download.is_deferred:
# Increase next_download slowly at first, then by large gaps later. The largest gap is the download
# frequency.
hours = 3 ** (download.attempts or 1)
seconds = hours * Seconds.hour
if download.frequency:
seconds = min(seconds, download.frequency)
delta = timedelta(seconds=seconds)
return now() + delta
if not download.frequency:
return None
if not download.id:
raise ValueError('Cannot get next download when Download is not in DB.')
freq = download.frequency
now_ = now()
# Get all downloads with same frequency, ordered by last_successful_download
# (NULL/oldest first - these are most overdue)
same_freq_downloads = session.query(Download).filter_by(frequency=freq).order_by(
Download.last_successful_download.asc().nullsfirst(),
Download.id # Tiebreaker for consistent ordering
).all()
# Identify overdue downloads (next_download in past, NOT new downloads with NULL next_download)
overdue_downloads = [
d for d in same_freq_downloads
if d.next_download is not None and d.next_download < now_
]
# New download added while others are overdue: run immediately
if download.next_download is None and len(overdue_downloads) >= 1:
return now_
# Multiple overdue: spread dynamically from NOW using zig_zag
if len(overdue_downloads) > 1 and download in overdue_downloads:
overdue_index = overdue_downloads.index(download)
# Most overdue runs immediately
if overdue_index == 0:
return now_
# Others spread across frequency period from NOW using zig_zag
end_time = now_ + timedelta(seconds=freq)
zagger = zig_zag(now_, end_time)
slots = [slot for slot, _ in zip(zagger, range(len(overdue_downloads)))]
return slots[overdue_index]
# Normal case: use fixed iteration boundaries with zig_zag
# Keep this Download in it's position within the like-frequency downloads.
downloads = [i.id for i in session.query(Download).filter_by(frequency=freq).order_by(Download.id)]
index = downloads.index(download.id)
# Download was successful. Spread the same-frequency downloads out over their iteration.
start_date = datetime(2000, 1, 1).replace(tzinfo=pytz.UTC)
# Weeks/months/etc. since start_date.
iterations = ((now_ - start_date) // freq).total_seconds()
# Download slots start the next nearest iteration since 2000-01-01.
# For example, if a weekly download was performed on 2000-01-01 it will get the same slot within
# 2000-01-01 to 2000-01-08.
start_date = start_date + timedelta(seconds=(iterations * freq) + freq)
end_date = start_date + timedelta(seconds=freq)
# Get this downloads position in the next iteration. If a download is performed at the 3rd slot this week,
# it will be downloaded the 3rd slot of next week.
zagger = zig_zag(start_date, end_date)
return [i for i, j in zip(zagger, range(len(downloads)))][index]
@staticmethod
def _delete_downloads_q(once: bool = False, status: str = None, returning=Download.id) -> Delete:
stmt = Download.__table__.delete().returning(returning)
if once:
stmt = stmt.where(Download.frequency == None)
if status:
stmt = stmt.where(Download.status == status)
return stmt
def delete_completed(self, session: Session) -> List[int]:
"""Delete any completed download records."""
stmt = self._delete_downloads_q(once=True, status=DownloadStatus.complete)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
return deleted_ids
def delete_failed(self, session: Session):
"""Delete any failed download records."""
stmt = self._delete_downloads_q(once=True, status=DownloadStatus.failed, returning=Download.url)
deleted_urls = [i for i, in session.execute(stmt).fetchall()]
# Add all downloads to permanent skip list.
self.add_to_skip_list(*deleted_urls)
session.commit()
def delete_once(self, session: Session):
"""Delete all once-download records."""
stmt = self._delete_downloads_q(once=True)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
save_downloads_config.activate_switch()
return deleted_ids
def delete_downloads_by_ids(self, session: Session, download_ids: List[int]) -> List[int]:
"""Delete specific downloads by their IDs."""
if not download_ids:
return []
stmt = Download.__table__.delete().where(Download.id.in_(download_ids)).returning(Download.id)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
save_downloads_config.activate_switch()
return deleted_ids
def retry_downloads_by_ids(self, session: Session, download_ids: List[int]) -> int:
"""Retry specific downloads by their IDs. Returns the number of downloads renewed."""
if not download_ids:
return 0
downloads = session.query(Download).filter(Download.id.in_(download_ids)).all()
count = 0
for download in downloads:
if download.status in (DownloadStatus.failed, DownloadStatus.deferred):
download.renew(reset_attempts=True)
count += 1
session.commit()
return count
def clear_completed_by_ids(self, session: Session, download_ids: List[int]) -> List[int]:
"""Clear (delete) specific completed once-downloads by their IDs."""
if not download_ids:
return []
from sqlalchemy import and_
stmt = Download.__table__.delete().where(
and_(
Download.id.in_(download_ids),
Download.status == DownloadStatus.complete,
Download.frequency == None # noqa - only once-downloads
)
).returning(Download.id)
deleted_ids = [i for i, in session.execute(stmt).fetchall()]
session.commit()
return deleted_ids
@staticmethod
def is_skipped(*urls: str) -> bool:
if skip_list := get_download_manager_config().skip_urls:
return all(i in skip_list for i in urls)
return False
@staticmethod
def add_to_skip_list(*urls: str):
get_download_manager_config().skip_urls = sorted(list(set(get_download_manager_config().skip_urls) | set(urls)))
@staticmethod
def remove_from_skip_list(url: str):
skip_urls = get_download_manager_config().skip_urls
if url in skip_urls:
get_download_manager_config().skip_urls = [i for i in get_download_manager_config().skip_urls if i != url]
# The global DownloadManager. This should be used everywhere!
download_manager = DownloadManager()
@api_app.signal('wrolpi.download.download')
async def signal_download_download(download_id: int, download_url: str):
"""Calls Downloaders based on the download information provided, as well as what is in the DB."""
from wrolpi.db import get_db_session
with timer('signal_download_download', 'trace'):
url = download_url
download_domain = None
name = f'download_worker'
worker_logger = logger.getChild(name)
try:
worker_logger.debug(f'Got download {download_id}')
with get_db_session(commit=True) as session:
# Mark the download as started in new session so the change is committed.
download = Download.find_by_id(session, download_id)
download.started()
download_domain = download.domain
downloader: Downloader = download.get_downloader()
if not downloader:
worker_logger.warning(f'Could not find downloader for {download.downloader=}')
try_again = True
try:
# Create download coroutine. Wrap it, so it can be canceled.
if not inspect.iscoroutinefunction(downloader.do_download):
raise RuntimeError(f'Coroutine expected from {downloader} do_download method.')
coro = downloader.do_download(download)
result = await downloader.cancel_wrapper(coro, download)
except BotBlockedDownloadError as e:
# Bot detection or invalid cookies - stop all pending downloads from this domain.
worker_logger.warning(f'BotBlockedDownloadError for {url}', exc_info=e)
result = DownloadResult(success=False, error=str(traceback.format_exc()))
try_again = False
# Fail all pending/new downloads from the same domain.
with get_db_session(commit=True) as fail_session:
domain = urlparse(url).netloc
siblings = fail_session.query(Download).filter(
Download.status.in_(('new', 'pending')),
Download.url.contains(f'://{domain}'),
Download.id != download_id,
).all()
for sibling in siblings:
sibling.error = f'Stopped: bot detection or invalid cookies on {domain}'
sibling.fail()
if siblings:
worker_logger.warning(
f'Failed {len(siblings)} pending downloads from {domain} due to bot detection')
except UnrecoverableDownloadError as e:
# Download failed and should not be retried.
worker_logger.warning(f'UnrecoverableDownloadError for {url}', exc_info=e)
result = DownloadResult(success=False, error=str(traceback.format_exc()))
try_again = False
except Exception as e:
worker_logger.warning(f'Failed to download {url}. Will be tried again later.', exc_info=e)
result = DownloadResult(success=False, error=str(traceback.format_exc()))
# If download has error, and not Internet is available, tell the user!
if result.error and not flags.have_internet.is_set():
result.error = f'{result.error}\n\nNo internet available!'
error_len = len(result.error) if result.error else 0
worker_logger.debug(
f'Got success={result.success} from {downloader} download_id={download.id} with {error_len=}')
with get_db_session(commit=True) as session:
# Modify the download in a new session because downloads may take a long time.
download: Download = session.query(Download).filter_by(id=download_id).one()
# Use a new location if provided, keep the old location if no new location is provided, otherwise
# clear out an outdated location.
download.location = result.location or download.location or None
# Clear any old errors if the download succeeded.
download.error = result.error if result.error else None
# Set status BEFORE calculating next_download. calculate_next_download uses
# the download's status and last_successful_download to determine scheduling.
# If status is still "pending" (stale), the overdue spread logic can return
# now() for the most overdue download, causing an infinite re-download loop.
if result.error and 'outside download window' in result.error:
# Download was paused due to window closing; reset to new so it resumes later.
download.renew()
download.error = result.error
elif try_again is False and not download.frequency:
# Only once-downloads can fail.
download.fail()
elif result.success:
download.complete()
else:
download.defer()
if isinstance(result.retry_seconds, int):
download.next_download = now() + timedelta(seconds=result.retry_seconds)
else:
download.next_download = download_manager.calculate_next_download(session, download)
urls = download.filter_excluded(result.downloads) if result.downloads else None
if urls:
worker_logger.info(f'Adding {len(result.downloads)} downloads from result of {download.url}')
child_settings = dict(result.settings) if result.settings else {}
child_settings['parent_download_url'] = download.url
download_manager.create_downloads(session, urls, downloader_name=download.sub_downloader,
settings=child_settings, reset_attempts=True)
# Remove this domain from the running list.
download_manager._delete_processing_domain(download_domain)
# Allow the download to resume.
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
except Exception as e:
worker_logger.warning(f'Unexpected error', exc_info=e)
finally:
# Remove this domain from the running list.
if download_domain:
download_manager._delete_processing_domain(download_domain)
# Ensure download progress is always cleaned up.
clear_download_progress(download_id)
@dataclass
class DownloadDictConfig:
downloader: str
last_successful_download: str
next_download: str
url: str
frequency: int = None
settings: dict = None
status: str = None
sub_downloader: str = None
@dataclass
class DownloadManagerConfigValidator:
version: int = None
downloads: list[DownloadDictConfig] = field(default_factory=list)
skip_urls: list[str] = field(default_factory=list)
class DownloadManagerConfig(ConfigFile):
file_name = 'download_manager.yaml'
default_config = dict(
downloads=[],
skip_urls=[],
version=0,
)
validator = DownloadManagerConfigValidator
@property
def skip_urls(self) -> List[str]:
return self._config['skip_urls'] or []
@skip_urls.setter
def skip_urls(self, value: List[str]):
self.update({'skip_urls': value})
@property
def downloads(self) -> List[dict]:
return self._config['downloads']
@downloads.setter
def downloads(self, value: List[dict]):
self.update({'downloads': value})
@staticmethod
def _filter_settings_for_yaml(settings: dict) -> dict:
"""Remove inheritable video settings that match current global defaults.
Keeps YAML minimal — only overrides are persisted."""
if not settings:
return settings
from modules.videos.lib import INHERITABLE_VIDEO_SETTINGS, _extract_global_inheritable, \
get_videos_downloader_config
global_defaults = _extract_global_inheritable(get_videos_downloader_config())
filtered = {}
for k, v in settings.items():
if k in INHERITABLE_VIDEO_SETTINGS and v == global_defaults.get(k):
continue
filtered[k] = v
return filtered or None
def dump_config(self, file: pathlib.Path = None, send_events=False, overwrite=False):
try:
with get_db_session() as session:
downloads: Iterable[Download] = session.query(Download).order_by(Download.url)
new_downloads = []
for download in downloads:
if download.last_successful_download and not download.frequency:
# This once-download has completed, do not save it.
continue
destination = download.destination
new_download = dict(
destination=str(destination) if destination else None,
downloader=download.downloader,
frequency=download.frequency,
last_successful_download=download.last_successful_download,
next_download=download.next_download,
settings=self._filter_settings_for_yaml(download.settings),
status=download.status,
sub_downloader=download.sub_downloader,
tag_names=download.tag_names,
url=download.url,
)
new_downloads.append(new_download)
get_download_manager_config().update({'downloads': new_downloads}, overwrite=overwrite)
except Exception as e:
message = f'Failed to save {self.get_relative_file()} config'
logger.error(message, exc_info=e)
if send_events:
Events.send_config_save_failed(message)
def import_config(self, file: pathlib.Path = None, send_events=False):
file = file or self.get_file()
# If config file doesn't exist, mark import as successful (nothing to import)
if not file.is_file():
logger.info('No downloads config file, skipping import')
self.successful_import = True
return
super().import_config(file)
downloads_data = self.downloads
# Empty downloads list = never delete DB records
if not downloads_data:
logger.info(f'No downloads in config, preserving existing DB downloads')
self.successful_import = True
return
with get_db_session(commit=True) as session:
from modules.zim.lib import zim_download_url_to_name
from modules.zim.models import ZimSubscription
try:
logger.warning('Importing downloads in config')
downloads_by_url = {i['url']: i for i in downloads_data}
existing_downloads: List[Download] = list(session.query(Download))
for existing in existing_downloads:
download = downloads_by_url.pop(existing.url, None)
if download:
# Download in config already exists, update the DB record.
# The config is the source of truth.
existing.downloader = download['downloader']
existing.destination = download['destination']
existing.frequency = download['frequency']
existing.last_successful_download = download.get('last_successful_download')
existing.next_download = download.get('next_download')
existing.status = download['status']
existing.sub_downloader = download['sub_downloader']
existing.settings = download.get('settings') or dict()
if 'destination' in existing.settings:
# `destination` may be from old config, or from ChannelDownloader.
destination = existing.settings.pop('destination')
existing.destination = existing.destination or destination
if 'tag_names' in existing.settings:
# `tag_names` may be from old config, or from ChannelDownloader.
tag_names = existing.settings.pop('tag_names')
existing.tag_names = existing.tag_names or tag_names
existing.flush()
else:
logger.warning(f'Deleting Download {existing.url} because it is no longer in the config')
session.delete(existing)
for download in downloads_by_url.values():
# These downloads are new, import them.
download = Download(
destination=download['destination'],
downloader=download['downloader'],
frequency=download['frequency'],
last_successful_download=download.get('last_successful_download'),
next_download=download.get('next_download'),
settings=download['settings'] or dict(),
status=download['status'],
sub_downloader=download['sub_downloader'],
tag_names=download['tag_names'],
url=(url := download['url']),
)
session.add(download)
logger.info(f'Adding new download {url}')
session.commit()
self.successful_import = True
except Exception as e:
self.successful_import = False
message = f'Failed to import {self.file_name}'
logger.error(message, exc_info=e)
if send_events:
Events.send_config_import_failed(message)
raise
try:
# Claim any Kiwix subscriptions for ZimSubscription(s).
downloads: List[Download] = session.query(Download)
need_commit = False
for download in downloads:
if not download.url.startswith('https://download.kiwix.org/') or not download.frequency:
# ZimSubscription requires download.kiwix.org AND a frequency.
continue
name, language = zim_download_url_to_name(download.url)
subscription = session.query(ZimSubscription).filter_by(name=name, language=language).one_or_none()
if not subscription:
subscription = ZimSubscription(name=name, language=language)
subscription.change_download(session, download.url, download.frequency)
session.add(subscription)
need_commit = True
if need_commit:
session.commit()
self.successful_import = True
except Exception as e:
self.successful_import = False
message = 'Failed to restore ZimSubscriptions'
logger.error(message, exc_info=e)
if send_events:
Events.send_config_import_failed(message)
raise
self.successful_import = True
def preview_backup_import(self, backup_date: str, mode: str) -> dict:
backup_file = self._get_backup_file(backup_date)
backup_data = self.read_config_file(backup_file)
current_data = self.read_config_file() if self.get_file().is_file() else dict(downloads=[], version=0)
backup_downloads = backup_data.get('downloads', [])
current_downloads = current_data.get('downloads', [])
current_urls = {dl.get('url') for dl in current_downloads if dl.get('url')}
backup_urls = {dl.get('url') for dl in backup_downloads if dl.get('url')}
add = []
remove = []
unchanged = 0
for dl in backup_downloads:
url = dl.get('url')
if not url:
continue
# In merge mode, skip once-downloads (no frequency)
if mode == 'merge' and not dl.get('frequency'):
continue
if url not in current_urls:
add.append(dict(type='download', url=url, downloader=dl.get('downloader', '')))
else:
unchanged += 1
if mode == 'overwrite':
current_url_to_dl = {dl.get('url'): dl for dl in current_downloads}
for url in sorted(current_urls - backup_urls):
dl = current_url_to_dl[url]
remove.append(dict(type='download', url=url, downloader=dl.get('downloader', '')))
return dict(mode=mode, add=add, remove=remove, unchanged=unchanged)
def import_backup(self, backup_date: str, mode: str, send_events: bool = False):
self._preserve_current_config()
import shutil
backup_file = self._get_backup_file(backup_date)
config_file = self.get_file()
if mode == 'overwrite':
config_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(backup_file, config_file)
elif mode == 'merge':
backup_data = self.read_config_file(backup_file)
current_data = self.read_config_file() if config_file.is_file() else dict(downloads=[], skip_urls=[],
version=0)
current_urls = {dl.get('url') for dl in current_data.get('downloads', []) if dl.get('url')}
merged_downloads = list(current_data.get('downloads', []))
for dl in backup_data.get('downloads', []):
url = dl.get('url')
# Only merge recurring downloads
if url and url not in current_urls and dl.get('frequency'):
merged_downloads.append(dl)
# Merge skip_urls
current_skip = set(current_data.get('skip_urls', []))
merged_skip = list(current_data.get('skip_urls', []))
for url in backup_data.get('skip_urls', []):
if url not in current_skip:
merged_skip.append(url)
merged_data = dict(
downloads=merged_downloads,
skip_urls=merged_skip,
version=current_data.get('version', 0) + 1,
)
config_file.parent.mkdir(parents=True, exist_ok=True)
self.write_config_data(merged_data, config_file)
self.import_config(send_events=send_events)
DOWNLOAD_MANAGER_CONFIG: DownloadManagerConfig = DownloadManagerConfig()
TEST_DOWNLOAD_MANAGER_CONFIG: DownloadManagerConfig = None
@dataclass
class DownloadCacheConfigValidator:
version: int = None
video_durations: list = field(default_factory=list)
class DownloadCacheConfig(ConfigFile):
file_name = 'download_cache.yaml'
default_config = dict(
video_durations=list(),
version=0,
)
validator = DownloadCacheConfigValidator
def import_config(self, file: pathlib.Path = None, send_events=False):
file = file or self.get_file()
if not file.is_file():
self.successful_import = True
return
super().import_config(file, send_events)
self.successful_import = True
@property
def video_durations(self) -> List[list]:
return self._config['video_durations'] or list()
@video_durations.setter
def video_durations(self, value: List[list]):
self.update({'video_durations': value})
DOWNLOAD_CACHE_CONFIG: DownloadCacheConfig = DownloadCacheConfig()
TEST_DOWNLOAD_CACHE_CONFIG: DownloadCacheConfig = None
@contextlib.contextmanager
def download_cache_config_context() -> Generator[DownloadCacheConfig, Any, None]:
"""Used to create a test config."""
global TEST_DOWNLOAD_CACHE_CONFIG
TEST_DOWNLOAD_CACHE_CONFIG = DownloadCacheConfig()
yield TEST_DOWNLOAD_CACHE_CONFIG
TEST_DOWNLOAD_CACHE_CONFIG = None
def get_download_cache_config() -> DownloadCacheConfig:
global TEST_DOWNLOAD_CACHE_CONFIG
if isinstance(TEST_DOWNLOAD_CACHE_CONFIG, ConfigFile):
return TEST_DOWNLOAD_CACHE_CONFIG
global DOWNLOAD_CACHE_CONFIG
return DOWNLOAD_CACHE_CONFIG
@register_switch_handler('save_download_cache_config')
def save_download_cache_config():
"""Save the download cache config to disk."""
get_download_cache_config().dump_config()
logger.info('save_download_cache_config completed')
save_download_cache_config: ActivateSwitchMethod
@contextlib.contextmanager
def downloads_manager_config_context() -> Generator[DownloadManagerConfig, Any, None]:
"""Used to create a test config."""
global TEST_DOWNLOAD_MANAGER_CONFIG
TEST_DOWNLOAD_MANAGER_CONFIG = DownloadManagerConfig()
yield TEST_DOWNLOAD_MANAGER_CONFIG
TEST_DOWNLOAD_MANAGER_CONFIG = None
def get_download_manager_config() -> DownloadManagerConfig:
global TEST_DOWNLOAD_MANAGER_CONFIG
if isinstance(TEST_DOWNLOAD_MANAGER_CONFIG, ConfigFile):
return TEST_DOWNLOAD_MANAGER_CONFIG
global DOWNLOAD_MANAGER_CONFIG
return DOWNLOAD_MANAGER_CONFIG
@register_switch_handler('save_downloads_config')
def save_downloads_config():
"""Fetch all Downloads from the DB, save them to the Download Manager Config."""
get_download_manager_config().dump_config()
logger.info('save_downloads_config completed')
save_downloads_config: ActivateSwitchMethod
async def import_downloads_config():
"""Upsert all Downloads in the Download Manager Config into the DB.
The config is the source of truth."""
if not PYTEST and not flags.db_up.is_set():
logger.warning(f'Refusing to import downloads config when DB is not up.')
return
get_download_manager_config().import_config()
def parse_feed(url: str) -> FeedParserDict:
"""Calls `feedparser.parse`, used for testing."""
return feedparser.parse(url)
class RSSDownloader(Downloader):
"""Downloads an RSS feed and creates new downloads for every unique link in the feed."""
name = 'rss'
pretty_name = 'RSS'
listable = False
def __repr__(self):
return '<RSSDownloader>'
async def do_download(self, download: Download) -> DownloadResult:
sub_downloader = download_manager.find_downloader_by_name(download.sub_downloader)
if not sub_downloader:
raise ValueError(f'Unable to find sub_downloader for {download.url}')
feed: FeedParserDict = parse_feed(download.url)
if feed['bozo'] and not self.acceptable_bozo_errors(feed):
# Feed did not parse
return DownloadResult(success=False, error='Failed to parse RSS feed')
if not isinstance(feed, dict) or not feed.get('entries'):
# RSS parsed but does not have entries.
return DownloadResult(success=False, error='RSS feed did not have any entries')
# Apply YT channel to the Download, if not already applied.
if yt_channel_id := feed.get('feed', dict()).get('yt_channelid'):
if not (download.location or download.collection_id):
self.apply_yt_channel(download.id, yt_channel_id)
# Filter entries using Download.settings.
entries = self.filter_entries(download, feed['entries'])
# Filter URL links.
urls = []
for idx, entry in enumerate(entries):
if url := entry.get('link'):
urls.append(url.strip())
else:
logger.warning(f'RSS entry {idx} did not have a link!')
if download.sub_downloader == 'video':
# Normalize video URLs before checking if already downloaded.
# YouTube Shorts URLs (e.g., youtube.com/shorts/ABC123) must be converted to watch URLs
# (e.g., youtube.com/watch?v=ABC123) to match what is stored in the database.
from modules.videos.normalize_video_url import normalize_video_url
urls = [normalize_video_url(i) for i in urls]
# 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)]
if download.sub_downloader == 'video': # VideoDownloader
urls = await self.filter_videos(download, urls)
logger.info(f'Successfully got {len(urls)} new URLs from RSS {download.url}')
# Pass settings onto the next Downloader.
from modules.videos.lib import CHANNEL_INHERITABLE_SETTINGS
next_download_settings = dict()
settings = download.settings or dict()
# Pass all channel-level inheritable settings to child video downloads.
for key in CHANNEL_INHERITABLE_SETTINGS:
if key in settings:
next_download_settings[key] = settings[key]
# Use download.destination column (settings['destination'] is legacy)
if download.destination:
next_download_settings['destination'] = str(download.destination)
elif i := settings.get('destination'):
# Fallback to legacy settings for backwards compatibility
next_download_settings['destination'] = i
result = DownloadResult(
success=True,
downloads=urls,
settings=next_download_settings,
)
return result
@staticmethod
async def filter_videos(download: Download, urls: list[str]) -> list[str]:
"""Filter Video URLs by comparing the Download's settings."""
from modules.videos.downloader import fetch_video_duration
settings = download.settings or dict()
urls_before = urls.copy()
maximum_duration: int = settings.get('maximum_duration')
minimum_duration: int = settings.get('minimum_duration')
if maximum_duration or minimum_duration:
# RSS feeds do not have video duration in the XML, so use a cached function to fetch the duration of the
# linked videos for filtering.
new_urls = []
for url in urls:
# `fetch_video_duration` is cached so can be called frequently.
try:
if maximum_duration and await fetch_video_duration(url) > maximum_duration:
continue
except Exception as e:
logger.error(f'Failed to fetch duration: {url}', exc_info=e)
try:
if minimum_duration and await fetch_video_duration(url) < minimum_duration:
continue
except Exception as e:
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)}')
return urls
@staticmethod
def filter_entries(download: Download, entries: List[dict]) -> List[dict]:
"""Filter Feed entries using Download's settings."""
# Use .lower() to ignore case.
title_exclude = (download.settings or dict()).get('title_exclude', '')
title_exclude = [i.lower() for i in title_exclude.split(',') if i]
title_include = (download.settings or dict()).get('title_include', '')
title_include = [i.lower() for i in title_include.split(',') if i]
if title_exclude or title_include:
filtered_entries = []
for entry in entries:
# Filter entries based off title.
title = entry.get('title', '').lower()
if title and title_exclude and any(i in title for i in title_exclude):
logger.info(f'RSSDownloader skipping excluded entry ({download.url}): {title}')
continue
if title and title_include and not any(i in title for i in title_include):
logger.info(f'RSSDownloader skipping non-included entry ({download.url}): {title}')
continue
filtered_entries.append(entry)
entries = filtered_entries
return entries
@staticmethod
def apply_yt_channel(download_id: int, yt_channel_id: str):
"""Get Channel that matches this Download, apply Channel/Collection information to the Download."""
with get_db_session() as session:
from modules.videos.models import Channel
channel = Channel.get_by_source_id(session, f'UC{yt_channel_id}')
if channel:
download_ = Download.get_by_id(session, download_id)
download_.collection = channel.collection
download_.collection_id = channel.collection_id
download_.location = download_.location or channel.location
session.commit()
@staticmethod
def acceptable_bozo_errors(feed):
"""Feedparser can report some errors, some we can ignore."""
if 'document declared as' in str(feed['bozo_exception']):
# Feed's encoding does not match what is declared, this is fine.
return True
return False
rss_downloader = RSSDownloader()