Gate all file write operations for network storage users (#3231)

This commit is contained in:
acx10
2026-03-07 16:17:00 -07:00
committed by acx10
parent 919657c6fe
commit 36c7185636
22 changed files with 340 additions and 67 deletions
+11 -1
View File
@@ -85,7 +85,7 @@ DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
DB_USER=booklore DB_USER=booklore
DB_PASSWORD=ChangeMe_BookLoreApp_2025! DB_PASSWORD=ChangeMe_BookLoreApp_2025!
# Storage: LOCAL (default) or NETWORK (for NFS/SMB, disables file reorganization) # Storage: LOCAL (default) or NETWORK (disables file operations, see Network Storage section below)
DISK_TYPE=LOCAL DISK_TYPE=LOCAL
# MariaDB # MariaDB
@@ -112,6 +112,7 @@ services:
- DATABASE_URL=${DATABASE_URL} - DATABASE_URL=${DATABASE_URL}
- DATABASE_USERNAME=${DB_USER} - DATABASE_USERNAME=${DB_USER}
- DATABASE_PASSWORD=${DB_PASSWORD} - DATABASE_PASSWORD=${DB_PASSWORD}
- DISK_TYPE=${DISK_TYPE}
depends_on: depends_on:
mariadb: mariadb:
condition: service_healthy condition: service_healthy
@@ -160,6 +161,15 @@ Open **http://localhost:6060**, create your admin account, and start building yo
--- ---
## ⚠️ Network Storage (NAS / NFS / SMB / CIFS)
> [!CAUTION]
> BookLore's file operations (metadata writing, file renaming, file organization) are built for **local file systems only**. Network-attached storage (NAS, NFS, SMB/CIFS mounts, cloud-backed FUSE, etc.) is **unsupported and untested**. Mount options, network latency, caching, and filesystem semantics are all outside BookLore's control and can cause silent file corruption, incomplete writes, missing files, and other unpredictable behavior. **Issues related to network storage will be closed without investigation.**
If your book files live on network storage, set `DISK_TYPE=NETWORK` in your `.env` file. This puts BookLore into **network storage mode**, which disables all file write and reorganization features. Metadata is stored in the database only and your files are never modified. This is the only supported configuration for network storage.
---
## 🎮 Live Demo ## 🎮 Live Demo
See BookLore in action before deploying your own instance. See BookLore in action before deploying your own instance.
@@ -25,6 +25,10 @@ public class AppProperties {
*/ */
private String diskType = "LOCAL"; private String diskType = "LOCAL";
public boolean isLocalStorage() {
return "LOCAL".equalsIgnoreCase(diskType);
}
@Getter @Getter
@Setter @Setter
public static class RemoteAuth { public static class RemoteAuth {
@@ -429,11 +429,10 @@ public class FileMoveService {
} }
private void validateLocalStorage() { private void validateLocalStorage() {
String diskType = appProperties.getDiskType(); if (!appProperties.isLocalStorage()) {
if (!"LOCAL".equalsIgnoreCase(diskType)) {
throw new IllegalStateException( throw new IllegalStateException(
"File move operations are only supported on local storage. " + "File move operations are only supported on local storage. " +
"Current disk type is configured as: " + diskType + ". " + "Current disk type is configured as: " + appProperties.getDiskType() + ". " +
"If you are using local storage, set DISK_TYPE=LOCAL in your environment." "If you are using local storage, set DISK_TYPE=LOCAL in your environment."
); );
} }
@@ -1,5 +1,6 @@
package org.booklore.service.metadata; package org.booklore.service.metadata;
import org.booklore.config.AppProperties;
import org.booklore.exception.ApiError; import org.booklore.exception.ApiError;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
import org.booklore.model.entity.AuthorEntity; import org.booklore.model.entity.AuthorEntity;
@@ -42,6 +43,7 @@ public class BookCoverService {
private static final int BATCH_SIZE = 100; private static final int BATCH_SIZE = 100;
private final AppProperties appProperties;
private final BookRepository bookRepository; private final BookRepository bookRepository;
private final NotificationService notificationService; private final NotificationService notificationService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
@@ -540,9 +542,11 @@ public class BookCoverService {
} }
private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) { private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) {
if (!appProperties.isLocalStorage()) {
return;
}
var primaryFile = bookEntity.getPrimaryBookFile(); var primaryFile = bookEntity.getPrimaryBookFile();
if (primaryFile == null) { if (primaryFile == null) {
// Physical book with no files - skip writing cover to file
return; return;
} }
@@ -560,6 +564,9 @@ public class BookCoverService {
} }
private void writeAudiobookCoverToFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) { private void writeAudiobookCoverToFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) {
if (!appProperties.isLocalStorage()) {
return;
}
var audiobookFile = bookEntity.getBookFiles().stream() var audiobookFile = bookEntity.getBookFiles().stream()
.filter(f -> f.getBookType() == BookFileType.AUDIOBOOK) .filter(f -> f.getBookType() == BookFileType.AUDIOBOOK)
.findFirst() .findFirst()
@@ -3,6 +3,7 @@ package org.booklore.service.metadata;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.booklore.config.AppProperties;
import org.booklore.model.MetadataClearFlags; import org.booklore.model.MetadataClearFlags;
import org.booklore.model.MetadataUpdateContext; import org.booklore.model.MetadataUpdateContext;
import org.booklore.model.MetadataUpdateWrapper; import org.booklore.model.MetadataUpdateWrapper;
@@ -53,6 +54,7 @@ public class BookMetadataUpdater {
private final ComicTeamRepository comicTeamRepository; private final ComicTeamRepository comicTeamRepository;
private final ComicLocationRepository comicLocationRepository; private final ComicLocationRepository comicLocationRepository;
private final ComicCreatorRepository comicCreatorRepository; private final ComicCreatorRepository comicCreatorRepository;
private final AppProperties appProperties;
private final FileService fileService; private final FileService fileService;
private final MetadataMatchService metadataMatchService; private final MetadataMatchService metadataMatchService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
@@ -123,7 +125,7 @@ public class BookMetadataUpdater {
log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage()); log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage());
} }
if (primaryFile != null && bookType != null && ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate)) { if (appProperties.isLocalStorage() && primaryFile != null && bookType != null && ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate)) {
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> { metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
try { try {
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null; String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
@@ -1,5 +1,6 @@
package org.booklore.service.metadata; package org.booklore.service.metadata;
import org.booklore.config.AppProperties;
import org.booklore.model.dto.FileMoveResult; import org.booklore.model.dto.FileMoveResult;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
import org.booklore.model.entity.*; import org.booklore.model.entity.*;
@@ -25,6 +26,7 @@ import java.util.Optional;
@RequiredArgsConstructor @RequiredArgsConstructor
public class MetadataManagementService { public class MetadataManagementService {
private final AppProperties appProperties;
private final AuthorRepository authorRepository; private final AuthorRepository authorRepository;
private final CategoryRepository categoryRepository; private final CategoryRepository categoryRepository;
private final MoodRepository moodRepository; private final MoodRepository moodRepository;
@@ -61,13 +63,15 @@ public class MetadataManagementService {
var primaryFile = book.getPrimaryBookFile(); var primaryFile = book.getPrimaryBookFile();
BookFileType bookType = primaryFile.getBookType(); BookFileType bookType = primaryFile.getBookType();
Optional<MetadataWriter> writerOpt = metadataWriterFactory.getWriter(bookType); if (appProperties.isLocalStorage()) {
if (writerOpt.isPresent()) { Optional<MetadataWriter> writerOpt = metadataWriterFactory.getWriter(bookType);
File file = book.getFullFilePath().toFile(); if (writerOpt.isPresent()) {
writerOpt.get().saveMetadataToFile(file, metadata, null, null); File file = book.getFullFilePath().toFile();
String newHash = FileFingerprint.generateHash(book.getFullFilePath()); writerOpt.get().saveMetadataToFile(file, metadata, null, null);
primaryFile.setCurrentHash(newHash); String newHash = FileFingerprint.generateHash(book.getFullFilePath());
bookModified = true; primaryFile.setCurrentHash(newHash);
bookModified = true;
}
} }
if (moveFile) { if (moveFile) {
@@ -1,6 +1,7 @@
package org.booklore.service.metadata.sidecar; package org.booklore.service.metadata.sidecar;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.booklore.config.AppProperties;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
import org.booklore.model.dto.settings.SidecarSettings; import org.booklore.model.dto.settings.SidecarSettings;
import org.booklore.model.dto.sidecar.SidecarMetadata; import org.booklore.model.dto.sidecar.SidecarMetadata;
@@ -22,12 +23,14 @@ import java.nio.file.StandardCopyOption;
@Service @Service
public class SidecarMetadataWriter { public class SidecarMetadataWriter {
private final AppProperties appProperties;
private final SidecarMetadataMapper mapper; private final SidecarMetadataMapper mapper;
private final FileService fileService; private final FileService fileService;
private final AppSettingService appSettingService; private final AppSettingService appSettingService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
public SidecarMetadataWriter(SidecarMetadataMapper mapper, FileService fileService, AppSettingService appSettingService) { public SidecarMetadataWriter(AppProperties appProperties, SidecarMetadataMapper mapper, FileService fileService, AppSettingService appSettingService) {
this.appProperties = appProperties;
this.mapper = mapper; this.mapper = mapper;
this.fileService = fileService; this.fileService = fileService;
this.appSettingService = appSettingService; this.appSettingService = appSettingService;
@@ -38,6 +41,9 @@ public class SidecarMetadataWriter {
} }
public void writeSidecarMetadata(BookEntity book) { public void writeSidecarMetadata(BookEntity book) {
if (!appProperties.isLocalStorage()) {
return;
}
if (book == null || book.getMetadata() == null) { if (book == null || book.getMetadata() == null) {
log.warn("Cannot write sidecar metadata: book or metadata is null"); log.warn("Cannot write sidecar metadata: book or metadata is null");
return; return;
@@ -82,7 +82,7 @@ class FileMoveServiceOrderingTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
when(appProperties.getDiskType()).thenReturn("LOCAL"); when(appProperties.isLocalStorage()).thenReturn(true);
doAnswer(invocation -> { doAnswer(invocation -> {
Consumer<TransactionStatus> action = invocation.getArgument(0); Consumer<TransactionStatus> action = invocation.getArgument(0);
@@ -78,7 +78,7 @@ class FileMoveServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
when(appProperties.getDiskType()).thenReturn("LOCAL"); when(appProperties.isLocalStorage()).thenReturn(true);
// Mock simple execution for transaction template // Mock simple execution for transaction template
doAnswer(invocation -> { doAnswer(invocation -> {
@@ -1111,4 +1111,27 @@ class FileMoveServiceTest {
verify(monitoringRegistrationService, times(2)).registerLibrary(any()); verify(monitoringRegistrationService, times(2)).registerLibrary(any());
} }
} }
@Nested
@DisplayName("NetworkStorageGating")
class NetworkStorageGating {
@Test
@DisplayName("bulkMoveFiles throws IllegalStateException on network storage")
void bulkMoveFiles_networkStorage_throwsIllegalStateException() {
when(appProperties.isLocalStorage()).thenReturn(false);
when(appProperties.getDiskType()).thenReturn("NETWORK");
FileMoveRequest request = new FileMoveRequest();
FileMoveRequest.Move move = new FileMoveRequest.Move();
move.setBookId(100L);
move.setTargetLibraryId(2L);
move.setTargetLibraryPathId(20L);
request.setMoves(List.of(move));
org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.bulkMoveFiles(request))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("File move operations are only supported on local storage");
}
}
} }
@@ -1,5 +1,6 @@
package org.booklore.service.metadata; package org.booklore.service.metadata;
import org.booklore.config.AppProperties;
import org.booklore.exception.APIException; import org.booklore.exception.APIException;
import org.booklore.model.dto.settings.AppSettings; import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
@@ -17,6 +18,7 @@ import org.booklore.service.metadata.writer.MetadataWriterFactory;
import org.booklore.service.file.FileFingerprint; import org.booklore.service.file.FileFingerprint;
import org.booklore.util.FileService; import org.booklore.util.FileService;
import org.booklore.util.SecurityContextVirtualThread; import org.booklore.util.SecurityContextVirtualThread;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -37,6 +39,7 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class BookCoverServiceTest { class BookCoverServiceTest {
@Mock private AppProperties appProperties;
@Mock private BookRepository bookRepository; @Mock private BookRepository bookRepository;
@Mock private NotificationService notificationService; @Mock private NotificationService notificationService;
@Mock private AppSettingService appSettingService; @Mock private AppSettingService appSettingService;
@@ -50,6 +53,11 @@ class BookCoverServiceTest {
@InjectMocks @InjectMocks
private BookCoverService service; private BookCoverService service;
@BeforeEach
void setUp() {
lenient().when(appProperties.isLocalStorage()).thenReturn(true);
}
private BookEntity buildBook(long id, boolean coverLocked) { private BookEntity buildBook(long id, boolean coverLocked) {
BookMetadataEntity metadata = BookMetadataEntity.builder() BookMetadataEntity metadata = BookMetadataEntity.builder()
.title("Test Book") .title("Test Book")
@@ -1056,4 +1064,45 @@ class BookCoverServiceTest {
verify(coverImageGenerator).generateCover(eq("Test Book"), argThat(s -> s.contains("Alice") && s.contains("Bob"))); verify(coverImageGenerator).generateCover(eq("Test Book"), argThat(s -> s.contains("Alice") && s.contains("Bob")));
} }
} }
@Nested
class NetworkStorageGating {
@Test
void writeCoverToBookFile_networkStorage_skipsFileWrite() {
when(appProperties.isLocalStorage()).thenReturn(false);
BookEntity book = buildBook(1L, false);
BookFileEntity bookFile = BookFileEntity.builder()
.bookType(BookFileType.EPUB)
.isBookFormat(true)
.build();
book.setBookFiles(List.of(bookFile));
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateCoverFromUrl(1L, "https://example.com/cover.jpg");
verify(metadataWriterFactory, never()).getWriter(any());
verify(bookRepository).save(book);
}
@Test
void writeAudiobookCoverToFile_networkStorage_skipsFileWrite() {
when(appProperties.isLocalStorage()).thenReturn(false);
BookEntity book = buildBookWithAudiobookLock(1L, false);
BookFileEntity audiobookFile = BookFileEntity.builder()
.bookType(BookFileType.AUDIOBOOK)
.build();
book.setBookFiles(List.of(audiobookFile));
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(book));
when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of());
service.updateAudiobookCoverFromUrl(1L, "https://example.com/audiobook-cover.jpg");
verify(metadataWriterFactory, never()).getWriter(any());
verify(bookRepository).save(book);
}
}
} }
@@ -1,5 +1,6 @@
package org.booklore.service.metadata; package org.booklore.service.metadata;
import org.booklore.config.AppProperties;
import org.booklore.model.MetadataClearFlags; import org.booklore.model.MetadataClearFlags;
import org.booklore.model.MetadataUpdateContext; import org.booklore.model.MetadataUpdateContext;
import org.booklore.model.MetadataUpdateWrapper; import org.booklore.model.MetadataUpdateWrapper;
@@ -38,6 +39,7 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class BookMetadataUpdaterTest { class BookMetadataUpdaterTest {
@Mock private AppProperties appProperties;
@Mock private AuthorRepository authorRepository; @Mock private AuthorRepository authorRepository;
@Mock private CategoryRepository categoryRepository; @Mock private CategoryRepository categoryRepository;
@Mock private MoodRepository moodRepository; @Mock private MoodRepository moodRepository;
@@ -64,6 +66,7 @@ class BookMetadataUpdaterTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
lenient().when(appProperties.isLocalStorage()).thenReturn(true);
metadataEntity = BookMetadataEntity.builder() metadataEntity = BookMetadataEntity.builder()
.bookId(1L) .bookId(1L)
.title("Original Title") .title("Original Title")
@@ -1842,4 +1845,32 @@ class BookMetadataUpdaterTest {
} }
} }
} }
@Nested
class NetworkStorageGating {
@Test
void updateBookMetadata_networkStorage_skipsFileWrite() {
when(appProperties.isLocalStorage()).thenReturn(false);
BookFileEntity bookFile = BookFileEntity.builder()
.bookType(BookFileType.EPUB)
.isBookFormat(true)
.build();
bookEntity.setBookFiles(new ArrayList<>(List.of(bookFile)));
BookMetadata newMeta = BookMetadata.builder().title("New Title").build();
MetadataUpdateContext context = buildContext(newMeta, MetadataReplaceMode.REPLACE_ALL);
try (MockedStatic<MetadataChangeDetector> mcd = mockStatic(MetadataChangeDetector.class)) {
mockSettingsAndChangeDetector(mcd, true, true);
mcd.when(() -> MetadataChangeDetector.hasValueChangesForFileWrite(any(), any(), any())).thenReturn(true);
updater.setBookMetadata(context);
verify(metadataWriterFactory, never()).getWriter(any());
verify(bookRepository).save(bookEntity);
}
}
}
} }
@@ -1,5 +1,6 @@
package org.booklore.service.metadata; package org.booklore.service.metadata;
import org.booklore.config.AppProperties;
import org.booklore.model.dto.FileMoveResult; import org.booklore.model.dto.FileMoveResult;
import org.booklore.model.dto.settings.AppSettings; import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.dto.settings.MetadataPersistenceSettings;
@@ -32,6 +33,7 @@ import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class MetadataManagementServiceTest { class MetadataManagementServiceTest {
@Mock private AppProperties appProperties;
@Mock private AuthorRepository authorRepository; @Mock private AuthorRepository authorRepository;
@Mock private CategoryRepository categoryRepository; @Mock private CategoryRepository categoryRepository;
@Mock private MoodRepository moodRepository; @Mock private MoodRepository moodRepository;
@@ -47,6 +49,7 @@ class MetadataManagementServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
lenient().when(appProperties.isLocalStorage()).thenReturn(true);
lenient().when(appSettingService.getAppSettings()).thenReturn( lenient().when(appSettingService.getAppSettings()).thenReturn(
AppSettings.builder() AppSettings.builder()
.metadataPersistenceSettings(MetadataPersistenceSettings.builder() .metadataPersistenceSettings(MetadataPersistenceSettings.builder()
@@ -551,4 +554,42 @@ class MetadataManagementServiceTest {
java.nio.file.Files.deleteIfExists(subDir); java.nio.file.Files.deleteIfExists(subDir);
java.nio.file.Files.deleteIfExists(tempDir); java.nio.file.Files.deleteIfExists(tempDir);
} }
@Test
void consolidateAuthors_networkStorage_skipsFileWrite() {
when(appProperties.isLocalStorage()).thenReturn(false);
AuthorEntity oldAuthor = AuthorEntity.builder().id(1L).name("Old").build();
AuthorEntity targetAuthor = AuthorEntity.builder().id(2L).name("Target").build();
when(authorRepository.findByNameIgnoreCase("Target")).thenReturn(Optional.of(targetAuthor));
when(authorRepository.save(targetAuthor)).thenReturn(targetAuthor);
when(authorRepository.findByNameIgnoreCase("Old")).thenReturn(Optional.of(oldAuthor));
BookFileEntity bookFile = BookFileEntity.builder()
.fileName("test.epub")
.fileSubPath("sub")
.bookType(BookFileType.EPUB)
.isBookFormat(true)
.build();
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/fake/path");
BookEntity book = BookEntity.builder()
.id(1L)
.bookFiles(new ArrayList<>(List.of(bookFile)))
.libraryPath(libraryPath)
.build();
BookMetadataEntity metadata = BookMetadataEntity.builder()
.authors(new ArrayList<>(List.of(oldAuthor)))
.book(book)
.build();
book.setMetadata(metadata);
when(bookMetadataRepository.findAllByAuthorsContaining(oldAuthor)).thenReturn(List.of(metadata));
service.consolidateMetadata(MergeMetadataType.authors, List.of("Target"), List.of("Old"));
verify(metadataWriterFactory, never()).getWriter(any());
verify(authorRepository).delete(oldAuthor);
}
} }
@@ -0,0 +1,54 @@
package org.booklore.service.metadata.sidecar;
import org.booklore.config.AppProperties;
import org.booklore.model.entity.BookEntity;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SidecarMetadataWriterTest {
@Mock
private AppProperties appProperties;
@Mock
private SidecarMetadataMapper mapper;
@Mock
private FileService fileService;
@Mock
private AppSettingService appSettingService;
@InjectMocks
private SidecarMetadataWriter sidecarMetadataWriter;
@BeforeEach
void setUp() {
lenient().when(appProperties.isLocalStorage()).thenReturn(true);
}
@Test
void writeSidecarMetadata_networkStorage_skipsWrite() {
when(appProperties.isLocalStorage()).thenReturn(false);
sidecarMetadataWriter.writeSidecarMetadata(new BookEntity());
verify(appSettingService, never()).getAppSettings();
}
@Test
void writeSidecarMetadata_localStorage_proceedsNormally() {
sidecarMetadataWriter.writeSidecarMetadata(null);
verify(appProperties).isLocalStorage();
}
}
@@ -37,7 +37,7 @@
{{ t('tabSearch') }} {{ t('tabSearch') }}
</p-tab> </p-tab>
} }
@if ((admin || canEditMetadata) && !isPhysical) { @if ((admin || canEditMetadata) && !isPhysical && isLocalStorage) {
<p-tab value="sidecar"> <p-tab value="sidecar">
<i [class]="'pi pi-file'"></i> <i [class]="'pi pi-file'"></i>
{{ t('tabSidecar') }} {{ t('tabSidecar') }}
@@ -63,7 +63,7 @@
<app-metadata-searcher [book$]="book$" [isActiveTab]="tab === 'match'"></app-metadata-searcher> <app-metadata-searcher [book$]="book$" [isActiveTab]="tab === 'match'"></app-metadata-searcher>
</p-tabpanel> </p-tabpanel>
} }
@if ((admin || canEditMetadata) && !isPhysical) { @if ((admin || canEditMetadata) && !isPhysical && isLocalStorage) {
<p-tabpanel value="sidecar"> <p-tabpanel value="sidecar">
<app-sidecar-viewer [book$]="book$"></app-sidecar-viewer> <app-sidecar-viewer [book$]="book$"></app-sidecar-viewer>
</p-tabpanel> </p-tabpanel>
@@ -50,6 +50,7 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
canEditMetadata: boolean = false; canEditMetadata: boolean = false;
admin: boolean = false; admin: boolean = false;
isPhysical: boolean = false; isPhysical: boolean = false;
isLocalStorage: boolean = true;
private appSettings$ = this.appSettingsService.appSettings$; private appSettings$ = this.appSettingsService.appSettings$;
private currentBookId$ = new BehaviorSubject<number | null>(null); private currentBookId$ = new BehaviorSubject<number | null>(null);
@@ -145,6 +146,16 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false; this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false;
this.admin = userState.user?.permissions?.admin ?? false; this.admin = userState.user?.permissions?.admin ?? false;
}); });
this.appSettings$
.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
)
.subscribe(settings => {
this.isLocalStorage = settings!.diskType === 'LOCAL';
});
} }
private fetchBookRecommendationsIfNeeded(bookId: number): void { private fetchBookRecommendationsIfNeeded(bookId: number): void {
@@ -66,30 +66,32 @@
</span> </span>
} }
</div> </div>
<div class="sidecar-actions"> @if (isLocalStorage) {
<p-button <div class="sidecar-actions">
icon="pi pi-upload" <p-button
[label]="t('libraryOverrides.exportSidecar')" icon="pi pi-upload"
size="small" [label]="t('libraryOverrides.exportSidecar')"
severity="secondary" size="small"
[outlined]="true" severity="secondary"
[loading]="isSidecarExporting(library.id!)" [outlined]="true"
(onClick)="exportSidecarForLibrary(library.id!, $event)" [loading]="isSidecarExporting(library.id!)"
[pTooltip]="t('libraryOverrides.exportTooltip')" (onClick)="exportSidecarForLibrary(library.id!, $event)"
tooltipPosition="top" [pTooltip]="t('libraryOverrides.exportTooltip')"
/> tooltipPosition="top"
<p-button />
icon="pi pi-download" <p-button
[label]="t('libraryOverrides.importSidecar')" icon="pi pi-download"
size="small" [label]="t('libraryOverrides.importSidecar')"
severity="secondary" size="small"
[outlined]="true" severity="secondary"
[loading]="isSidecarImporting(library.id!)" [outlined]="true"
(onClick)="importSidecarForLibrary(library.id!, $event)" [loading]="isSidecarImporting(library.id!)"
[pTooltip]="t('libraryOverrides.importTooltip')" (onClick)="importSidecarForLibrary(library.id!, $event)"
tooltipPosition="top" [pTooltip]="t('libraryOverrides.importTooltip')"
/> tooltipPosition="top"
</div> />
</div>
}
</div> </div>
</p-accordion-header> </p-accordion-header>
<p-accordion-content> <p-accordion-content>
@@ -41,11 +41,13 @@ export class LibraryMetadataSettingsComponent implements OnInit {
activePanel: number | null = null; activePanel: number | null = null;
sidecarExporting: Record<number, boolean> = {}; sidecarExporting: Record<number, boolean> = {};
sidecarImporting: Record<number, boolean> = {}; sidecarImporting: Record<number, boolean> = {};
isLocalStorage = true;
private cachedDefaultOptions: Record<number, MetadataRefreshOptions> = {}; private cachedDefaultOptions: Record<number, MetadataRefreshOptions> = {};
ngOnInit() { ngOnInit() {
this.appSettingsService.appSettings$.subscribe(appSettings => { this.appSettingsService.appSettings$.subscribe(appSettings => {
if (appSettings) { if (appSettings) {
this.isLocalStorage = appSettings.diskType === 'LOCAL';
this.defaultMetadataOptions = appSettings.defaultMetadataRefreshOptions; this.defaultMetadataOptions = appSettings.defaultMetadataRefreshOptions;
this.cachedDefaultOptions = {}; this.cachedDefaultOptions = {};
this.initializeLibraryOptions(appSettings); this.initializeLibraryOptions(appSettings);
@@ -10,27 +10,39 @@
</p> </p>
</div> </div>
<div class="section-notice"> @if (isNetworkStorage) {
<div class="warning-notice"> <div class="section-notice">
<i class="pi pi-exclamation-triangle"></i> <div class="info-notice">
<div> <i class="pi pi-lock"></i>
<strong>{{ t('networkWarningTitle') }}</strong> {{ t('networkWarning') }} <div>
<strong>{{ t('networkModeTitle') }}</strong> {{ t('networkModeDesc') }}
</div>
</div> </div>
</div> </div>
<div class="info-notice unsupported-formats-note"> } @else {
<i class="pi pi-info-circle"></i> <div class="section-notice">
<div> <div class="warning-notice">
<strong>Note:</strong> <span [innerHTML]="t('unsupportedNote')"></span> <i class="pi pi-exclamation-triangle"></i>
<div>
<strong>{{ t('networkWarningTitle') }}</strong> {{ t('networkWarning') }}
</div>
</div>
<div class="info-notice unsupported-formats-note">
<i class="pi pi-info-circle"></i>
<div>
<strong>Note:</strong> <span [innerHTML]="t('unsupportedNote')"></span>
</div>
</div> </div>
</div> </div>
</div> }
<div class="section-body"> <div class="section-body" [class.network-disabled]="isNetworkStorage">
<div class="setting-item"> <div class="setting-item">
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.saveToOriginalFile.epub.enabled" [ngModel]="metadataPersistence.saveToOriginalFile.epub.enabled"
(onChange)="onSaveToOriginalFileToggle('epub')"> (onChange)="onSaveToOriginalFileToggle('epub')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writeEpub') }}</label> <label class="setting-label">{{ t('writeEpub') }}</label>
</div> </div>
@@ -61,7 +73,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.saveToOriginalFile.cbx.enabled" [ngModel]="metadataPersistence.saveToOriginalFile.cbx.enabled"
(onChange)="onSaveToOriginalFileToggle('cbx')"> (onChange)="onSaveToOriginalFileToggle('cbx')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writeCbx') }}</label> <label class="setting-label">{{ t('writeCbx') }}</label>
</div> </div>
@@ -92,7 +105,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.saveToOriginalFile.pdf.enabled" [ngModel]="metadataPersistence.saveToOriginalFile.pdf.enabled"
(onChange)="onSaveToOriginalFileToggle('pdf')"> (onChange)="onSaveToOriginalFileToggle('pdf')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writePdf') }}</label> <label class="setting-label">{{ t('writePdf') }}</label>
</div> </div>
@@ -126,7 +140,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.saveToOriginalFile.audiobook.enabled" [ngModel]="metadataPersistence.saveToOriginalFile.audiobook.enabled"
(onChange)="onSaveToOriginalFileToggle('audiobook')"> (onChange)="onSaveToOriginalFileToggle('audiobook')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writeAudiobook') }}</label> <label class="setting-label">{{ t('writeAudiobook') }}</label>
</div> </div>
@@ -156,7 +171,7 @@
} }
</div> </div>
@if ((appSettings$ | async)?.diskType === 'LOCAL') { @if (!isNetworkStorage) {
<div class="setting-item"> <div class="setting-item">
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
@@ -180,12 +195,13 @@
</p> </p>
</div> </div>
<div class="section-body"> <div class="section-body" [class.network-disabled]="isNetworkStorage">
<div class="setting-item"> <div class="setting-item">
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.sidecarSettings?.enabled" [ngModel]="metadataPersistence.sidecarSettings?.enabled"
(onChange)="onSidecarToggle('enabled')"> (onChange)="onSidecarToggle('enabled')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('enableSidecar') }}</label> <label class="setting-label">{{ t('enableSidecar') }}</label>
</div> </div>
@@ -197,7 +213,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.sidecarSettings?.writeOnUpdate" [ngModel]="metadataPersistence.sidecarSettings?.writeOnUpdate"
(onChange)="onSidecarToggle('writeOnUpdate')"> (onChange)="onSidecarToggle('writeOnUpdate')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writeOnUpdate') }}</label> <label class="setting-label">{{ t('writeOnUpdate') }}</label>
</div> </div>
@@ -208,7 +225,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.sidecarSettings?.writeOnScan" [ngModel]="metadataPersistence.sidecarSettings?.writeOnScan"
(onChange)="onSidecarToggle('writeOnScan')"> (onChange)="onSidecarToggle('writeOnScan')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('writeOnScan') }}</label> <label class="setting-label">{{ t('writeOnScan') }}</label>
</div> </div>
@@ -219,7 +237,8 @@
<div class="setting-header"> <div class="setting-header">
<p-toggleswitch <p-toggleswitch
[ngModel]="metadataPersistence.sidecarSettings?.includeCoverFile" [ngModel]="metadataPersistence.sidecarSettings?.includeCoverFile"
(onChange)="onSidecarToggle('includeCoverFile')"> (onChange)="onSidecarToggle('includeCoverFile')"
[disabled]="isNetworkStorage">
</p-toggleswitch> </p-toggleswitch>
<label class="setting-label">{{ t('includeCover') }}</label> <label class="setting-label">{{ t('includeCover') }}</label>
</div> </div>
@@ -62,6 +62,11 @@
@include settings.settings-filesize-input; @include settings.settings-filesize-input;
} }
.network-disabled {
opacity: 0.5;
pointer-events: none;
}
.sidecar-section-header { .sidecar-section-header {
margin-top: 1.5rem; margin-top: 1.5rem;
padding-top: 1.5rem; padding-top: 1.5rem;
@@ -4,10 +4,8 @@ import {FormsModule} from '@angular/forms';
import {AppSettingKey, AppSettings, MetadataPersistenceSettings, SaveToOriginalFileSettings, SidecarSettings} from '../../../../shared/model/app-settings.model'; import {AppSettingKey, AppSettings, MetadataPersistenceSettings, SaveToOriginalFileSettings, SidecarSettings} from '../../../../shared/model/app-settings.model';
import {AppSettingsService} from '../../../../shared/service/app-settings.service'; import {AppSettingsService} from '../../../../shared/service/app-settings.service';
import {SettingsHelperService} from '../../../../shared/service/settings-helper.service'; import {SettingsHelperService} from '../../../../shared/service/settings-helper.service';
import {Observable} from 'rxjs';
import {filter, take} from 'rxjs/operators'; import {filter, take} from 'rxjs/operators';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {AsyncPipe} from '@angular/common';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco'; import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@Component({ @Component({
@@ -16,7 +14,6 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
ToggleSwitch, ToggleSwitch,
FormsModule, FormsModule,
Tooltip, Tooltip,
AsyncPipe,
TranslocoDirective TranslocoDirective
], ],
templateUrl: './metadata-persistence-settings-component.html', templateUrl: './metadata-persistence-settings-component.html',
@@ -53,11 +50,13 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
} }
}; };
isNetworkStorage = false;
private readonly appSettingsService = inject(AppSettingsService); private readonly appSettingsService = inject(AppSettingsService);
private readonly settingsHelper = inject(SettingsHelperService); private readonly settingsHelper = inject(SettingsHelperService);
private t = inject(TranslocoService); private t = inject(TranslocoService);
readonly appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$; private readonly appSettings$ = this.appSettingsService.appSettings$;
ngOnInit(): void { ngOnInit(): void {
this.loadSettings(); this.loadSettings();
@@ -101,6 +100,7 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
} }
private initializeSettings(settings: AppSettings): void { private initializeSettings(settings: AppSettings): void {
this.isNetworkStorage = settings.diskType !== 'LOCAL';
if (settings.metadataPersistenceSettings) { if (settings.metadataPersistenceSettings) {
const persistenceSettings = settings.metadataPersistenceSettings; const persistenceSettings = settings.metadataPersistenceSettings;
@@ -12,6 +12,8 @@
"sectionDesc": "Configure how metadata is written to original files and how files are moved or renamed when metadata changes.", "sectionDesc": "Configure how metadata is written to original files and how files are moved or renamed when metadata changes.",
"networkWarningTitle": "Network Storage Warning:", "networkWarningTitle": "Network Storage Warning:",
"networkWarning": "These features directly modify and move book files on disk (including rewriting metadata and renaming files). They are designed for local file systems only. Using them on NAS or cloud-backed storage is untested and may lead to file corruption, incomplete writes, or permanent data loss. Github issues related to network storage will not be supported.", "networkWarning": "These features directly modify and move book files on disk (including rewriting metadata and renaming files). They are designed for local file systems only. Using them on NAS or cloud-backed storage is untested and may lead to file corruption, incomplete writes, or permanent data loss. Github issues related to network storage will not be supported.",
"networkModeTitle": "Network Storage Mode Active:",
"networkModeDesc": "This instance is configured for network storage (DISK_TYPE=NETWORK). All file write and reorganization features are disabled. Metadata is stored in the database only and your book files are never modified.",
"unsupportedNote": "Writing metadata is <b>not supported</b> for FB2, AZW3, and MOBI formats.", "unsupportedNote": "Writing metadata is <b>not supported</b> for FB2, AZW3, and MOBI formats.",
"writeEpub": "Write Metadata to EPUB", "writeEpub": "Write Metadata to EPUB",
"writeEpubDesc": "Write metadata directly into EPUB files when editing book information.", "writeEpubDesc": "Write metadata directly into EPUB files when editing book information.",
@@ -12,6 +12,8 @@
"sectionDesc": "Configura cómo se escriben los metadatos en los archivos originales y cómo se mueven o renombran los archivos cuando cambian los metadatos.", "sectionDesc": "Configura cómo se escriben los metadatos en los archivos originales y cómo se mueven o renombran los archivos cuando cambian los metadatos.",
"networkWarningTitle": "Advertencia de almacenamiento en red:", "networkWarningTitle": "Advertencia de almacenamiento en red:",
"networkWarning": "Estas funciones modifican y mueven directamente los archivos de libros en el disco (incluyendo la reescritura de metadatos y el renombramiento de archivos). Están diseñadas solo para sistemas de archivos locales. Usarlas en NAS o almacenamiento en la nube no está probado y puede provocar corrupción de archivos, escrituras incompletas o pérdida permanente de datos. No se darán soporte a problemas de Github relacionados con almacenamiento en red.", "networkWarning": "Estas funciones modifican y mueven directamente los archivos de libros en el disco (incluyendo la reescritura de metadatos y el renombramiento de archivos). Están diseñadas solo para sistemas de archivos locales. Usarlas en NAS o almacenamiento en la nube no está probado y puede provocar corrupción de archivos, escrituras incompletas o pérdida permanente de datos. No se darán soporte a problemas de Github relacionados con almacenamiento en red.",
"networkModeTitle": "Modo de almacenamiento en red activo:",
"networkModeDesc": "Esta instancia está configurada para almacenamiento en red (DISK_TYPE=NETWORK). Todas las funciones de escritura y reorganización de archivos están deshabilitadas. Los metadatos se almacenan solo en la base de datos y los archivos de libros nunca se modifican.",
"unsupportedNote": "La escritura de metadatos <b>no es compatible</b> con los formatos FB2, AZW3 y MOBI.", "unsupportedNote": "La escritura de metadatos <b>no es compatible</b> con los formatos FB2, AZW3 y MOBI.",
"writeEpub": "Escribir metadatos en EPUB", "writeEpub": "Escribir metadatos en EPUB",
"writeEpubDesc": "Escribir metadatos directamente en archivos EPUB al editar información del libro.", "writeEpubDesc": "Escribir metadatos directamente en archivos EPUB al editar información del libro.",