audiobookshelf_get_random_items.py
return {"results": [], "total": 0, "limit": limit, "page": page}
def get_random_items(self, limit: int = 10) -> list[dict]:
"""Get a random, author-diverse sample from across the WHOLE library
(unlike get_recent_items, which is limited to the 'recently added' shelf
and can be dominated by whatever was last imported in bulk)."""
import random
try:
libs_response = self.libraries()
library_ids = list(libs_response.keys())
except Exception:
return []
pool: list[dict] = []
for library_id in library_ids:
try:
probe = self.get_library_items(library_id, limit=1, page=0)
total = int(probe.get("total", 0) or 0)
page_size = 60
page_count = max(1, (total + page_size - 1) // page_size)
result = self.get_library_items(library_id, limit=page_size, page=random.randrange(page_count))
except Exception as exc:
logging.debug(f"Failed to get library items for {library_id}: {exc}")
continue
for entity in result.get("results", []):
# Audiobookshelf may retain usable metadata and cover art while
# marking the original source path missing. Keep those entries;
# coverPath below is the reliable display criterion.
media = entity.get("media", {})
cover_path = media.get("coverPath")
if not cover_path:
continue
cover_url = f"{self.url}/api/items/{entity.get('id')}/cover"
thumb_url = self.generate_image_proxy_url(cover_url)
metadata = media.get("metadata", {})
title = metadata.get("title") or entity.get("relPath", "Unknown")
author = metadata.get("authorName") or None
pool.append(
{
"title": title,
"year": None,
"thumb": thumb_url,
"type": entity.get("mediaType", "book").lower(),
"added_at": None,
"author": author,
"series": metadata.get("seriesName") or None,
}
)