Searching wrolpi user's home directory for browser profiles.

This commit is contained in:
Roland 2025-04-17 17:02:39 -06:00
parent d8ccebf9bb
commit 00c86e1a1a
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
22 changed files with 472 additions and 138 deletions

View file

@ -565,7 +565,7 @@ async def html_to_readability(html: str | bytes, url: str, timeout: int = 120):
READABILITY_BIN, singlefile_file.name, shlex.quote(url))
# Docker containers may not have this directory. But, this directory is necessary on RPi.
cwd = '/home/wrolpi' if os.path.isdir('/home/wrolpi') else None
result = await run_command(cmd, cwd=cwd, timeout=timeout, debug=True)
result = await run_command(cmd, cwd=cwd, timeout=timeout)
logger.debug(f'readability for {url} exited with {result.return_code}')
stdout, stderr = result.stdout.decode(), result.stderr.decode()

View file

@ -193,7 +193,6 @@ async def run_import_command(*paths: Path):
cmd = (SUDO_BIN, f'{PROJECT_DIR}/scripts/import_map.sh', *paths)
result = await run_command(
cmd,
debug=True,
timeout=0, # No timeout, map importing could take days.
)

View file

@ -66,3 +66,9 @@ async def post_file_format(_: Request, body: schema.VideoFileFormatRequest):
error=str(e),
video_file_format=body.video_file_format,
), status=HTTPStatus.BAD_REQUEST)
@content_bp.get('/browser-profiles')
async def get_browser_profiles(_: Request):
browser_profiles = lib.get_browser_profiles()
return json_response(browser_profiles)

View file

@ -32,7 +32,7 @@ from .channel.lib import create_channel, get_channel
from .common import get_no_channel_directory, update_view_counts_and_censored, \
ffmpeg_video_complete
from .errors import UnknownChannel
from .lib import get_videos_downloader_config, YDL, ydl_logger, format_videos_destination
from .lib import get_videos_downloader_config, YDL, ydl_logger, format_videos_destination, browser_profile_to_yt_dlp_arg
from .models import Video, Channel
from .normalize_video_url import normalize_video_url
from .schema import ChannelPostRequest
@ -45,7 +45,7 @@ VIDEO_RESOLUTION_MAP = {
'480p': ['135+bestaudio', '231+bestaudio', '135+139', 'mp4-480p', 'res:480'],
'720p': [
'298+bestaudio', '232+bestaudio', # 720@60 avc1 + best audio
'136+bestaudio', '22', 'res:720'],
'136+bestaudio', '22', '311+bestaudio', 'res:720'],
'1080p': [
'299+bestaudio', '312+bestaudio', '270+bestaudio', # 1080@60 avc1 + best audio
'137+bestaudio', '614+bestaudio', 'res:1080'],
@ -328,7 +328,6 @@ class VideoDownloader(Downloader, ABC):
if download.attempts >= 10:
raise UnrecoverableDownloadError('Max download attempts reached')
download_id = download.id
url = normalize_video_url(download.url)
# Copy settings into Download (they may be from the ChannelDownloader)
@ -395,19 +394,13 @@ class VideoDownloader(Downloader, ABC):
# User has requested refresh of video metadata, skip the rest of the video downloader.
return await self.download_info_json(download, video_path)
# Do the real download.
cmd = (
str(YT_DLP_BIN),
'-c', # Continue downloads
'-f', video_resolutions,
'--match-filter', '!is_live', # Do not attempt to download Live videos.
'--write-subs',
'--write-auto-subs',
'--sub-format', DEFAULT_CAPTION_FORMAT,
'--convert-subs', DEFAULT_CAPTION_FORMAT,
'--convert-thumbnails', DEFAULT_POSTER_FORMAT,
'--write-thumbnail',
'--write-info-json',
'--merge-output-format', video_format,
# '--remux-video', video_format,
'--no-cache-dir',
@ -417,10 +410,32 @@ 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,
)
result = await self.process_runner(download, cmd, out_dir)
if config.continue_dl:
cmd = (*cmd, '--continue')
if config.writesubtitles:
cmd = (*cmd, '--write-subs', '--write-auto-subs')
if config.writethumbnail:
cmd = (*cmd, '--write-thumbnail')
if config.writeinfojson:
cmd = (*cmd, '--write-info-json')
if config.yt_dlp_extra_args:
cmd = (*cmd, *config.yt_dlp_extra_args.split(' '))
if config.browser_profile and (config.always_use_browser_profile or settings.get('use_browser_profile')):
browser_profile = pathlib.Path(config.browser_profile)
if browser_profile.exists():
browser_profile = browser_profile_to_yt_dlp_arg(browser_profile)
cmd = (*cmd, '--cookies-from-browser', browser_profile)
else:
logger.error(f'Browser profile {config.browser_profile} does not exist')
# Add destination and the video's URL to the command.
cmd = (*cmd,
'-o', video_path,
url,
)
# Do the real download.
result = await self.process_runner(download, cmd, out_dir, debug=True)
stdout = result.stdout.decode()
stderr = result.stderr.decode()

