Support File Move Operations with Watcher Refactor for Accurate Tracking

This commit is contained in:
aditya.chandel
2025-07-04 11:19:23 -06:00
committed by Aditya Chandel
parent 1c9c09628a
commit 841e359b92
73 changed files with 3714 additions and 852 deletions
@@ -0,0 +1,154 @@
<div class="p-fluid px-4 py-2 rounded-xl flex flex-col h-[800px]">
<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">
Customize Your File Organization
</p>
<p class="text-sm text-gray-300 leading-relaxed">
Define a naming pattern to reorganize selected book files on your system. Use dynamic placeholders like
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{title}' }}</code>
or
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{authors}' }}</code>
to automatically insert metadata. <br>
A preview below shows how files will be renamed and moved.
Once you're satisfied, click <span class="font-semibold text-green-400">Apply</span> to proceed.
<span class="text-yellow-500 font-medium flex items-center gap-2">
<i class="pi pi-exclamation-triangle text-yellow-400"></i>
Files will be physically moved on your system when you apply changes.
</span>
</p>
</div>
<div class="mb-2 px-1 text-sm text-muted">
<p-button
size="small"
text
severity="info"
(click)="placeholdersVisible = !placeholdersVisible">
{{ placeholdersVisible ? 'Hide' : 'Show' }} available placeholders
</p-button>
@if (placeholdersVisible) {
<div class="mx-4 my-2 flex flex-wrap gap-4">
<ul class="list-disc pl-4 min-w-[250px]">
<li><code>{{ '{title}' }}</code> - Book title</li>
<li><code>{{ '{authors}' }}</code> - Author(s)</li>
<li><code>{{ '{year}' }}</code> - Full year (e.g. 2025)</li>
<li><code>{{ '{series}' }}</code> - Series name</li>
<li><code>{{ '{seriesIndex}' }}</code> - Series index (e.g. 01)</li>
<li><code>{{ '{language}' }}</code> - Language (e.g. en)</li>
<li><code>{{ '{publisher}' }}</code> - Publisher</li>
<li><code>{{ '{isbn}' }}</code> - ISBN</li>
<li><code>{{ '{currentFilename}' }}</code> - Original file name (with extension)</li>
</ul>
<p-divider layout="vertical"></p-divider>
<div class="text-sm p-3 min-w-[250px]">
<p class="mb-1 font-medium">Tip: Optional placeholders</p>
<p>Wrap parts of your pattern in angle brackets <code>{{ '<...>' }}</code> to make them optional.</p>
<p>If any placeholder inside has no value, the whole block is removed.</p>
<p class="mt-1 font-semibold">Example:</p>
<p><code>{{ '<{seriesIndex} - >{title}' }}</code></p>
<p class="pl-4 mt-1">• <code>{{ '01 - Dune' }}</code> (if <code>{{ '{seriesIndex}' }}</code> is present)</p>
<p class="pl-4">• <code>{{ 'Dune' }}</code> (if <code>{{ '{seriesIndex}' }}</code> is missing)</p>
</div>
</div>
}
</div>
<div class="flex gap-2 mb-4 px-2 items-center w-full">
<input
type="text"
pInputText
[(ngModel)]="movePattern"
(ngModelChange)="applyPattern()"
[placeholder]="movePattern.trim() ? '' : getDefaultPattern()"
class="flex-1"
/>
<p-button
icon="pi pi-save"
label="Make Default"
severity="info"
outlined
(click)="setDefaultPattern()"
></p-button>
</div>
<div class="flex-grow overflow-y-auto mt-4">
<p-table
[value]="filePreviews"
[responsiveLayout]="'scroll'"
class="block min-w-full"
>
<ng-template pTemplate="header">
<tr>
<th style="width: 0.5rem; text-align: center;">ID</th>
<th>Current Path</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.libraryPathPrefix }}/</span><span>{{ preview.relativeOriginalPath }}</span>
</p>
</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.libraryPathPrefix }}/</span><span>{{ 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">
@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,219 @@
import {Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {InputText} from 'primeng/inputtext';
import {Divider} from 'primeng/divider';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {filter, take} from 'rxjs/operators';
import {BookService} from '../book/service/book.service';
import {Book} from '../book/model/book.model';
import {FileMoveRequest, FileOperationsService} from '../file-operations-service';
import {LibraryService} from "../book/service/library.service";
import {AppSettingsService} from '../core/service/app-settings.service';
import {AppSettingKey} from '../core/model/app-settings.model';
@Component({
selector: 'app-file-mover-component',
standalone: true,
imports: [Button, FormsModule, TableModule, InputText, Divider],
templateUrl: './file-mover-component.html',
styleUrl: './file-mover-component.scss'
})
export class FileMoverComponent {
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);
movePattern = '';
placeholdersVisible = false;
loading = false;
bookIds: Set<number> = new Set();
books: Book[] = [];
filePreviews: { originalPath: string; newPath: string; isMoved?: boolean }[] = [];
constructor() {
this.bookIds = new Set(this.config.data?.bookIds ?? []);
this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]);
this.appSettingsService.appSettings$.pipe(
filter(settings => settings != null),
take(1)
).subscribe(settings => {
this.movePattern = settings?.movePattern;
this.applyPattern();
});
}
applyPattern(): void {
this.filePreviews = this.books.map(book => {
const meta = book.metadata!;
const fileName = book.fileName ?? '';
const extension = fileName.match(/\.[^.]+$/)?.[0] ?? '';
const fileSubPath = book.fileSubPath ? `${book.fileSubPath.replace(/\/+$/g, '')}/` : '';
const relativeOriginalPath = `${fileSubPath}${fileName}`;
const libraryPathPrefix =
book.libraryPath?.id != null
? this.libraryService.getLibraryPathById(book.libraryPath.id)?.replace(/\/+$/g, '') ?? ''
: '';
const originalPath = `${libraryPathPrefix}/${relativeOriginalPath}`.replace(/\/\/+/g, '/');
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 (!this.movePattern?.trim()) {
// If pattern empty, just use current filename as the new path
newPath = `${fileSubPath}${fileName}`; // preserve subpath + filename
} else {
newPath = this.movePattern.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] ?? '');
// Append extension if not already present (most patterns won't include extension)
if (!newPath.endsWith(extension)) {
newPath += extension;
}
}
const relativeNewPath = newPath;
const fullNewPath = `${libraryPathPrefix}/${relativeNewPath}`.replace(/\/\/+/g, '/');
return {
bookId: book.id,
originalPath,
relativeOriginalPath,
libraryPathPrefix,
newPath: fullNewPath,
relativeNewPath
};
});
}
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 date = new Date(dateStr);
return isNaN(date.getTime()) ? '' : date.getFullYear().toString();
}
formatSeriesIndex(seriesNumber?: number): string {
if (seriesNumber == null) return '';
return this.sanitize(seriesNumber.toString());
}
getDefaultPattern(): string {
return 'e.g. {authors}/<{series}/><{seriesIndex}. >{title} - {authors}< ({year})>';
}
saveChanges(): void {
if (!this.movePattern?.trim()) {
this.messageService.add({
severity: 'error',
summary: 'Missing Pattern',
detail: 'Move pattern cannot be empty. Please enter a valid pattern.',
life: 3000
});
return;
}
this.loading = true;
const request: FileMoveRequest = {
bookIds: [...this.bookIds],
pattern: this.movePattern
};
this.fileOperationsService.moveFiles(request).subscribe({
next: () => {
this.loading = false;
this.filePreviews.forEach(p => (p.isMoved = true));
this.messageService.add({
severity: 'success',
summary: 'Files Moved',
detail: `${this.filePreviews.length} file(s) successfully relocated.`,
life: 3000
});
},
error: () => {
this.loading = false;
this.messageService.add({
severity: 'error',
summary: 'Move Failed',
detail: 'An error occurred while moving the files.',
life: 3000
});
}
});
}
setDefaultPattern(): void {
const trimmedPattern = this.movePattern?.trim();
if (!trimmedPattern) {
this.messageService.add({
severity: 'error',
summary: 'Cannot Save',
detail: 'Move pattern cannot be empty.'
});
return;
}
const payload = [
{
key: AppSettingKey.MOVE_FILE_PATTERN,
newValue: trimmedPattern
}
];
this.appSettingsService.saveSettings(payload).subscribe({
next: () => this.messageService.add({
severity: 'success',
summary: 'Saved',
detail: 'Move pattern saved as default.'
}),
error: () => this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to save default move pattern.'
})
});
}
cancel(): void {
this.ref.close();
}
}