Moving FileGroups instead of refreshing files after they have been moved.

This commit is contained in:
Roland 2024-08-15 19:32:01 -06:00
parent 6fe8a7b704
commit 0f232fd533
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
59 changed files with 1902 additions and 1040 deletions

View file

@ -49,17 +49,20 @@ class ArchiveDownloader(Downloader, ABC):
singlefile, readability, screenshot = await self.do_archive(download)
archive: Archive = await lib.model_archive_result(download.url, singlefile, readability, screenshot)
archive_id = archive.id
if download.settings and (tag_names := download.settings.get('tag_names')):
for name in tag_names:
archive.add_tag(name)
with get_db_session() as session:
archive = Archive.find_by_id(archive_id, session)
if download.settings and (tag_names := download.settings.get('tag_names')):
for name in tag_names:
archive.add_tag(name, session)
if session := Session.object_session(archive):
session.commit()
if session := Session.object_session(archive):
session.commit()
logger.info(f'Successfully downloaded Archive {download.url} {archive}')
logger.info(f'Successfully downloaded Archive {download.url} {archive}')
return DownloadResult(success=True, location=f'/archive/{archive.id}')
return DownloadResult(success=True, location=f'/archive/{archive.id}')
@optional_session
def already_downloaded(self, *urls: List[str], session: Session = None) -> List:

View file

@ -82,7 +82,7 @@ def archive_factory(test_session, archive_directory, make_files_structure):
archive.validate()
for tag_name in tag_names:
archive.add_tag(tag_name)
archive.add_tag(tag_name, test_session)
return archive

View file

