Returning all urls from a playlist, unless they're already downloaded. Changing all which() calls to contain BIN for clarity.

This commit is contained in:
Roland 2022-06-28 10:09:35 -06:00
parent 01c7f0716b
commit c772b57ddb
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
8 changed files with 58 additions and 77 deletions

View file

@ -146,10 +146,10 @@ def request_archive(url: str):
return singlefile, readability, screenshot
SINGLE_FILE_PATH = which('single-file',
SINGLE_FILE_BIN = which('single-file',
'/usr/bin/single-file', # rpi ubuntu
'/usr/local/bin/single-file', # debian
warn=True)
warn=True)
CHROMIUM = which('chromium-browser', 'chromium',
'/usr/bin/chromium-browser', # rpi ubuntu
'/usr/bin/chromium', # debian
@ -159,10 +159,10 @@ CHROMIUM = which('chromium-browser', 'chromium',
def local_singlefile(url: str):
"""Run the single-file executable to create an HTML file archive."""
if not SINGLE_FILE_PATH.is_file():
if not SINGLE_FILE_BIN.is_file():
raise FileNotFoundError(f'single-file not found')
cmd = (str(SINGLE_FILE_PATH),
cmd = (str(SINGLE_FILE_BIN),
url,
'--browser-executable-path', CHROMIUM,
'--browser-args', '["--no-sandbox"]',
@ -193,19 +193,19 @@ def local_screenshot(url: str) -> bytes:
return png
READABILITY_PATH = which('readability-extractor',
READABILITY_BIN = which('readability-extractor',
'/usr/bin/readability-extractor', # rpi ubuntu
'/usr/local/bin/readability-extractor', # debian
warn=True)
warn=True)
def local_extract_readability(path: str, url: str) -> dict:
"""Extract the readability from an HTML file, typically from single-file."""
logger.info(f'readability for {url}')
if not READABILITY_PATH.is_file():
if not READABILITY_BIN.is_file():
raise FileNotFoundError(f'Readability extractor not found')
cmd = (READABILITY_PATH, path, url)
cmd = (READABILITY_BIN, path, url)
logger.debug(f'readability cmd: {cmd}')
output = subprocess.check_output(cmd, timeout=60 * 3)
output = json.loads(output)

View file

@ -91,12 +91,12 @@ def split_file_name(path: Path) -> List[str]:
return words
FILE_PATH = which('file', '/usr/bin/file')
FILE_BIN = which('file', '/usr/bin/file')
def get_mimetype(path: Path) -> str:
"""Get the mimetype using the builtin `file` command."""
cmd = (FILE_PATH, '--mime-type', str(path.absolute()))
cmd = (FILE_BIN, '--mime-type', str(path.absolute()))
output = subprocess.check_output(cmd)
output = output.decode()
mimetype = output.split(' ')[-1].strip()

View file

@ -125,7 +125,7 @@ async def import_files(files: List[str]):
IMPORT_EVENT.clear()
BASH = which('bash', '/bin/bash', warn=True)
BASH_BIN = which('bash', '/bin/bash', warn=True)
async def import_file(path: Path):
@ -143,7 +143,7 @@ async def import_file(path: Path):
else:
raise ValueError(f'Cannot import unknown file! {path}')
cmd = f'{BASH} {PROJECT_DIR}/scripts/import_map.sh {path.absolute()}'
cmd = f'{BASH_BIN} {PROJECT_DIR}/scripts/import_map.sh {path.absolute()}'
logger.debug(f'Running import script: {cmd}')
start = now()
proc = await asyncio.create_subprocess_shell(cmd, stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE)

View file

@ -9,7 +9,7 @@ from typing import Tuple, List, Optional
import yt_dlp.utils
from sqlalchemy.orm import Session
from yt_dlp import YoutubeDL
from yt_dlp.extractor import YoutubeTabIE
from yt_dlp.extractor import YoutubeTabIE # noqa
from yt_dlp.utils import UnsupportedError, DownloadError
from wrolpi.cmd import which
@ -17,7 +17,7 @@ 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.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnknownChannel, ChannelURLEmpty, UnrecoverableDownloadError
from wrolpi.vars import PYTEST
from .channel.lib import create_channel, get_channel
@ -84,13 +84,18 @@ class ChannelDownloader(Downloader, ABC):
def do_download(self, download: Download) -> DownloadResult:
"""Update a Channel's catalog, then schedule downloads of every missing video."""
info = extract_info(download.url, process=False)
# Resolve the entries generator.
info['entries'] = list(info['entries'])
download.info_json = info
download.sub_downloader = video_downloader.name
if session := Session.object_session(download):
# May not have a session during testing.
session.commit()
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 the entries generator.
info['entries'] = list(info['entries'])
if self.is_a_playlist(info):
result = self.upsert_playlist_videos(download, channel)
@ -126,32 +131,10 @@ class ChannelDownloader(Downloader, ABC):
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)
# Resolve the entries generator.
info['entries'] = list(info['entries'])
# 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)
# Get all videos in the playlist
downloads = [i['url'] for i in download.info_json['entries']]
# Only download those that have not yet been downloaded.
downloads = [i for i in downloads if not video_downloader.already_downloaded(i)]
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}')
@ -179,7 +162,11 @@ class VideoDownloader(Downloader, ABC):
@optional_session
def already_downloaded(self, url: str, session: Session = None) -> Optional[Video]:
video = session.query(Video).filter_by(url=url).one_or_none()
# We only consider a video record with a video file as "downloaded".
video = session.query(Video).filter(
Video.url == url,
Video.video_path != None,
).one_or_none()
return video
@classmethod
@ -244,6 +231,7 @@ class VideoDownloader(Downloader, ABC):
'--write-info-json',
'--merge-output-format', PREFERRED_VIDEO_EXTENSION,
'-o', file_name_format,
'--no-cache-dir',
url,
)
return_code, logs = self.process_runner(url, cmd, out_dir)

View file

@ -408,7 +408,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 2 title',
'uploader': None,
'url': 'video_2_url',
'url': 'https://youtube.com/watch?v=video_2_url',
'view_count': 1413,
'webpage_url': 'https://youtube.com/watch?v=video_2_url'},
{'_type': 'url',
@ -418,7 +418,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 1 title',
'uploader': None,
'url': 'video_1_url',
'url': 'https://youtube.com/watch?v=video_1_url',
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_1_url'},
{'_type': 'url',
@ -428,7 +428,7 @@ example_playlist_json = {
'ie_key': 'Youtube',
'title': 'video 3 title',
'uploader': None,
'url': 'video_3_url',
'url': 'https://youtube.com/watch?v=video_3_url',
'view_count': 58504,
'webpage_url': 'https://youtube.com/watch?v=video_3_url'},
],
@ -463,14 +463,7 @@ def test_download_playlist(test_session, test_directory, mock_video_extract_info
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,
]
mock_video_extract_info.return_value = example_playlist_json # Playlist info is fetched first.
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.