Merge pull request #212 from adityachandelgit/develop
Merge Develop into Master for Release v0.4.0
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
name-template: 'v$NEXT_PATCH_VERSION'
|
||||
name-template: 'v$NEXT_PATCH_VERSION 🌟'
|
||||
tag-template: 'v$NEXT_PATCH_VERSION'
|
||||
|
||||
categories:
|
||||
@@ -23,31 +23,9 @@ categories:
|
||||
- 'ci'
|
||||
- 'cd'
|
||||
- 'workflow'
|
||||
- title: '🗂️ Other'
|
||||
labels:
|
||||
- 'other'
|
||||
- 'misc'
|
||||
- '*'
|
||||
|
||||
change-template: '- $TITLE (#$NUMBER) by @$AUTHOR'
|
||||
|
||||
template: |
|
||||
## Release Notes:
|
||||
|
||||
### 🚀 Features:
|
||||
$FEATURES
|
||||
|
||||
### 🐛 Bug Fixes:
|
||||
$BUGS
|
||||
|
||||
### 🛠️ Refactoring:
|
||||
$REFACTOR
|
||||
|
||||
### 📖 Documentation:
|
||||
$DOCS
|
||||
|
||||
### ⚙️ CI/CD:
|
||||
$CICD
|
||||
|
||||
### 🗂️ Other:
|
||||
$OTHER
|
||||
## 🌟 Changes in this release:
|
||||
$CHANGES
|
||||
+3
-6
@@ -10,25 +10,22 @@ COPY ./booklore-ui /angular-app/
|
||||
RUN npm run build --configuration=production
|
||||
|
||||
# Stage 2: Build the Spring Boot app with Gradle
|
||||
FROM gradle:jdk21-alpine AS springboot-build
|
||||
FROM gradle:8-jdk21-alpine AS springboot-build
|
||||
|
||||
WORKDIR /springboot-app
|
||||
|
||||
COPY ./booklore-api/gradlew ./booklore-api/gradle/ /springboot-app/
|
||||
COPY ./booklore-api/build.gradle ./booklore-api/settings.gradle /springboot-app/
|
||||
COPY ./booklore-api/gradle /springboot-app/gradle
|
||||
COPY ./booklore-api/src /springboot-app/src
|
||||
COPY ./booklore-api/src/main/resources/application.yaml /springboot-app/src/main/resources/application.yaml
|
||||
|
||||
# Inject version into application.yaml using yq
|
||||
ARG APP_VERSION
|
||||
RUN apk add --no-cache yq && \
|
||||
yq eval '.app.version = strenv(APP_VERSION)' -i /springboot-app/src/main/resources/application.yaml
|
||||
|
||||
RUN ./gradlew clean build
|
||||
RUN gradle clean build
|
||||
|
||||
# Stage 3: Final image
|
||||
FROM eclipse-temurin:21.0.5_11-jre-alpine
|
||||
FROM eclipse-temurin:21-jre-alpine
|
||||
|
||||
RUN apk update && apk add nginx
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ BookLore is a self-hosted web app for organizing and managing your personal book
|
||||
- **Organized Book Management** – Categorize books using Libraries and Shelves for better organization.
|
||||
- **Smart Metadata Handling** – Automatically fetch book details from sources like Goodreads, Amazon, and Google Books, or edit them manually.
|
||||
- **Multi-User Support** – Admins can create user accounts, assign libraries, and manage permissions for metadata edits, uploads, and downloads.
|
||||
- **Powerful eBook & PDF Reader** – A feature-rich reader for PDFs and ePubs, with per-user progress tracking and customizable reading settings.
|
||||
- **Powerful eBook & PDF Reader** – A feature-rich reader for PDFs and ePubs, with customizable reading settings.
|
||||
- **And More to Come!** – Continuous improvements and exciting new features are in development.
|
||||
|
||||
BookLore is perfect for self-hosters who want complete control over their digital library. Stay tuned for updates!
|
||||
@@ -120,14 +120,36 @@ Password: admin123
|
||||
|
||||
The following environment variables can be configured:
|
||||
|
||||
| Variable Name | Description | Default Value |
|
||||
|-------------------|---------------------------|---------------------------------------------------------------------|
|
||||
| DATABASE_URL | JDBC connection URL | `jdbc:mariadb://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}` |
|
||||
| DATABASE_HOST | Database hostname | `mariadb` |
|
||||
| DATABASE_PORT | Database port | `3306` |
|
||||
| DATABASE_NAME | Database name | `booklore` |
|
||||
| DATABASE_USERNAME | Database username for app | `root` |
|
||||
| DATABASE_PASSWORD | Database password for app | **required** |
|
||||
| Variable Name | Description | Default Value |
|
||||
|------------------------------|-----------------------------------------|---------------------------------------------------------------------|
|
||||
| DATABASE_URL | JDBC connection URL | `jdbc:mariadb://${DATABASE_HOST}:${DATABASE_PORT}/${DATABASE_NAME}` |
|
||||
| DATABASE_HOST | Database hostname | `mariadb` |
|
||||
| DATABASE_PORT | Database port | `3306` |
|
||||
| DATABASE_NAME | Database name | `booklore` |
|
||||
| DATABASE_USERNAME | Database username for app | `root` |
|
||||
| DATABASE_PASSWORD | Database password for app | **required** |
|
||||
| REMOTE_AUTH_ENABLED | Enable remote authentication | `false` |
|
||||
| REMOTE_AUTH_CREATE_NEW_USERS | Auto-create users from remote auth | `true` |
|
||||
| REMOTE_AUTH_HEADER_NAME | HTTP header containing user's name | `Remote-Name` |
|
||||
| REMOTE_AUTH_HEADER_USER | HTTP header containing username | `Remote-User` |
|
||||
| REMOTE_AUTH_HEADER_EMAIL | HTTP header containing user's email | `Remote-Email` |
|
||||
| REMOTE_AUTH_HEADER_GROUPS | HTTP header containing user's groups | `Remote-Groups` |
|
||||
| REMOTE_AUTH_ADMIN_GROUP | Group name that grants admin privileges | - |
|
||||
| LOG_LEVEL | Log level for the application | `INFO` |
|
||||
| ROOT_LOG_LEVEL | If you want to see all Spring logs | `INFO` |
|
||||
|
||||
### Remote Authentication (Trusted Header SSO, Forward Auth)
|
||||
|
||||
If you run BookLore behind a reverse proxy with remote authentication (middleware),
|
||||
you can enable automatic login by setting `REMOTE_AUTH_ENABLED` to `true`.
|
||||
|
||||
This allows you to use your existing authentication system (e.g., OAuth, SAML) to log in to BookLore.
|
||||
|
||||
Example implementations:
|
||||
- https://www.authelia.com/integration/trusted-header-sso/introduction/
|
||||
- https://caddyserver.com/docs/caddyfile/directives/forward_auth
|
||||
- https://doc.traefik.io/traefik/middlewares/http/forwardauth/
|
||||
- https://github.com/sevensolutions/traefik-oidc-auth (Traefik OIDC Auth)
|
||||
|
||||
## 🤝 Community & Support
|
||||
|
||||
|
||||
@@ -11,4 +11,19 @@ import org.springframework.stereotype.Component;
|
||||
@Setter
|
||||
public class AppProperties {
|
||||
private String pathConfig;
|
||||
private String version;
|
||||
|
||||
private RemoteAuth remoteAuth;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class RemoteAuth {
|
||||
private boolean enabled;
|
||||
private boolean createNewUsers;
|
||||
private String headerName;
|
||||
private String headerUser;
|
||||
private String headerEmail;
|
||||
private String headerGroups;
|
||||
private String adminGroup;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.WebSocketMessageBrokerStats;
|
||||
|
||||
@Configuration
|
||||
public class BeanConfig {
|
||||
|
||||
@Autowired
|
||||
private WebSocketMessageBrokerStats webSocketMessageBrokerStats;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
webSocketMessageBrokerStats.setLoggingPeriod(30 * 24 * 60 * 60 * 1000L); // 30 days
|
||||
}
|
||||
}
|
||||
+27
-3
@@ -1,10 +1,12 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -13,12 +15,15 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class AuthenticationService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserRepository userRepository;
|
||||
private final UserCreatorService userCreatorService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
@@ -34,15 +39,34 @@ public class AuthenticationService {
|
||||
throw ApiError.INVALID_CREDENTIALS.createException();
|
||||
}
|
||||
|
||||
return loginUser(user);
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginRemote(String name, String username, String email, String groups) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
throw ApiError.BAD_REQUEST.createException("Remote-User header is missing");
|
||||
}
|
||||
|
||||
Optional<BookLoreUserEntity> user = userRepository.findByUsername(username);
|
||||
if (user.isEmpty() && appProperties.getRemoteAuth().isCreateNewUsers()) {
|
||||
user = Optional.of(userCreatorService.createRemoteUser(name, username, email, groups));
|
||||
}
|
||||
|
||||
if (user.isEmpty()) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("User not found and remote user creation is disabled");
|
||||
}
|
||||
|
||||
return loginUser(user.get());
|
||||
}
|
||||
|
||||
public ResponseEntity<Map<String, String>> loginUser(BookLoreUserEntity user) {
|
||||
String accessToken = jwtUtils.generateAccessToken(user);
|
||||
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||
|
||||
boolean isDefaultPassword = user.isDefaultPassword();
|
||||
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"accessToken", accessToken,
|
||||
"refreshToken", refreshToken,
|
||||
"isDefaultPassword", String.valueOf(isDefaultPassword)
|
||||
"isDefaultPassword", String.valueOf(user.isDefaultPassword())
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,16 @@ import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.service.JwtSecretService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
|
||||
@@ -52,9 +57,9 @@ public class JwtUtils {
|
||||
extractClaims(token);
|
||||
return true;
|
||||
} catch (ExpiredJwtException e) {
|
||||
System.out.println("Token expired: " + e.getMessage());
|
||||
log.debug("Token expired: {}", e.getMessage());
|
||||
} catch (JwtException e) {
|
||||
System.out.println("Invalid token: " + e.getMessage());
|
||||
log.debug("Invalid token: {}", e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
+1
-1
@@ -36,7 +36,7 @@ public class SecurityConfig {
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login", "/api/v1/auth/refresh").permitAll()
|
||||
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login", "/api/v1/auth/refresh", "/api/v1/auth/remote").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll()
|
||||
.requestMatchers("/api/v1/books/*/cover").permitAll()
|
||||
.requestMatchers(
|
||||
|
||||
+23
-4
@@ -1,26 +1,29 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.RefreshTokenRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserLoginRequest;
|
||||
import com.adityachandel.booklore.service.user.UserCreatorService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
public class AuthenticationController {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserCreatorService userCreatorService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@@ -40,4 +43,20 @@ public class AuthenticationController {
|
||||
public ResponseEntity<Map<String, String>> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
|
||||
return authenticationService.refreshToken(request.getRefreshToken());
|
||||
}
|
||||
|
||||
@GetMapping("/remote")
|
||||
public ResponseEntity<Map<String, String>> loginRemote(@RequestHeader Map<String, String> headers) {
|
||||
if (!appProperties.getRemoteAuth().isEnabled()) {
|
||||
throw ApiError.REMOTE_AUTH_DISABLED.createException();
|
||||
}
|
||||
|
||||
String name = headers.get(appProperties.getRemoteAuth().getHeaderName().toLowerCase(Locale.ROOT));
|
||||
String username = headers.get(appProperties.getRemoteAuth().getHeaderUser().toLowerCase(Locale.ROOT));
|
||||
String email = headers.get(appProperties.getRemoteAuth().getHeaderEmail().toLowerCase(Locale.ROOT));
|
||||
String groups = headers.get(appProperties.getRemoteAuth().getHeaderGroups().toLowerCase(Locale.ROOT));
|
||||
log.debug("Remote-Auth: retrieved values from headers: name: {}, username: {}, email: {}, groups: {}", name, username, email, groups);
|
||||
log.debug("Remote-Auth: remote auth settings: {}", appProperties.getRemoteAuth());
|
||||
|
||||
return authenticationService.loginRemote(name, username, email, groups);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -11,6 +11,8 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/files")
|
||||
@@ -20,7 +22,7 @@ public class FileUploadController {
|
||||
|
||||
@PreAuthorize("@securityUtil.canUpload()")
|
||||
@PostMapping(value = "/upload", consumes = "multipart/form-data")
|
||||
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) {
|
||||
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("libraryId") long libraryId, @RequestParam("pathId") long pathId) throws IOException {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("Uploaded file is missing.");
|
||||
}
|
||||
|
||||
@@ -39,7 +39,8 @@ public enum ApiError {
|
||||
PASSWORD_INCORRECT(HttpStatus.BAD_REQUEST, "Incorrect current password"),
|
||||
PASSWORD_TOO_SHORT(HttpStatus.BAD_REQUEST, "Password must be at least 6 characters long"),
|
||||
PASSWORD_SAME_AS_CURRENT(HttpStatus.BAD_REQUEST, "New password cannot be the same as the current password"),
|
||||
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials");
|
||||
INVALID_CREDENTIALS(HttpStatus.BAD_REQUEST, "Invalid credentials"),
|
||||
REMOTE_AUTH_DISABLED(HttpStatus.NON_AUTHORITATIVE_INFORMATION, "Remote login is disabled");
|
||||
|
||||
private final HttpStatus status;
|
||||
private final String message;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class UploadedFileMetadata {
|
||||
private String title;
|
||||
private Set<String> authors;
|
||||
}
|
||||
+3
-10
@@ -11,16 +11,9 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AppSettings {
|
||||
private CoverSettings coverSettings;
|
||||
private String coverResolution;
|
||||
private MetadataRefreshOptions metadataRefreshOptions;
|
||||
private boolean autoBookSearch;
|
||||
private boolean similarBookRecommendation;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class CoverSettings {
|
||||
private String resolution;
|
||||
}
|
||||
}
|
||||
private String uploadPattern;
|
||||
}
|
||||
+21
-33
@@ -26,6 +26,7 @@ public class AppSettingService {
|
||||
public static final String AUTO_BOOK_SEARCH = "auto_book_search";
|
||||
public static final String COVER_IMAGE_RESOLUTION = "cover_image_resolution";
|
||||
public static final String SIMILAR_BOOK_RECOMMENDATION = "similar_book_recommendation";
|
||||
public static final String UPLOAD_FILE_PATTERN = "upload_file_pattern";
|
||||
|
||||
private volatile AppSettings appSettings;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
@@ -44,21 +45,19 @@ public class AppSettingService {
|
||||
return appSettings;
|
||||
}
|
||||
|
||||
public boolean isSimilarBookRecommendationEnabled() {
|
||||
return getAppSettings().isSimilarBookRecommendation();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateSetting(String name, Object val) throws JsonProcessingException {
|
||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||
if (setting == null) {
|
||||
throw new IllegalArgumentException("Setting not found for name: " + name);
|
||||
}
|
||||
if (name.equals(QUICK_BOOK_MATCH)) {
|
||||
|
||||
if (QUICK_BOOK_MATCH.equals(name)) {
|
||||
setting.setVal(objectMapper.writeValueAsString(val));
|
||||
} else {
|
||||
setting.setVal(val.toString());
|
||||
}
|
||||
|
||||
appSettingsRepository.save(setting);
|
||||
refreshCache();
|
||||
}
|
||||
@@ -75,7 +74,6 @@ public class AppSettingService {
|
||||
private AppSettings buildAppSettings() {
|
||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||
|
||||
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
||||
|
||||
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
||||
@@ -83,36 +81,26 @@ public class AppSettingService {
|
||||
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
||||
builder.metadataRefreshOptions(options);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse setting 'quick_book_match'", e);
|
||||
throw new RuntimeException("Failed to parse setting: " + QUICK_BOOK_MATCH, e);
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey(COVER_IMAGE_RESOLUTION)) {
|
||||
builder.coverSettings(AppSettings.CoverSettings.builder()
|
||||
.resolution(settingsMap.get(COVER_IMAGE_RESOLUTION))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey(AUTO_BOOK_SEARCH)) {
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingsMap.get(AUTO_BOOK_SEARCH)));
|
||||
} else {
|
||||
AppSettingEntity setting = new AppSettingEntity();
|
||||
setting.setName(AUTO_BOOK_SEARCH);
|
||||
setting.setVal("true");
|
||||
appSettingsRepository.save(setting);
|
||||
builder.autoBookSearch(true);
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey(SIMILAR_BOOK_RECOMMENDATION)) {
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(settingsMap.get(SIMILAR_BOOK_RECOMMENDATION)));
|
||||
} else {
|
||||
AppSettingEntity setting = new AppSettingEntity();
|
||||
setting.setName(SIMILAR_BOOK_RECOMMENDATION);
|
||||
setting.setVal("true");
|
||||
appSettingsRepository.save(setting);
|
||||
builder.similarBookRecommendation(true);
|
||||
}
|
||||
|
||||
builder.coverResolution(getOrCreateSetting(COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(getOrCreateSetting(AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(getOrCreateSetting(UPLOAD_FILE_PATTERN, ""));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private String getOrCreateSetting(String name, String defaultValue) {
|
||||
AppSettingEntity existing = appSettingsRepository.findByName(name);
|
||||
if (existing != null) {
|
||||
return existing.getVal();
|
||||
}
|
||||
AppSettingEntity newSetting = new AppSettingEntity();
|
||||
newSetting.setName(name);
|
||||
newSetting.setVal(defaultValue);
|
||||
appSettingsRepository.save(newSetting);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
|
||||
public interface BookFileMetadataExtractor {
|
||||
|
||||
UploadedFileMetadata extractMetadata(String filePath);
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import io.documentnode.epub4j.domain.Author;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EpubMetadataExtractor implements BookFileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||
|
||||
try (FileInputStream fis = new FileInputStream(filePath)) {
|
||||
Book epubBook = new EpubReader().readEpub(fis);
|
||||
|
||||
String title = epubBook.getTitle();
|
||||
if (title != null && !title.isBlank()) {
|
||||
metadata.setTitle(title);
|
||||
}
|
||||
|
||||
List<Author> epubAuthors = epubBook.getMetadata().getAuthors();
|
||||
if (!epubAuthors.isEmpty()) {
|
||||
Set<String> authors = epubAuthors.stream()
|
||||
.map(author -> author.getFirstname() + " " + author.getLastname())
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
metadata.setAuthors(authors);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to extract metadata from EPUB file {}: {}", filePath, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("Unexpected error while reading EPUB file {}: {}", filePath, e.getMessage());
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
+75
-26
@@ -1,8 +1,10 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
@@ -18,16 +20,18 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
@Slf4j
|
||||
public class FileUploadService {
|
||||
|
||||
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB
|
||||
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;
|
||||
private static final String PDF_MIME_TYPE = "application/pdf";
|
||||
private static final String EPUB_MIME_TYPE = "application/epub+zip";
|
||||
|
||||
@@ -35,11 +39,16 @@ public class FileUploadService {
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final NotificationService notificationService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
|
||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) {
|
||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
|
||||
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
validateFile(file);
|
||||
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
|
||||
.stream()
|
||||
@@ -47,29 +56,53 @@ public class FileUploadService {
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
|
||||
|
||||
Path storagePath = Paths.get(libraryPathEntity.getPath(), Objects.requireNonNull(file.getOriginalFilename()));
|
||||
File storageFile = storagePath.toFile();
|
||||
|
||||
if (storageFile.exists()) {
|
||||
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
||||
}
|
||||
Path tempPath = Files.createTempFile("upload-", Objects.requireNonNull(file.getOriginalFilename()));
|
||||
UploadedFileMetadata metadata;
|
||||
|
||||
try {
|
||||
file.transferTo(storagePath); // storagePath here is required for windows, otherwise it will be resoled relative to Tomcat FS
|
||||
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
|
||||
Book book = processFile(file, libraryEntity, libraryPathEntity, storageFile);
|
||||
file.transferTo(tempPath);
|
||||
|
||||
String fileType = Objects.requireNonNull(file.getContentType());
|
||||
|
||||
if (fileType.equalsIgnoreCase(PDF_MIME_TYPE)) {
|
||||
metadata = pdfMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
} else if (fileType.equalsIgnoreCase(EPUB_MIME_TYPE)) {
|
||||
metadata = epubMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
} else {
|
||||
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
|
||||
}
|
||||
|
||||
String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim();
|
||||
String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : "";
|
||||
String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename());
|
||||
|
||||
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
|
||||
File finalFile = finalPath.toFile();
|
||||
|
||||
if (finalFile.exists()) {
|
||||
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
||||
}
|
||||
|
||||
Files.createDirectories(finalPath.getParent());
|
||||
Files.move(tempPath, finalPath);
|
||||
|
||||
log.info("File uploaded to final location: {}", finalPath);
|
||||
|
||||
Book book = processFile(file, libraryEntity, libraryPathEntity, finalFile);
|
||||
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);
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
} finally {
|
||||
Files.deleteIfExists(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file) {
|
||||
String fileType = file.getContentType();
|
||||
if ((!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType))) {
|
||||
if (!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType)) {
|
||||
throw ApiError.INVALID_FILE_FORMAT.createException();
|
||||
}
|
||||
if (file.getSize() > MAX_FILE_SIZE) {
|
||||
@@ -93,18 +126,34 @@ public class FileUploadService {
|
||||
.fileName(file.getOriginalFilename())
|
||||
.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();
|
||||
}
|
||||
return switch (fileType) {
|
||||
case PDF -> pdfProcessor.processFile(libraryFile, false);
|
||||
case EPUB -> epubProcessor.processFile(libraryFile, false);
|
||||
};
|
||||
}
|
||||
|
||||
private String resolveUploadPath(String pattern, String title, String authors, String filename) {
|
||||
String path = pattern;
|
||||
boolean hasTitle = !title.isEmpty();
|
||||
boolean hasAuthors = !authors.isEmpty();
|
||||
|
||||
if (hasTitle) {
|
||||
path = path.replace("{title}", sanitize(title));
|
||||
}
|
||||
if (hasAuthors) {
|
||||
path = path.replace("{authors}", sanitize(authors));
|
||||
}
|
||||
if (!hasTitle && pattern.contains("{title}")) {
|
||||
return filename;
|
||||
}
|
||||
if (!hasAuthors && pattern.contains("{authors}")) {
|
||||
return hasTitle ? path.replace("{authors}", "").replaceAll("//+", "/") + "/" + filename : filename;
|
||||
}
|
||||
return path + "/" + filename;
|
||||
}
|
||||
|
||||
private String sanitize(String value) {
|
||||
return value.replaceAll("[\\/:*?\"<>|]", "").trim();
|
||||
}
|
||||
|
||||
private BookFileType determineFileType(String fileType) {
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PdfMetadataExtractor implements BookFileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||
File file = new File(filePath);
|
||||
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||
try (PDDocument pdf = Loader.loadPDF(file)) {
|
||||
PDDocumentInformation info = pdf.getDocumentInformation();
|
||||
if (info != null) {
|
||||
if (info.getTitle() != null && !info.getTitle().isBlank()) {
|
||||
metadata.setTitle(info.getTitle());
|
||||
}
|
||||
if (info.getAuthor() != null && !info.getAuthor().isBlank()) {
|
||||
metadata.setAuthors(Set.of(info.getAuthor().split(",")));
|
||||
}
|
||||
} else {
|
||||
log.warn("No document information found in: {}", filePath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error loading PDF file: {}, error: {}", filePath, e.getMessage());
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -34,7 +34,7 @@ public class FileProcessingUtils {
|
||||
}
|
||||
|
||||
public boolean saveCoverImage(BufferedImage coverImage, long bookId) throws IOException {
|
||||
String resolution = appSettingService.getAppSettings().getCoverSettings().getResolution();
|
||||
String resolution = appSettingService.getAppSettings().getCoverResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
+52
-11
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service.user;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.BookPreferences;
|
||||
import com.adityachandel.booklore.model.dto.UserCreateRequest;
|
||||
@@ -13,10 +14,12 @@ import com.adityachandel.booklore.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -25,6 +28,7 @@ import java.util.Optional;
|
||||
@AllArgsConstructor
|
||||
public class UserCreatorService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserRepository userRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
@@ -59,15 +63,48 @@ public class UserCreatorService {
|
||||
user.setLibraries(new ArrayList<>(libraries));
|
||||
}
|
||||
|
||||
ShelfEntity shelfEntity = ShelfEntity.builder()
|
||||
.user(user)
|
||||
.name("Favorites")
|
||||
.icon("heart")
|
||||
.build();
|
||||
userRepository.save(user);
|
||||
shelfRepository.save(shelfEntity);
|
||||
createUser(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookLoreUserEntity createRemoteUser(String name, String username, String email, String groups) {
|
||||
boolean isAdmin = false;
|
||||
if (groups != null && appProperties.getRemoteAuth().getAdminGroup() != null) {
|
||||
String groupsContent = groups.trim();
|
||||
if (groupsContent.startsWith("[") && groupsContent.endsWith("]")) {
|
||||
groupsContent = groupsContent.substring(1, groupsContent.length() - 1);
|
||||
}
|
||||
List<String> groupsList = Arrays.asList(groupsContent.split("\\s+"));
|
||||
isAdmin = groupsList.contains(appProperties.getRemoteAuth().getAdminGroup());
|
||||
log.debug("Remote-Auth: user {} will be admin: {}", username, isAdmin);
|
||||
}
|
||||
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername(username);
|
||||
user.setName(name != null ? name : username);
|
||||
user.setEmail(email);
|
||||
user.setDefaultPassword(false);
|
||||
user.setPasswordHash(passwordEncoder.encode(RandomStringUtils.secure().nextAlphanumeric(32)));
|
||||
|
||||
UserPermissionsEntity permissions = new UserPermissionsEntity();
|
||||
permissions.setUser(user);
|
||||
permissions.setPermissionUpload(true);
|
||||
permissions.setPermissionDownload(true);
|
||||
permissions.setPermissionEditMetadata(true);
|
||||
permissions.setPermissionEmailBook(true);
|
||||
permissions.setPermissionAdmin(isAdmin);
|
||||
user.setPermissions(permissions);
|
||||
|
||||
if (isAdmin) {
|
||||
List<LibraryEntity> libraries = libraryRepository.findAll();
|
||||
user.setLibraries(new ArrayList<>(libraries));
|
||||
}
|
||||
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
return createUser(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void createAdminUser() {
|
||||
BookLoreUserEntity user = new BookLoreUserEntity();
|
||||
user.setUsername("admin");
|
||||
@@ -88,16 +125,20 @@ public class UserCreatorService {
|
||||
user.setPermissions(permissions);
|
||||
user.setBookPreferences(buildDefaultBookPreferences());
|
||||
|
||||
createUser(user);
|
||||
log.info("Created admin user {}", user.getUsername());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
BookLoreUserEntity createUser(BookLoreUserEntity user) {
|
||||
ShelfEntity shelfEntity = ShelfEntity.builder()
|
||||
.user(user)
|
||||
.name("Favorites")
|
||||
.icon("heart")
|
||||
.build();
|
||||
|
||||
userRepository.save(user);
|
||||
user = userRepository.save(user);
|
||||
shelfRepository.save(shelfEntity);
|
||||
|
||||
log.info("Created admin user {}", user.getUsername());
|
||||
return user;
|
||||
}
|
||||
|
||||
public boolean doesAdminUserExist() {
|
||||
|
||||
@@ -2,6 +2,15 @@ app:
|
||||
path-config: '/app/data'
|
||||
version: 'v0.0.40'
|
||||
|
||||
remote-auth:
|
||||
enabled: ${REMOTE_AUTH_ENABLED:false}
|
||||
create-new-users: ${REMOTE_AUTH_CREATE_NEW_USERS:true}
|
||||
header-name: ${REMOTE_AUTH_HEADER_NAME:Remote-Name}
|
||||
header-user: ${REMOTE_AUTH_HEADER_USER:Remote-User}
|
||||
header-email: ${REMOTE_AUTH_HEADER_EMAIL:Remote-Email}
|
||||
header-groups: ${REMOTE_AUTH_HEADER_GROUPS:Remote-Groups}
|
||||
admin-group: ${REMOTE_AUTH_ADMIN_GROUP}
|
||||
|
||||
spring:
|
||||
servlet:
|
||||
multipart:
|
||||
@@ -39,6 +48,7 @@ spring:
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
root: ${ROOT_LOG_LEVEL:INFO}
|
||||
com.adityachandel.booklore: ${LOG_LEVEL:INFO}
|
||||
org.apache.fontbox: ERROR
|
||||
org.apache.pdfbox: ERROR
|
||||
Generated
+4
-4
@@ -28,7 +28,7 @@
|
||||
"ngx-infinite-scroll": "19.0.0",
|
||||
"primeicons": "7.0.0",
|
||||
"primeng": "19.0.10",
|
||||
"quill": "2.0.3",
|
||||
"quill": "2.0.2",
|
||||
"rxjs": "7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
"tailwindcss-primeui": "0.6.1",
|
||||
@@ -14396,9 +14396,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/quill": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/quill/-/quill-2.0.3.tgz",
|
||||
"integrity": "sha512-xEYQBqfYx/sfb33VJiKnSJp8ehloavImQ2A6564GAbqG55PGw1dAWUn1MUbQB62t0azawUS2CZZhWCjO8gRvTw==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/quill/-/quill-2.0.2.tgz",
|
||||
"integrity": "sha512-QfazNrhMakEdRG57IoYFwffUIr04LWJxbS/ZkidRFXYCQt63c1gK6Z7IHUXMx/Vh25WgPBU42oBaNzQ0K1R/xw==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"eventemitter3": "^5.0.1",
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"ngx-infinite-scroll": "19.0.0",
|
||||
"primeicons": "7.0.0",
|
||||
"primeng": "19.0.10",
|
||||
"quill": "2.0.3",
|
||||
"quill": "2.0.2",
|
||||
"rxjs": "7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
"tailwindcss-primeui": "0.6.1",
|
||||
|
||||
@@ -31,6 +31,11 @@ export class LoginComponent {
|
||||
errorMessage = '';
|
||||
|
||||
constructor(private authService: AuthService, private router: Router) {
|
||||
this.authService.remoteLogin().subscribe({
|
||||
next: () => {
|
||||
this.router.navigate(['/dashboard']);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
login(): void {
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||
|
||||
export interface CoverSettings {
|
||||
resolution: string;
|
||||
}
|
||||
|
||||
export interface AppSettings {
|
||||
autoBookSearch: boolean;
|
||||
similarBookRecommendation: boolean;
|
||||
metadataRefreshOptions: MetadataRefreshOptions;
|
||||
coverSettings?: CoverSettings
|
||||
coverResolution: string;
|
||||
uploadPattern: string;
|
||||
}
|
||||
|
||||
@@ -26,6 +26,17 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
|
||||
remoteLogin(): Observable<any> {
|
||||
return this.http.get<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/remote`).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveTokens(response.accessToken, response.refreshToken);
|
||||
this.getRxStompService().activate();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getRefreshToken();
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<div class="flex flex-col space-y-6 p-4 m-4 custom-border">
|
||||
<div>
|
||||
<h2 class="mb-3 text-lg">Enter Custom File Naming Pattern:</h2>
|
||||
<div class="flex gap-4 items-center">
|
||||
<input
|
||||
type="text"
|
||||
[(ngModel)]="uploadPattern"
|
||||
class="p-inputtext w-[500px]"
|
||||
placeholder="e.g., {title} - {authors}"
|
||||
(input)="onPatternChange(uploadPattern)"
|
||||
/>
|
||||
<p-button label="Save" icon="pi pi-check" (onClick)="savePattern()" [disabled]="!!errorMessage"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 class="mb-2">Preview:</h3>
|
||||
<p class="text-lg text-green-500">{{ generatePreview() }}</p>
|
||||
</div>
|
||||
|
||||
<div class="text-gray-400">
|
||||
<h3 class="mb-1 font-bold">Example Patterns:</h3>
|
||||
<div class="overflow-x-auto">
|
||||
<table class=" table-auto">
|
||||
<colgroup>
|
||||
<col style="width: auto;"/>
|
||||
<col style="width: 20px;"/>
|
||||
<col/>
|
||||
</colgroup>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title} - {authors}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief - Markus Zusak/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title}/{authors}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief/Markus Zusak/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title} ({authors})/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief (Markus Zusak)/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">{title}/filename.pdf</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/The Book Thief/filename.pdf</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="pr-2 break-words text-left">EMPTY</td>
|
||||
<td class="text-gray-300 text-center">→</td>
|
||||
<td class="pl-2 break-words text-left">/filename.pdf</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text text-gray-400">
|
||||
<strong>Note:</strong>
|
||||
<ul class="list-disc pl-6">
|
||||
<li>Only the placeholders {title} and {authors} are supported. These values will be extracted from the metadata of the uploaded PDF or EPUB file.</li>
|
||||
<li>Multiple authors will be joined using commas.</li>
|
||||
<li>If <code>{bookname}</code> is used but missing, the path defaults to <code>/filename.pdf</code>.</li>
|
||||
<li>If <code>{authors}</code> is used but missing, it falls back to <code>{bookname}/filename.pdf</code> if the title exists, otherwise <code>/filename.pdf</code>.
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,4 @@
|
||||
.custom-border {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Button} from 'primeng/button';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {AppSettingsService} from '../core/service/app-settings.service';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettings} from '../core/model/app-settings.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-file-upload-pattern',
|
||||
templateUrl: './file-upload-pattern.component.html',
|
||||
standalone: true,
|
||||
imports: [FormsModule, Button],
|
||||
styleUrls: ['./file-upload-pattern.component.scss']
|
||||
})
|
||||
export class FileUploadPatternComponent implements OnInit {
|
||||
title: string = 'The Book Thief';
|
||||
authors: string = 'Markus Zusak';
|
||||
uploadPattern: string = '';
|
||||
errorMessage: string = '';
|
||||
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private messageService = inject(MessageService);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
).subscribe(settings => {
|
||||
this.uploadPattern = settings?.uploadPattern || '';
|
||||
});
|
||||
}
|
||||
|
||||
generatePreview(): string {
|
||||
let path = this.uploadPattern
|
||||
.replace('{title}', this.title)
|
||||
.replace('{authors}', this.authors)
|
||||
.replace(/\/+$/, '')
|
||||
.trim();
|
||||
|
||||
return path ? `/${path}/filename.pdf` : '/filename.pdf';
|
||||
}
|
||||
|
||||
validatePattern(pattern: string): void {
|
||||
const isValid = /^[\w\s\-{}\/().]*$/.test(pattern);
|
||||
this.errorMessage = isValid ? '' : 'Pattern contains invalid characters.';
|
||||
}
|
||||
|
||||
onPatternChange(pattern: string): void {
|
||||
this.uploadPattern = pattern;
|
||||
this.validatePattern(pattern);
|
||||
}
|
||||
|
||||
savePattern(): void {
|
||||
this.saveSetting('upload_file_pattern', this.uploadPattern);
|
||||
}
|
||||
|
||||
private saveSetting(key: string, value: unknown): void {
|
||||
this.appSettingsService.saveSettings([{key, newValue: value}]).subscribe({
|
||||
next: () => this.showMessage('success', 'Settings Saved', 'The settings were successfully saved!'),
|
||||
error: () => this.showMessage('error', 'Error', 'There was an error saving the settings.')
|
||||
});
|
||||
}
|
||||
|
||||
private showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
|
||||
this.messageService.add({severity, summary, detail});
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,8 +2,8 @@
|
||||
<p-tabs [value]="tab" lazy="true">
|
||||
<p-tablist>
|
||||
<p-tab value="view">Book Details</p-tab>
|
||||
<p-tab *ngIf="canEditMetadata" value="edit">Edit Details</p-tab>
|
||||
<p-tab *ngIf="canEditMetadata" value="match">Match Book</p-tab>
|
||||
<p-tab *ngIf="canEditMetadata" value="edit">Edit Metadata</p-tab>
|
||||
<p-tab *ngIf="canEditMetadata" value="match">Search Metadata</p-tab>
|
||||
</p-tablist>
|
||||
<p-tabpanels class="h-[calc(100vh-10rem)]">
|
||||
<p-tabpanel value="view">
|
||||
|
||||
+54
-6
@@ -186,16 +186,14 @@
|
||||
<label for="reviewCount">Rating Count (Legacy)</label>
|
||||
<div class="flex justify-between items-center gap-2">
|
||||
<input [disabled]="true" pInputText id="reviewCount" formControlName="reviewCount" class="w-full"/>
|
||||
<p-button disabled *ngIf="!metadata['reviewCountLocked']" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('reviewCount')" severity="success"></p-button>
|
||||
<p-button disabled *ngIf="metadata['reviewCountLocked']" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('reviewCount')" severity="warn"></p-button>
|
||||
<p-button disabled icon="pi pi-lock" [outlined]="true" severity="warn"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 w-1/4">
|
||||
<label for="rating">Rating (Legacy)</label>
|
||||
<div class="flex justify-between items-center gap-2">
|
||||
<input [disabled]="true" pInputText id="rating" formControlName="rating" class="w-full"/>
|
||||
<p-button disabled *ngIf="!metadata['ratingLocked']" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('rating')" severity="success"></p-button>
|
||||
<p-button disabled *ngIf="metadata['ratingLocked']" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('rating')" severity="warn"></p-button>
|
||||
<p-button disabled icon="pi pi-lock" [outlined]="true" severity="warn"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -241,9 +239,59 @@
|
||||
|
||||
<div class="flex flex-row w-full pb-1">
|
||||
<div class="flex flex-col gap-1 w-full">
|
||||
<label for="description">Description</label>
|
||||
<div class="flex justify-between items-center gap-2">
|
||||
<textarea rows="14" pTextarea id="description" formControlName="description" class="w-full"></textarea>
|
||||
<p-tabs value="editor" class="w-full">
|
||||
<p-tablist>
|
||||
<p-tab value="editor">WYSIWYG Editor</p-tab>
|
||||
<p-tab value="html">HTML Editor</p-tab>
|
||||
</p-tablist>
|
||||
<p-tabpanels>
|
||||
<p-tabpanel value="editor">
|
||||
<form [formGroup]="metadataForm">
|
||||
<p-editor #quillEditor formControlName="description" [readonly]="quillDisabled()" [style]="{ height: '215px' }">
|
||||
<ng-template #header>
|
||||
<span class="ql-formats">
|
||||
<button class="ql-bold" aria-label="Bold"></button>
|
||||
<button class="ql-italic" aria-label="Italic"></button>
|
||||
<button class="ql-underline" aria-label="Underline"></button>
|
||||
<button class="ql-strike" aria-label="Strikethrough"></button>
|
||||
</span>
|
||||
<span class="ql-formats">
|
||||
<select class="ql-size" aria-label="Font Size">
|
||||
<option value="small">Small</option>
|
||||
<option selected>Normal</option>
|
||||
<option value="large">Large</option>
|
||||
<option value="huge">Huge</option>
|
||||
</select>
|
||||
</span>
|
||||
<span class="ql-formats">
|
||||
<button class="ql-list" value="ordered" aria-label="Numbered List"></button>
|
||||
<button class="ql-list" value="bullet" aria-label="Bullet List"></button>
|
||||
</span>
|
||||
<span class="ql-formats">
|
||||
<select class="ql-color" aria-label="Text Color"></select>
|
||||
<select class="ql-background" aria-label="Background Color"></select>
|
||||
</span>
|
||||
<span class="ql-formats">
|
||||
<button class="ql-clean" aria-label="Remove Formatting"></button>
|
||||
</span>
|
||||
</ng-template>
|
||||
</p-editor>
|
||||
</form>
|
||||
</p-tabpanel>
|
||||
<p-tabpanel value="html" class="w-full">
|
||||
<textarea
|
||||
class="w-full p-4"
|
||||
rows="10"
|
||||
[disabled]="quillDisabled()"
|
||||
[ngModel]="htmlTextarea"
|
||||
(ngModelChange)="onHtmlTextareaChange($event)"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
placeholder="Edit raw HTML here">
|
||||
</textarea>
|
||||
</p-tabpanel>
|
||||
</p-tabpanels>
|
||||
</p-tabs>
|
||||
<p-button *ngIf="!metadata['descriptionLocked']" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success"></p-button>
|
||||
<p-button *ngIf="metadata['descriptionLocked']" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn"></p-button>
|
||||
</div>
|
||||
|
||||
+71
-22
@@ -1,6 +1,5 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {Component, inject, OnInit, ViewChild} from '@angular/core';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Textarea} from 'primeng/textarea';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {FormControl, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
@@ -15,6 +14,9 @@ import {HttpResponse} from '@angular/common/http';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {Editor} from 'primeng/editor';
|
||||
import {debounceTime} from 'rxjs/operators';
|
||||
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-editor',
|
||||
@@ -23,7 +25,6 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
styleUrls: ['./metadata-editor.component.scss'],
|
||||
imports: [
|
||||
InputText,
|
||||
Textarea,
|
||||
Button,
|
||||
Divider,
|
||||
FormsModule,
|
||||
@@ -33,11 +34,19 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
FileUpload,
|
||||
ProgressSpinner,
|
||||
NgClass,
|
||||
Tooltip
|
||||
Tooltip,
|
||||
Editor,
|
||||
Tabs,
|
||||
TabList,
|
||||
Tab,
|
||||
TabPanels,
|
||||
TabPanel
|
||||
]
|
||||
})
|
||||
export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
@ViewChild(Editor) quillEditor!: Editor;
|
||||
|
||||
private metadataCenterService = inject(BookMetadataCenterService);
|
||||
private messageService = inject(MessageService);
|
||||
private bookService = inject(BookService);
|
||||
@@ -48,6 +57,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
currentBookId!: number;
|
||||
isUploading = false;
|
||||
isLoading = false;
|
||||
htmlTextarea = '';
|
||||
|
||||
constructor() {
|
||||
this.metadataForm = new FormGroup({
|
||||
@@ -101,6 +111,11 @@ export class MetadataEditorComponent implements OnInit {
|
||||
if (metadata) {
|
||||
this.currentBookId = metadata.bookId;
|
||||
|
||||
if (this.quillEditor && this.quillEditor.quill) {
|
||||
this.quillEditor.quill.root.innerHTML = metadata.description;
|
||||
this.quillDisabled();
|
||||
}
|
||||
|
||||
this.metadataForm.patchValue({
|
||||
title: metadata.title || null,
|
||||
subtitle: metadata.subtitle || null,
|
||||
@@ -146,27 +161,46 @@ export class MetadataEditorComponent implements OnInit {
|
||||
thumbnailUrlLocked: metadata.coverLocked || false,
|
||||
});
|
||||
|
||||
if (metadata.titleLocked) this.metadataForm.get('title')?.disable();
|
||||
if (metadata.subtitleLocked) this.metadataForm.get('subtitle')?.disable();
|
||||
if (metadata.authorsLocked) this.metadataForm.get('authors')?.disable();
|
||||
if (metadata.categoriesLocked) this.metadataForm.get('categories')?.disable();
|
||||
if (metadata.publisherLocked) this.metadataForm.get('publisher')?.disable();
|
||||
if (metadata.publishedDateLocked) this.metadataForm.get('publishedDate')?.disable();
|
||||
if (metadata.languageLocked) this.metadataForm.get('language')?.disable();
|
||||
if (metadata.isbn10Locked) this.metadataForm.get('isbn10')?.disable();
|
||||
if (metadata.isbn13Locked) this.metadataForm.get('isbn13')?.disable();
|
||||
const lockableFields: { key: keyof BookMetadata, control: string }[] = [
|
||||
{ key: 'titleLocked', control: 'title' },
|
||||
{ key: 'subtitleLocked', control: 'subtitle' },
|
||||
{ key: 'authorsLocked', control: 'authors' },
|
||||
{ key: 'categoriesLocked', control: 'categories' },
|
||||
{ key: 'publisherLocked', control: 'publisher' },
|
||||
{ key: 'publishedDateLocked', control: 'publishedDate' },
|
||||
{ key: 'languageLocked', control: 'language' },
|
||||
{ key: 'isbn10Locked', control: 'isbn10' },
|
||||
{ key: 'isbn13Locked', control: 'isbn13' },
|
||||
{ key: 'amazonReviewCountLocked', control: 'amazonReviewCount' },
|
||||
{ key: 'amazonRatingLocked', control: 'amazonRating' },
|
||||
{ key: 'goodreadsReviewCountLocked', control: 'goodreadsReviewCount' },
|
||||
{ key: 'goodreadsRatingLocked', control: 'goodreadsRating' },
|
||||
{ key: 'pageCountLocked', control: 'pageCount' },
|
||||
{ key: 'descriptionLocked', control: 'description' },
|
||||
{ key: 'seriesNameLocked', control: 'seriesName' },
|
||||
{ key: 'seriesNumberLocked', control: 'seriesNumber' },
|
||||
{ key: 'seriesTotalLocked', control: 'seriesTotal' }
|
||||
];
|
||||
|
||||
lockableFields.forEach(({ key, control }) => {
|
||||
const isLocked = metadata[key] === true;
|
||||
const formControl = this.metadataForm.get(control);
|
||||
if (formControl) {
|
||||
isLocked ? formControl.disable() : formControl.enable();
|
||||
}
|
||||
});
|
||||
|
||||
this.metadataForm.get('reviewCount')?.disable();
|
||||
this.metadataForm.get('rating')?.disable();
|
||||
if (metadata.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable();
|
||||
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable();
|
||||
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable();
|
||||
if (metadata.goodreadsRatingLocked) this.metadataForm.get('goodreadsRating')?.disable();
|
||||
if (metadata.pageCountLocked) this.metadataForm.get('pageCount')?.disable();
|
||||
if (metadata.descriptionLocked) this.metadataForm.get('description')?.disable();
|
||||
if (metadata.seriesNameLocked) this.metadataForm.get('seriesName')?.disable();
|
||||
if (metadata.seriesNumberLocked) this.metadataForm.get('seriesNumber')?.disable();
|
||||
if (metadata.seriesTotalLocked) this.metadataForm.get('seriesTotal')?.disable();
|
||||
}
|
||||
|
||||
this.metadataForm.get('description')?.valueChanges
|
||||
.pipe(debounceTime(100))
|
||||
.subscribe(value => {
|
||||
if (this.htmlTextarea !== value) {
|
||||
this.htmlTextarea = value;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -216,6 +250,21 @@ export class MetadataEditorComponent implements OnInit {
|
||||
this.updateMetadata(false);
|
||||
}
|
||||
|
||||
quillDisabled(): boolean {
|
||||
return this.metadataForm.get('descriptionLocked')?.value === true;
|
||||
}
|
||||
|
||||
onHtmlTextareaChange(value: string): void {
|
||||
this.htmlTextarea = value;
|
||||
const control = this.metadataForm.get('description');
|
||||
if (control?.value !== value) {
|
||||
control?.patchValue(value, { emitEvent: false });
|
||||
if (this.quillEditor && this.quillEditor.quill) {
|
||||
this.quillEditor.quill.root.innerHTML = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private buildMetadata(shouldLockAllFields: boolean | undefined) {
|
||||
const updatedBookMetadata: BookMetadata = {
|
||||
bookId: this.currentBookId,
|
||||
|
||||
+7
-3
@@ -75,9 +75,13 @@
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div *ngIf="metadata$ | async as metadata" class="flex-1 overflow-auto space-y-2 px-2">
|
||||
<div [ngClass]="{ 'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded }"
|
||||
class="transition-all duration-300 overflow-hidden description-container">
|
||||
<div class="description-content" [innerHTML]="metadata.description || 'No description available.'"></div>
|
||||
<div [ngClass]="{ 'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded }" class="transition-all duration-300 overflow-hidden description-container">
|
||||
<div class="readonly-editor px-2">
|
||||
<p-editor #quillEditor [readonly]="true" [style]="{height: '260px'}" [(ngModel)]="metadata.description">
|
||||
<ng-template #header>
|
||||
</ng-template>
|
||||
</p-editor>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div *ngIf="metadata.description && metadata.description.length > 100" class="text-left">
|
||||
|
||||
+17
-12
@@ -1,17 +1,22 @@
|
||||
::ng-deep .ql-toolbar.ql-snow {
|
||||
padding: 0 !important;
|
||||
::ng-deep .readonly-editor .p-editor {
|
||||
.p-editor-toolbar.ql-snow {
|
||||
padding: 0 !important;
|
||||
border: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.p-editor-content.ql-snow {
|
||||
border: none !important;
|
||||
border-end-end-radius: 0 !important;
|
||||
border-end-start-radius: 0 !important;
|
||||
}
|
||||
|
||||
.ql-editor {
|
||||
padding: 0 !important;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .p-editor .p-editor-toolbar.ql-snow {
|
||||
border: 0.5px solid var(--p-editor-toolbar-border-color) !important;
|
||||
}
|
||||
|
||||
::ng-deep .p-editor .p-editor-content {
|
||||
border-end-end-radius: 0 !important;
|
||||
border-end-start-radius: 0 !important;
|
||||
}
|
||||
|
||||
::ng-deep .ql-container {
|
||||
::ng-deep .readonly-editor .ql-container {
|
||||
font-size: 14px !important;
|
||||
}
|
||||
|
||||
|
||||
+13
-5
@@ -1,4 +1,4 @@
|
||||
import {Component, DestroyRef, inject, Input, OnInit} from '@angular/core';
|
||||
import {Component, DestroyRef, inject, Input, OnInit, ViewChild} from '@angular/core';
|
||||
import {Button, ButtonDirective} from 'primeng/button';
|
||||
import {AsyncPipe, DecimalPipe, NgClass, NgForOf, NgIf} from '@angular/common';
|
||||
import {first, Observable} from 'rxjs';
|
||||
@@ -21,19 +21,22 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
import {Editor} from 'primeng/editor';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-viewer',
|
||||
standalone: true,
|
||||
templateUrl: './metadata-viewer.component.html',
|
||||
styleUrl: './metadata-viewer.component.scss',
|
||||
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective]
|
||||
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective, Editor]
|
||||
})
|
||||
export class MetadataViewerComponent implements OnInit {
|
||||
|
||||
@Input() book: Book | undefined;
|
||||
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||
|
||||
@ViewChild(Editor) quillEditor!: Editor;
|
||||
|
||||
private dialogService = inject(DialogService);
|
||||
private emailService = inject(EmailService);
|
||||
private messageService = inject(MessageService);
|
||||
@@ -78,6 +81,9 @@ export class MetadataViewerComponent implements OnInit {
|
||||
.subscribe((metadata) => {
|
||||
if (metadata) {
|
||||
this.getBooksInSeries(metadata.bookId);
|
||||
if (this.quillEditor && this.quillEditor.quill) {
|
||||
this.quillEditor.quill.root.innerHTML = metadata.description;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -142,8 +148,10 @@ export class MetadataViewerComponent implements OnInit {
|
||||
}
|
||||
|
||||
isMetadataFullyLocked(metadata: BookMetadata): boolean {
|
||||
return Object.keys(metadata)
|
||||
.filter(key => key.endsWith('Locked'))
|
||||
.every(key => metadata[key] === true);
|
||||
const lockedKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
if (lockedKeys.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return lockedKeys.every(key => metadata[key] === true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,18 @@
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<p class="text-xl pb-2 pt-8">
|
||||
Uploaded Files Pattern
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Define a naming pattern for future uploads using available metadata. Existing files will remain unchanged."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<app-file-upload-pattern></app-file-upload-pattern>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<p class="text-xl pb-4 pt-8">
|
||||
Quick Book Match Preferences
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
|
||||
@@ -16,6 +16,7 @@ import {AppSettings} from '../../core/model/app-settings.model';
|
||||
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
|
||||
import {MetadataAdvancedFetchOptionsComponent} from '../../metadata/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {FileUploadPatternComponent} from '../../file-upload-pattern/file-upload-pattern.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-global-preferences',
|
||||
@@ -28,7 +29,8 @@ import {filter, take} from 'rxjs/operators';
|
||||
Tooltip,
|
||||
ToggleSwitch,
|
||||
FormsModule,
|
||||
MetadataAdvancedFetchOptionsComponent
|
||||
MetadataAdvancedFetchOptionsComponent,
|
||||
FileUploadPatternComponent
|
||||
],
|
||||
templateUrl: './global-preferences.component.html',
|
||||
styleUrl: './global-preferences.component.scss'
|
||||
@@ -58,8 +60,8 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
).subscribe(settings => {
|
||||
if (settings.coverSettings) {
|
||||
this.selectedResolution = settings.coverSettings.resolution;
|
||||
if (settings?.coverResolution) {
|
||||
this.selectedResolution = settings.coverResolution;
|
||||
}
|
||||
if (settings.metadataRefreshOptions) {
|
||||
this.currentMetadataOptions = settings.metadataRefreshOptions;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
@use "sass:meta";
|
||||
@import "../node_modules/primeicons/primeicons.css";
|
||||
|
||||
@include meta.load-css("assets/layout/styles/global.scss");
|
||||
|
||||
@tailwind base;
|
||||
@@ -10,3 +11,7 @@ html {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica,
|
||||
Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||
}
|
||||
|
||||
.p-toast {
|
||||
top: 4rem !important;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user