Improve robustness of book uploader error handling (#2130)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-03 16:47:59 -07:00
committed by GitHub
co-authored by acx10
parent d3a0e9ddc9
commit 3b3656c29b
10 changed files with 549 additions and 72 deletions
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.crons;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.dto.BookloreTelemetry;
import com.adityachandel.booklore.model.dto.InstallationPing;
import com.adityachandel.booklore.model.dto.settings.AppSettings;
import com.adityachandel.booklore.service.TelemetryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import jakarta.annotation.PostConstruct;
@@ -23,6 +24,7 @@ public class CronService {
private static final String LAST_TELEMETRY_KEY = "last_telemetry_sent";
private static final String LAST_PING_KEY = "last_ping_sent";
private static final String LAST_PING_APP_VERSION_KEY = "last_ping_app_version";
private static final long INTERVAL_HOURS = 24;
private final AppProperties appProperties;
@@ -38,44 +40,45 @@ public class CronService {
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 24)
public void sendTelemetryData() {
if (appSettingService.getAppSettings().isTelemetryEnabled()) {
try {
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/ingest";
BookloreTelemetry telemetry = telemetryService.collectTelemetry();
postData(url, telemetry);
AppSettings settings = appSettingService.getAppSettings();
if (settings != null && settings.isTelemetryEnabled()) {
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/ingest";
BookloreTelemetry telemetry = telemetryService.collectTelemetry();
if (postData(url, telemetry)) {
appSettingService.saveSetting(LAST_TELEMETRY_KEY, Instant.now().toString());
} catch (Exception e) {
log.warn("Failed to up stats: {}", e.getMessage());
}
}
}
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 10)
@Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 12)
public void sendPing() {
try {
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/heartbeat";
InstallationPing ping = telemetryService.getInstallationPing();
postData(url, ping);
String url = appProperties.getTelemetry().getBaseUrl() + "/api/v1/heartbeat";
InstallationPing ping = telemetryService.getInstallationPing();
if (ping != null && postData(url, ping)) {
appSettingService.saveSetting(LAST_PING_KEY, Instant.now().toString());
} catch (Exception e) {
log.warn("Failed to up ping: {}", e.getMessage());
appSettingService.saveSetting(LAST_PING_APP_VERSION_KEY, ping.getAppVersion());
}
}
private void postData(String url, Object body) {
restClient.post()
.uri(url)
.body(body)
.retrieve()
.body(String.class);
protected boolean postData(String url, Object body) {
try {
restClient.post()
.uri(url)
.body(body)
.retrieve()
.body(String.class);
return true;
} catch (Exception ex) {
log.debug("POST request to URL: {}, Message: {}", url, ex.getMessage());
return false;
}
}
private void checkAndRunTelemetry() {
if (!appSettingService.getAppSettings().isTelemetryEnabled()) {
AppSettings settings = appSettingService.getAppSettings();
if (settings == null || !settings.isTelemetryEnabled()) {
return;
}
String lastRunStr = appSettingService.getSettingValue(LAST_TELEMETRY_KEY);
if (shouldRunTask(lastRunStr)) {
log.info("Running stats on startup (last run: {})", lastRunStr);
@@ -85,6 +88,11 @@ public class CronService {
private void checkAndRunPing() {
String lastRunStr = appSettingService.getSettingValue(LAST_PING_KEY);
if (hasAppVersionChanged()) {
log.info("App version changed, sending immediate ping");
sendPing();
return;
}
if (shouldRunTask(lastRunStr)) {
log.info("Running ping on startup (last run: {})", lastRunStr);
sendPing();
@@ -96,7 +104,7 @@ public class CronService {
* Returns false for new installations (no last run recorded) to follow normal schedule.
* Returns true if more than INTERVAL_HOURS have passed since the last run,
* preventing data gaps when the server restarts close to scheduled execution time.
*
* <p>
* Example: Telemetry normally runs at 2:00 AM daily. If the server restarts at 1:55 AM,
* the scheduled task would reset and not run until 2:00 AM the next day (48 hours later).
* This method checks if 24+ hours have passed since the last run and executes immediately
@@ -115,4 +123,18 @@ public class CronService {
return false;
}
}
/**
* Checks if the app version has changed since the last ping.
* Returns true if this is an established installation with a version change.
*/
private boolean hasAppVersionChanged() {
String lastPingVersion = appSettingService.getSettingValue(LAST_PING_APP_VERSION_KEY);
InstallationPing ping = telemetryService.getInstallationPing();
String currentVersion = ping != null ? ping.getAppVersion() : null;
if (lastPingVersion == null || lastPingVersion.isEmpty() || currentVersion == null) {
return false;
}
return !lastPingVersion.equals(currentVersion);
}
}
@@ -339,6 +339,8 @@ public class BookService {
} catch (IOException e) {
log.warn("Failed to delete book file: {}", fullFilePath, e);
failedFileDeletions.add(book.getId());
} finally {
monitoringRegistrationService.registerSpecificPath(fullFilePath.getParent(), book.getLibrary().getId());
}
}
@@ -51,12 +51,11 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
@Override
public BookMetadata extractMetadata(File file) {
String baseName = FilenameUtils.getBaseName(file.getName());
String processedBaseName = processFilename(baseName);
String lowerName = file.getName().toLowerCase();
// Non-archive (fallback)
if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
// CBZ path (ZIP)
@@ -64,15 +63,15 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
try (ZipFile zipFile = new ZipFile(file)) {
ZipEntry entry = findComicInfoEntry(zipFile);
if (entry == null) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
try (InputStream is = zipFile.getInputStream(entry)) {
Document document = buildSecureDocument(is);
return mapDocumentToMetadata(document, processedBaseName);
return mapDocumentToMetadata(document, baseName);
}
} catch (Exception e) {
log.warn("Failed to extract metadata from CBZ", e);
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
}
@@ -81,19 +80,19 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) {
SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ);
if (entry == null) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry);
if (xmlBytes == null) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
Document document = buildSecureDocument(is);
return mapDocumentToMetadata(document, processedBaseName);
return mapDocumentToMetadata(document, baseName);
}
} catch (Exception e) {
log.warn("Failed to extract metadata from CB7", e);
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
}
@@ -102,23 +101,23 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
try {
FileHeader header = findComicInfoHeader(archive);
if (header == null) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
byte[] xmlBytes = readRarEntryBytes(archive, header);
if (xmlBytes == null) {
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
Document document = buildSecureDocument(is);
return mapDocumentToMetadata(document, processedBaseName);
return mapDocumentToMetadata(document, baseName);
}
} catch (Exception e) {
log.warn("Failed to extract metadata from CBR", e);
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
} catch (Exception ignore) {
}
return BookMetadata.builder().title(processedBaseName).build();
return BookMetadata.builder().title(baseName).build();
}
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
@@ -808,11 +807,6 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
return null;
}
private String processFilename(String baseName) {
// Replace underscores and hyphens with spaces
return Pattern.compile("[_\\-]").matcher(baseName).replaceAll(" ").trim();
}
private static boolean isComicInfoName(String name) {
if (name == null) return false;
String n = name.replace('\\', '/');
@@ -28,10 +28,21 @@ public class MonitoringRegistrationService {
}
public void unregisterSpecificPath(Path path) {
if (!Files.exists(path)) {
log.debug("Path does not exist, attempting to unregister anyway: {}", path);
}
monitoringService.unregisterPath(path);
}
public void registerSpecificPath(Path path, Long libraryId) {
if (!Files.exists(path)) {
log.warn("Cannot register path that does not exist: {}", path);
return;
}
if (!Files.isDirectory(path)) {
log.warn("Cannot register path that is not a directory: {}", path);
return;
}
monitoringService.registerPath(path, libraryId);
}
@@ -101,6 +101,14 @@ public class MonitoringService {
}
public synchronized boolean registerPath(Path path, Long libraryId) {
if (!Files.exists(path)) {
log.warn("Cannot register path that does not exist: {}", path);
return false;
}
if (!Files.isDirectory(path)) {
log.warn("Cannot register path that is not a directory: {}", path);
return false;
}
try {
if (monitoredPaths.add(path)) {
WatchKey key = path.register(watchService,
@@ -122,6 +130,9 @@ public class MonitoringService {
}
public synchronized void unregisterPath(Path path, boolean logUnregister) {
if (!Files.exists(path)) {
log.debug("Path does not exist, removing from monitoring if present: {}", path);
}
if (monitoredPaths.remove(path)) {
WatchKey key = registeredWatchKeys.remove(path);
if (key != null) key.cancel();