Checkpoint
This commit is contained in:
@@ -41,6 +41,7 @@ dependencies {
|
||||
implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0'
|
||||
implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.3.0'
|
||||
implementation 'org.apache.pdfbox:jbig2-imageio:3.0.3'
|
||||
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2'
|
||||
}
|
||||
|
||||
hibernate {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class ObjectMapperConfig {
|
||||
|
||||
/*@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.registerModule(new JavaTimeModule());
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
return objectMapper;
|
||||
}*/
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.model.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.service.AuthorService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
+20
-16
@@ -1,23 +1,20 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.dto.BookDTO;
|
||||
import com.adityachandel.booklore.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.exception.ErrorCode;
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.model.dto.response.GoogleBooksMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.SetMetadataRequest;
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
@RequestMapping("/v1/book")
|
||||
@RestController
|
||||
@@ -44,7 +41,6 @@ public class BookController {
|
||||
return ResponseEntity.ok(books);
|
||||
}
|
||||
|
||||
|
||||
@GetMapping("/search")
|
||||
public ResponseEntity<List<BookDTO>> searchBooks(@RequestParam String title) {
|
||||
List<BookDTO> books = booksService.search(title);
|
||||
@@ -53,14 +49,6 @@ public class BookController {
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Random random = new Random();
|
||||
int delay = 50 + random.nextInt(250);
|
||||
try {
|
||||
Thread.sleep(delay);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
return ResponseEntity.ok(booksService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@@ -85,4 +73,20 @@ public class BookController {
|
||||
booksService.updateLastReadTime(bookId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/fetch-metadata")
|
||||
public ResponseEntity<List<GoogleBooksMetadata>> getBookFetchMetadata(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(booksService.fetchProspectiveMetadataListByBookId(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/fetch-metadata")
|
||||
public ResponseEntity<List<GoogleBooksMetadata>> fetchMedataByTerm(@RequestParam String term) {
|
||||
return ResponseEntity.ok(booksService.fetchProspectiveMetadataListBySearchTerm(term));
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/set-metadata")
|
||||
public ResponseEntity<Void> setBookMetadata(@RequestBody SetMetadataRequest setMetadataRequest, @PathVariable long bookId) {
|
||||
booksService.setMetadata(setMetadataRequest, bookId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+12
-9
@@ -1,8 +1,8 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.dto.BookDTO;
|
||||
import com.adityachandel.booklore.dto.LibraryDTO;
|
||||
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.dto.LibraryDTO;
|
||||
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.service.LibraryService;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -20,9 +20,14 @@ public class LibraryController {
|
||||
|
||||
private LibraryService libraryService;
|
||||
|
||||
@PostMapping(consumes = "application/json", produces = "application/json")
|
||||
public SseEmitter createLibrary(@RequestBody CreateLibraryRequest request) {
|
||||
return libraryService.createLibrary(request);
|
||||
@PostMapping
|
||||
public ResponseEntity<LibraryDTO> createLibraryNew(@RequestBody CreateLibraryRequest request) {
|
||||
return ResponseEntity.ok(libraryService.createLibrary(request));
|
||||
}
|
||||
|
||||
@GetMapping(path = "/{libraryId}/parse")
|
||||
public SseEmitter parseLibrary(@RequestParam(required = false, defaultValue = "false") boolean force, @PathVariable long libraryId) {
|
||||
return libraryService.parseLibraryBooks(libraryId, force);
|
||||
}
|
||||
|
||||
@GetMapping("/{libraryId}")
|
||||
@@ -37,9 +42,7 @@ public class LibraryController {
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<Page<LibraryDTO>> getLibraries(
|
||||
@RequestParam(defaultValue = "0") @Min(0) int page,
|
||||
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
|
||||
public ResponseEntity<Page<LibraryDTO>> getLibraries(@RequestParam(defaultValue = "0") @Min(0) int page, @RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
|
||||
return ResponseEntity.ok(libraryService.getLibraries(page, size));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.adityachandel.booklore.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "author")
|
||||
public class Author {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "authors")
|
||||
private List<Book> books;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.enums.ParsingStatus;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class FileProcessResult {
|
||||
private LibraryFile libraryFile;
|
||||
private ParsingStatus parsingStatus;
|
||||
private BookDTO bookDTO;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class LibraryFile {
|
||||
private Library library;
|
||||
private String filePath;
|
||||
private String fileType;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.enums.ParsingStatus;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class ParseLibraryEvent {
|
||||
private long libraryId;
|
||||
private String file;
|
||||
private BookDTO book;
|
||||
private ParsingStatus parsingStatus;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.dto;
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
+2
-4
@@ -1,11 +1,9 @@
|
||||
package com.adityachandel.booklore.dto;
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@@ -16,5 +14,5 @@ public class BookDTO {
|
||||
private String title;
|
||||
private Instant lastReadTime;
|
||||
private Instant addedOn;
|
||||
private List<AuthorDTO> authors = new ArrayList<>();
|
||||
private BookMetadataDTO metadata;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class BookMetadataDTO {
|
||||
private Long bookId;
|
||||
private String googleBookId;
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String description;
|
||||
private String isbn13;
|
||||
private String isbn10;
|
||||
private Integer pageCount;
|
||||
private String thumbnail;
|
||||
private String language;
|
||||
private List<AuthorDTO> authors;
|
||||
private List<CategoryDTO> categories;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.dto;
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class CategoryDTO {
|
||||
private Long id;
|
||||
private String name;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.dto;
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
+3
-1
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.dto.request;
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -7,6 +8,7 @@ import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CreateLibraryRequest {
|
||||
private String name;
|
||||
private List<String> paths;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class SetMetadataRequest {
|
||||
private String googleBookId;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class GoogleBooksApiResponse {
|
||||
private List<Item> items;
|
||||
|
||||
@Data
|
||||
public static class Item {
|
||||
private String id;
|
||||
private VolumeInfo volumeInfo;
|
||||
|
||||
@Data
|
||||
public static class VolumeInfo {
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private List<String> authors;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String description;
|
||||
private List<IndustryIdentifier> industryIdentifiers;
|
||||
private Integer pageCount;
|
||||
private ImageLinks imageLinks;
|
||||
private String language;
|
||||
private List<String> categories;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class IndustryIdentifier {
|
||||
private String type;
|
||||
private String identifier;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ImageLinks {
|
||||
private String thumbnail;
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class GoogleBooksMetadata {
|
||||
private String googleBookId;
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String description;
|
||||
private String isbn13;
|
||||
private String isbn10;
|
||||
private Integer pageCount;
|
||||
private String thumbnail;
|
||||
private String language;
|
||||
private List<String> authors;
|
||||
private List<String> categories;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "author")
|
||||
public class Author {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "authors")
|
||||
private List<BookMetadata> bookMetadataList;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Author author = (Author) o;
|
||||
return Objects.equals(name, author.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name != null ? name.hashCode() : 0;
|
||||
}
|
||||
}
|
||||
+4
-12
@@ -1,10 +1,9 @@
|
||||
package com.adityachandel.booklore.entity;
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@@ -14,6 +13,7 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
@Table(name = "book")
|
||||
public class Book {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@@ -21,19 +21,11 @@ public class Book {
|
||||
@Column(name = "file_name", length = 1000)
|
||||
private String fileName;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
@Column(name = "path")
|
||||
private String path;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
name = "book_author_mapping",
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "author_id")
|
||||
)
|
||||
private List<Author> authors;
|
||||
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private BookMetadata metadata;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "library_id", nullable = false)
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "book_metadata")
|
||||
public class BookMetadata {
|
||||
|
||||
@Id
|
||||
@Column(name = "book_id")
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "google_book_id", nullable = false, unique = true)
|
||||
private String googleBookId;
|
||||
|
||||
@Column(name = "title", nullable = false)
|
||||
private String title;
|
||||
|
||||
@Column(name = "subtitle")
|
||||
private String subtitle;
|
||||
|
||||
@Column(name = "publisher")
|
||||
private String publisher;
|
||||
|
||||
@Column(name = "published_date")
|
||||
private String publishedDate;
|
||||
|
||||
@Column(name = "description", columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@Column(name = "isbn_13", length = 13)
|
||||
private String isbn13;
|
||||
|
||||
@Column(name = "isbn_10", length = 10)
|
||||
private String isbn10;
|
||||
|
||||
@Column(name = "page_count")
|
||||
private Integer pageCount;
|
||||
|
||||
@Column(name = "thumbnail", length = 1000)
|
||||
private String thumbnail;
|
||||
|
||||
@Column(name = "language", length = 10)
|
||||
private String language;
|
||||
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@MapsId
|
||||
@JoinColumn(name = "book_id")
|
||||
@JsonIgnore
|
||||
private Book book;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
name = "book_metadata_author_mapping",
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "author_id"))
|
||||
private List<Author> authors;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
name = "book_metadata_category_mapping",
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "category_id")
|
||||
)
|
||||
private List<Category> categories;
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.entity;
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "category")
|
||||
public class Category {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "name", nullable = false, unique = true)
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
|
||||
private List<BookMetadata> bookMetadataList;
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.entity;
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.convertor.PathsConverter;
|
||||
import jakarta.persistence.*;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.adityachandel.booklore.entity;
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
public class PathInfo {
|
||||
private String name;
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum ParsingStatus {
|
||||
PARSED_NEW_BOOK,
|
||||
EXISTING_BOOK_NO_FORCED_UPDATE,
|
||||
EXISTING_BOOK_FORCED_UPDATE,
|
||||
FAILED_TO_PARSE_BOOK,
|
||||
}
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.entity.Author;
|
||||
import com.adityachandel.booklore.model.entity.Author;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -14,8 +14,7 @@ public interface AuthorRepository extends JpaRepository<Author, Long> {
|
||||
|
||||
Optional<Author> findByName(String name);
|
||||
|
||||
@Query("SELECT a FROM Author a JOIN a.books b WHERE b.id = :bookId")
|
||||
@Query("SELECT a FROM Author a JOIN a.bookMetadataList bm WHERE bm.bookId = :bookId")
|
||||
List<Author> findAuthorsByBookId(@Param("bookId") Long bookId);
|
||||
|
||||
}
|
||||
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookMetadata;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface BookMetadataRepository extends JpaRepository<BookMetadata, Long> {
|
||||
}
|
||||
+7
-3
@@ -1,11 +1,12 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
import com.adityachandel.booklore.entity.Library;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
@@ -14,11 +15,14 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
|
||||
|
||||
Optional<Book> findByFileName(String fileName);
|
||||
|
||||
Page<Book> findBooksByLibraryId(Long libraryId, Pageable pageable);
|
||||
|
||||
Optional<Book> findBookByIdAndLibraryId(long id, long libraryId);
|
||||
|
||||
List<Book> findByTitleContainingIgnoreCase(String title);
|
||||
@Query("SELECT b FROM Book b JOIN b.metadata bm WHERE LOWER(bm.title) LIKE LOWER(CONCAT('%', :title, '%'))")
|
||||
List<Book> findByTitleContainingIgnoreCase(@Param("title") String title);
|
||||
|
||||
Page<Book> findByLastReadTimeIsNotNull(Pageable pageable);
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.entity.BookViewerSetting;
|
||||
import com.adityachandel.booklore.model.entity.BookViewerSetting;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.Category;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CategoryRepository extends JpaRepository<Category, Long> {
|
||||
|
||||
Optional<Category> findByName(String categoryName);
|
||||
}
|
||||
|
||||
+1
-3
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.entity.Library;
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
@@ -10,6 +10,4 @@ import java.util.List;
|
||||
@Repository
|
||||
public interface LibraryRepository extends JpaRepository<Library, Long>, JpaSpecificationExecutor<Library> {
|
||||
|
||||
List<Library> findByName(String name);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.entity.Author;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.model.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.model.entity.Author;
|
||||
import com.adityachandel.booklore.exception.ErrorCode;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.transformer.AuthorTransformer;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.Author;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.BookViewerSetting;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class BookCreatorService {
|
||||
|
||||
private AuthorRepository authorRepository;
|
||||
private BookRepository bookRepository;
|
||||
private BookMetadataRepository bookMetadataRepository;
|
||||
private BookViewerSettingRepository bookViewerSettingRepository;
|
||||
|
||||
public Book createShellBook(LibraryFile libraryFile) {
|
||||
File bookFile = new File(libraryFile.getFilePath());
|
||||
Book book = Book.builder().library(libraryFile.getLibrary()).path(bookFile.getPath()).fileName(bookFile.getName()).build();
|
||||
BookMetadata bookMetadata = BookMetadata.builder().build();
|
||||
BookViewerSetting bookViewerSetting = BookViewerSetting.builder()
|
||||
.book(book)
|
||||
.bookId(book.getId())
|
||||
.pageNumber(1)
|
||||
.sidebar_visible(true)
|
||||
.spread("odd")
|
||||
.zoom("page-fit")
|
||||
.build();
|
||||
book.setMetadata(bookMetadata);
|
||||
book.setViewerSetting(bookViewerSetting);
|
||||
return book;
|
||||
}
|
||||
|
||||
public void addAuthorsToBook(Set<String> authors, Book book) {
|
||||
for (String authorSrt : authors) {
|
||||
Optional<Author> authorOptional = authorRepository.findByName(authorSrt);
|
||||
Author author;
|
||||
if (authorOptional.isPresent()) {
|
||||
author = authorOptional.get();
|
||||
if(book.getMetadata().getAuthors() == null) {
|
||||
book.getMetadata().setAuthors(new ArrayList<>());
|
||||
}
|
||||
book.getMetadata().getAuthors().add(author);
|
||||
} else {
|
||||
author = Author.builder()
|
||||
.name(authorSrt)
|
||||
.build();
|
||||
author.setBookMetadataList(new ArrayList<>());
|
||||
book.getMetadata().setAuthors(new ArrayList<>());
|
||||
book.getMetadata().getAuthors().add(author);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void saveConnections(Book book) {
|
||||
if (book.getMetadata().getAuthors() != null && !book.getMetadata().getAuthors().isEmpty()) {
|
||||
authorRepository.saveAll(book.getMetadata().getAuthors());
|
||||
}
|
||||
bookRepository.save(book);
|
||||
bookMetadataRepository.save(book.getMetadata());
|
||||
bookViewerSettingRepository.save(book.getViewerSetting());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.dto.BookDTO;
|
||||
import com.adityachandel.booklore.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
import com.adityachandel.booklore.entity.BookViewerSetting;
|
||||
import com.adityachandel.booklore.entity.Library;
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.dto.response.GoogleBooksMetadata;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.model.dto.request.SetMetadataRequest;
|
||||
import com.adityachandel.booklore.exception.ErrorCode;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
|
||||
import com.adityachandel.booklore.service.parser.PdfParser;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.transformer.BookSettingTransformer;
|
||||
import com.adityachandel.booklore.transformer.BookTransformer;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -23,7 +21,6 @@ import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -31,10 +28,12 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -42,9 +41,12 @@ import java.util.stream.Stream;
|
||||
public class BooksService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final PdfParser pdfParser;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookViewerSettingRepository bookViewerSettingRepository;
|
||||
private final GoogleBookMetadataService googleBookMetadataService;
|
||||
private final BookMetadataRepository metadataRepository;
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
|
||||
|
||||
public BookDTO getBook(long bookId) {
|
||||
@@ -67,56 +69,6 @@ public class BooksService {
|
||||
return new PageImpl<>(bookDTOs, pageRequest, bookPage.getTotalElements());
|
||||
}
|
||||
|
||||
public List<Book> parseBooks(Library library, SseEmitter emitter) {
|
||||
List<Book> books = new ArrayList<>();
|
||||
for (String libraryPath : library.getPaths()) {
|
||||
books.addAll(parseBooks(libraryPath, emitter));
|
||||
}
|
||||
return books;
|
||||
}
|
||||
|
||||
private List<Book> parseBooks(String libraryPath, SseEmitter emitter) {
|
||||
List<Book> books = new ArrayList<>();
|
||||
try (Stream<Path> filePaths = Files.walk(Path.of(libraryPath))) {
|
||||
filePaths.filter(Files::isRegularFile).forEach(filePath -> handleFile(filePath, books, emitter));
|
||||
} catch (IOException e) {
|
||||
log.error("Error reading files from path: {}", libraryPath, e);
|
||||
throw ErrorCode.FILE_READ_ERROR.createException(libraryPath);
|
||||
}
|
||||
return books;
|
||||
}
|
||||
|
||||
private void handleFile(Path filePath, List<Book> books, SseEmitter emitter) {
|
||||
String fileName = filePath.getFileName().toString();
|
||||
if (fileName.endsWith(".pdf")) {
|
||||
sendSseEvent("Parsing: " + fileName, emitter);
|
||||
Book book = parsePdfBook(filePath);
|
||||
book.setPath(filePath.toAbsolutePath().toString());
|
||||
books.add(book);
|
||||
} else if (fileName.endsWith(".epub")) {
|
||||
log.info("EPUB File: {}", fileName);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendSseEvent(String message, SseEmitter emitter) {
|
||||
try {
|
||||
SseEmitter.SseEventBuilder event = SseEmitter.event()
|
||||
.data(message)
|
||||
.name("SSE Event");
|
||||
emitter.send(event);
|
||||
} catch (IOException e) {
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Book parsePdfBook(Path filePath) {
|
||||
Book book = pdfParser.parseBook(filePath.toAbsolutePath().toString(), appProperties.getPathConfig());
|
||||
book.setViewerSetting(BookViewerSetting.builder()
|
||||
.bookId(book.getId())
|
||||
.build());
|
||||
return book;
|
||||
}
|
||||
|
||||
public void saveBookViewerSetting(long bookId, BookViewerSettingDTO bookViewerSettingDTO) {
|
||||
BookViewerSetting bookViewerSetting = bookViewerSettingRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
|
||||
bookViewerSetting.setPageNumber(bookViewerSettingDTO.getPageNumber());
|
||||
@@ -128,7 +80,7 @@ public class BooksService {
|
||||
|
||||
public Resource getBookCover(long bookId) {
|
||||
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
|
||||
String thumbPath = appProperties.getPathConfig() + "/thumbs/" + PdfParser.getFileNameWithoutExtension(book.getFileName()) + ".jpg";
|
||||
String thumbPath = appProperties.getPathConfig() + "/thumbs/" + getFileNameWithoutExtension(book.getFileName()) + ".jpg";
|
||||
Path filePath = Paths.get(thumbPath);
|
||||
try {
|
||||
Resource resource = new UrlResource(filePath.toUri());
|
||||
@@ -165,4 +117,97 @@ public class BooksService {
|
||||
book.setLastReadTime(Instant.now());
|
||||
bookRepository.save(book);
|
||||
}
|
||||
|
||||
public List<GoogleBooksMetadata> fetchProspectiveMetadataListByBookId(long bookId) {
|
||||
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
|
||||
StringBuilder searchString = new StringBuilder();
|
||||
if (!book.getMetadata().getTitle().isEmpty()) {
|
||||
searchString.append(book.getMetadata().getTitle());
|
||||
}
|
||||
if (searchString.isEmpty()) {
|
||||
searchString.append(book.getFileName());
|
||||
}
|
||||
if (book.getMetadata().getAuthors() != null && !book.getMetadata().getAuthors().isEmpty()) {
|
||||
if (!searchString.isEmpty()) {
|
||||
searchString.append(" ");
|
||||
}
|
||||
searchString.append(book.getMetadata().getAuthors().stream()
|
||||
.map(Author::getName)
|
||||
.collect(Collectors.joining(", ")));
|
||||
}
|
||||
return googleBookMetadataService.queryByTerm(searchString.toString());
|
||||
}
|
||||
|
||||
public List<GoogleBooksMetadata> fetchProspectiveMetadataListBySearchTerm(String searchTerm) {
|
||||
return googleBookMetadataService.queryByTerm(searchTerm);
|
||||
}
|
||||
|
||||
public void setMetadata(SetMetadataRequest setMetadataRequest, long bookId) {
|
||||
Book book = bookRepository.findById(bookId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
|
||||
GoogleBooksMetadata gMetadata = googleBookMetadataService.getByGoogleBookId(setMetadataRequest.getGoogleBookId());
|
||||
BookMetadata metadata = book.getMetadata();
|
||||
metadata.setGoogleBookId(gMetadata.getGoogleBookId());
|
||||
metadata.setDescription(gMetadata.getDescription());
|
||||
metadata.setTitle(gMetadata.getTitle());
|
||||
metadata.setLanguage(gMetadata.getLanguage());
|
||||
metadata.setPublisher(gMetadata.getPublisher());
|
||||
String publishedDate = gMetadata.getPublishedDate();
|
||||
if (publishedDate != null && !publishedDate.isEmpty()) {
|
||||
String normalizeDate = normalizeDate(publishedDate);
|
||||
metadata.setPublishedDate(normalizeDate);
|
||||
}
|
||||
metadata.setSubtitle(gMetadata.getSubtitle());
|
||||
metadata.setPageCount(gMetadata.getPageCount());
|
||||
metadata.setThumbnail(gMetadata.getThumbnail());
|
||||
if (gMetadata.getAuthors() != null && !gMetadata.getAuthors().isEmpty()) {
|
||||
List<Author> authors = gMetadata.getAuthors().stream()
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(Author.builder().name(authorName).build())))
|
||||
.collect(Collectors.toList());
|
||||
metadata.setAuthors(authors);
|
||||
}
|
||||
if (gMetadata.getCategories() != null && !gMetadata.getCategories().isEmpty()) {
|
||||
List<Category> categories = gMetadata
|
||||
.getCategories()
|
||||
.stream()
|
||||
.map(c -> Arrays.stream(c.split("/"))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty() && !s.equalsIgnoreCase("General"))
|
||||
.toList())
|
||||
.flatMap(List::stream)
|
||||
.collect(Collectors.toSet())
|
||||
.stream()
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(Category.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toList());
|
||||
metadata.setCategories(categories);
|
||||
}
|
||||
metadata.setIsbn10(gMetadata.getIsbn10());
|
||||
metadata.setIsbn13(gMetadata.getIsbn13());
|
||||
authorRepository.saveAll(metadata.getAuthors());
|
||||
categoryRepository.saveAll(metadata.getCategories());
|
||||
metadataRepository.save(metadata);
|
||||
}
|
||||
|
||||
public String normalizeDate(String input) {
|
||||
DateTimeFormatter fullDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
if (input.matches("\\d{4}")) {
|
||||
return input + "-01-01";
|
||||
}
|
||||
try {
|
||||
LocalDate.parse(input, fullDateFormatter);
|
||||
return input;
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException("Invalid date format: " + input);
|
||||
}
|
||||
}
|
||||
|
||||
public String getFileNameWithoutExtension(String fileName) {
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex == -1) {
|
||||
return fileName;
|
||||
} else {
|
||||
return fileName.substring(0, dotIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
|
||||
public interface FileProcessor {
|
||||
FileProcessResult processFile(LibraryFile libraryFile, boolean forceProcess);
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.response.GoogleBooksApiResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.GoogleBooksMetadata;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GoogleBookMetadataService {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private static final String GOOGLE_BOOKS_API_URL = "https://www.googleapis.com/books/v1/volumes";
|
||||
|
||||
@SneakyThrows
|
||||
public List<GoogleBooksMetadata> queryByTerm(String term) {
|
||||
URI uri = UriComponentsBuilder.fromUriString(GOOGLE_BOOKS_API_URL).queryParam("q", term).build().toUri();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
List<GoogleBooksMetadata> googleBooksMetadataList = new ArrayList<>();
|
||||
if (response.statusCode() == 200) {
|
||||
GoogleBooksApiResponse googleBooksApiResponse = objectMapper.readValue(response.body(), GoogleBooksApiResponse.class);
|
||||
if (googleBooksApiResponse != null && googleBooksApiResponse.getItems() != null) {
|
||||
for (GoogleBooksApiResponse.Item item : googleBooksApiResponse.getItems()) {
|
||||
GoogleBooksMetadata googleBooksMetadata = handleItem(item);
|
||||
googleBooksMetadataList.add(googleBooksMetadata);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
System.out.println("Error: " + response.statusCode() + " - " + response.body());
|
||||
}
|
||||
return googleBooksMetadataList;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public GoogleBooksMetadata getByGoogleBookId(String googleBookId) {
|
||||
URI uri = UriComponentsBuilder.fromUriString(GOOGLE_BOOKS_API_URL + "/" + googleBookId)
|
||||
.build()
|
||||
.toUri();
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() == 200) {
|
||||
GoogleBooksApiResponse.Item item = objectMapper.readValue(response.body(), GoogleBooksApiResponse.Item.class);
|
||||
return handleItem(item);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private GoogleBooksMetadata handleItem(GoogleBooksApiResponse.Item item) {
|
||||
GoogleBooksApiResponse.Item.VolumeInfo volumeInfo = item.getVolumeInfo();
|
||||
GoogleBooksMetadata googleBooksMetadata = new GoogleBooksMetadata();
|
||||
googleBooksMetadata.setGoogleBookId(item.getId());
|
||||
googleBooksMetadata.setTitle(volumeInfo.getTitle());
|
||||
googleBooksMetadata.setSubtitle(volumeInfo.getSubtitle());
|
||||
googleBooksMetadata.setPublisher(volumeInfo.getPublisher());
|
||||
googleBooksMetadata.setPublishedDate(volumeInfo.getPublishedDate());
|
||||
googleBooksMetadata.setDescription(volumeInfo.getDescription());
|
||||
if (volumeInfo.getAuthors() != null && !volumeInfo.getAuthors().isEmpty()) {
|
||||
googleBooksMetadata.setAuthors(new ArrayList<>(volumeInfo.getAuthors()));
|
||||
}
|
||||
if (volumeInfo.getCategories() != null && !volumeInfo.getCategories().isEmpty()) {
|
||||
googleBooksMetadata.setCategories(new ArrayList<>(volumeInfo.getCategories()));
|
||||
}
|
||||
if (volumeInfo.getIndustryIdentifiers() != null) {
|
||||
for (GoogleBooksApiResponse.Item.IndustryIdentifier identifier : volumeInfo.getIndustryIdentifiers()) {
|
||||
if ("ISBN_13".equals(identifier.getType())) {
|
||||
googleBooksMetadata.setIsbn13(identifier.getIdentifier());
|
||||
} else if ("ISBN_10".equals(identifier.getType())) {
|
||||
googleBooksMetadata.setIsbn10(identifier.getIdentifier());
|
||||
}
|
||||
}
|
||||
}
|
||||
googleBooksMetadata.setPageCount(volumeInfo.getPageCount());
|
||||
googleBooksMetadata.setThumbnail(volumeInfo.getImageLinks() != null ? volumeInfo.getImageLinks().getThumbnail() : null);
|
||||
googleBooksMetadata.setLanguage(volumeInfo.getLanguage());
|
||||
return googleBooksMetadata;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,48 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.dto.BookDTO;
|
||||
import com.adityachandel.booklore.dto.LibraryDTO;
|
||||
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.entity.Author;
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
import com.adityachandel.booklore.entity.Library;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
import com.adityachandel.booklore.model.ParseLibraryEvent;
|
||||
import com.adityachandel.booklore.model.enums.ParsingStatus;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import com.adityachandel.booklore.exception.ErrorCode;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.transformer.BookTransformer;
|
||||
import com.adityachandel.booklore.transformer.LibraryTransformer;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.transformer.LibraryTransformer.createLibraryFromRequest;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class LibraryService {
|
||||
|
||||
private LibraryRepository libraryRepository;
|
||||
private BookRepository bookRepository;
|
||||
private BooksService booksService;
|
||||
private AuthorRepository authorRepository;
|
||||
private BookViewerSettingRepository bookViewerSettingRepository;
|
||||
private PdfFileProcessor pdfFileProcessor;
|
||||
|
||||
public LibraryDTO createLibrary(CreateLibraryRequest request) {
|
||||
Library library = Library.builder()
|
||||
.name(request.getName())
|
||||
.paths(request.getPaths())
|
||||
.build();
|
||||
return LibraryTransformer.convertToLibraryDTO(libraryRepository.save(library));
|
||||
}
|
||||
|
||||
public LibraryDTO getLibrary(long libraryId) {
|
||||
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
@@ -53,7 +60,6 @@ public class LibraryService {
|
||||
libraryRepository.deleteById(id);
|
||||
}
|
||||
|
||||
|
||||
public BookDTO getBook(long libraryId, long bookId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
Book book = bookRepository.findBookByIdAndLibraryId(bookId, libraryId).orElseThrow(() -> ErrorCode.BOOK_NOT_FOUND.createException(bookId));
|
||||
@@ -67,39 +73,73 @@ public class LibraryService {
|
||||
return bookPage.map(BookTransformer::convertToBookDTO);
|
||||
}
|
||||
|
||||
|
||||
public SseEmitter createLibrary(CreateLibraryRequest request) {
|
||||
public SseEmitter parseLibraryBooks(long libraryId, boolean force) {
|
||||
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ErrorCode.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
SseEmitter emitter = new SseEmitter();
|
||||
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
|
||||
|
||||
sseMvcExecutor.execute(() -> {
|
||||
try {
|
||||
Library library = createLibraryFromRequest(request);
|
||||
List<Book> books = booksService.parseBooks(library, emitter);
|
||||
books.forEach(book -> book.setLibrary(library));
|
||||
library.setBooks(books);
|
||||
|
||||
List<Author> authors = books.stream()
|
||||
.flatMap(book -> book.getAuthors().stream())
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
authorRepository.saveAll(authors);
|
||||
|
||||
libraryRepository.save(library);
|
||||
bookRepository.saveAll(books);
|
||||
bookViewerSettingRepository.saveAll(books.stream()
|
||||
.map(Book::getViewerSetting)
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(library);
|
||||
for (LibraryFile libraryFile : libraryFiles) {
|
||||
log.info(libraryFile.getFilePath());
|
||||
FileProcessResult fileProcessResult = processLibraryFile(libraryFile);
|
||||
ParseLibraryEvent event = createParseLibraryEvent(libraryId, fileProcessResult);
|
||||
emitter.send(event);
|
||||
}
|
||||
log.info("Finished processing library files");
|
||||
emitter.complete();
|
||||
log.info("emitter.complete()");
|
||||
} catch (Exception ex) {
|
||||
emitter.completeWithError(ex);
|
||||
} finally {
|
||||
log.info("sseMvcExecutor.shutdown()");
|
||||
sseMvcExecutor.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
private ParseLibraryEvent createParseLibraryEvent(long libraryId, FileProcessResult result) {
|
||||
return ParseLibraryEvent.builder()
|
||||
.libraryId(libraryId)
|
||||
.file(result.getLibraryFile().getFilePath())
|
||||
.parsingStatus(result.getParsingStatus())
|
||||
.book(result.getBookDTO())
|
||||
.build();
|
||||
}
|
||||
|
||||
private FileProcessResult processLibraryFile(LibraryFile libraryFile) {
|
||||
if (libraryFile.getFileType().equalsIgnoreCase("pdf")) {
|
||||
return pdfFileProcessor.processFile(libraryFile, false);
|
||||
} else if (libraryFile.getFileType().equalsIgnoreCase("epub")) {
|
||||
// TODO:: To implement
|
||||
return FileProcessResult.builder().parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK).libraryFile(libraryFile).build();
|
||||
}
|
||||
// TODO:: To handle
|
||||
return FileProcessResult.builder().parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK).libraryFile(libraryFile).build();
|
||||
}
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(Library library) throws IOException {
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
for (String libraryPath : library.getPaths()) {
|
||||
libraryFiles.addAll(findLibraryFiles(libraryPath, library));
|
||||
}
|
||||
return libraryFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(String directoryPath, Library library) throws IOException {
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
try (var stream = Files.walk(Path.of(directoryPath))) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.filter(file -> {
|
||||
String fileName = file.getFileName().toString().toLowerCase();
|
||||
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
|
||||
})
|
||||
.forEach(file -> {
|
||||
String fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? "PDF" : "EPUB";
|
||||
libraryFiles.add(new LibraryFile(library, file.toAbsolutePath().toString(), fileType));
|
||||
});
|
||||
}
|
||||
return libraryFiles;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.model.enums.ParsingStatus;
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadata;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.transformer.BookTransformer;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class PdfFileProcessor implements FileProcessor {
|
||||
|
||||
private BookRepository bookRepository;
|
||||
private BookCreatorService bookCreatorService;
|
||||
private AppProperties appProperties;
|
||||
|
||||
@Transactional
|
||||
@Override
|
||||
public FileProcessResult processFile(LibraryFile libraryFile, boolean forceProcess) {
|
||||
File bookFile = new File(libraryFile.getFilePath());
|
||||
String fileName = bookFile.getName();
|
||||
if (!forceProcess) {
|
||||
Optional<Book> bookOptional = bookRepository.findByFileName(fileName);
|
||||
if (bookOptional.isPresent()) {
|
||||
return FileProcessResult.builder()
|
||||
.libraryFile(libraryFile)
|
||||
.bookDTO(BookTransformer.convertToBookDTO(bookOptional.get()))
|
||||
.parsingStatus(ParsingStatus.EXISTING_BOOK_NO_FORCED_UPDATE)
|
||||
.build();
|
||||
} else {
|
||||
return processNewFile(libraryFile);
|
||||
}
|
||||
} else {
|
||||
return processNewFile(libraryFile);
|
||||
}
|
||||
}
|
||||
|
||||
private FileProcessResult processNewFile(LibraryFile libraryFile) {
|
||||
File bookFile = new File(libraryFile.getFilePath());
|
||||
Book book = bookCreatorService.createShellBook(libraryFile);
|
||||
BookMetadata bookMetadata = book.getMetadata();
|
||||
FileProcessResult fileProcessResult;
|
||||
try (PDDocument document = Loader.loadPDF(bookFile)) {
|
||||
if (document.getDocumentInformation() == null) {
|
||||
log.warn("No document information found");
|
||||
} else {
|
||||
if (document.getDocumentInformation().getTitle() != null) {
|
||||
bookMetadata.setTitle(document.getDocumentInformation().getTitle());
|
||||
}
|
||||
if (document.getDocumentInformation().getAuthor() != null) {
|
||||
Set<String> authors = getAuthors(document);
|
||||
bookCreatorService.addAuthorsToBook(authors, book);
|
||||
}
|
||||
}
|
||||
generateCoverImage(bookFile, new File(appProperties.getPathConfig() + "/thumbs"), document);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while processing file {}", libraryFile.getFilePath(), e);
|
||||
return FileProcessResult.builder()
|
||||
.libraryFile(libraryFile)
|
||||
.parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK)
|
||||
.build();
|
||||
}
|
||||
bookCreatorService.saveConnections(book);
|
||||
fileProcessResult = FileProcessResult.builder()
|
||||
.bookDTO(BookTransformer.convertToBookDTO(book))
|
||||
.parsingStatus(ParsingStatus.PARSED_NEW_BOOK)
|
||||
.libraryFile(libraryFile)
|
||||
.build();
|
||||
return fileProcessResult;
|
||||
}
|
||||
|
||||
private Set<String> getAuthors(PDDocument document) {
|
||||
String authorNamesUnsplit = document.getDocumentInformation().getAuthor();
|
||||
Set<String> authorNames = new HashSet<>();
|
||||
if (authorNamesUnsplit.contains("&")) {
|
||||
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split("&")));
|
||||
} else if (authorNamesUnsplit.contains(",")) {
|
||||
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split(",")));
|
||||
} else {
|
||||
authorNames.add(authorNamesUnsplit);
|
||||
}
|
||||
return authorNames.stream().map(String::trim).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void generateCoverImage(File bookFile, File coverDirectory, PDDocument document) throws IOException {
|
||||
PDFRenderer renderer = new PDFRenderer(document);
|
||||
BufferedImage coverImage = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
BufferedImage resizedImage = resizeImage(coverImage, 250, 350);
|
||||
String coverImageName = getFileNameWithoutExtension(bookFile.getName()) + ".jpg";
|
||||
File coverImageFile = new File(coverDirectory, coverImageName);
|
||||
ImageIO.write(resizedImage, "JPEG", coverImageFile);
|
||||
}
|
||||
|
||||
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.drawImage(tmp, 0, 0, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
|
||||
public static String getFileNameWithoutExtension(String fileName) {
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex == -1) {
|
||||
return fileName;
|
||||
} else {
|
||||
return fileName.substring(0, dotIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.adityachandel.booklore.service.parser;
|
||||
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
|
||||
public interface BookParser {
|
||||
|
||||
Book parseBook(String bookPath, String coverPath);
|
||||
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package com.adityachandel.booklore.service.parser;
|
||||
|
||||
/*@Service
|
||||
@AllArgsConstructor
|
||||
public class EBookParser implements BookParser {
|
||||
|
||||
@Override
|
||||
public Book parseBook(String bookPath, String coverPath) {
|
||||
return null;
|
||||
}
|
||||
}*/
|
||||
@@ -1,113 +0,0 @@
|
||||
package com.adityachandel.booklore.service.parser;
|
||||
|
||||
import com.adityachandel.booklore.entity.Author;
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class PdfParser implements BookParser {
|
||||
|
||||
private AuthorRepository authorRepository;
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Transactional
|
||||
@Override
|
||||
public Book parseBook(String bookPath, String coverPath) {
|
||||
File bookFile = new File(bookPath);
|
||||
log.info("Parsing: {}", bookFile.getName());
|
||||
File coverDirectory = new File(coverPath, "thumbs");
|
||||
Book book = Book.builder()
|
||||
.path(bookPath)
|
||||
.fileName(bookFile.getName())
|
||||
.authors(new ArrayList<>())
|
||||
.build();
|
||||
try (PDDocument document = Loader.loadPDF(bookFile)) {
|
||||
if (document.getDocumentInformation() == null) {
|
||||
log.warn("No document information found");
|
||||
} else {
|
||||
if (document.getDocumentInformation().getTitle() != null) {
|
||||
book.setTitle(document.getDocumentInformation().getTitle());
|
||||
}
|
||||
if (document.getDocumentInformation().getAuthor() != null) {
|
||||
String authorNamesUnsplit = document.getDocumentInformation().getAuthor();
|
||||
Set<String> authorNames = new HashSet<>();
|
||||
if (authorNamesUnsplit.contains("&")) {
|
||||
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split("&")));
|
||||
} else if (authorNamesUnsplit.contains(",")) {
|
||||
authorNames.addAll(Arrays.asList(authorNamesUnsplit.split(",")));
|
||||
} else {
|
||||
authorNames.add(authorNamesUnsplit);
|
||||
}
|
||||
for (String authorName : authorNames) {
|
||||
authorName = authorName.trim();
|
||||
Optional<Author> authorOptional = authorRepository.findByName(authorName);
|
||||
Author author;
|
||||
if (authorOptional.isPresent()) {
|
||||
author = authorOptional.get();
|
||||
book.getAuthors().add(author);
|
||||
author.getBooks().add(book);
|
||||
} else {
|
||||
author = Author.builder()
|
||||
.name(authorName)
|
||||
.build();
|
||||
author.setBooks(new ArrayList<>());
|
||||
author.getBooks().add(book);
|
||||
book.setAuthors(new ArrayList<>());
|
||||
book.getAuthors().add(author);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
generateCoverImage(bookFile, coverDirectory, document);
|
||||
} catch (Exception e) {
|
||||
log.info("Failed to parse: {}", bookFile.getName());
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
private void generateCoverImage(File bookFile, File coverDirectory, PDDocument document) throws IOException {
|
||||
PDFRenderer renderer = new PDFRenderer(document);
|
||||
BufferedImage coverImage = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
|
||||
BufferedImage resizedImage = resizeImage(coverImage, 250, 350);
|
||||
String coverImageName = getFileNameWithoutExtension(bookFile.getName()) + ".jpg";
|
||||
File coverImageFile = new File(coverDirectory, coverImageName);
|
||||
ImageIO.write(resizedImage, "JPEG", coverImageFile);
|
||||
}
|
||||
|
||||
public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
|
||||
Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
||||
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = resizedImage.createGraphics();
|
||||
g2d.drawImage(tmp, 0, 0, null);
|
||||
g2d.dispose();
|
||||
return resizedImage;
|
||||
}
|
||||
|
||||
public static String getFileNameWithoutExtension(String fileName) {
|
||||
int dotIndex = fileName.lastIndexOf('.');
|
||||
if (dotIndex == -1) {
|
||||
return fileName;
|
||||
} else {
|
||||
return fileName.substring(0, dotIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.entity.Author;
|
||||
import com.adityachandel.booklore.model.dto.AuthorDTO;
|
||||
import com.adityachandel.booklore.model.entity.Author;
|
||||
|
||||
public class AuthorTransformer {
|
||||
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadataDTO;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadata;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class BookMetadataTransformer {
|
||||
|
||||
public static BookMetadataDTO convertToBookDTO(BookMetadata bookMetadata) {
|
||||
return BookMetadataDTO.builder()
|
||||
.bookId(bookMetadata.getBookId())
|
||||
.googleBookId(bookMetadata.getGoogleBookId())
|
||||
.title(bookMetadata.getTitle())
|
||||
.description(bookMetadata.getDescription())
|
||||
.isbn10(bookMetadata.getIsbn10())
|
||||
.isbn13(bookMetadata.getIsbn13())
|
||||
.publisher(bookMetadata.getPublisher())
|
||||
.subtitle(bookMetadata.getSubtitle())
|
||||
.language(bookMetadata.getLanguage())
|
||||
.thumbnail(bookMetadata.getThumbnail())
|
||||
.pageCount(bookMetadata.getPageCount())
|
||||
.publishedDate(bookMetadata.getPublishedDate())
|
||||
.authors(bookMetadata.getAuthors() == null ? null : bookMetadata.getAuthors().stream().map(AuthorTransformer::toAuthorDTO).collect(Collectors.toList()))
|
||||
.categories(bookMetadata.getCategories() == null ? null : bookMetadata.getCategories().stream().map(CategoryTransformer::categoryDTO).collect(Collectors.toList()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.entity.BookViewerSetting;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettingDTO;
|
||||
import com.adityachandel.booklore.model.entity.BookViewerSetting;
|
||||
|
||||
public class BookSettingTransformer {
|
||||
|
||||
|
||||
+3
-6
@@ -1,9 +1,7 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.dto.BookDTO;
|
||||
import com.adityachandel.booklore.entity.Book;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
|
||||
public class BookTransformer {
|
||||
|
||||
@@ -12,10 +10,9 @@ public class BookTransformer {
|
||||
bookDTO.setId(book.getId());
|
||||
bookDTO.setLibraryId(book.getLibrary().getId());
|
||||
bookDTO.setFileName(book.getFileName());
|
||||
bookDTO.setTitle(book.getTitle());
|
||||
bookDTO.setLastReadTime(book.getLastReadTime());
|
||||
bookDTO.setAddedOn(book.getAddedOn());
|
||||
bookDTO.setAuthors(book.getAuthors().stream().map(AuthorTransformer::toAuthorDTO).collect(Collectors.toList()));
|
||||
bookDTO.setMetadata(BookMetadataTransformer.convertToBookDTO(book.getMetadata()));
|
||||
return bookDTO;
|
||||
}
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CategoryDTO;
|
||||
import com.adityachandel.booklore.model.entity.Category;
|
||||
|
||||
public class CategoryTransformer {
|
||||
|
||||
public static CategoryDTO categoryDTO(Category category) {
|
||||
return CategoryDTO.builder()
|
||||
.id(category.getId())
|
||||
.name(category.getName())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+3
-10
@@ -1,8 +1,8 @@
|
||||
package com.adityachandel.booklore.transformer;
|
||||
|
||||
import com.adityachandel.booklore.dto.LibraryDTO;
|
||||
import com.adityachandel.booklore.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.entity.Library;
|
||||
import com.adityachandel.booklore.model.dto.LibraryDTO;
|
||||
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
|
||||
public class LibraryTransformer {
|
||||
|
||||
@@ -12,11 +12,4 @@ public class LibraryTransformer {
|
||||
.name(library.getName())
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Library createLibraryFromRequest(CreateLibraryRequest request) {
|
||||
return Library.builder()
|
||||
.name(request.getName())
|
||||
.paths(request.getPaths())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,9 @@ app:
|
||||
path-config: '/Users/aditya.chandel/my-library-temp/config'
|
||||
|
||||
spring:
|
||||
mvc:
|
||||
async:
|
||||
request-timeout: 600000
|
||||
application:
|
||||
name: booklore-api
|
||||
datasource:
|
||||
|
||||
+41
-10
@@ -2,13 +2,12 @@ CREATE TABLE IF NOT EXISTS library
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) UNIQUE NOT NULL,
|
||||
paths BLOB
|
||||
paths TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
title VARCHAR(255),
|
||||
file_name VARCHAR(255) NOT NULL,
|
||||
library_id BIGINT NOT NULL,
|
||||
path VARCHAR(1000) NOT NULL,
|
||||
@@ -20,6 +19,23 @@ CREATE TABLE IF NOT EXISTS book
|
||||
INDEX idx_last_read_time (last_read_time)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book_metadata
|
||||
(
|
||||
book_id BIGINT NOT NULL PRIMARY KEY,
|
||||
google_book_id VARCHAR(255) UNIQUE,
|
||||
title VARCHAR(255),
|
||||
subtitle VARCHAR(255),
|
||||
publisher VARCHAR(255),
|
||||
published_date DATE,
|
||||
description TEXT,
|
||||
isbn_13 VARCHAR(13),
|
||||
isbn_10 VARCHAR(10),
|
||||
page_count INT,
|
||||
thumbnail VARCHAR(1000),
|
||||
language VARCHAR(10),
|
||||
CONSTRAINT fk_book_metadata FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS author
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
@@ -27,15 +43,10 @@ CREATE TABLE IF NOT EXISTS author
|
||||
CONSTRAINT unique_name UNIQUE (name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book_author_mapping
|
||||
CREATE TABLE IF NOT EXISTS category
|
||||
(
|
||||
book_id BIGINT NOT NULL,
|
||||
author_id BIGINT NOT NULL,
|
||||
CONSTRAINT fk_book_author_mapping_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_book_author_mapping_author FOREIGN KEY (author_id) REFERENCES author (id),
|
||||
CONSTRAINT unique_book_author UNIQUE (book_id, author_id),
|
||||
INDEX idx_book_id (book_id),
|
||||
INDEX idx_author_id (author_id)
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book_viewer_setting
|
||||
@@ -46,4 +57,24 @@ CREATE TABLE IF NOT EXISTS book_viewer_setting
|
||||
sidebar_visible BOOLEAN DEFAULT false,
|
||||
spread VARCHAR(16) DEFAULT 'odd',
|
||||
CONSTRAINT fk_book_viewer_setting FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book_metadata_category_mapping
|
||||
(
|
||||
book_id BIGINT NOT NULL,
|
||||
category_id BIGINT NOT NULL,
|
||||
PRIMARY KEY (book_id, category_id),
|
||||
CONSTRAINT fk_book_metadata_category_mapping_book FOREIGN KEY (book_id) REFERENCES book_metadata (book_id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_book_metadata_category_mapping_category FOREIGN KEY (category_id) REFERENCES category (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS book_metadata_author_mapping
|
||||
(
|
||||
book_id BIGINT NOT NULL,
|
||||
author_id BIGINT NOT NULL,
|
||||
PRIMARY KEY (book_id, author_id),
|
||||
CONSTRAINT fk_book_metadata_author_mapping_book FOREIGN KEY (book_id) REFERENCES book_metadata (book_id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_book_metadata_author_mapping_author FOREIGN KEY (author_id) REFERENCES author (id) ON DELETE CASCADE,
|
||||
INDEX idx_book_metadata_id (book_id),
|
||||
INDEX idx_author_id (author_id)
|
||||
);
|
||||
@@ -4,6 +4,7 @@ import {AppLayoutComponent} from './layout/app.layout.component';
|
||||
import {LibraryBrowserComponent} from './book/component/library-browser/library-browser.component';
|
||||
import {PdfViewerComponent} from './book/component/pdf-viewer/pdf-viewer.component';
|
||||
import {DashboardComponent} from './book/component/dashboard/dashboard.component';
|
||||
import {BookMetadataComponent} from './book-metadata/book-metadata.component';
|
||||
|
||||
const routes: Routes = [
|
||||
{
|
||||
@@ -14,6 +15,9 @@ const routes: Routes = [
|
||||
},
|
||||
{
|
||||
path: 'library/:libraryId/books', component: LibraryBrowserComponent,
|
||||
},
|
||||
{
|
||||
path: 'book/:bookId/info', component: BookMetadataComponent,
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -20,13 +20,16 @@ import {ToastModule} from 'primeng/toast';
|
||||
import {LibraryBrowserComponent} from './book/component/library-browser/library-browser.component';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {SearchComponent} from './book/component/search/search.component';
|
||||
import { BookMetadataComponent } from './book-metadata/book-metadata.component';
|
||||
import { BooksMetadataDialogComponent } from './books-metadata-dialog/books-metadata-dialog.component';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import { NotificationComponent } from './notification/notification.component';
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AppComponent,
|
||||
DirectoryPickerComponent,
|
||||
LibraryCreatorComponent,
|
||||
LibraryBrowserComponent
|
||||
LibraryCreatorComponent
|
||||
],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
@@ -45,7 +48,7 @@ import {SearchComponent} from './book/component/search/search.component';
|
||||
InfiniteScrollDirective,
|
||||
SearchComponent,
|
||||
],
|
||||
providers: [DialogService],
|
||||
providers: [DialogService, MessageService],
|
||||
bootstrap: [AppComponent]
|
||||
})
|
||||
export class AppModule { }
|
||||
|
||||
+4
-3
@@ -9,11 +9,12 @@
|
||||
(scroll)="onScroll($event)">
|
||||
|
||||
<div class="book-item" *ngFor="let book of books">
|
||||
<img [src]="coverImageSrc(book.id)" class="book-cover" alt="Cover of {{ book.title }}" loading="lazy"/>
|
||||
<img [src]="coverImageSrc(book.id)" class="book-cover" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
|
||||
<div class="book-info">
|
||||
<h4>{{ book.title }}</h4>
|
||||
<h4>{{ book.metadata.title }}</h4>
|
||||
<p>{{ getAuthorNames(book) }}</p>
|
||||
<p-button label="View" icon="pi pi-eye" class="view-btn" (click)="openBook(book.id)"></p-button>
|
||||
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="openBook(book.id)"></p-button>
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id)"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+9
-4
@@ -61,7 +61,7 @@ h4 {
|
||||
|
||||
p {
|
||||
color: var(--text-color-secondary);
|
||||
font-size: 0.7rem;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.2;
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
@@ -69,15 +69,20 @@ p {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.view-btn {
|
||||
.view-btn, .read-btn {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
transform: translate(-50%, -20%);
|
||||
display: none;
|
||||
z-index: 1;
|
||||
margin: -60px 0;
|
||||
}
|
||||
|
||||
.book-item:hover .view-btn {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.book-item:hover .read-btn {
|
||||
display: block;
|
||||
top: 75%;
|
||||
}
|
||||
|
||||
+7
-2
@@ -4,6 +4,7 @@ import {BookService} from '../../service/book.service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {NgForOf} from '@angular/common';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-dashboard-scroller',
|
||||
@@ -26,7 +27,7 @@ export class DashboardScrollerComponent implements OnInit {
|
||||
|
||||
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
|
||||
|
||||
constructor(private bookService: BookService) {
|
||||
constructor(private bookService: BookService, private router: Router) {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -67,7 +68,7 @@ export class DashboardScrollerComponent implements OnInit {
|
||||
}
|
||||
|
||||
getAuthorNames(book: Book): string {
|
||||
return book.authors?.map((author) => author.name).join(', ') || 'No authors available';
|
||||
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available';
|
||||
}
|
||||
|
||||
openBook(bookId: number): void {
|
||||
@@ -83,4 +84,8 @@ export class DashboardScrollerComponent implements OnInit {
|
||||
this.loadMore();
|
||||
}
|
||||
}
|
||||
|
||||
openBookInfo(bookId: number) {
|
||||
this.router.navigate(['/book', bookId, 'info']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,14 @@
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]=true
|
||||
(scrolled)="loadMore()">
|
||||
<div class="book-item" *ngFor="let book of books">
|
||||
<img [src]="coverImageSrc(book.id)" class="book-cover placeholder" alt="Cover of {{ book.title }}" loading="lazy"/>
|
||||
<img [src]="coverImageSrc(book.id)" class="book-cover placeholder" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
|
||||
<div class="book-info">
|
||||
<h4>{{ book.title }}</h4>
|
||||
<h4>{{ book.metadata.title }}</h4>
|
||||
<p>{{ getAuthorNames(book) }}</p>
|
||||
<p-button label="View" icon="pi pi-eye" class="view-btn" (click)="openBook(book.id)"></p-button>
|
||||
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="readBook(book.id)"></p-button>
|
||||
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id)"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
height: auto;
|
||||
background-color: var(--surface-card);
|
||||
border-radius: 8px;
|
||||
position: relative; /* Positioning container for the button and overlay */
|
||||
position: relative; /* Positioning container for the buttons and overlay */
|
||||
}
|
||||
|
||||
.book-cover {
|
||||
@@ -24,7 +24,7 @@
|
||||
object-fit: cover;
|
||||
background-color: #444;
|
||||
transition: background-color 0.3s ease, filter 0.3s ease; /* Add transition for blur effect */
|
||||
position: relative; /* Make this the reference point for the overlay */
|
||||
position: relative; /* Make this the reference point for the overlay and buttons */
|
||||
}
|
||||
|
||||
/* Blur and overlay effect */
|
||||
@@ -40,7 +40,7 @@
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5); /* Semi-transparent black overlay */
|
||||
z-index: 0; /* Put overlay behind the button */
|
||||
z-index: 0; /* Put overlay behind the buttons */
|
||||
}
|
||||
|
||||
.book-info {
|
||||
@@ -62,7 +62,6 @@ h4 {
|
||||
max-width: 100%;
|
||||
text-align: center;
|
||||
margin-bottom: 5px;
|
||||
|
||||
}
|
||||
|
||||
p {
|
||||
@@ -87,17 +86,22 @@ p {
|
||||
}
|
||||
|
||||
/* PrimeNG button styling */
|
||||
.view-btn {
|
||||
.view-btn, .read-btn {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%); /* Center button on the image */
|
||||
transform: translate(-50%, -20%); /* Center buttons within the book-cover */
|
||||
display: none; /* Hide by default */
|
||||
z-index: 1; /* Ensure it appears over the image */
|
||||
margin: -60px 0; /* Add spacing between the buttons */
|
||||
}
|
||||
|
||||
.book-item:hover .view-btn {
|
||||
display: block; /* Show the button when the card is hovered */
|
||||
display: block; /* Show the View button when the card is hovered */
|
||||
}
|
||||
|
||||
.book-item:hover .read-btn {
|
||||
display: block; /* Show the Read button when the card is hovered */
|
||||
top: 75%; /* Slightly adjust the position to be below the View button */
|
||||
}
|
||||
|
||||
.infinite-scroll {
|
||||
|
||||
@@ -1,33 +1,79 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Component, OnInit, NgZone } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { BookProgressService } from '../../service/book-progress-service';
|
||||
import { BookUpdateEvent } from '../../model/book-update-event.model';
|
||||
import { BookService } from '../../service/book.service';
|
||||
import { Book } from '../../model/book.model';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { combineLatest } from 'rxjs';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {Button} from 'primeng/button';
|
||||
import {NgForOf} from '@angular/common';
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-browser-v2',
|
||||
standalone: false,
|
||||
templateUrl: './library-browser.component.html',
|
||||
styleUrls: ['./library-browser.component.scss'],
|
||||
imports: [
|
||||
InfiniteScrollDirective,
|
||||
Button,
|
||||
NgForOf
|
||||
]
|
||||
})
|
||||
export class LibraryBrowserComponent implements OnInit {
|
||||
books: Book[] = [];
|
||||
private libraryId: number = 1;
|
||||
private currentPage: number = 0;
|
||||
|
||||
constructor(private bookService: BookService, private route: ActivatedRoute) {}
|
||||
constructor(
|
||||
private bookService: BookService,
|
||||
private activatedRoute: ActivatedRoute,
|
||||
private router: Router,
|
||||
private bookProgressService: BookProgressService,
|
||||
private ngZone: NgZone
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.paramMap.subscribe((params) => {
|
||||
const libraryId = params.get('libraryId');
|
||||
if (libraryId) {
|
||||
this.libraryId = +libraryId;
|
||||
this.resetState();
|
||||
this.loadBooks();
|
||||
}
|
||||
combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap])
|
||||
.subscribe(([params, queryParams]) => {
|
||||
const libraryId = params.get('libraryId');
|
||||
if (libraryId) {
|
||||
this.libraryId = +libraryId;
|
||||
this.resetState();
|
||||
this.loadBooks();
|
||||
}
|
||||
const watch = queryParams.get('watch');
|
||||
if (watch) {
|
||||
this.startListeningForProgress();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
startListeningForProgress(): void {
|
||||
this.bookProgressService.connect(this.libraryId).subscribe({
|
||||
next: (event: BookUpdateEvent) => this.addBookToCollection(event),
|
||||
error: (error) => console.error('Error receiving progress updates:', error),
|
||||
});
|
||||
}
|
||||
|
||||
addBookToCollection(event: BookUpdateEvent): void {
|
||||
if(event.parsingStatus === 'PARSED_NEW_BOOK') {
|
||||
const newBook: Book = {
|
||||
id: event.book.id,
|
||||
libraryId: event.book.libraryId,
|
||||
metadata: event.book.metadata,
|
||||
};
|
||||
this.ngZone.run(() => {
|
||||
if (!this.books.find((book) => book.id === newBook.id)) {
|
||||
this.books = [newBook, ...this.books];
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.error('Status other than: PARSED_NEW_BOOK');
|
||||
}
|
||||
}
|
||||
|
||||
resetState(): void {
|
||||
console.log("resetState")
|
||||
this.books = [];
|
||||
this.currentPage = 0;
|
||||
}
|
||||
@@ -38,9 +84,7 @@ export class LibraryBrowserComponent implements OnInit {
|
||||
this.books = [...this.books, ...response.content];
|
||||
this.currentPage++;
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('Error loading books:', err);
|
||||
},
|
||||
error: (err) => console.error('Error loading books:', err),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -53,11 +97,15 @@ export class LibraryBrowserComponent implements OnInit {
|
||||
}
|
||||
|
||||
getAuthorNames(book: Book): string {
|
||||
return book.authors?.map((author) => author.name).join(', ') || 'No authors available';
|
||||
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available';
|
||||
}
|
||||
|
||||
openBook(bookId: number): void {
|
||||
readBook(bookId: number): void {
|
||||
const url = `/pdf-viewer/book/${bookId}`;
|
||||
window.open(url, '_blank');
|
||||
}
|
||||
|
||||
openBookInfo(bookId: number) {
|
||||
this.router.navigate(['/book', bookId, 'info']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {DirectoryPickerComponent} from '../directory-picker/directory-picker.component';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {LibraryService} from '../../service/library.service';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-library-creator',
|
||||
@@ -20,8 +21,10 @@ export class LibraryCreatorComponent {
|
||||
public dialogService: DialogService,
|
||||
private dynamicDialogRef: DynamicDialogRef,
|
||||
private messageService: MessageService,
|
||||
private libraryServiceV2: LibraryService
|
||||
) {}
|
||||
private libraryServiceV2: LibraryService,
|
||||
private router: Router,
|
||||
) {
|
||||
}
|
||||
|
||||
show() {
|
||||
this.ref = this.dialogService.open(DirectoryPickerComponent, {
|
||||
@@ -29,7 +32,7 @@ export class LibraryCreatorComponent {
|
||||
modal: false,
|
||||
width: '50%',
|
||||
height: '75%',
|
||||
contentStyle: { overflow: 'auto' },
|
||||
contentStyle: {overflow: 'auto'},
|
||||
baseZIndex: 10
|
||||
});
|
||||
|
||||
@@ -56,6 +59,10 @@ export class LibraryCreatorComponent {
|
||||
this.libraryServiceV2.createLibrary(newLibrary).subscribe({
|
||||
next: (createdLibrary) => {
|
||||
console.log('Library successfully created:', createdLibrary);
|
||||
this.router.navigate(
|
||||
['/library', createdLibrary.id, 'books'],
|
||||
{queryParams: {watch: true}}
|
||||
);
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('Failed to create library:', err);
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
<ng-container *ngIf="books.length > 0; else noResults">
|
||||
<div class="search-dropdown-item" *ngFor="let book of books" (click)="onBookClick(book)">
|
||||
<img [src]="getBookCoverUrl(book.id)" alt="Book Cover" class="search-book-cover" />
|
||||
<span class="search-book-name">{{ book.title }}</span>
|
||||
<span class="search-book-name">{{ book.metadata.title }}</span>
|
||||
</div>
|
||||
</ng-container>
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import {BookMetadata} from './book.model';
|
||||
|
||||
export interface BookUpdateEvent {
|
||||
libraryId: number;
|
||||
filename: string;
|
||||
book: {
|
||||
id: number;
|
||||
libraryId: number;
|
||||
fileName: string;
|
||||
addedOn: string;
|
||||
metadata: BookMetadata;
|
||||
};
|
||||
parsingStatus: string;
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
import {Author} from './author.model';
|
||||
|
||||
export interface Book {
|
||||
id: number;
|
||||
libraryId: number;
|
||||
title: string;
|
||||
authors: Author[];
|
||||
metadata: BookMetadata
|
||||
}
|
||||
|
||||
export interface PaginatedBooksResponse {
|
||||
@@ -16,3 +13,29 @@ export interface PaginatedBooksResponse {
|
||||
first: boolean;
|
||||
last: boolean;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
thumbnail: string;
|
||||
title: string;
|
||||
authors: Author[];
|
||||
categories: Category[];
|
||||
publisher: string;
|
||||
publishedDate: string;
|
||||
isbn10: string;
|
||||
description: string;
|
||||
pageCount: number;
|
||||
language: string;
|
||||
googleBookId: string;
|
||||
}
|
||||
|
||||
export interface Author {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Category {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {BookUpdateEvent} from '../model/book-update-event.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookProgressService {
|
||||
private eventSource: EventSource | null = null;
|
||||
|
||||
connect(libraryId: number): Observable<BookUpdateEvent> {
|
||||
const url = `http://localhost:8080/v1/library/${libraryId}/parse`;
|
||||
|
||||
return new Observable((observer) => {
|
||||
this.eventSource = new EventSource(url);
|
||||
|
||||
this.eventSource.onmessage = (event) => {
|
||||
const data: BookUpdateEvent = JSON.parse(event.data);
|
||||
observer.next(data);
|
||||
};
|
||||
|
||||
this.eventSource.onerror = (error) => {
|
||||
console.error('SSE connection error:', error);
|
||||
observer.error(error);
|
||||
};
|
||||
|
||||
return () => {
|
||||
this.closeConnection();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
closeConnection(): void {
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
console.log('SSE connection closed');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { Book, PaginatedBooksResponse } from '../model/book.model';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {Book, BookMetadata, PaginatedBooksResponse} from '../model/book.model';
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BookSetting} from '../model/book-settings.model';
|
||||
|
||||
@Injectable({
|
||||
@@ -12,7 +12,8 @@ export class BookService {
|
||||
private readonly libraryUrl = 'http://localhost:8080/v1/library';
|
||||
private readonly bookUrl = 'http://localhost:8080/v1/book';
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
constructor(private http: HttpClient) {
|
||||
}
|
||||
|
||||
getBook(bookId: number): Observable<Book> {
|
||||
return this.http.get<Book>(`${this.bookUrl}/${bookId}`);
|
||||
@@ -36,7 +37,6 @@ export class BookService {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
searchBooks(query: string): Observable<Book[]> {
|
||||
if (query.length < 2) {
|
||||
return new Observable<Book[]>();
|
||||
@@ -64,4 +64,17 @@ export class BookService {
|
||||
updateLastReadTime(bookId: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.bookUrl}/${bookId}/update-last-read`, {});
|
||||
}
|
||||
|
||||
fetchBookMetadataByBookId(bookId: number): Observable<BookMetadata[]> {
|
||||
return this.http.get<BookMetadata[]>(`${this.bookUrl}/${bookId}/fetch-metadata`);
|
||||
}
|
||||
|
||||
fetchBookMetadataByTerm(term: string): Observable<BookMetadata[]> {
|
||||
return this.http.get<BookMetadata[]>(`${this.bookUrl}/fetch-metadata?term=${term}`);
|
||||
}
|
||||
|
||||
setBookMetadata(googleBookId: string, bookId: number): Observable<void> {
|
||||
const requestBody = {googleBookId: googleBookId};
|
||||
return this.http.put<void>(`${this.bookUrl}/${bookId}/set-metadata`, requestBody);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,5 +32,6 @@
|
||||
<i class="pi pi-cog"></i>
|
||||
<span>Settings</span>
|
||||
</button>
|
||||
<app-notification></app-notification>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import {Component, ElementRef, OnDestroy, ViewChild,} from '@angular/core';
|
||||
import {MenuItem} from 'primeng/api';
|
||||
import {LayoutService} from './service/app.layout.service';
|
||||
import {RouterLink} from '@angular/router';
|
||||
import {DialogService as PrimeDialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||
import {LibraryCreatorComponent} from '../book/component/library-creator/library-creator.component';
|
||||
import {TooltipModule} from 'primeng/tooltip';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {InputTextModule} from 'primeng/inputtext';
|
||||
import {SearchComponent} from '../book/component/search/search.component';
|
||||
import { Component, ElementRef, OnDestroy, ViewChild } from '@angular/core';
|
||||
import { MenuItem } from 'primeng/api';
|
||||
import { LayoutService } from './service/app.layout.service';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { DialogService as PrimeDialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
|
||||
import { LibraryCreatorComponent } from '../book/component/library-creator/library-creator.component';
|
||||
import { TooltipModule } from 'primeng/tooltip';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { InputTextModule } from 'primeng/inputtext';
|
||||
import { SearchComponent } from '../book/component/search/search.component';
|
||||
import { NotificationComponent } from '../notification/notification.component'; // Import the NotificationComponent
|
||||
|
||||
@Component({
|
||||
selector: 'app-topbar',
|
||||
@@ -17,6 +18,7 @@ import {SearchComponent} from '../book/component/search/search.component';
|
||||
FormsModule,
|
||||
InputTextModule,
|
||||
SearchComponent,
|
||||
NotificationComponent // Add NotificationComponent to imports
|
||||
],
|
||||
templateUrl: './app.topbar.component.html',
|
||||
})
|
||||
@@ -28,12 +30,11 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
@ViewChild('topbarmenubutton') topbarMenuButton!: ElementRef;
|
||||
@ViewChild('topbarmenu') menu!: ElementRef;
|
||||
|
||||
constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService) {
|
||||
}
|
||||
constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService) {}
|
||||
|
||||
openLibraryCreatorDialog(): void {
|
||||
this.ref = this.dialogService.open(LibraryCreatorComponent, {
|
||||
header: "Create New Library",
|
||||
header: 'Create New Library',
|
||||
modal: false,
|
||||
width: '50%',
|
||||
height: '50%',
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 1.5 KiB |
Reference in New Issue
Block a user