From 3b3656c29bf48bb459bdb6d75233db126251bf27 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sat, 3 Jan 2026 16:47:59 -0700 Subject: [PATCH] Improve robustness of book uploader error handling (#2130) Co-authored-by: acx10 --- .../booklore/crons/CronService.java | 70 ++-- .../booklore/service/book/BookService.java | 2 + .../extractor/CbxMetadataExtractor.java | 32 +- .../MonitoringRegistrationService.java | 11 + .../service/monitoring/MonitoringService.java | 11 + .../booklore/crons/CronServiceTest.java | 374 ++++++++++++++++++ .../extractor/ComicInfoParsingIssuesTest.java | 12 - .../book-uploader.component.html | 34 +- .../book-uploader.component.scss | 16 +- .../book-uploader/book-uploader.component.ts | 59 ++- 10 files changed, 549 insertions(+), 72 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/crons/CronServiceTest.java diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java b/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java index c0071e3f6..234ebdc91 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java @@ -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. - * + *

* 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); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java index 4dde851e9..b0f1562aa 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java @@ -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()); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java index d0e3bb7af..27f2cf2a9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java @@ -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('\\', '/'); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java index 78ca500ea..2b5fa8055 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringRegistrationService.java @@ -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); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java index e415d9562..a383b48eb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/monitoring/MonitoringService.java @@ -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(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/crons/CronServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/crons/CronServiceTest.java new file mode 100644 index 000000000..db3e0f824 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/crons/CronServiceTest.java @@ -0,0 +1,374 @@ +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 org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.client.RestClient; + +import java.time.Instant; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +class CronServiceTest { + + private AppProperties appProperties; + private TelemetryService telemetryService; + private RestClient restClient; + private AppSettingService appSettingService; + private CronService cronService; + + @BeforeEach + void setUp() { + appProperties = mock(AppProperties.class, RETURNS_DEEP_STUBS); + telemetryService = mock(TelemetryService.class); + restClient = mock(RestClient.class, RETURNS_DEEP_STUBS); + appSettingService = mock(AppSettingService.class); + cronService = new CronService(appProperties, telemetryService, restClient, appSettingService); + + AppSettings defaultSettings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(defaultSettings); + when(defaultSettings.isTelemetryEnabled()).thenReturn(true); + + InstallationPing defaultPing = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(defaultPing); + } + + @Test + void sendTelemetryData_telemetryDisabled_doesNotSend() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(false); + cronService.sendTelemetryData(); + verifyNoInteractions(telemetryService); + verify(appSettingService, never()).saveSetting(anyString(), anyString()); + } + + @Test + void sendTelemetryData_telemetryEnabled_postSuccess_savesSetting() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(true); + when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry"); + BookloreTelemetry telemetry = mock(BookloreTelemetry.class); + when(telemetryService.collectTelemetry()).thenReturn(telemetry); + RestClient.RequestBodyUriSpec post = mock(RestClient.RequestBodyUriSpec.class, RETURNS_DEEP_STUBS); + when(restClient.post()).thenReturn(post); + when(post.uri(anyString())).thenReturn(post); + when(post.body(any())).thenReturn(post); + when(post.retrieve().body(String.class)).thenReturn("ok"); + cronService.sendTelemetryData(); + verify(appSettingService).saveSetting(eq("last_telemetry_sent"), anyString()); + } + + @Test + void sendTelemetryData_telemetryEnabled_postFails_doesNotSaveSetting() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(true); + when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry"); + BookloreTelemetry telemetry = mock(BookloreTelemetry.class); + when(telemetryService.collectTelemetry()).thenReturn(telemetry); + + CronService spy = spy(cronService); + doReturn(false).when(spy).postData(anyString(), any()); + + spy.sendTelemetryData(); + verify(appSettingService, never()).saveSetting(eq("last_telemetry_sent"), anyString()); + } + + @Test + void sendPing_postSuccess_savesSettings() { + when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + RestClient.RequestBodyUriSpec post = mock(RestClient.RequestBodyUriSpec.class, RETURNS_DEEP_STUBS); + when(restClient.post()).thenReturn(post); + when(post.uri(anyString())).thenReturn(post); + when(post.body(any())).thenReturn(post); + when(post.retrieve().body(String.class)).thenReturn("ok"); + cronService.sendPing(); + verify(appSettingService).saveSetting(eq("last_ping_sent"), anyString()); + verify(appSettingService).saveSetting(eq("last_ping_app_version"), eq("1.0.0")); + } + + @Test + void sendPing_postFails_doesNotSaveSettings() { + when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + + CronService spy = spy(cronService); + doReturn(false).when(spy).postData(anyString(), any()); + + spy.sendPing(); + verify(appSettingService, never()).saveSetting(eq("last_ping_sent"), anyString()); + verify(appSettingService, never()).saveSetting(eq("last_ping_app_version"), anyString()); + } + + @Test + void shouldRunTask_nullOrEmpty_returnsFalse() { + assertFalse(cronServiceShouldRunTask(null)); + assertFalse(cronServiceShouldRunTask("")); + } + + @Test + void shouldRunTask_invalidTimestamp_returnsFalse() { + assertFalse(cronServiceShouldRunTask("not-a-timestamp")); + } + + @Test + void shouldRunTask_recentTimestamp_returnsFalse() { + String now = Instant.now().toString(); + assertFalse(cronServiceShouldRunTask(now)); + } + + @Test + void shouldRunTask_oldTimestamp_returnsTrue() { + String old = Instant.now().minusSeconds(60 * 60 * 25).toString(); + assertTrue(cronServiceShouldRunTask(old)); + } + + boolean cronServiceShouldRunTask(String lastRunStr) { + return invokeShouldRunTask(cronService, lastRunStr); + } + + boolean invokeShouldRunTask(CronService cronService, String lastRunStr) { + try { + var m = CronService.class.getDeclaredMethod("shouldRunTask", String.class); + m.setAccessible(true); + return (boolean) m.invoke(cronService, lastRunStr); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + void hasAppVersionChanged_noLastPing_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_lastPingEmpty_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(""); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_sameVersion_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_differentVersion_returnsTrue() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("2.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + assertTrue(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_nullPing_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + when(telemetryService.getInstallationPing()).thenReturn(null); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + boolean invokeHasAppVersionChanged(CronService cronService) { + try { + var m = CronService.class.getDeclaredMethod("hasAppVersionChanged"); + m.setAccessible(true); + return (boolean) m.invoke(cronService); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + void checkAndRunTelemetry_telemetryDisabled_doesNothing() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(false); + cronService.initScheduledTasks(); + verify(appSettingService, never()).getSettingValue("last_telemetry_sent"); + } + + @Test + void checkAndRunTelemetry_shouldRunTaskTrue_callsSendTelemetryData() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(true); + when(appSettingService.getSettingValue("last_telemetry_sent")).thenReturn(Instant.now().minusSeconds(60 * 60 * 25).toString()); + CronService spy = spy(cronService); + doNothing().when(spy).sendTelemetryData(); + // Ensure getInstallationPing returns non-null for ping checks + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + spy.initScheduledTasks(); + verify(spy).sendTelemetryData(); + } + + @Test + void checkAndRunPing_appVersionChanged_callsSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("2.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy).sendPing(); + } + + @Test + void checkAndRunPing_shouldRunTaskTrue_callsSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().minusSeconds(60 * 60 * 25).toString()); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy).sendPing(); + } + + @Test + void checkAndRunPing_shouldRunTaskFalse_doesNotCallSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().toString()); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy, never()).sendPing(); + } + + @Test + void sendTelemetryData_nullSettings_doesNotThrowOrSend() { + when(appSettingService.getAppSettings()).thenReturn(null); + cronService.sendTelemetryData(); + verifyNoInteractions(telemetryService); + verify(appSettingService, never()).saveSetting(anyString(), anyString()); + } + + @Test + void sendTelemetryData_telemetryEnabled_collectTelemetryReturnsNull_doesNotThrow() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(true); + when(appProperties.getTelemetry().getBaseUrl()).thenReturn("http://telemetry"); + when(telemetryService.collectTelemetry()).thenReturn(null); + + CronService spy = spy(cronService); + doReturn(false).when(spy).postData(anyString(), any()); + + spy.sendTelemetryData(); + verify(appSettingService, never()).saveSetting(eq("last_telemetry_sent"), anyString()); + } + + @Test + void sendPing_nullPing_doesNotSave() { + when(telemetryService.getInstallationPing()).thenReturn(null); + cronService.sendPing(); + verify(appSettingService, never()).saveSetting(anyString(), anyString()); + } + + @Test + void shouldRunTask_farFutureTimestamp_returnsFalse() { + String future = Instant.now().plusSeconds(60 * 60 * 25).toString(); + assertFalse(cronServiceShouldRunTask(future)); + } + + @Test + void shouldRunTask_epoch_returnsTrue() { + String epoch = Instant.EPOCH.toString(); + assertTrue(cronServiceShouldRunTask(epoch)); + } + + @Test + void hasAppVersionChanged_lastPingNullCurrentNull_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null); + when(telemetryService.getInstallationPing()).thenReturn(null); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_lastPingEmptyCurrentNull_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(""); + when(telemetryService.getInstallationPing()).thenReturn(null); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void hasAppVersionChanged_lastPingNonEmptyCurrentNull_returnsFalse() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + when(telemetryService.getInstallationPing()).thenReturn(null); + assertFalse(invokeHasAppVersionChanged(cronService)); + } + + @Test + void checkAndRunTelemetry_nullSettings_doesNothing() { + when(appSettingService.getAppSettings()).thenReturn(null); + cronService.initScheduledTasks(); + verify(appSettingService, never()).getSettingValue("last_telemetry_sent"); + } + + @Test + void checkAndRunTelemetry_shouldRunTaskFalse_doesNotCallSendTelemetryData() { + AppSettings settings = mock(AppSettings.class); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(settings.isTelemetryEnabled()).thenReturn(true); + when(appSettingService.getSettingValue("last_telemetry_sent")).thenReturn(Instant.now().toString()); + CronService spy = spy(cronService); + doNothing().when(spy).sendTelemetryData(); + spy.initScheduledTasks(); + verify(spy, never()).sendTelemetryData(); + } + + @Test + void checkAndRunPing_nullLastPingVersion_doesNotCallSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn(null); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy, never()).sendPing(); + } + + @Test + void checkAndRunPing_nullPing_doesNotCallSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + when(telemetryService.getInstallationPing()).thenReturn(null); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy, never()).sendPing(); + } + + @Test + void checkAndRunPing_shouldRunTaskFalseAndNoVersionChange_doesNotCallSendPing() { + when(appSettingService.getSettingValue("last_ping_app_version")).thenReturn("1.0.0"); + InstallationPing ping = InstallationPing.builder().appVersion("1.0.0").build(); + when(telemetryService.getInstallationPing()).thenReturn(ping); + when(appSettingService.getSettingValue("last_ping_sent")).thenReturn(Instant.now().toString()); + CronService spy = spy(cronService); + doNothing().when(spy).sendPing(); + spy.initScheduledTasks(); + verify(spy, never()).sendPing(); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java index de90842be..71a81cce3 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java @@ -118,18 +118,6 @@ class ComicInfoParsingIssuesTest { assertEquals(200.0f, metadata.getSeriesNumber()); } - @Test - void testComicInfoExtractionFallbackWhenNoComicInfo() throws Exception { - File cbz = createCbz("Daredevil_v1964_c001.cbz", new LinkedHashMap<>() {{ - put("page1.jpg", createTestImage(Color.YELLOW)); - put("page2.jpg", createTestImage(Color.CYAN)); - }}); - - BookMetadata metadata = extractor.extractMetadata(cbz); - - assertEquals("Daredevil v1964 c001", metadata.getTitle()); - } - @Test void testComicInfoWithExtendedFields() throws Exception { String xml = "" + diff --git a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.html b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.html index 31e38c6fd..706ceb4d6 100644 --- a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.html +++ b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.html @@ -86,7 +86,6 @@

{{ uploadFile.file.name }} {{ formatSize(uploadFile.file.size) }} @@ -155,11 +154,28 @@ } @case ('Failed') { - - + @if (uploadFile.errorMessage?.includes('exceeds maximum size')) { + @if (hasUploadCompleted()) { + + + } @else { + + } + } @else { + + + } } }
@@ -172,13 +188,13 @@
- +

Drag and Drop Files

Supported formats: .pdf, .epub, .cbz, .cbr, .cb7, .fb2
- Maximum file size: 100 MB per file + Maximum file size: {{ maxFileSizeDisplay }} per file

diff --git a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.scss b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.scss index 6c6a235a9..7a7c90a62 100644 --- a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.scss +++ b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.scss @@ -30,7 +30,6 @@ background: var(--primary-color); border-radius: 10px; - .header-icon { font-size: 1.5rem; color: var(--primary-contrast-color); @@ -270,7 +269,7 @@ align-items: center; justify-content: space-between; gap: 1rem; - padding: 0.75rem; + padding: 0.25rem 0.75rem; background: var(--card-background); border: 1px solid var(--border-color); border-radius: 8px; @@ -319,7 +318,11 @@ } &.success { - color: var(--green-500); + color: #22c55e; + } + + &.warning { + color: #f97316; } &.error { @@ -377,11 +380,16 @@ font-size: 2.5rem; color: var(--text-secondary-color); opacity: 0.6; + transition: color 0.3s ease; + + &.active { + color: #22c55e; + } } } .empty-title { - margin: 0 0 0.5rem 0; + margin: 0 0 1.5rem 0; font-size: 1.125rem; font-weight: 600; color: var(--text-color); diff --git a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.ts b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.ts index c8315915d..f8cf9af17 100644 --- a/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.ts +++ b/booklore-ui/src/app/shared/components/book-uploader/book-uploader.component.ts @@ -45,6 +45,7 @@ interface UploadingFile { export class BookUploaderComponent implements OnInit { files: UploadingFile[] = []; isUploading: boolean = false; + uploadCompleted: boolean = false; _selectedLibrary: Library | null = null; selectedPath: LibraryPath | null = null; @@ -57,6 +58,7 @@ export class BookUploaderComponent implements OnInit { readonly libraryState$: Observable = this.libraryService.libraryState$; appSettings$: Observable = this.appSettingsService.appSettings$; maxFileSizeBytes?: number; + maxFileSizeDisplay: string = '100 MB'; stateOptions = [ {label: 'Library', value: 'library'}, {label: 'Bookdrop', value: 'bookdrop'} @@ -70,7 +72,9 @@ export class BookUploaderComponent implements OnInit { take(1) ) .subscribe(settings => { - this.maxFileSizeBytes = (settings?.maxFileUploadSizeInMb ?? 100) * 1024 * 1024; + const maxSizeMb = settings?.maxFileUploadSizeInMb ?? 100; + this.maxFileSizeBytes = maxSizeMb * 1024 * 1024; + this.maxFileSizeDisplay = `${maxSizeMb} MB`; }); this.libraryState$.subscribe(state => { @@ -89,7 +93,7 @@ export class BookUploaderComponent implements OnInit { set selectedLibrary(library: Library | null) { this._selectedLibrary = library; - if(library?.paths?.length === 1) { + if (library?.paths?.length === 1) { this.selectedPath = library.paths[0]; } } @@ -115,7 +119,24 @@ export class BookUploaderComponent implements OnInit { const newFiles = event.currentFiles; for (const file of newFiles) { const exists = this.files.some(f => f.file.name === file.name && f.file.size === file.size); - if (!exists) { + if (exists) { + continue; + } + + if (this.maxFileSizeBytes && file.size > this.maxFileSizeBytes) { + const errorMsg = `File exceeds maximum size of ${this.formatSize(this.maxFileSizeBytes)}`; + this.files.unshift({ + file, + status: 'Failed', + errorMessage: errorMsg + }); + this.messageService.add({ + severity: 'error', + summary: 'File Too Large', + detail: `${file.name} exceeds the maximum file size of ${this.formatSize(this.maxFileSizeBytes)}`, + life: 5000 + }); + } else { this.files.unshift({file, status: 'Pending'}); } } @@ -144,6 +165,7 @@ export class BookUploaderComponent implements OnInit { if (filesToUpload.length === 0) return; this.isUploading = true; + this.uploadCompleted = false; const destination = this.value; const libraryId = this.selectedLibrary?.id?.toString(); const pathId = this.selectedPath?.id?.toString(); @@ -155,6 +177,7 @@ export class BookUploaderComponent implements OnInit { const batch = files.slice(startIndex, startIndex + batchSize); if (batch.length === 0) { this.isUploading = false; + this.uploadCompleted = true; if (destination === 'bookdrop') { this.ref.close('uploaded_to_bookdrop'); } @@ -167,7 +190,6 @@ export class BookUploaderComponent implements OnInit { uploadFile.status = 'Uploading'; const formData = new FormData(); - // Reconstruct the file to ensure strict type and name handling const cleanFile = new File([uploadFile.file], uploadFile.file.name, {type: uploadFile.file.type}); formData.append('file', cleanFile, uploadFile.file.name); @@ -216,6 +238,13 @@ export class BookUploaderComponent implements OnInit { return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles(); } + isUploadZoneActive(): boolean { + if (this.value === 'bookdrop') { + return true; + } + return !!(this.selectedLibrary && this.selectedPath); + } + formatSize(bytes: number): string { const k = 1024; const dm = 2; @@ -239,6 +268,28 @@ export class BookUploaderComponent implements OnInit { } } + getFileStatusLabel(uploadFile: UploadingFile): string { + if (uploadFile.status === 'Failed' && uploadFile.errorMessage?.includes('exceeds maximum size')) { + return 'Too Large'; + } + switch (uploadFile.status) { + case 'Pending': + return 'Ready'; + case 'Uploading': + return 'Uploading'; + case 'Uploaded': + return 'Uploaded'; + case 'Failed': + return 'Failed'; + default: + return uploadFile.status; + } + } + + hasUploadCompleted(): boolean { + return this.uploadCompleted; + } + closeDialog(): void { this.ref.close(); }