Adding ext to archive file format to match video file format.
Some checks are pending
CodeQL / Analyze (push) Waiting to run
Controller Tests / controller-tests (push) Waiting to run
Jest Tests / jest-tests (push) Waiting to run

This commit is contained in:
Roland 2025-12-23 19:11:07 -07:00
parent 641fb368eb
commit 4ba5226c68
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
4 changed files with 59 additions and 53 deletions

View file

@ -689,8 +689,9 @@ function ArchiveFileNameForm({form}) {
<li><code>%(download_month)s</code> - Month (zero-padded)</li>
<li><code>%(download_day)s</code> - Day (zero-padded)</li>
<li><code>%(domain)s</code> - Domain name</li>
<li><code>%(ext)s</code> - File extension (required, must be at end)</li>
</ul>
<p>Subdirectories supported: <code>%(download_year)s/%(title)s</code></p>
<p>Subdirectories supported: <code>%(download_year)s/%(title)s.%(ext)s</code></p>
</>}
/>;
@ -710,7 +711,7 @@ function ArchiveSettingsPage() {
const {t} = React.useContext(ThemeContext);
const emptyFormData = {
file_name_format: '%(download_datetime)s_%(title)s',
file_name_format: '%(download_datetime)s_%(title)s.%(ext)s',
};
const configSubmitter = async () => {

View file

@ -220,9 +220,9 @@ class ArchiveDownloaderConfigValidator:
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')
# Validate file_name_format ends with .%(ext)s (like video format)
if not self.file_name_format.endswith('.%(ext)s'):
raise ValueError('file_name_format must end with .%(ext)s')
class ArchiveDownloaderConfig(ConfigFile):
@ -234,7 +234,7 @@ class ArchiveDownloaderConfig(ConfigFile):
Format:
version: 0
file_name_format: '%(download_date)s_%(title)s'
file_name_format: '%(download_date)s_%(title)s.%(ext)s'
Variables available in file_name_format:
- %(title)s - Page title (extracted from HTML)
@ -244,15 +244,16 @@ class ArchiveDownloaderConfig(ConfigFile):
- %(download_month)s - Download month (zero-padded)
- %(download_day)s - Download day (zero-padded)
- %(domain)s - Domain name
- %(ext)s - File extension (required, must be at end)
Subdirectories can be included in the format, e.g.:
'%(download_year)s/%(download_datetime)s_%(title)s'
'%(download_year)s/%(download_datetime)s_%(title)s.%(ext)s'
"""
file_name = 'archives_downloader.yaml'
validator = ArchiveDownloaderConfigValidator
default_config = dict(
version=0,
file_name_format='%(download_datetime)s_%(title)s',
file_name_format='%(download_datetime)s_%(title)s.%(ext)s',
)
@property
@ -289,12 +290,12 @@ def format_archive_filename(
download_date: Date of download (defaults to now)
Returns:
Formatted filename/path (without .html extension, added later)
Formatted filename/path (with .html extension included)
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"
# With default format: "2025-12-22_My Article.html"
# With "%(download_year)s/%(title)s.%(ext)s": "2025/My Article.html"
"""
config = get_archive_downloader_config()
template = config.file_name_format
@ -309,6 +310,7 @@ def format_archive_filename(
download_year=str(download_date.year),
download_month=f'{download_date.month:02d}',
download_day=f'{download_date.day:02d}',
ext='html',
)
try:
@ -316,7 +318,7 @@ def format_archive_filename(
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"}'
return f'{archive_strftime(download_date)}_{escape_file_name(title) if title else "untitled"}.html'
def preview_archive_filename(file_name_format: str) -> str:
@ -331,8 +333,8 @@ def preview_archive_filename(file_name_format: str) -> str:
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')
if not file_name_format.endswith('.%(ext)s'):
raise RuntimeError('file_name_format must end with .%(ext)s')
sample_date = now()
variables = dict(
@ -343,11 +345,11 @@ def preview_archive_filename(file_name_format: str) -> str:
download_year=str(sample_date.year),
download_month=f'{sample_date.month:02d}',
download_day=f'{sample_date.day:02d}',
ext='html',
)
try:
preview = file_name_format % variables
return f'{preview}.html'
return file_name_format % variables
except KeyError as e:
raise RuntimeError(f'Invalid variable: {e}')
except ValueError as e:
@ -402,27 +404,29 @@ def get_new_archive_files(url: str, title: Optional[str], destination: pathlib.P
directory = get_archive_directory() / domain
directory.mkdir(parents=True, exist_ok=True)
# Use the configured file format template
# Use the configured file format template (returns full filename with .html extension)
title = title or 'NA'
title = title[:MAXIMUM_ARCHIVE_FILE_CHARACTER_LENGTH]
prefix = format_archive_filename(title, domain=domain)
formatted_filename = 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
# Handle subdirectories in the format (e.g., "%(download_year)s/%(title)s.%(ext)s")
if '/' in formatted_filename:
# Filename includes subdirectories, create them relative to base directory
full_path = directory / formatted_filename
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')
singlefile_path = full_path
stem = full_path.stem
readability_path = full_path.parent / f'{stem}.readability.html'
readability_txt_path = full_path.parent / f'{stem}.readability.txt'
readability_json_path = full_path.parent / f'{stem}.readability.json'
screenshot_path = full_path.parent / f'{stem}.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'
singlefile_path = directory / formatted_filename
stem = singlefile_path.stem
readability_path = directory / f'{stem}.readability.html'
readability_txt_path = directory / f'{stem}.readability.txt'
readability_json_path = directory / f'{stem}.readability.json'
screenshot_path = directory / f'{stem}.png'
paths = (singlefile_path, readability_path, readability_txt_path, readability_json_path, screenshot_path)

View file

@ -412,7 +412,7 @@ async def test_archive_generate_screenshot(test_session, async_client, archive_f
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'}
data = {'archive_file_format': '%(download_datetime)s_%(title)s.%(ext)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
@ -423,25 +423,25 @@ async def test_archive_file_format_preview(async_client):
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'}
data = {'archive_file_format': '%(download_date)s_%(title)s.%(ext)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'}
data = {'archive_file_format': '%(download_year)s/%(download_datetime)s_%(title)s.%(ext)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'}
# Test invalid format - missing .%(ext)s
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.BAD_REQUEST
assert 'error' in response.json
# Test invalid format - unknown variable
data = {'archive_file_format': '%(invalid_var)s_%(title)s'}
data = {'archive_file_format': '%(invalid_var)s_%(title)s.%(ext)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

View file

@ -427,7 +427,7 @@ def test_get_new_archive_files_with_subdirectory_format(test_directory, fake_now
# 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'
config._config['file_name_format'] = '%(download_year)s/%(download_datetime)s_%(title)s.%(ext)s'
try:
archive_files = get_new_archive_files('https://example.com/page', 'My Article')
@ -1265,14 +1265,14 @@ async def test_archive_downloader_config_import(test_directory, async_client):
"""ArchiveDownloaderConfig imports successfully and provides correct defaults."""
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'
# Default format should end with .%(ext)s
assert config.file_name_format.endswith('.%(ext)s')
assert config.file_name_format == '%(download_datetime)s_%(title)s.%(ext)s'
# Create a valid config file
config_path = config.get_file()
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text('version: 0\nfile_name_format: "%(download_datetime)s_%(title)s"\n')
config_path.write_text('version: 0\nfile_name_format: "%(download_datetime)s_%(title)s.%(ext)s"\n')
# Import should succeed and set successful_import
config.import_config()
@ -1282,19 +1282,19 @@ async def test_archive_downloader_config_import(test_directory, async_client):
def test_archive_downloader_config_validation():
"""ArchiveDownloaderConfig validator rejects invalid formats."""
# Valid format
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_%(title)s')
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_%(title)s.%(ext)s')
# Invalid format (missing %(title)s)
with pytest.raises(ValueError, match='must contain'):
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_no_title')
# Invalid format (missing .%(ext)s)
with pytest.raises(ValueError, match='must end with'):
ArchiveDownloaderConfigValidator(file_name_format='%(download_date)s_%(title)s')
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'
# Default format: %(download_datetime)s_%(title)s.%(ext)s
assert result == '2000-01-01-00-00-00_My Article.html'
def test_format_archive_filename_with_domain(test_directory, fake_now):
@ -1302,11 +1302,11 @@ def test_format_archive_filename_with_domain(test_directory, fake_now):
# 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'
config._config['file_name_format'] = '%(domain)s_%(title)s.%(ext)s'
try:
result = format_archive_filename('My Article', domain='example.com')
assert result == 'example.com_My Article'
assert result == 'example.com_My Article.html'
finally:
config._config['file_name_format'] = original_format
@ -1315,12 +1315,12 @@ 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'
config._config['file_name_format'] = '%(download_year)s/%(download_date)s_%(title)s.%(ext)s'
try:
result = format_archive_filename('My Article')
# Should include year subdirectory
assert result == '2000/2000-01-01_My Article'
assert result == '2000/2000-01-01_My Article.html'
finally:
config._config['file_name_format'] = original_format
@ -1332,3 +1332,4 @@ def test_format_archive_filename_escapes_special_chars(test_directory, fake_now)
# Special characters should be escaped
assert '/' not in result.split('/')[-1] # No slashes in filename part
assert '2000-01-01' in result
assert result.endswith('.html')