mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-05 06:09:57 -05:00
Adding feature where Videos can be downloaded to a destination directory.
This commit is contained in:
parent
61d2ffde36
commit
f1bc29d76f
22 changed files with 248 additions and 181 deletions
|
|
@ -8,7 +8,7 @@ from datetime import timedelta
|
|||
from decimal import Decimal
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Union, List, Set, Iterable, Optional, Tuple
|
||||
from typing import List, Set, Iterable, Optional, Tuple
|
||||
|
||||
import PIL
|
||||
from PIL import Image
|
||||
|
|
@ -136,35 +136,6 @@ def check_for_channel_conflicts(session: Session, id_=None, url=None, name=None,
|
|||
raise ChannelSourceIdConflict()
|
||||
|
||||
|
||||
def get_matching_directories(path: Union[str, Path]) -> List[str]:
|
||||
"""
|
||||
Return a list of directory strings that start with the provided path. If the path is a directory, return it's
|
||||
subdirectories, if the directory contains no subdirectories, return the directory.
|
||||
"""
|
||||
path = str(path)
|
||||
|
||||
ignored_directories = {
|
||||
str(get_no_channel_directory()),
|
||||
}
|
||||
|
||||
if os.path.isdir(path):
|
||||
# The provided path is a directory, return its subdirectories, or itself if no subdirectories exist
|
||||
paths = [os.path.join(path, i) for i in os.listdir(path)]
|
||||
paths = sorted(i for i in paths if os.path.isdir(i) and i not in ignored_directories)
|
||||
if len(paths) == 0:
|
||||
return [path]
|
||||
return paths
|
||||
|
||||
head, tail = os.path.split(path)
|
||||
paths = os.listdir(head)
|
||||
paths = [os.path.join(head, i) for i in paths]
|
||||
pattern = path.lower()
|
||||
paths = sorted(
|
||||
i for i in paths if os.path.isdir(i) and i.lower().startswith(pattern) and i not in ignored_directories)
|
||||
|
||||
return paths
|
||||
|
||||
|
||||
def duration_to_seconds(duration: str) -> int:
|
||||
"""Convert ffmpeg duration to seconds"""
|
||||
hours, minutes, seconds = duration.split(':')
|
||||
|
|
|
|||
|
|
@ -256,9 +256,12 @@ class VideoDownloader(Downloader, ABC):
|
|||
logger.info('Could not find channel')
|
||||
|
||||
# Use the default directory if this video has no channel.
|
||||
out_dir = get_no_channel_directory()
|
||||
if channel:
|
||||
out_dir = channel.directory
|
||||
if settings.get('destination'):
|
||||
out_dir = pathlib.Path(settings['destination'])
|
||||
else:
|
||||
out_dir = get_no_channel_directory()
|
||||
if channel:
|
||||
out_dir = channel.directory
|
||||
out_dir.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
logs = None # noqa
|
||||
|
|
|
|||
|
|
@ -157,16 +157,6 @@ class PaginationQuery:
|
|||
offset: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class DirectoriesRequest:
|
||||
search_str: Optional[str] = ''
|
||||
|
||||
|
||||
@dataclass
|
||||
class DirectoriesResponse:
|
||||
directories: List[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class FavoriteRequest:
|
||||
video_id: int
|
||||
|
|
|
|||
|
|
@ -12,49 +12,13 @@ from modules.videos.models import Channel, Video
|
|||
from wrolpi.common import get_absolute_media_path, sanitize_link
|
||||
from wrolpi.dates import local_timezone, now
|
||||
from wrolpi.downloader import Download, DownloadFrequency
|
||||
from wrolpi.test.common import build_test_directories, TestAPI
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
from .. import common
|
||||
from ..common import get_matching_directories, convert_image, remove_duplicate_video_paths, \
|
||||
from ..common import convert_image, remove_duplicate_video_paths, \
|
||||
apply_info_json, get_video_duration, generate_video_poster, is_valid_poster
|
||||
from ..lib import save_channels_config, get_channels_config, import_channels_config
|
||||
|
||||
|
||||
class TestCommon(TestAPI):
|
||||
|
||||
def test_matching_directories(self):
|
||||
structure = [
|
||||
'foo/qux/',
|
||||
'Bar/',
|
||||
'baz/baz'
|
||||
'barr',
|
||||
'bazz',
|
||||
]
|
||||
|
||||
with build_test_directories(structure) as temp_dir:
|
||||
temp_dir = pathlib.Path(temp_dir)
|
||||
|
||||
# No directories have c
|
||||
matches = get_matching_directories(temp_dir / 'c')
|
||||
assert matches == []
|
||||
|
||||
# Get all directories starting with f
|
||||
matches = get_matching_directories(temp_dir / 'f')
|
||||
assert matches == [str(temp_dir / 'foo')]
|
||||
|
||||
# Get all directories starting with b, ignore case
|
||||
matches = get_matching_directories(temp_dir / 'b')
|
||||
assert matches == [str(temp_dir / 'Bar'), str(temp_dir / 'baz')]
|
||||
|
||||
# baz matches, but it has no subdirectories
|
||||
matches = get_matching_directories(temp_dir / 'baz')
|
||||
assert matches == [str(temp_dir / 'baz')]
|
||||
|
||||
# foo is an exact match, return subdirectories
|
||||
matches = get_matching_directories(temp_dir / 'foo')
|
||||
assert matches == [str(temp_dir / 'foo/qux')]
|
||||
|
||||
|
||||
def test_get_absolute_media_path():
|
||||
path = get_absolute_media_path('videos')
|
||||
assert str(path).endswith('videos')
|
||||
|
|
|
|||
|
|
@ -443,6 +443,21 @@ async def test_download_result(test_session, test_directory, video_download_mana
|
|||
assert video.poster_file.associated, 'Poster file was not associated.'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_destination(test_session, test_directory, video_download_manager,
|
||||
mock_video_process_runner, mock_video_extract_info, mock_video_prepare_filename):
|
||||
mock_video_extract_info.return_value = example_video_json
|
||||
|
||||
settings = dict(destination=f'{test_directory}/custom')
|
||||
video_download_manager.create_download('https://example.com', downloader=VideoDownloader.name, settings=settings)
|
||||
mock_video_process_runner.return_value = (0, {'stdout': '', 'stderr': ''})
|
||||
mock_video_prepare_filename.return_value = str(test_directory / 'test video.mp4')
|
||||
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']\
|
||||
.startswith(f'{test_directory}/custom/%(uploader)s')
|
||||
|
||||
example_playlist_json = {
|
||||
'_type': 'playlist',
|
||||
'availability': None,
|
||||
|
|
|
|||
|
|
@ -5,13 +5,12 @@ from sanic.request import Request
|
|||
from sanic_ext import validate
|
||||
from sanic_ext.extensions.openapi import openapi
|
||||
|
||||
from wrolpi.common import logger, wrol_mode_check, run_after, get_media_directory, \
|
||||
get_relative_to_media_directory
|
||||
from wrolpi.common import logger, wrol_mode_check, run_after
|
||||
from wrolpi.errors import InvalidOrderBy, ValidationError
|
||||
from wrolpi.root_api import json_response
|
||||
from wrolpi.schema import JSONErrorResponse
|
||||
from . import lib
|
||||
from .. import common, schema
|
||||
from .. import schema
|
||||
|
||||
video_bp = Blueprint('Video', '/api/videos')
|
||||
|
||||
|
|
@ -52,21 +51,6 @@ async def search(_: Request, body: schema.VideoSearchRequest):
|
|||
return json_response(ret)
|
||||
|
||||
|
||||
@video_bp.post('/directories')
|
||||
@openapi.definition(
|
||||
summary='Get all directories that match the search_str, prefixed by the media directory.',
|
||||
body=schema.DirectoriesRequest,
|
||||
)
|
||||
@openapi.response(HTTPStatus.OK, schema.DirectoriesResponse)
|
||||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
@validate(schema.DirectoriesRequest)
|
||||
def directories(_, body: schema.DirectoriesRequest):
|
||||
search_str = str(get_media_directory() / (body.search_str or ''))
|
||||
dirs = common.get_matching_directories(search_str)
|
||||
dirs = [str(get_relative_to_media_directory(i)) for i in dirs]
|
||||
return response.json({'directories': dirs})
|
||||
|
||||
|
||||
@video_bp.delete('/video/<video_ids:[0-9,]+>')
|
||||
@video_bp.delete('/video/<video_ids:int>')
|
||||
@openapi.description('Delete videos.')
|
||||
|
|
|
|||
|
|
@ -157,28 +157,3 @@ def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixtu
|
|||
|
||||
wrol_mode_fixture(False)
|
||||
assert not test_download_manager.stopped.is_set()
|
||||
|
||||
|
||||
def test_video_directory_search(test_client, make_files_structure):
|
||||
"""Test that video directories can be searched."""
|
||||
make_files_structure([
|
||||
'foo/',
|
||||
'fool/',
|
||||
'not a directory',
|
||||
])
|
||||
|
||||
def assert_directories(search_str, expected):
|
||||
body = dict(search_str=search_str)
|
||||
request, response = test_client.post('/api/videos/directories', content=dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['directories'] == expected
|
||||
|
||||
# All directories are returned.
|
||||
assert_directories(None, ['foo', 'fool', 'videos'])
|
||||
assert_directories('', ['foo', 'fool', 'videos'])
|
||||
# Matches both directories.
|
||||
assert_directories('fo', ['foo', 'fool'])
|
||||
# Matches the one directory exactly.
|
||||
assert_directories('foo', ['foo'])
|
||||
# Does not exist.
|
||||
assert_directories('food', [])
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue