refactor(api): use spring content disposition helper for BookDownloadService (#449)

This commit is contained in:
James Ward
2026-04-22 17:27:11 -04:00
committed by Zach Yale
parent 7abac02b0c
commit 26379606df
2 changed files with 136 additions and 31 deletions
@@ -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")
@@ -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<Files> 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;
}
}