mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 12:56:24 -05:00
Fixing JS warnings.
Handling all combinations of toggle in light and dark. Changing CPUUsageProgress colors to be more readable in dark mode. Moving theme handling into Theme.js. Importing element wrappers from Theme.js to handle element theming. Changing video menu to dark mode. Creating ThemeContext to share Dark Mode setting. Removing duplicate code for search functions. Displaying X when downloads are disabled. Using react context to share settings across components. Refusing to start workers when WROL Mode is enabled. Changing warning to debug. Queuing recurring downloads first. Adding Video.url index. Adding special handling for youtube shorts to videos. Reworking Downloads to have one worker per process. Testing creating downloads and getting downloaders. Testing video validation and poster generation. Testing video statistics. Increasing inventory test coverage. Adding pytest.ini to automatically detect async test. Adding more archive test coverage. Testing Archive CRUD. Catching and logging when encountering error during indexing. Using FileIcon when Archive has no screenshot. A Video will be assigned to a Channel by its info json first, then to its directory. Including suffix in File json. Adding index for File.suffix. Gathering suffix during indexing. Passing entire file down to FileIcon. Moving logging up. Returning File.associated in file json. Associated files are last in file search. Removing duplicate refreshing code by creating new _refresh_directory function. Changing File.idempotency to a datetime to avoid having to clear idempotency. Truncating indexes to avoid error with large files. Don't overwrite video data when info json is empty. Using already_downloaded for channel videos. Awaiting refresh in Channel.refresh. Testing that videos already downloaded aren't downloaded again. Adding indexes for video/archive referenced paths. Changing grid width for mobile or computer. Adding button to refresh specific directories. Restoring Channel edit link. Fixing caption path in video_modeler. Adding ZIP files to mimetype colors. Using model instead of first file's model. Fetching File models in batches to avoid issuing a SELECT for every File with a model. Flushing generated poster file. Getting Channel in VideoPage, relying on Video.channl_id, falling back to URL's channel_id. Attaching Video to it's Channel during download. Using ExternalCardLink for ArchivePage singlefile link. Validating and indexing videos after download. Handling glob when file name contains matching characters. Reworking and testing split_path_stem_and_suffix and glob_shared_stem. Adding associated video files to DB during upsert. Adding pending downloads to dashboard. Hiding status when download is open. Handling when load is empty. Adding load statistics to Dashboard. Limiting concurrent after_refresh functions. Handling when no onSelect is declared. Adding ImageRow for FileTable. Moving image date into Card.Meta. Using ExternalLink for FileCard. Using ExternalLink for ImageCard. Handling when error occurs during refresh of a directory. Committing during refresh to avoid losing all files if an error occurs. Removing api health check to avoid spamming logs. Creating ImageCard to display image posters when they aren't too large. Removing archive.domain_id not null. Reworking file refresh to process all files in a single directory. Bumping version for major file rework. No longer checking for video corruption. Adding duration by default to speed up tests. Using register_indexer for all indexers. Adding CPU usage progress bar in Welcome. Modifying TextIndexer to ignore large text files. Counting all files during refresh. Adding refresh_logger to clarify logging. Checking for wrol_mode before refresh functions. Removing unused idempotency from video/channel tables. Using magic module to speed up mimetype identification. All tests pass. Archive tests pass. Changing video get endpoint to return 'file' to avoid ambiguity. Video tests pass. Simplifying regex filtering. Using regex to ignore case when filtering. Converting all channel classes to functions. Restoring channel refresh and download buttons. Matching format of Archive and Video pages. Adding sorting to Archives search. Reworking video orders for file search. Using SearchInput for videos search. Archives can be searched on the Archives page. Domains can be filtered. Reworking Archive search to use Files. Videos, Archives and Global search use the FilesView. Videos are claimed by their Channel based on the Channel's directory. Prev and Next video cards are displayed on the VideoPage. Creating useVideo for reworked VideoWrapper and VideoPage. Adding Paginator to FilesView. Moving file refresh button out of manage tab. Removing Files page tabs. Limiting refresh to one at a time. Adding class for card icon to match poster height. Video and Archives always re-claim their files on refresh. Archive files are indexed and claimed. FileView table is compact and striped. Videos page uses FileView. Updated navlinks to router v6. Removing ! character from file names. Disabling select button when cards are visible. Adding show/hide button for FileTable selection. The Archive Page is displayed. Adding mimetype dropdown. Upgrading to React Router v6 for useSearchParams. Validating video during modeling. Removing screenshot during corruption check because it was very slow. Updating app to use video files as search results. Updating video search to return Files. Video and WROLPi tests pass. Creating function to refresh files within a channel's directory. Removing troubleshooting print. Updating result order in test. Reworking video_factory to handle a specific video file location. Returning video model on file search. Getting session using video_file. Screenshotting when checking for video corruption. Reducing ffmpeg calls by gathering duration during poster generation. Moving video file matching into model. VideoIndexer is moved into video module. Video files are validated. Moving files module into wrolpi in preparation to use it in modules. Title and contents are indexed for text file. Files are indexed on refresh by using their indexer. Zip files are indexed using their contents. Testing multiple zip files. Adding unique to file.path. Checking that the correct indexer is used. Adding index to file.modification_datetime and file.size. Handling file info gathering in File.do_index. Only reading contents of file if file.indexed is False. Video model is found during file refresh. A Video record is created that has the associated files. Videos without associated files are found. Videos are found using registered video_modeler() rather than in refresh code. Removing old video columns. Handling video info json files. Trying to import each module individually. Will continue to import modules even if one fails. Reworking refresh so it performs less DB calls. Converting file.path to primary key. file.path is always a pathlib.Path. Updating video_factory to use new file system, testing it. Bump sanic from 21.9.1 to 21.12.2 in /docker/archive Bumps [sanic](https://github.com/sanic-org/sanic) from 21.9.1 to 21.12.2. - [Release notes](https://github.com/sanic-org/sanic/releases) - [Changelog](https://github.com/sanic-org/sanic/blob/main/CHANGELOG.rst) - [Commits](https://github.com/sanic-org/sanic/compare/v21.9.1...v21.12.2) --- updated-dependencies: - dependency-name: sanic dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com>
This commit is contained in:
parent
1ede5f3f55
commit
d4ed5fa5ce
98 changed files with 7441 additions and 5257 deletions
|
|
@ -1,20 +1,28 @@
|
|||
import json
|
||||
import pathlib
|
||||
from abc import ABC
|
||||
from typing import Tuple, Optional
|
||||
from typing import Tuple, Dict, List
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from wrolpi.common import logger
|
||||
from wrolpi.db import optional_session
|
||||
from wrolpi.common import logger, register_modeler, register_after_refresh, limit_concurrent
|
||||
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.vars import PYTEST
|
||||
from . import lib
|
||||
from .api import bp # noqa
|
||||
from .models import Archive
|
||||
from .lib import match_archive_files
|
||||
from .models import Archive, Domain
|
||||
|
||||
PRETTY_NAME = 'Archive'
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
__all__ = ['ArchiveDownloader', 'archive_downloader']
|
||||
|
||||
|
||||
class ArchiveDownloader(Downloader, ABC):
|
||||
name = 'archive'
|
||||
|
|
@ -38,9 +46,134 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
return DownloadResult(success=True, location=f'/archive/{archive.id}')
|
||||
|
||||
@optional_session
|
||||
def already_downloaded(self, url: str, session: Session = None) -> bool:
|
||||
return bool(session.query(Archive).filter_by(url=url).count())
|
||||
def already_downloaded(self, urls: List[str], session: Session = None) -> List:
|
||||
archives = list(session.query(Archive).filter(Archive.url.in_(urls)))
|
||||
return archives
|
||||
|
||||
|
||||
# Archive downloader is the last downloader which should be used.
|
||||
archive_downloader = ArchiveDownloader(priority=100)
|
||||
|
||||
|
||||
@register_modeler
|
||||
def archive_modeler(groups: Dict[str, List[File]], session: Session):
|
||||
archive_groups = {}
|
||||
for stem, group in groups.items():
|
||||
if any(lib.is_singlefile_file(i.path) for i in group):
|
||||
archive_groups[stem] = group
|
||||
|
||||
count = 0
|
||||
for stem, group in archive_groups.items():
|
||||
readability_file, singlefile_file, readability_json_file, readability_txt_file, screenshot_file = \
|
||||
match_archive_files(group)
|
||||
archive: Archive = Archive.find_by_path(singlefile_file.path, session)
|
||||
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.readability_file:
|
||||
archive.readability_file.associated = True
|
||||
archive.readability_file.do_index()
|
||||
if archive.readability_json_file:
|
||||
archive.readability_json_file.associated = True
|
||||
archive.readability_json_file.do_index()
|
||||
if archive.readability_txt_file:
|
||||
archive.readability_txt_file.associated = True
|
||||
archive.readability_txt_file.do_index()
|
||||
if archive.screenshot_file:
|
||||
archive.screenshot_file.associated = True
|
||||
archive.screenshot_file.do_index()
|
||||
|
||||
archive.singlefile_file.model = Archive.__tablename__
|
||||
|
||||
archive.singlefile_file.do_index()
|
||||
archive.validate()
|
||||
|
||||
# Remove this group, it will not be processed by other modelers.
|
||||
del groups[stem]
|
||||
|
||||
count += 1
|
||||
if not count % 100:
|
||||
# Commit occasionally.
|
||||
session.commit()
|
||||
|
||||
|
||||
@register_after_refresh
|
||||
@limit_concurrent(1)
|
||||
def archive_cleanup():
|
||||
# Process all Archives that have not been validated. Delete any that no longer exist, or are not real Archives.
|
||||
# Validate all other Archives.
|
||||
logger.info('Searching for invalid Archives')
|
||||
offset = 0
|
||||
limit = 100
|
||||
while True:
|
||||
with get_db_session(commit=True) as session:
|
||||
archives: List[Archive] = session.query(Archive).order_by(Archive.id).limit(limit).offset(offset)
|
||||
processed = 0
|
||||
deleted = 0
|
||||
for archive in archives:
|
||||
processed += 1
|
||||
if not lib.is_singlefile_file(archive.singlefile_path):
|
||||
# Archive is not a real archive.
|
||||
archive.singlefile_file.model = None
|
||||
session.delete(archive)
|
||||
deleted += 1
|
||||
if processed < limit:
|
||||
# Validated all archives.
|
||||
break
|
||||
offset += (limit - deleted)
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Remove any Domains without any Archives.
|
||||
domain_ids = [i[0] for i in session.execute('SELECT DISTINCT domain_id FROM archive') if i[0]]
|
||||
deleted = 0
|
||||
for domain in session.query(Domain):
|
||||
if domain.id not in domain_ids:
|
||||
deleted += 1
|
||||
session.delete(domain)
|
||||
|
||||
|
||||
@register_indexer('text/html')
|
||||
class ArchiveIndexer(Indexer, ABC):
|
||||
|
||||
@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)
|
||||
return a, None, None, d
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import asyncio
|
||||
from http import HTTPStatus
|
||||
|
||||
from sanic import response, Request
|
||||
|
|
@ -22,8 +21,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)
|
||||
alternatives = archive.alternatives
|
||||
return json_response({'archive': archive, 'alternatives': alternatives})
|
||||
archive_file = archive.singlefile_file.__json__()
|
||||
alternatives = [i.singlefile_file.__json__() for i in archive.alternatives]
|
||||
return json_response({'file': archive_file, 'alternatives': alternatives})
|
||||
|
||||
|
||||
@bp.delete('/<archive_id:int>')
|
||||
|
|
@ -35,13 +35,6 @@ async def delete_archive(_: Request, archive_id: int):
|
|||
return response.empty()
|
||||
|
||||
|
||||
@bp.post('/refresh')
|
||||
@wrol_mode_check
|
||||
async def refresh_archives(_: Request):
|
||||
asyncio.ensure_future(lib.refresh_archives())
|
||||
return response.empty()
|
||||
|
||||
|
||||
@bp.get('/domains')
|
||||
async def fetch_domains(_: Request):
|
||||
domains = lib.get_domains()
|
||||
|
|
@ -65,6 +58,6 @@ async def search_archives(_: Request, body: schema.ArchiveSearchRequest):
|
|||
limit = archive_limit_limiter(body.limit)
|
||||
offset = body.offset or 0
|
||||
|
||||
archives, total = lib.search(search_str, domain, limit, offset)
|
||||
archives, total = lib.archive_search(search_str, domain, limit, offset, body.order_by)
|
||||
ret = dict(archives=archives, totals=dict(archives=total))
|
||||
return json_response(ret)
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import pytest
|
|||
from modules.archive.lib import archive_strftime
|
||||
from modules.archive.models import Archive, Domain
|
||||
from wrolpi.dates import local_timezone
|
||||
from wrolpi.files.models import File
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
|
@ -18,7 +19,7 @@ def archive_directory(test_directory) -> pathlib.Path:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def archive_factory(test_session, archive_directory):
|
||||
def archive_factory(test_session, archive_directory, make_files_structure):
|
||||
def time_generator():
|
||||
timestamp = datetime.datetime(2000, 1, 1, 0, 0, 0)
|
||||
while True:
|
||||
|
|
@ -27,12 +28,12 @@ def archive_factory(test_session, archive_directory):
|
|||
|
||||
now = time_generator()
|
||||
|
||||
def _(domain: str = None, url: str = None, title: str = 'NA', contents: str = None) -> Archive:
|
||||
def _(domain: str = None, url: str = None, title: str = 'NA', contents: str = None,
|
||||
singlefile_contents: str = None) -> Archive:
|
||||
if domain:
|
||||
assert '/' not in domain
|
||||
|
||||
title = title or str(uuid4())
|
||||
url = url or f'https://example.com/{title}'
|
||||
domain_dir = domain or title
|
||||
domain_dir = archive_directory / domain_dir
|
||||
domain_dir.mkdir(exist_ok=True)
|
||||
|
|
@ -40,19 +41,25 @@ def archive_factory(test_session, archive_directory):
|
|||
archive_datetime = local_timezone(next(now))
|
||||
timestamp = archive_strftime(archive_datetime)
|
||||
|
||||
singlefile_path = domain_dir / f'{timestamp}_{title}.html'
|
||||
screenshot_path = domain_dir / f'{timestamp}_{title}.png'
|
||||
readability_path = domain_dir / f'{timestamp}_{title}.readability.html'
|
||||
readability_txt_path = domain_dir / f'{timestamp}_{title}.readability.txt'
|
||||
readability_json_path = domain_dir / f'{timestamp}_{title}.readability.json'
|
||||
|
||||
with readability_json_path.open('wt') as fh:
|
||||
json.dump({'url': url}, fh)
|
||||
json_contents = {}
|
||||
if title != 'NA':
|
||||
json_contents['title'] = title
|
||||
if url:
|
||||
json_contents['url'] = url
|
||||
json_contents = json.dumps(json_contents)
|
||||
singlefile_path, screenshot_path, readability_path, readability_txt_path, readability_json_path = \
|
||||
make_files_structure({
|
||||
str(domain_dir / f'{timestamp}_{title}.html'): singlefile_contents or '<html></html>',
|
||||
str(domain_dir / f'{timestamp}_{title}.png'): None,
|
||||
str(domain_dir / f'{timestamp}_{title}.readability.html'): '<html></html>',
|
||||
str(domain_dir / f'{timestamp}_{title}.readability.txt'): contents,
|
||||
str(domain_dir / f'{timestamp}_{title}.readability.json'): json_contents,
|
||||
})
|
||||
|
||||
if domain:
|
||||
domain = test_session.query(Domain).filter_by(domain=domain).one_or_none()
|
||||
|
||||
if not domain:
|
||||
if not domain and domain_dir.name != 'NA':
|
||||
domain = Domain(
|
||||
domain=domain_dir.name,
|
||||
directory=domain_dir,
|
||||
|
|
@ -61,23 +68,18 @@ def archive_factory(test_session, archive_directory):
|
|||
test_session.flush([domain])
|
||||
|
||||
archive = Archive(
|
||||
readability_json_path=readability_json_path,
|
||||
readability_path=readability_path,
|
||||
readability_txt_path=readability_txt_path,
|
||||
screenshot_path=screenshot_path,
|
||||
singlefile_path=singlefile_path,
|
||||
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,
|
||||
contents=contents,
|
||||
domain_id=domain.id if domain else None,
|
||||
archive_datetime=archive_datetime,
|
||||
)
|
||||
test_session.add(archive)
|
||||
|
||||
test_session.commit()
|
||||
|
||||
for path in archive.my_paths():
|
||||
path.touch()
|
||||
archive.singlefile_file.do_index()
|
||||
|
||||
return archive
|
||||
|
||||
|
|
|
|||
|
|
@ -7,21 +7,22 @@ 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
|
||||
|
||||
import aiohttp
|
||||
from bs4 import BeautifulSoup
|
||||
from selenium import webdriver
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from modules.archive.models import Domain, Archive
|
||||
from wrolpi.cmd import which
|
||||
from wrolpi.common import get_media_directory, logger, chunks, extract_domain, chdir, escape_file_name, walk, \
|
||||
aiohttp_post
|
||||
from wrolpi.common import get_media_directory, logger, extract_domain, chdir, escape_file_name, walk, \
|
||||
aiohttp_post, match_paths_to_suffixes, iterify
|
||||
from wrolpi.dates import now, Seconds, local_timezone
|
||||
from wrolpi.db import get_db_session, get_db_curs, get_ranked_models, optional_session
|
||||
from wrolpi.errors import InvalidDomain, UnknownURL, InvalidArchive
|
||||
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.vars import DOCKERIZED, PYTEST
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
|
@ -284,12 +285,11 @@ async def do_archive(url: str) -> Archive:
|
|||
archive = Archive(
|
||||
title=title,
|
||||
archive_datetime=now(),
|
||||
singlefile_path=archive_files.singlefile,
|
||||
readability_path=archive_files.readability,
|
||||
readability_json_path=archive_files.readability_json,
|
||||
readability_txt_path=archive_files.readability_txt,
|
||||
screenshot_path=archive_files.screenshot,
|
||||
contents=readability_txt,
|
||||
singlefile_file=File(path=archive_files.singlefile, model='archive'),
|
||||
readability_file=File(path=archive_files.readability) if archive_files.readability else None,
|
||||
readability_json_file=File(path=archive_files.readability_json) if archive_files.readability_json else None,
|
||||
readability_txt_file=File(path=archive_files.readability_txt) if archive_files.readability_txt else None,
|
||||
screenshot_file=File(path=archive_files.screenshot) if archive_files.screenshot else None,
|
||||
url=url,
|
||||
domain_id=domain.id,
|
||||
)
|
||||
|
|
@ -323,19 +323,12 @@ def get_title_from_html(html: str, url: str = None) -> str:
|
|||
logger.info(f'Unable to extract title {url}')
|
||||
|
||||
|
||||
def get_domain(session, domain: str) -> Domain:
|
||||
domain_ = session.query(Domain).filter_by(domain=domain).one_or_none()
|
||||
if not domain_:
|
||||
raise InvalidDomain(f'Invalid domain: {domain}')
|
||||
return domain_
|
||||
|
||||
|
||||
@optional_session
|
||||
def get_archive(session, archive_id: int) -> Archive:
|
||||
"""Get an Archive."""
|
||||
archive = session.query(Archive).filter_by(id=archive_id).one_or_none()
|
||||
if not archive:
|
||||
raise InvalidArchive(f'Invalid archive id: {archive_id}')
|
||||
raise UnknownArchive(f'Could not find archive with id: {archive_id}')
|
||||
return archive
|
||||
|
||||
|
||||
|
|
@ -344,7 +337,7 @@ def delete_archive(archive_id: int):
|
|||
with get_db_session(commit=True) as session:
|
||||
archive: Archive = session.query(Archive).filter_by(id=archive_id).one_or_none()
|
||||
if not archive:
|
||||
raise UnknownURL(f'Unknown Archive with id: {archive_id}')
|
||||
raise UnknownArchive(f'Unknown Archive with id: {archive_id}')
|
||||
|
||||
# Delete any files associated with this URL.
|
||||
archive.delete()
|
||||
|
|
@ -476,95 +469,13 @@ def is_archive_file(path: pathlib.Path) -> bool:
|
|||
return path.is_file() and path.suffix.lower() in ARCHIVE_SUFFIXES and bool(ARCHIVE_MATCHER.match(path.name))
|
||||
|
||||
|
||||
def _refresh_archives():
|
||||
def is_singlefile_file(path: pathlib.Path) -> bool:
|
||||
"""
|
||||
Search the Archives directory for archive files, update the database if new files are found. Remove any orphan
|
||||
URLs or Domains.
|
||||
Archive singlefile files are expected to start with the following: %Y-%m-%d-%H-%M-%S
|
||||
they must end with .html, but never with .readability.html.
|
||||
"""
|
||||
archive_directory = get_archive_directory()
|
||||
|
||||
# TODO remove this later when everyone has migrated their files.
|
||||
migrate_archive_files()
|
||||
|
||||
singlefile_paths = set()
|
||||
for domain_directory in filter(lambda i: i.is_dir(), archive_directory.iterdir()):
|
||||
logger.debug(f'Refreshing directory: {domain_directory}')
|
||||
all_archives_files = filter(is_archive_file, walk(domain_directory))
|
||||
archive_groups = group_archive_files(all_archives_files)
|
||||
archive_groups = list(archive_groups)
|
||||
archive_count = 0
|
||||
for chunk in chunks(archive_groups, 20):
|
||||
with get_db_session(commit=True) as session:
|
||||
for dt, archive_files in chunk:
|
||||
archive_count += 1
|
||||
singlefile_paths.add(str(archive_files.singlefile))
|
||||
upsert_archive(dt, archive_files, session)
|
||||
|
||||
if archive_count:
|
||||
logger.info(f'Inserted/updated {archive_count} archives in {domain_directory}')
|
||||
|
||||
singlefile_paths = list(singlefile_paths)
|
||||
with get_db_curs(commit=True) as curs:
|
||||
curs.execute('DELETE FROM archive WHERE singlefile_path != ALL(%s)', (singlefile_paths,))
|
||||
|
||||
with get_db_curs(commit=True) as curs:
|
||||
stmt = '''
|
||||
DELETE FROM domains WHERE
|
||||
id NOT IN (select distinct domain_id from archive)
|
||||
RETURNING domains.id
|
||||
'''
|
||||
curs.execute(stmt)
|
||||
domains = list(map(dict, curs.fetchall()))
|
||||
logger.info(f'Deleted {len(domains)} Domains')
|
||||
|
||||
with get_db_session(commit=True) as session:
|
||||
# Get all archives that have no text contents, but have txt files.
|
||||
archives = session.query(Archive).filter(
|
||||
Archive.contents == None, # noqa
|
||||
Archive.readability_txt_path != None,
|
||||
).all()
|
||||
for archive in archives:
|
||||
with archive.readability_txt_path.path.open('rt') as fh:
|
||||
archive.contents = fh.read()
|
||||
|
||||
|
||||
async def refresh_archives():
|
||||
_refresh_archives()
|
||||
|
||||
|
||||
def upsert_archive(dt: str, archive_files: ArchiveFiles, session: Session):
|
||||
"""Get or create an Archive, and it's URL/Domain. If it already exists, update it with these new files."""
|
||||
# Extract the URL from the JSON. Fail if this is not possible.
|
||||
try:
|
||||
with archive_files.readability_json.open() as fh:
|
||||
json_contents = json.load(fh)
|
||||
url = json_contents['url']
|
||||
title = json_contents.get('title')
|
||||
except Exception as e:
|
||||
raise InvalidArchive() from e
|
||||
|
||||
domain = get_or_create_domain(session, url)
|
||||
# Get the existing Archive, or create a new one.
|
||||
archive = session.query(Archive).filter_by(singlefile_path=archive_files.singlefile).one_or_none()
|
||||
if not archive:
|
||||
# No archive matches this singlefile_path, create a new one.
|
||||
archive = Archive(url=url, domain_id=domain.id)
|
||||
session.add(archive)
|
||||
session.flush()
|
||||
|
||||
if not archive.title and title:
|
||||
archive.title = title
|
||||
if not archive.title and archive_files.singlefile:
|
||||
# As a last resort, get the title from the HTML.
|
||||
archive.title = get_title_from_html(archive_files.singlefile.read_text(), url)
|
||||
|
||||
# Update the archive with the files that we have.
|
||||
archive.archive_datetime = dt
|
||||
archive.singlefile_path = archive_files.singlefile
|
||||
archive.readability_path = archive_files.readability
|
||||
archive.readability_txt_path = archive_files.readability_txt
|
||||
archive.readability_json_path = archive_files.readability_json
|
||||
archive.screenshot_path = archive_files.screenshot
|
||||
return path.is_file() and path.suffix.lower() == '.html' and not path.name.endswith('.readability.html') \
|
||||
and bool(ARCHIVE_MATCHER.match(path.name))
|
||||
|
||||
|
||||
def get_domains():
|
||||
|
|
@ -581,46 +492,69 @@ def get_domains():
|
|||
return domains
|
||||
|
||||
|
||||
def search(search_str: str, domain: str, limit: int, offset: int) -> Tuple[List[Archive], int]:
|
||||
with get_db_curs() as curs:
|
||||
columns = 'id, COUNT(*) OVER() AS total'
|
||||
params = dict(offset=offset, limit=limit)
|
||||
wheres = ''
|
||||
order_by = '1 DESC'
|
||||
ARCHIVE_ORDERS = {
|
||||
'date': 'a.archive_datetime ASC, LOWER(a.singlefile_path) ASC',
|
||||
'-date': 'a.archive_datetime DESC NULLS LAST, LOWER(a.singlefile_path) DESC',
|
||||
'rank': '2 DESC, a.archive_datetime DESC',
|
||||
'-rank': '2 ASC, a.archive_datetime ASC',
|
||||
}
|
||||
|
||||
if search_str:
|
||||
columns = 'id, ts_rank_cd(textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
params['search_str'] = search_str
|
||||
wheres += '\nAND textsearch @@ websearch_to_tsquery(%(search_str)s)'
|
||||
# highest rank, then most recent
|
||||
order_by = '2 DESC, archive_datetime DESC'
|
||||
|
||||
if domain:
|
||||
curs.execute('SELECT id FROM domains WHERE domain=%s', (domain,))
|
||||
try:
|
||||
domain_id = curs.fetchone()[0]
|
||||
except TypeError:
|
||||
# No domains match the provided domain.
|
||||
return [], 0
|
||||
params['domain_id'] = domain_id
|
||||
wheres += '\nAND domain_id = %(domain_id)s'
|
||||
def archive_search(search_str: str, domain: str, limit: int, offset: int, order_by: str) -> Tuple[List[Archive], int]:
|
||||
wheres = []
|
||||
params = dict(offset=offset, limit=limit)
|
||||
order = '1 DESC'
|
||||
|
||||
# TODO handle different Archive search orders.
|
||||
stmt = f'''
|
||||
SELECT {columns}
|
||||
FROM archive
|
||||
WHERE
|
||||
singlefile_path IS NOT NULL AND singlefile_path != ''
|
||||
{wheres}
|
||||
ORDER BY {order_by}
|
||||
OFFSET %(offset)s
|
||||
LIMIT %(limit)s
|
||||
'''
|
||||
curs.execute(stmt, params)
|
||||
results = [dict(i) for i in curs.fetchall()]
|
||||
total = results[0]['total'] if results else 0
|
||||
ranked_ids = [i['id'] for i in results]
|
||||
if search_str:
|
||||
columns = 'f.path, ts_rank(f.textsearch, websearch_to_tsquery(%(search_str)s)), COUNT(*) OVER() AS total'
|
||||
params['search_str'] = search_str
|
||||
wheres.append('\nAND textsearch @@ websearch_to_tsquery(%(search_str)s)')
|
||||
# highest rank, then most recent
|
||||
if not order_by:
|
||||
order = ARCHIVE_ORDERS['rank']
|
||||
else:
|
||||
# No search_str provided, get path and total only.
|
||||
columns = 'f.path, COUNT(*) OVER() AS total'
|
||||
|
||||
results = get_ranked_models(ranked_ids, Archive)
|
||||
if order_by:
|
||||
try:
|
||||
order = ARCHIVE_ORDERS[order_by]
|
||||
except KeyError:
|
||||
raise InvalidOrderBy(f'Invalid order by: {order_by}')
|
||||
|
||||
if domain:
|
||||
params['domain'] = domain
|
||||
wheres.append('AND domain_id = (select id from domains where domains.domain = %(domain)s)')
|
||||
|
||||
wheres = '\n'.join(wheres)
|
||||
stmt = f'''
|
||||
SELECT {columns}
|
||||
FROM archive a
|
||||
LEFT JOIN file f on f.path = a.singlefile_path
|
||||
WHERE
|
||||
a.singlefile_path != ''
|
||||
{wheres}
|
||||
ORDER BY {order}
|
||||
OFFSET %(offset)s
|
||||
LIMIT %(limit)s
|
||||
'''
|
||||
logger.warning(stmt, params)
|
||||
|
||||
results, total = handle_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)
|
||||
|
|
|
|||
|
|
@ -1,13 +1,22 @@
|
|||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
from typing import Generator
|
||||
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, Computed
|
||||
from sqlalchemy.orm import relationship, Session
|
||||
import pytz
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean
|
||||
from sqlalchemy.orm import relationship, Session, validates
|
||||
from sqlalchemy.orm.collections import InstrumentedList
|
||||
|
||||
from wrolpi.common import ModelHelper, Base, tsvector
|
||||
from wrolpi.common import ModelHelper, Base, logger
|
||||
from wrolpi.dates import TZDateTime
|
||||
from wrolpi.errors import InvalidArchive
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.media_path import MediaPathType
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
||||
class Archive(Base, ModelHelper):
|
||||
__tablename__ = 'archive'
|
||||
|
|
@ -16,34 +25,40 @@ class Archive(Base, ModelHelper):
|
|||
domain_id = Column(Integer, ForeignKey('domains.id'))
|
||||
domain = relationship('Domain', primaryjoin='Archive.domain_id==Domain.id')
|
||||
|
||||
singlefile_path = Column(MediaPathType)
|
||||
readability_path = Column(MediaPathType)
|
||||
readability_json_path = Column(MediaPathType)
|
||||
readability_txt_path = Column(MediaPathType)
|
||||
screenshot_path = Column(MediaPathType)
|
||||
|
||||
url = Column(String)
|
||||
title = Column(String)
|
||||
archive_datetime = Column(TZDateTime)
|
||||
contents = Column(String)
|
||||
validated = Column(Boolean)
|
||||
|
||||
textsearch = Column(tsvector, Computed('''setweight(to_tsvector('english'::regconfig, title), 'A') ||
|
||||
setweight(to_tsvector('english'::regconfig, contents), 'D')'''))
|
||||
# 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')
|
||||
|
||||
def __repr__(self):
|
||||
return f'<Archive id={self.id} url={self.url} singlefile={self.singlefile_path}>'
|
||||
if self.domain:
|
||||
return f'<Archive id={self.id} url={self.url} singlefile={repr(str(self.singlefile_path))} ' \
|
||||
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:
|
||||
if self.singlefile_path:
|
||||
yield self.singlefile_path.path
|
||||
yield self.singlefile_path
|
||||
if self.readability_path:
|
||||
yield self.readability_path.path
|
||||
yield self.readability_path
|
||||
if self.readability_json_path:
|
||||
yield self.readability_json_path.path
|
||||
yield self.readability_json_path
|
||||
if self.readability_txt_path:
|
||||
yield self.readability_txt_path.path
|
||||
yield self.readability_txt_path
|
||||
if self.screenshot_path:
|
||||
yield self.screenshot_path.path
|
||||
yield self.screenshot_path
|
||||
|
||||
def unlink(self):
|
||||
"""
|
||||
|
|
@ -73,6 +88,7 @@ class Archive(Base, ModelHelper):
|
|||
readability_txt_path=self.readability_txt_path,
|
||||
screenshot_path=self.screenshot_path,
|
||||
singlefile_path=self.singlefile_path,
|
||||
stem=self.singlefile_path.stem if self.singlefile_path else None,
|
||||
title=self.title,
|
||||
url=self.url,
|
||||
)
|
||||
|
|
@ -96,11 +112,103 @@ class Archive(Base, ModelHelper):
|
|||
Get a list of Archives that share my URL.
|
||||
"""
|
||||
session = Session.object_session(self)
|
||||
i = list(session.query(Archive).filter(
|
||||
alternatives = list(session.query(Archive).filter(
|
||||
Archive.id != self.id,
|
||||
Archive.url == self.url,
|
||||
).order_by(Archive.archive_datetime))
|
||||
return i
|
||||
return alternatives
|
||||
|
||||
def my_files(self) -> Generator[pathlib.Path, None, None]:
|
||||
"""Return all paths of this Archive. Returns nothing if all paths are None.""" # noqa
|
||||
if self.singlefile_path:
|
||||
yield self.singlefile_path
|
||||
if self.readability_path:
|
||||
yield self.readability_path
|
||||
if self.readability_txt_path:
|
||||
yield self.readability_txt_path
|
||||
if self.readability_json_path:
|
||||
yield self.readability_json_path
|
||||
if self.screenshot_path:
|
||||
yield self.screenshot_path
|
||||
|
||||
@staticmethod
|
||||
def find_by_path(path, session: Session) -> Base:
|
||||
archive = session.query(Archive).filter_by(singlefile_path=path).one_or_none()
|
||||
return archive
|
||||
|
||||
def read_singlefile_data(self):
|
||||
"""
|
||||
Read the start of the singlefile (if any) and decode the Archive information.
|
||||
"""
|
||||
match_url = re.compile(r'^\s+?url:\s+?(http.*)', re.MULTILINE)
|
||||
match_date = re.compile(r'^\s+?saved date:\s+?(.*)', re.MULTILINE)
|
||||
|
||||
if self.singlefile_path:
|
||||
with self.singlefile_path.open('rt') as fh:
|
||||
head = fh.read(500)
|
||||
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 {self.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 {self.singlefile_path}', exc_info=e)
|
||||
|
||||
def read_readability_data(self):
|
||||
"""Read the Readability JSON file, apply its contents to this record."""
|
||||
from modules.archive.lib import get_or_create_domain, get_title_from_html
|
||||
|
||||
readability_json_file = self.readability_json_file
|
||||
if not readability_json_file or not readability_json_file.path.is_file():
|
||||
raise InvalidArchive(f'Archive must have a readability json file: {self.singlefile_file.path}')
|
||||
|
||||
try:
|
||||
with readability_json_file.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
|
||||
|
||||
domain = None
|
||||
if url:
|
||||
domain = get_or_create_domain(Session.object_session(self), url)
|
||||
|
||||
if not title:
|
||||
title = get_title_from_html(self.singlefile_path.read_text())
|
||||
|
||||
self.url = url
|
||||
self.title = title
|
||||
self.domain_id = domain.id if domain else None
|
||||
|
||||
def validate(self):
|
||||
try:
|
||||
self.read_readability_data()
|
||||
self.read_singlefile_data()
|
||||
self.validated = True
|
||||
except Exception as e:
|
||||
logger.warning(f'Unable to validate {self}', exc_info=e)
|
||||
|
||||
@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):
|
||||
|
|
@ -119,3 +227,11 @@ class Domain(Base, ModelHelper):
|
|||
session = Session.object_session(self)
|
||||
session.execute('DELETE FROM archive WHERE domain_id=:id', dict(id=self.id))
|
||||
session.query(Domain).filter_by(id=self.id).delete()
|
||||
|
||||
@validates('domain')
|
||||
def validate_domain(self, key, value: str):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError('Domain must be a string')
|
||||
if len(value.split('.')) < 2:
|
||||
raise ValueError(f'Domain must contain at least one "." domain={repr(value)}')
|
||||
return value
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ class ArchiveSearchRequest:
|
|||
domain: Optional[str] = None
|
||||
offset: Optional[int] = None
|
||||
limit: Optional[int] = None
|
||||
order_by: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
|
|||
|
|
@ -5,16 +5,22 @@ 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
|
||||
assert [i['id'] for i in response.json['archives']] == ids, \
|
||||
f'{response.json["archives"][0]["id"]}..{response.json["archives"][19]["id"]}'
|
||||
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"]}'
|
||||
|
||||
|
||||
def test_archives_search(test_session, archive_directory, archive_factory, test_client):
|
||||
"""Archives can be searched by their title and their contents."""
|
||||
# Search with no archives.
|
||||
check_results(test_client, {'search_str': 'foo'}, [])
|
||||
|
||||
archive_factory('example.com', 'https://example.com/one', 'my archive', 'foo bar qux')
|
||||
archive_factory('example.com', 'https://example.com/one', 'other archive', 'foo baz qux qux')
|
||||
archive_factory('example.org', title='archive third', contents='baz qux qux qux')
|
||||
archive_factory('example.org') # has no contents
|
||||
test_session.commit()
|
||||
|
||||
# 1 and 2 contain "foo".
|
||||
data = {'search_str': 'foo'}
|
||||
|
|
@ -44,15 +50,20 @@ def test_archives_search(test_session, archive_directory, archive_factory, test_
|
|||
data = {'search_str': 'third'}
|
||||
check_results(test_client, data, [3, ])
|
||||
|
||||
# All titles contain "qux", but they contain different amounts. They are ordered by the amount.
|
||||
# All contents contain "qux", but they contain different amounts. They are ordered by the amount.
|
||||
data = {'search_str': 'qux'}
|
||||
check_results(test_client, data, [3, 2, 1])
|
||||
|
||||
data = {'search_str': 'qux', 'order_by': 'bad order_by'}
|
||||
request, response = test_client.post('/api/archive/search', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
def test_search_offset(archive_factory, test_client):
|
||||
|
||||
def test_search_offset(test_session, archive_factory, test_client):
|
||||
"""Archive search can be offset."""
|
||||
for i in range(500):
|
||||
archive_factory('example.com', f'https://example.com/{i}', contents='foo bar')
|
||||
test_session.commit()
|
||||
|
||||
data = {'search_str': None, 'offset': 0}
|
||||
check_results(test_client, data, list(range(500, 480, -1)))
|
||||
|
|
@ -66,28 +77,87 @@ def test_search_offset(archive_factory, test_client):
|
|||
check_results(test_client, data, [])
|
||||
|
||||
|
||||
def test_archives_search_no_query(archive_factory, test_client):
|
||||
def test_archives_search_no_query(test_session, archive_factory, test_client):
|
||||
"""Archive Search API endpoint does not require data in the body."""
|
||||
# Add 100 random archives.
|
||||
for _ in range(100):
|
||||
archive_factory('example.com')
|
||||
test_session.commit()
|
||||
|
||||
# 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['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['archives'] == 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['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == list(range(100, 80, -1))
|
||||
assert response.json['totals']['archives'] == 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['id'] for i in response.json['archives']] == []
|
||||
assert [i['archive']['id'] for i in response.json['archives']] == []
|
||||
assert response.json['totals']['archives'] == 0
|
||||
|
||||
|
||||
def test_archive_and_domain_crud(test_session, test_client, archive_factory):
|
||||
"""
|
||||
Getting an Archive returns it's File. Testing deleting Archives.
|
||||
"""
|
||||
# Can get empty results.
|
||||
request, response = test_client.get(f'/api/archive/1')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'] == []
|
||||
|
||||
archive1 = archive_factory(domain='example.com')
|
||||
archive2 = archive_factory(domain='example.com')
|
||||
test_session.commit()
|
||||
|
||||
# Archive1 has Archive2 as alternative.
|
||||
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['alternatives'][0]['archive']['id'] == archive2.id
|
||||
|
||||
# Archive2 has Archive1 as alternative.
|
||||
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['alternatives'][0]['archive']['id'] == archive1.id
|
||||
|
||||
# Only one domain.
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'][0]['domain'] == 'example.com'
|
||||
|
||||
# Deleting works.
|
||||
request, response = test_client.delete(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
|
||||
# Trying to delete again returns NOT_FOUND.
|
||||
request, response = test_client.delete(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
# Can't get deleted Archive.
|
||||
request, response = test_client.get(f'/api/archive/{archive1.id}')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
# Archive2 no longer has alternatives.
|
||||
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['alternatives'] == []
|
||||
|
||||
# No Archives, no Domains.
|
||||
request, response = test_client.delete(f'/api/archive/{archive2.id}')
|
||||
assert response.status_code == HTTPStatus.NO_CONTENT
|
||||
request, response = test_client.get(f'/api/archive/domains')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['domains'] == []
|
||||
|
|
|
|||
|
|
@ -1,17 +1,18 @@
|
|||
import json
|
||||
import pathlib
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
|
||||
import mock
|
||||
import pytest
|
||||
|
||||
from modules.archive import lib
|
||||
from modules.archive.lib import get_or_create_domain, _refresh_archives, \
|
||||
get_new_archive_files, delete_archive, do_archive, get_domains, get_archive_directory, group_archive_files, \
|
||||
ArchiveFiles
|
||||
from modules.archive.lib import get_or_create_domain, get_new_archive_files, delete_archive, do_archive, get_domains, \
|
||||
group_archive_files, ArchiveFiles
|
||||
from modules.archive.models import Archive, Domain
|
||||
from wrolpi.dates import local_timezone
|
||||
from wrolpi.db import get_db_session
|
||||
from wrolpi.files.models import File
|
||||
from wrolpi.media_path import MediaPath
|
||||
from wrolpi.root_api import CustomJSONEncoder
|
||||
from wrolpi.test.common import skip_circleci
|
||||
|
|
@ -35,8 +36,8 @@ def make_fake_request_archive(readability=True, screenshot=True, title=True):
|
|||
async def test_no_screenshot(test_session):
|
||||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(screenshot=False)):
|
||||
archive = await do_archive('https://example.com')
|
||||
assert isinstance(archive.singlefile_path, MediaPath)
|
||||
assert isinstance(archive.readability_path, MediaPath)
|
||||
assert isinstance(archive.singlefile_path, pathlib.Path)
|
||||
assert isinstance(archive.readability_path, pathlib.Path)
|
||||
# Screenshot was empty
|
||||
assert archive.screenshot_path is None
|
||||
|
||||
|
|
@ -45,8 +46,8 @@ async def test_no_screenshot(test_session):
|
|||
async def test_no_readability(test_session):
|
||||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive(readability=False)):
|
||||
archive = await do_archive('https://example.com')
|
||||
assert isinstance(archive.singlefile_path, MediaPath)
|
||||
assert isinstance(archive.screenshot_path, MediaPath)
|
||||
assert isinstance(archive.singlefile_path, pathlib.Path)
|
||||
assert isinstance(archive.screenshot_path, pathlib.Path)
|
||||
# Readability empty
|
||||
assert archive.readability_path is None
|
||||
assert archive.readability_txt_path is None
|
||||
|
|
@ -66,7 +67,7 @@ async def test_relationships(test_session, test_directory):
|
|||
url = 'https://wrolpi.org:443'
|
||||
domain = get_or_create_domain(session, url)
|
||||
archive = Archive(
|
||||
singlefile_path=f'{test_directory.name}/wrolpi.org:443/foo',
|
||||
singlefile_file=File(path=test_directory / 'wrolpi.org:443/foo'),
|
||||
title='bar',
|
||||
url=url,
|
||||
domain_id=domain.id,
|
||||
|
|
@ -77,18 +78,7 @@ async def test_relationships(test_session, test_directory):
|
|||
assert archive.domain == domain
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_validate_paths(test_session):
|
||||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
|
||||
archive = await do_archive('https://example.com')
|
||||
try:
|
||||
with get_db_session(commit=True):
|
||||
archive.singlefile_path = 'asdf'
|
||||
except ValueError as e:
|
||||
assert 'relative' in str(e), f'Relative path error was not raised'
|
||||
|
||||
|
||||
def test_archive_refresh_deleted_archive(test_session, archive_directory, archive_factory):
|
||||
def test_archive_refresh_deleted_archive(test_client, test_session, archive_directory, archive_factory):
|
||||
"""
|
||||
Archives/Domains should be deleted when archive files are deleted.
|
||||
"""
|
||||
|
|
@ -97,58 +87,58 @@ def test_archive_refresh_deleted_archive(test_session, archive_directory, archiv
|
|||
archive3 = archive_factory('example.com')
|
||||
archive4 = archive_factory('example.org')
|
||||
archive5 = archive_factory()
|
||||
test_session.commit()
|
||||
|
||||
# Empty directories should be ignored.
|
||||
empty = archive_directory / 'empty'
|
||||
empty.mkdir()
|
||||
(archive_directory / 'empty').mkdir()
|
||||
|
||||
def check_counts(archive_count, domain_count):
|
||||
assert test_session.query(Archive).count() == archive_count
|
||||
assert test_session.query(Domain).count() == domain_count
|
||||
assert test_session.query(Archive).count() == archive_count, 'Archive count does not match'
|
||||
assert test_session.query(Domain).count() == domain_count, 'Domain count does not match'
|
||||
|
||||
# All 3 archives are already in the DB.
|
||||
check_counts(archive_count=5, domain_count=3)
|
||||
_refresh_archives()
|
||||
check_counts(archive_count=5, domain_count=3)
|
||||
# All 5 archives are already in the DB.
|
||||
check_counts(archive_count=5, domain_count=2)
|
||||
test_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=5, domain_count=1)
|
||||
|
||||
# Delete archive2's files, it's the latest for 'https://example.com/1'
|
||||
for path in archive2.my_paths():
|
||||
for path in archive2.my_files():
|
||||
path.unlink()
|
||||
_refresh_archives()
|
||||
check_counts(archive_count=4, domain_count=3)
|
||||
test_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=4, domain_count=1)
|
||||
|
||||
# Delete archive1's files, now the URL is empty.
|
||||
for path in archive1.my_paths():
|
||||
for path in archive1.my_files():
|
||||
path.unlink()
|
||||
_refresh_archives()
|
||||
check_counts(archive_count=3, domain_count=3)
|
||||
test_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=3, domain_count=0)
|
||||
|
||||
# Delete archive3, now there is now example.com domain
|
||||
for path in archive3.my_paths():
|
||||
for path in archive3.my_files():
|
||||
path.unlink()
|
||||
_refresh_archives()
|
||||
check_counts(archive_count=2, domain_count=2)
|
||||
test_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=2, domain_count=0)
|
||||
|
||||
# Delete all the rest of the archives
|
||||
for path in archive4.my_paths():
|
||||
for path in archive4.my_files():
|
||||
path.unlink()
|
||||
for path in archive5.my_paths():
|
||||
for path in archive5.my_files():
|
||||
path.unlink()
|
||||
_refresh_archives()
|
||||
test_client.post('/api/files/refresh')
|
||||
check_counts(archive_count=0, domain_count=0)
|
||||
|
||||
|
||||
def test_fills_contents_with_refresh(test_session, archive_factory, test_client):
|
||||
def test_fills_contents_with_refresh(test_client, test_session, archive_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')
|
||||
archive3 = archive_factory('example.org')
|
||||
# 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>')
|
||||
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
|
||||
# Title can be found in archive3's singlefile
|
||||
archive3.singlefile_path.path.write_text('<html> some stuff<title>last title</title> other stuff</html>')
|
||||
|
||||
contents_title_archive = [
|
||||
('foo bar qux', 'my archive', archive1),
|
||||
|
|
@ -156,26 +146,26 @@ def test_fills_contents_with_refresh(test_session, archive_factory, test_client)
|
|||
('baz qux qux qux', None, archive3),
|
||||
]
|
||||
for contents, json_title, archive in contents_title_archive:
|
||||
with archive.readability_txt_path.path.open('wt') as fh:
|
||||
with archive.readability_txt_path.open('wt') as fh:
|
||||
fh.write(contents)
|
||||
if json_title:
|
||||
archive.readability_json_path.path.write_text(json.dumps({'title': json_title, 'url': archive.url}))
|
||||
archive.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.contents
|
||||
assert not archive2.contents
|
||||
assert not archive3.contents
|
||||
assert not archive4.contents
|
||||
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
|
||||
|
||||
# Fill the contents.
|
||||
_refresh_archives()
|
||||
test_client.post('/api/files/refresh')
|
||||
# The archives will be renamed with their title.
|
||||
archive1, archive2, archive3, archive4 = test_session.query(Archive).order_by(Archive.id)
|
||||
assert archive1.contents
|
||||
assert archive2.contents
|
||||
assert archive3.contents
|
||||
assert not archive4.contents
|
||||
assert archive1.singlefile_file.title
|
||||
assert archive2.singlefile_file.title
|
||||
assert archive3.singlefile_file.title
|
||||
assert not archive4.singlefile_file.d_text
|
||||
|
||||
# Missing title is filled.
|
||||
assert archive1.title == 'my archive'
|
||||
|
|
@ -207,6 +197,7 @@ def test_get_domains(test_session, archive_factory):
|
|||
archive1 = archive_factory('example.com')
|
||||
archive2 = archive_factory('example.com')
|
||||
archive3 = archive_factory('example.org')
|
||||
test_session.commit()
|
||||
|
||||
assert [i['domain'] for i in get_domains()] == ['example.com', 'example.org']
|
||||
|
||||
|
|
@ -231,22 +222,22 @@ async def test_new_archive(test_session, fake_now):
|
|||
# Everything is filled out.
|
||||
assert isinstance(archive1, Archive)
|
||||
assert archive1.archive_datetime is not None
|
||||
assert isinstance(archive1.singlefile_path, MediaPath)
|
||||
assert isinstance(archive1.readability_path, MediaPath)
|
||||
assert isinstance(archive1.readability_txt_path, MediaPath)
|
||||
assert isinstance(archive1.screenshot_path, MediaPath)
|
||||
assert isinstance(archive1.singlefile_path, pathlib.Path)
|
||||
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.url is not None
|
||||
assert archive1.domain is not None
|
||||
|
||||
# The actual files were dumped and read correctly.
|
||||
with open(archive1.singlefile_path.path) as fh:
|
||||
with open(archive1.singlefile_path) as fh:
|
||||
assert fh.read() == '<html>\ntest single-file\nジにてこちら\n<title>some title</title></html>'
|
||||
with open(archive1.readability_path.path) as fh:
|
||||
with open(archive1.readability_path) as fh:
|
||||
assert fh.read() == '<html>test readability content</html>'
|
||||
with open(archive1.readability_txt_path.path) as fh:
|
||||
with open(archive1.readability_txt_path) as fh:
|
||||
assert fh.read() == '<html>test readability textContent</html>'
|
||||
with open(archive1.readability_json_path.path) as fh:
|
||||
with open(archive1.readability_json_path) as fh:
|
||||
assert json.load(fh) == {'title': 'ジにてこちら', 'url': 'https://example.com'}
|
||||
|
||||
fake_now(datetime(2000, 1, 2))
|
||||
|
|
@ -259,7 +250,7 @@ async def test_new_archive(test_session, fake_now):
|
|||
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('example.com')
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title == 'ジにてこちら'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
|
|
@ -273,7 +264,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('example.com')
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title == 'some title'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
|
|
@ -287,7 +278,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('example.com')
|
||||
archive = await do_archive('https://example.com')
|
||||
assert archive.title is None
|
||||
|
||||
|
||||
|
|
@ -321,20 +312,20 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
fake_now(datetime(2000, 1, 1))
|
||||
|
||||
with mock.patch('modules.archive.lib.request_archive', make_fake_request_archive()):
|
||||
archive1 = await do_archive('example.com')
|
||||
archive1 = await do_archive('https://example.com')
|
||||
|
||||
assert archive1.title == 'ジにてこちら'
|
||||
|
||||
assert str(archive1.singlefile_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_ジにてこちら.html'
|
||||
assert str(archive1.readability_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_ジにてこちら.readability.html'
|
||||
assert str(archive1.readability_txt_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_ジにてこちら.readability.txt'
|
||||
assert str(archive1.readability_json_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_ジにてこちら.readability.json'
|
||||
assert str(archive1.screenshot_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_ジにてこちら.png'
|
||||
assert str(archive1.singlefile_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.html'
|
||||
assert str(archive1.readability_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.readability.html'
|
||||
assert str(archive1.readability_txt_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.readability.txt'
|
||||
assert str(archive1.readability_json_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.readability.json'
|
||||
assert str(archive1.screenshot_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_ジにてこちら.png'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
singlefile = '<html>\ntest single-file\nジにてこちら\n</html>' # no title in HTML
|
||||
|
|
@ -347,18 +338,18 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
return singlefile, r, s
|
||||
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
archive2 = await do_archive('example.com')
|
||||
archive2 = await do_archive('https://example.com')
|
||||
|
||||
assert str(archive2.singlefile_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_NA.html'
|
||||
assert str(archive2.readability_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_NA.readability.html'
|
||||
assert str(archive2.readability_txt_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_NA.readability.txt'
|
||||
assert str(archive2.readability_json_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_NA.readability.json'
|
||||
assert str(archive2.screenshot_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_NA.png'
|
||||
assert str(archive2.singlefile_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.html'
|
||||
assert str(archive2.readability_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.readability.html'
|
||||
assert str(archive2.readability_txt_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.readability.txt'
|
||||
assert str(archive2.readability_json_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.readability.json'
|
||||
assert str(archive2.screenshot_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.png'
|
||||
|
||||
async def fake_request_archive(_):
|
||||
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>dangerous ;\\//_title</html></html>'
|
||||
|
|
@ -371,62 +362,101 @@ async def test_title_in_filename(test_session, fake_now, test_directory):
|
|||
return singlefile, r, s
|
||||
|
||||
with mock.patch('modules.archive.lib.request_archive', fake_request_archive):
|
||||
archive3 = await do_archive('example.com')
|
||||
archive3 = await do_archive('https://example.com')
|
||||
|
||||
assert str(archive3.singlefile_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_dangerous ;_title.html'
|
||||
assert str(archive3.readability_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_dangerous ;_title.readability.html'
|
||||
assert str(archive3.readability_txt_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_dangerous ;_title.readability.txt'
|
||||
assert str(archive3.readability_json_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_dangerous ;_title.readability.json'
|
||||
assert str(archive3.screenshot_path.path.relative_to(test_directory)) == \
|
||||
'archive/2000-01-01-00-00-00_dangerous ;_title.png'
|
||||
assert str(archive3.singlefile_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.html'
|
||||
assert str(archive3.readability_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.readability.html'
|
||||
assert str(archive3.readability_txt_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.readability.txt'
|
||||
assert str(archive3.readability_json_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.readability.json'
|
||||
assert str(archive3.screenshot_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;_title.png'
|
||||
|
||||
|
||||
@skip_circleci
|
||||
def test_refresh_archives(test_session, test_directory):
|
||||
"""Archives can be found and put in the database. A single Archive will have multiple files."""
|
||||
archive_directory = get_archive_directory()
|
||||
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.
|
||||
"""
|
||||
# The start of a typical singlefile html file.
|
||||
singlefile_contents = '''<!DOCTYPE html> <html lang="en"><!--
|
||||
Page saved with SingleFile
|
||||
url: https://example.com
|
||||
saved date: Mon May 16 2022 23:51:35 GMT+0000 (Coordinated Universal Time)
|
||||
--><head><meta charset="utf-8">'''
|
||||
|
||||
# Make some test files to refresh.
|
||||
example_dir = archive_directory / 'example.com'
|
||||
example_dir.mkdir()
|
||||
(example_dir / '2021-10-05 16:20:10.346823.html').touch() # renames to 2021-10-05-16-20-10_NA.html
|
||||
(example_dir / '2021-10-05 16:20:10.346823.png').touch()
|
||||
(example_dir / '2021-10-05 16:20:10.346823-readability.txt').touch()
|
||||
(example_dir / '2021-10-05 16:20:10.346823-readability.json').touch()
|
||||
(example_dir / '2021-10-05 16:20:10.346823-readability.html').touch()
|
||||
with (example_dir / '2021-10-05 16:20:10.346823-readability.json').open('wt') as fh:
|
||||
json.dump({'url': 'foo'}, fh)
|
||||
|
||||
# These should log an error because they are missing the singlefile path.
|
||||
(example_dir / '2021-10-05 16:20:10.readability.html').touch()
|
||||
(example_dir / '2021-10-05 16:20:11.readability.json').touch()
|
||||
# Bad files should also be ignored.
|
||||
(example_dir / 'random file').touch()
|
||||
(example_dir / '2021-10-05 16:20:10.346827-something.html').mkdir()
|
||||
(example_dir / '2021-10-05 16:20:10 no extension').touch()
|
||||
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>',
|
||||
# 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,
|
||||
# Bad files should also be ignored.
|
||||
'archive/example.com/random file': 'hello',
|
||||
'archive/example.com/2021-10-05 16:20:10 no extension': None,
|
||||
})
|
||||
|
||||
# The single archive is found.
|
||||
_refresh_archives()
|
||||
with get_db_session() as session:
|
||||
assert session.query(Archive).count() == 1
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(Archive).count() == 1
|
||||
|
||||
# Running the refresh does not result in a new archive.
|
||||
_refresh_archives()
|
||||
with get_db_session() as session:
|
||||
assert session.query(Archive).count() == 1
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(Archive).count() == 1
|
||||
|
||||
# Archives file format was changed, lets check the new formats are found.
|
||||
(example_dir / '2021-10-05-16-20-11_The Title.html').touch()
|
||||
(example_dir / '2021-10-05-16-20-11_The Title.readability.json').write_text(json.dumps({'url': 'bar'}))
|
||||
_refresh_archives()
|
||||
make_files_structure({
|
||||
'archive/example.com/2021-10-05-16-20-11_The Title.html': '<html></html>',
|
||||
'archive/example.com/2021-10-05-16-20-11_The Title.readability.json': '{"url": "https://example.com"}',
|
||||
})
|
||||
test_client.post('/api/files/refresh')
|
||||
# The old formatted archive above is renamed.
|
||||
assert (example_dir / '2021-10-05-16-20-10_NA.html').is_file()
|
||||
with get_db_session() as session:
|
||||
assert session.query(Archive).count() == 2
|
||||
assert (test_directory / 'archive/example.com/2021-10-05-16-20-10_NA.html').is_file()
|
||||
assert test_session.query(Archive).count() == 2
|
||||
|
||||
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', \
|
||||
'Could not find readability text file containing "text"'
|
||||
assert response.json['files'][0]['archive']['archive_datetime'], 'Archive has no datetime'
|
||||
|
||||
|
||||
def test_refresh_archives_invalid_file(test_session, test_directory, test_client, make_files_structure):
|
||||
"""
|
||||
Invalid Archives should be removed during refresh.
|
||||
"""
|
||||
*_, bogus_path = make_files_structure({
|
||||
'2022-09-04-16-20-11_The Title.html': '<html></html>',
|
||||
'2022-09-04-16-20-11_The Title.readability.json': '{"url": "https://example.com"}',
|
||||
'bogus file': None,
|
||||
})
|
||||
test_client.post('/api/files/refresh')
|
||||
assert test_session.query(File).count() == 3 # Three files total.
|
||||
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.model = 'archive'
|
||||
test_session.commit()
|
||||
assert test_session.query(File).count() == 3
|
||||
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(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):
|
||||
|
|
@ -488,9 +518,10 @@ def test_migrate_archive_files(test_session, archive_directory, archive_factory)
|
|||
archive1 = archive_factory('example.com', title='the title')
|
||||
archive2 = archive_factory('example.com')
|
||||
archive3 = archive_factory('example.org')
|
||||
assert archive1.singlefile_path.path.is_file()
|
||||
assert archive2.singlefile_path.path.is_file()
|
||||
assert archive3.singlefile_path.path.is_file()
|
||||
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'
|
||||
|
|
@ -532,6 +563,25 @@ def test_migrate_archive_files(test_session, archive_directory, archive_factory)
|
|||
'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())
|
||||
assert all(i.is_file() for i in archive1.my_files())
|
||||
assert all(i.is_file() for i in archive2.my_files())
|
||||
assert all(i.is_file() for i in archive3.my_files())
|
||||
|
||||
|
||||
def test_archive_files(test_directory):
|
||||
af = lib.ArchiveFiles(
|
||||
singlefile=test_directory / 'archive/singlefile.html',
|
||||
)
|
||||
assert repr(af) == \
|
||||
"<ArchiveFiles singlefile='singlefile.html' readability=None readability_txt=None readability_json=None" \
|
||||
" screenshot=None>"
|
||||
|
||||
|
||||
def test_archive_order(test_session, test_directory, archive_factory):
|
||||
archive1 = archive_factory()
|
||||
archive2 = archive_factory()
|
||||
archive2.archive_datetime += timedelta(seconds=10)
|
||||
test_session.commit()
|
||||
|
||||
assert archive2 > archive1
|
||||
assert archive1 < archive2
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue