diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java index 5d4185742..6789c5db5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.config.security; import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.config.security.filter.CoverJwtFilter; +import com.adityachandel.booklore.config.security.filter.CustomFontJwtFilter; import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter; import com.adityachandel.booklore.config.security.filter.KoboAuthFilter; import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter; @@ -133,6 +134,21 @@ public class SecurityConfig { @Bean @Order(5) + public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception { + http + .securityMatcher("/api/v1/custom-fonts/*/file") + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() + ) + .addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + @Order(6) public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception { List publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS)); if (appProperties.getSwagger().isEnabled()) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java new file mode 100644 index 000000000..00328ca69 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java @@ -0,0 +1,93 @@ +package com.adityachandel.booklore.config.security.filter; + +import com.adityachandel.booklore.config.security.JwtUtils; +import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; +import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails; +import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Instant; + +@AllArgsConstructor +public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter { + + protected final JwtUtils jwtUtils; + protected final UserRepository userRepository; + protected final BookLoreUserTransformer bookLoreUserTransformer; + protected final AppSettingService appSettingService; + protected final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + // Extract token from query parameter (not from Authorization header) + String token = request.getParameter("token"); + if (token == null || token.isEmpty()) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token"); + return; + } + + try { + if (jwtUtils.validateToken(token)) { + authenticateLocalUser(token, request); + } else if (appSettingService.getAppSettings().isOidcEnabled()) { + authenticateOidcUser(token, request); + } else { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token"); + return; + } + } catch (Exception ex) { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage()); + return; + } + + chain.doFilter(request, response); + } + + protected void authenticateLocalUser(String token, HttpServletRequest request) { + Long userId = jwtUtils.extractUserId(token); + BookLoreUserEntity entity = userRepository.findById(userId) + .orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + protected void authenticateOidcUser(String token, HttpServletRequest request) throws Exception { + var processor = dynamicOidcJwtProcessor.getProcessor(); + var claimsSet = processor.process(token, null); + + if (claimsSet.getExpirationTime() == null || + claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) { + throw new RuntimeException("OIDC token expired or invalid"); + } + + OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); + OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); + String username = claimsSet.getStringClaim(claimMapping.getUsername()); + BookLoreUserEntity entity = userRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(user, null, null); + authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); + SecurityContextHolder.getContext().setAuthentication(authentication); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java index 4ad791311..0cb78fb9a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java @@ -2,92 +2,27 @@ package com.adityachandel.booklore.config.security.filter; import com.adityachandel.booklore.config.security.JwtUtils; import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; -import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails; import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; -import com.adityachandel.booklore.model.dto.BookLoreUser; -import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails; -import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.service.appsettings.AppSettingService; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.AllArgsConstructor; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; -import java.io.IOException; -import java.time.Instant; - -@AllArgsConstructor @Component -public class CoverJwtFilter extends OncePerRequestFilter { +public class CoverJwtFilter extends AbstractQueryParameterJwtFilter { - private final JwtUtils jwtUtils; - private final UserRepository userRepository; - private final BookLoreUserTransformer bookLoreUserTransformer; - private final AppSettingService appSettingService; - private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + public CoverJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = request.getRequestURI(); return !path.startsWith("/api/v1/media/"); } - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String token = request.getParameter("token"); - if (token == null || token.isEmpty()) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token"); - return; - } - try { - if (jwtUtils.validateToken(token)) { - authenticateLocalUser(token, request); - } else if (appSettingService.getAppSettings().isOidcEnabled()) { - authenticateOidcUser(token, request); - } else { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token"); - return; - } - } catch (Exception ex) { - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage()); - return; - } - - chain.doFilter(request, response); - } - - private void authenticateLocalUser(String token, HttpServletRequest request) { - Long userId = jwtUtils.extractUserId(token); - BookLoreUserEntity entity = userRepository.findById(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId)); - BookLoreUser user = bookLoreUserTransformer.toDTO(entity); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null); - authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - - private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception { - var processor = dynamicOidcJwtProcessor.getProcessor(); - var claimsSet = processor.process(token, null); - - if (claimsSet.getExpirationTime() == null || claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) { - throw new RuntimeException("OIDC token expired or invalid"); - } - - OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails(); - OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping(); - String username = claimsSet.getStringClaim(claimMapping.getUsername()); - BookLoreUserEntity entity = userRepository.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username)); - BookLoreUser user = bookLoreUserTransformer.toDTO(entity); - - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null); - authentication.setDetails(new UserAuthenticationDetails(request, user.getId())); - SecurityContextHolder.getContext().setAuthentication(authentication); - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java new file mode 100644 index 000000000..b72bc15d1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java @@ -0,0 +1,29 @@ +package com.adityachandel.booklore.config.security.filter; + +import com.adityachandel.booklore.config.security.JwtUtils; +import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor; +import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; + +@Component +public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter { + + public CustomFontJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + // Only filter requests to custom font file endpoints (e.g., /api/v1/custom-fonts/123/file) + return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file")); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java new file mode 100644 index 000000000..858c20bfb --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java @@ -0,0 +1,82 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.service.customfont.CustomFontService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +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.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Tag(name = "Custom Fonts", description = "Endpoints for managing custom fonts for EPUB reader") +@RestController +@RequestMapping("/api/v1/custom-fonts") +@RequiredArgsConstructor +public class CustomFontController { + + private final CustomFontService customFontService; + private final AuthenticationService authenticationService; + + @Operation(summary = "Upload a custom font", description = "Upload a custom font file (.ttf, .otf, .woff, .woff2) for the authenticated user") + @ApiResponse(responseCode = "200", description = "Font uploaded successfully") + @ApiResponse(responseCode = "400", description = "Invalid file or quota exceeded") + @PostMapping("/upload") + @PreAuthorize("isAuthenticated()") + public ResponseEntity uploadFont( + @Parameter(description = "Font file (.ttf, .otf, .woff, .woff2)") @RequestParam("file") MultipartFile file, + @Parameter(description = "Font display name") @RequestParam(value = "fontName", required = false) String fontName) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + CustomFontDto fontDto = customFontService.uploadFont(file, fontName, user.getId()); + return ResponseEntity.ok(fontDto); + } + + @Operation(summary = "Get all user's custom fonts", description = "Retrieve all custom fonts for the authenticated user") + @ApiResponse(responseCode = "200", description = "Fonts retrieved successfully") + @GetMapping + @PreAuthorize("isAuthenticated()") + public ResponseEntity> getUserFonts() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + List fonts = customFontService.getUserFonts(user.getId()); + return ResponseEntity.ok(fonts); + } + + @Operation(summary = "Delete a custom font", description = "Delete a custom font file and database record") + @ApiResponse(responseCode = "200", description = "Font deleted successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @DeleteMapping("/{fontId}") + @PreAuthorize("isAuthenticated()") + public ResponseEntity deleteFont(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + customFontService.deleteFont(fontId, user.getId()); + return ResponseEntity.ok().build(); + } + + @Operation(summary = "Get font file", description = "Retrieve the font file for use in the browser") + @ApiResponse(responseCode = "200", description = "Font file retrieved successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @GetMapping("/{fontId}/file") + @PreAuthorize("isAuthenticated()") + public ResponseEntity getFontFile(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Resource resource = customFontService.getFontFile(fontId, user.getId()); + + // Get font format to set correct content type + var format = customFontService.getFontFormat(fontId, user.getId()); + + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(format.getMimeType())) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline") + .body(resource); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java index 31a361650..f026289a0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java @@ -93,6 +93,27 @@ public class GlobalExceptionHandler { return new ResponseEntity<>(errorResponse, HttpStatus.OK); } + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + log.warn("Illegal argument: {}", ex.getMessage()); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalStateException(IllegalStateException ex) { + log.error("Illegal state: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT); + } + + @ExceptionHandler(UnsupportedOperationException.class) + public ResponseEntity handleUnsupportedOperationException(UnsupportedOperationException ex) { + log.error("Unsupported operation: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED); + } + @ExceptionHandler(Exception.class) public ResponseEntity handleGenericException(Exception ex) { ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java new file mode 100644 index 000000000..08da6c1fc --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.mapper; + +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface CustomFontMapper { + + CustomFontDto toDto(CustomFontEntity entity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java new file mode 100644 index 000000000..7017b6548 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java @@ -0,0 +1,22 @@ +package com.adityachandel.booklore.model.dto; + +import com.adityachandel.booklore.model.enums.FontFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CustomFontDto { + private Long id; + private String fontName; + private String originalFileName; + private FontFormat format; + private Long fileSize; + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java index 258f67bf1..3036a24d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java @@ -14,4 +14,5 @@ public class EpubViewerPreferences { private Integer fontSize; private Float letterSpacing; private Float lineHeight; + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java new file mode 100644 index 000000000..cc9089af0 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java @@ -0,0 +1,44 @@ +package com.adityachandel.booklore.model.entity; + +import com.adityachandel.booklore.model.enums.FontFormat; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "custom_font") +public class CustomFontEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "font_name", nullable = false) + private String fontName; + + @Column(name = "file_name", nullable = false, unique = true) + private String fileName; + + @Column(name = "original_file_name", nullable = false) + private String originalFileName; + + @Enumerated(EnumType.STRING) + @Column(name = "format", nullable = false) + private FontFormat format; + + @Column(name = "file_size", nullable = false) + private Long fileSize; + + @Column(name = "uploaded_at", nullable = false) + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java index 5e6fb116d..7de62e30c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java @@ -44,4 +44,7 @@ public class EpubViewerPreferencesEntity { @Column(name = "spread") private String spread; + + @Column(name = "custom_font_id") + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java new file mode 100644 index 000000000..b7163af85 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java @@ -0,0 +1,54 @@ +package com.adityachandel.booklore.model.enums; + +import lombok.Getter; + +@Getter +public enum FontFormat { + TTF("font/ttf", ".ttf"), + OTF("font/otf", ".otf"), + WOFF("font/woff", ".woff"), + WOFF2("font/woff2", ".woff2"); + + private final String mimeType; + private final String extension; + + FontFormat(String mimeType, String extension) { + this.mimeType = mimeType; + this.extension = extension; + } + + public static FontFormat fromExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported font format: " + extension); + } + + public static FontFormat fromMimeType(String mimeType) { + for (FontFormat format : values()) { + if (format.mimeType.equals(mimeType)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported MIME type: " + mimeType); + } + + public static boolean isSupportedExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return true; + } + } + return false; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java new file mode 100644 index 000000000..9276465ef --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface CustomFontRepository extends JpaRepository { + + List findByUserId(Long userId); + + int countByUserId(Long userId); + + Optional findByIdAndUserId(Long id, Long userId); + +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java new file mode 100644 index 000000000..42b0c3dd2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java @@ -0,0 +1,331 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomFontService { + + private final CustomFontRepository customFontRepository; + private final UserRepository userRepository; + private final CustomFontMapper customFontMapper; + private final AppProperties appProperties; + + private static final int MAX_FONTS_PER_USER = 10; + private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; + private static final String CUSTOM_FONTS_DIR = "custom-fonts"; + private static final int MAX_FONT_NAME_LENGTH = 100; + + @Transactional + public CustomFontDto uploadFont(MultipartFile file, String fontName, Long userId) { + Path fontPath = null; + CustomFontEntity savedEntity = null; + + try { + validateFontUpload(file, userId); + + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("User not found")); + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + FontFormat format = FontFormat.fromExtension(extension); + + String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String fileName = String.format("user_%d_font_%s%s", userId, uuid, format.getExtension()); + + Path fontDir = getFontDirectory(userId); + Files.createDirectories(fontDir); + fontPath = fontDir.resolve(fileName); + + validatePath(fontPath, fontDir); + + file.transferTo(fontPath.toFile()); + + validateFontMagicBytes(fontPath, format); + + String sanitizedFontName = sanitizeFontName(fontName, originalFilename); + + CustomFontEntity entity = CustomFontEntity.builder() + .user(user) + .fontName(sanitizedFontName) + .fileName(fileName) + .originalFileName(originalFilename) + .format(format) + .fileSize(file.getSize()) + .uploadedAt(LocalDateTime.now()) + .build(); + + savedEntity = customFontRepository.save(entity); + log.info("Font uploaded successfully for user {}: {} ({})", userId, sanitizedFontName, fileName); + + return customFontMapper.toDto(savedEntity); + + } catch (IOException e) { + log.error("Failed to upload font for user {}: {}", userId, e.getMessage(), e); + throw new APIException("Failed to upload font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } finally { + if (fontPath != null && savedEntity == null) { + try { + Files.deleteIfExists(fontPath); + log.debug("Cleaned up orphaned font file after upload failure: {}", fontPath); + } catch (IOException e) { + log.warn("Failed to cleanup orphaned font file: {}", fontPath, e); + } + } + } + } + + public List getUserFonts(Long userId) { + List fonts = customFontRepository.findByUserId(userId); + return fonts.stream() + .map(customFontMapper::toDto) + .collect(Collectors.toList()); + } + + @Transactional + public void deleteFont(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + IOException fileDeleteException = null; + + try { + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + validatePath(fontPath, fontDir); + + Files.deleteIfExists(fontPath); + } catch (IOException e) { + log.error("Failed to delete font file for user {}: {}", userId, e.getMessage(), e); + fileDeleteException = e; + } + + try { + customFontRepository.delete(font); + log.info("Font deleted successfully for user {}: {} ({})", userId, font.getFontName(), font.getFileName()); + } catch (Exception dbException) { + log.error("Failed to delete font from database for user {}: {}", userId, dbException.getMessage(), dbException); + + if (fileDeleteException != null) { + log.error("Additionally, file deletion also failed for font: {}", font.getFileName(), fileDeleteException); + } + + throw new APIException("Failed to delete font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } + + if (fileDeleteException != null) { + log.warn("Font deleted from database but failed to delete file for user {}: {}", userId, font.getFileName(), fileDeleteException); + } + } + + public Resource getFontFile(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + try { + validatePath(fontPath, fontDir); + } catch (IOException e) { + log.error("Invalid font path for user {}: {}", userId, fontPath, e); + throw new IllegalArgumentException("Invalid font file path"); + } + + File fontFile = fontPath.toFile(); + + if (!fontFile.exists()) { + throw new IllegalArgumentException("Font file not found on disk"); + } + + return new FileSystemResource(fontFile); + } + + public FontFormat getFontFormat(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + return font.getFormat(); + } + + private void validateFontUpload(MultipartFile file, Long userId) { + if (file.isEmpty()) { + throw new IllegalArgumentException("File is empty"); + } + + if (file.getSize() > MAX_FILE_SIZE_BYTES) { + throw new IllegalArgumentException("File size exceeds maximum limit of 5MB"); + } + + int currentFontCount = customFontRepository.countByUserId(userId); + if (currentFontCount >= MAX_FONTS_PER_USER) { + throw new IllegalArgumentException(String.format("Font limit exceeded. Maximum %d fonts per user allowed", MAX_FONTS_PER_USER)); + } + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + if (!FontFormat.isSupportedExtension(extension)) { + throw new IllegalArgumentException("Unsupported font format. Allowed formats: .ttf, .otf, .woff, .woff2"); + } + + String contentType = file.getContentType(); + if (contentType != null && !isSupportedMimeType(contentType)) { + log.warn("Potentially invalid MIME type for font: {}", contentType); + } + } + + private boolean isSupportedMimeType(String mimeType) { + return mimeType.equals("font/ttf") || + mimeType.equals("font/otf") || + mimeType.equals("font/woff") || + mimeType.equals("font/woff2") || + mimeType.equals("application/x-font-ttf") || + mimeType.equals("application/x-font-opentype") || + mimeType.equals("application/font-woff") || + mimeType.equals("application/font-woff2") || + mimeType.equals("application/octet-stream"); + } + + private String getFileExtension(String filename) { + int lastDotIndex = filename.lastIndexOf('.'); + if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) { + throw new IllegalArgumentException("File has no extension"); + } + return filename.substring(lastDotIndex); + } + + private Path getFontDirectory(Long userId) { + return Paths.get(appProperties.getPathConfig(), CUSTOM_FONTS_DIR, String.valueOf(userId)); + } + + /** + * Validates that the resolved path stays within the expected parent directory + * to prevent directory traversal attacks. + */ + private void validatePath(Path resolvedPath, Path expectedParent) throws IOException { + Path normalizedPath = resolvedPath.toAbsolutePath().normalize(); + Path normalizedParent = expectedParent.toAbsolutePath().normalize(); + + if (!normalizedPath.startsWith(normalizedParent)) { + log.error("Path traversal attempt detected: {} does not start with {}", normalizedPath, normalizedParent); + throw new IOException("Invalid file path: path traversal detected"); + } + } + + /** + * Validates font file format by checking magic bytes. + * Prevents malicious files from being uploaded with font extensions. + */ + private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException { + byte[] header = new byte[4]; + + try (var inputStream = Files.newInputStream(fontPath)) { + int bytesRead = inputStream.read(header); + + if (bytesRead < 4) { + throw new IllegalArgumentException("Invalid font file: file too small"); + } + } + + boolean isValid = false; + String detectedFormat = "Unknown"; + + // Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65) + if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) || + (header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) { + isValid = (expectedFormat == FontFormat.TTF); + detectedFormat = "TTF"; + } + // Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F) + else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) { + isValid = (expectedFormat == FontFormat.OTF); + detectedFormat = "OTF"; + } + // Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) { + isValid = (expectedFormat == FontFormat.WOFF); + detectedFormat = "WOFF"; + } + // Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) { + isValid = (expectedFormat == FontFormat.WOFF2); + detectedFormat = "WOFF2"; + } + + if (!isValid) { + log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat); + throw new IllegalArgumentException( + String.format("Invalid font file format. File appears to be %s but extension indicates %s", + detectedFormat, expectedFormat) + ); + } + + log.debug("Font file magic bytes validated successfully: {}", detectedFormat); + } + + /** + * Sanitizes font name to prevent XSS and ensure data integrity. + */ + private String sanitizeFontName(String fontName, String fallbackName) { + if (fontName == null || fontName.trim().isEmpty()) { + fontName = fallbackName; + } + + String sanitized = fontName.trim(); + + sanitized = sanitized.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); + + sanitized = sanitized.replaceAll("<[^>]*>", ""); + sanitized = sanitized.replaceAll("[<>\"'`]", ""); + + sanitized = sanitized.replaceAll("\\s+", " "); + + sanitized = sanitized.trim(); + + if (sanitized.isEmpty()) { + sanitized = fallbackName; + } + + if (sanitized.length() > MAX_FONT_NAME_LENGTH) { + sanitized = sanitized.substring(0, MAX_FONT_NAME_LENGTH).trim(); + } + + return sanitized; + } +} diff --git a/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql new file mode 100644 index 000000000..333d5feb7 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql @@ -0,0 +1,12 @@ +CREATE TABLE IF NOT EXISTS custom_font ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + font_name VARCHAR(255) NOT NULL, + file_name VARCHAR(255) NOT NULL UNIQUE, + original_file_name VARCHAR(255) NOT NULL, + format VARCHAR(10) NOT NULL, + file_size BIGINT NOT NULL, + uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_user_id (user_id) +); diff --git a/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql new file mode 100644 index 000000000..31f0d942a --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql @@ -0,0 +1,2 @@ +ALTER TABLE epub_viewer_preference ADD COLUMN IF NOT EXISTS custom_font_id BIGINT NULL; +ALTER TABLE epub_viewer_preference ADD FOREIGN KEY (custom_font_id) REFERENCES custom_font(id) ON DELETE SET NULL; diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java new file mode 100644 index 000000000..6d9c58942 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java @@ -0,0 +1,452 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CustomFontServiceTest { + + @TempDir + Path tempDir; + + @Mock + CustomFontRepository customFontRepository; + @Mock + UserRepository userRepository; + @Mock + CustomFontMapper customFontMapper; + + AppProperties appProperties; + CustomFontService service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + appProperties = new AppProperties(); + appProperties.setPathConfig(tempDir.toString()); + service = new CustomFontService(customFontRepository, userRepository, customFontMapper, appProperties); + } + + @Test + @DisplayName("uploadFont_withValidFile_shouldSaveSuccessfully") + void uploadFont_withValidFile_shouldSaveSuccessfully() throws IOException { + // Arrange + Long userId = 1L; + String fontName = "My Custom Font"; + // Create valid TTF magic bytes: 0x00 0x01 0x00 0x00 + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + CustomFontEntity savedEntity = CustomFontEntity.builder() + .id(1L) + .user(user) + .fontName(fontName) + .fileName("user_1_font_123.ttf") + .originalFileName("font.ttf") + .format(FontFormat.TTF) + .fileSize((long) fontContent.length) + .build(); + + CustomFontDto expectedDto = new CustomFontDto(); + expectedDto.setId(1L); + expectedDto.setFontName(fontName); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))).thenReturn(savedEntity); + when(customFontMapper.toDto(savedEntity)).thenReturn(expectedDto); + + // Act + CustomFontDto result = service.uploadFont(file, fontName, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.getFontName()).isEqualTo(fontName); + verify(customFontRepository).save(any(CustomFontEntity.class)); + + // Verify file was saved + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + assertThat(Files.exists(userFontDir)).isTrue(); + assertThat(Files.list(userFontDir).count()).isEqualTo(1); + } + + @Test + @DisplayName("uploadFont_whenQuotaExceeded_shouldThrowException") + void uploadFont_whenQuotaExceeded_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(10); // Max quota + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font limit exceeded"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withOversizedFile_shouldThrowException") + void uploadFont_withOversizedFile_shouldThrowException() { + // Arrange + Long userId = 1L; + byte[] largeContent = new byte[6 * 1024 * 1024]; // 6MB (exceeds 5MB limit) + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", largeContent); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("File size exceeds maximum limit"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidExtension_shouldThrowException") + void uploadFont_withInvalidExtension_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.exe", "font.exe", "application/octet-stream", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported font format"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidMagicBytes_shouldThrowException") + void uploadFont_withInvalidMagicBytes_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // File has .ttf extension but contains malicious content (not TTF magic bytes) + byte[] maliciousContent = "This is not a font file".getBytes(); + MultipartFile file = new MockMultipartFile("malicious.ttf", "malicious.ttf", "font/ttf", maliciousContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid font file format"); + + verify(customFontRepository, never()).save(any()); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("uploadFont_whenDatabaseSaveFails_shouldCleanupFile") + void uploadFont_whenDatabaseSaveFails_shouldCleanupFile() throws IOException { + // Arrange + Long userId = 1L; + // Create valid TTF magic bytes + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))) + .thenThrow(new RuntimeException("Database error")); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Database error"); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("deleteFont_withValidId_shouldDeleteFileAndRecord") + void deleteFont_withValidId_shouldDeleteFileAndRecord() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + service.deleteFont(fontId, userId); + + // Assert + verify(customFontRepository).delete(font); + assertThat(Files.exists(fontFile)).isFalse(); + } + + @Test + @DisplayName("deleteFont_whenFileDeletionFails_shouldStillDeleteRecord") + void deleteFont_whenFileDeletionFails_shouldStillDeleteRecord() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent_font.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + // Files.deleteIfExists doesn't throw when file doesn't exist, so this should succeed + assertThatCode(() -> service.deleteFont(fontId, userId)) + .doesNotThrowAnyException(); + + // Database record should be deleted + verify(customFontRepository, times(1)).delete(font); + } + + @Test + @DisplayName("deleteFont_withInvalidId_shouldThrowException") + void deleteFont_withInvalidId_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 999L; + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.deleteFont(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + + verify(customFontRepository, never()).delete(any()); + } + + @Test + @DisplayName("getFontFile_withValidId_shouldReturnResource") + void getFontFile_withValidId_shouldReturnResource() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + Resource result = service.getFontFile(fontId, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.exists()).isTrue(); + assertThat(result.getFile().toPath()).isEqualTo(fontFile); + } + + @Test + @DisplayName("getFontFile_whenUserNotOwner_shouldThrowException") + void getFontFile_whenUserNotOwner_shouldThrowException() { + // Arrange + Long userId = 1L; + Long otherUserId = 2L; + Long fontId = 1L; + + when(customFontRepository.findByIdAndUserId(fontId, otherUserId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, otherUserId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + } + + @Test + @DisplayName("getFontFile_withNonExistentFile_shouldThrowException") + void getFontFile_withNonExistentFile_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font file not found on disk"); + } + + @Test + @DisplayName("validatePath_withPathTraversal_shouldThrowException") + void validatePath_withPathTraversal_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // Use valid font extension to pass extension validation + String maliciousFileName = "../../../etc/passwd.ttf"; + // Create valid TTF magic bytes to pass magic byte validation + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile( + maliciousFileName, + maliciousFileName, + "font/ttf", + fontContent + ); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Mock repository save to complete the upload + when(customFontRepository.save(any(CustomFontEntity.class))).thenAnswer(invocation -> { + CustomFontEntity entity = invocation.getArgument(0); + entity.setId(1L); + return entity; + }); + + CustomFontDto mockDto = new CustomFontDto(); + mockDto.setId(1L); + when(customFontMapper.toDto(any(CustomFontEntity.class))).thenReturn(mockDto); + + // Act & Assert + // The service generates safe filenames, so even with malicious input, the path is safe + assertThatCode(() -> service.uploadFont(file, "Test", userId)) + .doesNotThrowAnyException(); // Safe because service generates safe filename + + // Verify no files were created outside the expected directory + Path expectedDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Path parentDir = tempDir.resolve("custom-fonts"); + + // Count files in user directory + long userDirFiles = Files.exists(expectedDir) ? Files.list(expectedDir).count() : 0; + + // Count files in parent directory (should only be the user directory) + long parentDirEntries = Files.list(parentDir).count(); + + assertThat(userDirFiles).isGreaterThanOrEqualTo(0); + assertThat(parentDirEntries).isEqualTo(1); // Only user directory, no escaped files + } + + @Test + @DisplayName("getUserFonts_shouldReturnAllUserFonts") + void getUserFonts_shouldReturnAllUserFonts() { + // Arrange + Long userId = 1L; + List entities = List.of( + CustomFontEntity.builder().id(1L).fontName("Font 1").build(), + CustomFontEntity.builder().id(2L).fontName("Font 2").build() + ); + + CustomFontDto dto1 = new CustomFontDto(); + dto1.setId(1L); + CustomFontDto dto2 = new CustomFontDto(); + dto2.setId(2L); + + when(customFontRepository.findByUserId(userId)).thenReturn(entities); + when(customFontMapper.toDto(entities.get(0))).thenReturn(dto1); + when(customFontMapper.toDto(entities.get(1))).thenReturn(dto2); + + // Act + List result = service.getUserFonts(userId); + + // Assert + assertThat(result).hasSize(2); + assertThat(result.get(0).getId()).isEqualTo(1L); + assertThat(result.get(1).getId()).isEqualTo(2L); + } + + @Test + @DisplayName("getFontFormat_shouldReturnCorrectFormat") + void getFontFormat_shouldReturnCorrectFormat() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .format(FontFormat.WOFF2) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + FontFormat result = service.getFontFormat(fontId, userId); + + // Assert + assertThat(result).isEqualTo(FontFormat.WOFF2); + } +} diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index d9c8ec3f2..773592002 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -201,6 +201,7 @@ export interface EpubViewerSetting { lineHeight: number; letterSpacing: number; spread: string; + customFontId?: number | null; } export interface CbxViewerSetting { diff --git a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html index 7abcc1680..a3f6251f6 100644 --- a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html +++ b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html @@ -166,7 +166,8 @@ [(ngModel)]="selectedFontType" (onChange)="changeFontType()" [style]="{ width: '100%' }" - placeholder="Select font"> + [loading]="!customFontsReady" + placeholder="Loading fonts...">
diff --git a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts index cb3ebbe99..f7618820e 100644 --- a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts +++ b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts @@ -1,7 +1,7 @@ import {Component, ElementRef, inject, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core'; import ePub from 'epubjs'; import {Drawer} from 'primeng/drawer'; -import {forkJoin, Subscription} from 'rxjs'; +import {firstValueFrom, forkJoin, Subscription} from 'rxjs'; import {Button} from 'primeng/button'; import {InputText} from 'primeng/inputtext'; import {CommonModule, Location} from '@angular/common'; @@ -25,6 +25,9 @@ import {IconField} from 'primeng/iconfield'; import {InputIcon} from 'primeng/inputicon'; import {BookmarkEditDialogComponent} from './bookmark-edit-dialog.component'; import {BookmarkViewDialogComponent} from './bookmark-view-dialog.component'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {CustomFont} from '../../../../shared/model/custom-font.model'; +import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util'; @Component({ selector: 'app-epub-reader', @@ -85,6 +88,9 @@ export class EpubReaderComponent implements OnInit, OnDestroy { selectedSpread?: string = 'double'; lineHeight?: number; letterSpacing?: number; + selectedCustomFontId?: number | null = null; + customFonts: CustomFont[] = []; + customFontsReady = false; fontTypes: any[] = [ {label: "Publisher's Default", value: null}, @@ -122,14 +128,30 @@ export class EpubReaderComponent implements OnInit, OnDestroy { private pageTitle = inject(PageTitleService); private bookMarkService = inject(BookMarkService); private readingSessionService = inject(ReadingSessionService); + private customFontService = inject(CustomFontService); epub!: Book; ngOnInit(): void { - this.routeSubscription = this.route.paramMap.subscribe((params) => { + this.routeSubscription = this.route.paramMap.subscribe(async (params) => { this.isLoading = true; const bookId = +params.get('bookId')!; + // Load custom fonts FIRST and wait for them + try { + const fonts = await firstValueFrom(this.customFontService.getUserFonts()); + this.customFonts = fonts; + // Wait for all fonts to load into the browser + await this.customFontService.loadAllFonts(fonts); + // Add custom fonts to dropdown + addCustomFontsToDropdown(fonts, this.fontTypes, 'select'); + } catch (err) { + console.error('Failed to load custom fonts:', err); + } finally { + // Mark fonts as ready even if loading fails (allows UI to proceed) + this.customFontsReady = true; + } + const myself$ = this.userService.getMyself(); const epub$ = this.bookService.getBookByIdFromAPI(bookId, false); const epubData$ = this.bookService.getFileContent(bookId); @@ -159,6 +181,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy { const resolvedLineHeight = settingScope === 'Global' ? globalSettings.lineHeight : individualSetting?.lineHeight; const resolvedLetterSpacing = settingScope === 'Global' ? globalSettings.letterSpacing : individualSetting?.letterSpacing; const resolvedSpread = settingScope === 'Global' ? globalSettings.spread || 'double' : individualSetting?.spread || 'double'; + const resolvedCustomFontId = settingScope === 'Global' ? globalSettings.customFontId : individualSetting?.customFontId; if (resolvedTheme != null) this.selectedTheme = resolvedTheme; if (resolvedFontFamily != null) this.selectedFontType = resolvedFontFamily; @@ -168,6 +191,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy { if (resolvedFlow != null) this.selectedFlow = resolvedFlow; if (resolvedSpread != null) this.selectedSpread = resolvedSpread; + // Set font type from settings (including custom font format) + // Don't set selectedCustomFontId yet - let applyEpubTheme() set it after verification + if (resolvedCustomFontId != null) { + this.selectedFontType = `custom:${resolvedCustomFontId}`; + } + this.initBook(); this.initRendition(); }; @@ -267,15 +296,103 @@ export class EpubReaderComponent implements OnInit, OnDestroy { } } - changeFontType(): void { - if (this.rendition) { - if (this.selectedFontType) { - this.rendition.themes.font(this.selectedFontType); - } else { - this.rendition.themes.font(''); - } - this.updateViewerSetting(); + async changeFontType(): Promise { + const result = await this.applyEpubTheme(); + + // Update state based on result + if (!result.success) { + // Font loading failed, clear the selection + this.selectedFontType = null; + this.selectedCustomFontId = null; + } else if (result.customFontId !== undefined) { + // Custom font loaded successfully or cleared + this.selectedCustomFontId = result.customFontId; } + + this.updateViewerSetting(); + } + + private async applyEpubTheme(): Promise<{ success: boolean, customFontId?: number | null }> { + if (!this.rendition) return { success: false }; + + // Determine font family - handle custom fonts + let fontFamily = this.selectedFontType; + let customFontToInject: CustomFont | null = null; + let customFontId: number | null = null; + + if (this.selectedFontType?.startsWith('custom:')) { + const fontId = parseInt(this.selectedFontType.split(':')[1]); + const customFont = this.customFonts.find(f => f.id === fontId); + if (customFont) { + try { + await this.customFontService.loadFontFace(customFont); + if (this.customFontService.isFontLoaded(customFont.fontName)) { + fontFamily = customFont.fontName; + customFontId = fontId; + customFontToInject = customFont; + } else { + // Font didn't load properly + return { success: false }; + } + } catch (error) { + // Font loading failed + console.error('Failed to load custom font:', error); + this.messageService.add({ + severity: 'warn', + summary: 'Custom fonts not loaded', + detail: 'Your custom fonts could not be loaded. The reader will use default fonts instead.', + }); + return { success: false }; + } + } + } else { + customFontId = null; + } + + // Inject or clear @font-face rules + if (customFontToInject) { + const fontUrl = this.customFontService.getFontUrl(customFontToInject.id); + const fontUrlWithToken = this.customFontService.appendToken(fontUrl); + this.rendition.themes.default({ + '@font-face': [{ + 'font-family': `"${customFontToInject.fontName}"`, + 'src': `url(${fontUrlWithToken})`, + 'font-weight': 'normal', + 'font-style': 'normal' + }] + }); + } else { + this.rendition.themes.default({}); + } + + // Apply font using EPUB.js font() method + if (fontFamily) { + this.rendition.themes.font(customFontToInject ? `"${fontFamily}"` : fontFamily); + } else { + this.rendition.themes.font(''); + } + + // Apply theme with other settings + const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {}; + const combinedTheme = { + ...baseTheme, + body: { + ...baseTheme.body, + ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), + ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), + }, + '*': { + ...baseTheme['*'], + ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), + ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), + }, + }; + + this.rendition.themes.override('font-size', `${this.fontSize}%`); + this.rendition.themes.register('custom', combinedTheme); + this.rendition.themes.select('custom'); + + return { success: true, customFontId }; } increaseFontSize(): void { @@ -298,6 +415,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy { if (this.selectedSpread === 'single' || this.selectedSpread === 'double') epubSettings.spread = this.selectedSpread; if (this.lineHeight) epubSettings.lineHeight = this.lineHeight; if (this.letterSpacing) epubSettings.letterSpacing = this.letterSpacing; + if (this.selectedCustomFontId != null) epubSettings.customFontId = this.selectedCustomFontId; const bookSetting: BookSetting = { epubSettings: epubSettings @@ -651,7 +769,6 @@ export class EpubReaderComponent implements OnInit, OnDestroy { ...baseTheme, body: { ...(baseTheme.body || {}), - ...(this.selectedFontType ? {'font-family': this.selectedFontType} : {}), ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), }, @@ -670,7 +787,18 @@ export class EpubReaderComponent implements OnInit, OnDestroy { ? this.rendition.display(targetCfi) : (this.epub?.epubProgress?.cfi ? this.rendition.display(this.epub.epubProgress.cfi) : this.rendition.display()); - displayPromise.then(() => { + displayPromise.then(async () => { + // Apply custom font after rendition is displayed + const result = await this.applyEpubTheme(); + + // If font loading failed during initialization, clear the selection + if (!result.success) { + this.selectedFontType = null; + this.selectedCustomFontId = null; + } else if (result.customFontId !== undefined) { + this.selectedCustomFontId = result.customFontId; + } + this.updateCurrentChapter(this.rendition.currentLocation()); this.setupKeyListener(); this.trackProgress(); diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html new file mode 100644 index 000000000..78c8594fe --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html @@ -0,0 +1,126 @@ +
+
+
+
+

+ + Custom Fonts +

+

+ Upload and manage your own fonts for a personalized reading experience in the EPUB reader. + You have {{ customFonts.length }} of {{ maxFonts }} custom fonts. +

+
+ +
+
+ +
+ + @if (customFonts.length === 0 && !isLoading) { +
+
+
+ +
+

No Custom Fonts Yet

+

+ Upload your favorite fonts to personalize your reading experience.
+ Click the "Add New Font" button above to get started. +

+

+ + Supported formats: TTF, OTF, WOFF, WOFF2 +

+
+
+ } @else { +
+
+

+ + Your Font Library + ({{ customFonts.length }}) +

+

+ Manage your uploaded custom fonts. Each font can be selected in the EPUB reader settings. +

+
+ +
+ @for (font of customFonts; track font.id) { +
+
+
+

{{ font.fontName }}

+ {{ font.format }} +
+ +
+ +
+ + @if (!fontsLoadedInBrowser) { +
+ + + + + + +
+ } @else { +
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +

+

+ Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +

+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 +
+
+ } +
+ + +
+ } +
+
+ } +
+
+ + diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss new file mode 100644 index 000000000..76b6a3e0e --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss @@ -0,0 +1,384 @@ +.main-container { + width: 100%; + padding: 1rem; + height: calc(100dvh - 10.5rem); + overflow-y: auto; + border-width: 1px; + border-radius: 0.5rem; + + @media (min-width: 768px) { + height: calc(100dvh - 11.65rem); + } +} + +.enclosing-container { + border-color: var(--p-content-border-color); + background: var(--p-content-background); +} + +.settings-header { + margin-top: 1rem; + margin-bottom: 2rem; + + .header-content { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 2rem; + + @media (max-width: 768px) { + flex-direction: column; + gap: 1rem; + } + } + + .header-text { + flex: 1; + } +} + +.settings-title { + display: flex; + align-items: center; + gap: 0.75rem; + font-size: 1.25rem; + font-weight: 700; + color: var(--p-text-color); + margin: 0 0 0.75rem 0; + + .pi { + color: var(--p-primary-color); + font-size: 1.25rem; + } +} + +.settings-description { + color: var(--p-text-muted-color); + font-size: 0.875rem; + line-height: 1.5; + margin-bottom: 0; +} + +.settings-content { + display: flex; + flex-direction: column; + gap: 2rem; +} + +.preferences-section { + @media (min-width: 768px) { + padding: 0 1rem; + } +} + +.section-header { + margin-bottom: 1rem; +} + +.section-title { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 1.125rem; + font-weight: 600; + color: var(--p-text-color); + margin: 0 0 0.5rem 0; + + .pi { + color: var(--p-primary-color); + } + + .font-count { + color: var(--p-text-muted-color); + font-size: 1rem; + font-weight: 500; + } +} + +.section-description { + color: var(--p-text-muted-color); + font-size: 0.875rem; + line-height: 1.5; + margin: 0; +} + +.settings-card { + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + background: var(--p-content-background); + padding: 1.5rem; + display: flex; + flex-direction: column; + gap: 1rem; +} + +// ==================== Empty State ==================== +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 3rem 1.5rem; + min-height: 300px; + + .empty-icon-wrapper { + display: flex; + align-items: center; + justify-content: center; + width: 80px; + height: 80px; + background: color-mix(in srgb, var(--p-primary-color) 10%, transparent); + border-radius: 50%; + margin-bottom: 1.5rem; + border: 3px dashed var(--p-primary-color); + + .empty-icon { + font-size: 2.5rem; + color: var(--p-primary-color); + opacity: 0.7; + } + } + + .empty-title { + margin: 0 0 0.75rem 0; + font-size: 1.25rem; + font-weight: 600; + color: var(--p-text-color); + } + + .empty-description { + margin: 0 0 1rem 0; + font-size: 0.9375rem; + color: var(--p-text-muted-color); + max-width: 500px; + line-height: 1.6; + } + + .empty-hint { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + margin: 0; + padding: 0.75rem 1.25rem; + background: color-mix(in srgb, var(--p-primary-color) 5%, transparent); + border: 1px solid color-mix(in srgb, var(--p-primary-color) 20%, transparent); + border-radius: 6px; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + max-width: 500px; + + i { + color: var(--p-primary-color); + font-size: 0.875rem; + flex-shrink: 0; + } + + strong { + color: var(--p-text-color); + font-weight: 600; + } + } + + @media (max-width: 768px) { + padding: 2rem 1rem; + min-height: 250px; + + .empty-icon-wrapper { + width: 70px; + height: 70px; + margin-bottom: 1rem; + + .empty-icon { + font-size: 2rem; + } + } + + .empty-title { + font-size: 1.125rem; + } + + .empty-description { + font-size: 0.875rem; + max-width: 100%; + } + + .empty-hint { + font-size: 0.75rem; + padding: 0.625rem 1rem; + max-width: 100%; + flex-direction: column; + text-align: center; + gap: 0.375rem; + } + } +} + +// ==================== Fonts Grid ==================== +.fonts-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); + gap: 1.5rem; + + @media (max-width: 768px) { + grid-template-columns: 1fr; + } +} + +// ==================== Font Card ==================== +.font-card { + padding: 0; + gap: 0; + + .font-card-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 1rem; + padding: 1rem 1rem 0.75rem; + border-bottom: 1px solid var(--p-content-border-color); + + .font-title-group { + flex: 1; + display: flex; + align-items: center; + gap: 0.75rem; + flex-wrap: wrap; + + .font-name { + margin: 0; + font-size: 1rem; + font-weight: 600; + color: var(--p-text-color); + } + + .format-tag { + display: inline-block; + padding: 0.1875rem 0.5rem; + border-radius: 4px; + background: transparent; + border: 1px solid var(--p-primary-color); + color: var(--p-primary-color); + font-size: 0.6875rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.025em; + } + } + } + + .font-preview-area { + padding: 1rem; + border-bottom: 1px solid var(--p-content-border-color); + + .preview-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--p-text-muted-color); + text-transform: uppercase; + letter-spacing: 0.025em; + margin-bottom: 0.75rem; + + i { + font-size: 0.75rem; + } + } + + .font-preview { + padding: 1rem; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background)); + display: flex; + flex-direction: column; + gap: 0.75rem; + + .preview-paragraph { + color: var(--p-text-color); + font-size: 0.9375rem; + line-height: 1.7; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-paragraph-small { + color: var(--p-text-color); + font-size: 0.8125rem; + line-height: 1.6; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-characters { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding-top: 0.5rem; + margin-top: 0.25rem; + border-top: 1px solid var(--p-content-border-color); + + span { + font-size: 0.6875rem; + color: var(--p-text-muted-color); + letter-spacing: 0.025em; + font-weight: 400; + } + } + } + + .font-preview-skeleton { + padding: 1rem; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background)); + display: flex; + flex-direction: column; + gap: 0.75rem; + } + } + + .font-metadata { + padding: 1rem; + background: color-mix(in srgb, var(--p-surface-ground) 20%, var(--p-content-background)); + + .metadata-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; + padding: 0.375rem 0; + + &:not(:last-child) { + border-bottom: 1px solid var(--p-content-border-color); + } + + .meta-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + font-weight: 500; + + i { + color: var(--p-primary-color); + font-size: 0.75rem; + } + } + + .meta-value { + font-size: 0.8125rem; + color: var(--p-text-color); + font-weight: 500; + text-align: right; + word-break: break-word; + } + } + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts new file mode 100644 index 000000000..d40cc7bb2 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts @@ -0,0 +1,133 @@ +import {Component, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {Button} from 'primeng/button'; +import {MessageService} from 'primeng/api'; +import {CustomFontService} from '../../../shared/service/custom-font.service'; +import {CustomFont, formatFileSize} from '../../../shared/model/custom-font.model'; +import {ConfirmDialog} from 'primeng/confirmdialog'; +import {ConfirmationService} from 'primeng/api'; +import {Tooltip} from 'primeng/tooltip'; +import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {FontUploadDialogComponent} from './font-upload-dialog/font-upload-dialog.component'; +import {Skeleton} from 'primeng/skeleton'; + +@Component({ + selector: 'app-custom-fonts', + standalone: true, + imports: [CommonModule, Button, ConfirmDialog, Tooltip, Skeleton], + templateUrl: './custom-fonts.component.html', + styleUrls: ['./custom-fonts.component.scss'], + providers: [ConfirmationService, DialogService] +}) +export class CustomFontsComponent implements OnInit { + customFonts: CustomFont[] = []; + isLoading = true; + fontsLoadedInBrowser = false; + uploadDialogRef: DynamicDialogRef | null = null; + + readonly maxFonts = 10; + + constructor( + private customFontService: CustomFontService, + private messageService: MessageService, + private confirmationService: ConfirmationService, + private dialogService: DialogService + ) {} + + ngOnInit(): void { + this.loadFonts(); + } + + async loadFonts(): Promise { + this.fontsLoadedInBrowser = false; + + try { + const fonts = await new Promise((resolve, reject) => { + this.customFontService.getUserFonts().subscribe({ + next: resolve, + error: reject + }); + }); + + this.customFonts = fonts; + this.isLoading = false; + + await this.customFontService.loadAllFonts(fonts); + + this.fontsLoadedInBrowser = true; + } catch (error) { + console.error('Failed to load fonts:', error); + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to load custom fonts' + }); + this.isLoading = false; + this.fontsLoadedInBrowser = true; + } + } + + openUploadDialog(): void { + if (this.customFonts.length >= this.maxFonts) { + this.messageService.add({ + severity: 'error', + summary: 'Quota Exceeded', + detail: `Maximum ${this.maxFonts} fonts allowed per user` + }); + return; + } + + this.uploadDialogRef = this.dialogService.open(FontUploadDialogComponent, { + showHeader: false, + styleClass: 'dynamic-dialog-minimal', + modal: true, + dismissableMask: false, + closable: false, + width: '700px', + breakpoints: { + '768px': '95vw' + } + }); + + if (this.uploadDialogRef) { + this.uploadDialogRef.onClose.subscribe((font: CustomFont | null) => { + if (font) { + this.customFonts.push(font); + } + this.uploadDialogRef = null; + }); + } + } + + deleteFont(font: CustomFont): void { + this.confirmationService.confirm({ + message: `Are you sure you want to delete the font "${font.fontName}"?`, + header: 'Delete Font', + icon: 'pi pi-exclamation-triangle', + accept: () => { + this.customFontService.deleteFont(font.id).subscribe({ + next: () => { + this.customFonts = this.customFonts.filter(f => f.id !== font.id); + this.messageService.add({ + severity: 'success', + summary: 'Success', + detail: `Font "${font.fontName}" deleted successfully` + }); + }, + error: (error) => { + console.error('Failed to delete font:', error); + this.messageService.add({ + severity: 'error', + summary: 'Delete Failed', + detail: 'Failed to delete font' + }); + } + }); + } + }); + } + + formatFileSize(bytes: number): string { + return formatFileSize(bytes); + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html new file mode 100644 index 000000000..687ff1e90 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html @@ -0,0 +1,131 @@ +
+
+
+ +
+
+

Add New Font

+

+ Upload a custom font for your EPUB reader +

+
+ +
+ +
+
+
+ + + Select Font File + +
+ + @if (!selectedFile) { +
+ +
+
+ +
+

Drag and Drop Font File

+

+ Supported formats: TTF, OTF, WOFF, WOFF2 +
+ Maximum file size: 5 MB +

+
+
+ } @else { +
+
+ +
+ {{ selectedFile.name }} + {{ formatFileSize(selectedFile.size) }} • {{ selectedFile.name.split('.').pop()?.toUpperCase() }} +
+
+ + @if (previewFontFamily) { +
+ +
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. + Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +

+

+ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +

+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyz + 0123456789 !@#$%^&*() +
+
+
+ } + +
+
+ +

+ This name will appear in the font selector when reading EPUB books. +

+
+
+ +
+
+
+ } +
+ + +
diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss new file mode 100644 index 000000000..91b3fa411 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss @@ -0,0 +1,443 @@ +.font-upload-dialog { + width: 700px; + max-width: 700px; + display: flex; + flex-direction: column; + + @media (max-width: 768px) { + width: 100%; + max-width: 100%; + } +} + +.panel-header { + position: relative; + display: flex; + align-items: center; + gap: 1rem; + padding: 1.5rem 1.5rem 1.25rem 1.5rem; + border-radius: 10px 10px 0 0; + border: 1px solid var(--border-color); + border-bottom: none; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + + .header-icon-wrapper { + display: flex; + align-items: center; + justify-content: center; + width: 48px; + height: 48px; + background: var(--primary-color); + border-radius: 10px; + + .header-icon { + font-size: 1.5rem; + color: var(--primary-contrast-color); + } + } + + .header-text { + flex: 1; + + .panel-title { + margin: 0 0 0.25rem 0; + font-size: 1.25rem; + font-weight: 600; + color: var(--text-color); + } + + .panel-description { + margin: 0; + font-size: 0.875rem; + color: var(--text-secondary-color); + } + } + + .close-button { + position: absolute; + top: 0.75rem; + right: 0.75rem; + } + + @media (max-width: 480px) { + padding: 1rem; + + .header-icon-wrapper { + width: 40px; + height: 40px; + + .header-icon { + font-size: 1.25rem; + } + } + + .header-text { + .panel-title { + font-size: 1.125rem; + } + + .panel-description { + font-size: 0.8rem; + } + } + + .close-button { + top: 0.5rem; + right: 0.5rem; + + ::ng-deep .p-button { + width: 2rem; + height: 2rem; + } + } + } +} + +.upload-container { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1.75rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-radius: 0 0 10px 10px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + + @media (max-width: 480px) { + padding: 1rem; + gap: 1rem; + } +} + +.file-upload-section { + display: flex; + flex-direction: column; + + .section-header { + display: flex; + align-items: center; + justify-content: center; + padding: 0.625rem 0.875rem; + background: var(--overlay-background); + border-radius: 6px; + + .section-title { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.9rem; + font-weight: 600; + color: var(--text-color); + + i { + color: var(--primary-color); + font-size: 1rem; + } + } + + @media (max-width: 480px) { + padding: 0.5rem 0.625rem; + + .section-title { + font-size: 0.85rem; + } + } + } + + .empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 1.5rem 1rem; + + .empty-icon-wrapper { + display: flex; + align-items: center; + justify-content: center; + width: 80px; + height: 80px; + background: var(--overlay-background); + border-radius: 50%; + margin-bottom: 1rem; + border: 3px dashed var(--border-color); + + .empty-icon { + font-size: 2.5rem; + color: var(--text-secondary-color); + opacity: 0.6; + } + } + + .empty-title { + margin: 0 0 0.5rem 0; + font-size: 1.125rem; + font-weight: 600; + color: var(--text-color); + } + + .empty-description { + margin: 0; + font-size: 0.875rem; + color: var(--text-secondary-color); + max-width: 450px; + line-height: 1.5; + + strong { + color: var(--text-color); + } + } + + @media (max-width: 480px) { + padding: 1.5rem 0.75rem; + min-height: 180px; + + .empty-icon-wrapper { + width: 70px; + height: 70px; + margin-bottom: 0.75rem; + + .empty-icon { + font-size: 2rem; + } + } + + .empty-title { + font-size: 1rem; + } + + .empty-description { + font-size: 0.8rem; + max-width: 100%; + } + } + } +} + +// ==================== Upload Zone ==================== +.upload-zone { + padding: 2rem; + text-align: center; + border: 2px dashed var(--border-color); + border-radius: 8px; + background: var(--ground-background); + transition: all 0.3s ease; + cursor: pointer; + + &:hover:not(.disabled) { + border-color: var(--primary-color); + background: color-mix( + in srgb, + var(--primary-color) 3%, + var(--ground-background) + ); + } + + &.drag-over { + border-color: var(--primary-color); + background: color-mix( + in srgb, + var(--primary-color) 8%, + var(--ground-background) + ); + + .empty-icon-wrapper { + border-color: var(--primary-color); + + .empty-icon { + color: var(--primary-color); + transform: scale(1.1); + } + } + } + + &.disabled { + cursor: not-allowed; + opacity: 0.6; + } +} + +// ==================== File Selected ==================== +.file-selected { + display: flex; + flex-direction: column; + gap: 1.5rem; + width: 100%; + max-width: 100%; + overflow: hidden; +} + +.file-info-card { + display: flex; + align-items: center; + gap: 1rem; + padding: 1rem; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--overlay-background); + width: 100%; + max-width: 100%; + overflow: hidden; + + i { + font-size: 2rem; + color: var(--primary-color); + flex-shrink: 0; + } + + .file-details { + flex: 1; + display: flex; + flex-direction: column; + gap: 0.25rem; + min-width: 0; + overflow: hidden; + + .file-name { + font-weight: 600; + color: var(--text-color); + font-size: 0.9375rem; + word-break: break-word; + overflow-wrap: break-word; + } + + .file-meta { + font-size: 0.8125rem; + color: var(--text-secondary-color); + } + } +} + +.preview-section { + display: flex; + flex-direction: column; + gap: 0.75rem; + width: 100%; + max-width: 100%; + overflow: hidden; + + .preview-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--text-secondary-color); + text-transform: uppercase; + letter-spacing: 0.025em; + + i { + font-size: 0.75rem; + color: var(--primary-color); + } + } + + .font-preview { + padding: 1.5rem; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--overlay-background); + display: flex; + flex-direction: column; + gap: 1rem; + max-height: 300px; + overflow-y: auto; + width: 100%; + max-width: 100%; + box-sizing: border-box; + + .preview-paragraph { + color: var(--text-color); + font-size: 1rem; + line-height: 1.7; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-paragraph-small { + color: var(--text-color); + font-size: 0.875rem; + line-height: 1.6; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-characters { + display: flex; + flex-direction: column; + gap: 0.375rem; + padding-top: 0.75rem; + margin-top: 0.5rem; + border-top: 1px solid var(--border-color); + + span { + font-size: 0.75rem; + color: var(--text-secondary-color); + letter-spacing: 0.025em; + font-weight: 400; + } + } + } +} + +.setting-item { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0; + width: 100%; + max-width: 100%; +} + +.setting-info { + width: 100%; + + .setting-label { + display: block; + font-weight: 600; + color: var(--text-color); + font-size: 1rem; + margin-bottom: 0.5rem; + } + + .setting-description { + color: var(--text-secondary-color); + font-size: 0.875rem; + line-height: 1.5; + margin: 0; + } +} + +.setting-control { + display: flex; + flex-direction: column; + gap: 0.75rem; + width: 100%; + + .font-name-input { + width: 100%; + } +} + +// ==================== Dialog Footer ==================== +.dialog-footer { + display: flex; + gap: 0.75rem; + justify-content: flex-end; + padding: 1rem 1.5rem 1.5rem; + border-top: 1px solid var(--border-color); + width: 100%; + max-width: 100%; + box-sizing: border-box; + + @media (max-width: 768px) { + flex-direction: column; + + ::ng-deep .p-button { + width: 100%; + } + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts new file mode 100644 index 000000000..1f26ed922 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts @@ -0,0 +1,244 @@ +import {Component, ViewChild, ElementRef, OnDestroy} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {Button} from 'primeng/button'; +import {MessageService} from 'primeng/api'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {formatFileSize} from '../../../../shared/model/custom-font.model'; +import {InputText} from 'primeng/inputtext'; +import {FormsModule} from '@angular/forms'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; + +@Component({ + selector: 'app-font-upload-dialog', + standalone: true, + imports: [CommonModule, Button, InputText, FormsModule], + templateUrl: './font-upload-dialog.component.html', + styleUrls: ['./font-upload-dialog.component.scss'] +}) +export class FontUploadDialogComponent implements OnDestroy { + @ViewChild('fileInput') fileInput!: ElementRef; + + isUploading = false; + uploadedFontName = ''; + selectedFile: File | null = null; + isDragOver = false; + previewFontFamily: string | null = null; + isLoadingPreview = false; + currentPreviewToken: number | null = null; + + readonly maxFileSize = 5242880; + readonly maxFonts = 10; + readonly acceptedFormats = ['.ttf', '.otf', '.woff', '.woff2']; + + constructor( + private customFontService: CustomFontService, + private messageService: MessageService, + private dialogRef: DynamicDialogRef + ) {} + + onUploadZoneClick(): void { + if (this.isUploading) { + return; + } + this.fileInput.nativeElement.click(); + } + + onFileInputChange(event: Event): void { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + + if (!file) return; + + if (!this.validateFile(file)) { + input.value = ''; + return; + } + + this.processFile(file); + input.value = ''; + } + + async loadFontPreview(file: File): Promise { + this.cleanupPreviewFont(); + + const previewToken = Date.now(); + this.currentPreviewToken = previewToken; + + if (this.isLoadingPreview) { + console.log('Cancelling previous preview load'); + } + + this.isLoadingPreview = true; + + try { + const previewFontName = `preview-font-${previewToken}`; + const arrayBuffer = await file.arrayBuffer(); + + if (this.currentPreviewToken !== previewToken) { + console.log('Preview operation cancelled - newer preview started'); + return; + } + + const fontFace = new FontFace(previewFontName, arrayBuffer); + await fontFace.load(); + + if (this.currentPreviewToken !== previewToken) { + console.log('Preview operation cancelled after load - newer preview started'); + document.fonts.delete(fontFace); + return; + } + + document.fonts.add(fontFace); + this.previewFontFamily = `"${previewFontName}"`; + } catch (error) { + if (this.currentPreviewToken === previewToken) { + console.error('Failed to load font preview:', error); + this.previewFontFamily = null; + this.messageService.add({ + severity: 'warn', + summary: 'Preview Failed', + detail: 'Unable to preview font, but you can still upload it' + }); + } + } finally { + if (this.currentPreviewToken === previewToken) { + this.isLoadingPreview = false; + } + } + } + + uploadFont(): void { + if (!this.selectedFile) { + this.messageService.add({ + severity: 'warn', + summary: 'No File Selected', + detail: 'Please select a font file to upload' + }); + return; + } + + this.isUploading = true; + this.customFontService.uploadFont(this.selectedFile, this.uploadedFontName || undefined).subscribe({ + next: (font) => { + this.messageService.add({ + severity: 'success', + summary: 'Success', + detail: `Font "${font.fontName}" uploaded successfully` + }); + this.isUploading = false; + this.dialogRef.close(font); // Return the uploaded font + }, + error: (error) => { + console.error('Failed to upload font:', error); + let errorMessage = 'Failed to upload font'; + if (error.status === 400) { + errorMessage = 'Invalid file format or quota exceeded'; + } + this.messageService.add({ + severity: 'error', + summary: 'Upload Failed', + detail: errorMessage + }); + + this.isUploading = false; + this.selectedFile = null; + this.uploadedFontName = ''; + this.cleanupPreviewFont(); + } + }); + } + + formatFileSize(bytes: number): string { + return formatFileSize(bytes); + } + + cancel(): void { + this.cleanupPreviewFont(); + this.dialogRef.close(null); + } + + onDragOver(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = true; + } + + onDragLeave(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = false; + } + + onDrop(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = false; + + const files = event.dataTransfer?.files; + if (files && files.length > 0) { + const file = files[0]; + + if (!this.validateFile(file)) { + return; + } + + this.processFile(file); + } + } + + private validateFile(file: File): boolean { + const fileName = file.name.toLowerCase(); + const isValidFormat = this.acceptedFormats.some(format => fileName.endsWith(format)); + + if (!isValidFormat) { + this.messageService.add({ + severity: 'error', + summary: 'Invalid File Type', + detail: 'Please upload a TTF, OTF, WOFF, or WOFF2 font file' + }); + return false; + } + + if (file.size > this.maxFileSize) { + this.messageService.add({ + severity: 'error', + summary: 'File Too Large', + detail: `File size must not exceed ${this.formatFileSize(this.maxFileSize)}` + }); + return false; + } + + return true; + } + + private processFile(file: File): void { + this.selectedFile = file; + this.uploadedFontName = file.name.replace(/\.[^/.]+$/, ''); + this.loadFontPreview(file); + } + + cleanupPreviewFont(): void { + if (this.previewFontFamily) { + const fontName = this.previewFontFamily.replace(/"/g, ''); + + try { + for (const font of document.fonts) { + if (font.family === fontName) { + document.fonts.delete(font); + } + } + } catch (error) { + console.error('Failed to cleanup preview font:', fontName, error); + } + + this.previewFontFamily = null; + } + + this.currentPreviewToken = null; + this.isLoadingPreview = false; + } + + ngOnDestroy(): void { + this.cleanupPreviewFont(); + } +} diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html index 5778b2cc1..ecf42ef2b 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html @@ -37,13 +37,22 @@ type="button" class="option-button font-button" [class.selected]="selectedFont === font.key" + [class.separator]="font.key === 'separator'" [attr.data-font]="font.key" + [disabled]="font.key === 'separator'" (click)="selectedFont = font.key" [pTooltip]="font.name" tooltipPosition="bottom"> - {{ font.displayName }} + + {{ font.displayName }} + } + + @if (!customFontsReady) { + + }

diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss index 3f0c50fe0..e88e7ea3a 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss @@ -194,6 +194,28 @@ &[data-font="monospace"] .option-text { font-family: 'Courier New', monospace; } + + // Custom font buttons use the loaded font + &[data-font^="custom:"] .option-text { + font-size: 0.875rem; + } + } + + &.separator { + cursor: default; + pointer-events: none; + opacity: 0.6; + background: transparent; + border-color: transparent; + font-weight: 600; + color: var(--p-text-muted-color); + min-width: auto; + padding: 0.25rem 0.5rem; + + &:hover { + transform: none; + box-shadow: none; + } } } } diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index 879e91839..3ad81b94d 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -1,27 +1,37 @@ -import {Component, inject, Input} from '@angular/core'; +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; import {Button} from 'primeng/button'; import {FormsModule} from '@angular/forms'; import {ReaderPreferencesService} from '../reader-preferences-service'; import {UserSettings} from '../../user-management/user.service'; import {Tooltip} from 'primeng/tooltip'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {CustomFont} from '../../../../shared/model/custom-font.model'; +import {skip, Subject, takeUntil} from 'rxjs'; +import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util'; +import {Skeleton} from 'primeng/skeleton'; @Component({ selector: 'app-epub-reader-preferences-component', imports: [ Button, FormsModule, - Tooltip + Tooltip, + Skeleton ], templateUrl: './epub-reader-preferences-component.html', styleUrl: './epub-reader-preferences-component.scss' }) -export class EpubReaderPreferencesComponent { +export class EpubReaderPreferencesComponent implements OnInit, OnDestroy { @Input() userSettings!: UserSettings; private readonly readerPreferencesService = inject(ReaderPreferencesService); + private readonly customFontService = inject(CustomFontService); + private readonly destroy$ = new Subject(); - readonly fonts = [ + customFonts: CustomFont[] = []; + + fonts = [ {name: 'Book Default', displayName: 'Default', key: null}, {name: 'Serif', displayName: 'Aa', key: 'serif'}, {name: 'Sans Serif', displayName: 'Aa', key: 'sans-serif'}, @@ -58,6 +68,81 @@ export class EpubReaderPreferencesComponent { {name: 'Dark Brown', key: 'dark-brown', color: '#3E2723'} ]; + customFontsReady = false; + + ngOnInit(): void { + this.subscribeToFontUpdates(); + + this.customFontService.getUserFonts().subscribe({ + next: () => { + this.customFontsReady = true; + }, + error: (err) => { + console.error('Failed to load custom fonts:', err); + this.customFontsReady = true; + } + }); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private subscribeToFontUpdates(): void { + this.customFontService.fonts$ + .pipe( + skip(1), + takeUntil(this.destroy$) + ) + .subscribe(async fonts => { + try { + const selectedFontDeleted = this.isCurrentlySelectedFontDeleted(fonts); + + if (this.hasCustomFontsChanged(fonts)) { + this.customFonts = fonts; + await this.customFontService.loadAllFonts(fonts); + this.updateFontsDropdown(fonts); + } + + if (selectedFontDeleted) { + this.resetToDefaultFont(); + } + } catch (err) { + console.error('Failed to process custom fonts:', err); + } + }); + } + + private hasCustomFontsChanged(newFonts: CustomFont[]): boolean { + if (newFonts.length !== this.customFonts.length) { + return true; + } + const newIds = new Set(newFonts.map(f => f.id)); + const currentIds = new Set(this.customFonts.map(f => f.id)); + return newFonts.some(f => !currentIds.has(f.id)) || this.customFonts.some(f => !newIds.has(f.id)); + } + + private updateFontsDropdown(fonts: CustomFont[]): void { + this.fonts = this.fonts.filter(font => !font.key || !font.key.startsWith('custom:')); + addCustomFontsToDropdown(fonts, this.fonts, 'preference'); + } + + private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean { + const customFontId = this.userSettings.epubReaderSetting.customFontId; + if (!customFontId) { + return false; + } + + const fontStillExists = newFonts.some(font => font.id === customFontId); + return !fontStillExists; + } + + private resetToDefaultFont(): void { + console.log('Selected custom font was deleted, resetting to default font'); + this.selectedFont = null; + } + get selectedTheme(): string | null { return this.userSettings.epubReaderSetting.theme; } @@ -70,14 +155,40 @@ export class EpubReaderPreferencesComponent { } get selectedFont(): string | null { + // If customFontId is set, return the custom font key + if (this.userSettings.epubReaderSetting.customFontId) { + return `custom:${this.userSettings.epubReaderSetting.customFontId}`; + } return this.userSettings.epubReaderSetting.font; } set selectedFont(value: string | null) { - if (typeof value === "string") { + // Handle custom fonts + if (value && value.startsWith('custom:')) { + const fontIdStr = value.split(':')[1]; + const fontId = parseInt(fontIdStr, 10); + + if (isNaN(fontId)) { + console.error('Invalid custom font ID:', value); + return; + } + + // Update both fields in local state + this.userSettings.epubReaderSetting.customFontId = fontId; this.userSettings.epubReaderSetting.font = value; + } else { + // Clear customFontId and set font in local state + this.userSettings.epubReaderSetting.customFontId = null; + if (typeof value === "string") { + this.userSettings.epubReaderSetting.font = value; + } else { + // value is null - set to default font + this.userSettings.epubReaderSetting.font = null as any; + } } - this.readerPreferencesService.updatePreference(['epubReaderSetting', 'font'], value); + + // Single API call with entire epubReaderSetting object + this.readerPreferencesService.updatePreference(['epubReaderSetting'], this.userSettings.epubReaderSetting); } get selectedFlow(): string | null { @@ -122,4 +233,13 @@ export class EpubReaderPreferencesComponent { this.fontSize -= 10; } } + + getCustomFontName(fontKey: string): string | null { + if (!fontKey || !fontKey.startsWith('custom:')) { + return null; + } + const fontId = parseInt(fontKey.split(':')[1]); + const customFont = this.customFonts.find(f => f.id === fontId); + return customFont ? customFont.fontName : null; + } } diff --git a/booklore-ui/src/app/features/settings/settings.component.html b/booklore-ui/src/app/features/settings/settings.component.html index 1e854b04f..aa0a7b675 100644 --- a/booklore-ui/src/app/features/settings/settings.component.html +++ b/booklore-ui/src/app/features/settings/settings.component.html @@ -6,6 +6,9 @@ Reader + + Custom Fonts + View @@ -56,6 +59,9 @@ + + + diff --git a/booklore-ui/src/app/features/settings/settings.component.ts b/booklore-ui/src/app/features/settings/settings.component.ts index ee34ca5f7..f6b1cc840 100644 --- a/booklore-ui/src/app/features/settings/settings.component.ts +++ b/booklore-ui/src/app/features/settings/settings.component.ts @@ -17,9 +17,11 @@ import {DeviceSettingsComponent} from './device-settings/device-settings-compone import {LibraryMetadataSettingsComponent} from './library-metadata-settings/library-metadata-settings.component'; import { PageTitleService } from "../../shared/service/page-title.service"; import {EmailV2Component} from './email-v2/email-v2.component'; +import {CustomFontsComponent} from './custom-fonts/custom-fonts.component'; export enum SettingsTab { ReaderSettings = 'reader', + CustomFonts = 'custom-fonts', ViewPreferences = 'view', DeviceSettings = 'device', UserManagement = 'user', @@ -47,6 +49,7 @@ export enum SettingsTab { AuthenticationSettingsComponent, ViewPreferencesParentComponent, ReaderPreferences, + CustomFontsComponent, MetadataSettingsComponent, DeviceSettingsComponent, FileNamingPatternComponent, diff --git a/booklore-ui/src/app/features/settings/user-management/user.service.ts b/booklore-ui/src/app/features/settings/user-management/user.service.ts index e8d31124a..2f88383af 100644 --- a/booklore-ui/src/app/features/settings/user-management/user.service.ts +++ b/booklore-ui/src/app/features/settings/user-management/user.service.ts @@ -105,6 +105,7 @@ export interface EpubReaderSetting { lineHeight: number; margin: number; letterSpacing: number; + customFontId?: number | null; } export interface CbxReaderSetting { diff --git a/booklore-ui/src/app/shared/model/custom-font.model.ts b/booklore-ui/src/app/shared/model/custom-font.model.ts new file mode 100644 index 000000000..27d56ac2a --- /dev/null +++ b/booklore-ui/src/app/shared/model/custom-font.model.ts @@ -0,0 +1,23 @@ +export interface CustomFont { + id: number; + fontName: string; + originalFileName: string; + format: FontFormat; + fileSize: number; + uploadedAt: string; +} + +export enum FontFormat { + TTF = 'TTF', + OTF = 'OTF', + WOFF = 'WOFF', + WOFF2 = 'WOFF2' +} + +export function formatFileSize(bytes: number): string { + if (bytes === 0) return '0 Bytes'; + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]; +} diff --git a/booklore-ui/src/app/shared/service/custom-font.service.ts b/booklore-ui/src/app/shared/service/custom-font.service.ts new file mode 100644 index 000000000..c3fcca505 --- /dev/null +++ b/booklore-ui/src/app/shared/service/custom-font.service.ts @@ -0,0 +1,122 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {BehaviorSubject, Observable, tap} from 'rxjs'; +import {CustomFont} from '../model/custom-font.model'; +import {API_CONFIG} from '../../core/config/api-config'; +import {AuthService} from './auth.service'; + +@Injectable({ + providedIn: 'root' +}) +export class CustomFontService { + private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`; + private fontsSubject = new BehaviorSubject([]); + public fonts$ = this.fontsSubject.asObservable(); + private loadedFonts = new Set(); + private authService = inject(AuthService); + + constructor(private http: HttpClient) {} + + uploadFont(file: File, fontName?: string): Observable { + const formData = new FormData(); + formData.append('file', file); + if (fontName) { + formData.append('fontName', fontName); + } + + return this.http.post(`${this.apiUrl}/upload`, formData).pipe( + tap(font => { + // Add to cache + const currentFonts = this.fontsSubject.value; + this.fontsSubject.next([...currentFonts, font]); + // Load the font immediately + this.loadFontFace(font).catch(err => { + console.error('Failed to load font after upload:', err); + }); + }) + ); + } + + getUserFonts(): Observable { + return this.http.get(this.apiUrl).pipe( + tap(fonts => { + this.fontsSubject.next(fonts); + }) + ); + } + + deleteFont(fontId: number): Observable { + return this.http.delete(`${this.apiUrl}/${fontId}`).pipe( + tap(() => { + // Remove from cache + const currentFonts = this.fontsSubject.value; + const updatedFonts = currentFonts.filter(f => f.id !== fontId); + this.fontsSubject.next(updatedFonts); + + // Remove from loaded fonts set and document.fonts + const deletedFont = currentFonts.find(f => f.id === fontId); + if (deletedFont) { + this.removeFontFace(deletedFont.fontName); + this.loadedFonts.delete(deletedFont.fontName); + } + }) + ); + } + + getFontUrl(fontId: number): string { + return `${this.apiUrl}/${fontId}/file`; + } + + private getToken(): string | null { + return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken(); + } + + public appendToken(url: string): string { + const token = this.getToken(); + return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url; + } + + async loadFontFace(font: CustomFont): Promise { + if (this.loadedFonts.has(font.fontName)) { + return; + } + + try { + const absoluteFontUrl = this.getFontUrl(font.id); + const fontUrlWithToken = this.appendToken(absoluteFontUrl); + + const fontFace = new FontFace( + font.fontName, + `url(${fontUrlWithToken})`, + { + weight: 'normal', + style: 'normal' + } + ); + + await fontFace.load(); + document.fonts.add(fontFace); + this.loadedFonts.add(font.fontName); + } catch (error) { + console.error(`Failed to load font ${font.fontName}:`, error); + throw error; + } + } + + async loadAllFonts(fonts: CustomFont[]): Promise { + const loadPromises = fonts.map(font => this.loadFontFace(font)); + await Promise.allSettled(loadPromises); + } + + isFontLoaded(fontName: string): boolean { + return this.loadedFonts.has(fontName); + } + + private removeFontFace(fontName: string): void { + for (const font of document.fonts) { + if (font.family === fontName) { + document.fonts.delete(font); + } + } + } +} diff --git a/booklore-ui/src/app/shared/util/custom-font.util.ts b/booklore-ui/src/app/shared/util/custom-font.util.ts new file mode 100644 index 000000000..396c96351 --- /dev/null +++ b/booklore-ui/src/app/shared/util/custom-font.util.ts @@ -0,0 +1,74 @@ +import { CustomFont } from '../model/custom-font.model'; + +/** + * Font dropdown item for epub-reader component (PrimeNG Select format) + */ +export interface FontDropdownItem { + label: string; + value: string | null; + disabled?: boolean; +} + +/** + * Font dropdown item for epub-reader-preferences component + */ +export interface FontPreferenceItem { + name: string; + displayName: string; + key: string | null; +} + +const MAX_FONT_DISPLAY_LENGTH = 12; + +/** + * Adds custom fonts to a dropdown array with a separator. + * Removes any existing separator before adding to prevent duplicates. + */ +export function addCustomFontsToDropdown( + fonts: CustomFont[], + targetArray: T[], + format: 'select' | 'preference' +): void { + if (fonts.length === 0) { + return; + } + + if (format === 'select') { + const separatorIndex = (targetArray as FontDropdownItem[]).findIndex(item => item.value === 'separator'); + if (separatorIndex !== -1) { + targetArray.splice(separatorIndex, 1); + } + + (targetArray as FontDropdownItem[]).push({ + label: '--- Custom Fonts ---', + value: 'separator', + disabled: true + }); + + fonts.forEach(font => { + (targetArray as FontDropdownItem[]).push({ + label: font.fontName, + value: `custom:${font.id}` + }); + }); + } else { + const separatorIndex = (targetArray as FontPreferenceItem[]).findIndex(item => item.key === 'separator'); + if (separatorIndex !== -1) { + targetArray.splice(separatorIndex, 1); + } + + (targetArray as FontPreferenceItem[]).push({ + name: '--- Custom Fonts ---', + displayName: '---', + key: 'separator' + }); + + fonts.forEach(font => { + (targetArray as FontPreferenceItem[]).push({ + name: font.fontName, + displayName: font.fontName.substring(0, MAX_FONT_DISPLAY_LENGTH), + key: `custom:${font.id}` + }); + }); + } +}