OPDS v2 fixes

This commit is contained in:
aditya.chandel
2025-08-31 08:45:59 -06:00
parent 31b724a0b8
commit 0d95817ae8
12 changed files with 150 additions and 65 deletions
@@ -15,6 +15,6 @@ public class WebMvcConfig implements WebMvcConfigurer {
@Override @Override
public void addInterceptors(InterceptorRegistry registry) { public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(opdsEnabledInterceptor) registry.addInterceptor(opdsEnabledInterceptor)
.addPathPatterns("/api/v1/opds/**"); .addPathPatterns("/api/v1/opds/**", "/api/v2/opds/**");
} }
} }
@@ -56,7 +56,8 @@ public class SecurityConfig {
}; };
private static final String[] COMMON_UNAUTHENTICATED_ENDPOINTS = { private static final String[] COMMON_UNAUTHENTICATED_ENDPOINTS = {
"/api/v1/opds/search.opds" "/api/v1/opds/search.opds",
"/api/v2/opds/search.opds"
}; };
@Bean @Bean
@@ -69,7 +70,7 @@ public class SecurityConfig {
public SecurityFilterChain opdsBasicAuthSecurityChain(HttpSecurity http) throws Exception { public SecurityFilterChain opdsBasicAuthSecurityChain(HttpSecurity http) throws Exception {
List<String> unauthenticatedEndpoints = new ArrayList<>(Arrays.asList(COMMON_UNAUTHENTICATED_ENDPOINTS)); List<String> unauthenticatedEndpoints = new ArrayList<>(Arrays.asList(COMMON_UNAUTHENTICATED_ENDPOINTS));
http http
.securityMatcher("/api/v1/opds/**") .securityMatcher("/api/v1/opds/**", "/api/v2/opds/**")
.csrf(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
@@ -84,6 +85,7 @@ public class SecurityConfig {
response.getWriter().write("HTTP Status 401 - " + authException.getMessage()); response.getWriter().write("HTTP Status 401 - " + authException.getMessage());
}) })
); );
return http.build(); return http.build();
} }
@@ -46,6 +46,7 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
private static final List<String> WHITELISTED_PATHS = List.of( private static final List<String> WHITELISTED_PATHS = List.of(
"/api/v1/opds/", "/api/v1/opds/",
"/api/v2/opds/",
"/api/v1/auth/refresh", "/api/v1/auth/refresh",
"/api/v1/setup/", "/api/v1/setup/",
"/api/kobo/" "/api/kobo/"
@@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/api/v1/opds") @RequestMapping({"/api/v1/opds", "/api/v2/opds"})
@RequiredArgsConstructor @RequiredArgsConstructor
public class OpdsController { public class OpdsController {
@@ -58,7 +58,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class) @ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<ErrorResponse> handleDataIntegrityViolation(DataIntegrityViolationException ex) { public ResponseEntity<ErrorResponse> handleDataIntegrityViolation(DataIntegrityViolationException ex) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Data integrity violation: " + ex.getMessage()); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
} }
@@ -15,7 +15,8 @@ public class OpdsEnabledInterceptor implements HandlerInterceptor {
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().startsWith("/api/v1/opds")) { String uri = request.getRequestURI();
if (uri.startsWith("/api/v1/opds") || uri.startsWith("/api/v2/opds")) {
if (!appSettingService.getAppSettings().isOpdsServerEnabled()) { if (!appSettingService.getAppSettings().isOpdsServerEnabled()) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "OPDS Server is disabled."); response.sendError(HttpServletResponse.SC_FORBIDDEN, "OPDS Server is disabled.");
return false; return false;
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.entity.OpdsUserV2Entity;
import com.adityachandel.booklore.repository.OpdsUserV2Repository; import com.adityachandel.booklore.repository.OpdsUserV2Repository;
import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.repository.UserRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@@ -35,14 +36,24 @@ public class OpdsUserV2Service {
} }
public OpdsUserV2 createOpdsUser(OpdsUserV2CreateRequest request) { public OpdsUserV2 createOpdsUser(OpdsUserV2CreateRequest request) {
try {
BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser(); BookLoreUser bookLoreUser = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + bookLoreUser.getId())); BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId())
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + bookLoreUser.getId()));
OpdsUserV2Entity opdsUserV2 = OpdsUserV2Entity.builder() OpdsUserV2Entity opdsUserV2 = OpdsUserV2Entity.builder()
.user(userEntity) .user(userEntity)
.username(request.getUsername()) .username(request.getUsername())
.passwordHash(passwordEncoder.encode(request.getPassword())) .passwordHash(passwordEncoder.encode(request.getPassword()))
.build(); .build();
return mapper.toDto(opdsUserV2Repository.save(opdsUserV2)); return mapper.toDto(opdsUserV2Repository.save(opdsUserV2));
} catch (DataIntegrityViolationException e) {
if (e.getMostSpecificCause().getMessage().contains("uq_username")) {
throw new DataIntegrityViolationException("Username '" + request.getUsername() + "' is already taken");
}
throw e;
}
} }
public void deleteOpdsUser(Long userId) { public void deleteOpdsUser(Long userId) {
@@ -33,7 +33,7 @@ public class OpdsService {
String feedVersion = extractVersionFromAcceptHeader(request); String feedVersion = extractVersionFromAcceptHeader(request);
return switch (feedVersion) { return switch (feedVersion) {
case "2.0" -> generateOpdsV2Feed(books); case "2.0" -> generateOpdsV2Feed(books);
default -> generateOpdsV1Feed(books); default -> generateOpdsV1Feed(books, request);
}; };
} }
@@ -42,7 +42,7 @@ public class OpdsService {
String feedVersion = extractVersionFromAcceptHeader(request); String feedVersion = extractVersionFromAcceptHeader(request);
return switch (feedVersion) { return switch (feedVersion) {
case "2.0" -> generateOpdsV2Feed(books); case "2.0" -> generateOpdsV2Feed(books);
default -> generateOpdsV1Feed(books); default -> generateOpdsV1Feed(books, request);
}; };
} }
@@ -109,29 +109,31 @@ public class OpdsService {
"""; """;
} }
private String generateOpdsV1Feed(List<Book> books) { private String generateOpdsV1Feed(List<Book> books, HttpServletRequest request) {
String version = extractVersionFromRequest(request); // v1 or v2
var feed = new StringBuilder(""" var feed = new StringBuilder("""
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/"> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/">
<title>Booklore Catalog</title> <title>Booklore Catalog</title>
<id>urn:booklore:catalog</id> <id>urn:booklore:catalog</id>
<updated>%s</updated> <updated>%s</updated>
<link rel="search" type="application/opensearchdescription+xml" title="Booklore Search" href="/api/v1/opds/search.opds"/> <link rel="search" type="application/opensearchdescription+xml" title="Booklore Search" href="/api/%s/opds/search.opds"/>
""".formatted(now())); """.formatted(now(), version));
books.forEach(book -> appendBookEntryV1(feed, book)); books.forEach(book -> appendBookEntryV1(feed, book, version));
feed.append("</feed>"); feed.append("</feed>");
return feed.toString(); return feed.toString();
} }
private void appendBookEntryV1(StringBuilder feed, Book book) { private void appendBookEntryV1(StringBuilder feed, Book book, String version) {
feed.append(""" feed.append("""
<entry> <entry>
<title>%s</title> <title>%s</title>
<id>urn:booklore:book:%d</id> <id>urn:booklore:book:%d</id>
<updated>%s</updated> <updated>%s</updated>
""".formatted(escapeXml(book.getMetadata().getTitle()), book.getId(), book.getAddedOn() != null ? book.getAddedOn() : now())); """.formatted(escapeXml(book.getMetadata().getTitle()), book.getId(),
book.getAddedOn() != null ? book.getAddedOn() : now()));
book.getMetadata().getAuthors().forEach(author -> feed.append(""" book.getMetadata().getAuthors().forEach(author -> feed.append("""
<author> <author>
@@ -139,11 +141,13 @@ public class OpdsService {
</author> </author>
""".formatted(escapeXml(author)))); """.formatted(escapeXml(author))));
appendOptionalTags(feed, book); appendOptionalTags(feed, book, version);
feed.append(" </entry>"); feed.append(" </entry>");
} }
private void appendOptionalTags(StringBuilder feed, Book book) { private void appendOptionalTags(StringBuilder feed, Book book, String version) {
String basePath = "/api/" + version + "/opds/";
if (book.getMetadata().getPublisher() != null) { if (book.getMetadata().getPublisher() != null) {
feed.append("<dc:publisher>").append(escapeXml(book.getMetadata().getPublisher())).append("</dc:publisher>"); feed.append("<dc:publisher>").append(escapeXml(book.getMetadata().getPublisher())).append("</dc:publisher>");
} }
@@ -166,12 +170,14 @@ public class OpdsService {
feed.append("<published>").append(book.getMetadata().getPublishedDate()).append("</published>"); feed.append("<published>").append(book.getMetadata().getPublishedDate()).append("</published>");
} }
// download link
feed.append(""" feed.append("""
<link href="/api/v1/opds/%d/download" rel="http://opds-spec.org/acquisition" type="application/%s"/> <link href="%s%d/download" rel="http://opds-spec.org/acquisition" type="application/%s"/>
""".formatted(book.getId(), fileMimeType(book))); """.formatted(basePath, book.getId(), fileMimeType(book)));
// cover link
if (book.getMetadata().getCoverUpdatedOn() != null) { if (book.getMetadata().getCoverUpdatedOn() != null) {
String coverPath = "/api/v1/opds/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn(); String coverPath = basePath + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
feed.append(""" feed.append("""
<link rel="http://opds-spec.org/image" href="%s" type="image/jpeg"/> <link rel="http://opds-spec.org/image" href="%s" type="image/jpeg"/>
<link rel="http://opds-spec.org/image/thumbnail" href="%s" type="image/jpeg"/> <link rel="http://opds-spec.org/image/thumbnail" href="%s" type="image/jpeg"/>
@@ -217,4 +223,8 @@ public class OpdsService {
.replace("\"", "&quot;") .replace("\"", "&quot;")
.replace("'", "&apos;"); .replace("'", "&apos;");
} }
private String extractVersionFromRequest(HttpServletRequest request) {
return (request.getRequestURI() != null && request.getRequestURI().startsWith("/api/v2/opds")) ? "v2" : "v1";
}
} }
@@ -0,0 +1,8 @@
ALTER TABLE opds_user_v2
DROP FOREIGN KEY fk_opds_user;
ALTER TABLE opds_user_v2
DROP INDEX uq_userid_username;
ALTER TABLE opds_user_v2
ADD CONSTRAINT uq_username UNIQUE (username);
ALTER TABLE opds_user_v2
ADD CONSTRAINT fk_opds_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
@@ -47,6 +47,7 @@ class OpdsServiceTest {
when(details.getOpdsUser()).thenReturn(mock(OpdsUser.class)); when(details.getOpdsUser()).thenReturn(mock(OpdsUser.class));
when(request.getHeader("Accept")).thenReturn(null); when(request.getHeader("Accept")).thenReturn(null);
when(request.getRequestURI()).thenReturn("/opds/catalog");
when(bookQueryService.getAllBooks(true)).thenReturn(List.of()); // minimal stub when(bookQueryService.getAllBooks(true)).thenReturn(List.of()); // minimal stub
String feed = service.generateCatalogFeed(request); String feed = service.generateCatalogFeed(request);
@@ -74,6 +75,7 @@ class OpdsServiceTest {
when(bookQueryService.searchBooksByMetadata("query")).thenReturn(List.of(book)); when(bookQueryService.searchBooksByMetadata("query")).thenReturn(List.of(book));
when(request.getHeader("Accept")).thenReturn(null); when(request.getHeader("Accept")).thenReturn(null);
when(request.getRequestURI()).thenReturn("/opds/search");
String feed = service.generateSearchResults(request, "query"); String feed = service.generateSearchResults(request, "query");
@@ -104,14 +106,51 @@ class OpdsServiceTest {
when(userDto.getPermissions()).thenReturn(dtoPerms); when(userDto.getPermissions()).thenReturn(dtoPerms);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(userDto); when(bookLoreUserTransformer.toDTO(entity)).thenReturn(userDto);
// Accept header drives v2 selection; do not stub request.getRequestURI() (unused here)
when(request.getHeader("Accept")).thenReturn("application/opds+json;version=2.0"); when(request.getHeader("Accept")).thenReturn("application/opds+json;version=2.0");
// stub the backend call exercised by getAllowedBooks for admin + no query
when(bookQueryService.getAllBooks(true)).thenReturn(List.of()); when(bookQueryService.getAllBooks(true)).thenReturn(List.of());
String feed = service.generateCatalogFeed(request); String feed = service.generateCatalogFeed(request);
assertEquals("OPDS v2.0 Feed is under construction", feed); assertEquals("OPDS v2.0 Feed is under construction", feed);
verify(bookQueryService).getAllBooks(true);
verify(userRepository).findById(9L); verify(userRepository).findById(9L);
verify(bookQueryService).getAllBooks(true);
}
@Test
void generateSearchResults_opdsV2_callsSearch_and_returnsV2Placeholder() {
// Setup v2 user (admin) so getAllowedBooks will call searchBooksByMetadata(query)
OpdsUserDetails details = mock(OpdsUserDetails.class);
when(authenticationService.getOpdsUser()).thenReturn(details);
when(details.getOpdsUser()).thenReturn(null);
OpdsUserV2 opdsUserV2 = mock(OpdsUserV2.class);
when(details.getOpdsUserV2()).thenReturn(opdsUserV2);
when(opdsUserV2.getUserId()).thenReturn(9L);
BookLoreUserEntity entity = mock(BookLoreUserEntity.class, RETURNS_DEEP_STUBS);
when(entity.getPermissions().isPermissionAccessOpds()).thenReturn(true);
when(userRepository.findById(9L)).thenReturn(Optional.of(entity));
BookLoreUser userDto = mock(BookLoreUser.class);
BookLoreUser.UserPermissions dtoPerms = mock(BookLoreUser.UserPermissions.class);
when(dtoPerms.isAdmin()).thenReturn(true);
when(userDto.getPermissions()).thenReturn(dtoPerms);
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(userDto);
// Accept header drives v2 selection; do not stub request.getRequestURI()
when(request.getHeader("Accept")).thenReturn("application/opds+json;version=2.0");
// getAllowedBooks will invoke searchBooksByMetadata for admin + query
when(bookQueryService.searchBooksByMetadata("query")).thenReturn(List.of(mock(Book.class)));
String feed = service.generateSearchResults(request, "query");
assertEquals("OPDS v2.0 Feed is under construction", feed);
verify(userRepository).findById(9L);
verify(bookQueryService).searchBooksByMetadata("query");
} }
@Test @Test
@@ -141,6 +180,7 @@ class OpdsServiceTest {
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(userDto); when(bookLoreUserTransformer.toDTO(entity)).thenReturn(userDto);
when(request.getHeader("Accept")).thenReturn(null); // v1 default; feed version not relevant for allowed-books logic when(request.getHeader("Accept")).thenReturn(null); // v1 default; feed version not relevant for allowed-books logic
when(request.getRequestURI()).thenReturn("/opds/catalog");
when(bookQueryService.getAllBooksByLibraryIds(Set.of(7L), true)).thenReturn(List.of()); when(bookQueryService.getAllBooksByLibraryIds(Set.of(7L), true)).thenReturn(List.of());
String feed = service.generateCatalogFeed(request); String feed = service.generateCatalogFeed(request);
@@ -166,4 +206,11 @@ class OpdsServiceTest {
assertTrue(ex.getMessage().contains("User not found")); assertTrue(ex.getMessage().contains("User not found"));
verify(userRepository).findById(42L); verify(userRepository).findById(42L);
} }
@Test
void generateSearchDescription_opdsV2_returnsV2Placeholder() {
when(request.getHeader("Accept")).thenReturn("application/opds+json;version=2.0");
String desc = service.generateSearchDescription(request);
assertEquals("OPDS v2.0 Feed is under construction", desc);
}
} }
@@ -13,7 +13,7 @@
</i> </i>
</h2> </h2>
<p class="settings-description"> <p class="settings-description">
Configure KOReader integration to sync your reading progress and annotations between your device and Booklore library. Configure KOReader integration to sync your reading progress between your device and Booklore library.
</p> </p>
</div> </div>
@@ -45,7 +45,7 @@
</p-toggle-switch> </p-toggle-switch>
</div> </div>
<p class="setting-description"> <p class="setting-description">
Turn on synchronization to automatically sync your reading progress and annotations. Turn on synchronization to automatically sync your reading progress.
</p> </p>
</div> </div>
</div> </div>
@@ -103,9 +103,11 @@
<p class="setting-description"> <p class="setting-description">
Your username for authenticating with the KOReader sync service. Your username for authenticating with the KOReader sync service.
</p> </p>
<small *ngIf="editMode && usernameModel.invalid && usernameModel.touched" class="error-message"> @if (editMode && usernameModel.invalid && usernameModel.touched) {
<small class="error-message">
Username is required. Username is required.
</small> </small>
}
</div> </div>
</div> </div>
@@ -145,9 +147,11 @@
<p class="setting-description"> <p class="setting-description">
Your password for authenticating with the KOReader sync service. Your password for authenticating with the KOReader sync service.
</p> </p>
<small *ngIf="editMode && passwordModel.invalid && passwordModel.touched" class="error-message"> @if (editMode && passwordModel.invalid && passwordModel.touched) {
<small class="error-message">
Password must be at least 6 characters. Password must be at least 6 characters.
</small> </small>
}
</div> </div>
</div> </div>
@@ -28,13 +28,13 @@ import {Password} from 'primeng/password';
TableModule, TableModule,
Password Password
], ],
providers: [ConfirmationService, MessageService], providers: [ConfirmationService],
templateUrl: './opds-settings-v2.html', templateUrl: './opds-settings-v2.html',
styleUrl: './opds-settings-v2.scss' styleUrl: './opds-settings-v2.scss'
}) })
export class OpdsSettingsV2 implements OnInit, OnDestroy { export class OpdsSettingsV2 implements OnInit, OnDestroy {
opdsEndpoint = `${API_CONFIG.BASE_URL}/api/v1/opds/catalog`; opdsEndpoint = `${API_CONFIG.BASE_URL}/api/v2/opds/catalog`;
private opdsService = inject(OpdsV2Service); private opdsService = inject(OpdsV2Service);
private confirmationService = inject(ConfirmationService); private confirmationService = inject(ConfirmationService);
@@ -84,17 +84,18 @@ export class OpdsSettingsV2 implements OnInit, OnDestroy {
if (!this.newUser.username || !this.newUser.password) return; if (!this.newUser.username || !this.newUser.password) return;
this.opdsService.createUser(this.newUser).pipe( this.opdsService.createUser(this.newUser).pipe(
takeUntil(this.destroy$), takeUntil(this.destroy$)
catchError(err => { ).subscribe({
console.error('Error creating user:', err); next: user => {
this.showMessage('error', 'Error', 'Failed to create user');
return of(null);
})
).subscribe(user => {
if (!user) return;
this.users.push(user); this.users.push(user);
this.resetCreateUserDialog(); this.resetCreateUserDialog();
this.showMessage('success', 'Success', 'User created successfully'); this.showMessage('success', 'Success', 'User created successfully');
},
error: err => {
console.error('Error creating user:', err);
const message = err?.error?.message || 'Failed to create user';
this.showMessage('error', 'Error', message);
}
}); });
} }