Archive files are migrated to new format.

This commit is contained in:
Roland 2022-02-02 20:43:11 -07:00
parent 8d3f65425a
commit 7b1c07f076
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
4 changed files with 311 additions and 138 deletions

View file

@ -5,8 +5,9 @@ from uuid import uuid4
import pytest
from modules.archive.lib import archive_strftime
from modules.archive.models import Archive, Domain
from wrolpi.dates import strftime_ms
from wrolpi.dates import local_timezone
@pytest.fixture
@ -26,7 +27,7 @@ def archive_factory(test_session, archive_directory):
now = time_generator()
def _(domain: str = None, url: str = None, title: str = None, contents: str = None) -> Archive:
def _(domain: str = None, url: str = None, title: str = 'NA', contents: str = None) -> Archive:
if domain:
assert '/' not in domain
@ -36,13 +37,14 @@ def archive_factory(test_session, archive_directory):
domain_dir = archive_directory / domain_dir
domain_dir.mkdir(exist_ok=True)
timestamp = strftime_ms(next(now))
archive_datetime = local_timezone(next(now))
timestamp = archive_strftime(archive_datetime)
singlefile_path = domain_dir / f'{timestamp}.html'
screenshot_path = domain_dir / f'{timestamp}.png'
readability_path = domain_dir / f'{timestamp}-readability.html'
readability_txt_path = domain_dir / f'{timestamp}-readability.txt'
readability_json_path = domain_dir / f'{timestamp}-readability.json'
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)
@ -68,7 +70,7 @@ def archive_factory(test_session, archive_directory):
url=url,
domain_id=domain.id,
contents=contents,
archive_datetime=timestamp,
archive_datetime=archive_datetime,
)
test_session.add(archive)

View file

