RSSDownloader can schedule downloads for other Downloaders using sub_downloader.

RSS download can be submitted in UI.

Checking if entry has link.

A video playlist can be downloaded.

Passing sub_downloader when submitting RSS feed.

Adding Archive downloader button.

Playlists need more info.

Removing expunge, it causes errors elsewhere.  Fixing tests.

Showing errors on recurring downloads.  Ignoring CharacterEncodingOverride bozo error for rss feed.

Changing download button order.

Fixing bug where channel attributes were unavailable after session.  Simplifying video format selection.

Calling validate_video in Video.validate() to avoid duplicate code.

Adding more frequent downloads for RSS Feeds.

DownloadManager skips downloads in it's list.

Renaming get_next_download to more clear calculate_next_download.

Stopping download manager when server is shutting down.

Not shutting down downloads during tests, not all tests use downloads.

Making methods static.
This commit is contained in:
Roland 2022-05-20 15:15:31 -06:00
parent f2d57fcb23
commit f14a230bc6
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
23 changed files with 1413 additions and 620 deletions

View file

@ -1,11 +1,15 @@
from abc import ABC
from typing import Tuple
from typing import Tuple, Optional
from sqlalchemy.orm import Session
from wrolpi.common import logger
from wrolpi.db import optional_session
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from . import lib
from .api import bp # noqa
from .models import Archive
PRETTY_NAME = 'Archive'
@ -33,6 +37,11 @@ class ArchiveDownloader(Downloader, ABC):
archive = lib.do_archive(download.url)
return DownloadResult(success=True, location=f'/archive/{archive.id}')
@optional_session
def already_downloaded(self, url: str, session: Session = None) -> Optional[Archive]:
archive = session.query(Archive).filter_by(url=url).one_or_none()
return archive
# Archive downloader is the last downloader which should be used.
archive_downloader = ArchiveDownloader(priority=100)

File diff suppressed because it is too large Load diff

View file

@ -100,6 +100,7 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
raise UnknownChannel(f'No channel matches {channel_id=} {source_id=} {url=} {directory=}')
logger.debug(f'Found {channel=} using {channel_id=} {source_id=} {url=} {directory=}')
session.refresh(channel)
if return_dict:
statistics = channel.get_statistics()
channel = channel.dict()

View file

