From 26379606dfcefefcabe6ac9ee0617a6c536d9e43 Mon Sep 17 00:00:00 2001 From: James Ward Date: Fri, 10 Apr 2026 18:52:10 -0400 Subject: [PATCH] refactor(api): use spring content disposition helper for `BookDownloadService` (#449) --- .../service/book/BookDownloadService.java | 57 +++++---- .../service/book/BookDownloadServiceTest.java | 110 ++++++++++++++++++ 2 files changed, 136 insertions(+), 31 deletions(-) create mode 100644 booklore-api/src/test/java/org/booklore/service/book/BookDownloadServiceTest.java diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookDownloadService.java b/booklore-api/src/main/java/org/booklore/service/book/BookDownloadService.java index 45b405b36..4c472ad4e 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookDownloadService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookDownloadService.java @@ -16,6 +16,7 @@ import org.booklore.service.kobo.KepubConversionService; import org.booklore.util.FileUtils; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +import org.springframework.http.ContentDisposition; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -26,13 +27,12 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; -import java.net.URLEncoder; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; import java.util.List; -import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -41,8 +41,6 @@ import java.util.zip.ZipOutputStream; @Service public class BookDownloadService { - private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]"); - private final BookRepository bookRepository; private final BookFileRepository bookFileRepository; private final KepubConversionService kepubConversionService; @@ -75,15 +73,10 @@ public class BookDownloadService { // Use FileSystemResource which properly handles file resources and closing Resource resource = new FileSystemResource(bookFile); - String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8) - .replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_"); - String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(bookFile.length()) - .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)) .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") .header(HttpHeaders.PRAGMA, "no-cache") .header(HttpHeaders.EXPIRES, "0") @@ -119,15 +112,10 @@ public class BookDownloadService { File bookFile = file.toFile(); Resource resource = new FileSystemResource(bookFile); - String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8) - .replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_"); - String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(bookFile.length()) - .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)) .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") .header(HttpHeaders.PRAGMA, "no-cache") .header(HttpHeaders.EXPIRES, "0") @@ -138,6 +126,24 @@ public class BookDownloadService { } } + private String getContentDisposition(File file) { + return getContentDisposition(file.getName()); + } + + private String getContentDisposition(Path path) { + return getContentDisposition(path.getFileName().toString()); + } + + private String getContentDisposition(String filename) { + Charset charset = filename.matches("\\p{ASCII}*") ? + StandardCharsets.US_ASCII : StandardCharsets.UTF_8; + + return ContentDisposition.builder("attachment") + .filename(filename, charset) + .build() + .toString(); + } + public void downloadAllBookFiles(Long bookId, HttpServletResponse response) { BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); @@ -178,11 +184,8 @@ public class BookDownloadService { String zipFileName = safeTitle + ".zip"; response.setContentType("application/zip"); - String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_"); - String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); + + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName)); try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { for (BookFileEntity bookFile : allFiles) { @@ -295,11 +298,7 @@ public class BookDownloadService { private void setResponseHeaders(HttpServletResponse response, File file) { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setContentLengthLong(file.length()); - String encodedFilename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8).replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getName()).replaceAll("_"); - String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(file)); } private void streamFileToResponse(File file, HttpServletResponse response) { @@ -344,14 +343,10 @@ public class BookDownloadService { Resource resource = new org.springframework.core.io.ByteArrayResource(zipBytes); String zipFileName = folderName + ".zip"; - String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_"); - String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); return ResponseEntity.ok() .contentType(MediaType.valueOf("application/zip")) - .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) + .header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName)) .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length)) .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") .header(HttpHeaders.PRAGMA, "no-cache") diff --git a/booklore-api/src/test/java/org/booklore/service/book/BookDownloadServiceTest.java b/booklore-api/src/test/java/org/booklore/service/book/BookDownloadServiceTest.java new file mode 100644 index 000000000..e5fb561de --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/book/BookDownloadServiceTest.java @@ -0,0 +1,110 @@ +package org.booklore.service.book; + +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.repository.*; +import org.booklore.service.appsettings.AppSettingService; +import org.booklore.service.kobo.CbxConversionService; +import org.booklore.service.kobo.KepubConversionService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.nio.file.Files; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class BookDownloadServiceTest { + + @Mock private BookRepository bookRepository; + + @Mock private BookFileRepository bookFileRepository; + + @Mock private KepubConversionService kepubConversionService; + + @Mock private CbxConversionService cbxConversionService; + + @Mock private AppSettingService appSettingService; + + @InjectMocks + private BookDownloadService bookDownloadService; + + private MockedStatic mockFiles; + + @BeforeEach + public void setup() throws Exception { + mockFiles = mockStatic(Files.class); + } + + @AfterEach + void tearDown() { + mockFiles.close(); + } + + @Test + public void downloadBook_includesContentDispositionAscii() { + String expected = "attachment; filename=\"example.epub\""; + + BookEntity bookEntity = getSampleBook("example.epub"); + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + mockFiles.when(() -> Files.exists(bookEntity.getFullFilePath())).thenReturn(true); + mockFiles.when(() -> Files.isDirectory(bookEntity.getFullFilePath())).thenReturn(false); + + String actual = bookDownloadService.downloadBook(1L) + .getHeaders() + .getFirst("Content-Disposition"); + + assertEquals(expected, actual); + } + + @Test + public void downloadBook_includesContentDispositionUTF8() { + String expected = "attachment; filename=\"=?UTF-8?Q?=C9=87xample.epub?=\"; filename*=UTF-8''%C9%87xample.epub"; + + BookEntity bookEntity = getSampleBook("ɇxample.epub"); + when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); + + mockFiles.when(() -> Files.exists(bookEntity.getFullFilePath())).thenReturn(true); + mockFiles.when(() -> Files.isDirectory(bookEntity.getFullFilePath())).thenReturn(false); + + String actual = bookDownloadService.downloadBook(1L) + .getHeaders() + .getFirst("Content-Disposition"); + + assertEquals(expected, actual); + } + + private BookEntity getSampleBook(String filename) { + LibraryPathEntity libraryPathEntity = LibraryPathEntity + .builder() + .path("/library") + .build(); + + BookFileEntity bookFileEntity = BookFileEntity.builder() + .fileName(filename) + .fileSubPath("/subpath") + .build(); + + BookEntity bookEntity = BookEntity.builder() + .bookFiles(List.of(bookFileEntity)) + .libraryPath(libraryPathEntity) + .build(); + + // Ensure we've set the identity here. + bookFileEntity.setBook(bookEntity); + + return bookEntity; + } +}