mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 17:36:18 -05:00
Allowing user to configure collection download destination directories, as well as directories in the file structure. This will allow sorting archives by destination year, for example.
This commit is contained in:
parent
3f4d5798e2
commit
1ebcae0965
21 changed files with 780 additions and 160 deletions
|
|
@ -49,12 +49,13 @@ class ArchiveDownloader(Downloader, ABC):
|
|||
if download.settings and download.settings.get('destination'):
|
||||
destination = pathlib.Path(download.settings['destination'])
|
||||
|
||||
# If no destination provided, look up the domain collection's directory
|
||||
# If no destination provided, use the domain collection's directory
|
||||
# get_or_set_directory will format from template and save on first use
|
||||
if not destination:
|
||||
with get_db_session() as session:
|
||||
with get_db_session(commit=True) as session:
|
||||
collection = lib.get_or_create_domain_collection(session, download.url)
|
||||
if collection and collection.directory:
|
||||
destination = collection.directory
|
||||
if collection:
|
||||
destination = collection.get_or_set_directory(session)
|
||||
|
||||
if DOCKERIZED or PYTEST:
|
||||
# Perform the archive in the Archive docker container. (Typically in the development environment).
|
||||
|
|
|
|||
|
|
@ -70,6 +70,26 @@ async def search_archives(_: Request, body: schema.ArchiveSearchRequest):
|
|||
return json_response(ret)
|
||||
|
||||
|
||||
@archive_bp.post('/file_format')
|
||||
@openapi.definition(
|
||||
description='Preview the archive file format',
|
||||
body=schema.ArchiveFileFormatRequest,
|
||||
)
|
||||
@validate(schema.ArchiveFileFormatRequest)
|
||||
async def post_file_format(_: Request, body: schema.ArchiveFileFormatRequest):
|
||||
try:
|
||||
preview = lib.preview_archive_filename(body.archive_file_format)
|
||||
return json_response(dict(
|
||||
archive_file_format=body.archive_file_format,
|
||||
preview=preview,
|
||||
))
|
||||
except RuntimeError as e:
|
||||
return json_response(dict(
|
||||
error=str(e),
|
||||
archive_file_format=body.archive_file_format,
|
||||
), status=HTTPStatus.BAD_REQUEST)
|
||||
|
||||
|
||||
@archive_bp.get('/upload')
|
||||
@openapi.definition(
|
||||
summary='A message to confirm to the user that they have the correct upload URL.'
|
||||
|
|
@ -106,7 +126,17 @@ async def singlefile_upload_switch_handler(url=None):
|
|||
logger.info(f'singlefile_upload_switch_handler queue size: {q_size}')
|
||||
|
||||
try:
|
||||
archive = await lib.singlefile_to_archive(singlefile)
|
||||
# Get URL from singlefile to determine destination
|
||||
url = lib.get_url_from_singlefile(singlefile)
|
||||
|
||||
# Get/create domain collection and get/set its directory
|
||||
destination = None
|
||||
with get_db_session(commit=True) as session:
|
||||
collection = lib.get_or_create_domain_collection(session, url)
|
||||
if collection:
|
||||
destination = collection.get_or_set_directory(session)
|
||||
|
||||
archive = await lib.singlefile_to_archive(singlefile, destination=destination)
|
||||
except Exception as e:
|
||||
logger.error(f'singlefile_upload_switch_handler failed', exc_info=e)
|
||||
Events.send_upload_archive_failed(f'Failed to convert singlefile to archive: {e}')
|
||||
|
|
|
|||
|
|
@ -213,6 +213,143 @@ def import_domains_config():
|
|||
logger.info('Importing domains config completed')
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArchiveDownloaderConfigValidator:
|
||||
"""Validator for archives_downloader.yaml config."""
|
||||
file_name_format: str
|
||||
version: int = 0
|
||||
|
||||
def __post_init__(self):
|
||||
# Validate file_name_format contains required %(title)s variable
|
||||
if '%(title)s' not in self.file_name_format:
|
||||
raise ValueError('file_name_format must contain %(title)s')
|
||||
|
||||
|
||||
class ArchiveDownloaderConfig(ConfigFile):
|
||||
"""
|
||||
Config file for Archive Downloader settings.
|
||||
|
||||
This config mirrors videos_downloader.yaml and holds settings for how
|
||||
archives are downloaded and named.
|
||||
|
||||
Format:
|
||||
version: 0
|
||||
file_name_format: '%(download_date)s_%(title)s'
|
||||
|
||||
Variables available in file_name_format:
|
||||
- %(title)s - Page title (extracted from HTML)
|
||||
- %(download_datetime)s - Full download datetime (YYYY-MM-DD-HH-MM-SS)
|
||||
- %(download_date)s - Download date only (YYYY-MM-DD)
|
||||
- %(download_year)s - Download year
|
||||
- %(download_month)s - Download month (zero-padded)
|
||||
- %(download_day)s - Download day (zero-padded)
|
||||
- %(domain)s - Domain name
|
||||
|
||||
Subdirectories can be included in the format, e.g.:
|
||||
'%(download_year)s/%(download_datetime)s_%(title)s'
|
||||
"""
|
||||
file_name = 'archives_downloader.yaml'
|
||||
validator = ArchiveDownloaderConfigValidator
|
||||
default_config = dict(
|
||||
version=0,
|
||||
file_name_format='%(download_datetime)s_%(title)s',
|
||||
)
|
||||
|
||||
@property
|
||||
def file_name_format(self) -> str:
|
||||
return self._config['file_name_format']
|
||||
|
||||
|
||||
# Global instance for archive downloader config
|
||||
ARCHIVE_DOWNLOADER_CONFIG: ArchiveDownloaderConfig = ArchiveDownloaderConfig()
|
||||
|
||||
|
||||
def get_archive_downloader_config() -> ArchiveDownloaderConfig:
|
||||
"""Get the global archive downloader config instance."""
|
||||
return ARCHIVE_DOWNLOADER_CONFIG
|
||||
|
||||
|
||||
def format_archive_filename(
|
||||
title: str,
|
||||
domain: str = None,
|
||||
download_date: datetime = None,
|
||||
) -> str:
|
||||
"""Format archive filename using config template.
|
||||
|
||||
This function formats the filename (and optional subdirectory path) for an archive
|
||||
using the file_name_format from archives_downloader.yaml.
|
||||
|
||||
Args:
|
||||
title: Page title (extracted from HTML)
|
||||
domain: Domain name of the archived URL
|
||||
download_date: Date of download (defaults to now)
|
||||
|
||||
Returns:
|
||||
Formatted filename/path (without .html extension, added later)
|
||||
|
||||
Example:
|
||||
format_archive_filename("My Article", "example.com")
|
||||
# With default format: "2025-12-22_My Article"
|
||||
# With "%(download_year)s/%(title)s": "2025/My Article"
|
||||
"""
|
||||
config = get_archive_downloader_config()
|
||||
template = config.file_name_format
|
||||
|
||||
download_date = download_date or now()
|
||||
|
||||
variables = dict(
|
||||
title=escape_file_name(title) if title else 'untitled',
|
||||
domain=domain or '',
|
||||
download_datetime=archive_strftime(download_date),
|
||||
download_date=download_date.strftime('%Y-%m-%d'),
|
||||
download_year=str(download_date.year),
|
||||
download_month=f'{download_date.month:02d}',
|
||||
download_day=f'{download_date.day:02d}',
|
||||
)
|
||||
|
||||
try:
|
||||
return template % variables
|
||||
except KeyError as e:
|
||||
logger.error(f'Invalid variable in archive file_name_format: {e}')
|
||||
# Fallback to default format
|
||||
return f'{archive_strftime(download_date)}_{escape_file_name(title) if title else "untitled"}'
|
||||
|
||||
|
||||
def preview_archive_filename(file_name_format: str) -> str:
|
||||
"""Preview the archive filename using sample data.
|
||||
|
||||
Args:
|
||||
file_name_format: The format template to preview
|
||||
|
||||
Returns:
|
||||
A preview string showing what the filename would look like
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the format is invalid or missing required variables
|
||||
"""
|
||||
if '%(title)s' not in file_name_format:
|
||||
raise RuntimeError('file_name_format must contain %(title)s')
|
||||
|
||||
sample_date = now()
|
||||
variables = dict(
|
||||
title='Example Page Title',
|
||||
domain='example.com',
|
||||
download_datetime=archive_strftime(sample_date),
|
||||
download_date=sample_date.strftime('%Y-%m-%d'),
|
||||
download_year=str(sample_date.year),
|
||||
download_month=f'{sample_date.month:02d}',
|
||||
download_day=f'{sample_date.day:02d}',
|
||||
)
|
||||
|
||||
try:
|
||||
preview = file_name_format % variables
|
||||
return f'{preview}.html'
|
||||
except KeyError as e:
|
||||
raise RuntimeError(f'Invalid variable: {e}')
|
||||
except ValueError as e:
|
||||
raise RuntimeError(f'Invalid format: {e}')
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArchiveFiles:
|
||||
"""Every Archive will have some of these files."""
|
||||
|
|
@ -241,38 +378,6 @@ def get_archive_directory() -> pathlib.Path:
|
|||
return archive_directory
|
||||
|
||||
|
||||
def get_domain_directory(url: str) -> pathlib.Path:
|
||||
"""Get the archive directory for a particular domain."""
|
||||
domain = extract_domain(url)
|
||||
directory = get_archive_directory() / domain
|
||||
if directory.is_dir():
|
||||
return directory
|
||||
elif directory.exists():
|
||||
raise FileNotFoundError(f'Domain directory {directory} is already a file')
|
||||
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
return directory
|
||||
|
||||
|
||||
def get_archive_destination(domain_collection: 'Collection') -> pathlib.Path:
|
||||
"""
|
||||
Get the destination directory for archives in a domain collection.
|
||||
|
||||
Args:
|
||||
domain_collection: The domain Collection (kind='domain')
|
||||
|
||||
Returns:
|
||||
Path where archives should be placed. If collection has a directory,
|
||||
returns that directory. Otherwise returns the default archives/<domain>/ path.
|
||||
"""
|
||||
if domain_collection.directory:
|
||||
# Restricted collection - use collection directory
|
||||
return get_media_directory() / domain_collection.directory
|
||||
else:
|
||||
# Unrestricted collection - use default archive/<domain>/ path
|
||||
return get_archive_directory() / domain_collection.name
|
||||
|
||||
|
||||
# File names include domain and datetime.
|
||||
MAXIMUM_ARCHIVE_FILE_CHARACTER_LENGTH = 200
|
||||
|
||||
|
|
@ -285,22 +390,35 @@ def get_new_archive_files(url: str, title: Optional[str], destination: pathlib.P
|
|||
title: Title for the archive files
|
||||
destination: Optional directory to save files to. If provided, files go here instead of archive/<domain>
|
||||
"""
|
||||
domain = extract_domain(url)
|
||||
if destination:
|
||||
directory = destination
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
else:
|
||||
directory = get_domain_directory(url)
|
||||
# Datetime is valid in Linux and Windows.
|
||||
dt = archive_strftime(now())
|
||||
# Fallback to archive/<domain>/ when no destination provided
|
||||
directory = get_archive_directory() / domain
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
title = escape_file_name(title or 'NA')
|
||||
# Use the configured file format template
|
||||
title = title or 'NA'
|
||||
title = title[:MAXIMUM_ARCHIVE_FILE_CHARACTER_LENGTH]
|
||||
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'
|
||||
screenshot_path = directory / f'{prefix}.png'
|
||||
prefix = format_archive_filename(title, domain=domain)
|
||||
|
||||
# Handle subdirectories in the format (e.g., "%(download_year)s/%(title)s")
|
||||
if '/' in prefix:
|
||||
# Prefix includes subdirectories, create them relative to base directory
|
||||
full_path = directory / prefix
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
singlefile_path = full_path.with_suffix('.html')
|
||||
readability_path = full_path.parent / f'{full_path.name}.readability.html'
|
||||
readability_txt_path = full_path.parent / f'{full_path.name}.readability.txt'
|
||||
readability_json_path = full_path.parent / f'{full_path.name}.readability.json'
|
||||
screenshot_path = full_path.with_suffix('.png')
|
||||
else:
|
||||
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'
|
||||
screenshot_path = directory / f'{prefix}.png'
|
||||
|
||||
paths = (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)
|
||||
|
||||
|
|
|
|||
|
|
@ -30,3 +30,8 @@ class ArchiveSearchRequest:
|
|||
class ArchiveSearchResponse:
|
||||
file_groups: List[ArchiveDict]
|
||||
totals: dict
|
||||
|
||||
|
||||
@dataclass
|
||||
class ArchiveFileFormatRequest:
|
||||
archive_file_format: str
|
||||
|
|
|
|||
|
|
@ -406,3 +406,42 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
|
|||
request, response = await async_client.post(f'/api/archive/{archive_wrol.id}/generate_screenshot')
|
||||
assert response.status_code == HTTPStatus.FORBIDDEN
|
||||
await wrol_mode_fixture(False)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_file_format_preview(async_client):
|
||||
"""Test the archive file format preview endpoint."""
|
||||
# Test valid format with download_datetime (default format)
|
||||
data = {'archive_file_format': '%(download_datetime)s_%(title)s'}
|
||||
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert 'preview' in response.json
|
||||
assert response.json['preview'].endswith('.html')
|
||||
assert 'Example Page Title' in response.json['preview']
|
||||
# Verify datetime format YYYY-MM-DD-HH-MM-SS
|
||||
import re
|
||||
assert re.search(r'\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}', response.json['preview'])
|
||||
|
||||
# Test valid format with download_date (date only)
|
||||
data = {'archive_file_format': '%(download_date)s_%(title)s'}
|
||||
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert re.search(r'\d{4}-\d{2}-\d{2}_', response.json['preview'])
|
||||
|
||||
# Test format with year subdirectory
|
||||
data = {'archive_file_format': '%(download_year)s/%(download_datetime)s_%(title)s'}
|
||||
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert '/' in response.json['preview'] # Contains subdirectory
|
||||
|
||||
# Test invalid format - missing title
|
||||
data = {'archive_file_format': '%(download_date)s'}
|
||||
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'error' in response.json
|
||||
|
||||
# Test invalid format - unknown variable
|
||||
data = {'archive_file_format': '%(invalid_var)s_%(title)s'}
|
||||
request, response = await async_client.post('/api/archive/file_format', content=json.dumps(data))
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
assert 'error' in response.json
|
||||
|
|
|
|||
|
|
@ -70,10 +70,15 @@ async def test_tag_unrestricted_domain_collection(async_client, test_session, ta
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_domain_collection_moves_files(
|
||||
test_session, archive_factory, tag_factory, test_directory, make_files_structure, archive_directory,
|
||||
await_switches,
|
||||
async_client, test_session, archive_factory, tag_factory, test_directory, make_files_structure,
|
||||
archive_directory, await_switches, test_wrolpi_config,
|
||||
):
|
||||
"""Tagging domain collection with directory moves archive files."""
|
||||
# Configure template to include tag in path
|
||||
from wrolpi.common import get_wrolpi_config
|
||||
config = get_wrolpi_config()
|
||||
config.update({'archive_destination': 'archive/%(domain_tag)s/%(domain)s'})
|
||||
|
||||
# Create domain collection with directory
|
||||
# Use archive_directory fixture to match where archive_factory creates files
|
||||
domain_dir = archive_directory / 'test.com'
|
||||
|
|
@ -254,48 +259,6 @@ async def test_get_or_create_domain_collection_with_directory(test_session, test
|
|||
assert collection.directory == domain_dir
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_archive_destination_with_directory(test_session, test_directory):
|
||||
"""get_archive_destination returns collection directory when set."""
|
||||
from modules.archive.lib import get_archive_destination
|
||||
from wrolpi.common import get_media_directory
|
||||
|
||||
domain_dir = get_media_directory() / 'archives' / 'tagged' / 'example.com'
|
||||
domain_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=domain_dir
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
destination = get_archive_destination(collection)
|
||||
|
||||
assert destination == domain_dir
|
||||
assert destination.is_dir()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_archive_destination_unrestricted(test_session):
|
||||
"""get_archive_destination returns default path for unrestricted collection."""
|
||||
from modules.archive.lib import get_archive_destination, get_archive_directory
|
||||
|
||||
collection = Collection(
|
||||
name='example.com',
|
||||
kind='domain',
|
||||
directory=None # Unrestricted
|
||||
)
|
||||
test_session.add(collection)
|
||||
test_session.commit()
|
||||
|
||||
destination = get_archive_destination(collection)
|
||||
expected = get_archive_directory() / 'example.com'
|
||||
|
||||
assert destination == expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tag_domain_without_directory_saves_config(test_session, test_directory, tag_factory, await_switches):
|
||||
"""Tagging domain collection without directory should still save config."""
|
||||
|
|
|
|||
|
|
@ -10,6 +10,9 @@ from PIL import Image
|
|||
from pytz import utc
|
||||
|
||||
from modules.archive import lib
|
||||
from modules.archive.lib import ArchiveDownloaderConfigValidator
|
||||
from modules.archive.lib import format_archive_filename
|
||||
from modules.archive.lib import get_archive_downloader_config
|
||||
from modules.archive.lib import get_or_create_domain_collection, get_new_archive_files, delete_archives, \
|
||||
model_archive_result, get_domains
|
||||
from modules.archive.models import Archive
|
||||
|
|
@ -373,7 +376,7 @@ def test_get_new_archive_files_length(test_directory, fake_now):
|
|||
|
||||
|
||||
@skip_circleci
|
||||
def test_get_new_archive_files(fake_now):
|
||||
def test_get_new_archive_files(test_directory, 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))
|
||||
archive_files = get_new_archive_files('https://example.com/two', None)
|
||||
|
|
@ -405,16 +408,50 @@ def test_get_new_archive_files_with_destination(test_directory, fake_now):
|
|||
|
||||
# Files should be in the custom destination, not archive/example.com
|
||||
assert str(archive_files.singlefile).endswith('archive/News/custom-domain.com/2001-01-01-00-00-00_Title.html')
|
||||
assert str(archive_files.readability).endswith('archive/News/custom-domain.com/2001-01-01-00-00-00_Title.readability.html')
|
||||
assert str(archive_files.readability_txt).endswith('archive/News/custom-domain.com/2001-01-01-00-00-00_Title.readability.txt')
|
||||
assert str(archive_files.readability).endswith(
|
||||
'archive/News/custom-domain.com/2001-01-01-00-00-00_Title.readability.html')
|
||||
assert str(archive_files.readability_txt).endswith(
|
||||
'archive/News/custom-domain.com/2001-01-01-00-00-00_Title.readability.txt')
|
||||
assert str(archive_files.readability_json).endswith(
|
||||
'archive/News/custom-domain.com/2001-01-01-00-00-00_Title.readability.json')
|
||||
assert str(archive_files.screenshot).endswith('archive/News/custom-domain.com/2001-01-01-00-00-00_Title.png')
|
||||
|
||||
|
||||
@skip_circleci
|
||||
def test_get_new_archive_files_with_subdirectory_format(test_directory, fake_now):
|
||||
"""Archive files use subdirectories when the config format contains subdirectories."""
|
||||
from modules.archive.lib import get_archive_downloader_config
|
||||
|
||||
fake_now(datetime(2001, 1, 1))
|
||||
|
||||
# Configure a file format with subdirectory
|
||||
config = get_archive_downloader_config()
|
||||
original_format = config._config['file_name_format']
|
||||
config._config['file_name_format'] = '%(download_year)s/%(download_datetime)s_%(title)s'
|
||||
|
||||
try:
|
||||
archive_files = get_new_archive_files('https://example.com/page', 'My Article')
|
||||
|
||||
# Files should be created in a year subdirectory
|
||||
assert str(archive_files.singlefile).endswith('archive/example.com/2001/2001-01-01-00-00-00_My Article.html')
|
||||
assert str(archive_files.readability).endswith(
|
||||
'archive/example.com/2001/2001-01-01-00-00-00_My Article.readability.html')
|
||||
assert str(archive_files.readability_txt).endswith(
|
||||
'archive/example.com/2001/2001-01-01-00-00-00_My Article.readability.txt')
|
||||
assert str(archive_files.readability_json).endswith(
|
||||
'archive/example.com/2001/2001-01-01-00-00-00_My Article.readability.json')
|
||||
assert str(archive_files.screenshot).endswith('archive/example.com/2001/2001-01-01-00-00-00_My Article.png')
|
||||
|
||||
# The subdirectory should exist
|
||||
subdir = test_directory / 'archive/example.com/2001'
|
||||
assert subdir.is_dir()
|
||||
finally:
|
||||
config._config['file_name_format'] = original_format
|
||||
|
||||
|
||||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
async def test_title_in_filename(test_session, fake_now, test_directory, image_bytes_factory):
|
||||
async def test_title_in_filename(async_client, test_session, fake_now, test_directory, image_bytes_factory):
|
||||
"""
|
||||
The Archive files have the title in the path.
|
||||
"""
|
||||
|
|
@ -457,6 +494,8 @@ async def test_title_in_filename(test_session, fake_now, test_directory, image_b
|
|||
assert str(archive2.screenshot_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_NA.png'
|
||||
|
||||
# Test with malformed HTML - <title> not properly closed with </title>
|
||||
# The parser includes </html></html> in the title, which gets escaped
|
||||
singlefile = '<html>\ntest single-file\nジにてこちら\n<title>dangerous ;\\//_title</html></html>'
|
||||
readability = dict(
|
||||
# No Title from Readability.
|
||||
|
|
@ -467,16 +506,18 @@ async def test_title_in_filename(test_session, fake_now, test_directory, image_b
|
|||
|
||||
archive3 = await model_archive_result('https://example.com', singlefile, readability, screenshot)
|
||||
|
||||
# Title includes </html></html> because the <title> tag is malformed (no </title>)
|
||||
# Slashes are escaped: </html> -> <⧸html>
|
||||
assert str(archive3.singlefile_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title.html'
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title⧸html⧸html.html'
|
||||
assert str(archive3.readability_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title.readability.html'
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title⧸html⧸html.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'
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title⧸html⧸html.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'
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title⧸html⧸html.readability.json'
|
||||
assert str(archive3.screenshot_path.relative_to(test_directory)) == \
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title.png'
|
||||
'archive/example.com/2000-01-01-00-00-00_dangerous ;⧸⧸_title⧸html⧸html.png'
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -880,7 +921,6 @@ async def test_get_custom_archive_directory(async_client, test_directory, test_w
|
|||
get_wrolpi_config().archive_destination = 'custom/archives'
|
||||
|
||||
assert lib.get_archive_directory() == (test_directory / 'custom/archives')
|
||||
assert lib.get_domain_directory('https://example.com') == (test_directory / 'custom/archives/example.com')
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -1102,7 +1142,7 @@ def test_link_domain_and_downloads(test_session, test_download_manager):
|
|||
@skip_circleci
|
||||
@pytest.mark.asyncio
|
||||
async def test_archive_download_uses_domain_collection_directory(async_client, test_session, test_directory, fake_now,
|
||||
monkeypatch):
|
||||
monkeypatch):
|
||||
"""
|
||||
Test that archive downloads use the domain collection's directory when no explicit destination is set.
|
||||
|
||||
|
|
@ -1218,3 +1258,67 @@ async def test_archive_download_explicit_destination_overrides_domain_collection
|
|||
f"Archive should be in explicit destination {explicit_dir}, but was in {archive.singlefile_path.parent}"
|
||||
assert not str(archive.singlefile_path).startswith(str(collection_dir)), \
|
||||
f"Archive should NOT be in collection directory {collection_dir}"
|
||||
|
||||
|
||||
def test_archive_downloader_config(test_directory):
|
||||
"""ArchiveDownloaderConfig loads and provides file_name_format."""
|
||||
config = get_archive_downloader_config()
|
||||
|
||||
# Default format should contain %(title)s
|
||||
assert '%(title)s' in config.file_name_format
|
||||
assert config.file_name_format == '%(download_datetime)s_%(title)s'
|
||||
|
||||
|
||||
def test_archive_downloader_config_validation():
|
||||
"""ArchiveDownloaderConfig validator rejects invalid formats."""
|
||||
# Valid format
|
||||
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_%(title)s')
|
||||
|
||||
# Invalid format (missing %(title)s)
|
||||
with pytest.raises(ValueError, match='must contain'):
|
||||
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_no_title')
|
||||
|
||||
|
||||
def test_format_archive_filename_default(test_directory, fake_now):
|
||||
"""format_archive_filename uses default format."""
|
||||
result = format_archive_filename('My Article')
|
||||
|
||||
# Default format: %(download_datetime)s_%(title)s
|
||||
assert result == '2000-01-01-00-00-00_My Article'
|
||||
|
||||
|
||||
def test_format_archive_filename_with_domain(test_directory, fake_now):
|
||||
"""format_archive_filename includes domain variable."""
|
||||
# Temporarily change the format to include domain
|
||||
config = get_archive_downloader_config()
|
||||
original_format = config._config['file_name_format']
|
||||
config._config['file_name_format'] = '%(domain)s_%(title)s'
|
||||
|
||||
try:
|
||||
result = format_archive_filename('My Article', domain='example.com')
|
||||
assert result == 'example.com_My Article'
|
||||
finally:
|
||||
config._config['file_name_format'] = original_format
|
||||
|
||||
|
||||
def test_format_archive_filename_with_year_subdirectory(test_directory, fake_now):
|
||||
"""format_archive_filename can include subdirectories in format."""
|
||||
config = get_archive_downloader_config()
|
||||
original_format = config._config['file_name_format']
|
||||
config._config['file_name_format'] = '%(download_year)s/%(download_date)s_%(title)s'
|
||||
|
||||
try:
|
||||
result = format_archive_filename('My Article')
|
||||
# Should include year subdirectory
|
||||
assert result == '2000/2000-01-01_My Article'
|
||||
finally:
|
||||
config._config['file_name_format'] = original_format
|
||||
|
||||
|
||||
def test_format_archive_filename_escapes_special_chars(test_directory, fake_now):
|
||||
"""format_archive_filename escapes special characters in title."""
|
||||
result = format_archive_filename('My/Article:With*Special?Chars')
|
||||
|
||||
# Special characters should be escaped
|
||||
assert '/' not in result.split('/')[-1] # No slashes in filename part
|
||||
assert '2000-01-01' in result
|
||||
|
|
|
|||
|
|
@ -837,6 +837,10 @@ def format_videos_destination(channel_name: str = None, channel_tag: str = None,
|
|||
-> pathlib.Path:
|
||||
"""Return the directory where Videos should be downloaded according to the WROLPi Config.
|
||||
|
||||
Note: When you have a Collection object, prefer using Collection.format_destination()
|
||||
or Collection.get_or_set_directory() instead, as they provide unified behavior
|
||||
across both channel and domain collections.
|
||||
|
||||
@warning: Directory may or may not exist."""
|
||||
videos_destination = get_wrolpi_config().videos_destination
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue