mirror of
https://github.com/calibrain/shelfmark.git
synced 2026-11-23 15:32:33 +00:00
refactor: one default and one reader for the Supported Book Formats list (#1532)
The default for Supported Book Formats (`epub, mobi, azw3, fb2, djvu, cbz, cbr`) was written out in five places: the settings registry, `postprocess/policy.py`, `irc/parser.py`, Prowlarr's `source.py` (added in #1490) and slskd's `source.py` (added in #1428). Both of those two arrived in 1.5.0, and both are mine, so this is cleaning up after myself as much as anything. The setting was also read three different ways. Post-processing split on commas only. slskd split on commas and spaces and stripped a leading dot. IRC split on commas and kept the dot. Prowlarr split on commas and kept `""` as a format when the value was an empty string. So `.epub` or `epub mobi` worked in one source and not another. This puts `DEFAULT_EBOOK_FORMATS` and `normalize_format_list` in `core/utils.py` next to `AUDIOBOOK_FORMATS`, and the registry, post-processing, IRC, Prowlarr and slskd all use them. I took the most lenient reading of the three (comma or space split, leading dot dropped, empties ignored, default when nothing is left), so no existing config gets stricter. I put the reader in `core/utils.py` and not in `policy.py` because the release sources can't import `policy` without pulling in the whole post-processing package. A config with a sensible list reads exactly as before. The only differences are for malformed values: an emptied setting or an empty string now falls back to the default in every place, where IRC used to filter everything out and Prowlarr treated `""` as a format. The audiobook default is a separate story and I left it alone: the registry and slskd default to every processable audiobook format plus the archives, while post-processing and IRC fall back to `m4b, mp3`. They only differ when the setting is unset or emptied, but they do differ, and I'd rather ask which one you want than pick one here. Ruff, basedpyright on the changed files and the backend suite pass (4400 passed, e2e not run). New tests cover the reader and the two fallbacks.
This commit is contained in:
1 parent
a11a63a29e
commit
8e425da527
7 files changed
+96
-63
No files matched your search
@@ -36,7 +36,7 @@ from shelfmark.core.settings_registry import (
|
||||
register_on_save,
|
||||
register_settings,
|
||||
)
|
||||
from shelfmark.core.utils import ARCHIVE_FORMATS, AUDIOBOOK_FORMATS
|
||||
from shelfmark.core.utils import ARCHIVE_FORMATS, AUDIOBOOK_FORMATS, DEFAULT_EBOOK_FORMATS
|
||||
|
||||
_DOWNLOAD_CLIENT_COMPLETED_PATH_TIMEOUT_DEFAULT = 60
|
||||
_DOWNLOAD_CLIENT_COMPLETED_PATH_TIMEOUT_MAX = 3600
|
||||
@@ -454,7 +454,7 @@ def general_settings() -> list[SettingsField]:
|
||||
label="Supported Book Formats",
|
||||
description="Book formats to include in search results. ZIP/RAR archives are extracted automatically and book files are used if found.",
|
||||
options=_FORMAT_OPTIONS,
|
||||
default=["epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr"],
|
||||
default=list(DEFAULT_EBOOK_FORMATS),
|
||||
),
|
||||
MultiSelectField(
|
||||
key="SUPPORTED_AUDIOBOOK_FORMATS",
|
||||
|
||||
+21
-1
@@ -7,7 +7,7 @@ import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from shelfmark.core.logger import setup_logger
|
||||
@@ -137,6 +137,26 @@ AUDIOBOOK_FORMATS = ("m4b", "mp3", "m4a", "mp4", "flac", "ogg", "wma", "aac", "w
|
||||
# what comes out of one after extraction.
|
||||
ARCHIVE_FORMATS = ("zip", "rar")
|
||||
|
||||
# What the Supported Book Formats setting holds until someone changes it. The settings
|
||||
# registry, post-processing and every release source fall back to this one list.
|
||||
DEFAULT_EBOOK_FORMATS = ("epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr")
|
||||
|
||||
|
||||
def normalize_format_list(value: object, default: tuple[str, ...] | list[str]) -> list[str]:
|
||||
"""Read a configured format list, or a comma or space separated string of them.
|
||||
|
||||
Lower-cases, drops a leading dot and empty items, and returns ``default`` when the
|
||||
value is not a list or string or nothing is left of it.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
items: list[Any] = value.replace(",", " ").split()
|
||||
elif isinstance(value, (list, tuple, set, frozenset)):
|
||||
items = list(value)
|
||||
else:
|
||||
return list(default)
|
||||
formats = [fmt for fmt in (str(item).strip().lower().lstrip(".") for item in items) if fmt]
|
||||
return formats or list(default)
|
||||
|
||||
|
||||
CONTENT_TYPES = [
|
||||
"book (fiction)",
|
||||
|
||||
@@ -17,15 +17,7 @@ circular imports (`archive` is used by the pipeline).
|
||||
from __future__ import annotations
|
||||
|
||||
import shelfmark.core.config as core_config
|
||||
|
||||
|
||||
def _normalize_format_list(value: object, default: list[str]) -> list[str]:
|
||||
if isinstance(value, str):
|
||||
return [fmt.strip().lower() for fmt in value.split(",") if fmt.strip()]
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
normalized = [str(fmt).strip().lower() for fmt in value if str(fmt).strip()]
|
||||
return normalized or default
|
||||
return default
|
||||
from shelfmark.core.utils import DEFAULT_EBOOK_FORMATS, normalize_format_list
|
||||
|
||||
|
||||
def _config_text(value: object) -> str:
|
||||
@@ -36,16 +28,15 @@ def _config_text(value: object) -> str:
|
||||
|
||||
def get_supported_formats() -> list[str]:
|
||||
"""Get current supported formats from config singleton."""
|
||||
default_formats = ["epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr"]
|
||||
formats = core_config.config.get("SUPPORTED_FORMATS", default_formats)
|
||||
return _normalize_format_list(formats, default_formats)
|
||||
formats = core_config.config.get("SUPPORTED_FORMATS", None)
|
||||
return normalize_format_list(formats, DEFAULT_EBOOK_FORMATS)
|
||||
|
||||
|
||||
def get_supported_audiobook_formats() -> list[str]:
|
||||
"""Get current supported audiobook formats from config singleton."""
|
||||
default_formats = ["m4b", "mp3"]
|
||||
formats = core_config.config.get("SUPPORTED_AUDIOBOOK_FORMATS", default_formats)
|
||||
return _normalize_format_list(formats, default_formats)
|
||||
return normalize_format_list(formats, default_formats)
|
||||
|
||||
|
||||
def get_file_organization(*, is_audiobook: bool) -> str:
|
||||
|
||||
@@ -5,13 +5,17 @@ Parses the text files sent via DCC that contain search results.
|
||||
|
||||
import re
|
||||
import zipfile
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shelfmark.core.config import config
|
||||
from shelfmark.core.logger import setup_logger
|
||||
from shelfmark.core.utils import ARCHIVE_FORMATS, AUDIOBOOK_FORMATS
|
||||
from shelfmark.core.utils import (
|
||||
ARCHIVE_FORMATS,
|
||||
AUDIOBOOK_FORMATS,
|
||||
DEFAULT_EBOOK_FORMATS,
|
||||
normalize_format_list,
|
||||
)
|
||||
from shelfmark.core.utils import is_audiobook as check_audiobook
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -52,30 +56,12 @@ ALL_RECOGNIZED_FORMATS = tuple(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_config_formats(raw_formats: object) -> set[str]:
|
||||
"""Normalize configured format values into a lowercase set."""
|
||||
if isinstance(raw_formats, str):
|
||||
return {fmt.strip().lower() for fmt in raw_formats.split(",") if fmt.strip()}
|
||||
if isinstance(raw_formats, Iterable):
|
||||
normalized_formats: set[str] = set()
|
||||
for fmt in raw_formats:
|
||||
normalized = str(fmt).strip().lower()
|
||||
if normalized:
|
||||
normalized_formats.add(normalized)
|
||||
return normalized_formats
|
||||
return set()
|
||||
|
||||
|
||||
def _get_supported_formats(content_type: str | None = None) -> set[str]:
|
||||
"""Get the supported formats for the requested content type."""
|
||||
if check_audiobook(content_type):
|
||||
formats = config.get("SUPPORTED_AUDIOBOOK_FORMATS", ["m4b", "mp3"])
|
||||
else:
|
||||
formats = config.get(
|
||||
"SUPPORTED_FORMATS", ["epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr"]
|
||||
)
|
||||
|
||||
return _normalize_config_formats(formats)
|
||||
formats = config.get("SUPPORTED_AUDIOBOOK_FORMATS", None)
|
||||
return set(normalize_format_list(formats, ["m4b", "mp3"]))
|
||||
return set(normalize_format_list(config.get("SUPPORTED_FORMATS", None), DEFAULT_EBOOK_FORMATS))
|
||||
|
||||
|
||||
# Regex to parse result lines
|
||||
|
||||
@@ -20,7 +20,7 @@ from shelfmark.core.logger import setup_logger
|
||||
from shelfmark.core.request_helpers import coerce_int, normalize_optional_text
|
||||
from shelfmark.core.search_plan import ReleaseSearchVariant
|
||||
from shelfmark.core.utils import AUDIOBOOK_FORMATS as CORE_AUDIOBOOK_FORMATS
|
||||
from shelfmark.core.utils import normalize_http_url
|
||||
from shelfmark.core.utils import DEFAULT_EBOOK_FORMATS, normalize_format_list, normalize_http_url
|
||||
from shelfmark.release_sources import (
|
||||
ColumnAlign,
|
||||
ColumnColorHint,
|
||||
@@ -377,9 +377,6 @@ _KNOWN_FILE_EXTENSIONS = frozenset(ALL_BOOK_FORMATS) | {
|
||||
"xps",
|
||||
}
|
||||
|
||||
# Same default as the Supported Book Formats setting and post-processing.
|
||||
_DEFAULT_SUPPORTED_FORMATS = ("epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr")
|
||||
|
||||
|
||||
def _unsupported_title_extension(title: str, content_type: str) -> str | None:
|
||||
"""Return the trailing extension of a title when it is a format the user did not enable.
|
||||
@@ -396,12 +393,7 @@ def _unsupported_title_extension(title: str, content_type: str) -> str | None:
|
||||
extension = match.group(1)
|
||||
if extension not in _KNOWN_FILE_EXTENSIONS:
|
||||
return None
|
||||
configured = config.get("SUPPORTED_FORMATS", None)
|
||||
if isinstance(configured, str):
|
||||
configured = configured.split(",")
|
||||
if not isinstance(configured, (list, tuple, set)) or not configured:
|
||||
configured = _DEFAULT_SUPPORTED_FORMATS
|
||||
supported = {str(fmt).strip().lower() for fmt in configured}
|
||||
supported = normalize_format_list(config.get("SUPPORTED_FORMATS", None), DEFAULT_EBOOK_FORMATS)
|
||||
if extension in supported:
|
||||
return None
|
||||
return extension
|
||||
|
||||
@@ -19,7 +19,13 @@ if TYPE_CHECKING:
|
||||
|
||||
from shelfmark.core.config import config
|
||||
from shelfmark.core.logger import setup_logger
|
||||
from shelfmark.core.utils import ARCHIVE_FORMATS, AUDIOBOOK_FORMATS, normalize_http_url
|
||||
from shelfmark.core.utils import (
|
||||
ARCHIVE_FORMATS,
|
||||
AUDIOBOOK_FORMATS,
|
||||
DEFAULT_EBOOK_FORMATS,
|
||||
normalize_format_list,
|
||||
normalize_http_url,
|
||||
)
|
||||
from shelfmark.core.utils import is_audiobook as check_audiobook
|
||||
from shelfmark.release_sources import (
|
||||
ColumnAlign,
|
||||
@@ -54,7 +60,6 @@ MAX_QUERY_VARIANTS = 3
|
||||
|
||||
# Whole-book audio files: one file holds the entire book, unlike chapter files.
|
||||
CONTAINER_FORMATS = frozenset({"m4b", "m4a"})
|
||||
_DEFAULT_EBOOK_FORMATS = ["epub", "mobi", "azw3", "fb2", "djvu", "cbz", "cbr"]
|
||||
_DEFAULT_AUDIOBOOK_FORMATS = [*AUDIOBOOK_FORMATS, *ARCHIVE_FORMATS]
|
||||
|
||||
|
||||
@@ -126,22 +131,15 @@ def make_source_id(username: str, remote_path: str) -> str:
|
||||
return f"{SOURCE_NAME}:{digest}"
|
||||
|
||||
|
||||
def _normalize_formats(raw: object, defaults: list[str]) -> set[str]:
|
||||
if isinstance(raw, str):
|
||||
raw = [part for part in raw.replace(",", " ").split() if part]
|
||||
if not isinstance(raw, (list, tuple)):
|
||||
return {f.lower() for f in defaults}
|
||||
formats = {str(item).strip().lower().lstrip(".") for item in raw if str(item).strip()}
|
||||
return formats or {f.lower() for f in defaults}
|
||||
|
||||
|
||||
def get_supported_formats(content_type: str | None) -> set[str]:
|
||||
"""Return the configured formats for the requested content type."""
|
||||
if check_audiobook(content_type):
|
||||
return _normalize_formats(
|
||||
config.get("SUPPORTED_AUDIOBOOK_FORMATS", None), _DEFAULT_AUDIOBOOK_FORMATS
|
||||
return set(
|
||||
normalize_format_list(
|
||||
config.get("SUPPORTED_AUDIOBOOK_FORMATS", None), _DEFAULT_AUDIOBOOK_FORMATS
|
||||
)
|
||||
)
|
||||
return _normalize_formats(config.get("SUPPORTED_FORMATS", None), _DEFAULT_EBOOK_FORMATS)
|
||||
return set(normalize_format_list(config.get("SUPPORTED_FORMATS", None), DEFAULT_EBOOK_FORMATS))
|
||||
|
||||
|
||||
def _coerce_int(value: object) -> int:
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""One default for the Supported Book Formats setting, read the same way everywhere."""
|
||||
|
||||
import pytest
|
||||
|
||||
from shelfmark.config import settings as app_settings
|
||||
from shelfmark.core.utils import DEFAULT_EBOOK_FORMATS, normalize_format_list
|
||||
from shelfmark.download.postprocess import policy
|
||||
|
||||
DEFAULT = ["epub", "mobi"]
|
||||
|
||||
|
||||
class TestNormalizeFormatList:
|
||||
def test_a_string_splits_on_commas_and_spaces_and_drops_leading_dots(self):
|
||||
assert normalize_format_list("epub, .MOBI azw3", DEFAULT) == ["epub", "mobi", "azw3"]
|
||||
|
||||
def test_a_list_is_lowercased_and_stripped(self):
|
||||
assert normalize_format_list([" EPUB ", ".mobi", "", " "], DEFAULT) == ["epub", "mobi"]
|
||||
|
||||
@pytest.mark.parametrize("value", ["", " , ", [], [""], (), set()])
|
||||
def test_nothing_left_falls_back_to_the_default(self, value):
|
||||
assert normalize_format_list(value, DEFAULT) == DEFAULT
|
||||
|
||||
@pytest.mark.parametrize("value", [None, 3, 1.5, {"epub": 1}, object()])
|
||||
def test_a_value_of_the_wrong_kind_falls_back_to_the_default(self, value):
|
||||
assert normalize_format_list(value, DEFAULT) == DEFAULT
|
||||
|
||||
def test_the_default_is_returned_as_a_new_list(self):
|
||||
assert normalize_format_list(None, DEFAULT_EBOOK_FORMATS) == list(DEFAULT_EBOOK_FORMATS)
|
||||
|
||||
|
||||
def test_the_registry_default_is_the_shared_default():
|
||||
field = next(
|
||||
f for f in app_settings.general_settings() if getattr(f, "key", "") == "SUPPORTED_FORMATS"
|
||||
)
|
||||
|
||||
assert field.default == list(DEFAULT_EBOOK_FORMATS)
|
||||
|
||||
|
||||
def test_post_processing_falls_back_to_the_shared_default(monkeypatch):
|
||||
class _Config:
|
||||
def get(self, key, default=None, user_id=None):
|
||||
return default
|
||||
|
||||
monkeypatch.setattr("shelfmark.core.config.config", _Config())
|
||||
|
||||
assert policy.get_supported_formats() == list(DEFAULT_EBOOK_FORMATS)
|
||||
Reference in new issue
Block a user