Improve robustness of book uploader error handling (#2130)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-19
@@ -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('\\', '/');
|
||||
|
||||
+11
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
-12
@@ -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 = "<ComicInfo>" +
|
||||
|
||||
@@ -86,7 +86,6 @@
|
||||
</div>
|
||||
<p-fileupload
|
||||
name="file"
|
||||
[maxFileSize]="maxFileSizeBytes"
|
||||
[customUpload]="true"
|
||||
[multiple]="true"
|
||||
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2"
|
||||
@@ -133,7 +132,7 @@
|
||||
<div class="file-item">
|
||||
<div class="file-info">
|
||||
<p-badge
|
||||
[value]="uploadFile.status === 'Pending' ? 'Ready' : uploadFile.status"
|
||||
[value]="getFileStatusLabel(uploadFile)"
|
||||
[severity]="getBadgeSeverity(uploadFile.status)"/>
|
||||
<span class="file-name">{{ uploadFile.file.name }}</span>
|
||||
<span class="file-size">{{ formatSize(uploadFile.file.size) }}</span>
|
||||
@@ -155,11 +154,28 @@
|
||||
<i class="pi pi-check status-icon success"></i>
|
||||
}
|
||||
@case ('Failed') {
|
||||
<i
|
||||
class="pi pi-exclamation-triangle status-icon error"
|
||||
[pTooltip]="uploadFile.errorMessage || 'Upload failed'"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
@if (uploadFile.errorMessage?.includes('exceeds maximum size')) {
|
||||
@if (hasUploadCompleted()) {
|
||||
<i
|
||||
class="pi pi-exclamation-triangle status-icon warning"
|
||||
[pTooltip]="uploadFile.errorMessage || 'File too large'"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
} @else {
|
||||
<p-button
|
||||
icon="pi pi-times"
|
||||
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
|
||||
severity="danger"
|
||||
[text]="true"
|
||||
[rounded]="true"/>
|
||||
}
|
||||
} @else {
|
||||
<i
|
||||
class="pi pi-exclamation-triangle status-icon error"
|
||||
[pTooltip]="uploadFile.errorMessage || 'Upload failed'"
|
||||
tooltipPosition="top">
|
||||
</i>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@@ -172,13 +188,13 @@
|
||||
<ng-template #empty>
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon-wrapper">
|
||||
<i class="pi pi-cloud-upload empty-icon"></i>
|
||||
<i class="pi pi-cloud-upload empty-icon" [class.active]="isUploadZoneActive()"></i>
|
||||
</div>
|
||||
<h3 class="empty-title">Drag and Drop Files</h3>
|
||||
<p class="empty-description">
|
||||
Supported formats: <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, <strong>.cb7</strong>, <strong>.fb2</strong>
|
||||
<br/>
|
||||
Maximum file size: 100 MB per file
|
||||
Maximum file size: {{ maxFileSizeDisplay }} per file
|
||||
</p>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<LibraryState> = this.libraryService.libraryState$;
|
||||
appSettings$: Observable<AppSettings | null> = 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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user