feat(bookmark): implement bookmark management with CRUD operations (#1795)
* feat(bookmark): implement bookmark management with CRUD operations and UI integration Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(bookmark): add uniqueness constraint for bookmarks and check for existing bookmarks before creation Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package com.adityachandel.booklore.controller;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMark;
|
||||||
|
import com.adityachandel.booklore.model.dto.CreateBookMarkRequest;
|
||||||
|
import com.adityachandel.booklore.service.book.BookMarkService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RequestMapping("/api/v1/bookmarks")
|
||||||
|
@Tag(name = "Bookmarks", description = "Endpoints for managing book bookmarks")
|
||||||
|
public class BookMarkController {
|
||||||
|
|
||||||
|
private final BookMarkService bookMarkService;
|
||||||
|
|
||||||
|
@Operation(summary = "Get bookmarks for a book", description = "Retrieve all bookmarks for a specific book.")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Bookmarks returned successfully")
|
||||||
|
@GetMapping("/book/{bookId}")
|
||||||
|
public List<BookMark> getBookmarksForBook(
|
||||||
|
@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||||
|
return bookMarkService.getBookmarksForBook(bookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Create a bookmark", description = "Create a new bookmark for a book.")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Bookmark created successfully")
|
||||||
|
@PostMapping
|
||||||
|
public BookMark createBookmark(
|
||||||
|
@Parameter(description = "Bookmark creation request") @Valid @RequestBody CreateBookMarkRequest request) {
|
||||||
|
return bookMarkService.createBookmark(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Delete a bookmark", description = "Delete a specific bookmark by its ID.")
|
||||||
|
@ApiResponse(responseCode = "204", description = "Bookmark deleted successfully")
|
||||||
|
@DeleteMapping("/{bookmarkId}")
|
||||||
|
public ResponseEntity<Void> deleteBookmark(
|
||||||
|
@Parameter(description = "ID of the bookmark to delete") @PathVariable Long bookmarkId) {
|
||||||
|
bookMarkService.deleteBookmark(bookmarkId);
|
||||||
|
return ResponseEntity.noContent().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.adityachandel.booklore.mapper;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMark;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMarkEntity;
|
||||||
|
import org.mapstruct.Mapper;
|
||||||
|
import org.mapstruct.Mapping;
|
||||||
|
|
||||||
|
@Mapper(componentModel = "spring")
|
||||||
|
public interface BookMarkMapper {
|
||||||
|
BookMark toDto(BookMarkEntity entity);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class BookMark {
|
||||||
|
private Long id;
|
||||||
|
private Long bookId;
|
||||||
|
private String cfi;
|
||||||
|
private String title;
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
|
import jakarta.validation.constraints.NotNull;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class CreateBookMarkRequest {
|
||||||
|
@NotNull
|
||||||
|
private Long bookId;
|
||||||
|
@NotEmpty
|
||||||
|
private String cfi;
|
||||||
|
private String title;
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package com.adityachandel.booklore.model.entity;
|
||||||
|
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
import org.hibernate.annotations.CreationTimestamp;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Table(name = "book_marks")
|
||||||
|
public class BookMarkEntity {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
|
private BookLoreUserEntity user;
|
||||||
|
|
||||||
|
@Column(name = "user_id", insertable = false, updatable = false)
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
@ManyToOne(fetch = FetchType.LAZY)
|
||||||
|
@JoinColumn(name = "book_id", nullable = false)
|
||||||
|
private BookEntity book;
|
||||||
|
|
||||||
|
@Column(name = "book_id", insertable = false, updatable = false)
|
||||||
|
private Long bookId;
|
||||||
|
|
||||||
|
@Column(name = "cfi", nullable = false, length = 1000)
|
||||||
|
private String cfi;
|
||||||
|
|
||||||
|
@Column(name = "title")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@CreationTimestamp
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
-1
@@ -32,7 +32,6 @@ public class MagicShelfEntity {
|
|||||||
|
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
@Column(name = "icon_type", nullable = false)
|
@Column(name = "icon_type", nullable = false)
|
||||||
|
|
||||||
@Builder.Default
|
@Builder.Default
|
||||||
private IconType iconType = IconType.PRIME_NG;
|
private IconType iconType = IconType.PRIME_NG;
|
||||||
|
|
||||||
|
|||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.adityachandel.booklore.repository;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMarkEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.data.jpa.repository.Query;
|
||||||
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface BookMarkRepository extends JpaRepository<BookMarkEntity, Long> {
|
||||||
|
|
||||||
|
Optional<BookMarkEntity> findByIdAndUserId(Long id, Long userId);
|
||||||
|
|
||||||
|
@Query("SELECT b FROM BookMarkEntity b WHERE b.bookId = :bookId AND b.userId = :userId ORDER BY b.createdAt DESC")
|
||||||
|
List<BookMarkEntity> findByBookIdAndUserIdOrderByCreatedAtDesc(@Param("bookId") Long bookId, @Param("userId") Long userId);
|
||||||
|
|
||||||
|
boolean existsByCfiAndBookIdAndUserId(String cfi, Long bookId, Long userId);
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package com.adityachandel.booklore.service.book;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.mapper.BookMarkMapper;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMark;
|
||||||
|
import com.adityachandel.booklore.model.dto.CreateBookMarkRequest;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMarkEntity;
|
||||||
|
import com.adityachandel.booklore.repository.BookMarkRepository;
|
||||||
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
|
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BookMarkService {
|
||||||
|
|
||||||
|
private final BookMarkRepository bookMarkRepository;
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final BookMarkMapper mapper;
|
||||||
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@Transactional(readOnly = true)
|
||||||
|
public List<BookMark> getBookmarksForBook(Long bookId) {
|
||||||
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
return bookMarkRepository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)
|
||||||
|
.stream()
|
||||||
|
.map(mapper::toDto)
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public BookMark createBookmark(CreateBookMarkRequest request) {
|
||||||
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
|
||||||
|
// Check for existing bookmark
|
||||||
|
if (bookMarkRepository.existsByCfiAndBookIdAndUserId(request.getCfi(), request.getBookId(), userId)) {
|
||||||
|
throw new IllegalArgumentException("Bookmark already exists at this location");
|
||||||
|
}
|
||||||
|
|
||||||
|
BookLoreUserEntity currentUser = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
|
||||||
|
|
||||||
|
BookEntity book = bookRepository.findById(request.getBookId())
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + request.getBookId()));
|
||||||
|
|
||||||
|
BookMarkEntity entity = BookMarkEntity.builder()
|
||||||
|
.user(currentUser)
|
||||||
|
.book(book)
|
||||||
|
.cfi(request.getCfi())
|
||||||
|
.title(request.getTitle())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
BookMarkEntity saved = bookMarkRepository.save(entity);
|
||||||
|
return mapper.toDto(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteBookmark(Long bookmarkId) {
|
||||||
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
BookMarkEntity bookmark = bookMarkRepository.findByIdAndUserId(bookmarkId, userId)
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("Bookmark not found: " + bookmarkId));
|
||||||
|
bookMarkRepository.delete(bookmark);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
CREATE TABLE book_marks
|
||||||
|
(
|
||||||
|
id BIGINT AUTO_INCREMENT NOT NULL,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
book_id BIGINT NOT NULL,
|
||||||
|
cfi VARCHAR(1000) NOT NULL,
|
||||||
|
title VARCHAR(255) NULL,
|
||||||
|
created_at datetime NOT NULL,
|
||||||
|
CONSTRAINT pk_book_marks PRIMARY KEY (id),
|
||||||
|
CONSTRAINT uq_user_book_cfi UNIQUE (user_id, book_id, cfi)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_book_marks_user_id ON book_marks (user_id);
|
||||||
|
CREATE INDEX idx_book_marks_book_id ON book_marks (book_id);
|
||||||
|
|
||||||
|
ALTER TABLE book_marks
|
||||||
|
ADD CONSTRAINT fk_book_marks_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
|
||||||
|
|
||||||
|
ALTER TABLE book_marks
|
||||||
|
ADD CONSTRAINT fk_book_marks_book_id FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE;
|
||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||||
|
import com.adityachandel.booklore.mapper.BookMarkMapper;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookMark;
|
||||||
|
import com.adityachandel.booklore.model.dto.CreateBookMarkRequest;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookMarkEntity;
|
||||||
|
import com.adityachandel.booklore.repository.BookMarkRepository;
|
||||||
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
|
import com.adityachandel.booklore.service.book.BookMarkService;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class BookMarkServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BookMarkRepository bookMarkRepository;
|
||||||
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
@Mock
|
||||||
|
private UserRepository userRepository;
|
||||||
|
@Mock
|
||||||
|
private BookMarkMapper mapper;
|
||||||
|
@Mock
|
||||||
|
private AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BookMarkService bookMarkService;
|
||||||
|
|
||||||
|
private final Long userId = 1L;
|
||||||
|
private final Long bookId = 100L;
|
||||||
|
private final Long bookmarkId = 50L;
|
||||||
|
private BookLoreUser userDto;
|
||||||
|
private BookLoreUserEntity userEntity;
|
||||||
|
private BookEntity bookEntity;
|
||||||
|
private BookMarkEntity bookmarkEntity;
|
||||||
|
private BookMark bookmarkDto;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
userDto = BookLoreUser.builder().id(userId).build();
|
||||||
|
userEntity = BookLoreUserEntity.builder().id(userId).build();
|
||||||
|
bookEntity = BookEntity.builder().id(bookId).build();
|
||||||
|
bookmarkEntity = BookMarkEntity.builder().id(bookmarkId).user(userEntity).book(bookEntity).cfi("cfi").title("title").build();
|
||||||
|
bookmarkDto = BookMark.builder().id(bookmarkId).bookId(bookId).cfi("cfi").title("title").build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getBookmarksForBook_Success() {
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||||
|
when(bookMarkRepository.findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId)).thenReturn(List.of(bookmarkEntity));
|
||||||
|
when(mapper.toDto(bookmarkEntity)).thenReturn(bookmarkDto);
|
||||||
|
|
||||||
|
List<BookMark> result = bookMarkService.getBookmarksForBook(bookId);
|
||||||
|
|
||||||
|
assertNotNull(result);
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(bookmarkId, result.get(0).getId());
|
||||||
|
verify(bookMarkRepository).findByBookIdAndUserIdOrderByCreatedAtDesc(bookId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createBookmark_Success() {
|
||||||
|
CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark");
|
||||||
|
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||||
|
when(userRepository.getReferenceById(userId)).thenReturn(userEntity);
|
||||||
|
when(bookRepository.findById(bookId)).thenReturn(Optional.of(bookEntity));
|
||||||
|
when(bookMarkRepository.save(any(BookMarkEntity.class))).thenReturn(bookmarkEntity);
|
||||||
|
when(mapper.toDto(bookmarkEntity)).thenReturn(bookmarkDto);
|
||||||
|
|
||||||
|
BookMark result = bookMarkService.createBookmark(request);
|
||||||
|
|
||||||
|
assertNotNull(result);
|
||||||
|
assertEquals(bookmarkId, result.getId());
|
||||||
|
verify(bookMarkRepository).save(any(BookMarkEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createBookmark_BookNotFound() {
|
||||||
|
CreateBookMarkRequest request = new CreateBookMarkRequest(bookId, "new-cfi", "New Bookmark");
|
||||||
|
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||||
|
when(userRepository.getReferenceById(userId)).thenReturn(userEntity);
|
||||||
|
when(bookRepository.findById(bookId)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
assertThrows(EntityNotFoundException.class, () -> bookMarkService.createBookmark(request));
|
||||||
|
verify(bookMarkRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteBookmark_Success() {
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||||
|
when(bookMarkRepository.findByIdAndUserId(bookmarkId, userId)).thenReturn(Optional.of(bookmarkEntity));
|
||||||
|
|
||||||
|
bookMarkService.deleteBookmark(bookmarkId);
|
||||||
|
|
||||||
|
verify(bookMarkRepository).delete(bookmarkEntity);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteBookmark_NotFound() {
|
||||||
|
when(authenticationService.getAuthenticatedUser()).thenReturn(userDto);
|
||||||
|
when(bookMarkRepository.findByIdAndUserId(bookmarkId, userId)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
assertThrows(EntityNotFoundException.class, () -> bookMarkService.deleteBookmark(bookmarkId));
|
||||||
|
verify(bookMarkRepository, never()).delete(any());
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
-1
@@ -12,7 +12,9 @@
|
|||||||
<div class="progress-info">
|
<div class="progress-info">
|
||||||
<span class="progress-percentage"><span class="progress-label">Progress: </span>{{ progressPercentage }}%</span>
|
<span class="progress-percentage"><span class="progress-label">Progress: </span>{{ progressPercentage }}%</span>
|
||||||
</div>
|
</div>
|
||||||
<p-drawer [(visible)]="isDrawerVisible" [modal]="true" [position]="'left'" header="Chapters">
|
<p-drawer [(visible)]="isDrawerVisible" [modal]="true" [position]="'left'" header="Table of Contents">
|
||||||
|
<div class="mb-3">
|
||||||
|
<h3 class="text-base font-semibold mb-2">Chapters</h3>
|
||||||
<ul class="chapter-list">
|
<ul class="chapter-list">
|
||||||
@for (chapter of chapters; track chapter) {
|
@for (chapter of chapters; track chapter) {
|
||||||
<li (click)="navigateToChapter(chapter); $event.stopPropagation()"
|
<li (click)="navigateToChapter(chapter); $event.stopPropagation()"
|
||||||
@@ -23,6 +25,36 @@
|
|||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
</ul>
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p-divider></p-divider>
|
||||||
|
|
||||||
|
<div class="mt-3">
|
||||||
|
<h3 class="text-base font-semibold mb-2">Bookmarks</h3>
|
||||||
|
@if (bookmarks.length === 0) {
|
||||||
|
<p class="text-sm text-gray-400 italic">No bookmarks yet</p>
|
||||||
|
} @else {
|
||||||
|
<ul class="bookmark-list">
|
||||||
|
@for (bookmark of bookmarks; track bookmark.id) {
|
||||||
|
<li class="bookmark-item">
|
||||||
|
<div class="bookmark-content" (click)="navigateToBookmark(bookmark); $event.stopPropagation()">
|
||||||
|
<i class="pi pi-bookmark-fill mr-2"></i>
|
||||||
|
<span>{{ bookmark.title }}</span>
|
||||||
|
</div>
|
||||||
|
<p-button
|
||||||
|
icon="pi pi-trash"
|
||||||
|
(click)="deleteBookmark(bookmark.id); $event.stopPropagation()"
|
||||||
|
[rounded]="true"
|
||||||
|
[text]="true"
|
||||||
|
severity="danger"
|
||||||
|
size="small"
|
||||||
|
pTooltip="Delete bookmark">
|
||||||
|
</p-button>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
</p-drawer>
|
</p-drawer>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -32,6 +64,14 @@
|
|||||||
|
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
<div class="flex gap-4">
|
<div class="flex gap-4">
|
||||||
|
<p-button
|
||||||
|
size="small"
|
||||||
|
[icon]="isBookmarked ? 'pi pi-bookmark-fill' : 'pi pi-bookmark'"
|
||||||
|
(click)="addBookmark()"
|
||||||
|
severity="secondary"
|
||||||
|
[disabled]="!currentCfi || isAddingBookmark"
|
||||||
|
pTooltip="Add bookmark">
|
||||||
|
</p-button>
|
||||||
@if (!locationsReady) {
|
@if (!locationsReady) {
|
||||||
<div class="location-indicator" pTooltip="Saving progress not ready yet">
|
<div class="location-indicator" pTooltip="Saving progress not ready yet">
|
||||||
<span class="dot"></span>
|
<span class="dot"></span>
|
||||||
|
|||||||
@@ -163,6 +163,46 @@
|
|||||||
border-radius: 0.45rem;
|
border-radius: 0.45rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.bookmark-list {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookmark-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: 0.35rem;
|
||||||
|
background-color: color-mix(in srgb, var(--primary-color) 10%, transparent);
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background-color: color-mix(in srgb, var(--primary-color) 20%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.bookmark-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
cursor: pointer;
|
||||||
|
flex: 1;
|
||||||
|
color: var(--text-color);
|
||||||
|
font-size: 14px;
|
||||||
|
|
||||||
|
i {
|
||||||
|
color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--primary-color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.location-indicator {
|
.location-indicator {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
+107
-3
@@ -1,6 +1,7 @@
|
|||||||
import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild, NgZone} from '@angular/core';
|
import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild, NgZone} from '@angular/core';
|
||||||
import ePub from 'epubjs';
|
import ePub from 'epubjs';
|
||||||
import {Drawer} from 'primeng/drawer';
|
import {Drawer} from 'primeng/drawer';
|
||||||
|
import {Subscription} from 'rxjs';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
|
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
@@ -12,6 +13,7 @@ import {Select} from 'primeng/select';
|
|||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {BookMarkService, BookMark} from '../../../../shared/service/book-mark.service';
|
||||||
import {Tooltip} from 'primeng/tooltip';
|
import {Tooltip} from 'primeng/tooltip';
|
||||||
import {Slider} from 'primeng/slider';
|
import {Slider} from 'primeng/slider';
|
||||||
import {FALLBACK_EPUB_SETTINGS, getChapter} from '../epub-reader-helper';
|
import {FALLBACK_EPUB_SETTINGS, getChapter} from '../epub-reader-helper';
|
||||||
@@ -36,6 +38,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
currentChapterHref: string | null = null;
|
currentChapterHref: string | null = null;
|
||||||
isDrawerVisible = false;
|
isDrawerVisible = false;
|
||||||
isSettingsDrawerVisible = false;
|
isSettingsDrawerVisible = false;
|
||||||
|
bookmarks: BookMark[] = [];
|
||||||
|
currentCfi: string | null = null;
|
||||||
|
isBookmarked = false;
|
||||||
|
isAddingBookmark = false;
|
||||||
|
isDeletingBookmark = false;
|
||||||
|
private routeSubscription?: Subscription;
|
||||||
|
|
||||||
public locationsReady = false;
|
public locationsReady = false;
|
||||||
public approxProgress = 0;
|
public approxProgress = 0;
|
||||||
@@ -80,11 +88,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private ngZone = inject(NgZone);
|
private ngZone = inject(NgZone);
|
||||||
private pageTitle = inject(PageTitleService);
|
private pageTitle = inject(PageTitleService);
|
||||||
|
private bookMarkService = inject(BookMarkService);
|
||||||
|
|
||||||
epub!: Book;
|
epub!: Book;
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.route.paramMap.subscribe((params) => {
|
this.routeSubscription = this.route.paramMap.subscribe((params) => {
|
||||||
this.isLoading = true;
|
this.isLoading = true;
|
||||||
const bookId = +params.get('bookId')!;
|
const bookId = +params.get('bookId')!;
|
||||||
|
|
||||||
@@ -92,10 +101,13 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
const epub$ = this.bookService.getBookByIdFromAPI(bookId, false);
|
const epub$ = this.bookService.getBookByIdFromAPI(bookId, false);
|
||||||
const epubData$ = this.bookService.getFileContent(bookId);
|
const epubData$ = this.bookService.getFileContent(bookId);
|
||||||
const bookSetting$ = this.bookService.getBookSetting(bookId);
|
const bookSetting$ = this.bookService.getBookSetting(bookId);
|
||||||
|
const bookmarks$ = this.bookMarkService.getBookmarksForBook(bookId);
|
||||||
|
|
||||||
forkJoin([myself$, epub$, epubData$, bookSetting$]).subscribe({
|
forkJoin([myself$, epub$, epubData$, bookSetting$, bookmarks$]).subscribe({
|
||||||
next: ([myself, epub, epubData, bookSetting]) => {
|
next: ([myself, epub, epubData, bookSetting, bookmarks]) => {
|
||||||
this.epub = epub;
|
this.epub = epub;
|
||||||
|
this.bookmarks = bookmarks;
|
||||||
|
this.updateBookmarkStatus();
|
||||||
const individualSetting = bookSetting?.epubSettings;
|
const individualSetting = bookSetting?.epubSettings;
|
||||||
const fileReader = new FileReader();
|
const fileReader = new FileReader();
|
||||||
|
|
||||||
@@ -363,6 +375,8 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.rendition.on('relocated', (location: any) => {
|
this.rendition.on('relocated', (location: any) => {
|
||||||
this.updateCurrentChapter(location);
|
this.updateCurrentChapter(location);
|
||||||
const cfi = location.end.cfi;
|
const cfi = location.end.cfi;
|
||||||
|
this.currentCfi = location.start.cfi;
|
||||||
|
this.updateBookmarkStatus();
|
||||||
const currentIndex = location.start.index;
|
const currentIndex = location.start.index;
|
||||||
const totalSpineItems = this.book.spine.items.length;
|
const totalSpineItems = this.book.spine.items.length;
|
||||||
let percentage: number;
|
let percentage: number;
|
||||||
@@ -400,6 +414,8 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
|
this.routeSubscription?.unsubscribe();
|
||||||
|
|
||||||
if (this.rendition) {
|
if (this.rendition) {
|
||||||
this.rendition.off('keyup', this.keyListener);
|
this.rendition.off('keyup', this.keyListener);
|
||||||
}
|
}
|
||||||
@@ -472,4 +488,92 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
|
|||||||
|
|
||||||
return chapters;
|
return chapters;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addBookmark(): void {
|
||||||
|
if (!this.currentCfi || this.isAddingBookmark) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isCurrentLocationBookmarked()) {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'info',
|
||||||
|
summary: 'Info',
|
||||||
|
detail: 'Bookmark already exists at this location',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isAddingBookmark = true;
|
||||||
|
const title = this.currentChapter || 'Untitled Bookmark';
|
||||||
|
const request = {
|
||||||
|
bookId: this.epub.id,
|
||||||
|
cfi: this.currentCfi,
|
||||||
|
title: title
|
||||||
|
};
|
||||||
|
|
||||||
|
this.bookMarkService.createBookmark(request).subscribe({
|
||||||
|
next: (bookmark) => {
|
||||||
|
this.bookmarks.push(bookmark);
|
||||||
|
this.updateBookmarkStatus();
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Success',
|
||||||
|
detail: 'Bookmark created successfully',
|
||||||
|
});
|
||||||
|
this.isAddingBookmark = false;
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Error',
|
||||||
|
detail: 'Failed to create bookmark',
|
||||||
|
});
|
||||||
|
this.isAddingBookmark = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteBookmark(bookmarkId: number): void {
|
||||||
|
if (this.isDeletingBookmark) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.isDeletingBookmark = true;
|
||||||
|
this.bookMarkService.deleteBookmark(bookmarkId).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
|
||||||
|
this.updateBookmarkStatus();
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Success',
|
||||||
|
detail: 'Bookmark deleted successfully',
|
||||||
|
});
|
||||||
|
this.isDeletingBookmark = false;
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Error',
|
||||||
|
detail: 'Failed to delete bookmark',
|
||||||
|
});
|
||||||
|
this.isDeletingBookmark = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
navigateToBookmark(bookmark: BookMark): void {
|
||||||
|
if (this.rendition && bookmark.cfi) {
|
||||||
|
this.rendition.display(bookmark.cfi);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isCurrentLocationBookmarked(): boolean {
|
||||||
|
if (!this.currentCfi) return false;
|
||||||
|
return this.bookmarks.some(b => b.cfi === this.currentCfi);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateBookmarkStatus(): void {
|
||||||
|
this.isBookmarked = this.currentCfi
|
||||||
|
? this.bookmarks.some(b => b.cfi === this.currentCfi)
|
||||||
|
: false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import {Injectable, inject} from '@angular/core';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {API_CONFIG} from '../../core/config/api-config';
|
||||||
|
|
||||||
|
export interface BookMark {
|
||||||
|
id: number;
|
||||||
|
bookId: number;
|
||||||
|
cfi: string;
|
||||||
|
title: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateBookMarkRequest {
|
||||||
|
bookId: number;
|
||||||
|
cfi: string;
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class BookMarkService {
|
||||||
|
|
||||||
|
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/bookmarks`;
|
||||||
|
private readonly http = inject(HttpClient);
|
||||||
|
|
||||||
|
getBookmarksForBook(bookId: number): Observable<BookMark[]> {
|
||||||
|
return this.http.get<BookMark[]>(`${this.url}/book/${bookId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
createBookmark(request: CreateBookMarkRequest): Observable<BookMark> {
|
||||||
|
return this.http.post<BookMark>(this.url, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteBookmark(bookmarkId: number): Observable<void> {
|
||||||
|
return this.http.delete<void>(`${this.url}/${bookmarkId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user