Merge pull request #887 from booklore-app/develop
Merge Develop into Master for release
This commit is contained in:
+11
-10
@@ -2,47 +2,48 @@ name-template: 'v$NEXT_PATCH_VERSION 🌟'
|
||||
tag-template: 'v$NEXT_PATCH_VERSION'
|
||||
|
||||
categories:
|
||||
- title: '### 🚀 New Features'
|
||||
- title: '🚀 New Features'
|
||||
labels:
|
||||
- 'feature'
|
||||
- title: '### ✨ Enhancements'
|
||||
- title: '✨ Enhancements'
|
||||
labels:
|
||||
- 'enhancement'
|
||||
- title: '### 🐛 Bug Fixes'
|
||||
- title: '🐛 Bug Fixes'
|
||||
labels:
|
||||
- 'bug'
|
||||
- 'fix'
|
||||
- title: '### 🛠️ Refactoring & Maintenance'
|
||||
- title: '🛠️ Refactoring & Maintenance'
|
||||
labels:
|
||||
- 'refactor'
|
||||
- 'cleanup'
|
||||
- 'chore'
|
||||
- title: '### 📦 Dependencies'
|
||||
- title: '📦 Dependencies'
|
||||
labels:
|
||||
- 'dependencies'
|
||||
- 'dependency'
|
||||
- 'deps'
|
||||
- title: '### ⚙️ CI/CD'
|
||||
- title: '⚙️ CI/CD'
|
||||
labels:
|
||||
- 'ci'
|
||||
- 'cd'
|
||||
- 'workflow'
|
||||
- title: '### 📖 Documentation'
|
||||
- title: '📖 Documentation'
|
||||
labels:
|
||||
- 'docs'
|
||||
- 'documentation'
|
||||
- title: '### 🧪 Experimental'
|
||||
- title: '🧪 Experimental'
|
||||
labels:
|
||||
- 'exploration'
|
||||
- 'experimental'
|
||||
|
||||
exclude-labels:
|
||||
- 'skip changelog'
|
||||
|
||||
change-template: '- $TITLE (#$NUMBER) by @$AUTHOR'
|
||||
|
||||
template: |
|
||||
## 🌟 What's New in v$NEXT_PATCH_VERSION
|
||||
|
||||
Welcome to another exciting release of Booklore! 📚✨
|
||||
|
||||
$CHANGES
|
||||
|
||||
### 🐳 Docker Images
|
||||
|
||||
-1
@@ -7,5 +7,4 @@ import java.util.Set;
|
||||
@Data
|
||||
public class FileMoveRequest {
|
||||
private Set<Long> bookIds;
|
||||
private String pattern;
|
||||
}
|
||||
|
||||
+3
-1
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.progress.PdfProgress;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import java.time.Instant;
|
||||
|
||||
@Data
|
||||
public class ReadProgressRequest {
|
||||
@@ -14,8 +15,9 @@ public class ReadProgressRequest {
|
||||
private EpubProgress epubProgress;
|
||||
private PdfProgress pdfProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private Instant dateFinished;
|
||||
|
||||
@AssertTrue(message = "Either epubProgress or pdfProgress must be provided")
|
||||
@AssertTrue(message = "At least one progress field must be provided")
|
||||
public boolean isProgressValid() {
|
||||
return epubProgress != null || pdfProgress != null || cbxProgress != null;
|
||||
}
|
||||
|
||||
-1
@@ -17,7 +17,6 @@ public class AppSettings {
|
||||
private boolean similarBookRecommendation;
|
||||
private boolean opdsServerEnabled;
|
||||
private String uploadPattern;
|
||||
private String movePattern;
|
||||
private Integer cbxCacheSizeInMb;
|
||||
private Integer pdfCacheSizeInMb;
|
||||
private Integer maxFileUploadSizeInMb;
|
||||
|
||||
@@ -312,6 +312,9 @@ public class BookService {
|
||||
userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
|
||||
userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
|
||||
}
|
||||
if (request.getDateFinished() != null) {
|
||||
userBookProgress.setDateFinished(request.getDateFinished());
|
||||
}
|
||||
userBookProgressRepository.save(userBookProgress);
|
||||
}
|
||||
|
||||
@@ -334,7 +337,7 @@ public class BookService {
|
||||
progress.setUser(userEntity);
|
||||
progress.setBook(book);
|
||||
progress.setReadStatus(readStatus);
|
||||
|
||||
|
||||
// Set dateFinished when status is READ, clear it otherwise
|
||||
if (readStatus == ReadStatus.READ) {
|
||||
progress.setDateFinished(Instant.now());
|
||||
|
||||
+1
-2
@@ -73,8 +73,7 @@ public class AppSettingService {
|
||||
|
||||
builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{currentFilename}"));
|
||||
builder.movePattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MOVE_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>"));
|
||||
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>"));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
|
||||
builder.oidcEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
|
||||
|
||||
+196
-127
@@ -4,10 +4,14 @@ import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
@@ -31,116 +35,175 @@ public class FileMoveService {
|
||||
private final NotificationService notificationService;
|
||||
private final LibraryService libraryService;
|
||||
private final MonitoringService monitoringService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void moveFiles(FileMoveRequest request) {
|
||||
Set<Long> bookIds = request.getBookIds();
|
||||
String pattern = request.getPattern();
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
String defaultPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
|
||||
log.info("Starting file move for {} books using pattern: '{}'", books.size(), pattern);
|
||||
log.info("Starting file move for {} books", books.size());
|
||||
|
||||
Set<Long> libraryIds = new HashSet<>();
|
||||
List<Book> updatedBooks = new ArrayList<>();
|
||||
boolean didPause = false;
|
||||
|
||||
if (!monitoringService.isPaused()) {
|
||||
monitoringService.pauseMonitoring();
|
||||
didPause = true;
|
||||
}
|
||||
boolean didPause = pauseMonitoringIfNeeded();
|
||||
|
||||
try {
|
||||
for (BookEntity book : books) {
|
||||
if (book.getMetadata() == null) continue;
|
||||
|
||||
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null
|
||||
|| book.getFileSubPath() == null || book.getFileName() == null) {
|
||||
log.error("Missing required path components for book id {}. Skipping.", book.getId());
|
||||
continue;
|
||||
}
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
if (!Files.exists(oldFilePath)) {
|
||||
log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle());
|
||||
|
||||
String newRelativePathStr = generatePathFromPattern(book, pattern);
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
Path newFilePath = libraryRoot.resolve(newRelativePathStr).normalize();
|
||||
|
||||
if (oldFilePath.equals(newFilePath)) {
|
||||
log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId());
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
if (newFilePath.getParent() != null) {
|
||||
Files.createDirectories(newFilePath.getParent());
|
||||
}
|
||||
|
||||
log.info("Moving file from {} to {}", oldFilePath, newFilePath);
|
||||
Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
|
||||
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
|
||||
|
||||
book.setFileSubPath(newFileSubPath);
|
||||
book.setFileName(newFileName);
|
||||
bookRepository.save(book);
|
||||
|
||||
updatedBooks.add(bookMapper.toBook(book));
|
||||
log.info("Updated book id {} with new path", book.getId());
|
||||
|
||||
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
|
||||
|
||||
if (book.getLibraryPath().getLibrary().getId() != null) {
|
||||
libraryIds.add(book.getLibraryPath().getLibrary().getId());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
processBookMove(book, defaultPattern, updatedBooks, libraryIds);
|
||||
}
|
||||
|
||||
log.info("Completed file move for {} books.", books.size());
|
||||
|
||||
if (!updatedBooks.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
|
||||
}
|
||||
|
||||
for (Long libraryId : libraryIds) {
|
||||
try {
|
||||
libraryService.rescanLibrary(libraryId);
|
||||
log.info("Rescanned library id {} after file move", libraryId);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
sendUpdateNotifications(updatedBooks);
|
||||
rescanLibraries(libraryIds);
|
||||
|
||||
} finally {
|
||||
if (didPause && !monitoringService.isPaused()) {
|
||||
log.info("Monitoring already resumed by another thread.");
|
||||
} else if (didPause) {
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
Thread.sleep(5_000);
|
||||
monitoringService.resumeMonitoring();
|
||||
log.info("Monitoring resumed after 5s delay");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted while delaying resume of monitoring");
|
||||
}
|
||||
});
|
||||
resumeMonitoringWithDelay(didPause);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean pauseMonitoringIfNeeded() {
|
||||
if (!monitoringService.isPaused()) {
|
||||
monitoringService.pauseMonitoring();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void processBookMove(BookEntity book, String defaultPattern, List<Book> updatedBooks, Set<Long> libraryIds) {
|
||||
if (book.getMetadata() == null) return;
|
||||
|
||||
String pattern = getFileNamingPattern(book, defaultPattern);
|
||||
if (pattern == null) return;
|
||||
|
||||
if (!hasRequiredPathComponents(book)) return;
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
if (!Files.exists(oldFilePath)) {
|
||||
log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle());
|
||||
|
||||
Path newFilePath = generateNewFilePath(book, pattern);
|
||||
if (oldFilePath.equals(newFilePath)) {
|
||||
log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
moveFileAndUpdateBook(book, oldFilePath, newFilePath, updatedBooks, libraryIds);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getFileNamingPattern(BookEntity book, String defaultPattern) {
|
||||
if (book.getLibraryPath() == null || book.getLibraryPath().getLibrary() == null) {
|
||||
log.error("Book id {} has no library associated. Skipping.", book.getId());
|
||||
return null;
|
||||
}
|
||||
LibraryEntity library = book.getLibraryPath().getLibrary();
|
||||
String pattern = library.getFileNamingPattern();
|
||||
if (pattern == null || pattern.trim().isEmpty()) {
|
||||
pattern = defaultPattern;
|
||||
log.info("Using default pattern for library {} as no custom pattern is set", library.getName());
|
||||
}
|
||||
if (pattern == null || pattern.trim().isEmpty()) {
|
||||
log.error("No file naming pattern available for book id {}. Skipping.", book.getId());
|
||||
return null;
|
||||
}
|
||||
|
||||
return pattern;
|
||||
}
|
||||
|
||||
private boolean hasRequiredPathComponents(BookEntity book) {
|
||||
if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null ||
|
||||
book.getFileSubPath() == null || book.getFileName() == null) {
|
||||
log.error("Missing required path components for book id {}. Skipping.", book.getId());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Path generateNewFilePath(BookEntity book, String pattern) {
|
||||
String newRelativePathStr = generatePathFromPattern(book, pattern);
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
return libraryRoot.resolve(newRelativePathStr).normalize();
|
||||
}
|
||||
|
||||
private void moveFileAndUpdateBook(BookEntity book, Path oldFilePath, Path newFilePath,
|
||||
List<Book> updatedBooks, Set<Long> libraryIds) throws IOException {
|
||||
if (newFilePath.getParent() != null) {
|
||||
Files.createDirectories(newFilePath.getParent());
|
||||
}
|
||||
|
||||
log.info("Moving file from {} to {}", oldFilePath, newFilePath);
|
||||
Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
updateBookPaths(book, newFilePath);
|
||||
bookRepository.save(book);
|
||||
updatedBooks.add(bookMapper.toBook(book));
|
||||
|
||||
log.info("Updated book id {} with new path", book.getId());
|
||||
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot));
|
||||
|
||||
if (book.getLibraryPath().getLibrary().getId() != null) {
|
||||
libraryIds.add(book.getLibraryPath().getLibrary().getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateBookPaths(BookEntity book, Path newFilePath) {
|
||||
String newFileName = newFilePath.getFileName().toString();
|
||||
Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent());
|
||||
String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/');
|
||||
|
||||
book.setFileSubPath(newFileSubPath);
|
||||
book.setFileName(newFileName);
|
||||
}
|
||||
|
||||
private void sendUpdateNotifications(List<Book> updatedBooks) {
|
||||
if (!updatedBooks.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks);
|
||||
}
|
||||
}
|
||||
|
||||
private void rescanLibraries(Set<Long> libraryIds) {
|
||||
for (Long libraryId : libraryIds) {
|
||||
try {
|
||||
libraryService.rescanLibrary(libraryId);
|
||||
log.info("Rescanned library id {} after file move", libraryId);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void resumeMonitoringWithDelay(boolean didPause) {
|
||||
if (didPause && !monitoringService.isPaused()) {
|
||||
log.info("Monitoring already resumed by another thread.");
|
||||
} else if (didPause) {
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
Thread.sleep(5_000);
|
||||
monitoringService.resumeMonitoring();
|
||||
log.info("Monitoring resumed after 5s delay");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.warn("Interrupted while delaying resume of monitoring");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public String generatePathFromPattern(BookEntity book, String pattern) {
|
||||
return PathPatternResolver.resolvePattern(book, pattern);
|
||||
}
|
||||
@@ -155,19 +218,7 @@ public class FileMoveService {
|
||||
}
|
||||
|
||||
while (currentDir != null) {
|
||||
boolean isLibraryRoot = false;
|
||||
for (Path root : normalizedRoots) {
|
||||
try {
|
||||
if (Files.isSameFile(root, currentDir)) {
|
||||
isLibraryRoot = true;
|
||||
break;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
||||
}
|
||||
}
|
||||
|
||||
if (isLibraryRoot) {
|
||||
if (isLibraryRoot(currentDir, normalizedRoots)) {
|
||||
log.debug("Reached library root: {}. Stopping cleanup.", currentDir);
|
||||
break;
|
||||
}
|
||||
@@ -178,30 +229,8 @@ public class FileMoveService {
|
||||
break;
|
||||
}
|
||||
|
||||
boolean hasImportantFiles = false;
|
||||
for (File file : files) {
|
||||
if (!ignoredFilenames.contains(file.getName())) {
|
||||
hasImportantFiles = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasImportantFiles) {
|
||||
for (File file : files) {
|
||||
try {
|
||||
Files.delete(file.toPath());
|
||||
log.info("Deleted ignored file: {}", file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
try {
|
||||
Files.delete(currentDir);
|
||||
log.info("Deleted empty directory: {}", currentDir);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
||||
break;
|
||||
}
|
||||
if (hasOnlyIgnoredFiles(files, ignoredFilenames)) {
|
||||
deleteIgnoredFilesAndDirectory(files, currentDir);
|
||||
currentDir = currentDir.getParent();
|
||||
} else {
|
||||
log.debug("Directory {} contains important files. Stopping cleanup.", currentDir);
|
||||
@@ -209,4 +238,44 @@ public class FileMoveService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isLibraryRoot(Path currentDir, Set<Path> normalizedRoots) {
|
||||
for (Path root : normalizedRoots) {
|
||||
try {
|
||||
if (Files.isSameFile(root, currentDir)) {
|
||||
return true;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to compare paths: {} and {}", root, currentDir);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean hasOnlyIgnoredFiles(File[] files, Set<String> ignoredFilenames) {
|
||||
for (File file : files) {
|
||||
if (!ignoredFilenames.contains(file.getName())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) {
|
||||
for (File file : files) {
|
||||
try {
|
||||
Files.delete(file.toPath());
|
||||
log.info("Deleted ignored file: {}", file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete ignored file: {}", file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Files.delete(currentDir);
|
||||
log.info("Deleted empty directory: {}", currentDir);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete directory: {}", currentDir, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+251
-237
@@ -1,14 +1,18 @@
|
||||
package com.adityachandel.booklore;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.request.FileMoveRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.file.FileMoveService;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -26,7 +30,8 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class FileMoveServiceMoveFilesTest {
|
||||
@@ -46,6 +51,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
@Mock
|
||||
private MonitoringService monitoringService;
|
||||
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
|
||||
@Mock
|
||||
private LibraryService libraryService;
|
||||
|
||||
@InjectMocks
|
||||
private FileMoveService fileMoveService;
|
||||
|
||||
@@ -56,6 +67,7 @@ class FileMoveServiceMoveFilesTest {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(42L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern(null)
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
@@ -65,7 +77,8 @@ class FileMoveServiceMoveFilesTest {
|
||||
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.title("Test Book")
|
||||
.authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>()))))
|
||||
.authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>())))
|
||||
)
|
||||
.publishedDate(LocalDate.of(2020, 1, 1))
|
||||
.build();
|
||||
|
||||
@@ -84,44 +97,21 @@ class FileMoveServiceMoveFilesTest {
|
||||
return book;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_successfulMove() throws IOException {
|
||||
String fileName = "testbook.epub";
|
||||
String fileSubPath = "oldfolder";
|
||||
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(1L));
|
||||
request.setPattern("NewFolder/{title}");
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub");
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("Expected the file to be moved to %s", expectedNewPath)
|
||||
.isTrue();
|
||||
|
||||
assertThat(Files.exists(oldFilePath))
|
||||
.withFailMessage("Original file path should no longer exist: %s", oldFilePath)
|
||||
.isFalse();
|
||||
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
Files.deleteIfExists(expectedNewPath.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_skipsNonexistentFile() {
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.title("NoFile")
|
||||
.build();
|
||||
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(43L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern("Moved/{title}")
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString())
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
@@ -133,10 +123,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
.build();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(2L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(2L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -165,10 +157,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
Files.createFile(fakeOldFile);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(3L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(3L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -183,195 +177,21 @@ class FileMoveServiceMoveFilesTest {
|
||||
Files.deleteIfExists(fakeOldFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_handlesEmptyPattern() throws IOException {
|
||||
String fileName = "emptypattern.epub";
|
||||
String fileSubPath = "folder";
|
||||
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(4L))).thenReturn(List.of(book));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(4L));
|
||||
request.setPattern("");
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve(fileName);
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("File should be moved to the original filename path when pattern is empty")
|
||||
.isTrue();
|
||||
|
||||
assertThat(Files.exists(oldFilePath))
|
||||
.withFailMessage("Original file path should no longer exist")
|
||||
.isFalse();
|
||||
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_removesIllegalCharactersFromPath() throws IOException {
|
||||
String fileName = "badchars.epub";
|
||||
String fileSubPath = "folder";
|
||||
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName);
|
||||
book.getMetadata().setTitle("Bad|Title:Test*?");
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(5L))).thenReturn(List.of(book));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(5L));
|
||||
request.setPattern("{title}");
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve("BadTitleTest.epub");
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("Illegal characters should be removed from generated path")
|
||||
.isTrue();
|
||||
|
||||
assertThat(Files.exists(oldFilePath))
|
||||
.withFailMessage("Original file path should no longer exist")
|
||||
.isFalse();
|
||||
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_deletesEmptyOldDirectories() throws IOException {
|
||||
String fileName = "deleteold.epub";
|
||||
String fileSubPath = "folder/emptydir";
|
||||
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(6L))).thenReturn(List.of(book));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(6L));
|
||||
request.setPattern("NewFolder/{title}");
|
||||
|
||||
Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize();
|
||||
assertThat(Files.exists(oldDir))
|
||||
.withFailMessage("Precondition failed: old directory must exist before move")
|
||||
.isTrue();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub");
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("Expected file to be moved to new location")
|
||||
.isTrue();
|
||||
|
||||
assertThat(Files.exists(oldDir))
|
||||
.withFailMessage("Expected old empty directory to be deleted after move")
|
||||
.isFalse();
|
||||
|
||||
assertThat(Files.exists(oldDir.getParent()))
|
||||
.withFailMessage("Expected parent directory of old directory to be deleted if empty")
|
||||
.isFalse();
|
||||
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
Files.deleteIfExists(expectedNewPath.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_keepsOldDirectoryIfNotEmpty() throws IOException {
|
||||
String fileName = "keepold.epub";
|
||||
String fileSubPath = "folder/notempty";
|
||||
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName);
|
||||
|
||||
Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize();
|
||||
Files.createDirectories(oldDir);
|
||||
|
||||
Path otherFile = oldDir.resolve("otherfile.txt");
|
||||
Files.createFile(otherFile);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(7L))).thenReturn(List.of(book));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(7L));
|
||||
request.setPattern("NewFolder/{title}");
|
||||
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub");
|
||||
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("Expected file to be moved to new location")
|
||||
.isTrue();
|
||||
assertThat(Files.exists(oldFilePath))
|
||||
.withFailMessage("Original file path should no longer exist")
|
||||
.isFalse();
|
||||
|
||||
assertThat(Files.exists(oldDir))
|
||||
.withFailMessage("Old directory should remain if it contains other files")
|
||||
.isTrue();
|
||||
assertThat(Files.exists(otherFile))
|
||||
.withFailMessage("Other files in old directory should remain intact")
|
||||
.isTrue();
|
||||
|
||||
Files.deleteIfExists(otherFile);
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
Files.deleteIfExists(expectedNewPath.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_handlesMultipleBooks() throws IOException {
|
||||
BookEntity book1 = createBookWithFile(tempLibraryRoot, "folder1", "book1.epub");
|
||||
book1.getMetadata().setTitle("Book One");
|
||||
|
||||
BookEntity book2 = createBookWithFile(tempLibraryRoot, "folder2", "book2.epub");
|
||||
book2.getMetadata().setTitle("Book Two");
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(8L, 9L))).thenReturn(List.of(book1, book2));
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(8L, 9L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
Path oldPath1 = book1.getFullFilePath();
|
||||
Path oldPath2 = book2.getFullFilePath();
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
Path expectedPath1 = tempLibraryRoot.resolve("Moved").resolve("Book One.epub");
|
||||
Path expectedPath2 = tempLibraryRoot.resolve("Moved").resolve("Book Two.epub");
|
||||
|
||||
assertThat(Files.exists(expectedPath1))
|
||||
.withFailMessage("Expected first book to be moved to new location")
|
||||
.isTrue();
|
||||
assertThat(Files.exists(expectedPath2))
|
||||
.withFailMessage("Expected second book to be moved to new location")
|
||||
.isTrue();
|
||||
|
||||
assertThat(Files.exists(oldPath1))
|
||||
.withFailMessage("Original path for first book should no longer exist")
|
||||
.isFalse();
|
||||
assertThat(Files.exists(oldPath2))
|
||||
.withFailMessage("Original path for second book should no longer exist")
|
||||
.isFalse();
|
||||
|
||||
Files.deleteIfExists(expectedPath1);
|
||||
Files.deleteIfExists(expectedPath2);
|
||||
Files.deleteIfExists(expectedPath1.getParent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_skipsBookWithNullFileName() throws IOException {
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.title("NullFileName")
|
||||
.build();
|
||||
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(46L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern("Moved/{title}")
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString())
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
@@ -383,10 +203,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
.build();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(10L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(10L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -402,8 +224,15 @@ class FileMoveServiceMoveFilesTest {
|
||||
.title("EmptyFileName")
|
||||
.build();
|
||||
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(47L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern("Moved/{title}")
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString())
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
@@ -415,10 +244,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
.build();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(11L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -434,8 +265,15 @@ class FileMoveServiceMoveFilesTest {
|
||||
.title("NullSubPath")
|
||||
.build();
|
||||
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(48L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern("Moved/{title}")
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString())
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
@@ -450,10 +288,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
Files.createFile(oldFile);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(12L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(12L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -467,8 +307,15 @@ class FileMoveServiceMoveFilesTest {
|
||||
|
||||
@Test
|
||||
void testMoveFiles_skipsBookWithNullMetadata() throws IOException {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(49L)
|
||||
.name("Test Library")
|
||||
.fileNamingPattern("Moved/{title}")
|
||||
.build();
|
||||
|
||||
LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString())
|
||||
.library(library)
|
||||
.build();
|
||||
|
||||
BookEntity book = BookEntity.builder()
|
||||
@@ -484,10 +331,12 @@ class FileMoveServiceMoveFilesTest {
|
||||
Files.createFile(oldFile);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(book));
|
||||
AppSettings appSettings = new AppSettings();
|
||||
appSettings.setUploadPattern("Moved/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(13L));
|
||||
request.setPattern("Moved/{title}");
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
|
||||
@@ -499,26 +348,191 @@ class FileMoveServiceMoveFilesTest {
|
||||
Files.deleteIfExists(oldFile);
|
||||
}
|
||||
|
||||
@Disabled
|
||||
@Test
|
||||
void testMoveFiles_patternWithUnknownPlaceholder() throws IOException {
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, "folder", "unknown.epub");
|
||||
book.getMetadata().setTitle("UnknownPlaceholder");
|
||||
void testMoveFiles_successfulMove() throws IOException {
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(14L))).thenReturn(List.of(book));
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("X/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
Book dto = Book.builder().id(book.getId()).build();
|
||||
when(bookMapper.toBook(book)).thenReturn(dto);
|
||||
|
||||
FileMoveRequest request = new FileMoveRequest();
|
||||
request.setBookIds(Set.of(14L));
|
||||
request.setPattern("Moved/{title}/{foo}");
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(book.getId()));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
fileMoveService.moveFiles(request);
|
||||
Path newPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub");
|
||||
assertThat(Files.exists(newPath)).isTrue();
|
||||
assertThat(Files.exists(oldFilePath)).isFalse();
|
||||
|
||||
Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("UnknownPlaceholder").resolve("{foo}.epub");
|
||||
assertThat(Files.exists(expectedNewPath))
|
||||
.withFailMessage("Unknown placeholders should remain in the generated path")
|
||||
.isTrue();
|
||||
|
||||
Files.deleteIfExists(expectedNewPath);
|
||||
Files.deleteIfExists(expectedNewPath.getParent());
|
||||
verify(bookRepository).save(book);
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), anyList());
|
||||
verify(libraryService).rescanLibrary(book.getLibraryPath().getLibrary().getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_usesDefaultPatternWhenLibraryPatternEmpty() throws IOException {
|
||||
LibraryEntity lib = LibraryEntity.builder()
|
||||
.id(99L).name("Lib").fileNamingPattern(" ").build();
|
||||
LibraryPathEntity lp = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString()).library(lib).build();
|
||||
|
||||
BookMetadataEntity meta = BookMetadataEntity.builder()
|
||||
.title("DFT").build();
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(55L).fileSubPath("old").fileName("a.epub")
|
||||
.libraryPath(lp).metadata(meta).build();
|
||||
|
||||
Path old = book.getFullFilePath();
|
||||
Files.createDirectories(old.getParent());
|
||||
Files.createFile(old);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(55L))).thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("DEF/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
Book dto = Book.builder().id(book.getId()).build();
|
||||
when(bookMapper.toBook(book)).thenReturn(dto);
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(55L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
Path moved = tempLibraryRoot.resolve("DEF").resolve("DFT.epub");
|
||||
assertThat(Files.exists(moved)).isTrue();
|
||||
verify(bookRepository).save(book);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_deletesEmptyParentDirectories() throws IOException {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(100L).name("Lib").fileNamingPattern(null).build();
|
||||
LibraryPathEntity lp = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString()).library(library).build();
|
||||
BookMetadataEntity meta = BookMetadataEntity.builder()
|
||||
.title("Nested").build();
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(101L).fileSubPath("a/b/c").fileName("nested.epub")
|
||||
.libraryPath(lp).metadata(meta).build();
|
||||
Path old = book.getFullFilePath();
|
||||
Files.createDirectories(old.getParent());
|
||||
Files.createFile(old);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(101L))).thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("Z/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(101L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
Path newPath = tempLibraryRoot.resolve("Z").resolve("Nested.epub");
|
||||
assertThat(Files.exists(newPath)).isTrue();
|
||||
assertThat(Files.notExists(tempLibraryRoot.resolve("a"))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_overwritesExistingDestination() throws IOException {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(102L).name("Lib").fileNamingPattern(null).build();
|
||||
LibraryPathEntity lp = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString()).library(library).build();
|
||||
BookMetadataEntity meta = BookMetadataEntity.builder()
|
||||
.title("Overwrite").build();
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(103L).fileSubPath("sub").fileName("file.epub")
|
||||
.libraryPath(lp).metadata(meta).build();
|
||||
Path old = book.getFullFilePath();
|
||||
Files.createDirectories(old.getParent());
|
||||
Files.write(old, "SRC".getBytes());
|
||||
Path destDir = tempLibraryRoot.resolve("DEST");
|
||||
Files.createDirectories(destDir);
|
||||
Path dest = destDir.resolve("Overwrite.epub");
|
||||
Files.write(dest, "OLD".getBytes());
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(103L))).thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("DEST/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(103L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
assertThat(Files.exists(dest)).isTrue();
|
||||
String content = Files.readString(dest);
|
||||
assertThat(content).isEqualTo("SRC");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_usesLibraryPatternWhenSet() throws IOException {
|
||||
LibraryEntity library = LibraryEntity.builder()
|
||||
.id(104L).name("Lib").fileNamingPattern("LIBY/{title}").build();
|
||||
LibraryPathEntity lp = LibraryPathEntity.builder()
|
||||
.path(tempLibraryRoot.toString()).library(library).build();
|
||||
BookMetadataEntity meta = BookMetadataEntity.builder()
|
||||
.title("LibTest").build();
|
||||
BookEntity book = BookEntity.builder()
|
||||
.id(105L).fileSubPath("x").fileName("file.epub")
|
||||
.libraryPath(lp).metadata(meta).build();
|
||||
Path old = book.getFullFilePath();
|
||||
Files.createDirectories(old.getParent());
|
||||
Files.createFile(old);
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(105L))).thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("DEFAULT/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build());
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(105L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
Path newPath = tempLibraryRoot.resolve("LIBY").resolve("LibTest.epub");
|
||||
assertThat(Files.exists(newPath)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_skipsWhenDestinationSameAsSource() throws IOException {
|
||||
BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub");
|
||||
Path oldFilePath = book.getFullFilePath();
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId())))
|
||||
.thenReturn(List.of(book));
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("sub/mybook.epub");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(book.getId()));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
assertThat(Files.exists(oldFilePath)).isTrue();
|
||||
verify(bookRepository, never()).save(any());
|
||||
verify(notificationService, never()).sendMessage(any(), anyList());
|
||||
verify(libraryService, never()).rescanLibrary(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMoveFiles_doesNotPauseMonitoringWhenAlreadyPaused() {
|
||||
when(monitoringService.isPaused()).thenReturn(true);
|
||||
when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of());
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setUploadPattern("X/{title}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
|
||||
FileMoveRequest req = new FileMoveRequest();
|
||||
req.setBookIds(Set.of(999L));
|
||||
fileMoveService.moveFiles(req);
|
||||
|
||||
verify(monitoringService, never()).pauseMonitoring();
|
||||
verify(monitoringService, never()).resumeMonitoring();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ export class BookDialogHelperService {
|
||||
openFileMoverDialog(selectedBooks: Set<number>) {
|
||||
const count = selectedBooks.size;
|
||||
return this.dialogService.open(FileMoverComponent, {
|
||||
header: `Relocate Book Files (${count} book${count !== 1 ? 's' : ''})`,
|
||||
header: `Organize Book Files (${count} book${count !== 1 ? 's' : ''})`,
|
||||
showHeader: true,
|
||||
modal: true,
|
||||
closable: true,
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
}
|
||||
</p>
|
||||
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
|
||||
(userData.permissions.admin || userData.permissions.canManipulateLibrary)) {
|
||||
(userState.user!.permissions.admin || userState.user!.permissions.canManipulateLibrary)) {
|
||||
<div class="ml-2 flex-shrink-0">
|
||||
<p-button
|
||||
icon="pi pi-ellipsis-v"
|
||||
@@ -286,13 +286,13 @@
|
||||
}
|
||||
}
|
||||
@if (selectedBooks.size > 0) {
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
<div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]>
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="flex">
|
||||
@if (entityType$ | async; as entityType) {
|
||||
<div class="flex gap-2 md:gap-6 pr-2">
|
||||
@if (userData.permissions.canEditMetadata) {
|
||||
@if (userState.user!.permissions.canEditMetadata) {
|
||||
<p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/>
|
||||
<p-button
|
||||
(click)="menu.toggle($event)"
|
||||
@@ -323,7 +323,7 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
@if (userData.permissions.canEditMetadata) {
|
||||
@if (userState.user!.permissions.canEditMetadata) {
|
||||
<p-button
|
||||
outlined="true"
|
||||
icon="pi pi-lock"
|
||||
@@ -375,7 +375,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (userData?.permissions?.admin || userData?.permissions?.canDeleteBook) {
|
||||
@if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
|
||||
<p-divider layout="vertical"></p-divider>
|
||||
<p-button
|
||||
outlined="true"
|
||||
|
||||
@@ -45,7 +45,7 @@ import {MultiSelect} from 'primeng/multiselect';
|
||||
import {TableColumnPreferenceService} from './table-column-preference-service';
|
||||
import {TieredMenu} from 'primeng/tieredmenu';
|
||||
import {BookMenuService} from '../../service/book-menu.service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf-service';
|
||||
import {MagicShelf, MagicShelfService} from '../../../magic-shelf.service';
|
||||
import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service';
|
||||
import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component';
|
||||
|
||||
@@ -136,7 +136,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
rawFilterParamFromUrl: string | null = null;
|
||||
hasSearchTerm = false;
|
||||
visibleColumns: { field: string; header: string }[] = [];
|
||||
entityViewPreferences!: EntityViewPreferences;
|
||||
entityViewPreferences: EntityViewPreferences | undefined;
|
||||
currentViewMode: string | undefined;
|
||||
lastAppliedSort: SortOption | null = null;
|
||||
private settingFiltersFromUrl = false;
|
||||
@@ -161,7 +161,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
|
||||
ngOnInit(): void {
|
||||
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
|
||||
this.bookService.loadBooks();
|
||||
|
||||
const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
|
||||
if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
|
||||
@@ -206,7 +205,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
combineLatest({
|
||||
paramMap: this.activatedRoute.queryParamMap,
|
||||
user: this.userService.userState$.pipe(
|
||||
filter((user): user is NonNullable<typeof user> => !!user),
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1)
|
||||
)
|
||||
}).subscribe(({paramMap, user}) => {
|
||||
@@ -216,6 +215,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION);
|
||||
const filterParams = paramMap.get(QUERY_PARAMS.FILTER);
|
||||
const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR);
|
||||
this.showFilter = sidebarParam === null ? true : sidebarParam === 'true';
|
||||
|
||||
const parsedFilters: Record<string, string[]> = {};
|
||||
|
||||
@@ -250,12 +250,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
this.currentFilterLabel = 'All Books';
|
||||
}
|
||||
|
||||
this.entityViewPreferences = user.userSettings?.entityViewPreferences;
|
||||
this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
|
||||
const globalPrefs = this.entityViewPreferences?.global;
|
||||
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
|
||||
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
|
||||
this.filterSortPreferenceService.initValue(user?.userSettings?.filterSortingMode);
|
||||
this.columnPreferenceService.initPreferences(user.userSettings?.tableColumnPreference);
|
||||
this.filterSortPreferenceService.initValue(user.user?.userSettings?.filterSortingMode);
|
||||
this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
|
||||
this.visibleColumns = this.columnPreferenceService.visibleColumns;
|
||||
|
||||
|
||||
@@ -298,8 +298,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
: VIEW_MODES.GRID)
|
||||
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
|
||||
|
||||
//this.showFilter = sidebarParam === 'true' || (sidebarParam === null && filterParams !== filterParams);
|
||||
|
||||
this.bookSorter.updateSortOptions();
|
||||
|
||||
if (this.lastAppliedSort?.field !== this.bookSorter.selectedSort.field || this.lastAppliedSort?.direction !== this.bookSorter.selectedSort.direction) {
|
||||
@@ -311,10 +309,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
[QUERY_PARAMS.VIEW]: this.currentViewMode,
|
||||
[QUERY_PARAMS.SORT]: this.bookSorter.selectedSort.field,
|
||||
[QUERY_PARAMS.DIRECTION]: this.bookSorter.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING,
|
||||
[QUERY_PARAMS.SIDEBAR]: this.showFilter.toString(),
|
||||
[QUERY_PARAMS.FILTER]: Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',')
|
||||
[QUERY_PARAMS.SIDEBAR]: this.showFilter.toString()
|
||||
};
|
||||
|
||||
if (Object.keys(parsedFilters).length > 0) {
|
||||
queryParams[QUERY_PARAMS.FILTER] = Object.entries(parsedFilters).map(([k, v]) => `${k}:${v.join('|')}`).join(',');
|
||||
}
|
||||
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
const changed = Object.keys(queryParams).some(k => currentParams[k] !== queryParams[k]);
|
||||
|
||||
@@ -479,11 +480,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
|
||||
toggleFilterSidebar() {
|
||||
this.showFilter = !this.showFilter;
|
||||
const currentParams = this.activatedRoute.snapshot.queryParams;
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
...currentParams,
|
||||
[QUERY_PARAMS.SIDEBAR]: this.showFilter.toString()
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@
|
||||
|
||||
<div [hidden]="bottomBarHidden">
|
||||
<div class="book-title-container flex items-center">
|
||||
<h4 class="book-title m-0 pl-2">{{ book.metadata?.title }}</h4>
|
||||
<h4 class="book-title m-0 pl-2" [title]="book.metadata?.title">{{ book.metadata?.title }}</h4>
|
||||
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body"></p-tieredmenu>
|
||||
<p-button
|
||||
class="custom-button-padding"
|
||||
|
||||
@@ -105,13 +105,16 @@
|
||||
|
||||
.select-checkbox {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: opacity 0.2s ease, visibility 0.2s ease;
|
||||
z-index: 2;
|
||||
}
|
||||
.select-checkbox .p-checkbox {
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.cover-container:hover .select-checkbox,
|
||||
.book-card.selected .select-checkbox {
|
||||
@@ -144,8 +147,8 @@
|
||||
|
||||
.series-number-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
top: 8px;
|
||||
left: 8px;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
@@ -156,8 +159,8 @@
|
||||
|
||||
.series-count-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
bottom: 8px;
|
||||
left: 8px;
|
||||
background-color: var(--primary-color);
|
||||
color: var(--primary-text-color-dark);
|
||||
font-size: 0.75rem;
|
||||
|
||||
@@ -21,7 +21,7 @@ import {BookSenderComponent} from '../../book-sender/book-sender.component';
|
||||
import {Router} from '@angular/router';
|
||||
import {ProgressBar} from 'primeng/progressbar';
|
||||
import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center-component/book-metadata-center.component';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {take, takeUntil} from 'rxjs/operators';
|
||||
import {readStatusLabels} from '../book-filter/book-filter.component';
|
||||
import {ResetProgressTypes} from '../../../../shared/constants/reset-progress-type';
|
||||
|
||||
@@ -67,12 +67,13 @@ export class BookCardComponent implements OnInit, OnDestroy {
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(user => !!user),
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(user => {
|
||||
this.userPermissions = user.permissions;
|
||||
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
.subscribe(userState => {
|
||||
this.userPermissions = userState.user?.permissions;
|
||||
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
this.initMenu();
|
||||
});
|
||||
}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service';
|
||||
import {MagicShelf} from '../../../../magic-shelf-service';
|
||||
import {MagicShelf} from '../../../../magic-shelf.service';
|
||||
import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component';
|
||||
import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service';
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import {filter, Subject} from 'rxjs';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center-component/book-metadata-center.component';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
import {take, takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table',
|
||||
@@ -75,11 +75,12 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(user => !!user),
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(user => {
|
||||
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
.subscribe(userState => {
|
||||
this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
|
||||
this.setScrollHeight();
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {Observable, BehaviorSubject} from 'rxjs';
|
||||
import {BehaviorSubject, Observable, Subject} from 'rxjs';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {map, debounceTime, filter, take} from 'rxjs/operators';
|
||||
import {debounceTime, filter, map, take, takeUntil} from 'rxjs/operators';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SeriesCollapseFilter implements BookFilter {
|
||||
export class SeriesCollapseFilter implements BookFilter, OnDestroy {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
|
||||
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
|
||||
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
private hasUserToggled = false;
|
||||
|
||||
constructor() {
|
||||
this.userService.userState$
|
||||
.pipe(filter(user => !!user), take(1))
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(user => {
|
||||
const prefs = user.userSettings?.entityViewPreferences;
|
||||
const prefs = user.user?.userSettings?.entityViewPreferences;
|
||||
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
|
||||
this.seriesCollapseSubject.next(initialCollapsed);
|
||||
});
|
||||
@@ -102,4 +107,9 @@ export class SeriesCollapseFilter implements BookFilter {
|
||||
life: 1500
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import {Component, inject, Input, OnInit} from '@angular/core';
|
||||
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {UrlHelperService} from '../../../utilities/service/url-helper.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {BookMetadataCenterComponent} from '../../../metadata/book-metadata-center-component/book-metadata-center.component';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {EmailService} from '../../../settings/email/email.service';
|
||||
import {ConfirmationService, MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {filter} from 'rxjs';
|
||||
import {filter, Subject} from 'rxjs';
|
||||
import {NgClass} from '@angular/common';
|
||||
import {BookMetadataHostService} from '../../../utilities/service/book-metadata-host-service';
|
||||
import {takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-card-lite-component',
|
||||
@@ -22,7 +18,7 @@ import {BookMetadataHostService} from '../../../utilities/service/book-metadata-
|
||||
templateUrl: './book-card-lite-component.html',
|
||||
styleUrl: './book-card-lite-component.scss'
|
||||
})
|
||||
export class BookCardLiteComponent implements OnInit {
|
||||
export class BookCardLiteComponent implements OnInit, OnDestroy {
|
||||
@Input() book!: Book;
|
||||
|
||||
private router = inject(Router);
|
||||
@@ -30,14 +26,19 @@ export class BookCardLiteComponent implements OnInit {
|
||||
private userService = inject(UserService);
|
||||
private bookMetadataHostService = inject(BookMetadataHostService);
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
isHovered: boolean = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$
|
||||
.pipe(filter(user => !!user))
|
||||
.pipe(
|
||||
filter(userState => !!userState),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe((user) => {
|
||||
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
this.metadataCenterViewMode = user?.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,4 +51,9 @@ export class BookCardLiteComponent implements OnInit {
|
||||
this.bookMetadataHostService.requestBookSwitch(book.id);
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, filter, map, tap} from 'rxjs/operators';
|
||||
import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
|
||||
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
|
||||
import {BookState} from '../model/state/book-state.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
@@ -9,6 +9,7 @@ import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-
|
||||
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
@@ -17,22 +18,57 @@ export class BookService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
private bookStateSubject = new BehaviorSubject<BookState>({
|
||||
books: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
bookState$ = this.bookStateSubject.asObservable();
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private loading$: Observable<Book[]> | null = null;
|
||||
|
||||
loadBooks(): void {
|
||||
const currentState = this.bookStateSubject.value;
|
||||
if (currentState.loaded && this.bookStateSubject.value.books != null) {
|
||||
return;
|
||||
}
|
||||
this.http.get<Book[]>(this.url).pipe(
|
||||
constructor() {
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.bookStateSubject.value;
|
||||
if (current.loaded && !current.books) {
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bookState$ = this.bookStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchBooks().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private fetchBooks(): Observable<Book[]> {
|
||||
return this.http.get<Book[]>(this.url).pipe(
|
||||
tap(books => {
|
||||
this.bookStateSubject.next({
|
||||
books: books || [],
|
||||
@@ -41,14 +77,15 @@ export class BookService {
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
const curr = this.bookStateSubject.value;
|
||||
this.bookStateSubject.next({
|
||||
books: null,
|
||||
books: curr.books,
|
||||
loaded: true,
|
||||
error: error.message,
|
||||
});
|
||||
return of(null);
|
||||
throw error;
|
||||
})
|
||||
).subscribe();
|
||||
);
|
||||
}
|
||||
|
||||
getBookByIdFromState(bookId: number): Book | undefined {
|
||||
@@ -282,6 +319,31 @@ export class BookService {
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
dateFinished: dateFinished
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body).pipe(
|
||||
tap(() => {
|
||||
// Update the book in the state
|
||||
const currentState = this.bookStateSubject.value;
|
||||
if (currentState.books) {
|
||||
const updatedBooks = currentState.books.map(book => {
|
||||
if (book.id === bookId) {
|
||||
return { ...book, dateFinished: dateFinished || undefined };
|
||||
}
|
||||
return book;
|
||||
});
|
||||
this.bookStateSubject.next({
|
||||
...currentState,
|
||||
books: updatedBooks
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
regenerateCovers(): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component';
|
||||
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf-service';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf.service';
|
||||
import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component';
|
||||
|
||||
@Injectable({
|
||||
|
||||
@@ -1,119 +1,145 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {BehaviorSubject, Observable, of, tap} from 'rxjs';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {catchError, map} from 'rxjs/operators';
|
||||
import {Library} from '../model/library.model';
|
||||
import {BookService} from './book.service';
|
||||
import {LibraryState} from '../model/state/library-state.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
import {Library} from '../model/library.model';
|
||||
import {LibraryState} from '../model/state/library-state.model';
|
||||
import {BookService} from './book.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
private libraryStateSubject = new BehaviorSubject<LibraryState>({
|
||||
libraries: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
libraryState$ = this.libraryStateSubject.asObservable();
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private loading$: Observable<Library[]> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.loadLibraries();
|
||||
}
|
||||
|
||||
private loadLibraries(): void {
|
||||
this.http.get<Library[]>(this.url).pipe(
|
||||
catchError(error => {
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.libraryStateSubject.next({
|
||||
libraries: null,
|
||||
loaded: true,
|
||||
error: error.message,
|
||||
error: null,
|
||||
});
|
||||
return of([]);
|
||||
})
|
||||
).subscribe(libraries => {
|
||||
this.libraryStateSubject.next({
|
||||
libraries,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.libraryStateSubject.value;
|
||||
if (current.loaded && !current.libraries) {
|
||||
this.libraryStateSubject.next({
|
||||
libraries: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
doesLibraryExistByName(name: string): boolean {
|
||||
const libraries = this.libraryStateSubject.value.libraries || [];
|
||||
return libraries.some(library => library.name === name);
|
||||
}
|
||||
libraryState$ = this.libraryStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchLibraries().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
findLibraryById(id: number): Library | undefined {
|
||||
return this.libraryStateSubject.value.libraries?.find(library => library.id === id);
|
||||
}
|
||||
|
||||
createLibrary(newLibrary: Library): Observable<Library> {
|
||||
return this.http.post<Library>(this.url, newLibrary).pipe(
|
||||
map(createdLibrary => {
|
||||
const currentState = this.libraryStateSubject.value;
|
||||
const updatedLibraries = currentState.libraries ? [...currentState.libraries, createdLibrary] : [createdLibrary];
|
||||
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
|
||||
return createdLibrary;
|
||||
}),
|
||||
catchError(error => {
|
||||
throw error;
|
||||
private fetchLibraries(): Observable<Library[]> {
|
||||
return this.http.get<Library[]>(this.url).pipe(
|
||||
tap(libs => this.libraryStateSubject.next({libraries: libs, loaded: true, error: null})),
|
||||
catchError(err => {
|
||||
const current = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLibrary(library: Library, libraryId: number | undefined): Observable<Library> {
|
||||
return this.http.put<Library>(`${this.url}/${libraryId}`, library).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;
|
||||
createLibrary(lib: Library): Observable<Library> {
|
||||
return this.http.post<Library>(this.url, lib).pipe(
|
||||
map(created => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const updated = curr.libraries ? [...curr.libraries, created] : [created];
|
||||
this.libraryStateSubject.next({...curr, libraries: updated});
|
||||
return created;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteLibrary(libraryId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${libraryId}`).pipe(
|
||||
updateLibrary(lib: Library, id?: number): Observable<Library> {
|
||||
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
|
||||
map(updated => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
||||
this.libraryStateSubject.next({...curr, libraries: list});
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteLibrary(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
this.bookService.removeBooksByLibraryId(libraryId);
|
||||
const currentState = this.libraryStateSubject.value;
|
||||
const updatedLibraries = currentState.libraries?.filter(library => library.id !== libraryId) || [];
|
||||
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
|
||||
this.bookService.removeBooksByLibraryId(id);
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
|
||||
this.libraryStateSubject.next({...curr, libraries: filtered});
|
||||
}),
|
||||
catchError(error => {
|
||||
const currentState = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...currentState, error: error.message});
|
||||
catchError(err => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...curr, error: err.message});
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshLibrary(libraryId: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {}).pipe(
|
||||
catchError(error => {
|
||||
const currentState = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...currentState, error: error.message});
|
||||
throw error;
|
||||
refreshLibrary(id: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
|
||||
catchError(err => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
this.libraryStateSubject.next({...curr, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getBookCount(libraryId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state => (state.books || []).filter(book => book.libraryId === libraryId).length)
|
||||
);
|
||||
updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
|
||||
return this.http
|
||||
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
|
||||
.pipe(
|
||||
map(updated => {
|
||||
const curr = this.libraryStateSubject.value;
|
||||
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
|
||||
this.libraryStateSubject.next({...curr, libraries: list});
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
doesLibraryExistByName(name: string): boolean {
|
||||
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
|
||||
}
|
||||
|
||||
findLibraryById(id: number): Library | undefined {
|
||||
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
|
||||
}
|
||||
|
||||
getLibrariesFromState(): Library[] {
|
||||
@@ -121,28 +147,14 @@ 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;
|
||||
return this.libraryStateSubject.value.libraries
|
||||
?.find(lib => lib.paths.some(p => p.id === pathId))
|
||||
?.paths.find(p => p.id === pathId)?.path;
|
||||
}
|
||||
|
||||
updateLibraryFileNamingPattern(libraryId: number, fileNamingPattern: string): Observable<Library> {
|
||||
return this.http.patch<Library>(`${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;
|
||||
})
|
||||
getBookCount(libraryId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,108 +1,96 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import { BehaviorSubject, Observable, of, tap } from 'rxjs';
|
||||
import { catchError, map } from 'rxjs/operators';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Shelf } from '../model/shelf.model';
|
||||
import { SortOption } from '../model/sort.model';
|
||||
import { BookService } from './book.service';
|
||||
import { ShelfState } from '../model/state/shelf-state.model';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {Library} from '../model/library.model';
|
||||
import { BehaviorSubject, Observable, of } from 'rxjs';
|
||||
import { tap, catchError, map, shareReplay, finalize } from 'rxjs/operators';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
import { Shelf } from '../model/shelf.model';
|
||||
import { ShelfState } from '../model/state/shelf-state.model';
|
||||
import { BookService } from './book.service';
|
||||
import { API_CONFIG } from '../../config/api-config';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ShelfService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
|
||||
private shelfStateSubject = new BehaviorSubject<ShelfState>({
|
||||
shelves: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
shelfState$ = this.shelfStateSubject.asObservable();
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private loading$: Observable<Shelf[]> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.loadShelves();
|
||||
}
|
||||
shelfState$ = this.shelfStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchShelves().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private loadShelves(): void {
|
||||
this.http.get<Shelf[]>(this.url).pipe(
|
||||
catchError(error => {
|
||||
this.shelfStateSubject.next({
|
||||
shelves: null,
|
||||
loaded: true,
|
||||
error: error.message,
|
||||
});
|
||||
return of([]);
|
||||
private fetchShelves(): Observable<Shelf[]> {
|
||||
return this.http.get<Shelf[]>(this.url).pipe(
|
||||
tap(shelves => this.shelfStateSubject.next({ shelves, loaded: true, error: null })),
|
||||
catchError(err => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({ shelves: curr.shelves, loaded: true, error: err.message });
|
||||
throw err;
|
||||
})
|
||||
).subscribe(shelves => {
|
||||
this.shelfStateSubject.next({
|
||||
shelves,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getShelfById(shelfId: number): Shelf | undefined {
|
||||
let shelfState = this.shelfStateSubject.value;
|
||||
return shelfState.shelves?.find(shelf => shelf.id === shelfId);
|
||||
);
|
||||
}
|
||||
|
||||
createShelf(shelf: Shelf): Observable<Shelf> {
|
||||
return this.http.post<Shelf>(this.url, shelf).pipe(
|
||||
map(newShelf => {
|
||||
const currentState = this.shelfStateSubject.value;
|
||||
const updatedShelves = currentState.shelves ? [...currentState.shelves, newShelf] : [newShelf];
|
||||
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
|
||||
this.shelfStateSubject.next({ ...curr, shelves: updated });
|
||||
return newShelf;
|
||||
}),
|
||||
catchError(error => {
|
||||
const currentState = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({ ...currentState, error: error.message });
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateShelf(shelf: Shelf, shelfId: number | undefined): Observable<Shelf> {
|
||||
return this.http.put<Shelf>(`${this.url}/${shelfId}`, shelf).pipe(
|
||||
map(updatedShelf => {
|
||||
const currentState = this.shelfStateSubject.value;
|
||||
const updatedShelves = currentState.shelves ? currentState.shelves.map(existingShelf =>
|
||||
existingShelf.id === updatedShelf.id ? updatedShelf : existingShelf) : [updatedShelf];
|
||||
this.shelfStateSubject.next({...currentState, shelves: updatedShelves,});
|
||||
return updatedShelf;
|
||||
}),
|
||||
catchError(error => {
|
||||
throw error;
|
||||
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
|
||||
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
|
||||
map(updated => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
|
||||
this.shelfStateSubject.next({ ...curr, shelves: list });
|
||||
return updated;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteShelf(shelfId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${shelfId}`).pipe(
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
this.bookService.removeBooksFromShelf(shelfId);
|
||||
const currentState = this.shelfStateSubject.value;
|
||||
const updatedShelves = currentState.shelves?.filter(shelf => shelf.id !== shelfId) || [];
|
||||
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves });
|
||||
this.bookService.removeBooksFromShelf(id);
|
||||
const curr = this.shelfStateSubject.value;
|
||||
const filtered = curr.shelves?.filter(s => s.id !== id) || [];
|
||||
this.shelfStateSubject.next({ ...curr, shelves: filtered });
|
||||
}),
|
||||
catchError(error => {
|
||||
const currentState = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({ ...currentState, error: error.message });
|
||||
catchError(err => {
|
||||
const curr = this.shelfStateSubject.value;
|
||||
this.shelfStateSubject.next({ ...curr, error: err.message });
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getShelfById(id: number): Shelf | undefined {
|
||||
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
|
||||
}
|
||||
|
||||
getBookCount(shelfId: number): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state =>
|
||||
(state.books || []).filter(book => book.shelves?.some(shelf => shelf.id === shelfId)).length
|
||||
(state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -110,7 +98,7 @@ export class ShelfService {
|
||||
getUnshelvedBookCount(): Observable<number> {
|
||||
return this.bookService.bookState$.pipe(
|
||||
map(state =>
|
||||
(state.books || []).filter(book => !book.shelves || book.shelves.length === 0).length
|
||||
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,7 +83,6 @@ export interface AppSettings {
|
||||
metadataRefreshOptions: MetadataRefreshOptions;
|
||||
coverResolution: string;
|
||||
uploadPattern: string;
|
||||
movePattern: string;
|
||||
opdsServerEnabled: boolean;
|
||||
remoteAuthEnabled: boolean;
|
||||
oidcEnabled: boolean;
|
||||
@@ -112,6 +111,5 @@ export enum AppSettingKey {
|
||||
METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS',
|
||||
METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS',
|
||||
METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS',
|
||||
MOVE_FILE_PATTERN = 'MOVE_FILE_PATTERN',
|
||||
METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {inject, Injectable, Injector} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, tap} from 'rxjs';
|
||||
import {BehaviorSubject, Observable, Subject, tap} from 'rxjs';
|
||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
|
||||
@@ -23,6 +23,9 @@ export class AuthService {
|
||||
private tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
|
||||
public token$ = this.tokenSubject.asObservable();
|
||||
|
||||
private logoutSubject = new Subject<void>();
|
||||
public logout$ = this.logoutSubject.asObservable();
|
||||
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
||||
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => {
|
||||
@@ -78,6 +81,7 @@ export class AuthService {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
this.tokenSubject.next(null);
|
||||
this.logoutSubject.next();
|
||||
this.getRxStompService().deactivate();
|
||||
if (this.oAuthService.clientId) {
|
||||
this.oAuthService.logOut();
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
<div>
|
||||
@if (isLibrariesEmpty$ | async) {
|
||||
<div class="dashboard-no-library">
|
||||
@if ((userService.userState$ | async)?.permissions; as permissions) {
|
||||
@if ((userService.userState$ | async)?.user?.permissions; as permissions) {
|
||||
<div>
|
||||
@if (permissions.admin || permissions.canManipulateLibrary) {
|
||||
<div>
|
||||
|
||||
@@ -46,7 +46,6 @@ export class MainDashboardComponent implements OnInit {
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.loadBooks();
|
||||
|
||||
this.lastReadBooks$ = this.bookService.bookState$.pipe(
|
||||
map((state: BookState) => (
|
||||
|
||||
@@ -12,7 +12,7 @@ import {AppVersion, VersionService} from '../../../core/service/version.service'
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {MagicShelf, MagicShelfService, MagicShelfState} from '../../../magic-shelf-service';
|
||||
import {MagicShelfService, MagicShelfState} from '../../../magic-shelf.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-menu',
|
||||
@@ -50,15 +50,15 @@ export class AppMenuComponent implements OnInit {
|
||||
});
|
||||
|
||||
this.userService.userState$.pipe(
|
||||
filter(settings => !!settings))
|
||||
.subscribe(user => {
|
||||
if (user?.userSettings.sidebarLibrarySorting) {
|
||||
this.librarySortField = this.validateSortField(user.userSettings.sidebarLibrarySorting.field);
|
||||
this.librarySortOrder = this.validateSortOrder(user.userSettings.sidebarLibrarySorting.order);
|
||||
filter(userState => !!userState?.user && userState.loaded))
|
||||
.subscribe(userState => {
|
||||
if (userState.user?.userSettings.sidebarLibrarySorting) {
|
||||
this.librarySortField = this.validateSortField(userState.user.userSettings.sidebarLibrarySorting.field);
|
||||
this.librarySortOrder = this.validateSortOrder(userState.user.userSettings.sidebarLibrarySorting.order);
|
||||
}
|
||||
if (user?.userSettings.sidebarShelfSorting) {
|
||||
this.shelfSortField = this.validateSortField(user.userSettings.sidebarShelfSorting.field);
|
||||
this.shelfSortOrder = this.validateSortOrder(user.userSettings.sidebarShelfSorting.order);
|
||||
if (userState.user?.userSettings.sidebarShelfSorting) {
|
||||
this.shelfSortField = this.validateSortField(userState.user.userSettings.sidebarShelfSorting.field);
|
||||
this.shelfSortOrder = this.validateSortOrder(userState.user.userSettings.sidebarShelfSorting.order);
|
||||
}
|
||||
this.initMenus();
|
||||
});
|
||||
|
||||
@@ -67,10 +67,10 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
constructor(public router: Router, private menuService: MenuService, private userService: UserService, private dialogLauncher: DialogLauncherService) {
|
||||
this.userService.userState$.subscribe(userData => {
|
||||
if (userData) {
|
||||
this.canManipulateLibrary = userData.permissions.canManipulateLibrary;
|
||||
this.admin = userData.permissions.admin;
|
||||
this.userService.userState$.subscribe(userState => {
|
||||
if (userState?.user) {
|
||||
this.canManipulateLibrary = userState.user.permissions.canManipulateLibrary;
|
||||
this.admin = userState.user.permissions.admin;
|
||||
}
|
||||
});
|
||||
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
|
||||
|
||||
@@ -29,18 +29,18 @@
|
||||
<app-book-searcher class="md:block flex-grow"></app-book-searcher>
|
||||
<ul class="topbar-items hidden md:flex items-center gap-3 ml-auto pl-4">
|
||||
<div class="flex gap-6">
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
<li>
|
||||
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) {
|
||||
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
|
||||
<a class="topbar-item" (click)="openLibraryCreatorDialog()" pTooltip="Create New Library" tooltipPosition="bottom">
|
||||
<i class="pi pi-plus-circle text-surface-100"></i>
|
||||
</a>
|
||||
}
|
||||
</li>
|
||||
}
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
<li>
|
||||
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) {
|
||||
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
|
||||
<a class="topbar-item" (click)="openFileUploadDialog()" pTooltip="Upload Book" tooltipPosition="bottom">
|
||||
<i class="pi pi-upload text-surface-100"></i>
|
||||
</a>
|
||||
@@ -137,8 +137,8 @@
|
||||
/>
|
||||
<p-popover #mobileMenu>
|
||||
<ul class="flex flex-col gap-1 w-48">
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
|
||||
<li>
|
||||
<button
|
||||
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
|
||||
|
||||
@@ -10,7 +10,7 @@ import {InputNumber} from 'primeng/inputnumber';
|
||||
import {ReadStatus} from '../book/model/book.model';
|
||||
import {LibraryService} from '../book/service/library.service';
|
||||
import {Library} from '../book/model/library.model';
|
||||
import {MagicShelfService} from '../magic-shelf-service';
|
||||
import {MagicShelfService} from '../magic-shelf.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {DynamicDialogConfig} from 'primeng/dynamicdialog';
|
||||
import {Chips} from 'primeng/chips';
|
||||
|
||||
+54
-23
@@ -2,10 +2,11 @@ import {inject, Injectable} from '@angular/core';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||
import {catchError, map, switchMap, tap} from 'rxjs/operators';
|
||||
import {catchError, map, switchMap, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
|
||||
import {BookService} from './book/service/book.service';
|
||||
import {GroupRule} from './magic-shelf-component/magic-shelf-component';
|
||||
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
|
||||
import {AuthService} from './core/service/auth.service';
|
||||
|
||||
export interface MagicShelf {
|
||||
id?: number | null;
|
||||
@@ -15,7 +16,7 @@ export interface MagicShelf {
|
||||
}
|
||||
|
||||
export interface MagicShelfState {
|
||||
shelves: MagicShelf[];
|
||||
shelves: MagicShelf[] | null;
|
||||
loaded: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
@@ -29,28 +30,64 @@ export class MagicShelfService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
|
||||
private readonly authService = inject(AuthService);
|
||||
|
||||
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
|
||||
shelves: [],
|
||||
shelves: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
public readonly shelvesState$ = this.shelvesStateSubject.asObservable();
|
||||
|
||||
private loading$: Observable<MagicShelf[]> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.loadUserShelves().subscribe();
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.shelvesStateSubject.next({
|
||||
shelves: null,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.shelvesStateSubject.value;
|
||||
if (current.loaded && !current.shelves) {
|
||||
this.shelvesStateSubject.next({
|
||||
shelves: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public readonly shelvesState$ = this.shelvesStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchMagicShelves().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private get state(): MagicShelfState {
|
||||
return this.shelvesStateSubject.value;
|
||||
}
|
||||
|
||||
loadUserShelves(): Observable<MagicShelf[]> {
|
||||
private fetchMagicShelves(): Observable<MagicShelf[]> {
|
||||
return this.http.get<MagicShelf[]>(this.url).pipe(
|
||||
tap((shelves) => this.updateShelves(shelves)),
|
||||
catchError((error) => {
|
||||
this.updateError(error.message);
|
||||
return of([]);
|
||||
tap(shelves => this.shelvesStateSubject.next({shelves, loaded: true, error: null})),
|
||||
catchError(err => {
|
||||
const curr = this.shelvesStateSubject.value;
|
||||
this.shelvesStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -65,12 +102,13 @@ export class MagicShelfService {
|
||||
|
||||
return this.http.post<MagicShelf>(this.url, payload).pipe(
|
||||
tap((newShelf) => {
|
||||
const shelves = this.state.shelves;
|
||||
const curr = this.state;
|
||||
const shelves = curr.shelves || [];
|
||||
const updated = shelves.some((s) => s.id === newShelf.id)
|
||||
? shelves.map((s) => (s.id === newShelf.id ? newShelf : s))
|
||||
: [...shelves, newShelf];
|
||||
|
||||
this.updateShelves(updated);
|
||||
this.shelvesStateSubject.next({...curr, shelves: updated});
|
||||
}),
|
||||
catchError((error) => {
|
||||
this.updateError(error.message);
|
||||
@@ -81,15 +119,16 @@ export class MagicShelfService {
|
||||
|
||||
getShelf(id: number): Observable<MagicShelf | undefined> {
|
||||
return this.shelvesState$.pipe(
|
||||
map(state => state.shelves.find(shelf => shelf.id === id))
|
||||
map(state => (state.shelves || []).find(shelf => shelf.id === id))
|
||||
);
|
||||
}
|
||||
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
const updated = this.state.shelves.filter((s) => s.id !== id);
|
||||
this.updateShelves(updated);
|
||||
const curr = this.state;
|
||||
const updated = (curr.shelves || []).filter((s) => s.id !== id);
|
||||
this.shelvesStateSubject.next({...curr, shelves: updated});
|
||||
}),
|
||||
catchError((error) => {
|
||||
this.updateError(error.message);
|
||||
@@ -98,14 +137,6 @@ export class MagicShelfService {
|
||||
);
|
||||
}
|
||||
|
||||
private updateShelves(shelves: MagicShelf[]): void {
|
||||
this.shelvesStateSubject.next({
|
||||
shelves,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
|
||||
private updateError(error: string): void {
|
||||
this.shelvesStateSubject.next({
|
||||
...this.state,
|
||||
+7
-5
@@ -67,7 +67,6 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookService.loadBooks();
|
||||
const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
|
||||
if (bookIdFromDialog != null) {
|
||||
this.currentBookId$.next(bookIdFromDialog);
|
||||
@@ -126,10 +125,13 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
|
||||
this.userService.userState$
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(userData => {
|
||||
this.canEditMetadata = userData?.permissions?.canEditMetadata ?? false;
|
||||
this.admin = userData?.permissions?.admin ?? false;
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(userState => {
|
||||
this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false;
|
||||
this.admin = userState.user?.permissions?.admin ?? false;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+55
-13
@@ -303,11 +303,6 @@
|
||||
{{ getStatusLabel(selectedReadStatus) }}
|
||||
</span>
|
||||
<p-menu #menu [popup]="true" [model]="readStatusMenuItems"></p-menu>
|
||||
@if (selectedReadStatus === 'READ' && book?.dateFinished) {
|
||||
<span class="text-xs text-gray-400 ml-2">
|
||||
Finished on {{ formatDate(book.dateFinished) }}
|
||||
</span>
|
||||
}
|
||||
</p>
|
||||
@if (book?.koreaderProgress && book.koreaderProgress?.percentage != null) {
|
||||
<p class="whitespace-nowrap flex items-center">
|
||||
@@ -333,6 +328,53 @@
|
||||
</span>
|
||||
</p>
|
||||
}
|
||||
@if (selectedReadStatus === ReadStatus.READ) {
|
||||
<div>
|
||||
@if (book?.dateFinished) {
|
||||
<div class="flex items-center gap-2">
|
||||
<p><strong>Finished On: </strong></p>
|
||||
@if (!isEditingDateFinished) {
|
||||
<div class="flex items-center gap-2">
|
||||
<p>{{ formatDate(book.dateFinished) }}</p>
|
||||
<i class="pi pi-pencil text-[cornflowerblue] hover:text-[darkturquoise] cursor-pointer"
|
||||
(click)="toggleDateFinishedEdit(book)">
|
||||
</i>
|
||||
</div>
|
||||
} @else {
|
||||
<div class="flex items-center">
|
||||
<p-datepicker
|
||||
[(ngModel)]="editDateFinished"
|
||||
dateFormat="dd-M-yy"
|
||||
size="small"
|
||||
[showIcon]="true"
|
||||
iconDisplay="input"
|
||||
[style]="{ 'width': '125px', 'font-size': '12px' }"
|
||||
class="text-xs">
|
||||
</p-datepicker>
|
||||
<p-button
|
||||
rounded
|
||||
icon="pi pi-check"
|
||||
size="small"
|
||||
severity="success"
|
||||
text
|
||||
(onClick)="saveDateFinished(book)"
|
||||
pTooltip="Save date">
|
||||
</p-button>
|
||||
<p-button
|
||||
rounded
|
||||
icon="pi pi-times"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
(onClick)="cancelDateFinishedEdit()"
|
||||
pTooltip="Cancel">
|
||||
</p-button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<p><strong>Page Count:</strong> {{ book?.metadata!.pageCount || '-' }}</p>
|
||||
</div>
|
||||
|
||||
@@ -350,7 +392,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
<div class="flex flex-wrap gap-3 pt-6">
|
||||
@if (book!.bookType === 'PDF') {
|
||||
@if (readMenuItems$ | async; as readItems) {
|
||||
@@ -376,28 +418,28 @@
|
||||
outlined
|
||||
(onClick)="assignShelf(book.id)">
|
||||
</p-button>
|
||||
@if (userData.permissions.canDownload || userData.permissions.admin) {
|
||||
@if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
|
||||
<p-button
|
||||
label="Download"
|
||||
icon="pi pi-download"
|
||||
severity="success"
|
||||
outlined
|
||||
(onClick)="download(book.id)">
|
||||
(onClick)="download(book!.id)">
|
||||
</p-button>
|
||||
}
|
||||
@if (userData.permissions.canEmailBook || userData.permissions.admin) {
|
||||
@if (userState.user!.permissions.canEmailBook || userState.user!.permissions.admin) {
|
||||
@if (emailMenuItems$ | async; as emailItems) {
|
||||
<p-splitbutton
|
||||
label="Quick Send"
|
||||
icon="pi pi-send"
|
||||
[model]="emailItems"
|
||||
(onClick)="quickSend(book.id)"
|
||||
(onClick)="quickSend(book!.id)"
|
||||
outlined
|
||||
severity="info">
|
||||
</p-splitbutton>
|
||||
}
|
||||
}
|
||||
@if (userData.permissions.canEditMetadata || userData.permissions.admin) {
|
||||
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
|
||||
@if (refreshMenuItems$ | async; as refreshItems) {
|
||||
<p-splitbutton
|
||||
[label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'"
|
||||
@@ -405,14 +447,14 @@
|
||||
[outlined]="true"
|
||||
[model]="refreshItems"
|
||||
severity="warn"
|
||||
(onClick)="quickRefresh(book.id)"
|
||||
(onClick)="quickRefresh(book!.id)"
|
||||
[disabled]="isAutoFetching"
|
||||
pTooltip="Automatically fetch metadata using default sources"
|
||||
tooltipPosition="top">
|
||||
</p-splitbutton>
|
||||
}
|
||||
}
|
||||
@if (userData.permissions.canDeleteBook || userData.permissions.admin) {
|
||||
@if (userState.user!.permissions.canDeleteBook || userState.user!.permissions.admin) {
|
||||
@if (otherItems$ | async; as otherItems) {
|
||||
<p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button>
|
||||
<p-menu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-menu>
|
||||
|
||||
+50
-4
@@ -29,13 +29,14 @@ import {Menu} from 'primeng/menu';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {BookCardLiteComponent} from '../../../book/components/book-card-lite/book-card-lite-component';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {DatePicker} from 'primeng/datepicker';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-viewer',
|
||||
standalone: true,
|
||||
templateUrl: './metadata-viewer.component.html',
|
||||
styleUrl: './metadata-viewer.component.scss',
|
||||
imports: [Button, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent]
|
||||
imports: [Button, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, Editor, ProgressBar, Menu, InfiniteScrollDirective, BookCardLiteComponent, DatePicker]
|
||||
})
|
||||
export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
@Input() book$!: Observable<Book | null>;
|
||||
@@ -65,6 +66,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
isAutoFetching = false;
|
||||
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
|
||||
selectedReadStatus: ReadStatus = ReadStatus.UNREAD;
|
||||
isEditingDateFinished = false;
|
||||
editDateFinished: Date | null = null;
|
||||
|
||||
readStatusOptions: { value: ReadStatus, label: string }[] = [
|
||||
{value: ReadStatus.UNREAD, label: 'Unread'},
|
||||
@@ -164,11 +167,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
|
||||
this.userService.userState$
|
||||
.pipe(
|
||||
filter(user => !!user),
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(user => {
|
||||
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
.subscribe(userState => {
|
||||
this.metadataCenterViewMode = userState.user?.userSettings.metadataCenterViewMode ?? 'route';
|
||||
});
|
||||
|
||||
this.book$
|
||||
@@ -592,5 +595,48 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
});
|
||||
}
|
||||
|
||||
toggleDateFinishedEdit(book: Book): void {
|
||||
if (this.isEditingDateFinished) {
|
||||
this.isEditingDateFinished = false;
|
||||
this.editDateFinished = null;
|
||||
} else {
|
||||
this.isEditingDateFinished = true;
|
||||
this.editDateFinished = book.dateFinished ? new Date(book.dateFinished) : new Date();
|
||||
}
|
||||
}
|
||||
|
||||
saveDateFinished(book: Book): void {
|
||||
if (!book) return;
|
||||
|
||||
const dateToSave = this.editDateFinished ? this.editDateFinished.toISOString() : null;
|
||||
|
||||
this.bookService.updateDateFinished(book.id, dateToSave).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Date Updated',
|
||||
detail: 'Book finish date has been updated.',
|
||||
life: 1500
|
||||
});
|
||||
this.isEditingDateFinished = false;
|
||||
this.editDateFinished = null;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Update Failed',
|
||||
detail: 'Could not update book finish date.',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancelDateFinishedEdit(): void {
|
||||
this.isEditingDateFinished = false;
|
||||
this.editDateFinished = null;
|
||||
}
|
||||
|
||||
protected readonly ResetProgressTypes = ResetProgressTypes;
|
||||
protected readonly ReadStatus = ReadStatus;
|
||||
}
|
||||
|
||||
+14
-8
@@ -5,9 +5,9 @@ import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||
import {Book} from '../../book/model/book.model';
|
||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {BookService} from '../../book/service/book.service';
|
||||
import {BehaviorSubject, combineLatest, Observable, Subscription} from 'rxjs';
|
||||
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {distinctUntilChanged, filter, map, shareReplay, switchMap} from 'rxjs/operators';
|
||||
import {distinctUntilChanged, filter, map, shareReplay, switchMap, takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-multi-book-metadata-editor-component',
|
||||
@@ -41,13 +41,16 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
|
||||
private readonly bookService = inject(BookService);
|
||||
private readonly userService = inject(UserService);
|
||||
|
||||
private userSubscription: Subscription = Subscription.EMPTY;
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.bookIds = this.config.data?.bookIds ?? [];
|
||||
|
||||
this.userSubscription = this.userService.userState$.subscribe(userData => {
|
||||
const userPermissions = userData?.permissions;
|
||||
this.userService.userState$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
const userPermissions = userState.user?.permissions;
|
||||
this.canEditMetadata = userPermissions?.canEditMetadata ?? false;
|
||||
this.admin = userPermissions?.admin ?? false;
|
||||
});
|
||||
@@ -60,7 +63,8 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
|
||||
map(books => {
|
||||
this.filteredBooks = books;
|
||||
return books;
|
||||
})
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
);
|
||||
|
||||
this.book$ = combineLatest([filteredBooks$, this.currentIndex$]).pipe(
|
||||
@@ -70,12 +74,14 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
|
||||
switchMap(book =>
|
||||
this.bookService.getBookByIdFromAPI(book.id, true)
|
||||
),
|
||||
shareReplay(1)
|
||||
shareReplay(1),
|
||||
takeUntil(this.destroy$)
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.userSubscription.unsubscribe();
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
this.currentIndex$.complete();
|
||||
}
|
||||
|
||||
|
||||
+12
-7
@@ -1,14 +1,15 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
|
||||
import {Password} from 'primeng/password';
|
||||
import {User, UserService} from '../../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {Subject} from 'rxjs';
|
||||
import {Message} from 'primeng/message';
|
||||
import {filter, takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-profile-dialog',
|
||||
@@ -20,7 +21,7 @@ import {Message} from 'primeng/message';
|
||||
InputText,
|
||||
Password,
|
||||
Message
|
||||
],
|
||||
],
|
||||
templateUrl: './user-profile-dialog.component.html',
|
||||
styleUrls: ['./user-profile-dialog.component.scss']
|
||||
})
|
||||
@@ -29,7 +30,7 @@ export class UserProfileDialogComponent implements OnInit, OnDestroy {
|
||||
isEditing = false;
|
||||
currentUser: User | null = null;
|
||||
editUserData: Partial<User> = {};
|
||||
private userSubscription: Subscription | null = null;
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
changePasswordForm: FormGroup;
|
||||
|
||||
@@ -51,14 +52,18 @@ export class UserProfileDialogComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userSubscription = this.userService.userState$.subscribe(user => {
|
||||
this.currentUser = user;
|
||||
this.userService.userState$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
this.currentUser = userState.user;
|
||||
this.resetEditForm();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.userSubscription?.unsubscribe();
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
static passwordsMatchValidator(form: FormGroup) {
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {User, UserService, UserSettings} from '../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {filter, takeUntil} from 'rxjs/operators';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ReaderPreferencesService {
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class ReaderPreferencesService implements OnDestroy {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private currentUser: User | null = null;
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
constructor() {
|
||||
this.userService.userState$.subscribe(user => this.currentUser = user);
|
||||
this.userService.userState$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => this.currentUser = userState.user);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
updatePreference(path: string[], value: any): void {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {filter, takeUntil} from 'rxjs/operators';
|
||||
|
||||
import {Observable, Subscription} from 'rxjs';
|
||||
import {Observable, Subject} from 'rxjs';
|
||||
import {RadioButton} from 'primeng/radiobutton';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {User, UserService, UserSettings} from '../user-management/user.service';
|
||||
import {UserService, UserSettings, UserState} from '../user-management/user.service';
|
||||
import {EpubReaderPreferencesComponent} from './epub-reader-preferences-component/epub-reader-preferences-component';
|
||||
import {PdfReaderPreferencesComponent} from './pdf-reader-preferences-component/pdf-reader-preferences-component';
|
||||
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences-component/cbx-reader-preferences-component';
|
||||
@@ -27,22 +28,24 @@ export class ReaderPreferences implements OnInit, OnDestroy {
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly readerPreferencesService = inject(ReaderPreferencesService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
userData$: Observable<User | null> = this.userService.userState$;
|
||||
private subscription?: Subscription;
|
||||
userData$: Observable<UserState> = this.userService.userState$;
|
||||
userSettings!: UserSettings;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.subscription = this.userData$.subscribe(user => {
|
||||
if (user) {
|
||||
this.userSettings = user.userSettings;
|
||||
this.loadPreferences(user.userSettings);
|
||||
}
|
||||
this.userData$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
this.userSettings = userState.user!.userSettings;
|
||||
this.loadPreferences(userState.user!.userSettings);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadPreferences(settings: UserSettings): void {
|
||||
|
||||
@@ -1,80 +1,82 @@
|
||||
@if (userService.userState$ | async; as userData) {
|
||||
<div>
|
||||
<div class="rounded-xl overflow-hidden">
|
||||
<p-tabs [(value)]="activeTab" scrollable>
|
||||
<p-tablist>
|
||||
<p-tab [value]="SettingsTab.ReaderSettings">
|
||||
<i class="pi pi-book"></i> Reader
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.ViewPreferences">
|
||||
<i class="pi pi-desktop"></i> View
|
||||
</p-tab>
|
||||
@if (userData.permissions.admin) {
|
||||
<p-tab [value]="SettingsTab.MetadataSettings">
|
||||
<i class="pi pi-sliders-h"></i> Metadata
|
||||
@if (userService.userState$ | async; as userState) {
|
||||
@if (userState.user) {
|
||||
<div>
|
||||
<div class="rounded-xl overflow-hidden">
|
||||
<p-tabs [(value)]="activeTab" scrollable>
|
||||
<p-tablist>
|
||||
<p-tab [value]="SettingsTab.ReaderSettings">
|
||||
<i class="pi pi-book"></i> Reader
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.ApplicationSettings">
|
||||
<i class="pi pi-cog"></i> Application
|
||||
<p-tab [value]="SettingsTab.ViewPreferences">
|
||||
<i class="pi pi-desktop"></i> View
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.UserManagement">
|
||||
<i class="pi pi-users"></i> User
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.EmailSettings">
|
||||
<i class="pi pi-envelope"></i> Email
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.NamingPattern">
|
||||
<i class="pi pi-sitemap"></i> Patterns
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.AuthenticationSettings">
|
||||
<i class="pi pi-lock"></i> Authentication
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.Opds">
|
||||
<i class="pi pi-globe"></i> OPDS
|
||||
</p-tab>
|
||||
}
|
||||
@if (userData.permissions.admin || userData.permissions.canSyncKoReader) {
|
||||
<p-tab [value]="SettingsTab.DeviceSettings">
|
||||
<i class="pi pi-mobile"></i> Devices
|
||||
</p-tab>
|
||||
}
|
||||
</p-tablist>
|
||||
<p-tabpanels>
|
||||
<p-tabpanel [value]="SettingsTab.ReaderSettings">
|
||||
<app-reader-preferences></app-reader-preferences>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.ViewPreferences">
|
||||
<app-view-preferences-parent></app-view-preferences-parent>
|
||||
</p-tabpanel>
|
||||
@if (userData.permissions.admin) {
|
||||
<p-tabpanel [value]="SettingsTab.MetadataSettings">
|
||||
<app-metadata-settings-component></app-metadata-settings-component>
|
||||
@if (userState.user.permissions.admin) {
|
||||
<p-tab [value]="SettingsTab.MetadataSettings">
|
||||
<i class="pi pi-sliders-h"></i> Metadata
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.ApplicationSettings">
|
||||
<i class="pi pi-cog"></i> Application
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.UserManagement">
|
||||
<i class="pi pi-users"></i> User
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.EmailSettings">
|
||||
<i class="pi pi-envelope"></i> Email
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.NamingPattern">
|
||||
<i class="pi pi-sitemap"></i> Patterns
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.AuthenticationSettings">
|
||||
<i class="pi pi-lock"></i> Authentication
|
||||
</p-tab>
|
||||
<p-tab [value]="SettingsTab.Opds">
|
||||
<i class="pi pi-globe"></i> OPDS
|
||||
</p-tab>
|
||||
}
|
||||
@if (userState.user.permissions.admin || userState.user.permissions.canSyncKoReader) {
|
||||
<p-tab [value]="SettingsTab.DeviceSettings">
|
||||
<i class="pi pi-mobile"></i> Devices
|
||||
</p-tab>
|
||||
}
|
||||
</p-tablist>
|
||||
<p-tabpanels>
|
||||
<p-tabpanel [value]="SettingsTab.ReaderSettings">
|
||||
<app-reader-preferences></app-reader-preferences>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.ApplicationSettings">
|
||||
<app-global-preferences></app-global-preferences>
|
||||
<p-tabpanel [value]="SettingsTab.ViewPreferences">
|
||||
<app-view-preferences-parent></app-view-preferences-parent>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.UserManagement">
|
||||
<app-user-management></app-user-management>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.EmailSettings">
|
||||
<app-email></app-email>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.NamingPattern">
|
||||
<app-file-naming-pattern></app-file-naming-pattern>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.AuthenticationSettings">
|
||||
<app-authentication-settings></app-authentication-settings>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.Opds">
|
||||
<app-opds-settings></app-opds-settings>
|
||||
</p-tabpanel>
|
||||
}
|
||||
@if (userData.permissions.admin || userData.permissions.canSyncKoReader) {
|
||||
<p-tabpanel [value]="SettingsTab.DeviceSettings">
|
||||
<app-device-settings-component></app-device-settings-component>
|
||||
</p-tabpanel>
|
||||
}
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
@if (userState.user.permissions.admin) {
|
||||
<p-tabpanel [value]="SettingsTab.MetadataSettings">
|
||||
<app-metadata-settings-component></app-metadata-settings-component>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.ApplicationSettings">
|
||||
<app-global-preferences></app-global-preferences>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.UserManagement">
|
||||
<app-user-management></app-user-management>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.EmailSettings">
|
||||
<app-email></app-email>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.NamingPattern">
|
||||
<app-file-naming-pattern></app-file-naming-pattern>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.AuthenticationSettings">
|
||||
<app-authentication-settings></app-authentication-settings>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel [value]="SettingsTab.Opds">
|
||||
<app-opds-settings></app-opds-settings>
|
||||
</p-tabpanel>
|
||||
}
|
||||
@if (userState.user.permissions.admin || userState.user.permissions.canSyncKoReader) {
|
||||
<p-tabpanel [value]="SettingsTab.DeviceSettings">
|
||||
<app-device-settings-component></app-device-settings-component>
|
||||
</p-tabpanel>
|
||||
}
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import { LowerCasePipe, NgStyle, TitleCasePipe } from '@angular/common';
|
||||
import {LowerCasePipe, NgStyle, TitleCasePipe} from '@angular/common';
|
||||
import {User, UserService} from './user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
@@ -13,7 +13,8 @@ import {Library} from '../../book/model/library.model';
|
||||
import {LibraryService} from '../../book/service/library.service';
|
||||
import {Dialog} from 'primeng/dialog';
|
||||
import {Password} from 'primeng/password';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {filter, take, takeUntil} from 'rxjs/operators';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-management',
|
||||
@@ -28,19 +29,20 @@ import {filter, take} from 'rxjs/operators';
|
||||
Password,
|
||||
LowerCasePipe,
|
||||
TitleCasePipe
|
||||
],
|
||||
],
|
||||
templateUrl: './user-management.component.html',
|
||||
styleUrls: ['./user-management.component.scss'],
|
||||
})
|
||||
export class UserManagementComponent implements OnInit {
|
||||
export class UserManagementComponent implements OnInit, OnDestroy {
|
||||
ref: DynamicDialogRef | undefined;
|
||||
private dialogService = inject(DialogService);
|
||||
private userService = inject(UserService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private messageService = inject(MessageService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
users: User[] = [];
|
||||
currentUser: User | undefined;
|
||||
currentUser: User | null = null;
|
||||
editingLibraryIds: number[] = [];
|
||||
allLibraries: Library[] = [];
|
||||
|
||||
@@ -49,19 +51,36 @@ export class UserManagementComponent implements OnInit {
|
||||
newPassword = '';
|
||||
confirmNewPassword = '';
|
||||
passwordError = '';
|
||||
isAdmin = false;
|
||||
|
||||
ngOnInit() {
|
||||
this.loadUsers();
|
||||
|
||||
this.userService.userState$
|
||||
.pipe(filter(user => !!user), take(1))
|
||||
.subscribe(user => this.currentUser = user);
|
||||
.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(userState => {
|
||||
this.currentUser = userState.user;
|
||||
this.isAdmin = userState.user?.permissions?.admin || false;
|
||||
});
|
||||
|
||||
this.libraryService.libraryState$
|
||||
.pipe(filter(state => !!state?.loaded), take(1))
|
||||
.pipe(
|
||||
filter(state => !!state?.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe(libraries => this.allLibraries = libraries.libraries ?? []);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
|
||||
loadUsers() {
|
||||
this.userService.getUsers().subscribe({
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import {inject, Injectable, Injector} from '@angular/core';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||
import {Library} from '../../book/model/library.model';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
import {catchError, distinctUntilChanged, finalize, shareReplay, tap} from 'rxjs/operators';
|
||||
import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
|
||||
export interface EntityViewPreferences {
|
||||
@@ -113,6 +111,12 @@ export interface User {
|
||||
provisioningMethod?: 'LOCAL' | 'OIDC' | 'REMOTE';
|
||||
}
|
||||
|
||||
export interface UserState {
|
||||
user: User | null;
|
||||
loaded: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -121,16 +125,70 @@ export class UserService {
|
||||
private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
|
||||
private userStateSubject = new BehaviorSubject<User | null>(null);
|
||||
userState$ = this.userStateSubject.asObservable();
|
||||
private userStateSubject = new BehaviorSubject<UserState>({
|
||||
user: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
private loading$: Observable<User> | null = null;
|
||||
|
||||
constructor() {
|
||||
this.authService.token$.pipe(
|
||||
distinctUntilChanged()
|
||||
).subscribe(token => {
|
||||
if (token === null) {
|
||||
this.userStateSubject.next({
|
||||
user: null,
|
||||
loaded: true,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
} else {
|
||||
const current = this.userStateSubject.value;
|
||||
if (current.loaded && !current.user) {
|
||||
this.userStateSubject.next({
|
||||
user: null,
|
||||
loaded: false,
|
||||
error: null,
|
||||
});
|
||||
this.loading$ = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
userState$ = this.userStateSubject.asObservable().pipe(
|
||||
tap(state => {
|
||||
if (!state.loaded && !state.error && !this.loading$) {
|
||||
this.loading$ = this.fetchMyself().pipe(
|
||||
shareReplay(1),
|
||||
finalize(() => (this.loading$ = null))
|
||||
);
|
||||
this.loading$.subscribe();
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
private fetchMyself(): Observable<User> {
|
||||
return this.http.get<User>(`${this.userUrl}/me`).pipe(
|
||||
tap(user => this.userStateSubject.next({ user, loaded: true, error: null })),
|
||||
catchError(err => {
|
||||
const curr = this.userStateSubject.value;
|
||||
this.userStateSubject.next({ user: curr.user, loaded: true, error: err.message });
|
||||
throw err;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
public setInitialUser(user: User): void {
|
||||
this.userStateSubject.next(user);
|
||||
this.userStateSubject.next({ user, loaded: true, error: null });
|
||||
}
|
||||
|
||||
getCurrentUser(): User | null {
|
||||
return this.userStateSubject.getValue();
|
||||
return this.userStateSubject.value.user;
|
||||
}
|
||||
|
||||
getMyself(): Observable<User> {
|
||||
@@ -188,11 +246,11 @@ export class UserService {
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
responseType: 'text' as 'json'
|
||||
}).subscribe(() => {
|
||||
const currentUser = this.userStateSubject.getValue();
|
||||
if (currentUser) {
|
||||
const updatedSettings = {...currentUser.userSettings, [key]: value};
|
||||
const updatedUser = {...currentUser, settings: updatedSettings};
|
||||
this.userStateSubject.next(updatedUser);
|
||||
const currentState = this.userStateSubject.value;
|
||||
if (currentState.user) {
|
||||
const updatedSettings = {...currentState.user.userSettings, [key]: value};
|
||||
const updatedUser = {...currentState.user, userSettings: updatedSettings};
|
||||
this.userStateSubject.next({...currentState, user: updatedUser});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+16
-5
@@ -1,10 +1,11 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {RadioButton} from 'primeng/radiobutton';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {UserService} from '../../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {take} from 'rxjs/operators';
|
||||
import {filter, take, takeUntil} from 'rxjs/operators';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-meta-center-view-mode-component',
|
||||
@@ -16,21 +17,31 @@ import {take} from 'rxjs/operators';
|
||||
templateUrl: './meta-center-view-mode-component.html',
|
||||
styleUrl: './meta-center-view-mode-component.scss'
|
||||
})
|
||||
export class MetaCenterViewModeComponent implements OnInit {
|
||||
export class MetaCenterViewModeComponent implements OnInit, OnDestroy {
|
||||
viewMode: 'route' | 'dialog' = 'route';
|
||||
|
||||
private userService = inject(UserService);
|
||||
private messageService = inject(MessageService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userService.userState$.pipe(take(1)).subscribe(user => {
|
||||
const preference = user?.userSettings?.metadataCenterViewMode;
|
||||
this.userService.userState$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
const preference = userState.user?.userSettings?.metadataCenterViewMode;
|
||||
if (preference === 'dialog' || preference === 'route') {
|
||||
this.viewMode = preference;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
onViewModeChange(value: 'route' | 'dialog'): void {
|
||||
this.viewMode = value;
|
||||
this.savePreference(value);
|
||||
|
||||
+13
-10
@@ -1,10 +1,11 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Select} from 'primeng/select';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {SidebarLibrarySorting, SidebarShelfSorting, User, UserService, UserSettings} from '../../user-management/user.service';
|
||||
import {SidebarLibrarySorting, SidebarShelfSorting, User, UserService, UserSettings, UserState} from '../../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Observable, Subscription} from 'rxjs';
|
||||
import {Observable, Subject} from 'rxjs';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {filter, takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-sidebar-sorting-preferences',
|
||||
@@ -30,22 +31,24 @@ export class SidebarSortingPreferencesComponent implements OnInit, OnDestroy {
|
||||
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
userData$: Observable<User | null> = this.userService.userState$;
|
||||
private subscription?: Subscription;
|
||||
userData$: Observable<UserState> = this.userService.userState$;
|
||||
private currentUser: User | null = null;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.subscription = this.userData$.subscribe(user => {
|
||||
if (user) {
|
||||
this.currentUser = user;
|
||||
this.loadPreferences(user.userSettings);
|
||||
}
|
||||
this.userData$.pipe(
|
||||
filter(userState => !!userState?.user && userState.loaded),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(userState => {
|
||||
this.currentUser = userState.user;
|
||||
this.loadPreferences(userState.user!.userSettings);
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadPreferences(settings: UserSettings): void {
|
||||
|
||||
+16
-8
@@ -1,4 +1,4 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
|
||||
import {MessageService} from 'primeng/api';
|
||||
@@ -8,10 +8,10 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
import {User, UserService} from '../../user-management/user.service';
|
||||
import {LibraryService} from '../../../book/service/library.service';
|
||||
import {ShelfService} from '../../../book/service/shelf.service';
|
||||
import {combineLatest} from 'rxjs';
|
||||
import {combineLatest, Subject} from 'rxjs';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {ToastModule} from 'primeng/toast';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {filter, take, takeUntil} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-view-preferences',
|
||||
@@ -27,7 +27,7 @@ import {filter, take} from 'rxjs/operators';
|
||||
templateUrl: './view-preferences.component.html',
|
||||
styleUrl: './view-preferences.component.scss'
|
||||
})
|
||||
export class ViewPreferencesComponent implements OnInit {
|
||||
export class ViewPreferencesComponent implements OnInit, OnDestroy {
|
||||
sortOptions = [
|
||||
{label: 'Title', field: 'title'},
|
||||
{label: 'Title + Series', field: 'titleSeries'},
|
||||
@@ -78,6 +78,7 @@ export class ViewPreferencesComponent implements OnInit {
|
||||
}[] = [];
|
||||
|
||||
private user: User | null = null;
|
||||
private readonly destroy$ = new Subject<void>();
|
||||
|
||||
private libraryService = inject(LibraryService);
|
||||
private shelfService = inject(ShelfService);
|
||||
@@ -86,13 +87,15 @@ export class ViewPreferencesComponent implements OnInit {
|
||||
|
||||
ngOnInit(): void {
|
||||
combineLatest([
|
||||
this.userService.userState$.pipe(filter(user => !!user), take(1)),
|
||||
this.userService.userState$.pipe(filter(userState => !!userState?.user && userState.loaded), take(1)),
|
||||
this.libraryService.libraryState$.pipe(filter(libraryState => !!libraryState?.libraries && libraryState.loaded), take(1)),
|
||||
this.shelfService.shelfState$.pipe(filter(shelfState => !!shelfState?.shelves && shelfState.loaded), take(1)),
|
||||
]).subscribe(([userState, librariesState, shelfState]) => {
|
||||
]).pipe(
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(([userState, librariesState, shelfState]) => {
|
||||
|
||||
this.user = userState;
|
||||
const prefs = userState?.userSettings?.entityViewPreferences;
|
||||
this.user = userState.user;
|
||||
const prefs = userState.user?.userSettings?.entityViewPreferences;
|
||||
const global = prefs?.global;
|
||||
this.selectedSort = global?.sortKey ?? 'title';
|
||||
this.selectedSortDir = global?.sortDir ?? 'ASC';
|
||||
@@ -118,6 +121,11 @@ export class ViewPreferencesComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
getAvailableEntities(index: number, type: 'LIBRARY' | 'SHELF') {
|
||||
const selected = this.overrides.map((o, i) => i !== index ? o.library : null);
|
||||
const source = type === 'LIBRARY' ? this.libraryOptions : this.shelfOptions;
|
||||
|
||||
+46
-70
@@ -2,81 +2,57 @@
|
||||
|
||||
<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
|
||||
File Organization Preview
|
||||
</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">Move Files</span> to proceed.
|
||||
<span class="text-yellow-500 font-medium flex items-center gap-2">
|
||||
<div class="text-sm text-gray-300 space-y-3">
|
||||
<p>
|
||||
Your files will be automatically renamed and organized based on your library's naming rules.
|
||||
Check the preview below to see how your files will look, 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></span>
|
||||
</p>
|
||||
<p 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>
|
||||
}
|
||||
This will actually move and rename files on your computer, 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">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="movePattern"
|
||||
(ngModelChange)="applyPattern()"
|
||||
[placeholder]="movePattern.trim() ? '' : getDefaultPattern()"
|
||||
class="flex-1"
|
||||
/>
|
||||
<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>
|
||||
|
||||
<p-button
|
||||
icon="pi pi-save"
|
||||
label="Make Default"
|
||||
severity="info"
|
||||
outlined
|
||||
(click)="setDefaultPattern()"
|
||||
></p-button>
|
||||
@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-grow overflow-y-auto mt-4">
|
||||
<div class="flex-grow overflow-y-auto">
|
||||
<p-table
|
||||
[value]="filePreviews"
|
||||
[responsiveLayout]="'scroll'"
|
||||
@@ -84,7 +60,7 @@
|
||||
>
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th style="width: 0.5rem; text-align: center;">ID</th>
|
||||
<th>ID</th>
|
||||
<th>Current Path</th>
|
||||
<th></th>
|
||||
<th>New Path</th>
|
||||
@@ -95,13 +71,13 @@
|
||||
<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>
|
||||
<span class="text-gray-400 select-none">{{ preview.libraryPathPrefix }}/</span><span class="text-gray-200">{{ 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>
|
||||
<span class="text-gray-400 select-none">{{ preview.libraryPathPrefix }}/</span><span class="text-gray-200">{{ preview.relativeNewPath }}</span>
|
||||
</p>
|
||||
</td>
|
||||
<td class="w-auto text-center">
|
||||
|
||||
+99
-69
@@ -1,28 +1,27 @@
|
||||
import {Component, inject} from '@angular/core';
|
||||
import {Component, inject, OnDestroy} 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 {filter, take, takeUntil} from 'rxjs/operators';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {FileMoveRequest, FileOperationsService} from '../../service/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],
|
||||
imports: [Button, FormsModule, TableModule, Divider],
|
||||
templateUrl: './file-mover-component.html',
|
||||
styleUrl: './file-mover-component.scss'
|
||||
})
|
||||
export class FileMoverComponent {
|
||||
export class FileMoverComponent implements OnDestroy {
|
||||
private config = inject(DynamicDialogConfig);
|
||||
private ref = inject(DynamicDialogRef);
|
||||
private bookService = inject(BookService);
|
||||
@@ -30,10 +29,18 @@ export class FileMoverComponent {
|
||||
private fileOperationsService = inject(FileOperationsService);
|
||||
private messageService = inject(MessageService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
movePattern = '';
|
||||
placeholdersVisible = false;
|
||||
libraryPatterns: {
|
||||
libraryId: number | null;
|
||||
libraryName: string;
|
||||
pattern: string;
|
||||
source: string;
|
||||
bookCount: number;
|
||||
}[] = [];
|
||||
defaultMovePattern = '';
|
||||
loading = false;
|
||||
patternsCollapsed = false;
|
||||
|
||||
bookIds: Set<number> = new Set();
|
||||
books: Book[] = [];
|
||||
@@ -42,12 +49,69 @@ export class FileMoverComponent {
|
||||
constructor() {
|
||||
this.bookIds = new Set(this.config.data?.bookIds ?? []);
|
||||
this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]);
|
||||
this.loadDefaultPattern();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
|
||||
private loadDefaultPattern(): void {
|
||||
this.appSettingsService.appSettings$.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
take(1),
|
||||
takeUntil(this.destroy$)
|
||||
).subscribe(settings => {
|
||||
this.movePattern = settings?.movePattern;
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -66,6 +130,14 @@ export class FileMoverComponent {
|
||||
: '';
|
||||
const originalPath = `${libraryPathPrefix}/${relativeOriginalPath}`.replace(/\/\/+/g, '/');
|
||||
|
||||
const bookLibraryId =
|
||||
book.libraryId ??
|
||||
book.libraryPath?.id ??
|
||||
(book as any).library?.id ??
|
||||
null;
|
||||
const libraryPattern = this.libraryPatterns.find(p => p.libraryId === bookLibraryId);
|
||||
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'),
|
||||
@@ -80,11 +152,10 @@ export class FileMoverComponent {
|
||||
|
||||
let newPath: string;
|
||||
|
||||
if (!this.movePattern?.trim()) {
|
||||
// If pattern empty, just use current filename as the new path
|
||||
newPath = `${fileSubPath}${fileName}`; // preserve subpath + filename
|
||||
if (!pattern?.trim()) {
|
||||
newPath = `${fileSubPath}${fileName}`;
|
||||
} else {
|
||||
newPath = this.movePattern.replace(/<([^<>]+)>/g, (_, block) => {
|
||||
newPath = pattern.replace(/<([^<>]+)>/g, (_, block) => {
|
||||
const placeholders = [...block.matchAll(/{(.*?)}/g)].map(m => m[1]);
|
||||
const allHaveValues = placeholders.every(key => values[key]?.trim());
|
||||
return allHaveValues
|
||||
@@ -94,7 +165,6 @@ export class FileMoverComponent {
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -111,6 +181,7 @@ export class FileMoverComponent {
|
||||
newPath: fullNewPath,
|
||||
relativeNewPath
|
||||
};
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -136,35 +207,23 @@ export class FileMoverComponent {
|
||||
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
|
||||
bookIds: [...this.bookIds]
|
||||
};
|
||||
|
||||
this.fileOperationsService.moveFiles(request).subscribe({
|
||||
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 Moved',
|
||||
detail: `${this.filePreviews.length} file(s) successfully relocated.`,
|
||||
summary: 'Files Organized!',
|
||||
detail: `Successfully organized ${this.filePreviews.length} file${this.filePreviews.length === 1 ? '' : 's'}.`,
|
||||
life: 3000
|
||||
});
|
||||
},
|
||||
@@ -172,48 +231,19 @@ export class FileMoverComponent {
|
||||
this.loading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Move Failed',
|
||||
detail: 'An error occurred while moving the files.',
|
||||
summary: 'Oops! Something went wrong',
|
||||
detail: 'We had trouble organizing your files. Please try again.',
|
||||
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();
|
||||
}
|
||||
|
||||
togglePatternsCollapsed(): void {
|
||||
this.patternsCollapsed = !this.patternsCollapsed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
export interface FileMoveRequest {
|
||||
bookIds: number[];
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
|
||||
Reference in New Issue
Block a user