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;
}
}
@@ -1,6 +1,5 @@
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Router } from '@angular/router';
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {AuthService} from '../../shared/service/auth.service';
import {OAuthService} from 'angular-oauth2-oidc';
@@ -235,14 +235,14 @@ describe('BookService', () => {
describe('Reading & Viewer Settings', () => {
it('should navigate to correct reader and update last read time', () => {
service.readBook(1, 'ngx');
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1']);
service.readBook(1);
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1'], undefined);
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
});
it('should not navigate if book not found', () => {
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null});
service.readBook(999, 'ngx');
service.readBook(999);
expect(routerMock.navigate).not.toHaveBeenCalled();
});
@@ -244,7 +244,7 @@ export class BookService {
/*------------------ Reading & Viewer Settings ------------------*/
readBook(bookId: number, reader: 'ngx' | 'streaming' = 'ngx'): void {
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming'): void {
const book = this.bookStateService
.getCurrentBookState()
.books?.find(b => b.id === bookId);
@@ -254,23 +254,39 @@ export class BookService {
return;
}
const baseUrl =
book.bookType === 'PDF'
? reader === 'ngx'
? 'pdf-reader'
: 'cbx-reader'
: book.bookType === 'EPUB' || book.bookType === 'FB2' || book.bookType === 'MOBI' || book.bookType === 'AZW3'
? 'ebook-reader'
: book.bookType === 'CBX'
? 'cbx-reader'
: null;
let baseUrl: string | null = null;
let queryParams: Record<string, any> | undefined;
switch (book.bookType) {
case 'PDF':
baseUrl = reader === 'pdf-streaming' ? 'cbx-reader' : 'pdf-reader';
break;
case 'EPUB':
baseUrl = 'ebook-reader';
if (reader === 'epub-streaming') {
queryParams = { streaming: true };
}
break;
case 'FB2':
case 'MOBI':
case 'AZW3':
baseUrl = 'ebook-reader';
break;
case 'CBX':
baseUrl = 'cbx-reader';
break;
}
if (!baseUrl) {
console.error('Unsupported book type:', book.bookType);
return;
}
this.router.navigate([`/${baseUrl}/book/${book.id}`]);
this.router.navigate([`/${baseUrl}/book/${book.id}`], queryParams ? { queryParams } : undefined);
this.updateLastReadTime(book.id);
}
@@ -555,13 +555,19 @@
<p-divider layout="vertical" class="action-divider"></p-divider>
}
@if (book!.bookType === 'PDF') {
@if (readMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" icon="pi pi-book" [model]="readItems" (onClick)="read(book.id, 'ngx')" severity="primary"/>
@if (pdfReadMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
}
}
@if (book!.bookType !== 'PDF') {
<p-button label="Read" icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
@if (book!.bookType === 'EPUB') {
@if (epubReadMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
}
}
@if (book!.bookType !== 'PDF' && book!.bookType !== 'EPUB') {
<p-button label="Read" outlined icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
}
<p-divider layout="vertical"></p-divider>
<p-button label="Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(book.id)" class="mobile-icon-only"></p-button>
@if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
@@ -575,7 +581,7 @@
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
@if (refreshMenuItems$ | async; as refreshItems) {
<p-splitbutton
[label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'"
[label]="isAutoFetching ? 'Fetching...' : 'Fetch'"
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
[outlined]="true"
[model]="refreshItems"
@@ -584,13 +590,13 @@
[disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top"
styleClass="mobile-icon-only">
class="mobile-icon-only">
</p-splitbutton>
}
}
@if (otherItems$ | async; as otherItems) {
@if (otherItems.length > 0) {
<p-button icon="pi pi-ellipsis-v" outlined severity="primary" (click)="entitymenu.toggle($event)"></p-button>
<p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button>
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
}
}
@@ -472,7 +472,6 @@
.action-buttons {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
@@ -70,7 +70,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
private destroyRef = inject(DestroyRef);
private dialogRef?: DynamicDialogRef;
readMenuItems$!: Observable<MenuItem[]>;
pdfReadMenuItems$!: Observable<MenuItem[]>;
epubReadMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
otherItems$!: Observable<MenuItem[]>;
downloadMenuItems$!: Observable<MenuItem[]>;
@@ -116,12 +117,22 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
])
);
this.readMenuItems$ = this.book$.pipe(
this.pdfReadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Streaming Reader',
command: () => this.read(book.id, 'streaming')
command: () => this.read(book.id, 'pdf-streaming')
}
])
);
this.epubReadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Streaming Reader (Beta)',
command: () => this.read(book.id, 'epub-streaming')
}
])
);
@@ -369,7 +380,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
this.isExpanded = !this.isExpanded;
}
read(bookId: number | undefined, reader: "ngx" | "streaming" | undefined): void {
read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming"): void {
if (bookId) this.bookService.readBook(bookId, reader);
}
@@ -88,9 +88,11 @@
</div>
}
} @else {
<div class="loading-container">
<p-progressSpinner class="custom-spinner"></p-progressSpinner>
<p class="loading-text">Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.</p>
<div class="loader-overlay">
<div class="loader-content">
<div class="spinner"></div>
<p class="loader-text">Loading book...</p>
</div>
</div>
}
</div>
@@ -458,3 +458,45 @@
}
}
}
.loader-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.loader-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.5rem;
}
.spinner {
width: 48px;
height: 48px;
border: 4px solid rgba(255, 255, 255, 0.2);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loader-text {
color: #fff;
font-size: 1.1rem;
margin: 0;
font-weight: 500;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@@ -313,11 +313,14 @@ $transition-fast: 150ms ease;
display: none;
}
.page-nav-left,
.page-nav-right {
.page-nav-left {
gap: 4px;
}
.page-nav-right {
display: none;
}
.page-nav-left {
margin: 0 auto;
justify-content: center;
@@ -1,21 +1,25 @@
<div class="cbx-header" [class.visible]="isVisible">
<button class="icon-btn" (click)="onOpenSidebar()" title="Contents">
<app-reader-icon name="menu" [size]="20" />
</button>
<button class="icon-btn" (click)="onToggleBookmark()" [title]="isCurrentPageBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentPageBookmarked">
<app-reader-icon name="bookmark" [size]="20" />
</button>
<button class="icon-btn" (click)="onOpenNoteDialog()" [title]="currentPageHasNotes ? 'Page has notes - Add another' : 'Add Note'" [class.has-notes]="currentPageHasNotes">
<app-reader-icon name="note" [size]="20" />
@if (currentPageHasNotes) {
<span class="indicator-dot"></span>
}
</button>
<div class="header-left">
<button class="icon-btn" (click)="onOpenSidebar()" title="Contents">
<app-reader-icon name="menu" [size]="20" />
</button>
<button class="icon-btn" (click)="onToggleBookmark()" [title]="isCurrentPageBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentPageBookmarked">
<app-reader-icon name="bookmark" [size]="20" />
</button>
<button class="icon-btn" (click)="onOpenNoteDialog()" [title]="currentPageHasNotes ? 'Page has notes - Add another' : 'Add Note'" [class.has-notes]="currentPageHasNotes">
<app-reader-icon name="note" [size]="20" />
@if (currentPageHasNotes) {
<span class="indicator-dot"></span>
}
</button>
</div>
<span class="book-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenSettings()" title="Settings">
<app-reader-icon name="settings" [size]="20" />
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" title="Close Reader">
<app-reader-icon name="close" [size]="20" />
</button>
<div class="header-right">
<button class="icon-btn" (click)="onOpenSettings()" title="Settings">
<app-reader-icon name="settings" [size]="20" />
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" title="Close Reader">
<app-reader-icon name="close" [size]="20" />
</button>
</div>
</div>
@@ -25,6 +25,13 @@
transform: translateY(-100%);
}
.header-left,
.header-right {
display: flex;
align-items: center;
z-index: 1;
}
.icon-btn {
background: none;
border: none;
@@ -47,7 +54,7 @@
background: rgba(255, 255, 255, 0.12);
}
&:last-of-type {
&:last-child {
margin-right: 0;
}
@@ -85,7 +92,10 @@
}
.book-title {
flex: 1;
position: absolute;
left: 50%;
transform: translateX(-50%);
max-width: calc(100% - 240px);
text-align: center;
font-size: 14px;
font-weight: 500;
@@ -96,21 +106,25 @@
overflow: hidden;
text-overflow: ellipsis;
min-height: 1.2em;
padding: 0 16px;
}
}
@media (max-width: 600px) {
.cbx-header {
padding: 0 8px;
padding: 0 4px;
.icon-btn {
padding: 10px;
padding: 5px;
margin-right: 6px;
app-reader-icon {
transform: scale(0.9);
}
}
.book-title {
font-size: 13px;
padding: 0 8px;
font-size: 12px;
max-width: calc(100% - 160px);
}
}
}
@@ -2,7 +2,7 @@ import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {CbxHeaderService} from './cbx-header.service';
import {ReaderIconComponent} from '../../../ebook-reader/shared/icon.component';
import {ReaderIconComponent} from '../../../ebook-reader';
import {CommonModule} from '@angular/common';
@Component({
@@ -0,0 +1,57 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config';
import {AuthService} from '../../../../shared/service/auth.service';
export interface EpubSpineItem {
idref: string;
href: string;
mediaType: string;
linear: boolean;
}
export interface EpubManifestItem {
id: string;
href: string;
mediaType: string;
properties?: string[];
size: number;
}
export interface EpubTocItem {
label: string;
href: string;
children?: EpubTocItem[];
}
export interface EpubBookInfo {
containerPath: string;
rootPath: string;
spine: EpubSpineItem[];
manifest: EpubManifestItem[];
toc: EpubTocItem;
metadata: Record<string, any>;
coverPath?: string;
}
@Injectable({
providedIn: 'root'
})
export class EpubStreamingService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/epub`;
private http = inject(HttpClient);
private authService = inject(AuthService);
getBookInfo(bookId: number): Observable<EpubBookInfo> {
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`);
}
getBaseUrl(): string {
return this.baseUrl;
}
getAuthToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
}
@@ -4,6 +4,7 @@ import {catchError, map, switchMap} from 'rxjs/operators';
import {ReaderAnnotationService, Annotation} from '../features/annotations/annotation-renderer.service';
import {ReaderEventService, ViewEvent, TextSelection} from './event.service';
import {PageInfo, ThemeInfo, PageDecorator} from '../shared/header-footer.util';
import {EpubStreamingService, EpubBookInfo} from './epub-streaming.service';
export type {ViewEvent, TextSelection} from './event.service';
export type {PageInfo, ThemeInfo} from '../shared/header-footer.util';
@@ -32,6 +33,7 @@ export interface BookMetadata {
export class ReaderViewManagerService {
private annotationService = inject(ReaderAnnotationService);
private eventService = inject(ReaderEventService);
private epubStreamingService = inject(EpubStreamingService);
private view: any;
public get events$(): Observable<ViewEvent> {
@@ -77,6 +79,29 @@ export class ReaderViewManagerService {
);
}
loadEpubStreaming(bookId: number): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return this.epubStreamingService.getBookInfo(bookId).pipe(
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo))),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo): Promise<void> {
const makeStreamingBook = (window as any).makeStreamingBook;
if (!makeStreamingBook) {
throw new Error('makeStreamingBook not available - Foliate script may not be loaded');
}
const baseUrl = this.epubStreamingService.getBaseUrl();
const authToken = this.epubStreamingService.getAuthToken();
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken);
await this.view.open(book);
}
destroy(): void {
this.eventService.destroy();
this.view?.remove();
@@ -2,6 +2,13 @@
class="reader"
[style.background-color]="stateService.currentState.theme.bg ?? ''">
<div class="header-trigger-zone"
[class.inactive]="headerVisible"
(mouseenter)="onHeaderTriggerZoneEnter()"></div>
<div class="footer-trigger-zone"
[class.inactive]="forceNavbarVisible"
(mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (isLoading) {
<div class="loader-overlay">
<div class="loader-content">
@@ -11,6 +11,34 @@
flex-direction: column;
}
.header-trigger-zone {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 20px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.footer-trigger-zone {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.reader-content {
position: relative;
flex: 1;
@@ -96,6 +96,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
showMetadata = false;
isCurrentCfiBookmarked = false;
forceNavbarVisible = false;
headerVisible = false;
book: Book | null = null;
sectionFractions: number[] = [];
@@ -115,6 +116,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
ngOnInit() {
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
this.visibilityManager.onStateChange((state) => {
this.headerVisible = state.headerVisible;
this.headerService.setForceVisible(state.headerVisible);
this.forceNavbarVisible = state.footerVisible;
});
@@ -209,19 +211,22 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
return this.stateService.initializeState(this.bookId).pipe(
switchMap(() => forkJoin({
state: this.stateService.initializeState(this.bookId),
book: this.bookService.getBookByIdFromAPI(this.bookId, false),
fileBlob: this.bookService.getFileContent(this.bookId)
book: this.bookService.getBookByIdFromAPI(this.bookId, false)
})),
switchMap(({book, fileBlob}) => {
switchMap(({book}) => {
this.book = book;
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
this.progressService.initialize(this.bookId, book.bookType!);
this.selectionService.initialize(this.bookId, this.destroy$);
this.headerService.initialize(this.bookId, book.metadata?.title || '', this.destroy$);
return this.viewManager.loadEpub(fileUrl).pipe(
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
const loadBook$ = book.bookType === 'EPUB' && useStreaming
? this.viewManager.loadEpubStreaming(this.bookId)
: this.loadBookBlob();
return loadBook$.pipe(
tap(() => {
this.applyStyles();
this.sidebarService.initialize(this.bookId, book, this.destroy$);
@@ -241,6 +246,16 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
);
}
private loadBookBlob(): Observable<void> {
return this.bookService.getFileContent(this.bookId).pipe(
switchMap(fileBlob => {
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
return this.viewManager.loadEpub(fileUrl);
})
);
}
private subscribeToStateChanges(): void {
this.stateService.state$
.pipe(takeUntil(this.destroy$))
@@ -291,6 +306,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.isCurrentCfiBookmarked = currentCfi
? bookmarks.some(b => b.cfi === currentCfi)
: false;
this.headerService.setCurrentCfiBookmarked(this.isCurrentCfiBookmarked);
});
}
@@ -329,6 +345,14 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.visibilityManager.updateWindowHeight(window.innerHeight);
}
onHeaderTriggerZoneEnter(): void {
this.visibilityManager.handleHeaderZoneEnter();
}
onFooterTriggerZoneEnter(): void {
this.visibilityManager.handleFooterZoneEnter();
}
handleSelectionAction(action: TextSelectionAction): void {
if (action.type === 'note') {
this.noteService.openNewNoteDialog();
@@ -2,13 +2,16 @@
<button class="icon-btn" (click)="onShowChapters()" title="Chapters">
<app-reader-icon name="menu" [size]="20"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onCreateBookmark()" title="Create Bookmark">
<button class="icon-btn" (click)="onCreateBookmark()" [title]="isCurrentCfiBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentCfiBookmarked">
<app-reader-icon name="bookmark"></app-reader-icon>
</button>
<span class="chapter-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenSearch()" title="Search">
<app-reader-icon name="search"></app-reader-icon>
</button>
<span class="chapter-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenNotes()" title="Notes">
<app-reader-icon name="note"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onShowControls()" title="Settings">
<app-reader-icon name="settings"></app-reader-icon>
</button>
@@ -29,23 +29,28 @@
border: none;
color: inherit;
cursor: pointer;
padding: 6px;
border-radius: 50%;
transition: background 0.15s, box-shadow 0.15s;
padding: 8px;
border-radius: 4px;
transition: color 0.15s, opacity 0.15s;
display: flex;
align-items: center;
justify-content: center;
margin-right: 8px;
margin-right: 4px;
opacity: 0.85;
&:hover {
background: rgba(255, 255, 255, 0.14);
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
opacity: 1;
}
&:last-of-type {
margin-right: 0;
}
&.active {
color: #ef4444;
opacity: 1;
}
.pi {
font-size: 16px;
}
@@ -68,10 +73,11 @@
@media (max-width: 600px) {
.reader-header {
padding: 0 6px;
padding: 0 2px;
.icon-btn {
padding: 10px;
margin-right: 2px;
}
}
}
@@ -3,6 +3,7 @@ import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {ReaderHeaderService} from './header.service';
import {ReaderIconComponent} from '../../shared/icon.component';
import {Router} from '@angular/router';
@Component({
selector: 'app-reader-header',
@@ -13,9 +14,11 @@ import {ReaderIconComponent} from '../../shared/icon.component';
})
export class ReaderHeaderComponent implements OnInit, OnDestroy {
private headerService = inject(ReaderHeaderService);
private router = inject(Router);
private destroy$ = new Subject<void>();
isVisible = false;
isCurrentCfiBookmarked = false;
get bookTitle(): string {
return this.headerService.title;
@@ -29,6 +32,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
this.headerService.forceVisible$
.pipe(takeUntil(this.destroy$))
.subscribe(visible => this.isVisible = visible);
this.headerService.isCurrentCfiBookmarked$
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarked => this.isCurrentCfiBookmarked = bookmarked);
}
ngOnDestroy(): void {
@@ -40,6 +47,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
this.headerService.openSidebar();
}
onOpenNotes(): void {
this.headerService.openLeftSidebar('notes');
}
onOpenSearch(): void {
this.headerService.openLeftSidebar('search');
}
@@ -53,6 +64,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
}
onClose(): void {
this.headerService.close();
if (window.history.length <= 2) {
this.router.navigate(['/dashboard']);
} else {
this.headerService.close();
}
}
}
@@ -23,6 +23,9 @@ export class ReaderHeaderService {
private _forceVisible = new BehaviorSubject<boolean>(false);
forceVisible$ = this._forceVisible.asObservable();
private _isCurrentCfiBookmarked = new BehaviorSubject<boolean>(false);
isCurrentCfiBookmarked$ = this._isCurrentCfiBookmarked.asObservable();
private _showControls = new Subject<void>();
private _showMetadata = new Subject<void>();
showControls$ = this._showControls.asObservable();
@@ -50,6 +53,10 @@ export class ReaderHeaderService {
this._forceVisible.next(visible);
}
setCurrentCfiBookmarked(bookmarked: boolean): void {
this._isCurrentCfiBookmarked.next(bookmarked);
}
openSidebar(): void {
this.sidebarService.open();
}
@@ -59,7 +66,7 @@ export class ReaderHeaderService {
}
createBookmark(): void {
this.sidebarService.createBookmark();
this.sidebarService.toggleBookmark();
}
openControls(): void {
@@ -84,26 +91,6 @@ export class ReaderHeaderService {
this.syncSettingsToBackend();
}
decreaseFontSize(): void {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
increaseLineHeight(): void {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
decreaseLineHeight(): void {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
setFlow(flow: 'paginated' | 'scrolled'): void {
this.stateService.setFlow(flow);
this.syncSettingsToBackend();
}
private syncSettingsToBackend(): void {
const state = this.stateService.currentState;
const setting: EbookViewerSetting = {
@@ -129,6 +116,7 @@ export class ReaderHeaderService {
reset(): void {
this._forceVisible.next(false);
this._isCurrentCfiBookmarked.next(false);
this.bookTitle = '';
}
}
@@ -234,6 +234,18 @@ export class ReaderSidebarService {
});
}
toggleBookmark(): void {
const currentCfi = this.progressService.currentCfi;
if (!currentCfi) return;
const existingBookmark = this._bookmarks.value.find(b => b.cfi === currentCfi);
if (existingBookmark) {
this.deleteBookmark(existingBookmark.id!);
} else {
this.createBookmark();
}
}
deleteBookmark(bookmarkId: number): void {
this.bookMarkHttpService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
@@ -41,6 +41,20 @@ export class ReaderHeaderFooterVisibilityManager {
}
}
handleHeaderZoneEnter(): void {
if (!this.isPinned) {
this.setHeaderVisible(true);
this.notifyStateChange();
}
}
handleFooterZoneEnter(): void {
if (!this.isPinned) {
this.setFooterVisible(true);
this.notifyStateChange();
}
}
togglePinned(): void {
this.isPinned = !this.isPinned;
this.updateVisibility();
+109 -7
View File
@@ -706,15 +706,35 @@ class Loader {
#cache = new Map()
#children = new Map()
#refCount = new Map()
#getDirectUrl = null // Function to get direct streaming URLs for lazy loading
eventTarget = new EventTarget()
constructor({ loadText, loadBlob, resources }) {
constructor({ loadText, loadBlob, resources, getDirectUrl }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.manifest = resources.manifest
this.assets = resources.manifest
this.#getDirectUrl = getDirectUrl ?? null
// needed only when replacing in (X)HTML w/o parsing (see below)
//.filter(({ mediaType }) => ![MIME.XHTML, MIME.HTML].includes(mediaType))
}
// Check if a media type is an image
#isImage(mediaType) {
return mediaType?.startsWith('image/') ?? false
}
// Check if a media type is a font
#isFont(mediaType) {
return mediaType?.includes('font') ||
mediaType === 'application/vnd.ms-opentype' ||
mediaType === 'application/x-font-ttf' ||
mediaType === 'application/x-font-otf' ||
mediaType === 'application/x-font-woff' ||
mediaType === 'font/otf' ||
mediaType === 'font/ttf' ||
mediaType === 'font/woff' ||
mediaType === 'font/woff2'
}
async createURL(href, data, type, parent) {
if (!data) return ''
const detail = { data, type }
@@ -838,13 +858,59 @@ class Loader {
// replace hrefs (excluding anchors)
const replace = async (el, attr) => el.setAttribute(attr,
await this.loadHref(el.getAttribute(attr), href, parents))
// Helper to check if element is an image that should use direct URL
const shouldUseDirectUrl = (el, attr) => {
if (!this.#getDirectUrl) return false
const srcAttr = el.getAttribute(attr)
if (!srcAttr || isExternal(srcAttr)) return false
const path = resolveURL(srcAttr, href)
const item = this.manifest.find(item => item.href === path)
return item && this.#isImage(item.mediaType)
}
// Replace with direct URL (for images) - browser loads on-demand
const replaceWithDirectUrl = (el, attr) => {
const srcAttr = el.getAttribute(attr)
const path = resolveURL(srcAttr, href)
const directUrl = this.#getDirectUrl(path)
if (directUrl) {
el.setAttribute(attr, directUrl)
el.setAttribute('loading', 'lazy') // Native lazy loading hint
return true
}
return false
}
// Process link elements (stylesheets, etc.)
for (const el of doc.querySelectorAll('link[href]')) await replace(el, 'href')
for (const el of doc.querySelectorAll('[src]')) await replace(el, 'src')
for (const el of doc.querySelectorAll('[poster]')) await replace(el, 'poster')
// Process elements with src attribute
// For images: use direct URLs so browser can load on-demand
// For others: load and create blob URL
for (const el of doc.querySelectorAll('[src]')) {
if (shouldUseDirectUrl(el, 'src')) {
replaceWithDirectUrl(el, 'src')
} else {
await replace(el, 'src')
}
}
// Process poster attributes (videos)
for (const el of doc.querySelectorAll('[poster]')) {
if (shouldUseDirectUrl(el, 'poster')) {
replaceWithDirectUrl(el, 'poster')
} else {
await replace(el, 'poster')
}
}
for (const el of doc.querySelectorAll('object[data]')) await replace(el, 'data')
for (const el of doc.querySelectorAll('[*|href]:not([href])'))
el.setAttributeNS(NS.XLINK, 'href', await this.loadHref(
el.getAttributeNS(NS.XLINK, 'href'), href, parents))
// Process srcset attributes
for (const el of doc.querySelectorAll('[srcset]'))
el.setAttribute('srcset', await replaceSeries(el.getAttribute('srcset'),
/(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g,
@@ -868,15 +934,48 @@ class Loader {
return this.createURL(href, result, mediaType, parent)
}
async replaceCSS(str, href, parents = []) {
// For url() references, use direct URLs for fonts and images (lazy loading)
// This avoids fetching all fonts/images upfront - browser fetches on-demand
const replacedUrls = await replaceSeries(str,
/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `url("${url}")`))
async (_, url) => {
if (isExternal(url)) return `url("${url}")`
const path = resolveURL(url, href)
const item = this.manifest.find(item => item.href === path)
// If we have getDirectUrl and this is a font or image, use direct URL
// This lets the browser fetch on-demand instead of us prefetching everything
if (this.#getDirectUrl && item && (this.#isFont(item.mediaType) || this.#isImage(item.mediaType))) {
const directUrl = this.#getDirectUrl(path)
if (directUrl) return `url("${directUrl}")`
}
// For other resources (like CSS), load them normally
const loadedUrl = await this.loadHref(url, href, parents)
return `url("${loadedUrl}")`
})
// apart from `url()`, strings can be used for `@import` (but why?!)
return replaceSeries(replacedUrls,
// CSS imports need to be loaded and processed
const replacedImports = await replaceSeries(replacedUrls,
/@import\s*["']([^"'\n]*?)["']/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `@import "${url}"`))
// Add font-display: swap to @font-face rules that don't have it
// This ensures text is visible immediately while fonts load
return replacedImports.replace(
/@font-face\s*\{([^}]*)\}/gi,
(match, content) => {
// Check if font-display is already set
if (/font-display\s*:/i.test(content)) {
return match
}
// Add font-display: swap before the closing brace
return `@font-face {${content}font-display: swap;}`
}
)
}
// find & replace all possible relative paths for all assets without parsing
replaceString(str, href, parents = []) {
@@ -932,10 +1031,12 @@ export class EPUB {
parser = new DOMParser()
#loader
#encryption
constructor({ loadText, loadBlob, getSize, sha1 }) {
#getDirectUrl = null
constructor({ loadText, loadBlob, getSize, getDirectUrl, sha1 }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.getSize = getSize
this.#getDirectUrl = getDirectUrl ?? null
this.#encryption = new Encryption(deobfuscators(sha1))
}
async #loadXML(uri) {
@@ -973,6 +1074,7 @@ ${doc.querySelector('parsererror').innerText}`)
loadBlob: uri => Promise.resolve(this.loadBlob(uri))
.then(this.#encryption.getDecoder(uri)),
resources: this.resources,
getDirectUrl: this.#getDirectUrl,
})
this.transformTarget = this.#loader.eventTarget
this.sections = this.resources.spine.map((spineItem, index) => {
@@ -0,0 +1,121 @@
/**
* Creates a streaming loader that fetches EPUB files from the server on-demand
* instead of loading the entire ZIP file into memory.
*
* @param {number} bookId - The book ID for API requests
* @param {string} baseUrl - API base URL (e.g., '/api/v1/epub')
* @param {Object} bookInfo - Pre-fetched EPUB metadata from /info endpoint
* @param {string} [authToken] - Optional authentication token
* @returns {Object} Loader interface compatible with Foliate's EPUB class
*/
export const makeStreamingLoader = (bookId, baseUrl, bookInfo, authToken = null) => {
// Build a map of file paths to their manifest info for quick lookup
const manifestMap = new Map(
bookInfo.manifest.map(item => [item.href, item])
)
// Build URL for fetching a file
const getFileUrl = (name) => {
if (!name) return null
// URL encode the path but preserve slashes
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
return `${baseUrl}/${bookId}/file/${encodedPath}`
}
// Build fetch options with auth header
const getFetchOptions = () => {
if (!authToken) return {}
return {
headers: {
'Authorization': `Bearer ${authToken}`
}
}
}
// Build URL with token for browser-initiated requests (fonts, images in CSS)
const getDirectFileUrl = (name) => {
if (!name) return null
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
let url = `${baseUrl}/${bookId}/file/${encodedPath}`
if (authToken) {
url += `?token=${encodeURIComponent(authToken)}`
}
return url
}
/**
* Load file as text
*/
const loadText = async (name) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load text: ${name}`, response.status)
return null
}
return await response.text()
} catch (e) {
console.error(`Error loading text ${name}:`, e)
return null
}
}
/**
* Load file as Blob with optional MIME type
*/
const loadBlob = async (name, type) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load blob: ${name}`, response.status)
return null
}
const blob = await response.blob()
// Return with specified type or detected type
if (type) {
return new Blob([blob], {type})
}
return blob
} catch (e) {
console.error(`Error loading blob ${name}:`, e)
return null
}
}
/**
* Get uncompressed size of a file
*/
const getSize = (name) => {
if (!name) return 0
const item = manifestMap.get(name)
return item?.size ?? 0
}
/**
* Get direct URL for a file without fetching it.
* This allows the browser to fetch resources on-demand (fonts, images).
* Note: Uses token in URL since browser-initiated requests can't use headers.
* @param {string} name - File path within the EPUB
* @returns {string|null} Direct URL to the file
*/
const getDirectUrl = (name) => {
if (!name) return null
return getDirectFileUrl(name)
}
return {
loadText,
loadBlob,
getSize,
getDirectUrl, // For lazy loading of fonts/images in CSS
// Expose for debugging
_bookInfo: bookInfo,
_manifestMap: manifestMap
}
}
export default makeStreamingLoader
+20
View File
@@ -2,6 +2,7 @@ import * as CFI from './epubcfi.js'
import {SectionProgress, TOCProgress} from './progress.js'
import {Overlayer} from './overlayer.js'
import {textWalker} from './text-walker.js'
import {makeStreamingLoader} from './streaming-loader.js'
const SEARCH_PREFIX = 'foliate-search:'
@@ -139,6 +140,22 @@ export const makeBook = async file => {
return book
}
/**
* Create an EPUB book using streaming loader instead of ZIP extraction.
* This avoids loading the entire EPUB into memory.
*
* @param {number} bookId - Book ID for API requests
* @param {string} baseUrl - API base URL for EPUB endpoints
* @param {Object} bookInfo - Pre-fetched metadata from /api/v1/epub/{bookId}/info
* @param {string} [authToken] - Optional authentication token
* @returns {Promise<EPUB>} Initialized EPUB book object
*/
export const makeStreamingBook = async (bookId, baseUrl, bookInfo, authToken = null) => {
const loader = makeStreamingLoader(bookId, baseUrl, bookInfo, authToken)
const {EPUB} = await import('./epub.js')
return new EPUB(loader).init()
}
class CursorAutohider {
#timeout
#el
@@ -653,3 +670,6 @@ export class View extends HTMLElement {
}
customElements.define('foliate-view', View)
// Export makeStreamingBook to window for use from Angular
window.makeStreamingBook = makeStreamingBook