@ -205,7 +205,8 @@ async def model_archive_result(url: str, singlefile: str, readability: dict, scr
archive.file_group.download_datetime = now()
archive.url = url
archive.domain = get_or_create_domain(session, url)
session.flush()
archive.flush()
archive.domain.flush()
return archive

View file

@ -315,8 +315,8 @@ class Archive(Base, ModelHelper):
archive = model_archive(file_group, session)
return archive
def add_tag(self, tag_id_or_name: int | str) -> TagFile:
return self.file_group.add_tag(tag_id_or_name)
def add_tag(self, tag_id_or_name: int | str, session: Session = None) -> TagFile:
return self.file_group.add_tag(tag_id_or_name, session)
class Domain(Base, ModelHelper):

View file

@ -84,7 +84,7 @@ def test_archives_search(test_session, archive_directory, archive_factory, test_
@pytest.mark.asyncio
async def test_search_archive_tags(test_session, test_async_client, archive_factory, tag_factory):
"""Tagged Archives can be searched."""
tag = tag_factory()
tag = await tag_factory()
archive_factory(domain='example.com', tag_names=[tag.name, ])
test_session.commit()

View file

@ -2,12 +2,15 @@ from http import HTTPStatus
from sanic import Blueprint
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from wrolpi.api_utils import json_response
from wrolpi.common import logger
from . import lib, schema
from .channel.api import channel_bp
from .lib import format_videos_destination
from .models import Channel
from .video.api import video_bp
content_bp = Blueprint('VideoContent', '/api/videos')
@ -25,3 +28,20 @@ logger = logger.getChild(__name__)
async def statistics(_: Request):
ret = await lib.get_statistics()
return json_response(ret, HTTPStatus.OK)
@content_bp.post('/tag_info')
@openapi.definition(
description='Get data about tagging a Channel',
body=schema.ChannelTagInfoRequest,
)
@validate(schema.ChannelTagInfoRequest)
async def channel_tag_info(_: Request, body: schema.ChannelTagInfoRequest):
from wrolpi.tags import Tag
channel = Channel.find_by_id(body.channel_id) if body.channel_id else None
channel_name = channel.name if channel else None
channel_url = channel.url if channel else None
tag_name = Tag.find_by_name(body.tag_name).name if body.tag_name else None
videos_destination = format_videos_destination(channel_name, tag_name, channel_url)
ret = dict(videos_destination=videos_destination)
return json_response(ret)

View file

@ -17,7 +17,7 @@ from wrolpi.vars import PYTEST
from . import lib
from .. import schema
from ..errors import UnknownChannel
from ..lib import save_channels_config, format_videos_destination
from ..lib import save_channels_config
from ..models import Channel
channel_bp = Blueprint('Channel', url_prefix='/api/videos/channels')
@ -78,9 +78,9 @@ def channel_post(_: Request, body: schema.ChannelPostRequest):
@validate(schema.ChannelPutRequest)
@run_after(save_channels_config)
@wrol_mode_check
def channel_update(_: Request, channel_id: int, body: schema.ChannelPutRequest):
async def channel_update(_: Request, channel_id: int, body: schema.ChannelPutRequest):
body.directory = pathlib.Path(body.directory) if body.directory else None
channel = lib.update_channel(data=body, channel_id=channel_id)
channel = await lib.update_channel(data=body, channel_id=channel_id)
return response.raw('', HTTPStatus.NO_CONTENT,
headers={'Location': f'/api/videos/channels/{channel.id}'})
@ -138,32 +138,14 @@ async def channel_download(_: Request, channel_id: int, body: schema.ChannelDown
return response.empty()
@channel_bp.post('/<channel_id:int>/tag_info')
@openapi.definition(
description='Get Channel Tag Info',
body=schema.ChannelTagInfoRequest,
)
@validate(schema.ChannelTagInfoRequest)
@run_after(save_channels_config)
@wrol_mode_check
async def channel_tag_info(_: Request, channel_id: int, body: schema.ChannelTagInfoRequest):
from wrolpi.tags import Tag
channel_name = Channel.find_by_id(channel_id).name
tag_name = Tag.find_by_name(body.tag_name).name if body.tag_name else None
videos_destination = format_videos_destination(channel_name, tag_name)
ret = dict(videos_destination=videos_destination)
return json_response(ret)
@channel_bp.post('/<channel_id:int>/tag')
@openapi.definition(
description='Tag Channel',
description='Tag/untag a Channel with a single tag',
body=schema.ChannelTagRequest,
)
@openapi.response(HTTPStatus.NO_CONTENT)
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
@validate(schema.ChannelTagRequest)
@run_after(save_channels_config)
@wrol_mode_check
async def channel_tag(_: Request, channel_id: int, body: schema.ChannelTagRequest):
directory = None
@ -174,3 +156,17 @@ async def channel_tag(_: Request, channel_id: int, body: schema.ChannelTagReques
await lib.tag_channel(body.tag_name, directory, channel_id)
return response.raw('', HTTPStatus.NO_CONTENT)
@channel_bp.post('/search')
@openapi.definition(
description='Search Channels',
body=schema.ChannelSearchRequest,
)
@validate(schema.ChannelSearchRequest)
async def channel_search(_: Request, body: schema.ChannelSearchRequest):
channels = await lib.search_channels(body.tag_names)
ret = dict(
channels=channels,
)
return json_response(ret)

View file

@ -7,10 +7,11 @@ from sqlalchemy.orm import Session
from wrolpi import flags
from wrolpi.common import run_after, logger, \
get_media_directory, wrol_mode_check
get_media_directory, wrol_mode_check, background_task
from wrolpi.db import get_db_curs, optional_session, get_db_session
from wrolpi.downloader import save_downloads_config, download_manager
from wrolpi.errors import UnknownDirectory, APIError, ValidationError, RefreshConflict
from wrolpi.errors import APIError, ValidationError, RefreshConflict
from wrolpi.vars import PYTEST
from .. import schema
from ..common import check_for_channel_conflicts
from ..errors import UnknownChannel, ChannelDirectoryConflict
@ -115,22 +116,10 @@ def get_channel(session: Session, *, channel_id: int = None, source_id: str = No
@run_after(save_channels_config)
@optional_session
def update_channel(session: Session, *, data: schema.ChannelPutRequest, channel_id: int) -> Channel:
async def update_channel(session: Session, *, data: schema.ChannelPutRequest, channel_id: int) -> Channel:
"""Update a Channel's DB record"""
channel = Channel.find_by_id(channel_id, session)
# Only update directory if it was empty
if data.directory and not channel.directory:
data.directory = get_media_directory() / data.directory
if not data.directory.is_dir():
if data.mkdir:
data.directory.mkdir()
else:
raise UnknownDirectory()
elif data.directory:
# Keep the old directory because the user can't change a Channel's directory.
data.directory = channel.directory
# Verify that the URL/Name/directory aren't taken
check_for_channel_conflicts(
session,
@ -140,11 +129,27 @@ def update_channel(session: Session, *, data: schema.ChannelPutRequest, channel_
directory=data.directory,
)
data = data.__dict__
old_directory = pathlib.Path(channel.directory)
new_directory = get_media_directory() / data.pop('directory')
# Apply the changes now that we've OK'd them
channel.update(data.__dict__)
channel.update(data)
session.commit()
async def _():
await channel.move_channel(new_directory, session, send_events=True)
if new_directory != old_directory:
if not new_directory.is_dir():
new_directory.mkdir(parents=True)
if PYTEST:
await _()
else:
background_task(_())
return channel
@ -252,7 +257,7 @@ async def update_channel_download(channel_id: int, download_id: int, url: str, f
@wrol_mode_check
@optional_session
async def tag_channel(tag_name: str, directory: pathlib.Path | None, channel_id: int, session: Session = None):
async def tag_channel(tag_name: str | None, directory: pathlib.Path | None, channel_id: int, session: Session = None):
"""Add a Tag to a Channel, or remove a Tag from a Channel if no `tag_name` is provided.
Move the Channel to the new directory, if provided."""
@ -261,29 +266,39 @@ async def tag_channel(tag_name: str, directory: pathlib.Path | None, channel_id:
if directory and flags.refreshing.is_set():
raise RefreshConflict('Refusing to move channel while file refresh is in progress')
channel = Channel.find_by_id(channel_id, session=session)
channel = Channel.find_by_id(channel_id, session)
if tag_name:
tag = Tag.find_by_name(tag_name, session=session)
tag = Tag.find_by_name(tag_name, session)
channel.tag_id = tag.id
channel.tag = tag
else:
channel.tag = channel.tag_id = None
session.flush([channel, ])
channel.flush()
session.commit()
# Do not move Channel files into a directory with files.
if directory and directory.is_dir() and next(directory.iterdir(), None):
if directory and directory != channel.directory and directory.is_dir() and next(directory.iterdir(), None):
raise ChannelDirectoryConflict('Channel directory already exists and is not empty')
# Only move Channel when requested.
if directory:
# Move to newly defined directory only if necessary.
logger.info(f'Tagging {channel} with {tag_name} moving to {directory} from {channel.directory}')
directory.mkdir(parents=True, exist_ok=True)
if channel.directory != directory:
await channel.move(directory, session)
coro = channel.move_channel(directory, session, send_events=True)
if PYTEST:
await coro
else:
background_task(coro)
else:
logger.info(f'Tagging {channel} with {tag_name}')
session.commit()
@optional_session
async def search_channels(tag_names: List[str], session: Session) -> List[Channel]:
"""Search Tagged Channels."""
from wrolpi.tags import Tag
channels = session.query(Channel).join(Tag).filter(Tag.name.in_(tag_names)).all()
return channels

View file

@ -1,6 +1,7 @@
import asyncio
import json
import pathlib
import shutil
import tempfile
from datetime import timedelta
from http import HTTPStatus
@ -96,7 +97,8 @@ def test_video_file_name(test_session, simple_video, test_client):
assert resp.json['file_group']['video'].get('stem') == 'simple_video'
def test_channel_conflicts(test_client, test_session, test_directory):
@pytest.mark.asyncio
async def test_channel_conflicts(test_async_client, test_session, test_directory):
channel_directory = tempfile.TemporaryDirectory(dir=test_directory).name
pathlib.Path(channel_directory).mkdir()
new_channel = dict(
@ -105,11 +107,11 @@ def test_channel_conflicts(test_client, test_session, test_directory):
url='https://example.com/channel1',
)
def _post_channel(channel):
return test_client.post('/api/videos/channels', content=json.dumps(channel))
async def _post_channel(channel):
return await test_async_client.post('/api/videos/channels', content=json.dumps(channel))
# Create it
request, response = _post_channel(new_channel)
request, response = await _post_channel(new_channel)
assert response.status_code == HTTPStatus.CREATED
# Name is an exact match
@ -119,7 +121,7 @@ def test_channel_conflicts(test_client, test_session, test_directory):
directory=channel_directory2,
name='Example Channel 1',
)
request, response = _post_channel(new_channel)
request, response = await _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'cause': {'code': 'CHANNEL_NAME_CONFLICT',
'error': 'The channel name is already taken.',
@ -133,7 +135,7 @@ def test_channel_conflicts(test_client, test_session, test_directory):
directory=channel_directory,
name='name is fine',
)
request, response = _post_channel(new_channel)
request, response = await _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'cause': {'code': 'CHANNEL_DIRECTORY_CONFLICT',
'error': 'The directory is already used by another channel.',
@ -150,7 +152,7 @@ def test_channel_conflicts(test_client, test_session, test_directory):
name='name is fine',
url='https://example.com/channel1',
)
request, response = _post_channel(new_channel)
request, response = await _post_channel(new_channel)
assert response.status_code == HTTPStatus.BAD_REQUEST
assert response.json == {'cause': {'code': 'CHANNEL_URL_CONFLICT',
'error': 'The URL is already used by another channel.',
@ -384,7 +386,8 @@ def test_search_videos_channel(test_client, test_session, video_factory):
dict(primary_path='vid1.mp4', video=dict(channel_id=channel2.id)))
def test_get_channel_videos_pagination(test_session, simple_channel, video_factory, assert_video_search):
@pytest.mark.asyncio
async def test_get_channel_videos_pagination(test_session, simple_channel, video_factory, assert_video_search):
for i in range(50):
video_factory(channel_id=simple_channel.id)
@ -406,8 +409,9 @@ def test_get_channel_videos_pagination(test_session, simple_channel, video_facto
]
last_ids = []
for offset, video_count in tests:
_, response = assert_video_search(channel_id=simple_channel.id, order_by='published_datetime', offset=offset,
limit=20)
_, response = await assert_video_search(channel_id=simple_channel.id, order_by='published_datetime',
offset=offset,
limit=20)
assert len(response.json['file_groups']) == video_count, 'Returned videos does not match'
current_ids = [i['id'] for i in response.json['file_groups']]
assert current_ids != last_ids, f'IDs are unchanged current_ids={current_ids}'
@ -416,7 +420,7 @@ def test_get_channel_videos_pagination(test_session, simple_channel, video_facto
@pytest.mark.asyncio
async def test_create_channel_download_api(test_async_client, test_session, simple_channel, tag_factory):
tag = tag_factory()
tag = await tag_factory()
# Create Download.
body = {'url': 'https://example.com/1', 'frequency': 42, 'settings': {'title_include': ''}}
@ -465,7 +469,7 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
videos_directory = get_videos_directory()
channel = channel_factory(name='Channel Name', download_frequency=120)
channel_directory = channel.directory
tag = tag_factory('Tag Name')
tag = await tag_factory('Tag Name')
v1, v2 = video_factory(title='video1', channel_id=channel.id), video_factory(title='video2', channel_id=channel.id)
# Create recurring download which uses the Channel's directory.
download = download_manager.recurring_download('https://example.com/1', 60, test_downloader.name,
@ -532,7 +536,7 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
# Channel can be Tagged, but not move directories.
# Channel can be Tagged, without moving directories.
body = dict(tag_name=tag.name)
request, response = await test_async_client.post(f'/api/videos/channels/{channel.id}/tag', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
@ -545,3 +549,79 @@ async def test_tag_channel(test_async_client, test_session, test_directory, chan
d1, d2 = test_session.query(Download).all()
assert d1.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d1} was not moved'
assert d2.settings['destination'] == str(test_directory / 'videos/Channel Name'), f'{d2} was not moved'
@pytest.mark.asyncio
async def test_move_channel(test_async_client, test_session, test_directory, channel_factory, tag_factory,
video_factory, test_channels_config, test_download_manager, test_downloader):
"""A Channel can be moved."""
channel = channel_factory(name='Channel Name')
vid1 = video_factory(channel_id=channel.id)
vid2 = video_factory(channel_id=channel.id)
test_session.commit()
assert str(channel.directory) == str(test_directory / 'videos/Channel Name')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/Channel Name/'))
assert str(vid2.video_path).startswith(str(test_directory / 'videos/Channel Name/'))
body = dict(
name=channel.name,
directory=str(test_directory / 'videos/New Directory'),
)
request, response = await test_async_client.put(f'/api/videos/channels/{channel.id}', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
channel = Channel.find_by_id(channel.id)
assert str(channel.directory) == str(test_directory / 'videos/New Directory')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/New Directory/'))
assert str(vid2.video_path).startswith(str(test_directory / 'videos/New Directory/'))
@pytest.mark.asyncio
async def test_move_channel_after_terminal_move(test_async_client, test_session, test_directory, channel_factory,
tag_factory, video_factory, test_channels_config, test_download_manager,
test_downloader):
"""A Channel can be moved in the UI after being moved in the Terminal."""
channel = channel_factory(name='Channel Name')
vid1 = video_factory(channel_id=channel.id)
test_session.commit()
assert str(channel.directory) == str(test_directory / 'videos/Channel Name')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/Channel Name/'))
# mv 'videos/Channel Name' 'videos/New Directory'
shutil.move(channel.directory, test_directory / 'videos/New Directory')
body = dict(
name=channel.name,
directory=str(test_directory / 'videos/New Directory'),
)
request, response = await test_async_client.put(f'/api/videos/channels/{channel.id}', json=body)
assert response.status_code == HTTPStatus.NO_CONTENT, response.content.decode()
channel = Channel.find_by_id(channel.id)
vid1 = test_session.query(Video).one()
assert str(channel.directory) == str(test_directory / 'videos/New Directory')
assert str(vid1.video_path).startswith(str(test_directory / 'videos/New Directory/'))
@pytest.mark.asyncio
async def test_search_tagged_channels(test_async_client, test_session, channel_factory, tag_factory,
video_factory):
"""Tagged Channels can be searched."""
tag = await tag_factory()
test_session.commit()
# Can search when empty.
body = dict(tag_names=[tag.name])
request, response = await test_async_client.post('/api/videos/channels/search', json=body)
assert response.status_code == HTTPStatus.OK
assert len(response.json['channels']) == 0, 'No Channels should be tagged'
channel1 = channel_factory(tag_name=tag.name)
channel2 = channel_factory()
test_session.commit()
body = dict(tag_names=[tag.name])
request, response = await test_async_client.post('/api/videos/channels/search', json=body)
assert response.status_code == HTTPStatus.OK
assert len(response.json['channels']) == 1, 'Only one Channel is tagged'
assert response.json['channels'][0]['id'] == channel1.id

View file

@ -1,6 +1,7 @@
from typing import List
import pytest
import yaml
from modules.videos import schema
from modules.videos.channel import lib
@ -124,3 +125,23 @@ async def test_search_channels_by_name(test_session, channel_factory, video_fact
await assert_search('foo', ['foo', 'foo bar', 'foobar'])
await assert_search('bar', ['foobar', 'foo bar', 'bar'], True)
@pytest.mark.asyncio
async def test_tag_channel_existing(test_async_client, test_session, test_directory, channel_factory, tag_factory,
video_factory, test_channels_config):
"""A Channel can already exist in a Tag's directory and still be tagged."""
channel_directory = test_directory / 'videos/one/Channel Name'
channel = channel_factory(name='Channel Name', download_frequency=120, directory=channel_directory)
video_factory(channel_id=channel.id)
test_session.commit()
assert str(channel.directory).startswith(f'{test_directory}/videos/one/')
tag = await tag_factory()
await lib.tag_channel(tag.name, channel_directory, channel.id, test_session)
# Channel's tag is saved to the config.
save_channels_config(test_session)
with test_channels_config.open() as fh:
config = yaml.load(fh, Loader=yaml.Loader)
assert config['channels'][0]['tag_name'] == tag.name

View file

@ -17,7 +17,7 @@ from sqlalchemy.orm import Session
from wrolpi.captions import FFMPEG_BIN
from wrolpi.cmd import FFPROBE_BIN
from wrolpi.common import logger, get_media_directory, get_wrolpi_config
from wrolpi.common import logger, get_media_directory
from wrolpi.dates import seconds_to_timestamp
from wrolpi.db import get_db_session, get_db_curs
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS
@ -204,7 +204,7 @@ def is_valid_poster(poster_path: Path) -> bool:
async def ffprobe_json(video_path: Union[Path, str]) -> dict:
"""Extract video file metadata using ffprobe.
>>> ffprobe_json('video')
>>> ffprobe_json('video.mp4')
{
'chapters': [],
'format': {},
@ -270,39 +270,6 @@ def get_video_duration(video_path: Path) -> Optional[int]:
return duration
def check_for_video_corruption(video_path: Path) -> bool:
"""Uses ffprobe to check for specific ways a video file can be corrupt.
Also attempts to screenshot the video near the end of it's duration, this check if the video is corrupted somewhere
in the middle."""
video_path = Path(video_path) if not isinstance(video_path, Path) else video_path
if not video_path.is_file():
raise FileNotFoundError(f'{video_path} does not exist!')
if not FFPROBE_BIN:
raise SystemError('ffprobe is not installed!')
# Just read the video using FFMPEG, this prints out useful information about the video.
cmd = (FFPROBE_BIN, str(video_path))
try:
proc = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
logger.warning(f'FFPROBE failed to check for corruption with stderr: {e.stderr.decode()}')
return True # video is corrupt.
messages = (
b'Invalid NAL unit size',
b'Error splitting the input into NAL units',
b'Invalid data found when processing input',
)
corrupt = False
for error in messages:
if error in proc.stderr:
logger.warning(f'Possible video corruption ({error.decode()}): {video_path}')
corrupt = True
return corrupt
async def update_view_counts_and_censored(channel_id: int):
"""Update view_count for all Videos in a channel using its info_json file. Also sets FileGroup.censored
if Video is no longer available on the Channel."""

View file

@ -40,14 +40,16 @@ def channel_factory(test_session, test_directory):
def factory(source_id: str = None, download_frequency: DownloadFrequency = None, url: str = None, name: str = None,
directory: pathlib.Path = None, tag_name: str = None):
name = name or str(uuid4())
tag = Tag.get_by_name(tag_name) if tag_name else None
tag = Tag.find_by_name(tag_name) if tag_name else None
channel = Channel(
name=name,
url=url or f'https://example.com/{name}',
source_id=source_id,
tag=tag,
tag_id=tag.id if tag else None,
)
channel.directory = directory or format_videos_destination(name, tag, channel.url)
tag_name = tag.name if tag else None
channel.directory = directory or format_videos_destination(name, tag_name, channel.url)
channel.directory.mkdir(exist_ok=True, parents=True)
test_session.add(channel)
test_session.flush([channel])
@ -242,12 +244,12 @@ def video_with_search_factory(test_session, test_directory, video_file_factory):
@pytest.fixture
def assert_video_search(test_client):
def assert_video_search(test_async_client):
"""A fixture which performs a video search request against the API.
If assert_* params are passed, the response is checked."""
def _search_videos(
async def _search_videos(
assert_total: int = None,
assert_ids: List[int] = None,
assert_paths: List[str] = None,
@ -272,7 +274,7 @@ def assert_video_search(test_client):
if channel_id is not None:
content['channel_id'] = channel_id
request, response = test_client.post('/api/videos/search', content=json.dumps(content))
request, response = await test_async_client.post('/api/videos/search', content=json.dumps(content))
assert response.json
assert response.status_code == HTTPStatus.OK

View file

@ -4,7 +4,7 @@ import os.path
import pathlib
import traceback
from abc import ABC
from typing import Tuple, List, Dict
from typing import Tuple, List, Dict, Optional
import yt_dlp.utils
from sqlalchemy.orm import Session
@ -64,6 +64,7 @@ def extract_info(url: str, ydl: YoutubeDL = YDL, process=False) -> dict:
def prepare_filename(entry: dict, ydl: YoutubeDL = YDL) -> str:
"""Get filename from YoutubeDL. Separated for testing."""
dir_name, file_name = os.path.split(ydl.prepare_filename(entry))
file_name = escape_file_name(file_name)
file_name = trim_file_name(file_name)
return f'{dir_name}/{file_name}'
@ -241,8 +242,8 @@ class VideoDownloader(Downloader, ABC):
# Video may have been downloaded previously, get its location for error reporting.
with get_db_session() as session:
videos = session.query(Video).join(FileGroup).filter_by(url=url).all()
location = videos[0].location if videos else None
video_ = Video.get_by_url(url, session)
location = video_.location if video_ else None
try:
download.info_json = download.info_json or extract_info(url)
@ -257,62 +258,7 @@ class VideoDownloader(Downloader, ABC):
if not download.info_json:
raise ValueError(f'Cannot download video with no info_json.')
found_channel = None
# Look for Channel using channel data first, fallback to uploader data.
channel_name = download.info_json.get('channel') or download.info_json.get('uploader')
channel_source_id = download.info_json.get('channel_id') or download.info_json.get('uploader_id')
channel_url = download.info_json.get('channel_url') or download.info_json.get('uploader_url')
channel = None
if channel_name or channel_source_id or channel_url:
# Try to find the channel via info_json from yt-dlp.
try:
channel = get_or_create_channel(source_id=channel_source_id, url=channel_url, name=channel_name)
if channel:
found_channel = 'yt_dlp'
logger.debug(f'Found a channel with source_id {channel=}')
except UnknownChannel:
# Can't find a channel, use the no channel directory.
pass
settings = download.settings or dict()
destination = settings.get('destination')
if not channel and destination:
# Destination may find Channel if not already found.
try:
channel = get_channel(directory=destination, return_dict=False)
found_channel = 'download_settings_directory'
logger.debug(f'Found a channel that shares the destination directory {channel=}')
except UnknownChannel:
# Destination must not be a channel.
pass
local_channel_id = settings.get('channel_id')
channel_url = settings.get('channel_url')
if not channel and (local_channel_id or channel_url):
# Could not find Channel via yt-dlp info_json, use info from ChannelDownloader if it created this Download.
logger.info(f'Using download.settings to find channel')
try:
channel = get_channel(channel_id=local_channel_id, url=channel_url, return_dict=False)
logger.debug(f'Found channel with channel url {channel=}')
except UnknownChannel:
# We do not need a Channel if we have a destination directory.
if not destination:
raise
if channel:
found_channel = 'download_settings'
channel_id = channel.id if channel else None
channel_directory = channel.directory if channel else None
if found_channel == 'yt_dlp':
logger.debug(f'Found {channel} using yt_dlp')
elif found_channel == 'download_settings':
logger.info(f'Found {channel} using Download.settings')
elif found_channel == 'download_settings_directory':
logger.info(f'Found {channel} using Download.settings directory')
else:
logger.warning('Could not find channel')
channel, channel_directory, channel_id, destination, settings = await self._get_channel(download)
if destination:
# Download to the directory specified in the settings.
@ -480,6 +426,63 @@ class VideoDownloader(Downloader, ABC):
)
return result
@staticmethod
async def _get_channel(download: Download) \
-> Tuple[Optional[Channel], Optional[pathlib.Path], Optional[int], Optional[pathlib.Path], dict]:
found_channel = None
# Look for Channel using channel data first, fallback to uploader data.
channel_name = download.info_json.get('channel') or download.info_json.get('uploader')
channel_source_id = download.info_json.get('channel_id') or download.info_json.get('uploader_id')
channel_url = download.info_json.get('channel_url') or download.info_json.get('uploader_url')
channel = None
if channel_name or channel_source_id or channel_url:
# Try to find the channel via info_json from yt-dlp.
try:
channel = get_or_create_channel(source_id=channel_source_id, url=channel_url, name=channel_name)
if channel:
found_channel = 'yt_dlp'
logger.debug(f'Found a channel with source_id {channel=}')
except UnknownChannel:
# Can't find a channel, use the no channel directory.
pass
settings = download.settings or dict()
destination = settings.get('destination')
if not channel and destination:
# Destination may find Channel if not already found.
try:
channel = get_channel(directory=destination, return_dict=False)
found_channel = 'download_settings_directory'
logger.debug(f'Found a channel that shares the destination directory {channel=}')
except UnknownChannel:
# Destination must not be a channel.
pass
channel_id = settings.get('channel_id')
channel_url = settings.get('channel_url')
if not channel and (channel_id or channel_url):
# Could not find Channel via yt-dlp info_json, use info from ChannelDownloader if it created this Download.
logger.info(f'Using download.settings to find channel')
try:
channel = get_channel(channel_id=channel_id, url=channel_url, return_dict=False)
logger.debug(f'Found channel with channel url {channel=}')
except UnknownChannel:
# We do not need a Channel if we have a destination directory.
if not destination:
raise
if channel:
found_channel = 'download_settings'
channel_id = channel.id if channel else None
channel_directory = channel.directory if channel else None
if found_channel == 'yt_dlp':
logger.debug(f'Found {channel} using yt_dlp')
elif found_channel == 'download_settings':
logger.info(f'Found {channel} using Download.settings')
elif found_channel == 'download_settings_directory':
logger.info(f'Found {channel} using Download.settings directory')
else:
logger.warning('Could not find channel')
return channel, channel_directory, channel_id, destination, settings
@staticmethod
def prepare_filename(url: str, out_dir: pathlib.Path) -> Tuple[pathlib.Path, dict]:
"""Get the full path of a video file from its URL."""

View file

@ -3,6 +3,7 @@ import dataclasses
import html
import pathlib
import re
import traceback
from typing import Generator
from typing import Tuple, Optional
@ -15,7 +16,7 @@ from modules.videos.models import Video
from wrolpi import before_startup, dates, flags
from wrolpi.captions import extract_captions
from wrolpi.common import ConfigFile, limit_concurrent, get_wrolpi_config, extract_domain, \
escape_file_name, get_media_directory
escape_file_name, get_media_directory, background_task
from wrolpi.dates import Seconds, from_timestamp
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download
@ -379,6 +380,22 @@ def save_channels_config(session: Session = None):
channel_import_logger = logger.getChild('channel_import')
async def fetch_channel_source_id(channel_id: int):
# If we can download from a channel, we must have its source_id.
try:
with get_db_session() as session:
from modules.videos.channel.lib import get_channel
channel = Channel.find_by_id(channel_id)
channel.source_id = channel.source_id or get_channel_source_id(channel.url)
if not channel.source_id:
channel_import_logger.warning(f'Unable to fetch source_id for {channel.url}')
else:
session.commit()
save_channels_config(session)
except Exception as e:
logger.error(f'Failed to get Channel source id of id={channel_id}', exc_info=e)
@before_startup
@limit_concurrent(1)
def import_channels_config():
@ -387,13 +404,17 @@ def import_channels_config():
logger.warning('Skipping import_channels_config for this test')
return
from .channel.lib import get_channel
channel_import_logger.info('Importing channels config')
try:
config = get_channels_config()
channels = config.channels
channel_directories = [i['directory'] for i in channels]
if len(channel_directories) != len(set(channel_directories)):
logger.error('Refusing to import channels config because it contains duplicate directories!')
return
updated_channel_ids = set()
save_config = False
with get_db_session(commit=True) as session:
for data in channels:
if isinstance(data, str):
@ -405,45 +426,37 @@ def import_channels_config():
for option in (i for i in REQUIRED_OPTIONS if i not in data):
raise ConfigError(f'Channel "{directory}" is required to have "{option}"')
channel = session.query(Channel).filter(
or_(
Channel.directory == str(directory),
Channel.directory == str(data['directory']),
Channel.directory == str(directory.relative_to(get_media_directory())),
),
).one_or_none()
# Try to find Channel by directory because it is unique.
channel = Channel.get_by_path(directory, session)
if not channel:
# Channel not yet in the DB, add it.
channel = Channel(directory=directory)
session.add(channel)
session.flush([channel, ])
# TODO refresh the files in the channel.
logger.warning(f'Creating new Channel from config {channel}')
# Only name and directory are required
channel.name = data['name']
channel.directory = directory
# A URL should not be an empty string
data['url'] = data['url'] or None
try:
# Try to find Channel using other attributes before creating new Channel.
channel = get_channel(
session,
source_id=data.get('source_id'),
url=data.get('url'),
directory=str(directory),
return_dict=False,
)
except UnknownChannel:
# Channel not yet in the DB, add it.
channel = Channel(directory=directory)
session.add(channel)
channel.flush()
# TODO refresh the files in the channel.
logger.warning(f'Creating new Channel from config {channel}')
# Copy existing channel data, update all values from the config. This is necessary to clear out
# values not in the config.
full_data = channel.dict()
full_data.update(data)
channel.update(full_data)
updated_channel_ids.add(channel.id)
if not channel.source_id and channel.url and flags.have_internet.is_set():
# If we can download from a channel, we must have its source_id.
try:
channel.source_id = get_channel_source_id(channel.url)
save_config = True
if not channel.source_id:
channel_import_logger.warning(f'Unable to fetch source_id for {channel.url}')
else:
session.commit()
except Exception as e:
logger.error(f'Failed to get Channel source id of {channel}', exc_info=e)
logger.info(f'Fetching channel source id for {channel}')
background_task(fetch_channel_source_id(channel.id))
channel_import_logger.debug(f'Updated {repr(channel.name)}'
f' url={channel.url}'
@ -454,17 +467,13 @@ def import_channels_config():
with get_db_session(commit=True) as session:
# Delete any Channels that were deleted from the config.
for channel in session.query(Channel):
if str(channel.directory) not in channel_directories:
if channel.id not in updated_channel_ids:
logger.warning(f'Deleting {channel} because it is not in the config.')
channel.delete_with_videos()
# Create any missing Downloads. Associated Downloads with any necessary Channels.
link_channel_and_downloads()
if save_config:
# Information about the channel was fetched, store it.
save_channels_config()
except Exception as e:
channel_import_logger.warning('Failed to load channels config!', exc_info=e)
if PYTEST:
@ -544,7 +553,8 @@ async def get_statistics():
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 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
@ -583,9 +593,11 @@ async def get_statistics():
curs.execute('''
SELECT
COUNT(id) AS "channels"
COUNT(c.id) AS "channels",
COUNT(c.id) FILTER ( WHERE c.tag_id IS NOT NULL ) AS "tagged_channels"
FROM
channel
channel c
LEFT JOIN public.tag t on t.id = c.tag_id
''')
channel_stats = dict(curs.fetchone())
ret = dict(statistics=dict(

View file

@ -1,4 +1,5 @@
import json
import json
import pathlib
from typing import Optional, Dict, List
@ -7,11 +8,14 @@ from sqlalchemy.orm import relationship, Session, deferred
from sqlalchemy.orm.collections import InstrumentedList
from modules.videos.errors import UnknownVideo, UnknownChannel
from wrolpi import flags
from wrolpi.captions import read_captions
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task, replace_file
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task, replace_file, \
unique_by_predicate
from wrolpi.db import get_db_curs, get_db_session, optional_session
from wrolpi.downloader import Download, download_manager, save_downloads_config
from wrolpi.errors import InvalidDownload
from wrolpi.events import Events
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix, move
from wrolpi.files.models import FileGroup
from wrolpi.media_path import MediaPathType
@ -223,6 +227,7 @@ class Video(ModelHelper, Base):
# Can't validate if there is no video file.
logger.error(f'Unable to validate video {self.id} without primary file!')
logger.debug(f'Validating {self}')
from .lib import validate_video
try:
validate_video(self, self.channel.generate_posters if self.channel else False)
@ -237,12 +242,14 @@ class Video(ModelHelper, Base):
# self.file_group.d_text is handled in `validate_video`.
if (comments := self.get_comments()) and len(comments) >= 5:
logger.debug(f'{self} has comments')
self.have_comments = True
# If this Video is in a Channel's directory, then it is part of that Channel.
session: Session = Session.object_session(self)
if session and (channel := Channel.get_by_path(self.video_path.parent, session)):
self.channel = channel
logger.debug(f'{self} has Channel {channel}')
@staticmethod
def from_paths(session: Session, *paths: pathlib.Path) -> 'Video':
@ -533,7 +540,7 @@ class Channel(ModelHelper, Base):
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
downloads: InstrumentedList = relationship('Download', primaryjoin='Download.channel_id==Channel.id')
tag_id = Column(Integer, ForeignKey('tag.id', ondelete='CASCADE'))
tag = relationship('Tag')
tag = relationship('Tag', primaryjoin='Channel.tag_id==Tag.id')
def __repr__(self):
return f'<Channel id={self.id} name={repr(self.name)} url={self.url} directory={self.directory}>'
@ -565,12 +572,9 @@ class Channel(ModelHelper, Base):
channel_id = self.id
data = data.copy()
# Remove unused values.
data.pop('move_to_tag_directory', None)
# URL should not be empty string.
if 'url' in data:
data['url'] = data['url'] or None
url = data.pop('url')
self.url = url or None
session: Session = Session.object_session(self)
@ -664,23 +668,19 @@ class Channel(ModelHelper, Base):
with get_db_curs() as curs:
stmt = '''
SELECT
SUM(size),
MAX(size),
COUNT(video.id),
SUM(fg.length)
SUM(size) AS "size",
MAX(size) AS "largest_video",
COUNT(video.id) AS "video_count",
SUM(fg.length) AS "length",
-- Videos may use multiple tags.
COUNT(video.id) FILTER ( WHERE tf.file_group_id IS NOT NULL ) AS "video_tags"
FROM video
LEFT JOIN file_group fg on fg.id = video.file_group_id
LEFT JOIN public.tag_file tf on fg.id = tf.file_group_id
WHERE channel_id = %(id)s
'''
curs.execute(stmt, dict(id=self.id))
size, largest_video, video_count, length = curs.fetchone()
statistics = dict(
video_count=video_count,
size=size,
largest_video=largest_video,
length=length,
)
return statistics
return dict(curs.fetchone())
async def refresh_files(self, send_events: bool = True):
"""Refresh all files within this Channel's directory. Mark this channel as refreshed."""
@ -772,39 +772,72 @@ class Channel(ModelHelper, Base):
channel = session.query(Channel).filter_by(url=url).one_or_none()
return channel
async def move(self, directory: pathlib.Path, session: Session):
def format_directory(self, tag_name: str) -> pathlib.Path:
from modules.videos.lib import format_videos_destination
return format_videos_destination(self.name, tag_name, self.url)
async def move_channel(self, directory: pathlib.Path, session: Session, send_events: bool = False):
"""Move the files of this Channel into a new directory."""
if not directory.is_dir():
raise FileNotFoundError(f'Destination directory does not exist: {directory}')
if self.directory and not next(self.directory.iterdir(), None):
raise FileExistsError(f'Refusing to move Channel when it has no files.')
old_directory = self.directory
self.directory = directory
session.flush([self, ])
# Change destination of all Downloads of this Channel, or any Downloads which download into this Channel's
# directory.
downloads = list(self.downloads)
downloads.extend(list(
session.query(Download).filter(Download.settings.contains({'destination': str(old_directory)}))
))
for download in downloads:
# Get new copy of `settings` to avoid bug where it wouldn't update.
settings = download.settings.copy() if download.settings else dict()
if settings.get('destination'):
download.settings = {**settings, 'destination': str(directory)}
def change_download_destinations(from_directory: pathlib.Path, to_directory: pathlib.Path):
downloads = list(self.downloads)
downloads.extend(Download.get_all_by_destination(from_directory))
downloads = unique_by_predicate(downloads, lambda i: i.id)
for download in downloads:
# Get new copy of `settings` to avoid bug where it wouldn't update.
settings = download.settings.copy() if download.settings else dict()
if settings.get('destination'):
logger.debug(f'Updating destination of {download}')
download.settings = {**settings, 'destination': str(to_directory)}
session.flush(downloads)
session.commit()
# Only one tag can be moved at a time.
with flags.refreshing:
# Change destination of all Downloads of this Channel, or any Downloads which download into this Channel's
# directory.
change_download_destinations(old_directory, directory)
# Save configs before move, this is because move imports configs.
from modules.videos.lib import save_channels_config
await save_downloads_config(session)
save_channels_config(session)
save_tags_config(session)
session.commit()
# Move the contents of the Channel directory into the destination directory.
await move(directory, *list(old_directory.iterdir()))
# Save configs before move, this is because move imports configs.
from modules.videos.lib import save_channels_config
await save_downloads_config(session)
save_channels_config(session)
save_tags_config(session)
if old_directory.exists() and not next(old_directory.iterdir(), None):
old_directory.rmdir()
# Move the contents of the Channel directory into the destination directory.
logger.info(f'Moving {self} from {repr(str(old_directory))}')
try:
if not old_directory.exists():
# Old directory does not exist, maintainer must have moved the Channel manually.
if PYTEST:
await refresh_files([old_directory, directory])
else:
background_task(refresh_files([old_directory, directory]))
if send_events:
Events.send_file_move_completed(f'Channel {repr(self.name)} was moved, but Tags were lost')
else:
# `move` also uses `flags.refreshing`
await move(directory, *list(old_directory.iterdir()))
if send_events:
Events.send_file_move_completed(f'Channel {repr(self.name)} was moved')
except Exception as e:
logger.error(f'Channel move failed! Reverting changes...', exc_info=e)
# Downloads must be moved back to the old directory.
change_download_destinations(directory, old_directory)
self.directory = old_directory
self.flush(session)
if send_events:
Events.send_file_move_failed(f'Moving Channel {self.name} has failed')
raise
finally:
session.commit()
if old_directory.exists() and not next(iter(old_directory.iterdir()), None):
# Old directory is empty, delete it.
old_directory.rmdir()

View file

@ -49,6 +49,7 @@ class ChannelTagRequest:
@dataclass
class ChannelTagInfoRequest:
channel_id: Optional[int] = None
tag_name: Optional[str] = None
@ -205,6 +206,7 @@ class VideoStatistics:
@dataclass
class ChannelStatistics:
channels: int
tagged_channels: int
@dataclass
@ -222,3 +224,8 @@ class CensoredVideoRequest:
@dataclass
class CensoredVideoResponse:
videos: List[VideoWithChannel]
@dataclass
class ChannelSearchRequest:
tag_names: List[str] = field(default_factory=list)

View file

@ -6,6 +6,7 @@ import pytest
from modules.videos.models import Video, Channel
from modules.videos.video import lib as video_lib
from wrolpi.common import get_wrolpi_config
from wrolpi.db import get_db_curs
from wrolpi.downloader import Download
from wrolpi.files.lib import refresh_files
@ -160,14 +161,15 @@ def test_api_download(test_session, test_client, test_directory):
assert not download.settings.get('tag_names')
def test_api_download_video_tags(test_session, test_client, tag_factory):
@pytest.mark.asyncio
async def test_api_download_video_tags(test_session, test_async_client, tag_factory):
"""A user can request Tags for a video being downloaded."""
tag1 = tag_factory()
tag2 = tag_factory()
tag1 = await tag_factory()
tag2 = await tag_factory()
content = dict(urls=['https://example.com/video1', ], downloader='video',
settings={'tag_names': [tag1.name, tag2.name]})
request, response = test_client.post('/api/download', content=json.dumps(content))
request, response = await test_async_client.post('/api/download', content=json.dumps(content))
assert response.status_code == HTTPStatus.NO_CONTENT
download = test_session.query(Download).one()
@ -176,7 +178,9 @@ def test_api_download_video_tags(test_session, test_client, tag_factory):
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):
@pytest.mark.asyncio
async 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.
videos = [
@ -193,37 +197,38 @@ def test_search_videos_file(test_client, test_session, test_directory, video_wit
# Repeated runs should return the same result
for _ in range(2):
# Only videos with a b are returned, ordered by the amount of b's
assert_video_search(search_str='b', assert_ids=[1, 2, 3, 4])
await assert_video_search(search_str='b', assert_ids=[1, 2, 3, 4])
# Only two captions have e
assert_video_search(search_str='e', assert_ids=[4, 1])
await assert_video_search(search_str='e', assert_ids=[4, 1])
# Only 2 contains 2
assert_video_search(search_str='2', assert_ids=[2, ])
await assert_video_search(search_str='2', assert_ids=[2, ])
# Only two captions have d
assert_video_search(search_str='d', assert_ids=[1, 2])
await assert_video_search(search_str='d', assert_ids=[1, 2])
# 5 can be gotten by it's title
assert_video_search(search_str='5', assert_ids=[5, ])
await assert_video_search(search_str='5', assert_ids=[5, ])
# only video 1 has e and d
assert_video_search(search_str='e d', assert_ids=[1, ])
await assert_video_search(search_str='e d', assert_ids=[1, ])
# video 1 and 4 have b and e, but 1 has more
assert_video_search(search_str='b e', assert_ids=[1, 4])
await assert_video_search(search_str='b e', assert_ids=[1, 4])
# Check totals are correct even with a limit
assert_video_search(search_str='b', limit=2, assert_ids=[1, 2], assert_total=4)
await assert_video_search(search_str='b', limit=2, assert_ids=[1, 2], assert_total=4)
def test_search_videos(test_session, video_factory, assert_video_search, simple_channel, tag_factory):
@pytest.mark.asyncio
async def test_search_videos(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)
vid3: Video = video_factory(upload_date='2022-09-18', with_video_file=True, title='vid3')
tag1, tag2 = tag_factory(), tag_factory()
tag1, tag2 = await tag_factory(), await tag_factory()
vid1.add_tag(tag1.id)
@ -237,22 +242,68 @@ def test_search_videos(test_session, video_factory, assert_video_search, simple_
assert test_session.query(Video).count() == 3
assert test_session.query(FileGroup).count() == 3
assert_video_search(assert_total=3, assert_ids=[vid1.id, vid2.id, vid3.id], order_by='published_datetime')
assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id, vid1.id], order_by='-published_datetime')
assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id], order_by='-published_datetime', limit=2)
assert_video_search(assert_total=3, assert_ids=[vid2.id, vid1.id], order_by='-published_datetime', limit=2,
offset=1)
assert_video_search(assert_total=1, assert_ids=[vid2.id], order_by='-published_datetime',
channel_id=simple_channel.id)
assert_video_search(assert_total=2, assert_ids=[vid1.id, vid2.id], tag_names=[tag1.name])
assert_video_search(assert_total=2, assert_ids=[vid3.id, vid2.id], tag_names=[tag2.name])
assert_video_search(assert_total=2, assert_ids=[vid1.id], tag_names=[tag1.name], limit=1)
await assert_video_search(assert_total=3, assert_ids=[vid1.id, vid2.id, vid3.id], order_by='published_datetime')
await assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id, vid1.id], order_by='-published_datetime')
await assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id], order_by='-published_datetime', limit=2)
await assert_video_search(assert_total=3, assert_ids=[vid2.id, vid1.id], order_by='-published_datetime', limit=2,
offset=1)
await assert_video_search(assert_total=1, assert_ids=[vid2.id], order_by='-published_datetime',
channel_id=simple_channel.id)
await assert_video_search(assert_total=2, assert_ids=[vid1.id, vid2.id], tag_names=[tag1.name])
await assert_video_search(assert_total=2, assert_ids=[vid3.id, vid2.id], tag_names=[tag2.name])
await assert_video_search(assert_total=2, assert_ids=[vid1.id], tag_names=[tag1.name], limit=1)
# Only vid2 has both tags.
assert_video_search(assert_total=1, assert_ids=[vid2.id], tag_names=[tag1.name, tag2.name])
await assert_video_search(assert_total=1, assert_ids=[vid2.id], tag_names=[tag1.name, tag2.name])
# No results, no total is returned from the DB.
assert_video_search(assert_total=0, assert_ids=[], tag_names=[tag1.name], offset=2)
await assert_video_search(assert_total=0, assert_ids=[], tag_names=[tag1.name], offset=2)
# Check all order_by.
for order_by in video_lib.VIDEO_ORDERS:
assert_video_search(order_by=order_by)
await assert_video_search(order_by=order_by)
@pytest.mark.asyncio
async def test_delete_video(test_async_client, test_session, video_factory, test_download_manager):
"""When a Video record is deleted, the FileGroup should be deleted. The URL is added to the
global skip list so the video is not downloaded again."""
video = video_factory(with_video_file=True, with_poster_ext='png')
video.file_group.url = 'https://example.com/video/1'
files = video.file_group.my_paths()
test_session.commit()
request, response = await test_async_client.delete(f'/api/videos/video/{video.id}')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_session.query(Video).count() == 0, 'Video was not deleted.'
assert test_session.query(FileGroup).count() == 0, 'Video FileGroup was not deleted.'
assert not any(i.exists() for i in files), 'All files should have been deleted.'
assert test_download_manager.is_skipped('https://example.com/video/1'), 'Video should not be downloaded again.'
@pytest.mark.asyncio
async def test_format_videos_description(test_async_client, test_session, test_directory, channel_factory, tag_factory):
channel = channel_factory(name='Channel Name')
tag = await tag_factory()
test_session.commit()
body = dict()
request, response = await test_async_client.post('/api/videos/tag_info', json=body)
assert response.status_code == HTTPStatus.OK
assert response.json['videos_destination'] == 'videos'
body = dict(channel_id=channel.id)
request, response = await test_async_client.post('/api/videos/tag_info', json=body)
assert response.status_code == HTTPStatus.OK
assert response.json['videos_destination'] == 'videos/Channel Name'
body = dict(channel_id=channel.id, tag_name=tag.name)
request, response = await test_async_client.post('/api/videos/tag_info', json=body)
assert response.status_code == HTTPStatus.OK
assert response.json['videos_destination'] == 'videos/one/Channel Name'
get_wrolpi_config().videos_destination = 'videos/%(channel_tag)s/%(channel_domain)s/%(channel_name)s'
body = dict(channel_id=channel.id, tag_name=tag.name)
request, response = await test_async_client.post('/api/videos/tag_info', json=body)
assert response.status_code == HTTPStatus.OK
assert response.json['videos_destination'] == 'videos/one/example.com/Channel Name'

View file

@ -135,10 +135,12 @@ def test_generate_video_poster(video_file):
@pytest.mark.asyncio
async def test_import_channel_downloads(test_async_client, test_session, channel_factory, test_channels_config):
async def test_import_channel_downloads(test_async_client, test_session, channel_factory, test_channels_config,
tag_factory):
"""Importing the Channels' config should create any missing download records"""
channel1 = channel_factory(source_id='foo', url='https://example.com/channel1')
channel2 = channel_factory(source_id='bar', url='https://example.com/channel2')
tag = await tag_factory()
assert len(test_session.query(Channel).all()) == 2
test_session.commit()
@ -228,8 +230,19 @@ async def test_import_channel_downloads(test_async_client, test_session, channel
assert {i.url for i in channel1.downloads} == {'https://example.com/channel1'}
assert {i.url for i in channel2.downloads} == {'https://example.com/channel2', 'https://example.org'}
# A Channel with a `tag_name` is tagged.
update_channel_config(get_channels_config(),
channel1.source_id,
{'tag_name': tag.name})
import_channels_config()
channel1, channel2 = test_session.query(Channel).order_by(Channel.url).all()
assert channel1.tag == tag and channel1.tag_id == tag.id
assert channel2.tag is None and channel2.tag_id is None
def test_import_channel_delete_missing_channels(test_session, channel_factory, test_channels_config):
@pytest.mark.asyncio
async def test_import_channel_delete_missing_channels(
test_async_client, test_session, channel_factory, test_channels_config):
"""The Channel import function deletes any Channels that are not in the config."""
# Create a DB and config with two Channels.
channel1 = channel_factory(source_id='foo')
@ -268,32 +281,6 @@ def test_import_channel_delete_missing_channels(test_session, channel_factory, t
assert str(channel2.directory) not in test_channels_config.read_text()
def test_check_for_video_corruption(video_file, test_directory):
# The test video is not corrupt.
assert common.check_for_video_corruption(video_file) is False
# An empty file is corrupt.
empty_file = test_directory / 'empty file.mp4'
empty_file.touch()
assert common.check_for_video_corruption(empty_file) is True
# A video file must be complete.
truncated_video = test_directory / 'truncated_video.mp4'
with truncated_video.open('wb') as fh:
fh.write(video_file.read_bytes()[:10000])
assert common.check_for_video_corruption(truncated_video) is True
# Check for specific ffprobe errors.
with mock.patch('modules.videos.common.subprocess') as mock_subprocess:
# `video_file` is ignored for these calls.
mock_subprocess.run().stderr = b'Something\nInvalid NAL unit size'
assert common.check_for_video_corruption(video_file) is True
mock_subprocess.run().stderr = b'Something\nError splitting the input into NAL units'
assert common.check_for_video_corruption(video_file) is True
mock_subprocess.run().stderr = b'Some stderr is fine'
assert common.check_for_video_corruption(video_file) is False
@pytest.mark.asyncio
async def test_ffprobe_json(test_async_client, video_file, corrupted_video_file):
content = await common.ffprobe_json(video_file)

View file

@ -107,7 +107,7 @@ async def test_download_video_tags(test_session, video_download_manager, video_f
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()
tag1, tag2 = await tag_factory(), await tag_factory()
url = 'https://www.youtube.com/watch?v=31jPEBiAC3c'
mock_video_extract_info.return_value = copy(example_video_json)

View file

@ -34,7 +34,7 @@ async def test_channel_move(test_async_client, test_session, test_directory, cha
foo.mkdir(parents=True)
# Move the Channel.
await channel.move(foo, test_session)
await channel.move_channel(foo, test_session)
assert channel.directory == foo
assert channel.directory != (test_directory / 'New Channel Directory')

View file

@ -29,27 +29,11 @@ def test_delete_video_no_channel(test_session, simple_video):
assert test_session.query(Video).count() == 0
def test_delete_video(test_session, video_factory):
"""When a Video record is deleted, all referenced file records should be deleted."""
video = video_factory(with_video_file=True, with_poster_ext='png')
test_session.commit()
assert video.video_path.is_file(), 'Video file was not created.'
assert video.poster_path.is_file(), 'Video poster was not created.'
assert test_session.query(Video).count() == 1, 'Video was not created.'
assert test_session.query(FileGroup).count() == 1, 'Video file and poster file were not created.'
video.delete()
test_session.commit()
assert test_session.query(Video).count() == 0, 'Video was not deleted.'
assert test_session.query(FileGroup).count() == 0, 'Video files were not deleted.'
@pytest.mark.asyncio
async def test_delete_video_with_tag(test_async_client, test_session, video_factory, tag_factory):
"""You cannot delete a video with a tag."""
video = video_factory(with_video_file=True, with_poster_ext='png')
tag = tag_factory()
tag = await tag_factory()
video.add_tag(tag.name)
test_session.commit()
@ -63,7 +47,7 @@ async def test_delete_video_with_tag(test_async_client, test_session, video_fact
@pytest.mark.asyncio
async def test_video_channel_refresh(test_session, test_directory, channel_factory, video_factory):
async def test_video_channel_refresh(test_async_client, test_session, test_directory, channel_factory, video_factory):
"""A Video will be associated with a Channel when it's files are in that Channel's directory."""
# Create a video file in this channel's directory.
channel = channel_factory()
@ -101,7 +85,7 @@ async def test_delete_duplicate_video(test_session, channel_factory, video_facto
channel.info_json = {'entries': [{'id': 'ABC123456', 'title': 'The video title'}]}
entry = channel.info_json['entries'][0]
tag = tag_factory()
tag = await tag_factory()
vid1 = video_factory(
channel_id=channel.id,
title=f'{channel.name}_20000101_ABC123456_The video title',
@ -150,7 +134,7 @@ async def test_delete_duplicate_video(test_session, channel_factory, video_facto
@pytest.mark.asyncio
async def test_delete_renamed_video(test_session, channel_factory, video_factory, tag_factory):
async def test_delete_renamed_video(test_async_client, test_session, channel_factory, video_factory, tag_factory):
"""If duplicate Video's exist, delete all the videos that do not have the new title."""
channel = channel_factory(name='Channel Name')
video_path = channel.directory / f'{channel.name}_20000101_ABC123456_Some new title.mp4'
@ -158,7 +142,7 @@ async def test_delete_renamed_video(test_session, channel_factory, video_factory
channel.info_json = {'entries': [{'id': 'ABC123456', 'title': 'Some new title'}]}
entry = channel.info_json['entries'][0]
tag = tag_factory()
tag = await tag_factory()
vid1 = video_factory(
channel_id=channel.id,
title=f'{channel.name}_20000101_ABC123456_The video title',

View file

@ -164,8 +164,11 @@ def delete_videos(*video_ids: int, session: Session = None):
raise UnknownVideo('Could not find videos to delete')
logger.warning(f'Deleting {len(videos)} videos')
# Get all URLs, skip them once (so config isn't saved multiple times).
urls = list(filter(None, [i.file_group.url for i in videos]))
download_manager.add_to_skip_list(*urls)
for video in videos:
video.delete(add_to_skip_list=True)
video.delete()
session.commit()

View file

@ -9,7 +9,7 @@ from modules.videos.models import Video
from wrolpi.dates import now
def test_get_video_prev_next(test_session, channel_factory, video_factory):
def test_get_video_prev_next(test_async_client, test_session, channel_factory, video_factory):
"""
Test that the previous and next videos will be retrieved when fetching a video.
"""
@ -69,7 +69,7 @@ def test_get_video_prev_next(test_session, channel_factory, video_factory):
raise AssertionError(f'Assert failed for {id_=} {prev_title=} {next_title=}') from e
def test_get_video_prev_next_no_upload_date(test_session, video_factory, channel_factory):
def test_get_video_prev_next_no_upload_date(test_async_client, test_session, video_factory, channel_factory):
"""
Previous and Next Videos should be those next to a Video file when videos do not have upload dates.
"""
@ -153,7 +153,7 @@ async def test_wrol_mode(test_async_client, simple_channel, simple_video, wrol_m
test_download_manager, tag_factory):
"""Many methods are blocked when WROL Mode is enabled."""
channel = dumps(dict(name=simple_channel.name, directory=str(simple_channel.directory)))
tag = tag_factory()
tag = await tag_factory()
await wrol_mode_fixture(True)

View file

@ -100,14 +100,14 @@ def zim_factory(test_session, zim_path_factory, test_directory):
@pytest.fixture
def assert_zim_search(test_client, test_directory):
def assert_zim_search(test_async_client, test_directory):
from http import HTTPStatus
def _(search_str: str, zim_id: int, expected: Dict, tag_names: List[str] = [],
expected_status_code: int = HTTPStatus.OK):
async def _(search_str: str, zim_id: int, expected: Dict, tag_names: List[str] = [],
expected_status_code: int = HTTPStatus.OK):
content = dict(search_str=search_str, tag_names=tag_names)
assert isinstance(zim_id, int), 'This fixture only supports Zim ids of type integer'
request, response = test_client.post(f'api/zim/search/{zim_id}', content=json.dumps(content))
request, response = await test_async_client.post(f'api/zim/search/{zim_id}', content=json.dumps(content))
assert response.status_code == expected_status_code
result = response.json['zim']

View file

@ -16,7 +16,7 @@ from modules.zim.kiwix import KIWIX_CATALOG
from modules.zim.models import Zim, Zims, TagZimEntry, ZimSubscription
from wrolpi import flags
from wrolpi.common import register_modeler, logger, extract_html_text, extract_headlines, get_media_directory, walk, \
register_refresh_cleanup, background_task, get_wrolpi_config
register_refresh_cleanup, background_task, get_wrolpi_config, unique_by_predicate
from wrolpi.db import get_db_session, optional_session, get_db_curs
from wrolpi.downloader import DownloadFrequency
from wrolpi.files.lib import refresh_files, split_file_name_words
@ -124,14 +124,11 @@ def get_entries_tags(paths: List[str], zim_id: int):
def get_unique_paths(*paths: str) -> List[str]:
"""Return a new list which contains unique Zim paths."""
new_paths = list()
simple_paths = list()
for path in paths:
simple_path = path.replace('-', '').replace('_', '').replace('/', '').lower()
if simple_path not in simple_paths:
new_paths.append(path)
simple_paths.append(simple_path)
return new_paths
unique_paths = unique_by_predicate(
paths,
lambda i: i.replace('-', '').replace('_', '').replace('/', '').lower()
)
return list(unique_paths)
@optional_session

View file

@ -8,16 +8,17 @@ from modules.zim.models import Zim
from wrolpi.downloader import Download
def test_zim_search(test_client, test_session, test_zim, tag_factory, assert_zim_search):
@pytest.mark.asyncio
async def test_zim_search(test_async_client, test_session, test_zim, tag_factory, assert_zim_search):
"""Entries can be tagged and retrieved using their containing Zim."""
tag1, tag2 = tag_factory(), tag_factory()
tag1, tag2 = await tag_factory(), await tag_factory()
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
test_session.commit()
# Test searching with only `search_str`.
assert_zim_search('one', 1, {
await assert_zim_search('one', 1, {
'path': test_zim.path,
'search': [
# Entry "One" contains a 'one' in the title, and the text.
@ -27,13 +28,13 @@ def test_zim_search(test_client, test_session, test_zim, tag_factory, assert_zim
],
'estimate': 2,
})
assert_zim_search('two', 1, {
await assert_zim_search('two', 1, {
'path': test_zim.path,
'search': [{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
{'path': 'home', 'headline': 'testing.\nOne\n<b>Two</b>', 'rank': 0.06079271}],
'estimate': 2,
})
assert_zim_search('item', 1, {
await assert_zim_search('item', 1, {
'path': test_zim.path,
'search': [{'path': 'one', 'headline': 'first <b>item</b>', 'rank': 0.06079271},
{'path': 'two', 'headline': 'second <b>item</b>', 'rank': 0.06079271}],
@ -41,35 +42,35 @@ def test_zim_search(test_client, test_session, test_zim, tag_factory, assert_zim
})
# Test searching with `search_str` and `tag_names`.
assert_zim_search('one', 1, tag_names=[tag2.name, ], expected={
await assert_zim_search('one', 1, tag_names=[tag2.name, ], expected={
'search': [
# Only entry "One" is tagged with Tag 2.
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
],
'estimate': 1,
})
assert_zim_search('one', 1, tag_names=[tag1.name, tag2.name], expected={
await assert_zim_search('one', 1, tag_names=[tag1.name, tag2.name], expected={
'search': [
# Only "One" is tagged with Tag 1 and contains "one".
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.06079271},
],
'estimate': 1,
})
assert_zim_search('two', 1, tag_names=[tag1.name, ], expected={
await assert_zim_search('two', 1, tag_names=[tag1.name, ], expected={
'search': [
# Only "Two" was tagged with Tag 1 and contains "two".
{'path': 'two', 'headline': 'This is the second item', 'rank': 0.06079271},
],
'estimate': 1,
})
assert_zim_search('two', 1, tag_names=[tag2.name, ], expected={
await assert_zim_search('two', 1, tag_names=[tag2.name, ], expected={
# Two was not tagged with Tag 1.
'search': [],
'estimate': 0,
})
# Test search with only `tag_names`.
assert_zim_search('', 1, tag_names=[tag1.name, tag2.name], expected={
await assert_zim_search('', 1, tag_names=[tag1.name, tag2.name], expected={
'search': [
# Return all entries that are tagged with the Tags.
{'path': 'one', 'headline': 'This is the first item', 'rank': 0.0, 'tag_names': ['one', 'two']},
@ -78,9 +79,10 @@ def test_zim_search(test_client, test_session, test_zim, tag_factory, assert_zim
})
def test_entries_by_tag(test_client, test_session, test_zim, tag_factory):
@pytest.mark.asyncio
async def test_entries_by_tag(test_async_client, test_session, test_zim, tag_factory):
"""Entries can be tagged and retrieved using their containing Zim."""
tag1, tag2 = tag_factory(), tag_factory()
tag1, tag2 = await tag_factory(), await tag_factory()
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
@ -96,36 +98,38 @@ def test_entries_by_tag(test_client, test_session, test_zim, tag_factory):
assert [(i.path, i.title) for i in result] == [('one', 'One'), ]
def test_zim_crud(test_client, test_session, test_directory, test_zim):
request, response = test_client.get('/api/zim')
@pytest.mark.asyncio
async def test_zim_crud(test_async_client, test_session, test_directory, test_zim):
request, response = await test_async_client.get('/api/zim')
assert response.status_code == HTTPStatus.OK
assert len(response.json['zims']) == 1
assert response.json['zims'][0]['path'] == test_zim.path.name
request, response = test_client.delete('/api/zim/1')
request, response = await test_async_client.delete('/api/zim/1')
assert response.status_code == HTTPStatus.NO_CONTENT
assert not test_zim.path.exists()
assert test_session.query(Zim).count() == 0
def test_zim_tag_and_untag(test_client, test_session, test_zim, tag_factory):
@pytest.mark.asyncio
async def test_zim_tag_and_untag(test_async_client, test_session, test_zim, tag_factory):
"""Zim entries can be Tagged and Untagged."""
tag1, tag2 = tag_factory(), tag_factory()
tag1, tag2 = await tag_factory(), await tag_factory()
test_session.commit()
# Entries can be tagged in the API.
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
request, response = test_client.post('/api/zim/tag', content=json.dumps(content))
request, response = await test_async_client.post('/api/zim/tag', content=json.dumps(content))
assert response.status_code == HTTPStatus.CREATED
# Entries can be untagged in the API.
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
request, response = test_client.post('/api/zim/untag', content=json.dumps(content))
request, response = await test_async_client.post('/api/zim/untag', content=json.dumps(content))
assert response.status_code == HTTPStatus.NO_CONTENT
# Cannot untag twice.
content = dict(tag_name=tag1.name, zim_id=test_zim.id, zim_entry='home')
request, response = test_client.post('/api/zim/untag', content=json.dumps(content))
request, response = await test_async_client.post('/api/zim/untag', content=json.dumps(content))
assert response.status_code == HTTPStatus.NOT_FOUND

View file

@ -51,14 +51,14 @@ async def test_zim_get_entry(test_async_client, test_session, zim_path_factory):
@pytest.mark.asyncio
async def test_zim_bad_entry(test_async_client, test_session, test_zim, tag_factory):
tag1 = tag_factory()
tag1 = await tag_factory()
with pytest.raises(UnknownZimEntry):
test_zim.tag_entry(tag1.name, 'path does not exist')
@pytest.mark.asyncio
async def test_zim_get_entries_tags(test_async_client, test_session, test_zim, tag_factory):
tag1, tag2 = tag_factory('tag1'), tag_factory('tag2')
tag1, tag2 = await tag_factory('tag1'), await tag_factory('tag2')
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
@ -70,7 +70,8 @@ async def test_zim_get_entries_tags(test_async_client, test_session, test_zim, t
@pytest.mark.asyncio
async def test_tag_zim_entry_model(test_async_client, test_session, zim_factory, tag_factory):
tze = zim_factory('zim1').tag_entry(tag_factory().name, 'one')
tag = await tag_factory()
tze = zim_factory('zim1').tag_entry(tag.name, 'one')
# Test TagZimEntry.__repr__
assert repr(tze) == "<TagZimEntry tag='one' zim=zim1 zim_entry=one>"
@ -78,7 +79,7 @@ async def test_tag_zim_entry_model(test_async_client, test_session, zim_factory,
@pytest.mark.asyncio
async def test_zim_entries_with_tags(test_async_client, test_session, zim_factory, tag_factory):
"""Can fetch Zim Entries that have Tags. Can filter only those entries that are tagged on a specific Zim."""
tag1, tag2 = tag_factory(), tag_factory()
tag1, tag2 = await tag_factory(), await tag_factory()
zim1, zim2 = zim_factory('zim1'), zim_factory('zim2')
# Tag Zim1 with both tags, but Zim2 shares one of the tags and is returned when no Zim is passed.
zim1.tag_entry(tag1.name, 'one')
@ -124,13 +125,14 @@ def test_get_unique_paths():
'A/Thomas_Harvey_Johnston']
def test_zim_tags_config(test_session, test_directory, test_zim, tag_factory, test_tags_config, fake_now):
@pytest.mark.asyncio
async def test_zim_tags_config(test_session, test_directory, test_zim, tag_factory, test_tags_config, fake_now):
fake_now(datetime.datetime(2000, 1, 1, 0, 0, 0, 1))
config = tags.get_tags_config()
assert not config.tag_zims
# Tag three Zim entries.
tag1, tag2 = tag_factory('Tag1'), tag_factory('Tag2')
tag1, tag2 = await tag_factory('Tag1'), await tag_factory('Tag2')
test_zim.tag_entry(tag1.name, 'one')
test_zim.tag_entry(tag2.name, 'one')
test_zim.tag_entry(tag1.name, 'two')
@ -243,12 +245,13 @@ async def test_zim_download(test_session, kiwix_download_zim, test_directory, te
assert not flags.outdated_zims.is_set()
def test_zim_tag_migration(test_session, test_directory, zim_factory, tag_factory, test_tags_config):
@pytest.mark.asyncio
async def test_zim_tag_migration(test_session, test_directory, zim_factory, tag_factory, test_tags_config):
"""When an outdated Zim file is deleted, the Tags should be moved to the latest Zim."""
zim1 = zim_factory('wikipedia_en_all_maxi_2020-01.zim') # The outdated Zim.
zim2 = zim_factory('wikipedia_en_all_maxi_2020-02.zim')
zim3 = zim_factory('wikipedia_en_all_maxi_2020-03.zim') # The latest Zim.
tag1, tag2 = tag_factory('tag1'), tag_factory('tag2')
tag1, tag2 = await tag_factory('tag1'), await tag_factory('tag2')
# Tag outdated Zim entries.
zim1.tag_entry(tag1.name, 'home')
zim1.tag_entry(tag2.name, 'one')