@ -349,7 +349,8 @@ def test_download_channel_no_refresh(test_session, download_channel, video_downl
test_session.commit()
with mock.patch('modules.videos.downloader.YDL.extract_info') as mock_extract_info:
mock_extract_info.return_value = {'entries': [], 'url': 'foo'}
mock_extract_info.return_value = {'entries': [], 'url': 'foo', 'uploader': 'some uploader',
'channel_id': 'the id', 'id': 'the id'}
video_download_manager.do_downloads_sync()
check_refreshed(True)

View file

@ -16,12 +16,13 @@ from wrolpi.cmd import which
from wrolpi.common import logger, extract_domain, get_media_directory
from wrolpi.dates import now
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.db import optional_session
from wrolpi.downloader import Downloader, Download, DOWNLOAD_MANAGER_CONFIG, DownloadResult
from wrolpi.errors import UnknownChannel, ChannelURLEmpty, UnrecoverableDownloadError
from wrolpi.vars import PYTEST
from .channel.lib import create_channel, get_channel
from .common import apply_info_json, get_no_channel_directory, get_videos_directory
from .lib import upsert_video, refresh_channel_videos, get_downloader_config, get_channel_source_id
from .lib import upsert_video, refresh_channel_videos, get_downloader_config
from .models import Video, Channel
from .schema import ChannelPostRequest
from .video_url_resolver import video_url_resolver
@ -39,7 +40,13 @@ ChannelIEs = {
}
PREFERRED_VIDEO_EXTENSION = 'mp4'
PREFERRED_VIDEO_FORMAT = 'best[height=720],22,720p,mp4-480p,mp4-360p,mp4-240p,18,bestvideo+bestaudio'
PREFERRED_VIDEO_FORMAT = ','.join([
'res:720', # Use the best 720p available first
'136+140', # 130=720p video-only, 140= high quality audio only
'22', # 720p video with audio
'18', # 360p video with audio
'bestvideo+bestaudio', # Download the highest resolution as a last resort (1080p is quite large).
])
def extract_info(url: str, ydl: YoutubeDL = YDL, process=False) -> dict:
@ -53,7 +60,7 @@ def prepare_filename(entry: dict, ydl: YoutubeDL = YDL) -> str:
class ChannelDownloader(Downloader, ABC):
"""Handles downloading of all Videos in a Channel."""
"""Handles downloading of videos in a Channel or Playlist."""
name = 'video_channel'
pretty_name = 'Video Channel'
listable = False
@ -69,41 +76,84 @@ class ChannelDownloader(Downloader, ABC):
logger.debug(f'{cls.__name__} not suitable for {url}')
return False, None
@staticmethod
def is_a_playlist(info: dict):
# A playlist will have an id different from its channel.
return info['id'] != info['channel_id']
def do_download(self, download: Download) -> DownloadResult:
"""Update a Channel's catalog, then schedule downloads of every missing video."""
with get_db_session() as session:
channel = session.query(Channel).filter_by(url=download.url).one_or_none()
info = extract_info(download.url, process=False)
if not channel:
# Couldn't get channel by URL, this is probably a playlist. Find the channel for the playlist.
channel_source_id = get_channel_source_id(download.url)
channel = get_channel(source_id=channel_source_id, return_dict=False)
channel_id = channel.id
name = info['uploader']
channel_source_id = info['channel_id']
channel = get_or_create_channel(channel_source_id, download.url, name)
channel.dict() # get all attributes while we have the session.
# Resolve all entries.
info['entries'] = list(info['entries'])
if self.is_a_playlist(info):
result = self.upsert_playlist_videos(download, channel)
else:
result = self.upsert_channel_videos(download, info, channel)
if PYTEST:
self.manager.do_downloads_sync()
else:
self.manager.start_downloads()
return result
@staticmethod
def upsert_channel_videos(download: Download, info: dict, channel: Channel) -> DownloadResult:
"""Get a list of all videos in a Channel, schedule downloads for any missing videos."""
try:
update_channel(channel)
update_channel_catalog(channel, info)
domain = extract_domain(download.url)
missing_videos = find_all_missing_videos(channel.id)
with get_db_session(commit=True) as session:
for video_id, source_id, missing_video in missing_videos:
url = video_url_resolver(domain, missing_video)
if url in DOWNLOAD_MANAGER_CONFIG.skip_urls:
# Don't try to download skipped videos.
continue
# Schedule any missing videos for download.
download = self.manager.get_or_create_download(url, session)
download.downloader = 'video'
if PYTEST:
self.manager.do_downloads_sync()
else:
self.manager.start_downloads()
return DownloadResult(success=True, location=f'/videos/channel/{channel_id}/video')
downloads = []
for video_id, source_id, missing_video in missing_videos:
url = missing_video.get('webpage_url') or video_url_resolver(domain, missing_video)
downloads.append(url)
return DownloadResult(success=True, location=f'/videos/channel/{channel.id}/video', downloads=downloads)
except Exception:
logger.warning(f'Failed to update catalog of channel {download.url}')
location = f'/videos/channel/{channel_id}/video' if channel_id else None
location = f'/videos/channel/{channel.id}/video' if channel.id else None
return DownloadResult(success=False, location=location, error=str(traceback.format_exc()))
@staticmethod
def upsert_playlist_videos(download: Download, channel: Channel) -> DownloadResult:
"""Get a list of all videos in a playlist, schedule downloads for any missing videos."""
try:
# Playlists require more information to download.
info = extract_info(download.url, process=True)
# Get all Video.source_id of this Channel.
with get_db_session() as session:
existing_ids = [i for (i,) in session.query(Video.source_id).filter(Video.channel_id == channel.id)]
# 'id' is our 'source_id'
if any(i['id'] not in existing_ids for i in info['entries']):
# At least one video in the playlist is not in the Channel catalog, update the catalog.
channel_info = extract_info(channel.url, process=True)
update_channel_catalog(channel, channel_info)
with get_db_session() as session:
channel_video_urls = [i for (i,) in session.query(Video.url).filter(Video.channel_id == channel.id,
Video.url != None)]
skip_urls = set(DOWNLOAD_MANAGER_CONFIG.skip_urls)
# All videos in the channel catalog that have not been downloaded (most will not be in the playlist).
missing_source_ids = {source_id for _, source_id, _ in _find_all_missing_videos(channel.id)}
downloads = [i['webpage_url'] for i in info['entries'] if
i['id'] in missing_source_ids and i['webpage_url'] not in skip_urls]
# A video may be in a playlist, but not published in the channel catalog.
downloads.extend(i['webpage_url'] for i in info['entries'] if i['webpage_url'] not in channel_video_urls)
return DownloadResult(success=True, location=f'/videos/channel/{channel.id}/video', downloads=downloads)
except Exception:
logger.warning(f'Failed to update catalog of playlist {download.url}')
location = f'/videos/channel/{channel.id}/video' if channel.id else None
return DownloadResult(success=False, location=location, error=str(traceback.format_exc()))
@ -125,11 +175,14 @@ class VideoDownloader(Downloader, ABC):
def __repr__(self):
return f'<VideoDownloader>'
@optional_session
def already_downloaded(self, url: str, session: Session = None) -> Optional[Video]:
video = session.query(Video).filter_by(url=url).one_or_none()
return video
@classmethod
def valid_url(cls, url) -> Tuple[bool, Optional[dict]]:
"""
Match against all Youtube-DL Info Extractors, except those that match a Channel.
"""
"""Match against all Youtube-DL Info Extractors, except those that match a Channel."""
for ie in YDL._ies.values():
if ie.suitable(url) and not ChannelDownloader.valid_url(url)[0]:
try:
@ -307,25 +360,22 @@ def get_or_create_channel(source_id: str = None, url: str = None, name: str = No
return channel
def update_channel(channel: Channel):
def update_channel_catalog(channel: Channel, info: dict):
"""
Connect to the Channel's host website and pull a catalog of all videos. Insert any new videos into the DB.
It is expected that any missing videos will be downloaded later.
"""
logger.info(f'Downloading video list for {channel.name} at {channel.url} This may take several minutes.')
info = extract_info(channel.url)
if 'url' in info:
url = info['url']
info = extract_info(url)
# Resolve all entries to dictionaries.
entries = info['entries'] = list(info['entries'])
entries = info['entries']
# yt-dlp may hand back a list of URLs, lets use the "Uploads" URL, if available.
try:
entries[0]['id']
except Exception:
logger.warning('yt-dlp did not return a list of URLs')
for entry in entries:
if entry['title'] == 'Uploads':
logger.info('Youtube-DL gave back a list of URLs, found the "Uploads" URL and using it.')
@ -376,19 +426,9 @@ def update_channel(channel: Channel):
apply_info_json(channel_id)
def _find_all_missing_videos(channel_id: id = None) -> List[Tuple]:
"""Get all Video entries which don't have the required media files (i.e. hasn't been downloaded).
Restrict to a single channel if `channel_id` is provided.
"""
def _find_all_missing_videos(channel_id: id) -> List[Tuple]:
"""Get all Video entries which don't have the required media files (i.e. hasn't been downloaded)."""
with get_db_curs() as curs:
# Get all channels by default.
where = ''
params = ()
if channel_id:
where = 'AND channel_id = %s'
params = (channel_id,)
query = f'''
SELECT
video.id, video.source_id, video.channel_id
@ -399,11 +439,11 @@ def _find_all_missing_videos(channel_id: id = None) -> List[Tuple]:
channel.url IS NOT NULL
AND channel.url != ''
AND video.source_id IS NOT NULL
{where}
AND channel_id = %s
AND video.channel_id IS NOT NULL
AND (video_path IS NULL OR video_path = '' OR poster_path IS NULL OR poster_path = '')
'''
logger.debug(query)
params = (channel_id,)
curs.execute(query, params)
missing_videos = list(curs.fetchall())
return missing_videos
@ -415,50 +455,33 @@ def find_all_missing_videos(channel_id: int = None) -> Tuple[dict, dict]:
Yields a Channel Dict object, our Video id, and the "entry" of the video from the channel's info_json['entries'].
"""
with get_db_session() as session:
if channel_id:
channel = get_channel(channel_id=channel_id, return_dict=False)
if not channel.url:
raise ChannelURLEmpty('No URL for this channel')
channels = [channel, ]
else:
channels = session.query(Channel).filter(Channel.info_json != None).all() # noqa
channel: Channel = get_channel(channel_id=channel_id, return_dict=False)
if not channel.url:
raise ChannelURLEmpty('No URL for this channel')
# Get all channels while in the db context.
channels = list(channels)
# Check that the channel has some videos. We can't be sure what is missing if we don't know what we have.
if channel.refreshed is False:
# Refresh this channel's videos.
refresh_channel_videos(channel)
# Check that each channel has some videos. We can't be sure what is missing if we don't know what we have.
for channel in channels:
if channel.refreshed is False:
# Refresh this channel's videos.
refresh_channel_videos(channel)
channels = {i.id: i for i in channels}
match_regexen = {i: re.compile(j.match_regex) for i, j in channels.items() if j.match_regex}
match_regex = re.compile(channel.match_regex) if channel.match_regex else None
# Convert the channel video entries into a form that allows them to be quickly retrieved without searching through
# the entire entries list.
channels_entries = {}
for channel_id_, channel in channels.items():
channels_entries[channel_id_] = {i['id']: i for i in channel.info_json['entries']}
channel_entries = {i['id']: i for i in channel.info_json['entries']}
# Yield all videos not skipped.
missing_videos = _find_all_missing_videos(channel_id)
for video_id, source_id, channel_id in missing_videos:
channel = channels[channel_id]
if channel.skip_download_videos and source_id in channel.skip_download_videos:
# This video has been marked to skip.
continue
try:
missing_video = channels_entries[channel_id][source_id]
missing_video = channel_entries[source_id]
except KeyError:
logger.warning(f'Video {channel.name} / {source_id} is not in {channel.name} info_json')
continue
match_regex: re.compile = match_regexen.get(channel_id)
if not match_regex or (match_regex and missing_video['title'] and match_regex.match(missing_video['title'])):
# No title match regex, or the title matches the regex.
yield video_id, source_id, missing_video

View file

@ -153,14 +153,7 @@ def validate_videos():
with get_db_session(commit=True) as session:
videos = session.query(Video).filter(Video.id.in_(chunk)).all()
for video in videos:
try:
channel_generate_poster = channel_generate_posters.get(video.channel_id)
validate_video(video, channel_generate_poster)
# All data about the Video has been found, we should not attempt to validate it again.
video.validated = True
except Exception as e:
# This video failed to validate, continue validation for the rest of the videos.
logger.warning(f'Failed to validate {video}', exc_info=e)
video.validate()
def validate_video(video: Video, channel_generate_poster: bool):
@ -605,7 +598,7 @@ YDL.add_default_info_extractors()
def get_channel_source_id(url: str) -> str:
channel_info = YDL.extract_info(url, download=False, process=False)
return channel_info.get('uploader_id') or channel_info['id']
return channel_info.get('uploader_id') or channel_info['channel_id']
async def get_statistics():
@ -747,15 +740,7 @@ def upsert_video(session: Session, video_path: pathlib.Path, channel: Channel =
session.flush()
session.refresh(video)
try:
# Fill in any missing data. Generate poster if enabled and necessary.
validate_video(video, channel.generate_posters if channel else False)
# All data about the Video has been found, we should not attempt to validate it again.
video.validated = True
except Exception as e:
# Could not validate, this could be an issue with a file. This should not prevent the video from being
# inserted.
logger.warning(f'Failed to validate {video}', exc_info=e)
video.validate()
session.flush()

View file

@ -55,8 +55,8 @@ class Video(ModelHelper, Base):
video_path = self.video_path
if self.video_path and isinstance(self.video_path, MediaPath):
video_path = self.video_path.path.relative_to(get_media_directory())
return f'<Video id={self.id} title={self.title} path={video_path} channel={self.channel_id} ' \
f'source_id={self.source_id}>'
return f'<Video id={self.id} title={repr(self.title)} path={video_path} channel={self.channel_id} ' \
f'source_id={repr(self.source_id)}>'
def dict(self) -> dict:
d = super().dict()
@ -255,6 +255,29 @@ class Video(ModelHelper, Base):
)
return d
def validate(self):
"""Perform a validation of this video and it's files. Mark this video as validated if no errors occur."""
if not self.video_path:
# Can't validate if there is no video file.
return False
from .lib import validate_video
try:
validate_video(self, self.channel.generate_posters if self.channel else False)
self.validated = True
except Exception as e:
logger.warning(f'Failed to validate video {self}', exc_info=e)
return self.validated
def check_for_corruption(self):
"""Uses ffprobe to check if this video is corrupt."""
if not self.video_path:
return
from .lib import check_for_video_corruption
return check_for_video_corruption(self.video_path.path)
class Channel(ModelHelper, Base):
__tablename__ = 'channel'
@ -279,6 +302,11 @@ class Channel(ModelHelper, Base):
def __repr__(self):
return f'<Channel id={self.id}, name={repr(self.name)}>'
def __eq__(self, other):
if isinstance(other, Channel):
return self.id == other.id
return False
def add_video_to_skip_list(self, source_id: str):
if not source_id:
raise UnknownVideo(f'Cannot skip video with empty source id: {source_id}')
@ -317,12 +345,13 @@ class Channel(ModelHelper, Base):
download.frequency = self.download_frequency
download.url = self.url
# Keep next_download if available.
download.next_download = download.next_download or download_manager.get_next_download(download, session)
download.next_download = download.next_download or download_manager.calculate_next_download(download,
session)
elif not download and self.download_frequency and self.url:
download = Download(frequency=self.download_frequency, url=self.url, downloader='video_channel')
session.add(download)
session.flush()
download.next_download = download_manager.get_next_download(download, session)
download.next_download = download_manager.calculate_next_download(download, session)
session.flush()
def config_view(self) -> dict:

View file

@ -9,10 +9,10 @@ from yt_dlp.utils import UnsupportedError
from modules.videos.channel.lib import download_channel
from modules.videos.downloader import find_all_missing_videos, VideoDownloader, \
ChannelDownloader, get_or_create_channel
ChannelDownloader, get_or_create_channel, channel_downloader
from modules.videos.models import Channel, Video
from wrolpi.db import get_db_context
from wrolpi.downloader import DownloadManager, Download
from wrolpi.downloader import DownloadManager, Download, DownloadResult
from wrolpi.errors import InvalidDownload
from wrolpi.test.common import TestAPI
from wrolpi.test.test_downloader import HTTPDownloader
@ -20,7 +20,7 @@ from wrolpi.vars import PROJECT_DIR
def test_find_all_missing_videos(test_session, channel_factory, video_factory):
channel1, channel2 = channel_factory(url='some url'), channel_factory(url='some other url')
channel1 = channel_factory(url='some url')
channel1.info_json = {'entries': [{'id': 'foo', 'view_count': 0}]}
test_session.commit()
@ -29,14 +29,14 @@ def test_find_all_missing_videos(test_session, channel_factory, video_factory):
video_factory()
# No missing videos
assert [] == list(find_all_missing_videos())
assert [] == list(find_all_missing_videos(channel1.id))
# Create a video that has no video file.
video = Video(title='needs to be downloaded', channel_id=channel1.id, source_id='foo')
test_session.add(video)
test_session.commit()
missing = list(find_all_missing_videos())
missing = list(find_all_missing_videos(channel1.id))
assert len(missing) == 1
# The video returned is the one we faked.
@ -73,6 +73,7 @@ example_video_json = {
example_channel_json = {
'_type': 'playlist',
'channel_id': 'some id',
'entries': [
{'_type': 'url',
'description': None,
@ -82,7 +83,8 @@ example_channel_json = {
'title': 'video 1 title',
'uploader': None,
'url': 'video_1_url',
'view_count': 58504},
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_1_url'},
{'_type': 'url',
'description': None,
'duration': None,
@ -91,12 +93,14 @@ example_channel_json = {
'title': 'video 2 title',
'uploader': None,
'url': 'video_2_url',
'view_count': 1413},
'view_count': 1413,
'webpage_url': 'https://youtube.com/watch?v=video_2_url'},
],
'extractor': 'youtube:tab',
'extractor_key': 'YoutubeTab',
'id': 'some id',
'title': 'channel title',
'uploader': 'the uploader',
'webpage_url': 'channel url',
'webpage_url_basename': 'videos',
}
@ -385,3 +389,93 @@ def test_download_result(test_session, test_directory, video_download_manager, m
download: Download = test_session.query(Download).one()
assert download.url == 'https://example.com'
assert download.location == '/videos/channel/1/video/1'
example_playlist_json = {
'_type': 'playlist',
'availability': None,
'channel': 'the channel name',
'channel_follower_count': None,
'channel_id': 'the channel id',
'channel_url': 'channel url',
'description': '',
'entries': [
{'_type': 'url',
'description': None,
'duration': None,
'id': 'video 2 id',
'ie_key': 'Youtube',
'title': 'video 2 title',
'uploader': None,
'url': 'video_2_url',
'view_count': 1413,
'webpage_url': 'https://youtube.com/watch?v=video_2_url'},
{'_type': 'url',
'description': None,
'duration': None,
'id': 'video 1 id',
'ie_key': 'Youtube',
'title': 'video 1 title',
'uploader': None,
'url': 'video_1_url',
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_1_url'},
{'_type': 'url',
'description': None,
'duration': None,
'id': 'video 3 id',
'ie_key': 'Youtube',
'title': 'video 3 title',
'uploader': None,
'url': 'video_3_url',
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_3_url'},
],
'extractor': 'youtube:tab',
'extractor_key': 'YoutubeTab',
'id': 'the playlist id',
'modified_date': '20220426',
'original_url': 'original url',
'playlist_count': 10,
'requested_entries': None,
'tags': [],
'title': 'some title',
'uploader': 'Playlist Uploader',
'uploader_id': 'uploader id',
'uploader_url': 'uploader url',
'view_count': 22298,
'webpage_url': 'webpage url',
'webpage_url_basename': 'playlist',
'webpage_url_domain': 'youtube.com',
}
def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager):
"""
All videos in a playlist can be downloaded for it's Channel.
"""
download = Download(url='playlist url')
test_session.add(download)
channel = get_or_create_channel(example_playlist_json['channel_id'], download.url, example_channel_json['uploader'])
test_session.add(Video(url='https://youtube.com/watch?v=video_1_url',
source_id='video 1 id', channel_id=channel.id, video_path='video exists',
poster_path='poster exists'))
test_session.commit()
mock_video_extract_info.side_effect = [
example_playlist_json, # Playlist info is fetched first.
example_playlist_json, # Playlist info is fetched again for more details.
example_channel_json, # Video 3 causes channel catalog to be fetched.
example_video_json,
example_video_json,
example_video_json,
]
with mock.patch('modules.videos.downloader.VideoDownloader.do_download') as mock_video_do_download:
mock_video_do_download.return_value = DownloadResult(success=True) # Don't download the videos.
result = channel_downloader.do_download(download)
assert result.success is True, 'Download was not successful'
assert set(result.downloads) == {
'https://youtube.com/watch?v=video_2_url',
'https://youtube.com/watch?v=video_3_url',
}