feat: add USE_BOOK_TITLE option for customizing download filenames (#95)

Implements #94
This commit is contained in:
CaliBrain
2025-03-16 14:42:19 -04:00
committed by GitHub
parent 909f4b403c
commit 392a8b5262
4 changed files with 18 additions and 3 deletions
+14 -3
View File
@@ -8,12 +8,17 @@ import subprocess
import os
from logger import setup_logger
from config import TMP_DIR, MAIN_LOOP_SLEEP_TIME, INGEST_DIR, CUSTOM_SCRIPT
from config import TMP_DIR, MAIN_LOOP_SLEEP_TIME, INGEST_DIR, CUSTOM_SCRIPT, USE_BOOK_TITLE
from models import book_queue, BookInfo, QueueStatus, SearchFilters
import book_manager
logger = setup_logger(__name__)
def _sanitize_filename(filename: str) -> str:
"""Sanitize a filename by replacing spaces with underscores and removing invalid characters."""
keepcharacters = (' ','.','_')
return "".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip()
def search_books(query: str, filters: SearchFilters) -> List[Dict[str, Any]]:
"""Search for books matching the query.
@@ -114,7 +119,13 @@ def _download_book(book_id: str) -> bool:
"""
try:
book_info = book_queue._book_data[book_id]
book_path = TMP_DIR / f"{book_id}.{book_info.format}"
if USE_BOOK_TITLE:
book_name = _sanitize_filename(book_info.title)
else:
book_name = book_id
book_name += f".{book_info.format}"
book_path = TMP_DIR / book_name
success = book_manager.download_book(book_info, book_path)
if not success:
@@ -124,7 +135,7 @@ def _download_book(book_id: str) -> bool:
logger.info(f"Running custom script: {CUSTOM_SCRIPT}")
subprocess.run([CUSTOM_SCRIPT, book_path])
final_path = INGEST_DIR / f"{book_id}.{book_info.format}"
final_path = INGEST_DIR / book_name
if os.path.exists(book_path):
shutil.move(book_path, final_path)
+2
View File
@@ -18,6 +18,8 @@ TMP_DIR = Path(os.getenv("TMP_DIR", "/tmp/cwa-book-downloader"))
INGEST_DIR = Path(os.getenv("INGEST_DIR", "/cwa-book-ingest"))
STATUS_TIMEOUT = int(os.getenv("STATUS_TIMEOUT", 3600))
USE_BOOK_TITLE = os.getenv("USE_BOOK_TITLE", "false").lower() in ["true", "yes", "1", "y"]
# Create necessary directories
TMP_DIR.mkdir(exist_ok=True)
LOG_DIR.mkdir(exist_ok=True)
+1
View File
@@ -8,6 +8,7 @@ services:
FLASK_PORT: 8084
FLASK_DEBUG: false
BOOK_LANGUAGE: en
USE_BOOK_TITLE: true
ports:
- 8084:8084
restart: unless-stopped
+1
View File
@@ -73,6 +73,7 @@ If logging is enabld, log folder default location is `/var/log/cwa-book-download
| `SUPPORTED_FORMATS` | Supported book formats | `epub,mobi,azw3,fb2,djvu,cbz,cbr` |
| `BOOK_LANGUAGE` | Preferred language for books | `en` |
| `AA_DONATOR_KEY` | Optional Donator key for Anna's Archive fast download API | `` |
| `USE_BOOK_TITLE` | Use book title as filename instead of ID | `false` |
If you change `BOOK_LANGUAGE`, you can add multiple comma separated languages, such as `en,fr,ru` etc.