perf(download): stream all book downloads via StreamingResponseBody (#1722)
This commit is contained in:
@@ -11,9 +11,9 @@ import org.booklore.service.book.BookFileDetachmentService;
|
|||||||
import org.booklore.service.file.AdditionalFileService;
|
import org.booklore.service.file.AdditionalFileService;
|
||||||
import org.booklore.service.upload.FileUploadService;
|
import org.booklore.service.upload.FileUploadService;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ public class AdditionalFileController {
|
|||||||
)
|
)
|
||||||
@GetMapping("/{fileId}/download")
|
@GetMapping("/{fileId}/download")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
public ResponseEntity<Resource> downloadAdditionalFile(
|
public ResponseEntity<StreamingResponseBody> downloadAdditionalFile(
|
||||||
@PathVariable Long bookId,
|
@PathVariable Long bookId,
|
||||||
@PathVariable Long fileId) throws IOException {
|
@PathVariable Long fileId) throws IOException {
|
||||||
return additionalFileService.downloadAdditionalFile(bookId, fileId);
|
return additionalFileService.downloadAdditionalFile(bookId, fileId);
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.Max;
|
import jakarta.validation.constraints.Max;
|
||||||
import jakarta.validation.constraints.Min;
|
import jakarta.validation.constraints.Min;
|
||||||
@@ -43,6 +42,7 @@ import org.springframework.data.domain.Page;
|
|||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
@@ -189,7 +189,7 @@ public class BookController {
|
|||||||
@GetMapping("/{bookId}/download")
|
@GetMapping("/{bookId}/download")
|
||||||
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
public ResponseEntity<StreamingResponseBody> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||||
return bookService.downloadBook(bookId);
|
return bookService.downloadBook(bookId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,10 +202,9 @@ public class BookController {
|
|||||||
@GetMapping("/{bookId}/download-all")
|
@GetMapping("/{bookId}/download-all")
|
||||||
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
public void downloadAllBookFiles(
|
public ResponseEntity<StreamingResponseBody> downloadAllBookFiles(
|
||||||
@Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId,
|
@Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId) {
|
||||||
HttpServletResponse response) {
|
return bookService.downloadAllBookFiles(bookId);
|
||||||
bookService.downloadAllBookFiles(bookId, response);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book file.")
|
@Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book file.")
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import org.booklore.service.komga.KomgaService;
|
|||||||
import org.booklore.service.opds.OpdsUserV2Service;
|
import org.booklore.service.opds.OpdsUserV2Service;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
@@ -185,7 +186,7 @@ public class KomgaController {
|
|||||||
|
|
||||||
@Operation(summary = "Download book file")
|
@Operation(summary = "Download book file")
|
||||||
@GetMapping("/v1/books/{bookId}/file")
|
@GetMapping("/v1/books/{bookId}/file")
|
||||||
public ResponseEntity<Resource> downloadBook(
|
public ResponseEntity<StreamingResponseBody> downloadBook(
|
||||||
@Parameter(description = "Book ID") @PathVariable Long bookId) {
|
@Parameter(description = "Book ID") @PathVariable Long bookId) {
|
||||||
validateBookContentAccess(bookId);
|
validateBookContentAccess(bookId);
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
@@ -48,7 +49,7 @@ public class OpdsController {
|
|||||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||||
})
|
})
|
||||||
@GetMapping("/{bookId}/download")
|
@GetMapping("/{bookId}/download")
|
||||||
public ResponseEntity<Resource> downloadBook(
|
public ResponseEntity<StreamingResponseBody> downloadBook(
|
||||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId,
|
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId,
|
||||||
@Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) {
|
@Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) {
|
||||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||||
|
|||||||
@@ -15,14 +15,13 @@ import org.booklore.service.kobo.CbxConversionService;
|
|||||||
import org.booklore.service.kobo.KepubConversionService;
|
import org.booklore.service.kobo.KepubConversionService;
|
||||||
import org.booklore.service.kobo.KoboSpanMapService;
|
import org.booklore.service.kobo.KoboSpanMapService;
|
||||||
import org.booklore.util.FileUtils;
|
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.ContentDisposition;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.util.FileSystemUtils;
|
import org.springframework.util.FileSystemUtils;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -37,8 +36,6 @@ import java.util.List;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipEntry;
|
||||||
import java.util.zip.ZipOutputStream;
|
import java.util.zip.ZipOutputStream;
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@@ -54,7 +51,7 @@ public class BookDownloadService {
|
|||||||
private final KoboSpanMapService koboSpanMapService;
|
private final KoboSpanMapService koboSpanMapService;
|
||||||
private final AppSettingService appSettingService;
|
private final AppSettingService appSettingService;
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadBook(Long bookId) {
|
public ResponseEntity<StreamingResponseBody> downloadBook(Long bookId) {
|
||||||
try {
|
try {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
@@ -75,26 +72,14 @@ public class BookDownloadService {
|
|||||||
return downloadFolderAsZip(file, primaryFile.getFileName());
|
return downloadFolderAsZip(file, primaryFile.getFileName());
|
||||||
}
|
}
|
||||||
|
|
||||||
File bookFile = file.toFile();
|
return streamFile(file);
|
||||||
|
|
||||||
// Use FileSystemResource which properly handles file resources and closing
|
|
||||||
Resource resource = new FileSystemResource(bookFile);
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
|
||||||
.contentLength(bookFile.length())
|
|
||||||
.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")
|
|
||||||
.body(resource);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to download book {}: {}", bookId, e.getMessage(), e);
|
log.error("Failed to download book {}: {}", bookId, e.getMessage(), e);
|
||||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadBookFile(Long bookId, Long fileId) {
|
public ResponseEntity<StreamingResponseBody> downloadBookFile(Long bookId, Long fileId) {
|
||||||
try {
|
try {
|
||||||
BookFileEntity bookFileEntity = bookFileRepository.findByIdWithBookAndLibraryPath(fileId)
|
BookFileEntity bookFileEntity = bookFileRepository.findByIdWithBookAndLibraryPath(fileId)
|
||||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileId));
|
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileId));
|
||||||
@@ -116,23 +101,29 @@ public class BookDownloadService {
|
|||||||
return downloadFolderAsZip(file, bookFileEntity.getFileName());
|
return downloadFolderAsZip(file, bookFileEntity.getFileName());
|
||||||
}
|
}
|
||||||
|
|
||||||
File bookFile = file.toFile();
|
return streamFile(file);
|
||||||
Resource resource = new FileSystemResource(bookFile);
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
|
||||||
.contentLength(bookFile.length())
|
|
||||||
.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")
|
|
||||||
.body(resource);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to download book file {}: {}", fileId, e.getMessage(), e);
|
log.error("Failed to download book file {}: {}", fileId, e.getMessage(), e);
|
||||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId);
|
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ResponseEntity<StreamingResponseBody> streamFile(Path file) {
|
||||||
|
StreamingResponseBody body = outputStream -> {
|
||||||
|
try (InputStream in = Files.newInputStream(file)) {
|
||||||
|
in.transferTo(outputStream);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.contentLength(file.toFile().length())
|
||||||
|
.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")
|
||||||
|
.body(body);
|
||||||
|
}
|
||||||
|
|
||||||
private String getContentDisposition(File file) {
|
private String getContentDisposition(File file) {
|
||||||
return getContentDisposition(file.getName());
|
return getContentDisposition(file.getName());
|
||||||
}
|
}
|
||||||
@@ -151,7 +142,7 @@ public class BookDownloadService {
|
|||||||
.toString();
|
.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void downloadAllBookFiles(Long bookId, HttpServletResponse response) {
|
public ResponseEntity<StreamingResponseBody> downloadAllBookFiles(Long bookId) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
|
||||||
@@ -173,77 +164,71 @@ public class BookDownloadService {
|
|||||||
|
|
||||||
// For folder-based audiobooks, let it fall through to ZIP creation
|
// For folder-based audiobooks, let it fall through to ZIP creation
|
||||||
if (!singleFile.isFolderBased() || !Files.isDirectory(filePath)) {
|
if (!singleFile.isFolderBased() || !Files.isDirectory(filePath)) {
|
||||||
File file = filePath.toFile();
|
return streamFile(filePath);
|
||||||
setResponseHeaders(response, file);
|
|
||||||
streamFileToResponse(file, response);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort files by filename for consistent ordering
|
// Resolve entity data upfront so streaming only handles file I/O
|
||||||
allFiles.sort(Comparator.comparing(BookFileEntity::getFileName));
|
List<ZipSource> sources = allFiles.stream()
|
||||||
|
.sorted(Comparator.comparing(BookFileEntity::getFileName))
|
||||||
|
.map(f -> new ZipSource(
|
||||||
|
FileUtils.requirePathWithinBase(f.getFullFilePath(), libraryRoot),
|
||||||
|
f.getFileName(),
|
||||||
|
f.isFolderBased()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
// Create ZIP with all files
|
|
||||||
String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null
|
String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null
|
||||||
? bookEntity.getMetadata().getTitle()
|
? bookEntity.getMetadata().getTitle()
|
||||||
: "book-" + bookId;
|
: "book-" + bookId;
|
||||||
String safeTitle = NON_ALPHANUMERIC_PATTERN.matcher(bookTitle).replaceAll("_");
|
String zipFileName = NON_ALPHANUMERIC_PATTERN.matcher(bookTitle).replaceAll("_") + ".zip";
|
||||||
String zipFileName = safeTitle + ".zip";
|
|
||||||
|
|
||||||
response.setContentType("application/zip");
|
StreamingResponseBody body = outputStream -> {
|
||||||
|
try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
|
||||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName));
|
for (ZipSource source : sources) {
|
||||||
|
if (!Files.exists(source.path())) {
|
||||||
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
|
log.warn("Skipping missing file during ZIP creation: {}", source.path());
|
||||||
for (BookFileEntity bookFile : allFiles) {
|
|
||||||
Path filePath = FileUtils.requirePathWithinBase(bookFile.getFullFilePath(), libraryRoot);
|
|
||||||
|
|
||||||
if (!Files.exists(filePath)) {
|
|
||||||
log.warn("Skipping missing file during ZIP creation: {}", filePath);
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle folder-based audiobooks - add all files from the folder
|
// Handle folder-based audiobooks - add all files from the folder
|
||||||
if (bookFile.isFolderBased() && Files.isDirectory(filePath)) {
|
if (source.folderBased() && Files.isDirectory(source.path())) {
|
||||||
String folderPrefix = bookFile.getFileName() + "/";
|
String folderPrefix = source.name() + "/";
|
||||||
try (var audioFiles = Files.list(filePath)) {
|
try (var audioFiles = Files.list(source.path())) {
|
||||||
for (Path audioFile : audioFiles
|
for (Path audioFile : audioFiles
|
||||||
.filter(Files::isRegularFile)
|
.filter(Files::isRegularFile)
|
||||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||||
.toList()) {
|
.toList()) {
|
||||||
String entryName = folderPrefix + audioFile.getFileName().toString();
|
addZipEntry(zos, folderPrefix + audioFile.getFileName().toString(), audioFile);
|
||||||
ZipEntry zipEntry = new ZipEntry(entryName);
|
|
||||||
zipEntry.setSize(Files.size(audioFile));
|
|
||||||
zos.putNextEntry(zipEntry);
|
|
||||||
|
|
||||||
try (InputStream fis = Files.newInputStream(audioFile)) {
|
|
||||||
fis.transferTo(zos);
|
|
||||||
}
|
|
||||||
|
|
||||||
zos.closeEntry();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Regular file
|
addZipEntry(zos, source.name(), source.path());
|
||||||
ZipEntry zipEntry = new ZipEntry(bookFile.getFileName());
|
}
|
||||||
zipEntry.setSize(Files.size(filePath));
|
}
|
||||||
zos.putNextEntry(zipEntry);
|
}
|
||||||
|
log.info("Successfully streamed ZIP for book {} with {} files", bookId, sources.size());
|
||||||
|
};
|
||||||
|
|
||||||
try (InputStream fis = Files.newInputStream(filePath)) {
|
return ResponseEntity.ok()
|
||||||
fis.transferTo(zos);
|
.contentType(MediaType.valueOf("application/zip"))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName))
|
||||||
|
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
||||||
|
.header(HttpHeaders.PRAGMA, "no-cache")
|
||||||
|
.header(HttpHeaders.EXPIRES, "0")
|
||||||
|
.body(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void addZipEntry(ZipOutputStream zos, String entryName, Path file) throws IOException {
|
||||||
|
ZipEntry zipEntry = new ZipEntry(entryName);
|
||||||
|
zipEntry.setSize(Files.size(file));
|
||||||
|
zos.putNextEntry(zipEntry);
|
||||||
|
try (InputStream in = Files.newInputStream(file)) {
|
||||||
|
in.transferTo(zos);
|
||||||
|
}
|
||||||
zos.closeEntry();
|
zos.closeEntry();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
zos.finish();
|
|
||||||
response.getOutputStream().flush();
|
|
||||||
|
|
||||||
log.info("Successfully created and streamed ZIP for book {} with {} files", bookId, allFiles.size());
|
private record ZipSource(Path path, String name, boolean folderBased) {
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("Failed to create ZIP for book {}: {}", bookId, e.getMessage(), e);
|
|
||||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void downloadKoboBook(Long bookId, HttpServletResponse response) {
|
public void downloadKoboBook(Long bookId, HttpServletResponse response) {
|
||||||
@@ -333,36 +318,28 @@ public class BookDownloadService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResponseEntity<Resource> downloadFolderAsZip(Path folderPath, String folderName) throws IOException {
|
private ResponseEntity<StreamingResponseBody> downloadFolderAsZip(Path folderPath, String folderName) {
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
StreamingResponseBody body = outputStream -> {
|
||||||
|
try (ZipOutputStream zos = new ZipOutputStream(outputStream);
|
||||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
var files = Files.list(folderPath)) {
|
||||||
// Get all files in the folder, sorted by name
|
// Get all files in the folder, sorted by name
|
||||||
try (var files = Files.list(folderPath)) {
|
|
||||||
for (Path audioFile : files
|
for (Path audioFile : files
|
||||||
.filter(Files::isRegularFile)
|
.filter(Files::isRegularFile)
|
||||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||||
.toList()) {
|
.toList()) {
|
||||||
ZipEntry entry = new ZipEntry(audioFile.getFileName().toString());
|
zos.putNextEntry(new ZipEntry(audioFile.getFileName().toString()));
|
||||||
zos.putNextEntry(entry);
|
|
||||||
Files.copy(audioFile, zos);
|
Files.copy(audioFile, zos);
|
||||||
zos.closeEntry();
|
zos.closeEntry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
byte[] zipBytes = baos.toByteArray();
|
|
||||||
Resource resource = new ByteArrayResource(zipBytes);
|
|
||||||
|
|
||||||
String zipFileName = folderName + ".zip";
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.valueOf("application/zip"))
|
.contentType(MediaType.valueOf("application/zip"))
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(zipFileName))
|
.header(HttpHeaders.CONTENT_DISPOSITION, getContentDisposition(folderName + ".zip"))
|
||||||
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length))
|
|
||||||
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
||||||
.header(HttpHeaders.PRAGMA, "no-cache")
|
.header(HttpHeaders.PRAGMA, "no-cache")
|
||||||
.header(HttpHeaders.EXPIRES, "0")
|
.header(HttpHeaders.EXPIRES, "0")
|
||||||
.body(resource);
|
.body(body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package org.booklore.service.book;
|
package org.booklore.service.book;
|
||||||
|
|
||||||
import jakarta.persistence.EntityManager;
|
import jakarta.persistence.EntityManager;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
@@ -31,6 +30,7 @@ import org.springframework.core.io.UrlResource;
|
|||||||
import org.springframework.data.domain.Page;
|
import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.*;
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -346,12 +346,12 @@ public class BookService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadBook(Long bookId) {
|
public ResponseEntity<StreamingResponseBody> downloadBook(Long bookId) {
|
||||||
return bookDownloadService.downloadBook(bookId);
|
return bookDownloadService.downloadBook(bookId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void downloadAllBookFiles(Long bookId, HttpServletResponse response) {
|
public ResponseEntity<StreamingResponseBody> downloadAllBookFiles(Long bookId) {
|
||||||
bookDownloadService.downloadAllBookFiles(bookId, response);
|
return bookDownloadService.downloadAllBookFiles(bookId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Resource> getBookContent(long bookId) {
|
public ResponseEntity<Resource> getBookContent(long bookId) {
|
||||||
|
|||||||
@@ -8,17 +8,15 @@ import org.booklore.repository.BookAdditionalFileRepository;
|
|||||||
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
import org.booklore.service.monitoring.MonitoringRegistrationService;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.core.io.UrlResource;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
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;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -96,7 +94,7 @@ public class AdditionalFileService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public ResponseEntity<Resource> downloadAdditionalFile(Long bookId, Long fileId) throws IOException {
|
public ResponseEntity<StreamingResponseBody> downloadAdditionalFile(Long bookId, Long fileId) throws IOException {
|
||||||
Optional<BookFileEntity> fileOpt = additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId);
|
Optional<BookFileEntity> fileOpt = additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId);
|
||||||
if (fileOpt.isEmpty()) {
|
if (fileOpt.isEmpty()) {
|
||||||
return ResponseEntity.notFound().build();
|
return ResponseEntity.notFound().build();
|
||||||
@@ -115,7 +113,11 @@ public class AdditionalFileService {
|
|||||||
return downloadFolderAsZip(file, filePath);
|
return downloadFolderAsZip(file, filePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
Resource resource = new UrlResource(filePath.toUri());
|
StreamingResponseBody body = outputStream -> {
|
||||||
|
try (InputStream in = Files.newInputStream(filePath)) {
|
||||||
|
in.transferTo(outputStream);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
|
String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
String fallbackFilename = NON_ASCII.matcher(file.getFileName()).replaceAll("_");
|
String fallbackFilename = NON_ASCII.matcher(file.getFileName()).replaceAll("_");
|
||||||
@@ -124,29 +126,24 @@ public class AdditionalFileService {
|
|||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||||
.body(resource);
|
.body(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ResponseEntity<Resource> downloadFolderAsZip(BookFileEntity file, Path folderPath) throws IOException {
|
private ResponseEntity<StreamingResponseBody> downloadFolderAsZip(BookFileEntity file, Path folderPath) {
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
StreamingResponseBody body = outputStream -> {
|
||||||
|
try (ZipOutputStream zos = new ZipOutputStream(outputStream);
|
||||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
var files = Files.list(folderPath)) {
|
||||||
// Get all files in the folder, sorted by name
|
// Get all files in the folder, sorted by name
|
||||||
try (var files = Files.list(folderPath)) {
|
|
||||||
for (Path audioFile : files
|
for (Path audioFile : files
|
||||||
.filter(Files::isRegularFile)
|
.filter(Files::isRegularFile)
|
||||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||||
.toList()) {
|
.toList()) {
|
||||||
ZipEntry entry = new ZipEntry(audioFile.getFileName().toString());
|
zos.putNextEntry(new ZipEntry(audioFile.getFileName().toString()));
|
||||||
zos.putNextEntry(entry);
|
|
||||||
Files.copy(audioFile, zos);
|
Files.copy(audioFile, zos);
|
||||||
zos.closeEntry();
|
zos.closeEntry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
byte[] zipBytes = baos.toByteArray();
|
|
||||||
Resource resource = new ByteArrayResource(zipBytes);
|
|
||||||
|
|
||||||
String zipFileName = file.getFileName() + ".zip";
|
String zipFileName = file.getFileName() + ".zip";
|
||||||
String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20");
|
String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
@@ -157,8 +154,7 @@ public class AdditionalFileService {
|
|||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.valueOf("application/zip"))
|
.contentType(MediaType.valueOf("application/zip"))
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||||
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length))
|
.body(body);
|
||||||
.body(resource);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateAdditionalFile(BookFileEntity file, BookEntity book) {
|
private void validateAdditionalFile(BookFileEntity file, BookEntity book) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import org.mockito.InjectMocks;
|
|||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.MockedStatic;
|
import org.mockito.MockedStatic;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
@@ -231,7 +231,7 @@ class AdditionalFileServiceTest {
|
|||||||
Long fileId = 1L;
|
Long fileId = 1L;
|
||||||
when(additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId)).thenReturn(Optional.empty());
|
when(additionalFileRepository.findByIdAndBookIdWithBookAndLibraryPath(fileId, bookId)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
ResponseEntity<StreamingResponseBody> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
||||||
|
|
||||||
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
|
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
|
||||||
assertNull(result.getBody());
|
assertNull(result.getBody());
|
||||||
@@ -257,7 +257,7 @@ class AdditionalFileServiceTest {
|
|||||||
Path actualPath = entityWithNonExistentFile.getFullFilePath();
|
Path actualPath = entityWithNonExistentFile.getFullFilePath();
|
||||||
filesMock.when(() -> Files.exists(actualPath)).thenReturn(false);
|
filesMock.when(() -> Files.exists(actualPath)).thenReturn(false);
|
||||||
|
|
||||||
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
ResponseEntity<StreamingResponseBody> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
||||||
|
|
||||||
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
|
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
|
||||||
assertNull(result.getBody());
|
assertNull(result.getBody());
|
||||||
@@ -277,7 +277,7 @@ class AdditionalFileServiceTest {
|
|||||||
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
try (MockedStatic<Files> filesMock = mockStatic(Files.class)) {
|
||||||
filesMock.when(() -> Files.exists(fileEntity.getFullFilePath())).thenReturn(true);
|
filesMock.when(() -> Files.exists(fileEntity.getFullFilePath())).thenReturn(true);
|
||||||
|
|
||||||
ResponseEntity<Resource> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
ResponseEntity<StreamingResponseBody> result = additionalFileService.downloadAdditionalFile(bookId, fileId);
|
||||||
|
|
||||||
assertEquals(HttpStatus.OK, result.getStatusCode());
|
assertEquals(HttpStatus.OK, result.getStatusCode());
|
||||||
assertNotNull(result.getBody());
|
assertNotNull(result.getBody());
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
|||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.core.io.ClassPathResource;
|
import org.springframework.core.io.ClassPathResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||||
import org.springframework.core.io.UrlResource;
|
import org.springframework.core.io.UrlResource;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -323,10 +324,10 @@ class BookServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void downloadBook_delegatesToDownloadService() {
|
void downloadBook_delegatesToDownloadService() {
|
||||||
ResponseEntity<Resource> response = ResponseEntity.ok(mock(Resource.class));
|
ResponseEntity<StreamingResponseBody> response = ResponseEntity.ok(mock(StreamingResponseBody.class));
|
||||||
when(bookDownloadService.downloadBook(1L)).thenReturn(response);
|
when(bookDownloadService.downloadBook(1L)).thenReturn(response);
|
||||||
|
|
||||||
ResponseEntity<Resource> result = bookService.downloadBook(1L);
|
ResponseEntity<StreamingResponseBody> result = bookService.downloadBook(1L);
|
||||||
|
|
||||||
assertEquals(response, result);
|
assertEquals(response, result);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user