Improve Angular project structure and code organization (#1328)
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
<div class="p-fluid px-4 py-2 rounded-xl flex flex-col h-full">
|
||||
|
||||
<div class="px-4 mx-2 mb-4 py-3 rounded-lg border border-[var(--border-color)] transition-all">
|
||||
<p class="text-[var(--primary-color)] font-semibold mb-1">
|
||||
File Organization Preview
|
||||
</p>
|
||||
<div class="text-sm text-gray-300 space-y-3">
|
||||
<p>
|
||||
Your files will be automatically renamed, organized, and can be moved between libraries based on your preferences.
|
||||
Check the preview below to see how your files will look, select target libraries if needed, then click <span class="font-semibold text-green-400">Move Files</span> to organize them.
|
||||
</p>
|
||||
<p>
|
||||
<i class="pi pi-lightbulb text-blue-400 mr-1"></i>
|
||||
<span class="text-blue-300">Want to change how files are named? Go to <strong>Settings → File Naming Pattern</strong>. Each library can have its own naming pattern!</span>
|
||||
</p>
|
||||
<p class="text-yellow-500 font-medium flex items-center gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-yellow-400"></i>
|
||||
This will actually move and rename files on your computer across different library folders. Make sure you're happy with the preview first!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4 mb-4 px-2 items-center w-full">
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center justify-between cursor-pointer" (click)="togglePatternsCollapsed()">
|
||||
<p-button
|
||||
outlined
|
||||
[icon]="patternsCollapsed ? 'pi pi-chevron-right' : 'pi pi-chevron-down'"
|
||||
iconPos="right"
|
||||
size="small"
|
||||
severity="info"
|
||||
[label]="patternsCollapsed ? 'Show Naming Rules' : 'Hide Naming Rules'">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
@if (!patternsCollapsed) {
|
||||
<div class="space-y-2 mt-2">
|
||||
@for (pattern of libraryPatterns; track pattern.libraryId) {
|
||||
<div class="p-3 border border-zinc-700 rounded-lg bg-zinc-800">
|
||||
<div class="flex justify-between items-start">
|
||||
<div class="flex-1">
|
||||
<p class="text-xs text-gray-400 mb-1">Library: {{ pattern.libraryName }}</p>
|
||||
<code class="text-[var(--primary-color)] font-mono text-sm">{{ pattern.pattern || 'No pattern available' }}</code>
|
||||
<p class="text-xs text-gray-400 mt-1">Source: {{ pattern.source }}</p>
|
||||
</div>
|
||||
<span class="text-xs bg-blue-600 text-white px-2 py-1 rounded ml-2">{{ pattern.bookCount }} book{{ pattern.bookCount > 1 ? 's' : '' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4 mb-4 px-2 items-center">
|
||||
<div class="flex items-center gap-3">
|
||||
<label class="text-sm font-medium text-gray-300">Set all files to:</label>
|
||||
<p-select
|
||||
[options]="availableLibraries"
|
||||
[(ngModel)]="defaultTargetLibraryId"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
placeholder="Select default library"
|
||||
(onChange)="onDefaultLibraryChange()"
|
||||
class="min-w-[200px]"
|
||||
size="small"
|
||||
appendTo="body"
|
||||
></p-select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-grow overflow-y-auto">
|
||||
<p-table
|
||||
[value]="filePreviews"
|
||||
[responsiveLayout]="'scroll'"
|
||||
class="block min-w-full"
|
||||
>
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Current Path</th>
|
||||
<th>Target Library</th>
|
||||
<th></th>
|
||||
<th>New Path</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="body" let-preview let-i="rowIndex">
|
||||
<tr>
|
||||
<td class="text-center">{{ preview.bookId }}</td>
|
||||
<td class="w-auto">
|
||||
<p>
|
||||
<span class="text-gray-400 select-none">{{ preview.currentLibraryName }}/</span><span class="text-gray-200">{{ preview.relativeOriginalPath }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="w-auto">
|
||||
<p-select
|
||||
[options]="availableLibraries"
|
||||
[(ngModel)]="preview.targetLibraryId"
|
||||
optionLabel="name"
|
||||
optionValue="id"
|
||||
placeholder="Select Library"
|
||||
(onChange)="onLibraryChange(preview)"
|
||||
[disabled]="preview.isMoved"
|
||||
class="w-full"
|
||||
appendTo="body"
|
||||
size="small"
|
||||
></p-select>
|
||||
</td>
|
||||
<td class="w-auto text-[var(--primary-color)] text-center">→</td>
|
||||
<td class="w-auto">
|
||||
<p>
|
||||
<span class="text-gray-400 select-none">{{ preview.targetLibraryName }}/</span><span class="text-gray-200">{{ preview.relativeNewPath }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="w-auto text-center">
|
||||
@if (preview.isMoved) {
|
||||
<i class="pi pi-check-circle text-green-600"></i>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4 pt-4">
|
||||
@if (movedFileCount > 0) {
|
||||
<span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none">
|
||||
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
|
||||
<i
|
||||
class="pi pi-check-circle ml-2 text-green-500 animate-bounce"
|
||||
style="animation-duration: 1.5s;"
|
||||
aria-label="Success"
|
||||
role="img"
|
||||
></i>
|
||||
</span>
|
||||
}
|
||||
@if (movedFileCount === 0) {
|
||||
<p-button
|
||||
[label]="loading ? 'Moving...' : 'Move Files'"
|
||||
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-arrows-h'"
|
||||
severity="success"
|
||||
(click)="saveChanges()"
|
||||
[disabled]="loading || filePreviews.length === 0"
|
||||
></p-button>
|
||||
<p-button
|
||||
label="Cancel"
|
||||
icon="pi pi-times"
|
||||
severity="danger"
|
||||
(click)="cancel()"
|
||||
></p-button>
|
||||
} @else {
|
||||
<p-button
|
||||
label="Close"
|
||||
icon="pi pi-times"
|
||||
severity="success"
|
||||
(click)="cancel()"
|
||||
></p-button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,3 @@
|
||||
:host ::ng-deep .p-datatable-tbody > tr > td {
|
||||
padding: 0.5rem 1rem !important;
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import {Component, inject, OnDestroy} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {filter, take, takeUntil} from 'rxjs/operators';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
import {BookService} from '../../../features/book/service/book.service';
|
||||
import {Book} from '../../../features/book/model/book.model';
|
||||
import {FileMoveRequest, FileOperationsService} from '../../service/file-operations-service';
|
||||
import {LibraryService} from "../../../features/book/service/library.service";
|
||||
import {AppSettingsService} from '../../service/app-settings.service';
|
||||
import {Select} from 'primeng/select';
|
||||
|
||||
interface FilePreview {
|
||||
bookId: number;
|
||||
originalPath: string;
|
||||
relativeOriginalPath: string;
|
||||
currentLibraryId: number | null;
|
||||
currentLibraryName: string;
|
||||
targetLibraryId: number | null;
|
||||
targetLibraryName: string;
|
||||
newPath: string;
|
||||
relativeNewPath: string;
|
||||
isMoved?: boolean;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-file-mover-component',
|
||||
standalone: true,
|
||||
imports: [Button, FormsModule, TableModule, Divider, Select],
|
||||
templateUrl: './file-mover-component.html',
|
||||
styleUrl: './file-mover-component.scss'
|
||||
})
|
||||
export class FileMoverComponent implements OnDestroy {
|
||||
private config = inject(DynamicDialogConfig);
|
||||
private ref = inject(DynamicDialogRef);
|
||||
private bookService = inject(BookService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private fileOperationsService = inject(FileOperationsService);
|
||||
private messageService = inject(MessageService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
libraryPatterns: {
|
||||
libraryId: number | null;
|
||||
libraryName: string;
|
||||
pattern: string;
|
||||
source: string;
|
||||
bookCount: number;
|
||||
}[] = [];
|
||||
defaultMovePattern = '';
|
||||
loading = false;
|
||||
patternsCollapsed = false;
|
||||
|
||||
bookIds: Set<number> = new Set();
|
||||
books: Book[] = [];
|
||||
availableLibraries: { id: number | null; name: string }[] = [];
|
||||
filePreviews: FilePreview[] = [];
|
||||
defaultTargetLibraryId: number | null = null;
|
||||
|
||||
constructor() {
|
||||
this.bookIds = new Set(this.config.data?.bookIds ?? []);
|
||||
this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]);
|
||||
this.loadAvailableLibraries();
|
||||
this.loadDefaultPattern();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadDefaultPattern(): void {
|
||||
this.appSettingsService.appSettings$.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(settings => {
|
||||
this.defaultMovePattern = settings?.uploadPattern || '';
|
||||
this.loadLibraryPatterns();
|
||||
});
|
||||
}
|
||||
|
||||
private loadLibraryPatterns(): void {
|
||||
this.libraryService.libraryState$.pipe(
|
||||
filter(state => state.loaded && state.libraries != null),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(state => {
|
||||
const booksByLibrary = new Map<number | null, Book[]>();
|
||||
this.books.forEach(book => {
|
||||
const libraryId =
|
||||
book.libraryId ??
|
||||
book.libraryPath?.id ??
|
||||
(book as any).library?.id ??
|
||||
null;
|
||||
if (!booksByLibrary.has(libraryId)) {
|
||||
booksByLibrary.set(libraryId, []);
|
||||
}
|
||||
booksByLibrary.get(libraryId)!.push(book);
|
||||
});
|
||||
|
||||
this.libraryPatterns = Array.from(booksByLibrary.entries()).map(([libraryId, books]) => {
|
||||
let libraryName = 'Unknown Library';
|
||||
let pattern = this.defaultMovePattern;
|
||||
let source = 'App Default';
|
||||
|
||||
if (libraryId) {
|
||||
const library = state.libraries?.find(lib => lib.id === libraryId);
|
||||
if (library) {
|
||||
libraryName = library.name;
|
||||
if (library.fileNamingPattern) {
|
||||
pattern = library.fileNamingPattern;
|
||||
source = 'Library Setting';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
libraryId,
|
||||
libraryName,
|
||||
pattern,
|
||||
source,
|
||||
bookCount: books.length
|
||||
};
|
||||
});
|
||||
|
||||
this.applyPattern();
|
||||
});
|
||||
}
|
||||
|
||||
private loadAvailableLibraries(): void {
|
||||
this.libraryService.libraryState$.pipe(
|
||||
filter(state => state.loaded && state.libraries != null),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(state => {
|
||||
this.availableLibraries = state.libraries?.map(lib => ({id: lib.id ?? null, name: lib.name})) || [];
|
||||
});
|
||||
}
|
||||
|
||||
applyPattern(): void {
|
||||
this.filePreviews = this.books.map(book => {
|
||||
const fileName = book.fileName ?? '';
|
||||
const fileSubPath = book.fileSubPath ? `${book.fileSubPath.replace(/\/+$/g, '')}/` : '';
|
||||
|
||||
const relativeOriginalPath = `${fileSubPath}${fileName}`;
|
||||
|
||||
const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as any).library?.id ?? null;
|
||||
const currentLibraryName = this.getLibraryNameById(currentLibraryId);
|
||||
|
||||
const targetLibraryId = currentLibraryId;
|
||||
const targetLibraryName = currentLibraryName;
|
||||
|
||||
const preview: FilePreview = {
|
||||
bookId: book.id,
|
||||
originalPath: this.getFullPath(currentLibraryId, relativeOriginalPath),
|
||||
relativeOriginalPath,
|
||||
currentLibraryId,
|
||||
currentLibraryName,
|
||||
targetLibraryId,
|
||||
targetLibraryName,
|
||||
newPath: '',
|
||||
relativeNewPath: ''
|
||||
};
|
||||
|
||||
this.updatePreviewPaths(preview, book);
|
||||
return preview;
|
||||
});
|
||||
}
|
||||
|
||||
onDefaultLibraryChange(): void {
|
||||
this.filePreviews.forEach(preview => {
|
||||
if (!preview.isMoved) {
|
||||
preview.targetLibraryId = this.defaultTargetLibraryId;
|
||||
preview.targetLibraryName = this.getLibraryNameById(this.defaultTargetLibraryId);
|
||||
|
||||
const book = this.books.find(b => b.id === preview.bookId);
|
||||
if (book) {
|
||||
this.updatePreviewPaths(preview, book);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onLibraryChange(preview: FilePreview): void {
|
||||
preview.targetLibraryName = this.getLibraryNameById(preview.targetLibraryId);
|
||||
const book = this.books.find(b => b.id === preview.bookId);
|
||||
if (book) {
|
||||
this.updatePreviewPaths(preview, book);
|
||||
}
|
||||
}
|
||||
|
||||
private updatePreviewPaths(preview: FilePreview, book: Book): void {
|
||||
const meta = book.metadata!;
|
||||
const fileName = book.fileName ?? '';
|
||||
const extension = fileName.match(/\.[^.]+$/)?.[0] ?? '';
|
||||
|
||||
const libraryPattern = this.libraryPatterns.find(p => p.libraryId === preview.targetLibraryId);
|
||||
const pattern = libraryPattern?.pattern || this.defaultMovePattern;
|
||||
|
||||
const values: Record<string, string> = {
|
||||
authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'),
|
||||
title: this.sanitize(meta.title || 'Untitled'),
|
||||
year: this.formatYear(meta.publishedDate),
|
||||
series: this.sanitize(meta.seriesName || ''),
|
||||
seriesIndex: this.formatSeriesIndex(meta.seriesNumber ?? undefined),
|
||||
language: this.sanitize(meta.language || ''),
|
||||
publisher: this.sanitize(meta.publisher || ''),
|
||||
isbn: this.sanitize(meta.isbn13 || meta.isbn10 || ''),
|
||||
currentFilename: this.sanitize(fileName)
|
||||
};
|
||||
|
||||
let newPath: string;
|
||||
|
||||
if (!pattern?.trim()) {
|
||||
newPath = fileName;
|
||||
} else {
|
||||
newPath = pattern.replace(/<([^<>]+)>/g, (_, block) => {
|
||||
const placeholders = [...block.matchAll(/{(.*?)}/g)].map(m => m[1]);
|
||||
const allHaveValues = placeholders.every(key => values[key]?.trim());
|
||||
return allHaveValues
|
||||
? block.replace(/{(.*?)}/g, (_: string, key: string) => values[key] ?? '')
|
||||
: '';
|
||||
});
|
||||
|
||||
newPath = newPath.replace(/{(.*?)}/g, (_, key) => values[key] ?? '');
|
||||
|
||||
if (!newPath.endsWith(extension)) {
|
||||
newPath += extension;
|
||||
}
|
||||
}
|
||||
|
||||
preview.relativeNewPath = newPath;
|
||||
preview.newPath = this.getFullPath(preview.targetLibraryId, newPath);
|
||||
}
|
||||
|
||||
private getLibraryNameById(libraryId: number | null): string {
|
||||
if (libraryId === null) return 'Unknown Library';
|
||||
return this.availableLibraries.find(lib => lib.id === libraryId)?.name || 'Unknown Library';
|
||||
}
|
||||
|
||||
private getFullPath(libraryId: number | null, relativePath: string): string {
|
||||
const libraryPath = libraryId ? this.libraryService.getLibraryPathById(libraryId)?.replace(/\/+$/g, '') : '';
|
||||
return libraryPath ? `${libraryPath}/${relativePath}`.replace(/\/\/+/g, '/') : relativePath;
|
||||
}
|
||||
|
||||
get movedFileCount(): number {
|
||||
return this.filePreviews.filter(p => p.isMoved).length;
|
||||
}
|
||||
|
||||
sanitize(input: string | undefined): string {
|
||||
return input?.replace(/[\\/:*?"<>|]/g, '')
|
||||
.replace(/[\x00-\x1F\x7F]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim() ?? '';
|
||||
}
|
||||
|
||||
formatYear(dateStr?: string): string {
|
||||
if (!dateStr) return '';
|
||||
const yearMatch = dateStr.match(/^(\d{4})/);
|
||||
if (yearMatch) {
|
||||
return yearMatch[1];
|
||||
}
|
||||
const date = new Date(dateStr);
|
||||
return isNaN(date.getTime()) ? '' : date.getUTCFullYear().toString();
|
||||
}
|
||||
|
||||
formatSeriesIndex(seriesNumber?: number): string {
|
||||
if (seriesNumber == null) return '';
|
||||
return this.sanitize(seriesNumber.toString());
|
||||
}
|
||||
|
||||
saveChanges(): void {
|
||||
this.loading = true;
|
||||
|
||||
const request: FileMoveRequest = {
|
||||
bookIds: [...this.bookIds],
|
||||
moves: this.filePreviews.map(preview => ({
|
||||
bookId: preview.bookId,
|
||||
targetLibraryId: preview.targetLibraryId
|
||||
}))
|
||||
};
|
||||
|
||||
this.fileOperationsService.moveFiles(request).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe({
|
||||
next: () => {
|
||||
this.loading = false;
|
||||
this.filePreviews.forEach(p => (p.isMoved = true));
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Files Organized!',
|
||||
detail: `Successfully organized ${this.filePreviews.length} file${this.filePreviews.length === 1 ? '' : 's'}.`,
|
||||
life: 3000
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.loading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Oops! Something went wrong',
|
||||
detail: 'We had trouble organizing your files. Please try again.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.ref.close();
|
||||
}
|
||||
|
||||
togglePatternsCollapsed(): void {
|
||||
this.patternsCollapsed = !this.patternsCollapsed;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user