From 7efb0e138d2f574601563756d45d83149bc3ff96 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Mon, 19 Jan 2026 18:07:57 -0700 Subject: [PATCH] Implement streaming EPUB reader with on-demand loading (#2350) Co-authored-by: acx10 --- .../config/security/SecurityConfig.java | 15 + .../filter/EpubStreamingJwtFilter.java | 117 +++ .../controller/EpubReaderController.java | 71 ++ .../booklore/controller/KoboController.java | 2 +- .../model/dto/response/EpubBookInfo.java | 23 + .../model/dto/response/EpubManifestItem.java | 20 + .../model/dto/response/EpubSpineItem.java | 17 + .../model/dto/response/EpubTocItem.java | 18 + .../service/reader/EpubReaderService.java | 697 ++++++++++++++++++ .../service/reader/EpubReaderServiceTest.java | 635 ++++++++++++++++ .../src/app/core/security/auth.guard.ts | 5 +- .../book/service/book.service.spec.ts | 6 +- .../app/features/book/service/book.service.ts | 40 +- .../metadata-viewer.component.html | 20 +- .../metadata-viewer.component.scss | 1 - .../metadata-viewer.component.ts | 19 +- .../cbx-reader/cbx-reader.component.html | 8 +- .../cbx-reader/cbx-reader.component.scss | 42 ++ .../layout/footer/cbx-footer.component.scss | 7 +- .../layout/header/cbx-header.component.html | 40 +- .../layout/header/cbx-header.component.scss | 28 +- .../layout/header/cbx-header.component.ts | 2 +- .../core/epub-streaming.service.ts | 57 ++ .../ebook-reader/core/view-manager.service.ts | 25 + .../ebook-reader/ebook-reader.component.html | 7 + .../ebook-reader/ebook-reader.component.scss | 28 + .../ebook-reader/ebook-reader.component.ts | 36 +- .../layout/header/header.component.html | 7 +- .../layout/header/header.component.scss | 20 +- .../layout/header/header.component.ts | 17 +- .../layout/header/header.service.ts | 30 +- .../layout/sidebar/sidebar.service.ts | 12 + .../ebook-reader/shared/visibility.util.ts | 14 + booklore-ui/src/assets/foliate/epub.js | 116 ++- .../src/assets/foliate/streaming-loader.js | 121 +++ booklore-ui/src/assets/foliate/view.js | 20 + 36 files changed, 2237 insertions(+), 106 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/EpubStreamingJwtFilter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubBookInfo.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubManifestItem.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubSpineItem.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubTocItem.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/reader/EpubReaderServiceTest.java create mode 100644 booklore-ui/src/app/features/readers/ebook-reader/core/epub-streaming.service.ts create mode 100644 booklore-ui/src/assets/foliate/streaming-loader.js diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java index c5d608c2c..162d88fc8 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java @@ -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 publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS)); if (appProperties.getSwagger().isEnabled()) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/EpubStreamingJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/EpubStreamingJwtFilter.java new file mode 100644 index 000000000..99dc04808 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/EpubStreamingJwtFilter.java @@ -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); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java new file mode 100644 index 000000000..8a8fc654c --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/EpubReaderController.java @@ -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 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()); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java index ca2a04b05..4ada7653e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java @@ -217,4 +217,4 @@ public class KoboController { } return koboServerProxy.proxyCurrentRequest(body, false); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubBookInfo.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubBookInfo.java new file mode 100644 index 000000000..5dba81f17 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubBookInfo.java @@ -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 spine; + private List manifest; + private EpubTocItem toc; + private Map metadata; + private String coverPath; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubManifestItem.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubManifestItem.java new file mode 100644 index 000000000..2b04d27d9 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubManifestItem.java @@ -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 properties; + private long size; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubSpineItem.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubSpineItem.java new file mode 100644 index 000000000..c6217b466 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubSpineItem.java @@ -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; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubTocItem.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubTocItem.java new file mode 100644 index 000000000..dbe5dc064 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/EpubTocItem.java @@ -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 children; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java new file mode 100644 index 000000000..d2f28e99f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/EpubReaderService.java @@ -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 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 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 manifest = parseManifest(opfDoc, rootPath, zipFile); + Map manifestById = new HashMap<>(); + for (EpubManifestItem item : manifest) { + manifestById.put(item.getId(), item); + } + + List spine = parseSpine(opfDoc, manifestById); + + Map 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 parseManifest(Document opfDoc, String rootPath, ZipFile zipFile) { + List 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 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 parseSpine(Document opfDoc, Map manifestById) { + List 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 parseMetadata(Document opfDoc) { + Map 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 children = parseNavOl((Element) ols.item(0), navDir); + + return EpubTocItem.builder() + .label("Table of Contents") + .children(children) + .build(); + } + + private List parseNavOl(Element ol, String basePath) { + List 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 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 children = parseNcxNavPoints(navMap, ncxDir); + + return EpubTocItem.builder() + .label("Table of Contents") + .children(children) + .build(); + } + + private List parseNcxNavPoints(Element parent, String basePath) { + List 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 subItems = parseNcxNavPoints(navPoint, basePath); + + return EpubTocItem.builder() + .label(label) + .href(href) + .children(subItems.isEmpty() ? null : subItems) + .build(); + } + + private String findCoverPath(Document opfDoc, List manifest, Map 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"; + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/EpubReaderServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/EpubReaderServiceTest.java new file mode 100644 index 000000000..3af19ece9 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/reader/EpubReaderServiceTest.java @@ -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 = """ + + + + + + + """; + + private static final String CONTENT_OPF = """ + + + + Test Book + Test Author + en + + + + + + + + + + + + + + """; + + private static final String NAV_XHTML = """ + + + Navigation + + + + + """; + + @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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + byte[] chapterContent = "Chapter 1 content".getBytes(StandardCharsets.UTF_8); + ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 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 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFileWithSizes(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + ZipFile zipFile = createMockZipFile(); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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 fileUtilsStatic = mockStatic(FileUtils.class)) { + fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath.toString()); + + byte[] chapterContent = "Chapter 1 content".getBytes(StandardCharsets.UTF_8); + ZipFile zipFile = createMockZipFileWithStreamableEntry("OEBPS/chapter1.xhtml", chapterContent); + ZipFile.Builder builder = createMockZipFileBuilder(zipFile); + + try (MockedStatic 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; + } +} diff --git a/booklore-ui/src/app/core/security/auth.guard.ts b/booklore-ui/src/app/core/security/auth.guard.ts index 04ec7efb5..d88426afc 100644 --- a/booklore-ui/src/app/core/security/auth.guard.ts +++ b/booklore-ui/src/app/core/security/auth.guard.ts @@ -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'; diff --git a/booklore-ui/src/app/features/book/service/book.service.spec.ts b/booklore-ui/src/app/features/book/service/book.service.spec.ts index 9337bd538..8ea737d70 100644 --- a/booklore-ui/src/app/features/book/service/book.service.spec.ts +++ b/booklore-ui/src/app/features/book/service/book.service.spec.ts @@ -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(); }); diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index 18efc7f2a..e9b6e304d 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -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 | 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); } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html index f96137668..1f80894a7 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -555,13 +555,19 @@ } @if (book!.bookType === 'PDF') { - @if (readMenuItems$ | async; as readItems) { - + @if (pdfReadMenuItems$ | async; as readItems) { + } } - @if (book!.bookType !== 'PDF') { - + @if (book!.bookType === 'EPUB') { + @if (epubReadMenuItems$ | async; as readItems) { + + } } + @if (book!.bookType !== 'PDF' && book!.bookType !== 'EPUB') { + + } + @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) { + class="mobile-icon-only"> } } @if (otherItems$ | async; as otherItems) { @if (otherItems.length > 0) { - + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss index 782ac2644..014359a51 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.scss @@ -472,7 +472,6 @@ .action-buttons { display: flex; - flex-wrap: wrap; gap: 0.5rem; align-items: center; } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 6a3bf1bc5..b48c451ef 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -70,7 +70,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges { private destroyRef = inject(DestroyRef); private dialogRef?: DynamicDialogRef; - readMenuItems$!: Observable; + pdfReadMenuItems$!: Observable; + epubReadMenuItems$!: Observable; refreshMenuItems$!: Observable; otherItems$!: Observable; downloadMenuItems$!: Observable; @@ -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); } diff --git a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.html b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.html index 296cd8e75..a970aed00 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.html +++ b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.html @@ -88,9 +88,11 @@ } } @else { -
- -

Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.

+
+
+
+

Loading book...

+
}
diff --git a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.scss b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.scss index a1ff301c6..b9c59b28a 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.scss +++ b/booklore-ui/src/app/features/readers/cbx-reader/cbx-reader.component.scss @@ -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); + } +} diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.scss b/booklore-ui/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.scss index b6d51bd81..146ee06e2 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.scss +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/footer/cbx-footer.component.scss @@ -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; diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.html b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.html index 2369ca96f..27eb281cb 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.html +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.html @@ -1,21 +1,25 @@
- - - +
+ + + +
{{ bookTitle }} - - +
+ + +
diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.scss b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.scss index 28c78f1fc..ac75a8110 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.scss +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.scss @@ -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); } } } diff --git a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.ts b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.ts index 4238cbce5..b901081e9 100644 --- a/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.ts +++ b/booklore-ui/src/app/features/readers/cbx-reader/layout/header/cbx-header.component.ts @@ -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({ diff --git a/booklore-ui/src/app/features/readers/ebook-reader/core/epub-streaming.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/epub-streaming.service.ts new file mode 100644 index 000000000..424e713eb --- /dev/null +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/epub-streaming.service.ts @@ -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; + 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 { + return this.http.get(`${this.baseUrl}/${bookId}/info`); + } + + getBaseUrl(): string { + return this.baseUrl; + } + + getAuthToken(): string | null { + return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken(); + } +} diff --git a/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts index 03641d68a..a1420ff7a 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/core/view-manager.service.ts @@ -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 { @@ -77,6 +79,29 @@ export class ReaderViewManagerService { ); } + loadEpubStreaming(bookId: number): Observable { + 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 { + 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(); diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html index 9a8be19c9..42a01f8b7 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.html @@ -2,6 +2,13 @@ class="reader" [style.background-color]="stateService.currentState.theme.bg ?? ''"> +
+ + @if (isLoading) {
diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss index 4f76c7af5..83934879d 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.scss @@ -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; diff --git a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts index 0f8691ad1..d8d3e1ee1 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/ebook-reader.component.ts @@ -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 { + 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(); diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html index 32802c2ca..c6bc17f0a 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.html @@ -2,13 +2,16 @@ - - {{ bookTitle }} + {{ bookTitle }} + diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss index 38470d3d5..5e1015067 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.scss @@ -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; } } } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts index 4cbf5600b..6246a0895 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.component.ts @@ -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(); 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(); + } } } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts index 95cd0438e..17adc2e0b 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/header/header.service.ts @@ -23,6 +23,9 @@ export class ReaderHeaderService { private _forceVisible = new BehaviorSubject(false); forceVisible$ = this._forceVisible.asObservable(); + private _isCurrentCfiBookmarked = new BehaviorSubject(false); + isCurrentCfiBookmarked$ = this._isCurrentCfiBookmarked.asObservable(); + private _showControls = new Subject(); private _showMetadata = new Subject(); 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 = ''; } } diff --git a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts index 486996b9a..cff396828 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/layout/sidebar/sidebar.service.ts @@ -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$)) diff --git a/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts b/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts index 0d143d033..fac7effd7 100644 --- a/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts +++ b/booklore-ui/src/app/features/readers/ebook-reader/shared/visibility.util.ts @@ -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(); diff --git a/booklore-ui/src/assets/foliate/epub.js b/booklore-ui/src/assets/foliate/epub.js index 0417d0d0e..c837ee839 100644 --- a/booklore-ui/src/assets/foliate/epub.js +++ b/booklore-ui/src/assets/foliate/epub.js @@ -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) => { diff --git a/booklore-ui/src/assets/foliate/streaming-loader.js b/booklore-ui/src/assets/foliate/streaming-loader.js new file mode 100644 index 000000000..b62c52660 --- /dev/null +++ b/booklore-ui/src/assets/foliate/streaming-loader.js @@ -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 diff --git a/booklore-ui/src/assets/foliate/view.js b/booklore-ui/src/assets/foliate/view.js index a347ba2b1..6b2830a21 100644 --- a/booklore-ui/src/assets/foliate/view.js +++ b/booklore-ui/src/assets/foliate/view.js @@ -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} 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