diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java index ab2d44260..bdc994606 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java @@ -41,8 +41,7 @@ public class LibraryController { }) @GetMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity getLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity getLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { return ResponseEntity.ok(libraryService.getLibrary(libraryId)); } @@ -50,8 +49,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Library created successfully") @PostMapping @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity createLibrary( - @Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { + public ResponseEntity createLibrary(@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { return ResponseEntity.ok(libraryService.createLibrary(request)); } @@ -71,8 +69,7 @@ public class LibraryController { @DeleteMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity deleteLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity deleteLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { libraryService.deleteLibrary(libraryId); return ResponseEntity.noContent().build(); } @@ -91,8 +88,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Books returned successfully") @GetMapping("/{libraryId}/book") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity> getBooks( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) { List books = libraryService.getBooks(libraryId); return ResponseEntity.ok(books); } @@ -119,4 +115,15 @@ public class LibraryController { Library updated = libraryService.setFileNamingPattern(libraryId, pattern); return ResponseEntity.ok(updated); } + + @Operation(summary = "Scan library paths", description = "Scan the provided library paths and return a count of processable files. Requires admin or manipulation permission.") + @ApiResponse(responseCode = "200", description = "Processable files count returned successfully") + @PostMapping("/scan") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity scanLibraryPaths( + @Parameter(description = "Library creation request with paths to scan") + @Validated @RequestBody CreateLibraryRequest request) { + int processableFilesCount = libraryService.scanLibraryPaths(request); + return ResponseEntity.ok(processableFilesCount); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java index 21a9c9a2e..b19b6749e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/BookFileType.java @@ -1,5 +1,33 @@ package com.adityachandel.booklore.model.enums; +import lombok.Getter; + +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; + +@Getter public enum BookFileType { - PDF, EPUB, CBX, FB2 + + PDF(Set.of("pdf")), + EPUB(Set.of("epub")), + CBX(Set.of("cbz", "cbr", "cb7")), + FB2(Set.of("fb2")); + + private final Set extensions; + + BookFileType(Set extensions) { + this.extensions = extensions; + } + + public boolean supports(String extension) { + return extensions.contains(extension.toLowerCase()); + } + + public static Optional fromExtension(String extension) { + String ext = extension.toLowerCase(); + return Arrays.stream(values()) + .filter(type -> type.supports(ext)) + .findFirst(); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 2f4b6f9ac..75ac24c27 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -42,7 +42,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]"); private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(".*\\.(jpg|jpeg|png|webp)"); private static final Pattern IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|webp)"); - private static final Pattern CBX_FILE_EXTENSION_PATTERN = Pattern.compile("(?i)\\.cb[rz7]$"); private final CbxMetadataExtractor cbxMetadataExtractor; public CbxProcessor(BookRepository bookRepository, @@ -99,17 +98,20 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce } private Optional extractImagesFromArchive(File file) { - String name = file.getName().toLowerCase(); - if (name.endsWith(".cbz")) { - return extractFirstImageFromZip(file); - } else if (name.endsWith(".cb7")) { - return extractFirstImageFrom7z(file); - } else if (name.endsWith(".cbr")) { - return extractFirstImageFromRar(file); - } else { + String name = file.getName(); + String extension = FileUtils.getExtension(name).toLowerCase(); + + if (!BookFileType.CBX.supports(extension)) { log.warn("Unsupported CBX format: {}", name); return Optional.empty(); } + + return switch (extension) { + case "cbz" -> extractFirstImageFromZip(file); + case "cb7" -> extractFirstImageFrom7z(file); + case "cbr" -> extractFirstImageFromRar(file); + default -> Optional.empty(); + }; } private Optional extractFirstImageFromZip(File file) { @@ -242,8 +244,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private void setMetadata(BookEntity bookEntity) { String baseName = new File(bookEntity.getFileName()).getName(); - String title = UNDERSCORE_HYPHEN_PATTERN.matcher(CBX_FILE_EXTENSION_PATTERN.matcher(baseName).replaceAll("")).replaceAll(" ") - .trim(); + String extension = FileUtils.getExtension(baseName); + if (BookFileType.CBX.supports(extension)) { + baseName = baseName.substring(0, baseName.length() - extension.length() - 1); + } + String title = UNDERSCORE_HYPHEN_PATTERN.matcher(baseName).replaceAll(" ").trim(); bookEntity.getMetadata().setTitle(truncate(title, 1000)); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java index 3099c376b..0dad29efb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/library/LibraryService.java @@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.LibraryScanMode; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; @@ -33,9 +34,14 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; @Slf4j @@ -250,4 +256,51 @@ public class LibraryService { library.setFileNamingPattern(pattern); return libraryMapper.toLibrary(libraryRepository.save(library)); } -} \ No newline at end of file + + public int scanLibraryPaths(CreateLibraryRequest request) { + int count = 0; + if (request.getPaths() == null || request.getPaths().isEmpty()) { + return count; + } + for (LibraryPath libraryPath : request.getPaths()) { + Path path = Paths.get(libraryPath.getPath()); + if (!Files.exists(path)) { + log.warn("Path does not exist: {}", path); + continue; + } + if (Files.isDirectory(path)) { + count += scanDirectory(path); + } else if (Files.isRegularFile(path) && isProcessableFile(path)) { + count++; + } + } + return count; + } + + private int scanDirectory(Path directory) { + int count = 0; + try (DirectoryStream stream = Files.newDirectoryStream(directory)) { + for (Path entry : stream) { + if (Files.isDirectory(entry)) { + count += scanDirectory(entry); + } else if (Files.isRegularFile(entry) && isProcessableFile(entry)) { + count++; + } + } + } catch (IOException e) { + log.error("Error scanning directory: {}", directory, e); + } + return count; + } + + private boolean isProcessableFile(Path file) { + String fileName = file.getFileName().toString().toLowerCase(); + for (BookFileType fileType : BookFileType.values()) { + if (fileName.endsWith("." + fileType.name().toLowerCase())) { + return true; + } + } + return false; + } +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java index 7cfb37ee0..eebb54bc2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileUtils.java @@ -63,6 +63,17 @@ public class FileUtils { } } + public String getExtension(String fileName) { + if (fileName == null) { + return ""; + } + int i = fileName.lastIndexOf('.'); + if (i >= 0 && i < fileName.length() - 1) { + return fileName.substring(i + 1); + } + return ""; + } + private List systemDirs = Arrays.asList( // synology "#recycle", diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index bfb4c60d4..32871b47e 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -13,7 +13,10 @@ import {MetadataProgressService} from './shared/service/metadata-progress.servic import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; import {Subscription} from 'rxjs'; import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component'; -import {TaskService, TaskProgressPayload} from './features/settings/task-management/task.service'; +import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service'; +import {LibraryService} from './features/book/service/library.service'; +import {LibraryLoadingService} from './features/library-creator/library-loading.service'; +import {scan, withLatestFrom} from 'rxjs/operators'; @Component({ selector: 'app-root', @@ -26,7 +29,9 @@ export class AppComponent implements OnInit, OnDestroy { loading = true; private subscriptions: Subscription[] = []; - private subscriptionsInitialized = false; // Prevent multiple subscription setups + private subscriptionsInitialized = false; + + private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup private authInit = inject(AuthInitializationService); private bookService = inject(BookService); private rxStompService = inject(RxStompService); @@ -34,7 +39,8 @@ export class AppComponent implements OnInit, OnDestroy { private metadataProgressService = inject(MetadataProgressService); private bookdropFileService = inject(BookdropFileService); private taskService = inject(TaskService); - private appConfigService = inject(AppConfigService); // Keep it here to ensure the service is initialized + private libraryService = inject(LibraryService); + private libraryLoadingService = inject(LibraryLoadingService); ngOnInit(): void { this.authInit.initialized$.subscribe(ready => { @@ -48,9 +54,25 @@ export class AppComponent implements OnInit, OnDestroy { private setupWebSocketSubscriptions(): void { this.subscriptions.push( - this.rxStompService.watch('/user/queue/book-add').subscribe(msg => - this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body)) - ) + this.rxStompService.watch('/user/queue/book-add').pipe( + withLatestFrom(this.libraryService.largeLibraryLoading$), + scan((acc, [msg, loadingState]) => { + const book = JSON.parse(msg.body); + if (loadingState.isLoading) { + const newCount = acc.count + 1; + this.libraryLoadingService.showBookLoadingProgress(book.metadata?.title || 'Unknown Book', newCount, loadingState.expectedCount); + this.bookService.handleNewlyCreatedBook(book); + if (newCount >= loadingState.expectedCount) { + this.libraryService.setLargeLibraryLoading(false, 0); + return {count: 0}; + } + return {count: newCount}; + } else { + this.bookService.handleNewlyCreatedBook(book); + return {count: 0}; + } + }, {count: 0}) + ).subscribe() ); this.subscriptions.push( this.rxStompService.watch('/user/queue/book-update').subscribe(msg => @@ -104,5 +126,6 @@ export class AppComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.subscriptions.forEach(sub => sub.unsubscribe()); + this.libraryLoadingService.hide(); } } diff --git a/booklore-ui/src/app/features/book/service/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index 55e03da89..679b37f45 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -22,6 +22,13 @@ export class LibraryService { error: null, }); + private largeLibraryLoadingSubject = new BehaviorSubject<{ isLoading: boolean; expectedCount: number }>({ + isLoading: false, + expectedCount: 0 + }); + + largeLibraryLoading$ = this.largeLibraryLoadingSubject.asObservable(); + private loading$: Observable | null = null; constructor() { @@ -72,6 +79,10 @@ export class LibraryService { ); } + scanLibraryPaths(lib: Library): Observable { + return this.http.post(`${this.url}/scan`, lib); + } + createLibrary(lib: Library): Observable { return this.http.post(this.url, lib).pipe( map(created => { @@ -150,4 +161,8 @@ export class LibraryService { map(state => (state.books || []).filter(b => b.libraryId === libraryId).length) ); } + + setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void { + this.largeLibraryLoadingSubject.next({ isLoading, expectedCount }); + } } diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index 46d240ffa..b260b3f5a 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -15,6 +15,8 @@ import {Select} from 'primeng/select'; import {Button} from 'primeng/button'; import {IconDisplayComponent} from '../../shared/components/icon-display/icon-display.component'; import {DialogLauncherService} from '../../shared/services/dialog-launcher.service'; +import {switchMap} from 'rxjs/operators'; +import {map, of} from 'rxjs'; @Component({ selector: 'app-library-creator', @@ -147,16 +149,17 @@ export class LibraryCreatorComponent implements OnInit { const iconValue = this.selectedIcon?.value || 'heart'; const iconType = this.selectedIcon?.type || 'PRIME_NG'; + const library: Library = { + name: this.chosenLibraryName, + icon: iconValue, + iconType: iconType, + paths: this.folders.map(folder => ({path: folder})), + watch: this.watch, + scanMode: this.scanMode, + defaultBookFormat: this.defaultBookFormat + }; + if (this.mode === 'edit') { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; this.libraryService.updateLibrary(library, this.library?.id).subscribe({ next: () => { this.messageService.add({severity: 'success', summary: 'Library Updated', detail: 'The library was updated successfully.'}); @@ -168,22 +171,36 @@ export class LibraryCreatorComponent implements OnInit { } }); } else { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; - this.libraryService.createLibrary(library).subscribe({ - next: (createdLibrary) => { - this.router.navigate(['/library', createdLibrary.id, 'books']); - this.messageService.add({severity: 'success', summary: 'Library Created', detail: 'The library was created successfully.'}); - this.dynamicDialogRef.close(); + this.libraryService.scanLibraryPaths(library).pipe( + switchMap(count => { + if (count < 500) { + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } else { + console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`); + this.libraryService.setLargeLibraryLoading(true, count); + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } + }) + ).subscribe({ + next: ({ createdLibrary, count }) => { + if (createdLibrary) { + this.router.navigate(['/library', createdLibrary.id, 'books']); + this.messageService.add({ + severity: 'success', + summary: 'Library Created', + detail: count >= 500 + ? `Library created with ${count} files. Loading in progress...` + : 'The library was created successfully.' + }); + this.dynamicDialogRef.close(); + } }, error: (e) => { + this.libraryService.setLargeLibraryLoading(false, 0); this.messageService.add({severity: 'error', summary: 'Creation Failed', detail: 'An error occurred while creating the library. Please try again.'}); console.error(e); } diff --git a/booklore-ui/src/app/features/library-creator/library-loading.service.ts b/booklore-ui/src/app/features/library-creator/library-loading.service.ts new file mode 100644 index 000000000..765a11170 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading.service.ts @@ -0,0 +1,47 @@ +import { Injectable, ComponentRef, ApplicationRef, createComponent, EnvironmentInjector } from '@angular/core'; +import { LibraryLoadingComponent } from './library-loading/library-loading.component'; + +@Injectable({ + providedIn: 'root' +}) +export class LibraryLoadingService { + private componentRef: ComponentRef | null = null; + + constructor( + private appRef: ApplicationRef, + private injector: EnvironmentInjector + ) {} + + showBookLoadingProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.updateProgress(bookTitle, current, total); + return; + } + + this.componentRef = createComponent(LibraryLoadingComponent, { + environmentInjector: this.injector + }); + + this.componentRef.instance.updateProgress(bookTitle, current, total); + + this.appRef.attachView(this.componentRef.hostView); + const domElem = (this.componentRef.hostView as any).rootNodes[0] as HTMLElement; + document.body.appendChild(domElem); + document.body.style.overflow = 'hidden'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.componentRef.instance.updateProgress(bookTitle, current, total); + } + } + + hide(): void { + if (this.componentRef) { + this.appRef.detachView(this.componentRef.hostView); + this.componentRef.destroy(); + this.componentRef = null; + document.body.style.overflow = ''; + } + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html new file mode 100644 index 000000000..1f552bf46 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html @@ -0,0 +1,50 @@ +
+
+
+ +

Loading Library

+
+ +
+
+ @if (!isComplete) { + + Processing: {{ truncatedTitle }} + + } + @if (isComplete) { + + + Library Loading Complete! + + } +
+ +
+ {{ current }} / {{ total }} + {{ percentage }}% +
+ +
+
+
+ + @if (!isComplete) { +
+
+
+
+
+ } +
+ + @if (isComplete) { + + } +
+
diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss new file mode 100644 index 000000000..e70294568 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss @@ -0,0 +1,151 @@ +.fullscreen-loader { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.85); + backdrop-filter: blur(8px); + display: flex; + justify-content: center; + align-items: center; + z-index: 9999; +} + +.library-loader-content { + background: var(--card-background); + padding: 2.5rem; + border-radius: 12px; + width: 550px; + max-width: 90vw; + box-sizing: border-box; + border: 1px solid var(--border-color); +} + +.library-loader-header { + text-align: center; + + i { + font-size: 3rem; + color: var(--primary-color); + margin-bottom: 1rem; + } + + h2 { + margin: 0 0 0.5rem 0; + color: var(--text-color); + font-size: 1.5rem; + } +} + +.library-loader-body { + .book-title { + color: var(--text-color-secondary); + margin-bottom: 1.5rem; + margin-top: 2.5rem; + font-size: 0.95rem; + word-break: break-word; + overflow-wrap: break-word; + line-height: 1.4; + display: flex; + align-items: flex-start; + + strong { + color: var(--text-color); + } + + .complete-message { + color: var(--primary-color); + font-size: 1.1rem; + + i { + margin-right: 0.5rem; + } + } + } + + .progress-info { + display: flex; + justify-content: space-between; + margin-bottom: 0.5rem; + color: var(--text-color-secondary); + font-size: 0.9rem; + } + + .progress-bar-container { + width: 100%; + height: 8px; + background: var(--card-background); + border-radius: 4px; + overflow: hidden; + + .progress-bar-fill { + height: 100%; + background: var(--primary-color); + transition: width 0.3s ease; + } + } + + .loader-animation { + margin-top: 1.5rem; + display: flex; + justify-content: center; + gap: 0.5rem; + + .dot { + width: 8px; + height: 8px; + background: var(--primary-color); + border-radius: 50%; + animation: bounce 1.4s infinite ease-in-out both; + + &:nth-child(2) { + animation-delay: 0.2s; + } + + &:nth-child(3) { + animation-delay: 0.4s; + } + } + } +} + +.library-loader-footer { + margin-top: 3rem; + text-align: center; + + .reload-button { + padding: 0.75rem 1.25rem; + background: var(--primary-color); + color: white; + border: none; + border-radius: 6px; + font-size: 1rem; + cursor: pointer; + transition: all 0.3s ease; + font-weight: 700; + + i { + margin-right: 0.5rem; + } + + &:hover { + background: var(--primary-hover-color); + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); + } + + &:active { + transform: translateY(0); + } + } +} + +@keyframes bounce { + 0%, 80%, 100% { + transform: scale(0); + } + 40% { + transform: scale(1); + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts new file mode 100644 index 000000000..fcaf5fb62 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts @@ -0,0 +1,39 @@ +import { Component } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-library-loading', + standalone: true, + imports: [CommonModule], + templateUrl: './library-loading.component.html', + styleUrl: './library-loading.component.scss' +}) +export class LibraryLoadingComponent { + bookTitle = ''; + current = 0; + total = 0; + isComplete = false; + + get percentage(): number { + return this.total > 0 ? Math.round((this.current / this.total) * 100) : 0; + } + + get truncatedTitle(): string { + const maxLength = 50; + return this.bookTitle.length <= maxLength + ? this.bookTitle + : this.bookTitle.substring(0, maxLength) + '...'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + this.bookTitle = bookTitle; + this.current = current; + this.total = total; + this.isComplete = current >= total; + } + + onReload(): void { + window.location.reload(); + } +} + diff --git a/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html b/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html index 5ee941490..2acf4b9a6 100644 --- a/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html +++ b/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html @@ -91,7 +91,7 @@ -
+
@for (folder of filteredPaths; track folder) {
{ - this.paths = folders; - this.filteredPaths = folders; - this.isLoading = false; - this.updateBreadcrumb(path); - folders.forEach(folder => { - this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder); - }); + setTimeout(() => { + this.paths = folders; + this.filteredPaths = folders; + this.isLoading = false; + this.updateBreadcrumb(path); + folders.forEach(folder => { + this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder); + }); + }, 100); }, error: (error) => { console.error('Error fetching folders:', error); @@ -104,21 +107,6 @@ export class DirectoryPickerComponent implements OnInit { this.searchQuery = ''; } - toggleFolderSelection(path: string, event?: Event): void { - if (event) { - event.stopPropagation(); - } - - const index = this.selectedFolders.indexOf(path); - if (index > -1) { - this.selectedFolders.splice(index, 1); - this.selectedFoldersMap[path] = false; - } else { - this.selectedFolders.push(path); - this.selectedFoldersMap[path] = true; - } - } - onCheckboxChange(path: string, checked: boolean): void { const index = this.selectedFolders.indexOf(path); if (checked && index === -1) { diff --git a/booklore-ui/src/app/shared/service/file-download.service.spec.ts b/booklore-ui/src/app/shared/service/file-download.service.spec.ts index dfc8a25e4..baeaea561 100644 --- a/booklore-ui/src/app/shared/service/file-download.service.spec.ts +++ b/booklore-ui/src/app/shared/service/file-download.service.spec.ts @@ -2,7 +2,7 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {TestBed} from '@angular/core/testing'; import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http'; -import {of, Subject, throwError} from 'rxjs'; +import {of, Subject} from 'rxjs'; import {FileDownloadService} from './file-download.service'; import {DownloadProgressService} from './download-progress.service'; import {MessageService} from 'primeng/api'; @@ -75,7 +75,7 @@ describe('FileDownloadService', () => { } }; - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'})); expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject)); expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100); @@ -97,26 +97,6 @@ describe('FileDownloadService', () => { expect(filename).toBe('default.txt'); }); - it('should handle download error and show error message', () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - service.downloadFile('/api/file', 'file.txt').subscribe({ - error: () => { - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); - } - }); - }); - - it('should not show error message for AbortError', () => { - httpClientMock.get.mockReturnValue(throwError(() => ({name: 'AbortError'}))); - service.downloadFile('/api/file', 'file.txt').subscribe({ - error: () => { - expect(messageServiceMock.add).not.toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); - } - }); - }); - it('should throw if no file content received', () => { const response = new HttpResponse({body: undefined, headers: new HttpHeaders()}); expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received'); @@ -194,20 +174,20 @@ describe('FileDownloadService - API Contract Tests', () => { describe('Behavior contract', () => { it('should call startDownload and updateProgress on DownloadProgressService', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled(); expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20); }); it('should call completeDownload on finalize', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); }); it('should show success message on download complete', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); }); }); diff --git a/booklore-ui/src/app/shared/service/file-download.service.ts b/booklore-ui/src/app/shared/service/file-download.service.ts index 96be67a83..75206846a 100644 --- a/booklore-ui/src/app/shared/service/file-download.service.ts +++ b/booklore-ui/src/app/shared/service/file-download.service.ts @@ -1,4 +1,4 @@ -import {Injectable, inject} from '@angular/core'; +import {inject, Injectable} from '@angular/core'; import {HttpClient, HttpEvent, HttpEventType, HttpResponse} from '@angular/common/http'; import {MessageService} from 'primeng/api'; import {DownloadProgressService} from './download-progress.service'; @@ -13,10 +13,10 @@ export class FileDownloadService { private downloadProgressService = inject(DownloadProgressService); private messageService = inject(MessageService); - downloadFile(url: string, defaultFilename: string): Observable { + downloadFile(url: string, defaultFilename: string): void { const cancelSubject = new Subject(); - return this.initiateDownload(url) + this.initiateDownload(url) .pipe( takeUntil(cancelSubject), tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)), @@ -25,7 +25,8 @@ export class FileDownloadService { this.handleDownloadError(error); return throwError(() => error); }) - ); + ) + .subscribe(); } private initiateDownload(url: string): Observable> {