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 ef0e0096f..e4fd54f95 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 @@ -19,8 +19,6 @@ import jakarta.validation.constraints.Min; import lombok.AllArgsConstructor; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java index 54cea4fd1..7b4d33a6d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookDownloadService.java @@ -11,8 +11,8 @@ import com.adityachandel.booklore.util.FileUtils; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.InputStreamResource; 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; @@ -20,6 +20,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; import java.io.File; +import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; @@ -41,11 +42,22 @@ public class BookDownloadService { .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize(); - Resource resource = new UrlResource(file.toUri()); + File bookFile = file.toFile(); + + if (!bookFile.exists()) { + throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId); + } + + InputStream inputStream = new FileInputStream(bookFile); + InputStreamResource resource = new InputStreamResource(inputStream); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) + .contentLength(bookFile.length()) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"") + .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate") + .header(HttpHeaders.PRAGMA, "no-cache") + .header(HttpHeaders.EXPIRES, "0") .body(resource); } catch (Exception e) { log.error("Failed to download book {}: {}", bookId, e.getMessage(), e); diff --git a/booklore-ui/src/app/app.component.html b/booklore-ui/src/app/app.component.html index 4a654f4bb..6f0f0d716 100644 --- a/booklore-ui/src/app/app.component.html +++ b/booklore-ui/src/app/app.component.html @@ -10,5 +10,6 @@ } @else { + } diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index 1f274aefb..3c6a4b9c3 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -14,13 +14,14 @@ import {BookdropFileNotification, BookdropFileService} from './bookdrop/bookdrop import {DuplicateFileNotification} from './shared/websocket/model/duplicate-file-notification.model'; import {DuplicateFileService} from './shared/websocket/duplicate-file.service'; import {Subscription} from 'rxjs'; +import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrl: './app.component.scss', standalone: true, - imports: [ConfirmDialog, Toast, RouterOutlet] + imports: [ConfirmDialog, Toast, RouterOutlet, DownloadProgressDialogComponent] }) export class AppComponent implements OnInit, OnDestroy { diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts index 22f755ca4..f7a8c5b65 100644 --- a/booklore-ui/src/app/book/service/book.service.ts +++ b/booklore-ui/src/app/book/service/book.service.ts @@ -10,6 +10,7 @@ import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refr import {MessageService} from 'primeng/api'; import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type'; import {AuthService} from '../../core/service/auth.service'; +import {FileDownloadService} from '../../shared/service/file-download.service'; @Injectable({ providedIn: 'root', @@ -21,6 +22,7 @@ export class BookService { private http = inject(HttpClient); private messageService = inject(MessageService); private authService = inject(AuthService); + private fileDownloadService = inject(FileDownloadService); private bookStateSubject = new BehaviorSubject({ books: null, @@ -355,43 +357,12 @@ export class BookService { 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), - }); + this.fileDownloadService.downloadFile(downloadUrl, `book_${bookId}`); } downloadAdditionalFile(bookId: number, fileId: number): void { const downloadUrl = `${this.url}/${bookId}/files/${fileId}/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] || `additional_file_${fileId}` - : `additional_file_${fileId}`; - this.saveFile(response.body as Blob, filename); - }, - error: (err) => console.error('Error downloading additional 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); + this.fileDownloadService.downloadFile(downloadUrl, `additional_file_${fileId}`); } savePdfProgress(bookId: number, page: number, percentage: number): Observable { @@ -510,8 +481,8 @@ export class BookService { ); } - getComicInfoMetadata(bookId: number): Observable { - return this.http.get(`${this.url}/${bookId}/cbx/metadata/comicinfo`); + getComicInfoMetadata(bookId: number): Observable { + return this.http.get(`${this.url}/${bookId}/cbx/metadata/comicinfo`); } autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable { diff --git a/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.html b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.html new file mode 100644 index 000000000..473745e16 --- /dev/null +++ b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.html @@ -0,0 +1,33 @@ + + + + {{ currentProgress.filename }} + + + + + {{ currentProgress.progress }}% + + + + + {{ formatBytes(currentProgress.loaded) }} / {{ formatBytes(currentProgress.total) }} + + + + + + + + diff --git a/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.scss b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.scss new file mode 100644 index 000000000..c9ab21c20 --- /dev/null +++ b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.scss @@ -0,0 +1,53 @@ +.download-content { + padding: 1rem 0; +} + +.filename { + font-weight: 600; + margin-bottom: 1rem; + word-break: break-word; +} + +.progress-bar-container { + margin: 1rem 0; +} + +.progress-bar-background { + width: 100%; + height: 1rem; + background-color: var(--p-surface-400); + border-radius: var(--border-radius, 4px); + overflow: hidden; + position: relative; +} + +.progress-bar-fill { + height: 100%; + background: linear-gradient(90deg, var(--p-primary-500), var(--p-primary-800)); + transition: width 0.3s ease-out; + will-change: width; + border-radius: var(--border-radius, 6px); + position: absolute; + top: 0; + left: 0; +} + +.progress-bar-label { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + font-weight: 600; + font-size: 0.875rem; + color: var(--p-text-color); + z-index: 1; + text-shadow: 0 0 2px rgba(255, 255, 255, 0.8); +} + +.download-info { + display: flex; + justify-content: space-between; + margin-top: 0.5rem; + font-size: 0.875rem; + color: var(--p-text-color); +} diff --git a/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.ts b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.ts new file mode 100644 index 000000000..2a51026b0 --- /dev/null +++ b/booklore-ui/src/app/shared/components/download-progress-dialog/download-progress-dialog.component.ts @@ -0,0 +1,51 @@ +import {Component, inject, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {DialogModule} from 'primeng/dialog'; +import {ButtonModule} from 'primeng/button'; +import {Subscription} from 'rxjs'; +import {DownloadProgress, DownloadProgressService} from '../../service/download-progress.service'; + +@Component({ + selector: 'app-download-progress-dialog', + standalone: true, + imports: [CommonModule, DialogModule, ButtonModule], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './download-progress-dialog.component.html', + styleUrl: './download-progress-dialog.component.scss' +}) +export class DownloadProgressDialogComponent implements OnDestroy { + private downloadProgressService = inject(DownloadProgressService); + private cdr = inject(ChangeDetectorRef); + private subscription: Subscription; + + currentProgress: DownloadProgress = { + visible: false, + filename: '', + progress: 0, + loaded: 0, + total: 0 + }; + + constructor() { + this.subscription = this.downloadProgressService.downloadProgress$.subscribe(progress => { + this.currentProgress = progress; + this.cdr.markForCheck(); + }); + } + + ngOnDestroy(): void { + this.subscription.unsubscribe(); + } + + cancelDownload(): void { + this.downloadProgressService.cancelDownload(); + } + + formatBytes(bytes: number): string { + if (bytes === 0) return '0 Bytes'; + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]; + } +} diff --git a/booklore-ui/src/app/shared/service/download-progress.service.ts b/booklore-ui/src/app/shared/service/download-progress.service.ts new file mode 100644 index 000000000..90478c680 --- /dev/null +++ b/booklore-ui/src/app/shared/service/download-progress.service.ts @@ -0,0 +1,127 @@ +import {Injectable} from '@angular/core'; +import {BehaviorSubject, Subject} from 'rxjs'; + +export interface DownloadProgress { + visible: boolean; + filename: string; + progress: number; + loaded: number; + total: number; + cancelSubject?: Subject; +} + +@Injectable({ + providedIn: 'root' +}) +export class DownloadProgressService { + private downloadProgressSubject = new BehaviorSubject({ + visible: false, + filename: '', + progress: 0, + loaded: 0, + total: 0 + }); + + private lastUpdateTime = 0; + private updateThrottleMs = 100; + private pendingUpdate: DownloadProgress | null = null; + private throttleTimer: any = null; + + downloadProgress$ = this.downloadProgressSubject.asObservable(); + + isDownloadInProgress(): boolean { + return this.downloadProgressSubject.value.visible; + } + + startDownload(filename: string, cancelSubject: Subject): void { + this.lastUpdateTime = 0; + this.pendingUpdate = null; + if (this.throttleTimer) { + clearTimeout(this.throttleTimer); + this.throttleTimer = null; + } + + this.downloadProgressSubject.next({ + visible: true, + filename, + progress: 0, + loaded: 0, + total: 0, + cancelSubject + }); + } + + updateProgress(loaded: number, total: number): void { + const current = this.downloadProgressSubject.value; + const progress = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0; + const now = Date.now(); + + const newProgress: DownloadProgress = { + visible: current.visible, + filename: current.filename, + progress, + loaded, + total, + cancelSubject: current.cancelSubject + }; + + if (progress === 100) { + if (this.throttleTimer) { + clearTimeout(this.throttleTimer); + this.throttleTimer = null; + } + this.downloadProgressSubject.next(newProgress); + this.lastUpdateTime = now; + this.pendingUpdate = null; + return; + } + + if (now - this.lastUpdateTime >= this.updateThrottleMs) { + this.downloadProgressSubject.next(newProgress); + this.lastUpdateTime = now; + this.pendingUpdate = null; + + if (this.throttleTimer) { + clearTimeout(this.throttleTimer); + this.throttleTimer = null; + } + } else { + this.pendingUpdate = newProgress; + + if (!this.throttleTimer) { + const remainingTime = this.updateThrottleMs - (now - this.lastUpdateTime); + this.throttleTimer = setTimeout(() => { + if (this.pendingUpdate) { + this.downloadProgressSubject.next(this.pendingUpdate); + this.lastUpdateTime = Date.now(); + this.pendingUpdate = null; + } + this.throttleTimer = null; + }, remainingTime); + } + } + } + + completeDownload(): void { + if (this.throttleTimer) { + clearTimeout(this.throttleTimer); + this.throttleTimer = null; + } + this.pendingUpdate = null; + + this.downloadProgressSubject.next({ + visible: false, + filename: '', + progress: 0, + loaded: 0, + total: 0 + }); + } + + cancelDownload(): void { + const current = this.downloadProgressSubject.value; + current.cancelSubject?.next(); + current.cancelSubject?.complete(); + this.completeDownload(); + } +} diff --git a/booklore-ui/src/app/shared/service/file-download.service.ts b/booklore-ui/src/app/shared/service/file-download.service.ts new file mode 100644 index 000000000..f116c7e69 --- /dev/null +++ b/booklore-ui/src/app/shared/service/file-download.service.ts @@ -0,0 +1,119 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient, HttpEvent, HttpEventType, HttpResponse} from '@angular/common/http'; +import {MessageService} from 'primeng/api'; +import {DownloadProgressService} from './download-progress.service'; +import {Observable, Subject, throwError} from 'rxjs'; +import {catchError, finalize, takeUntil, tap} from 'rxjs/operators'; + +@Injectable({ + providedIn: 'root' +}) +export class FileDownloadService { + private http = inject(HttpClient); + private downloadProgressService = inject(DownloadProgressService); + private messageService = inject(MessageService); + + downloadFile(url: string, defaultFilename: string): void { + const cancelSubject = new Subject(); + + this.initiateDownload(url) + .pipe( + takeUntil(cancelSubject), + tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)), + finalize(() => this.downloadProgressService.completeDownload()), + catchError(error => { + this.handleDownloadError(error); + return throwError(() => error); + }) + ) + .subscribe(); + } + + private initiateDownload(url: string): Observable> { + return this.http.get(url, { + responseType: 'blob', + observe: 'events', + reportProgress: true + }); + } + + private handleDownloadProgress( + event: HttpEvent, + defaultFilename: string, + cancelSubject: Subject + ): void { + if (event.type === HttpEventType.Response) { + this.handleDownloadComplete(event, defaultFilename); + } else if (event.type === HttpEventType.DownloadProgress) { + this.updateProgress(event, defaultFilename, cancelSubject); + } + } + + private updateProgress( + event: any, + defaultFilename: string, + cancelSubject: Subject + ): void { + if (event.total) { + if (!this.downloadProgressService.isDownloadInProgress()) { + this.downloadProgressService.startDownload(defaultFilename, cancelSubject); + } + this.downloadProgressService.updateProgress(event.loaded, event.total); + } + } + + private handleDownloadComplete(response: HttpResponse, defaultFilename: string): void { + const filename = this.extractFilenameFromResponse(response, defaultFilename); + const blob = response.body; + + if (!blob) { + throw new Error('No file content received'); + } + + this.triggerBrowserDownload(blob, filename); + this.showSuccessMessage(filename); + } + + private extractFilenameFromResponse(response: HttpResponse, defaultFilename: string): string { + const contentDisposition = response.headers.get('Content-Disposition'); + return contentDisposition + ? contentDisposition.match(/filename="(.+?)"/)?.[1] || defaultFilename + : defaultFilename; + } + + private triggerBrowserDownload(blob: Blob, filename: string): void { + const objectUrl = window.URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = objectUrl; + link.download = filename; + link.style.display = 'none'; + + document.body.appendChild(link); + link.click(); + + setTimeout(() => { + document.body.removeChild(link); + window.URL.revokeObjectURL(objectUrl); + }, 100); + } + + private handleDownloadError(error: any): void { + if (error?.name !== 'AbortError') { + this.messageService.add({ + severity: 'error', + summary: 'Download Failed', + detail: 'An error occurred while downloading the file. Please try again.', + life: 5000 + }); + } + } + + private showSuccessMessage(filename: string): void { + this.messageService.add({ + severity: 'success', + summary: 'Download Complete', + detail: `${filename} has been downloaded successfully.`, + life: 3000 + }); + } +}