Allow users to disable kobo shelf

This commit is contained in:
aditya.chandel
2025-08-28 21:12:45 -06:00
committed by Aditya Chandel
parent 8d04bc3498
commit 12b7aaa8e9
9 changed files with 154 additions and 77 deletions
@@ -143,7 +143,9 @@ public class KoboController {
public ResponseEntity<?> deleteBookFromLibrary(@PathVariable String bookId) { public ResponseEntity<?> deleteBookFromLibrary(@PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) { if (StringUtils.isNumeric(bookId)) {
Shelf userKoboShelf = shelfService.getUserKoboShelf(); 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(); return ResponseEntity.ok().build();
} else { } else {
return koboServerProxy.proxyCurrentRequest(null, false); return koboServerProxy.proxyCurrentRequest(null, false);
@@ -17,7 +17,6 @@ public class KoboSettingsController {
private final KoboSettingsService koboService; private final KoboSettingsService koboService;
@GetMapping @GetMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> getSettings() { public ResponseEntity<KoboSyncSettings> getSettings() {
KoboSyncSettings settings = koboService.getCurrentUserSettings(); KoboSyncSettings settings = koboService.getCurrentUserSettings();
return ResponseEntity.ok(settings); return ResponseEntity.ok(settings);
@@ -30,7 +29,7 @@ public class KoboSettingsController {
return ResponseEntity.ok(updated); return ResponseEntity.ok(updated);
} }
@PatchMapping("/sync") @PutMapping("/sync")
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()") @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<Void> toggleSync(@RequestParam boolean enabled) { public ResponseEntity<Void> toggleSync(@RequestParam boolean enabled) {
koboService.setSyncEnabled(enabled); koboService.setSyncEnabled(enabled);
@@ -8,5 +8,5 @@ public class KoboSyncSettings {
private Long id; private Long id;
private String userId; private String userId;
private String token; private String token;
private boolean syncEnabled = true; private boolean syncEnabled;
} }
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.model.dto.BookLoreUser; import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.KoboSyncSettings; 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.dto.request.ShelfCreateRequest;
import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity; import com.adityachandel.booklore.model.entity.ShelfEntity;
@@ -44,6 +45,7 @@ public class KoboSettingsService {
.orElseGet(() -> KoboUserSettingsEntity.builder() .orElseGet(() -> KoboUserSettingsEntity.builder()
.userId(user.getId()) .userId(user.getId())
.token(newToken) .token(newToken)
.syncEnabled(false)
.build()); .build());
ensureKoboShelfExists(user.getId()); ensureKoboShelfExists(user.getId());
@@ -55,9 +57,15 @@ public class KoboSettingsService {
@Transactional @Transactional
public void setSyncEnabled(boolean enabled) { public void setSyncEnabled(boolean enabled) {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
KoboUserSettingsEntity entity = repository.findByUserId(user.getId()) KoboUserSettingsEntity entity = repository.findByUserId(user.getId()).orElseThrow(() -> new IllegalStateException("Kobo settings not found for user"));
.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); entity.setSyncEnabled(enabled);
repository.save(entity); repository.save(entity);
} }
@@ -66,6 +74,7 @@ public class KoboSettingsService {
ensureKoboShelfExists(userId); ensureKoboShelfExists(userId);
KoboUserSettingsEntity entity = KoboUserSettingsEntity.builder() KoboUserSettingsEntity entity = KoboUserSettingsEntity.builder()
.userId(userId) .userId(userId)
.syncEnabled(false)
.token(generateToken()) .token(generateToken())
.build(); .build();
return repository.save(entity); return repository.save(entity);
@@ -75,10 +84,10 @@ public class KoboSettingsService {
Optional<ShelfEntity> shelf = shelfService.getShelf(userId, ShelfType.KOBO.getName()); Optional<ShelfEntity> shelf = shelfService.getShelf(userId, ShelfType.KOBO.getName());
if (shelf.isEmpty()) { if (shelf.isEmpty()) {
shelfService.createShelf( shelfService.createShelf(
ShelfCreateRequest.builder() ShelfCreateRequest.builder()
.name(ShelfType.KOBO.getName()) .name(ShelfType.KOBO.getName())
.icon(ShelfType.KOBO.getIcon()) .icon(ShelfType.KOBO.getIcon())
.build() .build()
); );
} }
} }
@@ -92,6 +101,7 @@ public class KoboSettingsService {
dto.setId(entity.getId()); dto.setId(entity.getId());
dto.setUserId(entity.getUserId().toString()); dto.setUserId(entity.getUserId().toString());
dto.setToken(entity.getToken()); dto.setToken(entity.getToken());
dto.setSyncEnabled(entity.isSyncEnabled());
return dto; return dto;
} }
} }
@@ -64,18 +64,13 @@ public class ShelfService {
} }
public void deleteShelf(Long shelfId) { 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); shelfRepository.deleteById(shelfId);
} }
public Shelf getUserKoboShelf() { public Shelf getUserKoboShelf() {
Long userId = getAuthenticatedUserId(); Long userId = getAuthenticatedUserId();
ShelfEntity koboShelf = shelfRepository.findByUserIdAndName(userId, ShelfType.KOBO.getName()) Optional<ShelfEntity> koboShelf = shelfRepository.findByUserIdAndName(userId, ShelfType.KOBO.getName());
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(ShelfType.KOBO.getName())); return koboShelf.map(shelfMapper::toShelf).orElse(null);
return shelfMapper.toShelf(koboShelf);
} }
public List<Book> getShelfBooks(Long shelfId) { public List<Book> getShelfBooks(Long shelfId) {
@@ -1,14 +1,14 @@
import { inject, Injectable } from '@angular/core'; import {inject, Injectable} from '@angular/core';
import { HttpClient } from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs'; import {BehaviorSubject, Observable, of} from 'rxjs';
import { tap, catchError, map, shareReplay, finalize } from 'rxjs/operators'; import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators';
import { Shelf } from '../model/shelf.model'; import {Shelf} from '../model/shelf.model';
import { ShelfState } from '../model/state/shelf-state.model'; import {ShelfState} from '../model/state/shelf-state.model';
import { BookService } from './book.service'; import {BookService} from './book.service';
import { API_CONFIG } from '../../config/api-config'; import {API_CONFIG} from '../../config/api-config';
@Injectable({ providedIn: 'root' }) @Injectable({providedIn: 'root'})
export class ShelfService { export class ShelfService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
private http = inject(HttpClient); private http = inject(HttpClient);
@@ -36,21 +36,30 @@ export class ShelfService {
private fetchShelves(): Observable<Shelf[]> { private fetchShelves(): Observable<Shelf[]> {
return this.http.get<Shelf[]>(this.url).pipe( return this.http.get<Shelf[]>(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 => { catchError(err => {
const curr = this.shelfStateSubject.value; 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; throw err;
}) })
); );
} }
public reloadShelves(): void {
this.fetchShelves().subscribe({
next: () => {
},
error: () => {
}
});
}
createShelf(shelf: Shelf): Observable<Shelf> { createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe( return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => { map(newShelf => {
const curr = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf]; const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({ ...curr, shelves: updated }); this.shelfStateSubject.next({...curr, shelves: updated});
return newShelf; return newShelf;
}) })
); );
@@ -61,7 +70,7 @@ export class ShelfService {
map(updated => { map(updated => {
const curr = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated]; 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; return updated;
}) })
); );
@@ -73,11 +82,11 @@ export class ShelfService {
this.bookService.removeBooksFromShelf(id); this.bookService.removeBooksFromShelf(id);
const curr = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const filtered = curr.shelves?.filter(s => s.id !== id) || []; const filtered = curr.shelves?.filter(s => s.id !== id) || [];
this.shelfStateSubject.next({ ...curr, shelves: filtered }); this.shelfStateSubject.next({...curr, shelves: filtered});
}), }),
catchError(err => { catchError(err => {
const curr = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...curr, error: err.message }); this.shelfStateSubject.next({...curr, error: err.message});
return of(); return of();
}) })
); );
@@ -1,7 +1,7 @@
<p-confirmDialog></p-confirmDialog> <p-confirmDialog></p-confirmDialog>
<p class="text-lg flex items-center gap-2 px-4 pt-4 pb-2"> <p class="text-lg flex items-center gap-2 px-4 pt-4 pb-2">
Kobo Integration Token: Kobo Integration Settings:
<i class="pi pi-info-circle text-sky-600" <i class="pi pi-info-circle text-sky-600"
pTooltip="Click to view Kobo setup documentation" pTooltip="Click to view Kobo setup documentation"
tooltipPosition="right" tooltipPosition="right"
@@ -12,42 +12,53 @@
@if (hasKoboTokenPermission) { @if (hasKoboTokenPermission) {
<form #koboForm="ngForm" class="px-4 py-2"> <form #koboForm="ngForm" class="px-4 py-2">
<div class="flex flex-col px-4 py-4 space-y-4"> <div class="flex flex-col p-4 space-y-6">
<div class="flex flex-col gap-1 max-w-[33rem]"> <div class="flex gap-2">
<label for="koboToken">Kobo Sync Token</label> <p-toggle-switch
<div class="flex items-center gap-2"> id="syncEnabled"
<input name="syncEnabled"
pInputText [(ngModel)]="koboSyncSettings.syncEnabled"
id="koboToken" (ngModelChange)="onSyncToggle()">
[(ngModel)]="koboToken" </p-toggle-switch>
[type]="showToken ? 'text' : 'password'" <label for="syncEnabled">Enable Kobo Sync</label>
readonly
fluid
name="koboToken"
/>
<p-button
icon="pi pi-copy"
outlined="true"
severity="info"
(onClick)="copyText(koboToken)">
</p-button>
<p-button
[icon]="showToken ? 'pi pi-eye-slash' : 'pi pi-eye'"
outlined="true"
severity="info"
(onClick)="toggleShowToken()">
</p-button>
</div>
</div> </div>
<p-button @if (koboSyncSettings.syncEnabled) {
icon="pi pi-refresh" <div class="flex flex-col gap-1 max-w-[33rem]">
outlined="true" <label for="koboToken">Kobo Sync Token</label>
severity="warn" <div class="flex items-center gap-2">
label="Regenerate Token" <input
(onClick)="confirmRegenerateToken()" pInputText
[disabled]="!credentialsSaved"> id="koboToken"
</p-button> [(ngModel)]="koboSyncSettings.token"
[type]="showToken ? 'text' : 'password'"
readonly
fluid
name="koboToken"
/>
<p-button
icon="pi pi-copy"
outlined="true"
severity="info"
(onClick)="copyText(koboSyncSettings.token)">
</p-button>
<p-button
[icon]="showToken ? 'pi pi-eye-slash' : 'pi pi-eye'"
outlined="true"
severity="info"
(onClick)="toggleShowToken()">
</p-button>
</div>
</div>
<p-button
icon="pi pi-refresh"
outlined="true"
severity="warn"
label="Regenerate Token"
(onClick)="confirmRegenerateToken()"
[disabled]="!credentialsSaved">
</p-button>
}
</div> </div>
</form> </form>
@@ -15,6 +15,7 @@ import {Slider} from 'primeng/slider';
import {AppSettingsService} from '../../../core/service/app-settings.service'; import {AppSettingsService} from '../../../core/service/app-settings.service';
import {SettingsHelperService} from '../../../core/service/settings-helper.service'; import {SettingsHelperService} from '../../../core/service/settings-helper.service';
import {AppSettingKey, KoboSettings} from '../../../core/model/app-settings.model'; import {AppSettingKey, KoboSettings} from '../../../core/model/app-settings.model';
import {ShelfService} from '../../../book/service/shelf.service';
@Component({ @Component({
selector: 'app-kobo-sync-setting-component', selector: 'app-kobo-sync-setting-component',
@@ -32,13 +33,13 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
protected userService = inject(UserService); protected userService = inject(UserService);
protected appSettingsService = inject(AppSettingsService); protected appSettingsService = inject(AppSettingsService);
protected settingsHelperService = inject(SettingsHelperService); protected settingsHelperService = inject(SettingsHelperService);
private shelfService = inject(ShelfService);
private readonly destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
private readonly sliderChange$ = new Subject<void>(); private readonly sliderChange$ = new Subject<void>();
hasKoboTokenPermission = false; hasKoboTokenPermission = false;
isAdmin = false; isAdmin = false;
koboToken = '';
credentialsSaved = false; credentialsSaved = false;
showToken = false; showToken = false;
@@ -47,6 +48,11 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
conversionLimitInMb: 100 conversionLimitInMb: 100
}; };
koboSyncSettings: KoboSyncSettings = {
token: '',
syncEnabled: false
}
ngOnInit() { ngOnInit() {
this.setupSliderDebouncing(); this.setupSliderDebouncing();
this.setupUserStateSubscription(); this.setupUserStateSubscription();
@@ -69,18 +75,19 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
this.hasKoboTokenPermission = (userState.user?.permissions.canSyncKobo) ?? false; this.hasKoboTokenPermission = (userState.user?.permissions.canSyncKobo) ?? false;
this.isAdmin = userState.user?.permissions.admin ?? false; this.isAdmin = userState.user?.permissions.admin ?? false;
if (this.hasKoboTokenPermission) { if (this.hasKoboTokenPermission) {
this.loadKoboToken(); this.loadKoboUserSettings();
} }
if (this.isAdmin) { if (this.isAdmin) {
this.loadKoboSettings(); this.loadKoboAdminSettings();
} }
}); });
} }
private loadKoboToken() { private loadKoboUserSettings() {
this.koboService.getUser().subscribe({ this.koboService.getUser().subscribe({
next: (settings: KoboSyncSettings) => { next: (settings: KoboSyncSettings) => {
this.koboToken = settings.token; this.koboSyncSettings.token = settings.token;
this.koboSyncSettings.syncEnabled = settings.syncEnabled;
this.credentialsSaved = !!settings.token; this.credentialsSaved = !!settings.token;
}, },
error: () => { error: () => {
@@ -89,7 +96,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
}); });
} }
private loadKoboSettings() { private loadKoboAdminSettings() {
this.appSettingsService.appSettings$ this.appSettingsService.appSettings$
.pipe( .pipe(
filter(settings => settings != null), filter(settings => settings != null),
@@ -122,7 +129,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
private regenerateToken() { private regenerateToken() {
this.koboService.createOrUpdateToken().subscribe({ this.koboService.createOrUpdateToken().subscribe({
next: (settings) => { next: (settings) => {
this.koboToken = settings.token; this.koboSyncSettings.token = settings.token;
this.credentialsSaved = true; this.credentialsSaved = true;
this.messageService.add({severity: 'success', summary: 'Token regenerated', detail: 'New token generated successfully'}); 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(); 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() { saveSettings() {
this.settingsHelperService.saveSetting(AppSettingKey.KOBO_SETTINGS, this.koboSettings) this.settingsHelperService.saveSetting(AppSettingKey.KOBO_SETTINGS, this.koboSettings)
.subscribe({ .subscribe({
@@ -5,6 +5,7 @@ import {API_CONFIG} from '../../config/api-config';
export interface KoboSyncSettings { export interface KoboSyncSettings {
token: string; token: string;
syncEnabled: boolean;
} }
@Injectable({ @Injectable({
@@ -14,11 +15,16 @@ export class KoboService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/kobo-settings`; private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/kobo-settings`;
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
getUser(): Observable<KoboSyncSettings> {
return this.http.get<KoboSyncSettings>(`${this.baseUrl}`);
}
createOrUpdateToken(): Observable<KoboSyncSettings> { createOrUpdateToken(): Observable<KoboSyncSettings> {
return this.http.put<KoboSyncSettings>(`${this.baseUrl}`, null); return this.http.put<KoboSyncSettings>(`${this.baseUrl}`, null);
} }
getUser(): Observable<KoboSyncSettings> { toggleSync(enabled: boolean): Observable<void> {
return this.http.get<KoboSyncSettings>(`${this.baseUrl}`); const params = new HttpParams().set('enabled', enabled.toString());
return this.http.put<void>(`${this.baseUrl}/sync`, null, { params });
} }
} }