mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-26 09:56:17 -05:00
Videos display comments. User can download comments using Refresh button.
This commit is contained in:
parent
ea4d640100
commit
f865d9fb0f
7 changed files with 270 additions and 14 deletions
|
|
@ -2,6 +2,7 @@
|
|||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import tempfile
|
||||
import traceback
|
||||
from abc import ABC
|
||||
from typing import Tuple, List, Dict
|
||||
|
|
@ -19,7 +20,7 @@ from wrolpi.db import get_db_session
|
|||
from wrolpi.db import optional_session
|
||||
from wrolpi.downloader import Downloader, Download, DownloadResult
|
||||
from wrolpi.errors import UnrecoverableDownloadError
|
||||
from wrolpi.files.lib import glob_shared_stem
|
||||
from wrolpi.files.lib import glob_shared_stem, split_path_stem_and_suffix
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.vars import PYTEST
|
||||
from .channel.lib import create_channel, get_channel
|
||||
|
|
@ -27,8 +28,8 @@ from .common import get_no_channel_directory, get_videos_directory, update_view_
|
|||
from .errors import UnknownChannel
|
||||
from .lib import get_downloader_config
|
||||
from .models import Video, Channel
|
||||
from .schema import ChannelPostRequest
|
||||
from .normalize_video_url import normalize_video_url
|
||||
from .schema import ChannelPostRequest
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
ydl_logger = logger.getChild('youtube-dl')
|
||||
|
|
@ -283,6 +284,10 @@ class VideoDownloader(Downloader, ABC):
|
|||
|
||||
logs = None # noqa
|
||||
try:
|
||||
if settings.get('do_not_download'):
|
||||
# User has requested refresh of video metadata, skip the rest of the video downloader.
|
||||
return await self.download_info_json(download)
|
||||
|
||||
video_path, entry = self.prepare_filename(url, out_dir)
|
||||
# Do the real download.
|
||||
file_name_format = '%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s'
|
||||
|
|
@ -303,6 +308,9 @@ class VideoDownloader(Downloader, ABC):
|
|||
'-o', file_name_format,
|
||||
'--no-cache-dir',
|
||||
'--compat-options', 'no-live-chat',
|
||||
# Get top 20 comments.
|
||||
'--write-comments',
|
||||
'--extractor-args', 'youtube:max_comments=20,all,10;comment_sort=top',
|
||||
# Use experimental feature to merge files.
|
||||
'--ppa', 'Merger+ffmpeg_o1:-strict -2',
|
||||
url,
|
||||
|
|
@ -438,6 +446,113 @@ class VideoDownloader(Downloader, ABC):
|
|||
logger.debug(f'Downloading {url} to {out_dir}')
|
||||
return final_filename, entry
|
||||
|
||||
async def download_info_json(self, download: Download) -> DownloadResult:
|
||||
"""User has requested to refresh Video metadata. Download only metadata files to temporary directory.
|
||||
Replace existing metadata files only after successful download."""
|
||||
url = download.url
|
||||
|
||||
# Download metadata files into temporary directory so yt-dlp always downloads the latest files.
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
tmp_dir = pathlib.Path(tmp_dir)
|
||||
|
||||
# Download the metadata files, but skip the video file.
|
||||
file_name_format = '%(uploader)s_%(upload_date)s_%(id)s_%(title)s.%(ext)s'
|
||||
cmd = (
|
||||
str(YT_DLP_BIN),
|
||||
'-f', PREFERRED_VIDEO_FORMAT,
|
||||
'--skip-download', # SKIP THE VIDEO FILE.
|
||||
'--match-filter', '!is_live', # Do not attempt to download Live videos.
|
||||
'--write-info-json',
|
||||
'--merge-output-format', PREFERRED_VIDEO_EXTENSION,
|
||||
'--remux-video', PREFERRED_VIDEO_EXTENSION,
|
||||
'-o', file_name_format,
|
||||
'--no-cache-dir',
|
||||
'--compat-options', 'no-live-chat',
|
||||
# Get top 20 comments, 10 replies per parent.
|
||||
'--write-comments',
|
||||
'--extractor-args', 'youtube:max_comments=all,20,all,10;comment_sort=top',
|
||||
url,
|
||||
)
|
||||
return_code, logs, _ = await self.process_runner(url, cmd, tmp_dir)
|
||||
|
||||
stderr = logs['stderr'].decode() if hasattr(logs['stderr'], 'decode') else logs['stderr']
|
||||
stdout = logs['stdout'].decode() if hasattr(logs['stdout'], 'decode') else logs['stdout']
|
||||
|
||||
if return_code != 0:
|
||||
error = f'{stdout}\n\n\n{stderr}\n\nvideo info json downloader process exited with {return_code}'
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error=error,
|
||||
)
|
||||
|
||||
# Find the info json file in the temporary directory.
|
||||
info_json_paths = [i for i in tmp_dir.iterdir() if i.name.endswith('.info.json') and i.stat().st_size]
|
||||
if len(info_json_paths) == 0:
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error='No info json file was downloaded.'
|
||||
)
|
||||
elif len(info_json_paths) > 1:
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error='More than one info json file was downloaded.'
|
||||
)
|
||||
|
||||
info_json_path = info_json_paths[0]
|
||||
|
||||
if not info_json_path.stat().st_size:
|
||||
return DownloadResult(
|
||||
success=False,
|
||||
error='Video info json file was empty',
|
||||
)
|
||||
|
||||
# Reformat new info json file for human reading.
|
||||
format_json_file(info_json_path)
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Find the existing video, replace its info json.
|
||||
video = Video.get_by_url(url, session)
|
||||
video_id = video.id
|
||||
channel_id = video.channel_id
|
||||
|
||||
if video.info_json_path and video.info_json_path.is_file():
|
||||
# Move old file temporarily. Only delete old data if the swap is successful.
|
||||
logger.debug(f'Replacing info json file: {video.info_json_path}')
|
||||
tmp_info_json_path = pathlib.Path(f'{video.info_json_path}.tmp')
|
||||
if tmp_info_json_path.is_file():
|
||||
if video.info_json_path.stat().st_size:
|
||||
tmp_info_json_path.unlink()
|
||||
else:
|
||||
raise UnrecoverableDownloadError(
|
||||
f'Temporary info json file already exists: {tmp_info_json_path}')
|
||||
|
||||
# Move existing info json file to a temporary location. Move it back if this fails.
|
||||
video.info_json_path.rename(tmp_info_json_path)
|
||||
try:
|
||||
video.info_json_path.write_text(info_json_path.read_text())
|
||||
tmp_info_json_path.unlink()
|
||||
except Exception as e:
|
||||
logger.error('Failed to swap video info json file', exc_info=e)
|
||||
tmp_info_json_path.rename(video.info_json_path)
|
||||
raise
|
||||
else:
|
||||
# info json file does not exist, write one next to the video.
|
||||
video_path = video.video_path
|
||||
stem, _ = split_path_stem_and_suffix(video_path)
|
||||
new_info_json_path = pathlib.Path(f'{stem}.info.json')
|
||||
new_info_json_path.write_text(info_json_path.read_text())
|
||||
video.file_group.append_files(new_info_json_path)
|
||||
|
||||
if channel_id:
|
||||
location = f'/videos/channel/{channel_id}/video/{video_id}'
|
||||
else:
|
||||
location = f'/videos/video/{video_id}'
|
||||
|
||||
logger.debug(f'Downloaded video info json {location=}')
|
||||
logger.info(f'Successfully downloaded video info json {url} {video}')
|
||||
|
||||
return DownloadResult(success=True, location=location)
|
||||
|
||||
|
||||
channel_downloader = ChannelDownloader()
|
||||
# Videos may match the ChannelDownloader, give it a higher priority.
|
||||
|
|
|
|||
|
|
@ -60,6 +60,8 @@ class Video(ModelHelper, Base):
|
|||
except Exception as e:
|
||||
logger.error(f'{self} ffprobe_json is invalid', exc_info=e)
|
||||
|
||||
info_json = self.get_info_json() or dict()
|
||||
|
||||
# Put live data in "video" instead of "data" to avoid confusion on the frontend.
|
||||
d['video'] = dict(
|
||||
caption=self.file_group.d_text,
|
||||
|
|
@ -68,6 +70,7 @@ class Video(ModelHelper, Base):
|
|||
channel_id=self.channel_id,
|
||||
codec_names=codec_names,
|
||||
codec_types=codec_types,
|
||||
comments=info_json.get('comments'),
|
||||
description=self.file_group.c_text or self.get_video_description(),
|
||||
id=self.id,
|
||||
info_json_file=self.info_json_file,
|
||||
|
|
@ -304,6 +307,14 @@ class Video(ModelHelper, Base):
|
|||
.filter(FileGroup.primary_path == path).one_or_none()
|
||||
return video
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_by_url(url: str, session: Session) -> Optional['Video']:
|
||||
video = session.query(Video) \
|
||||
.join(FileGroup, FileGroup.id == Video.file_group_id) \
|
||||
.filter(FileGroup.url == url).one_or_none()
|
||||
return video
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_by_id(id_: int, session: Session = None) -> Optional['Video']:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue