diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java index 5ad231d2b..94c312c51 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java @@ -143,7 +143,9 @@ public class KoboController { public ResponseEntity deleteBookFromLibrary(@PathVariable String bookId) { if (StringUtils.isNumeric(bookId)) { Shelf userKoboShelf = shelfService.getUserKoboShelf(); - bookService.assignShelvesToBooks(Set.of(Long.valueOf(bookId)), Set.of(), Set.of(userKoboShelf.getId())); + if (userKoboShelf != null) { + bookService.assignShelvesToBooks(Set.of(Long.valueOf(bookId)), Set.of(), Set.of(userKoboShelf.getId())); + } return ResponseEntity.ok().build(); } else { return koboServerProxy.proxyCurrentRequest(null, false); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboSettingsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboSettingsController.java index acf86c64a..4ab77e911 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboSettingsController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboSettingsController.java @@ -17,7 +17,6 @@ public class KoboSettingsController { private final KoboSettingsService koboService; @GetMapping - @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()") public ResponseEntity getSettings() { KoboSyncSettings settings = koboService.getCurrentUserSettings(); return ResponseEntity.ok(settings); @@ -30,7 +29,7 @@ public class KoboSettingsController { return ResponseEntity.ok(updated); } - @PatchMapping("/sync") + @PutMapping("/sync") @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()") public ResponseEntity toggleSync(@RequestParam boolean enabled) { koboService.setSyncEnabled(enabled); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/KoboSyncSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/KoboSyncSettings.java index 8bf2df0f3..2e6670794 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/KoboSyncSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/KoboSyncSettings.java @@ -8,5 +8,5 @@ public class KoboSyncSettings { private Long id; private String userId; private String token; - private boolean syncEnabled = true; + private boolean syncEnabled; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboSettingsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboSettingsService.java index a818ede8a..c80a8354c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboSettingsService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/KoboSettingsService.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.service; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.model.dto.BookLoreUser; import com.adityachandel.booklore.model.dto.KoboSyncSettings; +import com.adityachandel.booklore.model.dto.Shelf; import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest; import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; import com.adityachandel.booklore.model.entity.ShelfEntity; @@ -44,6 +45,7 @@ public class KoboSettingsService { .orElseGet(() -> KoboUserSettingsEntity.builder() .userId(user.getId()) .token(newToken) + .syncEnabled(false) .build()); ensureKoboShelfExists(user.getId()); @@ -55,9 +57,15 @@ public class KoboSettingsService { @Transactional public void setSyncEnabled(boolean enabled) { BookLoreUser user = authenticationService.getAuthenticatedUser(); - KoboUserSettingsEntity entity = repository.findByUserId(user.getId()) - .orElseThrow(() -> new IllegalStateException("Kobo settings not found for user")); - + KoboUserSettingsEntity entity = repository.findByUserId(user.getId()).orElseThrow(() -> new IllegalStateException("Kobo settings not found for user")); + Shelf userKoboShelf = shelfService.getUserKoboShelf(); + if (!enabled) { + if (userKoboShelf != null) { + shelfService.deleteShelf(userKoboShelf.getId()); + } + } else { + ensureKoboShelfExists(user.getId()); + } entity.setSyncEnabled(enabled); repository.save(entity); } @@ -66,6 +74,7 @@ public class KoboSettingsService { ensureKoboShelfExists(userId); KoboUserSettingsEntity entity = KoboUserSettingsEntity.builder() .userId(userId) + .syncEnabled(false) .token(generateToken()) .build(); return repository.save(entity); @@ -75,10 +84,10 @@ public class KoboSettingsService { Optional shelf = shelfService.getShelf(userId, ShelfType.KOBO.getName()); if (shelf.isEmpty()) { shelfService.createShelf( - ShelfCreateRequest.builder() - .name(ShelfType.KOBO.getName()) - .icon(ShelfType.KOBO.getIcon()) - .build() + ShelfCreateRequest.builder() + .name(ShelfType.KOBO.getName()) + .icon(ShelfType.KOBO.getIcon()) + .build() ); } } @@ -92,6 +101,7 @@ public class KoboSettingsService { dto.setId(entity.getId()); dto.setUserId(entity.getUserId().toString()); dto.setToken(entity.getToken()); + dto.setSyncEnabled(entity.isSyncEnabled()); return dto; } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java index 39cc1baa9..d9a4d134d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/ShelfService.java @@ -64,18 +64,13 @@ public class ShelfService { } public void deleteShelf(Long shelfId) { - ShelfEntity shelfEntity = findShelfByIdOrThrow(shelfId); - if (shelfEntity.getName().equalsIgnoreCase(ShelfType.KOBO.getName())) { - throw ApiError.SHELF_CANNOT_BE_DELETED.createException(ShelfType.KOBO.getName()); - } shelfRepository.deleteById(shelfId); } public Shelf getUserKoboShelf() { Long userId = getAuthenticatedUserId(); - ShelfEntity koboShelf = shelfRepository.findByUserIdAndName(userId, ShelfType.KOBO.getName()) - .orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(ShelfType.KOBO.getName())); - return shelfMapper.toShelf(koboShelf); + Optional koboShelf = shelfRepository.findByUserIdAndName(userId, ShelfType.KOBO.getName()); + return koboShelf.map(shelfMapper::toShelf).orElse(null); } public List getShelfBooks(Long shelfId) { diff --git a/booklore-ui/src/app/book/service/shelf.service.ts b/booklore-ui/src/app/book/service/shelf.service.ts index b1806c942..5aad7f357 100644 --- a/booklore-ui/src/app/book/service/shelf.service.ts +++ b/booklore-ui/src/app/book/service/shelf.service.ts @@ -1,14 +1,14 @@ -import { inject, Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { tap, catchError, map, shareReplay, finalize } from 'rxjs/operators'; +import {inject, Injectable} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {BehaviorSubject, Observable, of} from 'rxjs'; +import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators'; -import { Shelf } from '../model/shelf.model'; -import { ShelfState } from '../model/state/shelf-state.model'; -import { BookService } from './book.service'; -import { API_CONFIG } from '../../config/api-config'; +import {Shelf} from '../model/shelf.model'; +import {ShelfState} from '../model/state/shelf-state.model'; +import {BookService} from './book.service'; +import {API_CONFIG} from '../../config/api-config'; -@Injectable({ providedIn: 'root' }) +@Injectable({providedIn: 'root'}) export class ShelfService { private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private http = inject(HttpClient); @@ -36,21 +36,30 @@ export class ShelfService { private fetchShelves(): Observable { return this.http.get(this.url).pipe( - tap(shelves => this.shelfStateSubject.next({ shelves, loaded: true, error: null })), + tap(shelves => this.shelfStateSubject.next({shelves, loaded: true, error: null})), catchError(err => { const curr = this.shelfStateSubject.value; - this.shelfStateSubject.next({ shelves: curr.shelves, loaded: true, error: err.message }); + this.shelfStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message}); throw err; }) ); } + public reloadShelves(): void { + this.fetchShelves().subscribe({ + next: () => { + }, + error: () => { + } + }); + } + createShelf(shelf: Shelf): Observable { return this.http.post(this.url, shelf).pipe( map(newShelf => { const curr = this.shelfStateSubject.value; const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf]; - this.shelfStateSubject.next({ ...curr, shelves: updated }); + this.shelfStateSubject.next({...curr, shelves: updated}); return newShelf; }) ); @@ -61,7 +70,7 @@ export class ShelfService { map(updated => { const curr = this.shelfStateSubject.value; const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated]; - this.shelfStateSubject.next({ ...curr, shelves: list }); + this.shelfStateSubject.next({...curr, shelves: list}); return updated; }) ); @@ -73,11 +82,11 @@ export class ShelfService { this.bookService.removeBooksFromShelf(id); const curr = this.shelfStateSubject.value; const filtered = curr.shelves?.filter(s => s.id !== id) || []; - this.shelfStateSubject.next({ ...curr, shelves: filtered }); + this.shelfStateSubject.next({...curr, shelves: filtered}); }), catchError(err => { const curr = this.shelfStateSubject.value; - this.shelfStateSubject.next({ ...curr, error: err.message }); + this.shelfStateSubject.next({...curr, error: err.message}); return of(); }) ); diff --git a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html index bca17791d..3d813e46a 100644 --- a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html +++ b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.html @@ -1,7 +1,7 @@

- Kobo Integration Token: + Kobo Integration Settings: -

-
- -
- - - - - -
+
+
+ + +
- - + @if (koboSyncSettings.syncEnabled) { +
+ +
+ + + + + +
+
+ + + }
diff --git a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts index b324fa8fc..78716e6ac 100644 --- a/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts +++ b/booklore-ui/src/app/settings/device-settings-component/kobo-sync-settings-component/kobo-sync-settings-component.ts @@ -15,6 +15,7 @@ import {Slider} from 'primeng/slider'; import {AppSettingsService} from '../../../core/service/app-settings.service'; import {SettingsHelperService} from '../../../core/service/settings-helper.service'; import {AppSettingKey, KoboSettings} from '../../../core/model/app-settings.model'; +import {ShelfService} from '../../../book/service/shelf.service'; @Component({ selector: 'app-kobo-sync-setting-component', @@ -32,13 +33,13 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { protected userService = inject(UserService); protected appSettingsService = inject(AppSettingsService); protected settingsHelperService = inject(SettingsHelperService); + private shelfService = inject(ShelfService); private readonly destroy$ = new Subject(); private readonly sliderChange$ = new Subject(); hasKoboTokenPermission = false; isAdmin = false; - koboToken = ''; credentialsSaved = false; showToken = false; @@ -47,6 +48,11 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { conversionLimitInMb: 100 }; + koboSyncSettings: KoboSyncSettings = { + token: '', + syncEnabled: false + } + ngOnInit() { this.setupSliderDebouncing(); this.setupUserStateSubscription(); @@ -69,18 +75,19 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { this.hasKoboTokenPermission = (userState.user?.permissions.canSyncKobo) ?? false; this.isAdmin = userState.user?.permissions.admin ?? false; if (this.hasKoboTokenPermission) { - this.loadKoboToken(); + this.loadKoboUserSettings(); } if (this.isAdmin) { - this.loadKoboSettings(); + this.loadKoboAdminSettings(); } }); } - private loadKoboToken() { + private loadKoboUserSettings() { this.koboService.getUser().subscribe({ next: (settings: KoboSyncSettings) => { - this.koboToken = settings.token; + this.koboSyncSettings.token = settings.token; + this.koboSyncSettings.syncEnabled = settings.syncEnabled; this.credentialsSaved = !!settings.token; }, error: () => { @@ -89,7 +96,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { }); } - private loadKoboSettings() { + private loadKoboAdminSettings() { this.appSettingsService.appSettings$ .pipe( filter(settings => settings != null), @@ -122,7 +129,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { private regenerateToken() { this.koboService.createOrUpdateToken().subscribe({ next: (settings) => { - this.koboToken = settings.token; + this.koboSyncSettings.token = settings.token; this.credentialsSaved = true; this.messageService.add({severity: 'success', summary: 'Token regenerated', detail: 'New token generated successfully'}); }, @@ -140,6 +147,44 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { this.sliderChange$.next(); } + onSyncToggle() { + if (!this.koboSyncSettings.syncEnabled) { + this.confirmationService.confirm({ + message: 'Disabling Kobo sync will delete your Kobo shelf. Are you sure you want to proceed?', + header: 'Confirm Disable', + icon: 'pi pi-exclamation-triangle', + accept: () => this.performToggle(false), + reject: () => { + this.koboSyncSettings.syncEnabled = true; + } + }); + } else { + this.performToggle(true); + } + } + + private performToggle(enabled: boolean) { + this.koboService.toggleSync(enabled).subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Sync Updated', + detail: enabled + ? 'Kobo sync enabled' + : 'Kobo sync disabled' + }); + this.shelfService.reloadShelves(); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to update sync setting' + }); + } + }); + } + saveSettings() { this.settingsHelperService.saveSetting(AppSettingKey.KOBO_SETTINGS, this.koboSettings) .subscribe({ diff --git a/booklore-ui/src/app/settings/device-settings-component/kobo.service.ts b/booklore-ui/src/app/settings/device-settings-component/kobo.service.ts index 0eeec595b..3c6c9f1bf 100644 --- a/booklore-ui/src/app/settings/device-settings-component/kobo.service.ts +++ b/booklore-ui/src/app/settings/device-settings-component/kobo.service.ts @@ -5,6 +5,7 @@ import {API_CONFIG} from '../../config/api-config'; export interface KoboSyncSettings { token: string; + syncEnabled: boolean; } @Injectable({ @@ -14,11 +15,16 @@ export class KoboService { private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/kobo-settings`; private readonly http = inject(HttpClient); + getUser(): Observable { + return this.http.get(`${this.baseUrl}`); + } + createOrUpdateToken(): Observable { return this.http.put(`${this.baseUrl}`, null); } - getUser(): Observable { - return this.http.get(`${this.baseUrl}`); + toggleSync(enabled: boolean): Observable { + const params = new HttpParams().set('enabled', enabled.toString()); + return this.http.put(`${this.baseUrl}/sync`, null, { params }); } }