@ -5,6 +5,7 @@ import pathlib
import re
import subprocess
import tempfile
from dataclasses import dataclass
from datetime import datetime
from itertools import groupby
from typing import Iterator, Optional
@ -26,6 +27,26 @@ logger = logger.getChild(__name__)
ARCHIVE_SERVICE = 'http://archive:8080'
@dataclass
class ArchiveFiles:
"""Every Archive will have some of these files."""
singlefile: pathlib.Path = None
readability: pathlib.Path = None
readability_txt: pathlib.Path = None
readability_json: pathlib.Path = None
screenshot: pathlib.Path = None
def __repr__(self):
singlefile = str(self.singlefile.relative_to(get_archive_directory())) if self.singlefile else None
readability = str(self.readability.relative_to(get_archive_directory())) if self.readability else None
readability_txt = str(
self.readability_txt.relative_to(get_archive_directory())) if self.readability_txt else None
readability_json = str(
self.readability_json.relative_to(get_archive_directory())) if self.readability_json else None
screenshot = str(self.screenshot.relative_to(get_archive_directory())) if self.screenshot else None
return f'<ArchiveFiles {singlefile=} {readability=} {readability_txt=} {readability_json=} {screenshot=}>'
def get_archive_directory() -> pathlib.Path:
archive_directory = get_media_directory() / 'archive'
if not archive_directory.is_dir():
@ -48,28 +69,36 @@ def get_domain_directory(url: str) -> pathlib.Path:
return directory
def get_new_archive_files(url: str, title: Optional[str]):
def get_new_archive_files(url: str, title: Optional[str]) -> ArchiveFiles:
"""
Create a list of archive files using a shared name schema. Raise an error if any of them exist.
"""
directory = get_domain_directory(url)
dt = now().strftime('%Y-%m-%d-%H-%M-%S')
# Datetime is valid in Linux and Windows.
dt = archive_strftime(now())
title = escape_file_name(title or 'NA')
prefix = f'{dt}_{title}'
singlefile_path = directory / f'{prefix}.html'
readability_path = directory / f'{prefix}-readability.html'
readability_txt_path = directory / f'{prefix}-readability.txt'
readability_json_path = directory / f'{prefix}-readability.json'
readability_path = directory / f'{prefix}.readability.html'
readability_txt_path = directory / f'{prefix}.readability.txt'
readability_json_path = directory / f'{prefix}.readability.json'
screenshot_path = directory / f'{prefix}.png'
ret = (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)
paths = (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)
for path in ret:
for path in paths:
if path.exists():
raise FileExistsError(f'New archive file already exists: {path}')
return ret
archive_files = ArchiveFiles(
singlefile_path,
readability_path,
readability_txt_path,
readability_json_path,
screenshot_path,
)
return archive_files
ARCHIVE_TIMEOUT = Seconds.minute * 10 # Wait at most 10 minutes for response.
@ -120,9 +149,7 @@ def request_archive(url: str):
def local_singlefile(url: str):
"""
Run the single-file executable to create an HTML file archive.
"""
"""Run the single-file executable to create an HTML file archive."""
single_file_path = pathlib.Path('/usr/bin/single-file')
if not single_file_path.is_file():
raise FileNotFoundError(f'single-file not found at {single_file_path}')
@ -139,9 +166,7 @@ def local_singlefile(url: str):
def local_screenshot(url: str) -> bytes:
"""
Take a screenshot of the URL using selenium.
"""
"""Take a screenshot of the URL using selenium."""
logger.info(f'Screenshot: {url}')
# Set Chromium to headless. Use a wide window size so that screenshot will be the "desktop" version of the page.
@ -161,9 +186,7 @@ def local_screenshot(url: str) -> bytes:
def local_extract_readability(path: str, url: str) -> dict:
"""
Extract the readability from an HTML file, typically from single-file.
"""
"""Extract the readability from an HTML file, typically from single-file."""
logger.info(f'readability for {url}')
readability_path = pathlib.Path('/usr/bin/readability-extractor')
if not readability_path.is_file():
@ -178,9 +201,7 @@ def local_extract_readability(path: str, url: str) -> dict:
def local_archive(url: str):
"""
Perform an archive of the provided URL using local resources (without the Archive docker container).
"""
"""Perform an archive of the provided URL using local resources (without the Archive docker container)."""
# Archives must be performed in the wrolpi home directory because chrome saves the screenshot there, and will
# raise an error if global $HOME is not a real user directory. :(
with chdir('/home/wrolpi', with_home=True):
@ -217,33 +238,32 @@ def do_archive(url: str) -> Archive:
# Readability could not find title, lets use ours.
readability['title'] = title
singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path = \
get_new_archive_files(url, title)
archive_files = get_new_archive_files(url, title)
if readability:
# Write the readability parts to their own files. Write what is left after pops to the JSON file.
with readability_path.open('wt') as fh:
with archive_files.readability.open('wt') as fh:
fh.write(readability.pop('content'))
with readability_txt_path.open('wt') as fh:
with archive_files.readability_txt.open('wt') as fh:
readability_txt = readability.pop('textContent')
fh.write(readability_txt)
else:
# No readability was returned, so there are no files.
readability_txt = readability_path = readability_txt_path = None
readability_txt = archive_files.readability_txt = archive_files.readability = None
# Store the single-file HTML in its own file.
with singlefile_path.open('wt') as fh:
with archive_files.singlefile.open('wt') as fh:
fh.write(singlefile)
if screenshot:
with screenshot_path.open('wb') as fh:
with archive_files.screenshot.open('wb') as fh:
fh.write(screenshot)
else:
screenshot_path = None
archive_files.screenshot = None
# Always write a JSON file that contains at least the URL.
readability = readability or {}
readability['url'] = url
with readability_json_path.open('wt') as fh:
with archive_files.readability_json.open('wt') as fh:
fh.write(json.dumps(readability))
with get_db_session(commit=True) as session:
@ -251,11 +271,11 @@ def do_archive(url: str) -> Archive:
archive = Archive(
title=title,
archive_datetime=now(),
singlefile_path=singlefile_path,
readability_path=readability_path,
readability_json_path=readability_json_path,
readability_txt_path=readability_txt_path,
screenshot_path=screenshot_path,
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,
url=url,
domain_id=domain.id,
@ -317,6 +337,10 @@ def archive_strptime(dt: str) -> datetime:
return local_timezone(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.
@ -333,32 +357,92 @@ def group_archive_files(files: Iterator[pathlib.Path]) -> groupby:
continue
# Sort the files into their respective slots.
singlefile_path = readability_path = readability_txt_path = readability_json_path = screenshot_path = None
archive_files = ArchiveFiles()
file = None
for file in files:
if file.name.endswith('-readability.html'):
readability_path = file
elif file.name.endswith('.html'):
singlefile_path = file
elif file.name.endswith('.png') or file.name.endswith('.jpg') or file.name.endswith('.jpeg'):
screenshot_path = file
elif file.name.endswith('-readability.json'):
readability_json_path = file
elif file.name.endswith('-readability.txt'):
readability_txt_path = file
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 singlefile_path:
if not archive_files.singlefile:
logger.warning(f'Archive does not have a singlefile html! Ignoring. {file}')
continue
if not readability_json_path:
if not archive_files.readability_json:
logger.warning(f'Archive does not have a json file! Ignoring. {file}')
continue
yield dt, (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)
yield dt, archive_files
ARCHIVE_MATCHER = re.compile(r'\d{4}-\d\d-\d\d (\d\d:){2}\d\d\.\d{6}.*$')
NEW_ARCHIVE_MATCHER = re.compile(r'\d{4}-(\d{2}-){4}\d\d_.*$')
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')
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'}
@ -367,13 +451,7 @@ 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
"""
if not path.is_file():
return False
if path.suffix.lower() not in ARCHIVE_SUFFIXES:
return False
if bool(ARCHIVE_MATCHER.match(path.name)) or bool(NEW_ARCHIVE_MATCHER.match(path.name)):
return True
return False
return path.is_file() and path.suffix.lower() in ARCHIVE_SUFFIXES and bool(ARCHIVE_MATCHER.match(path.name))
def _refresh_archives():
@ -383,18 +461,22 @@ def _refresh_archives():
"""
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}')
archives_files = filter(is_archive_file, walk(domain_directory))
archive_groups = group_archive_files(archives_files)
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, files in chunk:
for dt, archive_files in chunk:
archive_count += 1
singlefile_paths.add(str(files[0]))
upsert_archive(dt, files, session)
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}')
@ -428,14 +510,11 @@ async def refresh_archives():
_refresh_archives()
def upsert_archive(dt: str, files, session: Session):
"""
Get or create an Archive and it's URL/Domain. If it already exists, update it with these new files.
"""
singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path = files
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 readability_json_path.open() as fh:
with archive_files.readability_json.open() as fh:
json_contents = json.load(fh)
url = json_contents['url']
except Exception as e:
@ -443,23 +522,20 @@ def upsert_archive(dt: str, files, session: Session):
domain = get_or_create_domain(session, url)
# Get the existing Archive, or create a new one.
archive = session.query(Archive).filter_by(singlefile_path=singlefile_path).one_or_none()
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,
)
archive = Archive(url=url, domain_id=domain.id)
session.add(archive)
session.flush()
# Update the archive with the files that we have.
archive.archive_datetime = dt
archive.singlefile_path = singlefile_path
archive.readability_path = readability_path
archive.readability_txt_path = readability_txt_path
archive.readability_json_path = readability_json_path
archive.screenshot_path = screenshot_path
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
def get_domains():

