Show a persistent loader while a large library is being created (#2200)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-07 18:10:53 -07:00
committed by GitHub
co-authored by acx10
parent 251fe65ec0
commit c17fe58f4c
17 changed files with 567 additions and 111 deletions
@@ -41,8 +41,7 @@ public class LibraryController {
})
@GetMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Library> getLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
public ResponseEntity<Library> 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<Library> createLibrary(
@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
public ResponseEntity<Library> 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<List<Book>> getBooks(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
public ResponseEntity<List<Book>> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
List<Book> 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<Integer> scanLibraryPaths(
@Parameter(description = "Library creation request with paths to scan")
@Validated @RequestBody CreateLibraryRequest request) {
int processableFilesCount = libraryService.scanLibraryPaths(request);
return ResponseEntity.ok(processableFilesCount);
}
}
@@ -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<String> extensions;
BookFileType(Set<String> extensions) {
this.extensions = extensions;
}
public boolean supports(String extension) {
return extensions.contains(extension.toLowerCase());
}
public static Optional<BookFileType> fromExtension(String extension) {
String ext = extension.toLowerCase();
return Arrays.stream(values())
.filter(type -> type.supports(ext))
.findFirst();
}
}
@@ -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<BufferedImage> 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<BufferedImage> 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));
}
}
}
@@ -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));
}
}
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<Path> 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;
}
}
@@ -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<String> systemDirs = Arrays.asList(
// synology
"#recycle",
+29 -6
View File
@@ -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();
}
}
@@ -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<Library[]> | null = null;
constructor() {
@@ -72,6 +79,10 @@ export class LibraryService {
);
}
scanLibraryPaths(lib: Library): Observable<number> {
return this.http.post<number>(`${this.url}/scan`, lib);
}
createLibrary(lib: Library): Observable<Library> {
return this.http.post<Library>(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 });
}
}
@@ -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);
}
@@ -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<LibraryLoadingComponent> | 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 = '';
}
}
}
@@ -0,0 +1,50 @@
<div class="fullscreen-loader">
<div class="library-loader-content">
<div class="library-loader-header">
<i class="pi pi-book"></i>
<h2>Loading Library</h2>
</div>
<div class="library-loader-body">
<div class="book-title">
@if (!isComplete) {
<ng-container>
Processing: <strong>{{ truncatedTitle }}</strong>
</ng-container>
}
@if (isComplete) {
<strong class="complete-message">
<i class="pi pi-check-circle"></i>
Library Loading Complete!
</strong>
}
</div>
<div class="progress-info">
<span>{{ current }} / {{ total }}</span>
<span>{{ percentage }}%</span>
</div>
<div class="progress-bar-container">
<div class="progress-bar-fill" [style.width.%]="percentage"></div>
</div>
@if (!isComplete) {
<div class="loader-animation">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
}
</div>
@if (isComplete) {
<div class="library-loader-footer">
<button class="reload-button" (click)="onReload()">
<i class="pi pi-bookmark"></i>
Open Library
</button>
</div>
}
</div>
</div>
@@ -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);
}
}
@@ -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();
}
}
@@ -91,7 +91,7 @@
</span>
</div>
<div class="directories-grid">
<div class="directories-grid" [class.fade-in]="!isLoading && filteredPaths.length > 0">
@for (folder of filteredPaths; track folder) {
<div
class="directory-item"
@@ -8,8 +8,8 @@
}
.directory-picker {
width: 650px;
max-width: 650px;
width: 700px;
max-width: 700px;
display: flex;
flex-direction: column;
@@ -206,8 +206,8 @@
border: 1px solid var(--border-color);
border-top: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
min-height: 350px;
max-height: 450px;
min-height: 500px;
max-height: 500px;
overflow: hidden;
@media (max-width: 480px) {
@@ -342,6 +342,16 @@
flex: 1;
padding-right: 0.25rem;
min-height: 0;
opacity: 1;
transition: opacity 0.3s ease-in-out;
&.loading {
opacity: 0;
}
&.fade-in {
animation: fadeInUp 0.4s ease-out;
}
&::-webkit-scrollbar {
width: 6px;
@@ -366,6 +376,17 @@
scrollbar-color: var(--border-color) var(--overlay-background);
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.directory-item {
display: flex;
align-items: center;
@@ -376,10 +397,18 @@
border-radius: 8px;
transition: all 0.3s ease;
cursor: pointer;
opacity: 0;
animation: fadeInItem 0.3s ease-out forwards;
@for $i from 1 through 20 {
&:nth-child(#{$i}) {
animation-delay: #{$i * 0.03}s;
}
}
&:hover {
border-color: var(--primary-color);
transform: translateX(3px);
transform: translateY(3px);
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
.directory-icon {
@@ -389,7 +418,7 @@
.navigate-icon {
opacity: 1;
transform: translateX(2px);
transform: translateY(2px);
}
}
@@ -498,6 +527,17 @@
}
}
@keyframes fadeInItem {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.dialog-footer {
display: flex;
justify-content: space-between;
@@ -28,7 +28,7 @@ import {Tooltip} from 'primeng/tooltip';
InputIcon,
IconField,
Tooltip
],
],
styleUrls: ['./directory-picker.component.scss']
})
export class DirectoryPickerComponent implements OnInit {
@@ -53,15 +53,18 @@ export class DirectoryPickerComponent implements OnInit {
getFolders(path: string): void {
this.isLoading = true;
this.filteredPaths = [];
this.utilityService.getFolders(path).subscribe({
next: (folders: string[]) => {
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) {
@@ -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'}));
});
});
@@ -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<any> {
downloadFile(url: string, defaultFilename: string): void {
const cancelSubject = new Subject<void>();
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<HttpEvent<Blob>> {