- Library paths are not identified by path ID.

- Revamp upload functionality.
This commit is contained in:
aditya.chandel
2025-01-16 18:11:28 -07:00
parent f6f5f718af
commit a11a42cd19
18 changed files with 281 additions and 69 deletions
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.service.FileUploadService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
@@ -16,9 +17,11 @@ public class FileUploadController {
private final FileUploadService fileUploadService;
@PostMapping("/upload")
public ResponseEntity<Void> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("filePath") String filePath) {
fileUploadService.uploadFile(file, libraryId, filePath);
return ResponseEntity.noContent().build();
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) {
if (file.isEmpty()) {
throw new IllegalArgumentException("Uploaded file is missing.");
}
return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId));
}
}
@@ -3,13 +3,14 @@ package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.Library;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryMapper {
@Mapping(target = "paths", source = "libraryEntity.libraryPaths")
Library toLibrary(LibraryEntity libraryEntity);
List<Library> toLibraryList(List<LibraryEntity> libraryEntities);
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.adityachandel.booklore.model.dto.Shelf;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import java.util.List;
@Mapper(componentModel = "spring")
public interface LibraryPathMapper {
LibraryPath toLibraryPath(LibraryPathEntity libraryPathEntity);
List<LibraryPath> toLibraryPathList(List<LibraryPathEntity> libraryPathEntities);
}
@@ -14,6 +14,6 @@ public class Library {
private String name;
private Sort sort;
private String icon;
private List<String> paths;
private List<LibraryPath> paths;
}
@@ -0,0 +1,14 @@
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 LibraryPath {
private Long id;
private Long libraryId;
private String path;
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.dto.LibraryPath;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
@@ -17,5 +18,5 @@ public class CreateLibraryRequest {
@NotBlank
private String icon;
@NotEmpty
private List<String> paths;
private List<LibraryPath> paths;
}
@@ -1,6 +1,5 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.convertor.PathsConverter;
import com.adityachandel.booklore.convertor.SortConverter;
import com.adityachandel.booklore.model.dto.Sort;
import jakarta.persistence.*;
@@ -26,12 +25,11 @@ public class LibraryEntity {
@Convert(converter = SortConverter.class)
private Sort sort;
@Convert(converter = PathsConverter.class)
@Column(name = "paths")
private List<String> paths;
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<BookEntity> bookEntities;
@OneToMany(mappedBy = "library", cascade = CascadeType.ALL, orphanRemoval = true)
private List<LibraryPathEntity> libraryPaths;
private String icon;
}
@@ -0,0 +1,25 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "library_path")
public class LibraryPathEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "library_id", nullable = false)
private LibraryEntity library;
@Column(nullable = false)
private String path;
}
@@ -2,10 +2,13 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.LibraryFile;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -14,54 +17,95 @@ import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
@AllArgsConstructor
@RequiredArgsConstructor
@Service
@Slf4j
public class FileUploadService {
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String EPUB_MIME_TYPE = "application/epub+zip";
private final LibraryRepository libraryRepository;
private final PdfFileProcessor fileProcessor;
private final PdfFileProcessor pdfProcessor;
private final EpubFileProcessor epubProcessor;
private final NotificationService notificationService;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file);
public void uploadFile(MultipartFile file, long libraryId, String filePath) {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
if (!libraryEntity.getPaths().contains(filePath)) {
throw ApiError.INVALID_LIBRARY_PATH.createException();
}
String fileType = file.getContentType();
if (!"application/pdf".equals(fileType) && !"application/epub+zip".equals(fileType)) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
if (file.getSize() > 100 * 1024 * 1024) {
throw ApiError.FILE_TOO_LARGE.createException();
}
try {
Path storagePath = Paths.get(filePath, file.getOriginalFilename());
File storageFile = storagePath.toFile();
if (storageFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
file.transferTo(storageFile);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.bookFileType(getFileType(fileType))
.filePath(storageFile.getAbsolutePath())
.build();
fileProcessor.processFile(libraryFile, false);
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
LibraryPathEntity libraryPath = libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
Path storagePath = Paths.get(libraryPath.getPath(), Objects.requireNonNull(file.getOriginalFilename()));
File storageFile = storagePath.toFile();
if (storageFile.exists()) {
throw ApiError.FILE_ALREADY_EXISTS.createException();
}
try {
file.transferTo(storageFile);
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
Book book = processFile(file, libraryEntity, storageFile);
notificationService.sendMessage(Topic.BOOK_ADD, book);
log.info("Book processed successfully: {}", book.getMetadata().getTitle());
return book;
} catch (IOException e) {
log.error("Error saving file: {}", e.getMessage());
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
}
}
private BookFileType getFileType(String f) {
if (f.equalsIgnoreCase("application/pdf")) {
return BookFileType.PDF;
} else if (f.equalsIgnoreCase("application/epub+zip")) {
return BookFileType.EPUB;
} else {
return null;
private void validateFile(MultipartFile file) {
String fileType = file.getContentType();
if ((!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType))) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
if (file.getSize() > MAX_FILE_SIZE) {
throw ApiError.FILE_TOO_LARGE.createException();
}
}
}
private Book processFile(MultipartFile file, LibraryEntity libraryEntity, File storageFile) {
BookFileType fileType = determineFileType(file.getContentType());
if (fileType == null) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.bookFileType(fileType)
.filePath(storageFile.getAbsolutePath())
.build();
switch (fileType) {
case PDF -> {
return pdfProcessor.processFile(libraryFile, false);
}
case EPUB -> {
return epubProcessor.processFile(libraryFile, false);
}
default -> {
log.warn("Unsupported file type for processing: {}", fileType);
throw ApiError.INVALID_FILE_FORMAT.createException();
}
}
}
private BookFileType determineFileType(String fileType) {
return switch (fileType.toLowerCase()) {
case PDF_MIME_TYPE -> BookFileType.PDF;
case EPUB_MIME_TYPE -> BookFileType.EPUB;
default -> null;
};
}
}
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.LibraryFile;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
@@ -81,7 +82,7 @@ public class LibraryProcessingService {
protected Book processLibraryFile(LibraryFile libraryFile) {
if (libraryFile.getBookFileType() == BookFileType.PDF) {
return pdfFileProcessor.processFile(libraryFile, false);
} else if(libraryFile.getBookFileType() == BookFileType.EPUB) {
} else if (libraryFile.getBookFileType() == BookFileType.EPUB) {
return epubFileProcessor.processFile(libraryFile, false);
}
return null;
@@ -113,8 +114,8 @@ public class LibraryProcessingService {
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>();
for (String libraryPath : libraryEntity.getPaths()) {
libraryFiles.addAll(findLibraryFiles(libraryPath, libraryEntity));
for (LibraryPathEntity libraryPath : libraryEntity.getLibraryPaths()) {
libraryFiles.addAll(findLibraryFiles(libraryPath.getPath(), libraryEntity));
}
return libraryFiles;
}
@@ -9,6 +9,7 @@ import com.adityachandel.booklore.model.dto.Sort;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import lombok.AllArgsConstructor;
@@ -17,7 +18,9 @@ import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
@@ -33,7 +36,13 @@ public class LibraryService {
public Library createLibrary(CreateLibraryRequest request) {
LibraryEntity libraryEntity = LibraryEntity.builder()
.name(request.getName())
.paths(request.getPaths())
.libraryPaths(
request.getPaths() == null || request.getPaths().isEmpty() ?
Collections.emptyList() :
request.getPaths().stream()
.map(path -> LibraryPathEntity.builder().path(path.getPath()).build())
.collect(Collectors.toList())
)
.icon(request.getIcon())
.build();
libraryEntity = libraryRepository.save(libraryEntity);
@@ -1,10 +1,17 @@
CREATE TABLE IF NOT EXISTS library
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL,
paths TEXT
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) UNIQUE NOT NULL,
sort VARCHAR(255) NULL,
icon VARCHAR(64) NOT NULL
);
CREATE TABLE IF NOT EXISTS library_path
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
path TEXT,
library_id BIGINT,
CONSTRAINT fk_library_path FOREIGN KEY (library_id) REFERENCES library (id)
);
CREATE TABLE IF NOT EXISTS book
@@ -0,0 +1,38 @@
<div
*ngIf="(libraryState$ | async)?.libraries as libraries"
class="flex flex-col gap-10 p-4 items-center justify-center min-w-[400px] max-w-[600px] w-full">
<p-dropdown
[options]="libraries"
optionLabel="name"
placeholder="Select Library"
[(ngModel)]="selectedLibrary"
class="w-full"></p-dropdown>
<p-dropdown
[options]="selectedLibrary?.paths"
optionLabel="path"
placeholder="Select Upload Location"
[(ngModel)]="selectedPath"
[disabled]="!selectedLibrary"
class="w-full"></p-dropdown>
<p-fileupload
#fu
mode="basic"
chooseLabel="Choose"
chooseIcon="pi pi-upload"
name="file"
[url]="getUploadUrl()"
accept=".pdf,.epub"
maxFileSize="104857600"
(onUpload)="onUpload($event)"
[disabled]="!selectedLibrary || !selectedPath"
class="w-full">
</p-fileupload>
<div class="flex flex-row items-center justify-between w-full">
<p-button label="Upload" (onClick)="fu.upload()" severity="primary" [disabled]="!fu.files.length" class=""/>
<p-button label="Clear" (click)="fu.clear()" severity="info" [disabled]="!fu.files.length" class=""/>
</div>
</div>
@@ -0,0 +1,48 @@
import {Component, inject, Input} from '@angular/core';
import {FileUpload, FileUploadEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {LibraryService} from '../book/service/library.service';
import {Observable} from 'rxjs';
import {LibraryState} from '../book/model/state/library-state.model';
import {AsyncPipe, NgIf} from '@angular/common';
import {DropdownModule} from 'primeng/dropdown';
import {FormsModule} from '@angular/forms';
import {Library, LibraryPath} from '../book/model/library.model';
import {MessageService} from 'primeng/api';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-book-uploader',
imports: [
FileUpload,
Button,
AsyncPipe,
DropdownModule,
FormsModule,
NgIf
],
templateUrl: './book-uploader.component.html',
styleUrl: './book-uploader.component.scss'
})
export class BookUploaderComponent {
private uploadUrl = 'http://localhost:8080/api/v1/files/upload';
private libraryService = inject(LibraryService);
private messageService = inject(MessageService);
private dynamicDialogRef = inject(DynamicDialogRef);
libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
selectedLibrary: Library | null = null;
selectedPath: LibraryPath | null = null;
getUploadUrl() {
return `${this.uploadUrl}?libraryId=${this.selectedLibrary?.id}&pathId=${this.selectedPath?.id}`;
}
onUpload($event: FileUploadEvent) {
this.dynamicDialogRef.close();
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Book successfully uploaded'});
}
}
@@ -13,6 +13,7 @@ import {NgIf} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {InputText} from 'primeng/inputtext';
import {BookService} from '../../service/book.service';
import {Library, LibraryPath} from '../../model/library.model';
@Component({
selector: 'app-library-creator',
@@ -97,21 +98,21 @@ export class LibraryCreatorComponent {
}
addLibrary() {
const newLibrary = {
const library: Library = {
name: this.libraryName,
paths: this.folders,
icon: this.selectedIcon ? this.selectedIcon.replace('pi pi-', '') : 'heart'
icon: this.selectedIcon?.replace('pi pi-', '') || 'heart',
paths: this.folders.map(folder => ({ path: folder }))
};
this.libraryService.createLibrary(newLibrary).subscribe({
this.libraryService.createLibrary(library).subscribe({
next: (createdLibrary) => {
this.router.navigate(
['/library', createdLibrary.id, 'books']
);
this.router.navigate(['/library', createdLibrary.id, 'books']);
},
error: (err) => {
console.error('Failed to create library:', err);
}
});
this.dynamicDialogRef.close();
}
@@ -5,5 +5,10 @@ export interface Library {
name: string;
icon: string;
sort?: SortOption;
paths: string[];
paths: LibraryPath[];
}
export interface LibraryPath {
id?: number;
path: string;
}
@@ -16,6 +16,7 @@ import {StyleClass} from 'primeng/styleclass';
import {Divider} from 'primeng/divider';
import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component';
import {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component';
import {BookUploaderComponent} from '../../../book-uploader/book-uploader.component';
@Component({
selector: 'app-topbar',
@@ -88,12 +89,10 @@ export class AppTopBarComponent implements OnDestroy {
}
openFileUploadDialog() {
this.ref = this.dialogService.open(FileUploadComponent, {
header: 'Upload Book',
this.ref = this.dialogService.open(BookUploaderComponent, {
header: 'Book Uploader',
modal: true,
closable: true,
width: '600px',
height: '330px',
style: {
position: 'absolute',
top: '15%',