Implement OPDS
This commit is contained in:
committed by
Aditya Chandel
parent
71bc927d54
commit
c4f8bf8322
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+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;
|
||||
|
||||
}
|
||||
+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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
@@ -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 {
|
||||
|
||||
@@ -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'
|
||||
|
||||
Reference in New Issue
Block a user