From 978bd05b1e6a67b6ce887affca9b174f993345b6 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" <8075870+adityachandelgit@users.noreply.github.com> Date: Sun, 10 Aug 2025 11:26:57 -0600 Subject: [PATCH] Add per-library customizable file naming patterns --- .../controller/LibraryController.java | 10 + .../booklore/model/dto/Library.java | 1 + .../dto/request/BookdropFinalizeRequest.java | 1 - .../booklore/model/entity/LibraryEntity.java | 3 + .../service/bookdrop/BookDropService.java | 22 +- .../service/library/LibraryService.java | 6 + ..._file_naming_pattern_column_to_library.sql | 3 + .../src/app/book/model/library.model.ts | 1 + .../src/app/book/service/library.service.ts | 17 +- .../bookdrop-file-review.component.html | 21 +- .../bookdrop-file-review.component.ts | 3 - .../bookdrop/bookdrop-file-task.service.ts | 2 - .../file-naming-pattern.component.html | 262 ++++++++++++++++++ .../file-naming-pattern.component.scss} | 4 + .../file-naming-pattern.component.ts} | 110 ++++---- .../file-upload-pattern.component.html | 235 ---------------- .../global-preferences.component.html | 4 - .../global-preferences.component.ts | 2 - .../src/app/settings/settings.component.html | 6 + .../src/app/settings/settings.component.ts | 23 +- 20 files changed, 394 insertions(+), 342 deletions(-) create mode 100644 booklore-api/src/main/resources/db/migration/V43__Add_file_naming_pattern_column_to_library.sql create mode 100644 booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.html rename booklore-ui/src/app/settings/{global-preferences/file-upload-pattern/file-upload-pattern.component.scss => file-naming-pattern/file-naming-pattern.component.scss} (57%) rename booklore-ui/src/app/settings/{global-preferences/file-upload-pattern/file-upload-pattern.component.ts => file-naming-pattern/file-naming-pattern.component.ts} (50%) delete mode 100644 booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html 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 b5d4a59d8..ed7f0cbb3 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 @@ -11,6 +11,7 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; +import java.util.Map; @RestController @RequestMapping("/api/v1/libraries") @@ -72,4 +73,13 @@ public class LibraryController { libraryService.rescanLibrary(libraryId); return ResponseEntity.noContent().build(); } + + @PatchMapping("/{libraryId}/file-naming-pattern") + @CheckLibraryAccess(libraryIdParam = "libraryId") + @PreAuthorize("@securityUtil.canManipulateLibrary() or @securityUtil.isAdmin()") + public ResponseEntity setFileNamingPattern(@PathVariable long libraryId, @RequestBody Map body) { + String pattern = body.get("fileNamingPattern"); + Library updated = libraryService.setFileNamingPattern(libraryId, pattern); + return ResponseEntity.ok(updated); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java index def8aa8c9..dece1d838 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/Library.java @@ -14,6 +14,7 @@ public class Library { private String name; private Sort sort; private String icon; + private String fileNamingPattern; private boolean watch; private List paths; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookdropFinalizeRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookdropFinalizeRequest.java index 58572a76c..59f00d5cb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookdropFinalizeRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/BookdropFinalizeRequest.java @@ -7,7 +7,6 @@ import java.util.List; @Data public class BookdropFinalizeRequest { - private String uploadPattern; private Boolean selectAll; private List excludedIds; private List files; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java index bb31d9a95..551040291 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java @@ -37,4 +37,7 @@ public class LibraryEntity { private boolean watch; private String icon; + + @Column(name = "file_naming_pattern") + private String fileNamingPattern; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java index 49003f6bb..bd22e96a9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/bookdrop/BookDropService.java @@ -22,6 +22,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookdropFileRepository; import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor; import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry; import com.adityachandel.booklore.service.metadata.MetadataRefreshService; @@ -70,6 +71,7 @@ public class BookDropService { private final AppProperties appProperties; private final BookdropFileMapper mapper; private final ObjectMapper objectMapper; + AppSettingService appSettingService; public BookdropFileNotification getFileNotificationSummary() { long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW); @@ -127,7 +129,7 @@ public class BookDropService { failedCount.incrementAndGet(); continue; } - processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount); + processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount); } } } else { @@ -156,7 +158,7 @@ public class BookDropService { failedCount.incrementAndGet(); continue; } - processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount); + processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount); } } } @@ -188,7 +190,6 @@ public class BookDropService { BookdropFinalizeRequest.BookdropFinalizeFile fileReq, Long defaultLibraryId, Long defaultPathId, - String uploadPattern, BookdropFinalizeResult results, AtomicInteger failedCount ) { @@ -217,13 +218,7 @@ public class BookDropService { log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId); } - BookdropFileResult result = moveFile( - libraryId, - pathId, - uploadPattern, - metadata, - fileEntity - ); + BookdropFileResult result = moveFile(libraryId, pathId, metadata, fileEntity); results.getResults().add(result); if (!result.isSuccess()) { @@ -241,7 +236,7 @@ public class BookDropService { } } - private BookdropFileResult moveFile(long libraryId, long pathId, String filePattern, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception { + private BookdropFileResult moveFile(long libraryId, long pathId, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception { LibraryEntity library = libraryRepository.findById(libraryId) .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); @@ -250,6 +245,11 @@ public class BookDropService { .findFirst() .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); + String filePattern = library.getFileNamingPattern(); + if (filePattern == null || filePattern.isBlank()) { + filePattern = appSettingService.getAppSettings().getUploadPattern(); + } + if (filePattern.endsWith("/") || filePattern.endsWith("\\")) { filePattern += "{currentFilename}"; } 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 fb0c3f00a..1107a37eb 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 @@ -231,4 +231,10 @@ public class LibraryService { List bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId); return bookEntities.stream().map(bookMapper::toBook).toList(); } + + public Library setFileNamingPattern(long libraryId, String pattern) { + LibraryEntity library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); + library.setFileNamingPattern(pattern); + return libraryMapper.toLibrary(libraryRepository.save(library)); + } } \ No newline at end of file diff --git a/booklore-api/src/main/resources/db/migration/V43__Add_file_naming_pattern_column_to_library.sql b/booklore-api/src/main/resources/db/migration/V43__Add_file_naming_pattern_column_to_library.sql new file mode 100644 index 000000000..1a9cf7443 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V43__Add_file_naming_pattern_column_to_library.sql @@ -0,0 +1,3 @@ +ALTER TABLE library + ADD COLUMN IF NOT EXISTS file_naming_pattern VARCHAR(1000); + diff --git a/booklore-ui/src/app/book/model/library.model.ts b/booklore-ui/src/app/book/model/library.model.ts index 4f4b4810e..dc00fd584 100644 --- a/booklore-ui/src/app/book/model/library.model.ts +++ b/booklore-ui/src/app/book/model/library.model.ts @@ -5,6 +5,7 @@ export interface Library { name: string; icon: string; watch: boolean; + fileNamingPattern?: string; sort?: SortOption; paths: LibraryPath[]; } diff --git a/booklore-ui/src/app/book/service/library.service.ts b/booklore-ui/src/app/book/service/library.service.ts index 529303431..a075b2c53 100644 --- a/booklore-ui/src/app/book/service/library.service.ts +++ b/booklore-ui/src/app/book/service/library.service.ts @@ -122,14 +122,27 @@ export class LibraryService { getLibraryPathById(pathId: number): string | undefined { const libraries = this.libraryStateSubject.value.libraries || []; - for (const library of libraries) { const match = library.paths.find(p => p.id === pathId); if (match) { return match.path; } } - return undefined; } + + updateLibraryFileNamingPattern(libraryId: number, fileNamingPattern: string): Observable { + return this.http.patch(`${this.url}/${libraryId}/file-naming-pattern`, { fileNamingPattern }).pipe( + map(updatedLibrary => { + const currentState = this.libraryStateSubject.value; + const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary => + existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary]; + this.libraryStateSubject.next({...currentState, libraries: updatedLibraries}); + return updatedLibrary; + }), + catchError(error => { + throw error; + }) + ); + } } diff --git a/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.html b/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.html index 5e7e45a90..1a1ce558f 100644 --- a/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.html +++ b/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.html @@ -33,25 +33,6 @@ } @if (bookdropFileUis.length !== 0) { - -
- - - -
-
@@ -126,7 +107,7 @@ }
-
+
@if (bookdropFileUis.length === 0) {
No bookdrop files to review. diff --git a/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.ts b/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.ts index 687ab8b75..2c6486b7e 100644 --- a/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.ts +++ b/booklore-ui/src/app/bookdrop/bookdrop-file-review-component/bookdrop-file-review.component.ts @@ -11,7 +11,6 @@ import {DropdownModule} from 'primeng/dropdown'; import {FormControl, FormGroup, FormsModule} from '@angular/forms'; import {Button} from 'primeng/button'; import {Select} from 'primeng/select'; -import {InputText} from 'primeng/inputtext'; import {Tooltip} from 'primeng/tooltip'; import {Divider} from 'primeng/divider'; import {ConfirmationService, MessageService} from 'primeng/api'; @@ -55,7 +54,6 @@ export interface BookdropFileUI { BookdropFileMetadataPickerComponent, Tooltip, Divider, - InputText, Checkbox, NgStyle, NgClass, @@ -425,7 +423,6 @@ export class BookdropFileReviewComponent implements OnInit { }); const payload: BookdropFinalizePayload = { - uploadPattern: this.uploadPattern, selectAll: this.selectAllAcrossPages, excludedIds: this.selectAllAcrossPages ? Array.from(this.excludedFiles) : undefined, defaultLibraryId: this.defaultLibraryId ? Number(this.defaultLibraryId) : undefined, diff --git a/booklore-ui/src/app/bookdrop/bookdrop-file-task.service.ts b/booklore-ui/src/app/bookdrop/bookdrop-file-task.service.ts index 2aafe6bf7..290d59f97 100644 --- a/booklore-ui/src/app/bookdrop/bookdrop-file-task.service.ts +++ b/booklore-ui/src/app/bookdrop/bookdrop-file-task.service.ts @@ -5,13 +5,11 @@ import {BookMetadata} from '../book/model/book.model'; import {API_CONFIG} from '../config/api-config'; export enum BookdropFileStatus { - PENDING_REVIEW = 'PENDING_REVIEW', ACCEPTED = 'ACCEPTED', REJECTED = 'REJECTED', } export interface BookdropFinalizePayload { - uploadPattern: string; selectAll?: boolean; excludedIds?: number[]; defaultLibraryId?: number; diff --git a/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.html b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.html new file mode 100644 index 000000000..2c9836b58 --- /dev/null +++ b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.html @@ -0,0 +1,262 @@ +
+
+

+ File Naming Patterns + + +

+
+ +
+

Default File Naming Pattern:

+

+ Define the default naming pattern for files. This pattern applies to all libraries unless overridden. +

+
+ + +
+ @if (defaultErrorMessage) { +
{{ defaultErrorMessage }}
+ } + +
+

Preview:

+

{{ generateDefaultPreview() }}

+
+
+ +
+

Overrides for Libraries:

+

+ Define custom naming patterns for specific libraries. Leave empty to use the default pattern. +

+ + @for (library of libraries; track library.id) { +
+
+ + {{ library.name }} + + + +
+
+

Preview:

+

{{ generateLibraryPreview(library) }}

+
+
+ } + +
+ +
+
+ +
+ + +

Available Placeholders:

+ +

+ Use placeholders to dynamically insert book metadata into file names and folder paths. These will be replaced with actual values when uploading or moving files. + You can also wrap parts of the pattern in {{ '{{<...>}' }} to make them optional, if any placeholder inside is missing, that section will be omitted entirely. +

+ +
+
+
    +
  • {{ '{title}' }} – Book title
  • +
  • {{ '{authors}' }} – Author(s)
  • +
  • {{ '{year}' }} – Full year (e.g. 2025)
  • +
  • {{ '{series}' }} – Series name
  • +
  • {{ '{seriesIndex}' }} – Series index (e.g. 01)
  • +
  • {{ '{language}' }} – Language code (e.g. en)
  • +
  • {{ '{publisher}' }} – Publisher name
  • +
  • {{ '{isbn}' }} – ISBN number
  • +
  • {{ '{currentFilename}' }} Original file name (with extension)
  • +
+ + + +
+

Optional blocks

+

+ Surround parts of your pattern with angle brackets + {{ '{<...>}' }} + to make them optional.
If any placeholder inside the block has no value, the whole block is excluded. +

+

Example:

+

{{ '{<{seriesIndex} - >{title}' }}

+

• 01 - Dune (if {{ '{seriesIndex}' }} exists)

+

• Dune (if {{ '{seriesIndex}' }} is missing)

+
+
+
+ + + +
+

Example Patterns & Output:

+ +
+

Examples with Full Metadata

+

+ title: Harry Potter and the Sorcerer's Stone + authors: J.K. Rowling + series: Harry Potter + seriesIndex: 01 + year: 1997 + currentFilename: harry1_original.epub +

+ +
+

Basic pattern: {{ '{authors} - {title}' }}

+

Output: J.K. Rowling - Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Pattern with punctuation: {{ '{title}: {series}' }}

+

Output: Harry Potter and the Sorcerer's Stone: Harry Potter.epub

+
+ +
+

Series in folder path: {{ '{authors}/{series}/{seriesIndex} - {title}' }}

+

Output: J.K. Rowling/Harry Potter/01 - Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Folder only: {{ '{title}/' }}

+

Output: /Harry Potter and the Sorcerer's Stone/harry1_original.epub

+
+ +
+

Absolute path: {{ '/{authors}/{title}' }}

+

Output: /J.K. Rowling/Harry Potter and the Sorcerer's Stone.epub

+
+ +
+

Reuse original filename in path: {{ '{authors}/{series}/{currentFilename}' }} +

+

Output: J.K. Rowling/Harry Potter/harry1_original.epub

+
+ +
+

Preserve original filename only: {{ '{currentFilename}' }}

+

Output: harry1_original.epub

+
+ +
+

Empty pattern (defaults to current filename): {{ '' }}

+

Output: harry1_original.epub

+
+
+ +
+

Examples with Missing Optional Fields

+

+ title: Project Hail Mary + authors: Andy Weir + year: 2021 + series: (not provided) + seriesIndex: (not provided) + currentFilename: project_hail_mary_final.epub +

+ +
+

Pattern with optional blocks: {{ '{authors}/<{series}/><{seriesIndex}. >{title}< ({year})>' }}

+

Output: Andy Weir/Project Hail Mary (2021).epub

+
+ +
+

Fallback with seriesIndex and dash: {{ '<{seriesIndex}. >{title}< - {authors}>' }}

+

Output: Project Hail Mary - Andy Weir.epub

+
+ +
+

Brackets & punctuation fallback: {{ '<[{series}] >{title} - {authors}' }}

+

Output: Project Hail Mary - Andy Weir.epub

+
+ +
+

Series + punctuation fallback: {{ '<{series}: >{title} by {authors}' }}

+

Output: Project Hail Mary by Andy Weir.epub

+
+ +
+

Only folders, no filename: {{ '{authors}/' }}

+

Output: Andy Weir/project_hail_mary_final.epub

+
+ +
+

Deep nested folders: {{ '{authors}/books/<{series}/>{title}/' }}

+

Output: Andy Weir/books/Project Hail Mary/project_hail_mary_final.epub

+
+ +
+

With static folder prefix: {{ 'Books/<{series}/>{authors} - {title}' }}

+

Output: Books/Andy Weir - Project Hail Mary.epub

+
+ +
+

Use original filename in path: {{ '{authors}/books/<{series}/>{currentFilename}' }}

+

Output: Andy Weir/books/project_hail_mary_final.epub

+
+ +
+

Prefix current filename manually: {{ '{authors}/final__{currentFilename}' }}

+

Output: Andy Weir/final__project_hail_mary_final.epub

+
+ +
+

Filename preserved, renamed folder: {{ '{title}/source/{currentFilename}' }}

+

Output: Project Hail Mary/source/project_hail_mary_final.epub

+
+ +
+

Use current filename with year suffix: {{ '{authors}/{year}__{currentFilename}' }}

+

Output: Andy Weir/2021__project_hail_mary_final.epub

+
+ +
+

Fallback with optional + extras folder: {{ '<{series}/>{authors}/extras/{currentFilename}' }}

+

Output: Andy Weir/extras/project_hail_mary_final.epub

+
+ +
+

Archive structure using original name: {{ 'archive/<{series}/>{year}/{currentFilename}' }}

+

Output: archive/2021/project_hail_mary_final.epub

+
+ +
+

Structured folder + renamed file: {{ '{authors}/<{series}/>{title} ({year}) by {authors}' }}

+

Output: Andy Weir/Project Hail Mary (2021) by Andy Weir.epub

+
+
+
+
+
+
+
diff --git a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.scss b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.scss similarity index 57% rename from booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.scss rename to booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.scss index 84ba7a775..98ea08bb0 100644 --- a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.scss +++ b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.scss @@ -1,3 +1,7 @@ +.enclosing-container { + border-color: var(--p-content-border-color); +} + .custom-border { border: 1px solid var(--border-color); border-radius: var(--card-border); diff --git a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.ts similarity index 50% rename from booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts rename to booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.ts index b35a09c87..2b7121dbd 100644 --- a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.ts +++ b/booklore-ui/src/app/settings/file-naming-pattern/file-naming-pattern.component.ts @@ -2,21 +2,23 @@ import {Component, inject, OnInit} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {Button} from 'primeng/button'; import {MessageService} from 'primeng/api'; -import {AppSettingsService} from '../../../core/service/app-settings.service'; -import {Observable} from 'rxjs'; -import {AppSettingKey, AppSettings} from '../../../core/model/app-settings.model'; -import {filter, take} from 'rxjs/operators'; +import {AppSettingsService} from '../../core/service/app-settings.service'; +import {forkJoin, Observable, of} from 'rxjs'; +import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model'; +import {catchError, filter, take} from 'rxjs/operators'; import {Divider} from 'primeng/divider'; import {Tooltip} from 'primeng/tooltip'; +import {Library} from '../../book/model/library.model'; +import {LibraryService} from '../../book/service/library.service'; @Component({ - selector: 'app-file-upload-pattern', - templateUrl: './file-upload-pattern.component.html', + selector: 'app-file-naming-pattern', + templateUrl: './file-naming-pattern.component.html', standalone: true, imports: [FormsModule, Button, Divider, Tooltip], - styleUrls: ['./file-upload-pattern.component.scss'], + styleUrls: ['./file-naming-pattern.component.scss'], }) -export class FileUploadPatternComponent implements OnInit { +export class FileNamingPatternComponent implements OnInit { readonly exampleMetadata: Record = { title: 'The Fellowship of the Ring', authors: 'J.R.R. Tolkien', @@ -28,14 +30,13 @@ export class FileUploadPatternComponent implements OnInit { isbn: '9780618574940', }; - uploadPattern = ''; - movePattern = ''; - - uploadErrorMessage = ''; - moveErrorMessage = ''; + defaultPattern = ''; + libraries: Library[] = []; + defaultErrorMessage = ''; private appSettingsService = inject(AppSettingsService); private messageService = inject(MessageService); + private libraryService = inject(LibraryService); appSettings$: Observable = this.appSettingsService.appSettings$; @@ -43,8 +44,13 @@ export class FileUploadPatternComponent implements OnInit { this.appSettings$ .pipe(filter((settings) => settings != null), take(1)) .subscribe((settings) => { - this.uploadPattern = settings?.uploadPattern ?? ''; - this.movePattern = settings?.movePattern ?? ''; + this.defaultPattern = settings?.uploadPattern ?? ''; + }); + + this.libraryService.libraryState$ + .pipe(filter(state => state.loaded && !!state.libraries)) + .subscribe(state => { + this.libraries = state.libraries ?? []; }); } @@ -65,77 +71,77 @@ export class FileUploadPatternComponent implements OnInit { return hasExtension ? path : path + ext; } - generateUploadPreview(): string { - let path = this.replacePlaceholders(this.uploadPattern || '', this.exampleMetadata); + private generatePreview(pattern: string): string { + let path = this.replacePlaceholders(pattern || '', this.exampleMetadata); if (!path) return '/original_filename.pdf'; - - // If pattern ends with slash, append original filename - if (path.endsWith('/')) { - return path + 'original_filename.pdf'; - } - - // Replace {originalFilename} placeholder if present + if (path.endsWith('/')) return path + 'original_filename.pdf'; if (path.includes('{originalFilename}')) { path = path.replace('{originalFilename}', 'original_filename.pdf'); return path.startsWith('/') ? path : `/${path}`; } - path = this.appendExtensionIfMissing(path); return path.startsWith('/') ? path : `/${path}`; } - generateMovePreview(): string { - let path = this.replacePlaceholders(this.movePattern || '', this.exampleMetadata); + generateDefaultPreview(): string { + return this.generatePreview(this.defaultPattern); + } - if (!path) return '/original_filename.pdf'; - - if (path.endsWith('/')) { - return path + 'original_filename.pdf'; - } - - if (path.includes('{originalFilename}')) { - path = path.replace('{originalFilename}', 'original_filename.pdf'); - return path.startsWith('/') ? path : `/${path}`; - } - - path = this.appendExtensionIfMissing(path); - return path.startsWith('/') ? path : `/${path}`; + generateLibraryPreview(library: Library): string { + return this.generatePreview(library.fileNamingPattern || this.defaultPattern); } validatePattern(pattern: string): boolean { - // Allow letters, numbers, whitespace, common punctuation and placeholders syntax const validPatternRegex = /^[\w\s\-{}\/().<>.,:'"]*$/; return validPatternRegex.test(pattern); } - onUploadPatternChange(pattern: string): void { - this.uploadPattern = pattern; - this.uploadErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; + onDefaultPatternChange(pattern: string): void { + this.defaultPattern = pattern; + this.defaultErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; } - onMovePatternChange(pattern: string): void { - this.movePattern = pattern; - this.moveErrorMessage = this.validatePattern(pattern) ? '' : 'Pattern contains invalid characters.'; + onLibraryPatternChange(library: Library): void { + // Optionally add per-library validation here + } + + clearLibraryPattern(library: Library): void { + library.fileNamingPattern = ''; } savePatterns(): void { - if (this.uploadErrorMessage || this.moveErrorMessage) { + if (this.defaultErrorMessage) { this.showMessage('error', 'Invalid Pattern', 'Please fix errors before saving.'); return; } this.appSettingsService .saveSettings([ - {key: AppSettingKey.UPLOAD_FILE_PATTERN, newValue: this.uploadPattern}, - {key: AppSettingKey.MOVE_FILE_PATTERN, newValue: this.movePattern}, + { key: AppSettingKey.UPLOAD_FILE_PATTERN, newValue: this.defaultPattern }, ]) .subscribe({ - next: () => this.showMessage('success', 'Settings Saved', 'The patterns were successfully saved!'), + next: () => this.showMessage('success', 'Settings Saved', 'The default pattern was successfully saved!'), error: () => this.showMessage('error', 'Error', 'There was an error saving the settings.'), }); } + saveLibraryPatterns(): void { + const patchRequests = this.libraries.map(library => + this.libraryService.updateLibraryFileNamingPattern(library.id!, library.fileNamingPattern || '').pipe( + catchError(() => of(null)) + ) + ); + forkJoin(patchRequests).subscribe(results => { + const failures = results.filter(result => result === null); + if (failures.length === 0) { + this.showMessage('success', 'Library Patterns Saved', 'Library-specific patterns were successfully saved!'); + } else { + this.showMessage('error', 'Error', `Failed to save ${failures.length} library pattern(s).`); + } + }); + } + private showMessage(severity: 'success' | 'error', summary: string, detail: string): void { - this.messageService.add({severity, summary, detail}); + this.messageService.add({ severity, summary, detail }); } } diff --git a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html b/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html deleted file mode 100644 index 2365d76d4..000000000 --- a/booklore-ui/src/app/settings/global-preferences/file-upload-pattern/file-upload-pattern.component.html +++ /dev/null @@ -1,235 +0,0 @@ -

- File Naming Patterns - - -

- -
- -
-

Enter Upload File Naming Pattern:

-

- Define how newly uploaded files are named and organized using book metadata. -

-
- - -
- @if (uploadErrorMessage) { -
{{ uploadErrorMessage }}
- } - -

Upload Pattern Preview:

-

{{ generateUploadPreview() }}

-
- -
-

Enter File Move Naming Pattern:

-

- Specify how book files should be renamed and relocated using metadata such as title, authors, or series. This pattern is applied when using the Move Files feature. -

-
- - -
- @if (moveErrorMessage) { -
{{ moveErrorMessage }}
- } - -

Move Pattern Preview:

-

{{ generateMovePreview() }}

- - - -

Available Placeholders:

- -

- Use placeholders to dynamically insert book metadata into file names and folder paths. These will be replaced with actual values when uploading or moving files. - You can also wrap parts of the pattern in {{ '{{<...>}' }} to make them optional, if any placeholder inside is missing, that section will be omitted entirely. -

- -
-
-
    -
  • {{ '{title}' }} – Book title
  • -
  • {{ '{authors}' }} – Author(s)
  • -
  • {{ '{year}' }} – Full year (e.g. 2025)
  • -
  • {{ '{series}' }} – Series name
  • -
  • {{ '{seriesIndex}' }} – Series index (e.g. 01)
  • -
  • {{ '{language}' }} – Language code (e.g. en)
  • -
  • {{ '{publisher}' }} – Publisher name
  • -
  • {{ '{isbn}' }} – ISBN number
  • -
  • {{ '{currentFilename}' }} Original file name (with extension)
  • -
- - - -
-

Optional blocks

-

- Surround parts of your pattern with angle brackets - {{ '{<...>}' }} - to make them optional.
If any placeholder inside the block has no value, the whole block is excluded. -

-

Example:

-

{{ '{<{seriesIndex} - >{title}' }}

-

• 01 - Dune (if {{ '{seriesIndex}' }} exists)

-

• Dune (if {{ '{seriesIndex}' }} is missing)

-
-
-
- - - -
-

Example Patterns & Output:

- -
-

Examples with Full Metadata

-

- title: Harry Potter and the Sorcerer's Stone - authors: J.K. Rowling - series: Harry Potter - seriesIndex: 01 - year: 1997 - currentFilename: harry1_original.epub -

- -
-

Basic pattern: {{ '{authors} - {title}' }}

-

Output: J.K. Rowling - Harry Potter and the Sorcerer's Stone.epub

-
- -
-

Pattern with punctuation: {{ '{title}: {series}' }}

-

Output: Harry Potter and the Sorcerer's Stone: Harry Potter.epub

-
- -
-

Series in folder path: {{ '{authors}/{series}/{seriesIndex} - {title}' }}

-

Output: J.K. Rowling/Harry Potter/01 - Harry Potter and the Sorcerer's Stone.epub

-
- -
-

Folder only: {{ '{title}/' }}

-

Output: /Harry Potter and the Sorcerer's Stone/harry1_original.epub

-
- -
-

Absolute path: {{ '/{authors}/{title}' }}

-

Output: /J.K. Rowling/Harry Potter and the Sorcerer's Stone.epub

-
- -
-

Reuse original filename in path: {{ '{authors}/{series}/{currentFilename}' }} -

-

Output: J.K. Rowling/Harry Potter/harry1_original.epub

-
- -
-

Preserve original filename only: {{ '{currentFilename}' }}

-

Output: harry1_original.epub

-
- -
-

Empty pattern (defaults to current filename): {{ '' }}

-

Output: harry1_original.epub

-
-
- -
-

Examples with Missing Optional Fields

-

- title: Project Hail Mary - authors: Andy Weir - year: 2021 - series: (not provided) - seriesIndex: (not provided) - currentFilename: project_hail_mary_final.epub -

- -
-

Pattern with optional blocks: {{ '{authors}/<{series}/><{seriesIndex}. >{title}< ({year})>' }}

-

Output: Andy Weir/Project Hail Mary (2021).epub

-
- -
-

Fallback with seriesIndex and dash: {{ '<{seriesIndex}. >{title}< - {authors}>' }}

-

Output: Project Hail Mary - Andy Weir.epub

-
- -
-

Brackets & punctuation fallback: {{ '<[{series}] >{title} - {authors}' }}

-

Output: Project Hail Mary - Andy Weir.epub

-
- -
-

Series + punctuation fallback: {{ '<{series}: >{title} by {authors}' }}

-

Output: Project Hail Mary by Andy Weir.epub

-
- -
-

Only folders, no filename: {{ '{authors}/' }}

-

Output: Andy Weir/project_hail_mary_final.epub

-
- -
-

Deep nested folders: {{ '{authors}/books/<{series}/>{title}/' }}

-

Output: Andy Weir/books/Project Hail Mary/project_hail_mary_final.epub

-
- -
-

With static folder prefix: {{ 'Books/<{series}/>{authors} - {title}' }}

-

Output: Books/Andy Weir - Project Hail Mary.epub

-
- -
-

Use original filename in path: {{ '{authors}/books/<{series}/>{currentFilename}' }}

-

Output: Andy Weir/books/project_hail_mary_final.epub

-
- -
-

Prefix current filename manually: {{ '{authors}/final__{currentFilename}' }}

-

Output: Andy Weir/final__project_hail_mary_final.epub

-
- -
-

Filename preserved, renamed folder: {{ '{title}/source/{currentFilename}' }}

-

Output: Project Hail Mary/source/project_hail_mary_final.epub

-
- -
-

Use current filename with year suffix: {{ '{authors}/{year}__{currentFilename}' }}

-

Output: Andy Weir/2021__project_hail_mary_final.epub

-
- -
-

Fallback with optional + extras folder: {{ '<{series}/>{authors}/extras/{currentFilename}' }}

-

Output: Andy Weir/extras/project_hail_mary_final.epub

-
- -
-

Archive structure using original name: {{ 'archive/<{series}/>{year}/{currentFilename}' }}

-

Output: archive/2021/project_hail_mary_final.epub

-
- -
-

Structured folder + renamed file: {{ '{authors}/<{series}/>{title} ({year}) by {authors}' }}

-

Output: Andy Weir/Project Hail Mary (2021) by Andy Weir.epub

-
-
-
-
-
diff --git a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html index 6735b2bb2..37fb5b716 100644 --- a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html +++ b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.html @@ -130,8 +130,4 @@
-
- -
-
diff --git a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts index 670ee91ef..7e100a35f 100644 --- a/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts +++ b/booklore-ui/src/app/settings/global-preferences/global-preferences.component.ts @@ -14,7 +14,6 @@ import {AppSettingsService} from '../../core/service/app-settings.service'; import {BookService} from '../../book/service/book.service'; import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model'; import {filter, take} from 'rxjs/operators'; -import {FileUploadPatternComponent} from './file-upload-pattern/file-upload-pattern.component'; import {InputText} from 'primeng/inputtext'; @Component({ @@ -28,7 +27,6 @@ import {InputText} from 'primeng/inputtext'; Tooltip, ToggleSwitch, FormsModule, - FileUploadPatternComponent, InputText ], templateUrl: './global-preferences.component.html', diff --git a/booklore-ui/src/app/settings/settings.component.html b/booklore-ui/src/app/settings/settings.component.html index c552f7567..bbe137430 100644 --- a/booklore-ui/src/app/settings/settings.component.html +++ b/booklore-ui/src/app/settings/settings.component.html @@ -22,6 +22,9 @@ Email + + Patterns + Authentication @@ -55,6 +58,9 @@ + + + diff --git a/booklore-ui/src/app/settings/settings.component.ts b/booklore-ui/src/app/settings/settings.component.ts index 821e06621..491d0a4e2 100644 --- a/booklore-ui/src/app/settings/settings.component.ts +++ b/booklore-ui/src/app/settings/settings.component.ts @@ -13,17 +13,19 @@ import {ReaderPreferences} from './reader-preferences/reader-preferences.compone import {MetadataSettingsComponent} from './metadata-settings-component/metadata-settings-component'; import {OpdsSettingsComponent} from './global-preferences/opds-settings/opds-settings.component'; import {DeviceSettingsComponent} from './device-settings-component/device-settings-component'; +import {FileNamingPatternComponent} from './file-naming-pattern/file-naming-pattern.component'; export enum SettingsTab { - ReaderSettings = 'reader-settings', - ViewPreferences = 'view-settings', - DeviceSettings = 'device-settings', - UserManagement = 'user-management', - EmailSettings = 'email-settings', - MetadataSettings = 'metadata-settings', - ApplicationSettings = 'app-settings', - AuthenticationSettings = 'auth-settings', - Opds = 'opds-settings' + ReaderSettings = 'reader', + ViewPreferences = 'view', + DeviceSettings = 'device', + UserManagement = 'user', + EmailSettings = 'email', + NamingPattern = 'naming-pattern', + MetadataSettings = 'metadata', + ApplicationSettings = 'application', + AuthenticationSettings = 'authentication', + Opds = 'opds' } @Component({ @@ -43,7 +45,8 @@ export enum SettingsTab { ReaderPreferences, MetadataSettingsComponent, OpdsSettingsComponent, - DeviceSettingsComponent + DeviceSettingsComponent, + FileNamingPatternComponent ], templateUrl: './settings.component.html', styleUrl: './settings.component.scss'