mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-22 16:06:19 -05:00
Video and Archive can be tagged when downloading.
This commit is contained in:
parent
a893d44094
commit
ede9d2236b
11 changed files with 118 additions and 49 deletions
|
|
@ -411,7 +411,7 @@ export async function getArchive(archiveId) {
|
|||
}
|
||||
}
|
||||
|
||||
export async function postDownload(urls, downloader, frequency, sub_downloader, excludedURLs, destination) {
|
||||
export async function postDownload(urls, downloader, frequency, sub_downloader, excludedURLs, destination, tagNames) {
|
||||
if (!downloader) {
|
||||
toast({
|
||||
type: 'error',
|
||||
|
|
@ -432,6 +432,9 @@ export async function postDownload(urls, downloader, frequency, sub_downloader,
|
|||
if (sub_downloader) {
|
||||
body['sub_downloader'] = sub_downloader;
|
||||
}
|
||||
if (tagNames) {
|
||||
body['tag_names'] = tagNames;
|
||||
}
|
||||
let response = await apiPost(`${API_URI}/download`, body);
|
||||
return response;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,11 +28,11 @@ class Downloader extends React.Component {
|
|||
}
|
||||
|
||||
submitDownload = async () => {
|
||||
let {urls, downloader, destination} = this.state;
|
||||
let {urls, downloader, destination, tagNames} = this.state;
|
||||
if (urls) {
|
||||
this.setState({pending: true, submitted: false});
|
||||
try {
|
||||
let response = await postDownload(urls, downloader, null, null, null, destination);
|
||||
let response = await postDownload(urls, downloader, null, null, null, destination, tagNames);
|
||||
if (response.status === 204) {
|
||||
this.setState({urls: '', pending: false, submitted: true});
|
||||
}
|
||||
|
|
@ -72,7 +72,6 @@ class Downloader extends React.Component {
|
|||
}
|
||||
|
||||
handleSelectedTags = (tagNames) => {
|
||||
console.log(tagNames);
|
||||
this.setState({tagNames});
|
||||
}
|
||||
|
||||
|
|
@ -87,7 +86,29 @@ class Downloader extends React.Component {
|
|||
render() {
|
||||
let disabled = !this.state.urls || !this.state.valid || this.state.pending || !this.state.downloader;
|
||||
const {advancedOpen, destination, submitted, tagNames} = this.state;
|
||||
const {header, withDestination} = this.props;
|
||||
const {header, withDestination, withTags} = this.props;
|
||||
|
||||
let destinationField;
|
||||
if (withDestination) {
|
||||
destinationField = <FormGroup>
|
||||
<FormField width={16}>
|
||||
<label>Destination</label>
|
||||
<DirectoryInput
|
||||
isDirectory={true}
|
||||
value={destination}
|
||||
setInput={this.handleDestinationChange}
|
||||
placeholder='download/into/custom/directory'
|
||||
/>
|
||||
</FormField>
|
||||
</FormGroup>;
|
||||
}
|
||||
|
||||
let tagsSelector;
|
||||
if (withTags) {
|
||||
tagsSelector = <TagsProvider>
|
||||
<TagsSelector selectedTagNames={tagNames} onToggle={this.handleSelectedTags}/>
|
||||
</TagsProvider>;
|
||||
}
|
||||
|
||||
const advancedAccordion = <Accordion>
|
||||
<AccordionTitle onClick={() => this.setState({advancedOpen: !advancedOpen})}>
|
||||
|
|
@ -95,21 +116,9 @@ class Downloader extends React.Component {
|
|||
</AccordionTitle>
|
||||
<AccordionContent active={advancedOpen}>
|
||||
<Segment>
|
||||
<FormGroup>
|
||||
<FormField width={16}>
|
||||
<label>Destination</label>
|
||||
<DirectoryInput
|
||||
isDirectory={true}
|
||||
value={destination}
|
||||
setInput={this.handleDestinationChange}
|
||||
placeholder='download/into/custom/directory'
|
||||
/>
|
||||
</FormField>
|
||||
</FormGroup>
|
||||
<br/>
|
||||
<TagsProvider>
|
||||
<TagsSelector selectedTagNames={tagNames} onToggle={this.handleSelectedTags}/>
|
||||
</TagsProvider>
|
||||
{destinationField}
|
||||
{withDestination && withTags && <br/>}
|
||||
{tagsSelector}
|
||||
</Segment>
|
||||
</AccordionContent>
|
||||
</Accordion>;
|
||||
|
|
@ -126,7 +135,7 @@ class Downloader extends React.Component {
|
|||
onChange={this.handleInputChange}
|
||||
value={this.state.urls}
|
||||
/>
|
||||
{withDestination && advancedAccordion}
|
||||
{(withDestination || withTags) && advancedAccordion}
|
||||
<Button content='Cancel' onClick={this.props.clearSelected}/>
|
||||
<Button primary style={{marginTop: '1em'}} disabled={disabled}>Download</Button>
|
||||
{submitted && viewDownloads}
|
||||
|
|
@ -419,12 +428,14 @@ export function DownloadMenu({onOpen, disabled}) {
|
|||
archive: <Downloader
|
||||
clearSelected={clearSelected}
|
||||
header={<><Icon name='file alternate'/> Archive</>}
|
||||
downloader='archive'/>,
|
||||
downloader='archive'
|
||||
withTags={true}/>,
|
||||
video: <Downloader
|
||||
clearSelected={clearSelected}
|
||||
header={<><Icon name='film'/> Videos</>}
|
||||
downloader='video'
|
||||
withDestination={true}/>,
|
||||
withDestination={true}
|
||||
withTags={true}/>,
|
||||
video_channel: <ChannelDownload clearSelected={clearSelected}/>,
|
||||
rss: <RSSDownload
|
||||
clearSelected={clearSelected}
|
||||
|
|
|
|||
|
|
@ -32,18 +32,19 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
def __repr__(self):
|
||||
return f'<ArchiveDownloader>'
|
||||
|
||||
@classmethod
|
||||
def valid_url(cls, url: str) -> Tuple[bool, None]:
|
||||
"""
|
||||
Archiver will attempt to archive anything, so it should be last!
|
||||
"""
|
||||
return True, None
|
||||
|
||||
async def do_download(self, download: Download) -> DownloadResult:
|
||||
if download.attempts > 3:
|
||||
raise UnrecoverableDownloadError(f'Max download attempts reached for {download.url}')
|
||||
|
||||
archive = await lib.do_archive(download.url)
|
||||
archive: Archive = await lib.do_archive(download.url)
|
||||
|
||||
if download.settings and (tag_names := download.settings.get('tag_names')):
|
||||
for name in tag_names:
|
||||
archive.add_tag(name)
|
||||
|
||||
if session := Session.object_session(archive):
|
||||
session.commit()
|
||||
|
||||
return DownloadResult(success=True, location=f'/archive/{archive.id}')
|
||||
|
||||
@optional_session
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import datetime
|
|||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from typing import Iterable, List, Optional
|
||||
from typing import Iterable, List, Optional, Union
|
||||
|
||||
import pytz
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger
|
||||
|
|
@ -14,6 +14,7 @@ from wrolpi.dates import TZDateTime
|
|||
from wrolpi.errors import InvalidArchive
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.media_path import MediaPathType
|
||||
from wrolpi.tags import Tag, TagFile
|
||||
from wrolpi.vars import PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -252,6 +253,10 @@ class Archive(Base, ModelHelper):
|
|||
archive = model_archive(file_group, session)
|
||||
return archive
|
||||
|
||||
def add_tag(self, tag_or_tag_name: Union[Tag, str]) -> TagFile:
|
||||
tag = Tag.find_by_name(tag_or_tag_name) if isinstance(tag_or_tag_name, str) else tag_or_tag_name
|
||||
return self.file_group.add_tag(tag)
|
||||
|
||||
|
||||
class Domain(Base, ModelHelper):
|
||||
__tablename__ = 'domains' # plural to avoid conflict
|
||||
|
|
|
|||
|
|
@ -6,11 +6,9 @@ from sanic_ext import validate
|
|||
from sanic_ext.extensions.openapi import openapi
|
||||
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.common import wrol_mode_check
|
||||
from wrolpi.root_api import add_blueprint, json_response
|
||||
from wrolpi.schema import JSONErrorResponse
|
||||
from . import lib, schema
|
||||
from .channel import lib as channel_lib
|
||||
from .channel.api import channel_bp
|
||||
from .video import lib as video_lib
|
||||
from .video.api import video_bp
|
||||
|
|
|
|||
|
|
@ -293,6 +293,13 @@ class VideoDownloader(Downloader, ABC):
|
|||
video.source_id = entry['id']
|
||||
video.channel_id = channel_id
|
||||
video_id = video.id
|
||||
|
||||
session.commit()
|
||||
|
||||
if download.settings and (tag_names := download.settings.get('tag_names')):
|
||||
for name in tag_names:
|
||||
video.add_tag(name)
|
||||
|
||||
except UnrecoverableDownloadError:
|
||||
raise
|
||||
except yt_dlp.utils.UnsupportedError as e:
|
||||
|
|
|
|||
|
|
@ -2,12 +2,13 @@ import json
|
|||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
|
||||
import mock.mock
|
||||
import pytest
|
||||
|
||||
from modules.videos.models import Video, Channel
|
||||
from modules.videos.video import lib as video_lib
|
||||
from wrolpi.db import get_db_curs
|
||||
from wrolpi.downloader import DownloadFrequency
|
||||
from wrolpi.downloader import DownloadFrequency, Download
|
||||
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
|
@ -160,6 +161,36 @@ def test_api_download_channel(test_session, test_client, simple_channel):
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT, response.json
|
||||
|
||||
|
||||
def test_api_download(test_session, test_client, test_directory):
|
||||
"""A video can be downloaded."""
|
||||
content = {'urls': 'https://example.com/video1', 'downloader': 'video', 'destination': 'dest',
|
||||
'excluded_urls': 'example.com'}
|
||||
request, response = test_client.post('/api/download', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.url == 'https://example.com/video1'
|
||||
assert download.downloader == 'video'
|
||||
assert download.settings['excluded_urls'] == ['example.com']
|
||||
assert download.settings['destination'] == str(test_directory / 'dest')
|
||||
assert download.settings['tag_names'] == []
|
||||
|
||||
|
||||
def test_api_download_video_tags(test_session, test_client, tag_factory):
|
||||
"""A user can request Tags for a video being downloaded."""
|
||||
tag1 = tag_factory()
|
||||
tag2 = tag_factory()
|
||||
|
||||
content = {'urls': 'https://example.com/video1', 'downloader': 'video', 'tag_names': [tag1.name, tag2.name]}
|
||||
request, response = test_client.post('/api/download', content=json.dumps(content))
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
download = test_session.query(Download).one()
|
||||
assert download.url == 'https://example.com/video1'
|
||||
assert download.downloader == 'video'
|
||||
assert download.settings['tag_names'] == [tag1.name, tag2.name]
|
||||
|
||||
|
||||
def test_search_videos_file(test_client, test_session, test_directory, video_with_search_factory, assert_video_search):
|
||||
"""Test that videos can be searched and that their order is by their textsearch rank."""
|
||||
# These captions have repeated letters, so they will be higher in the ranking.
|
||||
|
|
@ -204,7 +235,8 @@ def test_search_videos_file(test_client, test_session, test_directory, video_wit
|
|||
def test_search_videos(test_client, test_session, video_factory, assert_video_search, simple_channel, tag_factory):
|
||||
"""Search the Video table. This does not need to use a join with the File table."""
|
||||
vid1: Video = video_factory(upload_date='2022-09-16', with_video_file=True, title='vid1')
|
||||
vid2: Video = video_factory(upload_date='2022-09-17', with_video_file=True, title='vid2', channel_id=simple_channel.id)
|
||||
vid2: Video = video_factory(upload_date='2022-09-17', with_video_file=True, title='vid2',
|
||||
channel_id=simple_channel.id)
|
||||
vid3: Video = video_factory(upload_date='2022-09-18', with_video_file=True, title='vid3')
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
vid1.add_tag(tag1)
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ example_channel_json = {
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_no_channel(test_session, video_download_manager, video_factory, test_directory,
|
||||
async def test_download_no_channel(test_session, video_download_manager, test_directory,
|
||||
mock_video_extract_info, mock_video_process_runner):
|
||||
"""A video can be downloaded even if it does not have a Channel."""
|
||||
channel_dir = test_directory / 'NO CHANNEL'
|
||||
|
|
@ -136,6 +136,27 @@ async def test_download_no_channel(test_session, video_download_manager, video_f
|
|||
assert str(video.video_path) == f'{channel_dir}/video.mp4'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_video_tags(test_session, video_download_manager, video_file_factory, test_directory,
|
||||
mock_video_extract_info, mock_video_process_runner, tag_factory):
|
||||
"""A Video is tagged when Download record requires it."""
|
||||
video_path = video_file_factory()
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
|
||||
url = 'https://www.youtube.com/watch?v=31jPEBiAC3c'
|
||||
mock_video_extract_info.return_value = copy(example_video_json)
|
||||
with mock.patch('modules.videos.downloader.VideoDownloader.prepare_filename') as mock_prepare_filename:
|
||||
mock_prepare_filename.return_value = (video_path, {'id': 'foo'})
|
||||
settings = dict(tag_names=[tag1.name, tag2.name])
|
||||
video_download_manager.create_download(url, video_downloader.name, settings=settings)
|
||||
await video_download_manager.wait_for_all_downloads()
|
||||
|
||||
mock_video_process_runner.assert_called_once()
|
||||
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert [i.tag.name for i in video.file_group.tag_files] == [tag1.name, tag2.name]
|
||||
|
||||
|
||||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
|
||||
|
|
|
|||
|
|
@ -1125,16 +1125,6 @@ class RSSDownloader(Downloader, ABC):
|
|||
def __repr__(self):
|
||||
return '<RSSDownloader>'
|
||||
|
||||
@classmethod
|
||||
def valid_url(cls, url: str) -> Tuple[bool, Optional[dict]]:
|
||||
"""Attempts to parse an RSS Feed. If it succeeds, it returns a FeedParserDict as a dictionary."""
|
||||
feed = parse_feed(url)
|
||||
feed = dict(feed)
|
||||
if feed['bozo']:
|
||||
# Feed did not parse.
|
||||
return False, {}
|
||||
return True, dict(feed=feed)
|
||||
|
||||
def do_download(self, download: Download) -> DownloadResult:
|
||||
if isinstance(download.info_json, dict) and download.info_json.get('feed'):
|
||||
feed = download.info_json['feed']
|
||||
|
|
|
|||
|
|
@ -217,7 +217,7 @@ async def post_download(_: Request, body: schema.DownloadRequest):
|
|||
|
||||
excluded_urls = [i.strip() for i in body.excluded_urls.split(',')] if body.excluded_urls else None
|
||||
destination = str(get_media_directory() / body.destination) if body.destination else None
|
||||
settings = dict(excluded_urls=excluded_urls, destination=destination)
|
||||
settings = dict(excluded_urls=excluded_urls, destination=destination, tag_names=body.tag_names)
|
||||
if body.frequency:
|
||||
download_manager.recurring_download(urls[0], body.frequency, downloader_name=body.downloader,
|
||||
sub_downloader_name=body.sub_downloader, reset_attempts=True,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional, List
|
||||
|
||||
|
||||
|
|
@ -54,6 +54,7 @@ class DownloadRequest:
|
|||
sub_downloader: Optional[str] = None
|
||||
excluded_urls: Optional[str] = None
|
||||
destination: Optional[str] = None
|
||||
tag_names: List[str] = field(default_factory=lambda: list())
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue