feat(web-reader): HTTP Caching & Cache Storage for content responses (#75)

* Squashed commit of the following:

commit e799d02a1b3557fcbe9c67bd276ced9ddc783e83
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:47:08 2026 +0700

    should be done

commit d232c4d48bd97dbc7d8d800cdb3d18e85a73b8ec
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:32:49 2026 +0700

    ok done

commit 911d69c3347c6596ae0feb3261355f7b234b6171
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:32:15 2026 +0700

    dont break pls

commit 498e996bb42a74f9edda65b914a9124b15a8baea
Author: Nam Le <namle888029@gmail.com>
Date:   Sat Mar 21 11:35:32 2026 +0700

    changes:
    + avoid double caching
    + detach get & validate logic
    + error handling for cache insert

commit a215d11d6855a3381e4f2ecbca32d45d4b06869f
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 22:01:37 2026 +0700

    fix dup

commit 539b70f6f9c859bdf6d2a2557e3ba1c1fc10a601
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 21:46:43 2026 +0700

    fix
    + leaking Blob resource
    + scss lint
    + extra `}`

commit d1c8ceea944c0a25a9a2a54bb83122e0a9480b05
Author: NamLe029 <146613205+NamLe029@users.noreply.github.com>
Date:   Fri Mar 20 21:34:14 2026 +0700

    Apply suggestions from code review

    Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

commit ca14572c8c6df143295ebff2acf210f3a5164ed5
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 20:25:46 2026 +0700

    wording

commit 558b0f69fe6a6736aa114f592abd87451b173ccb
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 19:51:28 2026 +0700

    remove dexie

commit 4b0750824685e70dd5a13fd9e899064fd6b009c6
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 19:22:43 2026 +0700

    use observable for pdf bookdata

commit 1c88aff7c01a51a5263aca3522797624ed794862
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:07:14 2026 +0700

    switch to cache storage

commit c766428c32b97fab339b3438b6c4e693082a07a3
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 15:13:42 2026 +0700

    error handling

commit bdbaa8f5f769fcd80f3f93aac0c52ffba8bcec27
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 14:16:49 2026 +0700

    cleanup unecessary validation

commit 56e264ee5570948cf1512c8ce4de4622430d3cdc
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 12:50:45 2026 +0700

    apply simpleCacheService

commit 45ef6ae5d460b27d134b696951fd613eefcb2d64
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:02:44 2026 +0700

    interface for local settings

commit 421305dbcb108647b5f0cc29c567de5daee2a93d
Author: Nam Le <namle888029@gmail.com>
Date:   Wed Apr 1 18:01:20 2026 +0700

    simple cache service for caching request response

commit 1aa81b4a08b006d52e398da61464527fd90e51cb
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 12:47:54 2026 +0700

    local settings service for device-scoped settings

commit 647b4f561336617651f5c4f14fe83dc70df3f30f
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 12:46:35 2026 +0700

    add dexie dependency

commit d8bfed64b0096c2d99052fceee718413b5dc8b40
Author: Nam Le <namle888029@gmail.com>
Date:   Fri Mar 20 12:46:00 2026 +0700

    enable HTTP Caching (Last-Modified) for PDF, EPUB, audiobook content response

* delete unused

* final touch

* move local settings

* test

* remove test case for deleted  method

* lint

---------

Co-authored-by: brios <127139797+balazs-szucs@users.noreply.github.com>
This commit is contained in:
NamLe029
2026-04-22 17:27:00 -04:00
committed by Zach Yale
co-authored by brios
parent 73857a81ed
commit 5495225ad5
17 changed files with 593 additions and 112 deletions
@@ -277,9 +277,9 @@ public class SecurityConfig {
configuration.setAllowedOriginPatterns(origins);
}
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match"));
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date"));
configuration.setAllowedMethods(List.of("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match", "If-Modified-Since"));
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date", "Last-Modified"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
@@ -7,17 +7,14 @@ 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 lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.booklore.util.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.nio.file.Path;
@Slf4j
@@ -48,15 +45,13 @@ public class AudiobookReaderController {
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/stream")
public void streamAudiobook(
public ResponseEntity<? extends Resource> streamAudiobook(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex) {
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
return getFile(audioPath);
}
@Operation(summary = "Stream specific track", description = "Stream a specific track from a folder-based audiobook.")
@@ -65,15 +60,13 @@ public class AudiobookReaderController {
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/track/{trackIndex}/stream")
public void streamTrack(
public ResponseEntity<? extends Resource> streamTrack(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex,
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType) {
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
return getFile(audioPath);
}
@Operation(summary = "Get embedded cover art",
@@ -100,4 +93,18 @@ public class AudiobookReaderController {
return new ResponseEntity<>(coverData, headers, HttpStatus.OK);
}
private ResponseEntity<FileSystemResource> getFile(Path filePath) {
Long lastModified = FileUtils.getFileLastModified(filePath);
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
if (lastModified != null) {
builder.lastModified(lastModified);
}
return builder
.cacheControl(CacheControl.noCache().cachePrivate())
.contentType(MediaTypeFactory.getMediaType(filePath.toString()).orElse(MediaType.APPLICATION_OCTET_STREAM))
.body(new FileSystemResource(filePath));
}
}
@@ -147,12 +147,11 @@ public class BookController {
})
@GetMapping("/{bookId}/content")
@CheckBookAccess(bookIdParam = "bookId")
public void getBookContent(
public ResponseEntity<Resource> getBookContent(
@Parameter(description = "ID of the book") @PathVariable long bookId,
@Parameter(description = "Optional book type for alternative format (e.g., EPUB, PDF, MOBI)") @RequestParam(required = false) String bookType,
HttpServletRequest request,
HttpServletResponse response) throws java.io.IOException {
bookService.streamBookContent(bookId, bookType, request, response);
@Parameter(description = "Optional book type for alternative format (e.g., EPUB, PDF, MOBI)") @RequestParam(required = false) String bookType
) {
return bookService.getBookContent(bookId, bookType);
}
@Operation(summary = "Replace book content", description = "Overwrite the primary PDF file for a book with the uploaded content. Used by the document viewer to persist annotation changes.")
@@ -22,7 +22,6 @@ import org.booklore.service.monitoring.MonitoringRegistrationService;
import org.booklore.service.progress.ReadingProgressService;
import org.booklore.util.FileService;
import org.booklore.util.FileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -31,9 +30,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -347,41 +344,17 @@ public class BookService {
if (!file.exists()) {
throw ApiError.FILE_NOT_FOUND.createException(filePath);
}
Resource resource = new FileSystemResource(file);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(file.length())
.body(resource);
}
Long lastModified = FileUtils.getFileLastModified(Path.of(filePath));
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
public void streamBookContent(long bookId, String bookType, HttpServletRequest request, HttpServletResponse response) throws IOException {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
String filePath;
if (bookType != null) {
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
.filter(bf -> bf.getBookType() == requestedType)
.findFirst()
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book"));
filePath = bookFile.getFullFilePath().toString();
} else {
filePath = FileUtils.getBookFullPath(bookEntity).toString();
if (lastModified != null) {
builder.lastModified(lastModified);
}
Path path = Paths.get(filePath);
String fileName = path.getFileName().toString();
String extension = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf('.') + 1) : "";
String contentType = switch (extension.toLowerCase()) {
case "pdf" -> "application/pdf";
case "epub" -> "application/epub+zip";
case "mobi", "azw3" -> "application/x-mobipocket-ebook";
case "cbz" -> "application/vnd.comicbook+zip";
case "cbr" -> "application/vnd.comicbook-rar";
case "fb2" -> "application/x-fictionbook+xml";
default -> "application/octet-stream";
};
fileStreamingService.streamWithRangeSupport(path, contentType, request, response);
return builder
.cacheControl(CacheControl.noCache().cachePrivate())
.contentType(MediaTypeFactory.getMediaType(filePath).orElse(MediaType.APPLICATION_OCTET_STREAM))
.body(new FileSystemResource(file));
}
public void replaceBookContent(long bookId, String bookType, java.io.InputStream content) throws IOException {
@@ -68,6 +68,21 @@ public class FileUtils {
}
}
/**
* Get last modified time of the file in milliseconds since the
* epoch (00:00:00 GMT, January 1, 1970).
* @param filePath the path to the file
* @return milliseconds since the epoch, or null if an I/O error occurs
*/
public Long getFileLastModified(Path filePath) {
try {
return Files.getLastModifiedTime(filePath).toMillis();
} catch (IOException e) {
log.error("Failed to get last modified for path [{}]: {}", filePath, e.getMessage(), e);
return null;
}
}
/**
* Calculate total size of all files in a folder (for folder-based audiobooks).
*/
@@ -448,47 +448,5 @@ class BookServiceTest {
assertEquals(1, result.size());
assertTrue(result.contains(shelf1));
}
@Mock
private org.booklore.service.FileStreamingService fileStreamingService;
@Test
void streamBookContent_delegatesToStreamingService() throws Exception {
BookEntity entity = new BookEntity();
entity.setId(15L);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setBook(entity);
primaryFile.setBookType(BookFileType.EPUB);
primaryFile.setFileSubPath("");
primaryFile.setFileName("book.epub");
// Ensure bookFiles list is populated to avoid IndexOutOfBounds or similar if logic accesses it
entity.setBookFiles(List.of(primaryFile));
when(bookRepository.findByIdWithBookFiles(15L)).thenReturn(Optional.of(entity));
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
// We don't need to mock FileUtils static method if we set up the entity correctly
// But streamBookContent calls FileUtils.getBookFullPath(bookEntity) if bookType is null.
// Let's passed bookType="EPUB" to hit the specific branch, or null to hit default.
// The code uses:
// if (bookType != null) { ... } else { filePath = FileUtils.getBookFullPath(bookEntity); }
// Let's test the specific type path first as it isolates logic better,
// OR test the null path which is likely what the browser uses.
// The original error was "Cannot lazily initialize collection... getPrimaryBookFile... FileUtils.getBookFullPath"
// So I should test the `bookType = null` case which triggers `FileUtils.getBookFullPath`.
// However, `FileUtils.getBookFullPath` is static. I may need to mock it or ensure it works with the entity.
// `FileUtils.getBookFullPath` calls `book.getPrimaryBookFile()`.
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn(epubPath);
bookService.streamBookContent(15L, null, request, response);
verify(bookRepository).findByIdWithBookFiles(15L);
verify(fileStreamingService).streamWithRangeSupport(eq(epubPath), eq("application/epub+zip"), eq(request), eq(response));
}
}
}