Video downloads have many more options. Downloads are migrated.

Storing video settings in session storage to help user start downloads consistently.

Applying channel tag name to new channels when download videos or channels.

Initializing map tiles when importing and resetting map.
This commit is contained in:
Roland 2024-11-02 15:14:02 -06:00
parent a385d4f709
commit 5621d47309
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
77 changed files with 5878 additions and 2541 deletions

View file

@ -54,11 +54,13 @@ class ArchiveDownloader(Downloader, ABC):
with get_db_session() as session:
archive = Archive.find_by_id(archive_id, session)
if download.settings and (tag_names := download.settings.get('tag_names')):
need_commit = False
if tag_names := download.tag_names:
for name in tag_names:
archive.add_tag(name, session)
need_commit = True
if session := Session.object_session(archive):
if need_commit:
session.commit()
logger.info(f'Successfully downloaded Archive {download.url} {archive}')

View file

@ -18,6 +18,7 @@ from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.downloader import download_manager, Download, DownloadResult
from wrolpi.files.models import Directory
from wrolpi.switches import await_switches
from wrolpi.test.common import assert_dict_contains
@ -218,8 +219,7 @@ async def test_channel_download_requires_refresh(
downloaded_urls.append(download.url)
return DownloadResult(success=True)
with mock.patch('modules.videos.downloader.VideoDownloader.do_download', do_download), \
mock.patch('wrolpi.files.lib.apply_indexers'): # TODO why does apply_indexers break this test?
with mock.patch('modules.videos.downloader.VideoDownloader.do_download', do_download):
entries = [
dict(id=vid.source_id, view_count=0, webpage_url='https://example.com/1'), # Already downloaded.
dict(id='not downloaded', view_count=0, webpage_url='https://example.com/2'),
@ -228,8 +228,7 @@ async def test_channel_download_requires_refresh(
channel_id='the id', id='the id')
await video_download_manager.do_downloads()
await video_download_manager.wait_for_all_downloads()
# Give time for background tasks to finish. :(
await asyncio.sleep(1)
await await_switches()
# Channel was refreshed before downloading videos.
assert_refreshed(True)
@ -465,13 +464,12 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
v1, v2 = video_factory(title='video1', channel_id=channel.id), video_factory(title='video2', channel_id=channel.id)
# Create recurring download which uses the Channel's directory.
download = download_manager.recurring_download('https://example.com/1', 60, test_downloader.name,
settings={
'destination': str(test_directory / 'videos/Channel Name')})
destination=str(test_directory / 'videos/Channel Name'))
test_session.commit()
save_channels_config()
assert get_channels_config().channels[0]['directory'] == str(test_directory / 'videos/Channel Name')
# Channel download downloads into the Channel's directory.
assert channel.downloads[0].settings['destination'] == str(test_directory / 'videos/Channel Name')
assert channel.downloads[0].destination == test_directory / 'videos/Channel Name'
# Make extra file in the Channel's directory, it should be moved.
(channel_directory / 'extra file.txt').write_text('extra file contents')
# Channel directory is in the Videos directory.
@ -498,10 +496,8 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
assert not channel_directory.exists(), 'Old Channel directory should have been deleted.'
# Channel download goes into the Channel's directory.
d1, d2 = test_session.query(Download).all()
assert d1.settings['destination'] == str(test_directory / 'videos/Tag Name/Channel Name'), \
f'{d1} was not moved'
assert d2.settings['destination'] == str(test_directory / 'videos/Tag Name/Channel Name'), \
f'{d2} was not moved'
assert d1.destination == test_directory / 'videos/Tag Name/Channel Name', f'{d1} was not moved'
assert d2.destination == test_directory / 'videos/Tag Name/Channel Name', f'{d2} was not moved'
# Directory record was replaced.
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
@ -529,8 +525,8 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
assert not (test_directory / 'videos/Tag Name/Channel Name').exists()
# Downloads are moved back.
d1, d2 = test_session.query(Download).all()
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
assert d1.destination == test_directory / 'videos/Channel Name', f'{d1} was not moved'
assert d2.destination == test_directory / 'videos/Channel Name', f'{d2} was not moved'
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]
# Channel can be Tagged, without moving directories.
@ -544,8 +540,8 @@ async def test_tag_channel(async_client, test_session, test_directory, channel_f
assert str(get_relative_to_media_directory(v2.video_path)) == 'videos/Channel Name/video2.mp4'
# Downloads were not changed.
d1, d2 = test_session.query(Download).all()
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
assert d1.destination == test_directory / 'videos/Channel Name', f'{d1} was not moved'
assert d2.destination == test_directory / 'videos/Channel Name', f'{d2} was not moved'
assert [i.path for i in test_session.query(Directory)] == [channel.directory, ]

View file

@ -88,7 +88,7 @@ async def test_channel_download_relationships(test_session, download_channel):
assert len(channel.downloads) == 1
assert channel.downloads[0] == download and channel.downloads[0].url == 'https://example.com/channel1'
assert download.frequency == DownloadFrequency.weekly
assert download.settings['destination'] == str(channel.directory)
assert download.destination == channel.directory
# Deleting Download deletes the Download, but not the Channel.
download.delete()

View file

@ -147,7 +147,7 @@ def ffmpeg_video_complete(video_path: Path, seconds: int = None) -> bool:
path = Path(fh.name)
path.unlink()
try:
seconds = seconds or get_video_duration(video_path) - 5
seconds = seconds or extract_video_duration(video_path) - 5
ffmpeg_poster(video_path, path, seconds)
return True
except subprocess.CalledProcessError:
@ -243,7 +243,7 @@ async def ffprobe_json(video_path: Union[Path, str]) -> dict:
return content
def get_video_duration(video_path: Path) -> Optional[int]:
def extract_video_duration(video_path: Path) -> Optional[int]:
"""Get the duration of a video in seconds. Do this using ffprobe."""
if not isinstance(video_path, Path):
video_path = Path(video_path)

View file

@ -1,19 +1,23 @@
#! /usr/bin/env python3
import json
import logging
import os.path
import pathlib
import traceback
from abc import ABC
from datetime import timedelta
from typing import Tuple, List, Dict, Optional
import cachetools
import yt_dlp.utils
from cachetools.keys import hashkey
from sqlalchemy.orm import Session
from yt_dlp import YoutubeDL, DownloadError
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, \
format_json_file, trim_file_name
trim_file_name, cached_multiprocessing_result
from wrolpi.dates import now
from wrolpi.db import get_db_session
from wrolpi.db import optional_session
@ -23,10 +27,10 @@ from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix
from wrolpi.files.models import FileGroup
from wrolpi.vars import PYTEST, YTDLP_CACHE_DIR
from .channel.lib import create_channel, get_channel
from .common import get_no_channel_directory, get_videos_directory, update_view_counts_and_censored, \
from .common import get_no_channel_directory, update_view_counts_and_censored, \
ffmpeg_video_complete
from .errors import UnknownChannel
from .lib import get_downloader_config, YDL, ydl_logger
from .lib import get_downloader_config, YDL, ydl_logger, format_videos_destination
from .models import Video, Channel
from .normalize_video_url import normalize_video_url
from .schema import ChannelPostRequest
@ -34,27 +38,41 @@ from .video.lib import download_video_info_json
logger = logger.getChild(__name__)
# Channels are handled differently than a single video.
ChannelIEs = {
YoutubeTabIE,
VIDEO_RESOLUTION_MAP = {
'360p': ['134+140', 'mp4-360p', 'res:360'],
'480p': ['135+140', '135+139', 'mp4-480p', 'res:480'],
'720p': [
'298+140', # 720@60 avc1 + 135k audio
'136+140', '22', 'res:720'],
'1080p': [
'299+140', # 1080@60 avc1 + 135k audio
'137+140', '614+140', 'res:1080'],
'1440p': [
'639+140', # vp9 + 135k audio
'620+140', 'res:1440'],
'2160p': [
'642+140', # vp9 + 135k audio
'625+140', 'res:2160'],
'maximum': ['bestvideo*+bestaudio/best'],
}
PREFERRED_VIDEO_EXTENSION = 'mp4'
PREFERRED_VIDEO_FORMAT = ','.join([
'res:720', # Use the best 720p available first
'136+140', # 130=720p video-only, 140=medium quality audio only
'22', # 720p video with audio
'135+140', # 135=480p video-only, 140=medium quality audio only
'135+139', # 135=480p video-only, 139=low quality audio only
'mp4-480p',
'bestvideo*+bestaudio/best', # Download the highest resolution as a last resort (can be quite large).
])
PREFERRED_CAPTION_FORMAT = 'vtt'
PREFERRED_POSTER_FORMAT = 'jpg'
# VTT is the only format that a browser can use to display captions on a <video/>.
DEFAULT_CAPTION_FORMAT = 'vtt'
DEFAULT_POSTER_FORMAT = 'jpg'
DEFAULT_CHANNEL_DOWNLOAD_ORDER = 'newest'
def extract_info(url: str, ydl: YoutubeDL = YDL, process=False) -> dict:
"""Get info about a video. Separated for testing."""
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())
# 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) -> dict:
"""Get info about a video, channel, or playlist. Separated for testing."""
if PYTEST:
raise RuntimeError(f'Refusing to download {url} during testing! {ydl}')
@ -69,6 +87,25 @@ def prepare_filename(entry: dict, ydl: YoutubeDL = YDL) -> str:
return f'{dir_name}/{file_name}'
@cached_multiprocessing_result
async def fetch_video_duration(url: str) -> int:
"""Get video duration in seconds. Attempts to get the duration from a Video that has already been downloaded,
otherwise, fetches the duration using yt-dlp."""
with get_db_session() as session:
# Join with Video to get duration; a URL may have other files (such as an Archive).
video = Video.get_by_url(url, session=session)
if video and (duration := video.file_group.length):
logger.debug(f'Using already-known duration {duration} for {url} from FileGroup')
return duration
logger.debug(f'Fetching video duration from {url}')
# Duration can be extracted without processing.
info = extract_info(url, process=False)
duration = info['duration']
logger.info(f'Fetched video duration of {duration} from {url}')
return duration
class ChannelDownloader(Downloader, ABC):
"""Handles downloading of videos in a Channel or Playlist."""
name = 'video_channel'
@ -87,7 +124,7 @@ class ChannelDownloader(Downloader, ABC):
"""Update a Channel's catalog, then schedule downloads of every missing video."""
info = extract_info(download.url, process=False)
# Resolve the "entries" generator.
info: Dict = resolve_generators(info)
info: dict = resolve_generators(info)
entries = info.get('entries')
if entries and isinstance(entries[0], Dict) and entries[0].get('entries'):
# Entries contains more channels/playlist, tell the Maintainer to specify the URL.
@ -95,6 +132,9 @@ class ChannelDownloader(Downloader, ABC):
f' Try requesting the videos only:'
f' https://example.com -> https://example.com/videos')
download_settings = download.settings or dict()
channel_tag_name = i[0] if (i := download_settings.get('channel_tag_name')) else None
download.sub_downloader = video_downloader.name
download.info_json = info
if session := Session.object_session(download):
@ -105,7 +145,7 @@ class ChannelDownloader(Downloader, ABC):
if not name:
raise ValueError(f'Could not find name')
channel_source_id = info.get('channel_id') or info.get('id')
channel = get_or_create_channel(channel_source_id, download.url, name)
channel = get_or_create_channel(channel_source_id, download.url, name, channel_tag_name)
channel.dict() # get all attributes while we have the session.
location = f'/videos/channel/{channel.id}/video' if channel and channel.id else None
@ -114,14 +154,14 @@ class ChannelDownloader(Downloader, ABC):
settings = dict()
if channel:
settings.update(dict(channel_id=channel.id, channel_url=download.url))
# Downloads will inherit the destination, if defined.
destination = download.settings.get('destination') if download.settings else None
if destination:
settings['destination'] = destination
# A Download may have applied tags, send any to the VideoDownloader.
tag_names = download.settings.get('tag_names') if download.settings else None
if tag_names:
settings['tag_names'] = tag_names
if download.destination:
settings['destination'] = str(download.destination) # Need str for JSON conversion
if download.tag_names:
settings['tag_names'] = download.tag_names
if video_resolutions := download_settings.get('video_resolutions'):
settings['video_resolutions'] = video_resolutions
if video_format := download_settings.get('video_format'):
settings['video_format'] = video_format
is_a_playlist = self.is_a_playlist(info)
try:
@ -173,28 +213,49 @@ class ChannelDownloader(Downloader, ABC):
downloads = download.info_json['entries']
total_downloads = len(downloads)
title_include = download.settings.get('title_include') if download.settings else None
if title_include:
# Only download Videos that have title match words in title.
title_include = [i.strip() for i in title_include.split(',')]
settings = download.settings or dict()
title_exclude = settings.get('title_exclude', '')
title_exclude = [i.lower() for i in title_exclude.split(',') if i]
title_include = settings.get('title_include', '')
title_include = [i.lower() for i in title_include.split(',') if i]
if title_exclude or title_include:
new_downloads = []
for i in downloads:
if (title := i.get('title', '')) and any(j for j in title_include if j in title):
logger.debug(f'Video with title {title} matches {title_include}')
new_downloads.append(i)
title = i.get('title', '').lower()
if title and title_exclude and any(i in title for i in title_exclude):
logger.debug(f'Video with title {str(repr(title))} matches {title_exclude=}')
continue
if title and title_include and not any(i in title for i in title_include):
logger.debug(f'Video with title {str(repr(title))} matches {title_include=}')
continue
new_downloads.append(i)
downloads = new_downloads
title_exclude = download.settings.get('title_exclude') if download.settings else None
if title_exclude:
# Do not download any videos that contain the exclude words.
title_exclude = [i.strip() for i in title_exclude.split(',')]
new_downloads = list()
for i in downloads:
if (title := i.get('title', '')) and any(j for j in title_exclude if j in title):
logger.debug(f'Video with title {title} matches EXCLUDE {title_exclude}')
else:
new_downloads.append(i)
downloads = new_downloads
# Filter videos by their length.
try:
if minimum_duration := settings.get('minimum_duration'):
downloads = [i for i in downloads if int(i['duration']) >= minimum_duration]
if maximum_duration := settings.get('maximum_duration'):
downloads = [i for i in downloads if int(i['duration']) <= maximum_duration]
except KeyError as e:
raise RuntimeError('Unable to filter videos because there is no duration') from e
# Sort videos now that we have reduced the number necessary to sort, but before we limit count.
sort_key = settings.get('download_order', DEFAULT_CHANNEL_DOWNLOAD_ORDER)
# Default is videos are sorted by newest first.
if sort_key == 'oldest':
logger.debug(f'Downloading oldest videos from {download.url}')
downloads = downloads.reverse()
elif sort_key == 'views':
# Download videos with most views.
logger.debug(f'Downloading most viewed videos from {download.url}')
downloads = sorted(downloads, key=lambda i: i['view_count'], reverse=True)
# Limit the videos that will be downloads (this allows the user to download the "top 100" videos of a Channel)
if video_count_limit := settings.get('video_count_limit'):
logger.debug(f'Limiting video count to {video_count_limit}: {download.url}')
video_count_limit = int(video_count_limit)
downloads = downloads[:video_count_limit]
filtered_entries = len(downloads)
if filtered_entries != total_downloads:
@ -240,6 +301,11 @@ class VideoDownloader(Downloader, ABC):
download_id = download.id
url = normalize_video_url(download.url)
# Copy settings into Download (they may be from the ChannelDownloader)
settings = download.settings or dict()
download.destination = download.destination or settings.get('destination')
tag_names = download.tag_names = download.tag_names or settings.get('tag_names')
# Video may have been downloaded previously, get its location for error reporting.
with get_db_session() as session:
video_ = Video.get_by_url(url, session)
@ -265,8 +331,8 @@ class VideoDownloader(Downloader, ABC):
if destination:
# Download to the directory specified in the settings.
out_dir = pathlib.Path(settings['destination'])
logger.debug(f'Downloading {url} to destination from settings')
out_dir = destination
logger.debug(f'Downloading {url} to destination {destination} from settings')
elif channel:
out_dir = channel_directory
logger.debug(f'Downloading {url} to channel directory: {channel_directory}')
@ -275,11 +341,24 @@ class VideoDownloader(Downloader, ABC):
out_dir = get_no_channel_directory()
logger.debug(f'Downloading {url} to default directory')
# Make output directory. (Maybe string from settings)
out_dir = out_dir if isinstance(out_dir, pathlib.Path) else pathlib.Path(out_dir)
out_dir.mkdir(exist_ok=True, parents=True)
if tag_names and logger.isEnabledFor(logging.DEBUG):
logger.debug(f'Downloading {url} with {tag_names=}')
config = get_downloader_config()
logs = None # noqa
try:
video_path, entry = self.prepare_filename(url, out_dir)
# Use user-provided/channel-provided first, or fallback to defaults from config.
video_resolutions = settings.get('video_resolutions') or config.video_resolutions
# yt-dlp expects a string like so: 299+140,298+140,bestvideo*+bestaudio/best
video_resolutions = ','.join(j for i in video_resolutions for j in VIDEO_RESOLUTION_MAP[i])
video_format = settings.get('video_format') or config.merge_output_format
video_path, entry = self.prepare_filename(url, out_dir, video_resolutions, video_format)
if settings.get('download_metadata_only'):
# User has requested refresh of video metadata, skip the rest of the video downloader.
@ -289,18 +368,17 @@ class VideoDownloader(Downloader, ABC):
cmd = (
str(YT_DLP_BIN),
'-c', # Continue downloads
'-f', PREFERRED_VIDEO_FORMAT,
'-f', video_resolutions,
'--match-filter', '!is_live', # Do not attempt to download Live videos.
'--write-subs',
'--write-auto-subs',
'--sub-format', PREFERRED_CAPTION_FORMAT,
'--convert-subs', PREFERRED_CAPTION_FORMAT,
'--convert-thumbnails', PREFERRED_POSTER_FORMAT,
'--sub-format', DEFAULT_CAPTION_FORMAT,
'--convert-subs', DEFAULT_CAPTION_FORMAT,
'--convert-thumbnails', DEFAULT_POSTER_FORMAT,
'--write-thumbnail',
'--write-info-json',
'--merge-output-format', PREFERRED_VIDEO_EXTENSION,
'--remux-video', PREFERRED_VIDEO_EXTENSION,
'-o', video_path,
'--merge-output-format', video_format,
# '--remux-video', video_format,
'--no-cache-dir',
'--compat-options', 'no-live-chat',
# Get top 20 comments, 10 replies per parent.
@ -308,6 +386,7 @@ class VideoDownloader(Downloader, ABC):
'--extractor-args', 'youtube:max_comments=all,20,all,10;comment_sort=top',
# Use experimental feature to merge files.
'--ppa', 'Merger+ffmpeg_o1:-strict -2',
'-o', video_path,
url,
)
return_code, logs, _ = await self.process_runner(download_id, url, cmd, out_dir)
@ -323,7 +402,7 @@ class VideoDownloader(Downloader, ABC):
location=location,
)
preferred_path = video_path.with_suffix(f'.{PREFERRED_VIDEO_EXTENSION}')
preferred_path = video_path.with_suffix(f'.{video_format}')
if not video_path.is_file() and preferred_path.is_file():
# Prepared filename does not exist, but video with preferred video extension does, it was probably
# remuxed by yt-dlp.
@ -364,7 +443,7 @@ class VideoDownloader(Downloader, ABC):
with get_db_session(commit=True) as session:
# Second session is started because SQLAlchemy will forget what we have done.
video = Video.get_by_id(video_id, session)
if download.settings and (tag_names := download.settings.get('tag_names')):
if tag_names:
existing_names = video.file_group.tag_names
for name in tag_names:
if name not in existing_names:
@ -428,6 +507,9 @@ class VideoDownloader(Downloader, ABC):
@staticmethod
async def _get_channel(download: Download) \
-> Tuple[Optional[Channel], Optional[pathlib.Path], Optional[int], Optional[pathlib.Path], dict]:
settings = download.settings or dict()
channel_tag_name = i[0] if (i := settings.get('channel_tag_name')) else None
found_channel = None
# Look for Channel using channel data first, fallback to uploader data.
channel_name = download.info_json.get('channel') or download.info_json.get('uploader')
@ -437,15 +519,15 @@ class VideoDownloader(Downloader, ABC):
if channel_name or channel_source_id or channel_url:
# Try to find the channel via info_json from yt-dlp.
try:
channel = get_or_create_channel(source_id=channel_source_id, url=channel_url, name=channel_name)
channel = get_or_create_channel(source_id=channel_source_id, url=channel_url, name=channel_name,
tag_name=channel_tag_name)
if channel:
found_channel = 'yt_dlp'
logger.debug(f'Found a channel with source_id {channel=}')
except UnknownChannel:
# Can't find a channel, use the no channel directory.
pass
settings = download.settings or dict()
destination = settings.get('destination')
destination = download.destination
if not channel and destination:
# Destination may find Channel if not already found.
try:
@ -455,7 +537,7 @@ class VideoDownloader(Downloader, ABC):
except UnknownChannel:
# Destination must not be a channel.
pass
channel_id = settings.get('channel_id')
channel_id = download.channel_id
channel_url = settings.get('channel_url')
if not channel and (channel_id or channel_url):
# Could not find Channel via yt-dlp info_json, use info from ChannelDownloader if it created this Download.
@ -469,6 +551,7 @@ class VideoDownloader(Downloader, ABC):
raise
if channel:
found_channel = 'download_settings'
channel_id = channel.id if channel else None
channel_directory = channel.directory if channel else None
if found_channel == 'yt_dlp':
@ -483,17 +566,20 @@ class VideoDownloader(Downloader, ABC):
return channel, channel_directory, channel_id, destination, settings
@staticmethod
def prepare_filename(url: str, out_dir: pathlib.Path) -> Tuple[pathlib.Path, dict]:
def prepare_filename(url: str, out_dir: pathlib.Path, video_resolutions: str, video_format: str) \
-> Tuple[pathlib.Path, dict]:
"""Get the full path of a video file from its URL using yt-dlp."""
if not out_dir.is_dir():
raise ValueError(f'Output directory does not exist! {out_dir=}')
# YoutubeDL expects specific options, add onto the default options
options = get_downloader_config().dict()
options['outtmpl'] = f'{out_dir}/{options["file_name_format"]}'
options['merge_output_format'] = PREFERRED_VIDEO_EXTENSION
options['remuxvideo'] = PREFERRED_VIDEO_EXTENSION
options['format'] = PREFERRED_VIDEO_FORMAT
config = get_downloader_config()
options = config.yt_dlp_options
# yt-dlp expects the absolute path.
options['outtmpl'] = f'{out_dir}/{config.file_name_format}'
options['merge_output_format'] = video_format
# options['remuxvideo'] = video_format
options['format'] = video_resolutions
options['cachdir'] = YTDLP_CACHE_DIR
# Create a new YoutubeDL for the output directory.
@ -523,7 +609,7 @@ class VideoDownloader(Downloader, ABC):
# Trim long filename, add video suffix, add back into parent directory.
filename = escape_file_name(filename)
final_filename = parent / f'{filename}.{PREFERRED_VIDEO_EXTENSION}'
final_filename = parent / f'{filename}.{video_format}'
final_filename = trim_file_name(final_filename)
logger.debug(f'Video file name was too long. Trimmed to: {final_filename.name}')
@ -586,7 +672,7 @@ channel_downloader = ChannelDownloader()
video_downloader = VideoDownloader()
def get_or_create_channel(source_id: str = None, url: str = None, name: str = None) -> Channel:
def get_or_create_channel(source_id: str = None, url: str = None, name: str = None, tag_name: str = None) -> Channel:
"""
Attempt to find a Channel using the provided params. The params are in order of reliability.
@ -604,7 +690,7 @@ def get_or_create_channel(source_id: str = None, url: str = None, name: str = No
raise UnknownChannel(f'Cannot create channel without a name')
# Channel does not exist. Create one in the video directory.
channel_directory = get_videos_directory() / escape_file_name(name)
channel_directory = format_videos_destination(name, tag_name, url)
if not channel_directory.is_dir():
channel_directory.mkdir(parents=True)
data = ChannelPostRequest(
@ -612,6 +698,7 @@ def get_or_create_channel(source_id: str = None, url: str = None, name: str = No
name=name,
url=url,
directory=str(channel_directory.relative_to(get_media_directory())),
tag_name=tag_name,
)
channel = create_channel(data=data, return_dict=False)
# Create the directory now that the channel is approved.

View file

@ -3,9 +3,9 @@ import dataclasses
import html
import pathlib
import re
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import datetime
from typing import Generator, Type
from typing import Generator, Type, List
from typing import Tuple, Optional
import pytz
@ -15,7 +15,7 @@ from yt_dlp import YoutubeDL
from modules.videos.models import Video
from wrolpi import dates, flags
from wrolpi.captions import extract_captions
from wrolpi.common import ConfigFile, extract_domain, \
from wrolpi.common import ConfigFile, extract_domain, logger, \
escape_file_name, get_media_directory, background_task, Base, get_wrolpi_config
from wrolpi.dates import Seconds, from_timestamp
from wrolpi.db import get_db_curs, get_db_session
@ -26,8 +26,8 @@ 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
from .common import is_valid_poster, convert_image, \
generate_video_poster, logger, ConfigError, \
get_video_duration
generate_video_poster, ConfigError, \
extract_video_duration
from .errors import UnknownChannel
from .models import Channel
@ -151,7 +151,7 @@ def validate_video(video: Video, channel_generate_poster: bool):
video.file_group.length = float(video_streams[0]['duration'])
else:
# Slowest method.
video.file_group.length = get_video_duration(video_path)
video.file_group.length = extract_video_duration(video_path)
if video_path and not video.caption_paths and video.file_group.d_text and not EXTRACT_SUBTITLES:
# Caption file was deleted, clear out old captions.
@ -276,7 +276,7 @@ class ChannelsConfig(ConfigFile):
session.add(channel)
channel.flush()
# TODO refresh the files in the channel.
logger.warning(f'Creating new Channel from config {channel}')
logger.warning(f'Creating new Channel from config: {directory}')
# Copy existing channel data, update all values from the config. This is necessary to clear out
# values not in the config.
@ -344,9 +344,8 @@ def set_test_channels_config():
@dataclass
class VideoDownloaderConfigValidator:
class VideoDownloaderConfigYtDlpOptionsValidator:
continue_dl: bool
dateafter: str
file_name_format: str
nooverwrites: bool
quiet: bool
@ -355,105 +354,90 @@ class VideoDownloaderConfigValidator:
writesubtitles: bool
writethumbnail: bool
youtube_include_dash_manifest: bool
@dataclass
class VideoDownloaderConfigValidator:
video_resolutions: List[str] = field(default_factory=lambda: ['1080p', '720p', '480p', '360p', 'maximum'])
version: int = None
yt_dlp_options: VideoDownloaderConfigYtDlpOptionsValidator = field(default_factory=dict)
class VideoDownloaderConfig(ConfigFile):
file_name = 'videos_downloader.yaml'
default_config = dict(
continue_dl=True,
dateafter='19900101',
file_name_format='%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s',
nooverwrites=True,
quiet=False,
video_resolutions=['1080p', '720p', '480p', '360p', 'maximum'],
version=0,
writeautomaticsub=True,
writeinfojson=True,
writesubtitles=True,
writethumbnail=True,
youtube_include_dash_manifest=False,
yt_dlp_options=dict(
continue_dl=True,
file_name_format='%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s',
merge_output_format='mp4',
nooverwrites=True,
quiet=False,
writeautomaticsub=True,
writeinfojson=True,
writesubtitles=True,
writethumbnail=True,
youtube_include_dash_manifest=False,
),
)
validator = VideoDownloaderConfigValidator
@property
def continue_dl(self) -> bool:
return self._config['continue_dl']
@continue_dl.setter
def continue_dl(self, value: bool):
self.update({'continue_dl': value})
return self._config['yt_dlp_options']['continue_dl']
@property
def dateafter(self) -> str:
return self._config['dateafter']
def video_resolutions(self) -> List[str]:
return self._config['video_resolutions']
@dateafter.setter
def dateafter(self, value: str):
self.update({'dateafter': value})
@video_resolutions.setter
def video_resolutions(self, value: List[str]):
self.update({'video_resolutions': value})
@property
def file_name_format(self) -> str:
return self._config['file_name_format']
@file_name_format.setter
def file_name_format(self, value: str):
self.update({'file_name_format': value})
return self._config['yt_dlp_options']['file_name_format']
@property
def nooverwrites(self) -> bool:
return self._config['nooverwrites']
return self._config['yt_dlp_options']['nooverwrites']
@nooverwrites.setter
def nooverwrites(self, value: bool):
self.update({'nooverwrites': value})
@property
def merge_output_format(self) -> bool:
return self._config['yt_dlp_options']['merge_output_format']
@property
def quiet(self) -> bool:
return self._config['quiet']
@quiet.setter
def quiet(self, value: bool):
self.update({'quiet': value})
return self._config['yt_dlp_options']['quiet']
@property
def writeautomaticsub(self) -> bool:
return self._config['writeautomaticsub']
@writeautomaticsub.setter
def writeautomaticsub(self, value: bool):
self.update({'writeautomaticsub': value})
return self._config['yt_dlp_options']['writeautomaticsub']
@property
def writeinfojson(self) -> bool:
return self._config['writeinfojson']
@writeinfojson.setter
def writeinfojson(self, value: bool):
self.update({'writeinfojson': value})
return self._config['yt_dlp_options']['writeinfojson']
@property
def writesubtitles(self) -> bool:
return self._config['writesubtitles']
@writesubtitles.setter
def writesubtitles(self, value: bool):
self.update({'writesubtitles': value})
return self._config['yt_dlp_options']['writesubtitles']
@property
def writethumbnail(self) -> bool:
return self._config['writethumbnail']
@writethumbnail.setter
def writethumbnail(self, value: bool):
self.update({'writethumbnail': value})
return self._config['yt_dlp_options']['writethumbnail']
@property
def youtube_include_dash_manifest(self) -> bool:
return self._config['youtube_include_dash_manifest']
return self._config['yt_dlp_options']['youtube_include_dash_manifest']
@youtube_include_dash_manifest.setter
def youtube_include_dash_manifest(self, value: bool):
self.update({'youtube_include_dash_manifest': value})
@property
def yt_dlp_options(self) -> dict:
return self._config['yt_dlp_options']
@yt_dlp_options.setter
def yt_dlp_options(self, value: dict):
self.update({'yt_dlp_options': value})
VIDEO_DOWNLOADER_CONFIG: VideoDownloaderConfig = VideoDownloaderConfig()
@ -528,11 +512,11 @@ def import_channels_config():
channel_import_logger.info('Importing channels config completed')
def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel):
def link_channel_and_downloads(session: Session, channel_: Type[Base] = Channel, download_: Type[Base] = Download):
"""Create any missing Downloads for any Channel.url/Channel.directory that has a Download. Associate any Download
related to a Channel."""
# Only Downloads with a frequency can be a Channel Download.
downloads = list(session.query(Download).filter(Download.frequency.isnot(None)).all())
downloads = list(session.query(download_).filter(download_.frequency.isnot(None)).all())
# Download.url is unique and cannot be null.
downloads_by_url = {i.url: i for i in downloads}
# Many Downloads may share the same destination.
@ -738,7 +722,8 @@ def format_videos_destination(channel_name: str = None, channel_tag: str = None,
try:
videos_destination = videos_destination % variables
except KeyError as e:
raise FileNotFoundError(f'Cannot download to the defined "videos_destination"') from e
msg = f'Cannot download to the "videos_destination" from Settings: {videos_destination}'
raise FileNotFoundError(msg) from e
videos_destination = get_media_directory() / videos_destination.lstrip('/')

View file

@ -552,6 +552,10 @@ class Channel(ModelHelper, Base):
def tag_name(self) -> str | None:
return self.tag.name if self.tag else None
@property
def location(self) -> str:
return f'/videos/channel/{self.id}/video'
def delete_with_videos(self):
"""Delete all Video records (but not video files) related to this Channel. Then delete the Channel."""
session = Session.object_session(self)
@ -658,6 +662,7 @@ class Channel(ModelHelper, Base):
def dict(self, with_statistics: bool = False, with_downloads: bool = True) -> dict:
d = super(Channel, self).dict()
d['tag_name'] = self.tag_name
d['rss_url'] = self.get_rss_url()
d['directory'] = \
self.directory.relative_to(get_media_directory()) if self.directory else None
if with_statistics:
@ -767,7 +772,7 @@ class Channel(ModelHelper, Base):
if not download:
download = download_manager.recurring_download(url, frequency, ChannelDownloader.name, session=session,
sub_downloader_name=VideoDownloader.name,
settings=dict(destination=str(self.directory)),
destination=self.directory,
reset_attempts=reset_attempts,
)
if reset_attempts:
@ -778,7 +783,9 @@ class Channel(ModelHelper, Base):
def get_rss_url(self) -> str | None:
"""Return the RSS Feed URL for this Channel, if any is possible."""
if self.url and self.source_id and 'youtube.com' in self.url:
yt_url = 'youtube.com' in self.url if self.url else False
yt_source_id = self.source_id.startswith('UC') if self.source_id else False
if yt_url and yt_source_id:
return f'https://www.youtube.com/feeds/videos.xml?channel_id={self.source_id}'
@staticmethod
@ -806,11 +813,7 @@ class Channel(ModelHelper, Base):
downloads.extend(Download.get_all_by_destination(from_directory))
downloads = unique_by_predicate(downloads, lambda i: i.id)
for download in downloads:
# Get new copy of `settings` to avoid bug where it wouldn't update.
settings = download.settings.copy() if download.settings else dict()
if settings.get('destination'):
logger.debug(f'Updating destination of {download}')
download.settings = {**settings, 'destination': str(to_directory)}
download.destination = to_directory
session.flush(downloads)
# Only one tag can be moved at a time.
@ -858,3 +861,7 @@ class Channel(ModelHelper, Base):
if old_directory.exists() and not next(iter(old_directory.iterdir()), None):
# Old directory is empty, delete it.
old_directory.rmdir()
@staticmethod
def get_by_source_id(session: Session, source_id: str) -> Optional['Channel']:
return session.query(Channel).filter_by(source_id=source_id).one_or_none()

View file

@ -148,16 +148,16 @@ def test_channels_with_videos(test_session, test_client, test_directory, channel
def test_api_download(test_session, test_client, test_directory):
"""A video can be downloaded."""
content = dict(urls=['https://example.com/video1', ], downloader='video',
settings=dict(excluded_urls='example.com', destination='dest'))
content = dict(urls=['https://example.com/video1', ], downloader='video', destination='dest',
settings=dict(excluded_urls='example.com'))
request, response = test_client.post('/api/download', content=json.dumps(content))
assert response.status_code == HTTPStatus.NO_CONTENT
download = test_session.query(Download).one()
assert download.url == 'https://example.com/video1'
assert download.downloader == 'video'
assert download.settings['excluded_urls'] == ['example.com']
assert download.settings['destination'] == str(test_directory / 'dest')
assert download.settings['excluded_urls'] == 'example.com'
assert download.destination == test_directory / 'dest'
assert not download.settings.get('tag_names')

View file

@ -14,7 +14,7 @@ from wrolpi.files import lib as files_lib
from wrolpi.switches import await_switches
from wrolpi.vars import PROJECT_DIR
from .. import common
from ..common import convert_image, update_view_counts_and_censored, get_video_duration, generate_video_poster, \
from ..common import convert_image, update_view_counts_and_censored, extract_video_duration, generate_video_poster, \
is_valid_poster
from ..lib import save_channels_config, get_channels_config, import_channels_config, ChannelsConfig, \
convert_or_generate_poster
@ -25,23 +25,23 @@ def test_get_absolute_media_path(test_directory):
assert str(path).endswith('videos')
def test_get_video_duration(test_directory, corrupted_video_file):
def test_extract_video_duration(test_directory, corrupted_video_file):
"""
Video duration can be retrieved from the video file.
"""
video_path = PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4'
assert get_video_duration(video_path) == 5
assert extract_video_duration(video_path) == 5
with pytest.raises(FileNotFoundError):
get_video_duration(PROJECT_DIR / 'test/does not exist.mp4')
extract_video_duration(PROJECT_DIR / 'test/does not exist.mp4')
with pytest.raises(subprocess.CalledProcessError):
empty_file = test_directory / 'empty.mp4'
empty_file.touch()
get_video_duration(empty_file)
extract_video_duration(empty_file)
with pytest.raises(subprocess.CalledProcessError):
get_video_duration(corrupted_video_file)
extract_video_duration(corrupted_video_file)
def test_convert_image():
@ -304,10 +304,10 @@ async def test_ffprobe_json(async_client, video_file, corrupted_video_file):
@pytest.mark.asyncio
async def test_video_ffprobe_json(test_session, video_file):
async def test_video_ffprobe_json(async_client, test_session, video_file):
"""ffprobe data is extracted when a video is modeled."""
with mock.patch('modules.videos.lib.get_video_duration') as mock_get_video_duration:
mock_get_video_duration.side_effect = Exception('duration should be from ffprobe json')
with mock.patch('modules.videos.lib.extract_video_duration') as mock_extract_video_duration:
mock_extract_video_duration.side_effect = Exception('duration should be from ffprobe json')
await files_lib.refresh_files()
video = test_session.query(Video).one()

View file

@ -2,6 +2,7 @@ import asyncio
import json
import shutil
from copy import copy
from http import HTTPStatus
from unittest import mock
import pytest
@ -9,8 +10,10 @@ import pytest
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader
from modules.videos.models import Channel, Video
from wrolpi.conftest import test_directory
from wrolpi.downloader import Download, DownloadResult
from wrolpi.errors import InvalidDownload
from wrolpi.switches import await_switches
from wrolpi.vars import PROJECT_DIR
example_video_json = {
@ -50,6 +53,7 @@ example_channel_json = {
'uploader': None,
'url': 'video_1_url',
'view_count': 58504,
'upload_date': '20190707',
'webpage_url': 'https://youtube.com/watch?v=video_1_url'},
{'_type': 'url',
'description': None,
@ -60,6 +64,7 @@ example_channel_json = {
'uploader': None,
'url': 'video_2_url',
'view_count': 1413,
'upload_date': '20190707',
'webpage_url': 'https://youtube.com/watch?v=video_2_url'},
],
'extractor': 'youtube:tab',
@ -124,7 +129,7 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
@pytest.mark.asyncio
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
async def test_download_channel(test_session, test_directory, simple_channel, video_download_manager, video_file,
mock_video_extract_info, mock_video_prepare_filename,
mock_video_process_runner):
"""Downloading (updating the catalog of) a Channel updates its info_json.
@ -170,6 +175,7 @@ async def test_download_channel(test_session, simple_channel, video_download_man
assert downloads[0].settings == {
'channel_id': 1,
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
'destination': str(test_directory),
}
reset_downloads()
@ -187,17 +193,21 @@ async def test_download_channel(test_session, simple_channel, video_download_man
assert downloads[0].settings == {
'channel_id': 1,
'channel_url': 'https://www.youtube.com/c/LearningSelfReliance/videos',
'destination': str(test_directory),
}
def test_get_or_create_channel(test_session):
@pytest.mark.asyncio
async def test_get_or_create_channel(async_client, test_session, test_directory, tag_factory):
"""A Channel may need to be created for an arbitrary download.
Attempt to use an existing Channel if we can match it.
"""
c1 = Channel(name='foo', source_id='foo', url='foo')
one, two = await tag_factory(), await tag_factory()
c1 = Channel(name='foo', source_id='foo', url='https://example.com')
c2 = Channel(name='bar', source_id='bar')
c3 = Channel(name='baz', source_id='baz', url='baz')
c3 = Channel(name='baz', source_id='baz', url='https://example.net')
c4 = Channel(name='qux')
test_session.add_all([c1, c2, c3, c4])
test_session.commit()
@ -205,8 +215,8 @@ def test_get_or_create_channel(test_session):
# All existing channels should be used.
tests = [
(dict(source_id='foo'), c1),
(dict(url='foo'), c1),
(dict(url='foo', source_id='bar'), c2), # source_id has priority.
(dict(url='https://example.com'), c1),
(dict(url='https://example.com', source_id='bar'), c2), # source_id has priority.
(dict(name='foo', source_id='bar'), c2),
(dict(source_id='bar'), c2),
(dict(source_id='baz'), c3),
@ -217,15 +227,30 @@ def test_get_or_create_channel(test_session):
assert expected.id == channel.id, f'Expected {expected} for {kwargs} but got {channel}'
# A new channel is created. It will not be automatically downloaded.
channel = get_or_create_channel(source_id='quux', name='quux', url='quux')
channel = get_or_create_channel(source_id='quux', name='quux', url='https://example.org')
assert channel.id == 5
assert channel.source_id == 'quux'
assert channel.name == 'quux'
assert channel.url == 'quux'
assert channel.url == 'https://example.org'
# New channel can be retrieved.
assert get_or_create_channel(source_id='quux') == channel
# A Channel can be created with a tag name.
channel = get_or_create_channel(name='One Channel', tag_name=one.name)
await await_switches()
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.tag_name == one.name and channel.tag == one
# Getting the same Channel will not change the tag.
channel = get_or_create_channel(name='One Channel', tag_name=two.name)
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.tag_name == one.name and channel.tag == one
channel = get_or_create_channel(name='One Channel')
assert channel.directory == test_directory / f'videos/one/One Channel'
assert channel.directory.is_dir()
assert channel.tag_name == one.name and channel.tag == one
def test_channel_downloader_hidden(video_download_manager):
"""
@ -331,9 +356,8 @@ async def test_download_destination(test_session, test_directory, video_download
mock_video_prepare_filename.reset_mock()
settings = dict(destination=f'{test_directory}/custom')
video_download_manager.create_download('https://example.com/2', downloader_name=VideoDownloader.name,
settings=settings)
destination=f'{test_directory}/custom')
await video_download_manager.wait_for_all_downloads()
# Output directory matches the custom directory specified.
assert mock_video_prepare_filename.call_args_list[0].kwargs['ydl'].params['outtmpl']['default'] \
@ -356,6 +380,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 2 title',
'uploader': None,
'upload_date': '20241108',
'url': 'https://www.youtube.com/shorts/video_2_url',
'view_count': 1413,
'webpage_url': 'https://www.youtube.com/shorts/video_2_url'},
@ -366,6 +391,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 1 title',
'uploader': None,
'upload_date': '20241108',
'url': 'https://www.youtube.com/watch?v=video_1_url',
'view_count': 58504,
'webpage_url': 'https://www.youtube.com/watch?v=video_1_url'},
@ -376,6 +402,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 3 title',
'uploader': None,
'upload_date': '20241108',
'url': 'https://youtube.com/watch?v=video_3_url',
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_3_url'},
@ -403,7 +430,7 @@ example_playlist_json = {
async def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager,
video_file):
"""All videos in a playlist can be downloaded for it's Channel."""
download = Download(url='playlist url')
download = Download(url='https://example.com/playlist-url')
test_session.add(download)
channel = get_or_create_channel(example_playlist_json['channel_id'], download.url, example_channel_json['uploader'])
video = Video.from_paths(test_session, video_file)
@ -422,3 +449,48 @@ async def test_download_playlist(test_session, test_directory, mock_video_extrac
'https://www.youtube.com/watch?v=video_2_url', # Shorts is converted to regular URL.
'https://youtube.com/watch?v=video_3_url',
}
@pytest.mark.asyncio
async def test_channel_download_crud(test_session, async_client, assert_downloads, tag_factory):
"""Test creatin"""
one, two = await tag_factory(), await tag_factory()
download = {
'urls': ['https://www.youtube.com/@wrolpi/videos'],
'destination': '',
'downloader': 'video_channel',
'sub_downloader': 'video',
'frequency': 2592000,
'tag_names': [one.name, two.name],
'settings': {
'channel_tag_name': [one.name, ],
'download_order': 'newest',
'maximum_duration': 600,
'minimum_duration': 60,
'title_exclude': 'foo,bar',
'title_include': 'baz,qux',
'video_count_limit': 100,
'video_resolutions': ['1080p', '720p', '480p', '360p', 'maximum'],
'video_format': 'mp4',
}
}
request, response = await async_client.post('/api/download', json=download)
assert response.status == HTTPStatus.NO_CONTENT
download = test_session.query(Download).one()
assert download.url == 'https://www.youtube.com/@wrolpi/videos'
assert download.tag_names == ['one', 'two']
assert download.downloader == 'video_channel'
assert download.sub_downloader == 'video'
assert download.frequency == 2592000
assert download.settings
assert download.settings['channel_tag_name'] == ['one']
assert download.settings['download_order'] == 'newest'
assert download.settings['maximum_duration'] == 600
assert download.settings['minimum_duration'] == 60
assert download.settings['title_exclude'] == 'foo,bar'
assert download.settings['title_include'] == 'baz,qux'
assert download.settings['video_count_limit'] == 100
assert download.settings['video_resolutions'] == ['1080p', '720p', '480p', '360p', 'maximum']
assert download.settings['video_format'] == 'mp4'

View file

@ -1,5 +1,6 @@
import pathlib
import shutil
from http import HTTPStatus
import pytest
@ -266,3 +267,26 @@ async def test_format_videos_destination(async_client, test_directory):
wrolpi_config.videos_destination = '%(channel_tag)s/%(channel)s'
with pytest.raises(FileNotFoundError):
assert format_videos_destination()
@pytest.mark.asyncio
async def test_video_downloader_config_api(async_client, test_directory):
config = lib.get_downloader_config()
assert config.video_resolutions == ['1080p', '720p', '480p', '360p', 'maximum']
request, response = await async_client.get('/api/config/videos_downloader.yaml')
assert response.status == HTTPStatus.OK
config = response.json['config']
config['video_resolutions'] = ['720p', 'maximum']
body = dict(config=config)
request, response = await async_client.post('/api/config/videos_downloader.yaml', json=body)
assert response.status == HTTPStatus.NO_CONTENT
config = lib.get_downloader_config()
assert config.video_resolutions == ['720p', 'maximum']
assert (test_directory / 'config/videos_downloader.yaml').is_file()
assert config.is_valid()
contents = config.read_config_file()
assert contents['video_resolutions'] == ['720p', 'maximum']
assert '1080p' not in config.get_file().read_text()