Add an option to save metadata directly into the EPUB file, along with the ability to back up and restore the original metadata.
This commit is contained in:
committed by
Aditya Chandel
parent
faae595ef6
commit
03ce268d8e
+1
@@ -50,6 +50,7 @@ public class SecurityConfig {
|
||||
"/api/v1/settings",
|
||||
"/api/v1/setup/**",
|
||||
"/api/v1/books/*/cover",
|
||||
"/api/v1/books/*/backup-cover",
|
||||
"/api/v1/opds/*/cover.jpg",
|
||||
"/api/v1/cbx/*/pages/*",
|
||||
"/api/v1/pdf/*/pages/*"
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.BookRecommendation;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataBackupRestoreService;
|
||||
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import jakarta.validation.Valid;
|
||||
@@ -26,6 +27,7 @@ public class BookController {
|
||||
|
||||
private final BookService bookService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
private final MetadataBackupRestoreService metadataBackupRestoreService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
@@ -42,6 +44,15 @@ public class BookController {
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/backup-cover")
|
||||
public ResponseEntity<Resource> getBackupBookCover(@PathVariable long bookId) {
|
||||
Resource file = metadataBackupRestoreService.getBackupCover(bookId);
|
||||
return ResponseEntity.ok()
|
||||
.header("Content-Disposition", "inline; filename=cover.jpg")
|
||||
.contentType(org.springframework.http.MediaType.IMAGE_JPEG)
|
||||
.body(file);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/content")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
|
||||
return bookService.getBookContent(bookId);
|
||||
|
||||
+22
-1
@@ -1,10 +1,14 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.*;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.quartz.JobSchedulerService;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
@@ -15,6 +19,7 @@ import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@@ -27,6 +32,7 @@ public class MetadataController {
|
||||
private final JobSchedulerService jobSchedulerService;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
@PostMapping("/{bookId}/metadata/prospective")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@@ -39,7 +45,8 @@ public class MetadataController {
|
||||
public ResponseEntity<BookMetadata> updateMetadata(
|
||||
@RequestBody BookMetadata setMetadataRequest, @PathVariable long bookId,
|
||||
@RequestParam(defaultValue = "true") boolean mergeCategories) {
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookMetadataUpdater.setBookMetadata(bookId, setMetadataRequest, true, mergeCategories), true);
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookMetadataUpdater.setBookMetadata(bookEntity, setMetadataRequest, true, mergeCategories), true);
|
||||
return ResponseEntity.ok(bookMetadata);
|
||||
}
|
||||
|
||||
@@ -88,4 +95,18 @@ public class MetadataController {
|
||||
metadataMatchService.recalculateAllMatchScores();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/metadata/restore")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<EpubMetadata> getBackedUpMetadata(@PathVariable Long bookId) throws IOException {
|
||||
EpubMetadata restoredMetadata = bookMetadataService.getBackedUpMetadata(bookId);
|
||||
return ResponseEntity.ok(restoredMetadata);
|
||||
}
|
||||
|
||||
@PostMapping("/{bookId}/metadata/restore")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<BookMetadata> restoreMetadata(@PathVariable Long bookId) throws IOException {
|
||||
BookMetadata restoredMetadata = bookMetadataService.restoreMetadataFromBackup(bookId);
|
||||
return ResponseEntity.ok(restoredMetadata);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface EpubMetadataMapper {
|
||||
|
||||
EpubMetadataMapper INSTANCE = Mappers.getMapper(EpubMetadataMapper.class);
|
||||
|
||||
EpubMetadata toEpubMetadata(BookMetadata bookMetadata);
|
||||
|
||||
BookMetadata toBookMetadata(EpubMetadata epubMetadata);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Set;
|
||||
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class EpubMetadata {
|
||||
private Long bookId;
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private String publisher;
|
||||
private LocalDate publishedDate;
|
||||
private String description;
|
||||
private String seriesName;
|
||||
private Float seriesNumber;
|
||||
private Integer seriesTotal;
|
||||
private String isbn13;
|
||||
private String isbn10;
|
||||
private Integer pageCount;
|
||||
private String language;
|
||||
private String asin;
|
||||
private Double amazonRating;
|
||||
private Integer amazonReviewCount;
|
||||
private String goodreadsId;
|
||||
private Double goodreadsRating;
|
||||
private Integer goodreadsReviewCount;
|
||||
private String hardcoverId;
|
||||
private Double hardcoverRating;
|
||||
private Integer hardcoverReviewCount;
|
||||
private String googleId;
|
||||
private Set<String> authors;
|
||||
private Set<String> categories;
|
||||
}
|
||||
+1
@@ -11,6 +11,7 @@ public enum AppSettingKey {
|
||||
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true),
|
||||
METADATA_PROVIDER_SETTINGS("metadata_provider_settings", true),
|
||||
METADATA_MATCH_WEIGHTS("metadata_match_weights", true),
|
||||
METADATA_PERSISTENCE_SETTINGS("metadata_persistence_settings", true),
|
||||
|
||||
AUTO_BOOK_SEARCH("auto_book_search", false),
|
||||
COVER_IMAGE_RESOLUTION("cover_image_resolution", false),
|
||||
|
||||
+1
-1
@@ -20,11 +20,11 @@ public class AppSettings {
|
||||
private Integer cbxCacheSizeInMb;
|
||||
private Integer pdfCacheSizeInMb;
|
||||
private Integer maxFileUploadSizeInMb;
|
||||
|
||||
private boolean remoteAuthEnabled;
|
||||
private boolean oidcEnabled;
|
||||
private OidcProviderDetails oidcProviderDetails;
|
||||
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
|
||||
private MetadataProviderSettings metadataProviderSettings;
|
||||
private MetadataMatchWeights metadataMatchWeights;
|
||||
private MetadataPersistenceSettings metadataPersistenceSettings;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.adityachandel.booklore.model.dto.settings;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MetadataPersistenceSettings {
|
||||
private boolean saveToOriginalFile;
|
||||
private boolean backupMetadata;
|
||||
private boolean backupCover;
|
||||
}
|
||||
+1
@@ -69,6 +69,7 @@ public class AppSettingService {
|
||||
builder.oidcAutoProvisionDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, OidcAutoProvisionDetails.class, null, false));
|
||||
builder.metadataProviderSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PROVIDER_SETTINGS, MetadataProviderSettings.class, settingPersistenceHelper.getDefaultMetadataProviderSettings(), true));
|
||||
builder.metadataMatchWeights(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_MATCH_WEIGHTS, MetadataMatchWeights.class, settingPersistenceHelper.getDefaultMetadataMatchWeights(), true));
|
||||
builder.metadataPersistenceSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PERSISTENCE_SETTINGS, MetadataPersistenceSettings.class, settingPersistenceHelper.getDefaultMetadataPersistenceSettings(), true));
|
||||
|
||||
builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true")));
|
||||
|
||||
+9
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.appsettings;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettingKey;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
|
||||
import com.adityachandel.booklore.model.entity.AppSettingEntity;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
@@ -168,4 +169,12 @@ public class SettingPersistenceHelper {
|
||||
.coverImage(5)
|
||||
.build();
|
||||
}
|
||||
|
||||
public MetadataPersistenceSettings getDefaultMetadataPersistenceSettings() {
|
||||
return MetadataPersistenceSettings.builder()
|
||||
.saveToOriginalFile(false)
|
||||
.backupMetadata(false)
|
||||
.backupCover(false)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+67
-271
@@ -1,29 +1,25 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
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.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.EpubMetadataReader;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import io.documentnode.epub4j.domain.Identifier;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.FileHeader;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
@@ -32,24 +28,21 @@ import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
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.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import io.documentnode.epub4j.domain.Identifier;
|
||||
import io.documentnode.epub4j.domain.Metadata;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.FileHeader;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -62,6 +55,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final EpubMetadataReader epubMetadataReader;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -97,16 +91,11 @@ public class EpubProcessor implements FileProcessor {
|
||||
try {
|
||||
File epubFile = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(epubFile));
|
||||
|
||||
// Try the default method
|
||||
Resource coverImage = epub.getCoverImage();
|
||||
|
||||
// Fallback: look for a manifest resource with common "cover" keywords
|
||||
if (coverImage == null) {
|
||||
for (Resource res : epub.getResources().getAll()) {
|
||||
String id = res.getId();
|
||||
String href = res.getHref();
|
||||
|
||||
if ((id != null && id.toLowerCase().contains("cover")) ||
|
||||
(href != null && href.toLowerCase().contains("cover"))) {
|
||||
|
||||
@@ -117,156 +106,56 @@ public class EpubProcessor implements FileProcessor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean saved = saveCoverImage(coverImage, bookEntity.getId());
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return saved;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for epub file {}, error: {}", bookEntity.getFileName(), e.getMessage(), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Set<String> getAuthors(io.documentnode.epub4j.domain.Book book) {
|
||||
return book.getMetadata().getAuthors().stream()
|
||||
.map(author -> author.getFirstname() + " " + author.getLastname())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
log.debug("***Setting metadata for book {}", bookEntity.getFileName());
|
||||
try (FileInputStream fis = new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
|
||||
io.documentnode.epub4j.domain.Book book = new EpubReader().readEpub(fis);
|
||||
EpubMetadata epubMetadata = epubMetadataReader.readMetadata(bookFile);
|
||||
if (epubMetadata == null) return;
|
||||
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
bookMetadata.setTitle(truncate(epubMetadata.getTitle(), 1000));
|
||||
bookMetadata.setSubtitle(truncate(epubMetadata.getSubtitle(), 1000));
|
||||
bookMetadata.setDescription(truncate(epubMetadata.getDescription(), 2000));
|
||||
bookMetadata.setPublisher(truncate(epubMetadata.getPublisher(), 1000));
|
||||
bookMetadata.setPublishedDate(epubMetadata.getPublishedDate());
|
||||
bookMetadata.setSeriesName(truncate(epubMetadata.getSeriesName(), 1000));
|
||||
bookMetadata.setSeriesNumber(epubMetadata.getSeriesNumber());
|
||||
bookMetadata.setSeriesTotal(epubMetadata.getSeriesTotal());
|
||||
bookMetadata.setIsbn13(truncate(epubMetadata.getIsbn13(), 64));
|
||||
bookMetadata.setIsbn10(truncate(epubMetadata.getIsbn10(), 64));
|
||||
bookMetadata.setPageCount(epubMetadata.getPageCount());
|
||||
|
||||
if (epubMetadata != null) {
|
||||
bookMetadata.setTitle(truncate(epubMetadata.getFirstTitle(), 1000));
|
||||
String lang = epubMetadata.getLanguage();
|
||||
bookMetadata.setLanguage(truncate((lang == null || lang.equalsIgnoreCase("UND")) ? "en" : lang, 1000));
|
||||
|
||||
if (epubMetadata.getDescriptions() != null && !epubMetadata.getDescriptions().isEmpty()) {
|
||||
bookMetadata.setDescription(truncate(epubMetadata.getDescriptions().getFirst(), 2000));
|
||||
}
|
||||
bookMetadata.setAsin(truncate(epubMetadata.getAsin(), 20));
|
||||
bookMetadata.setAmazonRating(epubMetadata.getAmazonRating());
|
||||
bookMetadata.setAmazonReviewCount(epubMetadata.getAmazonReviewCount());
|
||||
bookMetadata.setGoodreadsId(truncate(epubMetadata.getGoodreadsId(), 100));
|
||||
bookMetadata.setGoodreadsRating(epubMetadata.getGoodreadsRating());
|
||||
bookMetadata.setGoodreadsReviewCount(epubMetadata.getGoodreadsReviewCount());
|
||||
bookMetadata.setHardcoverId(truncate(epubMetadata.getHardcoverId(), 100));
|
||||
bookMetadata.setHardcoverRating(epubMetadata.getHardcoverRating());
|
||||
bookMetadata.setHardcoverReviewCount(epubMetadata.getHardcoverReviewCount());
|
||||
bookMetadata.setGoogleId(truncate(epubMetadata.getGoogleId(), 100));
|
||||
|
||||
if (epubMetadata.getPublishers() != null && !epubMetadata.getPublishers().isEmpty()) {
|
||||
bookMetadata.setPublisher(truncate(epubMetadata.getPublishers().getFirst(), 2000));
|
||||
}
|
||||
bookCreatorService.addAuthorsToBook(epubMetadata.getAuthors(), bookEntity);
|
||||
|
||||
List<String> identifiers = epubMetadata.getIdentifiers().stream()
|
||||
.map(Identifier::getValue)
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.map(id -> id.contains(":") ? id.substring(id.indexOf(":") + 1) : id) // strip prefix
|
||||
.map(id -> id.replace("-", "")) // remove dashes
|
||||
.toList();
|
||||
|
||||
|
||||
if (!identifiers.isEmpty()) {
|
||||
// Checking for ISBN 13 (strict 13-digit numeric)
|
||||
String isbn13 = identifiers.stream()
|
||||
.filter(id -> id.length() == 13 && id.matches("\\d{13}"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
// Checking for ISBN 10 (strict 10-digit format or ends in X)
|
||||
String isbn10 = identifiers.stream()
|
||||
.filter(id -> id.length() == 10 && id.matches("\\d{9}[\\dXx]"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
// Checking for ASIN (alphanumeric 10 chars, must not be ISBN-10)
|
||||
String asin = identifiers.stream()
|
||||
.filter(id -> id.length() == 10 && id.matches("^[A-Z0-9]{10}$"))
|
||||
.filter(id -> !id.equalsIgnoreCase(isbn10))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
bookMetadata.setIsbn13(truncate(isbn13, 64));
|
||||
bookMetadata.setIsbn10(truncate(isbn10, 64));
|
||||
bookMetadata.setAsin(truncate(asin, 20));
|
||||
}
|
||||
|
||||
bookMetadata.setLanguage(truncate(
|
||||
epubMetadata.getLanguage() == null || epubMetadata.getLanguage().equalsIgnoreCase("UND") ? "en" : epubMetadata.getLanguage(), 1000
|
||||
));
|
||||
|
||||
if (epubMetadata.getDates() != null && !epubMetadata.getDates().isEmpty()) {
|
||||
epubMetadata.getDates().stream()
|
||||
.findFirst()
|
||||
.ifPresent(publishedDate -> {
|
||||
String dateString = publishedDate.getValue();
|
||||
if (isValidLocalDate(dateString)) {
|
||||
LocalDate parsedDate = LocalDate.parse(dateString);
|
||||
bookMetadata.setPublishedDate(parsedDate);
|
||||
} else if (isValidOffsetDateTime(dateString)) {
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateString);
|
||||
bookMetadata.setPublishedDate(offsetDateTime.toLocalDate());
|
||||
} else {
|
||||
log.error("Unable to parse date: {}", dateString);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Calibre (EPUB2) series tags
|
||||
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
|
||||
if (seriesName != null && !seriesName.isEmpty()) {
|
||||
bookMetadata.setSeriesName(truncate(seriesName, 1000));
|
||||
}
|
||||
|
||||
String seriesIndex = epubMetadata.getMetaAttribute("calibre:series_index");
|
||||
if (seriesIndex != null && !seriesIndex.isEmpty()) {
|
||||
try {
|
||||
double indexValue = Double.parseDouble(seriesIndex);
|
||||
bookMetadata.setSeriesNumber((float) indexValue);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Unable to parse series number: {}", seriesIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// fall-back to OPF for anything still missing
|
||||
extractFromOpf(FileUtils.getBookFullPath(bookEntity), bookMetadata);
|
||||
|
||||
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
|
||||
|
||||
// Get subjects and filter out invalid ones
|
||||
List<String> subjects = epubMetadata.getSubjects();
|
||||
List<String> validSubjects = new ArrayList<>();
|
||||
|
||||
if (subjects != null && !subjects.isEmpty()) {
|
||||
for (String subject : subjects) {
|
||||
// Skip null or empty subjects
|
||||
if (subject == null || subject.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip subjects that are too long (likely not real categories)
|
||||
// Real categories are typically short, descriptive terms
|
||||
if (subject.length() > 100) {
|
||||
log.warn("Skipping suspiciously long subject in {}: length={}, value='{}'",
|
||||
bookEntity.getFileName(), subject.length(),
|
||||
subject.substring(0, Math.min(50, subject.length())) + "...");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip subjects that contain newlines or excessive whitespace (likely descriptions)
|
||||
if (subject.contains("\n") || subject.contains("\r") || subject.contains(" ")) {
|
||||
log.warn("Skipping subject with newlines/whitespace in {}: '{}'",
|
||||
bookEntity.getFileName(),
|
||||
subject.substring(0, Math.min(50, subject.length())) + "...");
|
||||
continue;
|
||||
}
|
||||
|
||||
validSubjects.add(subject);
|
||||
}
|
||||
}
|
||||
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error loading epub file {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
if (epubMetadata.getCategories() != null) {
|
||||
List<String> validSubjects = epubMetadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.toList();
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,101 +164,8 @@ public class EpubProcessor implements FileProcessor {
|
||||
return fileProcessingUtils.saveCoverImage(originalImage, bookId);
|
||||
}
|
||||
|
||||
private boolean isValidLocalDate(String dateString) {
|
||||
try {
|
||||
LocalDate.parse(dateString);
|
||||
return true;
|
||||
} catch (DateTimeParseException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isValidOffsetDateTime(String dateString) {
|
||||
try {
|
||||
OffsetDateTime.parse(dateString);
|
||||
return true;
|
||||
} catch (DateTimeParseException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String truncate(String input, int maxLength) {
|
||||
if (input == null) return null;
|
||||
return input.length() <= maxLength ? input : input.substring(0, maxLength);
|
||||
}
|
||||
|
||||
private void extractFromOpf(String epubPath, BookMetadataEntity meta) {
|
||||
try (ZipFile zip = new ZipFile(epubPath)) {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
|
||||
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
|
||||
if (containerHdr == null) return;
|
||||
try (InputStream cis = zip.getInputStream(containerHdr)) {
|
||||
Document containerDoc;
|
||||
try {
|
||||
containerDoc = builder.parse(cis);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
if (containerDoc == null) return;
|
||||
NodeList roots = containerDoc.getElementsByTagName("rootfile");
|
||||
if (roots.getLength() == 0) return;
|
||||
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
|
||||
if (StringUtils.isBlank(opfPath)) return;
|
||||
FileHeader opfHdr = zip.getFileHeader(opfPath);
|
||||
if (opfHdr == null) return;
|
||||
try (InputStream in = zip.getInputStream(opfHdr)) {
|
||||
Document doc;
|
||||
try {
|
||||
doc = builder.parse(in);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
if (doc == null) return;
|
||||
if (StringUtils.isBlank(meta.getIsbn13()) || StringUtils.isBlank(meta.getIsbn10())) {
|
||||
NodeList idNodes = doc.getElementsByTagNameNS("*", "identifier");
|
||||
for (int i = 0; i < idNodes.getLength(); i++) {
|
||||
String idRaw = idNodes.item(i).getTextContent().trim();
|
||||
String isbn = idRaw.toLowerCase().startsWith("isbn:") ? idRaw.substring(5) : idRaw;
|
||||
if (isbn.length() == 13 && StringUtils.isBlank(meta.getIsbn13())) {
|
||||
meta.setIsbn13(truncate(isbn, 64));
|
||||
}
|
||||
if (isbn.length() == 10 && StringUtils.isBlank(meta.getIsbn10())) {
|
||||
meta.setIsbn10(truncate(isbn, 64));
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeList metaNodes = doc.getElementsByTagNameNS("*", "meta");
|
||||
for (int i = 0; i < metaNodes.getLength(); i++) {
|
||||
Element m = (Element) metaNodes.item(i);
|
||||
String nameAttr = m.getAttribute("name");
|
||||
String propAttr = m.getAttribute("property");
|
||||
String content = m.hasAttribute("content") ? m.getAttribute("content").trim() : m.getTextContent().trim();
|
||||
|
||||
if (StringUtils.isBlank(meta.getSeriesName()) && (nameAttr.equalsIgnoreCase("calibre:series") || propAttr.equalsIgnoreCase("belongs-to-collection"))) {
|
||||
meta.setSeriesName(truncate(content, 1000));
|
||||
}
|
||||
if (meta.getSeriesNumber() == null && (nameAttr.equalsIgnoreCase("calibre:series_index") || propAttr.equalsIgnoreCase("group-position"))) {
|
||||
try {
|
||||
int number = (int) Double.parseDouble(content);
|
||||
meta.setSeriesNumber((float) number);
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
if (meta.getPageCount() == null && (nameAttr.equalsIgnoreCase("calibre:pages") || nameAttr.equalsIgnoreCase("pageCount") || propAttr.equalsIgnoreCase("schema:pageCount") || propAttr.equalsIgnoreCase("media:pageCount"))) {
|
||||
try {
|
||||
int pages = Integer.parseInt(content);
|
||||
meta.setPageCount(pages);
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-5
@@ -10,26 +10,27 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
@@ -46,6 +47,8 @@ public class LibraryProcessingService {
|
||||
private final BookRepository bookRepository;
|
||||
private final EntityManager entityManager;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final FileService fileService;
|
||||
private final BookQueryService bookQueryService;
|
||||
|
||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
private final Map<String, ScheduledFuture<?>> deletionTasks = new ConcurrentHashMap<>();
|
||||
@@ -212,13 +215,43 @@ public class LibraryProcessingService {
|
||||
|
||||
@Transactional
|
||||
protected void deleteRemovedBooks(List<Long> bookIds) {
|
||||
bookRepository.deleteByIdIn(bookIds);
|
||||
List<BookEntity> books = bookRepository.findAllById(bookIds);
|
||||
for (BookEntity book : books) {
|
||||
try {
|
||||
if (book.getMetadata() != null && StringUtils.isNotBlank(book.getMetadata().getThumbnail())) {
|
||||
Path thumbnailPath = Path.of(fileService.getThumbnailPath(book.getId()));
|
||||
deleteDirectoryRecursively(thumbnailPath);
|
||||
}
|
||||
Path backupDir = Path.of(fileService.getBookMetadataBackupPath(book.getId()));
|
||||
if (Files.exists(backupDir)) {
|
||||
deleteDirectoryRecursively(backupDir);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to clean up files for book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
bookRepository.deleteAll(books);
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
|
||||
if (bookIds.size() > 1) {
|
||||
log.info("Books removed: {}", bookIds);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (Files.exists(path)) {
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(p -> {
|
||||
try {
|
||||
Files.deleteIfExists(p);
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete file or directory: {}", p, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void processLibraryFiles(List<LibraryFile> libraryFiles) {
|
||||
for (LibraryFile libraryFile : libraryFiles) {
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BookMetadataRestorer {
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final EpubMetadataWriter epubMetadataWriter;
|
||||
|
||||
@Transactional
|
||||
public void restoreMetadata(BookEntity bookEntity, EpubMetadata backup) {
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
if (!isLocked(metadata.getTitleLocked())) metadata.setTitle(backup.getTitle());
|
||||
if (!isLocked(metadata.getSubtitleLocked())) metadata.setSubtitle(backup.getSubtitle());
|
||||
if (!isLocked(metadata.getPublisherLocked())) metadata.setPublisher(backup.getPublisher());
|
||||
if (!isLocked(metadata.getPublishedDateLocked())) metadata.setPublishedDate(backup.getPublishedDate());
|
||||
if (!isLocked(metadata.getDescriptionLocked())) metadata.setDescription(backup.getDescription());
|
||||
if (!isLocked(metadata.getLanguageLocked())) metadata.setLanguage(backup.getLanguage());
|
||||
if (!isLocked(metadata.getPageCountLocked())) metadata.setPageCount(backup.getPageCount());
|
||||
|
||||
if (!isLocked(metadata.getSeriesNameLocked())) metadata.setSeriesName(backup.getSeriesName());
|
||||
if (!isLocked(metadata.getSeriesNumberLocked())) metadata.setSeriesNumber(backup.getSeriesNumber());
|
||||
if (!isLocked(metadata.getSeriesTotalLocked())) metadata.setSeriesTotal(backup.getSeriesTotal());
|
||||
|
||||
if (!isLocked(metadata.getIsbn13Locked())) metadata.setIsbn13(backup.getIsbn13());
|
||||
if (!isLocked(metadata.getIsbn10Locked())) metadata.setIsbn10(backup.getIsbn10());
|
||||
if (!isLocked(metadata.getAsinLocked())) metadata.setAsin(backup.getAsin());
|
||||
if (!isLocked(metadata.getGoodreadsIdLocked())) metadata.setGoodreadsId(backup.getGoodreadsId());
|
||||
if (!isLocked(metadata.getHardcoverIdLocked())) metadata.setHardcoverId(backup.getHardcoverId());
|
||||
if (!isLocked(metadata.getGoogleIdLocked())) metadata.setGoogleId(backup.getGoogleId());
|
||||
|
||||
if (!isLocked(metadata.getAuthorsLocked())) {
|
||||
Set<AuthorEntity> authors = Set.of();
|
||||
if (backup.getAuthors() != null) {
|
||||
authors = backup.getAuthors().stream()
|
||||
.map(name -> authorRepository.findByName(name)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
metadata.setAuthors(authors);
|
||||
}
|
||||
|
||||
if (!isLocked(metadata.getCategoriesLocked())) {
|
||||
Set<CategoryEntity> categories = Set.of();
|
||||
if (backup.getCategories() != null) {
|
||||
categories = backup.getCategories().stream()
|
||||
.map(name -> categoryRepository.findByName(name)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(name).build())))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
metadata.setCategories(categories);
|
||||
}
|
||||
|
||||
if (!isLocked(metadata.getAmazonRatingLocked())) metadata.setAmazonRating(backup.getAmazonRating());
|
||||
if (!isLocked(metadata.getAmazonReviewCountLocked())) metadata.setAmazonReviewCount(backup.getAmazonReviewCount());
|
||||
|
||||
if (!isLocked(metadata.getGoodreadsRatingLocked())) metadata.setGoodreadsRating(backup.getGoodreadsRating());
|
||||
if (!isLocked(metadata.getGoodreadsReviewCountLocked())) metadata.setGoodreadsReviewCount(backup.getGoodreadsReviewCount());
|
||||
|
||||
if (!isLocked(metadata.getHardcoverRatingLocked())) metadata.setHardcoverRating(backup.getHardcoverRating());
|
||||
if (!isLocked(metadata.getHardcoverReviewCountLocked())) metadata.setHardcoverReviewCount(backup.getHardcoverReviewCount());
|
||||
|
||||
bookMetadataRepository.save(metadata);
|
||||
|
||||
try {
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookRepository.save(bookEntity);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to calculate/save metadata match score for book ID {}: {}", bookEntity.getId(), e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
epubMetadataWriter.writeMetadataToFile(bookFile, metadata);
|
||||
log.info("Embedded metadata written to EPUB for book ID {}", bookEntity.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to write metadata to EPUB for book ID {}: {}", bookEntity.getId(), e.getMessage());
|
||||
}
|
||||
|
||||
log.info("Metadata fully restored from backup for book ID {}", bookEntity.getId());
|
||||
}
|
||||
|
||||
private boolean isLocked(Boolean locked) {
|
||||
return locked != null && locked;
|
||||
}
|
||||
}
|
||||
+20
-1
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
|
||||
@@ -27,13 +28,19 @@ import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.service.metadata.parser.BookParser;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -62,6 +69,7 @@ public class BookMetadataService {
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
private final MetadataBackupRestoreService metadataBackupRestoreService;
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
@@ -134,7 +142,7 @@ public class BookMetadataService {
|
||||
@Transactional
|
||||
protected BookMetadataEntity updateBookMetadata(BookEntity bookEntity, BookMetadata metadata, boolean replaceCover, boolean mergeCategories) {
|
||||
if (metadata != null) {
|
||||
BookMetadataEntity bookMetadata = bookMetadataUpdater.setBookMetadata(bookEntity.getId(), metadata, replaceCover, mergeCategories);
|
||||
BookMetadataEntity bookMetadata = bookMetadataUpdater.setBookMetadata(bookEntity, metadata, replaceCover, mergeCategories);
|
||||
bookEntity.setMetadata(bookMetadata);
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, book);
|
||||
@@ -474,4 +482,15 @@ public class BookMetadataService {
|
||||
}
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
}
|
||||
|
||||
public BookMetadata restoreMetadataFromBackup(Long bookId) throws IOException {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
metadataBackupRestoreService.restoreEmbeddedMetadata(bookEntity);
|
||||
bookRepository.saveAndFlush(bookEntity);
|
||||
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
|
||||
}
|
||||
|
||||
public EpubMetadata getBackedUpMetadata(Long bookId) {
|
||||
return metadataBackupRestoreService.getBackedUpMetadata(bookId);
|
||||
}
|
||||
}
|
||||
+86
-49
@@ -2,8 +2,16 @@ package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -13,9 +21,9 @@ import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
@@ -33,29 +41,58 @@ public class BookMetadataUpdater {
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final FileService fileService;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final MetadataBackupRestoreService metadataBackupRestoreService;
|
||||
private final EpubMetadataWriter epubMetadataWriter;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public BookMetadataEntity setBookMetadata(long bookId, BookMetadata newMetadata, boolean setThumbnail, boolean mergeCategories) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
public BookMetadataEntity setBookMetadata(BookEntity bookEntity, BookMetadata newMetadata, boolean setThumbnail, boolean mergeCategories) {
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
updateLocks(newMetadata, metadata);
|
||||
|
||||
if (metadata.areAllFieldsLocked()) {
|
||||
log.warn("Attempted to update metadata for book with ID {}, but all fields are locked. No update performed.", bookId);
|
||||
log.warn("Attempted to update metadata for book with ID {}, but all fields are locked. No update performed.", bookEntity.getId());
|
||||
return metadata;
|
||||
}
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean writeToFile = settings.isSaveToOriginalFile();
|
||||
boolean backupEnabled = settings.isBackupMetadata();
|
||||
boolean backupCover = settings.isBackupCover();
|
||||
|
||||
if (writeToFile && backupEnabled) {
|
||||
try {
|
||||
metadataBackupRestoreService.backupEmbeddedMetadataIfNotExists(bookEntity, backupCover);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to backup metadata for book ID {}: {}", bookEntity.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
updateBasicFields(newMetadata, metadata);
|
||||
updateAuthorsIfNeeded(newMetadata, metadata);
|
||||
updateCategoriesIfNeeded(newMetadata, metadata, mergeCategories);
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, setThumbnail);
|
||||
updateThumbnailIfNeeded(bookEntity.getId(), newMetadata, metadata, setThumbnail);
|
||||
|
||||
bookMetadataRepository.save(metadata);
|
||||
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookRepository.save(bookEntity);
|
||||
try {
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookRepository.save(bookEntity);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to calculate/save metadata match score for book ID {}: {}", bookEntity.getId(), e.getMessage());
|
||||
}
|
||||
|
||||
if (writeToFile) {
|
||||
try {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
epubMetadataWriter.writeMetadataToFile(bookFile, metadata);
|
||||
log.info("Embedded metadata written to EPUB for book ID {}", bookEntity.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to write metadata to EPUB for book ID {}: {}", bookEntity.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
@@ -88,10 +125,10 @@ public class BookMetadataUpdater {
|
||||
private void updateAuthorsIfNeeded(BookMetadata newMetadata, BookMetadataEntity metadata) {
|
||||
if (shouldUpdateField(metadata.getAuthorsLocked(), newMetadata.getAuthors()) && newMetadata.getAuthors() != null && !newMetadata.getAuthors().isEmpty()) {
|
||||
metadata.setAuthors(newMetadata.getAuthors().stream()
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,19 +137,19 @@ public class BookMetadataUpdater {
|
||||
if (mergeCategories) {
|
||||
HashSet<CategoryEntity> existingCategories = new HashSet<>(metadata.getCategories());
|
||||
newMetadata.getCategories().stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.forEach(categoryName -> {
|
||||
CategoryEntity categoryEntity = categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build()));
|
||||
existingCategories.add(categoryEntity);
|
||||
});
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.forEach(categoryName -> {
|
||||
CategoryEntity categoryEntity = categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build()));
|
||||
existingCategories.add(categoryEntity);
|
||||
});
|
||||
metadata.setCategories(new HashSet<>(existingCategories));
|
||||
} else if (!newMetadata.getCategories().isEmpty()) {
|
||||
metadata.setCategories(newMetadata.getCategories().stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,31 +183,31 @@ public class BookMetadataUpdater {
|
||||
|
||||
private void updateLocks(BookMetadata newMetadata, BookMetadataEntity metadata) {
|
||||
List<Pair<Boolean, Consumer<Boolean>>> lockMappings = List.of(
|
||||
Pair.of(newMetadata.getTitleLocked(), metadata::setTitleLocked),
|
||||
Pair.of(newMetadata.getSubtitleLocked(), metadata::setSubtitleLocked),
|
||||
Pair.of(newMetadata.getPublisherLocked(), metadata::setPublisherLocked),
|
||||
Pair.of(newMetadata.getPublishedDateLocked(), metadata::setPublishedDateLocked),
|
||||
Pair.of(newMetadata.getDescriptionLocked(), metadata::setDescriptionLocked),
|
||||
Pair.of(newMetadata.getIsbn13Locked(), metadata::setIsbn13Locked),
|
||||
Pair.of(newMetadata.getIsbn10Locked(), metadata::setIsbn10Locked),
|
||||
Pair.of(newMetadata.getAsinLocked(), metadata::setAsinLocked),
|
||||
Pair.of(newMetadata.getGoodreadsIdLocked(), metadata::setGoodreadsIdLocked),
|
||||
Pair.of(newMetadata.getHardcoverIdLocked(), metadata::setHardcoverIdLocked),
|
||||
Pair.of(newMetadata.getGoogleIdLocked(), metadata::setGoogleIdLocked),
|
||||
Pair.of(newMetadata.getPageCountLocked(), metadata::setPageCountLocked),
|
||||
Pair.of(newMetadata.getLanguageLocked(), metadata::setLanguageLocked),
|
||||
Pair.of(newMetadata.getAmazonRatingLocked(), metadata::setAmazonRatingLocked),
|
||||
Pair.of(newMetadata.getAmazonReviewCountLocked(), metadata::setAmazonReviewCountLocked),
|
||||
Pair.of(newMetadata.getGoodreadsRatingLocked(), metadata::setGoodreadsRatingLocked),
|
||||
Pair.of(newMetadata.getGoodreadsReviewCountLocked(), metadata::setGoodreadsReviewCountLocked),
|
||||
Pair.of(newMetadata.getHardcoverRatingLocked(), metadata::setHardcoverRatingLocked),
|
||||
Pair.of(newMetadata.getHardcoverReviewCountLocked(), metadata::setHardcoverReviewCountLocked),
|
||||
Pair.of(newMetadata.getSeriesNameLocked(), metadata::setSeriesNameLocked),
|
||||
Pair.of(newMetadata.getSeriesNumberLocked(), metadata::setSeriesNumberLocked),
|
||||
Pair.of(newMetadata.getSeriesTotalLocked(), metadata::setSeriesTotalLocked),
|
||||
Pair.of(newMetadata.getAuthorsLocked(), metadata::setAuthorsLocked),
|
||||
Pair.of(newMetadata.getCategoriesLocked(), metadata::setCategoriesLocked),
|
||||
Pair.of(newMetadata.getCoverLocked(), metadata::setCoverLocked)
|
||||
Pair.of(newMetadata.getTitleLocked(), metadata::setTitleLocked),
|
||||
Pair.of(newMetadata.getSubtitleLocked(), metadata::setSubtitleLocked),
|
||||
Pair.of(newMetadata.getPublisherLocked(), metadata::setPublisherLocked),
|
||||
Pair.of(newMetadata.getPublishedDateLocked(), metadata::setPublishedDateLocked),
|
||||
Pair.of(newMetadata.getDescriptionLocked(), metadata::setDescriptionLocked),
|
||||
Pair.of(newMetadata.getIsbn13Locked(), metadata::setIsbn13Locked),
|
||||
Pair.of(newMetadata.getIsbn10Locked(), metadata::setIsbn10Locked),
|
||||
Pair.of(newMetadata.getAsinLocked(), metadata::setAsinLocked),
|
||||
Pair.of(newMetadata.getGoodreadsIdLocked(), metadata::setGoodreadsIdLocked),
|
||||
Pair.of(newMetadata.getHardcoverIdLocked(), metadata::setHardcoverIdLocked),
|
||||
Pair.of(newMetadata.getGoogleIdLocked(), metadata::setGoogleIdLocked),
|
||||
Pair.of(newMetadata.getPageCountLocked(), metadata::setPageCountLocked),
|
||||
Pair.of(newMetadata.getLanguageLocked(), metadata::setLanguageLocked),
|
||||
Pair.of(newMetadata.getAmazonRatingLocked(), metadata::setAmazonRatingLocked),
|
||||
Pair.of(newMetadata.getAmazonReviewCountLocked(), metadata::setAmazonReviewCountLocked),
|
||||
Pair.of(newMetadata.getGoodreadsRatingLocked(), metadata::setGoodreadsRatingLocked),
|
||||
Pair.of(newMetadata.getGoodreadsReviewCountLocked(), metadata::setGoodreadsReviewCountLocked),
|
||||
Pair.of(newMetadata.getHardcoverRatingLocked(), metadata::setHardcoverRatingLocked),
|
||||
Pair.of(newMetadata.getHardcoverReviewCountLocked(), metadata::setHardcoverReviewCountLocked),
|
||||
Pair.of(newMetadata.getSeriesNameLocked(), metadata::setSeriesNameLocked),
|
||||
Pair.of(newMetadata.getSeriesNumberLocked(), metadata::setSeriesNumberLocked),
|
||||
Pair.of(newMetadata.getSeriesTotalLocked(), metadata::setSeriesTotalLocked),
|
||||
Pair.of(newMetadata.getAuthorsLocked(), metadata::setAuthorsLocked),
|
||||
Pair.of(newMetadata.getCategoriesLocked(), metadata::setCategoriesLocked),
|
||||
Pair.of(newMetadata.getCoverLocked(), metadata::setCoverLocked)
|
||||
);
|
||||
lockMappings.forEach(pair -> applyLock(pair.getLeft(), pair.getRight()));
|
||||
}
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.FileHeader;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
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 java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EpubMetadataReader {
|
||||
|
||||
public EpubMetadata readMetadata(File epubFile) {
|
||||
try (ZipFile zip = new ZipFile(epubFile)) {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
|
||||
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
|
||||
if (containerHdr == null) return null;
|
||||
|
||||
try (InputStream cis = zip.getInputStream(containerHdr)) {
|
||||
Document containerDoc = builder.parse(cis);
|
||||
NodeList roots = containerDoc.getElementsByTagName("rootfile");
|
||||
if (roots.getLength() == 0) return null;
|
||||
|
||||
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
|
||||
if (StringUtils.isBlank(opfPath)) return null;
|
||||
|
||||
FileHeader opfHdr = zip.getFileHeader(opfPath);
|
||||
if (opfHdr == null) return null;
|
||||
|
||||
try (InputStream in = zip.getInputStream(opfHdr)) {
|
||||
Document doc = builder.parse(in);
|
||||
Element metadata = (Element) doc.getElementsByTagNameNS("*", "metadata").item(0);
|
||||
if (metadata == null) return null;
|
||||
|
||||
EpubMetadata.EpubMetadataBuilder builderMeta = EpubMetadata.builder();
|
||||
Set<String> authors = new HashSet<>();
|
||||
Set<String> categories = new HashSet<>();
|
||||
|
||||
boolean seriesFound = false;
|
||||
boolean seriesIndexFound = false;
|
||||
|
||||
NodeList children = metadata.getChildNodes();
|
||||
for (int i = 0; i < children.getLength(); i++) {
|
||||
if (!(children.item(i) instanceof Element el)) continue;
|
||||
|
||||
String tag = el.getLocalName();
|
||||
String text = el.getTextContent().trim();
|
||||
|
||||
switch (tag) {
|
||||
case "title" -> builderMeta.title(text);
|
||||
case "description" -> builderMeta.description(text);
|
||||
case "publisher" -> builderMeta.publisher(text);
|
||||
case "language" -> builderMeta.language(text);
|
||||
case "creator" -> authors.add(text);
|
||||
case "subject" -> categories.add(text);
|
||||
case "identifier" -> {
|
||||
String value = text.toLowerCase().startsWith("isbn:") ? text.substring(5) : text;
|
||||
if (value.length() == 13) builderMeta.isbn13(value);
|
||||
else if (value.length() == 10) builderMeta.isbn10(value);
|
||||
}
|
||||
case "date" -> {
|
||||
try {
|
||||
builderMeta.publishedDate(LocalDate.parse(text));
|
||||
} catch (Exception e) {
|
||||
log.warn("Invalid date format in OPF: {}", text);
|
||||
}
|
||||
}
|
||||
case "meta" -> {
|
||||
String name = el.getAttribute("name").trim().toLowerCase();
|
||||
String prop = el.getAttribute("property").trim().toLowerCase();
|
||||
String content = el.hasAttribute("content") ? el.getAttribute("content").trim() : text;
|
||||
if (StringUtils.isBlank(content)) continue;
|
||||
|
||||
if (!seriesFound && (prop.equals("booklore:series") || name.equals("calibre:series") || prop.equals("calibre:series") || prop.equals("belongs-to-collection"))) {
|
||||
builderMeta.seriesName(content);
|
||||
seriesFound = true;
|
||||
}
|
||||
|
||||
if (!seriesIndexFound && (prop.equals("booklore:series_index") || name.equals("calibre:series_index") || prop.equals("calibre:series_index") || prop.equals("group-position"))) {
|
||||
try {
|
||||
builderMeta.seriesNumber(Float.parseFloat(content));
|
||||
seriesIndexFound = true;
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
|
||||
if (name.equals("calibre:pages") || name.equals("pagecount") ||
|
||||
prop.equals("schema:pagecount") || prop.equals("media:pagecount") ||
|
||||
prop.equals("booklore:page_count")) {
|
||||
try {
|
||||
builderMeta.pageCount(Integer.parseInt(content));
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
|
||||
switch (prop) {
|
||||
case "booklore:asin" -> builderMeta.asin(content);
|
||||
case "booklore:amazon_rating" -> safeParseDouble(content, builderMeta::amazonRating);
|
||||
case "booklore:amazon_rating_count" -> safeParseInt(content, builderMeta::amazonReviewCount);
|
||||
case "booklore:goodreads_id" -> builderMeta.goodreadsId(content);
|
||||
case "booklore:goodreads_rating" -> safeParseDouble(content, builderMeta::goodreadsRating);
|
||||
case "booklore:goodreads_rating_count" -> safeParseInt(content, builderMeta::goodreadsReviewCount);
|
||||
case "booklore:hardcover_id" -> builderMeta.hardcoverId(content);
|
||||
case "booklore:hardcover_rating" -> safeParseDouble(content, builderMeta::hardcoverRating);
|
||||
case "booklore:hardcover_rating_count" -> safeParseInt(content, builderMeta::hardcoverReviewCount);
|
||||
case "booklore:google_books_id" -> builderMeta.googleId(content);
|
||||
case "booklore:page_count" -> safeParseInt(content, builderMeta::pageCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
builderMeta.authors(authors);
|
||||
builderMeta.categories(categories);
|
||||
return builderMeta.build();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to read metadata from EPUB file {}: {}", epubFile.getName(), e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void safeParseInt(String value, java.util.function.IntConsumer setter) {
|
||||
try {
|
||||
setter.accept(Integer.parseInt(value));
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
|
||||
private void safeParseDouble(String value, java.util.function.DoubleConsumer setter) {
|
||||
try {
|
||||
setter.accept(Double.parseDouble(value));
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import io.documentnode.epub4j.domain.*;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.xml.namespace.QName;
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.Date;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EpubMetadataWriter {
|
||||
|
||||
private static final String OPF_NS = "http://www.idpf.org/2007/opf";
|
||||
|
||||
@Transactional
|
||||
public void writeMetadataToFile(File epubFile, BookMetadataEntity metadata) {
|
||||
try {
|
||||
Book book = new EpubReader().readEpub(new FileInputStream(epubFile));
|
||||
Metadata meta = book.getMetadata();
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getTitle())) {
|
||||
meta.getTitles().clear();
|
||||
meta.addTitle(metadata.getTitle());
|
||||
}
|
||||
|
||||
Set<AuthorEntity> authors = metadata.getAuthors();
|
||||
if (authors != null && !authors.isEmpty()) {
|
||||
meta.getAuthors().clear();
|
||||
for (AuthorEntity author : authors) {
|
||||
String[] parts = author.getName().trim().split(" ", 2);
|
||||
String firstName = parts.length > 1 ? parts[0] : "";
|
||||
String lastName = parts.length > 1 ? parts[1] : parts[0];
|
||||
meta.addAuthor(new Author(firstName, lastName));
|
||||
}
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getDescription())) {
|
||||
meta.getDescriptions().clear();
|
||||
meta.addDescription(metadata.getDescription());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getPublisher())) {
|
||||
meta.getPublishers().clear();
|
||||
meta.addPublisher(metadata.getPublisher());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getLanguage())) {
|
||||
meta.setLanguage(metadata.getLanguage());
|
||||
}
|
||||
|
||||
if (metadata.getPublishedDate() != null) {
|
||||
meta.getDates().clear();
|
||||
meta.addDate(new io.documentnode.epub4j.domain.Date(metadata.getPublishedDate().toString()));
|
||||
}
|
||||
|
||||
meta.getIdentifiers().removeIf(id -> {
|
||||
String scheme = Optional.ofNullable(id.getScheme()).orElse("").toUpperCase();
|
||||
return scheme.equals("ISBN") || scheme.equals("ASIN");
|
||||
});
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getIsbn13())) {
|
||||
meta.addIdentifier(new Identifier(Identifier.Scheme.ISBN, metadata.getIsbn13()));
|
||||
} else if (StringUtils.isNotBlank(metadata.getIsbn10())) {
|
||||
meta.addIdentifier(new Identifier(Identifier.Scheme.ISBN, metadata.getIsbn10()));
|
||||
} else if (StringUtils.isNotBlank(metadata.getAsin())) {
|
||||
meta.addIdentifier(new Identifier("ASIN", metadata.getAsin()));
|
||||
}
|
||||
|
||||
var categories = metadata.getCategories();
|
||||
if (categories != null && !categories.isEmpty()) {
|
||||
meta.getSubjects().clear();
|
||||
meta.getSubjects().addAll(categories.stream().map(CategoryEntity::getName).distinct().toList());
|
||||
}
|
||||
|
||||
Map<QName, String> otherProps = new HashMap<>();
|
||||
|
||||
putIfValid(otherProps, "calibre:series", metadata.getSeriesName());
|
||||
putIfValid(otherProps, "calibre:series_index", toStringSafe(metadata.getSeriesNumber()));
|
||||
putIfValid(otherProps, "booklore:series", metadata.getSeriesName());
|
||||
putIfValid(otherProps, "booklore:series_index", toStringSafe(metadata.getSeriesNumber()));
|
||||
putIfValid(otherProps, "booklore:asin", metadata.getAsin());
|
||||
putIfValid(otherProps, "booklore:amazon_rating", toStringSafe(metadata.getAmazonRating()));
|
||||
putIfValid(otherProps, "booklore:amazon_rating_count", toStringSafe(metadata.getAmazonReviewCount()));
|
||||
putIfValid(otherProps, "booklore:goodreads_id", metadata.getGoodreadsId());
|
||||
putIfValid(otherProps, "booklore:goodreads_rating", toStringSafe(metadata.getGoodreadsRating()));
|
||||
putIfValid(otherProps, "booklore:goodreads_rating_count", toStringSafe(metadata.getGoodreadsReviewCount()));
|
||||
putIfValid(otherProps, "booklore:hardcover_id", metadata.getHardcoverId());
|
||||
putIfValid(otherProps, "booklore:hardcover_rating", toStringSafe(metadata.getHardcoverRating()));
|
||||
putIfValid(otherProps, "booklore:hardcover_rating_count", toStringSafe(metadata.getHardcoverReviewCount()));
|
||||
putIfValid(otherProps, "booklore:google_books_id", metadata.getGoogleId());
|
||||
putIfValid(otherProps, "booklore:page_count", toStringSafe(metadata.getPageCount()));
|
||||
|
||||
meta.setOtherProperties(otherProps);
|
||||
|
||||
if (StringUtils.isNotBlank(metadata.getThumbnail())) {
|
||||
File coverFile = new File(metadata.getThumbnail());
|
||||
if (coverFile.exists()) {
|
||||
try (FileInputStream coverStream = new FileInputStream(coverFile)) {
|
||||
byte[] coverData = coverStream.readAllBytes();
|
||||
String coverId = "cover-image";
|
||||
|
||||
Resource cover = new Resource(coverData, "images/cover.jpg");
|
||||
cover.setId(coverId);
|
||||
|
||||
book.getResources().remove("images/cover.jpg");
|
||||
book.getResources().add(cover);
|
||||
book.setCoverImage(cover);
|
||||
|
||||
log.info("Cover image replaced for EPUB: {}", coverFile.getName());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to read new cover image: {}", e.getMessage());
|
||||
}
|
||||
} else {
|
||||
log.warn("Cover path set but file not found: {}", metadata.getThumbnail());
|
||||
}
|
||||
}
|
||||
|
||||
File tempFile = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp");
|
||||
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
|
||||
new EpubWriter().write(book, fos);
|
||||
}
|
||||
|
||||
if (!epubFile.delete()) {
|
||||
throw new IOException("Could not delete original EPUB file");
|
||||
}
|
||||
if (!tempFile.renameTo(epubFile)) {
|
||||
throw new IOException("Could not rename temp EPUB file");
|
||||
}
|
||||
|
||||
log.info("Successfully wrote embedded metadata to EPUB: {}", epubFile.getName());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to write metadata to EPUB file {}: {}", epubFile.getName(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfValid(Map<QName, String> map, String localName, String value) {
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
map.put(new QName(OPF_NS, localName), value);
|
||||
}
|
||||
}
|
||||
|
||||
private String toStringSafe(Object obj) {
|
||||
if (obj == null) return null;
|
||||
String str = String.valueOf(obj);
|
||||
return StringUtils.isNotBlank(str) && !"null".equalsIgnoreCase(str) ? str : null;
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.EpubMetadata;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import io.documentnode.epub4j.epub.EpubWriter;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.time.Instant;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class MetadataBackupRestoreService {
|
||||
|
||||
private final FileService fileService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final BookRepository bookRepository;
|
||||
private final EpubMetadataReader epubMetadataReader;
|
||||
private final BookMetadataRestorer bookMetadataRestorer;
|
||||
|
||||
public void backupEmbeddedMetadataIfNotExists(BookEntity bookEntity, boolean backupCover) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
Path backupDir = resolveBackupDir(bookEntity);
|
||||
Path metadataFile = backupDir.resolve("metadata.json");
|
||||
Path coverFile = backupDir.resolve("cover.jpg");
|
||||
Path filenameCheckFile = backupDir.resolve("original-filename.txt");
|
||||
|
||||
try {
|
||||
if (Files.exists(metadataFile)) {
|
||||
log.info("Backup already exists for book ID {}", bookEntity.getId());
|
||||
return;
|
||||
}
|
||||
|
||||
Files.createDirectories(backupDir);
|
||||
|
||||
EpubMetadata metadata = epubMetadataReader.readMetadata(bookFile);
|
||||
String json = objectMapper.writer().writeValueAsString(metadata);
|
||||
Files.writeString(metadataFile, json, StandardOpenOption.CREATE_NEW);
|
||||
|
||||
Files.writeString(filenameCheckFile, bookEntity.getFileName(), StandardOpenOption.CREATE_NEW);
|
||||
|
||||
if (backupCover) {
|
||||
try (FileInputStream fis = new FileInputStream(bookFile)) {
|
||||
Book epubBook = new EpubReader().readEpub(fis);
|
||||
Resource coverImage = epubBook.getCoverImage();
|
||||
if (coverImage != null) {
|
||||
Files.write(coverFile, coverImage.getData(), StandardOpenOption.CREATE_NEW);
|
||||
log.info("Backup cover image saved for book ID {} at {}", bookEntity.getId(), coverFile);
|
||||
} else {
|
||||
log.warn("No cover image found in EPUB for book ID {}", bookEntity.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Created backup of embedded metadata for book ID {} at {}", bookEntity.getId(), backupDir);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to create metadata backup for book ID {}", bookEntity.getId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void restoreEmbeddedMetadata(BookEntity bookEntity) throws IOException {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
Path backupDir = resolveBackupDir(bookEntity);
|
||||
Path metadataFile = backupDir.resolve("metadata.json");
|
||||
Path coverFile = backupDir.resolve("cover.jpg");
|
||||
Path filenameCheckFile = backupDir.resolve("original-filename.txt");
|
||||
|
||||
if (Files.notExists(metadataFile)) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Metadata backup file not found.");
|
||||
}
|
||||
|
||||
if (Files.notExists(filenameCheckFile)) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Filename check file is missing.");
|
||||
}
|
||||
|
||||
String backedUpFilename = Files.readString(filenameCheckFile).trim();
|
||||
String currentFilename = bookEntity.getFileName().trim();
|
||||
|
||||
if (!currentFilename.equals(backedUpFilename)) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("The backup is for a different file.");
|
||||
}
|
||||
|
||||
EpubMetadata backupMetadata = readEpubMetadata(metadataFile, bookEntity.getId());
|
||||
bookMetadataRestorer.restoreMetadata(bookEntity, backupMetadata);
|
||||
|
||||
if (Files.exists(coverFile)) {
|
||||
try {
|
||||
byte[] coverData = Files.readAllBytes(coverFile);
|
||||
Resource cover = new Resource(coverData, "images/cover.jpg");
|
||||
cover.setId("cover-image");
|
||||
|
||||
Book epubBook = new EpubReader().readEpub(new FileInputStream(bookFile));
|
||||
epubBook.getResources().remove("images/cover.jpg");
|
||||
epubBook.getResources().add(cover);
|
||||
epubBook.setCoverImage(cover);
|
||||
|
||||
File tempFile = new File(bookFile.getParentFile(), bookFile.getName() + ".tmp");
|
||||
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
|
||||
new EpubWriter().write(epubBook, fos);
|
||||
}
|
||||
|
||||
if (!bookFile.delete()) {
|
||||
throw new IOException("Could not delete original EPUB file during restore.");
|
||||
}
|
||||
if (!tempFile.renameTo(bookFile)) {
|
||||
throw new IOException("Could not rename temp EPUB file during restore.");
|
||||
}
|
||||
|
||||
log.info("Restored cover image from backup for book ID {}", bookEntity.getId());
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to restore cover image for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
updateThumbnailIfNeeded(bookEntity.getId(), coverFile, bookEntity.getMetadata());
|
||||
|
||||
log.info("Successfully restored embedded metadata for book ID {}", bookEntity.getId());
|
||||
}
|
||||
|
||||
private void updateThumbnailIfNeeded(long bookId, Path coverPath, BookMetadataEntity metadata) {
|
||||
String thumbnailPath = null;
|
||||
try {
|
||||
thumbnailPath = fileService.createThumbnail(bookId, coverPath.toString());
|
||||
metadata.setCoverUpdatedOn(Instant.now());
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
metadata.setThumbnail(thumbnailPath);
|
||||
}
|
||||
|
||||
public EpubMetadata getBackedUpMetadata(Long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
Path metadataFile = resolveBackupDir(bookEntity).resolve("metadata.json");
|
||||
|
||||
if (Files.notExists(metadataFile)) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Metadata backup file not found.");
|
||||
}
|
||||
|
||||
try {
|
||||
ObjectReader reader = objectMapper.readerFor(EpubMetadata.class);
|
||||
return reader.readValue(metadataFile.toFile());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to read metadata backup for book ID {}: {}", bookId, e.getMessage(), e);
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to read metadata backup file.");
|
||||
}
|
||||
}
|
||||
|
||||
private EpubMetadata readEpubMetadata(Path metadataFile, Long bookId) {
|
||||
try {
|
||||
ObjectReader reader = objectMapper.readerFor(EpubMetadata.class);
|
||||
return reader.readValue(metadataFile.toFile());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to read metadata backup for book ID {}: {}", bookId, e.getMessage(), e);
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to read metadata backup file.");
|
||||
}
|
||||
}
|
||||
|
||||
private Path resolveBackupDir(BookEntity bookEntity) {
|
||||
return Path.of(fileService.getMetadataBackupPath(), String.valueOf(bookEntity.getId()));
|
||||
}
|
||||
|
||||
public org.springframework.core.io.Resource getBackupCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
Path coverPath = resolveBackupDir(bookEntity).resolve("cover.jpg");
|
||||
|
||||
if (Files.notExists(coverPath)) {
|
||||
log.warn("No cover image found in backup for book ID {} at {}", bookId, coverPath);
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Backup cover image not found.");
|
||||
}
|
||||
|
||||
return new FileSystemResource(coverPath);
|
||||
}
|
||||
}
|
||||
+10
-3
@@ -450,11 +450,18 @@ public class AmazonBookParser implements BookParser {
|
||||
|
||||
private String getThumbnail(Document doc) {
|
||||
try {
|
||||
Element imageElement = doc.select("#landingImage").first();
|
||||
Element imageElement = doc.selectFirst("#landingImage");
|
||||
if (imageElement != null) {
|
||||
return imageElement.attr("src");
|
||||
String highRes = imageElement.attr("data-old-hires");
|
||||
if (!highRes.isBlank()) {
|
||||
return highRes;
|
||||
}
|
||||
String fallback = imageElement.attr("src");
|
||||
if (!fallback.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
log.warn("Failed to parse thumbnail: Image element not found.");
|
||||
log.warn("Failed to parse thumbnail: No suitable image URL found.");
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to parse thumbnail: {}", e.getMessage());
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -14,6 +14,7 @@ import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
@@ -26,6 +27,7 @@ import java.nio.file.Paths;
|
||||
public class FileService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void createThumbnailFromFile(long bookId, MultipartFile file) {
|
||||
try {
|
||||
@@ -82,19 +84,45 @@ public class FileService {
|
||||
}
|
||||
}
|
||||
|
||||
public Resource getBackupBookCover(String thumbnailPath) {
|
||||
Path thumbPath;
|
||||
if (thumbnailPath == null || thumbnailPath.isEmpty()) {
|
||||
thumbPath = Paths.get(getMissingThumbnailPath());
|
||||
} else {
|
||||
thumbPath = Paths.get(thumbnailPath);
|
||||
}
|
||||
try {
|
||||
Resource resource = new UrlResource(thumbPath.toUri());
|
||||
if (resource.exists() && resource.isReadable()) {
|
||||
return resource;
|
||||
} else {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException(thumbPath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw ApiError.IMAGE_NOT_FOUND.createException(thumbPath);
|
||||
}
|
||||
}
|
||||
|
||||
public String createThumbnail(long bookId, String thumbnailUrl) throws IOException {
|
||||
String newFilename = "f.jpg";
|
||||
resizeAndSaveImage(thumbnailUrl, new File(getThumbnailPath(bookId)), newFilename);
|
||||
return getThumbnailPath(bookId) + newFilename;
|
||||
}
|
||||
|
||||
private void resizeAndSaveImage(String imageUrl, File outputFolder, String outputFileName) throws IOException {
|
||||
private void resizeAndSaveImage(String imageSource, File outputFolder, String outputFileName) throws IOException {
|
||||
BufferedImage originalImage;
|
||||
try (InputStream inputStream = new URL(imageUrl).openStream()) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
File file = new File(imageSource);
|
||||
if (file.exists()) {
|
||||
try (InputStream inputStream = new FileInputStream(file)) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
} else {
|
||||
try (InputStream inputStream = new URL(imageSource).openStream()) {
|
||||
originalImage = ImageIO.read(inputStream);
|
||||
}
|
||||
}
|
||||
if (originalImage == null) {
|
||||
throw new IOException("Failed to read image from URL: " + imageUrl);
|
||||
throw new IOException("Failed to read image from: " + imageSource);
|
||||
}
|
||||
BufferedImage resizedImage = resizeImage(originalImage);
|
||||
if (!outputFolder.exists() && !outputFolder.mkdirs()) {
|
||||
@@ -106,10 +134,15 @@ public class FileService {
|
||||
}
|
||||
|
||||
private BufferedImage resizeImage(BufferedImage originalImage) {
|
||||
BufferedImage resizedImage = new BufferedImage(250, 350, BufferedImage.TYPE_INT_RGB);
|
||||
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
BufferedImage resizedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
g2d.drawImage(originalImage, 0, 0, 250, 350, null);
|
||||
g2d.drawImage(originalImage, 0, 0, x, y, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
@@ -118,6 +151,14 @@ public class FileService {
|
||||
return appProperties.getPathConfig() + "/thumbs/" + bookId + "/";
|
||||
}
|
||||
|
||||
public String getMetadataBackupPath() {
|
||||
return appProperties.getPathConfig() + "/metadata_backup/";
|
||||
}
|
||||
|
||||
public String getBookMetadataBackupPath(long bookId) {
|
||||
return appProperties.getPathConfig() + "/metadata_backup/" + bookId + "/";
|
||||
}
|
||||
|
||||
public String getCbxCachePath() {
|
||||
return appProperties.getPathConfig() + "/cbx_cache";
|
||||
}
|
||||
@@ -129,5 +170,4 @@ public class FileService {
|
||||
public String getMissingThumbnailPath() {
|
||||
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user