Add authors hierarchy and series metadata to OPDS feed (#1777)

This commit enhances the OPDS server with two major features:

1. Series Metadata in OPDS Feed:
   - Add series name and book number to OPDS book entries
   - Uses standard OPDS/EPUB 3 metadata format with <meta> tags
   - Includes belongs-to-collection and group-position properties

2. Authors Navigation Hierarchy:
   - Add new /authors endpoint for browsing books by author
   - Implement authors list navigation feed with alphabetical sorting
   - Add author filtering to catalog feed via ?author parameter
   - Support library-based access control for author lists
   - Add authors link to root OPDS navigation

Changes:
- OpdsFeedService: Add series metadata to appendMetadata(), add generateAuthorsNavigation()
- OpdsController: Add getAuthorsNavigation() endpoint
- OpdsBookService: Add getDistinctAuthors() and getBooksByAuthorName() methods
- BookOpdsRepository: Add queries for distinct authors and books by author name
- Updated generateCatalogFeed() to support author parameter
- Updated determineFeedTitle() and determineFeedId() to handle author context

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
shiggsy365
2025-12-07 19:17:57 -07:00
committed by GitHub
co-authored by Claude
parent afe9c59380
commit b00bc5f908
4 changed files with 189 additions and 4 deletions
@@ -97,6 +97,16 @@ public class OpdsController {
.body(feed);
}
@Operation(summary = "Get OPDS authors navigation", description = "Retrieve the OPDS authors navigation feed.")
@ApiResponse(responseCode = "200", description = "Authors navigation feed returned successfully")
@GetMapping(value = "/authors", produces = OPDS_CATALOG_MEDIA_TYPE)
public ResponseEntity<String> getAuthorsNavigation(@Parameter(hidden = true) HttpServletRequest request) {
String feed = opdsFeedService.generateAuthorsNavigation(request);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
.body(feed);
}
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
@@ -122,4 +122,52 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query(value = "SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false)
List<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
// ============================================
// AUTHORS - Distinct Authors List
// ============================================
@Query("""
SELECT DISTINCT a FROM AuthorEntity a
JOIN a.bookMetadataEntityList m
JOIN m.book b
WHERE (b.deleted IS NULL OR b.deleted = false)
ORDER BY a.name
""")
List<com.adityachandel.booklore.model.entity.AuthorEntity> findDistinctAuthors();
@Query("""
SELECT DISTINCT a FROM AuthorEntity a
JOIN a.bookMetadataEntityList m
JOIN m.book b
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
ORDER BY a.name
""")
List<com.adityachandel.booklore.model.entity.AuthorEntity> findDistinctAuthorsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
// ============================================
// BOOKS BY AUTHOR - Two Query Pattern
// ============================================
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
JOIN b.metadata m
JOIN m.authors a
WHERE a.name = :authorName
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByAuthorName(@Param("authorName") String authorName, Pageable pageable);
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
JOIN b.metadata m
JOIN m.authors a
WHERE a.name = :authorName
AND b.library.id IN :libraryIds
AND (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.addedOn DESC
""")
Page<Long> findBookIdsByAuthorNameAndLibraryIds(@Param("authorName") String authorName, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
}
@@ -157,6 +157,68 @@ public class OpdsBookService {
return books.stream().map(bookMapper::toBook).toList();
}
public List<String> getDistinctAuthors(Long userId) {
if (userId == null) {
return List.of();
}
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
List<com.adityachandel.booklore.model.entity.AuthorEntity> authors;
if (user.getPermissions().isAdmin()) {
authors = bookOpdsRepository.findDistinctAuthors();
} else {
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
authors = bookOpdsRepository.findDistinctAuthorsByLibraryIds(libraryIds);
}
return authors.stream()
.map(com.adityachandel.booklore.model.entity.AuthorEntity::getName)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
}
public Page<Book> getBooksByAuthorName(Long userId, String authorName, int page, int size) {
if (userId == null) {
throw ApiError.FORBIDDEN.createException("Authentication required");
}
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
if (user.getPermissions().isAdmin()) {
Page<Long> idPage = bookOpdsRepository.findBookIdsByAuthorName(authorName, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
return createPageFromEntities(books, idPage, pageable);
}
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
Page<Long> idPage = bookOpdsRepository.findBookIdsByAuthorNameAndLibraryIds(authorName, libraryIds, pageable);
if (idPage.isEmpty()) {
return new PageImpl<>(List.of(), pageable, 0);
}
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable);
return applyBookFilters(booksPage, userId);
}
private Page<Book> getAllBooksPageInternal(int page, int size) {
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
@@ -90,6 +90,16 @@ public class OpdsFeedService {
</entry>
""".formatted(now()));
feed.append("""
<entry>
<title>Authors</title>
<id>urn:booklore:navigation:authors</id>
<updated>%s</updated>
<link rel="subsection" href="/api/v1/opds/authors" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<content type="text">Browse books by author</content>
</entry>
""".formatted(now()));
feed.append("""
<entry>
<title>Surprise Me</title>
@@ -223,11 +233,49 @@ public class OpdsFeedService {
return feed.toString();
}
public String generateAuthorsNavigation(HttpServletRequest request) {
Long userId = getUserId();
List<String> authors = opdsBookService.getDistinctAuthors(userId);
var feed = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opds="http://opds-spec.org/2010/catalog">
<id>urn:booklore:navigation:authors</id>
<title>Authors</title>
<updated>%s</updated>
<link rel="self" href="/api/v1/opds/authors" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
""".formatted(now()));
for (String author : authors) {
feed.append("""
<entry>
<title>%s</title>
<id>urn:booklore:author:%s</id>
<updated>%s</updated>
<link rel="subsection" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
<content type="text">Books by %s</content>
</entry>
""".formatted(
escapeXml(author),
escapeXml(author),
now(),
escapeXml("/api/v1/opds/catalog?author=" + java.net.URLEncoder.encode(author, java.nio.charset.StandardCharsets.UTF_8)),
escapeXml(author)
));
}
feed.append("</feed>");
return feed.toString();
}
public String generateCatalogFeed(HttpServletRequest request) {
Long libraryId = parseLongParam(request, "libraryId", null);
Long shelfId = parseLongParam(request, "shelfId", null);
Long magicShelfId = parseLongParam(request, "magicShelfId", null);
String query = request.getParameter("q");
String author = request.getParameter("author");
int page = Math.max(1, parseLongParam(request, "page", 1L).intValue());
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
@@ -236,12 +284,14 @@ public class OpdsFeedService {
if (magicShelfId != null) {
booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, page - 1, size);
} else if (author != null && !author.isBlank()) {
booksPage = opdsBookService.getBooksByAuthorName(userId, author, page - 1, size);
} else {
booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfId, page - 1, size);
}
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId);
String feedId = determineFeedId(libraryId, shelfId, magicShelfId);
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId, author);
String feedId = determineFeedId(libraryId, shelfId, magicShelfId, author);
var feed = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?>
@@ -427,6 +477,15 @@ public class OpdsFeedService {
if (meta.getIsbn10() != null) {
feed.append(" <dc:identifier>urn:isbn:").append(escapeXml(meta.getIsbn10())).append("</dc:identifier>\n");
}
// Series metadata
if (meta.getSeriesName() != null) {
feed.append(" <meta property=\"belongs-to-collection\" id=\"series\">")
.append(escapeXml(meta.getSeriesName())).append("</meta>\n");
if (meta.getSeriesNumber() != null) {
feed.append(" <meta property=\"group-position\" refines=\"#series\">")
.append(meta.getSeriesNumber()).append("</meta>\n");
}
}
}
private void appendLinks(StringBuilder feed, Book book) {
@@ -443,7 +502,7 @@ public class OpdsFeedService {
}
}
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId) {
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId, String author) {
if (magicShelfId != null) {
return magicShelfBookService.getMagicShelfName(magicShelfId);
}
@@ -453,10 +512,13 @@ public class OpdsFeedService {
if (libraryId != null) {
return opdsBookService.getLibraryName(libraryId);
}
if (author != null && !author.isBlank()) {
return "Books by " + author;
}
return "Booklore Catalog";
}
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId) {
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId, String author) {
if (magicShelfId != null) {
return "urn:booklore:magic-shelf:" + magicShelfId;
}
@@ -466,6 +528,9 @@ public class OpdsFeedService {
if (libraryId != null) {
return "urn:booklore:library:" + libraryId;
}
if (author != null && !author.isBlank()) {
return "urn:booklore:author:" + author;
}
return "urn:booklore:catalog";
}