feat: ComicInfo.xml support for CBX files (#1073)
* write, read ComicInfo.xml for CBZ files * updated with recommendations from previous PR https://github.com/booklore-app/booklore/pull/1069 * read ComicInfo.xml on CBR, extract first image for CBZ/CBR files, save CBR metadata in ComicInfo.xml as CBZ * Delete CBR file after CBZ conversion. Update DB * Backs up file before updating. Restores back up if errored * Test classes * Update booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java Updating RAR binary availability check Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Code updates from PR suggestions * Support to extract ComicInfo.xml for .cb7 files * Writer extension for .cb7 files * Adding com.github.junrar to build.gradle (forgot in previous commit) * Settings toggle to control CBR/CB7 to CBZ conversion * indentation complains * removed duplicated junrar inport * Restore comicinfo.xml metadata in edit view * retrieve ComicInfo.xml metadata for new files in library scan * private class definition was missed after merge * Delete --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -60,6 +60,9 @@ dependencies {
|
||||
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0'
|
||||
implementation 'io.documentnode:epub4j-core:4.2.2'
|
||||
|
||||
// --- UNRAR Support ---
|
||||
implementation 'com.github.junrar:junrar:7.5.5'
|
||||
|
||||
// --- JSON & Web Scraping ---
|
||||
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.19.2'
|
||||
implementation 'org.jsoup:jsoup:1.21.1'
|
||||
@@ -71,7 +74,6 @@ dependencies {
|
||||
// --- API Documentation ---
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.9'
|
||||
implementation 'org.apache.commons:commons-compress:1.28.0'
|
||||
implementation 'com.github.junrar:junrar:7.5.5'
|
||||
implementation 'org.apache.commons:commons-text:1.14.0'
|
||||
|
||||
// --- Test Dependencies ---
|
||||
|
||||
@@ -36,6 +36,7 @@ public class BookController {
|
||||
|
||||
private final BookService bookService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
private final BookMetadataService bookMetadataService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
@@ -59,6 +60,12 @@ public class BookController {
|
||||
return ResponseEntity.ok(bookService.getBooksByIds(ids, withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cbx/metadata/comicinfo")
|
||||
public ResponseEntity<?> getComicInfoMetadata(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookMetadataService.getComicInfoMetadata(bookId));
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/{bookId}/content")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
|
||||
|
||||
+1
@@ -11,6 +11,7 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
public class MetadataPersistenceSettings {
|
||||
private boolean saveToOriginalFile;
|
||||
private boolean convertCbrCb7ToCbz;
|
||||
private boolean backupMetadata;
|
||||
private boolean backupCover;
|
||||
}
|
||||
|
||||
+1
@@ -183,6 +183,7 @@ public class SettingPersistenceHelper {
|
||||
public MetadataPersistenceSettings getDefaultMetadataPersistenceSettings() {
|
||||
return MetadataPersistenceSettings.builder()
|
||||
.saveToOriginalFile(false)
|
||||
.convertCbrCb7ToCbz(false)
|
||||
.backupMetadata(false)
|
||||
.backupCover(false)
|
||||
.build();
|
||||
|
||||
+43
-2
@@ -1,13 +1,16 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
@@ -28,11 +31,13 @@ import java.util.*;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CbxProcessor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
|
||||
public CbxProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
@@ -40,9 +45,11 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
BookMetadataRepository bookMetadataRepository,
|
||||
MetadataMatchService metadataMatchService) {
|
||||
MetadataMatchService metadataMatchService,
|
||||
CbxMetadataExtractor cbxMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.bookMetadataRepository = bookMetadataRepository;
|
||||
this.cbxMetadataExtractor = cbxMetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -51,7 +58,8 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
if (generateCover(bookEntity)) {
|
||||
fileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
|
||||
extractAndSetMetadata(bookEntity);
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@@ -167,6 +175,39 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private void extractAndSetMetadata(BookEntity bookEntity) {
|
||||
try {
|
||||
BookMetadata extracted = cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
|
||||
if (extracted == null) {
|
||||
// Fallback to filename-derived title
|
||||
setMetadata(bookEntity);
|
||||
return;
|
||||
}
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
metadata.setTitle(truncate(extracted.getTitle(), 1000));
|
||||
metadata.setDescription(truncate(extracted.getDescription(), 5000));
|
||||
metadata.setPublisher(truncate(extracted.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(extracted.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(extracted.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(extracted.getSeriesNumber());
|
||||
metadata.setSeriesTotal(extracted.getSeriesTotal());
|
||||
metadata.setPageCount(extracted.getPageCount());
|
||||
metadata.setLanguage(truncate(extracted.getLanguage(), 1000));
|
||||
|
||||
if (extracted.getAuthors() != null) {
|
||||
bookCreatorService.addAuthorsToBook(extracted.getAuthors(), bookEntity);
|
||||
}
|
||||
if (extracted.getCategories() != null) {
|
||||
bookCreatorService.addCategoriesToBook(extracted.getCategories(), bookEntity);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract ComicInfo metadata for '{}': {}", bookEntity.getFileName(), e.getMessage());
|
||||
// Fallback to filename-derived title
|
||||
setMetadata(bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private void setMetadata(BookEntity bookEntity) {
|
||||
String baseName = new File(bookEntity.getFileName()).getName();
|
||||
String title = baseName
|
||||
|
||||
+20
-2
@@ -11,8 +11,10 @@ import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.BulkMetadataUpdateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.Lock;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
@@ -27,9 +29,11 @@ import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestore;
|
||||
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.parser.BookParser;
|
||||
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -37,6 +41,7 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
@@ -67,6 +72,7 @@ public class BookMetadataService {
|
||||
private final BookQueryService bookQueryService;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
private final MetadataBackupRestoreFactory metadataBackupRestoreFactory;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final MetadataWriterFactory metadataWriterFactory;
|
||||
private final MetadataClearFlagsMapper metadataClearFlagsMapper;
|
||||
|
||||
@@ -163,8 +169,10 @@ public class BookMetadataService {
|
||||
|
||||
private BookMetadata updateCover(Long bookId, BiConsumer<MetadataWriter, BookEntity> writerAction) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
if (appSettingService.getAppSettings().getMetadataPersistenceSettings().isSaveToOriginalFile()) {
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean saveToOriginalFile = settings.isSaveToOriginalFile();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(bookEntity.getBookType())
|
||||
.ifPresent(writer -> writerAction.accept(writer, bookEntity));
|
||||
}
|
||||
@@ -219,6 +227,16 @@ public class BookMetadataService {
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
}
|
||||
|
||||
public BookMetadata getComicInfoMetadata(long bookId) {
|
||||
log.info("Extracting ComicInfo metadata for book ID: {}", bookId);
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
if (bookEntity.getBookType() != BookFileType.CBX) {
|
||||
log.info("Unsupported operation for file type: {}", bookEntity.getBookType().name());
|
||||
return null;
|
||||
}
|
||||
return cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
|
||||
}
|
||||
|
||||
public BookMetadata restoreMetadataFromBackup(Long bookId) throws IOException {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
metadataBackupRestoreFactory.getService(bookEntity.getBookType()).restoreEmbeddedMetadata(bookEntity);
|
||||
|
||||
+27
-3
@@ -74,11 +74,12 @@ public class BookMetadataUpdater {
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean writeToFile = settings.isSaveToOriginalFile();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
boolean backupEnabled = settings.isBackupMetadata();
|
||||
boolean backupCover = settings.isBackupCover();
|
||||
BookFileType bookType = bookEntity.getBookType();
|
||||
|
||||
if (writeToFile && backupEnabled) {
|
||||
if (writeToFile && backupEnabled && (bookType != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
try {
|
||||
MetadataBackupRestore service = metadataBackupRestoreFactory.getService(bookType);
|
||||
if (service != null) {
|
||||
@@ -104,7 +105,10 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
|
||||
if ((writeToFile && hasValueChanges) || thumbnailRequiresUpdate) {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
if (bookType == BookFileType.CBX && !convertCbrCb7ToCbz) {
|
||||
log.info("CBX metadata writing disabled for book ID {}", bookId);
|
||||
} else {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
try {
|
||||
String thumbnailUrl = setThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
|
||||
@@ -115,12 +119,32 @@ public class BookMetadataUpdater {
|
||||
|
||||
File file = new File(bookEntity.getFullFilePath().toUri());
|
||||
writer.writeMetadataToFile(file, metadata, thumbnailUrl, false, clearFlags);
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
|
||||
String newHash = "";
|
||||
|
||||
// Special handling: If original file was .cbr or .cb7 and now .cbz exists, update to .cbz
|
||||
File resultingFile = file;
|
||||
if (!file.exists()) {
|
||||
// Replace last extension .cbr or .cb7 (case-insensitive) with .cbz
|
||||
String cbzName = file.getName().replaceFirst("(?i)\\.(cbr|cb7)$", ".cbz");
|
||||
File cbzFile = new File(file.getParentFile(), cbzName);
|
||||
if (cbzFile.exists()) {
|
||||
bookEntity.setFileName(cbzName);
|
||||
resultingFile = cbzFile;
|
||||
}
|
||||
bookEntity.setFileSizeKb(resultingFile.length() / 1024);
|
||||
log.info("Converted to CBZ: {} -> {}", file.getAbsolutePath(), resultingFile.getAbsolutePath());
|
||||
newHash = FileFingerprint.generateHash(resultingFile.toPath());
|
||||
} else {
|
||||
newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
}
|
||||
|
||||
bookEntity.setCurrentHash(newHash);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.service.metadata.backuprestore;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
@@ -103,8 +105,10 @@ public class BookMetadataRestorer {
|
||||
}
|
||||
|
||||
try {
|
||||
boolean saveToOriginal = appSettingService.getAppSettings().getMetadataPersistenceSettings().isSaveToOriginalFile();
|
||||
if (saveToOriginal) {
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean saveToOriginal = settings.isSaveToOriginalFile();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
if (saveToOriginal && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(bookEntity.getBookType()).ifPresent(writer -> {
|
||||
try {
|
||||
File file = new File(bookEntity.getFullFilePath().toUri());
|
||||
|
||||
+644
-42
@@ -1,58 +1,660 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Arrays;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.Collections;
|
||||
import java.util.stream.Collectors;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
String baseName = FilenameUtils.getBaseName(file.getName());
|
||||
return BookMetadata.builder()
|
||||
.title(baseName)
|
||||
.build();
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
String baseName = FilenameUtils.getBaseName(file.getName());
|
||||
String lowerName = file.getName().toLowerCase();
|
||||
|
||||
// Non-archive (fallback)
|
||||
if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
|
||||
private byte[] generatePlaceholderCover(int width, int height) {
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
|
||||
g.setColor(Color.LIGHT_GRAY);
|
||||
g.fillRect(0, 0, width, height);
|
||||
|
||||
g.setColor(Color.DARK_GRAY);
|
||||
g.setFont(new Font("SansSerif", Font.BOLD, width / 10));
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
String text = "Preview Unavailable";
|
||||
|
||||
int textWidth = fm.stringWidth(text);
|
||||
int textHeight = fm.getAscent();
|
||||
g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2);
|
||||
|
||||
g.dispose();
|
||||
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
ImageIO.write(image, "jpg", baos);
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to generate placeholder image", e);
|
||||
return null;
|
||||
// CBZ path (ZIP)
|
||||
if (lowerName.endsWith(".cbz")) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry entry = findComicInfoEntry(zipFile);
|
||||
if (entry == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
return mapDocumentToMetadata(document, baseName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract metadata from CBZ", e);
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
}
|
||||
|
||||
// CB7 path (7z)
|
||||
if (lowerName.endsWith(".cb7")) {
|
||||
try (SevenZFile sevenZ = new SevenZFile(file)) {
|
||||
SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ);
|
||||
if (entry == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry);
|
||||
if (xmlBytes == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
return mapDocumentToMetadata(document, baseName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract metadata from CB7", e);
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
}
|
||||
|
||||
// CBR path (RAR)
|
||||
Archive archive = null;
|
||||
try {
|
||||
archive = new Archive(file);
|
||||
FileHeader header = findComicInfoHeader(archive);
|
||||
if (header == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
byte[] xmlBytes = readRarEntryBytes(archive, header);
|
||||
if (xmlBytes == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
return mapDocumentToMetadata(document, baseName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract metadata from CBR", e);
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
} finally {
|
||||
try { if (archive != null) archive.close(); } catch (Exception ignore) {}
|
||||
}
|
||||
}
|
||||
|
||||
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
if ("comicinfo.xml".equalsIgnoreCase(name)) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Document buildSecureDocument(InputStream is) throws Exception {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
factory.setExpandEntityReferences(false);
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
return builder.parse(is);
|
||||
}
|
||||
|
||||
private BookMetadata mapDocumentToMetadata(
|
||||
Document document,
|
||||
String fallbackTitle
|
||||
) {
|
||||
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder();
|
||||
|
||||
String title = getTextContent(document, "Title");
|
||||
builder.title(title == null || title.isBlank() ? fallbackTitle : title);
|
||||
|
||||
builder.description(
|
||||
coalesce(
|
||||
getTextContent(document, "Summary"),
|
||||
getTextContent(document, "Description")
|
||||
)
|
||||
);
|
||||
builder.publisher(getTextContent(document, "Publisher"));
|
||||
builder.seriesName(getTextContent(document, "Series"));
|
||||
builder.seriesNumber(parseFloat(getTextContent(document, "Number")));
|
||||
builder.seriesTotal(parseInteger(getTextContent(document, "Count")));
|
||||
builder.publishedDate(
|
||||
parseDate(
|
||||
getTextContent(document, "Year"),
|
||||
getTextContent(document, "Month"),
|
||||
getTextContent(document, "Day")
|
||||
)
|
||||
);
|
||||
builder.pageCount(
|
||||
parseInteger(
|
||||
coalesce(
|
||||
getTextContent(document, "PageCount"),
|
||||
getTextContent(document, "Pages")
|
||||
)
|
||||
)
|
||||
);
|
||||
builder.language(getTextContent(document, "LanguageISO"));
|
||||
|
||||
Set<String> authors = new HashSet<>();
|
||||
authors.addAll(splitValues(getTextContent(document, "Writer")));
|
||||
authors.addAll(splitValues(getTextContent(document, "Penciller")));
|
||||
authors.addAll(splitValues(getTextContent(document, "Inker")));
|
||||
authors.addAll(splitValues(getTextContent(document, "Colorist")));
|
||||
authors.addAll(splitValues(getTextContent(document, "Letterer")));
|
||||
authors.addAll(splitValues(getTextContent(document, "CoverArtist")));
|
||||
if (!authors.isEmpty()) {
|
||||
builder.authors(authors);
|
||||
}
|
||||
|
||||
Set<String> categories = new HashSet<>();
|
||||
categories.addAll(splitValues(getTextContent(document, "Genre")));
|
||||
categories.addAll(splitValues(getTextContent(document, "Tags")));
|
||||
if (!categories.isEmpty()) {
|
||||
builder.categories(categories);
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private String getTextContent(Document document, String tag) {
|
||||
NodeList nodes = document.getElementsByTagName(tag);
|
||||
if (nodes.getLength() == 0) {
|
||||
return null;
|
||||
}
|
||||
return nodes.item(0).getTextContent().trim();
|
||||
}
|
||||
|
||||
private String coalesce(String a, String b) {
|
||||
return (a != null && !a.isBlank())
|
||||
? a
|
||||
: (b != null && !b.isBlank() ? b : null);
|
||||
}
|
||||
|
||||
private Set<String> splitValues(String value) {
|
||||
if (value == null) {
|
||||
return new HashSet<>();
|
||||
}
|
||||
return Arrays.stream(value.split("[,;]"))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private Integer parseInteger(String value) {
|
||||
try {
|
||||
return (value == null || value.isBlank())
|
||||
? null
|
||||
: Integer.parseInt(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Float parseFloat(String value) {
|
||||
try {
|
||||
return (value == null || value.isBlank())
|
||||
? null
|
||||
: Float.parseFloat(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate parseDate(String year, String month, String day) {
|
||||
Integer y = parseInteger(year);
|
||||
Integer m = parseInteger(month);
|
||||
Integer d = parseInteger(day);
|
||||
if (y == null) {
|
||||
return null;
|
||||
}
|
||||
if (m == null) {
|
||||
m = 1;
|
||||
}
|
||||
if (d == null) {
|
||||
d = 1;
|
||||
}
|
||||
try {
|
||||
return LocalDate.of(y, m, d);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public BookMetadata extractFromComicInfoXml(File xmlFile) {
|
||||
try (InputStream is = new FileInputStream(xmlFile)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String fallbackTitle = xmlFile.getParentFile() != null
|
||||
? xmlFile.getParentFile().getName()
|
||||
: xmlFile.getName();
|
||||
return mapDocumentToMetadata(document, fallbackTitle);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse ComicInfo.xml: {}", e.getMessage());
|
||||
String fallbackTitle = xmlFile.getParentFile() != null
|
||||
? xmlFile.getParentFile().getName()
|
||||
: xmlFile.getName();
|
||||
return BookMetadata.builder().title(fallbackTitle).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
String lowerName = file.getName().toLowerCase();
|
||||
|
||||
// Non-archive fallback
|
||||
if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) {
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
|
||||
// CBZ path
|
||||
if (lowerName.endsWith(".cbz")) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry coverEntry = findFrontCoverEntry(zipFile);
|
||||
if (coverEntry != null) {
|
||||
try (InputStream is = zipFile.getInputStream(coverEntry)) {
|
||||
return is.readAllBytes();
|
||||
}
|
||||
} else {
|
||||
// Fallback: first image after sorting alphabetically
|
||||
ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile);
|
||||
if (firstImage != null) {
|
||||
try (InputStream is2 = zipFile.getInputStream(firstImage)) {
|
||||
return is2.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover image from CBZ", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
}
|
||||
|
||||
// CB7 path
|
||||
if (lowerName.endsWith(".cb7")) {
|
||||
try (SevenZFile sevenZ = new SevenZFile(file)) {
|
||||
// Try via ComicInfo.xml first
|
||||
SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ);
|
||||
if (ci != null) {
|
||||
byte[] xmlBytes = readSevenZEntryBytes(sevenZ, ci);
|
||||
if (xmlBytes != null) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
SevenZArchiveEntry byName = findSevenZEntryByName(sevenZ, imageName);
|
||||
if (byName != null) {
|
||||
return readSevenZEntryBytes(sevenZ, byName);
|
||||
}
|
||||
try {
|
||||
int index = Integer.parseInt(imageName);
|
||||
SevenZArchiveEntry byIndex = findSevenZImageEntryByIndex(sevenZ, index);
|
||||
if (byIndex != null) {
|
||||
return readSevenZEntryBytes(sevenZ, byIndex);
|
||||
}
|
||||
} catch (NumberFormatException ignore) {
|
||||
// continue to fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: first image alphabetically
|
||||
SevenZArchiveEntry first = findFirstAlphabeticalSevenZImageEntry(sevenZ);
|
||||
if (first != null) {
|
||||
return readSevenZEntryBytes(sevenZ, first);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover image from CB7", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
}
|
||||
|
||||
// CBR path
|
||||
Archive archive = null;
|
||||
try {
|
||||
archive = new Archive(file);
|
||||
|
||||
// Try via ComicInfo.xml first
|
||||
FileHeader comicInfo = findComicInfoHeader(archive);
|
||||
if (comicInfo != null) {
|
||||
byte[] xmlBytes = readRarEntryBytes(archive, comicInfo);
|
||||
if (xmlBytes != null) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
FileHeader byName = findRarHeaderByName(archive, imageName);
|
||||
if (byName != null) {
|
||||
return readRarEntryBytes(archive, byName);
|
||||
}
|
||||
try {
|
||||
int index = Integer.parseInt(imageName);
|
||||
FileHeader byIndex = findRarImageHeaderByIndex(archive, index);
|
||||
if (byIndex != null) {
|
||||
return readRarEntryBytes(archive, byIndex);
|
||||
}
|
||||
} catch (NumberFormatException ignore) {
|
||||
// ignore and continue fallback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: first image in alphabetical order
|
||||
FileHeader firstImage = findFirstAlphabeticalImageHeader(archive);
|
||||
if (firstImage != null) {
|
||||
return readRarEntryBytes(archive, firstImage);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover image from CBR", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
} finally {
|
||||
try { if (archive != null) archive.close(); } catch (Exception ignore) {}
|
||||
}
|
||||
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
|
||||
private ZipEntry findFrontCoverEntry(ZipFile zipFile) {
|
||||
ZipEntry comicInfoEntry = findComicInfoEntry(zipFile);
|
||||
if (comicInfoEntry != null) {
|
||||
try (InputStream is = zipFile.getInputStream(comicInfoEntry)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
ZipEntry byName = zipFile.getEntry(imageName);
|
||||
if (byName != null) {
|
||||
return byName;
|
||||
}
|
||||
try {
|
||||
int index = Integer.parseInt(imageName);
|
||||
ZipEntry byIndex = findImageEntryByIndex(zipFile, index);
|
||||
if (byIndex != null) {
|
||||
return byIndex;
|
||||
}
|
||||
} catch (NumberFormatException ignore) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse ComicInfo.xml for cover", e);
|
||||
}
|
||||
}
|
||||
ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile);
|
||||
return firstImage;
|
||||
}
|
||||
|
||||
private ZipEntry findImageEntryByIndex(ZipFile zipFile, int index) {
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
int count = 0;
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (!entry.isDirectory() && isImageEntry(entry.getName())) {
|
||||
if (count == index) {
|
||||
return entry;
|
||||
}
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String findFrontCoverImageName(Document document) {
|
||||
NodeList pages = document.getElementsByTagName("Page");
|
||||
for (int i = 0; i < pages.getLength(); i++) {
|
||||
org.w3c.dom.Node node = pages.item(i);
|
||||
if (node instanceof org.w3c.dom.Element) {
|
||||
org.w3c.dom.Element page = (org.w3c.dom.Element) node;
|
||||
String type = page.getAttribute("Type");
|
||||
if (type != null && type.equalsIgnoreCase("FrontCover")) {
|
||||
String imageFile = page.getAttribute("ImageFile");
|
||||
if (imageFile != null && !imageFile.isBlank()) {
|
||||
return imageFile.trim();
|
||||
}
|
||||
String image = page.getAttribute("Image");
|
||||
if (image != null && !image.isBlank()) {
|
||||
return image.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean isImageEntry(String name) {
|
||||
String lower = name.toLowerCase();
|
||||
return (
|
||||
lower.endsWith(".jpg") ||
|
||||
lower.endsWith(".jpeg") ||
|
||||
lower.endsWith(".png") ||
|
||||
lower.endsWith(".gif") ||
|
||||
lower.endsWith(".bmp") ||
|
||||
lower.endsWith(".webp")
|
||||
);
|
||||
}
|
||||
|
||||
private byte[] generatePlaceholderCover(int width, int height) {
|
||||
BufferedImage image = new BufferedImage(
|
||||
width,
|
||||
height,
|
||||
BufferedImage.TYPE_INT_RGB
|
||||
);
|
||||
Graphics2D g = image.createGraphics();
|
||||
|
||||
g.setColor(Color.LIGHT_GRAY);
|
||||
g.fillRect(0, 0, width, height);
|
||||
|
||||
g.setColor(Color.DARK_GRAY);
|
||||
g.setFont(new Font("SansSerif", Font.BOLD, width / 10));
|
||||
FontMetrics fm = g.getFontMetrics();
|
||||
String text = "Preview Unavailable";
|
||||
|
||||
int textWidth = fm.stringWidth(text);
|
||||
int textHeight = fm.getAscent();
|
||||
g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2);
|
||||
|
||||
g.dispose();
|
||||
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
ImageIO.write(image, "jpg", baos);
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to generate placeholder image", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ==== RAR (.cbr) helpers ====
|
||||
private FileHeader findComicInfoHeader(Archive archive) {
|
||||
if (archive == null) return null;
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
String name = fh.getFileName();
|
||||
if (name == null) continue;
|
||||
String base = baseName(name);
|
||||
if ("comicinfo.xml".equalsIgnoreCase(base)) {
|
||||
return fh;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private FileHeader findRarHeaderByName(Archive archive, String imageName) {
|
||||
if (archive == null || imageName == null) return null;
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
String name = fh.getFileName();
|
||||
if (name == null) continue;
|
||||
if (name.equalsIgnoreCase(imageName)) return fh;
|
||||
// also try base-name match to be lenient
|
||||
if (baseName(name).equalsIgnoreCase(baseName(imageName))) return fh;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private FileHeader findRarImageHeaderByIndex(Archive archive, int index) {
|
||||
int count = 0;
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
if (!fh.isDirectory() && isImageEntry(fh.getFileName())) {
|
||||
if (count == index) return fh;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private FileHeader findFirstImageHeader(Archive archive) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
if (!fh.isDirectory() && isImageEntry(fh.getFileName())) {
|
||||
return fh;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] readRarEntryBytes(Archive archive, FileHeader header) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
archive.extractFile(header, baos);
|
||||
return baos.toByteArray();
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read RAR entry bytes for {}", header != null ? header.getFileName() : "<null>", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String baseName(String path) {
|
||||
if (path == null) return null;
|
||||
int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
|
||||
return slash >= 0 ? path.substring(slash + 1) : path;
|
||||
}
|
||||
|
||||
private FileHeader findFirstAlphabeticalImageHeader(Archive archive) {
|
||||
if (archive == null) return null;
|
||||
List<FileHeader> images = new ArrayList<>();
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
if (fh == null || fh.isDirectory()) continue;
|
||||
String name = fh.getFileName();
|
||||
if (name == null) continue;
|
||||
if (isImageEntry(name)) {
|
||||
images.add(fh);
|
||||
}
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
images.sort(Comparator.comparing(
|
||||
fh -> fh.getFileName() == null ? "" : fh.getFileName(),
|
||||
String.CASE_INSENSITIVE_ORDER
|
||||
));
|
||||
return images.get(0);
|
||||
}
|
||||
|
||||
private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) {
|
||||
List<ZipEntry> images = new ArrayList<>();
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry e = entries.nextElement();
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) {
|
||||
images.add(e);
|
||||
}
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
images.sort(Comparator.comparing(
|
||||
entry -> entry.getName() == null ? "" : entry.getName(),
|
||||
String.CASE_INSENSITIVE_ORDER
|
||||
));
|
||||
return images.get(0);
|
||||
}
|
||||
|
||||
// ==== 7z (.cb7) helpers ====
|
||||
private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) throws IOException {
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e == null || e.isDirectory()) continue;
|
||||
String name = e.getName();
|
||||
if (name != null && name.equalsIgnoreCase("ComicInfo.xml")) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) throws IOException {
|
||||
if (imageName == null) return null;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e == null || e.isDirectory()) continue;
|
||||
String name = e.getName();
|
||||
if (name == null) continue;
|
||||
if (name.equalsIgnoreCase(imageName)) return e;
|
||||
// also allow base-name match
|
||||
if (baseName(name).equalsIgnoreCase(baseName(imageName))) return e;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) throws IOException {
|
||||
int count = 0;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) {
|
||||
if (count == index) return e;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) throws IOException {
|
||||
List<SevenZArchiveEntry> images = new ArrayList<>();
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (!e.isDirectory() && isImageEntry(e.getName())) {
|
||||
images.add(e);
|
||||
}
|
||||
}
|
||||
if (images.isEmpty()) return null;
|
||||
images.sort(Comparator.comparing(
|
||||
entry -> entry.getName() == null ? "" : entry.getName(),
|
||||
String.CASE_INSENSITIVE_ORDER
|
||||
));
|
||||
return images.get(0);
|
||||
}
|
||||
|
||||
private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException {
|
||||
try (InputStream is = sevenZ.getInputStream(entry);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
if (is == null) return null;
|
||||
is.transferTo(baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
+454
@@ -0,0 +1,454 @@
|
||||
package com.adityachandel.booklore.service.metadata.writer;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CbxMetadataWriter implements MetadataWriter {
|
||||
|
||||
@Override
|
||||
public void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, boolean restoreMode, MetadataClearFlags clearFlags) {
|
||||
Path backup = null;
|
||||
boolean writeSucceeded = false;
|
||||
try {
|
||||
// Create a backup next to the source file (temp name, safe to delete later)
|
||||
backup = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak");
|
||||
Files.copy(file.toPath(), backup, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex);
|
||||
}
|
||||
try {
|
||||
String nameLower = file.getName().toLowerCase(Locale.ROOT);
|
||||
boolean isCbz = nameLower.endsWith(".cbz");
|
||||
boolean isCbr = nameLower.endsWith(".cbr");
|
||||
boolean isCb7 = nameLower.endsWith(".cb7");
|
||||
|
||||
if (!isCbz && !isCbr && !isCb7) {
|
||||
log.warn("Unsupported file type for CBX writer: {}", file.getName());
|
||||
return;
|
||||
}
|
||||
|
||||
// Build (or load and update) ComicInfo.xml as a Document
|
||||
Document doc;
|
||||
if (isCbz) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry existing = findComicInfoEntry(zipFile);
|
||||
if (existing != null) {
|
||||
try (InputStream is = zipFile.getInputStream(existing)) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
} else if (isCb7) {
|
||||
try (SevenZFile sevenZ = new SevenZFile(file)) {
|
||||
SevenZArchiveEntry existing = null;
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e != null && !e.isDirectory() && isComicInfoName(e.getName())) {
|
||||
existing = e; break;
|
||||
}
|
||||
}
|
||||
if (existing != null) {
|
||||
try (InputStream is = sevenZ.getInputStream(existing)) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
} else { // CBR
|
||||
try (Archive archive = new Archive(file)) {
|
||||
FileHeader existing = findComicInfoHeader(archive);
|
||||
if (existing != null) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
archive.extractFile(existing, baos);
|
||||
try (InputStream is = new java.io.ByteArrayInputStream(baos.toByteArray())) {
|
||||
doc = buildSecureDocument(is);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
doc = newEmptyComicInfo();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply metadata to the Document
|
||||
Element root = doc.getDocumentElement();
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(metadata);
|
||||
helper.copyTitle(restoreMode, clearFlags != null && clearFlags.isTitle(), val -> setElement(doc, root, "Title", val));
|
||||
helper.copyDescription(restoreMode, clearFlags != null && clearFlags.isDescription(), val -> {
|
||||
setElement(doc, root, "Summary", val);
|
||||
removeElement(root, "Description");
|
||||
});
|
||||
helper.copyPublisher(restoreMode, clearFlags != null && clearFlags.isPublisher(), val -> setElement(doc, root, "Publisher", val));
|
||||
helper.copySeriesName(restoreMode, clearFlags != null && clearFlags.isSeriesName(), val -> setElement(doc, root, "Series", val));
|
||||
helper.copySeriesNumber(restoreMode, clearFlags != null && clearFlags.isSeriesNumber(), val -> setElement(doc, root, "Number", formatFloat(val)));
|
||||
helper.copySeriesTotal(restoreMode, clearFlags != null && clearFlags.isSeriesTotal(), val -> setElement(doc, root, "Count", val != null ? val.toString() : null));
|
||||
helper.copyPublishedDate(restoreMode, clearFlags != null && clearFlags.isPublishedDate(), date -> setDateElements(doc, root, date));
|
||||
helper.copyPageCount(restoreMode, clearFlags != null && clearFlags.isPageCount(), val -> setElement(doc, root, "PageCount", val != null ? val.toString() : null));
|
||||
helper.copyLanguage(restoreMode, clearFlags != null && clearFlags.isLanguage(), val -> setElement(doc, root, "LanguageISO", val));
|
||||
helper.copyAuthors(restoreMode, clearFlags != null && clearFlags.isAuthors(), set -> {
|
||||
setElement(doc, root, "Writer", join(set));
|
||||
removeElement(root, "Penciller");
|
||||
removeElement(root, "Inker");
|
||||
removeElement(root, "Colorist");
|
||||
removeElement(root, "Letterer");
|
||||
removeElement(root, "CoverArtist");
|
||||
});
|
||||
helper.copyCategories(restoreMode, clearFlags != null && clearFlags.isCategories(), set -> {
|
||||
setElement(doc, root, "Genre", join(set));
|
||||
removeElement(root, "Tags");
|
||||
});
|
||||
|
||||
// Serialize ComicInfo.xml
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
|
||||
ByteArrayOutputStream xmlBaos = new ByteArrayOutputStream();
|
||||
transformer.transform(new DOMSource(doc), new StreamResult(xmlBaos));
|
||||
byte[] xmlBytes = xmlBaos.toByteArray();
|
||||
|
||||
// Repack depending on container type; always write to a temp target then atomic move
|
||||
if (isCbz) {
|
||||
Path temp = Files.createTempFile("cbx_edit", ".cbz");
|
||||
repackZipReplacingComicInfo(file.toPath(), temp, xmlBytes);
|
||||
atomicReplace(temp, file.toPath());
|
||||
writeSucceeded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isCb7) {
|
||||
// Convert to CBZ with updated ComicInfo.xml
|
||||
Path tempZip = Files.createTempFile("cbx_edit", ".cbz");
|
||||
try (SevenZFile sevenZ = new SevenZFile(file);
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempZip))) {
|
||||
for (SevenZArchiveEntry e : sevenZ.getEntries()) {
|
||||
if (e.isDirectory()) continue;
|
||||
String entryName = e.getName();
|
||||
if (isComicInfoName(entryName)) continue; // skip old
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
log.warn("Skipping unsafe 7z entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream is = sevenZ.getInputStream(e)) {
|
||||
if (is != null) is.transferTo(zos);
|
||||
}
|
||||
zos.closeEntry();
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
}
|
||||
Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz");
|
||||
atomicReplace(tempZip, target);
|
||||
try { Files.deleteIfExists(file.toPath()); } catch (Exception ignored) {}
|
||||
writeSucceeded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// CBR path
|
||||
String rarBin = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar");
|
||||
boolean rarAvailable = isRarAvailable(rarBin);
|
||||
|
||||
if (rarAvailable) {
|
||||
Path tempDir = Files.createTempDirectory("cbx_rar_");
|
||||
try {
|
||||
// Extract entire RAR into a temp directory
|
||||
try (Archive archive = new Archive(file)) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
String name = fh.getFileName();
|
||||
if (name == null || name.isBlank()) continue;
|
||||
if (!isSafeEntryName(name)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", name);
|
||||
continue;
|
||||
}
|
||||
Path out = tempDir.resolve(name).normalize();
|
||||
if (!out.startsWith(tempDir)) {
|
||||
log.warn("Skipping traversal entry outside tempDir: {}", name);
|
||||
continue;
|
||||
}
|
||||
if (fh.isDirectory()) {
|
||||
Files.createDirectories(out);
|
||||
} else {
|
||||
Files.createDirectories(out.getParent());
|
||||
try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
|
||||
archive.extractFile(fh, os);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Write/replace ComicInfo.xml in extracted tree root
|
||||
Path comicInfo = tempDir.resolve("ComicInfo.xml");
|
||||
Files.write(comicInfo, xmlBytes);
|
||||
|
||||
// Rebuild RAR in-place (replace original file)
|
||||
Path targetRar = file.toPath().toAbsolutePath().normalize();
|
||||
String rarExec = isSafeExecutable(rarBin) ? rarBin : "rar"; // prefer validated path, then PATH lookup
|
||||
ProcessBuilder pb = new ProcessBuilder(rarExec, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), ".");
|
||||
pb.directory(tempDir.toFile());
|
||||
Process p = pb.start();
|
||||
int code = p.waitFor();
|
||||
if (code == 0) {
|
||||
writeSucceeded = true;
|
||||
return;
|
||||
} else {
|
||||
log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", code, file.getName());
|
||||
}
|
||||
} finally {
|
||||
try { // cleanup temp dir
|
||||
java.nio.file.Files.walk(tempDir)
|
||||
.sorted(java.util.Comparator.reverseOrder())
|
||||
.forEach(path -> { try { Files.deleteIfExists(path); } catch (Exception ignore) {} });
|
||||
} catch (Exception ignore) {}
|
||||
}
|
||||
} else {
|
||||
log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", file.getName());
|
||||
}
|
||||
|
||||
// Fallback: convert the CBR to CBZ containing updated ComicInfo.xml
|
||||
Path tempZip = Files.createTempFile("cbx_edit", ".cbz");
|
||||
try (Archive archive = new Archive(file);
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempZip))) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
if (fh.isDirectory()) continue;
|
||||
String entryName = fh.getFileName();
|
||||
if (isComicInfoName(entryName)) continue; // skip old
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
archive.extractFile(fh, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
}
|
||||
Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz");
|
||||
atomicReplace(tempZip, target);
|
||||
try { Files.deleteIfExists(file.toPath()); } catch (Exception ignored) {}
|
||||
writeSucceeded = true;
|
||||
} catch (Exception e) {
|
||||
// Attempt to restore the original file from backup
|
||||
try {
|
||||
if (backup != null) {
|
||||
Files.copy(backup, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
log.info("Restored original file from backup after failure: {}", file.getAbsolutePath());
|
||||
}
|
||||
} catch (Exception restoreEx) {
|
||||
log.warn("Failed to restore original file from backup: {} -> {}", backup, file.getAbsolutePath(), restoreEx);
|
||||
}
|
||||
log.warn("Failed to write metadata for {}: {}", file.getName(), e.getMessage(), e);
|
||||
} finally {
|
||||
if (writeSucceeded && backup != null) {
|
||||
try { Files.deleteIfExists(backup); } catch (Exception ignore) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------- helpers -----------------------
|
||||
|
||||
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String n = entry.getName();
|
||||
if (isComicInfoName(n)) return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private FileHeader findComicInfoHeader(Archive archive) {
|
||||
for (FileHeader fh : archive.getFileHeaders()) {
|
||||
String name = fh.getFileName();
|
||||
if (name != null && isComicInfoName(name)) return fh;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Document buildSecureDocument(InputStream is) throws Exception {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
factory.setExpandEntityReferences(false);
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
return builder.parse(is);
|
||||
}
|
||||
|
||||
private Document newEmptyComicInfo() throws Exception {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
DocumentBuilder builder = factory.newDocumentBuilder();
|
||||
Document doc = builder.newDocument();
|
||||
doc.appendChild(doc.createElement("ComicInfo"));
|
||||
return doc;
|
||||
}
|
||||
|
||||
private void setElement(Document doc, Element root, String tag, String value) {
|
||||
removeElement(root, tag);
|
||||
if (value != null && !value.isBlank()) {
|
||||
Element el = doc.createElement(tag);
|
||||
el.setTextContent(value);
|
||||
root.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
private void removeElement(Element root, String tag) {
|
||||
NodeList nodes = root.getElementsByTagName(tag);
|
||||
for (int i = nodes.getLength() - 1; i >= 0; i--) {
|
||||
root.removeChild(nodes.item(i));
|
||||
}
|
||||
}
|
||||
|
||||
private void setDateElements(Document doc, Element root, LocalDate date) {
|
||||
if (date == null) {
|
||||
removeElement(root, "Year");
|
||||
removeElement(root, "Month");
|
||||
removeElement(root, "Day");
|
||||
return;
|
||||
}
|
||||
setElement(doc, root, "Year", Integer.toString(date.getYear()));
|
||||
setElement(doc, root, "Month", Integer.toString(date.getMonthValue()));
|
||||
setElement(doc, root, "Day", Integer.toString(date.getDayOfMonth()));
|
||||
}
|
||||
|
||||
private String join(Set<String> set) {
|
||||
return (set == null || set.isEmpty()) ? null : String.join(", ", set);
|
||||
}
|
||||
|
||||
private String formatFloat(Float val) {
|
||||
if (val == null) return null;
|
||||
if (val % 1 == 0) return Integer.toString(val.intValue());
|
||||
return val.toString();
|
||||
}
|
||||
|
||||
private static boolean isComicInfoName(String name) {
|
||||
if (name == null) return false;
|
||||
String n = name.replace('\\', '/');
|
||||
if (n.endsWith("/")) return false;
|
||||
String lower = n.toLowerCase(Locale.ROOT);
|
||||
return lower.equals("comicinfo.xml") || lower.endsWith("/comicinfo.xml");
|
||||
}
|
||||
|
||||
private static boolean isSafeEntryName(String name) {
|
||||
if (name == null || name.isBlank()) return false;
|
||||
String n = name.replace('\\', '/');
|
||||
if (n.startsWith("/")) return false; // absolute
|
||||
if (n.contains("../")) return false; // traversal
|
||||
if (n.contains("\0")) return false; // NUL
|
||||
return true;
|
||||
}
|
||||
|
||||
private void repackZipReplacingComicInfo(Path sourceZip, Path targetZip, byte[] xmlBytes) throws Exception {
|
||||
try (ZipFile zipFile = new ZipFile(sourceZip.toFile());
|
||||
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) {
|
||||
ZipEntry existing = findComicInfoEntry(zipFile);
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String entryName = entry.getName();
|
||||
if (existing != null && entryName.equals(existing.getName())) {
|
||||
continue; // skip old ComicInfo.xml
|
||||
}
|
||||
if (!isSafeEntryName(entryName)) {
|
||||
log.warn("Skipping unsafe ZIP entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
is.transferTo(zos);
|
||||
}
|
||||
zos.closeEntry();
|
||||
}
|
||||
String entryName = (existing != null ? existing.getName() : "ComicInfo.xml");
|
||||
zos.putNextEntry(new ZipEntry(entryName));
|
||||
zos.write(xmlBytes);
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private static void atomicReplace(Path temp, Path target) throws Exception {
|
||||
try {
|
||||
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (Exception e) {
|
||||
// Fallback if filesystem doesn't support ATOMIC_MOVE
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isRarAvailable(String rarBin) {
|
||||
try {
|
||||
String exec = isSafeExecutable(rarBin) ? rarBin : "rar";
|
||||
Process check = new ProcessBuilder(exec, "--help").redirectErrorStream(true).start();
|
||||
int exitCode = check.waitFor();
|
||||
return (exitCode == 0);
|
||||
} catch (Exception ex) {
|
||||
log.warn("RAR binary check failed: {}", ex.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the provided executable reference is a simple name or sanitized absolute/relative path.
|
||||
* No spaces or shell meta chars; passed as argv to ProcessBuilder (no shell).
|
||||
*/
|
||||
private boolean isSafeExecutable(String exec) {
|
||||
if (exec == null || exec.isBlank()) return false;
|
||||
// allow word chars, dot, slash, backslash, dash and underscore (no spaces or shell metas)
|
||||
return exec.matches("^[\\w./\\\\-]+$");
|
||||
}
|
||||
|
||||
private static String stripExtension(String filename) {
|
||||
int i = filename.lastIndexOf('.');
|
||||
if (i > 0) return filename.substring(0, i);
|
||||
return filename;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookFileType getSupportedBookType() {
|
||||
return BookFileType.CBX;
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CbxMetadataExtractorTest {
|
||||
|
||||
private CbxMetadataExtractor extractor;
|
||||
private Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
extractor = new CbxMetadataExtractor();
|
||||
tempDir = Files.createTempDirectory("cbx_test_");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws IOException {
|
||||
if (tempDir != null) {
|
||||
// best-effort cleanup
|
||||
Files.walk(tempDir)
|
||||
.sorted((a, b) -> b.compareTo(a))
|
||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractMetadata_fromCbz_withComicInfo_populatesFields() throws Exception {
|
||||
String xml = "" +
|
||||
"<ComicInfo>" +
|
||||
" <Title>My Comic</Title>" +
|
||||
" <Summary>A short summary</Summary>" +
|
||||
" <Publisher>Indie</Publisher>" +
|
||||
" <Series>Series X</Series>" +
|
||||
" <Number>2.5</Number>" +
|
||||
" <Count>12</Count>" +
|
||||
" <Year>2020</Year><Month>7</Month><Day>14</Day>" +
|
||||
" <PageCount>42</PageCount>" +
|
||||
" <LanguageISO>en</LanguageISO>" +
|
||||
" <Writer>Alice</Writer>" +
|
||||
" <Penciller>Bob</Penciller>" +
|
||||
" <Tags>action;adventure</Tags>" +
|
||||
"</ComicInfo>";
|
||||
|
||||
File cbz = createCbz("with_meta.cbz", new LinkedHashMap<>() {{
|
||||
put("ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||
put("page1.jpg", new byte[]{1,2,3});
|
||||
}});
|
||||
|
||||
BookMetadata md = extractor.extractMetadata(cbz);
|
||||
assertEquals("My Comic", md.getTitle());
|
||||
assertEquals("A short summary", md.getDescription());
|
||||
assertEquals("Indie", md.getPublisher());
|
||||
assertEquals("Series X", md.getSeriesName());
|
||||
assertEquals(2.5f, md.getSeriesNumber());
|
||||
assertEquals(Integer.valueOf(12), md.getSeriesTotal());
|
||||
assertEquals(LocalDate.of(2020,7,14), md.getPublishedDate());
|
||||
assertEquals(Integer.valueOf(42), md.getPageCount());
|
||||
assertEquals("en", md.getLanguage());
|
||||
assertTrue(md.getAuthors().contains("Alice"));
|
||||
assertTrue(md.getAuthors().contains("Bob"));
|
||||
assertTrue(md.getCategories().contains("action"));
|
||||
assertTrue(md.getCategories().contains("adventure"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractCover_fromCbz_usesComicInfoImageFile() throws Exception {
|
||||
String xml = "" +
|
||||
"<ComicInfo>" +
|
||||
" <Pages>" +
|
||||
" <Page Type=\"FrontCover\" ImageFile=\"images/002.jpg\"/>" +
|
||||
" </Pages>" +
|
||||
"</ComicInfo>";
|
||||
|
||||
byte[] img1 = new byte[]{11};
|
||||
byte[] img2 = new byte[]{22, 22}; // expect this one
|
||||
byte[] img3 = new byte[]{33, 33, 33};
|
||||
|
||||
File cbz = createCbz("with_cover.cbz", new LinkedHashMap<>() {{
|
||||
put("ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||
put("images/001.jpg", img1);
|
||||
put("images/002.jpg", img2);
|
||||
put("images/003.jpg", img3);
|
||||
}});
|
||||
|
||||
byte[] cover = extractor.extractCover(cbz);
|
||||
assertArrayEquals(img2, cover);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractCover_fromCbz_fallbackAlphabeticalFirst() throws Exception {
|
||||
// No ComicInfo.xml, images intentionally added in unsorted order
|
||||
byte[] aPng = new byte[]{1,1}; // alphabetically first (A.png)
|
||||
byte[] bJpg = new byte[]{2};
|
||||
byte[] cJpeg = new byte[]{3,3,3};
|
||||
|
||||
File cbz = createCbz("fallback.cbz", new LinkedHashMap<>() {{
|
||||
put("z/pageC.jpeg", cJpeg);
|
||||
put("A.png", aPng); // should be chosen
|
||||
put("b.jpg", bJpg);
|
||||
}});
|
||||
|
||||
byte[] cover = extractor.extractCover(cbz);
|
||||
assertArrayEquals(aPng, cover);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractMetadata_nonArchive_fallbackTitle() throws Exception {
|
||||
Path txt = tempDir.resolve("Some Book Title.txt");
|
||||
Files.write(txt, "hello".getBytes(StandardCharsets.UTF_8));
|
||||
BookMetadata md = extractor.extractMetadata(txt.toFile());
|
||||
assertEquals("Some Book Title", md.getTitle());
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
private File createCbz(String name, Map<String, byte[]> entries) throws IOException {
|
||||
Path out = tempDir.resolve(name);
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
|
||||
for (Map.Entry<String, byte[]> e : entries.entrySet()) {
|
||||
String entryName = e.getKey();
|
||||
byte[] data = e.getValue();
|
||||
ZipEntry ze = new ZipEntry(entryName);
|
||||
// set a fixed time to avoid platform-dependent headers
|
||||
ze.setTime(0L);
|
||||
zos.putNextEntry(ze);
|
||||
try (InputStream is = new ByteArrayInputStream(data)) {
|
||||
is.transferTo(zos);
|
||||
}
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toFile();
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package com.adityachandel.booklore.service.metadata.writer;
|
||||
|
||||
import com.adityachandel.booklore.model.MetadataClearFlags;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CbxMetadataWriterTest {
|
||||
|
||||
private CbxMetadataWriter writer;
|
||||
private Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
writer = new CbxMetadataWriter();
|
||||
tempDir = Files.createTempDirectory("cbx_writer_test_");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws Exception {
|
||||
if (tempDir != null) {
|
||||
Files.walk(tempDir)
|
||||
.sorted((a, b) -> b.compareTo(a))
|
||||
.forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} });
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSupportedBookType_isCbx() {
|
||||
assertEquals(BookFileType.CBX, writer.getSupportedBookType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeMetadataToFile_cbz_updatesOrCreatesComicInfo_andPreservesOtherFiles() throws Exception {
|
||||
// Create a CBZ without ComicInfo.xml and with a couple of images
|
||||
File cbz = createCbz(tempDir.resolve("sample.cbz"), new String[]{
|
||||
"images/002.jpg", "images/001.jpg"
|
||||
});
|
||||
|
||||
// Prepare metadata
|
||||
BookMetadataEntity meta = new BookMetadataEntity();
|
||||
meta.setTitle("My Comic");
|
||||
meta.setDescription("Short desc");
|
||||
meta.setPublisher("Indie");
|
||||
meta.setSeriesName("Series X");
|
||||
meta.setSeriesNumber(2.5f);
|
||||
meta.setSeriesTotal(12);
|
||||
meta.setPublishedDate(LocalDate.of(2020,7,14));
|
||||
meta.setPageCount(42);
|
||||
meta.setLanguage("en");
|
||||
Set<String> authors = new HashSet<>();
|
||||
authors.add("Alice");
|
||||
authors.add("Bob");
|
||||
meta.setAuthors(authors);
|
||||
Set<String> cats = new HashSet<>();
|
||||
cats.add("action");
|
||||
cats.add("adventure");
|
||||
meta.setCategories(cats);
|
||||
|
||||
// Execute
|
||||
writer.writeMetadataToFile(cbz, meta, null, false, MetadataClearFlags.builder().build());
|
||||
|
||||
// Assert ComicInfo.xml exists and contains our fields
|
||||
try (ZipFile zip = new ZipFile(cbz)) {
|
||||
ZipEntry ci = zip.getEntry("ComicInfo.xml");
|
||||
assertNotNull(ci, "ComicInfo.xml should be present after write");
|
||||
|
||||
Document doc = parseXml(zip.getInputStream(ci));
|
||||
String title = text(doc, "Title");
|
||||
String summary = text(doc, "Summary");
|
||||
String publisher = text(doc, "Publisher");
|
||||
String series = text(doc, "Series");
|
||||
String number = text(doc, "Number");
|
||||
String count = text(doc, "Count");
|
||||
String year = text(doc, "Year");
|
||||
String month = text(doc, "Month");
|
||||
String day = text(doc, "Day");
|
||||
String pageCount = text(doc, "PageCount");
|
||||
String lang = text(doc, "LanguageISO");
|
||||
String writerEl = text(doc, "Writer");
|
||||
String genre = text(doc, "Genre");
|
||||
|
||||
assertEquals("My Comic", title);
|
||||
assertEquals("Short desc", summary);
|
||||
assertEquals("Indie", publisher);
|
||||
assertEquals("Series X", series);
|
||||
assertEquals("2.5", number);
|
||||
assertEquals("12", count);
|
||||
assertEquals("2020", year);
|
||||
assertEquals("7", month);
|
||||
assertEquals("14", day);
|
||||
assertEquals("42", pageCount);
|
||||
assertEquals("en", lang);
|
||||
assertTrue(writerEl.contains("Alice"));
|
||||
assertTrue(writerEl.contains("Bob"));
|
||||
assertTrue(genre.toLowerCase().contains("action"));
|
||||
assertTrue(genre.toLowerCase().contains("adventure"));
|
||||
|
||||
// Ensure original image entries are preserved
|
||||
assertNotNull(zip.getEntry("images/001.jpg"));
|
||||
assertNotNull(zip.getEntry("images/002.jpg"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception {
|
||||
// Create a CBZ *with* an existing ComicInfo.xml
|
||||
Path out = tempDir.resolve("with_meta.cbz");
|
||||
String xml = "<ComicInfo>\n" +
|
||||
" <Title>Old Title</Title>\n" +
|
||||
" <Summary>Old Summary</Summary>\n" +
|
||||
"</ComicInfo>";
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out.toFile()))) {
|
||||
put(zos, "ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||
put(zos, "a.jpg", new byte[]{1});
|
||||
}
|
||||
|
||||
BookMetadataEntity meta = new BookMetadataEntity();
|
||||
meta.setTitle("New Title");
|
||||
meta.setDescription("New Summary");
|
||||
|
||||
writer.writeMetadataToFile(out.toFile(), meta, null, false, MetadataClearFlags.builder().build());
|
||||
|
||||
try (ZipFile zip = new ZipFile(out.toFile())) {
|
||||
ZipEntry ci = zip.getEntry("ComicInfo.xml");
|
||||
Document doc = parseXml(zip.getInputStream(ci));
|
||||
assertEquals("New Title", text(doc, "Title"));
|
||||
assertEquals("New Summary", text(doc, "Summary"));
|
||||
// a.jpg should still exist
|
||||
assertNotNull(zip.getEntry("a.jpg"));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------- helpers -------------
|
||||
|
||||
private static File createCbz(Path path, String[] imageNames) throws Exception {
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(path.toFile()))) {
|
||||
for (String name : imageNames) {
|
||||
put(zos, name, new byte[]{1,2,3});
|
||||
}
|
||||
}
|
||||
return path.toFile();
|
||||
}
|
||||
|
||||
private static void put(ZipOutputStream zos, String name, byte[] data) throws Exception {
|
||||
ZipEntry ze = new ZipEntry(name);
|
||||
ze.setTime(0L);
|
||||
zos.putNextEntry(ze);
|
||||
zos.write(data);
|
||||
zos.closeEntry();
|
||||
}
|
||||
|
||||
private static Document parseXml(InputStream is) throws Exception {
|
||||
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
|
||||
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
|
||||
DocumentBuilder b = f.newDocumentBuilder();
|
||||
return b.parse(is);
|
||||
}
|
||||
|
||||
private static String text(Document doc, String tag) {
|
||||
var list = doc.getElementsByTagName(tag);
|
||||
if (list.getLength() == 0) return null;
|
||||
return list.item(0).getTextContent();
|
||||
}
|
||||
}
|
||||
@@ -510,6 +510,10 @@ export class BookService {
|
||||
);
|
||||
}
|
||||
|
||||
getComicInfoMetadata(bookId: number): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/${bookId}/cbx/metadata/comicinfo`);
|
||||
}
|
||||
|
||||
autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable<any> {
|
||||
return this.http.put<void>(`${this.url}/metadata/refresh`, metadataRefreshRequest).pipe(
|
||||
map(() => {
|
||||
|
||||
@@ -82,6 +82,7 @@ export interface Douban {
|
||||
|
||||
export interface MetadataPersistenceSettings {
|
||||
saveToOriginalFile: boolean;
|
||||
convertCbrCb7ToCbz: boolean;
|
||||
backupMetadata: boolean;
|
||||
backupCover: boolean;
|
||||
}
|
||||
|
||||
+16
@@ -452,6 +452,11 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
|
||||
@if (book.bookType === 'CBX') {
|
||||
<p-button label="Restore ComicInfo" icon="pi pi-info-circle" [outlined]="true" severity="info" (onClick)="restoreCbxMetadata()" pTooltip="Retrieve metadata from ComicInfo.xml file" tooltipPosition="top"></p-button>
|
||||
<p-divider layout="vertical"/>
|
||||
}
|
||||
|
||||
@if (book.bookType === 'PDF' || book.bookType === 'EPUB') {
|
||||
<p-button label="Restore" icon="pi pi-refresh" [outlined]="true" severity="danger" (onClick)="restoreMetadata()" pTooltip="Revert all changes to original metadata" tooltipPosition="top"></p-button>
|
||||
<p-divider layout="vertical"/>
|
||||
@@ -486,6 +491,17 @@
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
|
||||
@if (book.bookType === 'CBX') {
|
||||
<p-button
|
||||
icon="pi pi-info-circle"
|
||||
[outlined]="true"
|
||||
severity="warn"
|
||||
(onClick)="restoreCbxMetadata()"
|
||||
pTooltip="Restore ComicInfo"
|
||||
tooltipPosition="top">
|
||||
</p-button>
|
||||
}
|
||||
|
||||
@if (book.bookType === 'PDF' || book.bookType === 'EPUB') {
|
||||
<p-button
|
||||
icon="pi pi-refresh"
|
||||
|
||||
+362
-260
@@ -1,36 +1,58 @@
|
||||
import {Component, DestroyRef, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Book, BookMetadata, MetadataClearFlags, MetadataUpdateWrapper} from '../../../book/model/book.model';
|
||||
import {UrlHelperService} from '../../../utilities/service/url-helper.service';
|
||||
import {FileUpload, FileUploadErrorEvent, FileUploadEvent} from 'primeng/fileupload';
|
||||
import {HttpResponse} from '@angular/common/http';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {MetadataRestoreDialogComponent} from '../../../book/components/book-browser/metadata-restore-dialog-component/metadata-restore-dialog-component';
|
||||
import {DialogService} from 'primeng/dynamicdialog';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {MetadataRefreshRequest} from '../../model/request/metadata-refresh-request.model';
|
||||
import {MetadataRefreshType} from '../../model/request/metadata-refresh-type.enum';
|
||||
import {AutoComplete} from 'primeng/autocomplete';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {IftaLabel} from 'primeng/iftalabel';
|
||||
import {CoverSearchComponent} from '../../cover-search/cover-search.component';
|
||||
import {Image} from 'primeng/image';
|
||||
import {LazyLoadImageModule} from 'ng-lazyload-image';
|
||||
import {
|
||||
Component,
|
||||
DestroyRef,
|
||||
EventEmitter,
|
||||
inject,
|
||||
Input,
|
||||
OnInit,
|
||||
Output,
|
||||
} from "@angular/core";
|
||||
import { InputText } from "primeng/inputtext";
|
||||
import { Button } from "primeng/button";
|
||||
import { Divider } from "primeng/divider";
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
} from "@angular/forms";
|
||||
import { Observable } from "rxjs";
|
||||
import { AsyncPipe } from "@angular/common";
|
||||
import { MessageService } from "primeng/api";
|
||||
import {
|
||||
Book,
|
||||
BookMetadata,
|
||||
MetadataClearFlags,
|
||||
MetadataUpdateWrapper,
|
||||
} from "../../../book/model/book.model";
|
||||
import { UrlHelperService } from "../../../utilities/service/url-helper.service";
|
||||
import {
|
||||
FileUpload,
|
||||
FileUploadErrorEvent,
|
||||
FileUploadEvent,
|
||||
} from "primeng/fileupload";
|
||||
import { HttpResponse } from "@angular/common/http";
|
||||
import { BookService } from "../../../book/service/book.service";
|
||||
import { ProgressSpinner } from "primeng/progressspinner";
|
||||
import { Tooltip } from "primeng/tooltip";
|
||||
import { filter, take } from "rxjs/operators";
|
||||
import { MetadataRestoreDialogComponent } from "../../../book/components/book-browser/metadata-restore-dialog-component/metadata-restore-dialog-component";
|
||||
import { DialogService } from "primeng/dynamicdialog";
|
||||
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
|
||||
import { MetadataRefreshRequest } from "../../model/request/metadata-refresh-request.model";
|
||||
import { MetadataRefreshType } from "../../model/request/metadata-refresh-type.enum";
|
||||
import { AutoComplete } from "primeng/autocomplete";
|
||||
import { Textarea } from "primeng/textarea";
|
||||
import { IftaLabel } from "primeng/iftalabel";
|
||||
import { CoverSearchComponent } from "../../cover-search/cover-search.component";
|
||||
import { Image } from "primeng/image";
|
||||
import { LazyLoadImageModule } from "ng-lazyload-image";
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-editor',
|
||||
selector: "app-metadata-editor",
|
||||
standalone: true,
|
||||
templateUrl: './metadata-editor.component.html',
|
||||
styleUrls: ['./metadata-editor.component.scss'],
|
||||
templateUrl: "./metadata-editor.component.html",
|
||||
styleUrls: ["./metadata-editor.component.scss"],
|
||||
imports: [
|
||||
InputText,
|
||||
Button,
|
||||
@@ -45,11 +67,10 @@ import {LazyLoadImageModule} from 'ng-lazyload-image';
|
||||
Textarea,
|
||||
IftaLabel,
|
||||
Image,
|
||||
LazyLoadImageModule
|
||||
]
|
||||
LazyLoadImageModule,
|
||||
],
|
||||
})
|
||||
export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
@Input() book$!: Observable<Book | null>;
|
||||
@Output() nextBookClicked = new EventEmitter<void>();
|
||||
@Output() previousBookClicked = new EventEmitter<void>();
|
||||
@@ -83,47 +104,47 @@ export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
filterCategories(event: { query: string }) {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredCategories = this.allCategories.filter(cat =>
|
||||
this.filteredCategories = this.allCategories.filter((cat) =>
|
||||
cat.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
filterAuthors(event: { query: string }) {
|
||||
const query = event.query.toLowerCase();
|
||||
this.filteredAuthors = this.allAuthors.filter(cat =>
|
||||
this.filteredAuthors = this.allAuthors.filter((cat) =>
|
||||
cat.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.metadataForm = new FormGroup({
|
||||
title: new FormControl(''),
|
||||
subtitle: new FormControl(''),
|
||||
authors: new FormControl(''),
|
||||
categories: new FormControl(''),
|
||||
publisher: new FormControl(''),
|
||||
publishedDate: new FormControl(''),
|
||||
isbn10: new FormControl(''),
|
||||
isbn13: new FormControl(''),
|
||||
description: new FormControl(''),
|
||||
pageCount: new FormControl(''),
|
||||
language: new FormControl(''),
|
||||
asin: new FormControl(''),
|
||||
personalRating: new FormControl(''),
|
||||
amazonRating: new FormControl(''),
|
||||
amazonReviewCount: new FormControl(''),
|
||||
goodreadsId: new FormControl(''),
|
||||
comicvineId: new FormControl(''),
|
||||
goodreadsRating: new FormControl(''),
|
||||
goodreadsReviewCount: new FormControl(''),
|
||||
hardcoverId: new FormControl(''),
|
||||
hardcoverRating: new FormControl(''),
|
||||
hardcoverReviewCount: new FormControl(''),
|
||||
googleId: new FormControl(''),
|
||||
seriesName: new FormControl(''),
|
||||
seriesNumber: new FormControl(''),
|
||||
seriesTotal: new FormControl(''),
|
||||
thumbnailUrl: new FormControl(''),
|
||||
title: new FormControl(""),
|
||||
subtitle: new FormControl(""),
|
||||
authors: new FormControl(""),
|
||||
categories: new FormControl(""),
|
||||
publisher: new FormControl(""),
|
||||
publishedDate: new FormControl(""),
|
||||
isbn10: new FormControl(""),
|
||||
isbn13: new FormControl(""),
|
||||
description: new FormControl(""),
|
||||
pageCount: new FormControl(""),
|
||||
language: new FormControl(""),
|
||||
asin: new FormControl(""),
|
||||
personalRating: new FormControl(""),
|
||||
amazonRating: new FormControl(""),
|
||||
amazonReviewCount: new FormControl(""),
|
||||
goodreadsId: new FormControl(""),
|
||||
comicvineId: new FormControl(""),
|
||||
goodreadsRating: new FormControl(""),
|
||||
goodreadsReviewCount: new FormControl(""),
|
||||
hardcoverId: new FormControl(""),
|
||||
hardcoverRating: new FormControl(""),
|
||||
hardcoverReviewCount: new FormControl(""),
|
||||
googleId: new FormControl(""),
|
||||
seriesName: new FormControl(""),
|
||||
seriesNumber: new FormControl(""),
|
||||
seriesTotal: new FormControl(""),
|
||||
thumbnailUrl: new FormControl(""),
|
||||
|
||||
titleLocked: new FormControl(false),
|
||||
subtitleLocked: new FormControl(false),
|
||||
@@ -140,7 +161,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
personalRatingLocked: new FormControl(false),
|
||||
amazonRatingLocked: new FormControl(false),
|
||||
amazonReviewCountLocked: new FormControl(false),
|
||||
goodreadsIdLocked: new FormControl(''),
|
||||
goodreadsIdLocked: new FormControl(""),
|
||||
comicvineIdLocked: new FormControl(false),
|
||||
goodreadsRatingLocked: new FormControl(false),
|
||||
goodreadsReviewCountLocked: new FormControl(false),
|
||||
@@ -156,32 +177,32 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.book$
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(book => {
|
||||
const metadata = book?.metadata;
|
||||
if (!metadata) return;
|
||||
this.currentBookId = metadata.bookId;
|
||||
if (this.refreshingBookIds.has(book.id)) {
|
||||
this.refreshingBookIds.delete(book.id);
|
||||
this.isAutoFetching = false;
|
||||
}
|
||||
this.originalMetadata = structuredClone(metadata);
|
||||
this.populateFormFromMetadata(metadata);
|
||||
});
|
||||
this.book$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((book) => {
|
||||
const metadata = book?.metadata;
|
||||
if (!metadata) return;
|
||||
this.currentBookId = metadata.bookId;
|
||||
if (this.refreshingBookIds.has(book.id)) {
|
||||
this.refreshingBookIds.delete(book.id);
|
||||
this.isAutoFetching = false;
|
||||
}
|
||||
this.originalMetadata = structuredClone(metadata);
|
||||
this.populateFormFromMetadata(metadata);
|
||||
});
|
||||
|
||||
this.bookService.bookState$
|
||||
.pipe(
|
||||
filter(bookState => bookState.loaded),
|
||||
filter((bookState) => bookState.loaded),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(bookState => {
|
||||
.subscribe((bookState) => {
|
||||
const authors = new Set<string>();
|
||||
const categories = new Set<string>();
|
||||
|
||||
(bookState.books ?? []).forEach(book => {
|
||||
book.metadata?.authors?.forEach(author => authors.add(author));
|
||||
book.metadata?.categories?.forEach(category => categories.add(category));
|
||||
(bookState.books ?? []).forEach((book) => {
|
||||
book.metadata?.authors?.forEach((author) => authors.add(author));
|
||||
book.metadata?.categories?.forEach((category) =>
|
||||
categories.add(category)
|
||||
);
|
||||
});
|
||||
|
||||
this.allAuthors = Array.from(authors);
|
||||
@@ -249,36 +270,36 @@ export class MetadataEditorComponent implements OnInit {
|
||||
});
|
||||
|
||||
const lockableFields: { key: keyof BookMetadata; control: string }[] = [
|
||||
{key: 'titleLocked', control: 'title'},
|
||||
{key: 'subtitleLocked', control: 'subtitle'},
|
||||
{key: 'authorsLocked', control: 'authors'},
|
||||
{key: 'categoriesLocked', control: 'categories'},
|
||||
{key: 'publisherLocked', control: 'publisher'},
|
||||
{key: 'publishedDateLocked', control: 'publishedDate'},
|
||||
{key: 'languageLocked', control: 'language'},
|
||||
{key: 'isbn10Locked', control: 'isbn10'},
|
||||
{key: 'isbn13Locked', control: 'isbn13'},
|
||||
{key: 'asinLocked', control: 'asin'},
|
||||
{key: 'amazonReviewCountLocked', control: 'amazonReviewCount'},
|
||||
{key: 'amazonRatingLocked', control: 'amazonRating'},
|
||||
{key: 'personalRatingLocked', control: 'personalRating'},
|
||||
{key: 'goodreadsIdLocked', control: 'goodreadsId'},
|
||||
{key: 'comicvineIdLocked', control: 'comicvineId'},
|
||||
{key: 'goodreadsReviewCountLocked', control: 'goodreadsReviewCount'},
|
||||
{key: 'goodreadsRatingLocked', control: 'goodreadsRating'},
|
||||
{key: 'hardcoverIdLocked', control: 'hardcoverId'},
|
||||
{key: 'hardcoverReviewCountLocked', control: 'hardcoverReviewCount'},
|
||||
{key: 'hardcoverRatingLocked', control: 'hardcoverRating'},
|
||||
{key: 'googleIdLocked', control: 'googleId'},
|
||||
{key: 'pageCountLocked', control: 'pageCount'},
|
||||
{key: 'descriptionLocked', control: 'description'},
|
||||
{key: 'seriesNameLocked', control: 'seriesName'},
|
||||
{key: 'seriesNumberLocked', control: 'seriesNumber'},
|
||||
{key: 'seriesTotalLocked', control: 'seriesTotal'},
|
||||
{key: 'coverLocked', control: 'thumbnailUrl'},
|
||||
{ key: "titleLocked", control: "title" },
|
||||
{ key: "subtitleLocked", control: "subtitle" },
|
||||
{ key: "authorsLocked", control: "authors" },
|
||||
{ key: "categoriesLocked", control: "categories" },
|
||||
{ key: "publisherLocked", control: "publisher" },
|
||||
{ key: "publishedDateLocked", control: "publishedDate" },
|
||||
{ key: "languageLocked", control: "language" },
|
||||
{ key: "isbn10Locked", control: "isbn10" },
|
||||
{ key: "isbn13Locked", control: "isbn13" },
|
||||
{ key: "asinLocked", control: "asin" },
|
||||
{ key: "amazonReviewCountLocked", control: "amazonReviewCount" },
|
||||
{ key: "amazonRatingLocked", control: "amazonRating" },
|
||||
{ key: "personalRatingLocked", control: "personalRating" },
|
||||
{ key: "goodreadsIdLocked", control: "goodreadsId" },
|
||||
{ key: "comicvineIdLocked", control: "comicvineId" },
|
||||
{ key: "goodreadsReviewCountLocked", control: "goodreadsReviewCount" },
|
||||
{ key: "goodreadsRatingLocked", control: "goodreadsRating" },
|
||||
{ key: "hardcoverIdLocked", control: "hardcoverId" },
|
||||
{ key: "hardcoverReviewCountLocked", control: "hardcoverReviewCount" },
|
||||
{ key: "hardcoverRatingLocked", control: "hardcoverRating" },
|
||||
{ key: "googleIdLocked", control: "googleId" },
|
||||
{ key: "pageCountLocked", control: "pageCount" },
|
||||
{ key: "descriptionLocked", control: "description" },
|
||||
{ key: "seriesNameLocked", control: "seriesName" },
|
||||
{ key: "seriesNumberLocked", control: "seriesNumber" },
|
||||
{ key: "seriesTotalLocked", control: "seriesTotal" },
|
||||
{ key: "coverLocked", control: "thumbnailUrl" },
|
||||
];
|
||||
|
||||
for (const {key, control} of lockableFields) {
|
||||
for (const { key, control } of lockableFields) {
|
||||
const isLocked = metadata[key] === true;
|
||||
const formControl = this.metadataForm.get(control);
|
||||
if (formControl) {
|
||||
@@ -292,11 +313,11 @@ export class MetadataEditorComponent implements OnInit {
|
||||
if (!values.includes(event.value)) {
|
||||
this.metadataForm.get(fieldName)?.setValue([...values, event.value]);
|
||||
}
|
||||
(event.originalEvent.target as HTMLInputElement).value = '';
|
||||
(event.originalEvent.target as HTMLInputElement).value = "";
|
||||
}
|
||||
|
||||
onAutoCompleteKeyUp(fieldName: string, event: KeyboardEvent) {
|
||||
if (event.key === 'Enter') {
|
||||
if (event.key === "Enter") {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const value = input.value?.trim();
|
||||
if (value) {
|
||||
@@ -304,36 +325,46 @@ export class MetadataEditorComponent implements OnInit {
|
||||
if (!values.includes(value)) {
|
||||
this.metadataForm.get(fieldName)?.setValue([...values, value]);
|
||||
}
|
||||
input.value = '';
|
||||
input.value = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onSave(): void {
|
||||
this.isSaving = true;
|
||||
this.bookService.updateBookMetadata(this.currentBookId, this.buildMetadataWrapper(undefined), false).subscribe({
|
||||
next: (response) => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book metadata updated'});
|
||||
},
|
||||
error: (err) => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: err?.error?.message || 'Failed to update book metadata'
|
||||
});
|
||||
}
|
||||
});
|
||||
this.bookService
|
||||
.updateBookMetadata(
|
||||
this.currentBookId,
|
||||
this.buildMetadataWrapper(undefined),
|
||||
false
|
||||
)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: "info",
|
||||
summary: "Success",
|
||||
detail: "Book metadata updated",
|
||||
});
|
||||
},
|
||||
error: (err) => {
|
||||
this.isSaving = false;
|
||||
this.messageService.add({
|
||||
severity: "error",
|
||||
summary: "Error",
|
||||
detail: err?.error?.message || "Failed to update book metadata",
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
toggleLock(field: string): void {
|
||||
if (field === 'thumbnailUrl') {
|
||||
field = 'cover'
|
||||
if (field === "thumbnailUrl") {
|
||||
field = "cover";
|
||||
}
|
||||
const isLocked = this.metadataForm.get(field + 'Locked')?.value;
|
||||
const isLocked = this.metadataForm.get(field + "Locked")?.value;
|
||||
const updatedLockedState = !isLocked;
|
||||
this.metadataForm.get(field + 'Locked')?.setValue(updatedLockedState);
|
||||
this.metadataForm.get(field + "Locked")?.setValue(updatedLockedState);
|
||||
if (updatedLockedState) {
|
||||
this.metadataForm.get(field)?.disable();
|
||||
} else {
|
||||
@@ -344,9 +375,9 @@ export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
lockAll(): void {
|
||||
Object.keys(this.metadataForm.controls).forEach((key) => {
|
||||
if (key.endsWith('Locked')) {
|
||||
if (key.endsWith("Locked")) {
|
||||
this.metadataForm.get(key)?.setValue(true);
|
||||
const fieldName = key.replace('Locked', '');
|
||||
const fieldName = key.replace("Locked", "");
|
||||
this.metadataForm.get(fieldName)?.disable();
|
||||
}
|
||||
});
|
||||
@@ -355,9 +386,9 @@ export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
unlockAll(): void {
|
||||
Object.keys(this.metadataForm.controls).forEach((key) => {
|
||||
if (key.endsWith('Locked')) {
|
||||
if (key.endsWith("Locked")) {
|
||||
this.metadataForm.get(key)?.setValue(false);
|
||||
const fieldName = key.replace('Locked', '');
|
||||
const fieldName = key.replace("Locked", "");
|
||||
this.metadataForm.get(fieldName)?.enable();
|
||||
}
|
||||
});
|
||||
@@ -365,74 +396,78 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
quillDisabled(): boolean {
|
||||
return this.metadataForm.get('descriptionLocked')?.value === true;
|
||||
return this.metadataForm.get("descriptionLocked")?.value === true;
|
||||
}
|
||||
|
||||
private buildMetadataWrapper(shouldLockAllFields?: boolean): MetadataUpdateWrapper {
|
||||
private buildMetadataWrapper(
|
||||
shouldLockAllFields?: boolean
|
||||
): MetadataUpdateWrapper {
|
||||
const form = this.metadataForm;
|
||||
|
||||
const metadata: BookMetadata = {
|
||||
bookId: this.currentBookId,
|
||||
title: form.get('title')?.value,
|
||||
subtitle: form.get('subtitle')?.value,
|
||||
authors: form.get('authors')?.value ?? [],
|
||||
categories: form.get('categories')?.value ?? [],
|
||||
publisher: form.get('publisher')?.value,
|
||||
publishedDate: form.get('publishedDate')?.value,
|
||||
isbn10: form.get('isbn10')?.value,
|
||||
isbn13: form.get('isbn13')?.value,
|
||||
description: form.get('description')?.value,
|
||||
pageCount: form.get('pageCount')?.value,
|
||||
rating: form.get('rating')?.value,
|
||||
reviewCount: form.get('reviewCount')?.value,
|
||||
asin: form.get('asin')?.value,
|
||||
personalRating: form.get('personalRating')?.value,
|
||||
amazonRating: form.get('amazonRating')?.value,
|
||||
amazonReviewCount: form.get('amazonReviewCount')?.value,
|
||||
goodreadsId: form.get('goodreadsId')?.value,
|
||||
comicvineId: form.get('comicvineId')?.value,
|
||||
goodreadsRating: form.get('goodreadsRating')?.value,
|
||||
goodreadsReviewCount: form.get('goodreadsReviewCount')?.value,
|
||||
hardcoverId: form.get('hardcoverId')?.value,
|
||||
hardcoverRating: form.get('hardcoverRating')?.value,
|
||||
hardcoverReviewCount: form.get('hardcoverReviewCount')?.value,
|
||||
googleId: form.get('googleId')?.value,
|
||||
language: form.get('language')?.value,
|
||||
seriesName: form.get('seriesName')?.value,
|
||||
seriesNumber: form.get('seriesNumber')?.value,
|
||||
seriesTotal: form.get('seriesTotal')?.value,
|
||||
thumbnailUrl: form.get('thumbnailUrl')?.value,
|
||||
title: form.get("title")?.value,
|
||||
subtitle: form.get("subtitle")?.value,
|
||||
authors: form.get("authors")?.value ?? [],
|
||||
categories: form.get("categories")?.value ?? [],
|
||||
publisher: form.get("publisher")?.value,
|
||||
publishedDate: form.get("publishedDate")?.value,
|
||||
isbn10: form.get("isbn10")?.value,
|
||||
isbn13: form.get("isbn13")?.value,
|
||||
description: form.get("description")?.value,
|
||||
pageCount: form.get("pageCount")?.value,
|
||||
rating: form.get("rating")?.value,
|
||||
reviewCount: form.get("reviewCount")?.value,
|
||||
asin: form.get("asin")?.value,
|
||||
personalRating: form.get("personalRating")?.value,
|
||||
amazonRating: form.get("amazonRating")?.value,
|
||||
amazonReviewCount: form.get("amazonReviewCount")?.value,
|
||||
goodreadsId: form.get("goodreadsId")?.value,
|
||||
comicvineId: form.get("comicvineId")?.value,
|
||||
goodreadsRating: form.get("goodreadsRating")?.value,
|
||||
goodreadsReviewCount: form.get("goodreadsReviewCount")?.value,
|
||||
hardcoverId: form.get("hardcoverId")?.value,
|
||||
hardcoverRating: form.get("hardcoverRating")?.value,
|
||||
hardcoverReviewCount: form.get("hardcoverReviewCount")?.value,
|
||||
googleId: form.get("googleId")?.value,
|
||||
language: form.get("language")?.value,
|
||||
seriesName: form.get("seriesName")?.value,
|
||||
seriesNumber: form.get("seriesNumber")?.value,
|
||||
seriesTotal: form.get("seriesTotal")?.value,
|
||||
thumbnailUrl: form.get("thumbnailUrl")?.value,
|
||||
|
||||
// Locks
|
||||
titleLocked: form.get('titleLocked')?.value,
|
||||
subtitleLocked: form.get('subtitleLocked')?.value,
|
||||
authorsLocked: form.get('authorsLocked')?.value,
|
||||
categoriesLocked: form.get('categoriesLocked')?.value,
|
||||
publisherLocked: form.get('publisherLocked')?.value,
|
||||
publishedDateLocked: form.get('publishedDateLocked')?.value,
|
||||
isbn10Locked: form.get('isbn10Locked')?.value,
|
||||
isbn13Locked: form.get('isbn13Locked')?.value,
|
||||
descriptionLocked: form.get('descriptionLocked')?.value,
|
||||
pageCountLocked: form.get('pageCountLocked')?.value,
|
||||
languageLocked: form.get('languageLocked')?.value,
|
||||
asinLocked: form.get('asinLocked')?.value,
|
||||
amazonRatingLocked: form.get('amazonRatingLocked')?.value,
|
||||
personalRatingLocked: form.get('personalRatingLocked')?.value,
|
||||
amazonReviewCountLocked: form.get('amazonReviewCountLocked')?.value,
|
||||
goodreadsIdLocked: form.get('goodreadsIdLocked')?.value,
|
||||
comicvineIdLocked: form.get('comicvineIdLocked')?.value,
|
||||
goodreadsRatingLocked: form.get('goodreadsRatingLocked')?.value,
|
||||
goodreadsReviewCountLocked: form.get('goodreadsReviewCountLocked')?.value,
|
||||
hardcoverIdLocked: form.get('hardcoverIdLocked')?.value,
|
||||
hardcoverRatingLocked: form.get('hardcoverRatingLocked')?.value,
|
||||
hardcoverReviewCountLocked: form.get('hardcoverReviewCountLocked')?.value,
|
||||
googleIdLocked: form.get('googleIdLocked')?.value,
|
||||
seriesNameLocked: form.get('seriesNameLocked')?.value,
|
||||
seriesNumberLocked: form.get('seriesNumberLocked')?.value,
|
||||
seriesTotalLocked: form.get('seriesTotalLocked')?.value,
|
||||
coverLocked: form.get('coverLocked')?.value,
|
||||
titleLocked: form.get("titleLocked")?.value,
|
||||
subtitleLocked: form.get("subtitleLocked")?.value,
|
||||
authorsLocked: form.get("authorsLocked")?.value,
|
||||
categoriesLocked: form.get("categoriesLocked")?.value,
|
||||
publisherLocked: form.get("publisherLocked")?.value,
|
||||
publishedDateLocked: form.get("publishedDateLocked")?.value,
|
||||
isbn10Locked: form.get("isbn10Locked")?.value,
|
||||
isbn13Locked: form.get("isbn13Locked")?.value,
|
||||
descriptionLocked: form.get("descriptionLocked")?.value,
|
||||
pageCountLocked: form.get("pageCountLocked")?.value,
|
||||
languageLocked: form.get("languageLocked")?.value,
|
||||
asinLocked: form.get("asinLocked")?.value,
|
||||
amazonRatingLocked: form.get("amazonRatingLocked")?.value,
|
||||
personalRatingLocked: form.get("personalRatingLocked")?.value,
|
||||
amazonReviewCountLocked: form.get("amazonReviewCountLocked")?.value,
|
||||
goodreadsIdLocked: form.get("goodreadsIdLocked")?.value,
|
||||
comicvineIdLocked: form.get("comicvineIdLocked")?.value,
|
||||
goodreadsRatingLocked: form.get("goodreadsRatingLocked")?.value,
|
||||
goodreadsReviewCountLocked: form.get("goodreadsReviewCountLocked")?.value,
|
||||
hardcoverIdLocked: form.get("hardcoverIdLocked")?.value,
|
||||
hardcoverRatingLocked: form.get("hardcoverRatingLocked")?.value,
|
||||
hardcoverReviewCountLocked: form.get("hardcoverReviewCountLocked")?.value,
|
||||
googleIdLocked: form.get("googleIdLocked")?.value,
|
||||
seriesNameLocked: form.get("seriesNameLocked")?.value,
|
||||
seriesNumberLocked: form.get("seriesNumberLocked")?.value,
|
||||
seriesTotalLocked: form.get("seriesTotalLocked")?.value,
|
||||
coverLocked: form.get("coverLocked")?.value,
|
||||
|
||||
...(shouldLockAllFields !== undefined && {allFieldsLocked: shouldLockAllFields})
|
||||
...(shouldLockAllFields !== undefined && {
|
||||
allFieldsLocked: shouldLockAllFields,
|
||||
}),
|
||||
};
|
||||
|
||||
const original = this.originalMetadata;
|
||||
@@ -442,66 +477,70 @@ export class MetadataEditorComponent implements OnInit {
|
||||
const prev = (original[key] as any) ?? null;
|
||||
|
||||
const isEmpty = (val: any): boolean =>
|
||||
val === null || val === '' || (Array.isArray(val) && val.length === 0);
|
||||
val === null || val === "" || (Array.isArray(val) && val.length === 0);
|
||||
|
||||
return isEmpty(current) && !isEmpty(prev);
|
||||
};
|
||||
|
||||
const clearFlags: MetadataClearFlags = {
|
||||
title: wasCleared('title'),
|
||||
subtitle: wasCleared('subtitle'),
|
||||
authors: wasCleared('authors'),
|
||||
categories: wasCleared('categories'),
|
||||
publisher: wasCleared('publisher'),
|
||||
publishedDate: wasCleared('publishedDate'),
|
||||
isbn10: wasCleared('isbn10'),
|
||||
isbn13: wasCleared('isbn13'),
|
||||
description: wasCleared('description'),
|
||||
pageCount: wasCleared('pageCount'),
|
||||
language: wasCleared('language'),
|
||||
asin: wasCleared('asin'),
|
||||
personalRating: wasCleared('personalRating'),
|
||||
amazonRating: wasCleared('personalRating'),
|
||||
amazonReviewCount: wasCleared('amazonReviewCount'),
|
||||
goodreadsId: wasCleared('goodreadsId'),
|
||||
comicvineId: wasCleared('comicvineId'),
|
||||
goodreadsRating: wasCleared('goodreadsRating'),
|
||||
goodreadsReviewCount: wasCleared('goodreadsReviewCount'),
|
||||
hardcoverId: wasCleared('hardcoverId'),
|
||||
hardcoverRating: wasCleared('hardcoverRating'),
|
||||
hardcoverReviewCount: wasCleared('hardcoverReviewCount'),
|
||||
googleId: wasCleared('googleId'),
|
||||
seriesName: wasCleared('seriesName'),
|
||||
seriesNumber: wasCleared('seriesNumber'),
|
||||
seriesTotal: wasCleared('seriesTotal'),
|
||||
cover: false
|
||||
title: wasCleared("title"),
|
||||
subtitle: wasCleared("subtitle"),
|
||||
authors: wasCleared("authors"),
|
||||
categories: wasCleared("categories"),
|
||||
publisher: wasCleared("publisher"),
|
||||
publishedDate: wasCleared("publishedDate"),
|
||||
isbn10: wasCleared("isbn10"),
|
||||
isbn13: wasCleared("isbn13"),
|
||||
description: wasCleared("description"),
|
||||
pageCount: wasCleared("pageCount"),
|
||||
language: wasCleared("language"),
|
||||
asin: wasCleared("asin"),
|
||||
personalRating: wasCleared("personalRating"),
|
||||
amazonRating: wasCleared("personalRating"),
|
||||
amazonReviewCount: wasCleared("amazonReviewCount"),
|
||||
goodreadsId: wasCleared("goodreadsId"),
|
||||
comicvineId: wasCleared("comicvineId"),
|
||||
goodreadsRating: wasCleared("goodreadsRating"),
|
||||
goodreadsReviewCount: wasCleared("goodreadsReviewCount"),
|
||||
hardcoverId: wasCleared("hardcoverId"),
|
||||
hardcoverRating: wasCleared("hardcoverRating"),
|
||||
hardcoverReviewCount: wasCleared("hardcoverReviewCount"),
|
||||
googleId: wasCleared("googleId"),
|
||||
seriesName: wasCleared("seriesName"),
|
||||
seriesNumber: wasCleared("seriesNumber"),
|
||||
seriesTotal: wasCleared("seriesTotal"),
|
||||
cover: false,
|
||||
};
|
||||
|
||||
return {metadata, clearFlags};
|
||||
return { metadata, clearFlags };
|
||||
}
|
||||
|
||||
private updateMetadata(shouldLockAllFields: boolean | undefined): void {
|
||||
let metadataUpdateWrapper = this.buildMetadataWrapper(shouldLockAllFields);
|
||||
this.bookService.updateBookMetadata(this.currentBookId, metadataUpdateWrapper, false).subscribe({
|
||||
next: (response) => {
|
||||
if (shouldLockAllFields !== undefined) {
|
||||
this.bookService
|
||||
.updateBookMetadata(this.currentBookId, metadataUpdateWrapper, false)
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
if (shouldLockAllFields !== undefined) {
|
||||
this.messageService.add({
|
||||
severity: "success",
|
||||
summary: shouldLockAllFields
|
||||
? "Metadata Locked"
|
||||
: "Metadata Unlocked",
|
||||
detail: shouldLockAllFields
|
||||
? "All fields have been successfully locked."
|
||||
: "All fields have been successfully unlocked.",
|
||||
});
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: shouldLockAllFields ? 'Metadata Locked' : 'Metadata Unlocked',
|
||||
detail: shouldLockAllFields
|
||||
? 'All fields have been successfully locked.'
|
||||
: 'All fields have been successfully unlocked.',
|
||||
severity: "error",
|
||||
summary: "Error",
|
||||
detail: "Failed to update lock state",
|
||||
});
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update lock state',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
getUploadCoverUrl(): string {
|
||||
@@ -513,15 +552,22 @@ export class MetadataEditorComponent implements OnInit {
|
||||
}
|
||||
|
||||
onUpload(event: FileUploadEvent): void {
|
||||
const response: HttpResponse<any> = event.originalEvent as HttpResponse<any>;
|
||||
const response: HttpResponse<any> =
|
||||
event.originalEvent as HttpResponse<any>;
|
||||
if (response && response.status === 200) {
|
||||
const bookMetadata: BookMetadata = response.body as BookMetadata;
|
||||
this.bookService.handleBookMetadataUpdate(this.currentBookId, bookMetadata);
|
||||
this.bookService.handleBookMetadataUpdate(
|
||||
this.currentBookId,
|
||||
bookMetadata
|
||||
);
|
||||
this.isUploading = false;
|
||||
} else {
|
||||
this.isUploading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error', summary: 'Upload Failed', detail: 'An error occurred while uploading the cover', life: 3000
|
||||
severity: "error",
|
||||
summary: "Upload Failed",
|
||||
detail: "An error occurred while uploading the cover",
|
||||
life: 3000,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -529,7 +575,10 @@ export class MetadataEditorComponent implements OnInit {
|
||||
onUploadError($event: FileUploadErrorEvent) {
|
||||
this.isUploading = false;
|
||||
this.messageService.add({
|
||||
severity: 'error', summary: 'Upload Error', detail: 'An error occurred while uploading the cover', life: 3000
|
||||
severity: "error",
|
||||
summary: "Upload Error",
|
||||
detail: "An error occurred while uploading the cover",
|
||||
life: 3000,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -537,29 +586,75 @@ export class MetadataEditorComponent implements OnInit {
|
||||
this.bookService.regenerateCover(bookId).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Success',
|
||||
detail: 'Book cover regenerated successfully. Refresh page to see the new cover.'
|
||||
severity: "success",
|
||||
summary: "Success",
|
||||
detail:
|
||||
"Book cover regenerated successfully. Refresh page to see the new cover.",
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to start cover regeneration'
|
||||
severity: "error",
|
||||
summary: "Error",
|
||||
detail: "Failed to start cover regeneration",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// restoreCbxMetadata() {
|
||||
// this.isLoading = true;
|
||||
// this.bookService.getComicInfoMetadata(this.currentBookId).subscribe();
|
||||
// setTimeout(() => {
|
||||
// this.isLoading = false;
|
||||
// // this.refreshingBookIds.delete(bookId);
|
||||
// }, 10000);
|
||||
// }
|
||||
restoreCbxMetadata() {
|
||||
this.isLoading = true;
|
||||
console.log("LOADING CBX METADATA FOR BOOK ID:", this.currentBookId);
|
||||
this.bookService.getComicInfoMetadata(this.currentBookId).subscribe({
|
||||
next: (metadata) => {
|
||||
console.log("Retrieved ComicInfo.xml metadata:", metadata);
|
||||
|
||||
if (metadata) {
|
||||
this.originalMetadata = structuredClone(metadata);
|
||||
this.populateFormFromMetadata(metadata);
|
||||
this.messageService.add({
|
||||
severity: "success",
|
||||
summary: "Restored",
|
||||
detail: "Metadata loaded from ComicInfo.xml",
|
||||
});
|
||||
} else {
|
||||
this.messageService.add({
|
||||
severity: "warn",
|
||||
summary: "No Data",
|
||||
detail: "ComicInfo.xml not found or empty.",
|
||||
});
|
||||
}
|
||||
this.isLoading = false;
|
||||
},
|
||||
error: (err) => {
|
||||
console.error("Error loading ComicInfo.xml metadata:", err);
|
||||
console.error(err.message);
|
||||
this.isLoading = false;
|
||||
this.messageService.add({
|
||||
severity: "error",
|
||||
summary: "Error",
|
||||
detail: err?.error?.message || "Failed to load ComicInfo.xml",
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
restoreMetadata() {
|
||||
this.dialogService.open(MetadataRestoreDialogComponent, {
|
||||
header: 'Restore Metadata from Backup',
|
||||
header: "Restore Metadata from Backup",
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookId: [this.currentBookId]
|
||||
}
|
||||
bookId: [this.currentBookId],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -592,18 +687,25 @@ export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
openCoverSearch() {
|
||||
const ref = this.dialogService.open(CoverSearchComponent, {
|
||||
header: 'Search Cover',
|
||||
header: "Search Cover",
|
||||
modal: true,
|
||||
closable: true,
|
||||
data: {
|
||||
bookId: [this.currentBookId]
|
||||
bookId: [this.currentBookId],
|
||||
},
|
||||
style: {
|
||||
width: '90vw',
|
||||
height: '90vh',
|
||||
maxWidth: '1200px',
|
||||
position: 'absolute'
|
||||
width: "90vw",
|
||||
height: "90vh",
|
||||
maxWidth: "1200px",
|
||||
position: "absolute",
|
||||
},
|
||||
});
|
||||
|
||||
ref.onClose.subscribe((result) => {
|
||||
if (result) {
|
||||
this.metadataForm.get("thumbnailUrl")?.setValue(result);
|
||||
this.onSave();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -23,6 +23,23 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Convert CBR/CB7 to CBZ</label>
|
||||
<p-toggleswitch
|
||||
[ngModel]="metadataPersistence.convertCbrCb7ToCbz"
|
||||
(onChange)="onPersistenceToggle('convertCbrCb7ToCbz')"
|
||||
[disabled]="!metadataPersistence.saveToOriginalFile">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
<i class="pi pi-info-circle"></i>
|
||||
Converts CBR and CB7 files to CBZ format when updating metadata. If disabled, edits to CBR/CB7 files will not be written to the original file.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
|
||||
+2
@@ -20,6 +20,7 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
|
||||
|
||||
metadataPersistence: MetadataPersistenceSettings = {
|
||||
saveToOriginalFile: false,
|
||||
convertCbrCb7ToCbz: false,
|
||||
backupMetadata: true,
|
||||
backupCover: true
|
||||
};
|
||||
@@ -62,6 +63,7 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
|
||||
this.metadataPersistence.saveToOriginalFile = !this.metadataPersistence.saveToOriginalFile;
|
||||
|
||||
if (!this.metadataPersistence.saveToOriginalFile) {
|
||||
this.metadataPersistence.convertCbrCb7ToCbz = false;
|
||||
this.metadataPersistence.backupMetadata = false;
|
||||
this.metadataPersistence.backupCover = false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user