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) {
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);
@@ -17,7 +17,6 @@ public class KoboSettingsController {
private final KoboSettingsService koboService;
@GetMapping
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> 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<Void> toggleSync(@RequestParam boolean enabled) {
koboService.setSyncEnabled(enabled);
@@ -8,5 +8,5 @@ public class KoboSyncSettings {
private Long id;
private String userId;
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.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<ShelfEntity> 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;
}
}
@@ -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<ShelfEntity> koboShelf = shelfRepository.findByUserIdAndName(userId, ShelfType.KOBO.getName());
return koboShelf.map(shelfMapper::toShelf).orElse(null);
}
public List<Book> getShelfBooks(Long shelfId) {
@@ -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<Shelf[]> {
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 => {
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<Shelf> {
return this.http.post<Shelf>(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();
})
);
@@ -1,7 +1,7 @@
<p-confirmDialog></p-confirmDialog>
<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"
pTooltip="Click to view Kobo setup documentation"
tooltipPosition="right"
@@ -12,42 +12,53 @@
@if (hasKoboTokenPermission) {
<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 gap-1 max-w-[33rem]">
<label for="koboToken">Kobo Sync Token</label>
<div class="flex items-center gap-2">
<input
pInputText
id="koboToken"
[(ngModel)]="koboToken"
[type]="showToken ? 'text' : 'password'"
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 class="flex flex-col p-4 space-y-6">
<div class="flex gap-2">
<p-toggle-switch
id="syncEnabled"
name="syncEnabled"
[(ngModel)]="koboSyncSettings.syncEnabled"
(ngModelChange)="onSyncToggle()">
</p-toggle-switch>
<label for="syncEnabled">Enable Kobo Sync</label>
</div>
<p-button
icon="pi pi-refresh"
outlined="true"
severity="warn"
label="Regenerate Token"
(onClick)="confirmRegenerateToken()"
[disabled]="!credentialsSaved">
</p-button>
@if (koboSyncSettings.syncEnabled) {
<div class="flex flex-col gap-1 max-w-[33rem]">
<label for="koboToken">Kobo Sync Token</label>
<div class="flex items-center gap-2">
<input
pInputText
id="koboToken"
[(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>
</form>
@@ -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<void>();
private readonly sliderChange$ = new Subject<void>();
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({
@@ -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<KoboSyncSettings> {
return this.http.get<KoboSyncSettings>(`${this.baseUrl}`);
}
createOrUpdateToken(): Observable<KoboSyncSettings> {
return this.http.put<KoboSyncSettings>(`${this.baseUrl}`, null);
}
getUser(): Observable<KoboSyncSettings> {
return this.http.get<KoboSyncSettings>(`${this.baseUrl}`);
toggleSync(enabled: boolean): Observable<void> {
const params = new HttpParams().set('enabled', enabled.toString());
return this.http.put<void>(`${this.baseUrl}/sync`, null, { params });
}
}