Implement streaming EPUB reader with on-demand loading (#2350)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-19 18:07:57 -07:00
committed by GitHub
co-authored by acx10
parent da83a70281
commit 7efb0e138d
36 changed files with 2237 additions and 106 deletions
@@ -168,6 +168,21 @@ public class SecurityConfig {
@Bean
@Order(6)
public SecurityFilterChain epubStreamingSecurityChain(HttpSecurity http, EpubStreamingJwtFilter epubStreamingJwtFilter) throws Exception {
http
.securityMatcher("/api/v1/epub/*/file/**")
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
)
.addFilterBefore(epubStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
@Order(7)
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
if (appProperties.getSwagger().isEnabled()) {
@@ -0,0 +1,117 @@
package com.adityachandel.booklore.config.security.filter;
import com.adityachandel.booklore.config.security.JwtUtils;
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.time.Instant;
/**
* JWT filter for EPUB streaming endpoints that supports both:
* 1. Authorization header (Bearer token) - for fetch() requests
* 2. Query parameter (token) - for browser-initiated requests (fonts, images in CSS)
*/
@Component
@AllArgsConstructor
public class EpubStreamingJwtFilter extends OncePerRequestFilter {
private final JwtUtils jwtUtils;
private final UserRepository userRepository;
private final BookLoreUserTransformer bookLoreUserTransformer;
private final AppSettingService appSettingService;
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
// Only filter requests to EPUB file streaming endpoint
return !path.matches("/api/v1/epub/\\d+/file/.*");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// Try Authorization header first, then fall back to query parameter
String token = extractTokenFromHeader(request);
if (token == null) {
token = request.getParameter("token");
}
if (token == null || token.isEmpty()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
return;
}
try {
if (jwtUtils.validateToken(token)) {
authenticateLocalUser(token, request);
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
authenticateOidcUser(token, request);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
return;
}
} catch (Exception ex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
return;
}
chain.doFilter(request, response);
}
private String extractTokenFromHeader(HttpServletRequest request) {
String bearer = request.getHeader("Authorization");
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
}
private void authenticateLocalUser(String token, HttpServletRequest request) {
Long userId = jwtUtils.extractUserId(token);
BookLoreUserEntity entity = userRepository.findById(userId)
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(user, null, null);
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
var processor = dynamicOidcJwtProcessor.getProcessor();
var claimsSet = processor.process(token, null);
if (claimsSet.getExpirationTime() == null ||
claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
throw new RuntimeException("OIDC token expired or invalid");
}
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
String username = claimsSet.getStringClaim(claimMapping.getUsername());
BookLoreUserEntity entity = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(user, null, null);
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
@@ -0,0 +1,71 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.response.EpubBookInfo;
import com.adityachandel.booklore.service.reader.EpubReaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/api/v1/epub")
@RequiredArgsConstructor
@Tag(name = "EPUB Reader", description = "Endpoints for reading EPUB format books with streaming support")
public class EpubReaderController {
private final EpubReaderService epubReaderService;
@Operation(summary = "Get EPUB book info",
description = "Retrieve parsed metadata, spine, manifest, and TOC for an EPUB book.")
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
@GetMapping("/{bookId}/info")
public ResponseEntity<EpubBookInfo> getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return ResponseEntity.ok(epubReaderService.getBookInfo(bookId));
}
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
@ApiResponse(responseCode = "200", description = "File content returned successfully")
@GetMapping("/{bookId}/file/**")
public void getFile(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String prefix = "/api/v1/epub/" + bookId + "/file/";
String filePath = fullPath.substring(prefix.length());
filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
String contentType = epubReaderService.getContentType(bookId, filePath);
response.setContentType(contentType);
long fileSize = epubReaderService.getFileSize(bookId, filePath);
if (fileSize > 0) {
response.setContentLengthLong(fileSize);
}
if (contentType.startsWith("font/") ||
"application/font-woff".equals(contentType) ||
"application/font-woff2".equals(contentType) ||
"application/vnd.ms-fontobject".equals(contentType)) {
response.setHeader("Access-Control-Allow-Origin", "*");
}
response.setHeader("Cache-Control", "public, max-age=3600");
epubReaderService.streamFile(bookId, filePath, response.getOutputStream());
}
}
@@ -217,4 +217,4 @@ public class KoboController {
}
return koboServerProxy.proxyCurrentRequest(body, false);
}
}
}
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubBookInfo {
private String containerPath;
private String rootPath;
private List<EpubSpineItem> spine;
private List<EpubManifestItem> manifest;
private EpubTocItem toc;
private Map<String, Object> metadata;
private String coverPath;
}
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubManifestItem {
private String id;
private String href;
private String mediaType;
private List<String> properties;
private long size;
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubSpineItem {
private String idref;
private String href;
private String mediaType;
private boolean linear;
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class EpubTocItem {
private String label;
private String href;
private List<EpubTocItem> children;
}
@@ -0,0 +1,697 @@
package com.adityachandel.booklore.service.reader;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.response.EpubBookInfo;
import com.adityachandel.booklore.model.dto.response.EpubManifestItem;
import com.adityachandel.booklore.model.dto.response.EpubSpineItem;
import com.adityachandel.booklore.model.dto.response.EpubTocItem;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.util.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.pdfbox.io.IOUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Service
@RequiredArgsConstructor
public class EpubReaderService {
private static final String CONTAINER_PATH = "META-INF/container.xml";
private static final String CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container";
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
private static final String DC_NS = "http://purl.org/dc/elements/1.1/";
private static final String NCX_NS = "http://www.daisy.org/z3986/2005/ncx/";
private static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
private static final String EPUB_NS = "http://www.idpf.org/2007/ops";
private static final int MAX_CACHE_ENTRIES = 50;
private static final Charset[] ENCODINGS_TO_TRY = {
StandardCharsets.UTF_8,
StandardCharsets.ISO_8859_1,
Charset.forName("CP437")
};
private final BookRepository bookRepository;
private final Map<String, CachedEpubMetadata> metadataCache = new ConcurrentHashMap<>();
private static class CachedEpubMetadata {
final EpubBookInfo bookInfo;
final long lastModified;
final Charset successfulEncoding;
volatile long lastAccessed;
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified, Charset encoding) {
this.bookInfo = bookInfo;
this.lastModified = lastModified;
this.successfulEncoding = encoding;
this.lastAccessed = System.currentTimeMillis();
}
}
public EpubBookInfo getBookInfo(Long bookId) {
Path epubPath = getBookPath(bookId);
try {
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
return metadata.bookInfo;
} catch (IOException e) {
log.error("Failed to read EPUB for book {}", bookId, e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read EPUB: " + e.getMessage());
}
}
public void streamFile(Long bookId, String filePath, OutputStream outputStream) throws IOException {
Path epubPath = getBookPath(bookId);
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
String cleanPath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
String actualPath;
if (CONTAINER_PATH.equals(cleanPath) || cleanPath.equals(metadata.bookInfo.getContainerPath())) {
actualPath = cleanPath;
} else {
actualPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
}
if (!isValidPath(actualPath, metadata.bookInfo)) {
throw new FileNotFoundException("File not found in EPUB: " + filePath);
}
streamEntryFromZip(epubPath, actualPath, outputStream, metadata.successfulEncoding);
}
public String getContentType(Long bookId, String filePath) {
Path epubPath = getBookPath(bookId);
try {
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
return metadata.bookInfo.getManifest().stream()
.filter(item -> item.getHref().equals(normalizedPath))
.findFirst()
.map(EpubManifestItem::getMediaType)
.orElse(guessContentType(filePath));
} catch (IOException e) {
return guessContentType(filePath);
}
}
public long getFileSize(Long bookId, String filePath) {
Path epubPath = getBookPath(bookId);
try {
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
return metadata.bookInfo.getManifest().stream()
.filter(item -> item.getHref().equals(normalizedPath))
.findFirst()
.map(EpubManifestItem::getSize)
.orElse(0L);
} catch (IOException e) {
return 0L;
}
}
private Path getBookPath(Long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
return Path.of(bookFullPath);
}
private CachedEpubMetadata getCachedMetadata(Path epubPath) throws IOException {
String cacheKey = epubPath.toString();
long currentModified = Files.getLastModifiedTime(epubPath).toMillis();
CachedEpubMetadata cached = metadataCache.get(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
log.debug("Cache hit for EPUB: {}", epubPath.getFileName());
return cached;
}
log.debug("Cache miss for EPUB: {}, parsing...", epubPath.getFileName());
CachedEpubMetadata newMetadata = parseEpubMetadata(epubPath, currentModified);
metadataCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
private void evictOldestCacheEntries() {
if (metadataCache.size() <= MAX_CACHE_ENTRIES) {
return;
}
List<String> keysToRemove = metadataCache.entrySet().stream()
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
.limit(metadataCache.size() - MAX_CACHE_ENTRIES)
.map(Map.Entry::getKey)
.toList();
keysToRemove.forEach(key -> {
metadataCache.remove(key);
log.debug("Evicted EPUB cache entry: {}", key);
});
}
private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException {
for (Charset encoding : ENCODINGS_TO_TRY) {
try {
EpubBookInfo bookInfo = parseEpubWithEncoding(epubPath, encoding);
return new CachedEpubMetadata(bookInfo, lastModified, encoding);
} catch (Exception e) {
log.debug("Failed to parse EPUB with encoding {}: {}", encoding, e.getMessage());
}
}
throw new IOException("Unable to parse EPUB with any supported encoding");
}
private EpubBookInfo parseEpubWithEncoding(Path epubPath, Charset charset) throws Exception {
try (ZipFile zipFile = ZipFile.builder()
.setPath(epubPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.get()) {
String opfPath = parseContainerXml(zipFile);
String rootPath = opfPath.contains("/") ? opfPath.substring(0, opfPath.lastIndexOf('/') + 1) : "";
Document opfDoc = parseXmlEntry(zipFile, opfPath);
Element packageEl = opfDoc.getDocumentElement();
List<EpubManifestItem> manifest = parseManifest(opfDoc, rootPath, zipFile);
Map<String, EpubManifestItem> manifestById = new HashMap<>();
for (EpubManifestItem item : manifest) {
manifestById.put(item.getId(), item);
}
List<EpubSpineItem> spine = parseSpine(opfDoc, manifestById);
Map<String, Object> metadata = parseMetadata(opfDoc);
String navPath = null;
String ncxPath = null;
for (EpubManifestItem item : manifest) {
if (item.getProperties() != null && item.getProperties().contains("nav")) {
navPath = item.getHref();
}
if ("application/x-dtbncx+xml".equals(item.getMediaType())) {
ncxPath = item.getHref();
}
}
EpubTocItem toc = null;
if (navPath != null) {
try {
toc = parseNavDocument(zipFile, navPath, rootPath);
} catch (Exception e) {
log.warn("Failed to parse nav document, trying NCX: {}", e.getMessage());
}
}
if (toc == null && ncxPath != null) {
try {
toc = parseNcx(zipFile, ncxPath, rootPath);
} catch (Exception e) {
log.warn("Failed to parse NCX: {}", e.getMessage());
}
}
String coverPath = findCoverPath(opfDoc, manifest, manifestById);
return EpubBookInfo.builder()
.containerPath(opfPath)
.rootPath(rootPath)
.spine(spine)
.manifest(manifest)
.toc(toc)
.metadata(metadata)
.coverPath(coverPath)
.build();
}
}
private String parseContainerXml(ZipFile zipFile) throws Exception {
Document doc = parseXmlEntry(zipFile, CONTAINER_PATH);
NodeList rootfiles = doc.getElementsByTagNameNS(CONTAINER_NS, "rootfile");
if (rootfiles.getLength() == 0) {
rootfiles = doc.getElementsByTagName("rootfile");
}
if (rootfiles.getLength() == 0) {
throw new IOException("No rootfile found in container.xml");
}
Element rootfile = (Element) rootfiles.item(0);
String fullPath = rootfile.getAttribute("full-path");
if (fullPath == null || fullPath.isEmpty()) {
throw new IOException("No full-path attribute in rootfile");
}
return fullPath;
}
private List<EpubManifestItem> parseManifest(Document opfDoc, String rootPath, ZipFile zipFile) {
List<EpubManifestItem> manifest = new ArrayList<>();
NodeList items = opfDoc.getElementsByTagNameNS(OPF_NS, "item");
if (items.getLength() == 0) {
items = opfDoc.getElementsByTagName("item");
}
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String id = item.getAttribute("id");
String href = item.getAttribute("href");
String mediaType = item.getAttribute("media-type");
String properties = item.getAttribute("properties");
String fullHref = rootPath + href;
long size = getEntrySize(zipFile, fullHref);
List<String> propList = null;
if (properties != null && !properties.isEmpty()) {
propList = Arrays.asList(properties.split("\\s+"));
}
manifest.add(EpubManifestItem.builder()
.id(id)
.href(fullHref)
.mediaType(mediaType)
.properties(propList)
.size(size)
.build());
}
return manifest;
}
private List<EpubSpineItem> parseSpine(Document opfDoc, Map<String, EpubManifestItem> manifestById) {
List<EpubSpineItem> spine = new ArrayList<>();
NodeList itemrefs = opfDoc.getElementsByTagNameNS(OPF_NS, "itemref");
if (itemrefs.getLength() == 0) {
itemrefs = opfDoc.getElementsByTagName("itemref");
}
for (int i = 0; i < itemrefs.getLength(); i++) {
Element itemref = (Element) itemrefs.item(i);
String idref = itemref.getAttribute("idref");
String linear = itemref.getAttribute("linear");
EpubManifestItem manifestItem = manifestById.get(idref);
if (manifestItem != null) {
spine.add(EpubSpineItem.builder()
.idref(idref)
.href(manifestItem.getHref())
.mediaType(manifestItem.getMediaType())
.linear(!"no".equals(linear))
.build());
}
}
return spine;
}
private Map<String, Object> parseMetadata(Document opfDoc) {
Map<String, Object> metadata = new HashMap<>();
String title = getElementTextByNS(opfDoc, DC_NS, "title");
if (title == null) title = getElementText(opfDoc, "dc:title");
if (title != null) metadata.put("title", title);
String creator = getElementTextByNS(opfDoc, DC_NS, "creator");
if (creator == null) creator = getElementText(opfDoc, "dc:creator");
if (creator != null) metadata.put("creator", creator);
String language = getElementTextByNS(opfDoc, DC_NS, "language");
if (language == null) language = getElementText(opfDoc, "dc:language");
if (language != null) metadata.put("language", language);
String publisher = getElementTextByNS(opfDoc, DC_NS, "publisher");
if (publisher == null) publisher = getElementText(opfDoc, "dc:publisher");
if (publisher != null) metadata.put("publisher", publisher);
String identifier = getElementTextByNS(opfDoc, DC_NS, "identifier");
if (identifier == null) identifier = getElementText(opfDoc, "dc:identifier");
if (identifier != null) metadata.put("identifier", identifier);
String description = getElementTextByNS(opfDoc, DC_NS, "description");
if (description == null) description = getElementText(opfDoc, "dc:description");
if (description != null) metadata.put("description", description);
return metadata;
}
private EpubTocItem parseNavDocument(ZipFile zipFile, String navPath, String rootPath) throws Exception {
Document doc = parseXmlEntry(zipFile, navPath);
NodeList navs = doc.getElementsByTagNameNS(XHTML_NS, "nav");
if (navs.getLength() == 0) {
navs = doc.getElementsByTagName("nav");
}
Element tocNav = null;
for (int i = 0; i < navs.getLength(); i++) {
Element nav = (Element) navs.item(i);
String type = nav.getAttributeNS(EPUB_NS, "type");
if (type == null || type.isEmpty()) {
type = nav.getAttribute("epub:type");
}
if ("toc".equals(type)) {
tocNav = nav;
break;
}
}
if (tocNav == null && navs.getLength() > 0) {
tocNav = (Element) navs.item(0);
}
if (tocNav == null) {
return null;
}
NodeList ols = tocNav.getElementsByTagNameNS(XHTML_NS, "ol");
if (ols.getLength() == 0) {
ols = tocNav.getElementsByTagName("ol");
}
if (ols.getLength() == 0) {
return null;
}
String navDir = navPath.contains("/") ? navPath.substring(0, navPath.lastIndexOf('/') + 1) : rootPath;
List<EpubTocItem> children = parseNavOl((Element) ols.item(0), navDir);
return EpubTocItem.builder()
.label("Table of Contents")
.children(children)
.build();
}
private List<EpubTocItem> parseNavOl(Element ol, String basePath) {
List<EpubTocItem> items = new ArrayList<>();
NodeList children = ol.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element li && "li".equals(li.getLocalName())) {
EpubTocItem item = parseNavLi(li, basePath);
if (item != null) {
items.add(item);
}
}
}
return items;
}
private EpubTocItem parseNavLi(Element li, String basePath) {
Element link = null;
NodeList children = li.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element el) {
if ("a".equals(el.getLocalName()) || "span".equals(el.getLocalName())) {
link = el;
break;
}
}
}
if (link == null) return null;
String label = link.getTextContent().trim();
String href = link.getAttribute("href");
if (href != null && !href.isEmpty() && !href.startsWith("http")) {
href = resolveHref(href, basePath);
}
List<EpubTocItem> subItems = null;
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i) instanceof Element el && "ol".equals(el.getLocalName())) {
subItems = parseNavOl(el, basePath);
break;
}
}
return EpubTocItem.builder()
.label(label)
.href(href)
.children(subItems)
.build();
}
private EpubTocItem parseNcx(ZipFile zipFile, String ncxPath, String rootPath) throws Exception {
Document doc = parseXmlEntry(zipFile, ncxPath);
NodeList navMaps = doc.getElementsByTagNameNS(NCX_NS, "navMap");
if (navMaps.getLength() == 0) {
navMaps = doc.getElementsByTagName("navMap");
}
if (navMaps.getLength() == 0) {
return null;
}
Element navMap = (Element) navMaps.item(0);
String ncxDir = ncxPath.contains("/") ? ncxPath.substring(0, ncxPath.lastIndexOf('/') + 1) : rootPath;
List<EpubTocItem> children = parseNcxNavPoints(navMap, ncxDir);
return EpubTocItem.builder()
.label("Table of Contents")
.children(children)
.build();
}
private List<EpubTocItem> parseNcxNavPoints(Element parent, String basePath) {
List<EpubTocItem> items = new ArrayList<>();
NodeList navPoints = parent.getChildNodes();
for (int i = 0; i < navPoints.getLength(); i++) {
if (navPoints.item(i) instanceof Element el && "navPoint".equals(el.getLocalName())) {
EpubTocItem item = parseNcxNavPoint(el, basePath);
if (item != null) {
items.add(item);
}
}
}
return items;
}
private EpubTocItem parseNcxNavPoint(Element navPoint, String basePath) {
String label = null;
NodeList labels = navPoint.getElementsByTagNameNS(NCX_NS, "navLabel");
if (labels.getLength() == 0) {
labels = navPoint.getElementsByTagName("navLabel");
}
if (labels.getLength() > 0) {
Element labelEl = (Element) labels.item(0);
NodeList texts = labelEl.getElementsByTagNameNS(NCX_NS, "text");
if (texts.getLength() == 0) {
texts = labelEl.getElementsByTagName("text");
}
if (texts.getLength() > 0) {
label = texts.item(0).getTextContent().trim();
}
}
String href = null;
NodeList contents = navPoint.getElementsByTagNameNS(NCX_NS, "content");
if (contents.getLength() == 0) {
contents = navPoint.getElementsByTagName("content");
}
if (contents.getLength() > 0) {
Element content = (Element) contents.item(0);
href = content.getAttribute("src");
if (href != null && !href.isEmpty()) {
href = resolveHref(href, basePath);
}
}
List<EpubTocItem> subItems = parseNcxNavPoints(navPoint, basePath);
return EpubTocItem.builder()
.label(label)
.href(href)
.children(subItems.isEmpty() ? null : subItems)
.build();
}
private String findCoverPath(Document opfDoc, List<EpubManifestItem> manifest, Map<String, EpubManifestItem> manifestById) {
for (EpubManifestItem item : manifest) {
if (item.getProperties() != null && item.getProperties().contains("cover-image")) {
return item.getHref();
}
}
NodeList metas = opfDoc.getElementsByTagNameNS(OPF_NS, "meta");
if (metas.getLength() == 0) {
metas = opfDoc.getElementsByTagName("meta");
}
for (int i = 0; i < metas.getLength(); i++) {
Element meta = (Element) metas.item(i);
if ("cover".equals(meta.getAttribute("name"))) {
String coverId = meta.getAttribute("content");
EpubManifestItem coverItem = manifestById.get(coverId);
if (coverItem != null) {
return coverItem.getHref();
}
}
}
return null;
}
private Document parseXmlEntry(ZipFile zipFile, String entryPath) throws Exception {
ZipArchiveEntry entry = zipFile.getEntry(entryPath);
if (entry == null) {
throw new FileNotFoundException("Entry not found: " + entryPath);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
DocumentBuilder builder = factory.newDocumentBuilder();
try (InputStream is = zipFile.getInputStream(entry)) {
return builder.parse(is);
}
}
private long getEntrySize(ZipFile zipFile, String entryPath) {
ZipArchiveEntry entry = zipFile.getEntry(entryPath);
return entry != null ? entry.getSize() : 0;
}
private String getElementTextByNS(Document doc, String ns, String tagName) {
NodeList nodes = doc.getElementsByTagNameNS(ns, tagName);
if (nodes.getLength() > 0) {
return nodes.item(0).getTextContent().trim();
}
return null;
}
private String getElementText(Document doc, String tagName) {
NodeList nodes = doc.getElementsByTagName(tagName);
if (nodes.getLength() > 0) {
return nodes.item(0).getTextContent().trim();
}
return null;
}
private String resolveHref(String href, String basePath) {
if (href == null || href.isEmpty()) return href;
if (href.startsWith("/")) return href.substring(1);
if (href.startsWith("http://") || href.startsWith("https://")) return href;
String result = basePath + href;
while (result.contains("/../")) {
int idx = result.indexOf("/../");
int prevSlash = result.lastIndexOf('/', idx - 1);
if (prevSlash >= 0) {
result = result.substring(0, prevSlash) + result.substring(idx + 3);
} else {
break;
}
}
return result;
}
private String normalizePath(String path, String rootPath) {
if (path == null) return null;
String normalized = path.startsWith("/") ? path.substring(1) : path;
if (rootPath != null && !rootPath.isEmpty() && normalized.startsWith(rootPath)) {
return normalized;
}
if (rootPath != null && !rootPath.isEmpty()) {
return rootPath + normalized;
}
return normalized;
}
private boolean isValidPath(String path, EpubBookInfo info) {
if (path == null) return false;
if (path.contains("..")) return false;
if (CONTAINER_PATH.equals(path)) return true;
if (info.getContainerPath() != null && info.getContainerPath().equals(path)) return true;
return info.getManifest().stream()
.anyMatch(item -> item.getHref().equals(path));
}
private void streamEntryFromZip(Path epubPath, String entryName, OutputStream outputStream, Charset cachedEncoding) throws IOException {
if (cachedEncoding != null) {
if (tryStreamEntryFromZip(epubPath, entryName, outputStream, cachedEncoding)) {
return;
}
}
for (Charset encoding : ENCODINGS_TO_TRY) {
if (encoding.equals(cachedEncoding)) continue;
if (tryStreamEntryFromZip(epubPath, entryName, outputStream, encoding)) {
return;
}
}
throw new IOException("Unable to stream entry from EPUB: " + entryName);
}
private boolean tryStreamEntryFromZip(Path epubPath, String entryName, OutputStream outputStream, Charset charset) throws IOException {
try (ZipFile zipFile = ZipFile.builder()
.setPath(epubPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.get()) {
ZipArchiveEntry entry = zipFile.getEntry(entryName);
if (entry != null) {
try (InputStream in = zipFile.getInputStream(entry)) {
IOUtils.copy(in, outputStream);
}
return true;
}
}
return false;
}
private String guessContentType(String path) {
if (path == null) return "application/octet-stream";
String lower = path.toLowerCase();
if (lower.endsWith(".xhtml") || lower.endsWith(".html") || lower.endsWith(".htm")) {
return "application/xhtml+xml";
}
if (lower.endsWith(".css")) return "text/css";
if (lower.endsWith(".js")) return "application/javascript";
if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
if (lower.endsWith(".png")) return "image/png";
if (lower.endsWith(".gif")) return "image/gif";
if (lower.endsWith(".svg")) return "image/svg+xml";
if (lower.endsWith(".webp")) return "image/webp";
if (lower.endsWith(".woff")) return "font/woff";
if (lower.endsWith(".woff2")) return "font/woff2";
if (lower.endsWith(".ttf")) return "font/ttf";
if (lower.endsWith(".otf")) return "font/otf";
if (lower.endsWith(".eot")) return "application/vnd.ms-fontobject";
if (lower.endsWith(".xml")) return "application/xml";
if (lower.endsWith(".ncx")) return "application/x-dtbncx+xml";
if (lower.endsWith(".smil")) return "application/smil+xml";
if (lower.endsWith(".mp3")) return "audio/mpeg";
if (lower.endsWith(".mp4")) return "video/mp4";
if (lower.endsWith(".webm")) return "video/webm";
return "application/octet-stream";
}
}
@@ -0,0 +1,635 @@
package com.adityachandel.booklore.service.reader;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.response.EpubBookInfo;
import com.adityachandel.booklore.model.dto.response.EpubManifestItem;
import com.adityachandel.booklore.model.dto.response.EpubSpineItem;
import com.adityachandel.booklore.model.dto.response.EpubTocItem;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.util.FileUtils;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class EpubReaderServiceTest {
@Mock
BookRepository bookRepository;
@InjectMocks
EpubReaderService epubReaderService;
BookEntity bookEntity;
Path epubPath;
@TempDir
Path tempDir;
private static final String CONTAINER_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>
""";
private static final String CONTENT_OPF = """
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>Test Book</dc:title>
<dc:creator>Test Author</dc:creator>
<dc:language>en</dc:language>
</metadata>
<manifest>
<item id="chapter1" href="chapter1.xhtml" media-type="application/xhtml+xml"/>
<item id="chapter2" href="chapter2.xhtml" media-type="application/xhtml+xml"/>
<item id="style" href="style.css" media-type="text/css"/>
<item id="cover" href="cover.jpg" media-type="image/jpeg" properties="cover-image"/>
<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
</manifest>
<spine>
<itemref idref="chapter1"/>
<itemref idref="chapter2"/>
</spine>
</package>
""";
private static final String NAV_XHTML = """
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
<head><title>Navigation</title></head>
<body>
<nav epub:type="toc">
<ol>
<li><a href="chapter1.xhtml">Chapter 1</a></li>
<li><a href="chapter2.xhtml">Chapter 2</a></li>
</ol>
</nav>
</body>
</html>
""";
@BeforeEach
void setup() throws Exception {
bookEntity = new BookEntity();
bookEntity.setId(1L);
epubPath = tempDir.resolve("test.epub");
Files.deleteIfExists(epubPath);
}
@Test
void testGetBookInfo_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
assertNotNull(bookInfo);
assertEquals("OEBPS/content.opf", bookInfo.getContainerPath());
assertEquals("OEBPS/", bookInfo.getRootPath());
assertEquals("Test Book", bookInfo.getMetadata().get("title"));
assertEquals("Test Author", bookInfo.getMetadata().get("creator"));
assertEquals("en", bookInfo.getMetadata().get("language"));
assertEquals(5, bookInfo.getManifest().size());
assertEquals(2, bookInfo.getSpine().size());
assertEquals("OEBPS/cover.jpg", bookInfo.getCoverPath());
}
}
}
@Test
void testGetBookInfo_BookNotFound() {
when(bookRepository.findById(999L)).thenReturn(Optional.empty());
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
() -> epubReaderService.getBookInfo(999L));
}
@Test
void testGetBookInfo_CacheHit() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First call - should parse
EpubBookInfo bookInfo1 = epubReaderService.getBookInfo(1L);
// Second call - should use cache
EpubBookInfo bookInfo2 = epubReaderService.getBookInfo(1L);
assertSame(bookInfo1, bookInfo2);
// ZipFile builder should be called only once for parsing
verify(builder, times(1)).get();
}
}
}
@Test
void testStreamFile_Success() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
byte[] chapterContent = "<html><body>Chapter 1 content</body></html>".getBytes(StandardCharsets.UTF_8);
ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent);
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
// Reset mock for streaming call
reset(builder);
when(builder.setPath(epubPath)).thenReturn(builder);
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
when(builder.get()).thenReturn(zipFile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
epubReaderService.streamFile(1L, "chapter1.xhtml", outputStream);
assertArrayEquals(chapterContent, outputStream.toByteArray());
}
}
}
@Test
void testStreamFile_FileNotFound() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
assertThrows(FileNotFoundException.class,
() -> epubReaderService.streamFile(1L, "nonexistent.xhtml", outputStream));
}
}
}
@Test
void testStreamFile_PathTraversalBlocked() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
assertThrows(FileNotFoundException.class,
() -> epubReaderService.streamFile(1L, "../../../etc/passwd", outputStream));
}
}
}
@Test
void testStreamFile_ContainerXmlAllowed() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
byte[] containerContent = CONTAINER_XML.getBytes(StandardCharsets.UTF_8);
ZipFile zipFile = createMockZipFileWithStreamableEntry("META-INF/container.xml", containerContent);
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
// Reset mock for streaming call
reset(builder);
when(builder.setPath(epubPath)).thenReturn(builder);
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
when(builder.get()).thenReturn(zipFile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
epubReaderService.streamFile(1L, "META-INF/container.xml", outputStream);
assertArrayEquals(containerContent, outputStream.toByteArray());
}
}
}
@Test
void testGetContentType_FromManifest() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
assertEquals("application/xhtml+xml", epubReaderService.getContentType(1L, "chapter1.xhtml"));
assertEquals("text/css", epubReaderService.getContentType(1L, "style.css"));
assertEquals("image/jpeg", epubReaderService.getContentType(1L, "cover.jpg"));
}
}
}
@Test
void testGetContentType_Fallback() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
// Unknown file should use fallback guessing
assertEquals("image/png", epubReaderService.getContentType(1L, "image.png"));
assertEquals("image/gif", epubReaderService.getContentType(1L, "animation.gif"));
assertEquals("font/woff2", epubReaderService.getContentType(1L, "font.woff2"));
assertEquals("application/octet-stream", epubReaderService.getContentType(1L, "unknown.xyz"));
}
}
}
@Test
void testGetFileSize_FromManifest() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFileWithSizes();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
assertEquals(1024L, epubReaderService.getFileSize(1L, "chapter1.xhtml"));
assertEquals(2048L, epubReaderService.getFileSize(1L, "chapter2.xhtml"));
}
}
}
@Test
void testGetFileSize_NotFound() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
assertEquals(0L, epubReaderService.getFileSize(1L, "nonexistent.xhtml"));
}
}
}
@Test
void testSpineOrder() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
List<EpubSpineItem> spine = bookInfo.getSpine();
assertEquals(2, spine.size());
assertEquals("chapter1", spine.get(0).getIdref());
assertEquals("OEBPS/chapter1.xhtml", spine.get(0).getHref());
assertEquals("chapter2", spine.get(1).getIdref());
assertEquals("OEBPS/chapter2.xhtml", spine.get(1).getHref());
}
}
}
@Test
void testTocParsing() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
EpubTocItem toc = bookInfo.getToc();
assertNotNull(toc);
assertEquals("Table of Contents", toc.getLabel());
assertNotNull(toc.getChildren());
assertEquals(2, toc.getChildren().size());
assertEquals("Chapter 1", toc.getChildren().get(0).getLabel());
assertEquals("Chapter 2", toc.getChildren().get(1).getLabel());
}
}
}
@Test
void testManifestProperties() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
ZipFile zipFile = createMockZipFile();
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
EpubBookInfo bookInfo = epubReaderService.getBookInfo(1L);
// Find cover item
EpubManifestItem coverItem = bookInfo.getManifest().stream()
.filter(item -> "cover".equals(item.getId()))
.findFirst()
.orElse(null);
assertNotNull(coverItem);
assertNotNull(coverItem.getProperties());
assertTrue(coverItem.getProperties().contains("cover-image"));
// Find nav item
EpubManifestItem navItem = bookInfo.getManifest().stream()
.filter(item -> "nav".equals(item.getId()))
.findFirst()
.orElse(null);
assertNotNull(navItem);
assertNotNull(navItem.getProperties());
assertTrue(navItem.getProperties().contains("nav"));
}
}
}
@Test
void testStreamFile_LeadingSlashHandled() throws Exception {
when(bookRepository.findById(1L)).thenReturn(Optional.of(bookEntity));
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString());
byte[] chapterContent = "<html><body>Chapter 1 content</body></html>".getBytes(StandardCharsets.UTF_8);
ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent);
ZipFile.Builder builder = createMockZipFileBuilder(zipFile);
try (MockedStatic<ZipFile> zipFileStatic = mockStatic(ZipFile.class)) {
zipFileStatic.when(ZipFile::builder).thenReturn(builder);
Files.createFile(epubPath);
Files.setLastModifiedTime(epubPath, FileTime.fromMillis(System.currentTimeMillis()));
// First populate the cache
epubReaderService.getBookInfo(1L);
// Reset mock for streaming call
reset(builder);
when(builder.setPath(epubPath)).thenReturn(builder);
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
when(builder.get()).thenReturn(zipFile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Path with leading slash should work
epubReaderService.streamFile(1L, "/chapter1.xhtml", outputStream);
assertArrayEquals(chapterContent, outputStream.toByteArray());
}
}
}
// Helper methods to create mock ZipFile objects
private ZipFile createMockZipFile() throws Exception {
ZipFile zipFile = mock(ZipFile.class);
// Container entry - use thenAnswer to return fresh stream each time
ZipArchiveEntry containerEntry = mock(ZipArchiveEntry.class);
when(containerEntry.getSize()).thenReturn((long) CONTAINER_XML.length());
when(zipFile.getEntry("META-INF/container.xml")).thenReturn(containerEntry);
when(zipFile.getInputStream(containerEntry))
.thenAnswer(inv -> new ByteArrayInputStream(CONTAINER_XML.getBytes(StandardCharsets.UTF_8)));
// OPF entry
ZipArchiveEntry opfEntry = mock(ZipArchiveEntry.class);
when(opfEntry.getSize()).thenReturn((long) CONTENT_OPF.length());
when(zipFile.getEntry("OEBPS/content.opf")).thenReturn(opfEntry);
when(zipFile.getInputStream(opfEntry))
.thenAnswer(inv -> new ByteArrayInputStream(CONTENT_OPF.getBytes(StandardCharsets.UTF_8)));
// Nav entry
ZipArchiveEntry navEntry = mock(ZipArchiveEntry.class);
when(navEntry.getSize()).thenReturn((long) NAV_XHTML.length());
when(zipFile.getEntry("OEBPS/nav.xhtml")).thenReturn(navEntry);
when(zipFile.getInputStream(navEntry))
.thenAnswer(inv -> new ByteArrayInputStream(NAV_XHTML.getBytes(StandardCharsets.UTF_8)));
// Chapter entries with sizes
ZipArchiveEntry chapter1Entry = mock(ZipArchiveEntry.class);
when(chapter1Entry.getSize()).thenReturn(100L);
when(zipFile.getEntry("OEBPS/chapter1.xhtml")).thenReturn(chapter1Entry);
ZipArchiveEntry chapter2Entry = mock(ZipArchiveEntry.class);
when(chapter2Entry.getSize()).thenReturn(200L);
when(zipFile.getEntry("OEBPS/chapter2.xhtml")).thenReturn(chapter2Entry);
ZipArchiveEntry styleEntry = mock(ZipArchiveEntry.class);
when(styleEntry.getSize()).thenReturn(50L);
when(zipFile.getEntry("OEBPS/style.css")).thenReturn(styleEntry);
ZipArchiveEntry coverEntry = mock(ZipArchiveEntry.class);
when(coverEntry.getSize()).thenReturn(5000L);
when(zipFile.getEntry("OEBPS/cover.jpg")).thenReturn(coverEntry);
return zipFile;
}
private ZipFile createMockZipFileWithStreamableEntry(String entryPath, byte[] content) throws Exception {
ZipFile zipFile = createMockZipFile();
ZipArchiveEntry entry = mock(ZipArchiveEntry.class);
when(entry.getSize()).thenReturn((long) content.length);
when(zipFile.getEntry(entryPath)).thenReturn(entry);
when(zipFile.getInputStream(entry)).thenAnswer(inv -> new ByteArrayInputStream(content));
return zipFile;
}
private ZipFile createMockZipFileWithSizes() throws Exception {
ZipFile zipFile = mock(ZipFile.class);
// Container entry - use thenAnswer for fresh stream each time
ZipArchiveEntry containerEntry = mock(ZipArchiveEntry.class);
when(containerEntry.getSize()).thenReturn((long) CONTAINER_XML.length());
when(zipFile.getEntry("META-INF/container.xml")).thenReturn(containerEntry);
when(zipFile.getInputStream(containerEntry))
.thenAnswer(inv -> new ByteArrayInputStream(CONTAINER_XML.getBytes(StandardCharsets.UTF_8)));
// OPF entry
ZipArchiveEntry opfEntry = mock(ZipArchiveEntry.class);
when(opfEntry.getSize()).thenReturn((long) CONTENT_OPF.length());
when(zipFile.getEntry("OEBPS/content.opf")).thenReturn(opfEntry);
when(zipFile.getInputStream(opfEntry))
.thenAnswer(inv -> new ByteArrayInputStream(CONTENT_OPF.getBytes(StandardCharsets.UTF_8)));
// Nav entry
ZipArchiveEntry navEntry = mock(ZipArchiveEntry.class);
when(navEntry.getSize()).thenReturn((long) NAV_XHTML.length());
when(zipFile.getEntry("OEBPS/nav.xhtml")).thenReturn(navEntry);
when(zipFile.getInputStream(navEntry))
.thenAnswer(inv -> new ByteArrayInputStream(NAV_XHTML.getBytes(StandardCharsets.UTF_8)));
// Chapter entries with specific sizes
ZipArchiveEntry chapter1Entry = mock(ZipArchiveEntry.class);
when(chapter1Entry.getSize()).thenReturn(1024L);
when(zipFile.getEntry("OEBPS/chapter1.xhtml")).thenReturn(chapter1Entry);
ZipArchiveEntry chapter2Entry = mock(ZipArchiveEntry.class);
when(chapter2Entry.getSize()).thenReturn(2048L);
when(zipFile.getEntry("OEBPS/chapter2.xhtml")).thenReturn(chapter2Entry);
ZipArchiveEntry styleEntry = mock(ZipArchiveEntry.class);
when(styleEntry.getSize()).thenReturn(512L);
when(zipFile.getEntry("OEBPS/style.css")).thenReturn(styleEntry);
ZipArchiveEntry coverEntry = mock(ZipArchiveEntry.class);
when(coverEntry.getSize()).thenReturn(10240L);
when(zipFile.getEntry("OEBPS/cover.jpg")).thenReturn(coverEntry);
return zipFile;
}
private ZipFile.Builder createMockZipFileBuilder(ZipFile zipFile) throws Exception {
ZipFile.Builder builder = mock(ZipFile.Builder.class, RETURNS_DEEP_STUBS);
when(builder.setPath(epubPath)).thenReturn(builder);
when(builder.setCharset(any(Charset.class))).thenReturn(builder);
when(builder.setUseUnicodeExtraFields(anyBoolean())).thenReturn(builder);
when(builder.get()).thenReturn(zipFile);
return builder;
}
}