mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-04 13:49:57 -05:00
Making example label a tag.
Tags can be created and deleted in UI. Adding tag_file using id to avoid session error. Using UTC in test. Matching tag_names style in test. Tag icon is displayed on file rows. Archives, Videos and Files can be filtered by their tags. Tags can be added and removed from UI. Tags are displayed in VideoPlayer. The tags of a file are returned in it's JSON. Video favorites are converted to Favorite tag on channel config import. Updating tests to match frontend usage. PDF creator and modification time are displayed. Reworking file search to use Video.__json__ for complex video relations. Archives can be viewed. Removing ebook.title. Reworking alembic migration to be an upgrade rather than a replace. Skipping test on circleci. Clearing out video caption index only if extract_subtitles if off. Channel tests pass. Some video tests pass. Missing videos can be found. A video can be downloaded. Orphaned files can be found. Videos can be tagged. Videos can be searched. Videos can be modeled. Converting some tests to use FileGroup.primary_path. Adding archive and domains to alembic migration. Testing cascading Archive titles. Archives now uses FileGroup. archive.lib tests pass. Archive is partially converted to FileGroup. Calculating FileGroup.primary file on refresh, rather than on select. wrolpi tests pass. Using FilesType to convert between str/pathlib.Path for FileGroup.files. Using list of files in FileGroup.files instead of dictionary. Storing files in dedicated FileGroup.files to avoid overwriting them. Adding comment explaining CASE. Not overwriting FileGroup.data on refresh if no change has been detected. Removing File model in favor of FileGroup.data. Adding typing to Files methods. Files are indexed using the primary mimetype of the FileGroup. files test_lib tests pass. Removing file_group_file in favor of simple one-to-many relationship. PDF files are indexed during refresh. Adding Tag and TagFile to tag files with specific tags. Only iterating when full_stem_ids has contents. Testing that FileGroups are related to their Files. Files and file_groups are created and linked. Bump webpack from 5.75.0 to 5.76.1 in /app (#160) Bumps [webpack](https://github.com/webpack/webpack) from 5.75.0 to 5.76.1. - [Release notes](https://github.com/webpack/webpack/releases) - [Commits](https://github.com/webpack/webpack/compare/v5.75.0...v5.76.1) --- updated-dependencies: - dependency-name: webpack dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
parent
9fbfc8c0a7
commit
5615ce542d
71 changed files with 4160 additions and 3161 deletions
|
|
@ -1,20 +1,20 @@
|
|||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
from abc import ABC
|
||||
from typing import Tuple, Dict, List
|
||||
from typing import Tuple, List
|
||||
|
||||
from sqlalchemy import not_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi.common import logger, register_modeler, register_after_refresh, limit_concurrent, split_lines_by_length
|
||||
from wrolpi.db import optional_session, get_db_session
|
||||
from wrolpi.downloader import Downloader, Download, DownloadResult
|
||||
from wrolpi.errors import UnrecoverableDownloadError
|
||||
from wrolpi.files.indexers import register_indexer, Indexer
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.errors import UnrecoverableDownloadError, InvalidArchive
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.vars import PYTEST
|
||||
from . import lib
|
||||
from .api import bp # noqa
|
||||
from .lib import match_archive_files
|
||||
from .lib import is_singlefile_file, get_title_from_html
|
||||
from .models import Archive, Domain
|
||||
|
||||
PRETTY_NAME = 'Archive'
|
||||
|
|
@ -55,58 +55,129 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
archive_downloader = ArchiveDownloader(priority=100)
|
||||
|
||||
|
||||
def find_archive_file_in_group(group: List[File]):
|
||||
for file in group:
|
||||
if lib.is_singlefile_file(file.path):
|
||||
return file
|
||||
def model_archive(file_group: FileGroup, session: Session = None) -> Archive:
|
||||
file_group_id = file_group.id
|
||||
if not file_group_id:
|
||||
session.flush([file_group])
|
||||
file_group_id = file_group.id
|
||||
|
||||
# All Archives have an HTML Singlefile.
|
||||
html_paths = file_group.my_paths('text/html')
|
||||
if not html_paths:
|
||||
logger.error('Query returned a group without an HTML file!')
|
||||
raise InvalidArchive('FileGroup does not contain any html files')
|
||||
|
||||
# All Archives have a Singlefile.
|
||||
for file in html_paths:
|
||||
if is_singlefile_file(file):
|
||||
singlefile_path = file
|
||||
break
|
||||
else:
|
||||
logger.debug(f'No Archive singlefile found in {file_group}')
|
||||
raise InvalidArchive('FileGroup does not contain a singlefile')
|
||||
|
||||
readability_json_path = None
|
||||
json_files = file_group.my_json_files()
|
||||
for json_file in json_files:
|
||||
path = json_file['path']
|
||||
if path.name.endswith('.readability.json'):
|
||||
readability_json_path = path
|
||||
break
|
||||
|
||||
readability_txt_path = None
|
||||
text_files = file_group.my_text_files()
|
||||
for text_file in text_files:
|
||||
path = text_file['path']
|
||||
if path.name.endswith('.readability.txt'):
|
||||
readability_txt_path = path
|
||||
break
|
||||
|
||||
try:
|
||||
file_group.model = 'archive'
|
||||
file_group.primary_path = singlefile_path
|
||||
|
||||
title = None
|
||||
if readability_json_path:
|
||||
title = get_title(readability_json_path)
|
||||
if not title:
|
||||
title = get_title_from_html(singlefile_path.read_text())
|
||||
|
||||
contents = None
|
||||
if readability_txt_path:
|
||||
contents = get_article(readability_txt_path)
|
||||
|
||||
archive = Archive(file_group_id=file_group_id, file_group=file_group)
|
||||
session.add(archive)
|
||||
archive.validate()
|
||||
session.flush([archive])
|
||||
|
||||
file_group.title = file_group.a_text = title
|
||||
file_group.d_text = contents
|
||||
file_group.data = {
|
||||
'id': archive.id,
|
||||
'archive_datetime': archive.archive_datetime,
|
||||
'domain': archive.domain.domain if archive.domain else None,
|
||||
'readability_json_path': archive.readability_json_path,
|
||||
'readability_path': archive.readability_path,
|
||||
'readability_txt_path': archive.readability_txt_path,
|
||||
'screenshot_path': archive.screenshot_path,
|
||||
'singlefile_path': archive.singlefile_path,
|
||||
'url': archive.url,
|
||||
}
|
||||
|
||||
return archive
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to model Archive {file_group}', exc_info=e)
|
||||
if PYTEST:
|
||||
raise
|
||||
|
||||
|
||||
@register_modeler
|
||||
def archive_modeler(groups: Dict[str, List[File]], session: Session):
|
||||
archive_files = {stem: file for stem, group in groups.items() if (file := find_archive_file_in_group(group))}
|
||||
if not archive_files:
|
||||
# No archives in these groups.
|
||||
return
|
||||
# Get all matching Archive records (if any) in one query.
|
||||
archive_paths = [i.path for i in archive_files.values()]
|
||||
archive_records = {i.singlefile_path: i for i in
|
||||
session.query(Archive).filter(Archive.singlefile_path.in_(archive_paths))}
|
||||
async def archive_modeler():
|
||||
invalid_archives = set()
|
||||
|
||||
for stem, archive_file in archive_files.items():
|
||||
group = groups[stem]
|
||||
while True:
|
||||
with get_db_session(commit=True) as session:
|
||||
results = session.query(FileGroup, Archive) \
|
||||
.filter(
|
||||
# Get all groups that contain a PDF that have not been indexed.
|
||||
FileGroup.indexed != True,
|
||||
FileGroup.mimetype == 'text/html',
|
||||
).filter(not_(FileGroup.id.in_(list(invalid_archives)))) \
|
||||
.outerjoin(Archive, Archive.file_group_id == FileGroup.id) \
|
||||
.limit(20)
|
||||
|
||||
readability_file, singlefile_file, readability_json_file, readability_txt_file, screenshot_file = \
|
||||
match_archive_files(group)
|
||||
processed = 0
|
||||
for file_group, archive in results:
|
||||
processed += 1
|
||||
|
||||
archive: Archive = archive_records.get(archive_file.path)
|
||||
if not archive:
|
||||
archive = Archive(singlefile_file=singlefile_file)
|
||||
session.add(archive)
|
||||
archive.readability_file = readability_file
|
||||
archive.readability_json_file = readability_json_file
|
||||
archive.readability_txt_file = readability_txt_file
|
||||
archive.screenshot_file = screenshot_file
|
||||
if archive:
|
||||
try:
|
||||
archive_id = archive.id
|
||||
archive.validate()
|
||||
except Exception:
|
||||
# Archive could not be indexed.
|
||||
invalid_archives |= {file_group.id, }
|
||||
|
||||
if archive.readability_file:
|
||||
archive.readability_file.associated = True
|
||||
archive.readability_file.do_stats()
|
||||
if archive.readability_json_file:
|
||||
archive.readability_json_file.associated = True
|
||||
archive.readability_json_file.do_stats()
|
||||
if archive.readability_txt_file:
|
||||
archive.readability_txt_file.associated = True
|
||||
archive.readability_txt_file.do_stats()
|
||||
if archive.screenshot_file:
|
||||
archive.screenshot_file.associated = True
|
||||
archive.screenshot_file.do_stats()
|
||||
logger.error(f'Unable to validate Archive {archive_id}')
|
||||
if PYTEST:
|
||||
raise
|
||||
else:
|
||||
try:
|
||||
model_archive(file_group, session=session)
|
||||
except InvalidArchive:
|
||||
# FileGroup was not an archive group.
|
||||
invalid_archives |= {file_group.id, }
|
||||
|
||||
archive.singlefile_file.model = Archive.__tablename__
|
||||
# Even if indexing fails, we mark it as indexed. We won't retry indexing this.
|
||||
file_group.indexed = True
|
||||
|
||||
archive.singlefile_file.do_index()
|
||||
archive.validate()
|
||||
if processed < 20:
|
||||
# Did not reach limit, do not query again.
|
||||
break
|
||||
|
||||
# Remove this group, it will not be processed by other modelers.
|
||||
del groups[stem]
|
||||
# Sleep to catch cancel.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
|
||||
@register_after_refresh
|
||||
|
|
@ -124,7 +195,13 @@ def archive_cleanup():
|
|||
deleted = 0
|
||||
for archive in archives:
|
||||
processed += 1
|
||||
if not lib.is_singlefile_file(archive.singlefile_path):
|
||||
singlefile_path = archive.singlefile_path
|
||||
if not singlefile_path:
|
||||
archive.file_group.model = None
|
||||
session.delete(archive)
|
||||
deleted += 1
|
||||
continue
|
||||
if not lib.is_singlefile_file(singlefile_path):
|
||||
# Archive is not a real archive.
|
||||
archive.singlefile_file.model = None
|
||||
session.delete(archive)
|
||||
|
|
@ -142,45 +219,18 @@ def archive_cleanup():
|
|||
session.delete(domain)
|
||||
|
||||
|
||||
@register_indexer('text/html')
|
||||
class ArchiveIndexer(Indexer, ABC):
|
||||
"""Gathers index data from the files associated with an Archive."""
|
||||
def get_title(path):
|
||||
with path.open('rt') as fh:
|
||||
try:
|
||||
return json.load(fh)['title']
|
||||
except Exception:
|
||||
if not PYTEST:
|
||||
logger.warning(f'Archive readability json file exists, but cannot get title. {path}')
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_title(file: File):
|
||||
singlefile_path: pathlib.Path = file.path.path if hasattr(file.path, 'path') else file.path
|
||||
readability_json_path = singlefile_path.with_suffix('.readability.json')
|
||||
if readability_json_path.is_file():
|
||||
with readability_json_path.open('rt') as fh:
|
||||
try:
|
||||
return json.load(fh)['title']
|
||||
except Exception:
|
||||
if not PYTEST:
|
||||
logger.warning(f'Archive readability json file exists, but cannot get title. {file}')
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_article(file: File):
|
||||
singlefile_path: pathlib.Path = file.path.path if hasattr(file.path, 'path') else file.path
|
||||
readability_txt_path = singlefile_path.with_suffix('.readability.txt')
|
||||
if readability_txt_path.is_file():
|
||||
return readability_txt_path.read_text()
|
||||
|
||||
@classmethod
|
||||
def create_index(cls, file: File) -> Tuple:
|
||||
"""
|
||||
Index an Archive file and it's associated files. This mimetype matches non-archive (non-singlefile) html files,
|
||||
so this index will return empty if a readability file is found.
|
||||
|
||||
a = title
|
||||
b = <empty>
|
||||
c = <empty>
|
||||
d = readability article
|
||||
"""
|
||||
if file.path.name.endswith('.readability.html'):
|
||||
# Readability files are not the primary Archive file.
|
||||
return None, None, None, None
|
||||
a = cls.get_title(file)
|
||||
d = cls.get_article(file)
|
||||
d = split_lines_by_length(d)
|
||||
return a, None, None, d
|
||||
def get_article(path):
|
||||
if path.is_file():
|
||||
text = path.read_text()
|
||||
text = split_lines_by_length(text)
|
||||
return text
|
||||
|
|
|
|||
|
|
@ -22,9 +22,9 @@ logger = logger.getChild(__name__)
|
|||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
async def get_archive(_: Request, archive_id: int):
|
||||
archive = lib.get_archive(archive_id=archive_id)
|
||||
archive_file = archive.singlefile_file.__json__()
|
||||
history = [i.singlefile_file.__json__() for i in archive.history]
|
||||
return json_response({'file': archive_file, 'history': history})
|
||||
archive_file_group = archive.file_group.__json__()
|
||||
history = [i.file_group.__json__() for i in archive.history]
|
||||
return json_response({'file_group': archive_file_group, 'history': history})
|
||||
|
||||
|
||||
@bp.delete('/<archive_ids:int>')
|
||||
|
|
@ -52,7 +52,7 @@ archive_limit_limiter = api_param_limiter(100)
|
|||
|
||||
@bp.post('/search')
|
||||
@openapi.definition(
|
||||
summary='Search archive contents and titles',
|
||||
summary='A File search with more filtering related to Archives',
|
||||
body=schema.ArchiveSearchRequest,
|
||||
)
|
||||
@openapi.response(HTTPStatus.OK, schema.ArchiveSearchResponse)
|
||||
|
|
@ -64,6 +64,6 @@ async def search_archives(_: Request, body: schema.ArchiveSearchRequest):
|
|||
limit = archive_limit_limiter(body.limit)
|
||||
offset = body.offset or 0
|
||||
|
||||
archives, total = lib.archive_search(search_str, domain, limit, offset, body.order_by)
|
||||
ret = dict(archives=archives, totals=dict(archives=total))
|
||||
file_groups, total = lib.search_archives(search_str, domain, limit, offset, body.order_by, body.tag_names)
|
||||
ret = dict(file_groups=file_groups, totals=dict(file_groups=total))
|
||||
return json_response(ret)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import copy
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
|
|
@ -9,7 +8,6 @@ import pytz
|
|||
|
||||
from modules.archive.lib import archive_strftime
|
||||
from modules.archive.models import Archive, Domain
|
||||
from wrolpi.files.models import File
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
|
@ -68,45 +66,17 @@ def archive_factory(test_session, archive_directory, make_files_structure):
|
|||
test_session.add(domain)
|
||||
test_session.flush([domain])
|
||||
|
||||
archive = Archive(
|
||||
readability_json_file=File(path=readability_json_path) if readability_json_path else None,
|
||||
readability_file=File(path=readability_path) if readability_path else None,
|
||||
readability_txt_file=File(path=readability_txt_path) if readability_txt_path else None,
|
||||
screenshot_file=File(path=screenshot_path) if screenshot_path else None,
|
||||
singlefile_file=File(path=singlefile_path, model='archive'),
|
||||
title=title,
|
||||
url=url,
|
||||
domain_id=domain.id if domain else None,
|
||||
archive_datetime=archive_datetime,
|
||||
)
|
||||
test_session.add(archive)
|
||||
archive.singlefile_file.do_index()
|
||||
# Only add files that were created.
|
||||
files = (readability_path, readability_json_path, readability_txt_path, screenshot_path, singlefile_path)
|
||||
files = list(filter(None, files))
|
||||
|
||||
archive = Archive.from_paths(test_session, *files)
|
||||
archive.url = url
|
||||
archive.title = title
|
||||
archive.archive_datetime = next(now)
|
||||
archive.domain = domain
|
||||
archive.validate()
|
||||
|
||||
return archive
|
||||
|
||||
return _
|
||||
|
||||
|
||||
SINGLEFILE_CONTENTS = '''<html><!--
|
||||
Page saved with SingleFile
|
||||
url: https://example.com
|
||||
saved date: Thu May 12 2022 00:38:02 GMT+0000 (Coordinated Universal Time)
|
||||
--><head><meta charset="utf-8">
|
||||
|
||||
<meta name="msapplication-TileColor" content="#2d89ef">
|
||||
<meta name="theme-color" content="#000000">
|
||||
|
||||
<title>the title</title>
|
||||
|
||||
<body>
|
||||
some body contents
|
||||
</body>
|
||||
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def singlefile_contents() -> str:
|
||||
"""Return a short HTML string that contains an example Singlefile file."""
|
||||
return copy.deepcopy(SINGLEFILE_CONTENTS)
|
||||
|
|
|
|||
|
|
@ -7,22 +7,19 @@ import subprocess
|
|||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from functools import partial
|
||||
from itertools import groupby
|
||||
from typing import Iterator, Optional, Tuple, List
|
||||
from typing import Optional, Tuple, List
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from selenium import webdriver
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from modules.archive.models import Domain, Archive
|
||||
from wrolpi.cmd import READABILITY_BIN, SINGLE_FILE_BIN, CHROMIUM
|
||||
from wrolpi.common import get_media_directory, logger, extract_domain, chdir, escape_file_name, walk, \
|
||||
aiohttp_post, match_paths_to_suffixes, iterify
|
||||
from wrolpi.common import get_media_directory, logger, extract_domain, chdir, escape_file_name, aiohttp_post
|
||||
from wrolpi.dates import now, Seconds
|
||||
from wrolpi.db import get_db_session, get_db_curs, optional_session
|
||||
from wrolpi.errors import UnknownArchive, InvalidOrderBy
|
||||
from wrolpi.files.lib import handle_search_results
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_clauses
|
||||
from wrolpi.vars import DOCKERIZED, PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -52,8 +49,6 @@ class ArchiveFiles:
|
|||
|
||||
def get_archive_directory() -> pathlib.Path:
|
||||
archive_directory = get_media_directory() / 'archive'
|
||||
if not archive_directory.is_dir():
|
||||
archive_directory.mkdir()
|
||||
return archive_directory
|
||||
|
||||
|
||||
|
|
@ -66,7 +61,7 @@ def get_domain_directory(url: str) -> pathlib.Path:
|
|||
elif directory.exists():
|
||||
raise FileNotFoundError(f'Domain directory {directory} is already a file')
|
||||
|
||||
directory.mkdir()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
return directory
|
||||
|
||||
|
||||
|
|
@ -265,45 +260,23 @@ async def do_archive(url: str) -> Archive:
|
|||
fh.write(json.dumps(readability))
|
||||
|
||||
# Create any File models that we can, index them all.
|
||||
singlefile_file = File(path=archive_files.singlefile, model='archive')
|
||||
singlefile_file.do_index()
|
||||
readability_file = None
|
||||
if archive_files.readability:
|
||||
readability_file = File(path=archive_files.readability, associated=True)
|
||||
readability_file.do_index()
|
||||
readability_json_file = None
|
||||
if archive_files.readability_json:
|
||||
readability_json_file = File(path=archive_files.readability_json, associated=True)
|
||||
readability_json_file.do_index()
|
||||
readability_txt_file = None
|
||||
if archive_files.readability_txt:
|
||||
readability_txt_file = File(path=archive_files.readability_txt, associated=True)
|
||||
readability_txt_file.do_index()
|
||||
screenshot_file = None
|
||||
if archive_files.screenshot:
|
||||
screenshot_file = File(path=archive_files.screenshot, associated=True)
|
||||
screenshot_file.do_index()
|
||||
paths = (
|
||||
archive_files.singlefile, archive_files.readability, archive_files.readability_json,
|
||||
archive_files.readability_txt,
|
||||
archive_files.screenshot)
|
||||
paths = list(filter(None, paths))
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
domain = get_or_create_domain(session, url)
|
||||
archive = Archive(
|
||||
title=title,
|
||||
archive_datetime=now(),
|
||||
singlefile_file=singlefile_file,
|
||||
readability_file=readability_file,
|
||||
readability_json_file=readability_json_file,
|
||||
readability_txt_file=readability_txt_file,
|
||||
screenshot_file=screenshot_file,
|
||||
url=url,
|
||||
domain_id=domain.id,
|
||||
)
|
||||
session.add(archive)
|
||||
archive = Archive.from_paths(session, *paths)
|
||||
archive.archive_datetime = now()
|
||||
archive.url = url
|
||||
archive.domain = get_or_create_domain(session, url)
|
||||
session.flush()
|
||||
|
||||
return archive
|
||||
|
||||
|
||||
def get_or_create_domain(session, url) -> Domain:
|
||||
def get_or_create_domain(session: Session, url) -> Domain:
|
||||
"""
|
||||
Get/create the Domain for this archive.
|
||||
"""
|
||||
|
|
@ -348,132 +321,11 @@ def delete_archives(*archive_ids: List[int]):
|
|||
archive.delete()
|
||||
|
||||
|
||||
def archive_strptime(dt: str) -> datetime:
|
||||
try:
|
||||
return datetime.strptime(dt, '%Y-%m-%d-%H-%M-%S')
|
||||
except ValueError:
|
||||
return datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
|
||||
|
||||
|
||||
def archive_strftime(dt: datetime) -> str:
|
||||
return dt.strftime('%Y-%m-%d-%H-%M-%S')
|
||||
|
||||
|
||||
def group_archive_files(files: Iterator[pathlib.Path]) -> groupby:
|
||||
"""
|
||||
Group archive files by their timestamp.
|
||||
"""
|
||||
# groupby requires the files to be sorted.
|
||||
files = sorted(files)
|
||||
# Group archive files by their datetime at the beginning of the file.
|
||||
groups = groupby(files, key=lambda i: i.name[:19])
|
||||
for dt, files in groups:
|
||||
try:
|
||||
dt = archive_strptime(dt)
|
||||
except ValueError:
|
||||
logger.info(f'Ignoring invalid archives of {dt=}')
|
||||
continue
|
||||
|
||||
# Sort the files into their respective slots.
|
||||
archive_files = ArchiveFiles()
|
||||
file = None
|
||||
for file in files:
|
||||
name = file.name
|
||||
# TODO remove the -readability matching once migrated.
|
||||
if name.endswith('.readability.html') or name.endswith('-readability.html'):
|
||||
archive_files.readability = file
|
||||
elif name.endswith('.html'):
|
||||
archive_files.singlefile = file
|
||||
elif name.endswith('.png') or name.endswith('.jpg') or name.endswith('.jpeg'):
|
||||
archive_files.screenshot = file
|
||||
elif name.endswith('.readability.json') or name.endswith('-readability.json'):
|
||||
archive_files.readability_json = file
|
||||
elif name.endswith('.readability.txt') or name.endswith('-readability.txt'):
|
||||
archive_files.readability_txt = file
|
||||
|
||||
if not archive_files.singlefile:
|
||||
logger.warning(f'Archive does not have a singlefile html! Ignoring. {file}')
|
||||
continue
|
||||
if not archive_files.readability_json:
|
||||
logger.warning(f'Archive does not have a json file! Ignoring. {file}')
|
||||
continue
|
||||
|
||||
yield dt, archive_files
|
||||
|
||||
|
||||
OLD_ARCHIVE_MATCHER = re.compile(r'\d{4}-\d\d-\d\d (\d\d:){2}\d\d\.\d{6}.*$')
|
||||
|
||||
|
||||
def migrate_archive_files():
|
||||
"""
|
||||
Rename Archive files from "YYYY-mm-dd HH:MM:SS.ZZZZZ.html" to "YYYY-mm-dd-HH-MM-SS_{TITLE}.html" and all their
|
||||
associated files.
|
||||
"""
|
||||
archive_directory = get_archive_directory()
|
||||
|
||||
def _is_archive_file(path: pathlib.Path) -> bool:
|
||||
return path.is_file() and path.suffix.lower() in ARCHIVE_SUFFIXES and bool(OLD_ARCHIVE_MATCHER.match(path.name))
|
||||
|
||||
plan = []
|
||||
|
||||
# It is safer to plan the renames before we make them.
|
||||
for domain_directory in filter(lambda i: i.is_dir(), archive_directory.iterdir()):
|
||||
all_archives_files = filter(_is_archive_file, walk(domain_directory))
|
||||
archive_groups = group_archive_files(all_archives_files)
|
||||
for dt, archive_files in archive_groups:
|
||||
archive_files: ArchiveFiles
|
||||
with archive_files.readability_json.open() as fh:
|
||||
title = escape_file_name(json.load(fh).get('title') or 'NA')
|
||||
|
||||
title = title[:50]
|
||||
|
||||
dt = archive_strftime(dt)
|
||||
prefix = f'{dt}_{title}'
|
||||
singlefile_path = domain_directory / f'{prefix}.html'
|
||||
readability_path = domain_directory / f'{prefix}.readability.html'
|
||||
readability_txt_path = domain_directory / f'{prefix}.readability.txt'
|
||||
readability_json_path = domain_directory / f'{prefix}.readability.json'
|
||||
screenshot_path = domain_directory / f'{prefix}.png'
|
||||
|
||||
# Every Archive is required to have these files.
|
||||
plan.append((archive_files.singlefile, singlefile_path))
|
||||
plan.append((archive_files.readability_json, readability_json_path))
|
||||
# These files are optional.
|
||||
if archive_files.readability:
|
||||
plan.append((archive_files.readability, readability_path))
|
||||
if archive_files.readability_txt:
|
||||
plan.append((archive_files.readability_txt, readability_txt_path))
|
||||
if archive_files.screenshot:
|
||||
plan.append((archive_files.screenshot, screenshot_path))
|
||||
|
||||
if not plan:
|
||||
logger.info('Could not find any Archive files to migrate. Was it already performed?')
|
||||
return plan
|
||||
|
||||
# Check that all new files do not exist.
|
||||
for old, new in plan:
|
||||
if new.exists():
|
||||
raise FileExistsError(f'Cannot migrate archive files! {new} already exists!')
|
||||
|
||||
# Finally, move all the files now that its safe.
|
||||
for old, new in plan:
|
||||
old.rename(new)
|
||||
|
||||
return plan
|
||||
|
||||
|
||||
ARCHIVE_MATCHER = re.compile(r'\d{4}(-\d\d){5}_.*$')
|
||||
ARCHIVE_SUFFIXES = {'.txt', '.html', '.json', '.png', '.jpg', '.jpeg'}
|
||||
|
||||
|
||||
def is_archive_file(path: pathlib.Path) -> bool:
|
||||
"""
|
||||
Archive files are expected to start with the following: %Y-%m-%d-%H-%M-%S
|
||||
they must have one of the following suffixes: .txt, .html, .json, .png, .jpg, .jpeg
|
||||
"""
|
||||
return path.is_file() and path.suffix.lower() in ARCHIVE_SUFFIXES and bool(ARCHIVE_MATCHER.match(path.name))
|
||||
|
||||
|
||||
SINGLEFILE_HEADER = '''<!--
|
||||
Page saved with SingleFile'''
|
||||
|
||||
|
|
@ -492,7 +344,7 @@ def is_singlefile_file(path: pathlib.Path) -> bool:
|
|||
# A file name matching exactly the Archive format from WROLPi should always be an Archive.
|
||||
return True
|
||||
with path.open('rt') as fh:
|
||||
# Lastly, try to read the header of this HTML file.
|
||||
# Lastly, try to read the header of this HTML file. Read a large part of the head because URLs can be long.
|
||||
header = fh.read(1000)
|
||||
if SINGLEFILE_HEADER in header:
|
||||
return True
|
||||
|
|
@ -514,68 +366,64 @@ def get_domains():
|
|||
|
||||
|
||||
ARCHIVE_ORDERS = {
|
||||
'date': 'a.archive_datetime ASC, LOWER(a.singlefile_path) ASC',
|
||||
'-date': 'a.archive_datetime DESC NULLS LAST, LOWER(a.singlefile_path) DESC',
|
||||
'date': 'a.archive_datetime ASC, LOWER(fg.primary_path) ASC',
|
||||
'-date': 'a.archive_datetime DESC NULLS LAST, LOWER(fg.primary_path) DESC',
|
||||
'rank': '2 DESC, a.archive_datetime DESC',
|
||||
'-rank': '2 ASC, a.archive_datetime ASC',
|
||||
}
|
||||
|
||||
|
||||
def archive_search(search_str: str, domain: str, limit: int, offset: int, order_by: str) -> Tuple[List[Archive], int]:
|
||||
wheres = []
|
||||
def search_archives(search_str: str, domain: str, limit: int, offset: int, order: str, tag_names: List[str]) \
|
||||
-> Tuple[List[dict], int]:
|
||||
# Always filter FileGroups to Archives.
|
||||
wheres = ["fg.model = 'archive'"]
|
||||
joins = []
|
||||
|
||||
params = dict(search_str=search_str, offset=int(offset), limit=int(limit))
|
||||
order = '1 DESC'
|
||||
order_by = '1 DESC'
|
||||
|
||||
if search_str:
|
||||
# A search_str was provided by the user, modify the query to filter by it.
|
||||
select_columns = 'f.path, ts_rank(f.textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
wheres.append('f.textsearch @@ websearch_to_tsquery(%(search_str)s)')
|
||||
select_columns = 'ts_rank(fg.textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
wheres.append('fg.textsearch @@ websearch_to_tsquery(%(search_str)s)')
|
||||
params['search_str'] = search_str
|
||||
join = 'LEFT JOIN file f on f.path = a.singlefile_path'
|
||||
else:
|
||||
# No search_str provided. Get path and total only. Don't join the "file" to speed up query.
|
||||
select_columns = 'a.singlefile_path AS path, COUNT(*) OVER() AS total'
|
||||
join = ''
|
||||
select_columns = 'fg.id, COUNT(*) OVER() AS total'
|
||||
|
||||
if order_by:
|
||||
if order:
|
||||
try:
|
||||
order = ARCHIVE_ORDERS[order_by]
|
||||
order_by = ARCHIVE_ORDERS[order]
|
||||
except KeyError:
|
||||
raise InvalidOrderBy(f'Invalid order by: {order_by}')
|
||||
raise InvalidOrderBy(f'Invalid order by: {order}')
|
||||
|
||||
if tag_names:
|
||||
where_, params_, join_ = tag_names_to_clauses(tag_names)
|
||||
wheres.append(where_)
|
||||
params.update(params_)
|
||||
joins.append(join_)
|
||||
|
||||
if domain:
|
||||
params['domain'] = domain
|
||||
wheres.append('domain_id = (select id from domains where domains.domain = %(domain)s)')
|
||||
wheres.append('a.domain_id = (select id from domains where domains.domain = %(domain)s)')
|
||||
|
||||
select_columns = f", {select_columns}" if select_columns else ""
|
||||
wheres = '\n AND '.join(wheres)
|
||||
where = f'WHERE\n{wheres}' if wheres else ''
|
||||
join = '\n'.join(joins)
|
||||
stmt = f'''
|
||||
SELECT
|
||||
{select_columns}
|
||||
FROM archive a
|
||||
fg.id -- always get `file_group.id` for `handle_file_group_search_results`
|
||||
{select_columns}
|
||||
FROM file_group fg
|
||||
LEFT JOIN archive a ON a.file_group_id = fg.id
|
||||
{join}
|
||||
{where}
|
||||
ORDER BY {order}
|
||||
GROUP BY fg.id, a.archive_datetime
|
||||
ORDER BY {order_by}
|
||||
OFFSET %(offset)s LIMIT %(limit)s
|
||||
'''.strip()
|
||||
logger.debug(stmt, params)
|
||||
|
||||
results, total = handle_search_results(stmt, params)
|
||||
results, total = handle_file_group_search_results(stmt, params)
|
||||
return results, total
|
||||
|
||||
|
||||
match_archive_paths = partial(match_paths_to_suffixes, suffix_groups=(
|
||||
('.readability.html',),
|
||||
('.html',),
|
||||
('.readability.json',),
|
||||
('.readability.txt',),
|
||||
('.jpg', '.jpeg', '.webp', '.png'),
|
||||
))
|
||||
|
||||
|
||||
@iterify(tuple)
|
||||
def match_archive_files(files: List[File]) -> Tuple[File, File, File, File, File]:
|
||||
archive_paths = match_archive_paths([i.path for i in files])
|
||||
for path in archive_paths:
|
||||
yield next((i for i in files if i.path == path), None)
|
||||
|
|
|
|||
|
|
@ -2,19 +2,19 @@ import datetime
|
|||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from typing import Generator, Optional, Iterable
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
import pytz
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger
|
||||
from sqlalchemy.orm import relationship, Session, validates
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.common import ModelHelper, Base, logger
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.errors import InvalidArchive
|
||||
from wrolpi.files.lib import split_path_stem_and_suffix
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.media_path import MediaPathType
|
||||
from wrolpi.vars import PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
|
@ -28,25 +28,13 @@ class Archive(Base, ModelHelper):
|
|||
__tablename__ = 'archive'
|
||||
id = Column(Integer, primary_key=True)
|
||||
|
||||
archive_datetime = Column(TZDateTime)
|
||||
url = Column(String)
|
||||
|
||||
domain_id = Column(Integer, ForeignKey('domains.id'))
|
||||
domain = relationship('Domain', primaryjoin='Archive.domain_id==Domain.id')
|
||||
|
||||
url = Column(String)
|
||||
title = Column(String)
|
||||
archive_datetime = Column(TZDateTime)
|
||||
validated = Column(Boolean)
|
||||
|
||||
# Associated Files.
|
||||
singlefile_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
singlefile_file: File = relationship('File', primaryjoin='Archive.singlefile_path==File.path')
|
||||
readability_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
readability_file: File = relationship('File', primaryjoin='Archive.readability_path==File.path')
|
||||
readability_json_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
readability_json_file: File = relationship('File', primaryjoin='Archive.readability_json_path==File.path')
|
||||
readability_txt_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
readability_txt_file: File = relationship('File', primaryjoin='Archive.readability_txt_path==File.path')
|
||||
screenshot_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
screenshot_file: File = relationship('File', primaryjoin='Archive.screenshot_path==File.path')
|
||||
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), unique=True, nullable=False)
|
||||
file_group: FileGroup = relationship('FileGroup')
|
||||
|
||||
def __repr__(self):
|
||||
if self.domain:
|
||||
|
|
@ -54,29 +42,11 @@ class Archive(Base, ModelHelper):
|
|||
f'domain={self.domain.domain}>'
|
||||
return f'<Archive id={self.id} url={self.url} singlefile={repr(str(self.singlefile_path))}>'
|
||||
|
||||
def my_paths(self) -> Generator[pathlib.Path, None, None]:
|
||||
if self.singlefile_path:
|
||||
yield self.singlefile_path
|
||||
if self.readability_path:
|
||||
yield self.readability_path
|
||||
if self.readability_json_path:
|
||||
yield self.readability_json_path
|
||||
if self.readability_txt_path:
|
||||
yield self.readability_txt_path
|
||||
if self.screenshot_path:
|
||||
yield self.screenshot_path
|
||||
def my_paths(self, *mimetypes: str) -> List[pathlib.Path]:
|
||||
return self.file_group.my_paths(*mimetypes)
|
||||
|
||||
def my_files(self) -> Generator[File, None, None]:
|
||||
if self.singlefile_file:
|
||||
yield self.singlefile_file
|
||||
if self.readability_file:
|
||||
yield self.readability_file
|
||||
if self.readability_json_file:
|
||||
yield self.readability_json_file
|
||||
if self.readability_txt_file:
|
||||
yield self.readability_txt_file
|
||||
if self.screenshot_file:
|
||||
yield self.screenshot_file
|
||||
def my_files(self, *mimetypes: str) -> List[dict]:
|
||||
return self.file_group.my_files(*mimetypes)
|
||||
|
||||
def unlink(self):
|
||||
"""
|
||||
|
|
@ -95,32 +65,12 @@ class Archive(Base, ModelHelper):
|
|||
|
||||
return self.archive_datetime > other.archive_datetime
|
||||
|
||||
def __json__(self):
|
||||
stem, _ = split_path_stem_and_suffix(self.singlefile_path) if self.singlefile_path else (None, None)
|
||||
d = dict(
|
||||
archive_datetime=self.archive_datetime,
|
||||
domain=self.domain.dict() if self.domain else None,
|
||||
domain_id=self.domain_id,
|
||||
id=self.id,
|
||||
readability_json_path=self.readability_json_path,
|
||||
readability_path=self.readability_path,
|
||||
readability_txt_path=self.readability_txt_path,
|
||||
screenshot_path=self.screenshot_path,
|
||||
singlefile_path=self.singlefile_path,
|
||||
stem=stem,
|
||||
title=self.title,
|
||||
url=self.url,
|
||||
)
|
||||
return d
|
||||
|
||||
def delete(self):
|
||||
self.unlink()
|
||||
|
||||
session = Session.object_session(self)
|
||||
|
||||
for file in self.my_files():
|
||||
session.delete(file)
|
||||
|
||||
session.delete(self.file_group)
|
||||
session.delete(self)
|
||||
|
||||
if self.domain:
|
||||
|
|
@ -139,101 +89,175 @@ class Archive(Base, ModelHelper):
|
|||
).order_by(Archive.archive_datetime))
|
||||
return history
|
||||
|
||||
def read_singlefile_data(self):
|
||||
"""
|
||||
Read the start of the singlefile (if any) and decode the Archive information.
|
||||
"""
|
||||
path = self.singlefile_file.path if self.singlefile_file else self.singlefile_path
|
||||
if not path:
|
||||
# Can't read contents of nothing.
|
||||
raise ValueError('Cannot read singlefile data when this has no files')
|
||||
@property
|
||||
def singlefile_file(self) -> Optional[dict]:
|
||||
from modules.archive.lib import is_singlefile_file
|
||||
files = self.file_group.my_files('text/html')
|
||||
for file in files:
|
||||
if is_singlefile_file(file['path']):
|
||||
return file
|
||||
|
||||
with path.open('rt') as fh:
|
||||
head = fh.read(1000)
|
||||
if 'Page saved with SingleFile' not in head:
|
||||
return
|
||||
try:
|
||||
if match := MATCH_URL.findall(head):
|
||||
self.url = match[0].strip()
|
||||
except Exception as e:
|
||||
logger.error(f'Could not get URL from singlefile {path}', exc_info=e)
|
||||
try:
|
||||
if match := MATCH_DATE.findall(head):
|
||||
dt = match[0].strip()
|
||||
dt = ' '.join(dt.split(' ')[:5])
|
||||
# SingleFile uses GMT.
|
||||
dt = datetime.datetime.strptime(
|
||||
dt,
|
||||
'%a %b %d %Y %H:%M:%S' # Fri Jun 17 2022 19:24:52
|
||||
).replace(tzinfo=pytz.timezone('GMT'))
|
||||
self.archive_datetime = dt
|
||||
except Exception as e:
|
||||
logger.error(f'Could not get archive date from singlefile {path}', exc_info=e)
|
||||
@property
|
||||
def singlefile_path(self) -> Optional[pathlib.Path]:
|
||||
if singlefile_file := self.singlefile_file:
|
||||
return singlefile_file['path']
|
||||
|
||||
@property
|
||||
def readability_file(self) -> Optional[dict]:
|
||||
files = self.file_group.my_files('text/html')
|
||||
for file in files:
|
||||
if file['path'].name.endswith('.readability.html'):
|
||||
return file
|
||||
|
||||
@property
|
||||
def readability_path(self) -> Optional[pathlib.Path]:
|
||||
if readability_file := self.readability_file:
|
||||
return readability_file['path']
|
||||
|
||||
@property
|
||||
def readability_txt_file(self) -> Optional[dict]:
|
||||
files = self.file_group.my_files('text/plain', 'text/html')
|
||||
for file in files:
|
||||
if file['path'].name.endswith('.readability.txt'):
|
||||
return file
|
||||
|
||||
@property
|
||||
def readability_txt_path(self) -> Optional[pathlib.Path]:
|
||||
if readability_txt_file := self.readability_txt_file:
|
||||
return readability_txt_file['path']
|
||||
|
||||
@property
|
||||
def readability_json_file(self) -> Optional[dict]:
|
||||
files = self.file_group.my_files()
|
||||
for file in files:
|
||||
if file['path'].name.endswith('.readability.json'):
|
||||
return file
|
||||
|
||||
@property
|
||||
def readability_json_path(self) -> Optional[pathlib.Path]:
|
||||
if readability_json_file := self.readability_json_file:
|
||||
return readability_json_file['path']
|
||||
|
||||
@property
|
||||
def screenshot_file(self) -> Optional[dict]:
|
||||
files = self.file_group.my_files('image/')
|
||||
for file in files:
|
||||
return file
|
||||
|
||||
@property
|
||||
def screenshot_path(self) -> Optional[pathlib.Path]:
|
||||
if screenshot_file := self.screenshot_file:
|
||||
return screenshot_file['path']
|
||||
|
||||
def read_readability_data(self):
|
||||
"""Read the Readability JSON file, apply its contents to this record."""
|
||||
readability_json_file = self.readability_json_file
|
||||
if not readability_json_file or not readability_json_file.path.is_file():
|
||||
path = self.singlefile_file.path if self.singlefile_file else self.singlefile_path
|
||||
logger.warning(f'{path} does not have an info json file')
|
||||
readability_json_path = self.readability_json_path
|
||||
if not readability_json_path:
|
||||
logger.warning(f'{self.singlefile_path} does not have an info json file')
|
||||
return
|
||||
if not readability_json_path.is_file():
|
||||
error = f'Cannot read data from {readability_json_path} because it not exist.'
|
||||
if PYTEST:
|
||||
raise ValueError(error)
|
||||
logger.error(error)
|
||||
return
|
||||
|
||||
try:
|
||||
with readability_json_file.path.open() as fh:
|
||||
with readability_json_path.open() as fh:
|
||||
json_contents = json.load(fh)
|
||||
url = json_contents.get('url')
|
||||
title = json_contents.get('title')
|
||||
except Exception as e:
|
||||
raise InvalidArchive() from e
|
||||
|
||||
self.url = url
|
||||
self.title = title
|
||||
# Readability is most trusted, it should overwrite any previous data.
|
||||
self.url = url or self.url
|
||||
self.file_group.title = title or self.file_group.title
|
||||
|
||||
def read_singlefile_data(self):
|
||||
"""Read the start of the singlefile (if any) and extract any Archive information."""
|
||||
path = self.singlefile_path
|
||||
if not path:
|
||||
# Can't read contents of nothing.
|
||||
raise ValueError('Cannot read singlefile data when this has no files')
|
||||
|
||||
if self.url and self.archive_datetime:
|
||||
# This data has already been read.
|
||||
return
|
||||
|
||||
with path.open('rt') as fh:
|
||||
head = fh.read(1000)
|
||||
if 'Page saved with SingleFile' not in head:
|
||||
logger.error(f'Could not find SingleFile header in {self}')
|
||||
return
|
||||
|
||||
if not self.url:
|
||||
try:
|
||||
if match := MATCH_URL.findall(head):
|
||||
self.url = match[0].strip()
|
||||
except Exception as e:
|
||||
logger.error(f'Could not get URL from singlefile {path}', exc_info=e)
|
||||
|
||||
if not self.archive_datetime:
|
||||
try:
|
||||
if match := MATCH_DATE.findall(head):
|
||||
dt = match[0].strip()
|
||||
dt = ' '.join(dt.split(' ')[:5])
|
||||
# SingleFile uses GMT.
|
||||
dt = datetime.datetime.strptime(
|
||||
dt,
|
||||
'%a %b %d %Y %H:%M:%S' # Fri Jun 17 2022 19:24:52
|
||||
).replace(tzinfo=pytz.timezone('GMT'))
|
||||
self.archive_datetime = dt
|
||||
except Exception as e:
|
||||
logger.error(f'Could not get archive date from singlefile {path}', exc_info=e)
|
||||
|
||||
def apply_domain(self):
|
||||
"""Get the domain from the URL."""
|
||||
from modules.archive.lib import get_or_create_domain
|
||||
domain = None
|
||||
if self.url:
|
||||
domain = get_or_create_domain(Session.object_session(self), self.url)
|
||||
session = Session.object_session(self)
|
||||
if not session:
|
||||
raise ValueError('No session found!')
|
||||
domain = get_or_create_domain(session, self.url)
|
||||
# Clear domain if the URL is missing.
|
||||
self.domain_id = domain.id if domain else None
|
||||
|
||||
def apply_title(self):
|
||||
def apply_singlefile_title(self):
|
||||
"""Get the title from the Singlefile, if its missing."""
|
||||
from modules.archive.lib import get_title_from_html
|
||||
if self.singlefile_path and not self.title:
|
||||
self.title = get_title_from_html(self.singlefile_path.read_text())
|
||||
if self.singlefile_path and not self.file_group.title:
|
||||
self.file_group.title = get_title_from_html(self.singlefile_path.read_text())
|
||||
|
||||
def validate(self):
|
||||
"""Fill in any missing data about this Archive from it's files."""
|
||||
try:
|
||||
self.read_readability_data()
|
||||
self.read_singlefile_data()
|
||||
self.apply_domain()
|
||||
self.apply_title()
|
||||
self.validated = True
|
||||
self.apply_singlefile_title()
|
||||
except Exception as e:
|
||||
logger.warning(f'Unable to validate {self}', exc_info=e)
|
||||
if PYTEST:
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def find_by_path(path, session: Session) -> Optional[Base]:
|
||||
archive = session.query(Archive).filter_by(singlefile_path=path).one_or_none()
|
||||
def from_paths(session: Session, *paths: pathlib.Path) -> 'Archive':
|
||||
"""Create a new Archive and FileGroup from the provided paths.
|
||||
|
||||
The files will be read and Archive data extracted."""
|
||||
from modules.archive import model_archive
|
||||
file_group = FileGroup.from_paths(session, *paths)
|
||||
archive = model_archive(file_group, session)
|
||||
return archive
|
||||
|
||||
@staticmethod
|
||||
def find_by_paths(paths, session):
|
||||
archives = list(session.query(Archive).filter(Archive.singlefile_path.in_(paths)))
|
||||
return archives
|
||||
|
||||
@property
|
||||
def primary_path(self):
|
||||
return self.singlefile_path
|
||||
|
||||
|
||||
class Domain(Base, ModelHelper):
|
||||
__tablename__ = 'domains' # plural to avoid conflict
|
||||
id = Column(Integer, primary_key=True)
|
||||
|
||||
domain = Column(String)
|
||||
domain = Column(String, nullable=False)
|
||||
directory = Column(MediaPathType)
|
||||
|
||||
archives: InstrumentedList = relationship('Archive', primaryjoin='Archive.domain_id==Domain.id')
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
|
|
@ -30,9 +30,10 @@ class ArchiveSearchRequest:
|
|||
offset: Optional[int] = None
|
||||
limit: Optional[int] = None
|
||||
order_by: Optional[str] = None
|
||||
tag_names: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArchiveSearchResponse:
|
||||
videos: List[ArchiveDict]
|
||||
file_groups: List[ArchiveDict]
|
||||
totals: dict
|
||||
|
|
|
|||
|
|
@ -4,11 +4,14 @@ from http import HTTPStatus
|
|||
|
||||
def check_results(test_client, data, ids):
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
if not response.status_code == HTTPStatus.OK:
|
||||
raise AssertionError(str(response.json))
|
||||
|
||||
if ids:
|
||||
assert response.json['archives'], f'Expected {len(ids)} archives but did not receive any'
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == ids, \
|
||||
f'{response.json["archives"][0]["archive"]["id"]}..{response.json["archives"]["archive"][19]["id"]}'
|
||||
file_groups = response.json['file_groups']
|
||||
assert file_groups, f'Expected {len(ids)} archives but did not receive any'
|
||||
assert [i['id'] for i in response.json['file_groups']] == ids, \
|
||||
f'{response.json["file_groups"][0]["id"]}..{response.json["file_groups"][-1]["id"]}'
|
||||
|
||||
|
||||
def test_archives_search(test_session, archive_directory, archive_factory, test_client):
|
||||
|
|
@ -87,22 +90,22 @@ def test_archives_search_no_query(test_session, archive_factory, test_client):
|
|||
# All archives are returned when no `search_str` is passed.
|
||||
request, response = test_client.post('/api/archive/search', content='{}')
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['archives'] == 100
|
||||
assert [i['id'] for i in response.json['file_groups']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['file_groups'] == 100
|
||||
|
||||
# All archives are from "example.com".
|
||||
data = dict(domain='example.com')
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['archives'] == 100
|
||||
assert [i['id'] for i in response.json['file_groups']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['file_groups'] == 100
|
||||
|
||||
# No archives are from "example.org".
|
||||
data = dict(domain='example.org')
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == []
|
||||
assert response.json['totals']['archives'] == 0
|
||||
assert [i['id'] for i in response.json['file_groups']] == []
|
||||
assert response.json['totals']['file_groups'] == 0
|
||||
|
||||
|
||||
def test_archive_and_domain_crud(test_session, test_client, archive_factory):
|
||||
|
|
@ -121,14 +124,14 @@ def test_archive_and_domain_crud(test_session, test_client, archive_factory):
|
|||
# Archive1 has Archive2 as history.
|
||||
request, response = test_client.get(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['file']['archive']['id'] == archive1.id
|
||||
assert response.json['history'][0]['archive']['id'] == archive2.id
|
||||
assert response.json['file_group']['id'] == archive1.id
|
||||
assert response.json['history'][0]['id'] == archive2.id
|
||||
|
||||
# Archive2 has Archive1 as history.
|
||||
request, response = test_client.get(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert archive2.id == response.json['file']['archive']['id']
|
||||
assert response.json['history'][0]['archive']['id'] == archive1.id
|
||||
assert archive2.id == response.json['file_group']['id']
|
||||
assert response.json['history'][0]['id'] == archive1.id
|
||||
|
||||
# Only one domain.
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
|
|
@ -150,7 +153,7 @@ def test_archive_and_domain_crud(test_session, test_client, archive_factory):
|
|||
# Archive2 no longer has history.
|
||||
request, response = test_client.get(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['file']['archive']['id'] == archive2.id
|
||||
assert response.json['file_group']['id'] == archive2.id
|
||||
assert response.json['history'] == []
|
||||
|
||||
# No Archives, no Domains.
|
||||
|
|
|
|||
|
|
@ -1,31 +1,36 @@
|
|||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import mock
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from modules.archive import lib
|
||||
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, do_archive, get_domains, \
|
||||
group_archive_files, ArchiveFiles
|
||||
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archives, do_archive, get_domains
|
||||
from modules.archive.models import Archive, Domain
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.files.lib import refresh_files
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.root_api import CustomJSONEncoder
|
||||
from wrolpi.test.common import skip_circleci
|
||||
|
||||
|
||||
def make_fake_request_archive(readability=True, screenshot=True, title=True):
|
||||
async def fake_request_archive(_):
|
||||
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
with tempfile.NamedTemporaryFile(suffix='.png') as fh:
|
||||
Image.new('RGB', (1, 1), color='grey').save(fh)
|
||||
fh.seek(0)
|
||||
image = fh.read()
|
||||
singlefile = '<html><!--\n Page saved with SingleFile\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
r = dict(
|
||||
content=f'<html>test readability content</html>',
|
||||
textContent='<html>test readability textContent</html>',
|
||||
textContent='test readability textContent',
|
||||
title='ジにてこちら' if title else None,
|
||||
) if readability else None
|
||||
s = b'screenshot data' if screenshot else None
|
||||
s = image if screenshot else None
|
||||
return singlefile, r, s
|
||||
|
||||
return fake_request_archive
|
||||
|
|
@ -61,13 +66,12 @@ async def test_dict(test_session):
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_relationships(test_session, test_directory):
|
||||
async def test_relationships(test_session, test_directory, example_singlefile):
|
||||
with get_db_session(commit=True) as session:
|
||||
url = 'https://wrolpi.org:443'
|
||||
domain = get_or_create_domain(session, url)
|
||||
archive = Archive(
|
||||
singlefile_file=File(path=test_directory / 'wrolpi.org:443/foo'),
|
||||
title='bar',
|
||||
file_group=FileGroup.from_paths(test_session, example_singlefile),
|
||||
url=url,
|
||||
domain_id=domain.id,
|
||||
)
|
||||
|
|
@ -77,6 +81,50 @@ async def test_relationships(test_session, test_directory):
|
|||
assert archive.domain == domain
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_title(test_session, archive_factory, singlefile_contents_factory):
|
||||
"""An Archive's title can be fetched in multiple ways. This tests from most to least reliable."""
|
||||
# Create some test files, delete all records for a fresh refresh.
|
||||
archive_factory(
|
||||
domain='example.com',
|
||||
url='https://example.com/json-url',
|
||||
title='json title',
|
||||
singlefile_contents=singlefile_contents_factory('singlefile title', 'https://example.com/singlefile-url'),
|
||||
)
|
||||
test_session.query(FileGroup).delete()
|
||||
test_session.commit()
|
||||
|
||||
await refresh_files()
|
||||
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
assert test_session.query(Archive).count() == 1
|
||||
|
||||
archive1: Archive = test_session.query(Archive).one()
|
||||
|
||||
# Readability JSON is trusted first.
|
||||
assert archive1.url == 'https://example.com/json-url'
|
||||
assert archive1.file_group.title == 'json title'
|
||||
|
||||
# Delete JSON file.
|
||||
archive1.readability_json_path.unlink()
|
||||
test_session.delete(archive1)
|
||||
await refresh_files()
|
||||
|
||||
archive1: Archive = test_session.query(Archive).one()
|
||||
assert archive1.url == 'https://example.com/singlefile-url'
|
||||
assert archive1.file_group.title == 'singlefile title'
|
||||
|
||||
# Clear out title and URL from Singlefile.
|
||||
archive1.singlefile_path.write_text(singlefile_contents_factory('', ''))
|
||||
test_session.delete(archive1)
|
||||
await refresh_files()
|
||||
|
||||
# No title/URL could be found.
|
||||
archive1: Archive = test_session.query(Archive).one()
|
||||
assert archive1.url is None
|
||||
assert archive1.file_group.title is None
|
||||
|
||||
|
||||
def test_archive_refresh_deleted_archive(test_client, test_session, archive_directory, archive_factory):
|
||||
"""Archives/Domains should be deleted when archive files are deleted."""
|
||||
archive1 = archive_factory('example.com', 'https://example.com/1')
|
||||
|
|
@ -125,17 +173,17 @@ def test_archive_refresh_deleted_archive(test_client, test_session, archive_dire
|
|||
check_counts(archive_count=0, domain_count=0)
|
||||
|
||||
|
||||
def test_fills_contents_with_refresh(test_client, test_session, archive_factory):
|
||||
@pytest.mark.asyncio
|
||||
async def test_fills_contents_with_refresh(test_client, test_session, archive_factory, singlefile_contents_factory):
|
||||
"""Refreshing archives fills in any missing contents."""
|
||||
archive1 = archive_factory('example.com', 'https://example.com/one')
|
||||
archive2 = archive_factory('example.com', 'https://example.com/one')
|
||||
# Title can be found in archive3's singlefile
|
||||
archive3 = archive_factory('example.org',
|
||||
singlefile_contents='<html> some stuff<title>last title</title> other stuff</html>')
|
||||
archive3 = archive_factory('example.org', singlefile_contents=singlefile_contents_factory('last title'))
|
||||
archive4 = archive_factory('example.org') # has no contents
|
||||
|
||||
# Clear the title, this will be filled in.
|
||||
archive1.title = archive2.title = archive3.title = archive4.title = None
|
||||
archive1.file_group.title = archive2.file_group.title = archive3.file_group.title = archive4.file_group.title = None
|
||||
|
||||
contents_title_archive = [
|
||||
('foo bar qux', 'my archive', archive1),
|
||||
|
|
@ -143,31 +191,31 @@ def test_fills_contents_with_refresh(test_client, test_session, archive_factory)
|
|||
('baz qux qux qux', None, archive3),
|
||||
]
|
||||
for contents, json_title, archive in contents_title_archive:
|
||||
with archive.readability_txt_path.open('wt') as fh:
|
||||
archive: Archive
|
||||
readability_txt_path = archive.singlefile_path.with_suffix('.readability.txt')
|
||||
with readability_txt_path.open('wt') as fh:
|
||||
fh.write(contents)
|
||||
if json_title:
|
||||
archive.readability_json_path.write_text(json.dumps({'title': json_title, 'url': archive.url}))
|
||||
readability_json_path = archive.singlefile_path.with_suffix('.readability.json')
|
||||
readability_json_path.write_text(json.dumps({'title': json_title, 'url': archive.url}))
|
||||
test_session.commit()
|
||||
|
||||
# Contents are empty. Archives are all missing the title.
|
||||
assert not archive1.singlefile_file.d_text
|
||||
assert not archive2.singlefile_file.d_text
|
||||
assert not archive3.singlefile_file.d_text
|
||||
assert not archive4.singlefile_file.d_text
|
||||
assert not archive1.file_group.d_text
|
||||
assert not archive2.file_group.d_text
|
||||
assert not archive3.file_group.d_text
|
||||
assert not archive4.file_group.d_text
|
||||
|
||||
# Fill the contents.
|
||||
test_client.post('/api/files/refresh')
|
||||
await refresh_files()
|
||||
# The archives will be renamed with their title.
|
||||
archive1, archive2, archive3, archive4 = test_session.query(Archive).order_by(Archive.id)
|
||||
assert archive1.singlefile_file.title
|
||||
assert archive2.singlefile_file.title
|
||||
assert archive3.singlefile_file.title
|
||||
assert not archive4.singlefile_file.d_text
|
||||
assert not archive4.file_group.d_text
|
||||
|
||||
# Missing title is filled.
|
||||
assert archive1.title == 'my archive'
|
||||
assert archive2.title == 'other archive'
|
||||
assert archive3.title == 'last title' # from json
|
||||
# Missing titles are filled.
|
||||
assert archive1.file_group.title == 'my archive'
|
||||
assert archive2.file_group.title == 'other archive'
|
||||
assert archive3.file_group.title == 'last title' # from singlefile HTML
|
||||
|
||||
|
||||
def test_delete_archive(test_session, archive_factory):
|
||||
|
|
@ -183,12 +231,12 @@ def test_delete_archive(test_session, archive_factory):
|
|||
assert archive3.my_paths() and all(i.is_file() for i in archive3.my_paths())
|
||||
|
||||
assert test_session.query(Archive).count() == 3
|
||||
assert test_session.query(File).count() == 15
|
||||
assert test_session.query(FileGroup).count() == 3
|
||||
|
||||
# Delete the oldest.
|
||||
delete_archives(archive1.id, archive3.id)
|
||||
assert test_session.query(Archive).count() == 1
|
||||
assert test_session.query(File).count() == 5
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
# Files were deleted.
|
||||
assert archive1.my_paths() and not any(i.is_file() for i in archive1.my_paths())
|
||||
assert archive3.my_paths() and not any(i.is_file() for i in archive3.my_paths())
|
||||
|
|
@ -202,7 +250,7 @@ def test_delete_archive(test_session, archive_factory):
|
|||
assert domain is None
|
||||
|
||||
# All Files were deleted.
|
||||
assert test_session.query(File).count() == 0
|
||||
assert test_session.query(FileGroup).count() == 0
|
||||
assert archive2.my_paths() and not any(i.is_file() for i in archive2.my_paths())
|
||||
|
||||
|
||||
|
|
@ -215,6 +263,10 @@ def test_get_domains(test_session, archive_factory):
|
|||
archive3 = archive_factory('example.org')
|
||||
test_session.commit()
|
||||
|
||||
assert archive1.domain
|
||||
assert archive2.domain
|
||||
assert archive3.domain
|
||||
|
||||
assert [i['domain'] for i in get_domains()] == ['example.com', 'example.org']
|
||||
|
||||
archive2.delete()
|
||||
|
|
@ -242,17 +294,17 @@ async def test_new_archive(test_session, fake_now):
|
|||
assert isinstance(archive1.readability_path, pathlib.Path)
|
||||
assert isinstance(archive1.readability_txt_path, pathlib.Path)
|
||||
assert isinstance(archive1.screenshot_path, pathlib.Path)
|
||||
assert archive1.title == 'ジにてこちら'
|
||||
assert archive1.file_group.title == 'ジにてこちら'
|
||||
assert archive1.url is not None
|
||||
assert archive1.domain is not None
|
||||
|
||||
# The actual files were dumped and read correctly.
|
||||
with open(archive1.singlefile_path) as fh:
|
||||
assert fh.read() == '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
assert fh.read() == '<html><!--\n Page saved with SingleFile\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
with open(archive1.readability_path) as fh:
|
||||
assert fh.read() == '<html>test readability content</html>'
|
||||
with open(archive1.readability_txt_path) as fh:
|
||||
assert fh.read() == '<html>test readability textContent</html>'
|
||||
assert fh.read() == 'test readability textContent'
|
||||
with open(archive1.readability_json_path) as fh:
|
||||
assert json.load(fh) == {'title': 'ジにてこちら', 'url': 'https://example.com'}
|
||||
|
||||
|
|
@ -267,7 +319,7 @@ async def test_get_title_from_html(test_session, fake_now):
|
|||
fake_now(datetime(2000, 1, 1))
|
||||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title == 'ジにてこちら'
|
||||
assert archive.file_group.title == 'ジにてこちら'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
|
|
@ -281,7 +333,7 @@ async def test_get_title_from_html(test_session, fake_now):
|
|||
fake_now(datetime(2000, 1, 2))
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title == 'some title'
|
||||
assert archive.file_group.title == 'some title'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
singlefile = '<html></html>'
|
||||
|
|
@ -295,7 +347,7 @@ async def test_get_title_from_html(test_session, fake_now):
|
|||
fake_now(datetime(2000, 1, 3))
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title is None
|
||||
assert archive.file_group.title is None
|
||||
|
||||
|
||||
@skip_circleci
|
||||
|
|
@ -333,7 +385,7 @@ def test_get_new_archive_files(fake_now):
|
|||
|
||||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
async def test_title_in_filename(test_session, fake_now, test_directory):
|
||||
async def test_title_in_filename(test_session, fake_now, test_directory, image_bytes_factory):
|
||||
"""
|
||||
The Archive files have the title in the path.
|
||||
"""
|
||||
|
|
@ -342,7 +394,7 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
|
||||
archive1 = await do_archive('https://example.com')
|
||||
|
||||
assert archive1.title == 'ジにてこちら'
|
||||
assert archive1.file_group.title == 'ジにてこちら'
|
||||
|
||||
assert str(archive1.singlefile_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.html'
|
||||
|
|
@ -360,9 +412,9 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
r = dict(
|
||||
# No Title from Readability.
|
||||
content=f'<html>test readability content</html>',
|
||||
textContent='<html>test readability textContent</html>',
|
||||
textContent='test readability textContent',
|
||||
)
|
||||
s = b'screenshot data'
|
||||
s = image_bytes_factory()
|
||||
return singlefile, r, s
|
||||
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
|
|
@ -386,7 +438,7 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
content=f'<html>test readability content</html>',
|
||||
textContent='<html>test readability textContent</html>',
|
||||
)
|
||||
s = b'screenshot data'
|
||||
s = image_bytes_factory()
|
||||
return singlefile, r, s
|
||||
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
|
|
@ -404,7 +456,7 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.png'
|
||||
|
||||
|
||||
@skip_circleci
|
||||
# @skip_circleci
|
||||
def test_refresh_archives(test_session, test_directory, test_client, make_files_structure):
|
||||
"""
|
||||
Archives can be found and put in the database. A single Archive will have multiple files.
|
||||
|
|
@ -418,11 +470,11 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
|
|||
|
||||
make_files_structure({
|
||||
# These are all for an individual Archive.
|
||||
'archive/example.com/2021-10-05 16:20:10.346823.html': singlefile_contents, # renames to 2021-10-05-16-20-10_NA
|
||||
'archive/example.com/2021-10-05 16:20:10.346823.png': None,
|
||||
'archive/example.com/2021-10-05 16:20:10.346823-readability.txt': 'article text contents',
|
||||
'archive/example.com/2021-10-05 16:20:10.346823-readability.json': '{"url": "https://example.com"}',
|
||||
'archive/example.com/2021-10-05 16:20:10.346823-readability.html': '<html></html>',
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.html': singlefile_contents,
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.png': None,
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.txt': 'article text contents',
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.json': '{"url": "https://example.com"}',
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.html': '<html></html>',
|
||||
# These should log an error because they are missing the singlefile path.
|
||||
'archive/example.com/2021-10-05 16:20:10.readability.html': '<html></html>',
|
||||
'archive/example.com/2021-10-05 16:20:10.readability.json': None,
|
||||
|
|
@ -435,6 +487,11 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
|
|||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(Archive).count() == 1
|
||||
|
||||
# Cause a re-index of the archive.
|
||||
test_session.query(FileGroup).filter_by(
|
||||
full_stem=str(test_directory / 'archive/example.com/2021-10-05-16-20-10_NA')).one().indexed = False
|
||||
test_session.commit()
|
||||
|
||||
# Running the refresh does not result in a new archive.
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(Archive).count() == 1
|
||||
|
|
@ -452,11 +509,15 @@ def test_refresh_archives(test_session, test_directory, test_client, make_files_
|
|||
content = json.dumps({'search_str': 'text', 'model': 'archive'})
|
||||
request, response = test_client.post('/api/files/search', content=content)
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['files'], 'No files matched "text"'
|
||||
assert response.json['files'][0]['model'] == 'archive', 'Returned file was not an archive'
|
||||
assert response.json['files'][0].get('path') == 'archive/example.com/2021-10-05-16-20-10_NA.html', \
|
||||
assert response.json['file_groups'], 'No files matched "text"'
|
||||
assert response.json['file_groups'][0]['model'] == 'archive', 'Returned file was not an archive'
|
||||
assert response.json['file_groups'][0]['data'].get('readability_path') == \
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.html',\
|
||||
'Could not find readability html file'
|
||||
assert response.json['file_groups'][0]['data'].get('readability_txt_path') == \
|
||||
'archive/example.com/2021-10-05-16-20-10_NA.readability.txt',\
|
||||
'Could not find readability text file containing "text"'
|
||||
assert response.json['files'][0]['archive']['archive_datetime'], 'Archive has no datetime'
|
||||
assert response.json['file_groups'][0]['data']['archive_datetime'], 'Archive has no datetime'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -482,18 +543,9 @@ async def test_refresh_archives_index(test_session, test_directory, test_client,
|
|||
|
||||
archive: Archive = test_session.query(Archive).one()
|
||||
assert archive.singlefile_path == singlefile
|
||||
assert archive.singlefile_file.a_text == 'the title'
|
||||
assert archive.singlefile_file.d_text == 'article text contents'
|
||||
|
||||
# The associated files are not indexed.
|
||||
for name in ('screenshot_file', 'readability_file', 'readability_json_file', 'readability_txt_file'):
|
||||
file = getattr(archive, name)
|
||||
assert file.associated is True, 'The associated file is not marked'
|
||||
assert file.indexed is False
|
||||
# file.a_text is the file name.
|
||||
assert not file.b_text
|
||||
assert not file.c_text
|
||||
assert not file.d_text
|
||||
assert archive.file_group.a_text == 'the title'
|
||||
assert archive.file_group.d_text == 'article text contents'
|
||||
assert archive.file_group.indexed is True
|
||||
|
||||
|
||||
def test_refresh_archives_invalid_file(test_session, test_directory, test_client, make_files_structure):
|
||||
|
|
@ -506,76 +558,24 @@ def test_refresh_archives_invalid_file(test_session, test_directory, test_client
|
|||
'bogus file': None,
|
||||
})
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(File).count() == 3 # Three files total.
|
||||
assert test_session.query(FileGroup).count() == 2 # One bogus file, one archive group.
|
||||
assert test_session.query(Archive).count() == 1 # Only one real archive.
|
||||
|
||||
# Create an invalid Archive, it should be removed during refresh.
|
||||
test_session.add(Archive(singlefile_path=bogus_path))
|
||||
# Claim the bogus file as an Archive, this should be removed.
|
||||
bogus_file: File = test_session.query(File).filter_by(path=bogus_path).one()
|
||||
bogus_file: FileGroup = test_session.query(FileGroup).filter_by(primary_path=bogus_path).one()
|
||||
bogus_file.model = 'archive'
|
||||
archive = Archive(file_group=bogus_file)
|
||||
test_session.add(archive)
|
||||
test_session.commit()
|
||||
assert test_session.query(File).count() == 3
|
||||
assert test_session.query(FileGroup).count() == 2
|
||||
assert test_session.query(Archive).count() == 2
|
||||
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(File).count() == 3, 'More files in DB than we created'
|
||||
assert test_session.query(FileGroup).count() == 2, 'More files in DB than we created'
|
||||
assert test_session.query(Archive).count() == 1, 'The bogus Archive was not removed'
|
||||
assert bogus_file.model is None, 'Model was not removed'
|
||||
|
||||
|
||||
def test_group_archive_files(test_directory):
|
||||
"""Archive files should be grouped together when they are the same Archive."""
|
||||
files = [
|
||||
pathlib.Path('2021-10-05 16:20:10.346823.html'),
|
||||
pathlib.Path('2021-10-05 16:20:10.346823.readability.json'),
|
||||
pathlib.Path('2000-01-01-00-00-00_Title.html'),
|
||||
pathlib.Path('2000-01-01-00-00-00_Title.readability.json'),
|
||||
pathlib.Path('not an archive'),
|
||||
pathlib.Path('2000-01-01-00-00-01_Missing a singlefile.readability.json'),
|
||||
]
|
||||
|
||||
group1 = ArchiveFiles(
|
||||
singlefile=pathlib.Path('2000-01-01-00-00-00_Title.html'),
|
||||
readability_json=pathlib.Path('2000-01-01-00-00-00_Title.readability.json')
|
||||
)
|
||||
group2 = ArchiveFiles(
|
||||
singlefile=pathlib.Path('2021-10-05 16:20:10.346823.html'),
|
||||
readability_json=pathlib.Path('2021-10-05 16:20:10.346823.readability.json'),
|
||||
)
|
||||
assert list(group_archive_files(files)) == [
|
||||
(datetime(2000, 1, 1, 0, 0, 0), group1),
|
||||
(datetime(2021, 10, 5, 16, 20, 10), group2),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'name,expected', [
|
||||
('foo', False),
|
||||
('2000-01-01-00-00-00_Some Title.html', True),
|
||||
('2000-01-01-00-00-00_Some Title.readability.json', True),
|
||||
('2000-01-01-00-00-00_Some Title.readability.html', True),
|
||||
('2000-01-01-00-00-00_Some Title.readability.txt', True),
|
||||
('2000-01-01-00-00-00_Some Title.png', True),
|
||||
('2000-01-01-00-00-00_Some Title.jpg', True),
|
||||
('2000-01-01-00-00-00_Some Title.jpeg', True),
|
||||
('2000-01-01-00-00-00_Some NA.html', True),
|
||||
('2000-01-01-00-00-00_NA.readability.json', True),
|
||||
('2000-01-01-00-00-00_NA.readability.html', True),
|
||||
('2000-01-01-00-00-00_NA.readability.txt', True),
|
||||
('2000-01-01-00-00-00_NA.png', True),
|
||||
('2000-01-01-00-00-00_NA.jpg', True),
|
||||
('2000-01-01-00-00-00_NA.jpeg', True),
|
||||
('2000-01-01-00-00-00_ジにてこちら.html', True),
|
||||
('2000-01-01-00-00-00no underscore.html', False),
|
||||
]
|
||||
)
|
||||
def test_is_archive_file(name, expected, test_directory):
|
||||
path = test_directory / name
|
||||
path.touch()
|
||||
assert lib.is_archive_file(path) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'name,expected', [
|
||||
('foo', False),
|
||||
|
|
@ -587,69 +587,12 @@ def test_is_archive_file(name, expected, test_directory):
|
|||
('foo.html', True),
|
||||
]
|
||||
)
|
||||
def test_is_singlefile_file(name, expected, make_files_structure, singlefile_contents):
|
||||
def test_is_singlefile_file(name, expected, make_files_structure, singlefile_contents_factory):
|
||||
"""A Singlefile may not be created by WROLPi, an HTML file created by Singlefile can also be an Archive."""
|
||||
path, = make_files_structure({name: singlefile_contents})
|
||||
path, = make_files_structure({name: singlefile_contents_factory()})
|
||||
assert lib.is_singlefile_file(path) == expected
|
||||
|
||||
|
||||
@skip_circleci
|
||||
def test_migrate_archive_files(test_session, archive_directory, archive_factory):
|
||||
"""Test that migration of all old Archive formatted files are migrated."""
|
||||
# Create some updated archives that should be ignored.
|
||||
archive1 = archive_factory('example.com', title='the title')
|
||||
archive2 = archive_factory('example.com')
|
||||
archive3 = archive_factory('example.org')
|
||||
test_session.commit()
|
||||
assert archive1.singlefile_path.is_file()
|
||||
assert archive2.singlefile_path.is_file()
|
||||
assert archive3.singlefile_path.is_file()
|
||||
|
||||
example_com_directory = archive_directory / 'example.com'
|
||||
example_org_directory = archive_directory / 'example.org'
|
||||
|
||||
# Archive4
|
||||
(example_com_directory / '2021-10-05 16:20:10.346823.html').touch()
|
||||
path = example_com_directory / '2021-10-05 16:20:10.346823.readability.json'
|
||||
path.write_text(json.dumps({'title': 'my title'}))
|
||||
# Archive5
|
||||
(example_com_directory / '2000-01-01 00:00:00.000000.html').touch()
|
||||
path = example_com_directory / '2000-01-01 00:00:00.000000.readability.json'
|
||||
path.write_text(json.dumps({'title': 'invalid#*: title'}))
|
||||
# Archive6
|
||||
(example_org_directory / '2000-01-01 00:00:00.000000.html').touch()
|
||||
path = example_org_directory / '2000-01-01 00:00:00.000000.readability.json'
|
||||
path.write_text(json.dumps({'title': 'A' * 500})) # Really long file name.
|
||||
|
||||
# Migration forms a plan, then performs it.
|
||||
plan = lib.migrate_archive_files()
|
||||
for old, new in plan:
|
||||
# All files are moved.
|
||||
assert not old.is_file()
|
||||
assert new.is_file()
|
||||
# Check that only the outdated files are moved.
|
||||
plan = [(i.relative_to(archive_directory), j.relative_to(archive_directory)) for i, j in plan]
|
||||
assert plan == [
|
||||
(pathlib.Path('example.com/2000-01-01 00:00:00.000000.html'),
|
||||
pathlib.Path('example.com/2000-01-01-00-00-00_invalid# title.html')),
|
||||
(pathlib.Path('example.com/2000-01-01 00:00:00.000000.readability.json'),
|
||||
pathlib.Path('example.com/2000-01-01-00-00-00_invalid# title.readability.json')),
|
||||
(pathlib.Path('example.com/2021-10-05 16:20:10.346823.html'),
|
||||
pathlib.Path('example.com/2021-10-05-16-20-10_my title.html')),
|
||||
(pathlib.Path('example.com/2021-10-05 16:20:10.346823.readability.json'),
|
||||
pathlib.Path('example.com/2021-10-05-16-20-10_my title.readability.json')),
|
||||
(pathlib.Path('example.org/2000-01-01 00:00:00.000000.html'),
|
||||
pathlib.Path('example.org/2000-01-01-00-00-00_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.html')),
|
||||
(pathlib.Path('example.org/2000-01-01 00:00:00.000000.readability.json'),
|
||||
pathlib.Path(
|
||||
'example.org/2000-01-01-00-00-00_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.readability.json')),
|
||||
]
|
||||
# New Archive files still exist.
|
||||
assert all(i.is_file() for i in archive1.my_paths())
|
||||
assert all(i.is_file() for i in archive2.my_paths())
|
||||
assert all(i.is_file() for i in archive3.my_paths())
|
||||
|
||||
|
||||
def test_archive_files(test_directory):
|
||||
af = lib.ArchiveFiles(
|
||||
singlefile=test_directory / 'archive/singlefile.html',
|
||||
|
|
@ -687,17 +630,11 @@ async def test_archive_download_index(test_session, test_directory, image_file):
|
|||
assert archive.readability_path and archive.readability_path.exists()
|
||||
assert archive.readability_json_path
|
||||
assert archive.readability_txt_path and archive.readability_txt_path.exists()
|
||||
assert archive.readability_txt_file.d_text == 'the readability', 'Readability text was not indexed'
|
||||
assert archive.title == 'the singlefile', 'Did not get the title from the singlefile'
|
||||
assert archive.file_group.d_text == 'the readability', 'Readability text was not indexed'
|
||||
assert archive.file_group.title == 'the singlefile', 'Did not get the title from the singlefile'
|
||||
assert archive.screenshot_path and archive.screenshot_file and archive.screenshot_path.is_file(), \
|
||||
'Did not store the screenshot'
|
||||
|
||||
assert not archive.singlefile_file.associated
|
||||
assert archive.readability_txt_file.associated \
|
||||
and archive.readability_json_file.associated \
|
||||
and archive.readability_file.associated \
|
||||
and archive.screenshot_file.associated, 'Archive files must be associated'
|
||||
|
||||
|
||||
def test_archive_history(test_session, archive_factory):
|
||||
"""Archive's can have a history of other archives.
|
||||
|
|
|
|||
|
|
@ -1,163 +1,89 @@
|
|||
import json
|
||||
import pathlib
|
||||
from abc import ABC
|
||||
from typing import List, Dict
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
import asyncio
|
||||
from typing import List, Tuple
|
||||
|
||||
from modules.videos.models import Video, Channel
|
||||
from wrolpi.captions import read_captions, extract_captions
|
||||
from wrolpi.common import logger, register_modeler, register_after_refresh, limit_concurrent, split_lines_by_length
|
||||
from wrolpi.db import get_db_curs
|
||||
from wrolpi.files.indexers import Indexer, register_indexer
|
||||
from wrolpi.files.lib import split_path_stem_and_suffix
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.common import logger, limit_concurrent, register_modeler, register_after_refresh
|
||||
from wrolpi.db import get_db_curs, get_db_session
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.vars import PYTEST
|
||||
from .downloader import video_downloader # Import downloaders so they are registered.
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
__all__ = ['video_modeler', 'VideoIndexer']
|
||||
__all__ = ['video_modeler']
|
||||
|
||||
|
||||
def find_video_file_in_group(group: List[File]):
|
||||
return next((i for i in group if i.mimetype.startswith('video/') and i.path.suffix != '.part'), None)
|
||||
VIDEO_PROCESSING_LIMIT = 20
|
||||
|
||||
|
||||
@register_modeler
|
||||
def video_modeler(groups: Dict[str, List[File]], session: Session):
|
||||
new_videos = []
|
||||
async def video_modeler():
|
||||
while True:
|
||||
with get_db_session(commit=True) as session:
|
||||
file_groups = session.query(FileGroup, Video).filter(
|
||||
FileGroup.indexed != True,
|
||||
FileGroup.mimetype.like('video/%'),
|
||||
).outerjoin(Video, Video.file_group_id == FileGroup.id) \
|
||||
.limit(VIDEO_PROCESSING_LIMIT)
|
||||
file_groups: List[Tuple[FileGroup, Video]] = list(file_groups)
|
||||
|
||||
# Search all groups for video files.
|
||||
video_files = {stem: video_file for stem, group in groups.items() if
|
||||
(video_file := find_video_file_in_group(group))}
|
||||
if not video_files:
|
||||
# No videos in these groups.
|
||||
return
|
||||
# Get all matching Video records (if any) in one query.
|
||||
video_paths = [i.path for i in video_files.values()]
|
||||
video_records = {i.video_path: i for i in session.query(Video).filter(Video.video_path.in_(video_paths))}
|
||||
processed = 0
|
||||
for file_group, video in file_groups:
|
||||
processed += 1
|
||||
|
||||
for stem, video_file in video_files.items():
|
||||
group = groups[stem]
|
||||
video_id = None
|
||||
try:
|
||||
if not video:
|
||||
video = Video(file_group=file_group)
|
||||
session.add(video)
|
||||
session.flush([video])
|
||||
video_id = video.id
|
||||
video.validate()
|
||||
except Exception as e:
|
||||
if PYTEST:
|
||||
raise
|
||||
logger.error(f'Unable to model Video {video_id=}', exc_info=e)
|
||||
|
||||
session.flush(group)
|
||||
poster_file = info_json_file = caption_file = None
|
||||
for file in group:
|
||||
if file.mimetype.startswith('image/'):
|
||||
poster_file = file
|
||||
elif file.path.name.endswith('.info.json'):
|
||||
info_json_file = file
|
||||
# Prefer WebVTT over SRT. (SRT cannot be displayed for HTML video).
|
||||
elif file.path.name.endswith('.en.vtt'):
|
||||
caption_file = file
|
||||
elif file.path.name.endswith('.en.srt'):
|
||||
caption_file = caption_file or file
|
||||
file_group.indexed = True
|
||||
|
||||
if poster_file:
|
||||
poster_file.associated = True
|
||||
poster_file.do_stats()
|
||||
if caption_file:
|
||||
caption_file.associated = True
|
||||
caption_file.do_stats()
|
||||
if info_json_file:
|
||||
info_json_file.associated = True
|
||||
info_json_file.do_stats()
|
||||
if processed < VIDEO_PROCESSING_LIMIT:
|
||||
# Did not reach limit, do not query again.
|
||||
break
|
||||
|
||||
video: Video = video_records.get(video_file.path)
|
||||
if not video:
|
||||
video = Video(video_file=video_file)
|
||||
session.add(video)
|
||||
|
||||
size = video_file.path.stat().st_size
|
||||
|
||||
if poster_file != video.poster_file or \
|
||||
caption_file != video.caption_file or \
|
||||
info_json_file != video.info_json_file or \
|
||||
video.size != size:
|
||||
# Files might have been changed. Re-index.
|
||||
video.video_file.indexed = False
|
||||
|
||||
video.poster_file = poster_file
|
||||
video.caption_file = caption_file
|
||||
video.info_json_file = info_json_file
|
||||
video.size = size
|
||||
video_file.model = Video.__tablename__
|
||||
|
||||
new_videos.append(video)
|
||||
|
||||
if new_videos:
|
||||
session.flush(new_videos)
|
||||
for video in new_videos:
|
||||
video.video_file.do_index()
|
||||
video.validate(session)
|
||||
|
||||
# Remove this group, it will not be processed by other modelers.
|
||||
stem, _ = split_path_stem_and_suffix(video.video_path)
|
||||
del groups[stem]
|
||||
logger.debug(f'Modeled {processed} videos')
|
||||
|
||||
# Sleep to catch cancel.
|
||||
await asyncio.sleep(0)
|
||||
|
||||
@register_after_refresh
|
||||
@limit_concurrent(1)
|
||||
def video_cleanup():
|
||||
# Claim all Videos in a Channel's directory for that Channel. But, only if they have not yet been claimed.
|
||||
logger.info('Claiming Videos for their Channels')
|
||||
with get_db_curs(commit=True) as curs:
|
||||
# Delete all Videos if the FileModel no longer contains a video.
|
||||
curs.execute('''
|
||||
WITH deleted AS
|
||||
(UPDATE file_group SET model=null WHERE model='video' AND mimetype NOT LIKE 'video/%' RETURNING id)
|
||||
DELETE FROM video WHERE file_group_id = ANY(select id from deleted)
|
||||
''')
|
||||
# Claim all Videos in a Channel's directory for that Channel. But, only if they have not yet been claimed.
|
||||
curs.execute('''
|
||||
UPDATE video v
|
||||
SET channel_id = c.id
|
||||
SET
|
||||
channel_id = c.id
|
||||
FROM channel c
|
||||
LEFT JOIN file_group fg ON fg.primary_path LIKE c.directory || '/%'::VARCHAR
|
||||
WHERE
|
||||
v.video_path LIKE c.directory || '/%'::VARCHAR
|
||||
AND v.channel_id IS NULL
|
||||
v.channel_id IS NULL
|
||||
AND fg.id = v.file_group_id
|
||||
''')
|
||||
curs.execute('''
|
||||
UPDATE file_group fg
|
||||
SET
|
||||
-- Update channel information in file_group.data
|
||||
-- Example: data = {'channel': {'id': 1, 'name': 'example'}}
|
||||
data = fg.data::jsonb || jsonb_build_object('channel',
|
||||
jsonb_build_object('id', v.channel_id, 'name', c.name))
|
||||
FROM video v
|
||||
LEFT JOIN channel c on c.id = v.channel_id
|
||||
WHERE fg.id = v.file_group_id
|
||||
''')
|
||||
|
||||
|
||||
EXTRACT_SUBTITLES = False
|
||||
|
||||
|
||||
@register_indexer('video')
|
||||
class VideoIndexer(Indexer, ABC):
|
||||
"""Handles video files like mp4/ogg."""
|
||||
|
||||
@staticmethod
|
||||
def get_description(file):
|
||||
video_path: pathlib.Path = file.path.path if hasattr(file.path, 'path') else file.path
|
||||
info_json_path = video_path.with_suffix('.info.json')
|
||||
if info_json_path.is_file():
|
||||
with info_json_path.open('rt') as fh:
|
||||
try:
|
||||
return json.load(fh)['description']
|
||||
except Exception:
|
||||
if not PYTEST:
|
||||
logger.warning(f'Video info json file exists, but cannot get description. {file}')
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def create_index(cls, file):
|
||||
"""
|
||||
Index the video file and it's associated files.
|
||||
|
||||
a = title.
|
||||
b = <empty>
|
||||
c = description from info json.
|
||||
d = captions from info json, or extracted from video file.
|
||||
"""
|
||||
a = cls.get_title(file)
|
||||
c = cls.get_description(file)
|
||||
|
||||
# Detect the associated caption files.
|
||||
d = None
|
||||
if (en_vtt := file.path.with_suffix('.en.vtt')).is_file():
|
||||
d = read_captions(en_vtt)
|
||||
elif (vtt := file.path.with_suffix('.vtt')).is_file():
|
||||
d = read_captions(vtt)
|
||||
elif (en_srt := file.path.with_suffix('.en.srt')).is_file():
|
||||
d = read_captions(en_srt)
|
||||
elif (srt := file.path.with_suffix('.srt')).is_file():
|
||||
d = read_captions(srt)
|
||||
elif EXTRACT_SUBTITLES:
|
||||
d = extract_captions(file.path) or ''
|
||||
|
||||
d = split_lines_by_length(d)
|
||||
return a, None, c, d
|
||||
|
|
|
|||
|
|
@ -36,18 +36,16 @@ def download(_, channel_id: int = None):
|
|||
return response.empty()
|
||||
|
||||
|
||||
@content_bp.post('/favorite')
|
||||
@content_bp.post('/tag')
|
||||
@openapi.definition(
|
||||
description='Toggle the favorite flag on a video',
|
||||
body=schema.FavoriteRequest,
|
||||
description='Associate a Video with a Tag',
|
||||
body=schema.TagRequest,
|
||||
)
|
||||
@validate(schema.FavoriteRequest)
|
||||
@openapi.response(HTTPStatus.OK, schema.FavoriteResponse)
|
||||
@validate(schema.TagRequest)
|
||||
@openapi.response(HTTPStatus.BAD_REQUEST, JSONErrorResponse)
|
||||
async def favorite(_: Request, body: schema.FavoriteRequest):
|
||||
_favorite = video_lib.set_video_favorite(body.video_id, body.favorite)
|
||||
ret = {'video_id': body.video_id, 'favorite': _favorite}
|
||||
return json_response(ret, HTTPStatus.OK)
|
||||
async def tag(_: Request, body: schema.TagRequest):
|
||||
video_lib.tag_video(body.video_id, body.tag_name)
|
||||
return response.empty()
|
||||
|
||||
|
||||
@content_bp.get('/statistics')
|
||||
|
|
|
|||
|
|
@ -58,8 +58,6 @@ async def get_channels_video_count() -> Dict[int, int]:
|
|||
FROM
|
||||
channel AS c
|
||||
LEFT JOIN video AS v ON v.channel_id = c.id
|
||||
WHERE
|
||||
v.video_path IS NOT NULL
|
||||
GROUP BY 1
|
||||
'''
|
||||
curs.execute(stmt)
|
||||
|
|
|
|||
|
|
@ -28,10 +28,10 @@ def test_get_channels(test_directory, channel_factory, test_client):
|
|||
def test_get_video(test_client, test_session, simple_channel, video_factory):
|
||||
"""Test that you get can information about a video. Test that video file can be gotten."""
|
||||
now_ = now()
|
||||
video1 = video_factory(channel_id=simple_channel.id)
|
||||
video1.upload_date, video1.title = now_, 'vid1'
|
||||
video2 = video_factory(channel_id=simple_channel.id)
|
||||
video2.upload_date, video2.title = now_ + timedelta(seconds=1), 'vid2'
|
||||
video1 = video_factory(channel_id=simple_channel.id, title='vid1')
|
||||
video1.upload_date = now_
|
||||
video2 = video_factory(channel_id=simple_channel.id, title='vid2')
|
||||
video2.upload_date = now_ + timedelta(seconds=1)
|
||||
test_session.commit()
|
||||
|
||||
# Test that a 404 is returned when no video exists
|
||||
|
|
@ -42,11 +42,11 @@ def test_get_video(test_client, test_session, simple_channel, video_factory):
|
|||
# Get the video info we inserted
|
||||
_, response = test_client.get('/api/videos/video/1')
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
assert_dict_contains(response.json['file']['video'], {'title': 'vid1'})
|
||||
assert_dict_contains(response.json['file_group'], {'title': 'vid1'})
|
||||
|
||||
# The next video is included.
|
||||
assert response.json['prev'] is None
|
||||
assert_dict_contains(response.json['next']['video'], {'title': 'vid2'})
|
||||
assert_dict_contains(response.json['next'], {'title': 'vid2'})
|
||||
|
||||
|
||||
def test_channel_no_download_frequency(test_client, test_session, test_directory, simple_channel):
|
||||
|
|
@ -173,8 +173,8 @@ def test_video_file_name(test_session, simple_video, test_client):
|
|||
"""If a Video has no title, the front-end can use the file name as the title."""
|
||||
_, resp = test_client.get(f'/api/videos/video/{simple_video.id}')
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json['file']['video']['video_path'] == 'simple_video.mp4'
|
||||
assert resp.json['file']['video'].get('stem') == 'simple_video'
|
||||
assert resp.json['file_group']['video']['video_path'] == 'simple_video.mp4'
|
||||
assert resp.json['file_group']['video'].get('stem') == 'simple_video'
|
||||
|
||||
|
||||
def test_channel_conflicts(test_client, test_session, test_directory):
|
||||
|
|
@ -443,7 +443,7 @@ def test_search_videos_channel(test_client, test_session, video_factory):
|
|||
d = dict(channel_id=channel1.id)
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['files']) == 0
|
||||
assert len(response.json['file_groups']) == 0
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
vid1 = video_factory(title='vid1', channel_id=channel2.id)
|
||||
|
|
@ -454,15 +454,15 @@ def test_search_videos_channel(test_client, test_session, video_factory):
|
|||
# Videos are gotten by their respective channels
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['files']) == 1
|
||||
assert response.json['totals']['files'] == 1
|
||||
assert_dict_contains(response.json['files'][0], dict(path='vid2.mp4', video=dict(channel_id=channel1.id)))
|
||||
assert len(response.json['file_groups']) == 1
|
||||
assert response.json['totals']['file_groups'] == 1
|
||||
assert_dict_contains(response.json['file_groups'][0], dict(primary_path='vid2.mp4', video=dict(channel_id=channel1.id)))
|
||||
|
||||
d = dict(channel_id=channel2.id)
|
||||
request, response = test_client.post(f'/api/videos/search', content=json.dumps(d))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['files']) == 1
|
||||
assert_dict_contains(response.json['files'][0], dict(path='vid1.mp4', video=dict(channel_id=channel2.id)))
|
||||
assert len(response.json['file_groups']) == 1
|
||||
assert_dict_contains(response.json['file_groups'][0], dict(primary_path='vid1.mp4', video=dict(channel_id=channel2.id)))
|
||||
|
||||
|
||||
def test_get_channel_videos_pagination(test_client, test_session, simple_channel, video_factory, assert_video_search):
|
||||
|
|
@ -488,7 +488,7 @@ def test_get_channel_videos_pagination(test_client, test_session, simple_channel
|
|||
last_ids = []
|
||||
for offset, video_count in tests:
|
||||
_, response = assert_video_search(channel_id=simple_channel.id, order_by='id', offset=offset, limit=20)
|
||||
assert len(response.json['files']) == video_count, 'Returned videos does not match'
|
||||
current_ids = [i['video']['id'] for i in response.json['files']]
|
||||
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}'
|
||||
last_ids = current_ids
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import asyncio
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
|
@ -92,40 +93,3 @@ def test_channels_no_url(test_session, test_directory):
|
|||
|
||||
save_channels_config()
|
||||
import_channels_config()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_videos_finds_channel(test_session, test_client, channel_factory, video_factory):
|
||||
"""A Video will be assigned to a Channel by its info json first, then to its directory."""
|
||||
channel1 = channel_factory(source_id='channel1')
|
||||
channel2 = channel_factory(source_id='channel2')
|
||||
|
||||
# Put the video in the wrong directory. It should be matched to the info json channel first, then to it's directory
|
||||
channel1.source_id = 'channel source id'
|
||||
vid1 = video_factory(
|
||||
with_video_file=(channel2.directory / 'video1.mp4'),
|
||||
with_info_json={'channel_id': channel1.source_id},
|
||||
)
|
||||
test_session.commit()
|
||||
assert not vid1.channel_id
|
||||
|
||||
with mock.patch('wrolpi.common.after_refresh') as mock_after_refresh:
|
||||
# Channel can be found in `video_cleanup`, prevent that with mock.
|
||||
mock_after_refresh.side_effect = []
|
||||
await refresh_files()
|
||||
|
||||
# Channel in info_json was found during validation.
|
||||
assert vid1.channel_id == channel1.id
|
||||
|
||||
# Refresh using cleanup, info json should be trusted.
|
||||
await refresh_files()
|
||||
assert vid1.channel_id == channel1.id
|
||||
|
||||
# Remove the info json, the Video's Channel will be its directory.
|
||||
vid1.channel_id = None
|
||||
vid1.info_json_path.unlink()
|
||||
test_session.commit()
|
||||
await refresh_files()
|
||||
test_session.refresh(vid1)
|
||||
vid1 = test_session.query(Video).one()
|
||||
assert vid1.channel_id == channel2.id
|
||||
|
|
|
|||
|
|
@ -12,35 +12,3 @@ def test_delete_channel_no_url(test_session, test_client, channel_factory):
|
|||
test_session.commit()
|
||||
|
||||
channel.delete_with_videos()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_channel_refresh_censored(test_session, channel_factory, video_factory):
|
||||
"""Censored videos are discovered when refreshing a channel's directory."""
|
||||
channel = channel_factory()
|
||||
channel.info_json = {
|
||||
'entries': [
|
||||
{'id': 'one', 'view_count': 100},
|
||||
{'id': 'two', 'view_count': 200},
|
||||
# Three was deleted, it should be marked as censored.
|
||||
# {'id': 'three', 'view_count': 300},
|
||||
]
|
||||
}
|
||||
vid1 = video_factory(channel_id=channel.id, source_id='one')
|
||||
vid2 = video_factory(channel_id=channel.id, source_id='two')
|
||||
vid3 = video_factory(channel_id=channel.id, source_id='three')
|
||||
test_session.commit()
|
||||
|
||||
assert channel.refreshed is False
|
||||
assert vid1.censored is False and vid1.view_count is None
|
||||
assert vid2.censored is False and vid1.view_count is None
|
||||
assert vid3.censored is False and vid1.view_count is None
|
||||
|
||||
await channel.refresh_files()
|
||||
|
||||
channel = test_session.query(Channel).one()
|
||||
|
||||
assert channel.refreshed is True
|
||||
assert vid1.censored is False and vid1.view_count == 100
|
||||
assert vid2.censored is False and vid2.view_count == 200
|
||||
assert vid3.censored is True and vid3.view_count is None
|
||||
|
|
|
|||
|
|
@ -6,9 +6,8 @@ import subprocess
|
|||
import tempfile
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Tuple
|
||||
from typing import Optional, Tuple
|
||||
|
||||
import PIL
|
||||
from PIL import Image
|
||||
|
|
@ -16,25 +15,16 @@ from sqlalchemy.orm import Session
|
|||
|
||||
from wrolpi.captions import FFMPEG_BIN
|
||||
from wrolpi.cmd import FFPROBE_BIN
|
||||
from wrolpi.common import logger, iterify, get_media_directory, \
|
||||
minimize_dict, match_paths_to_suffixes
|
||||
from wrolpi.common import logger, get_media_directory
|
||||
from wrolpi.db import get_db_session, get_db_curs
|
||||
from wrolpi.errors import ChannelNameConflict, ChannelURLConflict, \
|
||||
ChannelDirectoryConflict, ChannelSourceIdConflict
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.vars import DEFAULT_FILE_PERMISSIONS
|
||||
from .models import Channel
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
REQUIRED_OPTIONS = ['name', 'directory']
|
||||
MINIMUM_CHANNEL_KEYS = {'id', 'name', 'directory', 'url', 'video_count'}
|
||||
MINIMUM_INFO_JSON_KEYS = {'description', 'view_count', 'webpage_url'}
|
||||
MINIMUM_VIDEO_KEYS = {'id', 'title', 'upload_date', 'duration', 'channel', 'channel_id', 'favorite', 'size',
|
||||
'poster_path', 'caption_path', 'video_path', 'info_json', 'channel', 'viewed', 'source_id',
|
||||
'view_count'}
|
||||
# These are the supported video formats. These are in order of their preference.
|
||||
VIDEO_EXTENSIONS = ('mp4', 'ogg', 'webm', 'flv')
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
|
|
@ -145,7 +135,7 @@ def generate_video_poster(video_path: Path) -> Tuple[Path, Optional[int]]:
|
|||
|
||||
def convert_image(existing_path: Path, destination_path: Path, ext: str = 'jpeg'):
|
||||
"""Convert an image from one format to another. Remove the existing image file. This will safely overwrite an
|
||||
image if the existing path is the same as the destination path.
|
||||
image if the destination file already exists.
|
||||
"""
|
||||
with tempfile.NamedTemporaryFile(dir=destination_path.parent, delete=False) as fh:
|
||||
img = Image.open(existing_path).convert('RGB')
|
||||
|
|
@ -225,11 +215,8 @@ def check_for_video_corruption(video_path: Path) -> bool:
|
|||
return corrupt
|
||||
|
||||
|
||||
def apply_info_json(channel_id: int):
|
||||
"""Update view_count for all Videos in a channel using its info_json file.
|
||||
|
||||
Mark any videos not in the info_json as "censored".
|
||||
"""
|
||||
def update_view_counts(channel_id: int):
|
||||
"""Update view_count for all Videos in a channel using its info_json file."""
|
||||
with get_db_session() as session:
|
||||
channel: Channel = session.query(Channel).filter_by(id=channel_id).one()
|
||||
channel_name = channel.name
|
||||
|
|
@ -255,47 +242,3 @@ def apply_info_json(channel_id: int):
|
|||
curs.execute(stmt, (view_counts_str, channel_id))
|
||||
count = len(curs.fetchall())
|
||||
logger.debug(f'Updated {count} view counts in DB for {channel_name}.')
|
||||
|
||||
# Mark any video not in the info_json entries as censored.
|
||||
source_ids = [i['id'] for i in info['entries']]
|
||||
stmt = '''
|
||||
UPDATE video SET censored=(source_id != ALL(%s))
|
||||
WHERE channel_id=%s
|
||||
'''
|
||||
curs.execute(stmt, (source_ids, channel_id))
|
||||
|
||||
|
||||
minimize_channel = partial(minimize_dict, keys=MINIMUM_CHANNEL_KEYS)
|
||||
minimize_video_info_json = partial(minimize_dict, keys=MINIMUM_INFO_JSON_KEYS)
|
||||
_minimize_video = partial(minimize_dict, keys=MINIMUM_VIDEO_KEYS)
|
||||
|
||||
|
||||
def minimize_video(video: dict) -> dict:
|
||||
"""
|
||||
Return a Video dictionary that contains only the key/values typically used. Minimize the Channel and info_json,
|
||||
if they are present.
|
||||
"""
|
||||
video = _minimize_video(video)
|
||||
|
||||
if video.get('channel'):
|
||||
video['channel'] = minimize_channel(video['channel'])
|
||||
if video.get('info_json'):
|
||||
video['info_json'] = minimize_video_info_json(video['info_json'])
|
||||
|
||||
return video
|
||||
|
||||
|
||||
match_video_paths = partial(match_paths_to_suffixes, suffix_groups=(
|
||||
tuple(f'.{i}' for i in VIDEO_EXTENSIONS),
|
||||
('.jpg', '.jpeg', '.webp', '.png'),
|
||||
('.description',),
|
||||
('.en.vtt', '.en.srt'),
|
||||
('.info.json',),
|
||||
))
|
||||
|
||||
|
||||
@iterify(tuple)
|
||||
def match_video_files(files: List[File]) -> Tuple[File, File, File, File, File]:
|
||||
video_paths = match_video_paths([i.path for i in files])
|
||||
for path in video_paths:
|
||||
yield next((i for i in files if i.path == path), None)
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ from modules.videos.downloader import VideoDownloader, ChannelDownloader
|
|||
from modules.videos.lib import set_test_channels_config, set_test_downloader_config
|
||||
from modules.videos.models import Channel, Video
|
||||
from wrolpi.downloader import DownloadFrequency, DownloadManager, Download
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
|
|
@ -71,13 +71,12 @@ def download_channel(test_session, test_directory, video_download_manager) -> Ch
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def simple_video(test_session, test_directory, simple_channel) -> Video:
|
||||
def simple_video(test_session, test_directory, simple_channel, video_file) -> Video:
|
||||
"""A Video with an empty video file whose channel is the Simple Channel."""
|
||||
video_path = test_directory / 'simple_video.mp4'
|
||||
video_path.touch()
|
||||
video_file = File(path=video_path, model='video')
|
||||
video = Video(video_file=video_file, channel_id=simple_channel.id)
|
||||
test_session.add(video)
|
||||
video_file.rename(video_path)
|
||||
video = Video.from_paths(test_session, video_path)
|
||||
video.channel = simple_channel
|
||||
test_session.commit()
|
||||
video = test_session.query(Video).filter_by(id=video.id).one()
|
||||
return video
|
||||
|
|
@ -89,7 +88,7 @@ def video_factory(test_session, test_directory):
|
|||
|
||||
def factory(channel_id: int = None, title: str = None, upload_date=None, with_video_file=None,
|
||||
with_info_json: dict = None, with_poster_ext: str = None, with_caption_file: bool = False,
|
||||
source_id: str = None):
|
||||
source_id: str = None) -> Video:
|
||||
title = title or str(uuid4())
|
||||
|
||||
if with_video_file and isinstance(with_video_file, (pathlib.Path, str)):
|
||||
|
|
@ -104,13 +103,8 @@ def video_factory(test_session, test_directory):
|
|||
(test_directory / 'videos/NO CHANNEL').mkdir(exist_ok=True, parents=True)
|
||||
path = test_directory / f'videos/NO CHANNEL/{title}.mp4'
|
||||
|
||||
video_file = File(path=path, model='video')
|
||||
test_session.add(video_file)
|
||||
|
||||
if with_video_file:
|
||||
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', path)
|
||||
else:
|
||||
path.touch()
|
||||
# Create a real video file for mimetype.
|
||||
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', path)
|
||||
|
||||
info_json_path = None
|
||||
if with_info_json:
|
||||
|
|
@ -118,32 +112,25 @@ def video_factory(test_session, test_directory):
|
|||
with_info_json = {'duration': 5} if with_info_json is True else with_info_json
|
||||
info_json_path = path.with_suffix('.info.json')
|
||||
info_json_path.write_text(json.dumps(with_info_json))
|
||||
test_session.add(File(path=info_json_path))
|
||||
|
||||
poster_path = None
|
||||
if with_poster_ext:
|
||||
poster_path = path.with_suffix(f'.{with_poster_ext}')
|
||||
poster_path = path.with_suffix(f'.{with_poster_ext.lstrip(".")}')
|
||||
Image.new('RGB', (25, 25)).save(poster_path)
|
||||
test_session.add(File(path=poster_path))
|
||||
|
||||
caption_path = None
|
||||
if with_caption_file:
|
||||
caption_path = path.with_suffix('.en.vtt')
|
||||
shutil.copy(PROJECT_DIR / 'test/example1.en.vtt', caption_path)
|
||||
test_session.add(File(path=caption_path))
|
||||
|
||||
video = Video(
|
||||
video_path=path,
|
||||
title=title,
|
||||
channel_id=channel_id,
|
||||
source_id=source_id or title,
|
||||
info_json_path=info_json_path,
|
||||
poster_path=poster_path,
|
||||
caption_path=caption_path,
|
||||
upload_date=upload_date,
|
||||
)
|
||||
test_session.add(video)
|
||||
video_file.do_index()
|
||||
paths = (path, info_json_path, poster_path, caption_path)
|
||||
paths = list(filter(None, paths))
|
||||
|
||||
video = Video.from_paths(test_session, *paths)
|
||||
video.channel_id = channel_id
|
||||
video.source_id = source_id or title
|
||||
video.upload_date = upload_date
|
||||
video.validate()
|
||||
return video
|
||||
|
||||
return factory
|
||||
|
|
@ -167,9 +154,8 @@ def video_download_manager(test_download_manager) -> DownloadManager:
|
|||
def test_channels_config(test_directory):
|
||||
(test_directory / 'config').mkdir(exist_ok=True)
|
||||
config_path = test_directory / 'config/channels.yaml'
|
||||
set_test_channels_config(True)
|
||||
yield config_path
|
||||
set_test_channels_config(False)
|
||||
with set_test_channels_config():
|
||||
yield config_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
|
@ -213,14 +199,19 @@ def assert_video_ids(test_session):
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def video_with_search_factory(test_session, test_directory):
|
||||
def video_with_search_factory(test_session, test_directory, video_file_factory):
|
||||
"""A factory that creates a Video record with an associated video File record."""
|
||||
|
||||
def video_with_search(path: str = None, title: str = None, b_text: str = None, c_text: str = None,
|
||||
d_text: str = None, mimetype: str = 'video/mp4'):
|
||||
path = path or (test_directory / str(uuid4())).absolute()
|
||||
video_file = File(path=path, a_text=title, d_text=d_text, mimetype=mimetype, model='video')
|
||||
video = Video(title=title, video_file=video_file)
|
||||
video_file_group = FileGroup.from_paths(test_session, video_file_factory(path))
|
||||
video_file_group.a_text = title
|
||||
video_file_group.b_text = b_text
|
||||
video_file_group.c_text = c_text
|
||||
video_file_group.d_text = d_text
|
||||
video_file_group.mimetype = mimetype
|
||||
video_file_group.model = 'video'
|
||||
video = Video(file_group=video_file_group)
|
||||
test_session.add(video)
|
||||
return video
|
||||
|
||||
|
|
@ -238,7 +229,7 @@ def assert_video_search(test_client):
|
|||
assert_ids: List[int] = None,
|
||||
assert_paths: List[str] = None,
|
||||
search_str: str = None,
|
||||
filters: List[str] = None,
|
||||
tag_names: List[str] = None,
|
||||
offset: int = None,
|
||||
limit: int = None,
|
||||
order_by: str = None,
|
||||
|
|
@ -247,8 +238,8 @@ def assert_video_search(test_client):
|
|||
content = dict()
|
||||
if search_str is not None:
|
||||
content['search_str'] = search_str
|
||||
if filters is not None:
|
||||
content['filters'] = filters
|
||||
if tag_names is not None:
|
||||
content['tag_names'] = tag_names
|
||||
if offset is not None:
|
||||
content['offset'] = offset
|
||||
if limit is not None:
|
||||
|
|
@ -264,16 +255,15 @@ def assert_video_search(test_client):
|
|||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
if assert_ids is not None:
|
||||
assert 'files' in response.json, 'No video files in response'
|
||||
assert [i['video']['id'] for i in response.json['files']] == assert_ids, 'Video IDs do not match'
|
||||
assert 'file_groups' in response.json, 'No video file_groups in response'
|
||||
assert [i['id'] for i in response.json['file_groups']] == assert_ids, 'Video IDs do not match'
|
||||
|
||||
if assert_paths is not None:
|
||||
assert 'files' in response.json, 'No video files in response'
|
||||
assert [i['video']['video_path'] for i in response.json['files']] == assert_paths, \
|
||||
'Video paths do not match'
|
||||
assert 'file_groups' in response.json, 'No video file_groups in response'
|
||||
assert [i['primary_path'] for i in response.json['file_groups']] == assert_paths, 'Video paths do not match'
|
||||
|
||||
if assert_total:
|
||||
assert response.json['totals']['files'] == int(assert_total), 'Total video files does not match'
|
||||
if assert_total and not (count := response.json['totals']['file_groups']) == int(assert_total):
|
||||
raise AssertionError(f'Video count does not match: {count} != {assert_total}')
|
||||
|
||||
return request, response
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import re
|
|||
import traceback
|
||||
from abc import ABC
|
||||
from typing import Tuple, List, Optional, Dict
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import yt_dlp.utils
|
||||
from sqlalchemy.orm import Session
|
||||
|
|
@ -15,18 +16,18 @@ from yt_dlp.utils import UnsupportedError, DownloadError
|
|||
from wrolpi.cmd import YT_DLP_BIN
|
||||
from wrolpi.common import logger, get_media_directory, escape_file_name, resolve_generators
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.db import get_db_session, get_db_curs
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.db import optional_session
|
||||
from wrolpi.downloader import Downloader, Download, DownloadResult
|
||||
from wrolpi.errors import UnknownChannel, ChannelURLEmpty, UnrecoverableDownloadError
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.lib import glob_shared_stem
|
||||
from wrolpi.vars import PYTEST
|
||||
from .channel.lib import create_channel, get_channel
|
||||
from .common import apply_info_json, get_no_channel_directory, get_videos_directory
|
||||
from .common import get_no_channel_directory, get_videos_directory, update_view_counts
|
||||
from .lib import get_downloader_config
|
||||
from .models import Video, Channel
|
||||
from .schema import ChannelPostRequest
|
||||
from .video_url_resolver import normalize_youtube_shorts_url
|
||||
from .video_url_resolver import normalize_youtube_shorts_url, video_url_resolver
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
ydl_logger = logger.getChild('youtube-dl')
|
||||
|
|
@ -319,13 +320,11 @@ class VideoDownloader(Downloader, ABC):
|
|||
)
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
video_file = File.upsert(video_path, session)
|
||||
video: Video = Video.upsert(video_file, session)
|
||||
# Find any files downloaded with the video (poster, caption, etc.).
|
||||
video_paths = glob_shared_stem(video_path)
|
||||
video = Video.from_paths(session, *video_paths)
|
||||
video.source_id = entry['id']
|
||||
video.channel_id = channel_id
|
||||
video.video_file.do_index()
|
||||
video.validate(session)
|
||||
session.flush([video])
|
||||
video_id = video.id
|
||||
except UnrecoverableDownloadError:
|
||||
raise
|
||||
|
|
@ -464,9 +463,6 @@ def update_channel_catalog(channel: Channel, info: dict):
|
|||
logger.warning(f'entries: {entries}')
|
||||
raise KeyError('No id key for entry!') from e
|
||||
|
||||
# In order to store the Video's URL, we will need a quick lookup.
|
||||
urls = {i['id']: i.get('webpage_url') for i in entries}
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Get the channel in this new context.
|
||||
channel: Channel = session.query(Channel).filter_by(id=channel.id).one()
|
||||
|
|
@ -474,20 +470,7 @@ def update_channel_catalog(channel: Channel, info: dict):
|
|||
channel.info_json = info
|
||||
channel.info_date = now()
|
||||
channel.source_id = info.get('id')
|
||||
|
||||
with get_db_curs() as curs:
|
||||
# Get all known videos in this channel.
|
||||
query = 'SELECT source_id FROM video WHERE channel_id=%s AND source_id IS NOT NULL'
|
||||
curs.execute(query, (channel.id,))
|
||||
known_source_ids = {i[0] for i in curs.fetchall()}
|
||||
|
||||
new_source_ids = all_source_ids.difference(known_source_ids)
|
||||
|
||||
logger.info(f'Got {len(new_source_ids)} new videos for channel {channel.name}')
|
||||
channel_id = channel.id
|
||||
for source_id in new_source_ids:
|
||||
url = urls.get(source_id)
|
||||
session.add(Video(source_id=source_id, channel_id=channel_id, url=url))
|
||||
|
||||
# Write the Channel's info to a JSON file.
|
||||
if channel.directory:
|
||||
|
|
@ -496,30 +479,44 @@ def update_channel_catalog(channel: Channel, info: dict):
|
|||
json.dump(info, fh, indent=2)
|
||||
|
||||
# Update all view counts using the latest from the Channel's info_json.
|
||||
apply_info_json(channel_id)
|
||||
update_view_counts(channel_id)
|
||||
|
||||
|
||||
def _find_all_missing_videos(channel_id: id) -> List[Tuple]:
|
||||
"""Get all Video entries which don't have the required media files (i.e. hasn't been downloaded)."""
|
||||
with get_db_curs() as curs:
|
||||
query = f'''
|
||||
SELECT
|
||||
video.id, video.source_id, video.channel_id
|
||||
FROM
|
||||
video
|
||||
LEFT JOIN channel ON channel.id = video.channel_id
|
||||
WHERE
|
||||
channel.url IS NOT NULL
|
||||
AND channel.url != ''
|
||||
AND video.source_id IS NOT NULL
|
||||
AND channel_id = %s
|
||||
AND video.channel_id IS NOT NULL
|
||||
AND (video_path IS NULL OR video_path = '' OR poster_path IS NULL OR poster_path = '')
|
||||
'''
|
||||
params = (channel_id,)
|
||||
curs.execute(query, params)
|
||||
missing_videos = list(curs.fetchall())
|
||||
return missing_videos
|
||||
with get_db_session() as session:
|
||||
channel: Channel = Channel.get_by_id(channel_id)
|
||||
if not channel:
|
||||
raise UnknownChannel(f'Cannot find channel with id {channel_id}')
|
||||
|
||||
def resolve_url(entry: dict) -> str:
|
||||
parsed = urlparse(entry.get('webpage_url') or entry['url'])
|
||||
domain = parsed.hostname
|
||||
url_ = video_url_resolver(domain, entry)
|
||||
url_ = normalize_youtube_shorts_url(url_)
|
||||
return url_
|
||||
|
||||
info_json = channel.info_json
|
||||
# (source_id, url, channel_id)
|
||||
channel_videos = [(i['id'], resolve_url(i), channel_id) for i in info_json['entries']]
|
||||
|
||||
video_source_ids = [i[0] for i in channel_videos]
|
||||
videos_with_source_id = list(session.query(Video).filter(Video.source_id.in_(video_source_ids)))
|
||||
found_source_ids = set()
|
||||
missing_files = []
|
||||
for video in videos_with_source_id:
|
||||
found_source_ids |= {video.source_id, }
|
||||
if not video.poster_path:
|
||||
missing_files.append(video)
|
||||
elif not video.video_path:
|
||||
missing_files.append(video)
|
||||
|
||||
missing_source_ids = set(video_source_ids) - found_source_ids
|
||||
for source_id in missing_source_ids:
|
||||
yield None, source_id, channel_id
|
||||
|
||||
for video in missing_files:
|
||||
yield video.id, video.source_id, channel_id
|
||||
|
||||
|
||||
async def find_all_missing_videos(channel_id: int = None):
|
||||
|
|
|
|||
|
|
@ -1,20 +1,24 @@
|
|||
import contextlib
|
||||
import datetime
|
||||
import functools
|
||||
import html
|
||||
import pathlib
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from typing import Tuple, Optional, Union, Generator
|
||||
import warnings
|
||||
from typing import Tuple, Optional, Generator
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
from yt_dlp import YoutubeDL
|
||||
|
||||
from wrolpi import before_startup
|
||||
from wrolpi.common import ConfigFile, get_media_directory, sanitize_link, register_after_refresh
|
||||
from wrolpi.dates import from_timestamp, Seconds
|
||||
from wrolpi.captions import extract_captions
|
||||
from wrolpi.common import ConfigFile, get_media_directory, sanitize_link, register_after_refresh, limit_concurrent
|
||||
from wrolpi.dates import Seconds
|
||||
from wrolpi.db import get_db_curs, get_db_session, optional_session
|
||||
from wrolpi.errors import UnknownDirectory
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.vars import PYTEST
|
||||
from .common import is_valid_poster, convert_image, \
|
||||
generate_video_poster, logger, REQUIRED_OPTIONS, ConfigError, \
|
||||
|
|
@ -61,7 +65,10 @@ def get_channel_id_by_source_id(session: Session, source_id: str) -> Optional[in
|
|||
return channel.id if channel else None
|
||||
|
||||
|
||||
def validate_video(video: Video, channel_generate_poster: bool, session: Session):
|
||||
EXTRACT_SUBTITLES = False
|
||||
|
||||
|
||||
def validate_video(video: Video, channel_generate_poster: bool):
|
||||
"""
|
||||
Validate a single video.
|
||||
|
||||
|
|
@ -71,13 +78,13 @@ def validate_video(video: Video, channel_generate_poster: bool, session: Session
|
|||
A Video is also valid when it has a JPEG poster, if any. If no poster can be
|
||||
found, it will be generated from the video file.
|
||||
"""
|
||||
info_json_path = video.info_json_file.path if video.info_json_file else video.info_json_path
|
||||
json_data_missing = bool(video.title) and bool(video.duration) and bool(video.view_count) and bool(video.url) \
|
||||
and bool(video.upload_date)
|
||||
info_json_path = video.info_json_path
|
||||
json_data_missing = bool(video.file_group.title) and bool(video.duration) and bool(video.view_count) \
|
||||
and bool(video.url) and bool(video.upload_date)
|
||||
if info_json_path and json_data_missing is False:
|
||||
# These properties can be found in the info json.
|
||||
video_info_json = process_video_info_json(video)
|
||||
video.title = video_info_json.title
|
||||
video.file_group.title = video_info_json.title
|
||||
video.duration = video_info_json.duration
|
||||
video.url = video_info_json.url
|
||||
# View count will probably be overwritten by more recent data when this Video's Channel is
|
||||
|
|
@ -89,35 +96,40 @@ def validate_video(video: Video, channel_generate_poster: bool, session: Session
|
|||
|
||||
video_path = video.video_path
|
||||
|
||||
if not video.title or not video.upload_date or not video.source_id:
|
||||
if video_path and (not video.file_group.title or not video.upload_date or not video.source_id):
|
||||
# Video is missing things that can be extracted from the video file name.
|
||||
# These are the least trusted, so anything already on the video should be trusted.
|
||||
_, upload_date, source_id, title = parse_video_file_name(video_path)
|
||||
video.title = video.title or html.unescape(title)
|
||||
video.upload_date = video.upload_date or upload_date
|
||||
upload_date = upload_date or video.upload_date
|
||||
if upload_date:
|
||||
upload_date = datetime.datetime.strptime(upload_date, '%Y%M%d')
|
||||
upload_date = upload_date.replace(tzinfo=datetime.timezone.utc)
|
||||
video.file_group.title = video.file_group.title or html.unescape(title)
|
||||
video.upload_date = upload_date
|
||||
video.source_id = video.source_id or source_id
|
||||
|
||||
if not video.size or not video.modification_datetime:
|
||||
stat = video_path.stat()
|
||||
video.size = video.size or stat.st_size
|
||||
video.modification_datetime = video.modification_datetime or from_timestamp(stat.st_mtime)
|
||||
|
||||
if channel_generate_poster:
|
||||
# Try to convert/generate, but keep the old poster if those fail.
|
||||
new_poster_path, duration = convert_or_generate_poster(video) or video.poster_path
|
||||
if new_poster_path:
|
||||
# Poster was created/updated.
|
||||
poster_file = File.upsert(new_poster_path, session)
|
||||
session.flush([poster_file])
|
||||
video.poster_file = poster_file
|
||||
video.poster_path = new_poster_path
|
||||
video.file_group.append_files(new_poster_path)
|
||||
if duration:
|
||||
video.duration = duration
|
||||
|
||||
if not video.duration:
|
||||
if video_path and not video.duration:
|
||||
# Duration was not retrieved during poster generation.
|
||||
video.duration = get_video_duration(video_path)
|
||||
|
||||
if video_path and not video.caption_paths and video.file_group.d_text and not EXTRACT_SUBTITLES:
|
||||
# Caption file was deleted, clear out old captions.
|
||||
video.file_group.d_text = None
|
||||
elif video_path and not video.file_group.d_text and EXTRACT_SUBTITLES:
|
||||
# Captions were not found, extract them from the video.
|
||||
video.file_group.d_text = extract_captions(video_path)
|
||||
elif video_path and video.caption_paths and not video.file_group.d_text:
|
||||
video.file_group.d_text = video.get_caption_text()
|
||||
|
||||
|
||||
def convert_or_generate_poster(video: Video) -> Tuple[Optional[pathlib.Path], Optional[int]]:
|
||||
"""
|
||||
|
|
@ -128,28 +140,32 @@ def convert_or_generate_poster(video: Video) -> Tuple[Optional[pathlib.Path], Op
|
|||
"""
|
||||
video_path = video.video_path
|
||||
# Modification/generation of poster is enabled for this channel.
|
||||
if video.poster_path or video.poster_file:
|
||||
if video.poster_path:
|
||||
# Check that the poster is a more universally supported JPEG.
|
||||
old: pathlib.Path = video.poster_path if video.poster_path else video.poster_file.path
|
||||
old: pathlib.Path = video.poster_path
|
||||
new = old.with_suffix('.jpg')
|
||||
|
||||
if old != new and new.exists():
|
||||
# Destination JPEG already exists (it may have the wrong format).
|
||||
old.unlink()
|
||||
old = video.poster_path = new
|
||||
old = new
|
||||
|
||||
if not is_valid_poster(old):
|
||||
# Poster is not valid, convert it and place it in the new location.
|
||||
try:
|
||||
convert_image(old, new)
|
||||
old.unlink(missing_ok=True)
|
||||
if not new.is_file():
|
||||
raise FileNotFoundError(f'Failed to convert poster: {new}')
|
||||
if old != new:
|
||||
# Only remove the old one if we are not converting in-place.
|
||||
old.unlink(missing_ok=True)
|
||||
logger.info(f'Converted invalid poster {repr(str(old))} to {repr(str(new))}')
|
||||
return new, None
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to convert invalid poster {old} to {new}', exc_info=e)
|
||||
return None, None
|
||||
|
||||
if not video.poster_path and not video.poster_file:
|
||||
if not video.poster_path:
|
||||
# Video poster was not discovered, or converted. Let's generate it.
|
||||
try:
|
||||
poster_path, duration = generate_video_poster(video_path)
|
||||
|
|
@ -185,10 +201,12 @@ class ChannelsConfig(ConfigFile):
|
|||
|
||||
@property
|
||||
def favorites(self) -> dict:
|
||||
warnings.warn('Favorites have bee moved to Tags', DeprecationWarning)
|
||||
return self._config['favorites']
|
||||
|
||||
@favorites.setter
|
||||
def favorites(self, value: dict):
|
||||
warnings.warn('Favorites have bee moved to Tags', DeprecationWarning)
|
||||
self.update({'favorites': value})
|
||||
|
||||
|
||||
|
|
@ -205,12 +223,12 @@ def get_channels_config():
|
|||
return CHANNELS_CONFIG
|
||||
|
||||
|
||||
def set_test_channels_config(enable: bool):
|
||||
@contextlib.contextmanager
|
||||
def set_test_channels_config():
|
||||
global TEST_CHANNELS_CONFIG
|
||||
if enable is True:
|
||||
TEST_CHANNELS_CONFIG = ChannelsConfig()
|
||||
else:
|
||||
TEST_CHANNELS_CONFIG = None
|
||||
TEST_CHANNELS_CONFIG = ChannelsConfig()
|
||||
yield
|
||||
TEST_CHANNELS_CONFIG = None
|
||||
|
||||
|
||||
class VideoDownloaderConfig(ConfigFile):
|
||||
|
|
@ -334,46 +352,14 @@ def get_channels_config_from_db(session: Session) -> dict:
|
|||
"""Create a dictionary that contains all the Channels from the DB."""
|
||||
channels = session.query(Channel).order_by(Channel.directory).all()
|
||||
channels = sorted((i.config_view() for i in channels), key=lambda i: i['directory'])
|
||||
|
||||
# Get all Videos that are favorites. Store them in their own config section, so they can be preserved if a channel
|
||||
# is deleted or the DB is wiped.
|
||||
favorite_videos = session.query(Video).filter(Video.favorite != None, Video.video_path != None).all() # noqa
|
||||
favorites = defaultdict(lambda: {})
|
||||
for video in favorite_videos:
|
||||
if video.channel:
|
||||
directory = video.channel.directory.relative_to(get_media_directory())
|
||||
favorites[str(directory)][video.video_path.name] = dict(favorite=video.favorite)
|
||||
else:
|
||||
favorites['NO CHANNEL'][video.video_path.name] = dict(favorite=video.favorite)
|
||||
favorites = dict(favorites)
|
||||
|
||||
return dict(channels=channels, favorites=favorites)
|
||||
|
||||
|
||||
def _detect_old_favorites(config: Union[ChannelsConfig, dict]) -> bool:
|
||||
# TODO remove these old favorites after beta.
|
||||
media_directory = get_media_directory()
|
||||
favorites = config.favorites if hasattr(config, 'favorites') else config['favorites']
|
||||
for channel, favorites in favorites.items():
|
||||
if channel == 'NO CHANNEL':
|
||||
continue
|
||||
if not (media_directory / channel).is_dir():
|
||||
return True
|
||||
return False
|
||||
return dict(channels=channels)
|
||||
|
||||
|
||||
@optional_session()
|
||||
def save_channels_config(session=None, preserve_favorites: bool = True):
|
||||
def save_channels_config(session: Session = None):
|
||||
"""Get the Channel information from the DB, save it to the config."""
|
||||
config = get_channels_config_from_db(session)
|
||||
channels_config = get_channels_config()
|
||||
# TODO remove these old favorites after beta.
|
||||
old_favorites = _detect_old_favorites(channels_config)
|
||||
if old_favorites and config['favorites']:
|
||||
# There are favorites in the database, remove the old favorites.
|
||||
channels_config.favorites = {}
|
||||
if preserve_favorites:
|
||||
config['favorites'].update(channels_config.favorites or {})
|
||||
channels_config.update(config)
|
||||
|
||||
|
||||
|
|
@ -382,6 +368,7 @@ channel_import_logger = logger.getChild('channel_import')
|
|||
|
||||
@before_startup
|
||||
@register_after_refresh
|
||||
@limit_concurrent(1)
|
||||
def import_channels_config():
|
||||
"""Import channel settings to the DB. Existing channels will be updated."""
|
||||
if PYTEST and not TEST_CHANNELS_CONFIG:
|
||||
|
|
@ -469,15 +456,19 @@ def import_channels_config():
|
|||
else:
|
||||
channel_dir = get_no_channel_directory()
|
||||
|
||||
favorites_tag = Tag.find_by_name('Favorite')
|
||||
if not favorites_tag:
|
||||
channel_import_logger.warning(f'Cannot tag favorite videos without Favorite tag!')
|
||||
return
|
||||
|
||||
# Set favorite Videos of this Channel.
|
||||
for video_path, data in favorites.items():
|
||||
# Favorite in the config is the name of the video_path. Add the channel directory onto this
|
||||
# video_path, so we can match the complete path for the Video.
|
||||
video_path = channel_dir / video_path
|
||||
video = session.query(Video).filter_by(video_path=video_path).one_or_none()
|
||||
# If no Video is found, it may be that we need to refresh.
|
||||
if video:
|
||||
video.favorite = data['favorite']
|
||||
file_group = FileGroup.find_by_path(video_path, session)
|
||||
if file_group:
|
||||
file_group.add_tag(favorites_tag, session)
|
||||
else:
|
||||
channel_import_logger.warning(f'Cannot find video to favorite: {video_path}')
|
||||
except Exception as e:
|
||||
|
|
@ -503,22 +494,12 @@ async def get_statistics():
|
|||
SELECT
|
||||
-- total videos
|
||||
COUNT(id) AS "videos",
|
||||
-- total videos that are marked as favorite
|
||||
COUNT(id) FILTER (WHERE favorite IS NOT NULL) AS "favorites",
|
||||
-- total videos downloaded over the past week/month/year
|
||||
COUNT(id) FILTER (WHERE upload_date >= current_date - interval '1 week') AS "week",
|
||||
COUNT(id) FILTER (WHERE upload_date >= current_date - interval '1 month') AS "month",
|
||||
COUNT(id) FILTER (WHERE upload_date >= current_date - interval '1 year') AS "year",
|
||||
-- sum of all video lengths in seconds
|
||||
COALESCE(SUM(duration), 0) AS "sum_duration",
|
||||
-- sum of all video file sizes
|
||||
COALESCE(SUM(size), 0)::BIGINT AS "sum_size",
|
||||
-- largest video
|
||||
COALESCE(MAX(size), 0) AS "max_size"
|
||||
COUNT(id) FILTER (WHERE upload_date >= current_date - interval '1 year') AS "year"
|
||||
FROM
|
||||
video
|
||||
WHERE
|
||||
video_path IS NOT NULL
|
||||
''')
|
||||
video_stats = dict(curs.fetchone())
|
||||
|
||||
|
|
@ -526,8 +507,7 @@ async def get_statistics():
|
|||
curs.execute('''
|
||||
SELECT
|
||||
DATE_TRUNC('month', months.a),
|
||||
COUNT(id)::BIGINT,
|
||||
SUM(size)::BIGINT AS "size"
|
||||
COUNT(id)::BIGINT
|
||||
FROM
|
||||
generate_series(
|
||||
date_trunc('month', current_date) - interval '2 years',
|
||||
|
|
@ -538,7 +518,6 @@ async def get_statistics():
|
|||
video.upload_date >= date_trunc('month', months.a)
|
||||
AND video.upload_date < date_trunc('month', months.a) + interval '1 month'
|
||||
AND video.upload_date IS NOT NULL
|
||||
AND video.video_path IS NOT NULL
|
||||
GROUP BY
|
||||
1
|
||||
ORDER BY
|
||||
|
|
@ -610,18 +589,11 @@ def find_orphaned_video_files(directory: pathlib.Path) -> Generator[pathlib.Path
|
|||
directory = str(directory).rstrip('/')
|
||||
|
||||
curs.execute(f'''
|
||||
SELECT f1.path
|
||||
FROM (
|
||||
-- Get array of mimetypes for each full_stem group.
|
||||
select f2.full_stem, array_agg(f2.mimetype) as mimetypes
|
||||
from file f2
|
||||
where f2.full_stem like '{directory}/%'
|
||||
group by 1) AS stem_groups
|
||||
-- Get all files that match the full_stem.
|
||||
LEFT JOIN file f1 ON stem_groups.full_stem = f1.full_stem
|
||||
-- Get all groups which DO NOT contain one of the video mimetypes.
|
||||
WHERE NOT (select array_agg(f3.mimetype) from file f3 where f3.mimetype like 'video/%') && stem_groups.mimetypes
|
||||
SELECT files
|
||||
FROM file_group
|
||||
WHERE
|
||||
mimetype NOT LIKE 'video%'
|
||||
AND full_stem LIKE '{directory}/%'
|
||||
''')
|
||||
results = map(lambda i: pathlib.Path(i[0]), curs.fetchall())
|
||||
results = filter(lambda i: i.is_file(), results)
|
||||
results = (pathlib.Path(j['path']) for i in curs.fetchall() for j in i[0])
|
||||
yield from results
|
||||
|
|
|
|||
|
|
@ -1,21 +1,23 @@
|
|||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional, Generator, Dict, List
|
||||
from typing import Optional, Dict, List, Union
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ARRAY, ForeignKey
|
||||
from sqlalchemy.orm import relationship, Session
|
||||
from sqlalchemy import Column, Integer, String, Boolean, JSON, Date, ARRAY, ForeignKey, BigInteger, any_
|
||||
from sqlalchemy.orm import relationship, Session, deferred
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.captions import read_captions
|
||||
from wrolpi.common import Base, ModelHelper, logger, get_media_directory, background_task
|
||||
from wrolpi.dates import now, TZDateTime
|
||||
from wrolpi.db import get_db_curs, get_db_session
|
||||
from wrolpi.db import get_db_curs, get_db_session, optional_session
|
||||
from wrolpi.downloader import Download, download_manager
|
||||
from wrolpi.errors import UnknownVideo
|
||||
from wrolpi.files.lib import refresh_directory_files_recursively, glob_shared_stem, split_path_stem_and_suffix
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.lib import refresh_files, get_mimetype, split_path_stem_and_suffix
|
||||
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__)
|
||||
|
|
@ -24,119 +26,73 @@ logger = logger.getChild(__name__)
|
|||
class Video(ModelHelper, Base):
|
||||
__tablename__ = 'video'
|
||||
id = Column(Integer, primary_key=True)
|
||||
channel_id = Column(Integer, ForeignKey('channel.id'))
|
||||
channel = relationship('Channel', primaryjoin='Video.channel_id==Channel.id', back_populates='videos')
|
||||
validated = Column(Boolean, default=False)
|
||||
|
||||
censored = Column(Boolean, default=False)
|
||||
duration = Column(Integer)
|
||||
favorite = Column(TZDateTime)
|
||||
modification_datetime = Column(TZDateTime)
|
||||
size = Column(Integer)
|
||||
source_id = Column(String)
|
||||
title = Column(String)
|
||||
upload_date = Column(TZDateTime)
|
||||
upload_date: datetime.datetime = Column(TZDateTime)
|
||||
url = Column(String)
|
||||
view_count = Column(Integer)
|
||||
viewed = Column(TZDateTime)
|
||||
|
||||
# Associated Files
|
||||
caption_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
caption_file: File = relationship('File', primaryjoin='Video.caption_path==File.path')
|
||||
info_json_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
info_json_file: File = relationship('File', primaryjoin='Video.info_json_path==File.path')
|
||||
poster_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
poster_file: File = relationship('File', primaryjoin='Video.poster_path==File.path')
|
||||
video_path: pathlib.Path = Column(MediaPathType, ForeignKey('file.path', ondelete='CASCADE'))
|
||||
video_file: File = relationship('File', primaryjoin='Video.video_path==File.path')
|
||||
channel_id = Column(Integer, ForeignKey('channel.id'))
|
||||
channel = relationship('Channel', primaryjoin='Video.channel_id==Channel.id', back_populates='videos')
|
||||
file_group_id = Column(BigInteger, ForeignKey('file_group.id', ondelete='CASCADE'), unique=True, nullable=False)
|
||||
file_group: FileGroup = relationship('FileGroup')
|
||||
|
||||
def __repr__(self):
|
||||
v = self.video_file
|
||||
v = None
|
||||
if self.video_path:
|
||||
video_path = self.video_path.path if hasattr(self.video_path, 'path') else self.video_path
|
||||
v = video_path.relative_to(get_media_directory())
|
||||
return f'<Video id={self.id} title={repr(self.title)} path={v} channel={self.channel_id} ' \
|
||||
v = self.video_path.relative_to(get_media_directory())
|
||||
return f'<Video id={self.id} title={repr(self.file_group.name)} path={v} channel={self.channel_id} ' \
|
||||
f'source_id={repr(self.source_id)}>'
|
||||
|
||||
@classmethod
|
||||
def upsert(cls, video_file: File, session: Session):
|
||||
video = session.query(Video).filter_by(video_file=video_file).one_or_none()
|
||||
if not video:
|
||||
video = Video(video_file=video_file)
|
||||
video: Video
|
||||
video.video_path = video.video_path or video_file.path
|
||||
video.video_file = video.video_file or video_file
|
||||
video.size = video.video_path.stat().st_size
|
||||
session.add(video)
|
||||
def __json__(self) -> dict:
|
||||
d = self.file_group.__json__()
|
||||
|
||||
video.find_my_files()
|
||||
channel = None
|
||||
if self.channel:
|
||||
channel = dict(id=self.channel.id, name=self.channel.name)
|
||||
|
||||
# Claim the video file for this model.
|
||||
video.video_file.model = cls.__tablename__
|
||||
|
||||
return video
|
||||
|
||||
def my_paths(self) -> Generator[Path, None, None]:
|
||||
"""Return all paths of this Video. Returns nothing if all paths are None."""
|
||||
if self.poster_path:
|
||||
yield self.poster_path
|
||||
if self.caption_path:
|
||||
yield self.caption_path
|
||||
if self.info_json_path:
|
||||
yield self.info_json_path
|
||||
if self.video_path:
|
||||
yield self.video_path
|
||||
|
||||
def my_files(self) -> Generator[File, None, None]:
|
||||
"""Return all Files of this Video. Returns nothing if all paths are None."""
|
||||
if self.poster_file:
|
||||
yield self.poster_file
|
||||
if self.caption_file:
|
||||
yield self.caption_file
|
||||
if self.info_json_file:
|
||||
yield self.info_json_file
|
||||
if self.video_file:
|
||||
yield self.video_file
|
||||
# Put live data in "video" instead of "data" to avoid confusion on the frontend.
|
||||
d['video'] = dict(
|
||||
caption=self.file_group.d_text,
|
||||
caption_files=self.caption_files,
|
||||
channel=channel,
|
||||
channel_id=self.channel_id,
|
||||
description=self.file_group.c_text or self.get_video_description(),
|
||||
id=self.id,
|
||||
info_json_file=self.info_json_file,
|
||||
info_json_path=self.info_json_path,
|
||||
poster_file=self.poster_file,
|
||||
poster_path=self.poster_path,
|
||||
source_id=self.source_id,
|
||||
stem=split_path_stem_and_suffix(self.video_path)[0],
|
||||
upload_date=self.upload_date.isoformat() if self.upload_date else None,
|
||||
url=self.url,
|
||||
video_path=self.video_path,
|
||||
view_count=self.view_count,
|
||||
)
|
||||
return d
|
||||
|
||||
def delete(self):
|
||||
"""
|
||||
Remove all files and File records related to this video. Delete this Video record.
|
||||
Add it to it's Channel's skip list.
|
||||
"""
|
||||
for path in self.my_paths():
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
needs_save = bool(self.favorite)
|
||||
|
||||
"""Remove all files and File records related to this video. Delete this Video record.
|
||||
Add it to it's Channel's skip list."""
|
||||
self.add_to_skip_list()
|
||||
self.favorite = None
|
||||
session = Session.object_session(self)
|
||||
session.commit()
|
||||
session.delete(self)
|
||||
|
||||
for file in self.my_files():
|
||||
session.delete(file)
|
||||
|
||||
if needs_save:
|
||||
# Save the Channels config. This video was a favorite and that needs to be removed.
|
||||
from modules.videos.lib import save_channels_config
|
||||
save_channels_config(preserve_favorites=False)
|
||||
self.file_group.delete()
|
||||
|
||||
def add_to_skip_list(self):
|
||||
"""Add this video to it's Channel's skip list."""
|
||||
if self.channel and self.source_id:
|
||||
self.channel.add_video_to_skip_list(self.source_id)
|
||||
|
||||
def set_favorite(self, favorite: bool) -> Optional[datetime]:
|
||||
self.favorite = now() if favorite else None
|
||||
return self.favorite
|
||||
|
||||
def set_viewed(self):
|
||||
self.viewed = now()
|
||||
|
||||
def get_info_json(self) -> Optional[Dict]:
|
||||
"""If this Video has an info_json file, return it's contents. Otherwise, return None."""
|
||||
info_json_path = self.info_json_file.path if self.info_json_file else self.info_json_path
|
||||
info_json_path = self.info_json_path
|
||||
if not info_json_path:
|
||||
return
|
||||
|
||||
|
|
@ -145,10 +101,6 @@ class Video(ModelHelper, Base):
|
|||
return json.load(fh)
|
||||
except FileNotFoundError:
|
||||
logger.warning(f'Unable to find info json file! {info_json_path}')
|
||||
if self.video_path.is_file():
|
||||
# Clear out the info_json only if the video file exists. We don't want to clear out the info_json if
|
||||
# the drive hasn't been mounted.
|
||||
self.info_json_file = self.info_json_path = None
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(f'Unable to parse info json {self.info_json_path}', exc_info=e)
|
||||
|
|
@ -165,11 +117,6 @@ class Video(ModelHelper, Base):
|
|||
if description:
|
||||
return description
|
||||
|
||||
if self.description_path:
|
||||
with open(self.description_path, 'rt') as fh:
|
||||
contents = fh.read()
|
||||
return contents
|
||||
|
||||
def get_surrounding_videos(self):
|
||||
"""
|
||||
Get the previous and next videos around this video. The videos must be in the same channel.
|
||||
|
|
@ -236,96 +183,111 @@ class Video(ModelHelper, Base):
|
|||
|
||||
return previous_video, next_video
|
||||
|
||||
def __json__(self):
|
||||
from modules.videos.common import minimize_video_info_json
|
||||
info_json = minimize_video_info_json(self.get_info_json()) if self.info_json_path else None
|
||||
stem, _ = split_path_stem_and_suffix(self.video_path) if self.video_file else (None, None)
|
||||
|
||||
d = dict(
|
||||
caption_path=self.caption_path,
|
||||
censored=self.censored,
|
||||
channel=self.channel,
|
||||
channel_id=self.channel_id,
|
||||
modification_datetime=self.modification_datetime,
|
||||
duration=self.duration,
|
||||
favorite=self.favorite,
|
||||
id=self.id,
|
||||
info_json=info_json,
|
||||
info_json_path=self.info_json_path,
|
||||
poster_path=self.poster_path,
|
||||
size=self.size,
|
||||
source_id=self.source_id,
|
||||
stem=stem,
|
||||
title=self.title,
|
||||
upload_date=self.upload_date,
|
||||
url=self.url,
|
||||
validated=self.validated,
|
||||
view_count=self.view_count,
|
||||
video_path=self.video_path.relative_to(get_media_directory()),
|
||||
viewed=self.viewed,
|
||||
)
|
||||
return d
|
||||
|
||||
def validate(self, session: Session):
|
||||
"""Perform a validation of this video and it's files. Mark this video as validated if no errors occur."""
|
||||
if not self.video_file:
|
||||
def validate(self):
|
||||
"""Perform a validation of this video and it's files."""
|
||||
if not self.file_group.primary_path:
|
||||
# Can't validate if there is no video file.
|
||||
return False
|
||||
logger.error(f'Unable to validate video {self.id} without primary file!')
|
||||
|
||||
from .lib import validate_video
|
||||
try:
|
||||
validate_video(self, self.channel.generate_posters if self.channel else False, session)
|
||||
self.validated = True
|
||||
validate_video(self, self.channel.generate_posters if self.channel else False)
|
||||
except Exception as e:
|
||||
logger.warning(f'Failed to validate video {self}', exc_info=e)
|
||||
|
||||
return self.validated
|
||||
|
||||
def find_my_files(self):
|
||||
"""Search near the video file for it's associated files. (poster, caption, etc.)"""
|
||||
from modules.videos.common import match_video_files
|
||||
if not self.video_path:
|
||||
raise ValueError("Can't find files when I don't have a video path!")
|
||||
|
||||
# Associated files share the same stem, but different extensions.
|
||||
associated_paths = glob_shared_stem(self.video_path)
|
||||
associated_paths.pop(associated_paths.index(self.video_path))
|
||||
|
||||
# Get the session from the video first, fallback to the video file.
|
||||
session: Session = Session.object_session(self) or Session.object_session(self.video_file)
|
||||
|
||||
files = [File.upsert(i, session) for i in associated_paths]
|
||||
_, poster_file, description_file, caption_file, info_json_file = match_video_files(files)
|
||||
|
||||
if poster_file:
|
||||
poster_file.do_index()
|
||||
poster_file.associated = True
|
||||
if caption_file:
|
||||
caption_file.do_index()
|
||||
caption_file.associated = True
|
||||
if info_json_file:
|
||||
info_json_file.do_index()
|
||||
info_json_file.associated = True
|
||||
|
||||
session.flush([i for i in files])
|
||||
|
||||
self.poster_file = poster_file
|
||||
self.caption_file = caption_file
|
||||
self.info_json_file = info_json_file
|
||||
self.file_group.model = Video.__tablename__
|
||||
self.file_group.a_text = self.file_group.title
|
||||
self.file_group.c_text = self.get_video_description()
|
||||
# self.file_group.d_text is handled in `validate_video`.
|
||||
|
||||
@staticmethod
|
||||
def find_by_path(path, session):
|
||||
video = session.query(Video).filter_by(video_path=path).one_or_none()
|
||||
def from_paths(session: Session, *paths: pathlib.Path) -> 'Video':
|
||||
str_paths = list(map(str, paths))
|
||||
file_group = session.query(FileGroup).filter(FileGroup.primary_path == any_(str_paths)).one_or_none()
|
||||
if not file_group:
|
||||
# This video has not been downloaded previously.
|
||||
file_group = FileGroup.from_paths(session, *paths)
|
||||
|
||||
# Video may have been downloaded previously.
|
||||
video = session.query(Video).filter(Video.file_group_id == file_group.id).one_or_none()
|
||||
if not video:
|
||||
video = Video(file_group=file_group)
|
||||
|
||||
video.validate()
|
||||
session.add(video)
|
||||
session.flush([video, file_group])
|
||||
return video
|
||||
|
||||
@property
|
||||
def info_json_file(self) -> Optional[dict]:
|
||||
for file in self.file_group.my_json_files():
|
||||
return file
|
||||
|
||||
@property
|
||||
def info_json_path(self) -> Optional[pathlib.Path]:
|
||||
if info_json_file := self.info_json_file:
|
||||
return info_json_file['path']
|
||||
|
||||
@property
|
||||
def video_path(self) -> Optional[pathlib.Path]:
|
||||
if self.file_group.primary_path and get_mimetype(self.file_group.primary_path).startswith('video/'):
|
||||
return self.file_group.primary_path
|
||||
|
||||
# No primary file somehow, return the first video file.
|
||||
for file_group in self.file_group.my_video_files():
|
||||
return file_group['path']
|
||||
|
||||
@property
|
||||
def poster_file(self) -> Optional[dict]:
|
||||
for file_group in self.file_group.my_poster_files():
|
||||
return file_group
|
||||
|
||||
@property
|
||||
def poster_path(self) -> Optional[pathlib.Path]:
|
||||
if poster_file := self.poster_file:
|
||||
return poster_file['path']
|
||||
|
||||
@property
|
||||
def caption_files(self) -> List[dict]:
|
||||
return self.file_group.my_files('text/srt') + self.file_group.my_files('text/vtt')
|
||||
|
||||
@property
|
||||
def caption_paths(self) -> List[pathlib.Path]:
|
||||
return [i['path'] for i in self.caption_files]
|
||||
|
||||
def get_caption_text(self) -> Optional[str]:
|
||||
"""Search the FileGroup's files for a caption file. Return the captions from only the best caption file."""
|
||||
caption_paths = self.caption_paths
|
||||
# Some SRT files are more supported than others, these are their preferred order.
|
||||
caption_text = None
|
||||
if english_srt := [i for i in caption_paths if i.name.endswith('.en.srt')]:
|
||||
caption_text = read_captions(english_srt[0])
|
||||
elif srt := [i for i in caption_paths if i.name.endswith('.srt')]:
|
||||
caption_text = read_captions(srt[0])
|
||||
elif english_vtt := [i for i in caption_paths if i.name.endswith('.en.vtt')]:
|
||||
caption_text = read_captions(english_vtt[0])
|
||||
elif vtt := [i for i in caption_paths if i.name.endswith('.vtt')]:
|
||||
caption_text = read_captions(vtt[0])
|
||||
|
||||
return caption_text
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def find_by_path(path, session: Session) -> Optional['Video']:
|
||||
video = session.query(Video) \
|
||||
.join(FileGroup, FileGroup.id == Video.file_group_id) \
|
||||
.filter(FileGroup.primary_path == path).one_or_none()
|
||||
return video
|
||||
|
||||
@staticmethod
|
||||
def find_by_paths(paths: List[pathlib.Path], session) -> List:
|
||||
videos = list(session.query(Video).filter(Video.video_path.in_(paths)))
|
||||
return videos
|
||||
@optional_session
|
||||
def find_by_id(id_: int, session: Session) -> Optional['Video']:
|
||||
video = session.query(Video).filter(Video.id == id_).one_or_none()
|
||||
return video
|
||||
|
||||
@property
|
||||
def primary_path(self):
|
||||
return self.video_path
|
||||
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 Channel(ModelHelper, Base):
|
||||
|
|
@ -342,7 +304,7 @@ class Channel(ModelHelper, Base):
|
|||
source_id = Column(String)
|
||||
refreshed = Column(Boolean, default=False)
|
||||
|
||||
info_json = Column(JSON)
|
||||
info_json = deferred(Column(JSON))
|
||||
info_date = Column(Date)
|
||||
|
||||
videos: InstrumentedList = relationship('Video', primaryjoin='Channel.id==Video.channel_id')
|
||||
|
|
@ -414,7 +376,6 @@ class Channel(ModelHelper, Base):
|
|||
calculate_duration=self.calculate_duration,
|
||||
directory=str(self.directory),
|
||||
download_frequency=self.download_frequency,
|
||||
favorites={},
|
||||
generate_posters=self.generate_posters,
|
||||
match_regex=self.match_regex or '',
|
||||
name=self.name,
|
||||
|
|
@ -464,9 +425,10 @@ class Channel(ModelHelper, Base):
|
|||
SELECT
|
||||
SUM(size),
|
||||
MAX(size),
|
||||
COUNT(id)
|
||||
COUNT(video.id)
|
||||
FROM video
|
||||
WHERE channel_id = %(id)s AND video_path IS NOT NULL
|
||||
LEFT JOIN file_group fg on fg.id = video.file_group_id
|
||||
WHERE channel_id = %(id)s
|
||||
'''
|
||||
curs.execute(stmt, dict(id=self.id))
|
||||
size, largest_video, video_count = curs.fetchone()
|
||||
|
|
@ -484,20 +446,26 @@ class Channel(ModelHelper, Base):
|
|||
self_id = self.id
|
||||
|
||||
# Refresh all files within this channel's directory first.
|
||||
await refresh_directory_files_recursively(self.directory, send_events=send_events)
|
||||
await refresh_files(self.directory, send_events=send_events)
|
||||
|
||||
# Apply any info_json (discover censored videos, etc.) second.
|
||||
from modules.videos.common import apply_info_json
|
||||
# Apply any info_json (update view counts) second.
|
||||
from modules.videos.common import update_view_counts
|
||||
if PYTEST:
|
||||
apply_info_json(self_id)
|
||||
update_view_counts(self_id)
|
||||
self.refreshed = True
|
||||
else:
|
||||
|
||||
# Perform info_json in background task. Channel will be marked as refreshed after this completes.
|
||||
async def _():
|
||||
apply_info_json(self_id)
|
||||
update_view_counts(self_id)
|
||||
with get_db_session(commit=True) as session:
|
||||
channel: Channel = session.query(Channel).filter(Channel.id == self_id).one()
|
||||
channel.refreshed = True
|
||||
|
||||
background_task(_())
|
||||
|
||||
@staticmethod
|
||||
@optional_session
|
||||
def get_by_id(id_: int, session: Session = None) -> Optional['Channel']:
|
||||
channel = session.query(Channel).filter_by(id=id_).one_or_none()
|
||||
return channel
|
||||
|
|
|
|||
|
|
@ -139,11 +139,12 @@ class VideoResponse:
|
|||
@dataclass
|
||||
class VideoSearchRequest:
|
||||
search_str: Optional[str] = None
|
||||
filters: List[str] = field(default_factory=list)
|
||||
tags: List[str] = field(default_factory=list)
|
||||
offset: Optional[int] = None
|
||||
limit: Optional[int] = VIDEO_QUERY_LIMIT
|
||||
order_by: Optional[str] = DEFAULT_VIDEO_ORDER
|
||||
channel_id: Optional[int] = None
|
||||
tag_names: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -158,15 +159,9 @@ class PaginationQuery:
|
|||
|
||||
|
||||
@dataclass
|
||||
class FavoriteRequest:
|
||||
class TagRequest:
|
||||
video_id: int
|
||||
favorite: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class FavoriteResponse:
|
||||
video_id: int
|
||||
favorite: datetime
|
||||
tag_name: str
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -177,7 +172,6 @@ class WROLModeRequest:
|
|||
@dataclass
|
||||
class VideoStatistics:
|
||||
videos: int
|
||||
favorites: int
|
||||
week: int
|
||||
month: int
|
||||
year: int
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import json
|
||||
import shutil
|
||||
from http import HTTPStatus
|
||||
from pathlib import Path
|
||||
|
||||
|
|
@ -7,101 +6,106 @@ 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.files.lib import refresh_files
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
from wrolpi.files.lib import refresh_files, split_path_stem_and_suffix
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refresh_videos_index(test_session, test_directory, video_factory):
|
||||
"""A video discovered during refresh has files associated with it. Only the video file is indexed."""
|
||||
"""The video modeler indexes video data into the Video's FileGroup."""
|
||||
video_factory(with_video_file=True, with_caption_file=True, with_poster_ext='jpg', with_info_json=True)
|
||||
test_session.commit()
|
||||
|
||||
test_session.query(File).delete()
|
||||
test_session.query(FileGroup).delete()
|
||||
test_session.commit()
|
||||
|
||||
for _ in range(1):
|
||||
# Refreshing twice does not change the results.
|
||||
await refresh_files()
|
||||
|
||||
assert test_session.query(File).count() == 4
|
||||
assert test_session.query(FileGroup).count() == 1
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert video.video_file.indexed is True, 'Video was not indexed'
|
||||
assert video.video_file.a_text, 'Video title was not indexed'
|
||||
assert video.video_file.d_text, 'Video captions were not indexed'
|
||||
|
||||
assert not video.poster_file.indexed
|
||||
assert not video.caption_file.indexed
|
||||
assert not video.info_json_file.indexed
|
||||
assert video.file_group.indexed is True, 'Video was not indexed'
|
||||
assert video.file_group.a_text and video.file_group.title, 'Video title was not indexed'
|
||||
assert video.file_group.d_text, 'Video captions were not indexed'
|
||||
|
||||
# Delete caption file, the video should be indexed again.
|
||||
video: Video = test_session.query(Video).one()
|
||||
video.caption_path.unlink()
|
||||
for path in video.caption_paths:
|
||||
path.unlink()
|
||||
|
||||
await refresh_files()
|
||||
assert video.video_file.indexed is True, 'Video was not indexed'
|
||||
assert video.video_file.a_text, 'Video title was not indexed'
|
||||
assert not video.video_file.d_text, 'Video captions were not removed'
|
||||
assert video.file_group.indexed is True, 'Video was not indexed'
|
||||
assert video.file_group.a_text and video.file_group.title, 'Video title was not indexed'
|
||||
assert not video.file_group.d_text, 'Video captions were not removed'
|
||||
|
||||
|
||||
def test_refresh_videos(test_client, test_session, test_directory, simple_channel, video_factory):
|
||||
def test_refresh_videos(test_client, test_session, test_directory, simple_channel, video_factory, video_file_factory,
|
||||
image_bytes_factory):
|
||||
subdir = test_directory / 'subdir'
|
||||
subdir.mkdir()
|
||||
|
||||
# video1 is in a subdirectory, move its files into the subdirectory.
|
||||
video1 = video_factory(channel_id=simple_channel.id, with_video_file=subdir / 'video1.mp4',
|
||||
with_info_json=True,
|
||||
with_poster_ext='jpg')
|
||||
with_info_json=True, with_poster_ext='jpg')
|
||||
test_session.commit()
|
||||
test_session.delete(video1.poster_file)
|
||||
video1.poster_path = None
|
||||
video1.file_group.size = video1.file_group.data = None
|
||||
video1.file_group.files = list()
|
||||
# video2 is in the test directory.
|
||||
video2 = video_factory(channel_id=simple_channel.id, with_video_file=True, with_info_json=True,
|
||||
with_poster_ext='jpg')
|
||||
video2.poster_path = video2.poster_file = video1.poster_path = None
|
||||
video2.file_group.data = None
|
||||
video2.file_group.files = []
|
||||
test_session.commit()
|
||||
|
||||
assert not video1.size, 'video1 should not have size during creation'
|
||||
assert not video1.file_group.size, 'video1 should not have size during creation'
|
||||
|
||||
# Create a video not in the DB.
|
||||
vid3 = test_directory / 'vid3.mp4'
|
||||
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny_720p_1mb.mp4', vid3)
|
||||
vid3 = video_file_factory(test_directory / 'vid3.mp4')
|
||||
|
||||
# Orphan poster should be ignored.
|
||||
orphan_poster = Path(test_directory / 'channel name_20000104_defghijklmn_title.jpg')
|
||||
orphan_poster.touch()
|
||||
orphan_poster.write_bytes(image_bytes_factory())
|
||||
|
||||
# Create a bogus video in the channel.
|
||||
video_file = File(path=test_directory / 'foo')
|
||||
video_file.idempotency = None # File was not added in the current refresh.
|
||||
bogus = Video(video_file=video_file, channel_id=simple_channel.id)
|
||||
test_session.add(bogus)
|
||||
test_session.commit()
|
||||
video_file = test_directory / 'foo.mp4'
|
||||
with get_db_curs(commit=True) as curs:
|
||||
full_stem, _ = split_path_stem_and_suffix(video_file, full=True)
|
||||
stmt = "INSERT INTO file_group (mimetype, full_stem, primary_path, indexed, files, model)" \
|
||||
" values ('video/mp4', %(full_stem)s, %(primary_path)s, true, %(files)s, 'video') RETURNING id"
|
||||
params = {'full_stem': full_stem, 'primary_path': str(video_file), 'files': list()}
|
||||
curs.execute(stmt, params)
|
||||
video4_id = curs.fetchall()[0][0]
|
||||
stmt = "INSERT INTO video (file_group_id) values (%(video_id)s)"
|
||||
curs.execute(stmt, {'video_id': str(video4_id)})
|
||||
|
||||
test_client.post('/api/files/refresh')
|
||||
|
||||
test_session.expire_all()
|
||||
|
||||
# Posters were found during refresh.
|
||||
assert video1.poster_path
|
||||
assert 'subdir' in str(video1.poster_path)
|
||||
assert video2.poster_path
|
||||
assert video1.file_group.my_poster_files()
|
||||
assert 'subdir' in str(video1.file_group.my_poster_files()[0])
|
||||
assert video2.file_group.my_poster_files()
|
||||
# Missing video3 was found
|
||||
video3: Video = test_session.query(Video).filter_by(id=4).one()
|
||||
assert video3.video_path == vid3
|
||||
assert len(set(test_session.query(Video.video_path))) == 3, 'Should have 3 distinct video files'
|
||||
assert len(set(test_session.query(FileGroup.primary_path).filter(FileGroup.model == 'video'))) == 3, \
|
||||
'Should have 3 distinct video files'
|
||||
# Bogus video was removed.
|
||||
assert not any('foo' in str(i.video_path) for i in test_session.query(Video).all())
|
||||
assert not any('foo.mp4' in str(i.video_path) for i in test_session.query(Video).all())
|
||||
# Orphan file was not deleted.
|
||||
assert orphan_poster.is_file(), 'Orphan poster was removed!'
|
||||
|
||||
assert video1.size, 'video1 size was not found'
|
||||
assert video1.file_group.size, 'video1 size was not found'
|
||||
|
||||
# Remove video1's poster, video1 should be updated.
|
||||
video1_video_path = str(video1.video_path)
|
||||
video1.poster_path.unlink()
|
||||
test_client.post('/api/files/refresh')
|
||||
video1 = test_session.query(Video).filter_by(video_path=video1_video_path).one()
|
||||
video1 = Video.find_by_path(video1_video_path, test_session)
|
||||
assert not video1.poster_path
|
||||
|
||||
|
||||
|
|
@ -133,9 +137,9 @@ def test_channels_with_videos(test_session, test_client, test_directory, channel
|
|||
assert test_session.query(Video).count() == 3, 'Did not find correct amount of video files.'
|
||||
assert {i[0] for i in test_session.query(Channel.name)} == {'channel1', 'channel2'}, 'Channels were changed.'
|
||||
|
||||
vid1: Video = test_session.query(Video).filter_by(video_path=vid1_path).one()
|
||||
vid2: Video = test_session.query(Video).filter_by(video_path=vid2_path).one()
|
||||
vid3: Video = test_session.query(Video).filter_by(video_path=vid3_path).one()
|
||||
vid1 = Video.find_by_path(vid1_path)
|
||||
vid2 = Video.find_by_path(vid2_path)
|
||||
vid3 = Video.find_by_path(vid3_path)
|
||||
|
||||
assert vid1.channel == channel1
|
||||
assert vid2.channel == channel2
|
||||
|
|
@ -156,7 +160,7 @@ def test_api_download_channel(test_session, test_client, simple_channel):
|
|||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
|
||||
def test_search_videos_file(test_client, test_session, test_directory, video_with_search_factory):
|
||||
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 = [
|
||||
|
|
@ -170,58 +174,56 @@ def test_search_videos_file(test_client, test_session, test_directory, video_wit
|
|||
video_with_search_factory(title=title, d_text=caption)
|
||||
test_session.commit()
|
||||
|
||||
def assert_search(search_str, expected, limit=20, total=None):
|
||||
d = json.dumps({'search_str': search_str, 'limit': limit})
|
||||
_, resp = test_client.post('/api/videos/search', content=d)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
response_ids = [i['video']['id'] for i in resp.json['files']]
|
||||
assert response_ids == expected
|
||||
assert resp.json['totals']['files'] == (total or len(expected))
|
||||
|
||||
# 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_search('b', [1, 2, 3, 4])
|
||||
assert_video_search(search_str='b', assert_ids=[1, 2, 3, 4])
|
||||
|
||||
# Only two captions have e
|
||||
assert_search('e', [4, 1])
|
||||
assert_video_search(search_str='e', assert_ids=[4, 1])
|
||||
|
||||
# Only 2 contains 2
|
||||
assert_video_search(search_str='2', assert_ids=[2, ])
|
||||
|
||||
# Only two captions have d
|
||||
assert_search('d', [1, 2])
|
||||
assert_video_search(search_str='d', assert_ids=[1, 2])
|
||||
|
||||
# 5 can be gotten by it's title
|
||||
assert_search('5', [5])
|
||||
assert_video_search(search_str='5', assert_ids=[5, ])
|
||||
|
||||
# only video 1 has e and d
|
||||
assert_search('e d', [1])
|
||||
assert_video_search(search_str='e d', assert_ids=[1, ])
|
||||
|
||||
# video 1 and 4 have b and e, but 1 has more
|
||||
assert_search('b e', [1, 4])
|
||||
assert_video_search(search_str='b e', assert_ids=[1, 4])
|
||||
|
||||
# Check totals are correct even with a limit
|
||||
assert_search('b', [1, 2], limit=2, total=4)
|
||||
assert_video_search(search_str='b', limit=2, assert_ids=[1, 2], assert_total=4)
|
||||
|
||||
|
||||
def test_search_videos(test_client, test_session, video_factory, assert_video_search, simple_channel):
|
||||
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_factory(upload_date='2022-09-16', with_video_file=True)
|
||||
vid2 = video_factory(upload_date='2022-09-17', with_video_file=True, channel_id=simple_channel.id)
|
||||
vid3 = video_factory(upload_date='2022-09-18', with_video_file=True)
|
||||
vid1.set_favorite(True)
|
||||
vid1 = video_factory(upload_date='2022-09-16', with_video_file=True, title='vid1')
|
||||
vid2 = video_factory(upload_date='2022-09-17', with_video_file=True, title='vid2', channel_id=simple_channel.id)
|
||||
vid3 = video_factory(upload_date='2022-09-18', with_video_file=True, title='vid3')
|
||||
tag1, tag2 = tag_factory(), tag_factory()
|
||||
vid1.add_tag(tag1)
|
||||
vid3.add_tag(tag2)
|
||||
test_session.commit()
|
||||
assert test_session.query(Video).count() == 3
|
||||
assert test_session.query(File).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='upload_date')
|
||||
assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id, vid1.id], order_by='-upload_date')
|
||||
assert_video_search(assert_total=3, assert_ids=[vid3.id, vid2.id], order_by='-upload_date', limit=2)
|
||||
assert_video_search(assert_total=3, assert_ids=[vid2.id, vid1.id], order_by='-upload_date', limit=2, offset=1)
|
||||
assert_video_search(assert_total=1, assert_ids=[vid2.id], order_by='-upload_date', channel_id=simple_channel.id)
|
||||
assert_video_search(assert_total=1, assert_ids=[vid1.id], filters=['favorite'])
|
||||
assert_video_search(assert_total=1, assert_ids=[vid1.id], filters=['favorite'], limit=1)
|
||||
assert_video_search(assert_total=1, assert_ids=[vid1.id], tag_names=[tag1.name])
|
||||
assert_video_search(assert_total=1, assert_ids=[vid1.id], tag_names=[tag1.name], limit=1)
|
||||
assert_video_search(assert_total=2, assert_ids=[vid3.id, vid1.id], tag_names=[tag1.name, tag2.name])
|
||||
|
||||
# No results, no total is returned from the DB.
|
||||
assert_video_search(assert_total=0, assert_ids=[], filters=['favorite'], offset=1)
|
||||
assert_video_search(assert_total=0, assert_ids=[], tag_names=[tag1.name], offset=1)
|
||||
|
||||
# Check all order_by.
|
||||
for order_by in video_lib.VIDEO_ORDERS:
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ from wrolpi.dates import now
|
|||
from wrolpi.downloader import Download, DownloadFrequency
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
from .. import common
|
||||
from ..common import convert_image, apply_info_json, get_video_duration, generate_video_poster, is_valid_poster
|
||||
from ..common import convert_image, update_view_counts, get_video_duration, generate_video_poster, is_valid_poster
|
||||
from ..lib import save_channels_config, get_channels_config, import_channels_config
|
||||
|
||||
|
||||
|
|
@ -101,22 +101,22 @@ def test_update_view_count(test_session, channel_factory, video_factory):
|
|||
check_view_counts({'vid1': None, 'vid2': None, 'vid3': None, 'vid4': None})
|
||||
|
||||
# Channel 1 is updated, the other channels are left alone.
|
||||
apply_info_json(channel1.id)
|
||||
update_view_counts(channel1.id)
|
||||
check_view_counts({'vid1': 10, 'vid2': None, 'vid3': None, 'vid4': None})
|
||||
|
||||
# Channel 2 is updated, the other channels are left alone. The 'bad_id' video is ignored.
|
||||
apply_info_json(channel2.id)
|
||||
update_view_counts(channel2.id)
|
||||
check_view_counts({'vid1': 10, 'vid2': 11, 'vid3': None, 'vid4': None})
|
||||
|
||||
# All videos are updated.
|
||||
apply_info_json(channel3.id)
|
||||
update_view_counts(channel3.id)
|
||||
check_view_counts({'vid1': 10, 'vid2': 11, 'vid3': 13, 'vid4': 14})
|
||||
|
||||
# An outdated view count will be overwritten.
|
||||
vid = test_session.query(Video).filter_by(id=1).one()
|
||||
vid.view_count = 8
|
||||
check_view_counts({'vid1': 8, 'vid2': 11, 'vid3': 13, 'vid4': 14})
|
||||
apply_info_json(channel1.id)
|
||||
update_view_counts(channel1.id)
|
||||
check_view_counts({'vid1': 10, 'vid2': 11, 'vid3': 13, 'vid4': 14})
|
||||
|
||||
|
||||
|
|
@ -130,128 +130,6 @@ def test_generate_video_poster(video_file):
|
|||
assert poster_path.stat().st_size > 0
|
||||
|
||||
|
||||
def test_update_censored_videos(test_session, video_factory, simple_channel):
|
||||
vid1 = video_factory(channel_id=simple_channel.id)
|
||||
vid2 = video_factory(channel_id=simple_channel.id)
|
||||
vid3 = video_factory(channel_id=simple_channel.id)
|
||||
vid4 = video_factory() # should not be censored because it has no channel.
|
||||
test_session.commit()
|
||||
|
||||
def check_censored(expected):
|
||||
for video_id, censored in expected:
|
||||
video = test_session.query(Video).filter_by(id=video_id).one()
|
||||
assert video.censored == censored
|
||||
|
||||
# Videos are not censored by default.
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, False), (vid2.id, False), (vid3.id, False), (vid4.id, False)])
|
||||
|
||||
# All videos are in the info_json.
|
||||
simple_channel.info_json = {
|
||||
'entries': [
|
||||
dict(id=vid1.source_id, view_count=0),
|
||||
dict(id=vid2.source_id, view_count=0),
|
||||
dict(id=vid3.source_id, view_count=0),
|
||||
]
|
||||
}
|
||||
test_session.commit()
|
||||
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, False), (vid2.id, False), (vid3.id, False), (vid4.id, False)])
|
||||
|
||||
simple_channel.info_json = {
|
||||
'entries': [
|
||||
dict(id=vid1.source_id, view_count=0), # vid2 is missing
|
||||
dict(id=vid3.source_id, view_count=0),
|
||||
]
|
||||
}
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, False), (vid2.id, True), (vid3.id, False), (vid4.id, False)])
|
||||
|
||||
simple_channel.info_json = {
|
||||
'entries': [
|
||||
dict(id=vid1.source_id, view_count=0), # vid2 is back, vid3 is missing.
|
||||
dict(id=vid2.source_id, view_count=0),
|
||||
]
|
||||
}
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, False), (vid2.id, False), (vid3.id, True), (vid4.id, False)])
|
||||
|
||||
simple_channel.info_json = {
|
||||
'entries': [] # all videos gone
|
||||
}
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, True), (vid2.id, True), (vid3.id, True), (vid4.id, False)])
|
||||
|
||||
# Channels without info json preserve their last censored.
|
||||
simple_channel.info_json = None
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
check_censored([(vid1.id, True), (vid2.id, True), (vid3.id, True), (vid4.id, False)])
|
||||
|
||||
|
||||
def test_import_favorites(test_session, test_directory, simple_channel, video_factory, test_channels_config):
|
||||
"""
|
||||
A favorited Video will be preserved through everything (channel deletion, DB wipe) and can be imported and will be
|
||||
favorited again.
|
||||
|
||||
A Video's favorited status can only be cleared by calling `Video.delete`.
|
||||
"""
|
||||
video_factory(channel_id=simple_channel.id) # never favorited
|
||||
vid2 = video_factory(channel_id=None) # has no channel
|
||||
vid3 = video_factory(channel_id=simple_channel.id)
|
||||
favorite = vid3.favorite = vid2.favorite = datetime(2000, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
|
||||
test_session.commit()
|
||||
vid2_video_path = vid2.video_path
|
||||
|
||||
favorites = {
|
||||
str(simple_channel.directory.relative_to(test_directory)): {vid3.video_path.name: {'favorite': favorite}},
|
||||
'NO CHANNEL': {vid2.video_path.name: {'favorite': favorite}},
|
||||
}
|
||||
|
||||
# Save config, verify that favorite is set.
|
||||
save_channels_config()
|
||||
config = get_channels_config()
|
||||
assert config.favorites == favorites
|
||||
|
||||
def import_and_verify(favorited_ids: List[int]):
|
||||
with mock.patch('modules.videos.lib.get_channel_source_id', lambda i: 'foo'):
|
||||
import_channels_config()
|
||||
for video in test_session.query(Video).all():
|
||||
if video.id in favorited_ids:
|
||||
assert video.favorite
|
||||
else:
|
||||
assert not video.favorite
|
||||
|
||||
# Clear the favorite (as if the DB was wiped), verify that the favorite is imported and set.
|
||||
vid2.favorite = None
|
||||
import_and_verify([vid2.id, vid3.id])
|
||||
|
||||
# Removing the video does not delete the favorite. If the DB is wiped, we do not want to lose our favorites!
|
||||
test_session.query(Video).filter_by(id=vid2.id).delete()
|
||||
test_session.commit()
|
||||
save_channels_config()
|
||||
config = get_channels_config()
|
||||
assert config.favorites == favorites
|
||||
import_and_verify([vid3.id])
|
||||
|
||||
# Add vid2 again, it should be favorited on import.
|
||||
vid2 = Video(video_path=vid2_video_path)
|
||||
test_session.add(vid2)
|
||||
test_session.commit()
|
||||
import_and_verify([vid3.id, vid2.id])
|
||||
|
||||
# Deleting the Video in the model really removes the favorite status.
|
||||
vid3.delete()
|
||||
config = get_channels_config()
|
||||
assert config.favorites == {'NO CHANNEL': {vid2.video_path.name: {'favorite': favorite}}}
|
||||
import_and_verify([vid2.id])
|
||||
|
||||
|
||||
def test_import_channel_downloads(test_session, channel_factory, test_channels_config):
|
||||
"""Importing the Channels' config should create any missing download records"""
|
||||
channel1 = channel_factory(source_id='foo')
|
||||
|
|
@ -305,67 +183,6 @@ def test_import_channel_downloads(test_session, channel_factory, test_channels_c
|
|||
assert next_download == str(download.next_download)
|
||||
|
||||
|
||||
def test_import_channels_config_outdated(test_session, test_directory, channel_factory, test_channels_config,
|
||||
video_factory):
|
||||
"""The Channels' config used to use a "link" to differentiate channels, test that old configs can be imported."""
|
||||
channel1 = channel_factory(name='Channel1', download_frequency=DownloadFrequency.weekly)
|
||||
channel2 = channel_factory(name='Channel2', download_frequency=DownloadFrequency.weekly)
|
||||
test_session.commit()
|
||||
|
||||
vid1 = video_factory(title='vid1', channel_id=channel1.id)
|
||||
vid2 = video_factory(title='vid2', channel_id=channel2.id)
|
||||
vid3 = video_factory(title='vid3')
|
||||
vid4 = video_factory(title='vid4')
|
||||
test_session.commit()
|
||||
|
||||
channel1_name, channel_1_directory = channel1.name, channel1.directory
|
||||
channel2_name, channel_2_directory = channel2.name, channel2.directory
|
||||
|
||||
assert channel1.directory.exists() and channel1.directory.is_absolute()
|
||||
assert channel2.directory.exists() and channel2.directory.is_absolute()
|
||||
|
||||
# Channel's used to have a relative directory in the DB.
|
||||
test_session.execute('UPDATE channel SET directory=:directory WHERE id=2',
|
||||
dict(directory=str(channel_2_directory.relative_to(test_directory))),
|
||||
)
|
||||
|
||||
save_channels_config()
|
||||
|
||||
# The config has a list of Channels, use the old method of a "dict" with the sanitized name as the key.
|
||||
channels_config = get_channels_config()
|
||||
channels_config.channels = {sanitize_link(i['name']): i for i in channels_config.channels}
|
||||
# Change frequency to verify that the channels are updated.
|
||||
for link, channel in channels_config.channels.items():
|
||||
channel['download_frequency'] = DownloadFrequency.biweekly
|
||||
# Change the favorites to the old "link" method as well.
|
||||
channels_config.favorites = {
|
||||
sanitize_link(channel1.name): {str(vid1.video_path): {'favorite': now()}},
|
||||
sanitize_link(channel2.name): {str(vid2.video_path): {'favorite': now()}},
|
||||
'NO CHANNEL': {str(vid3.video_path): {'favorite': now()}},
|
||||
}
|
||||
channels_config.save()
|
||||
|
||||
assert not vid1.favorite and not vid2.favorite and not vid3.favorite and not vid3.favorite
|
||||
|
||||
assert test_session.query(Channel).count() == 2
|
||||
|
||||
with mock.patch('modules.videos.lib.get_channel_source_id') as mock_get_channel_source_id:
|
||||
mock_get_channel_source_id.return_value = 'some source id'
|
||||
import_channels_config()
|
||||
|
||||
# No new channels were created. Existing channels were updated.
|
||||
assert test_session.query(Channel).count() == 2
|
||||
channel1, channel2 = test_session.query(Channel).order_by(Channel.id)
|
||||
assert channel1.name == channel1_name and str(channel1.directory) == str(channel_1_directory)
|
||||
# Channel2's directory is now absolute.
|
||||
assert channel2.name == channel2_name and str(channel2.directory) == str(channel_2_directory)
|
||||
assert channel1.download_frequency == DownloadFrequency.biweekly
|
||||
assert channel2.download_frequency == DownloadFrequency.biweekly
|
||||
# Videos were favorited by their channel "link".
|
||||
assert vid1.favorite and vid2.favorite and vid3.favorite
|
||||
assert not vid4.favorite
|
||||
|
||||
|
||||
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
|
||||
|
|
|
|||
|
|
@ -13,27 +13,15 @@ from modules.videos.models import Channel, Video
|
|||
from wrolpi.db import get_db_context
|
||||
from wrolpi.downloader import Download, DownloadResult
|
||||
from wrolpi.errors import InvalidDownload
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.test.common import skip_circleci
|
||||
from wrolpi.test.test_downloader import HTTPDownloader
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_find_all_missing_videos(test_session, channel_factory, video_factory):
|
||||
async def test_find_all_missing_videos(test_session, channel_factory, video_factory, image_file):
|
||||
channel1 = channel_factory(url='some url')
|
||||
channel1.info_json = {'entries': [{'id': 'foo', 'view_count': 0}]}
|
||||
test_session.commit()
|
||||
|
||||
# Two videos are already downloaded.
|
||||
video_factory()
|
||||
video_factory()
|
||||
|
||||
# No missing videos
|
||||
assert [] == [i async for i in find_all_missing_videos(channel1.id)]
|
||||
|
||||
# Create a video that has no video file.
|
||||
video = Video(title='needs to be downloaded', channel_id=channel1.id, source_id='foo')
|
||||
test_session.add(video)
|
||||
channel1.info_json = {'entries': [{'id': 'foo', 'view_count': 0, 'webpage_url': 'https://example.com'}]}
|
||||
test_session.commit()
|
||||
|
||||
missing = [i async for i in find_all_missing_videos(channel1.id)]
|
||||
|
|
@ -41,11 +29,25 @@ async def test_find_all_missing_videos(test_session, channel_factory, video_fact
|
|||
|
||||
# The video returned is the one we faked.
|
||||
id_, source_id, entry = missing[0]
|
||||
# Two videos were created for this test already.
|
||||
assert id_ == 3
|
||||
# No Video.id because the video is missing.
|
||||
assert id_ is None
|
||||
# The fake entry we added is regurgitated back.
|
||||
assert entry == channel1.info_json['entries'][0]
|
||||
|
||||
# Create a video without a poster, attempt to download it.
|
||||
video = video_factory(channel_id=channel1.id, with_video_file=True)
|
||||
channel1.info_json = {'entries': [
|
||||
{'id': 'foo', 'view_count': 0, 'webpage_url': 'https://example.com'},
|
||||
{'id': video.source_id, 'view_count': 0, 'webpage_url': 'https://example.com/new'},
|
||||
]}
|
||||
test_session.commit()
|
||||
|
||||
missing = [i async for i in find_all_missing_videos(channel1.id)]
|
||||
assert len(missing) == 2
|
||||
|
||||
_, new = missing
|
||||
assert new == (video.id, video.source_id, channel1.info_json['entries'][1])
|
||||
|
||||
|
||||
example_video_json = {
|
||||
'age_limit': 0,
|
||||
|
|
@ -174,11 +176,12 @@ async def test_download_no_channel(test_session, video_download_manager, video_f
|
|||
assert str(video.video_path) == f'{channel_dir}/video.mp4'
|
||||
|
||||
|
||||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_channel(test_session, simple_channel, video_download_manager, video_file,
|
||||
mock_video_extract_info, mock_video_prepare_filename,
|
||||
mock_video_process_runner):
|
||||
"""Downloading (updating the catalog of) a Channel creates download records for all of it's missing videos.
|
||||
"""Downloading (updating the catalog of) a Channel updates it's info_json.
|
||||
|
||||
If a Channel has `match_regex` only those videos with matching titles will be downloaded."""
|
||||
url = 'https://www.youtube.com/c/LearningSelfReliance/videos'
|
||||
|
|
@ -407,10 +410,8 @@ async def test_video_download(test_session, test_directory, simple_channel, vide
|
|||
assert test_session.query(Channel).one()
|
||||
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert video.video_path.is_absolute(), 'Video path is not absolute'
|
||||
assert video.poster_path == poster_path, 'Video poster was not discovered'
|
||||
assert video.validated, 'Video was not validated'
|
||||
assert video.video_file and video.video_file.indexed, 'Video was not indexed'
|
||||
assert video.video_path.is_absolute() and video.video_path == video_path, 'Video path is not absolute'
|
||||
assert video.video_path.is_absolute() and video.poster_path == poster_path, 'Video poster was not discovered'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -433,11 +434,10 @@ async def test_download_result(test_session, test_directory, video_download_mana
|
|||
assert download.url == 'https://example.com'
|
||||
assert download.location == '/videos/channel/1/video/1'
|
||||
|
||||
# Video files are associated.
|
||||
# Video has its files.
|
||||
video = test_session.query(Video).one()
|
||||
assert not video.video_file.associated, 'Video file should not be associated.'
|
||||
assert video.video_path.is_file(), 'Video file was not found.'
|
||||
assert video.poster_path.is_file(), 'Poster file was not found.'
|
||||
assert video.poster_file.associated, 'Poster file was not associated.'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -527,15 +527,16 @@ example_playlist_json = {
|
|||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager):
|
||||
async def test_download_playlist(test_session, test_directory, mock_video_extract_info, video_download_manager,
|
||||
video_file):
|
||||
"""All videos in a playlist can be downloaded for it's Channel."""
|
||||
download = Download(url='playlist url')
|
||||
test_session.add(download)
|
||||
channel = get_or_create_channel(example_playlist_json['channel_id'], download.url, example_channel_json['uploader'])
|
||||
video_file = File(path=test_directory / 'video file.mp4')
|
||||
test_session.add(video_file)
|
||||
test_session.add(Video(url='https://www.youtube.com/watch?v=video_1_url',
|
||||
source_id='video 1 id', channel_id=channel.id, video_file=video_file))
|
||||
video = Video.from_paths(test_session, video_file)
|
||||
video.channel_id = channel.id
|
||||
video.source_id = 'video 1 id'
|
||||
video.url = 'https://www.youtube.com/watch?v=video_1_url'
|
||||
test_session.commit()
|
||||
|
||||
mock_video_extract_info.return_value = example_playlist_json # Playlist info is fetched first.
|
||||
|
|
|
|||
|
|
@ -1,55 +1,19 @@
|
|||
import datetime
|
||||
import pathlib
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
import sqlalchemy
|
||||
|
||||
from modules.videos import lib
|
||||
from modules.videos.common import apply_info_json
|
||||
from modules.videos.lib import parse_video_file_name, validate_video, get_statistics
|
||||
from modules.videos.models import Video
|
||||
from modules.videos.video.lib import search_videos
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.lib import refresh_files
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.files.models import FileGroup
|
||||
from wrolpi.tags import Tag
|
||||
from wrolpi.vars import PROJECT_DIR
|
||||
|
||||
|
||||
def test_search_censored_videos(test_session, simple_channel, video_factory):
|
||||
for i in map(str, range(50)):
|
||||
video_factory(channel_id=simple_channel.id, source_id=i)
|
||||
vid = video_factory(source_id=51) # this should never be modified because it has no channel
|
||||
test_session.add(vid)
|
||||
test_session.commit()
|
||||
|
||||
def set_entries(entries):
|
||||
simple_channel.info_json = {
|
||||
'entries': [{'id': j, 'view_count': 0} for j in entries]} if entries else sqlalchemy.null()
|
||||
test_session.commit()
|
||||
apply_info_json(simple_channel.id)
|
||||
test_session.commit()
|
||||
|
||||
# All source_ids are in the entries.
|
||||
set_entries(map(str, range(50)))
|
||||
videos, total = search_videos(filters=['censored'], order_by='id', limit=20)
|
||||
assert [i['video']['source_id'] for i in videos] == []
|
||||
assert total == 0
|
||||
|
||||
# First 5 are censored.
|
||||
set_entries(map(str, range(5, 50)))
|
||||
videos, total = search_videos(filters=['censored'], order_by='id', limit=20)
|
||||
assert [i['video']['source_id'] for i in videos] == [str(i) for i in range(5)]
|
||||
assert all(i['video']['censored'] for i in videos)
|
||||
assert total == 5
|
||||
|
||||
# First 25 are censored.
|
||||
set_entries(map(str, range(25, 50)))
|
||||
videos, total = search_videos(filters=['censored'], order_by='id', limit=20)
|
||||
assert [i['video']['source_id'] for i in videos] == [str(i) for i in range(20)]
|
||||
assert all(i['video']['censored'] for i in videos)
|
||||
assert total == 25
|
||||
|
||||
|
||||
@pytest.mark.parametrize('file_name,expected', [
|
||||
('channel_20000101_12345678910_ some title.mp4', ('channel', '20000101', '12345678910', 'some title')),
|
||||
('channel name_NA_12345678910_ some title.mp4', ('channel name', None, '12345678910', 'some title')),
|
||||
|
|
@ -75,57 +39,6 @@ def test_parse_video_file_name(file_name, expected):
|
|||
assert parse_video_file_name(video_path) == expected, f'{file_name} != {expected}'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_associated_video_files(test_session, test_directory, video_file, image_file, vtt_file1):
|
||||
"""A Video file has files related to it. They should be attached to the Video record."""
|
||||
caption_file = video_file.with_suffix('.en.vtt')
|
||||
vtt_file1.rename(caption_file)
|
||||
poster_file = video_file.with_suffix('.jpeg')
|
||||
image_file.rename(poster_file)
|
||||
|
||||
await files_lib.refresh_files()
|
||||
test_session.commit()
|
||||
|
||||
# All files were found.
|
||||
file_paths = {i.path for i in test_session.query(File)}
|
||||
assert len(file_paths) == 3
|
||||
|
||||
video: Video = test_session.query(Video).one()
|
||||
video_id = video.id
|
||||
assert video.video_file == video_file
|
||||
assert video.poster_file == poster_file
|
||||
assert video.caption_file == caption_file
|
||||
assert video.video_file.modification_datetime
|
||||
assert video.video_file.size
|
||||
assert video.video_file.indexed
|
||||
|
||||
await files_lib.refresh_files()
|
||||
test_session.commit()
|
||||
|
||||
# No new files were added.
|
||||
assert {i.path for i in test_session.query(File)} == file_paths
|
||||
# Same video exists.
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert video.id == video_id, 'Video id changed. Was the video recreated?'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unassociated_video(test_session, test_directory, video_file):
|
||||
"""A Video file without associated files is still a Video."""
|
||||
# Move the video file into a new subdirectory. The video file should still be found.
|
||||
sub_dir = test_directory / 'subdir'
|
||||
sub_dir.mkdir()
|
||||
new_video_file_path = sub_dir / video_file.name
|
||||
video_file.rename(new_video_file_path)
|
||||
video_file = new_video_file_path
|
||||
|
||||
await files_lib.refresh_files()
|
||||
test_session.commit()
|
||||
|
||||
video: Video = test_session.query(Video).one()
|
||||
assert video.video_file == video_file
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_factory(test_session, video_factory, channel_factory):
|
||||
"""
|
||||
|
|
@ -142,35 +55,42 @@ async def test_video_factory(test_session, video_factory, channel_factory):
|
|||
)
|
||||
test_session.commit()
|
||||
|
||||
assert video.video_path and video.video_file and video.video_path.is_file()
|
||||
assert video.caption_path and video.caption_file and video.caption_path.is_file()
|
||||
assert video.poster_path and video.poster_file and video.poster_path.is_file()
|
||||
assert video.info_json_path and video.info_json_file and video.info_json_path.is_file()
|
||||
assert video.video_path and video.video_path.is_file()
|
||||
assert video.caption_paths and all(i.is_file() for i in video.caption_paths)
|
||||
assert video.poster_path and video.poster_path.is_file()
|
||||
assert video.info_json_path and video.info_json_path.is_file()
|
||||
|
||||
assert video.video_file.a_text # title
|
||||
assert video.video_file.b_text is None
|
||||
assert video.video_file.c_text and 'hello' in video.video_file.c_text # description
|
||||
assert video.video_file.d_text # captions
|
||||
assert video.file_group.a_text # title
|
||||
assert video.file_group.b_text is None
|
||||
assert video.file_group.c_text
|
||||
assert video.file_group.d_text # captions
|
||||
assert video.source_id == 'some id'
|
||||
|
||||
|
||||
def test_validate_video(test_session, test_directory, video_factory):
|
||||
def test_validate_video(test_session, test_directory, video_factory, image_bytes_factory, video_file):
|
||||
"""A video poster will be generated only if the channel permits."""
|
||||
vid1 = video_factory(with_video_file=True)
|
||||
video_file = video_file.rename(test_directory / 'Channel Name_20000101_1234567890_The Title.mp4')
|
||||
vid1 = video_factory(with_video_file=video_file)
|
||||
# Clear source_id so source_id in the file will be extracted.
|
||||
vid1.source_id = None
|
||||
assert not vid1.poster_path
|
||||
|
||||
validate_video(vid1, True, test_session)
|
||||
validate_video(vid1, True)
|
||||
assert vid1.video_path == video_file
|
||||
assert vid1.poster_path, 'Poster was not created'
|
||||
assert vid1.poster_path.is_file(), 'Poster path does not exist'
|
||||
assert vid1.video_path.stem == vid1.poster_path.stem
|
||||
assert vid1.poster_path.suffix == '.jpg'
|
||||
assert vid1.upload_date == datetime.datetime(2000, 1, 1, 0, 1, tzinfo=datetime.timezone.utc)
|
||||
assert vid1.source_id == '1234567890'
|
||||
assert vid1.file_group.title == 'The Title'
|
||||
|
||||
# A PNG is replaced.
|
||||
vid2 = video_factory(with_video_file=True, with_poster_ext='.png')
|
||||
vid2.poster_path.with_suffix('.jpg').touch() # New poster exists, replace it.
|
||||
vid2.poster_path.with_suffix('.jpg').write_bytes(image_bytes_factory()) # New poster exists, replace it.
|
||||
assert vid2.poster_path and vid2.poster_path.is_file() and vid2.poster_path.suffix == '.png', \
|
||||
'Poster was not initialized'
|
||||
validate_video(vid2, True, test_session)
|
||||
validate_video(vid2, True)
|
||||
assert vid2.poster_path.is_file(), 'New poster was not generated'
|
||||
assert vid2.poster_path.suffix == '.jpg'
|
||||
|
||||
|
|
@ -197,34 +117,62 @@ async def test_get_statistics(test_session, video_factory, channel_factory):
|
|||
@pytest.mark.asyncio
|
||||
async def test_orphaned_files(test_session, make_files_structure, test_directory, video_factory):
|
||||
# A Video without associated files is not orphaned.
|
||||
vid1 = video_factory(with_video_file=True)
|
||||
vid1 = video_factory(title='vid1', with_video_file=True)
|
||||
# The video files will be removed...
|
||||
vid2 = video_factory(with_video_file=True, with_caption_file=True, with_poster_ext='jpeg', with_info_json=True)
|
||||
vid3 = video_factory(with_video_file=True, with_poster_ext='jpg')
|
||||
vid2 = video_factory(title='vid2', with_video_file=True, with_caption_file=True, with_poster_ext='jpeg',
|
||||
with_info_json=True)
|
||||
vid3 = video_factory(title='vid3', with_video_file=True, with_poster_ext='jpg')
|
||||
# This will be ignored because it is not in the "videos" subdirectory.
|
||||
shutil.copy(PROJECT_DIR / 'test/example1.en.vtt', test_directory / 'video4.en.vtt')
|
||||
shutil.copy(PROJECT_DIR / 'test/example1.en.vtt', test_directory / 'vid4.en.vtt')
|
||||
test_session.commit()
|
||||
|
||||
# Remove vid2 video. Caption, poster, info_json are now orphaned.
|
||||
vid2.video_path.unlink()
|
||||
vid2_caption_path, vid2_poster_path, vid2_info_json_path = vid2.caption_path, vid2.poster_path, vid2.info_json_path
|
||||
vid2_caption_paths, vid2_poster_path, vid2_info_json_path = vid2.caption_paths, vid2.poster_path, vid2.info_json_path
|
||||
# Remove vid3 video. Poster is now orphaned.
|
||||
vid3.video_path.unlink()
|
||||
vid3_poster_path = vid3.poster_path
|
||||
await refresh_files()
|
||||
await files_lib.refresh_files()
|
||||
test_session.commit()
|
||||
|
||||
# 6 files when two video files are deleted.
|
||||
# (vid1, vid2[caption,poster,json], vid3 poster, vid4)
|
||||
assert test_session.query(File).count() == 6
|
||||
assert test_session.query(FileGroup).count() == 4
|
||||
assert test_session.query(Video).count() == 1
|
||||
|
||||
videos_directory = test_directory / 'videos'
|
||||
results = lib.find_orphaned_video_files(videos_directory)
|
||||
|
||||
assert sorted(list(results)) == sorted([
|
||||
vid2_caption_path,
|
||||
vid2_caption_paths[0],
|
||||
vid2_info_json_path,
|
||||
vid2_poster_path,
|
||||
vid3_poster_path,
|
||||
])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_import_channels_config_favorites_tags(test_session, test_directory, test_channels_config, video_factory,
|
||||
simple_channel):
|
||||
"""Video favorites have been moved to Tags. Any Favorited video should be tagged with Favorite tag."""
|
||||
test_session.add(Tag(name='Favorite'))
|
||||
video1 = video_factory(channel_id=simple_channel.id)
|
||||
video2 = video_factory(channel_id=simple_channel.id)
|
||||
test_session.commit()
|
||||
|
||||
# Favorite video1 in config.
|
||||
channels_config = lib.get_channels_config()
|
||||
channels_config.favorites = {
|
||||
str(simple_channel.directory.relative_to(test_directory)): {
|
||||
str(video1.video_path.relative_to(simple_channel.directory)): now().isoformat(),
|
||||
}
|
||||
}
|
||||
|
||||
# The import function will tag the Video with Favorite.
|
||||
lib.import_channels_config()
|
||||
|
||||
# video1 has Favorite tag. It is also in the config.
|
||||
assert video1.file_group.tag_files and video1.file_group.tag_files[0].tag.name == 'Favorite'
|
||||
assert str(video1.file_group.primary_path.relative_to(test_directory)) in test_channels_config.read_text()
|
||||
# video2 was not tagged.
|
||||
assert not video2.file_group.tag_files
|
||||
|
|
|
|||
|
|
@ -1,45 +1,73 @@
|
|||
import pytest
|
||||
|
||||
from modules.videos.models import Video
|
||||
from wrolpi.dates import now
|
||||
from wrolpi.files.models import File
|
||||
|
||||
|
||||
def test_timezone(test_session):
|
||||
"""
|
||||
A Video's dates should have a TimeZone.
|
||||
"""
|
||||
video = Video(upload_date=now())
|
||||
test_session.add(video)
|
||||
test_session.commit()
|
||||
assert video.upload_date.tzinfo
|
||||
from wrolpi.files import lib as files_lib
|
||||
from wrolpi.files.models import FileGroup
|
||||
|
||||
|
||||
def test_delete_video_no_channel(test_session, simple_video):
|
||||
"""
|
||||
A Video can be deleted even if it does not have a channel.
|
||||
"""
|
||||
"""A Video can be deleted even if it does not have a channel."""
|
||||
assert simple_video.channel
|
||||
video_id = simple_video.id
|
||||
simple_video.channel_id = None
|
||||
test_session.commit()
|
||||
|
||||
simple_video: Video = test_session.query(Video).filter_by(id=video_id).one()
|
||||
paths = list(simple_video.file_group.my_paths())
|
||||
|
||||
assert not simple_video.channel
|
||||
simple_video.delete()
|
||||
|
||||
# All files were deleted.
|
||||
for path in paths:
|
||||
assert not path.exists()
|
||||
|
||||
def test_delete_video(test_session, simple_video, image_file):
|
||||
"""When a Video record is deleted, all referenced file records should be deleted."""
|
||||
simple_video.poster_file = File(path=image_file)
|
||||
test_session.add(simple_video.poster_file)
|
||||
test_session.commit()
|
||||
|
||||
assert simple_video.video_path.is_file(), 'Video file was not created.'
|
||||
assert simple_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(File).count() == 2, 'Video file and poster file were not created.'
|
||||
assert test_session.query(FileGroup).count() == 0
|
||||
assert test_session.query(Video).count() == 0
|
||||
|
||||
simple_video.delete()
|
||||
|
||||
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(File).count() == 0, 'Video files were not deleted.'
|
||||
assert test_session.query(FileGroup).count() == 0, 'Video files were not deleted.'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_video_channel_refresh(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()
|
||||
video1_path = channel.directory / 'video1.mp4'
|
||||
video_factory(channel_id=channel.id, with_video_file=video1_path, with_poster_ext='jpg')
|
||||
# Create another video outside the channel's directory. It should not have a channel.
|
||||
video2_path = test_directory / 'video2.mp4'
|
||||
video_factory(with_video_file=video2_path)
|
||||
# Delete all FileGroups so the channel will be associated again.
|
||||
test_session.query(FileGroup).delete()
|
||||
test_session.commit()
|
||||
|
||||
await files_lib.refresh_files()
|
||||
|
||||
assert test_session.query(FileGroup).count() == 2
|
||||
assert test_session.query(Video).count() == 2
|
||||
|
||||
# The video is associated with `simple_channel` because its file is in the Channel's directory.
|
||||
video1: Video = Video.find_by_path(video1_path, test_session)
|
||||
video2: Video = Video.find_by_path(video2_path, test_session)
|
||||
assert video1.channel == channel
|
||||
assert not video2.channel
|
||||
assert video1.__json__()['video']['channel']
|
||||
video_channel = video1.__json__()['video']['channel']
|
||||
assert video_channel['id'] == channel.id
|
||||
assert video_channel['name'] == channel.name
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ logger = logger.getChild(__name__)
|
|||
@openapi.response(HTTPStatus.NOT_FOUND, JSONErrorResponse)
|
||||
def video_get(_: Request, video_id: int):
|
||||
video, previous_video, next_video = lib.get_video_for_app(video_id)
|
||||
return json_response({'file': video, 'prev': previous_video, 'next': next_video})
|
||||
return json_response({'file_group': video, 'prev': previous_video, 'next': next_video})
|
||||
|
||||
|
||||
@video_bp.post('/search')
|
||||
|
|
@ -38,16 +38,16 @@ async def search(_: Request, body: schema.VideoSearchRequest):
|
|||
if body.order_by not in lib.VIDEO_ORDERS:
|
||||
raise InvalidOrderBy('Invalid order by')
|
||||
|
||||
files, videos_total = lib.search_videos(
|
||||
file_groups, videos_total = lib.search_videos(
|
||||
body.search_str,
|
||||
body.offset,
|
||||
body.limit,
|
||||
body.channel_id,
|
||||
body.order_by,
|
||||
body.filters,
|
||||
body.tag_names,
|
||||
)
|
||||
|
||||
ret = {'files': list(files), 'totals': {'files': videos_total}}
|
||||
ret = {'file_groups': list(file_groups), 'totals': {'file_groups': videos_total}}
|
||||
return json_response(ret)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
from datetime import datetime
|
||||
from typing import Tuple, Optional, List
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
|
||||
from modules.videos.models import Video
|
||||
from wrolpi.common import run_after, logger
|
||||
from wrolpi.db import get_db_session, optional_session
|
||||
from wrolpi.errors import UnknownVideo
|
||||
from wrolpi.files.lib import handle_search_results
|
||||
from wrolpi.files.lib import handle_file_group_search_results, tag_names_to_clauses
|
||||
from ..lib import save_channels_config
|
||||
from ..models import Video
|
||||
|
||||
logger.getChild(__name__)
|
||||
|
||||
|
|
@ -31,47 +30,44 @@ def get_video_for_app(video_id: int) -> Tuple[dict, Optional[dict], Optional[dic
|
|||
video.set_viewed()
|
||||
previous_video, next_video = video.get_surrounding_videos()
|
||||
|
||||
caption = video.video_file.d_text
|
||||
video = video.video_file.__json__()
|
||||
video['video']['caption'] = caption
|
||||
previous_video = previous_video.video_file.__json__() if previous_video and previous_video.video_file else None
|
||||
next_video = next_video.video_file.__json__() if next_video and next_video.video_file else None
|
||||
video = video.__json__()
|
||||
previous_video = previous_video.__json__() if previous_video and previous_video.file_group else None
|
||||
next_video = next_video.__json__() if next_video and next_video.file_group else None
|
||||
|
||||
return video, previous_video, next_video
|
||||
|
||||
|
||||
VIDEO_ORDERS = {
|
||||
'upload_date': 'v.upload_date ASC, LOWER(v.video_path) ASC',
|
||||
'-upload_date': 'v.upload_date DESC NULLS LAST, LOWER(v.video_path) DESC',
|
||||
'rank': '2 DESC, LOWER(v.video_path) DESC',
|
||||
'-rank': '2 ASC, LOWER(v.video_path) ASC',
|
||||
'id': 'v.id ASC',
|
||||
'-id': 'v.id DESC',
|
||||
'size': 'f.size ASC, LOWER(v.video_path) ASC',
|
||||
'-size': 'f.size DESC, LOWER(v.video_path) DESC',
|
||||
'duration': 'duration ASC, LOWER(v.video_path) ASC',
|
||||
'-duration': 'duration DESC, LOWER(v.video_path) DESC',
|
||||
'favorite': 'favorite ASC, LOWER(v.video_path) ASC',
|
||||
'-favorite': 'favorite DESC, LOWER(v.video_path) DESC',
|
||||
'upload_date': 'v.upload_date ASC, LOWER(fg.primary_path) ASC',
|
||||
'-upload_date': 'v.upload_date DESC NULLS LAST, LOWER(fg.primary_path) DESC',
|
||||
'rank': '2 DESC, LOWER(fg.primary_path) DESC',
|
||||
'-rank': '2 ASC, LOWER(fg.primary_path) ASC',
|
||||
'id': 'fg.id ASC',
|
||||
'-id': 'fg.id DESC',
|
||||
'size': 'fg.size ASC, LOWER(fg.primary_path) ASC',
|
||||
'-size': 'fg.size DESC, LOWER(fg.primary_path) DESC',
|
||||
'duration': 'duration ASC, LOWER(fg.primary_path) ASC',
|
||||
'-duration': 'duration DESC, LOWER(fg.primary_path) DESC',
|
||||
'viewed': 'v.viewed ASC',
|
||||
'-viewed': 'v.viewed DESC',
|
||||
'view_count': 'v.view_count ASC',
|
||||
'-view_count': 'v.view_count DESC',
|
||||
'modification_datetime': 'f.modification_datetime ASC',
|
||||
'-modification_datetime': 'f.modification_datetime DESC',
|
||||
'modification_datetime': 'fg.modification_datetime ASC',
|
||||
'-modification_datetime': 'fg.modification_datetime DESC',
|
||||
}
|
||||
NO_NULL_ORDERS = {
|
||||
'viewed': 'v.viewed IS NOT NULL',
|
||||
'-viewed': 'v.viewed IS NOT NULL',
|
||||
'duration': 'v.duration IS NOT NULL',
|
||||
'-duration': 'v.duration IS NOT NULL',
|
||||
'size': 'f.size IS NOT NULL',
|
||||
'-size': 'f.size IS NOT NULL',
|
||||
'size': 'fg.size IS NOT NULL',
|
||||
'-size': 'fg.size IS NOT NULL',
|
||||
'view_count': 'v.view_count IS NOT NULL',
|
||||
'-view_count': 'v.view_count IS NOT NULL',
|
||||
'modification_datetime': 'f.modification_datetime IS NOT NULL',
|
||||
'-modification_datetime': 'f.modification_datetime IS NOT NULL',
|
||||
'modification_datetime': 'fg.modification_datetime IS NOT NULL',
|
||||
'-modification_datetime': 'fg.modification_datetime IS NOT NULL',
|
||||
}
|
||||
JOIN_ORDERS = ('upload_date', '-upload_date', 'viewed', '-viewed', 'view_count', '-view_count', 'duration', '-duration')
|
||||
DEFAULT_VIDEO_ORDER = 'rank'
|
||||
VIDEO_QUERY_LIMIT = 24
|
||||
|
||||
|
|
@ -81,77 +77,77 @@ def search_videos(
|
|||
offset: int = None,
|
||||
limit: int = VIDEO_QUERY_LIMIT,
|
||||
channel_id: int = None,
|
||||
order_by: str = None,
|
||||
filters: List[str] = None,
|
||||
order: str = None,
|
||||
tag_names: List[str] = None,
|
||||
) -> Tuple[List[dict], int]:
|
||||
filters = filters or []
|
||||
wheres = ['v.video_path IS NOT NULL']
|
||||
tag_names = tag_names or []
|
||||
# Only search videos.
|
||||
wheres = ["fg.model = 'video'"]
|
||||
joins = list()
|
||||
join_video = False
|
||||
|
||||
params = dict(search_str=search_str, offset=offset)
|
||||
if channel_id:
|
||||
wheres.append('v.channel_id = %(channel_id)s')
|
||||
joins.append('LEFT JOIN channel c ON c.id = v.channel_id')
|
||||
join_video = True
|
||||
params['channel_id'] = channel_id
|
||||
|
||||
# Apply filters.
|
||||
if 'favorite' in filters:
|
||||
wheres.append('v.favorite IS NOT NULL')
|
||||
if 'censored' in filters:
|
||||
wheres.append('v.censored = true')
|
||||
|
||||
if search_str:
|
||||
# A search_str was provided by the user, modify the query to filter by it.
|
||||
select_columns = 'f.path, ts_rank(f.textsearch, websearch_to_tsquery(%(search_str)s)), ' \
|
||||
'COUNT(*) OVER() AS total'
|
||||
wheres.append('f.textsearch @@ websearch_to_tsquery(%(search_str)s)')
|
||||
select_columns = 'fg.id, ts_rank(fg.textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
wheres.append('fg.textsearch @@ websearch_to_tsquery(%(search_str)s)')
|
||||
params['search_str'] = search_str
|
||||
join = 'LEFT JOIN file f on f.path = v.video_path'
|
||||
else:
|
||||
# No search_str provided. Get path and total only.
|
||||
select_columns = 'v.video_path AS path, COUNT(*) OVER() AS total'
|
||||
join = ''
|
||||
# No search_str provided. Get id and total only.
|
||||
select_columns = 'fg.id, COUNT(*) OVER() AS total'
|
||||
|
||||
if order_by in {'size', '-size', 'modification_datetime', '-modification_datetime'}:
|
||||
# Size and modification_datetime are from the video file.
|
||||
join = 'LEFT JOIN file f on f.path = v.video_path'
|
||||
if tag_names:
|
||||
where_, params_, join_ = tag_names_to_clauses(tag_names)
|
||||
wheres.append(where_)
|
||||
params.update(params_)
|
||||
joins.append(join_)
|
||||
|
||||
# Convert the user-friendly order by into a real order by, restrict what can be interpolated by using the
|
||||
# whitelist.
|
||||
order = VIDEO_ORDERS[DEFAULT_VIDEO_ORDER]
|
||||
if order_by:
|
||||
order_by = VIDEO_ORDERS[DEFAULT_VIDEO_ORDER]
|
||||
if order:
|
||||
try:
|
||||
order = VIDEO_ORDERS[order_by]
|
||||
order_by = VIDEO_ORDERS[order]
|
||||
except KeyError:
|
||||
raise
|
||||
if order_by in NO_NULL_ORDERS:
|
||||
wheres.append(NO_NULL_ORDERS[order_by])
|
||||
if order in NO_NULL_ORDERS:
|
||||
wheres.append(NO_NULL_ORDERS[order])
|
||||
if order in JOIN_ORDERS:
|
||||
join_video = True
|
||||
|
||||
if join_video:
|
||||
joins.insert(0, 'LEFT JOIN video v on v.file_group_id = fg.id')
|
||||
|
||||
wheres = '\n AND '.join(wheres)
|
||||
where = f'WHERE\n{wheres}' if wheres else ''
|
||||
join = '\n'.join(joins)
|
||||
stmt = f'''
|
||||
SELECT
|
||||
{select_columns}
|
||||
FROM video v
|
||||
FROM file_group fg
|
||||
{join}
|
||||
{where}
|
||||
ORDER BY {order}
|
||||
ORDER BY {order_by}
|
||||
OFFSET %(offset)s LIMIT {int(limit)}
|
||||
'''.strip()
|
||||
logger.debug(stmt, params)
|
||||
|
||||
results, total = handle_search_results(stmt, params)
|
||||
results, total = handle_file_group_search_results(stmt, params)
|
||||
return results, total
|
||||
|
||||
|
||||
@run_after(save_channels_config)
|
||||
def set_video_favorite(video_id: int, favorite: bool) -> Optional[datetime]:
|
||||
"""
|
||||
Set the Video.favorite to the current datetime if `favorite` is True, otherwise None.
|
||||
"""
|
||||
with get_db_session(commit=True) as session:
|
||||
video = session.query(Video).filter_by(id=video_id).one()
|
||||
favorite = video.set_favorite(favorite)
|
||||
|
||||
return favorite
|
||||
def tag_video(video_id: int, tag_name: str):
|
||||
"""Tag a video"""
|
||||
with get_db_session(commit=True):
|
||||
video = Video.find_by_id(video_id)
|
||||
video.add_tag(tag_name)
|
||||
|
||||
|
||||
@optional_session
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import json
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from json import dumps
|
||||
|
|
@ -60,19 +61,19 @@ def test_get_video_prev_next(test_session, channel_factory, video_factory):
|
|||
if prev_title is None:
|
||||
assert prev_video is None
|
||||
else:
|
||||
assert prev_video and prev_video.title == prev_title
|
||||
assert prev_video and prev_video.file_group.title == prev_title
|
||||
|
||||
if next_title is None:
|
||||
assert next_video is None
|
||||
else:
|
||||
assert next_video and next_video.title == next_title
|
||||
assert next_video and next_video.file_group.title == next_title
|
||||
except AssertionError as e:
|
||||
raise AssertionError(f'Assert failed for {id_=} {prev_title=} {next_title=}') from e
|
||||
|
||||
|
||||
def test_get_video_for_app(test_session, simple_channel, simple_video):
|
||||
vid, prev, next_ = get_video_for_app(simple_video.id)
|
||||
assert vid['video']['id'] == simple_video.id
|
||||
assert vid['id'] == simple_video.id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -85,7 +86,7 @@ def test_video_delete(test_client, test_session, test_directory, channel_factory
|
|||
|
||||
assert test_session.query(Video).count() == 2
|
||||
|
||||
vid1_video_path, vid1_caption_path = vid1.video_path, vid1.caption_path
|
||||
vid1_video_path, vid1_caption_path = vid1.video_path, vid1.caption_paths[0]
|
||||
vid2_video_path, vid2_info_json_path = vid2.video_path, vid2.info_json_path
|
||||
|
||||
# No videos have been deleted yet.
|
||||
|
|
@ -120,10 +121,10 @@ def test_video_delete(test_client, test_session, test_directory, channel_factory
|
|||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
|
||||
def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixture, test_download_manager):
|
||||
def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixture, 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)))
|
||||
favorite = dumps(dict(video_id=simple_video.id, favorite=True))
|
||||
tag = tag_factory()
|
||||
|
||||
wrol_mode_fixture(True)
|
||||
|
||||
|
|
@ -152,8 +153,9 @@ def test_wrol_mode(test_directory, simple_channel, simple_video, wrol_mode_fixtu
|
|||
assert resp.json['code'] == API_ERRORS[WROLModeEnabled]['code']
|
||||
|
||||
# THE REST OF THESE METHODS ARE ALLOWED
|
||||
_, resp = api_app.test_client.post('/api/videos/favorite', content=favorite)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
content = dict(video_id=simple_video.id, tag_name=tag.name)
|
||||
_, resp = api_app.test_client.post('/api/videos/tag', content=json.dumps(content))
|
||||
assert resp.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
assert test_download_manager.stopped.is_set()
|
||||
|
||||
|
|
|
|||
|
|
@ -11,9 +11,7 @@ formatters = {
|
|||
|
||||
|
||||
def video_url_resolver(domain: str, entry: dict) -> str:
|
||||
"""
|
||||
Guess the full URL of a Youtube-DL entry.
|
||||
"""
|
||||
"""Guess the full URL of a Youtube-DL entry."""
|
||||
if 'webpage_url' in entry:
|
||||
return entry['webpage_url']
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue