Implement magic shelves with dynamic rule-based filters

This commit is contained in:
aditya.chandel
2025-07-28 07:59:00 -06:00
committed by Aditya Chandel
parent 0777d473dc
commit 63518b7eb8
36 changed files with 1767 additions and 65 deletions
@@ -67,7 +67,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
}
} catch (Exception e) {
log.error("Token authentication failed", e);
log.debug("Token authentication failed", e);
}
return null;
}
@@ -0,0 +1,41 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.service.MagicShelfService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/magic-shelves")
public class MagicShelfController {
private final MagicShelfService magicShelfService;
public MagicShelfController(MagicShelfService magicShelfService) {
this.magicShelfService = magicShelfService;
}
@GetMapping
public ResponseEntity<List<MagicShelf>> getAllForUser() {
return ResponseEntity.ok(magicShelfService.getUserShelves());
}
@GetMapping("/{id}")
public ResponseEntity<MagicShelf> getShelf(@PathVariable Long id) {
return ResponseEntity.ok(magicShelfService.getShelf(id));
}
@PostMapping
public ResponseEntity<MagicShelf> createUpdateShelf(@Valid @RequestBody MagicShelf shelf) {
return ResponseEntity.ok(magicShelfService.createOrUpdateShelf(shelf));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteShelf(@PathVariable Long id) {
magicShelfService.deleteShelf(id);
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class MagicShelf {
private Long id;
@NotBlank(message = "Shelf name must not be blank")
@Size(max = 255, message = "Shelf name must not exceed 255 characters")
private String name;
@NotBlank(message = "Icon must not be blank")
@Size(max = 64, message = "Icon must not exceed 64 characters")
private String icon;
@NotNull(message = "Filter JSON must not be null")
@Size(min = 2, message = "Filter JSON must not be empty")
private String filterJson;
}
@@ -0,0 +1,45 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "magic_shelf", uniqueConstraints = {
@UniqueConstraint(columnNames = {"user_id", "name"})
})
public class MagicShelfEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id", nullable = false)
private Long userId;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String icon;
@Column(name = "filter_json", columnDefinition = "json", nullable = false)
private String filterJson;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt = LocalDateTime.now();
@PreUpdate
public void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface MagicShelfRepository extends JpaRepository<MagicShelfEntity, Long> {
List<MagicShelfEntity> findAllByUserId(Long userId);
Optional<MagicShelfEntity> findByUserIdAndName(Long userId, String name);
boolean existsByUserIdAndName(Long userId, String name);
}
@@ -0,0 +1,79 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
import com.adityachandel.booklore.repository.MagicShelfRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@AllArgsConstructor
@Service
public class MagicShelfService {
private final MagicShelfRepository repository;
private final AuthenticationService authenticationService;
public List<MagicShelf> getUserShelves() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return repository.findAllByUserId(userId).stream()
.map(this::toDto)
.toList();
}
@Transactional
public MagicShelf createOrUpdateShelf(MagicShelf dto) {
Long userId = authenticationService.getAuthenticatedUser().getId();
if (dto.getId() != null) {
MagicShelfEntity existing = repository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
if (!existing.getUserId().equals(userId)) {
throw new SecurityException("You are not authorized to update this shelf");
}
existing.setName(dto.getName());
existing.setIcon(dto.getIcon());
existing.setFilterJson(dto.getFilterJson());
return toDto(repository.save(existing));
}
if (repository.existsByUserIdAndName(userId, dto.getName())) {
throw new IllegalArgumentException("A shelf with the same name already exists for this user.");
}
return toDto(repository.save(toEntity(dto, userId)));
}
@Transactional
public void deleteShelf(Long id) {
Long userId = authenticationService.getAuthenticatedUser().getId();
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
if (!shelf.getUserId().equals(userId)) {
throw new SecurityException("You are not authorized to delete this shelf");
}
repository.deleteById(id);
}
private MagicShelf toDto(MagicShelfEntity entity) {
MagicShelf dto = new MagicShelf();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setIcon(entity.getIcon());
dto.setFilterJson(entity.getFilterJson());
return dto;
}
private MagicShelfEntity toEntity(MagicShelf dto, Long userId) {
MagicShelfEntity entity = new MagicShelfEntity();
entity.setId(dto.getId());
entity.setName(dto.getName());
entity.setIcon(dto.getIcon());
entity.setFilterJson(dto.getFilterJson());
entity.setUserId(userId);
return entity;
}
public MagicShelf getShelf(Long id) {
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
return toDto(shelf);
}
}
@@ -63,7 +63,7 @@ public class MetadataMatchService {
if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount();
if (isPresent(metadata.getThumbnail())) score += weights.getCoverImage();
return score / totalWeight;
return (score / totalWeight) * 100f;
}
private boolean isPresent(String value) {
@@ -51,7 +51,7 @@ public class AppMigrationService {
@Transactional
public void populateMetadataScoresOnce() {
if (migrationRepository.existsById("populateMetadataScores")) return;
if (migrationRepository.existsById("populateMetadataScores_v2")) return;
List<BookEntity> books = bookQueryService.getAllFullBookEntities();
for (BookEntity book : books) {
@@ -60,8 +60,8 @@ public class AppMigrationService {
}
bookRepository.saveAll(books);
log.info("Migration 'populateMetadataScores' applied to {} books.", books.size());
migrationRepository.save(new AppMigrationEntity("populateMetadataScores", LocalDateTime.now(), "Calculate and store metadata match score for all books"));
log.info("Migration 'populateMetadataScores_v2' applied to {} books.", books.size());
migrationRepository.save(new AppMigrationEntity("populateMetadataScores_v2", LocalDateTime.now(), "Calculate and store metadata match score for all books"));
}
@Transactional
@@ -0,0 +1,11 @@
CREATE TABLE magic_shelf
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
icon VARCHAR(64) NOT NULL,
filter_json JSON NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_user_name (user_id, name)
);