diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 417726cc9..4b1b91a82 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -32,6 +32,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-websocket' implementation 'org.springframework.boot:spring-boot-starter-quartz' + implementation 'org.springframework.boot:spring-boot-starter-actuator' // Lombok compileOnly 'org.projectlombok:lombok' diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/WebConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/WebConfig.java index af5c80084..4003889c3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/WebConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/WebConfig.java @@ -12,6 +12,7 @@ public class WebConfig implements WebMvcConfigurer { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("*") + .exposedHeaders("Content-Disposition") .allowedHeaders("*"); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java index bb4d88792..668168bcc 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java @@ -73,4 +73,9 @@ public class BookController { booksService.updateReadProgress(request); return ResponseEntity.noContent().build(); } + + @GetMapping("/{bookId}/download") + public ResponseEntity downloadFile(@PathVariable("bookId") Long bookId) { + return booksService.prepareFileForDownload(bookId); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java index afb641614..9e6a66656 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/ApiError.java @@ -22,7 +22,8 @@ public enum ApiError { SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"), ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."), METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"), - INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"),; + FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"), + INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"); private final HttpStatus status; private final String message; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java index 7f3ad2528..b4c09c3b0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BooksService.java @@ -20,14 +20,19 @@ import jakarta.validation.Valid; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.io.IOException; +import java.net.MalformedURLException; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.time.Instant; import java.util.List; import java.util.Set; @@ -145,4 +150,23 @@ public class BooksService { } bookRepository.save(book); } + + public ResponseEntity prepareFileForDownload(Long bookId) { + try { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + String filePath = bookEntity.getPath(); + Path file = Paths.get(filePath).toAbsolutePath().normalize(); + Resource resource = new UrlResource(file.toUri()); + String contentType = Files.probeContentType(file); + if (contentType == null) { + contentType = "application/octet-stream"; + } + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"") + .body(resource); + } catch (Exception e) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + } } \ No newline at end of file diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts index 31135cff1..a2a9e2f55 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts @@ -9,6 +9,7 @@ import {BookService} from '../../../service/book.service'; import {CheckboxModule} from 'primeng/checkbox'; import {FormsModule} from '@angular/forms'; import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service'; +import {FileService} from '../../../service/file.service'; @Component({ @@ -26,6 +27,7 @@ export class BookCardComponent implements OnInit { items: MenuItem[] | undefined; isHovered: boolean = false; + private fileService = inject(FileService); private bookService = inject(BookService); private dialogService = inject(DialogService); private metadataDialogService = inject(MetadataDialogService); @@ -66,6 +68,13 @@ export class BookCardComponent implements OnInit { icon: 'pi pi-info-circle', command: () => this.metadataDialogService.openBookDetailsDialog(this.book.id), }, + { + label: 'Download', + icon: 'pi pi-download', + command: () => { + this.fileService.downloadFile(this.book.id) + }, + }, ], }, ]; diff --git a/booklore-ui/src/app/book/service/file.service.ts b/booklore-ui/src/app/book/service/file.service.ts new file mode 100644 index 000000000..b92cc2a0b --- /dev/null +++ b/booklore-ui/src/app/book/service/file.service.ts @@ -0,0 +1,36 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient, HttpHeaders} from '@angular/common/http'; + +@Injectable({ + providedIn: 'root', +}) +export class FileService { + private readonly url = 'http://localhost:8080/v1/book'; + private readonly http = inject(HttpClient); + + downloadFile(bookId: number): void { + const downloadUrl = `${this.url}/${bookId}/download`; + this.http.get(downloadUrl, {responseType: 'blob', observe: 'response'}) + .subscribe({ + next: (response) => { + const contentDisposition = response.headers.get('Content-Disposition'); + const filename = contentDisposition + ? contentDisposition.match(/filename="(.+?)"/)?.[1] || `book_${bookId}.pdf` + : `book_${bookId}.pdf`; + this.saveFile(response.body as Blob, filename); + }, + error: (err) => console.error('Error downloading file:', err), + }); + } + + private saveFile(blob: Blob, filename: string): void { + const url = window.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + window.URL.revokeObjectURL(url); + } +} diff --git a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html index 40605c566..b8093d73c 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -15,7 +15,7 @@
- +
diff --git a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index d40973a1c..04470a728 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -9,6 +9,7 @@ import {FormsModule} from '@angular/forms'; import {Tag} from 'primeng/tag'; import {Editor} from 'primeng/editor'; import {Author, Book} from '../../../book/model/book.model'; +import {FileService} from '../../../book/service/file.service'; @Component({ selector: 'app-metadata-viewer', @@ -20,6 +21,7 @@ import {Author, Book} from '../../../book/model/book.model'; export class MetadataViewerComponent { private bookService = inject(BookService); + private fileService = inject(FileService); private metadataCenterService = inject(BookMetadataCenterService); metadata$: Observable = this.metadataCenterService.bookMetadata$; @@ -39,4 +41,8 @@ export class MetadataViewerComponent { getAuthorNames(authors: Author[]): string { return authors.map(author => author.name).join(', '); } + + download(bookId: number) { + this.fileService.downloadFile(bookId); + } }