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:
@@ -277,9 +277,9 @@ public class SecurityConfig {
|
|||||||
configuration.setAllowedOriginPatterns(origins);
|
configuration.setAllowedOriginPatterns(origins);
|
||||||
}
|
}
|
||||||
|
|
||||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
configuration.setAllowedMethods(List.of("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||||
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Range", "If-None-Match"));
|
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"));
|
configuration.setExposedHeaders(List.of("Content-Disposition", "Accept-Ranges", "Content-Range", "Content-Length", "ETag", "Date", "Last-Modified"));
|
||||||
configuration.setAllowCredentials(true);
|
configuration.setAllowCredentials(true);
|
||||||
|
|
||||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
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.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.booklore.util.FileUtils;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.core.io.FileSystemResource;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.*;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -48,15 +45,13 @@ public class AudiobookReaderController {
|
|||||||
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
@GetMapping("/{bookId}/stream")
|
@GetMapping("/{bookId}/stream")
|
||||||
public void streamAudiobook(
|
public ResponseEntity<? extends Resource> streamAudiobook(
|
||||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||||
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
|
@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,
|
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex) {
|
||||||
HttpServletRequest request,
|
|
||||||
HttpServletResponse response) throws IOException {
|
|
||||||
|
|
||||||
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, 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.")
|
@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")
|
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
@GetMapping("/{bookId}/track/{trackIndex}/stream")
|
@GetMapping("/{bookId}/track/{trackIndex}/stream")
|
||||||
public void streamTrack(
|
public ResponseEntity<? extends Resource> streamTrack(
|
||||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||||
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex,
|
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex,
|
||||||
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
|
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType) {
|
||||||
HttpServletRequest request,
|
|
||||||
HttpServletResponse response) throws IOException {
|
|
||||||
|
|
||||||
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
|
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
|
||||||
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
|
return getFile(audioPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get embedded cover art",
|
@Operation(summary = "Get embedded cover art",
|
||||||
@@ -100,4 +93,18 @@ public class AudiobookReaderController {
|
|||||||
|
|
||||||
return new ResponseEntity<>(coverData, headers, HttpStatus.OK);
|
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")
|
@GetMapping("/{bookId}/content")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
public void getBookContent(
|
public ResponseEntity<Resource> getBookContent(
|
||||||
@Parameter(description = "ID of the book") @PathVariable long bookId,
|
@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,
|
@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 {
|
return bookService.getBookContent(bookId, bookType);
|
||||||
bookService.streamBookContent(bookId, bookType, request, response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@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.")
|
@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.service.progress.ReadingProgressService;
|
||||||
import org.booklore.util.FileService;
|
import org.booklore.util.FileService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.FileSystemResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.core.io.UrlResource;
|
import org.springframework.core.io.UrlResource;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.*;
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -347,41 +344,17 @@ public class BookService {
|
|||||||
if (!file.exists()) {
|
if (!file.exists()) {
|
||||||
throw ApiError.FILE_NOT_FOUND.createException(filePath);
|
throw ApiError.FILE_NOT_FOUND.createException(filePath);
|
||||||
}
|
}
|
||||||
Resource resource = new FileSystemResource(file);
|
Long lastModified = FileUtils.getFileLastModified(Path.of(filePath));
|
||||||
return ResponseEntity.ok()
|
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
|
||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
|
||||||
.contentLength(file.length())
|
|
||||||
.body(resource);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void streamBookContent(long bookId, String bookType, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
if (lastModified != null) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
builder.lastModified(lastModified);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Path path = Paths.get(filePath);
|
return builder
|
||||||
String fileName = path.getFileName().toString();
|
.cacheControl(CacheControl.noCache().cachePrivate())
|
||||||
String extension = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf('.') + 1) : "";
|
.contentType(MediaTypeFactory.getMediaType(filePath).orElse(MediaType.APPLICATION_OCTET_STREAM))
|
||||||
String contentType = switch (extension.toLowerCase()) {
|
.body(new FileSystemResource(file));
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void replaceBookContent(long bookId, String bookType, java.io.InputStream content) throws IOException {
|
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).
|
* Calculate total size of all files in a folder (for folder-based audiobooks).
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -448,47 +448,5 @@ class BookServiceTest {
|
|||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
assertTrue(result.contains(shelf1));
|
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {AdditionalFileType} from '../model/book.model';
|
|||||||
import {BOOKS_QUERY_KEY, bookDetailQueryKey} from './book-query-keys';
|
import {BOOKS_QUERY_KEY, bookDetailQueryKey} from './book-query-keys';
|
||||||
import {BookFileService} from './book-file.service';
|
import {BookFileService} from './book-file.service';
|
||||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||||
|
import {LocalSettingsService} from '../../../shared/service/local-settings.service';
|
||||||
|
|
||||||
type BuildBookOverrides = Omit<Partial<Book>, 'metadata'> & {
|
type BuildBookOverrides = Omit<Partial<Book>, 'metadata'> & {
|
||||||
metadata?: Partial<BookMetadata>;
|
metadata?: Partial<BookMetadata>;
|
||||||
@@ -51,6 +52,7 @@ describe('BookFileService', () => {
|
|||||||
let queryClient: QueryClient;
|
let queryClient: QueryClient;
|
||||||
let messageService: {add: ReturnType<typeof vi.fn>};
|
let messageService: {add: ReturnType<typeof vi.fn>};
|
||||||
let fileDownloadService: {downloadFile: ReturnType<typeof vi.fn>};
|
let fileDownloadService: {downloadFile: ReturnType<typeof vi.fn>};
|
||||||
|
let localSettingsService: {get: ReturnType<typeof vi.fn>};
|
||||||
let translate: ReturnType<typeof vi.fn>;
|
let translate: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -62,6 +64,9 @@ describe('BookFileService', () => {
|
|||||||
fileDownloadService = {
|
fileDownloadService = {
|
||||||
downloadFile: vi.fn(),
|
downloadFile: vi.fn(),
|
||||||
};
|
};
|
||||||
|
localSettingsService = {
|
||||||
|
get: vi.fn().mockReturnValue({cacheStorageEnabled: false}),
|
||||||
|
};
|
||||||
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
translate = vi.fn((key: string, params?: Record<string, unknown>) => (
|
||||||
params ? `${key}:${JSON.stringify(params)}` : key
|
params ? `${key}:${JSON.stringify(params)}` : key
|
||||||
));
|
));
|
||||||
@@ -75,6 +80,7 @@ describe('BookFileService', () => {
|
|||||||
{provide: MessageService, useValue: messageService},
|
{provide: MessageService, useValue: messageService},
|
||||||
{provide: FileDownloadService, useValue: fileDownloadService},
|
{provide: FileDownloadService, useValue: fileDownloadService},
|
||||||
{provide: TranslocoService, useValue: {translate}},
|
{provide: TranslocoService, useValue: {translate}},
|
||||||
|
{provide: LocalSettingsService, useValue: localSettingsService},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
import {inject, Injectable} from '@angular/core';
|
import {inject, Injectable} from '@angular/core';
|
||||||
import {Observable, throwError} from 'rxjs';
|
import {Observable, throwError, from} from 'rxjs';
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {catchError, tap} from 'rxjs/operators';
|
import {catchError, tap} from 'rxjs/operators';
|
||||||
import {AdditionalFile, AdditionalFileType, Book, DetachBookFileResponse, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model';
|
import {AdditionalFile, AdditionalFileType, Book, DetachBookFileResponse, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model';
|
||||||
import {API_CONFIG} from '../../../core/config/api-config';
|
import {API_CONFIG} from '../../../core/config/api-config';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||||
|
import {CacheStorageService} from '../../../shared/service/cache-storage.service';
|
||||||
|
import {LocalSettingsService} from '../../../shared/service/local-settings.service';
|
||||||
import {TranslocoService} from '@jsverse/transloco';
|
import {TranslocoService} from '@jsverse/transloco';
|
||||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||||
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
|
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
|
||||||
@@ -21,6 +23,8 @@ export class BookFileService {
|
|||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private fileDownloadService = inject(FileDownloadService);
|
private fileDownloadService = inject(FileDownloadService);
|
||||||
private queryClient = inject(QueryClient);
|
private queryClient = inject(QueryClient);
|
||||||
|
private cacheStorageService = inject(CacheStorageService);
|
||||||
|
private localSettingsService = inject(LocalSettingsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
|
|
||||||
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
||||||
@@ -28,6 +32,8 @@ export class BookFileService {
|
|||||||
if (bookType) {
|
if (bookType) {
|
||||||
url += `?bookType=${bookType}`;
|
url += `?bookType=${bookType}`;
|
||||||
}
|
}
|
||||||
|
if (this.localSettingsService.get().cacheStorageEnabled)
|
||||||
|
return from(this.cacheStorageService.getCache(url).then(response => response.blob()));
|
||||||
return this.http.get<Blob>(url, {responseType: 'blob' as 'json'});
|
return this.http.get<Blob>(url, {responseType: 'blob' as 'json'});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { ActivatedRoute } from '@angular/router';
|
|||||||
import { NgxExtendedPdfViewerModule, NgxExtendedPdfViewerService, pdfDefaultOptions, ZoomType } from 'ngx-extended-pdf-viewer';
|
import { NgxExtendedPdfViewerModule, NgxExtendedPdfViewerService, pdfDefaultOptions, ZoomType } from 'ngx-extended-pdf-viewer';
|
||||||
import { PageTitleService } from "../../../shared/service/page-title.service";
|
import { PageTitleService } from "../../../shared/service/page-title.service";
|
||||||
import { BookService } from '../../book/service/book.service';
|
import { BookService } from '../../book/service/book.service';
|
||||||
import { forkJoin, from, Subject, Subscription } from 'rxjs';
|
import { forkJoin, from, Observable, of, Subject, Subscription } from "rxjs";
|
||||||
import { debounceTime, map, switchMap } from 'rxjs/operators';
|
import { debounceTime, map, switchMap } from 'rxjs/operators';
|
||||||
import { BookSetting } from '../../book/model/book.model';
|
import { BookSetting } from '../../book/model/book.model';
|
||||||
import { UserService } from '../../settings/user-management/user.service';
|
import { UserService } from '../../settings/user-management/user.service';
|
||||||
@@ -15,6 +15,8 @@ import { ReaderIconComponent } from '../../readers/ebook-reader/shared/icon.comp
|
|||||||
import { ProgressSpinner } from 'primeng/progressspinner';
|
import { ProgressSpinner } from 'primeng/progressspinner';
|
||||||
import { MessageService } from 'primeng/api';
|
import { MessageService } from 'primeng/api';
|
||||||
import { TranslocoService, TranslocoPipe } from '@jsverse/transloco';
|
import { TranslocoService, TranslocoPipe } from '@jsverse/transloco';
|
||||||
|
import { CacheStorageService } from '../../../shared/service/cache-storage.service'
|
||||||
|
import { LocalSettingsService } from '../../../shared/service/local-settings.service';
|
||||||
import { ReadingSessionService } from '../../../shared/service/reading-session.service';
|
import { ReadingSessionService } from '../../../shared/service/reading-session.service';
|
||||||
import { WakeLockService } from '../../../shared/service/wake-lock.service';
|
import { WakeLockService } from '../../../shared/service/wake-lock.service';
|
||||||
import { Location } from '@angular/common';
|
import { Location } from '@angular/common';
|
||||||
@@ -38,6 +40,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
constructor() {
|
constructor() {
|
||||||
pdfDefaultOptions.rangeChunkSize = 512 * 1024;
|
pdfDefaultOptions.rangeChunkSize = 512 * 1024;
|
||||||
pdfDefaultOptions.disableAutoFetch = true;
|
pdfDefaultOptions.disableAutoFetch = true;
|
||||||
|
pdfDefaultOptions.disableStream = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
@@ -97,6 +100,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
private location = inject(Location);
|
private location = inject(Location);
|
||||||
private pdfViewerService = inject(NgxExtendedPdfViewerService);
|
private pdfViewerService = inject(NgxExtendedPdfViewerService);
|
||||||
private pdfAnnotationService = inject(PdfAnnotationService);
|
private pdfAnnotationService = inject(PdfAnnotationService);
|
||||||
|
private cacheStorageService = inject(CacheStorageService);
|
||||||
|
private localSettingsService = inject(LocalSettingsService);
|
||||||
private readonly t = inject(TranslocoService);
|
private readonly t = inject(TranslocoService);
|
||||||
private wakeLockService = inject(WakeLockService);
|
private wakeLockService = inject(WakeLockService);
|
||||||
private annotationToolbarObserver?: MutationObserver;
|
private annotationToolbarObserver?: MutationObserver;
|
||||||
@@ -131,9 +136,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
]).pipe(map(([bookSetting, myself]) => ({ book, bookSetting, myself })));
|
]).pipe(map(([bookSetting, myself]) => ({ book, bookSetting, myself })));
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
}),
|
||||||
|
switchMap(({book, bookSetting, myself}) => {
|
||||||
|
return this.getBookData(this.bookId.toString(), this.altBookType).pipe(
|
||||||
|
map(bookData => ({book, bookSetting, myself, bookData}))
|
||||||
|
);
|
||||||
})
|
})
|
||||||
).subscribe({
|
).subscribe({
|
||||||
next: ({ book, bookSetting, myself }) => {
|
next: ({ book, bookSetting, myself, bookData }) => {
|
||||||
const pdfMeta = book;
|
const pdfMeta = book;
|
||||||
const pdfPrefs = bookSetting;
|
const pdfPrefs = bookSetting;
|
||||||
|
|
||||||
@@ -151,9 +161,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
}
|
}
|
||||||
this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
|
this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
|
||||||
this.page = pdfMeta.pdfProgress?.page || 1;
|
this.page = pdfMeta.pdfProgress?.page || 1;
|
||||||
this.bookData = this.altBookType
|
this.bookData = bookData;
|
||||||
? `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content?bookType=${this.altBookType}`
|
|
||||||
: `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content`;
|
|
||||||
const token = this.authService.getInternalAccessToken();
|
const token = this.authService.getInternalAccessToken();
|
||||||
this.authorization = token ? `Bearer ${token}` : '';
|
this.authorization = token ? `Bearer ${token}` : '';
|
||||||
this.isLoading = false;
|
this.isLoading = false;
|
||||||
@@ -474,6 +482,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
}
|
}
|
||||||
this.updateProgress();
|
this.updateProgress();
|
||||||
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
|
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
|
||||||
|
|
||||||
|
if (this.bookData?.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(this.bookData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Chrome auto-hide ---
|
// --- Chrome auto-hide ---
|
||||||
@@ -585,6 +597,20 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
this.location.back();
|
this.location.back();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getBookData(
|
||||||
|
bookId: string,
|
||||||
|
fileType: string | undefined,
|
||||||
|
): Observable<string> {
|
||||||
|
const uri = fileType
|
||||||
|
? `${API_CONFIG.BASE_URL}/api/v1/books/${bookId}/content?bookType=${fileType}`
|
||||||
|
: `${API_CONFIG.BASE_URL}/api/v1/books/${bookId}/content`;
|
||||||
|
if (!this.localSettingsService.get().cacheStorageEnabled) return of(uri);
|
||||||
|
return from(this.cacheStorageService.getCache(uri)).pipe(
|
||||||
|
switchMap(res => res.blob()),
|
||||||
|
map(blob => URL.createObjectURL(blob))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
private loadAnnotations(): void {
|
private loadAnnotations(): void {
|
||||||
this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({
|
this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({
|
||||||
next: async (response) => {
|
next: async (response) => {
|
||||||
|
|||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
<ng-container *transloco="let t; prefix: 'settingsNaming'">
|
||||||
|
<div class="local-settings-container">
|
||||||
|
<div class="settings-header">
|
||||||
|
<h2 class="settings-title">
|
||||||
|
<i class="pi pi-home"></i>
|
||||||
|
Local Settings
|
||||||
|
</h2>
|
||||||
|
<p class="settings-description">
|
||||||
|
Browser level settings that only affect the current device. These settings are stored in the browser's local
|
||||||
|
storage and will not be synced across devices.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settings-card">
|
||||||
|
<div class="section-header">
|
||||||
|
<h3 class="section-title">
|
||||||
|
<i class="pi pi-database"></i>
|
||||||
|
Cache Storage Settings
|
||||||
|
</h3>
|
||||||
|
<p class="section-description">
|
||||||
|
Configure Cache Storage to improve performance and reduce server requests.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settings-content">
|
||||||
|
<div class="setting-item">
|
||||||
|
<div class="setting-info">
|
||||||
|
<span class="setting-label">Enable Cache Storage</span>
|
||||||
|
<span class="setting-description">Store data locally in your browser for faster access</span>
|
||||||
|
</div>
|
||||||
|
<div class="setting-control">
|
||||||
|
<p-checkbox [(ngModel)]="settings.cacheStorageEnabled" [binary]="true" (onChange)="onSettingChange()">
|
||||||
|
</p-checkbox>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="setting-item">
|
||||||
|
<div class="setting-info">
|
||||||
|
<span class="setting-label">Cache Storage Usage (MB)</span>
|
||||||
|
<span class="setting-description">Current size occupied by Cache Storage</span>
|
||||||
|
</div>
|
||||||
|
<div class="setting-control action-buttons">
|
||||||
|
<span class="setting-value">{{ cacheStorageUsageMb | number: '1.2-2' }} MB</span>
|
||||||
|
<p-button type="button" label="Refresh" icon="pi pi-refresh" severity="secondary" [outlined]="true"
|
||||||
|
[disabled]="isLoadingCacheStorageUsage" [loading]="isLoadingCacheStorageUsage" (onClick)="loadCacheStorageUsage()">
|
||||||
|
</p-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="setting-item action-item">
|
||||||
|
<div class="setting-info">
|
||||||
|
<span class="setting-label">Clear Cache</span>
|
||||||
|
<span class="setting-description">Remove all data stored in Cache Storage</span>
|
||||||
|
</div>
|
||||||
|
<div class="setting-control">
|
||||||
|
<p-button type="button" label="Clear Cache" icon="pi pi-trash" severity="danger" [outlined]="true"
|
||||||
|
[disabled]="isClearingCacheStorage" [loading]="isClearingCacheStorage" (onClick)="clearCacheStorage()">
|
||||||
|
</p-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ng-container>
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
@use "../../../../shared/styles/settings-shared" as settings;
|
||||||
|
|
||||||
|
.local-settings-container {
|
||||||
|
@include settings.settings-page-container;
|
||||||
|
}
|
||||||
|
|
||||||
|
@include settings.settings-page-header;
|
||||||
|
|
||||||
|
.settings-title {
|
||||||
|
@include settings.settings-page-title;
|
||||||
|
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-description {
|
||||||
|
@include settings.settings-page-description;
|
||||||
|
}
|
||||||
|
|
||||||
|
@include settings.settings-section-divider;
|
||||||
|
|
||||||
|
.settings-card {
|
||||||
|
@include settings.settings-card;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header {
|
||||||
|
@include settings.settings-section-header;
|
||||||
|
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
@include settings.settings-section-title;
|
||||||
|
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-description {
|
||||||
|
@include settings.settings-section-description;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-content {
|
||||||
|
@include settings.settings-section-body;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-item {
|
||||||
|
@include settings.settings-item;
|
||||||
|
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
|
||||||
|
&.action-item {
|
||||||
|
border-left-color: var(--p-orange-500);
|
||||||
|
background: color-mix(
|
||||||
|
in srgb,
|
||||||
|
var(--ground-background) 40%,
|
||||||
|
var(--p-surface-800) 60%
|
||||||
|
);
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: color-mix(
|
||||||
|
in srgb,
|
||||||
|
var(--ground-background) 20%,
|
||||||
|
var(--p-surface-800) 80%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (width <= 768px) {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-info {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-label {
|
||||||
|
@include settings.settings-label;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-description {
|
||||||
|
@include settings.settings-item-description;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-control {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
|
||||||
|
.setting-value {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-color);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.action-buttons {
|
||||||
|
flex-flow: row wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (width <= 768px) {
|
||||||
|
width: 100%;
|
||||||
|
justify-content: flex-start;
|
||||||
|
align-items: flex-start;
|
||||||
|
|
||||||
|
&.action-buttons {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
import {Component, inject, OnInit} from "@angular/core";
|
||||||
|
import {FormsModule} from "@angular/forms";
|
||||||
|
import {DecimalPipe} from "@angular/common";
|
||||||
|
import {Checkbox} from "primeng/checkbox";
|
||||||
|
import {Button} from "primeng/button";
|
||||||
|
import {ConfirmationService, MessageService} from "primeng/api";
|
||||||
|
import {TranslocoDirective} from "@jsverse/transloco";
|
||||||
|
import {LocalSettingsService, LocalSettings} from "../../../../shared/service/local-settings.service";
|
||||||
|
import {CacheStorageService} from "../../../../shared/service/cache-storage.service";
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: "app-local-settings",
|
||||||
|
imports: [
|
||||||
|
FormsModule,
|
||||||
|
DecimalPipe,
|
||||||
|
Checkbox,
|
||||||
|
Button,
|
||||||
|
TranslocoDirective,
|
||||||
|
],
|
||||||
|
templateUrl: "./local-settings.component.html",
|
||||||
|
styleUrl: "./local-settings.component.scss",
|
||||||
|
})
|
||||||
|
export class LocalSettingsComponent implements OnInit {
|
||||||
|
private localSettingsService = inject(LocalSettingsService);
|
||||||
|
private cacheStorageService = inject(CacheStorageService);
|
||||||
|
private messageService = inject(MessageService);
|
||||||
|
private confirmationService = inject(ConfirmationService);
|
||||||
|
|
||||||
|
protected settings: LocalSettings = this.localSettingsService.get();
|
||||||
|
|
||||||
|
protected isLoadingCacheStorageUsage = false;
|
||||||
|
protected isClearingCacheStorage = false;
|
||||||
|
protected cacheStorageUsageMb = 0;
|
||||||
|
|
||||||
|
async ngOnInit(): Promise<void> {
|
||||||
|
await this.loadCacheStorageUsage();
|
||||||
|
}
|
||||||
|
|
||||||
|
onSettingChange(): void {
|
||||||
|
this.localSettingsService.commitSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearCacheStorage(): void {
|
||||||
|
this.confirmationService.confirm({
|
||||||
|
message:
|
||||||
|
"Are you sure you want to clear all Cache Storage data? This action cannot be undone.",
|
||||||
|
header: "Clear Cache Storage",
|
||||||
|
icon: "pi pi-exclamation-triangle",
|
||||||
|
acceptLabel: "Clear",
|
||||||
|
rejectLabel: "Cancel",
|
||||||
|
acceptButtonProps: {
|
||||||
|
label: "Clear",
|
||||||
|
severity: "danger",
|
||||||
|
},
|
||||||
|
rejectButtonProps: {
|
||||||
|
label: "Cancel",
|
||||||
|
severity: "secondary",
|
||||||
|
},
|
||||||
|
accept: async () => {
|
||||||
|
this.isClearingCacheStorage = true;
|
||||||
|
try {
|
||||||
|
await this.cacheStorageService.clear();
|
||||||
|
await this.loadCacheStorageUsage();
|
||||||
|
this.messageService.add({
|
||||||
|
severity: "success",
|
||||||
|
summary: "Storage Cache cleared",
|
||||||
|
detail: "All Cache Storage data has been cleared successfully.",
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: "error",
|
||||||
|
summary: "Clear cache failed",
|
||||||
|
detail: "Unable to clear Cache Storage. Please try again.",
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
this.isClearingCacheStorage = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async loadCacheStorageUsage(): Promise<void> {
|
||||||
|
this.isLoadingCacheStorageUsage = true;
|
||||||
|
try {
|
||||||
|
const totalBytes = await this.cacheStorageService.getCacheSizeInBytes();
|
||||||
|
this.cacheStorageUsageMb = totalBytes / (1024 * 1024);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error loading Cache Storage usage:", error);
|
||||||
|
this.cacheStorageUsageMb = 0;
|
||||||
|
} finally {
|
||||||
|
this.isLoadingCacheStorageUsage = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
@@ -12,6 +12,7 @@
|
|||||||
|
|
||||||
<div class="settings-content">
|
<div class="settings-content">
|
||||||
<app-settings-application-mode [userSettings]="userSettings"></app-settings-application-mode>
|
<app-settings-application-mode [userSettings]="userSettings"></app-settings-application-mode>
|
||||||
|
<app-local-settings/>
|
||||||
|
|
||||||
<div class="preferences-section">
|
<div class="preferences-section">
|
||||||
<div class="section-header">
|
<div class="section-header">
|
||||||
@@ -83,6 +84,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
|
|||||||
+2
-1
@@ -9,13 +9,14 @@ import {PdfReaderPreferencesComponent} from './pdf-reader-preferences/pdf-reader
|
|||||||
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component';
|
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component';
|
||||||
import {CustomFontsComponent} from '../custom-fonts/custom-fonts.component';
|
import {CustomFontsComponent} from '../custom-fonts/custom-fonts.component';
|
||||||
import {SettingsApplicationModeComponent} from './settings-application-mode/settings-application-mode.component';
|
import {SettingsApplicationModeComponent} from './settings-application-mode/settings-application-mode.component';
|
||||||
|
import {LocalSettingsComponent} from "./local-settings/local-settings.component";
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-reader-preferences',
|
selector: 'app-reader-preferences',
|
||||||
templateUrl: './reader-preferences.component.html',
|
templateUrl: './reader-preferences.component.html',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
styleUrls: ['./reader-preferences.component.scss'],
|
styleUrls: ['./reader-preferences.component.scss'],
|
||||||
imports: [FormsModule, TooltipModule, TranslocoDirective, EpubReaderPreferencesComponent, PdfReaderPreferencesComponent, CbxReaderPreferencesComponent, CustomFontsComponent, SettingsApplicationModeComponent]
|
imports: [FormsModule, TooltipModule, TranslocoDirective, EpubReaderPreferencesComponent, PdfReaderPreferencesComponent, CbxReaderPreferencesComponent, CustomFontsComponent, SettingsApplicationModeComponent, LocalSettingsComponent]
|
||||||
})
|
})
|
||||||
export class ReaderPreferences {
|
export class ReaderPreferences {
|
||||||
private readonly userService = inject(UserService);
|
private readonly userService = inject(UserService);
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ export enum SettingsTab {
|
|||||||
styleUrl: './settings.component.scss'
|
styleUrl: './settings.component.scss'
|
||||||
})
|
})
|
||||||
export class SettingsComponent implements OnInit, OnDestroy {
|
export class SettingsComponent implements OnInit, OnDestroy {
|
||||||
|
|
||||||
protected userService = inject(UserService);
|
protected userService = inject(UserService);
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import {inject, Injectable} from "@angular/core";
|
||||||
|
import {HttpClient, HttpErrorResponse, HttpResponse} from "@angular/common/http";
|
||||||
|
import {firstValueFrom} from "rxjs";
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: "root",
|
||||||
|
})
|
||||||
|
export class CacheStorageService {
|
||||||
|
private static readonly CACHE_NAME = "storage";
|
||||||
|
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
|
async getCache(uri: string, noValidate: boolean = false): Promise<Response> {
|
||||||
|
const cachedResponse = await this.attemptToGetAndValidateCache(uri, noValidate);
|
||||||
|
if (cachedResponse) {
|
||||||
|
return cachedResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache stale or failed to get, fetch from uri
|
||||||
|
|
||||||
|
const httpResponse = await this.fetchFromUri(uri);
|
||||||
|
const headers = new Headers();
|
||||||
|
httpResponse.headers.keys().forEach((key) => {
|
||||||
|
headers.set(key, httpResponse.headers.get(key)!);
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = new Response(httpResponse.body, {
|
||||||
|
headers: headers,
|
||||||
|
status: httpResponse.status,
|
||||||
|
statusText: httpResponse.statusText,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.put(uri, res.clone()).catch((error) => {
|
||||||
|
console.error("Error caching response:", error);
|
||||||
|
});
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws no throws
|
||||||
|
* @returns cached response, or null if cache is stale or failed to access/validate
|
||||||
|
*/
|
||||||
|
private async attemptToGetAndValidateCache(uri: string, noValidate: boolean = false): Promise<Response | null> {
|
||||||
|
let stale: boolean = true;
|
||||||
|
let entry;
|
||||||
|
try {
|
||||||
|
entry = await this.match(uri);
|
||||||
|
if (entry) {
|
||||||
|
stale = false;
|
||||||
|
if (!noValidate) {
|
||||||
|
stale = !(await this.validateCacheFromUri(uri, entry));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error accessing or validating cache:", error);
|
||||||
|
stale = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!stale && entry)
|
||||||
|
return entry;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchFromUri(uri: string): Promise<HttpResponse<ArrayBuffer>> {
|
||||||
|
return firstValueFrom(
|
||||||
|
this.http.get<ArrayBuffer>(uri, {
|
||||||
|
responseType: "arraybuffer" as "json",
|
||||||
|
observe: "response",
|
||||||
|
cache: "no-store", // Avoid double caching
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async validateCacheFromUri(uri: string, entry: Response): Promise<boolean> {
|
||||||
|
const h = entry.headers.get("last-modified");
|
||||||
|
if (h == null) return false;
|
||||||
|
try {
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.http.head<ArrayBuffer>(uri, {
|
||||||
|
observe: "response",
|
||||||
|
responseType: "arraybuffer" as "json",
|
||||||
|
headers: { "if-modified-since": h },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.status === 304;
|
||||||
|
} catch (error: unknown) { // It throws if the status is not 2xx
|
||||||
|
if (error instanceof HttpErrorResponse && error.status === 304) {
|
||||||
|
return true; // Not modified, cache is valid
|
||||||
|
}
|
||||||
|
console.error("Error validating cache:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match(uri: string): Promise<Response | undefined> {
|
||||||
|
return this.cache().then((cache) => cache.match(uri));
|
||||||
|
}
|
||||||
|
|
||||||
|
has(uri: string): Promise<boolean> {
|
||||||
|
return this.cache().then((cache) =>
|
||||||
|
cache.match(uri).then((response) => !!response),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
put(uri: string, entry: Response): Promise<void> {
|
||||||
|
return this.cache().then((cache) => cache.put(uri, entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(uri: string): Promise<boolean> {
|
||||||
|
return this.cache().then((cache) => cache.delete(uri));
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): Promise<void> {
|
||||||
|
return this.cache()
|
||||||
|
.then((cache) => cache.keys())
|
||||||
|
.then((keys) => Promise.all(keys.map((key) => this.delete(key.url))))
|
||||||
|
.then(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCacheSizeInBytes(): Promise<number> {
|
||||||
|
return this.cache()
|
||||||
|
.then((cache) => cache.keys())
|
||||||
|
.then((keys) => keys.map((key) => this.match(key.url)))
|
||||||
|
.then((promises) => Promise.all(promises))
|
||||||
|
.then((responses) => responses.map(response => parseInt(response?.headers.get("content-length") || "0")))
|
||||||
|
.then((sizes) => sizes.reduce((total, size) => total + size, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private cache(): Promise<Cache> {
|
||||||
|
return caches.open(CacheStorageService.CACHE_NAME);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { inject, Injectable } from "@angular/core";
|
||||||
|
import { LocalStorageService } from "./local-storage.service";
|
||||||
|
|
||||||
|
export interface LocalSettings {
|
||||||
|
cacheStorageEnabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: "root",
|
||||||
|
})
|
||||||
|
export class LocalSettingsService {
|
||||||
|
private localStorage = inject(LocalStorageService);
|
||||||
|
public readonly storageName = "local_settings";
|
||||||
|
|
||||||
|
public readonly defaultSettings: LocalSettings = {
|
||||||
|
cacheStorageEnabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
protected settings: LocalSettings;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.settings = { ...this.defaultSettings };
|
||||||
|
|
||||||
|
// Load settings from localStorage on initialization
|
||||||
|
this.repairSettings();
|
||||||
|
this.loadSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
get(): LocalSettings {
|
||||||
|
return this.settings;
|
||||||
|
}
|
||||||
|
|
||||||
|
loadSettings(): void {
|
||||||
|
const settings = this.getFromLocalStorage();
|
||||||
|
if (settings) {
|
||||||
|
this.setFields(settings);
|
||||||
|
} else {
|
||||||
|
this.setFields(this.defaultSettings);
|
||||||
|
this.commitToLocalStorage(this.settings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
commitSettings(): void {
|
||||||
|
this.commitToLocalStorage(this.settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getFromLocalStorage(): LocalSettings | null {
|
||||||
|
const stored = this.localStorage.get<LocalSettings>(this.storageName);
|
||||||
|
if (stored) {
|
||||||
|
return { ...this.defaultSettings, ...stored }; // Defaults will be overridden by stored values
|
||||||
|
}
|
||||||
|
return null; // Settings does not exist or some fields is missing
|
||||||
|
}
|
||||||
|
|
||||||
|
private commitToLocalStorage(settings: LocalSettings): void {
|
||||||
|
this.localStorage.set(this.storageName, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure that all settings fields are present.
|
||||||
|
* If any field is missing, reset to default settings.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
private repairSettings(): void {
|
||||||
|
if (!this.getFromLocalStorage()) {
|
||||||
|
this.commitToLocalStorage(this.defaultSettings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the fields of the settings object.
|
||||||
|
*/
|
||||||
|
private setFields(settings: LocalSettings): void {
|
||||||
|
if (settings === this.settings) return; // Referential equality
|
||||||
|
this.settings = { ...settings };
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user