Merge pull request #236 from adityachandelgit/develop
Merge Develop into Master for Release
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import com.adityachandel.booklore.interceptor.OpdsEnabledInterceptor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final OpdsEnabledInterceptor opdsEnabledInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(opdsEnabledInterceptor)
|
||||
.addPathPatterns("/api/v1/opds/**");
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
|
||||
import com.adityachandel.booklore.repository.OpdsUserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CustomOpdsUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final OpdsUserRepository opdsUserRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
OpdsUserEntity user = opdsUserRepository.findByUsername(username)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||
|
||||
return User.builder()
|
||||
.username(user.getUsername())
|
||||
.password(user.getPassword())
|
||||
.roles("USER")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+38
-11
@@ -1,15 +1,21 @@
|
||||
package com.adityachandel.booklore.config.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
@@ -18,12 +24,17 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@EnableMethodSecurity
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final CustomOpdsUserDetailsService customOpdsUserDetailsService;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter, CustomOpdsUserDetailsService customOpdsUserDetailsService) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.customOpdsUserDetailsService = customOpdsUserDetailsService;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
@@ -39,24 +50,39 @@ public class SecurityConfig {
|
||||
.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(
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs/**",
|
||||
"/swagger-ui.html"
|
||||
).permitAll()
|
||||
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui.html").permitAll()
|
||||
.requestMatchers("/api/v1/opds/**").authenticated()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.httpBasic(customizer -> {
|
||||
customizer.realmName("Booklore OPDS");
|
||||
})
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
|
||||
return http.getSharedObject(AuthenticationManagerBuilder.class)
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
|
||||
provider.setUserDetailsService(customOpdsUserDetailsService);
|
||||
provider.setPasswordEncoder(passwordEncoder());
|
||||
return provider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOriginPatterns(List.of("*"));
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS" , "PATCH"));
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||
configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
|
||||
configuration.setExposedHeaders(List.of("Content-Disposition"));
|
||||
configuration.setAllowCredentials(true);
|
||||
@@ -72,4 +98,5 @@ public class SecurityConfig {
|
||||
registrationBean.addUrlPatterns("/api/v1/books/*/cover");
|
||||
return registrationBean;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+2
-2
@@ -34,7 +34,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
List<String> authHeaders = accessor.getNativeHeader("Authorization");
|
||||
|
||||
if (authHeaders == null || authHeaders.isEmpty()) {
|
||||
log.warn("WebSocket connection rejected: No Authorization header");
|
||||
log.debug("WebSocket connection rejected: No Authorization header");
|
||||
throw new IllegalArgumentException("Missing Authorization header");
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
Authentication auth = authenticateToken(token);
|
||||
|
||||
if (auth == null) {
|
||||
log.warn("WebSocket connection rejected: Invalid token");
|
||||
log.debug("WebSocket connection rejected: Invalid token");
|
||||
throw new IllegalArgumentException("Invalid Authorization token");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import com.adityachandel.booklore.service.OpdsService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/opds")
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsController {
|
||||
|
||||
private final OpdsService opdsService;
|
||||
private final BooksService booksService;
|
||||
|
||||
@GetMapping(value = "/catalog", produces = "application/atom+xml;profile=opds-catalog")
|
||||
public ResponseEntity<String> getCatalogFeed(HttpServletRequest request) {
|
||||
String feed = opdsService.generateCatalogFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/atom+xml;profile=opds-catalog"))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return booksService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover.jpg")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = booksService.getBookCover(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + coverImage.getFilename() + "\"")
|
||||
.body(coverImage);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.OpdsUser;
|
||||
import com.adityachandel.booklore.model.dto.request.OpdsUserCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.PasswordResetRequest;
|
||||
import com.adityachandel.booklore.service.OpdsUserService;
|
||||
import com.adityachandel.booklore.service.user.UserService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/opds-users")
|
||||
public class OpdsUserController {
|
||||
|
||||
private final OpdsUserService opdsUserService;
|
||||
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
@PostMapping
|
||||
public ResponseEntity<Void> createOpdsUser(@RequestBody OpdsUserCreateRequest request) {
|
||||
opdsUserService.createOpdsUser(request.getUsername(), request.getPassword());
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
@GetMapping
|
||||
public ResponseEntity<List<OpdsUser>> listOpdsUsers() {
|
||||
List<OpdsUser> users = opdsUserService.getOpdsUsers();
|
||||
return ResponseEntity.ok(users);
|
||||
}
|
||||
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteOpdsUser(@PathVariable Long id) {
|
||||
opdsUserService.deleteOpdsUser(id);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PutMapping("/{userId}/reset-password")
|
||||
public ResponseEntity<Void> resetPassword(@PathVariable("userId") Long userId, @RequestBody PasswordResetRequest resetRequest) {
|
||||
opdsUserService.resetPassword(userId, resetRequest.getPassword());
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.adityachandel.booklore.interceptor;
|
||||
|
||||
import com.adityachandel.booklore.service.AppSettingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsEnabledInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||
if (request.getRequestURI().startsWith("/api/v1/opds")) {
|
||||
if (!appSettingService.getAppSettings().isOpdsServerEnabled()) {
|
||||
response.sendError(HttpServletResponse.SC_FORBIDDEN, "OPDS Server is disabled.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.adityachandel.booklore.mapper;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.OpdsUser;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface OpdsUserMapper {
|
||||
|
||||
OpdsUser toOpdsUser(OpdsUserEntity opdsUserEntity);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public class Book {
|
||||
private Long libraryId;
|
||||
private String fileName;
|
||||
private String filePath;
|
||||
private Long fileSizeKb;
|
||||
private String title;
|
||||
private Instant lastReadTime;
|
||||
private Instant addedOn;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OpdsUser {
|
||||
private Long id;
|
||||
private String username;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class OpdsUserCreateRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PasswordResetRequest {
|
||||
private String password;
|
||||
}
|
||||
+1
@@ -15,5 +15,6 @@ public class AppSettings {
|
||||
private MetadataRefreshOptions metadataRefreshOptions;
|
||||
private boolean autoBookSearch;
|
||||
private boolean similarBookRecommendation;
|
||||
private boolean opdsServerEnabled;
|
||||
private String uploadPattern;
|
||||
}
|
||||
+7
@@ -7,6 +7,9 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@@ -16,4 +19,8 @@ public class LibraryFile {
|
||||
private String fileSubPath;
|
||||
private String fileName;
|
||||
private BookFileType bookFileType;
|
||||
|
||||
public Path getFullPath() {
|
||||
return Paths.get(libraryPathEntity.getPath(), fileSubPath, fileName);
|
||||
}
|
||||
}
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "app_migration")
|
||||
public class AppMigrationEntity {
|
||||
|
||||
@Id
|
||||
@Column(name = "migration_key", nullable = false, unique = true)
|
||||
private String key;
|
||||
|
||||
@Column(name = "executed_at", nullable = false)
|
||||
private LocalDateTime executedAt;
|
||||
|
||||
@Column(name = "description")
|
||||
private String description;
|
||||
}
|
||||
@@ -31,6 +31,9 @@ public class BookEntity {
|
||||
@Column(name = "book_type")
|
||||
private BookFileType bookType;
|
||||
|
||||
@Column(name = "file_size_kb")
|
||||
private Long fileSizeKb;
|
||||
|
||||
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private BookMetadataEntity metadata;
|
||||
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
@Table(name = "opds_user")
|
||||
public class OpdsUserEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "username", nullable = false)
|
||||
private String username;
|
||||
|
||||
@Column(name = "password", nullable = false)
|
||||
private String password;
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface AppMigrationRepository extends JpaRepository<AppMigrationEntity, String> {
|
||||
}
|
||||
+2
-3
@@ -38,9 +38,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)")
|
||||
void deleteByIdIn(Collection<Long> ids);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library IN (SELECT l FROM LibraryEntity l WHERE l IN :userLibraries)")
|
||||
List<BookEntity> findBooksByUserLibraries(@Param("userLibraries") List<LibraryEntity> userLibraries);
|
||||
|
||||
List<BookEntity> findByLibraryIdIn(Set<Long> userLibraryIds);
|
||||
|
||||
List<BookEntity> findByFileSizeKbIsNull();
|
||||
}
|
||||
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface OpdsUserRepository extends JpaRepository<OpdsUserEntity, Long> {
|
||||
boolean existsByUsername(String username);
|
||||
|
||||
Optional<OpdsUserEntity> findByUsername(String username);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.AppMigrationRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class AppMigrationService {
|
||||
|
||||
private AppMigrationRepository migrationRepository;
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Transactional
|
||||
public void populateMissingFileSizesOnce() {
|
||||
if (migrationRepository.existsById("populateFileSizes")) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookRepository.findByFileSizeKbIsNull();
|
||||
for (BookEntity book : books) {
|
||||
Long sizeInKb = FileUtils.getFileSizeInKb(book);
|
||||
if (sizeInKb != null) {
|
||||
book.setFileSizeKb(sizeInKb);
|
||||
}
|
||||
}
|
||||
bookRepository.saveAll(books);
|
||||
|
||||
log.info("Starting migration 'populateFileSizes' for {} books.", books.size());
|
||||
AppMigrationEntity migration = new AppMigrationEntity();
|
||||
migration.setKey("populateFileSizes");
|
||||
migration.setExecutedAt(LocalDateTime.now());
|
||||
migration.setDescription("Populate file size for existing books");
|
||||
migrationRepository.save(migration);
|
||||
log.info("Migration 'populateFileSizes' executed successfully.");
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class AppMigrationStartup {
|
||||
|
||||
private final AppMigrationService appMigrationService;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void runMigrationsOnce() {
|
||||
appMigrationService.populateMissingFileSizesOnce();
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ public class AppSettingService {
|
||||
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";
|
||||
public static final String OPDS_SERVER_ENABLED = "opds_server_enabled";
|
||||
|
||||
private volatile AppSettings appSettings;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
@@ -89,6 +90,7 @@ public class AppSettingService {
|
||||
builder.autoBookSearch(Boolean.parseBoolean(getOrCreateSetting(AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(getOrCreateSetting(UPLOAD_FILE_PATTERN, ""));
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(OPDS_SERVER_ENABLED, "false")));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
||||
+8
-3
@@ -4,15 +4,20 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class BookCreatorService {
|
||||
@@ -23,19 +28,19 @@ public class BookCreatorService {
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
|
||||
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(libraryFile.getLibraryEntity())
|
||||
.libraryPath(libraryFile.getLibraryPathEntity())
|
||||
.fileName(libraryFile.getFileName())
|
||||
.fileSubPath(libraryFile.getFileSubPath())
|
||||
.bookType(bookFileType)
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
BookMetadataEntity bookMetadataEntity = BookMetadataEntity.builder().build();
|
||||
bookEntity.setMetadata(bookMetadataEntity);
|
||||
bookEntity = bookRepository.saveAndFlush(bookEntity);
|
||||
|
||||
return bookEntity;
|
||||
return bookRepository.saveAndFlush(bookEntity);
|
||||
}
|
||||
|
||||
public void addCategoriesToBook(List<String> categories, BookEntity bookEntity) {
|
||||
|
||||
@@ -7,10 +7,7 @@ import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -18,7 +15,6 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -32,12 +28,9 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
@@ -124,21 +117,26 @@ public class BooksService {
|
||||
public Book getBook(long bookId, boolean withDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity());
|
||||
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setLastReadTime(userProgress.getLastReadTime());
|
||||
book.setPdfProgress(userProgress.getPdfProgress());
|
||||
book.setEpubProgress(userProgress.getEpubProgress());
|
||||
book.setFilePath(bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileSubPath() + "/" + bookEntity.getFileName());
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
|
||||
if (!withDescription) {
|
||||
book.getMetadata().setDescription(null);
|
||||
}
|
||||
|
||||
return book;
|
||||
}
|
||||
|
||||
public List<Book> getBooks(boolean withDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
List<BookEntity> books;
|
||||
if (userEntity.getPermissions().isPermissionAdmin()) {
|
||||
@@ -152,12 +150,14 @@ public class BooksService {
|
||||
|
||||
return books.stream()
|
||||
.map(bookEntity -> {
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookEntity.getId())
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository
|
||||
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
|
||||
.orElse(new UserBookProgressEntity());
|
||||
Book book = bookMapper.toBookWithDescription(bookEntity, withDescription);
|
||||
book.setLastReadTime(userProgress.getLastReadTime());
|
||||
book.setPdfProgress(userProgress.getPdfProgress());
|
||||
book.setEpubProgress(userProgress.getEpubProgress());
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
return book;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
var books = bookRepository.findAll();
|
||||
var feedVersion = extractVersionFromAcceptHeader(request);
|
||||
|
||||
return switch (feedVersion) {
|
||||
case "2.0" -> generateOpdsV2Feed(books);
|
||||
default -> generateOpdsV1Feed(books);
|
||||
};
|
||||
}
|
||||
|
||||
private String extractVersionFromAcceptHeader(HttpServletRequest request) {
|
||||
var acceptHeader = request.getHeader("Accept");
|
||||
return (acceptHeader != null && acceptHeader.contains("version=2.0")) ? "2.0" : "1.2";
|
||||
}
|
||||
|
||||
private String generateOpdsV1Feed(List<BookEntity> books) {
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/">
|
||||
<title>Booklore Catalog</title>
|
||||
<id>urn:booklore:catalog</id>
|
||||
<updated>%s</updated>
|
||||
""".formatted(now()));
|
||||
|
||||
books.forEach(book -> appendBookEntryV1(feed, book));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
private void appendBookEntryV1(StringBuilder feed, BookEntity book) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:book:%d</id>
|
||||
<updated>%s</updated>
|
||||
""".formatted(escapeXml(book.getMetadata().getTitle()), book.getId(), book.getAddedOn() != null ? book.getAddedOn() : now()));
|
||||
|
||||
book.getMetadata().getAuthors().forEach(author -> feed.append("""
|
||||
<author>
|
||||
<name>%s</name>
|
||||
</author>
|
||||
""".formatted(escapeXml(author.getName()))));
|
||||
|
||||
appendOptionalTags(feed, book);
|
||||
feed.append(" </entry>");
|
||||
}
|
||||
|
||||
private void appendOptionalTags(StringBuilder feed, BookEntity book) {
|
||||
if (book.getMetadata().getPublisher() != null) {
|
||||
feed.append("<dc:publisher>").append(escapeXml(book.getMetadata().getPublisher())).append("</dc:publisher>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getLanguage() != null) {
|
||||
feed.append("<dc:language>").append(escapeXml(book.getMetadata().getLanguage())).append("</dc:language>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getCategories() != null) {
|
||||
book.getMetadata().getCategories().forEach(category ->
|
||||
feed.append("<dc:subject>").append(escapeXml(category.getName())).append("</dc:subject>")
|
||||
);
|
||||
}
|
||||
|
||||
if (book.getMetadata().getIsbn10() != null) {
|
||||
feed.append("<dc:identifier>").append(escapeXml("urn:isbn:" + book.getMetadata().getIsbn10())).append("</dc:identifier>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getPublishedDate() != null) {
|
||||
feed.append("<published>").append(book.getMetadata().getPublishedDate()).append("</published>");
|
||||
}
|
||||
|
||||
feed.append("""
|
||||
<link href="/api/v1/opds/%d/download" rel="http://opds-spec.org/acquisition" type="application/%s"/>
|
||||
""".formatted(book.getId(), fileMimeType(book)));
|
||||
|
||||
if (book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
String coverPath = "/api/v1/opds/" + book.getId() + "/cover.jpg?" + book.getMetadata().getCoverUpdatedOn();
|
||||
feed.append("""
|
||||
<link rel="http://opds-spec.org/image" href="%s" type="image/jpeg"/>
|
||||
<link rel="http://opds-spec.org/image/thumbnail" href="%s" type="image/jpeg"/>
|
||||
""".formatted(escapeXml(coverPath), escapeXml(coverPath)));
|
||||
}
|
||||
|
||||
if (book.getMetadata().getDescription() != null) {
|
||||
feed.append("<summary>").append(escapeXml(book.getMetadata().getDescription())).append("</summary>");
|
||||
}
|
||||
}
|
||||
|
||||
private String generateOpdsV2Feed(List<BookEntity> books) {
|
||||
// Placeholder for OPDS v2.0 feed implementation (similar structure as v1)
|
||||
return "OPDS v2.0 Feed is under construction";
|
||||
}
|
||||
|
||||
private String now() {
|
||||
return DateTimeFormatter.ISO_INSTANT.format(java.time.Instant.now());
|
||||
}
|
||||
|
||||
private String fileMimeType(BookEntity book) {
|
||||
return switch (book.getBookType()) {
|
||||
case PDF -> "pdf";
|
||||
case EPUB -> "epub+zip";
|
||||
default -> "octet-stream";
|
||||
};
|
||||
}
|
||||
|
||||
private String escapeXml(String input) {
|
||||
return input == null ? "" :
|
||||
input.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.OpdsUserMapper;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUser;
|
||||
import com.adityachandel.booklore.model.entity.OpdsUserEntity;
|
||||
import com.adityachandel.booklore.repository.OpdsUserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsUserService {
|
||||
|
||||
private final OpdsUserRepository opdsUserRepository;
|
||||
private final OpdsUserMapper opdsUserMapper;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public void createOpdsUser(String username, String password) {
|
||||
if (opdsUserRepository.existsByUsername(username)) {
|
||||
throw ApiError.USERNAME_ALREADY_TAKEN.createException(username);
|
||||
}
|
||||
OpdsUserEntity opdsUser = new OpdsUserEntity();
|
||||
opdsUser.setUsername(username);
|
||||
opdsUser.setPassword(passwordEncoder.encode(password));
|
||||
opdsUserRepository.save(opdsUser);
|
||||
}
|
||||
|
||||
public List<OpdsUser> getOpdsUsers() {
|
||||
return opdsUserRepository.findAll()
|
||||
.stream()
|
||||
.map(opdsUserMapper::toOpdsUser)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void deleteOpdsUser(Long id) {
|
||||
if (!opdsUserRepository.existsById(id)) {
|
||||
throw ApiError.USER_NOT_FOUND.createException(id);
|
||||
}
|
||||
opdsUserRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public void resetPassword(Long id, String newPassword) {
|
||||
OpdsUserEntity opdsUser = opdsUserRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
|
||||
opdsUser.setPassword(passwordEncoder.encode(newPassword));
|
||||
opdsUserRepository.save(opdsUser);
|
||||
}
|
||||
}
|
||||
+13
-10
@@ -40,16 +40,19 @@ public class UserService {
|
||||
|
||||
public BookLoreUser updateUser(Long id, UserUpdateRequest updateRequest) {
|
||||
BookLoreUserEntity user = userRepository.findById(id).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(id));
|
||||
|
||||
user.setName(updateRequest.getName());
|
||||
user.setEmail(updateRequest.getEmail());
|
||||
user.getPermissions().setPermissionUpload(updateRequest.getPermissions().isCanUpload());
|
||||
user.getPermissions().setPermissionDownload(updateRequest.getPermissions().isCanDownload());
|
||||
user.getPermissions().setPermissionEditMetadata(updateRequest.getPermissions().isCanEditMetadata());
|
||||
user.getPermissions().setPermissionEmailBook(updateRequest.getPermissions().isCanEmailBook());
|
||||
|
||||
List<Long> libraryIds = updateRequest.getAssignedLibraries();
|
||||
if (libraryIds != null) {
|
||||
// only admins can update permissions and assigned libraries
|
||||
if (updateRequest.getPermissions() != null && getMyself().getPermissions().isAdmin()) {
|
||||
user.getPermissions().setPermissionUpload(updateRequest.getPermissions().isCanUpload());
|
||||
user.getPermissions().setPermissionDownload(updateRequest.getPermissions().isCanDownload());
|
||||
user.getPermissions().setPermissionEditMetadata(updateRequest.getPermissions().isCanEditMetadata());
|
||||
user.getPermissions().setPermissionEmailBook(updateRequest.getPermissions().isCanEmailBook());
|
||||
}
|
||||
|
||||
if (updateRequest.getAssignedLibraries() != null && getMyself().getPermissions().isAdmin()) {
|
||||
List<Long> libraryIds = updateRequest.getAssignedLibraries();
|
||||
List<LibraryEntity> updatedLibraries = libraryRepository.findAllById(libraryIds);
|
||||
user.setLibraries(updatedLibraries);
|
||||
}
|
||||
@@ -104,7 +107,7 @@ public class UserService {
|
||||
throw ApiError.PASSWORD_SAME_AS_CURRENT.createException();
|
||||
}
|
||||
|
||||
if (!isValidPassword(changePasswordRequest.getNewPassword())) {
|
||||
if (!meetsMinimumPasswordRequirements(changePasswordRequest.getNewPassword())) {
|
||||
throw ApiError.PASSWORD_TOO_SHORT.createException();
|
||||
}
|
||||
|
||||
@@ -115,14 +118,14 @@ public class UserService {
|
||||
|
||||
public void changeUserPassword(ChangeUserPasswordRequest request) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(request.getUserId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(request.getUserId()));
|
||||
if (!isValidPassword(request.getNewPassword())) {
|
||||
if (!meetsMinimumPasswordRequirements(request.getNewPassword())) {
|
||||
throw ApiError.PASSWORD_TOO_SHORT.createException();
|
||||
}
|
||||
userEntity.setPasswordHash(passwordEncoder.encode(request.getNewPassword()));
|
||||
userRepository.save(userEntity);
|
||||
}
|
||||
|
||||
private boolean isValidPassword(String password) {
|
||||
private boolean meetsMinimumPasswordRequirements(String password) {
|
||||
return password != null && password.length() >= 6;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,45 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
public class FileUtils {
|
||||
|
||||
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
|
||||
|
||||
public static String getBookFullPath(BookEntity bookEntity) {
|
||||
return bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileSubPath() + "/" + bookEntity.getFileName();
|
||||
return String.format("%s/%s/%s", bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName());
|
||||
}
|
||||
|
||||
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
|
||||
return Optional.ofNullable(Path.of(basePath)
|
||||
.relativize(fullFilePath)
|
||||
.getParent())
|
||||
.map(Path::toString)
|
||||
.map(path -> path.replace("\\", "/"))
|
||||
.map(path -> path.toString().replace("\\", "/"))
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
public static Long getFileSizeInKb(BookEntity bookEntity) {
|
||||
Path filePath = Path.of(getBookFullPath(bookEntity));
|
||||
return getFileSizeInKb(filePath);
|
||||
}
|
||||
|
||||
public static Long getFileSizeInKb(Path filePath) {
|
||||
try {
|
||||
if (!Files.exists(filePath)) {
|
||||
log.warn(FILE_NOT_FOUND_MESSAGE + "{}", filePath.toAbsolutePath());
|
||||
return null;
|
||||
}
|
||||
return Files.size(filePath) / 1024;
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to get file size for path [{}]: {}", filePath, e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE opds_user
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE book
|
||||
ADD COLUMN file_size_kb BIGINT;
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE app_migration
|
||||
(
|
||||
migration_key VARCHAR(100) PRIMARY KEY COMMENT 'Unique identifier for the migration',
|
||||
executed_at TIMESTAMP NOT NULL COMMENT 'When the migration was executed',
|
||||
description TEXT COMMENT 'Optional description of what the migration did'
|
||||
) COMMENT = 'Tracks one-time application-level data migrations';
|
||||
@@ -8,7 +8,6 @@ import {SettingsComponent} from './settings/settings.component';
|
||||
import {PdfViewerComponent} from './book/components/pdf-viewer/pdf-viewer.component';
|
||||
import {EpubViewerComponent} from './book/components/epub-viewer/component/epub-viewer.component';
|
||||
import {ChangePasswordComponent} from './core/component/change-password/change-password.component';
|
||||
import {EmailComponent} from './settings/email/email.component';
|
||||
import {BookMetadataCenterComponent} from './metadata/book-metadata-center/book-metadata-center.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
|
||||
@@ -117,6 +117,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
{label: 'Author', icon: '', field: 'author', command: () => this.sortBooks('author')},
|
||||
{label: 'Last Read', field: 'lastReadTime', command: () => this.sortBooks('lastReadTime')},
|
||||
{label: 'Added On', field: 'addedOn', command: () => this.sortBooks('addedOn')},
|
||||
{label: 'File Size', icon: '', field: 'fileSizeKb', command: () => this.sortBooks('fileSizeKb')},
|
||||
{label: 'Locked', icon: '', field: 'locked', command: () => this.sortBooks('locked')},
|
||||
{label: 'Publisher', icon: '', field: 'publisher', command: () => this.sortBooks('publisher')},
|
||||
{label: 'Published Date', icon: '', field: 'publishedDate', command: () => this.sortBooks('publishedDate')},
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
<th>Published</th>
|
||||
<th>Last Read</th>
|
||||
<th>Added</th>
|
||||
<th>File Size</th>
|
||||
<th>Lang</th>
|
||||
<th>Pages</th>
|
||||
<th>Amazon</th>
|
||||
@@ -67,6 +68,10 @@
|
||||
<td class="min-w-[9rem] max-w-[9rem] overflow-hidden truncate text-right">
|
||||
{{ book.addedOn ? (book.addedOn | date: 'dd-MMM-yyyy') : '' }}
|
||||
</td>
|
||||
<td class="min-w-[7rem] max-w-[9rem] overflow-hidden truncate"
|
||||
[title]="book.fileSizeKb + ' KB'">
|
||||
{{ formatFileSize(book.fileSizeKb) }}
|
||||
</td>
|
||||
<td class="min-w-[6rem] max-w-[6rem] overflow-hidden truncate">{{ metadata.language }}</td>
|
||||
<td class="min-w-[4rem] max-w-[5rem] overflow-hidden truncate">{{ metadata.pageCount }}</td>
|
||||
<td class="min-w-[10rem] max-w-[10rem] overflow-hidden truncate">
|
||||
|
||||
@@ -106,6 +106,12 @@ export class BookTableComponent implements OnChanges {
|
||||
.every(key => metadata[key] === true);
|
||||
}
|
||||
|
||||
formatFileSize(kb?: number): string {
|
||||
if (kb == null || isNaN(kb)) return '-';
|
||||
const mb = kb / 1024;
|
||||
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${mb.toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
toggleMetadataLock(metadata: BookMetadata): void {
|
||||
const lockKeys = Object.keys(metadata).filter(key => key.endsWith('Locked'));
|
||||
const allLocked = lockKeys.every(key => metadata[key] === true);
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
[sidebarVisible]="false"
|
||||
[zoom]="zoom"
|
||||
[spread]="spread"
|
||||
[showBookModeButton]="false"
|
||||
(pageChange)="onPageChange($event)"
|
||||
(zoomChange)="onZoomChange($event)"
|
||||
(spreadChange)="onSpreadChange($event)">
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface Book {
|
||||
epubProgress?: string;
|
||||
pdfProgress?: number;
|
||||
filePath?: string;
|
||||
fileSizeKb?: number;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
|
||||
@@ -24,7 +24,8 @@ export class SortService {
|
||||
.filter((key) => key.endsWith('Locked'))
|
||||
.every((key) => book.metadata?.[key] === true),
|
||||
lastReadTime: (book) => book.lastReadTime ? new Date(book.lastReadTime).getTime() : null,
|
||||
addedOn: (book) => book.addedOn ? new Date(book.addedOn).getTime() : null
|
||||
addedOn: (book) => book.addedOn ? new Date(book.addedOn).getTime() : null,
|
||||
fileSizeKb: (book) => book.fileSizeKb || null
|
||||
};
|
||||
|
||||
applySort(books: Book[], selectedSort: SortOption | null): Book[] {
|
||||
|
||||
@@ -6,4 +6,5 @@ export interface AppSettings {
|
||||
metadataRefreshOptions: MetadataRefreshOptions;
|
||||
coverResolution: string;
|
||||
uploadPattern: string;
|
||||
opdsServerEnabled: boolean;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -6,12 +6,13 @@ 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';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-file-upload-pattern',
|
||||
templateUrl: './file-upload-pattern.component.html',
|
||||
standalone: true,
|
||||
imports: [FormsModule, Button],
|
||||
imports: [FormsModule, Button, Tooltip],
|
||||
styleUrls: ['./file-upload-pattern.component.scss']
|
||||
})
|
||||
export class FileUploadPatternComponent implements OnInit {
|
||||
|
||||
@@ -56,25 +56,31 @@
|
||||
</li>
|
||||
|
||||
<p-divider layout="vertical"/>
|
||||
<li class="relative">
|
||||
<button type="button"
|
||||
class="topbar-item config-item"
|
||||
enterActiveClass="animate-scalein"
|
||||
enterFromClass="hidden"
|
||||
leaveActiveClass="animate-fadeout"
|
||||
leaveToClass="hidden"
|
||||
pStyleClass="@next" [hideOnOutsideClick]="true">
|
||||
<i class="pi pi-palette"></i>
|
||||
</button>
|
||||
<app-theme-configurator></app-theme-configurator>
|
||||
</li>
|
||||
|
||||
<p-divider layout="vertical"/>
|
||||
<li>
|
||||
<button class="topbar-item" (click)="logout()" pTooltip="Logout" tooltipPosition="top">
|
||||
<i class="pi pi-sign-out text-surface-700 dark:text-surface-100"></i>
|
||||
</button>
|
||||
</li>
|
||||
<div class="flex gap-6">
|
||||
<li class="relative">
|
||||
<button type="button"
|
||||
class="topbar-item config-item"
|
||||
enterActiveClass="animate-scalein"
|
||||
enterFromClass="hidden"
|
||||
leaveActiveClass="animate-fadeout"
|
||||
leaveToClass="hidden"
|
||||
pStyleClass="@next" [hideOnOutsideClick]="true">
|
||||
<i class="pi pi-palette"></i>
|
||||
</button>
|
||||
<app-theme-configurator></app-theme-configurator>
|
||||
</li>
|
||||
<li>
|
||||
<button class="topbar-item" (click)="openUserProfileDialog()" pTooltip="Profile" tooltipPosition="top">
|
||||
<i class="pi pi-user text-surface-700 dark:text-surface-100"></i>
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="topbar-item" (click)="logout()" pTooltip="Logout" tooltipPosition="top">
|
||||
<i class="pi pi-sign-out text-surface-700 dark:text-surface-100"></i>
|
||||
</button>
|
||||
</li>
|
||||
</div>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {LiveNotificationBoxComponent} from '../../../core/component/live-notific
|
||||
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
|
||||
import {AuthService} from '../../../core/service/auth.service';
|
||||
import {UserService} from '../../../user.service';
|
||||
import {UserProfileDialogComponent} from '../../../user-profile-dialog/user-profile-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-topbar',
|
||||
@@ -118,6 +119,18 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
this.router.navigate(['/settings']);
|
||||
}
|
||||
|
||||
openUserProfileDialog() {
|
||||
this.ref = this.dialogService.open(UserProfileDialogComponent, {
|
||||
header: 'User Profile Information',
|
||||
modal: true,
|
||||
closable: true,
|
||||
style: {
|
||||
position: 'absolute',
|
||||
top: '10%',
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
logout() {
|
||||
this.authService.logout();
|
||||
window.location.href = '/login';
|
||||
|
||||
+23
-5
@@ -30,19 +30,36 @@
|
||||
<div class="flex items-center gap-2 pt-2">
|
||||
<ng-container *ngIf="metadata.amazonRating || metadata.goodreadsRating; else legacyRating">
|
||||
<p *ngIf="metadata.amazonRating" class="font-semibold">Amazon: {{ metadata.amazonRating }}</p>
|
||||
<p-rating *ngIf="metadata.amazonRating" [(ngModel)]="metadata.amazonRating" readonly stars="5"></p-rating>
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.amazonRating"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.amazonRating)">
|
||||
</p-rating>
|
||||
<p *ngIf="metadata.amazonRating" class="font-semibold"> ({{ metadata.amazonReviewCount | number:'1.0-0' }})</p>
|
||||
|
||||
<p *ngIf="metadata.amazonRating && metadata.goodreadsRating">|</p>
|
||||
|
||||
<p *ngIf="metadata.goodreadsRating" class="font-semibold">Goodreads: {{ metadata.goodreadsRating }}</p>
|
||||
<p-rating *ngIf="metadata.goodreadsRating" [(ngModel)]="metadata.goodreadsRating" readonly stars="5"></p-rating>
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.goodreadsRating"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.goodreadsRating)">
|
||||
</p-rating>
|
||||
<p *ngIf="metadata.goodreadsRating" class="font-semibold"> ({{ metadata.goodreadsReviewCount | number:'1.0-0' }})</p>
|
||||
</ng-container>
|
||||
|
||||
<ng-template #legacyRating>
|
||||
<p-rating [(ngModel)]="metadata.rating" readonly stars="5"></p-rating>
|
||||
<p class="font-semibold">({{ metadata.reviewCount | number:'1.0-0' }} Ratings)</p>
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.rating"
|
||||
readonly
|
||||
stars="5"
|
||||
[style.--p-rating-icon-active-color]="getStarColor(metadata.rating)">
|
||||
</p-rating>
|
||||
<p class="font-semibold">
|
||||
{{ metadata?.reviewCount ? '(' + (metadata?.reviewCount | number:'1.0-0') + ' Ratings)' : 'No Ratings' }}
|
||||
</p>
|
||||
</ng-template>
|
||||
</div>
|
||||
|
||||
@@ -50,13 +67,14 @@
|
||||
<p-tag *ngFor="let category of metadata.categories" [value]="category" class="shrink-0"></p-tag>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-x-20 gap-y-2 pt-6" style="grid-template-columns: repeat(3, max-content);">
|
||||
<div class="grid gap-x-20 gap-y-2 pt-6" style="grid-template-columns: repeat(4, max-content);">
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Publisher:</span> {{ metadata.publisher || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ metadata.publishedDate || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ metadata.isbn13 || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ metadata.pageCount || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB() }}</p>
|
||||
</div>
|
||||
|
||||
<p class="pt-2"><span class="font-bold">File Path:</span> {{ book?.filePath }}</p>
|
||||
|
||||
+25
@@ -154,4 +154,29 @@ export class MetadataViewerComponent implements OnInit {
|
||||
}
|
||||
return lockedKeys.every(key => metadata[key] === true);
|
||||
}
|
||||
|
||||
getFileSizeInMB(): string {
|
||||
const sizeKb = this.book?.fileSizeKb;
|
||||
if (sizeKb != null) {
|
||||
const sizeMb = sizeKb / 1024;
|
||||
return `${sizeMb.toFixed(2)} MB`;
|
||||
}
|
||||
return '-';
|
||||
}
|
||||
|
||||
getStarColor(rating?: number | null): string {
|
||||
if (rating == null) {
|
||||
return 'rgb(203, 213, 225)';
|
||||
} else if (rating >= 4.5) {
|
||||
return 'rgb(34, 197, 94)';
|
||||
} else if (rating >= 4) {
|
||||
return 'rgb(52, 211, 153)';
|
||||
} else if (rating >= 3.5) {
|
||||
return 'rgb(234, 179, 8)';
|
||||
} else if (rating >= 2.5) {
|
||||
return 'rgb(249, 115, 22)';
|
||||
} else {
|
||||
return 'rgb(239, 68, 68)';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
<p class="text-xl pb-2 pt-6 flex items-center gap-2">
|
||||
OPDS Server Settings
|
||||
<i
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="OPDS allows your book collection to be accessed by compatible reading apps through your private server."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<div class="flex flex-col space-y-6 p-4 m-4 custom-border">
|
||||
|
||||
<div class="flex items-center gap-4">
|
||||
<p class="text-lg py-1">OPDS Server Enabled:</p>
|
||||
<p-toggleButton
|
||||
[(ngModel)]="opdsEnabled"
|
||||
onLabel="OPDS ON"
|
||||
offLabel="OPDS OFF"
|
||||
(onChange)="toggleOpdsServer()"
|
||||
style="width: 150px;">
|
||||
</p-toggleButton>
|
||||
</div>
|
||||
|
||||
<div *ngIf="opdsEnabled" class="mt-6">
|
||||
<p-button
|
||||
label="Create New User"
|
||||
icon="pi pi-plus"
|
||||
outlined="true"
|
||||
severity="primary"
|
||||
(onClick)="openCreateUserDialog()">
|
||||
</p-button>
|
||||
|
||||
<div class="mt-3">
|
||||
<p-table [value]="users" [responsiveLayout]="'scroll'">
|
||||
<ng-template pTemplate="header">
|
||||
<tr>
|
||||
<th>Username</th>
|
||||
<th>Password</th>
|
||||
<th>Reset Password</th>
|
||||
<th>Delete</th>
|
||||
</tr>
|
||||
</ng-template>
|
||||
<ng-template pTemplate="body" let-user>
|
||||
<tr>
|
||||
<td>{{ user.username }}</td>
|
||||
<td class="flex items-center gap-2">
|
||||
<p-password
|
||||
[(ngModel)]="user.password"
|
||||
[disabled]="true">
|
||||
</p-password>
|
||||
<i
|
||||
class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="The password is hidden for security reasons and is only visible once during creation. You can reset the password if needed."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</td>
|
||||
<td>
|
||||
<p-button
|
||||
icon="pi pi-key"
|
||||
severity="warn"
|
||||
size="small"
|
||||
outlined="true"
|
||||
(onClick)="openResetPasswordDialog(user)">
|
||||
</p-button>
|
||||
</td>
|
||||
<td>
|
||||
<p-button
|
||||
icon="pi pi-trash"
|
||||
severity="danger"
|
||||
size="small"
|
||||
outlined="true"
|
||||
(onClick)="deleteUser(user.id)">
|
||||
</p-button>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</p-table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-dialog
|
||||
header="Create New OPDS User"
|
||||
[(visible)]="createUserDialogVisible"
|
||||
[modal]="true"
|
||||
[style]="{ width: '400px' }">
|
||||
<div>
|
||||
<div>
|
||||
<label for="username">Username</label>
|
||||
<input id="username" type="text" pInputText [(ngModel)]="newUser.username" class="w-full"/>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<label for="password">Password</label>
|
||||
<i
|
||||
class="pi pi-info-circle text-yellow-500"
|
||||
pTooltip="Password can only be seen now. It won’t be retrievable later. Please save it securely."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</div>
|
||||
<input id="password" pInputText [(ngModel)]="newUser.password" class="w-full"/>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end mt-6 gap-4">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
(onClick)="cancelCreateUser()">
|
||||
</p-button>
|
||||
<p-button
|
||||
label="Save"
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
(onClick)="saveNewUser()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</p-dialog>
|
||||
|
||||
<p-dialog
|
||||
header="Reset User Password"
|
||||
[(visible)]="resetPasswordDialogVisible"
|
||||
[modal]="true"
|
||||
[style]="{ width: '400px' }">
|
||||
<div>
|
||||
<p class="mb-6 mt-2">Reset password for: <b>{{ selectedUser?.username }}</b></p>
|
||||
<div>
|
||||
<div class="flex items-center">
|
||||
<label for="newPassword">New Password</label>
|
||||
<i
|
||||
class="pi pi-info-circle text-yellow-500 ml-2"
|
||||
pTooltip="Password can only be seen now. It won’t be retrievable later. Please save it securely."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</div>
|
||||
<input id="newPassword" pInputText [(ngModel)]="newPassword" class="w-full"/>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end mt-4 gap-4">
|
||||
<p-button
|
||||
label="Cancel"
|
||||
icon="pi pi-times"
|
||||
severity="secondary"
|
||||
(onClick)="cancelResetPassword()">
|
||||
</p-button>
|
||||
<p-button
|
||||
label="Save"
|
||||
icon="pi pi-check"
|
||||
severity="success"
|
||||
(onClick)="confirmResetPassword()">
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
</p-dialog>
|
||||
@@ -0,0 +1,4 @@
|
||||
.custom-border {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { Component, inject, OnInit } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { NgIf } from '@angular/common';
|
||||
import { TableModule } from 'primeng/table';
|
||||
import { Button } from 'primeng/button';
|
||||
import { InputText } from 'primeng/inputtext';
|
||||
import { Dialog } from 'primeng/dialog';
|
||||
import { Tooltip } from 'primeng/tooltip';
|
||||
import { ToggleButton } from 'primeng/togglebutton';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { filter, take } from 'rxjs/operators';
|
||||
|
||||
import { OpdsUser, OpdsUserService } from '../opds-user.service';
|
||||
import { AppSettingsService } from '../core/service/app-settings.service';
|
||||
import { AppSettings } from '../core/model/app-settings.model';
|
||||
import { Password } from 'primeng/password';
|
||||
|
||||
@Component({
|
||||
selector: 'app-opds-settings',
|
||||
standalone: true,
|
||||
imports: [
|
||||
FormsModule,
|
||||
NgIf,
|
||||
TableModule,
|
||||
Button,
|
||||
InputText,
|
||||
Dialog,
|
||||
Tooltip,
|
||||
ToggleButton,
|
||||
Password
|
||||
],
|
||||
templateUrl: './opds-settings.component.html',
|
||||
styleUrl: './opds-settings.component.scss'
|
||||
})
|
||||
export class OpdsSettingsComponent implements OnInit {
|
||||
opdsEnabled = false;
|
||||
users: OpdsUser[] = [];
|
||||
selectedUser: OpdsUser | null = null;
|
||||
createUserDialogVisible = false;
|
||||
resetPasswordDialogVisible = false;
|
||||
newUser = { username: '', password: '' };
|
||||
newPassword = '';
|
||||
|
||||
private readonly appSettings$ = inject(AppSettingsService).appSettings$;
|
||||
private readonly opdsUserService = inject(OpdsUserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$
|
||||
.pipe(
|
||||
filter((settings): settings is AppSettings => settings != null),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
this.opdsEnabled = settings.opdsServerEnabled ?? false;
|
||||
if (this.opdsEnabled) {
|
||||
this.loadUsers();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
toggleOpdsServer(): void {
|
||||
this.saveSetting('opds_server_enabled', this.opdsEnabled);
|
||||
if (this.opdsEnabled) {
|
||||
this.loadUsers();
|
||||
} else {
|
||||
this.users = [];
|
||||
}
|
||||
}
|
||||
|
||||
loadUsers(): void {
|
||||
this.opdsUserService.getUsers().subscribe({
|
||||
next: (users) => this.users = users,
|
||||
error: () => this.showError('Load Users Failed', 'Unable to fetch users.')
|
||||
});
|
||||
}
|
||||
|
||||
openCreateUserDialog(): void {
|
||||
this.newUser = { username: '', password: '' };
|
||||
this.createUserDialogVisible = true;
|
||||
}
|
||||
|
||||
cancelCreateUser(): void {
|
||||
this.createUserDialogVisible = false;
|
||||
}
|
||||
|
||||
saveNewUser(): void {
|
||||
const { username, password } = this.newUser;
|
||||
|
||||
if (username.trim() && password.trim()) {
|
||||
this.opdsUserService.createUser(this.newUser).subscribe({
|
||||
next: () => {
|
||||
this.createUserDialogVisible = false;
|
||||
this.loadUsers();
|
||||
this.showSuccess('User Created', 'New OPDS user created successfully.');
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || 'Unable to create user.';
|
||||
this.showError('Create User Failed', errorMessage);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.showWarning('Invalid Input', 'Username and Password are required.');
|
||||
}
|
||||
}
|
||||
|
||||
openResetPasswordDialog(user: OpdsUser): void {
|
||||
this.selectedUser = user;
|
||||
this.newPassword = '';
|
||||
this.resetPasswordDialogVisible = true;
|
||||
}
|
||||
|
||||
cancelResetPassword(): void {
|
||||
this.resetPasswordDialogVisible = false;
|
||||
this.selectedUser = null;
|
||||
this.newPassword = '';
|
||||
}
|
||||
|
||||
confirmResetPassword(): void {
|
||||
if (this.selectedUser && this.newPassword.trim()) {
|
||||
this.opdsUserService.resetPassword(this.selectedUser.id, this.newPassword).subscribe({
|
||||
next: () => {
|
||||
this.resetPasswordDialogVisible = false;
|
||||
this.showSuccess('Password Reset', 'User password reset successfully.');
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || 'Unable to reset password.';
|
||||
this.showError('Reset Password Failed', errorMessage);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.showWarning('Invalid Input', 'New password is required.');
|
||||
}
|
||||
}
|
||||
|
||||
deleteUser(userId: number): void {
|
||||
this.opdsUserService.deleteUser(userId).subscribe({
|
||||
next: () => {
|
||||
this.loadUsers();
|
||||
this.showSuccess('User Deleted', 'User deleted successfully.');
|
||||
},
|
||||
error: () => {
|
||||
this.showError('Delete User Failed', 'Unable to delete user.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private saveSetting(key: string, value: unknown): void {
|
||||
this.appSettingsService.saveSettings([{ key, newValue: value }]).subscribe({
|
||||
next: () => {
|
||||
let successMessage = 'Settings saved successfully.';
|
||||
if (key === 'opds_server_enabled') {
|
||||
successMessage = (value === true)
|
||||
? 'OPDS Server Enabled.'
|
||||
: 'OPDS Server Disabled.';
|
||||
}
|
||||
this.showSuccess('Settings Saved', successMessage);
|
||||
},
|
||||
error: () => {
|
||||
this.showError('Error', 'There was an error saving the settings.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private showSuccess(summary: string, detail: string): void {
|
||||
this.messageService.add({ severity: 'success', summary, detail });
|
||||
}
|
||||
|
||||
private showError(summary: string, detail: string): void {
|
||||
this.messageService.add({ severity: 'error', summary, detail });
|
||||
}
|
||||
|
||||
private showWarning(summary: string, detail: string): void {
|
||||
this.messageService.add({ severity: 'warn', summary, detail });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
|
||||
export interface OpdsUser {
|
||||
id: number;
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class OpdsUserService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/opds-users`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
constructor() {
|
||||
}
|
||||
|
||||
createUser(userData: Omit<OpdsUser, 'id'>): Observable<void> {
|
||||
return this.http.post<void>(this.url, userData);
|
||||
}
|
||||
|
||||
getUsers(): Observable<OpdsUser[]> {
|
||||
return this.http.get<OpdsUser[]>(this.url);
|
||||
}
|
||||
|
||||
deleteUser(userId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${userId}`);
|
||||
}
|
||||
|
||||
resetPassword(resetPasswordUserId: number, newPassword: string): Observable<void> {
|
||||
const resetPayload = {
|
||||
password: newPassword
|
||||
};
|
||||
return this.http.put<void>(`${this.url}/${resetPasswordUserId}/reset-password`, resetPayload);
|
||||
}
|
||||
}
|
||||
@@ -71,14 +71,10 @@
|
||||
|
||||
<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-opds-settings></app-opds-settings>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<app-file-upload-pattern></app-file-upload-pattern>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refr
|
||||
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';
|
||||
import {OpdsSettingsComponent} from '../../opds-settings/opds-settings.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-global-preferences',
|
||||
@@ -30,7 +31,8 @@ import {FileUploadPatternComponent} from '../../file-upload-pattern/file-upload-
|
||||
ToggleSwitch,
|
||||
FormsModule,
|
||||
MetadataAdvancedFetchOptionsComponent,
|
||||
FileUploadPatternComponent
|
||||
FileUploadPatternComponent,
|
||||
OpdsSettingsComponent
|
||||
],
|
||||
templateUrl: './global-preferences.component.html',
|
||||
styleUrl: './global-preferences.component.scss'
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="min-w-[300px] md:min-w-[500px]">
|
||||
|
||||
<section>
|
||||
<div class="flex flex-col gap-4">
|
||||
<h2 class="text-xl font-semibold">User Profile</h2>
|
||||
<div class="px-4 py-2">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">Username</label>
|
||||
<p *ngIf="!isEditing" class="text-lg">{{ currentUser?.username || 'N/A' }}</p>
|
||||
<input *ngIf="isEditing" disabled id="username" type="text" pInputText [(ngModel)]="editUserData.username" class="w-full"/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium mb-1">Full Name</label>
|
||||
<p *ngIf="!isEditing" class="text-lg">{{ currentUser?.name || 'N/A' }}</p>
|
||||
<input *ngIf="isEditing" id="fullname" type="text" pInputText [(ngModel)]="editUserData.name" class="w-full"/>
|
||||
</div>
|
||||
|
||||
<div class="md:col-span-2">
|
||||
<label class="block text-sm font-medium mb-1">Email</label>
|
||||
<p *ngIf="!isEditing" class="text-lg">{{ currentUser?.email || 'N/A' }}</p>
|
||||
<input *ngIf="isEditing" id="email" type="email" pInputText [(ngModel)]="editUserData.email" class="w-full"/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-start mt-6">
|
||||
<div *ngIf="!isEditing">
|
||||
<p-button label="Edit" severity="info" icon="pi pi-pencil" (onClick)="toggleEdit()"></p-button>
|
||||
</div>
|
||||
<div *ngIf="isEditing" class="flex gap-2">
|
||||
<p-button label="Cancel" severity="secondary" icon="pi pi-times" (onClick)="toggleEdit()"></p-button>
|
||||
<p-button label="Save" severity="success" icon="pi pi-check" (onClick)="updateProfile()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<section class="space-y-6 pt-4">
|
||||
<div class="flex flex-col gap-4">
|
||||
<h2 class="text-xl font-semibold">Change Password</h2>
|
||||
<div class="change-password-wrapper">
|
||||
<div class="px-4 py-2">
|
||||
<form [formGroup]="changePasswordForm" (ngSubmit)="submitPasswordChange()">
|
||||
<div class="p-field mb-4">
|
||||
<label for="currentPassword">Current Password</label>
|
||||
<p-password id="currentPassword" formControlName="currentPassword" [feedback]="false" fluid></p-password>
|
||||
<p-message *ngIf="changePasswordForm.get('currentPassword')?.invalid && changePasswordForm.get('currentPassword')?.touched" severity="error" text="Current password is required."></p-message>
|
||||
</div>
|
||||
|
||||
<div class="p-field mb-4">
|
||||
<label for="newPassword">New Password (at least 6 characters)</label>
|
||||
<p-password id="newPassword" formControlName="newPassword" [feedback]="false" fluid></p-password>
|
||||
<p-message *ngIf="changePasswordForm.get('newPassword')?.errors?.['minlength'] && changePasswordForm.get('newPassword')?.touched" severity="error" text="Password must be at least 6 characters long."></p-message>
|
||||
</div>
|
||||
|
||||
<div class="p-field mb-4">
|
||||
<label for="confirmNewPassword">Confirm New Password</label>
|
||||
<p-password id="confirmNewPassword" formControlName="confirmNewPassword" [feedback]="false" fluid></p-password>
|
||||
<p-message *ngIf="passwordsMismatch" severity="error" text="Passwords do not match."></p-message>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-start pt-4">
|
||||
<p-button type="submit" severity="info" label="Change Password" icon="pi pi-key" [disabled]="changePasswordForm.invalid" class="p-fluid"></p-button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
<div *ngIf="!currentUser" class="flex items-center justify-center min-h-[50vh] text-lg">
|
||||
Loading user data...
|
||||
</div>
|
||||
@@ -0,0 +1,151 @@
|
||||
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
|
||||
import {Button} from 'primeng/button';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {NgIf} from '@angular/common';
|
||||
import {Password} from 'primeng/password';
|
||||
import {User, UserService} from '../user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Subscription} from 'rxjs';
|
||||
import {Message} from 'primeng/message';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-profile-dialog',
|
||||
imports: [
|
||||
Button,
|
||||
Divider,
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
InputText,
|
||||
NgIf,
|
||||
Password,
|
||||
Message
|
||||
],
|
||||
templateUrl: './user-profile-dialog.component.html',
|
||||
styleUrls: ['./user-profile-dialog.component.scss']
|
||||
})
|
||||
export class UserProfileDialogComponent implements OnInit, OnDestroy {
|
||||
|
||||
isEditing = false;
|
||||
currentUser: User | null = null;
|
||||
editUserData: Partial<User> = {};
|
||||
private userSubscription: Subscription | null = null;
|
||||
|
||||
changePasswordForm: FormGroup;
|
||||
|
||||
protected readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly fb = inject(FormBuilder);
|
||||
|
||||
constructor() {
|
||||
this.changePasswordForm = this.fb.group(
|
||||
{
|
||||
currentPassword: ['', Validators.required],
|
||||
newPassword: ['', [Validators.required, Validators.minLength(6)]],
|
||||
confirmNewPassword: ['', [Validators.required, Validators.minLength(6)]]
|
||||
},
|
||||
{
|
||||
validators: [UserProfileDialogComponent.passwordsMatchValidator]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.userSubscription = this.userService.userData$.subscribe(user => {
|
||||
this.currentUser = user;
|
||||
this.resetEditForm();
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.userSubscription?.unsubscribe();
|
||||
}
|
||||
|
||||
static passwordsMatchValidator(form: FormGroup) {
|
||||
const newPassword = form.get('newPassword')?.value;
|
||||
const confirmPassword = form.get('confirmNewPassword')?.value;
|
||||
return newPassword === confirmPassword ? null : {mismatch: true};
|
||||
}
|
||||
|
||||
get passwordsMismatch() {
|
||||
return this.changePasswordForm.hasError('mismatch') &&
|
||||
this.changePasswordForm.get('confirmNewPassword')?.touched;
|
||||
}
|
||||
|
||||
toggleEdit(): void {
|
||||
this.isEditing = !this.isEditing;
|
||||
if (this.isEditing) {
|
||||
this.resetEditForm();
|
||||
}
|
||||
}
|
||||
|
||||
resetEditForm(): void {
|
||||
if (this.currentUser) {
|
||||
this.editUserData = {
|
||||
username: this.currentUser.username,
|
||||
name: this.currentUser.name,
|
||||
email: this.currentUser.email,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
updateProfile(): void {
|
||||
if (!this.currentUser) {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'User data not available.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.editUserData.name === this.currentUser.name && this.editUserData.email === this.currentUser.email) {
|
||||
this.messageService.add({severity: 'info', summary: 'Info', detail: 'No changes detected.'});
|
||||
this.isEditing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.userService.updateUser(this.currentUser.id, this.editUserData).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Profile updated successfully'});
|
||||
this.isEditing = false;
|
||||
this.resetEditForm();
|
||||
},
|
||||
error: (err) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: err.error?.message || 'Failed to update profile',
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
submitPasswordChange(): void {
|
||||
if (this.changePasswordForm.invalid) {
|
||||
this.changePasswordForm.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const {currentPassword, newPassword} = this.changePasswordForm.value;
|
||||
|
||||
this.userService.changePassword(currentPassword, newPassword).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Password changed successfully'});
|
||||
this.resetPasswordForm();
|
||||
},
|
||||
error: (err) => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: err?.message || 'Failed to change password',
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
resetPasswordForm(): void {
|
||||
this.changePasswordForm.reset();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import {inject, Injectable, Injector} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {BehaviorSubject, Observable, of, throwError} from 'rxjs';
|
||||
import {BehaviorSubject, Observable, tap, throwError} from 'rxjs';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
import {jwtDecode} from 'jwt-decode';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {Library} from './book/model/library.model';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
@@ -41,11 +40,6 @@ export interface UserBookPreferences {
|
||||
};
|
||||
}
|
||||
|
||||
interface JwtPayload {
|
||||
sub: string;
|
||||
userId: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@@ -84,8 +78,12 @@ export class UserService {
|
||||
return this.http.get<User[]>(this.userUrl);
|
||||
}
|
||||
|
||||
updateUser(userId: number, updateData: Partial<User>): Observable<{ message: string }> {
|
||||
return this.http.put<{ message: string }>(`${this.userUrl}/${userId}`, updateData);
|
||||
updateUser(userId: number, updateData: Partial<User>): Observable<User> {
|
||||
return this.http.put<User>(`${this.userUrl}/${userId}`, updateData).pipe(
|
||||
tap(user => {
|
||||
this.userDataSubject.next(user);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteUser(userId: number): Observable<void> {
|
||||
|
||||
Reference in New Issue
Block a user