View file

@ -3,9 +3,12 @@ import pathlib
from datetime import datetime
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
get_new_archive_files, delete_archive, do_archive, get_domains, get_archive_directory, group_archive_files, \
ArchiveFiles
from modules.archive.models import Archive, Domain
from wrolpi.dates import local_timezone
from wrolpi.db import get_db_session
@ -137,7 +140,7 @@ def test_archive_refresh_deleted_archive(test_session, archive_directory, archiv
check_counts(archive_count=0, domain_count=0)
def test_refresh_archives_fills_contents(test_session, archive_factory, test_client):
def test_fills_contents_with_refresh(test_session, archive_factory, test_client):
"""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')
@ -163,6 +166,8 @@ def test_refresh_archives_fills_contents(test_session, archive_factory, test_cli
# Fill the contents.
_refresh_archives()
# 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
@ -278,20 +283,21 @@ def test_get_title_from_html(test_session, fake_now):
def test_get_new_archive_files(fake_now):
"""Archive files have a specific format so they are sorted by datetime, and are near each other."""
fake_now(datetime(2001, 1, 1))
s, r, t, j, c = map(str, get_new_archive_files('https://example.com/two', None))
assert str(s).endswith('archive/example.com/2001-01-01-00-00-00_NA.html')
assert str(r).endswith('archive/example.com/2001-01-01-00-00-00_NA-readability.html')
assert str(t).endswith('archive/example.com/2001-01-01-00-00-00_NA-readability.txt')
assert str(j).endswith('archive/example.com/2001-01-01-00-00-00_NA-readability.json')
assert str(c).endswith('archive/example.com/2001-01-01-00-00-00_NA.png')
archive_files = get_new_archive_files('https://example.com/two', None)
assert str(archive_files.singlefile).endswith('archive/example.com/2001-01-01-00-00-00_NA.html')
assert str(archive_files.readability).endswith('archive/example.com/2001-01-01-00-00-00_NA.readability.html')
assert str(archive_files.readability_txt).endswith('archive/example.com/2001-01-01-00-00-00_NA.readability.txt')
assert str(archive_files.readability_json).endswith('archive/example.com/2001-01-01-00-00-00_NA.readability.json')
assert str(archive_files.screenshot).endswith('archive/example.com/2001-01-01-00-00-00_NA.png')
s, r, t, j, c = get_new_archive_files('https://www.example.com/one', 'Title')
archive_files = get_new_archive_files('https://www.example.com/one', 'Title')
# Leading www. is removed.
assert str(s).endswith('archive/example.com/2001-01-01-00-00-00_Title.html')
assert str(r).endswith('archive/example.com/2001-01-01-00-00-00_Title-readability.html')
assert str(t).endswith('archive/example.com/2001-01-01-00-00-00_Title-readability.txt')
assert str(j).endswith('archive/example.com/2001-01-01-00-00-00_Title-readability.json')
assert str(c).endswith('archive/example.com/2001-01-01-00-00-00_Title.png')
assert str(archive_files.singlefile).endswith('archive/example.com/2001-01-01-00-00-00_Title.html')
assert str(archive_files.readability).endswith('archive/example.com/2001-01-01-00-00-00_Title.readability.html')
assert str(archive_files.readability_txt).endswith('archive/example.com/2001-01-01-00-00-00_Title.readability.txt')
assert str(archive_files.readability_json).endswith(
'archive/example.com/2001-01-01-00-00-00_Title.readability.json')
assert str(archive_files.screenshot).endswith('archive/example.com/2001-01-01-00-00-00_Title.png')
def test_title_in_filename(test_session, fake_now, test_directory):
@ -308,11 +314,11 @@ def test_title_in_filename(test_session, fake_now, test_directory):
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'
'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'
'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'
'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'
@ -332,11 +338,11 @@ def test_title_in_filename(test_session, fake_now, test_directory):
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'
'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'
'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'
'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'
@ -356,11 +362,11 @@ def test_title_in_filename(test_session, fake_now, test_directory):
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'
'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'
'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'
'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'
@ -370,24 +376,25 @@ def test_refresh_archives(test_session, test_directory):
archive_directory = get_archive_directory()
# Make some test files to refresh.
example = archive_directory / 'example.com'
example.mkdir()
(example / '2021-10-05 16:20:10.346823.html').touch()
(example / '2021-10-05 16:20:10.346823.png').touch()
(example / '2021-10-05 16:20:10.346823-readability.txt').touch()
(example / '2021-10-05 16:20:10.346823-readability.json').touch()
(example / '2021-10-05 16:20:10.346823-readability.html').touch()
with (example / '2021-10-05 16:20:10.346823-readability.json').open('wt') as fh:
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 / '2021-10-05 16:20:10-readability.html').touch()
(example / '2021-10-05 16:20:11-readability.json').touch()
(example / 'random file').touch()
(example / '2021-10-05 16:20:10.346827-something.html').mkdir()
(example / '2021-10-05 16:20:10 no extension').touch()
(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()
# This single archive is found.
# The single archive is found.
_refresh_archives()
with get_db_session() as session:
assert session.query(Archive).count() == 1
@ -398,28 +405,116 @@ def test_refresh_archives(test_session, test_directory):
assert session.query(Archive).count() == 1
# Archives file format was changed, lets check the new formats are found.
(example / '2021-10-05-16-20-10_The Title.html').touch()
(example / '2021-10-05-16-20-10_The Title-readability.json').write_text(json.dumps({'url': 'bar'}))
(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()
# 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
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('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('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)) == [
(local_timezone(datetime(2000, 1, 1, 0, 0, 0)),
(
pathlib.Path('2000-01-01-00-00-00_Title.html'), None, None,
pathlib.Path('2000-01-01-00-00-00_Title-readability.json'), None,
)),
(local_timezone(datetime(2021, 10, 5, 16, 20, 10)),
(
pathlib.Path('2021-10-05 16:20:10.346823.html'), None, None,
pathlib.Path('2021-10-05 16:20:10.346823-readability.json'), None)),
(local_timezone(datetime(2000, 1, 1, 0, 0, 0)), group1),
(local_timezone(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
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')
assert archive1.singlefile_path.path.is_file()
assert archive2.singlefile_path.path.is_file()
assert archive3.singlefile_path.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': 'invalid#*: title'}))
# 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_invalid# title.html')),
(pathlib.Path('example.org/2000-01-01 00:00:00.000000.readability.json'),
pathlib.Path('example.org/2000-01-01-00-00-00_invalid# title.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())

View file

@ -641,7 +641,7 @@ def zig_zag(low: ZIG_TYPE, high: ZIG_TYPE) -> Generator[ZIG_TYPE, None, None]:
def walk(path: Path) -> Generator[Path, None, None]:
"""Walk a directory structure yielding all files and directories."""
"""Recursively Walk a directory structure yielding all files and directories."""
for path in path.iterdir():
yield path
if path.is_dir():