View file

@ -24,7 +24,7 @@ from wrolpi.errors import UnknownDirectory
from wrolpi.events import Events
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 wrolpi.vars import YTDLP_CACHE_DIR, PYTEST, WROLPI_HOME
from .common import is_valid_poster, convert_image, \
generate_video_poster, ConfigError, \
extract_video_duration
@ -380,6 +380,9 @@ class VideoDownloaderConfigValidator:
video_resolutions: List[str] = field(default_factory=lambda: ['1080p', '720p', '480p', 'maximum'])
version: int = None
yt_dlp_options: VideoDownloaderConfigYtDlpOptionsValidator = field(default_factory=dict)
yt_dlp_extra_args: str = ''
always_use_browser_profile: bool = False
browser_profile: str = ''
def __post_init__(self):
allowed_fields = {i.name for i in dataclasses.fields(VideoDownloaderConfigYtDlpOptionsValidator)}
@ -405,6 +408,9 @@ class VideoDownloaderConfig(ConfigFile):
writethumbnail=True,
youtube_include_dash_manifest=False,
),
yt_dlp_extra_args='',
always_use_browser_profile=False,
browser_profile='',
)
validator = VideoDownloaderConfigValidator
@ -464,6 +470,30 @@ class VideoDownloaderConfig(ConfigFile):
def yt_dlp_options(self, value: dict):
self.update({'yt_dlp_options': value})
@property
def yt_dlp_extra_args(self) -> str:
return self._config['yt_dlp_extra_args']
@yt_dlp_extra_args.setter
def yt_dlp_extra_args(self, value: str):
self.update({**self._config, 'yt_dlp_extra_args': value})
@property
def browser_profile(self) -> str:
return self._config['browser_profile']
@browser_profile.setter
def browser_profile(self, value: str):
self.update({**self._config, 'browser_profile': value})
@property
def always_use_browser_profile(self) -> bool:
return self._config['always_use_browser_profile']
@always_use_browser_profile.setter
def always_use_browser_profile(self, value: bool):
self.update({**self._config, 'always_use_browser_profile': value})
def import_config(self, file: pathlib.Path = None, send_events=False):
super().import_config(file, send_events)
self.successful_import = True
@ -595,53 +625,48 @@ def get_channel_source_id(url: str) -> str:
async def get_statistics():
with get_db_curs() as curs:
curs.execute('''
SELECT
-- total videos
COUNT(v.id) AS "videos",
-- total videos downloaded over the past week/month/year
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 week') AS "week",
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 month') AS "month",
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 year') AS "year",
-- sum of all video lengths in seconds
COALESCE(SUM(fg.length), 0) AS "sum_duration",
-- sum of all video file sizes
COALESCE(SUM(fg.size), 0)::BIGINT AS "sum_size",
-- largest video
COALESCE(MAX(fg.size), 0) AS "max_size",
-- Videos may or may not have comments.
COUNT(v.id) FILTER ( WHERE v.have_comments = TRUE ) AS "have_comments",
COUNT(v.id) FILTER ( WHERE v.have_comments = FALSE AND v.comments_failed = FALSE
and fg.censored = false and fg.url is not null) AS "missing_comments",
COUNT(v.id) FILTER ( WHERE v.comments_failed = TRUE ) AS "failed_comments",
COUNT(v.id) FILTER ( WHERE fg.censored = TRUE ) as "censored_videos"
FROM
video v
LEFT JOIN file_group fg on v.file_group_id = fg.id
''')
SELECT
-- total videos
COUNT(v.id) AS "videos",
-- total videos downloaded over the past week/month/year
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 week') AS "week",
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 month') AS "month",
COUNT(v.id) FILTER (WHERE published_datetime >= current_date - interval '1 year') AS "year",
-- sum of all video lengths in seconds
COALESCE(SUM(fg.length), 0) AS "sum_duration",
-- sum of all video file sizes
COALESCE(SUM(fg.size), 0)::BIGINT AS "sum_size",
-- largest video
COALESCE(MAX(fg.size), 0) AS "max_size",
-- Videos may or may not have comments.
COUNT(v.id) FILTER ( WHERE v.have_comments = TRUE ) AS "have_comments",
COUNT(v.id) FILTER ( WHERE v.have_comments = FALSE AND v.comments_failed = FALSE
and fg.censored = false and
fg.url is not null) AS "missing_comments",
COUNT(v.id) FILTER ( WHERE v.comments_failed = TRUE ) AS "failed_comments",
COUNT(v.id) FILTER ( WHERE fg.censored = TRUE ) as "censored_videos"
FROM video v
LEFT JOIN file_group fg on v.file_group_id = fg.id
''')
video_stats = dict(curs.fetchone())
# Get the total videos downloaded every month for the past two years.
curs.execute('''
SELECT
DATE_TRUNC('month', months.a),
COUNT(video.id)::BIGINT,
SUM(size)::BIGINT AS "size"
FROM
generate_series(
date_trunc('month', current_date) - interval '2 years',
date_trunc('month', current_date) - interval '1 month',
'1 month'::interval) AS months(a),
video
LEFT JOIN file_group fg on video.file_group_id = fg.id
WHERE
published_datetime >= date_trunc('month', months.a)
AND published_datetime < date_trunc('month', months.a) + interval '1 month'
AND published_datetime IS NOT NULL
GROUP BY
1
ORDER BY
1
''')
SELECT DATE_TRUNC('month', months.a),
COUNT(video.id)::BIGINT,
SUM(size)::BIGINT AS "size"
FROM generate_series(
date_trunc('month', current_date) - interval '2 years',
date_trunc('month', current_date) - interval '1 month',
'1 month'::interval) AS months(a),
video
LEFT JOIN file_group fg on video.file_group_id = fg.id
WHERE published_datetime >= date_trunc('month', months.a)
AND published_datetime < date_trunc('month', months.a) + interval '1 month'
AND published_datetime IS NOT NULL
GROUP BY 1
ORDER BY 1
''')
monthly_videos = [dict(i) for i in curs.fetchall()]
historical_stats = dict(monthly_videos=monthly_videos)
@ -651,13 +676,11 @@ async def get_statistics():
if monthly_videos else 0
curs.execute('''
SELECT
COUNT(c.id) AS "channels",
COUNT(c.id) FILTER ( WHERE c.tag_id IS NOT NULL ) AS "tagged_channels"
FROM
channel c
LEFT JOIN public.tag t on t.id = c.tag_id
''')
SELECT COUNT(c.id) AS "channels",
COUNT(c.id) FILTER ( WHERE c.tag_id IS NOT NULL ) AS "tagged_channels"
FROM channel c
LEFT JOIN public.tag t on t.id = c.tag_id
''')
channel_stats = dict(curs.fetchone())
ret = dict(statistics=dict(
videos=video_stats,
@ -766,3 +789,41 @@ def format_videos_destination(channel_name: str = None, channel_tag: str = None,
videos_destination = get_media_directory() / videos_destination.lstrip('/')
return videos_destination
def get_browser_profiles(home: pathlib.Path = WROLPI_HOME) -> dict:
"""Searches the provided home directory for Chromium and Firefox profiles."""
logger.debug(f'Searching for browser profiles in {home}')
profiles = dict(chromium_profiles=[], firefox_profiles=[])
chromium_directory = home / '.config/chromium'
default_chromium_profile = chromium_directory / 'Default'
if default_chromium_profile.is_dir():
profiles['chromium_profiles'].append(default_chromium_profile)
chromium_profiles = chromium_directory.glob('Profile *')
for chromium_profile in chromium_profiles:
if chromium_profile.is_dir():
profiles['chromium_profiles'].append(chromium_profile)
firefox_profiles_directory = home / '.mozilla/firefox'
firefox_profiles_file = firefox_profiles_directory / 'profiles.ini'
if firefox_profiles_file.is_file():
# Read the profile.ini and get the default profile path.
firefox_profiles_file = firefox_profiles_file.read_text()
default_firefox_profile = re.findall(r'Default=(.*)', firefox_profiles_file)
if default_firefox_profile:
default_firefox_profile = firefox_profiles_directory / default_firefox_profile[0]
if default_firefox_profile.is_dir():
profiles['firefox_profiles'].append(default_firefox_profile)
return profiles
def browser_profile_to_yt_dlp_arg(profile: pathlib.Path) -> str:
"""Takes a Path and returns a string that can be used as a yt-dlp `--cookies-from-browser` argument."""
*_, browser, profile = str(profile).split('/')
return f'{browser}:{profile}'

View file

@ -3,12 +3,14 @@ import json
import shutil
from copy import copy
from http import HTTPStatus
from pathlib import Path
from unittest import mock
import pytest
from modules.videos.downloader import VideoDownloader, \
get_or_create_channel, channel_downloader, video_downloader, preview_filename
from modules.videos.lib import get_videos_downloader_config
from modules.videos.models import Channel, Video
from wrolpi.conftest import test_directory, await_switches
from wrolpi.downloader import Download, DownloadResult
@ -546,3 +548,57 @@ def test_normalize_video_file_names(test_directory, video_download_manager):
info_json,
}
assert not vtt.exists()
@pytest.mark.asyncio
async def test_video_download_cookies(test_session, test_directory, mock_video_extract_info, await_switches,
video_download_manager, mock_video_process_runner, image_file, test_videos_downloader_config):
config = get_videos_downloader_config()
config.browser_profile = str(test_directory / 'firefox/some directory')
(test_directory / 'firefox/some directory').mkdir(parents=True)
video_path = test_directory / 'a video.mp4'
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', video_path)
# Request video download with cookies.
settings = {'use_browser_profile': True}
url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name, settings=settings)
await video_download_manager.wait_for_all_downloads()
download, cmd, out_dir = mock_video_process_runner.call_args[0]
assert '--cookies-from-browser' in cmd
assert 'firefox:some directory' in cmd
@pytest.mark.asyncio
async def test_video_download_always_use_cookies(test_session, test_directory, mock_video_extract_info, await_switches,
video_download_manager, mock_video_process_runner, image_file, test_videos_downloader_config):
config = get_videos_downloader_config()
config.always_use_browser_profile = True
config.browser_profile = str(test_directory / 'chromium/some directory')
(test_directory / 'chromium/some directory').mkdir(parents=True)
video_path = test_directory / 'a video.mp4'
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', video_path)
url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
mock_video_extract_info.return_value = example_video_json
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
video_download_manager.create_download(url, video_downloader.name)
await video_download_manager.wait_for_all_downloads()
download, cmd, out_dir = mock_video_process_runner.call_args[0]
assert '--cookies-from-browser' in cmd
assert 'chromium:some directory' in cmd

View file

@ -303,3 +303,15 @@ async def test_videos_downloader_config_api(async_client, test_directory, test_v
request, response = await async_client.post('/api/config?file_name=videos_downloader.yaml', json=body)
assert response.status == HTTPStatus.BAD_REQUEST
assert 'Invalid config' in response.json.get('error')
@pytest.mark.parametrize('file_name,expected', [
('/home/wrolpi/.config/chromium/Default', 'chromium:Default'),
('/home/wrolpi/.mozilla/firefox/29el0wk0.default-release', 'firefox:29el0wk0.default-release'),
])
def test_browser_profile_to_yt_dlp_arg(file_name, expected):
"""
Test the conversion of a browser profile to yt-dlp arguments.
"""
file_name = pathlib.Path(file_name)
assert lib.browser_profile_to_yt_dlp_arg(file_name) == expected