feat(audiobook_library): add AudiobookshelfApi client and function to trigger metadata embedding for ids

This commit is contained in:
Lucas Vivo committed 2026-11-04 07:50:44 +01:00
1 parent 832c7bdafb
commit 6018845525
1 file changed
+175 -23
+175 -23
View File
@@ -6,7 +6,9 @@ import logging
import re
import sqlite3
import subprocess
import requests
import sys
from typing import Any
import tempfile
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -37,6 +39,7 @@ from serverlibrary import (
score_match_jaccard,
setup_logging,
words,
parser_add_loglevel
)
ID3_FRAME_CLASSES = {
@@ -1069,6 +1072,8 @@ class AudiobookLibrary:
def __init__(
self,
library_path: Path,
api_url: str,
api_key: str,
sql_database_path: Path,
dry_run: bool,
path_filter: str = "",
@@ -1076,6 +1081,7 @@ class AudiobookLibrary:
):
self.path_filter = path_filter
self.sql_database_instance = self.SqlDatabase(sql_database_path)
self.api_instance = self.AudiobookshelfApi(api_url,api_key)
self.dry_run = dry_run
logging.setLoggerClass(CustomLogger)
logger: CustomLogger = logging.getLogger(__name__) # type: ignore[assignment]
@@ -1239,6 +1245,138 @@ class AudiobookLibrary:
comment = ""
file["metaTags"]["tagComment"] = comment
class AudiobookshelfApi:
def __init__(self, url: str, api_key: str, timeout: int = 30):
self.url = url.rstrip("/")
self.timeout = timeout
self.session = requests.Session()
self.session.headers["Authorization"] = f"Bearer {api_key}"
self.books = []
def _request(self, method: str, endpoint: str, **kwargs) -> Any:
resp = self.session.request(
method,
f"{self.url}{endpoint}",
timeout=self.timeout,
**kwargs,
)
try:
resp.raise_for_status()
except requests.exceptions.HTTPError:
logger.error(f"{method} {endpoint}")
logger.error(resp)
if not resp.content or resp.status_code != 200:
logger.error(f"Request failed: {resp}")
return None
# No content
if not resp.content:
return None
# Only parse JSON if response claims to be JSON
content_type = resp.headers.get("Content-Type", "")
if "application/json" in content_type:
return resp.json()
# Return raw text otherwise
return resp.text
def get(self, endpoint: str, **kwargs):
return self._request("GET", endpoint, params=kwargs)
def post(self, endpoint: str, data: dict, **kwargs):
return self._request("POST", endpoint, json=data, params=kwargs)
def put(self, endpoint: str, data: dict):
return self._request("PUT", endpoint, json=data)
def delete(self, endpoint: str):
return self._request("DELETE", endpoint)
def load_books(self) -> list[dict]:
"""Load all books from all libraries into self.books."""
self.books = []
libraries = self.get("/api/libraries")["libraries"]
for library in libraries:
library_id = library["id"]
response = self.get(
f"/api/libraries/{library_id}/items",
minified="0"
)
self.books.extend(response["results"])
return self.books
def embed_metadata_for_book(self, item_id: str) -> None:
book = next((b for b in self.books if b["id"] == item_id), None)
if book:
title = (
book.get("media", {})
.get("metadata", {})
.get("title", item_id)
)
if book.get("media", {}).get("numAudioFiles", 0) > 0:
logger.info(f"Embedding metadata: {title}")
self.post(
f"/api/tools/item/{item_id}/embed-metadata",
data={},
backup=False,
)
else:
logger.info(f"{title} is an epub only book")
else:
logger.info(f"Book not found: {item_id}")
def embed_metadata_for_all_books(self, args) -> None:
for book in self.books:
item_id = book["id"]
book_name = (
book.get("media", {})
.get("metadata", {})
.get("title", item_id)
)
book_path = book.get("path", "")
logger.info(f"Embedding metadata: {book_name} ({book_path})")
if args.dry_run:
continue
try:
self.embed_metadata_for_book(item_id)
except Exception as e:
logger.error(f"Failed: {book_name}: {e}")
def embed_metadata_from_file(self, filename: str) -> None:
filename = Path(filename).expanduser().resolve()
with open(filename, encoding="utf-8") as f:
item_ids = [
line.strip()
for line in f
if line.strip() and not line.startswith("#")
]
logger.info(f"Loaded {len(item_ids)} item IDs from {filename}")
for item_id in item_ids:
book = next(
(b for b in self.books if b["id"] == item_id),
None
)
try:
self.embed_metadata_for_book(item_id)
except Exception as e:
logger.error(f"Failed: {item_id}: {e}")
def add(self, book: Audiobook):
self.audiobooks.append(book)
@@ -1390,14 +1528,7 @@ def main():
parser.add_argument("library", type=Path, help="Library path")
parser.add_argument(
"-ll",
"--log-level",
type=str.upper,
default="INFO",
choices=["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Set log level",
)
parser_add_loglevel(parser)
m4b_group = parser.add_argument_group("M4B creation")
m4b_group.add_argument(
@@ -1438,6 +1569,24 @@ def main():
default=Path("/docker/audiobookshelf/config/absdatabase.sqlite"),
help="SQL Database Path",
)
parser.add_argument(
"--api-url",
type=str,
default="https://audiobooks.someoneslinux.selfhost.eu",
help="API Url for Audiobookshelf API",
)
parser.add_argument(
"--api-key",
type=str,
default="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXlJZCI6Ijc3NTc5NDE0LTczMGItNDllMy04YTgzLTk3M2Y1MjRiOGVlNyIsIm5hbWUiOiJBdWRpb2Jvb2tfbGlicmFyeS5weSIsInR5cGUiOiJhcGkiLCJpYXQiOjE3OTM3MDIyODd9.GJVOgYcWM4JpJyMhqzQAHJCfypKiWNBfJHwdM_uvZHU",
help="API Key for Audiobookshelf API",
)
parser.add_argument(
"-em",
"--encode-meta",
action="store_true",
help="Encode Metadata to Audiobook files",
)
parser.add_argument(
"-fd",
"--fix-db",
@@ -1470,16 +1619,13 @@ def main():
database_path = args.sql_database.expanduser()
database_path = database_path.resolve()
if args.fix_db and not database_path.is_file():
logger.error(f"Database is not a file: {database_path}")
return
library = AudiobookLibrary(
library_dir, database_path, args.dry_run, path_filter=args.path_filter
library_dir, args.api_url,args.api_key,database_path, args.dry_run, path_filter=args.path_filter
)
if args.fix_db:
library.sql_database_instance.init()
if args.encode_meta:
library.api_instance.load_books()
library.api_instance.embed_metadata_from_file("~/embed_ids.txt")
#library.api_instance.embed_metadata_for_all_books(args)
library.fix_artist_dir()
library.fix_artists(args.force_artist_from_path)
library.fix_composers()
@@ -1489,6 +1635,19 @@ def main():
library.fix_genres()
library.fix_titles()
if args.fix_db:
if not database_path.is_file():
logger.error(f"Database is not a file: {database_path}")
return
library.sql_database_instance.init()
library.sql_database_instance.fix_genres()
library.sql_database_instance.fix_comments()
if not args.dry_run:
library.sql_database_instance.update_books()
library.sql_database_instance.commit()
library.sql_database_instance.close()
if args.create_m4b:
library.create_m4b_from_dir(
keep_originals=args.keep_originals,
@@ -1496,13 +1655,6 @@ def main():
library.write_metadata()
if args.fix_db:
library.sql_database_instance.fix_genres()
library.sql_database_instance.fix_comments()
if not args.dry_run:
library.sql_database_instance.update_books()
library.sql_database_instance.commit()
library.sql_database_instance.close()
if args.move:
library.create_structured_directories(args.dry_run)