40 Commits

Author SHA1 Message Date
Stefan Hardegger
f92dcc5314 Advanced Filters - Build optimizations 2025-09-04 15:49:24 +02:00
Stefan Hardegger
702fcb33c1 Improvements to Editor 2025-09-02 09:28:06 +02:00
Stefan Hardegger
11b2a8b071 revert postgres version 2025-09-01 16:19:14 +02:00
Stefan Hardegger
d1289bd616 Security Updates and random improvement. 2025-09-01 16:02:19 +02:00
Stefan Hardegger
15708b5ab2 Table of Content functionality 2025-08-22 09:03:21 +02:00
Stefan Hardegger
a660056003 Various improvements 2025-08-21 13:55:38 +02:00
Stefan Hardegger
35a5825e76 Fix cover images display 2025-08-21 12:38:48 +02:00
Stefan Hardegger
87a4999ffe Fixing Database switching functionality. 2025-08-21 08:54:28 +02:00
Stefan Hardegger
4ee5fa2330 fix 2025-08-20 15:11:41 +02:00
Stefan Hardegger
6128d61349 Library Switching functionality 2025-08-20 15:10:40 +02:00
Stefan Hardegger
5e347f2e2e Incrase permitted upload size 2025-08-20 08:11:36 +02:00
Stefan Hardegger
8eb126a304 performance 2025-08-18 19:27:57 +02:00
Stefan Hardegger
3dc02420fe performance optimization in library view 2025-08-18 19:03:42 +02:00
Stefan Hardegger
241a15a174 Series auto complete 2025-08-18 14:19:14 +02:00
Stefan Hardegger
6b97c0a70f fix loop 2025-08-18 10:41:32 +02:00
Stefan Hardegger
e952241e3c fix 2025-08-18 10:32:02 +02:00
Stefan Hardegger
65f1c6edc7 fix 2025-08-18 10:16:20 +02:00
Stefan Hardegger
40fe3fdb80 Improvements, Fixes. 2025-08-18 10:04:38 +02:00
Stefan Hardegger
95ce5fb532 Bugfixes and Improvements Tag Management 2025-08-18 08:54:18 +02:00
Stefan Hardegger
1a99d9830d Tag Enhancement + bugfixes 2025-08-17 17:16:40 +02:00
Stefan Hardegger
6b83783381 Small improvements 2025-08-15 07:58:36 +02:00
Stefan Hardegger
460ec358ca New Switchable Library Layout 2025-08-14 19:46:50 +02:00
Stefan Hardegger
1d14d3d7aa Fix for Random Story Function 2025-08-14 13:14:46 +02:00
Stefan Hardegger
4357351ec8 randomized 2025-08-13 14:49:57 +02:00
Stefan Hardegger
4ab03953ae random story selector 2025-08-13 14:48:40 +02:00
Stefan Hardegger
142d8328c2 revert security config 2025-08-12 15:14:14 +02:00
Stefan Hardegger
c46108c317 various improvements and performance enhancements 2025-08-12 14:55:51 +02:00
Stefan Hardegger
75c207970d Changing Authors 2025-08-12 12:57:34 +02:00
Stefan Hardegger
3b22d155db restructuring 2025-08-11 14:40:56 +02:00
Stefan Hardegger
51e3d20c24 various fixes 2025-08-11 08:15:20 +02:00
Stefan Hardegger
5d195b63ef Fix dead links 2025-08-08 15:05:10 +02:00
Stefan Hardegger
5b3a9d183e Image Handling in Epub Import/export 2025-08-08 14:50:49 +02:00
Stefan Hardegger
379c8c170f Various improvements & Epub support 2025-08-08 14:09:14 +02:00
Stefan Hardegger
090b858a54 Bugfix 2025-07-31 13:43:23 +02:00
Stefan Hardegger
b0c14d4b37 DB Backup Bugfix 2025-07-31 08:36:33 +02:00
Stefan Hardegger
7227061d25 DB Backup Bugfix 2025-07-31 08:25:47 +02:00
Stefan Hardegger
415eab07de DB Backup Bugfix 2025-07-31 07:54:43 +02:00
Stefan Hardegger
e89331e059 DB Backup Bugfix 2025-07-31 07:46:14 +02:00
Stefan Hardegger
370bef2f07 DB Backup Bug 2025-07-31 07:38:05 +02:00
Stefan Hardegger
9e788c2018 bugfix DB Backup 2025-07-31 07:30:23 +02:00
130 changed files with 21366 additions and 1660 deletions

3
.gitignore vendored
View File

@@ -46,4 +46,5 @@ Thumbs.db
# Application data
images/
data/
data/
backend/cookies.txt

View File

@@ -0,0 +1,466 @@
# EPUB Import/Export Specification
## 🎉 Phase 1 & 2 Implementation Complete
**Status**: Both Phase 1 and Phase 2 fully implemented and operational as of August 2025
**Phase 1 Achievements**:
- ✅ Complete EPUB import functionality with validation and error handling
- ✅ Single story EPUB export with XML validation fixes
- ✅ Reading position preservation using EPUB CFI standards
- ✅ Full frontend UI integration with navigation and authentication
- ✅ Moved export button to Story Detail View for better UX
- ✅ Added EPUB import to main Add Story menu dropdown
**Phase 2 Enhancements**:
-**Enhanced Cover Processing**: Automatic extraction and optimization of cover images during EPUB import
-**Advanced Metadata Extraction**: Comprehensive extraction of subjects/tags, keywords, publisher, language, publication dates, and identifiers
-**Collection EPUB Export**: Full collection export with table of contents, proper chapter structure, and metadata aggregation
-**Image Validation**: Robust cover image processing with format detection, resizing, and storage management
-**API Endpoints**: Complete REST API for both individual story and collection EPUB operations
## Overview
This specification defines the requirements and implementation details for importing and exporting EPUB files in StoryCove. The feature enables users to import stories from EPUB files and export their stories/collections as EPUB files with preserved reading positions.
## Scope
### In Scope
- **EPUB Import**: Parse DRM-free EPUB files and import as stories
- **EPUB Export**: Export individual stories and collections as EPUB files
- **Reading Position Preservation**: Store and restore reading positions using EPUB standards
- **Metadata Handling**: Extract and preserve story metadata (title, author, cover, etc.)
- **Content Processing**: HTML content sanitization and formatting
### Out of Scope (Phase 1)
- DRM-protected EPUB files (future consideration)
- Real-time reading position sync between devices
- Advanced EPUB features (audio, video, interactive content)
- EPUB validation beyond basic structure
## Technical Architecture
### Backend Implementation
- **Language**: Java (Spring Boot)
- **Primary Library**: EPUBLib (nl.siegmann.epublib:epublib-core:3.1)
- **Processing**: Server-side generation and parsing
- **File Handling**: Multipart file upload for import, streaming download for export
### Dependencies
```xml
<dependency>
<groupId>com.positiondev.epublib</groupId>
<artifactId>epublib-core</artifactId>
<version>3.1</version>
</dependency>
```
### Phase 1 Implementation Notes
- **EPUBImportService**: Implemented with full validation, metadata extraction, and reading position handling
- **EPUBExportService**: Implemented with XML validation fixes for EPUB reader compatibility
- **ReadingPosition Entity**: Created with EPUB CFI support and database indexing
- **Authentication**: All endpoints secured with JWT authentication and proper frontend integration
- **UI Integration**: Export moved to Story Detail View, Import added to main navigation menu
- **XML Compliance**: Fixed XHTML validation issues by properly formatting self-closing tags (`<br>``<br />`)
## EPUB Import Specification
### Supported Formats
- **EPUB 2.0** and **EPUB 3.x** formats
- **DRM-Free** files only
- **Maximum file size**: 50MB
- **Supported content**: Text-based stories with HTML content
### Import Process Flow
1. **File Upload**: User uploads EPUB file via web interface
2. **Validation**: Check file format, size, and basic EPUB structure
3. **Parsing**: Extract metadata, content, and resources using EPUBLib
4. **Content Processing**: Sanitize HTML content using existing Jsoup pipeline
5. **Story Creation**: Create Story entity with extracted data
6. **Preview**: Show extracted story details for user confirmation
7. **Finalization**: Save story to database with imported metadata
### Metadata Mapping
```java
// EPUB Metadata → StoryCove Story Entity
epub.getMetadata().getFirstTitle() story.title
epub.getMetadata().getAuthors().get(0) story.authorName
epub.getMetadata().getDescriptions().get(0) story.summary
epub.getCoverImage() story.coverPath
epub.getMetadata().getSubjects() story.tags
```
### Content Extraction
- **Multi-chapter EPUBs**: Combine all content files into single HTML
- **Chapter separation**: Insert `<hr>` or `<h2>` tags between chapters
- **HTML sanitization**: Apply existing sanitization rules
- **Image handling**: Extract and store cover images, inline images optional
### API Endpoints
#### POST /api/stories/import-epub
```java
@PostMapping("/import-epub")
public ResponseEntity<?> importEPUB(@RequestParam("file") MultipartFile file) {
// Implementation in EPUBImportService
}
```
**Request**: Multipart file upload
**Response**:
```json
{
"message": "EPUB imported successfully",
"storyId": "uuid",
"extractedData": {
"title": "Story Title",
"author": "Author Name",
"summary": "Story description",
"chapterCount": 12,
"wordCount": 45000,
"hasCovers": true
}
}
```
## EPUB Export Specification
### Export Types
1. **Single Story Export**: Convert one story to EPUB
2. **Collection Export**: Multiple stories as single EPUB with chapters
### EPUB Structure Generation
```
story.epub
├── mimetype
├── META-INF/
│ └── container.xml
└── OEBPS/
├── content.opf # Package metadata
├── toc.ncx # Navigation
├── stylesheet.css # Styling
├── cover.html # Cover page
├── chapter001.xhtml # Story content
├── images/
│ └── cover.jpg # Cover image
└── fonts/ (optional)
```
### Reading Position Implementation
#### EPUB 3 CFI (Canonical Fragment Identifier)
```xml
<!-- In content.opf metadata -->
<meta property="epub-cfi" content="/6/4[chap01]!/4[body01]/10[para05]/3:142"/>
<meta property="reading-percentage" content="0.65"/>
<meta property="last-read-timestamp" content="2023-12-07T10:30:00Z"/>
```
#### StoryCove Custom Metadata (Fallback)
```xml
<meta name="storycove:reading-chapter" content="3"/>
<meta name="storycove:reading-paragraph" content="15"/>
<meta name="storycove:reading-offset" content="142"/>
<meta name="storycove:reading-percentage" content="0.65"/>
```
#### CFI Generation Logic
```java
public String generateCFI(ReadingPosition position) {
return String.format("/6/%d[chap%02d]!/4[body01]/%d[para%02d]/3:%d",
(position.getChapterIndex() * 2) + 4,
position.getChapterIndex(),
(position.getParagraphIndex() * 2) + 4,
position.getParagraphIndex(),
position.getCharacterOffset());
}
```
### API Endpoints
#### GET /api/stories/{id}/export-epub
```java
@GetMapping("/{id}/export-epub")
public ResponseEntity<StreamingResponseBody> exportStory(@PathVariable UUID id) {
// Implementation in EPUBExportService
}
```
**Response**: EPUB file download with headers:
```
Content-Type: application/epub+zip
Content-Disposition: attachment; filename="story-title.epub"
```
#### GET /api/collections/{id}/export-epub
```java
@GetMapping("/{id}/export-epub")
public ResponseEntity<StreamingResponseBody> exportCollection(@PathVariable UUID id) {
// Implementation in EPUBExportService
}
```
**Response**: Multi-story EPUB with table of contents
## Data Models
### ReadingPosition Entity
```java
@Entity
@Table(name = "reading_positions")
public class ReadingPosition {
@Id
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "story_id")
private Story story;
@Column(name = "chapter_index")
private Integer chapterIndex = 0;
@Column(name = "paragraph_index")
private Integer paragraphIndex = 0;
@Column(name = "character_offset")
private Integer characterOffset = 0;
@Column(name = "progress_percentage")
private Double progressPercentage = 0.0;
@Column(name = "epub_cfi")
private String canonicalFragmentIdentifier;
@Column(name = "last_read_at")
private LocalDateTime lastReadAt;
@Column(name = "device_identifier")
private String deviceIdentifier;
// Constructors, getters, setters
}
```
### EPUB Import Request DTO
```java
public class EPUBImportRequest {
private String filename;
private Long fileSize;
private Boolean preserveChapterStructure = true;
private Boolean extractCover = true;
private String targetCollectionId; // Optional: add to specific collection
}
```
### EPUB Export Options DTO
```java
public class EPUBExportOptions {
private Boolean includeReadingPosition = true;
private Boolean includeCoverImage = true;
private Boolean includeMetadata = true;
private String cssStylesheet; // Optional custom CSS
private EPUBVersion version = EPUBVersion.EPUB3;
}
```
## Service Layer Architecture
### EPUBImportService
```java
@Service
public class EPUBImportService {
// Core import method
public Story importEPUBFile(MultipartFile file, EPUBImportRequest request);
// Helper methods
private void validateEPUBFile(MultipartFile file);
private Book parseEPUBStructure(InputStream inputStream);
private Story extractStoryData(Book epub);
private String combineChapterContent(Book epub);
private void extractAndSaveCover(Book epub, Story story);
private List<String> extractTags(Book epub);
private ReadingPosition extractReadingPosition(Book epub);
}
```
### EPUBExportService
```java
@Service
public class EPUBExportService {
// Core export methods
public byte[] exportSingleStory(UUID storyId, EPUBExportOptions options);
public byte[] exportCollection(UUID collectionId, EPUBExportOptions options);
// Helper methods
private Book createEPUBStructure(Story story, ReadingPosition position);
private Book createCollectionEPUB(Collection collection, List<ReadingPosition> positions);
private void addReadingPositionMetadata(Book book, ReadingPosition position);
private String generateCFI(ReadingPosition position);
private Resource createChapterResource(Story story);
private Resource createStylesheetResource();
private void addCoverImage(Book book, Story story);
}
```
## Frontend Integration
### Import UI Flow
1. **Upload Interface**: File input with EPUB validation
2. **Progress Indicator**: Show parsing progress
3. **Preview Screen**: Display extracted metadata for confirmation
4. **Confirmation**: Allow editing of title, author, summary before saving
5. **Success**: Redirect to created story
### Export UI Flow
1. **Export Button**: Available on story detail and collection pages
2. **Options Modal**: Allow selection of export options
3. **Progress Indicator**: Show EPUB generation progress
4. **Download**: Automatic file download on completion
### Frontend API Calls
```typescript
// Import EPUB
const importEPUB = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/api/stories/import-epub', {
method: 'POST',
body: formData,
});
return await response.json();
};
// Export Story
const exportStoryEPUB = async (storyId: string) => {
const response = await fetch(`/api/stories/${storyId}/export-epub`, {
method: 'GET',
});
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${storyTitle}.epub`;
a.click();
};
```
## Error Handling
### Import Errors
- **Invalid EPUB format**: "Invalid EPUB file format"
- **File too large**: "File size exceeds 50MB limit"
- **DRM protected**: "DRM-protected EPUBs not supported"
- **Corrupted file**: "EPUB file appears to be corrupted"
- **No content**: "EPUB contains no readable content"
### Export Errors
- **Story not found**: "Story not found or access denied"
- **Missing content**: "Story has no content to export"
- **Generation failure**: "Failed to generate EPUB file"
## Security Considerations
### File Upload Security
- **File type validation**: Verify EPUB MIME type and structure
- **Size limits**: Enforce maximum file size limits
- **Content sanitization**: Apply existing HTML sanitization
- **Virus scanning**: Consider integration with antivirus scanning
### Content Security
- **HTML sanitization**: Apply existing Jsoup rules to imported content
- **Image validation**: Validate extracted cover images
- **Metadata escaping**: Escape special characters in metadata
## Testing Strategy
### Unit Tests
- EPUB parsing and validation logic
- CFI generation and parsing
- Metadata extraction accuracy
- Content sanitization
### Integration Tests
- End-to-end import/export workflow
- Reading position preservation
- Multi-story collection export
- Error handling scenarios
### Test Data
- Sample EPUB files for various scenarios
- EPUBs with and without reading positions
- Multi-chapter EPUBs
- EPUBs with covers and metadata
## Performance Considerations
### Import Performance
- **Streaming processing**: Process large EPUBs without loading entirely into memory
- **Async processing**: Consider async import for large files
- **Progress tracking**: Provide progress feedback for large imports
### Export Performance
- **Caching**: Cache generated EPUBs for repeated exports
- **Streaming**: Stream EPUB generation for large collections
- **Resource optimization**: Optimize image and content sizes
## Future Enhancements (Out of Scope)
### Phase 2 Considerations
- **DRM support**: Research legal and technical feasibility
- **Reading position sync**: Real-time sync across devices
- **Advanced EPUB features**: Enhanced typography, annotations
- **Bulk operations**: Import/export multiple EPUBs
- **EPUB validation**: Full EPUB compliance checking
### Integration Possibilities
- **Cloud storage**: Export directly to Google Drive, Dropbox
- **E-reader sync**: Direct sync with Kindle, Kobo devices
- **Reading analytics**: Track reading patterns and statistics
## Implementation Phases
### Phase 1: Core Functionality ✅ **COMPLETED**
- [x] Basic EPUB import (DRM-free)
- [x] Single story export
- [x] Reading position storage and retrieval
- [x] Frontend UI integration
### Phase 2: Enhanced Features ✅ **COMPLETED**
- [x] Collection export with table of contents
- [x] Advanced metadata handling (subjects, keywords, publisher, language, etc.)
- [x] Enhanced cover image processing for import/export
- [x] Comprehensive error handling
### Phase 3: Advanced Features
- [ ] DRM exploration (legal research required)
- [ ] Reading position sync
- [ ] Advanced EPUB features
- [ ] Analytics and reporting
## Acceptance Criteria
### Import Success Criteria ✅ **COMPLETED**
- [x] Successfully parse EPUB 2.0 and 3.x files
- [x] Extract title, author, summary, and content accurately
- [x] Preserve formatting and basic HTML structure
- [x] Handle cover images correctly
- [x] Import reading positions when present
- [x] Provide clear error messages for invalid files
### Export Success Criteria ✅ **FULLY COMPLETED**
- [x] Generate valid EPUB files compatible with major readers
- [x] Include accurate metadata and content
- [x] Embed reading positions using CFI standard
- [x] Support single story export
- [x] Support collection export with proper structure
- [x] Generate proper table of contents for collections
- [x] Include cover images when available
---
*This specification serves as the implementation guide for the EPUB import/export feature. All implementation decisions should reference this document for consistency and completeness.*

122
README.md
View File

@@ -161,43 +161,75 @@ cd backend
## 📖 Documentation
- **[API Documentation](docs/API.md)**: Complete REST API reference with examples
- **[Data Model](docs/DATA_MODEL.md)**: Detailed database schema and relationships
- **[Technical Specification](storycove-spec.md)**: Comprehensive technical specification
- **[Technical Specification](storycove-spec.md)**: Complete technical specification with API documentation, data models, and all feature specifications
- **[Web Scraper Specification](storycove-scraper-spec.md)**: URL content grabbing functionality
- **Environment Configuration**: Multi-environment deployment setup (see above)
- **Development Setup**: Local development environment setup (see below)
> **Note**: All feature specifications (Collections, Tag Enhancements, EPUB Import/Export) have been consolidated into the main technical specification for easier maintenance and reference.
## 🗄️ Data Model
StoryCove uses a PostgreSQL database with the following core entities:
### **Stories**
- **Primary Key**: UUID
- **Fields**: title, summary, description, content_html, content_plain, source_url, word_count, rating, volume, cover_path, reading_position, last_read_at
- **Relationships**: Many-to-One with Author, Many-to-One with Series, Many-to-Many with Tags
- **Features**: Automatic word count calculation, HTML sanitization, plain text extraction, reading progress tracking
- **Fields**: title, summary, description, content_html, content_plain, source_url, word_count, rating, volume, cover_path, is_read, reading_position, last_read_at, created_at, updated_at
- **Relationships**: Many-to-One with Author, Many-to-One with Series, Many-to-Many with Tags, One-to-Many with ReadingPositions
- **Features**: Automatic word count calculation, HTML sanitization, plain text extraction, reading progress tracking, duplicate detection
### **Authors**
- **Primary Key**: UUID
- **Fields**: name, notes, author_rating, avatar_image_path
- **Relationships**: One-to-Many with Stories, One-to-Many with Author URLs
- **Features**: URL collection storage, rating system, statistics calculation
- **Fields**: name, notes, author_rating, avatar_image_path, created_at, updated_at
- **Relationships**: One-to-Many with Stories, One-to-Many with Author URLs (via @ElementCollection)
- **Features**: URL collection storage, rating system, statistics calculation, average story rating calculation
### **Collections**
- **Primary Key**: UUID
- **Fields**: name, description, rating, cover_image_path, is_archived, created_at, updated_at
- **Relationships**: Many-to-Many with Tags, One-to-Many with CollectionStories
- **Features**: Story ordering with gap-based positioning, statistics calculation, EPUB export, Typesense search
### **CollectionStories** (Junction Table)
- **Composite Key**: collection_id, story_id
- **Fields**: position, added_at
- **Relationships**: Links Collections to Stories with ordering
- **Features**: Gap-based positioning for efficient reordering
### **Series**
- **Primary Key**: UUID
- **Fields**: name, description
- **Fields**: name, description, created_at
- **Relationships**: One-to-Many with Stories (ordered by volume)
- **Features**: Volume-based story ordering, navigation methods
- **Features**: Volume-based story ordering, navigation methods (next/previous story)
### **Tags**
- **Primary Key**: UUID
- **Fields**: name (unique)
- **Relationships**: Many-to-Many with Stories
- **Features**: Autocomplete support, usage statistics
- **Fields**: name (unique), color (hex), description, created_at
- **Relationships**: Many-to-Many with Stories, Many-to-Many with Collections, One-to-Many with TagAliases
- **Features**: Color coding, alias system, autocomplete support, usage statistics, AI-powered suggestions
### **Join Tables**
- **story_tags**: Links stories to tags
- **author_urls**: Stores multiple URLs per author
### **TagAliases**
- **Primary Key**: UUID
- **Fields**: alias_name (unique), canonical_tag_id, created_from_merge, created_at
- **Relationships**: Many-to-One with Tag (canonical)
- **Features**: Transparent alias resolution, merge tracking, autocomplete integration
### **ReadingPositions**
- **Primary Key**: UUID
- **Fields**: story_id, chapter_index, chapter_title, word_position, character_position, percentage_complete, epub_cfi, context_before, context_after, created_at, updated_at
- **Relationships**: Many-to-One with Story
- **Features**: Advanced reading position tracking, EPUB CFI support, context preservation, percentage calculation
### **Libraries**
- **Primary Key**: UUID
- **Fields**: name, description, is_default, created_at, updated_at
- **Features**: Multi-library support, library switching functionality
### **Core Join Tables**
- **story_tags**: Links stories to tags (Many-to-Many)
- **collection_tags**: Links collections to tags (Many-to-Many)
- **collection_stories**: Links collections to stories with ordering
- **author_urls**: Stores multiple URLs per author (@ElementCollection)
## 🔌 REST API Reference
@@ -209,6 +241,7 @@ StoryCove uses a PostgreSQL database with the following core entities:
### **Stories** (`/api/stories`)
- `GET /` - List stories (paginated)
- `GET /{id}` - Get specific story
- `GET /{id}/read` - Get story for reading interface
- `POST /` - Create new story
- `PUT /{id}` - Update story
- `DELETE /{id}` - Delete story
@@ -218,6 +251,10 @@ StoryCove uses a PostgreSQL database with the following core entities:
- `POST /{id}/tags/{tagId}` - Add tag to story
- `DELETE /{id}/tags/{tagId}` - Remove tag from story
- `POST /{id}/reading-progress` - Update reading position
- `POST /{id}/reading-status` - Mark story as read/unread
- `GET /{id}/collections` - Get collections containing story
- `GET /random` - Get random story with optional filters
- `GET /check-duplicate` - Check for duplicate stories
- `GET /search` - Search stories (Typesense with faceting)
- `GET /search/suggestions` - Get search suggestions
- `GET /author/{authorId}` - Stories by author
@@ -225,6 +262,16 @@ StoryCove uses a PostgreSQL database with the following core entities:
- `GET /tags/{tagName}` - Stories with tag
- `GET /recent` - Recent stories
- `GET /top-rated` - Top-rated stories
- `POST /batch/add-to-collection` - Add multiple stories to collection
- `POST /reindex` - Manual Typesense reindex
- `POST /reindex-typesense` - Reindex stories in Typesense
- `POST /recreate-typesense-collection` - Recreate Typesense collection
#### **EPUB Import/Export** (`/api/stories/epub`)
- `POST /import` - Import story from EPUB file
- `POST /export` - Export story as EPUB with options
- `GET /{id}/epub` - Export story as EPUB (simple)
- `POST /validate` - Validate EPUB file structure
### **Authors** (`/api/authors`)
- `GET /` - List authors (paginated)
@@ -244,14 +291,49 @@ StoryCove uses a PostgreSQL database with the following core entities:
### **Tags** (`/api/tags`)
- `GET /` - List tags (paginated)
- `GET /{id}` - Get specific tag
- `POST /` - Create new tag
- `PUT /{id}` - Update tag
- `POST /` - Create new tag (with color and description)
- `PUT /{id}` - Update tag (name, color, description)
- `DELETE /{id}` - Delete tag
- `GET /search` - Search tags
- `GET /autocomplete` - Tag autocomplete
- `GET /autocomplete` - Tag autocomplete with alias resolution
- `GET /popular` - Most used tags
- `GET /unused` - Unused tags
- `GET /stats` - Tag statistics
- `GET /collections` - Tags used by collections
- `GET /resolve/{name}` - Resolve tag name (handles aliases)
#### **Tag Aliases** (`/api/tags/{tagId}/aliases`)
- `POST /` - Add alias to tag
- `DELETE /{aliasId}` - Remove alias from tag
#### **Tag Management**
- `POST /merge` - Merge multiple tags into one
- `POST /merge/preview` - Preview tag merge operation
- `POST /suggest` - AI-powered tag suggestions for content
### **Collections** (`/api/collections`)
- `GET /` - Search and list collections (Typesense)
- `GET /{id}` - Get collection details
- `POST /` - Create new collection (JSON or multipart)
- `PUT /{id}` - Update collection metadata
- `DELETE /{id}` - Delete collection
- `PUT /{id}/archive` - Archive/unarchive collection
- `POST /{id}/cover` - Upload collection cover image
- `DELETE /{id}/cover` - Remove collection cover image
- `GET /{id}/stats` - Get collection statistics
#### **Collection Story Management**
- `POST /{id}/stories` - Add stories to collection
- `DELETE /{id}/stories/{storyId}` - Remove story from collection
- `PUT /{id}/stories/order` - Reorder stories in collection
- `GET /{id}/read/{storyId}` - Get story with collection context
#### **Collection EPUB Export**
- `GET /{id}/epub` - Export collection as EPUB
- `POST /{id}/epub` - Export collection as EPUB with options
#### **Collection Management**
- `POST /reindex-typesense` - Reindex collections in Typesense
### **Series** (`/api/series`)
- `GET /` - List series (paginated)

View File

@@ -0,0 +1,305 @@
# Tag Enhancement Specification
> **✅ Implementation Status: COMPLETED**
> This feature has been fully implemented and is available in the system.
> All tag enhancements including colors, aliases, merging, and AI suggestions are working.
> Last updated: January 2025
## Overview
This document outlines the comprehensive enhancement of the tagging functionality in StoryCove, including color tags, tag deletion, merging, and aliases. These features will be accessible through a new "Tag Maintenance" page linked from the Settings page.
## Features
### 1. Color Tags
**Purpose**: Assign optional colors to tags for visual distinction and better organization.
**Implementation Details**:
- **Color Selection**: Predefined color palette that complements the app's theme
- **Custom Colors**: Fallback option with full color picker for advanced users
- **Default Behavior**: Tags without colors use consistent default styling
- **Accessibility**: All colors ensure sufficient contrast ratios
**UI Design**:
```
Color Selection Interface:
[Theme Blue] [Theme Green] [Theme Purple] [Theme Orange] ... [Custom ▼]
```
**Database Changes**:
```sql
ALTER TABLE tags ADD COLUMN color VARCHAR(7); -- hex colors like #3B82F6
ALTER TABLE tags ADD COLUMN description TEXT;
```
### 2. Tag Deletion
**Purpose**: Remove unused or unwanted tags from the system.
**Safety Features**:
- Show impact: "This tag is used by X stories"
- Confirmation dialog with story count
- Option to reassign stories to different tag before deletion
- Simple workflow appropriate for single-user application
**Behavior**:
- Display number of affected stories
- Require confirmation for deletion
- Optionally allow reassignment to another tag
### 3. Tag Merging
**Purpose**: Combine similar tags into a single canonical tag to reduce duplication.
**Workflow**:
1. User selects multiple tags to merge
2. User chooses which tag name becomes canonical
3. System shows merge preview with story counts
4. All story associations transfer to canonical tag
5. **Automatic Aliasing**: Merged tags automatically become aliases
**Example**:
```
Merge Preview:
• "magictf" (5 stories) → "magic tf" (12 stories)
• Result: "magic tf" (17 stories)
• "magictf" will become an alias for "magic tf"
```
**Technical Implementation**:
```sql
-- Merge operation (atomic transaction)
BEGIN TRANSACTION;
UPDATE story_tags SET tag_id = target_tag_id WHERE tag_id = source_tag_id;
INSERT INTO tag_aliases (alias_name, canonical_tag_id, created_from_merge)
VALUES (source_tag_name, target_tag_id, TRUE);
DELETE FROM tags WHERE id = source_tag_id;
COMMIT;
```
### 4. Tag Aliases
**Purpose**: Prevent tag duplication by allowing alternative names that resolve to canonical tags.
**Key Features**:
- **Transparent Resolution**: Users type "magictf" and automatically get "magic tf"
- **Hover Display**: Show aliases when hovering over tags
- **Import Integration**: Automatic alias resolution during story imports
- **Auto-Generation**: Created automatically during tag merges
**Database Schema**:
```sql
CREATE TABLE tag_aliases (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
alias_name VARCHAR(255) UNIQUE NOT NULL,
canonical_tag_id UUID NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_from_merge BOOLEAN DEFAULT FALSE
);
CREATE INDEX idx_tag_aliases_name ON tag_aliases(alias_name);
```
**UI Behavior**:
- Tags with aliases show subtle indicator (e.g., small "+" icon)
- Hover tooltip displays:
```
magic tf
────────────
Aliases: magictf, magic_tf, magic-transformation
```
## Tag Maintenance Page
### Access
- Reachable only through Settings page
- Button: "Tag Maintenance" or "Manage Tags"
### Main Interface
**Tag Management Table**:
```
┌─ Search: [____________] [Color Filter ▼] [Sort: Usage ▼]
├─
├─ ☐ magic tf 🔵 (17 stories) [+2 aliases] [Edit] [Delete]
├─ ☐ transformation 🟢 (34 stories) [+1 alias] [Edit] [Delete]
├─ ☐ sci-fi 🟣 (45 stories) [Edit] [Delete]
└─
[Merge Selected] [Bulk Delete] [Export/Import Tags]
```
**Features**:
- Searchable and filterable tag list
- Sortable by name, usage count, creation date
- Bulk selection for merge/delete operations
- Visual indicators for color and alias count
### Tag Edit Modal
```
Edit Tag: "magic tf"
┌─ Name: [magic tf ]
├─ Color: [🔵] [Theme Colors...] [Custom...]
├─ Description: [Optional description]
├─
├─ Aliases (2):
│ • magictf [Remove]
│ • magic_tf [Remove]
│ [Add Alias: ____________] [Add]
├─
├─ Used by 17 stories [View Stories]
└─ [Save] [Cancel]
```
**Functionality**:
- Edit tag name, color, and description
- Manage aliases (add/remove)
- View associated stories
- Prevent circular alias references
### Merge Interface
**Selection Process**:
1. Select multiple tags from main table
2. Click "Merge Selected"
3. Choose canonical tag name
4. Preview merge results
5. Confirm operation
**Preview Display**:
- Show before/after story counts
- List all aliases that will be created
- Highlight any conflicts or issues
## Integration Points
### 1. Import/Scraping Enhancement
```javascript
// Tag resolution during imports
const resolveTagName = async (inputTag) => {
const alias = await tagApi.findAlias(inputTag);
return alias ? alias.canonicalTag : inputTag;
};
```
### 2. Tag Input Components
**Enhanced Autocomplete**:
- Include both canonical names and aliases in suggestions
- Show resolution: "magictf → magic tf" in dropdown
- Always save canonical name to database
### 3. Search Functionality
**Transparent Alias Search**:
- Search for "magictf" includes stories tagged with "magic tf"
- User doesn't need to know about canonical/alias distinction
- Expand search queries to include all aliases
### 4. Display Components
**Tag Rendering**:
- Apply colors consistently across all tag displays
- Show alias indicator where appropriate
- Implement hover tooltips for alias information
## Implementation Phases
### Phase 1: Core Infrastructure
- [ ] Database schema updates (tags.color, tag_aliases table)
- [ ] Basic tag editing functionality (name, color, description)
- [ ] Color palette component with theme colors
- [ ] Tag edit modal interface
### Phase 2: Merging & Aliasing
- [ ] Tag merge functionality with automatic alias creation
- [ ] Alias resolution in import/scraping logic
- [ ] Tag input component enhancements
- [ ] Search integration with alias expansion
### Phase 3: UI Polish & Advanced Features
- [ ] Hover tooltips for alias display
- [ ] Bulk operations (merge multiple, bulk delete)
- [ ] Advanced filtering and sorting options
- [ ] Tag maintenance page integration with Settings
### Phase 4: Smart Features (Optional)
- [ ] Auto-merge suggestions for similar tag names
- [ ] Color auto-assignment based on usage patterns
- [ ] Import intelligence and learning from user decisions
## Technical Considerations
### Performance
- Index alias names for fast lookup during imports
- Optimize tag queries with proper database indexing
- Consider caching for frequently accessed tag/alias mappings
### Data Integrity
- Prevent circular alias references
- Atomic transactions for merge operations
- Cascade deletion handling for tag relationships
### User Experience
- Clear visual feedback for all operations
- Comprehensive preview before destructive actions
- Consistent color and styling across the application
### Accessibility
- Sufficient color contrast for all tag colors
- Keyboard navigation support
- Screen reader compatibility
- Don't rely solely on color for information
## API Endpoints
### New Endpoints Needed
- `GET /api/tags/{id}/aliases` - Get aliases for a tag
- `POST /api/tags/merge` - Merge multiple tags
- `POST /api/tags/{id}/aliases` - Add alias to tag
- `DELETE /api/tags/{id}/aliases/{aliasId}` - Remove alias
- `PUT /api/tags/{id}/color` - Update tag color
- `GET /api/tags/resolve/{name}` - Resolve tag name (check aliases)
### Enhanced Endpoints
- `GET /api/tags` - Include color and alias count in response
- `PUT /api/tags/{id}` - Support color and description updates
- `DELETE /api/tags/{id}` - Enhanced with story impact information
## Configuration
### Theme Color Palette
Define a curated set of colors that work well with both light and dark themes:
- Primary blues: #3B82F6, #1D4ED8, #60A5FA
- Greens: #10B981, #059669, #34D399
- Purples: #8B5CF6, #7C3AED, #A78BFA
- Warm tones: #F59E0B, #D97706, #F97316
- Neutrals: #6B7280, #4B5563, #9CA3AF
### Settings Integration
- Add "Tag Maintenance" button to Settings page
- Consider adding tag-related preferences (default colors, etc.)
## Success Criteria
1. **Color Tags**: Tags can be assigned colors that display consistently throughout the application
2. **Tag Deletion**: Users can safely delete tags with appropriate warnings and reassignment options
3. **Tag Merging**: Similar tags can be merged with automatic alias creation
4. **Alias Resolution**: Imports automatically resolve aliases to canonical tags
5. **User Experience**: All operations are intuitive with clear feedback and preview options
6. **Performance**: Tag operations remain fast even with large numbers of tags and aliases
7. **Data Integrity**: No orphaned references or circular alias chains
## Future Enhancements
- **Tag Statistics**: Usage analytics and trends
- **Tag Recommendations**: AI-powered tag suggestions during story import
- **Tag Templates**: Predefined tag sets for common story types
- **Export/Import**: Backup and restore tag configurations
- **Tag Validation**: Rules for tag naming conventions
---
*This specification serves as the definitive guide for implementing the tag enhancement features in StoryCove. All implementation should refer back to this document to ensure consistency and completeness.*

View File

@@ -2,15 +2,15 @@ FROM openjdk:17-jdk-slim
WORKDIR /app
COPY pom.xml .
COPY src ./src
# Install Maven
RUN apt-get update && apt-get install -y maven && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y maven && \
mvn clean package -DskipTests && \
apt-get remove -y maven && \
apt-get autoremove -y && \
rm -rf /var/lib/apt/lists/*
# Copy source code
COPY . .
# Build the application
RUN mvn clean package -DskipTests
EXPOSE 8080
CMD ["java", "-jar", "target/storycove-backend-0.0.1-SNAPSHOT.jar"]
ENTRYPOINT ["java", "-jar", "target/storycove-backend-0.0.1-SNAPSHOT.jar"]

4
backend/cookies_new.txt Normal file
View File

@@ -0,0 +1,4 @@
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

View File

@@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
<version>3.5.5</version>
<relativePath/>
</parent>
@@ -17,7 +17,7 @@
<properties>
<java.version>17</java.version>
<testcontainers.version>1.19.3</testcontainers.version>
<testcontainers.version>1.21.3</testcontainers.version>
</properties>
<dependencyManagement>
@@ -56,18 +56,18 @@
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
<version>0.13.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.3</version>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
@@ -84,6 +84,11 @@
<artifactId>typesense-java</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.positiondev.epublib</groupId>
<artifactId>epublib-core</artifactId>
<version>3.1</version>
</dependency>
<!-- Test dependencies -->
<dependency>

View File

@@ -0,0 +1,64 @@
package com.storycove.config;
import com.storycove.service.LibraryService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* Database configuration that sets up library-aware datasource routing.
*
* This configuration replaces the default Spring Boot datasource with a routing
* datasource that automatically directs all database operations to the appropriate
* library-specific database based on the current active library.
*/
@Configuration
public class DatabaseConfig {
@Value("${spring.datasource.url}")
private String baseDbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.password}")
private String dbPassword;
/**
* Create a fallback datasource for when no library is active.
* This connects to the main database specified in application.yml.
*/
@Bean(name = "fallbackDataSource")
public DataSource fallbackDataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(baseDbUrl);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(10);
config.setConnectionTimeout(30000);
return new HikariDataSource(config);
}
/**
* Primary datasource bean - uses smart routing that excludes authentication operations
*/
@Bean(name = "dataSource")
@Primary
@DependsOn("libraryService")
public DataSource primaryDataSource(LibraryService libraryService) {
SmartRoutingDataSource routingDataSource = new SmartRoutingDataSource(
libraryService, baseDbUrl, dbUsername, dbPassword);
routingDataSource.setDefaultTargetDataSource(fallbackDataSource());
routingDataSource.setTargetDataSources(new java.util.HashMap<>());
return routingDataSource;
}
}

View File

@@ -0,0 +1,65 @@
package com.storycove.config;
import com.storycove.service.LibraryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Custom DataSource router that dynamically routes database calls to the appropriate
* library-specific datasource based on the current active library.
*
* This makes ALL Spring Data JPA repositories automatically library-aware without
* requiring changes to existing repository or service code.
*/
public class LibraryAwareDataSource extends AbstractRoutingDataSource {
private static final Logger logger = LoggerFactory.getLogger(LibraryAwareDataSource.class);
private final LibraryService libraryService;
public LibraryAwareDataSource(LibraryService libraryService) {
this.libraryService = libraryService;
// Set empty target datasources to satisfy AbstractRoutingDataSource requirements
// We override determineTargetDataSource() so this won't be used
setTargetDataSources(new java.util.HashMap<>());
}
@Override
protected Object determineCurrentLookupKey() {
String currentLibraryId = libraryService.getCurrentLibraryId();
logger.debug("Routing database call to library: {}", currentLibraryId);
return currentLibraryId;
}
@Override
protected javax.sql.DataSource determineTargetDataSource() {
try {
// Check if LibraryService is properly initialized
if (libraryService == null) {
logger.debug("LibraryService not available, using default datasource");
return getResolvedDefaultDataSource();
}
// Check if any library is currently active
String currentLibraryId = libraryService.getCurrentLibraryId();
if (currentLibraryId == null) {
logger.debug("No active library, using default datasource");
return getResolvedDefaultDataSource();
}
// Try to get the current library datasource
javax.sql.DataSource libraryDataSource = libraryService.getCurrentDataSource();
logger.debug("Successfully routing database call to library: {}", currentLibraryId);
return libraryDataSource;
} catch (IllegalStateException e) {
// This is expected during authentication, startup, or when no library is active
logger.debug("No active library (IllegalStateException) - using default datasource: {}", e.getMessage());
return getResolvedDefaultDataSource();
} catch (Exception e) {
logger.warn("Unexpected error determining target datasource, falling back to default: {}", e.getMessage(), e);
return getResolvedDefaultDataSource();
}
}
}

View File

@@ -0,0 +1,158 @@
package com.storycove.config;
import com.storycove.service.LibraryService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Smart routing datasource that:
* 1. Routes to library-specific databases when a library is active
* 2. Excludes authentication operations (keeps them on default database)
* 3. Uses request context to determine when routing is appropriate
*/
public class SmartRoutingDataSource extends AbstractRoutingDataSource {
private static final Logger logger = LoggerFactory.getLogger(SmartRoutingDataSource.class);
private final LibraryService libraryService;
private final Map<String, DataSource> libraryDataSources = new ConcurrentHashMap<>();
// Database connection details - will be injected via constructor
private final String baseDbUrl;
private final String dbUsername;
private final String dbPassword;
public SmartRoutingDataSource(LibraryService libraryService, String baseDbUrl, String dbUsername, String dbPassword) {
this.libraryService = libraryService;
this.baseDbUrl = baseDbUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
logger.info("SmartRoutingDataSource initialized with database: {}", baseDbUrl);
}
@Override
protected Object determineCurrentLookupKey() {
try {
// Check if this is an authentication request - if so, use default database
if (isAuthenticationRequest()) {
logger.debug("Authentication request detected, using default database");
return null; // null means use default datasource
}
// Check if we have an active library
if (libraryService != null) {
String currentLibraryId = libraryService.getCurrentLibraryId();
if (currentLibraryId != null && !currentLibraryId.trim().isEmpty()) {
logger.info("ROUTING: Directing to library-specific database: {}", currentLibraryId);
return currentLibraryId;
} else {
logger.info("ROUTING: No active library, using default database");
}
} else {
logger.info("ROUTING: LibraryService is null, using default database");
}
} catch (Exception e) {
logger.debug("Error determining lookup key, falling back to default database", e);
}
return null; // Use default datasource
}
/**
* Check if the current request is an authentication request that should use the default database
*/
private boolean isAuthenticationRequest() {
try {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
String requestURI = attributes.getRequest().getRequestURI();
String method = attributes.getRequest().getMethod();
// Authentication endpoints that should use default database
if (requestURI.contains("/auth/") ||
requestURI.contains("/login") ||
requestURI.contains("/api/libraries/switch") ||
(requestURI.contains("/api/libraries") && "POST".equals(method))) {
return true;
}
}
} catch (Exception e) {
logger.debug("Could not determine request context", e);
}
return false;
}
@Override
protected DataSource determineTargetDataSource() {
Object lookupKey = determineCurrentLookupKey();
if (lookupKey != null) {
String libraryId = (String) lookupKey;
return getLibraryDataSource(libraryId);
}
return getDefaultDataSource();
}
/**
* Get or create a datasource for the specified library
*/
private DataSource getLibraryDataSource(String libraryId) {
return libraryDataSources.computeIfAbsent(libraryId, id -> {
try {
HikariConfig config = new HikariConfig();
// Replace database name in URL with library-specific name
String libraryUrl = baseDbUrl.replaceAll("/[^/]*$", "/" + "storycove_" + id);
config.setJdbcUrl(libraryUrl);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(5); // Smaller pool for library-specific databases
config.setConnectionTimeout(10000);
config.setMaxLifetime(600000); // 10 minutes
logger.info("Created new datasource for library: {} -> {}", id, libraryUrl);
return new HikariDataSource(config);
} catch (Exception e) {
logger.error("Failed to create datasource for library: {}", id, e);
return getDefaultDataSource();
}
});
}
private DataSource getDefaultDataSource() {
// Use the default target datasource that was set in the configuration
try {
return (DataSource) super.determineTargetDataSource();
} catch (Exception e) {
logger.debug("Could not get default datasource via super method", e);
}
// Fallback: create a basic datasource
logger.warn("No default datasource available, creating fallback");
HikariConfig config = new HikariConfig();
config.setJdbcUrl(baseDbUrl);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(10);
config.setConnectionTimeout(30000);
return new HikariDataSource(config);
}
}

View File

@@ -1,5 +1,6 @@
package com.storycove.controller;
import com.storycove.service.LibraryService;
import com.storycove.service.PasswordAuthenticationService;
import com.storycove.util.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
@@ -18,18 +19,21 @@ import java.time.Duration;
public class AuthController {
private final PasswordAuthenticationService passwordService;
private final LibraryService libraryService;
private final JwtUtil jwtUtil;
public AuthController(PasswordAuthenticationService passwordService, JwtUtil jwtUtil) {
public AuthController(PasswordAuthenticationService passwordService, LibraryService libraryService, JwtUtil jwtUtil) {
this.passwordService = passwordService;
this.libraryService = libraryService;
this.jwtUtil = jwtUtil;
}
@PostMapping("/login")
public ResponseEntity<?> login(@Valid @RequestBody LoginRequest request, HttpServletResponse response) {
if (passwordService.authenticate(request.getPassword())) {
String token = jwtUtil.generateToken();
// Use new library-aware authentication
String token = passwordService.authenticateAndSwitchLibrary(request.getPassword());
if (token != null) {
// Set httpOnly cookie
ResponseCookie cookie = ResponseCookie.from("token", token)
.httpOnly(true)
@@ -40,7 +44,8 @@ public class AuthController {
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return ResponseEntity.ok(new LoginResponse("Authentication successful", token));
String libraryInfo = passwordService.getCurrentLibraryInfo();
return ResponseEntity.ok(new LoginResponse("Authentication successful - " + libraryInfo, token));
} else {
return ResponseEntity.status(401).body(new ErrorResponse("Invalid password"));
}
@@ -48,6 +53,9 @@ public class AuthController {
@PostMapping("/logout")
public ResponseEntity<?> logout(HttpServletResponse response) {
// Clear authentication state
libraryService.clearAuthentication();
// Clear the cookie
ResponseCookie cookie = ResponseCookie.from("token", "")
.httpOnly(true)

View File

@@ -335,6 +335,44 @@ public class AuthorController {
}
}
@PostMapping("/clean-author-names")
public ResponseEntity<Map<String, Object>> cleanAuthorNames() {
try {
List<Author> allAuthors = authorService.findAllWithStories();
int cleanedCount = 0;
for (Author author : allAuthors) {
String originalName = author.getName();
String cleanedName = originalName != null ? originalName.trim() : "";
if (!cleanedName.equals(originalName)) {
logger.info("Cleaning author name: '{}' -> '{}'", originalName, cleanedName);
author.setName(cleanedName);
authorService.update(author.getId(), author);
cleanedCount++;
}
}
// Reindex all authors after cleaning
if (cleanedCount > 0) {
typesenseService.reindexAllAuthors(allAuthors);
}
return ResponseEntity.ok(Map.of(
"success", true,
"message", "Cleaned " + cleanedCount + " author names and reindexed",
"cleanedCount", cleanedCount,
"totalAuthors", allAuthors.size()
));
} catch (Exception e) {
logger.error("Failed to clean author names", e);
return ResponseEntity.ok(Map.of(
"success", false,
"error", e.getMessage()
));
}
}
@GetMapping("/top-rated")
public ResponseEntity<List<AuthorSummaryDto>> getTopRatedAuthors(@RequestParam(defaultValue = "10") int limit) {
Pageable pageable = PageRequest.of(0, limit);

View File

@@ -6,6 +6,7 @@ import com.storycove.entity.CollectionStory;
import com.storycove.entity.Story;
import com.storycove.entity.Tag;
import com.storycove.service.CollectionService;
import com.storycove.service.EPUBExportService;
import com.storycove.service.ImageService;
import com.storycove.service.ReadingTimeService;
import com.storycove.service.TypesenseService;
@@ -32,16 +33,19 @@ public class CollectionController {
private final ImageService imageService;
private final TypesenseService typesenseService;
private final ReadingTimeService readingTimeService;
private final EPUBExportService epubExportService;
@Autowired
public CollectionController(CollectionService collectionService,
ImageService imageService,
@Autowired(required = false) TypesenseService typesenseService,
ReadingTimeService readingTimeService) {
ReadingTimeService readingTimeService,
EPUBExportService epubExportService) {
this.collectionService = collectionService;
this.imageService = imageService;
this.typesenseService = typesenseService;
this.readingTimeService = readingTimeService;
this.epubExportService = epubExportService;
}
/**
@@ -310,6 +314,85 @@ public class CollectionController {
}
}
/**
* GET /api/collections/{id}/epub - Export collection as EPUB
*/
@GetMapping("/{id}/epub")
public ResponseEntity<org.springframework.core.io.Resource> exportCollectionAsEPUB(@PathVariable UUID id) {
logger.info("Exporting collection {} to EPUB", id);
try {
Collection collection = collectionService.findById(id);
List<Story> stories = collection.getCollectionStories().stream()
.sorted((cs1, cs2) -> Integer.compare(cs1.getPosition(), cs2.getPosition()))
.map(cs -> cs.getStory())
.collect(java.util.stream.Collectors.toList());
if (stories.isEmpty()) {
logger.warn("Collection {} contains no stories for export", id);
return ResponseEntity.badRequest()
.body(null);
}
EPUBExportRequest request = new EPUBExportRequest();
request.setIncludeCoverImage(true);
request.setIncludeMetadata(true);
request.setIncludeReadingPosition(false); // Collections don't have reading positions
org.springframework.core.io.Resource resource = epubExportService.exportCollectionAsEPUB(id, request);
String filename = epubExportService.getCollectionEPUBFilename(collection);
logger.info("Successfully exported collection EPUB: {}", filename);
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
.header("Content-Type", "application/epub+zip")
.body(resource);
} catch (Exception e) {
logger.error("Error exporting collection EPUB: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* POST /api/collections/{id}/epub - Export collection as EPUB with custom options
*/
@PostMapping("/{id}/epub")
public ResponseEntity<org.springframework.core.io.Resource> exportCollectionAsEPUBWithOptions(
@PathVariable UUID id,
@Valid @RequestBody EPUBExportRequest request) {
logger.info("Exporting collection {} to EPUB with custom options", id);
try {
Collection collection = collectionService.findById(id);
List<Story> stories = collection.getCollectionStories().stream()
.sorted((cs1, cs2) -> Integer.compare(cs1.getPosition(), cs2.getPosition()))
.map(cs -> cs.getStory())
.collect(java.util.stream.Collectors.toList());
if (stories.isEmpty()) {
logger.warn("Collection {} contains no stories for export", id);
return ResponseEntity.badRequest()
.body(null);
}
org.springframework.core.io.Resource resource = epubExportService.exportCollectionAsEPUB(id, request);
String filename = epubExportService.getCollectionEPUBFilename(collection);
logger.info("Successfully exported collection EPUB with options: {}", filename);
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
.header("Content-Type", "application/epub+zip")
.body(resource);
} catch (Exception e) {
logger.error("Error exporting collection EPUB: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
// Mapper methods
private CollectionDto mapToCollectionDto(Collection collection) {

View File

@@ -81,4 +81,74 @@ public class DatabaseController {
.body(Map.of("success", false, "message", "Failed to clear database: " + e.getMessage()));
}
}
@PostMapping("/backup-complete")
public ResponseEntity<Resource> backupComplete() {
try {
Resource backup = databaseManagementService.createCompleteBackup();
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"));
String filename = "storycove_complete_backup_" + timestamp + ".zip";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.header(HttpHeaders.CONTENT_TYPE, "application/zip")
.body(backup);
} catch (Exception e) {
throw new RuntimeException("Failed to create complete backup: " + e.getMessage(), e);
}
}
@PostMapping("/restore-complete")
public ResponseEntity<Map<String, Object>> restoreComplete(@RequestParam("file") MultipartFile file) {
System.err.println("Complete restore endpoint called with file: " + (file != null ? file.getOriginalFilename() : "null"));
try {
if (file.isEmpty()) {
System.err.println("File is empty - returning bad request");
return ResponseEntity.badRequest()
.body(Map.of("success", false, "message", "No file uploaded"));
}
if (!file.getOriginalFilename().endsWith(".zip")) {
System.err.println("Invalid file type: " + file.getOriginalFilename());
return ResponseEntity.badRequest()
.body(Map.of("success", false, "message", "Invalid file type. Please upload a .zip file"));
}
System.err.println("File validation passed, calling restore service...");
databaseManagementService.restoreFromCompleteBackup(file.getInputStream());
System.err.println("Restore service completed successfully");
return ResponseEntity.ok(Map.of(
"success", true,
"message", "Complete backup restored successfully from " + file.getOriginalFilename()
));
} catch (IOException e) {
System.err.println("IOException during restore: " + e.getMessage());
e.printStackTrace();
return ResponseEntity.internalServerError()
.body(Map.of("success", false, "message", "Failed to read backup file: " + e.getMessage()));
} catch (Exception e) {
System.err.println("Exception during restore: " + e.getMessage());
e.printStackTrace();
return ResponseEntity.internalServerError()
.body(Map.of("success", false, "message", "Failed to restore complete backup: " + e.getMessage()));
}
}
@PostMapping("/clear-complete")
public ResponseEntity<Map<String, Object>> clearComplete() {
try {
int deletedRecords = databaseManagementService.clearAllDataAndFiles();
return ResponseEntity.ok(Map.of(
"success", true,
"message", "Database and files cleared successfully",
"deletedRecords", deletedRecords
));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("success", false, "message", "Failed to clear database and files: " + e.getMessage()));
}
}
}

View File

@@ -1,6 +1,7 @@
package com.storycove.controller;
import com.storycove.service.ImageService;
import com.storycove.service.LibraryService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
@@ -10,6 +11,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -21,9 +23,17 @@ import java.util.Map;
public class FileController {
private final ImageService imageService;
private final LibraryService libraryService;
public FileController(ImageService imageService) {
public FileController(ImageService imageService, LibraryService libraryService) {
this.imageService = imageService;
this.libraryService = libraryService;
}
private String getCurrentLibraryId() {
String libraryId = libraryService.getCurrentLibraryId();
System.out.println("FileController - Current Library ID: " + libraryId);
return libraryId != null ? libraryId : "default";
}
@PostMapping("/upload/cover")
@@ -34,7 +44,11 @@ public class FileController {
Map<String, String> response = new HashMap<>();
response.put("message", "Cover uploaded successfully");
response.put("path", imagePath);
response.put("url", "/api/files/images/" + imagePath);
String currentLibraryId = getCurrentLibraryId();
String imageUrl = "/api/files/images/" + currentLibraryId + "/" + imagePath;
response.put("url", imageUrl);
System.out.println("Upload response - path: " + imagePath + ", url: " + imageUrl);
return ResponseEntity.ok(response);
} catch (IllegalArgumentException e) {
@@ -53,7 +67,8 @@ public class FileController {
Map<String, String> response = new HashMap<>();
response.put("message", "Avatar uploaded successfully");
response.put("path", imagePath);
response.put("url", "/api/files/images/" + imagePath);
String currentLibraryId = getCurrentLibraryId();
response.put("url", "/api/files/images/" + currentLibraryId + "/" + imagePath);
return ResponseEntity.ok(response);
} catch (IllegalArgumentException e) {
@@ -64,17 +79,18 @@ public class FileController {
}
}
@GetMapping("/images/**")
public ResponseEntity<Resource> serveImage(@RequestParam String path) {
@GetMapping("/images/{libraryId}/**")
public ResponseEntity<Resource> serveImage(@PathVariable String libraryId, HttpServletRequest request) {
try {
// Extract path from the URL
String imagePath = path.replace("/api/files/images/", "");
// Extract the full request path after /api/files/images/{libraryId}/
String requestURI = request.getRequestURI();
String imagePath = requestURI.replaceFirst(".*/api/files/images/" + libraryId + "/", "");
if (!imageService.imageExists(imagePath)) {
if (!imageService.imageExistsInLibrary(imagePath, libraryId)) {
return ResponseEntity.notFound().build();
}
Path fullPath = imageService.getImagePath(imagePath);
Path fullPath = imageService.getImagePathInLibrary(imagePath, libraryId);
Resource resource = new FileSystemResource(fullPath);
if (!resource.exists()) {

View File

@@ -0,0 +1,242 @@
package com.storycove.controller;
import com.storycove.dto.LibraryDto;
import com.storycove.service.LibraryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/libraries")
public class LibraryController {
private static final Logger logger = LoggerFactory.getLogger(LibraryController.class);
private final LibraryService libraryService;
@Autowired
public LibraryController(LibraryService libraryService) {
this.libraryService = libraryService;
}
/**
* Get all available libraries (for settings UI)
*/
@GetMapping
public ResponseEntity<List<LibraryDto>> getAllLibraries() {
try {
List<LibraryDto> libraries = libraryService.getAllLibraries();
return ResponseEntity.ok(libraries);
} catch (Exception e) {
logger.error("Failed to get libraries", e);
return ResponseEntity.internalServerError().build();
}
}
/**
* Get current active library info
*/
@GetMapping("/current")
public ResponseEntity<LibraryDto> getCurrentLibrary() {
try {
var library = libraryService.getCurrentLibrary();
if (library == null) {
return ResponseEntity.noContent().build();
}
LibraryDto dto = new LibraryDto(
library.getId(),
library.getName(),
library.getDescription(),
true, // always active since it's current
library.isInitialized()
);
return ResponseEntity.ok(dto);
} catch (Exception e) {
logger.error("Failed to get current library", e);
return ResponseEntity.internalServerError().build();
}
}
/**
* Switch to a different library (requires re-authentication)
* This endpoint returns a switching status that the frontend can poll
*/
@PostMapping("/switch")
public ResponseEntity<Map<String, Object>> initiateLibrarySwitch(@RequestBody Map<String, String> request) {
try {
String password = request.get("password");
if (password == null || password.trim().isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "Password required"));
}
String libraryId = libraryService.authenticateAndGetLibrary(password);
if (libraryId == null) {
return ResponseEntity.status(401).body(Map.of("error", "Invalid password"));
}
// Check if already on this library
if (libraryId.equals(libraryService.getCurrentLibraryId())) {
return ResponseEntity.ok(Map.of(
"status", "already_active",
"message", "Already using this library"
));
}
// Initiate switch in background thread
new Thread(() -> {
try {
libraryService.switchToLibrary(libraryId);
logger.info("Library switch completed: {}", libraryId);
} catch (Exception e) {
logger.error("Library switch failed: {}", libraryId, e);
}
}).start();
return ResponseEntity.ok(Map.of(
"status", "switching",
"targetLibrary", libraryId,
"message", "Switching to library, please wait..."
));
} catch (Exception e) {
logger.error("Failed to initiate library switch", e);
return ResponseEntity.internalServerError().body(Map.of("error", "Server error"));
}
}
/**
* Check library switch status
*/
@GetMapping("/switch/status")
public ResponseEntity<Map<String, Object>> getLibrarySwitchStatus() {
try {
var currentLibrary = libraryService.getCurrentLibrary();
boolean isReady = currentLibrary != null;
Map<String, Object> response = new HashMap<>();
response.put("ready", isReady);
if (isReady) {
response.put("currentLibrary", currentLibrary.getId());
response.put("currentLibraryName", currentLibrary.getName());
} else {
response.put("currentLibrary", null);
response.put("currentLibraryName", null);
}
return ResponseEntity.ok(response);
} catch (Exception e) {
logger.error("Failed to get switch status", e);
return ResponseEntity.ok(Map.of("ready", false, "error", "Status check failed"));
}
}
/**
* Change password for current library
*/
@PostMapping("/password")
public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> request) {
try {
String currentPassword = request.get("currentPassword");
String newPassword = request.get("newPassword");
if (currentPassword == null || newPassword == null) {
return ResponseEntity.badRequest().body(Map.of("error", "Current and new passwords required"));
}
String currentLibraryId = libraryService.getCurrentLibraryId();
if (currentLibraryId == null) {
return ResponseEntity.badRequest().body(Map.of("error", "No active library"));
}
boolean success = libraryService.changeLibraryPassword(currentLibraryId, currentPassword, newPassword);
if (success) {
return ResponseEntity.ok(Map.of("success", true, "message", "Password changed successfully"));
} else {
return ResponseEntity.badRequest().body(Map.of("error", "Current password is incorrect"));
}
} catch (Exception e) {
logger.error("Failed to change password", e);
return ResponseEntity.internalServerError().body(Map.of("error", "Server error"));
}
}
/**
* Create a new library
*/
@PostMapping("/create")
public ResponseEntity<Map<String, Object>> createLibrary(@RequestBody Map<String, String> request) {
try {
String name = request.get("name");
String description = request.get("description");
String password = request.get("password");
if (name == null || name.trim().isEmpty() || password == null || password.trim().isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "Name and password are required"));
}
var newLibrary = libraryService.createNewLibrary(name.trim(), description, password);
return ResponseEntity.ok(Map.of(
"success", true,
"library", Map.of(
"id", newLibrary.getId(),
"name", newLibrary.getName(),
"description", newLibrary.getDescription()
),
"message", "Library created successfully. You can now log in with the new password to access it."
));
} catch (Exception e) {
logger.error("Failed to create library", e);
return ResponseEntity.internalServerError().body(Map.of("error", "Server error"));
}
}
/**
* Update library metadata (name and description)
*/
@PutMapping("/{libraryId}/metadata")
public ResponseEntity<Map<String, Object>> updateLibraryMetadata(
@PathVariable String libraryId,
@RequestBody Map<String, String> updates) {
try {
String newName = updates.get("name");
String newDescription = updates.get("description");
if (newName == null || newName.trim().isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "Library name is required"));
}
// Update the library
libraryService.updateLibraryMetadata(libraryId, newName, newDescription);
// Return updated library info
LibraryDto updatedLibrary = libraryService.getLibraryById(libraryId);
if (updatedLibrary != null) {
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("message", "Library metadata updated successfully");
response.put("library", updatedLibrary);
return ResponseEntity.ok(response);
} else {
return ResponseEntity.notFound().build();
}
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
} catch (Exception e) {
logger.error("Failed to update library metadata for {}: {}", libraryId, e.getMessage(), e);
return ResponseEntity.internalServerError().body(Map.of("error", "Failed to update library metadata"));
}
}
}

View File

@@ -14,6 +14,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@@ -25,6 +26,7 @@ import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -42,6 +44,8 @@ public class StoryController {
private final TypesenseService typesenseService;
private final CollectionService collectionService;
private final ReadingTimeService readingTimeService;
private final EPUBImportService epubImportService;
private final EPUBExportService epubExportService;
public StoryController(StoryService storyService,
AuthorService authorService,
@@ -50,7 +54,9 @@ public class StoryController {
ImageService imageService,
CollectionService collectionService,
@Autowired(required = false) TypesenseService typesenseService,
ReadingTimeService readingTimeService) {
ReadingTimeService readingTimeService,
EPUBImportService epubImportService,
EPUBExportService epubExportService) {
this.storyService = storyService;
this.authorService = authorService;
this.seriesService = seriesService;
@@ -59,6 +65,8 @@ public class StoryController {
this.collectionService = collectionService;
this.typesenseService = typesenseService;
this.readingTimeService = readingTimeService;
this.epubImportService = epubImportService;
this.epubExportService = epubExportService;
}
@GetMapping
@@ -78,12 +86,59 @@ public class StoryController {
return ResponseEntity.ok(storyDtos);
}
@GetMapping("/random")
public ResponseEntity<StorySummaryDto> getRandomStory(
@RequestParam(required = false) String searchQuery,
@RequestParam(required = false) List<String> tags,
@RequestParam(required = false) Long seed,
// Advanced filters
@RequestParam(required = false) Integer minWordCount,
@RequestParam(required = false) Integer maxWordCount,
@RequestParam(required = false) String createdAfter,
@RequestParam(required = false) String createdBefore,
@RequestParam(required = false) String lastReadAfter,
@RequestParam(required = false) String lastReadBefore,
@RequestParam(required = false) Integer minRating,
@RequestParam(required = false) Integer maxRating,
@RequestParam(required = false) Boolean unratedOnly,
@RequestParam(required = false) String readingStatus,
@RequestParam(required = false) Boolean hasReadingProgress,
@RequestParam(required = false) Boolean hasCoverImage,
@RequestParam(required = false) String sourceDomain,
@RequestParam(required = false) String seriesFilter,
@RequestParam(required = false) Integer minTagCount,
@RequestParam(required = false) Boolean popularOnly,
@RequestParam(required = false) Boolean hiddenGemsOnly) {
logger.info("Getting random story with filters - searchQuery: {}, tags: {}, seed: {}",
searchQuery, tags, seed);
Optional<Story> randomStory = storyService.findRandomStory(searchQuery, tags, seed,
minWordCount, maxWordCount, createdAfter, createdBefore, lastReadAfter, lastReadBefore,
minRating, maxRating, unratedOnly, readingStatus, hasReadingProgress, hasCoverImage,
sourceDomain, seriesFilter, minTagCount, popularOnly, hiddenGemsOnly);
if (randomStory.isPresent()) {
StorySummaryDto storyDto = convertToSummaryDto(randomStory.get());
return ResponseEntity.ok(storyDto);
} else {
return ResponseEntity.noContent().build(); // 204 No Content when no stories match filters
}
}
@GetMapping("/{id}")
public ResponseEntity<StoryDto> getStoryById(@PathVariable UUID id) {
Story story = storyService.findById(id);
return ResponseEntity.ok(convertToDto(story));
}
@GetMapping("/{id}/read")
public ResponseEntity<StoryReadingDto> getStoryForReading(@PathVariable UUID id) {
logger.info("Getting story {} for reading", id);
Story story = storyService.findById(id);
return ResponseEntity.ok(convertToReadingDto(story));
}
@PostMapping
public ResponseEntity<StoryDto> createStory(@Valid @RequestBody CreateStoryRequest request) {
logger.info("Creating new story: {}", request.getTitle());
@@ -99,6 +154,14 @@ public class StoryController {
public ResponseEntity<StoryDto> updateStory(@PathVariable UUID id,
@Valid @RequestBody UpdateStoryRequest request) {
logger.info("Updating story: {} (ID: {})", request.getTitle(), id);
// Handle author creation/lookup at controller level before calling service
if (request.getAuthorName() != null && !request.getAuthorName().trim().isEmpty() && request.getAuthorId() == null) {
Author author = findOrCreateAuthor(request.getAuthorName().trim());
request.setAuthorId(author.getId());
request.setAuthorName(null); // Clear author name since we now have the ID
}
Story updatedStory = storyService.updateWithTagNames(id, request);
logger.info("Successfully updated story: {}", updatedStory.getTitle());
return ResponseEntity.ok(convertToDto(updatedStory));
@@ -230,12 +293,32 @@ public class StoryController {
@RequestParam(required = false) Integer minRating,
@RequestParam(required = false) Integer maxRating,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
@RequestParam(required = false) String sortDir,
@RequestParam(required = false) String facetBy,
// Advanced filters
@RequestParam(required = false) Integer minWordCount,
@RequestParam(required = false) Integer maxWordCount,
@RequestParam(required = false) String createdAfter,
@RequestParam(required = false) String createdBefore,
@RequestParam(required = false) String lastReadAfter,
@RequestParam(required = false) String lastReadBefore,
@RequestParam(required = false) Boolean unratedOnly,
@RequestParam(required = false) String readingStatus,
@RequestParam(required = false) Boolean hasReadingProgress,
@RequestParam(required = false) Boolean hasCoverImage,
@RequestParam(required = false) String sourceDomain,
@RequestParam(required = false) String seriesFilter,
@RequestParam(required = false) Integer minTagCount,
@RequestParam(required = false) Boolean popularOnly,
@RequestParam(required = false) Boolean hiddenGemsOnly) {
if (typesenseService != null) {
SearchResultDto<StorySearchDto> results = typesenseService.searchStories(
query, page, size, authors, tags, minRating, maxRating, sortBy, sortDir);
query, page, size, authors, tags, minRating, maxRating, sortBy, sortDir, facetBy,
minWordCount, maxWordCount, createdAfter, createdBefore, lastReadAfter, lastReadBefore,
unratedOnly, readingStatus, hasReadingProgress, hasCoverImage, sourceDomain, seriesFilter,
minTagCount, popularOnly, hiddenGemsOnly);
return ResponseEntity.ok(results);
} else {
// Fallback to basic search if Typesense is not available
@@ -380,20 +463,43 @@ public class StoryController {
if (updateReq.getSourceUrl() != null) {
story.setSourceUrl(updateReq.getSourceUrl());
}
if (updateReq.getVolume() != null) {
story.setVolume(updateReq.getVolume());
}
// Volume will be handled in series logic below
// Handle author - either by ID or by name
if (updateReq.getAuthorId() != null) {
Author author = authorService.findById(updateReq.getAuthorId());
story.setAuthor(author);
} else if (updateReq.getAuthorName() != null && !updateReq.getAuthorName().trim().isEmpty()) {
Author author = findOrCreateAuthor(updateReq.getAuthorName().trim());
story.setAuthor(author);
}
// Handle series - either by ID or by name
// Handle series - either by ID, by name, or remove from series
if (updateReq.getSeriesId() != null) {
Series series = seriesService.findById(updateReq.getSeriesId());
story.setSeries(series);
} else if (updateReq.getSeriesName() != null && !updateReq.getSeriesName().trim().isEmpty()) {
Series series = seriesService.findOrCreate(updateReq.getSeriesName().trim());
story.setSeries(series);
} else if (updateReq.getSeriesName() != null) {
logger.info("Processing series update: seriesName='{}', isEmpty={}", updateReq.getSeriesName(), updateReq.getSeriesName().trim().isEmpty());
if (updateReq.getSeriesName().trim().isEmpty()) {
// Empty series name means remove from series
logger.info("Removing story from series");
if (story.getSeries() != null) {
story.getSeries().removeStory(story);
story.setSeries(null);
story.setVolume(null);
logger.info("Story removed from series");
}
} else {
// Non-empty series name means add to series
logger.info("Adding story to series: '{}', volume: {}", updateReq.getSeriesName().trim(), updateReq.getVolume());
Series series = seriesService.findOrCreate(updateReq.getSeriesName().trim());
story.setSeries(series);
// Set volume only if series is being set
if (updateReq.getVolume() != null) {
story.setVolume(updateReq.getVolume());
logger.info("Story added to series: {} with volume: {}", series.getName(), updateReq.getVolume());
} else {
logger.info("Story added to series: {} with no volume", series.getName());
}
}
}
// Note: Tags are now handled in StoryService.updateWithTagNames()
@@ -407,7 +513,43 @@ public class StoryController {
dto.setSummary(story.getSummary());
dto.setDescription(story.getDescription());
dto.setContentHtml(story.getContentHtml());
dto.setContentPlain(story.getContentPlain());
dto.setSourceUrl(story.getSourceUrl());
dto.setCoverPath(story.getCoverPath());
dto.setWordCount(story.getWordCount());
dto.setRating(story.getRating());
dto.setVolume(story.getVolume());
dto.setCreatedAt(story.getCreatedAt());
dto.setUpdatedAt(story.getUpdatedAt());
// Reading progress fields
dto.setIsRead(story.getIsRead());
dto.setReadingPosition(story.getReadingPosition());
dto.setLastReadAt(story.getLastReadAt());
if (story.getAuthor() != null) {
dto.setAuthorId(story.getAuthor().getId());
dto.setAuthorName(story.getAuthor().getName());
}
if (story.getSeries() != null) {
dto.setSeriesId(story.getSeries().getId());
dto.setSeriesName(story.getSeries().getName());
}
dto.setTags(story.getTags().stream()
.map(this::convertTagToDto)
.collect(Collectors.toList()));
return dto;
}
private StoryReadingDto convertToReadingDto(Story story) {
StoryReadingDto dto = new StoryReadingDto();
dto.setId(story.getId());
dto.setTitle(story.getTitle());
dto.setSummary(story.getSummary());
dto.setDescription(story.getDescription());
dto.setContentHtml(story.getContentHtml());
dto.setSourceUrl(story.getSourceUrl());
dto.setCoverPath(story.getCoverPath());
dto.setWordCount(story.getWordCount());
@@ -479,8 +621,11 @@ public class StoryController {
TagDto tagDto = new TagDto();
tagDto.setId(tag.getId());
tagDto.setName(tag.getName());
tagDto.setColor(tag.getColor());
tagDto.setDescription(tag.getDescription());
tagDto.setCreatedAt(tag.getCreatedAt());
// storyCount can be set if needed, but it might be expensive to calculate for each tag
tagDto.setStoryCount(tag.getStories() != null ? tag.getStories().size() : 0);
tagDto.setAliasCount(tag.getAliases() != null ? tag.getAliases().size() : 0);
return tagDto;
}
@@ -533,6 +678,117 @@ public class StoryController {
}
}
// EPUB Import endpoint
@PostMapping("/epub/import")
public ResponseEntity<EPUBImportResponse> importEPUB(
@RequestParam("file") MultipartFile file,
@RequestParam(required = false) UUID authorId,
@RequestParam(required = false) String authorName,
@RequestParam(required = false) UUID seriesId,
@RequestParam(required = false) String seriesName,
@RequestParam(required = false) Integer seriesVolume,
@RequestParam(required = false) List<String> tags,
@RequestParam(defaultValue = "true") Boolean preserveReadingPosition,
@RequestParam(defaultValue = "false") Boolean overwriteExisting,
@RequestParam(defaultValue = "true") Boolean createMissingAuthor,
@RequestParam(defaultValue = "true") Boolean createMissingSeries) {
logger.info("Importing EPUB file: {}", file.getOriginalFilename());
EPUBImportRequest request = new EPUBImportRequest();
request.setEpubFile(file);
request.setAuthorId(authorId);
request.setAuthorName(authorName);
request.setSeriesId(seriesId);
request.setSeriesName(seriesName);
request.setSeriesVolume(seriesVolume);
request.setTags(tags);
request.setPreserveReadingPosition(preserveReadingPosition);
request.setOverwriteExisting(overwriteExisting);
request.setCreateMissingAuthor(createMissingAuthor);
request.setCreateMissingSeries(createMissingSeries);
try {
EPUBImportResponse response = epubImportService.importEPUB(request);
if (response.isSuccess()) {
logger.info("Successfully imported EPUB: {} (Story ID: {})",
response.getStoryTitle(), response.getStoryId());
return ResponseEntity.ok(response);
} else {
logger.warn("EPUB import failed: {}", response.getMessage());
return ResponseEntity.badRequest().body(response);
}
} catch (Exception e) {
logger.error("Error importing EPUB: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(EPUBImportResponse.error("Internal server error: " + e.getMessage()));
}
}
// EPUB Export endpoint
@PostMapping("/epub/export")
public ResponseEntity<org.springframework.core.io.Resource> exportEPUB(
@Valid @RequestBody EPUBExportRequest request) {
logger.info("Exporting story {} to EPUB", request.getStoryId());
try {
if (!epubExportService.canExportStory(request.getStoryId())) {
return ResponseEntity.badRequest().build();
}
org.springframework.core.io.Resource resource = epubExportService.exportStoryAsEPUB(request);
Story story = storyService.findById(request.getStoryId());
String filename = epubExportService.getEPUBFilename(story);
logger.info("Successfully exported EPUB: {}", filename);
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
.header("Content-Type", "application/epub+zip")
.body(resource);
} catch (Exception e) {
logger.error("Error exporting EPUB: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
// EPUB Export by story ID (GET endpoint)
@GetMapping("/{id}/epub")
public ResponseEntity<org.springframework.core.io.Resource> exportStoryAsEPUB(@PathVariable UUID id) {
logger.info("Exporting story {} to EPUB via GET", id);
EPUBExportRequest request = new EPUBExportRequest(id);
return exportEPUB(request);
}
// Validate EPUB file
@PostMapping("/epub/validate")
public ResponseEntity<Map<String, Object>> validateEPUBFile(@RequestParam("file") MultipartFile file) {
logger.info("Validating EPUB file: {}", file.getOriginalFilename());
try {
List<String> errors = epubImportService.validateEPUBFile(file);
Map<String, Object> response = Map.of(
"valid", errors.isEmpty(),
"errors", errors,
"filename", file.getOriginalFilename(),
"size", file.getSize()
);
return ResponseEntity.ok(response);
} catch (Exception e) {
logger.error("Error validating EPUB file: {}", e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to validate EPUB file"));
}
}
// Request DTOs
public static class CreateStoryRequest {
private String title;
@@ -580,6 +836,7 @@ public class StoryController {
private String sourceUrl;
private Integer volume;
private UUID authorId;
private String authorName;
private UUID seriesId;
private String seriesName;
private List<String> tagNames;
@@ -599,6 +856,8 @@ public class StoryController {
public void setVolume(Integer volume) { this.volume = volume; }
public UUID getAuthorId() { return authorId; }
public void setAuthorId(UUID authorId) { this.authorId = authorId; }
public String getAuthorName() { return authorName; }
public void setAuthorName(String authorName) { this.authorName = authorName; }
public UUID getSeriesId() { return seriesId; }
public void setSeriesId(UUID seriesId) { this.seriesId = seriesId; }
public String getSeriesName() { return seriesName; }

View File

@@ -1,9 +1,13 @@
package com.storycove.controller;
import com.storycove.dto.TagDto;
import com.storycove.dto.TagAliasDto;
import com.storycove.entity.Tag;
import com.storycove.entity.TagAlias;
import com.storycove.service.TagService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@@ -21,6 +25,7 @@ import java.util.stream.Collectors;
@RequestMapping("/api/tags")
public class TagController {
private static final Logger logger = LoggerFactory.getLogger(TagController.class);
private final TagService tagService;
public TagController(TagService tagService) {
@@ -54,6 +59,8 @@ public class TagController {
public ResponseEntity<TagDto> createTag(@Valid @RequestBody CreateTagRequest request) {
Tag tag = new Tag();
tag.setName(request.getName());
tag.setColor(request.getColor());
tag.setDescription(request.getDescription());
Tag savedTag = tagService.create(tag);
return ResponseEntity.status(HttpStatus.CREATED).body(convertToDto(savedTag));
@@ -66,6 +73,12 @@ public class TagController {
if (request.getName() != null) {
existingTag.setName(request.getName());
}
if (request.getColor() != null) {
existingTag.setColor(request.getColor());
}
if (request.getDescription() != null) {
existingTag.setDescription(request.getDescription());
}
Tag updatedTag = tagService.update(id, existingTag);
return ResponseEntity.ok(convertToDto(updatedTag));
@@ -95,7 +108,7 @@ public class TagController {
@RequestParam String query,
@RequestParam(defaultValue = "10") int limit) {
List<Tag> tags = tagService.findByNameStartingWith(query, limit);
List<Tag> tags = tagService.findByNameOrAliasStartingWith(query, limit);
List<TagDto> tagDtos = tags.stream().map(this::convertToDto).collect(Collectors.toList());
return ResponseEntity.ok(tagDtos);
@@ -142,15 +155,124 @@ public class TagController {
return ResponseEntity.ok(tagDtos);
}
// Tag alias endpoints
@PostMapping("/{tagId}/aliases")
public ResponseEntity<TagAliasDto> addAlias(@PathVariable UUID tagId,
@RequestBody Map<String, String> request) {
String aliasName = request.get("aliasName");
if (aliasName == null || aliasName.trim().isEmpty()) {
return ResponseEntity.badRequest().build();
}
try {
TagAlias alias = tagService.addAlias(tagId, aliasName.trim());
TagAliasDto dto = new TagAliasDto();
dto.setId(alias.getId());
dto.setAliasName(alias.getAliasName());
dto.setCanonicalTagId(alias.getCanonicalTag().getId());
dto.setCanonicalTagName(alias.getCanonicalTag().getName());
dto.setCreatedFromMerge(alias.getCreatedFromMerge());
dto.setCreatedAt(alias.getCreatedAt());
return ResponseEntity.status(HttpStatus.CREATED).body(dto);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
@DeleteMapping("/{tagId}/aliases/{aliasId}")
public ResponseEntity<?> removeAlias(@PathVariable UUID tagId, @PathVariable UUID aliasId) {
try {
tagService.removeAlias(tagId, aliasId);
return ResponseEntity.ok(Map.of("message", "Alias removed successfully"));
} catch (Exception e) {
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
}
}
@GetMapping("/resolve/{name}")
public ResponseEntity<TagDto> resolveTag(@PathVariable String name) {
try {
Tag resolvedTag = tagService.resolveTagByName(name);
if (resolvedTag != null) {
return ResponseEntity.ok(convertToDto(resolvedTag));
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
@PostMapping("/merge")
public ResponseEntity<?> mergeTags(@Valid @RequestBody MergeTagsRequest request) {
try {
Tag resultTag = tagService.mergeTags(request.getSourceTagUUIDs(), request.getTargetTagUUID());
return ResponseEntity.ok(convertToDto(resultTag));
} catch (Exception e) {
logger.error("Failed to merge tags", e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "Unknown error occurred";
return ResponseEntity.badRequest().body(Map.of("error", errorMessage));
}
}
@PostMapping("/merge/preview")
public ResponseEntity<?> previewMerge(@Valid @RequestBody MergeTagsRequest request) {
try {
MergePreviewResponse preview = tagService.previewMerge(request.getSourceTagUUIDs(), request.getTargetTagUUID());
return ResponseEntity.ok(preview);
} catch (Exception e) {
logger.error("Failed to preview merge", e);
String errorMessage = e.getMessage() != null ? e.getMessage() : "Unknown error occurred";
return ResponseEntity.badRequest().body(Map.of("error", errorMessage));
}
}
@PostMapping("/suggest")
public ResponseEntity<List<TagSuggestion>> suggestTags(@RequestBody TagSuggestionRequest request) {
try {
List<TagSuggestion> suggestions = tagService.suggestTags(
request.getTitle(),
request.getContent(),
request.getSummary(),
request.getLimit() != null ? request.getLimit() : 10
);
return ResponseEntity.ok(suggestions);
} catch (Exception e) {
logger.error("Failed to suggest tags", e);
return ResponseEntity.ok(List.of()); // Return empty list on error
}
}
private TagDto convertToDto(Tag tag) {
TagDto dto = new TagDto();
dto.setId(tag.getId());
dto.setName(tag.getName());
dto.setColor(tag.getColor());
dto.setDescription(tag.getDescription());
dto.setStoryCount(tag.getStories() != null ? tag.getStories().size() : 0);
dto.setCollectionCount(tag.getCollections() != null ? tag.getCollections().size() : 0);
dto.setAliasCount(tag.getAliases() != null ? tag.getAliases().size() : 0);
dto.setCreatedAt(tag.getCreatedAt());
// updatedAt field not present in Tag entity per spec
// Convert aliases to DTOs for full context
if (tag.getAliases() != null && !tag.getAliases().isEmpty()) {
List<TagAliasDto> aliaseDtos = tag.getAliases().stream()
.map(alias -> {
TagAliasDto aliasDto = new TagAliasDto();
aliasDto.setId(alias.getId());
aliasDto.setAliasName(alias.getAliasName());
aliasDto.setCanonicalTagId(alias.getCanonicalTag().getId());
aliasDto.setCanonicalTagName(alias.getCanonicalTag().getName());
aliasDto.setCreatedFromMerge(alias.getCreatedFromMerge());
aliasDto.setCreatedAt(alias.getCreatedAt());
return aliasDto;
})
.collect(Collectors.toList());
dto.setAliases(aliaseDtos);
}
return dto;
}
@@ -168,15 +290,112 @@ public class TagController {
// Request DTOs
public static class CreateTagRequest {
private String name;
private String color;
private String description;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
public static class UpdateTagRequest {
private String name;
private String color;
private String description;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
public static class MergeTagsRequest {
private List<String> sourceTagIds;
private String targetTagId;
public List<String> getSourceTagIds() { return sourceTagIds; }
public void setSourceTagIds(List<String> sourceTagIds) { this.sourceTagIds = sourceTagIds; }
public String getTargetTagId() { return targetTagId; }
public void setTargetTagId(String targetTagId) { this.targetTagId = targetTagId; }
// Helper methods to convert to UUID
public List<UUID> getSourceTagUUIDs() {
return sourceTagIds != null ? sourceTagIds.stream().map(UUID::fromString).toList() : null;
}
public UUID getTargetTagUUID() {
return targetTagId != null ? UUID.fromString(targetTagId) : null;
}
}
public static class MergePreviewResponse {
private String targetTagName;
private int targetStoryCount;
private int totalResultStoryCount;
private List<String> aliasesToCreate;
public String getTargetTagName() { return targetTagName; }
public void setTargetTagName(String targetTagName) { this.targetTagName = targetTagName; }
public int getTargetStoryCount() { return targetStoryCount; }
public void setTargetStoryCount(int targetStoryCount) { this.targetStoryCount = targetStoryCount; }
public int getTotalResultStoryCount() { return totalResultStoryCount; }
public void setTotalResultStoryCount(int totalResultStoryCount) { this.totalResultStoryCount = totalResultStoryCount; }
public List<String> getAliasesToCreate() { return aliasesToCreate; }
public void setAliasesToCreate(List<String> aliasesToCreate) { this.aliasesToCreate = aliasesToCreate; }
}
public static class TagSuggestionRequest {
private String title;
private String content;
private String summary;
private Integer limit;
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getSummary() { return summary; }
public void setSummary(String summary) { this.summary = summary; }
public Integer getLimit() { return limit; }
public void setLimit(Integer limit) { this.limit = limit; }
}
public static class TagSuggestion {
private String tagName;
private double confidence;
private String reason;
public TagSuggestion() {}
public TagSuggestion(String tagName, double confidence, String reason) {
this.tagName = tagName;
this.confidence = confidence;
this.reason = reason;
}
public String getTagName() { return tagName; }
public void setTagName(String tagName) { this.tagName = tagName; }
public double getConfidence() { return confidence; }
public void setConfidence(double confidence) { this.confidence = confidence; }
public String getReason() { return reason; }
public void setReason(String reason) { this.reason = reason; }
}
}

View File

@@ -0,0 +1,115 @@
package com.storycove.dto;
import jakarta.validation.constraints.NotNull;
import java.util.List;
import java.util.UUID;
public class EPUBExportRequest {
@NotNull(message = "Story ID is required")
private UUID storyId;
private String customTitle;
private String customAuthor;
private Boolean includeReadingPosition = true;
private Boolean includeCoverImage = true;
private Boolean includeMetadata = true;
private List<String> customMetadata;
private String language = "en";
private Boolean splitByChapters = false;
private Integer maxWordsPerChapter;
public EPUBExportRequest() {}
public EPUBExportRequest(UUID storyId) {
this.storyId = storyId;
}
public UUID getStoryId() {
return storyId;
}
public void setStoryId(UUID storyId) {
this.storyId = storyId;
}
public String getCustomTitle() {
return customTitle;
}
public void setCustomTitle(String customTitle) {
this.customTitle = customTitle;
}
public String getCustomAuthor() {
return customAuthor;
}
public void setCustomAuthor(String customAuthor) {
this.customAuthor = customAuthor;
}
public Boolean getIncludeReadingPosition() {
return includeReadingPosition;
}
public void setIncludeReadingPosition(Boolean includeReadingPosition) {
this.includeReadingPosition = includeReadingPosition;
}
public Boolean getIncludeCoverImage() {
return includeCoverImage;
}
public void setIncludeCoverImage(Boolean includeCoverImage) {
this.includeCoverImage = includeCoverImage;
}
public Boolean getIncludeMetadata() {
return includeMetadata;
}
public void setIncludeMetadata(Boolean includeMetadata) {
this.includeMetadata = includeMetadata;
}
public List<String> getCustomMetadata() {
return customMetadata;
}
public void setCustomMetadata(List<String> customMetadata) {
this.customMetadata = customMetadata;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Boolean getSplitByChapters() {
return splitByChapters;
}
public void setSplitByChapters(Boolean splitByChapters) {
this.splitByChapters = splitByChapters;
}
public Integer getMaxWordsPerChapter() {
return maxWordsPerChapter;
}
public void setMaxWordsPerChapter(Integer maxWordsPerChapter) {
this.maxWordsPerChapter = maxWordsPerChapter;
}
}

View File

@@ -0,0 +1,133 @@
package com.storycove.dto;
import jakarta.validation.constraints.NotNull;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.UUID;
public class EPUBImportRequest {
@NotNull(message = "EPUB file is required")
private MultipartFile epubFile;
private UUID authorId;
private String authorName;
private UUID seriesId;
private String seriesName;
private Integer seriesVolume;
private List<String> tags;
private Boolean preserveReadingPosition = true;
private Boolean overwriteExisting = false;
private Boolean createMissingAuthor = true;
private Boolean createMissingSeries = true;
private Boolean extractCover = true;
public EPUBImportRequest() {}
public MultipartFile getEpubFile() {
return epubFile;
}
public void setEpubFile(MultipartFile epubFile) {
this.epubFile = epubFile;
}
public UUID getAuthorId() {
return authorId;
}
public void setAuthorId(UUID authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public UUID getSeriesId() {
return seriesId;
}
public void setSeriesId(UUID seriesId) {
this.seriesId = seriesId;
}
public String getSeriesName() {
return seriesName;
}
public void setSeriesName(String seriesName) {
this.seriesName = seriesName;
}
public Integer getSeriesVolume() {
return seriesVolume;
}
public void setSeriesVolume(Integer seriesVolume) {
this.seriesVolume = seriesVolume;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Boolean getPreserveReadingPosition() {
return preserveReadingPosition;
}
public void setPreserveReadingPosition(Boolean preserveReadingPosition) {
this.preserveReadingPosition = preserveReadingPosition;
}
public Boolean getOverwriteExisting() {
return overwriteExisting;
}
public void setOverwriteExisting(Boolean overwriteExisting) {
this.overwriteExisting = overwriteExisting;
}
public Boolean getCreateMissingAuthor() {
return createMissingAuthor;
}
public void setCreateMissingAuthor(Boolean createMissingAuthor) {
this.createMissingAuthor = createMissingAuthor;
}
public Boolean getCreateMissingSeries() {
return createMissingSeries;
}
public void setCreateMissingSeries(Boolean createMissingSeries) {
this.createMissingSeries = createMissingSeries;
}
public Boolean getExtractCover() {
return extractCover;
}
public void setExtractCover(Boolean extractCover) {
this.extractCover = extractCover;
}
}

View File

@@ -0,0 +1,107 @@
package com.storycove.dto;
import java.util.List;
import java.util.UUID;
public class EPUBImportResponse {
private boolean success;
private String message;
private UUID storyId;
private String storyTitle;
private Integer totalChapters;
private Integer wordCount;
private ReadingPositionDto readingPosition;
private List<String> warnings;
private List<String> errors;
public EPUBImportResponse() {}
public EPUBImportResponse(boolean success, String message) {
this.success = success;
this.message = message;
}
public static EPUBImportResponse success(UUID storyId, String storyTitle) {
EPUBImportResponse response = new EPUBImportResponse(true, "EPUB imported successfully");
response.setStoryId(storyId);
response.setStoryTitle(storyTitle);
return response;
}
public static EPUBImportResponse error(String message) {
return new EPUBImportResponse(false, message);
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public UUID getStoryId() {
return storyId;
}
public void setStoryId(UUID storyId) {
this.storyId = storyId;
}
public String getStoryTitle() {
return storyTitle;
}
public void setStoryTitle(String storyTitle) {
this.storyTitle = storyTitle;
}
public Integer getTotalChapters() {
return totalChapters;
}
public void setTotalChapters(Integer totalChapters) {
this.totalChapters = totalChapters;
}
public Integer getWordCount() {
return wordCount;
}
public void setWordCount(Integer wordCount) {
this.wordCount = wordCount;
}
public ReadingPositionDto getReadingPosition() {
return readingPosition;
}
public void setReadingPosition(ReadingPositionDto readingPosition) {
this.readingPosition = readingPosition;
}
public List<String> getWarnings() {
return warnings;
}
public void setWarnings(List<String> warnings) {
this.warnings = warnings;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
}

View File

@@ -8,6 +8,7 @@ public class HtmlSanitizationConfigDto {
private Map<String, List<String>> allowedAttributes;
private List<String> allowedCssProperties;
private Map<String, List<String>> removedAttributes;
private Map<String, Map<String, List<String>>> allowedProtocols;
private String description;
public HtmlSanitizationConfigDto() {}
@@ -44,6 +45,14 @@ public class HtmlSanitizationConfigDto {
this.removedAttributes = removedAttributes;
}
public Map<String, Map<String, List<String>>> getAllowedProtocols() {
return allowedProtocols;
}
public void setAllowedProtocols(Map<String, Map<String, List<String>>> allowedProtocols) {
this.allowedProtocols = allowedProtocols;
}
public String getDescription() {
return description;
}

View File

@@ -0,0 +1,61 @@
package com.storycove.dto;
public class LibraryDto {
private String id;
private String name;
private String description;
private boolean isActive;
private boolean isInitialized;
// Constructors
public LibraryDto() {}
public LibraryDto(String id, String name, String description, boolean isActive, boolean isInitialized) {
this.id = id;
this.name = name;
this.description = description;
this.isActive = isActive;
this.isInitialized = isInitialized;
}
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public boolean isInitialized() {
return isInitialized;
}
public void setInitialized(boolean initialized) {
isInitialized = initialized;
}
}

View File

@@ -0,0 +1,124 @@
package com.storycove.dto;
import java.time.LocalDateTime;
import java.util.UUID;
public class ReadingPositionDto {
private UUID id;
private UUID storyId;
private Integer chapterIndex;
private String chapterTitle;
private Integer wordPosition;
private Integer characterPosition;
private Double percentageComplete;
private String epubCfi;
private String contextBefore;
private String contextAfter;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
public ReadingPositionDto() {}
public ReadingPositionDto(UUID storyId, Integer chapterIndex, Integer wordPosition) {
this.storyId = storyId;
this.chapterIndex = chapterIndex;
this.wordPosition = wordPosition;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getStoryId() {
return storyId;
}
public void setStoryId(UUID storyId) {
this.storyId = storyId;
}
public Integer getChapterIndex() {
return chapterIndex;
}
public void setChapterIndex(Integer chapterIndex) {
this.chapterIndex = chapterIndex;
}
public String getChapterTitle() {
return chapterTitle;
}
public void setChapterTitle(String chapterTitle) {
this.chapterTitle = chapterTitle;
}
public Integer getWordPosition() {
return wordPosition;
}
public void setWordPosition(Integer wordPosition) {
this.wordPosition = wordPosition;
}
public Integer getCharacterPosition() {
return characterPosition;
}
public void setCharacterPosition(Integer characterPosition) {
this.characterPosition = characterPosition;
}
public Double getPercentageComplete() {
return percentageComplete;
}
public void setPercentageComplete(Double percentageComplete) {
this.percentageComplete = percentageComplete;
}
public String getEpubCfi() {
return epubCfi;
}
public void setEpubCfi(String epubCfi) {
this.epubCfi = epubCfi;
}
public String getContextBefore() {
return contextBefore;
}
public void setContextBefore(String contextBefore) {
this.contextBefore = contextBefore;
}
public String getContextAfter() {
return contextAfter;
}
public void setContextAfter(String contextAfter) {
this.contextAfter = contextAfter;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -21,7 +21,7 @@ public class StoryDto {
private String description;
private String contentHtml;
private String contentPlain;
// contentPlain removed for performance - use StoryReadingDto when content is needed
private String sourceUrl;
private String coverPath;
private Integer wordCount;
@@ -90,13 +90,6 @@ public class StoryDto {
this.contentHtml = contentHtml;
}
public String getContentPlain() {
return contentPlain;
}
public void setContentPlain(String contentPlain) {
this.contentPlain = contentPlain;
}
public String getSourceUrl() {
return sourceUrl;

View File

@@ -0,0 +1,202 @@
package com.storycove.dto;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
/**
* Story DTO specifically for reading view.
* Contains contentHtml but excludes contentPlain for performance.
*/
public class StoryReadingDto {
private UUID id;
private String title;
private String summary;
private String description;
private String contentHtml; // For reading - includes HTML
// contentPlain excluded for performance
private String sourceUrl;
private String coverPath;
private Integer wordCount;
private Integer rating;
private Integer volume;
// Reading progress fields
private Boolean isRead;
private Integer readingPosition;
private LocalDateTime lastReadAt;
// Related entities as simple references
private UUID authorId;
private String authorName;
private UUID seriesId;
private String seriesName;
private List<TagDto> tags;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
public StoryReadingDto() {}
// Getters and Setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContentHtml() {
return contentHtml;
}
public void setContentHtml(String contentHtml) {
this.contentHtml = contentHtml;
}
public String getSourceUrl() {
return sourceUrl;
}
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
public String getCoverPath() {
return coverPath;
}
public void setCoverPath(String coverPath) {
this.coverPath = coverPath;
}
public Integer getWordCount() {
return wordCount;
}
public void setWordCount(Integer wordCount) {
this.wordCount = wordCount;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public Boolean getIsRead() {
return isRead;
}
public void setIsRead(Boolean isRead) {
this.isRead = isRead;
}
public Integer getReadingPosition() {
return readingPosition;
}
public void setReadingPosition(Integer readingPosition) {
this.readingPosition = readingPosition;
}
public LocalDateTime getLastReadAt() {
return lastReadAt;
}
public void setLastReadAt(LocalDateTime lastReadAt) {
this.lastReadAt = lastReadAt;
}
public UUID getAuthorId() {
return authorId;
}
public void setAuthorId(UUID authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public UUID getSeriesId() {
return seriesId;
}
public void setSeriesId(UUID seriesId) {
this.seriesId = seriesId;
}
public String getSeriesName() {
return seriesName;
}
public void setSeriesName(String seriesName) {
this.seriesName = seriesName;
}
public List<TagDto> getTags() {
return tags;
}
public void setTags(List<TagDto> tags) {
this.tags = tags;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@@ -9,7 +9,6 @@ public class StorySearchDto {
private UUID id;
private String title;
private String description;
private String contentPlain;
private String sourceUrl;
private String coverPath;
private Integer wordCount;
@@ -18,6 +17,7 @@ public class StorySearchDto {
// Reading status
private Boolean isRead;
private LocalDateTime lastReadAt;
// Author info
private UUID authorId;
@@ -64,13 +64,6 @@ public class StorySearchDto {
this.description = description;
}
public String getContentPlain() {
return contentPlain;
}
public void setContentPlain(String contentPlain) {
this.contentPlain = contentPlain;
}
public String getSourceUrl() {
return sourceUrl;
@@ -120,6 +113,14 @@ public class StorySearchDto {
this.isRead = isRead;
}
public LocalDateTime getLastReadAt() {
return lastReadAt;
}
public void setLastReadAt(LocalDateTime lastReadAt) {
this.lastReadAt = lastReadAt;
}
public UUID getAuthorId() {
return authorId;
}

View File

@@ -0,0 +1,77 @@
package com.storycove.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.UUID;
public class TagAliasDto {
private UUID id;
@NotBlank(message = "Alias name is required")
@Size(max = 100, message = "Alias name must not exceed 100 characters")
private String aliasName;
private UUID canonicalTagId;
private String canonicalTagName; // For convenience in frontend
private Boolean createdFromMerge;
private LocalDateTime createdAt;
public TagAliasDto() {}
public TagAliasDto(String aliasName, UUID canonicalTagId) {
this.aliasName = aliasName;
this.canonicalTagId = canonicalTagId;
}
// Getters and Setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getAliasName() {
return aliasName;
}
public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
public UUID getCanonicalTagId() {
return canonicalTagId;
}
public void setCanonicalTagId(UUID canonicalTagId) {
this.canonicalTagId = canonicalTagId;
}
public String getCanonicalTagName() {
return canonicalTagName;
}
public void setCanonicalTagName(String canonicalTagName) {
this.canonicalTagName = canonicalTagName;
}
public Boolean getCreatedFromMerge() {
return createdFromMerge;
}
public void setCreatedFromMerge(Boolean createdFromMerge) {
this.createdFromMerge = createdFromMerge;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
}

View File

@@ -4,6 +4,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
public class TagDto {
@@ -14,8 +15,16 @@ public class TagDto {
@Size(max = 100, message = "Tag name must not exceed 100 characters")
private String name;
@Size(max = 7, message = "Color must be a valid hex color code")
private String color;
@Size(max = 500, message = "Description must not exceed 500 characters")
private String description;
private Integer storyCount;
private Integer collectionCount;
private Integer aliasCount;
private List<TagAliasDto> aliases;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@@ -42,6 +51,22 @@ public class TagDto {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStoryCount() {
return storyCount;
}
@@ -58,6 +83,22 @@ public class TagDto {
this.collectionCount = collectionCount;
}
public Integer getAliasCount() {
return aliasCount;
}
public void setAliasCount(Integer aliasCount) {
this.aliasCount = aliasCount;
}
public List<TagAliasDto> getAliases() {
return aliases;
}
public void setAliases(List<TagAliasDto> aliases) {
this.aliases = aliases;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}

View File

@@ -0,0 +1,93 @@
package com.storycove.entity;
public class Library {
private String id;
private String name;
private String description;
private String passwordHash;
private String dbName;
private String typesenseCollection;
private String imagePath;
private boolean initialized;
// Constructors
public Library() {}
public Library(String id, String name, String description, String passwordHash, String dbName) {
this.id = id;
this.name = name;
this.description = description;
this.passwordHash = passwordHash;
this.dbName = dbName;
this.typesenseCollection = "stories_" + id;
this.imagePath = "/images/" + id;
this.initialized = false;
}
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
this.typesenseCollection = "stories_" + id;
this.imagePath = "/images/" + id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getTypesenseCollection() {
return typesenseCollection;
}
public void setTypesenseCollection(String typesenseCollection) {
this.typesenseCollection = typesenseCollection;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public boolean isInitialized() {
return initialized;
}
public void setInitialized(boolean initialized) {
this.initialized = initialized;
}
}

View File

@@ -0,0 +1,230 @@
package com.storycove.entity;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import com.fasterxml.jackson.annotation.JsonBackReference;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "reading_positions", indexes = {
@Index(name = "idx_reading_position_story", columnList = "story_id")
})
public class ReadingPosition {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@NotNull
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "story_id", nullable = false)
@JsonBackReference("story-reading-positions")
private Story story;
@Column(name = "chapter_index")
private Integer chapterIndex;
@Column(name = "chapter_title")
private String chapterTitle;
@Column(name = "word_position")
private Integer wordPosition;
@Column(name = "character_position")
private Integer characterPosition;
@Column(name = "percentage_complete")
private Double percentageComplete;
@Column(name = "epub_cfi", columnDefinition = "TEXT")
private String epubCfi;
@Column(name = "context_before", length = 500)
private String contextBefore;
@Column(name = "context_after", length = 500)
private String contextAfter;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
public ReadingPosition() {}
public ReadingPosition(Story story) {
this.story = story;
this.chapterIndex = 0;
this.wordPosition = 0;
this.characterPosition = 0;
this.percentageComplete = 0.0;
}
public ReadingPosition(Story story, Integer chapterIndex, Integer wordPosition) {
this.story = story;
this.chapterIndex = chapterIndex;
this.wordPosition = wordPosition;
this.characterPosition = 0;
this.percentageComplete = 0.0;
}
public void updatePosition(Integer chapterIndex, Integer wordPosition, Integer characterPosition) {
this.chapterIndex = chapterIndex;
this.wordPosition = wordPosition;
this.characterPosition = characterPosition;
calculatePercentageComplete();
}
public void updatePositionWithCfi(String epubCfi, Integer chapterIndex, Integer wordPosition) {
this.epubCfi = epubCfi;
this.chapterIndex = chapterIndex;
this.wordPosition = wordPosition;
calculatePercentageComplete();
}
private void calculatePercentageComplete() {
if (story != null && story.getWordCount() != null && story.getWordCount() > 0) {
int totalWords = story.getWordCount();
int currentPosition = (chapterIndex != null ? chapterIndex * 1000 : 0) +
(wordPosition != null ? wordPosition : 0);
this.percentageComplete = Math.min(100.0, (double) currentPosition / totalWords * 100);
}
}
public boolean isAtBeginning() {
return (chapterIndex == null || chapterIndex == 0) &&
(wordPosition == null || wordPosition == 0);
}
public boolean isCompleted() {
return percentageComplete != null && percentageComplete >= 95.0;
}
// Getters and Setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public Story getStory() {
return story;
}
public void setStory(Story story) {
this.story = story;
}
public Integer getChapterIndex() {
return chapterIndex;
}
public void setChapterIndex(Integer chapterIndex) {
this.chapterIndex = chapterIndex;
}
public String getChapterTitle() {
return chapterTitle;
}
public void setChapterTitle(String chapterTitle) {
this.chapterTitle = chapterTitle;
}
public Integer getWordPosition() {
return wordPosition;
}
public void setWordPosition(Integer wordPosition) {
this.wordPosition = wordPosition;
}
public Integer getCharacterPosition() {
return characterPosition;
}
public void setCharacterPosition(Integer characterPosition) {
this.characterPosition = characterPosition;
}
public Double getPercentageComplete() {
return percentageComplete;
}
public void setPercentageComplete(Double percentageComplete) {
this.percentageComplete = percentageComplete;
}
public String getEpubCfi() {
return epubCfi;
}
public void setEpubCfi(String epubCfi) {
this.epubCfi = epubCfi;
}
public String getContextBefore() {
return contextBefore;
}
public void setContextBefore(String contextBefore) {
this.contextBefore = contextBefore;
}
public String getContextAfter() {
return contextAfter;
}
public void setContextAfter(String contextAfter) {
this.contextAfter = contextAfter;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReadingPosition)) return false;
ReadingPosition that = (ReadingPosition) o;
return id != null && id.equals(that.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String toString() {
return "ReadingPosition{" +
"id=" + id +
", storyId=" + (story != null ? story.getId() : null) +
", chapterIndex=" + chapterIndex +
", wordPosition=" + wordPosition +
", percentageComplete=" + percentageComplete +
'}';
}
}

View File

@@ -5,6 +5,7 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import java.time.LocalDateTime;
import java.util.HashSet;
@@ -24,6 +25,14 @@ public class Tag {
@Column(nullable = false, unique = true)
private String name;
@Size(max = 7, message = "Color must be a valid hex color code")
@Column(length = 7)
private String color; // hex color like #3B82F6
@Size(max = 500, message = "Description must not exceed 500 characters")
@Column(length = 500)
private String description;
@ManyToMany(mappedBy = "tags")
@JsonBackReference("story-tags")
@@ -33,6 +42,10 @@ public class Tag {
@JsonBackReference("collection-tags")
private Set<Collection> collections = new HashSet<>();
@OneToMany(mappedBy = "canonicalTag", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference("tag-aliases")
private Set<TagAlias> aliases = new HashSet<>();
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
@@ -43,6 +56,12 @@ public class Tag {
this.name = name;
}
public Tag(String name, String color, String description) {
this.name = name;
this.color = color;
this.description = description;
}
// Getters and Setters
@@ -62,6 +81,22 @@ public class Tag {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Story> getStories() {
return stories;
@@ -79,6 +114,14 @@ public class Tag {
this.collections = collections;
}
public Set<TagAlias> getAliases() {
return aliases;
}
public void setAliases(Set<TagAlias> aliases) {
this.aliases = aliases;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}

View File

@@ -0,0 +1,113 @@
package com.storycove.entity;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "tag_aliases")
public class TagAlias {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@NotBlank(message = "Alias name is required")
@Size(max = 100, message = "Alias name must not exceed 100 characters")
@Column(name = "alias_name", nullable = false, unique = true)
private String aliasName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "canonical_tag_id", nullable = false)
@JsonManagedReference("tag-aliases")
private Tag canonicalTag;
@Column(name = "created_from_merge", nullable = false)
private Boolean createdFromMerge = false;
@CreationTimestamp
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;
public TagAlias() {}
public TagAlias(String aliasName, Tag canonicalTag) {
this.aliasName = aliasName;
this.canonicalTag = canonicalTag;
}
public TagAlias(String aliasName, Tag canonicalTag, Boolean createdFromMerge) {
this.aliasName = aliasName;
this.canonicalTag = canonicalTag;
this.createdFromMerge = createdFromMerge;
}
// Getters and Setters
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getAliasName() {
return aliasName;
}
public void setAliasName(String aliasName) {
this.aliasName = aliasName;
}
public Tag getCanonicalTag() {
return canonicalTag;
}
public void setCanonicalTag(Tag canonicalTag) {
this.canonicalTag = canonicalTag;
}
public Boolean getCreatedFromMerge() {
return createdFromMerge;
}
public void setCreatedFromMerge(Boolean createdFromMerge) {
this.createdFromMerge = createdFromMerge;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TagAlias)) return false;
TagAlias tagAlias = (TagAlias) o;
return id != null && id.equals(tagAlias.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@Override
public String toString() {
return "TagAlias{" +
"id=" + id +
", aliasName='" + aliasName + '\'' +
", canonicalTag=" + (canonicalTag != null ? canonicalTag.getName() : null) +
", createdFromMerge=" + createdFromMerge +
'}';
}
}

View File

@@ -4,7 +4,6 @@ import com.storycove.entity.Author;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

View File

@@ -2,7 +2,6 @@ package com.storycove.repository;
import com.storycove.entity.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

View File

@@ -0,0 +1,57 @@
package com.storycove.repository;
import com.storycove.entity.ReadingPosition;
import com.storycove.entity.Story;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface ReadingPositionRepository extends JpaRepository<ReadingPosition, UUID> {
Optional<ReadingPosition> findByStoryId(UUID storyId);
Optional<ReadingPosition> findByStory(Story story);
List<ReadingPosition> findByStoryIdIn(List<UUID> storyIds);
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.story.id = :storyId ORDER BY rp.updatedAt DESC")
List<ReadingPosition> findByStoryIdOrderByUpdatedAtDesc(@Param("storyId") UUID storyId);
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete >= :minPercentage")
List<ReadingPosition> findByMinimumPercentageComplete(@Param("minPercentage") Double minPercentage);
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete >= 95.0")
List<ReadingPosition> findCompletedReadings();
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.percentageComplete > 0 AND rp.percentageComplete < 95.0")
List<ReadingPosition> findInProgressReadings();
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.updatedAt >= :since ORDER BY rp.updatedAt DESC")
List<ReadingPosition> findRecentlyUpdated(@Param("since") LocalDateTime since);
@Query("SELECT rp FROM ReadingPosition rp ORDER BY rp.updatedAt DESC")
List<ReadingPosition> findAllOrderByUpdatedAtDesc();
@Query("SELECT COUNT(rp) FROM ReadingPosition rp WHERE rp.percentageComplete >= 95.0")
long countCompletedReadings();
@Query("SELECT COUNT(rp) FROM ReadingPosition rp WHERE rp.percentageComplete > 0 AND rp.percentageComplete < 95.0")
long countInProgressReadings();
@Query("SELECT AVG(rp.percentageComplete) FROM ReadingPosition rp WHERE rp.percentageComplete > 0")
Double findAverageReadingProgress();
@Query("SELECT rp FROM ReadingPosition rp WHERE rp.epubCfi IS NOT NULL")
List<ReadingPosition> findPositionsWithEpubCfi();
boolean existsByStoryId(UUID storyId);
void deleteByStoryId(UUID storyId);
}

View File

@@ -7,7 +7,6 @@ import com.storycove.entity.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@@ -119,4 +118,126 @@ public interface StoryRepository extends JpaRepository<Story, UUID> {
@Query("SELECT s FROM Story s WHERE UPPER(s.title) = UPPER(:title) AND UPPER(s.author.name) = UPPER(:authorName)")
List<Story> findByTitleAndAuthorNameIgnoreCase(@Param("title") String title, @Param("authorName") String authorName);
/**
* Count all stories for random selection (no filters)
*/
@Query(value = "SELECT COUNT(*) FROM stories", nativeQuery = true)
long countAllStories();
/**
* Count stories matching tag name filter for random selection
*/
@Query(value = "SELECT COUNT(DISTINCT s.id) FROM stories s " +
"JOIN story_tags st ON s.id = st.story_id " +
"JOIN tags t ON st.tag_id = t.id " +
"WHERE UPPER(t.name) = UPPER(?1)",
nativeQuery = true)
long countStoriesByTagName(String tagName);
/**
* Find a random story using offset (no filters)
*/
@Query(value = "SELECT s.* FROM stories s ORDER BY s.id OFFSET ?1 LIMIT 1", nativeQuery = true)
Optional<Story> findRandomStory(long offset);
/**
* Find a random story matching tag name filter using offset
*/
@Query(value = "SELECT s.* FROM stories s " +
"JOIN story_tags st ON s.id = st.story_id " +
"JOIN tags t ON st.tag_id = t.id " +
"WHERE UPPER(t.name) = UPPER(?1) " +
"ORDER BY s.id OFFSET ?2 LIMIT 1",
nativeQuery = true)
Optional<Story> findRandomStoryByTagName(String tagName, long offset);
/**
* Count stories matching multiple tags (ALL tags must be present)
*/
@Query(value = "SELECT COUNT(*) FROM (" +
" SELECT DISTINCT s.id FROM stories s " +
" JOIN story_tags st ON s.id = st.story_id " +
" JOIN tags t ON st.tag_id = t.id " +
" WHERE UPPER(t.name) IN (?1) " +
" GROUP BY s.id " +
" HAVING COUNT(DISTINCT t.name) = ?2" +
") as matched_stories",
nativeQuery = true)
long countStoriesByMultipleTags(List<String> upperCaseTagNames, int tagCount);
/**
* Find random story matching multiple tags (ALL tags must be present)
*/
@Query(value = "SELECT s.* FROM stories s " +
"JOIN story_tags st ON s.id = st.story_id " +
"JOIN tags t ON st.tag_id = t.id " +
"WHERE UPPER(t.name) IN (?1) " +
"GROUP BY s.id, s.title, s.summary, s.description, s.content_html, s.content_plain, s.source_url, s.cover_path, s.word_count, s.rating, s.volume, s.is_read, s.reading_position, s.last_read_at, s.author_id, s.series_id, s.created_at, s.updated_at " +
"HAVING COUNT(DISTINCT t.name) = ?2 " +
"ORDER BY s.id OFFSET ?3 LIMIT 1",
nativeQuery = true)
Optional<Story> findRandomStoryByMultipleTags(List<String> upperCaseTagNames, int tagCount, long offset);
/**
* Count stories matching text search (title, author, tags)
*/
@Query(value = "SELECT COUNT(DISTINCT s.id) FROM stories s " +
"LEFT JOIN authors a ON s.author_id = a.id " +
"LEFT JOIN story_tags st ON s.id = st.story_id " +
"LEFT JOIN tags t ON st.tag_id = t.id " +
"WHERE (UPPER(s.title) LIKE UPPER(?1) OR UPPER(a.name) LIKE UPPER(?1) OR UPPER(t.name) LIKE UPPER(?1))",
nativeQuery = true)
long countStoriesByTextSearch(String searchPattern);
/**
* Find random story matching text search (title, author, tags)
*/
@Query(value = "SELECT DISTINCT s.* FROM stories s " +
"LEFT JOIN authors a ON s.author_id = a.id " +
"LEFT JOIN story_tags st ON s.id = st.story_id " +
"LEFT JOIN tags t ON st.tag_id = t.id " +
"WHERE (UPPER(s.title) LIKE UPPER(?1) OR UPPER(a.name) LIKE UPPER(?1) OR UPPER(t.name) LIKE UPPER(?1)) " +
"ORDER BY s.id OFFSET ?2 LIMIT 1",
nativeQuery = true)
Optional<Story> findRandomStoryByTextSearch(String searchPattern, long offset);
/**
* Count stories matching both text search AND tags
*/
@Query(value = "SELECT COUNT(DISTINCT s.id) FROM stories s " +
"LEFT JOIN authors a ON s.author_id = a.id " +
"LEFT JOIN story_tags st ON s.id = st.story_id " +
"LEFT JOIN tags t ON st.tag_id = t.id " +
"WHERE (UPPER(s.title) LIKE UPPER(?1) OR UPPER(a.name) LIKE UPPER(?1) OR UPPER(t.name) LIKE UPPER(?1)) " +
"AND s.id IN (" +
" SELECT s2.id FROM stories s2 " +
" JOIN story_tags st2 ON s2.id = st2.story_id " +
" JOIN tags t2 ON st2.tag_id = t2.id " +
" WHERE UPPER(t2.name) IN (?2) " +
" GROUP BY s2.id " +
" HAVING COUNT(DISTINCT t2.name) = ?3" +
")",
nativeQuery = true)
long countStoriesByTextSearchAndTags(String searchPattern, List<String> upperCaseTagNames, int tagCount);
/**
* Find random story matching both text search AND tags
*/
@Query(value = "SELECT DISTINCT s.* FROM stories s " +
"LEFT JOIN authors a ON s.author_id = a.id " +
"LEFT JOIN story_tags st ON s.id = st.story_id " +
"LEFT JOIN tags t ON st.tag_id = t.id " +
"WHERE (UPPER(s.title) LIKE UPPER(?1) OR UPPER(a.name) LIKE UPPER(?1) OR UPPER(t.name) LIKE UPPER(?1)) " +
"AND s.id IN (" +
" SELECT s2.id FROM stories s2 " +
" JOIN story_tags st2 ON s2.id = st2.story_id " +
" JOIN tags t2 ON st2.tag_id = t2.id " +
" WHERE UPPER(t2.name) IN (?2) " +
" GROUP BY s2.id " +
" HAVING COUNT(DISTINCT t2.name) = ?3" +
") " +
"ORDER BY s.id OFFSET ?4 LIMIT 1",
nativeQuery = true)
Optional<Story> findRandomStoryByTextSearchAndTags(String searchPattern, List<String> upperCaseTagNames, int tagCount, long offset);
}

View File

@@ -0,0 +1,60 @@
package com.storycove.repository;
import com.storycove.entity.TagAlias;
import com.storycove.entity.Tag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public interface TagAliasRepository extends JpaRepository<TagAlias, UUID> {
/**
* Find alias by exact alias name (case-insensitive)
*/
@Query("SELECT ta FROM TagAlias ta WHERE LOWER(ta.aliasName) = LOWER(:aliasName)")
Optional<TagAlias> findByAliasNameIgnoreCase(@Param("aliasName") String aliasName);
/**
* Find all aliases for a specific canonical tag
*/
List<TagAlias> findByCanonicalTag(Tag canonicalTag);
/**
* Find all aliases for a specific canonical tag ID
*/
@Query("SELECT ta FROM TagAlias ta WHERE ta.canonicalTag.id = :tagId")
List<TagAlias> findByCanonicalTagId(@Param("tagId") UUID tagId);
/**
* Find aliases created from merge operations
*/
List<TagAlias> findByCreatedFromMergeTrue();
/**
* Check if an alias name already exists
*/
boolean existsByAliasNameIgnoreCase(String aliasName);
/**
* Delete all aliases for a specific tag
*/
void deleteByCanonicalTag(Tag canonicalTag);
/**
* Count aliases for a specific tag
*/
@Query("SELECT COUNT(ta) FROM TagAlias ta WHERE ta.canonicalTag.id = :tagId")
long countByCanonicalTagId(@Param("tagId") UUID tagId);
/**
* Find aliases that start with the given prefix (case-insensitive)
*/
@Query("SELECT ta FROM TagAlias ta WHERE LOWER(ta.aliasName) LIKE LOWER(CONCAT(:prefix, '%'))")
List<TagAlias> findByAliasNameStartingWithIgnoreCase(@Param("prefix") String prefix);
}

View File

@@ -17,8 +17,12 @@ public interface TagRepository extends JpaRepository<Tag, UUID> {
Optional<Tag> findByName(String name);
Optional<Tag> findByNameIgnoreCase(String name);
boolean existsByName(String name);
boolean existsByNameIgnoreCase(String name);
List<Tag> findByNameContainingIgnoreCase(String name);
Page<Tag> findByNameContainingIgnoreCase(String name, Pageable pageable);

View File

@@ -3,6 +3,7 @@ package com.storycove.security;
import com.storycove.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -28,13 +29,27 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
String token = null;
// First try to get token from Authorization header
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
token = authHeader.substring(7);
}
// If no token in header, try to get from cookies
if (token == null) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("token".equals(cookie.getName())) {
token = cookie.getValue();
break;
}
}
}
}
if (token != null && jwtUtil.validateToken(token) && !jwtUtil.isTokenExpired(token)) {
String subject = jwtUtil.getSubjectFromToken(token);

View File

@@ -242,7 +242,7 @@ public class AuthorService {
rating, author.getName(), author.getAuthorRating());
author.setAuthorRating(rating);
Author savedAuthor = authorRepository.save(author);
authorRepository.save(author);
// Flush and refresh to ensure the entity is up-to-date
authorRepository.flush();

View File

@@ -1,6 +1,8 @@
package com.storycove.service;
import com.storycove.dto.SearchResultDto;
import com.storycove.dto.StoryReadingDto;
import com.storycove.dto.TagDto;
import com.storycove.entity.Collection;
import com.storycove.entity.CollectionStory;
import com.storycove.entity.Story;
@@ -9,14 +11,10 @@ import com.storycove.repository.CollectionRepository;
import com.storycove.repository.CollectionStoryRepository;
import com.storycove.repository.StoryRepository;
import com.storycove.repository.TagRepository;
import com.storycove.service.exception.DuplicateResourceException;
import com.storycove.service.exception.ResourceNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -264,7 +262,7 @@ public class CollectionService {
*/
@Transactional
public void reorderStories(UUID collectionId, List<Map<String, Object>> storyOrders) {
Collection collection = findByIdBasic(collectionId);
findByIdBasic(collectionId); // Validate collection exists
// Two-phase update to avoid unique constraint violations:
// Phase 1: Set all positions to negative values (temporary)
@@ -336,7 +334,7 @@ public class CollectionService {
);
return Map.of(
"story", story,
"story", convertToReadingDto(story),
"collection", collectionContext
);
}
@@ -430,4 +428,49 @@ public class CollectionService {
public List<Collection> findAllForIndexing() {
return collectionRepository.findAllActiveCollections();
}
private StoryReadingDto convertToReadingDto(Story story) {
StoryReadingDto dto = new StoryReadingDto();
dto.setId(story.getId());
dto.setTitle(story.getTitle());
dto.setSummary(story.getSummary());
dto.setDescription(story.getDescription());
dto.setContentHtml(story.getContentHtml());
dto.setSourceUrl(story.getSourceUrl());
dto.setCoverPath(story.getCoverPath());
dto.setWordCount(story.getWordCount());
dto.setRating(story.getRating());
dto.setVolume(story.getVolume());
dto.setCreatedAt(story.getCreatedAt());
dto.setUpdatedAt(story.getUpdatedAt());
// Reading progress fields
dto.setIsRead(story.getIsRead());
dto.setReadingPosition(story.getReadingPosition());
dto.setLastReadAt(story.getLastReadAt());
if (story.getAuthor() != null) {
dto.setAuthorId(story.getAuthor().getId());
dto.setAuthorName(story.getAuthor().getName());
}
if (story.getSeries() != null) {
dto.setSeriesId(story.getSeries().getId());
dto.setSeriesName(story.getSeries().getName());
}
dto.setTags(story.getTags().stream()
.map(this::convertTagToDto)
.collect(Collectors.toList()));
return dto;
}
private TagDto convertTagToDto(Tag tag) {
TagDto dto = new TagDto();
dto.setId(tag.getId());
dto.setName(tag.getName());
dto.setStoryCount(tag.getStories().size());
return dto;
}
}

View File

@@ -0,0 +1,584 @@
package com.storycove.service;
import com.storycove.dto.EPUBExportRequest;
import com.storycove.entity.Collection;
import com.storycove.entity.ReadingPosition;
import com.storycove.entity.Story;
import com.storycove.repository.ReadingPositionRepository;
import com.storycove.service.exception.ResourceNotFoundException;
import nl.siegmann.epublib.domain.*;
import nl.siegmann.epublib.epub.EpubWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@Transactional
public class EPUBExportService {
private final StoryService storyService;
private final ReadingPositionRepository readingPositionRepository;
private final CollectionService collectionService;
@Autowired
public EPUBExportService(StoryService storyService,
ReadingPositionRepository readingPositionRepository,
CollectionService collectionService) {
this.storyService = storyService;
this.readingPositionRepository = readingPositionRepository;
this.collectionService = collectionService;
}
public Resource exportStoryAsEPUB(EPUBExportRequest request) throws IOException {
Story story = storyService.findById(request.getStoryId());
Book book = createEPUBBook(story, request);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
EpubWriter epubWriter = new EpubWriter();
epubWriter.write(book, outputStream);
return new ByteArrayResource(outputStream.toByteArray());
}
public Resource exportCollectionAsEPUB(UUID collectionId, EPUBExportRequest request) throws IOException {
Collection collection = collectionService.findById(collectionId);
List<Story> stories = collection.getCollectionStories().stream()
.sorted((cs1, cs2) -> Integer.compare(cs1.getPosition(), cs2.getPosition()))
.map(cs -> cs.getStory())
.collect(Collectors.toList());
if (stories.isEmpty()) {
throw new ResourceNotFoundException("Collection contains no stories to export");
}
Book book = createCollectionEPUBBook(collection, stories, request);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
EpubWriter epubWriter = new EpubWriter();
epubWriter.write(book, outputStream);
return new ByteArrayResource(outputStream.toByteArray());
}
private Book createEPUBBook(Story story, EPUBExportRequest request) throws IOException {
Book book = new Book();
setupMetadata(book, story, request);
addCoverImage(book, story, request);
addContent(book, story, request);
addReadingPosition(book, story, request);
return book;
}
private Book createCollectionEPUBBook(Collection collection, List<Story> stories, EPUBExportRequest request) throws IOException {
Book book = new Book();
setupCollectionMetadata(book, collection, stories, request);
addCollectionCoverImage(book, collection, request);
addCollectionContent(book, stories, request);
return book;
}
private void setupMetadata(Book book, Story story, EPUBExportRequest request) {
Metadata metadata = book.getMetadata();
String title = request.getCustomTitle() != null ?
request.getCustomTitle() : story.getTitle();
metadata.addTitle(title);
String authorName = request.getCustomAuthor() != null ?
request.getCustomAuthor() :
(story.getAuthor() != null ? story.getAuthor().getName() : "Unknown Author");
metadata.addAuthor(new Author(authorName));
metadata.setLanguage(request.getLanguage() != null ? request.getLanguage() : "en");
metadata.addIdentifier(new Identifier("storycove", story.getId().toString()));
if (story.getDescription() != null) {
metadata.addDescription(story.getDescription());
}
if (request.getIncludeMetadata()) {
metadata.addDate(new Date(java.util.Date.from(
story.getCreatedAt().atZone(java.time.ZoneId.systemDefault()).toInstant()
), Date.Event.CREATION));
if (story.getSeries() != null) {
// Add series and metadata info to description instead of using addMeta
StringBuilder description = new StringBuilder();
if (story.getDescription() != null) {
description.append(story.getDescription()).append("\n\n");
}
description.append("Series: ").append(story.getSeries().getName());
if (story.getVolume() != null) {
description.append(" (Volume ").append(story.getVolume()).append(")");
}
description.append("\n");
if (story.getWordCount() != null) {
description.append("Word Count: ").append(story.getWordCount()).append("\n");
}
if (story.getRating() != null) {
description.append("Rating: ").append(story.getRating()).append("/5\n");
}
if (!story.getTags().isEmpty()) {
String tags = story.getTags().stream()
.map(tag -> tag.getName())
.reduce((a, b) -> a + ", " + b)
.orElse("");
description.append("Tags: ").append(tags).append("\n");
}
description.append("\nGenerated by StoryCove on ")
.append(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
metadata.addDescription(description.toString());
}
}
if (request.getCustomMetadata() != null && !request.getCustomMetadata().isEmpty()) {
// Add custom metadata to description since addMeta doesn't exist
StringBuilder customDesc = new StringBuilder();
for (String customMeta : request.getCustomMetadata()) {
String[] parts = customMeta.split(":", 2);
if (parts.length == 2) {
customDesc.append(parts[0].trim()).append(": ").append(parts[1].trim()).append("\n");
}
}
if (customDesc.length() > 0) {
String existingDesc = metadata.getDescriptions().isEmpty() ? "" : metadata.getDescriptions().get(0);
metadata.addDescription(existingDesc + "\n" + customDesc.toString());
}
}
}
private void addCoverImage(Book book, Story story, EPUBExportRequest request) {
if (!request.getIncludeCoverImage() || story.getCoverPath() == null) {
return;
}
try {
Path coverPath = Paths.get(story.getCoverPath());
if (Files.exists(coverPath)) {
byte[] coverImageData = Files.readAllBytes(coverPath);
String mimeType = Files.probeContentType(coverPath);
if (mimeType == null) {
mimeType = "image/jpeg";
}
nl.siegmann.epublib.domain.Resource coverResource =
new nl.siegmann.epublib.domain.Resource(coverImageData, "cover.jpg");
book.setCoverImage(coverResource);
}
} catch (IOException e) {
// Skip cover image on error
}
}
private void addContent(Book book, Story story, EPUBExportRequest request) {
String content = story.getContentHtml();
if (content == null) {
content = story.getContentPlain() != null ?
"<p>" + story.getContentPlain().replace("\n", "</p><p>") + "</p>" :
"<p>No content available</p>";
}
if (request.getSplitByChapters()) {
addChapterizedContent(book, content, request);
} else {
addSingleChapterContent(book, content, story);
}
}
private void addSingleChapterContent(Book book, String content, Story story) {
String html = createChapterHTML(story.getTitle(), content);
nl.siegmann.epublib.domain.Resource chapterResource =
new nl.siegmann.epublib.domain.Resource(html.getBytes(), "chapter.html");
book.addSection(story.getTitle(), chapterResource);
}
private void addChapterizedContent(Book book, String content, EPUBExportRequest request) {
Document doc = Jsoup.parse(content);
Elements chapters = doc.select("div.chapter, h1, h2, h3");
if (chapters.isEmpty()) {
List<String> paragraphs = splitByWords(content,
request.getMaxWordsPerChapter() != null ? request.getMaxWordsPerChapter() : 2000);
for (int i = 0; i < paragraphs.size(); i++) {
String chapterTitle = "Chapter " + (i + 1);
String html = createChapterHTML(chapterTitle, paragraphs.get(i));
nl.siegmann.epublib.domain.Resource chapterResource =
new nl.siegmann.epublib.domain.Resource(html.getBytes(), "chapter" + (i + 1) + ".html");
book.addSection(chapterTitle, chapterResource);
}
} else {
for (int i = 0; i < chapters.size(); i++) {
Element chapter = chapters.get(i);
String chapterTitle = chapter.text();
if (chapterTitle.trim().isEmpty()) {
chapterTitle = "Chapter " + (i + 1);
}
String chapterContent = chapter.html();
String html = createChapterHTML(chapterTitle, chapterContent);
nl.siegmann.epublib.domain.Resource chapterResource =
new nl.siegmann.epublib.domain.Resource(html.getBytes(), "chapter" + (i + 1) + ".html");
book.addSection(chapterTitle, chapterResource);
}
}
}
private List<String> splitByWords(String content, int maxWordsPerChapter) {
String[] words = content.split("\\s+");
List<String> chapters = new ArrayList<>();
StringBuilder currentChapter = new StringBuilder();
int wordCount = 0;
for (String word : words) {
currentChapter.append(word).append(" ");
wordCount++;
if (wordCount >= maxWordsPerChapter) {
chapters.add(currentChapter.toString().trim());
currentChapter = new StringBuilder();
wordCount = 0;
}
}
if (currentChapter.length() > 0) {
chapters.add(currentChapter.toString().trim());
}
return chapters;
}
private String createChapterHTML(String title, String content) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" " +
"\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
"<head>" +
"<title>" + escapeHtml(title) + "</title>" +
"<style type=\"text/css\">" +
"body { font-family: serif; margin: 1em; }" +
"h1 { text-align: center; }" +
"p { text-indent: 1em; margin: 0.5em 0; }" +
"</style>" +
"</head>" +
"<body>" +
"<h1>" + escapeHtml(title) + "</h1>" +
fixHtmlForXhtml(content) +
"</body>" +
"</html>";
}
private void addReadingPosition(Book book, Story story, EPUBExportRequest request) {
if (!request.getIncludeReadingPosition()) {
return;
}
Optional<ReadingPosition> positionOpt = readingPositionRepository.findByStoryId(story.getId());
if (positionOpt.isPresent()) {
ReadingPosition position = positionOpt.get();
Metadata metadata = book.getMetadata();
// Add reading position to description since addMeta doesn't exist
StringBuilder positionDesc = new StringBuilder();
if (position.getEpubCfi() != null) {
positionDesc.append("EPUB CFI: ").append(position.getEpubCfi()).append("\n");
}
if (position.getChapterIndex() != null && position.getWordPosition() != null) {
positionDesc.append("Reading Position: Chapter ")
.append(position.getChapterIndex())
.append(", Word ").append(position.getWordPosition()).append("\n");
}
if (position.getPercentageComplete() != null) {
positionDesc.append("Reading Progress: ")
.append(String.format("%.1f%%", position.getPercentageComplete())).append("\n");
}
positionDesc.append("Last Read: ")
.append(position.getUpdatedAt().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
String existingDesc = metadata.getDescriptions().isEmpty() ? "" : metadata.getDescriptions().get(0);
metadata.addDescription(existingDesc + "\n\n--- Reading Position ---\n" + positionDesc.toString());
}
}
private String fixHtmlForXhtml(String html) {
if (html == null) return "";
// Fix common XHTML validation issues
String fixed = html
// Fix self-closing tags to be XHTML compliant
.replaceAll("<br>", "<br />")
.replaceAll("<hr>", "<hr />")
.replaceAll("<img([^>]*)>", "<img$1 />")
.replaceAll("<input([^>]*)>", "<input$1 />")
.replaceAll("<area([^>]*)>", "<area$1 />")
.replaceAll("<base([^>]*)>", "<base$1 />")
.replaceAll("<col([^>]*)>", "<col$1 />")
.replaceAll("<embed([^>]*)>", "<embed$1 />")
.replaceAll("<link([^>]*)>", "<link$1 />")
.replaceAll("<meta([^>]*)>", "<meta$1 />")
.replaceAll("<param([^>]*)>", "<param$1 />")
.replaceAll("<source([^>]*)>", "<source$1 />")
.replaceAll("<track([^>]*)>", "<track$1 />")
.replaceAll("<wbr([^>]*)>", "<wbr$1 />");
return fixed;
}
private String escapeHtml(String text) {
if (text == null) return "";
return text.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
public String getEPUBFilename(Story story) {
StringBuilder filename = new StringBuilder();
if (story.getAuthor() != null) {
filename.append(sanitizeFilename(story.getAuthor().getName()))
.append(" - ");
}
filename.append(sanitizeFilename(story.getTitle()));
if (story.getSeries() != null && story.getVolume() != null) {
filename.append(" (")
.append(sanitizeFilename(story.getSeries().getName()))
.append(" ")
.append(story.getVolume())
.append(")");
}
filename.append(".epub");
return filename.toString();
}
private String sanitizeFilename(String filename) {
if (filename == null) return "unknown";
return filename.replaceAll("[^a-zA-Z0-9._\\- ]", "")
.trim()
.replaceAll("\\s+", "_");
}
private void setupCollectionMetadata(Book book, Collection collection, List<Story> stories, EPUBExportRequest request) {
Metadata metadata = book.getMetadata();
String title = request.getCustomTitle() != null ?
request.getCustomTitle() : collection.getName();
metadata.addTitle(title);
// Use collection creator as author, or combine story authors
String authorName = "Collection";
if (stories.size() == 1) {
Story story = stories.get(0);
authorName = story.getAuthor() != null ? story.getAuthor().getName() : "Unknown Author";
} else {
// For multiple stories, use "Various Authors" or collection name
authorName = "Various Authors";
}
if (request.getCustomAuthor() != null) {
authorName = request.getCustomAuthor();
}
metadata.addAuthor(new Author(authorName));
metadata.setLanguage(request.getLanguage() != null ? request.getLanguage() : "en");
metadata.addIdentifier(new Identifier("storycove-collection", collection.getId().toString()));
// Create description from collection description and story list
StringBuilder description = new StringBuilder();
if (collection.getDescription() != null && !collection.getDescription().trim().isEmpty()) {
description.append(collection.getDescription()).append("\n\n");
}
description.append("This collection contains ").append(stories.size()).append(" stories:\n");
for (int i = 0; i < stories.size() && i < 10; i++) {
Story story = stories.get(i);
description.append((i + 1)).append(". ").append(story.getTitle());
if (story.getAuthor() != null) {
description.append(" by ").append(story.getAuthor().getName());
}
description.append("\n");
}
if (stories.size() > 10) {
description.append("... and ").append(stories.size() - 10).append(" more stories.");
}
metadata.addDescription(description.toString());
if (request.getIncludeMetadata()) {
metadata.addDate(new Date(java.util.Date.from(
collection.getCreatedAt().atZone(java.time.ZoneId.systemDefault()).toInstant()
), Date.Event.CREATION));
// Add collection statistics to description
int totalWordCount = stories.stream().mapToInt(s -> s.getWordCount() != null ? s.getWordCount() : 0).sum();
description.append("\n\nTotal Word Count: ").append(totalWordCount);
description.append("\nGenerated by StoryCove on ")
.append(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
metadata.addDescription(description.toString());
}
}
private void addCollectionCoverImage(Book book, Collection collection, EPUBExportRequest request) {
if (!request.getIncludeCoverImage()) {
return;
}
try {
// Try to use collection cover first
if (collection.getCoverImagePath() != null) {
Path coverPath = Paths.get(collection.getCoverImagePath());
if (Files.exists(coverPath)) {
byte[] coverImageData = Files.readAllBytes(coverPath);
String mimeType = Files.probeContentType(coverPath);
if (mimeType == null) {
mimeType = "image/jpeg";
}
nl.siegmann.epublib.domain.Resource coverResource =
new nl.siegmann.epublib.domain.Resource(coverImageData, "collection-cover.jpg");
book.setCoverImage(coverResource);
return;
}
}
// TODO: Could generate a composite cover from story covers
// For now, skip cover if collection doesn't have one
} catch (IOException e) {
// Skip cover image on error
}
}
private void addCollectionContent(Book book, List<Story> stories, EPUBExportRequest request) {
// Create table of contents chapter
StringBuilder tocContent = new StringBuilder();
tocContent.append("<h1>Table of Contents</h1>\n<ul>\n");
for (int i = 0; i < stories.size(); i++) {
Story story = stories.get(i);
tocContent.append("<li><a href=\"#story").append(i + 1).append("\">")
.append(escapeHtml(story.getTitle()));
if (story.getAuthor() != null) {
tocContent.append(" by ").append(escapeHtml(story.getAuthor().getName()));
}
tocContent.append("</a></li>\n");
}
tocContent.append("</ul>\n");
String tocHtml = createChapterHTML("Table of Contents", tocContent.toString());
nl.siegmann.epublib.domain.Resource tocResource =
new nl.siegmann.epublib.domain.Resource(tocHtml.getBytes(), "toc.html");
book.addSection("Table of Contents", tocResource);
// Add each story as a chapter
for (int i = 0; i < stories.size(); i++) {
Story story = stories.get(i);
String storyContent = story.getContentHtml();
if (storyContent == null) {
storyContent = story.getContentPlain() != null ?
"<p>" + story.getContentPlain().replace("\n", "</p><p>") + "</p>" :
"<p>No content available</p>";
}
// Add story metadata header
StringBuilder storyHtml = new StringBuilder();
storyHtml.append("<div id=\"story").append(i + 1).append("\">\n");
storyHtml.append("<h1>").append(escapeHtml(story.getTitle())).append("</h1>\n");
if (story.getAuthor() != null) {
storyHtml.append("<p><em>by ").append(escapeHtml(story.getAuthor().getName())).append("</em></p>\n");
}
if (story.getDescription() != null && !story.getDescription().trim().isEmpty()) {
storyHtml.append("<div class=\"summary\">\n")
.append("<p>").append(escapeHtml(story.getDescription())).append("</p>\n")
.append("</div>\n");
}
storyHtml.append("<hr />\n");
storyHtml.append(fixHtmlForXhtml(storyContent));
storyHtml.append("</div>\n");
String chapterTitle = story.getTitle();
if (story.getAuthor() != null) {
chapterTitle += " by " + story.getAuthor().getName();
}
String html = createChapterHTML(chapterTitle, storyHtml.toString());
nl.siegmann.epublib.domain.Resource storyResource =
new nl.siegmann.epublib.domain.Resource(html.getBytes(), "story" + (i + 1) + ".html");
book.addSection(chapterTitle, storyResource);
}
}
public boolean canExportStory(UUID storyId) {
try {
Story story = storyService.findById(storyId);
return story.getContentHtml() != null || story.getContentPlain() != null;
} catch (ResourceNotFoundException e) {
return false;
}
}
public String getCollectionEPUBFilename(Collection collection) {
StringBuilder filename = new StringBuilder();
filename.append(sanitizeFilename(collection.getName()));
filename.append("_collection.epub");
return filename.toString();
}
}

View File

@@ -0,0 +1,520 @@
package com.storycove.service;
import com.storycove.dto.EPUBImportRequest;
import com.storycove.dto.EPUBImportResponse;
import com.storycove.dto.ReadingPositionDto;
import com.storycove.entity.*;
import com.storycove.repository.ReadingPositionRepository;
import com.storycove.service.exception.InvalidFileException;
import com.storycove.service.exception.ResourceNotFoundException;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Metadata;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class EPUBImportService {
private final StoryService storyService;
private final AuthorService authorService;
private final SeriesService seriesService;
private final TagService tagService;
private final ReadingPositionRepository readingPositionRepository;
private final HtmlSanitizationService sanitizationService;
private final ImageService imageService;
@Autowired
public EPUBImportService(StoryService storyService,
AuthorService authorService,
SeriesService seriesService,
TagService tagService,
ReadingPositionRepository readingPositionRepository,
HtmlSanitizationService sanitizationService,
ImageService imageService) {
this.storyService = storyService;
this.authorService = authorService;
this.seriesService = seriesService;
this.tagService = tagService;
this.readingPositionRepository = readingPositionRepository;
this.sanitizationService = sanitizationService;
this.imageService = imageService;
}
public EPUBImportResponse importEPUB(EPUBImportRequest request) {
try {
MultipartFile epubFile = request.getEpubFile();
if (epubFile == null || epubFile.isEmpty()) {
return EPUBImportResponse.error("EPUB file is required");
}
if (!isValidEPUBFile(epubFile)) {
return EPUBImportResponse.error("Invalid EPUB file format");
}
Book book = parseEPUBFile(epubFile);
Story story = createStoryFromEPUB(book, request);
Story savedStory = storyService.create(story);
EPUBImportResponse response = EPUBImportResponse.success(savedStory.getId(), savedStory.getTitle());
response.setWordCount(savedStory.getWordCount());
response.setTotalChapters(book.getSpine().size());
if (request.getPreserveReadingPosition() != null && request.getPreserveReadingPosition()) {
ReadingPosition readingPosition = extractReadingPosition(book, savedStory);
if (readingPosition != null) {
ReadingPosition savedPosition = readingPositionRepository.save(readingPosition);
response.setReadingPosition(convertToDto(savedPosition));
}
}
return response;
} catch (Exception e) {
return EPUBImportResponse.error("Failed to import EPUB: " + e.getMessage());
}
}
private boolean isValidEPUBFile(MultipartFile file) {
String filename = file.getOriginalFilename();
if (filename == null || !filename.toLowerCase().endsWith(".epub")) {
return false;
}
String contentType = file.getContentType();
return "application/epub+zip".equals(contentType) ||
"application/zip".equals(contentType) ||
contentType == null;
}
private Book parseEPUBFile(MultipartFile epubFile) throws IOException {
try (InputStream inputStream = epubFile.getInputStream()) {
EpubReader epubReader = new EpubReader();
return epubReader.readEpub(inputStream);
} catch (Exception e) {
throw new InvalidFileException("Failed to parse EPUB file: " + e.getMessage());
}
}
private Story createStoryFromEPUB(Book book, EPUBImportRequest request) {
Metadata metadata = book.getMetadata();
String title = extractTitle(metadata);
String authorName = extractAuthorName(metadata, request);
String description = extractDescription(metadata);
String content = extractContent(book);
Story story = new Story();
story.setTitle(title);
story.setDescription(description);
story.setContentHtml(sanitizationService.sanitize(content));
// Extract and process cover image
if (request.getExtractCover() == null || request.getExtractCover()) {
String coverPath = extractAndSaveCoverImage(book);
if (coverPath != null) {
story.setCoverPath(coverPath);
}
}
if (request.getAuthorId() != null) {
try {
Author author = authorService.findById(request.getAuthorId());
story.setAuthor(author);
} catch (ResourceNotFoundException e) {
if (request.getCreateMissingAuthor()) {
Author newAuthor = createAuthor(authorName);
story.setAuthor(newAuthor);
}
}
} else if (authorName != null && request.getCreateMissingAuthor()) {
Author author = findOrCreateAuthor(authorName);
story.setAuthor(author);
}
if (request.getSeriesId() != null && request.getSeriesVolume() != null) {
try {
Series series = seriesService.findById(request.getSeriesId());
story.setSeries(series);
story.setVolume(request.getSeriesVolume());
} catch (ResourceNotFoundException e) {
if (request.getCreateMissingSeries() && request.getSeriesName() != null) {
Series newSeries = createSeries(request.getSeriesName());
story.setSeries(newSeries);
story.setVolume(request.getSeriesVolume());
}
}
}
// Handle tags from request or extract from EPUB metadata
List<String> allTags = new ArrayList<>();
if (request.getTags() != null && !request.getTags().isEmpty()) {
allTags.addAll(request.getTags());
}
// Extract subjects/keywords from EPUB metadata
List<String> epubTags = extractTags(metadata);
if (epubTags != null && !epubTags.isEmpty()) {
allTags.addAll(epubTags);
}
// Remove duplicates and create tags
allTags.stream()
.distinct()
.forEach(tagName -> {
Tag tag = tagService.findOrCreate(tagName.trim());
story.addTag(tag);
});
// Extract additional metadata for potential future use
extractAdditionalMetadata(metadata, story);
return story;
}
private String extractTitle(Metadata metadata) {
List<String> titles = metadata.getTitles();
if (titles != null && !titles.isEmpty()) {
return titles.get(0);
}
return "Untitled EPUB";
}
private String extractAuthorName(Metadata metadata, EPUBImportRequest request) {
if (request.getAuthorName() != null && !request.getAuthorName().trim().isEmpty()) {
return request.getAuthorName().trim();
}
if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) {
return metadata.getAuthors().get(0).getFirstname() + " " + metadata.getAuthors().get(0).getLastname();
}
return "Unknown Author";
}
private String extractDescription(Metadata metadata) {
List<String> descriptions = metadata.getDescriptions();
if (descriptions != null && !descriptions.isEmpty()) {
return descriptions.get(0);
}
return null;
}
private List<String> extractTags(Metadata metadata) {
List<String> tags = new ArrayList<>();
// Extract subjects (main source of tags in EPUB)
List<String> subjects = metadata.getSubjects();
if (subjects != null && !subjects.isEmpty()) {
tags.addAll(subjects);
}
// Extract keywords from meta tags
String keywords = metadata.getMetaAttribute("keywords");
if (keywords != null && !keywords.trim().isEmpty()) {
String[] keywordArray = keywords.split("[,;]");
for (String keyword : keywordArray) {
String trimmed = keyword.trim();
if (!trimmed.isEmpty()) {
tags.add(trimmed);
}
}
}
// Extract genre information
String genre = metadata.getMetaAttribute("genre");
if (genre != null && !genre.trim().isEmpty()) {
tags.add(genre.trim());
}
return tags;
}
private void extractAdditionalMetadata(Metadata metadata, Story story) {
// Extract language (could be useful for future i18n)
String language = metadata.getLanguage();
if (language != null && !language.trim().isEmpty()) {
// Store as metadata in story description if needed
// For now, we'll just log it for potential future use
System.out.println("EPUB Language: " + language);
}
// Extract publisher information
List<String> publishers = metadata.getPublishers();
if (publishers != null && !publishers.isEmpty()) {
String publisher = publishers.get(0);
// Could append to description or store separately in future
System.out.println("EPUB Publisher: " + publisher);
}
// Extract publication date
List<nl.siegmann.epublib.domain.Date> dates = metadata.getDates();
if (dates != null && !dates.isEmpty()) {
for (nl.siegmann.epublib.domain.Date date : dates) {
System.out.println("EPUB Date (" + date.getEvent() + "): " + date.getValue());
}
}
// Extract ISBN or other identifiers
List<nl.siegmann.epublib.domain.Identifier> identifiers = metadata.getIdentifiers();
if (identifiers != null && !identifiers.isEmpty()) {
for (nl.siegmann.epublib.domain.Identifier identifier : identifiers) {
System.out.println("EPUB Identifier (" + identifier.getScheme() + "): " + identifier.getValue());
}
}
}
private String extractContent(Book book) {
StringBuilder contentBuilder = new StringBuilder();
List<SpineReference> spine = book.getSpine().getSpineReferences();
for (SpineReference spineRef : spine) {
try {
Resource resource = spineRef.getResource();
if (resource != null && resource.getData() != null) {
String html = new String(resource.getData(), "UTF-8");
Document doc = Jsoup.parse(html);
doc.select("script, style").remove();
String chapterContent = doc.body() != null ? doc.body().html() : doc.html();
contentBuilder.append("<div class=\"chapter\">")
.append(chapterContent)
.append("</div>");
}
} catch (Exception e) {
// Skip this chapter on error
continue;
}
}
return contentBuilder.toString();
}
private Author findOrCreateAuthor(String authorName) {
Optional<Author> existingAuthor = authorService.findByNameOptional(authorName);
if (existingAuthor.isPresent()) {
return existingAuthor.get();
}
return createAuthor(authorName);
}
private Author createAuthor(String authorName) {
Author author = new Author();
author.setName(authorName);
return authorService.create(author);
}
private Series createSeries(String seriesName) {
Series series = new Series();
series.setName(seriesName);
return seriesService.create(series);
}
private ReadingPosition extractReadingPosition(Book book, Story story) {
try {
Metadata metadata = book.getMetadata();
String positionMeta = metadata.getMetaAttribute("reading-position");
String cfiMeta = metadata.getMetaAttribute("epub-cfi");
ReadingPosition position = new ReadingPosition(story);
if (cfiMeta != null) {
position.setEpubCfi(cfiMeta);
}
if (positionMeta != null) {
try {
String[] parts = positionMeta.split(":");
if (parts.length >= 2) {
position.setChapterIndex(Integer.parseInt(parts[0]));
position.setWordPosition(Integer.parseInt(parts[1]));
}
} catch (NumberFormatException e) {
// Ignore invalid position format
}
}
return position;
} catch (Exception e) {
// Return null if no reading position found
return null;
}
}
private String extractAndSaveCoverImage(Book book) {
try {
Resource coverResource = book.getCoverImage();
if (coverResource != null && coverResource.getData() != null) {
// Create a temporary MultipartFile from the EPUB cover data
byte[] imageData = coverResource.getData();
String mediaType = coverResource.getMediaType() != null ?
coverResource.getMediaType().toString() : "image/jpeg";
// Determine file extension from media type
String extension = getExtensionFromMediaType(mediaType);
String filename = "epub_cover_" + System.currentTimeMillis() + "." + extension;
// Create a custom MultipartFile implementation for the cover image
MultipartFile coverFile = new EPUBCoverMultipartFile(imageData, filename, mediaType);
// Use ImageService to process and save the cover
return imageService.uploadImage(coverFile, ImageService.ImageType.COVER);
}
} catch (Exception e) {
// Log error but don't fail the import
System.err.println("Failed to extract cover image: " + e.getMessage());
}
return null;
}
private String getExtensionFromMediaType(String mediaType) {
switch (mediaType.toLowerCase()) {
case "image/jpeg":
case "image/jpg":
return "jpg";
case "image/png":
return "png";
case "image/gif":
return "gif";
case "image/webp":
return "webp";
default:
return "jpg"; // Default fallback
}
}
private ReadingPositionDto convertToDto(ReadingPosition position) {
if (position == null) return null;
ReadingPositionDto dto = new ReadingPositionDto();
dto.setId(position.getId());
dto.setStoryId(position.getStory().getId());
dto.setChapterIndex(position.getChapterIndex());
dto.setChapterTitle(position.getChapterTitle());
dto.setWordPosition(position.getWordPosition());
dto.setCharacterPosition(position.getCharacterPosition());
dto.setPercentageComplete(position.getPercentageComplete());
dto.setEpubCfi(position.getEpubCfi());
dto.setContextBefore(position.getContextBefore());
dto.setContextAfter(position.getContextAfter());
dto.setCreatedAt(position.getCreatedAt());
dto.setUpdatedAt(position.getUpdatedAt());
return dto;
}
public List<String> validateEPUBFile(MultipartFile file) {
List<String> errors = new ArrayList<>();
if (file == null || file.isEmpty()) {
errors.add("EPUB file is required");
return errors;
}
if (!isValidEPUBFile(file)) {
errors.add("Invalid EPUB file format. Only .epub files are supported");
}
if (file.getSize() > 100 * 1024 * 1024) { // 100MB limit
errors.add("EPUB file size exceeds 100MB limit");
}
try {
Book book = parseEPUBFile(file);
if (book.getMetadata() == null) {
errors.add("EPUB file contains no metadata");
}
if (book.getSpine() == null || book.getSpine().isEmpty()) {
errors.add("EPUB file contains no readable content");
}
} catch (Exception e) {
errors.add("Failed to parse EPUB file: " + e.getMessage());
}
return errors;
}
/**
* Custom MultipartFile implementation for EPUB cover images
*/
private static class EPUBCoverMultipartFile implements MultipartFile {
private final byte[] data;
private final String filename;
private final String contentType;
public EPUBCoverMultipartFile(byte[] data, String filename, String contentType) {
this.data = data;
this.filename = filename;
this.contentType = contentType;
}
@Override
public String getName() {
return "coverImage";
}
@Override
public String getOriginalFilename() {
return filename;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return data == null || data.length == 0;
}
@Override
public long getSize() {
return data != null ? data.length : 0;
}
@Override
public byte[] getBytes() {
return data;
}
@Override
public InputStream getInputStream() {
return new java.io.ByteArrayInputStream(data);
}
@Override
public void transferTo(java.io.File dest) throws IOException {
try (java.io.FileOutputStream fos = new java.io.FileOutputStream(dest)) {
fos.write(data);
}
}
@Override
public void transferTo(java.nio.file.Path dest) throws IOException {
java.nio.file.Files.write(dest, data);
}
}
}

View File

@@ -83,7 +83,26 @@ public class HtmlSanitizationService {
}
}
// Remove specific attributes (like href from links for security)
// Configure allowed protocols for specific attributes (e.g., href)
if (config.getAllowedProtocols() != null) {
for (Map.Entry<String, Map<String, List<String>>> tagEntry : config.getAllowedProtocols().entrySet()) {
String tag = tagEntry.getKey();
Map<String, List<String>> attributeProtocols = tagEntry.getValue();
if (attributeProtocols != null) {
for (Map.Entry<String, List<String>> attrEntry : attributeProtocols.entrySet()) {
String attribute = attrEntry.getKey();
List<String> protocols = attrEntry.getValue();
if (protocols != null) {
allowlist.addProtocols(tag, attribute, protocols.toArray(new String[0]));
}
}
}
}
}
// Remove specific attributes if needed (deprecated in favor of protocol control)
if (config.getRemovedAttributes() != null) {
for (Map.Entry<String, List<String>> entry : config.getRemovedAttributes().entrySet()) {
String tag = entry.getKey();

View File

@@ -1,5 +1,6 @@
package com.storycove.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -20,15 +21,23 @@ import java.util.UUID;
public class ImageService {
private static final Set<String> ALLOWED_CONTENT_TYPES = Set.of(
"image/jpeg", "image/jpg", "image/png", "image/webp"
"image/jpeg", "image/jpg", "image/png"
);
private static final Set<String> ALLOWED_EXTENSIONS = Set.of(
"jpg", "jpeg", "png", "webp"
"jpg", "jpeg", "png"
);
@Value("${storycove.images.upload-dir:/app/images}")
private String uploadDir;
private String baseUploadDir;
@Autowired
private LibraryService libraryService;
private String getUploadDir() {
String libraryPath = libraryService.getCurrentImagePath();
return baseUploadDir + libraryPath;
}
@Value("${storycove.images.cover.max-width:800}")
private int coverMaxWidth;
@@ -61,7 +70,7 @@ public class ImageService {
validateFile(file);
// Create directories if they don't exist
Path typeDir = Paths.get(uploadDir, imageType.getDirectory());
Path typeDir = Paths.get(getUploadDir(), imageType.getDirectory());
Files.createDirectories(typeDir);
// Generate unique filename
@@ -88,7 +97,7 @@ public class ImageService {
}
try {
Path fullPath = Paths.get(uploadDir, imagePath);
Path fullPath = Paths.get(getUploadDir(), imagePath);
return Files.deleteIfExists(fullPath);
} catch (IOException e) {
return false;
@@ -96,7 +105,7 @@ public class ImageService {
}
public Path getImagePath(String imagePath) {
return Paths.get(uploadDir, imagePath);
return Paths.get(getUploadDir(), imagePath);
}
public boolean imageExists(String imagePath) {
@@ -107,6 +116,19 @@ public class ImageService {
return Files.exists(getImagePath(imagePath));
}
public boolean imageExistsInLibrary(String imagePath, String libraryId) {
if (imagePath == null || imagePath.trim().isEmpty() || libraryId == null) {
return false;
}
return Files.exists(getImagePathInLibrary(imagePath, libraryId));
}
public Path getImagePathInLibrary(String imagePath, String libraryId) {
String libraryPath = libraryService.getImagePathForLibrary(libraryId);
return Paths.get(baseUploadDir + libraryPath, imagePath);
}
private void validateFile(MultipartFile file) throws IOException {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("File is empty");

View File

@@ -0,0 +1,73 @@
package com.storycove.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Base service class that provides library-aware database access.
*
* This approach is safer than routing at the datasource level because:
* 1. It doesn't interfere with Spring's initialization process
* 2. It allows fine-grained control over which operations are library-aware
* 3. It provides clear separation between authentication (uses default DB) and library operations
*/
@Component
public class LibraryAwareService {
@Autowired
private LibraryService libraryService;
@Autowired
@Qualifier("dataSource")
private DataSource defaultDataSource;
/**
* Get a database connection for the current active library.
* Falls back to default datasource if no library is active.
*/
public Connection getCurrentLibraryConnection() throws SQLException {
try {
// Try to get library-specific connection
DataSource libraryDataSource = libraryService.getCurrentDataSource();
return libraryDataSource.getConnection();
} catch (IllegalStateException e) {
// No active library - use default datasource
return defaultDataSource.getConnection();
}
}
/**
* Get a database connection for the default/fallback database.
* Use this for authentication and system-level operations.
*/
public Connection getDefaultConnection() throws SQLException {
return defaultDataSource.getConnection();
}
/**
* Check if a library is currently active
*/
public boolean hasActiveLibrary() {
try {
return libraryService.getCurrentLibraryId() != null;
} catch (Exception e) {
return false;
}
}
/**
* Get the current active library ID, or null if none
*/
public String getCurrentLibraryId() {
try {
return libraryService.getCurrentLibraryId();
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,862 @@
package com.storycove.service;
import com.storycove.entity.Library;
import com.storycove.dto.LibraryDto;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.typesense.api.Client;
import org.typesense.resources.Node;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class LibraryService implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(LibraryService.class);
@Value("${spring.datasource.url}")
private String baseDbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.password}")
private String dbPassword;
@Value("${typesense.host}")
private String typesenseHost;
@Value("${typesense.port}")
private String typesensePort;
@Value("${typesense.api-key}")
private String typesenseApiKey;
private final ObjectMapper objectMapper = new ObjectMapper();
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
private final Map<String, Library> libraries = new ConcurrentHashMap<>();
// Spring ApplicationContext for accessing other services without circular dependencies
private ApplicationContext applicationContext;
// Current active resources
private volatile String currentLibraryId;
private volatile Client currentTypesenseClient;
// Security: Track if user has explicitly authenticated in this session
private volatile boolean explicitlyAuthenticated = false;
private static final String LIBRARIES_CONFIG_PATH = "/app/config/libraries.json";
private static final Path libraryConfigDir = Paths.get("/app/config");
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@PostConstruct
public void initialize() {
loadLibrariesFromFile();
// If no libraries exist, create a default one
if (libraries.isEmpty()) {
createDefaultLibrary();
}
// Security: Do NOT automatically switch to any library on startup
// Users must authenticate before accessing any library
explicitlyAuthenticated = false;
currentLibraryId = null;
if (!libraries.isEmpty()) {
logger.info("Loaded {} libraries. Authentication required to access any library.", libraries.size());
} else {
logger.info("No libraries found. A default library will be created on first authentication.");
}
logger.info("Security: Application startup completed. All users must re-authenticate.");
}
@PreDestroy
public void cleanup() {
currentLibraryId = null;
currentTypesenseClient = null;
explicitlyAuthenticated = false;
}
/**
* Clear authentication state (for logout)
*/
public void clearAuthentication() {
explicitlyAuthenticated = false;
currentLibraryId = null;
currentTypesenseClient = null;
logger.info("Authentication cleared - user must re-authenticate to access libraries");
}
public String authenticateAndGetLibrary(String password) {
for (Library library : libraries.values()) {
if (passwordEncoder.matches(password, library.getPasswordHash())) {
// Mark as explicitly authenticated for this session
explicitlyAuthenticated = true;
logger.info("User explicitly authenticated for library: {}", library.getId());
return library.getId();
}
}
return null; // Authentication failed
}
/**
* Switch to library after authentication with forced reindexing
* This ensures Typesense is always up-to-date after login
*/
public synchronized void switchToLibraryAfterAuthentication(String libraryId) throws Exception {
logger.info("Switching to library after authentication: {} (forcing reindex)", libraryId);
switchToLibrary(libraryId, true);
}
public synchronized void switchToLibrary(String libraryId) throws Exception {
switchToLibrary(libraryId, false);
}
public synchronized void switchToLibrary(String libraryId, boolean forceReindex) throws Exception {
// Security: Only allow library switching after explicit authentication
if (!explicitlyAuthenticated) {
throw new IllegalStateException("Library switching requires explicit authentication. Please log in first.");
}
if (libraryId.equals(currentLibraryId) && !forceReindex) {
return; // Already active and no forced reindex requested
}
Library library = libraries.get(libraryId);
if (library == null) {
throw new IllegalArgumentException("Library not found: " + libraryId);
}
String previousLibraryId = currentLibraryId;
if (libraryId.equals(currentLibraryId) && forceReindex) {
logger.info("Forcing reindex for current library: {} ({})", library.getName(), libraryId);
} else {
logger.info("Switching to library: {} ({})", library.getName(), libraryId);
}
// Close current resources
closeCurrentResources();
// Set new active library (datasource routing handled by SmartRoutingDataSource)
currentLibraryId = libraryId;
currentTypesenseClient = createTypesenseClient(library.getTypesenseCollection());
// Initialize Typesense collections for this library
try {
TypesenseService typesenseService = applicationContext.getBean(TypesenseService.class);
// First ensure collections exist
typesenseService.initializeCollectionsForCurrentLibrary();
logger.info("Completed Typesense initialization for library: {}", libraryId);
} catch (Exception e) {
logger.warn("Failed to initialize Typesense for library {}: {}", libraryId, e.getMessage());
// Don't fail the switch - collections can be created later
}
logger.info("Successfully switched to library: {}", library.getName());
// Perform complete reindex AFTER library switch is fully complete
// This ensures database routing is properly established
if (forceReindex || !libraryId.equals(previousLibraryId)) {
logger.info("Starting post-switch Typesense reindex for library: {}", libraryId);
// Run reindex asynchronously to avoid blocking authentication response
// and allow time for database routing to fully stabilize
String finalLibraryId = libraryId;
new Thread(() -> {
try {
// Give routing time to stabilize
Thread.sleep(500);
logger.info("Starting async Typesense reindex for library: {}", finalLibraryId);
TypesenseService typesenseService = applicationContext.getBean(TypesenseService.class);
typesenseService.performCompleteReindex();
logger.info("Completed async Typesense reindexing for library: {}", finalLibraryId);
} catch (Exception e) {
logger.warn("Failed to async reindex Typesense for library {}: {}", finalLibraryId, e.getMessage());
}
}, "TypesenseReindex-" + libraryId).start();
}
}
public DataSource getCurrentDataSource() {
if (currentLibraryId == null) {
throw new IllegalStateException("No active library - please authenticate first");
}
// Return the Spring-managed primary datasource which handles routing automatically
try {
return applicationContext.getBean("dataSource", DataSource.class);
} catch (Exception e) {
throw new IllegalStateException("Failed to get routing datasource", e);
}
}
public Client getCurrentTypesenseClient() {
if (currentTypesenseClient == null) {
throw new IllegalStateException("No active library - please authenticate first");
}
return currentTypesenseClient;
}
public String getCurrentLibraryId() {
return currentLibraryId;
}
public Library getCurrentLibrary() {
if (currentLibraryId == null) {
return null;
}
return libraries.get(currentLibraryId);
}
public List<LibraryDto> getAllLibraries() {
List<LibraryDto> result = new ArrayList<>();
for (Library library : libraries.values()) {
boolean isActive = library.getId().equals(currentLibraryId);
result.add(new LibraryDto(
library.getId(),
library.getName(),
library.getDescription(),
isActive,
library.isInitialized()
));
}
return result;
}
public LibraryDto getLibraryById(String libraryId) {
Library library = libraries.get(libraryId);
if (library != null) {
boolean isActive = library.getId().equals(currentLibraryId);
return new LibraryDto(
library.getId(),
library.getName(),
library.getDescription(),
isActive,
library.isInitialized()
);
}
return null;
}
public String getCurrentImagePath() {
Library current = getCurrentLibrary();
return current != null ? current.getImagePath() : "/images/default";
}
public String getImagePathForLibrary(String libraryId) {
if (libraryId == null) {
return "/images/default";
}
Library library = libraries.get(libraryId);
return library != null ? library.getImagePath() : "/images/default";
}
public boolean changeLibraryPassword(String libraryId, String currentPassword, String newPassword) {
Library library = libraries.get(libraryId);
if (library == null) {
return false;
}
// Verify current password
if (!passwordEncoder.matches(currentPassword, library.getPasswordHash())) {
return false;
}
// Update password
library.setPasswordHash(passwordEncoder.encode(newPassword));
saveLibrariesToFile();
logger.info("Password changed for library: {}", library.getName());
return true;
}
public Library createNewLibrary(String name, String description, String password) {
// Generate unique ID
String id = name.toLowerCase().replaceAll("[^a-z0-9]", "");
int counter = 1;
String originalId = id;
while (libraries.containsKey(id)) {
id = originalId + counter++;
}
Library newLibrary = new Library(
id,
name,
description,
passwordEncoder.encode(password),
"storycove_" + id
);
try {
// Test database creation by creating a connection
DataSource testDs = createDataSource(newLibrary.getDbName());
testDs.getConnection().close(); // This will create the database and schema if it doesn't exist
// Initialize library resources (image directories)
initializeNewLibraryResources(id);
newLibrary.setInitialized(true);
logger.info("Database and resources created for library: {}", newLibrary.getDbName());
} catch (Exception e) {
logger.warn("Database/resource creation failed for library {}: {}", id, e.getMessage());
// Continue anyway - resources will be created when needed
}
libraries.put(id, newLibrary);
saveLibrariesToFile();
logger.info("Created new library: {} ({})", name, id);
return newLibrary;
}
private void loadLibrariesFromFile() {
try {
File configFile = new File(LIBRARIES_CONFIG_PATH);
if (configFile.exists()) {
String content = Files.readString(Paths.get(LIBRARIES_CONFIG_PATH));
Map<String, Object> config = objectMapper.readValue(content, new TypeReference<Map<String, Object>>() {});
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> librariesData = (Map<String, Map<String, Object>>) config.get("libraries");
for (Map.Entry<String, Map<String, Object>> entry : librariesData.entrySet()) {
String id = entry.getKey();
Map<String, Object> data = entry.getValue();
Library library = new Library();
library.setId(id);
library.setName((String) data.get("name"));
library.setDescription((String) data.get("description"));
library.setPasswordHash((String) data.get("passwordHash"));
library.setDbName((String) data.get("dbName"));
library.setInitialized((Boolean) data.getOrDefault("initialized", false));
libraries.put(id, library);
logger.info("Loaded library: {} ({})", library.getName(), id);
}
} else {
logger.info("No libraries configuration file found, will create default");
}
} catch (IOException e) {
logger.error("Failed to load libraries configuration", e);
}
}
private void createDefaultLibrary() {
// Check if we're migrating from the old single-library system
String existingDbName = extractDatabaseName(baseDbUrl);
Library defaultLibrary = new Library(
"main",
"Main Library",
"Your existing story collection (migrated)",
passwordEncoder.encode("temp-password-change-me"), // Temporary password
existingDbName // Use existing database name
);
defaultLibrary.setInitialized(true); // Mark as initialized since it has existing data
libraries.put("main", defaultLibrary);
saveLibrariesToFile();
logger.warn("=".repeat(80));
logger.warn("MIGRATION: Created 'Main Library' for your existing data");
logger.warn("Temporary password: 'temp-password-change-me'");
logger.warn("IMPORTANT: Please set a proper password in Settings > Library Settings");
logger.warn("=".repeat(80));
}
private String extractDatabaseName(String jdbcUrl) {
// Extract database name from JDBC URL like "jdbc:postgresql://db:5432/storycove"
int lastSlash = jdbcUrl.lastIndexOf('/');
if (lastSlash != -1 && lastSlash < jdbcUrl.length() - 1) {
String dbPart = jdbcUrl.substring(lastSlash + 1);
// Remove any query parameters
int queryStart = dbPart.indexOf('?');
return queryStart != -1 ? dbPart.substring(0, queryStart) : dbPart;
}
return "storycove"; // fallback
}
private void saveLibrariesToFile() {
try {
Map<String, Object> config = new HashMap<>();
Map<String, Map<String, Object>> librariesData = new HashMap<>();
for (Library library : libraries.values()) {
Map<String, Object> data = new HashMap<>();
data.put("name", library.getName());
data.put("description", library.getDescription());
data.put("passwordHash", library.getPasswordHash());
data.put("dbName", library.getDbName());
data.put("initialized", library.isInitialized());
librariesData.put(library.getId(), data);
}
config.put("libraries", librariesData);
// Ensure config directory exists
new File("/app/config").mkdirs();
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(config);
Files.writeString(Paths.get(LIBRARIES_CONFIG_PATH), json);
logger.info("Saved libraries configuration");
} catch (IOException e) {
logger.error("Failed to save libraries configuration", e);
}
}
private DataSource createDataSource(String dbName) {
String url = baseDbUrl.replaceAll("/[^/]*$", "/" + dbName);
logger.info("Creating DataSource for: {}", url);
// First, ensure the database exists
ensureDatabaseExists(dbName);
HikariConfig config = new HikariConfig();
config.setJdbcUrl(url);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(10);
config.setConnectionTimeout(30000);
return new HikariDataSource(config);
}
private void ensureDatabaseExists(String dbName) {
// Connect to the 'postgres' database to create the new database
String adminUrl = baseDbUrl.replaceAll("/[^/]*$", "/postgres");
HikariConfig adminConfig = new HikariConfig();
adminConfig.setJdbcUrl(adminUrl);
adminConfig.setUsername(dbUsername);
adminConfig.setPassword(dbPassword);
adminConfig.setDriverClassName("org.postgresql.Driver");
adminConfig.setMaximumPoolSize(1);
adminConfig.setConnectionTimeout(30000);
boolean databaseCreated = false;
try (HikariDataSource adminDataSource = new HikariDataSource(adminConfig);
var connection = adminDataSource.getConnection();
var statement = connection.createStatement()) {
// Check if database exists
String checkQuery = "SELECT 1 FROM pg_database WHERE datname = ?";
try (var preparedStatement = connection.prepareStatement(checkQuery)) {
preparedStatement.setString(1, dbName);
try (var resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
logger.info("Database {} already exists", dbName);
return; // Database exists, nothing to do
}
}
}
// Create database if it doesn't exist
// Note: Database names cannot be parameterized, but we validate the name is safe
if (!dbName.matches("^[a-zA-Z][a-zA-Z0-9_]*$")) {
throw new IllegalArgumentException("Invalid database name: " + dbName);
}
String createQuery = "CREATE DATABASE " + dbName;
statement.executeUpdate(createQuery);
logger.info("Created database: {}", dbName);
databaseCreated = true;
} catch (SQLException e) {
logger.error("Failed to ensure database {} exists: {}", dbName, e.getMessage());
throw new RuntimeException("Database creation failed", e);
}
// If we just created the database, initialize its schema
if (databaseCreated) {
initializeNewDatabaseSchema(dbName);
}
}
private void initializeNewDatabaseSchema(String dbName) {
logger.info("Initializing schema for new database: {}", dbName);
// Create a temporary DataSource for the new database to initialize schema
String newDbUrl = baseDbUrl.replaceAll("/[^/]*$", "/" + dbName);
HikariConfig config = new HikariConfig();
config.setJdbcUrl(newDbUrl);
config.setUsername(dbUsername);
config.setPassword(dbPassword);
config.setDriverClassName("org.postgresql.Driver");
config.setMaximumPoolSize(1);
config.setConnectionTimeout(30000);
try (HikariDataSource tempDataSource = new HikariDataSource(config)) {
// Use Hibernate to create the schema
// This mimics what Spring Boot does during startup
createSchemaUsingHibernate(tempDataSource);
logger.info("Schema initialized for database: {}", dbName);
} catch (Exception e) {
logger.error("Failed to initialize schema for database {}: {}", dbName, e.getMessage());
throw new RuntimeException("Schema initialization failed", e);
}
}
public void initializeNewLibraryResources(String libraryId) {
Library library = libraries.get(libraryId);
if (library == null) {
throw new IllegalArgumentException("Library not found: " + libraryId);
}
try {
logger.info("Initializing resources for new library: {}", library.getName());
// 1. Create image directory structure
initializeImageDirectories(library);
// 2. Initialize Typesense collections (this will be done when switching to the library)
// The TypesenseService.initializeCollections() will be called automatically
logger.info("Successfully initialized resources for library: {}", library.getName());
} catch (Exception e) {
logger.error("Failed to initialize resources for library {}: {}", libraryId, e.getMessage());
throw new RuntimeException("Library resource initialization failed", e);
}
}
private void initializeImageDirectories(Library library) {
try {
// Create the library-specific image directory
String imagePath = "/app/images/" + library.getId();
java.nio.file.Path libraryImagePath = java.nio.file.Paths.get(imagePath);
if (!java.nio.file.Files.exists(libraryImagePath)) {
java.nio.file.Files.createDirectories(libraryImagePath);
logger.info("Created image directory: {}", imagePath);
// Create subdirectories for different image types
java.nio.file.Files.createDirectories(libraryImagePath.resolve("stories"));
java.nio.file.Files.createDirectories(libraryImagePath.resolve("authors"));
java.nio.file.Files.createDirectories(libraryImagePath.resolve("collections"));
logger.info("Created image subdirectories for library: {}", library.getId());
} else {
logger.info("Image directory already exists: {}", imagePath);
}
} catch (Exception e) {
logger.error("Failed to create image directories for library {}: {}", library.getId(), e.getMessage());
throw new RuntimeException("Image directory creation failed", e);
}
}
private void createSchemaUsingHibernate(DataSource dataSource) {
// Create the essential tables manually using the same DDL that Hibernate would generate
// This is simpler than setting up a full Hibernate configuration for schema creation
String[] createTableStatements = {
// Authors table
"""
CREATE TABLE authors (
author_rating integer,
created_at timestamp(6) not null,
updated_at timestamp(6) not null,
id uuid not null,
avatar_image_path varchar(255),
name varchar(255) not null,
notes TEXT,
primary key (id)
)
""",
// Author URLs table
"""
CREATE TABLE author_urls (
author_id uuid not null,
url varchar(255)
)
""",
// Series table
"""
CREATE TABLE series (
created_at timestamp(6) not null,
id uuid not null,
description varchar(1000),
name varchar(255) not null,
primary key (id)
)
""",
// Tags table
"""
CREATE TABLE tags (
color varchar(7),
created_at timestamp(6) not null,
id uuid not null,
description varchar(500),
name varchar(255) not null unique,
primary key (id)
)
""",
// Tag aliases table
"""
CREATE TABLE tag_aliases (
created_from_merge boolean not null,
created_at timestamp(6) not null,
canonical_tag_id uuid not null,
id uuid not null,
alias_name varchar(255) not null unique,
primary key (id)
)
""",
// Collections table
"""
CREATE TABLE collections (
is_archived boolean not null,
rating integer,
created_at timestamp(6) not null,
updated_at timestamp(6) not null,
id uuid not null,
cover_image_path varchar(500),
name varchar(500) not null,
description TEXT,
primary key (id)
)
""",
// Stories table
"""
CREATE TABLE stories (
is_read boolean,
rating integer,
reading_position integer,
volume integer,
word_count integer,
created_at timestamp(6) not null,
last_read_at timestamp(6),
updated_at timestamp(6) not null,
author_id uuid,
id uuid not null,
series_id uuid,
description varchar(1000),
content_html TEXT,
content_plain TEXT,
cover_path varchar(255),
source_url varchar(255),
summary TEXT,
title varchar(255) not null,
primary key (id)
)
""",
// Reading positions table
"""
CREATE TABLE reading_positions (
chapter_index integer,
character_position integer,
percentage_complete float(53),
word_position integer,
created_at timestamp(6) not null,
updated_at timestamp(6) not null,
id uuid not null,
story_id uuid not null,
context_after varchar(500),
context_before varchar(500),
chapter_title varchar(255),
epub_cfi TEXT,
primary key (id)
)
""",
// Junction tables
"""
CREATE TABLE story_tags (
story_id uuid not null,
tag_id uuid not null,
primary key (story_id, tag_id)
)
""",
"""
CREATE TABLE collection_stories (
position integer not null,
added_at timestamp(6) not null,
collection_id uuid not null,
story_id uuid not null,
primary key (collection_id, story_id),
unique (collection_id, position)
)
""",
"""
CREATE TABLE collection_tags (
collection_id uuid not null,
tag_id uuid not null,
primary key (collection_id, tag_id)
)
"""
};
String[] createIndexStatements = {
"CREATE INDEX idx_reading_position_story ON reading_positions (story_id)"
};
String[] createConstraintStatements = {
// Foreign key constraints
"ALTER TABLE author_urls ADD CONSTRAINT FKdqhp51m0uveybsts098gd79uo FOREIGN KEY (author_id) REFERENCES authors",
"ALTER TABLE stories ADD CONSTRAINT FKhwecpqeaxy40ftrctef1u7gw7 FOREIGN KEY (author_id) REFERENCES authors",
"ALTER TABLE stories ADD CONSTRAINT FK1kulyvy7wwcolp2gkndt57cp7 FOREIGN KEY (series_id) REFERENCES series",
"ALTER TABLE reading_positions ADD CONSTRAINT FKglfhdhflan3pgyr2u0gxi21i5 FOREIGN KEY (story_id) REFERENCES stories",
"ALTER TABLE story_tags ADD CONSTRAINT FKmans33ijt0nf65t0sng2r848j FOREIGN KEY (tag_id) REFERENCES tags",
"ALTER TABLE story_tags ADD CONSTRAINT FKq9guid7swnjxwdpgxj3jo1rsi FOREIGN KEY (story_id) REFERENCES stories",
"ALTER TABLE tag_aliases ADD CONSTRAINT FKqfsawmcj3ey4yycb6958y24ch FOREIGN KEY (canonical_tag_id) REFERENCES tags",
"ALTER TABLE collection_stories ADD CONSTRAINT FKr55ho4vhj0wp03x13iskr1jds FOREIGN KEY (collection_id) REFERENCES collections",
"ALTER TABLE collection_stories ADD CONSTRAINT FK7n41tbbrt7r2e81hpu3612r1o FOREIGN KEY (story_id) REFERENCES stories",
"ALTER TABLE collection_tags ADD CONSTRAINT FKceq7ggev8n8ibjui1x5yo4x67 FOREIGN KEY (tag_id) REFERENCES tags",
"ALTER TABLE collection_tags ADD CONSTRAINT FKq9sa5s8csdpbphrvb48tts8jt FOREIGN KEY (collection_id) REFERENCES collections"
};
try (var connection = dataSource.getConnection();
var statement = connection.createStatement()) {
// Create tables
for (String sql : createTableStatements) {
statement.executeUpdate(sql);
}
// Create indexes
for (String sql : createIndexStatements) {
statement.executeUpdate(sql);
}
// Create constraints
for (String sql : createConstraintStatements) {
statement.executeUpdate(sql);
}
logger.info("Successfully created all database tables and constraints");
} catch (SQLException e) {
logger.error("Failed to create database schema", e);
throw new RuntimeException("Schema creation failed", e);
}
}
private Client createTypesenseClient(String collection) {
logger.info("Creating Typesense client for collection: {}", collection);
List<Node> nodes = Arrays.asList(
new Node("http", typesenseHost, typesensePort)
);
org.typesense.api.Configuration configuration = new org.typesense.api.Configuration(nodes, Duration.ofSeconds(10), typesenseApiKey);
return new Client(configuration);
}
private void closeCurrentResources() {
// No need to close datasource - SmartRoutingDataSource handles this
// Typesense client doesn't need explicit cleanup
currentTypesenseClient = null;
// Don't clear currentLibraryId here - only when explicitly switching
}
/**
* Update library metadata (name and description)
*/
public synchronized void updateLibraryMetadata(String libraryId, String newName, String newDescription) throws Exception {
if (libraryId == null || libraryId.trim().isEmpty()) {
throw new IllegalArgumentException("Library ID cannot be null or empty");
}
Library library = libraries.get(libraryId);
if (library == null) {
throw new IllegalArgumentException("Library not found: " + libraryId);
}
// Validate new name
if (newName == null || newName.trim().isEmpty()) {
throw new IllegalArgumentException("Library name cannot be null or empty");
}
String oldName = library.getName();
String oldDescription = library.getDescription();
// Update the library object
library.setName(newName.trim());
library.setDescription(newDescription != null ? newDescription.trim() : "");
try {
// Save to configuration file
saveLibraryConfiguration(library);
logger.info("Updated library metadata - ID: {}, Name: '{}' -> '{}', Description: '{}' -> '{}'",
libraryId, oldName, newName, oldDescription, library.getDescription());
} catch (Exception e) {
// Rollback changes on failure
library.setName(oldName);
library.setDescription(oldDescription);
throw new RuntimeException("Failed to update library metadata: " + e.getMessage(), e);
}
}
/**
* Save library configuration to file
*/
private void saveLibraryConfiguration(Library library) throws Exception {
Path libraryConfigPath = libraryConfigDir.resolve(library.getId() + ".json");
// Create library configuration object
Map<String, Object> config = new HashMap<>();
config.put("id", library.getId());
config.put("name", library.getName());
config.put("description", library.getDescription());
config.put("passwordHash", library.getPasswordHash());
config.put("dbName", library.getDbName());
config.put("typesenseCollection", library.getTypesenseCollection());
config.put("imagePath", library.getImagePath());
config.put("initialized", library.isInitialized());
// Write to file
ObjectMapper mapper = new ObjectMapper();
String configJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(config);
Files.writeString(libraryConfigPath, configJson, StandardCharsets.UTF_8);
logger.debug("Saved library configuration to: {}", libraryConfigPath);
}
}

View File

@@ -1,36 +1,83 @@
package com.storycove.service;
import org.springframework.beans.factory.annotation.Value;
import com.storycove.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class PasswordAuthenticationService {
@Value("${storycove.auth.password}")
private String applicationPassword;
private static final Logger logger = LoggerFactory.getLogger(PasswordAuthenticationService.class);
private final PasswordEncoder passwordEncoder;
private final LibraryService libraryService;
private final JwtUtil jwtUtil;
public PasswordAuthenticationService(PasswordEncoder passwordEncoder) {
@Autowired
public PasswordAuthenticationService(
PasswordEncoder passwordEncoder,
LibraryService libraryService,
JwtUtil jwtUtil) {
this.passwordEncoder = passwordEncoder;
this.libraryService = libraryService;
this.jwtUtil = jwtUtil;
}
public boolean authenticate(String providedPassword) {
/**
* Authenticate user and switch to the appropriate library
* Returns JWT token if authentication successful, null otherwise
*/
public String authenticateAndSwitchLibrary(String providedPassword) {
if (providedPassword == null || providedPassword.trim().isEmpty()) {
return false;
return null;
}
// If application password starts with {bcrypt}, it's already encoded
if (applicationPassword.startsWith("{bcrypt}") || applicationPassword.startsWith("$2")) {
return passwordEncoder.matches(providedPassword, applicationPassword);
// Find which library this password belongs to
String libraryId = libraryService.authenticateAndGetLibrary(providedPassword);
if (libraryId == null) {
logger.warn("Authentication failed - invalid password");
return null;
}
// Otherwise, compare directly (for development/testing)
return applicationPassword.equals(providedPassword);
try {
// Switch to the authenticated library with forced reindexing (may take 2-3 seconds)
libraryService.switchToLibraryAfterAuthentication(libraryId);
// Generate JWT token with library context
String token = jwtUtil.generateToken("user", libraryId);
logger.info("Successfully authenticated and switched to library: {}", libraryId);
return token;
} catch (Exception e) {
logger.error("Failed to switch to library: {}", libraryId, e);
return null;
}
}
/**
* Legacy method - kept for backward compatibility
*/
@Deprecated
public boolean authenticate(String providedPassword) {
return authenticateAndSwitchLibrary(providedPassword) != null;
}
public String encodePassword(String rawPassword) {
return passwordEncoder.encode(rawPassword);
}
/**
* Get current library info for authenticated user
*/
public String getCurrentLibraryInfo() {
var library = libraryService.getCurrentLibrary();
if (library != null) {
return String.format("Library: %s (%s)", library.getName(), library.getId());
}
return "No library active";
}
}

View File

@@ -5,6 +5,8 @@ import com.storycove.repository.SeriesRepository;
import com.storycove.service.exception.DuplicateResourceException;
import com.storycove.service.exception.ResourceNotFoundException;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -20,6 +22,8 @@ import java.util.UUID;
@Validated
@Transactional
public class SeriesService {
private static final Logger logger = LoggerFactory.getLogger(SeriesService.class);
private final SeriesRepository seriesRepository;

View File

@@ -4,13 +4,15 @@ import com.storycove.entity.Author;
import com.storycove.entity.Series;
import com.storycove.entity.Story;
import com.storycove.entity.Tag;
import com.storycove.repository.ReadingPositionRepository;
import com.storycove.repository.StoryRepository;
import com.storycove.repository.TagRepository;
import com.storycove.service.exception.DuplicateResourceException;
import com.storycove.service.exception.ResourceNotFoundException;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@@ -18,19 +20,24 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
@Validated
@Transactional
public class StoryService {
private static final Logger logger = LoggerFactory.getLogger(StoryService.class);
private final StoryRepository storyRepository;
private final TagRepository tagRepository;
private final ReadingPositionRepository readingPositionRepository;
private final AuthorService authorService;
private final TagService tagService;
private final SeriesService seriesService;
@@ -40,6 +47,7 @@ public class StoryService {
@Autowired
public StoryService(StoryRepository storyRepository,
TagRepository tagRepository,
ReadingPositionRepository readingPositionRepository,
AuthorService authorService,
TagService tagService,
SeriesService seriesService,
@@ -47,6 +55,7 @@ public class StoryService {
@Autowired(required = false) TypesenseService typesenseService) {
this.storyRepository = storyRepository;
this.tagRepository = tagRepository;
this.readingPositionRepository = readingPositionRepository;
this.authorService = authorService;
this.tagService = tagService;
this.seriesService = seriesService;
@@ -74,11 +83,13 @@ public class StoryService {
return storyRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Story", id.toString()));
}
@Transactional(readOnly = true)
public Optional<Story> findByIdOptional(UUID id) {
return storyRepository.findById(id);
}
@Transactional(readOnly = true)
public Optional<Story> findByTitle(String title) {
@@ -114,7 +125,7 @@ public class StoryService {
@Transactional(readOnly = true)
public List<Story> findBySeries(UUID seriesId) {
Series series = seriesService.findById(seriesId);
seriesService.findById(seriesId); // Validate series exists
return storyRepository.findBySeriesOrderByVolume(seriesId);
}
@@ -432,13 +443,17 @@ public class StoryService {
public void delete(UUID id) {
Story story = findById(id);
// Clean up reading positions first (to avoid foreign key constraint violations)
readingPositionRepository.deleteByStoryId(id);
// Remove from series if part of one
if (story.getSeries() != null) {
story.getSeries().removeStory(story);
}
// Remove tags (this will update tag usage counts)
story.getTags().forEach(tag -> story.removeTag(tag));
// Create a copy to avoid ConcurrentModificationException
new ArrayList<>(story.getTags()).forEach(tag -> story.removeTag(tag));
// Delete from Typesense first (if available)
if (typesenseService != null) {
@@ -601,17 +616,33 @@ public class StoryService {
if (updateReq.getVolume() != null) {
story.setVolume(updateReq.getVolume());
}
// Handle author - either by ID or by name
if (updateReq.getAuthorId() != null) {
Author author = authorService.findById(updateReq.getAuthorId());
story.setAuthor(author);
}
// Handle series - either by ID or by name
if (updateReq.getSeriesId() != null) {
Series series = seriesService.findById(updateReq.getSeriesId());
story.setSeries(series);
} else if (updateReq.getSeriesName() != null) {
if (updateReq.getSeriesName().trim().isEmpty()) {
// Empty series name means remove from series
story.setSeries(null);
} else {
// Find or create series by name
Series series = seriesService.findByNameOptional(updateReq.getSeriesName().trim())
.orElseGet(() -> {
Series newSeries = new Series();
newSeries.setName(updateReq.getSeriesName().trim());
return seriesService.create(newSeries);
});
story.setSeries(series);
}
}
}
}
private void updateStoryTagsByNames(Story story, java.util.List<String> tagNames) {
// Clear existing tags first
Set<Tag> existingTags = new HashSet<>(story.getTags());
@@ -640,4 +671,137 @@ public class StoryService {
}
return storyRepository.findByTitleAndAuthorNameIgnoreCase(title.trim(), authorName.trim());
}
/**
* Find a random story based on optional filters.
* Uses Typesense for consistency with Library search functionality.
* Supports text search and multiple tags using the same logic as the Library view.
* @param searchQuery Optional search query
* @param tags Optional list of tags to filter by
* @return Optional containing the random story if found
*/
@Transactional(readOnly = true)
public Optional<Story> findRandomStory(String searchQuery, List<String> tags) {
return findRandomStory(searchQuery, tags, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null);
}
public Optional<Story> findRandomStory(String searchQuery, List<String> tags, Long seed) {
return findRandomStory(searchQuery, tags, seed, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null);
}
/**
* Find a random story based on optional filters with seed support.
* Uses Typesense for consistency with Library search functionality.
* Supports text search and multiple tags using the same logic as the Library view.
* @param searchQuery Optional search query
* @param tags Optional list of tags to filter by
* @param seed Optional seed for consistent randomization (null for truly random)
* @return Optional containing the random story if found
*/
@Transactional(readOnly = true)
public Optional<Story> findRandomStory(String searchQuery, List<String> tags, Long seed,
Integer minWordCount, Integer maxWordCount,
String createdAfter, String createdBefore,
String lastReadAfter, String lastReadBefore,
Integer minRating, Integer maxRating, Boolean unratedOnly,
String readingStatus, Boolean hasReadingProgress,
Boolean hasCoverImage, String sourceDomain,
String seriesFilter, Integer minTagCount,
Boolean popularOnly, Boolean hiddenGemsOnly) {
// Use Typesense if available for consistency with Library search
if (typesenseService != null) {
try {
Optional<UUID> randomStoryId = typesenseService.getRandomStoryId(searchQuery, tags, seed,
minWordCount, maxWordCount, createdAfter, createdBefore, lastReadAfter, lastReadBefore,
minRating, maxRating, unratedOnly, readingStatus, hasReadingProgress, hasCoverImage,
sourceDomain, seriesFilter, minTagCount, popularOnly, hiddenGemsOnly);
if (randomStoryId.isPresent()) {
return storyRepository.findById(randomStoryId.get());
}
return Optional.empty();
} catch (Exception e) {
// Fallback to database queries if Typesense fails
logger.warn("Typesense random story lookup failed, falling back to database queries", e);
}
}
// Fallback to repository-based implementation (global routing handles library selection)
return findRandomStoryFromRepository(searchQuery, tags);
}
/**
* Find random story using repository methods (for default database or when library-aware fails)
*/
private Optional<Story> findRandomStoryFromRepository(String searchQuery, List<String> tags) {
// Clean up inputs
String cleanSearchQuery = (searchQuery != null && !searchQuery.trim().isEmpty()) ? searchQuery.trim() : null;
List<String> cleanTags = (tags != null) ? tags.stream()
.filter(tag -> tag != null && !tag.trim().isEmpty())
.map(String::trim)
.collect(Collectors.toList()) : List.of();
long totalCount = 0;
Optional<Story> randomStory = Optional.empty();
if (cleanSearchQuery != null && !cleanTags.isEmpty()) {
// Both search query and tags
String searchPattern = "%" + cleanSearchQuery + "%";
List<String> upperCaseTags = cleanTags.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
totalCount = storyRepository.countStoriesByTextSearchAndTags(searchPattern, upperCaseTags, cleanTags.size());
if (totalCount > 0) {
long randomOffset = (long) (Math.random() * totalCount);
randomStory = storyRepository.findRandomStoryByTextSearchAndTags(searchPattern, upperCaseTags, cleanTags.size(), randomOffset);
}
} else if (cleanSearchQuery != null) {
// Only search query
String searchPattern = "%" + cleanSearchQuery + "%";
totalCount = storyRepository.countStoriesByTextSearch(searchPattern);
if (totalCount > 0) {
long randomOffset = (long) (Math.random() * totalCount);
randomStory = storyRepository.findRandomStoryByTextSearch(searchPattern, randomOffset);
}
} else if (!cleanTags.isEmpty()) {
// Only tags
if (cleanTags.size() == 1) {
// Single tag - use optimized single tag query
totalCount = storyRepository.countStoriesByTagName(cleanTags.get(0));
if (totalCount > 0) {
long randomOffset = (long) (Math.random() * totalCount);
randomStory = storyRepository.findRandomStoryByTagName(cleanTags.get(0), randomOffset);
}
} else {
// Multiple tags
List<String> upperCaseTags = cleanTags.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
totalCount = storyRepository.countStoriesByMultipleTags(upperCaseTags, cleanTags.size());
if (totalCount > 0) {
long randomOffset = (long) (Math.random() * totalCount);
randomStory = storyRepository.findRandomStoryByMultipleTags(upperCaseTags, cleanTags.size(), randomOffset);
}
}
} else {
// No filters - get random from all stories
totalCount = storyRepository.countAllStories();
if (totalCount > 0) {
long randomOffset = (long) (Math.random() * totalCount);
randomStory = storyRepository.findRandomStory(randomOffset);
}
}
return randomStory;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,15 @@
package com.storycove.service;
import com.storycove.entity.Story;
import com.storycove.entity.Tag;
import com.storycove.entity.TagAlias;
import com.storycove.repository.TagRepository;
import com.storycove.repository.TagAliasRepository;
import com.storycove.service.exception.DuplicateResourceException;
import com.storycove.service.exception.ResourceNotFoundException;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@@ -12,20 +17,27 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@Service
@Validated
@Transactional
public class TagService {
private static final Logger logger = LoggerFactory.getLogger(TagService.class);
private final TagRepository tagRepository;
private final TagAliasRepository tagAliasRepository;
@Autowired
public TagService(TagRepository tagRepository) {
public TagService(TagRepository tagRepository, TagAliasRepository tagAliasRepository) {
this.tagRepository = tagRepository;
this.tagAliasRepository = tagAliasRepository;
}
@Transactional(readOnly = true)
@@ -207,5 +219,273 @@ public class TagService {
if (updates.getName() != null) {
existing.setName(updates.getName());
}
if (updates.getColor() != null) {
existing.setColor(updates.getColor());
}
if (updates.getDescription() != null) {
existing.setDescription(updates.getDescription());
}
}
// Tag alias management methods
public TagAlias addAlias(UUID tagId, String aliasName) {
Tag canonicalTag = findById(tagId);
// Check if alias already exists (case-insensitive)
if (tagAliasRepository.existsByAliasNameIgnoreCase(aliasName)) {
throw new DuplicateResourceException("Tag alias", aliasName);
}
// Check if alias name conflicts with existing tag names
if (tagRepository.existsByNameIgnoreCase(aliasName)) {
throw new DuplicateResourceException("Tag alias conflicts with existing tag name", aliasName);
}
TagAlias alias = new TagAlias();
alias.setAliasName(aliasName);
alias.setCanonicalTag(canonicalTag);
alias.setCreatedFromMerge(false);
return tagAliasRepository.save(alias);
}
public void removeAlias(UUID tagId, UUID aliasId) {
findById(tagId); // Validate tag exists
TagAlias alias = tagAliasRepository.findById(aliasId)
.orElseThrow(() -> new ResourceNotFoundException("Tag alias", aliasId.toString()));
// Verify the alias belongs to the specified tag
if (!alias.getCanonicalTag().getId().equals(tagId)) {
throw new IllegalArgumentException("Alias does not belong to the specified tag");
}
tagAliasRepository.delete(alias);
}
@Transactional(readOnly = true)
public Tag resolveTagByName(String name) {
// First try to find exact tag match
Optional<Tag> directMatch = tagRepository.findByNameIgnoreCase(name);
if (directMatch.isPresent()) {
return directMatch.get();
}
// Then try to find by alias
Optional<TagAlias> aliasMatch = tagAliasRepository.findByAliasNameIgnoreCase(name);
if (aliasMatch.isPresent()) {
return aliasMatch.get().getCanonicalTag();
}
return null;
}
@Transactional
public Tag mergeTags(List<UUID> sourceTagIds, UUID targetTagId) {
// Validate target tag exists
Tag targetTag = findById(targetTagId);
// Validate source tags exist and are different from target
List<Tag> sourceTags = sourceTagIds.stream()
.filter(id -> !id.equals(targetTagId)) // Don't merge tag with itself
.map(this::findById)
.toList();
if (sourceTags.isEmpty()) {
throw new IllegalArgumentException("No valid source tags to merge");
}
// Perform the merge atomically
for (Tag sourceTag : sourceTags) {
// Move all stories from source tag to target tag
// Create a copy to avoid ConcurrentModificationException
List<Story> storiesToMove = new ArrayList<>(sourceTag.getStories());
storiesToMove.forEach(story -> {
story.removeTag(sourceTag);
story.addTag(targetTag);
});
// Create alias for the source tag name
TagAlias alias = new TagAlias();
alias.setAliasName(sourceTag.getName());
alias.setCanonicalTag(targetTag);
alias.setCreatedFromMerge(true);
tagAliasRepository.save(alias);
// Delete the source tag
tagRepository.delete(sourceTag);
}
return tagRepository.save(targetTag);
}
@Transactional(readOnly = true)
public List<Tag> findByNameOrAliasStartingWith(String query, int limit) {
// Find tags that start with the query
List<Tag> directMatches = tagRepository.findByNameStartingWithIgnoreCase(query.toLowerCase());
// Find tags via aliases that start with the query
List<TagAlias> aliasMatches = tagAliasRepository.findByAliasNameStartingWithIgnoreCase(query.toLowerCase());
List<Tag> aliasTagMatches = aliasMatches.stream()
.map(TagAlias::getCanonicalTag)
.distinct()
.toList();
// Combine and deduplicate
Set<Tag> allMatches = new HashSet<>(directMatches);
allMatches.addAll(aliasTagMatches);
// Convert to list and limit results
return allMatches.stream()
.sorted((a, b) -> a.getName().compareToIgnoreCase(b.getName()))
.limit(limit)
.toList();
}
@Transactional(readOnly = true)
public com.storycove.controller.TagController.MergePreviewResponse previewMerge(List<UUID> sourceTagIds, UUID targetTagId) {
// Validate target tag exists
Tag targetTag = findById(targetTagId);
// Validate source tags exist and are different from target
List<Tag> sourceTags = sourceTagIds.stream()
.filter(id -> !id.equals(targetTagId))
.map(this::findById)
.toList();
if (sourceTags.isEmpty()) {
throw new IllegalArgumentException("No valid source tags to merge");
}
// Calculate preview data
int targetStoryCount = targetTag.getStories().size();
// Collect all unique stories from all tags (including target) to handle overlaps correctly
Set<Story> allUniqueStories = new HashSet<>(targetTag.getStories());
for (Tag sourceTag : sourceTags) {
allUniqueStories.addAll(sourceTag.getStories());
}
int totalStories = allUniqueStories.size();
List<String> aliasesToCreate = sourceTags.stream()
.map(Tag::getName)
.toList();
// Create response object using the controller's inner class
var preview = new com.storycove.controller.TagController.MergePreviewResponse();
preview.setTargetTagName(targetTag.getName());
preview.setTargetStoryCount(targetStoryCount);
preview.setTotalResultStoryCount(totalStories);
preview.setAliasesToCreate(aliasesToCreate);
return preview;
}
@Transactional(readOnly = true)
public List<com.storycove.controller.TagController.TagSuggestion> suggestTags(String title, String content, String summary, int limit) {
List<com.storycove.controller.TagController.TagSuggestion> suggestions = new ArrayList<>();
// Get all existing tags for matching
List<Tag> existingTags = findAll();
// Combine all text for analysis
String combinedText = (title != null ? title : "") + " " +
(summary != null ? summary : "") + " " +
(content != null ? stripHtml(content) : "");
if (combinedText.trim().isEmpty()) {
return suggestions;
}
String lowerText = combinedText.toLowerCase();
// Score each existing tag based on how well it matches the content
for (Tag tag : existingTags) {
double score = calculateTagRelevanceScore(tag, lowerText, title, summary);
if (score > 0.1) { // Only suggest tags with reasonable confidence
String reason = generateReason(tag, lowerText, title, summary);
suggestions.add(new com.storycove.controller.TagController.TagSuggestion(
tag.getName(), score, reason
));
}
}
// Sort by confidence score (descending) and limit results
return suggestions.stream()
.sorted((a, b) -> Double.compare(b.getConfidence(), a.getConfidence()))
.limit(limit)
.collect(java.util.stream.Collectors.toList());
}
private double calculateTagRelevanceScore(Tag tag, String lowerText, String title, String summary) {
String tagName = tag.getName().toLowerCase();
double score = 0.0;
// Exact matches get highest score
if (lowerText.contains(" " + tagName + " ") || lowerText.startsWith(tagName + " ") || lowerText.endsWith(" " + tagName)) {
score += 0.8;
}
// Partial matches in title get high score
if (title != null && title.toLowerCase().contains(tagName)) {
score += 0.6;
}
// Partial matches in summary get medium score
if (summary != null && summary.toLowerCase().contains(tagName)) {
score += 0.4;
}
// Word-based matching (split tag name and look for individual words)
String[] tagWords = tagName.split("[\\s-_]+");
int matchedWords = 0;
for (String word : tagWords) {
if (word.length() > 2 && lowerText.contains(word)) {
matchedWords++;
}
}
if (tagWords.length > 0) {
score += 0.3 * ((double) matchedWords / tagWords.length);
}
// Boost score based on tag popularity (more used tags are more likely to be relevant)
int storyCount = tag.getStories() != null ? tag.getStories().size() : 0;
if (storyCount > 0) {
score += Math.min(0.2, storyCount * 0.01); // Small boost, capped at 0.2
}
return Math.min(1.0, score); // Cap at 1.0
}
private String generateReason(Tag tag, String lowerText, String title, String summary) {
String tagName = tag.getName().toLowerCase();
if (title != null && title.toLowerCase().contains(tagName)) {
return "Found in title";
}
if (summary != null && summary.toLowerCase().contains(tagName)) {
return "Found in summary";
}
if (lowerText.contains(" " + tagName + " ") || lowerText.startsWith(tagName + " ") || lowerText.endsWith(" " + tagName)) {
return "Exact match in content";
}
String[] tagWords = tagName.split("[\\s-_]+");
for (String word : tagWords) {
if (word.length() > 2 && lowerText.contains(word)) {
return "Related keywords found";
}
}
return "Similar content";
}
private String stripHtml(String html) {
if (html == null) return "";
// Simple HTML tag removal - replace with a proper HTML parser if needed
return html.replaceAll("<[^>]+>", " ").replaceAll("\\s+", " ").trim();
}
}

View File

@@ -0,0 +1,12 @@
package com.storycove.service.exception;
public class InvalidFileException extends RuntimeException {
public InvalidFileException(String message) {
super(message);
}
public InvalidFileException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -3,35 +3,64 @@ package com.storycove.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;
@Component
public class JwtUtil {
@Value("${storycove.jwt.secret}")
private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
// Security: Generate new secret on each startup to invalidate all existing tokens
private String secret;
@Value("${storycove.jwt.expiration:86400000}") // 24 hours default
private Long expiration;
@PostConstruct
public void initialize() {
// Generate a new random secret on startup to invalidate all existing JWT tokens
// This ensures users must re-authenticate after application restart
SecureRandom random = new SecureRandom();
byte[] secretBytes = new byte[64]; // 512 bits
random.nextBytes(secretBytes);
this.secret = Base64.getEncoder().encodeToString(secretBytes);
logger.info("JWT secret rotated on startup - all existing tokens invalidated");
logger.info("Users will need to re-authenticate after application restart for security");
}
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(secret.getBytes());
}
public String generateToken() {
return generateToken("user", null);
}
public String generateToken(String subject, String libraryId) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expiration);
return Jwts.builder()
.subject("user")
var builder = Jwts.builder()
.subject(subject)
.issuedAt(now)
.expiration(expiryDate)
.signWith(getSigningKey())
.compact();
.expiration(expiryDate);
// Add library context if provided
if (libraryId != null) {
builder.claim("libraryId", libraryId);
}
return builder.signWith(getSigningKey()).compact();
}
public boolean validateToken(String token) {
@@ -62,4 +91,13 @@ public class JwtUtil {
public String getSubjectFromToken(String token) {
return getClaimsFromToken(token).getSubject();
}
public String getLibraryIdFromToken(String token) {
try {
Claims claims = getClaimsFromToken(token);
return claims.get("libraryId", String.class);
} catch (Exception e) {
return null;
}
}
}

View File

@@ -16,8 +16,8 @@ spring:
servlet:
multipart:
max-file-size: 5MB
max-request-size: 10MB
max-file-size: 256MB # Increased for backup restore
max-request-size: 260MB # Slightly higher to account for form data
server:
port: 8080
@@ -28,10 +28,10 @@ storycove:
cors:
allowed-origins: ${STORYCOVE_CORS_ALLOWED_ORIGINS:http://localhost:3000,http://localhost:6925}
jwt:
secret: ${JWT_SECRET:default-secret-key}
secret: ${JWT_SECRET} # REQUIRED: Must be at least 32 characters, no default for security
expiration: 86400000 # 24 hours
auth:
password: ${APP_PASSWORD:admin}
password: ${APP_PASSWORD} # REQUIRED: No default password for security
typesense:
api-key: ${TYPESENSE_API_KEY:xyz}
host: ${TYPESENSE_HOST:localhost}
@@ -43,5 +43,7 @@ storycove:
logging:
level:
com.storycove: DEBUG
org.springframework.security: DEBUG
com.storycove: ${LOG_LEVEL:INFO} # Use INFO for production, DEBUG for development
org.springframework.security: WARN # Reduce security logging
org.springframework.web: WARN
org.hibernate.SQL: ${SQL_LOG_LEVEL:WARN} # Control SQL logging separately

View File

@@ -17,7 +17,7 @@
"h4": ["class", "style"],
"h5": ["class", "style"],
"h6": ["class", "style"],
"a": ["class"],
"a": ["class", "href", "title"],
"table": ["class", "style"],
"th": ["class", "style", "colspan", "rowspan"],
"td": ["class", "style", "colspan", "rowspan"],
@@ -38,8 +38,10 @@
"font-weight", "font-style", "text-align", "text-decoration", "margin",
"padding", "text-indent", "line-height"
],
"removedAttributes": {
"a": ["href", "target"]
"allowedProtocols": {
"a": {
"href": ["http", "https", "#", "/"]
}
},
"description": "HTML sanitization configuration for StoryCove story content. This configuration is shared between frontend (DOMPurify) and backend (Jsoup) to ensure consistency."
}

View File

@@ -15,10 +15,12 @@ public abstract class BaseRepositoryTest {
private static final PostgreSQLContainer<?> postgres;
static {
postgres = new PostgreSQLContainer<>("postgres:15-alpine")
@SuppressWarnings("resource") // Container is managed by shutdown hook
PostgreSQLContainer<?> container = new PostgreSQLContainer<>("postgres:15-alpine")
.withDatabaseName("storycove_test")
.withUsername("test")
.withPassword("test");
postgres = container;
postgres.start();
// Add shutdown hook to properly close the container

View File

@@ -9,7 +9,6 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
@@ -23,7 +22,6 @@ import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.times;
@@ -46,7 +44,7 @@ class AuthorServiceTest {
testAuthor.setId(testId);
testAuthor.setNotes("Test notes");
// Initialize service with null TypesenseService (which is allowed)
// Initialize service with null TypesenseService (which is allowed for tests)
authorService = new AuthorService(authorRepository, null);
}
@@ -176,7 +174,7 @@ class AuthorServiceTest {
when(authorRepository.existsByName("Updated Author")).thenReturn(false);
when(authorRepository.save(any(Author.class))).thenReturn(testAuthor);
Author result = authorService.update(testId, updates);
authorService.update(testId, updates);
assertEquals("Updated Author", testAuthor.getName());
assertEquals("Updated notes", testAuthor.getNotes());
@@ -318,7 +316,7 @@ class AuthorServiceTest {
when(authorRepository.findById(testId)).thenReturn(Optional.of(testAuthor));
when(authorRepository.save(any(Author.class))).thenReturn(testAuthor);
Author result = authorService.setRating(testId, 4);
authorService.setRating(testId, 4);
assertEquals(4, testAuthor.getAuthorRating());
verify(authorRepository, times(2)).findById(testId); // Called twice: once initially, once after flush
@@ -342,7 +340,7 @@ class AuthorServiceTest {
when(authorRepository.findById(testId)).thenReturn(Optional.of(testAuthor));
when(authorRepository.save(any(Author.class))).thenReturn(testAuthor);
Author result = authorService.setRating(testId, null);
authorService.setRating(testId, null);
assertNull(testAuthor.getAuthorRating());
verify(authorRepository, times(2)).findById(testId); // Called twice: once initially, once after flush

View File

@@ -1,6 +1,7 @@
package com.storycove.service;
import com.storycove.entity.Story;
import com.storycove.repository.ReadingPositionRepository;
import com.storycove.repository.StoryRepository;
import com.storycove.repository.TagRepository;
import com.storycove.service.exception.ResourceNotFoundException;
@@ -28,6 +29,9 @@ class StoryServiceTest {
@Mock
private TagRepository tagRepository;
@Mock
private ReadingPositionRepository readingPositionRepository;
private StoryService storyService;
private Story testStory;
@@ -44,6 +48,7 @@ class StoryServiceTest {
storyService = new StoryService(
storyRepository,
tagRepository,
readingPositionRepository, // added for foreign key constraint handling
null, // authorService - not needed for reading progress tests
null, // tagService - not needed for reading progress tests
null, // seriesService - not needed for reading progress tests

View File

@@ -0,0 +1,7 @@
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.29.0</center>
</body>
</html>

4
cookies.txt Normal file
View File

@@ -0,0 +1,4 @@
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

View File

@@ -42,6 +42,7 @@ services:
- STORYCOVE_CORS_ALLOWED_ORIGINS=${STORYCOVE_CORS_ALLOWED_ORIGINS:-http://localhost:3000,http://localhost:6925}
volumes:
- images_data:/app/images
- library_config:/app/config
depends_on:
- postgres
- typesense
@@ -61,7 +62,7 @@ services:
- storycove-network
typesense:
image: typesense/typesense:0.25.0
image: typesense/typesense:29.0
# No port mapping - only accessible within the Docker network
environment:
- TYPESENSE_API_KEY=${TYPESENSE_API_KEY}
@@ -75,6 +76,7 @@ volumes:
postgres_data:
typesense_data:
images_data:
library_config:
configs:
nginx_config:
@@ -91,7 +93,7 @@ configs:
}
server {
listen 80;
client_max_body_size 10M;
client_max_body_size 256M;
location / {
proxy_pass http://frontend;
proxy_http_version 1.1;

View File

@@ -1,40 +1,58 @@
# Use node 18 alpine for smaller image size
FROM node:18-alpine
# Multi-stage build for better layer caching and smaller final image
FROM node:18-alpine AS deps
WORKDIR /app
# Install dumb-init for proper signal handling
# Install dumb-init early
RUN apk add --no-cache dumb-init
# Copy package files
# Copy package files first to leverage Docker layer caching
COPY package*.json ./
# Install all dependencies (including devDependencies needed for build)
# Set npm config for better CI performance
RUN npm ci --prefer-offline --no-audit
# Install dependencies with optimized settings
RUN npm ci --prefer-offline --no-audit --frozen-lockfile
# Copy source code
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Set Node.js memory limit for build (helpful in constrained environments)
# Set Node.js memory limit for build
ENV NODE_OPTIONS="--max-old-space-size=1024"
ENV NEXT_TELEMETRY_DISABLED=1
# Build the application
RUN npm run build
# Remove devDependencies after build to reduce image size
RUN npm prune --omit=dev
# Production stage
FROM node:18-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init
# Create non-root user for security
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# Change ownership of the app directory
RUN chown -R nextjs:nodejs /app
# Copy necessary files from builder stage
COPY --from=builder /app/next.config.js* ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
# Copy built application
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["npm", "start"]
CMD ["node", "server.js"]

View File

@@ -1,5 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
// Enable standalone output for optimized Docker builds
output: 'standalone',
// Removed Next.js rewrites since nginx handles all API routing
webpack: (config, { isServer }) => {
// Exclude cheerio and its dependencies from client-side bundling

View File

@@ -10,9 +10,9 @@
"dependencies": {
"@heroicons/react": "^2.2.0",
"autoprefixer": "^10.4.16",
"axios": "^1.6.0",
"axios": "^1.11.0",
"cheerio": "^1.0.0-rc.12",
"dompurify": "^3.0.5",
"dompurify": "^3.2.6",
"next": "14.0.0",
"postcss": "^8.4.31",
"react": "^18",
@@ -1372,13 +1372,13 @@
}
},
"node_modules/axios": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.10.0.tgz",
"integrity": "sha512-/1xYAC4MP/HEG+3duIhFr4ZQXR4sQXOIe+o6sdqzeykGLx6Upp/1p8MHqhINOvGeP7xyNHe7tsiJByc4SSVUxw==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
"integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},

View File

@@ -12,9 +12,9 @@
"dependencies": {
"@heroicons/react": "^2.2.0",
"autoprefixer": "^10.4.16",
"axios": "^1.6.0",
"axios": "^1.11.0",
"cheerio": "^1.0.0-rc.12",
"dompurify": "^3.0.5",
"dompurify": "^3.2.6",
"next": "14.0.0",
"postcss": "^8.4.31",
"react": "^18",

View File

@@ -1,28 +1,29 @@
'use client';
import { useState, useRef, useEffect } from 'react';
import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '../../contexts/AuthContext';
import AppLayout from '../../components/layout/AppLayout';
import ImportLayout from '../../components/layout/ImportLayout';
import { Input, Textarea } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import TagInput from '../../components/stories/TagInput';
import RichTextEditor from '../../components/stories/RichTextEditor';
import ImageUpload from '../../components/ui/ImageUpload';
import AuthorSelector from '../../components/stories/AuthorSelector';
import SeriesSelector from '../../components/stories/SeriesSelector';
import { storyApi, authorApi } from '../../lib/api';
export default function AddStoryPage() {
const [importMode, setImportMode] = useState<'manual' | 'url'>('manual');
const [importUrl, setImportUrl] = useState('');
const [scraping, setScraping] = useState(false);
const [formData, setFormData] = useState({
title: '',
summary: '',
authorName: '',
authorId: undefined as string | undefined,
contentHtml: '',
sourceUrl: '',
tags: [] as string[],
seriesName: '',
seriesId: undefined as string | undefined,
volume: '',
});
@@ -45,16 +46,20 @@ export default function AddStoryPage() {
const searchParams = useSearchParams();
const { isAuthenticated } = useAuth();
// Pre-fill author if authorId is provided in URL
// Handle URL parameters
useEffect(() => {
const authorId = searchParams.get('authorId');
const from = searchParams.get('from');
// Pre-fill author if authorId is provided in URL
if (authorId) {
const loadAuthor = async () => {
try {
const author = await authorApi.getAuthor(authorId);
setFormData(prev => ({
...prev,
authorName: author.name
authorName: author.name,
authorId: author.id
}));
} catch (error) {
console.error('Failed to load author:', error);
@@ -62,6 +67,65 @@ export default function AddStoryPage() {
};
loadAuthor();
}
// Handle URL import data
if (from === 'url-import') {
const title = searchParams.get('title') || '';
const summary = searchParams.get('summary') || '';
const author = searchParams.get('author') || '';
const sourceUrl = searchParams.get('sourceUrl') || '';
const tagsParam = searchParams.get('tags');
const content = searchParams.get('content') || '';
let tags: string[] = [];
try {
tags = tagsParam ? JSON.parse(tagsParam) : [];
} catch (error) {
console.error('Failed to parse tags:', error);
tags = [];
}
setFormData(prev => ({
...prev,
title,
summary,
authorName: author,
authorId: undefined, // Reset author ID when importing from URL
contentHtml: content,
sourceUrl,
tags
}));
// Show success message
setErrors({ success: 'Story data imported successfully! Review and edit as needed before saving.' });
}
}, [searchParams]);
// Load pending story data from bulk combine operation
useEffect(() => {
const fromBulkCombine = searchParams.get('from') === 'bulk-combine';
if (fromBulkCombine) {
const pendingStoryData = localStorage.getItem('pendingStory');
if (pendingStoryData) {
try {
const storyData = JSON.parse(pendingStoryData);
setFormData(prev => ({
...prev,
title: storyData.title || '',
authorName: storyData.author || '',
authorId: undefined, // Reset author ID for bulk combined stories
contentHtml: storyData.content || '',
sourceUrl: storyData.sourceUrl || '',
summary: storyData.summary || '',
tags: storyData.tags || []
}));
// Clear the pending data
localStorage.removeItem('pendingStory');
} catch (error) {
console.error('Failed to load pending story data:', error);
}
}
}
}, [searchParams]);
// Check for duplicates when title and author are both present
@@ -133,54 +197,29 @@ export default function AddStoryPage() {
setFormData(prev => ({ ...prev, tags }));
};
const handleImportFromUrl = async () => {
if (!importUrl.trim()) {
setErrors({ importUrl: 'URL is required' });
return;
const handleAuthorChange = (authorName: string, authorId?: string) => {
setFormData(prev => ({
...prev,
authorName,
authorId: authorId // This will be undefined if creating new author, which clears the existing ID
}));
// Clear error when user changes author
if (errors.authorName) {
setErrors(prev => ({ ...prev, authorName: '' }));
}
};
setScraping(true);
setErrors({});
try {
const response = await fetch('/scrape/story', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: importUrl }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to scrape story');
}
const scrapedStory = await response.json();
// Pre-fill the form with scraped data
setFormData({
title: scrapedStory.title || '',
summary: scrapedStory.summary || '',
authorName: scrapedStory.author || '',
contentHtml: scrapedStory.content || '',
sourceUrl: scrapedStory.sourceUrl || importUrl,
tags: scrapedStory.tags || [],
seriesName: '',
volume: '',
});
// Switch to manual mode so user can edit the pre-filled data
setImportMode('manual');
setImportUrl('');
// Show success message
setErrors({ success: 'Story data imported successfully! Review and edit as needed before saving.' });
} catch (error: any) {
console.error('Failed to import story:', error);
setErrors({ importUrl: error.message });
} finally {
setScraping(false);
const handleSeriesChange = (seriesName: string, seriesId?: string) => {
setFormData(prev => ({
...prev,
seriesName,
seriesId: seriesId // This will be undefined if creating new series, which clears the existing ID
}));
// Clear error when user changes series
if (errors.seriesName) {
setErrors(prev => ({ ...prev, seriesName: '' }));
}
};
@@ -228,8 +267,10 @@ export default function AddStoryPage() {
contentHtml: formData.contentHtml,
sourceUrl: formData.sourceUrl || undefined,
volume: formData.seriesName ? parseInt(formData.volume) : undefined,
seriesName: formData.seriesName || undefined,
authorName: formData.authorName || undefined,
// Send seriesId if we have it (existing series), otherwise send seriesName (new series)
...(formData.seriesId ? { seriesId: formData.seriesId } : { seriesName: formData.seriesName || undefined }),
// Send authorId if we have it (existing author), otherwise send authorName (new author)
...(formData.authorId ? { authorId: formData.authorId } : { authorName: formData.authorName }),
tagNames: formData.tags.length > 0 ? formData.tags : undefined,
};
@@ -240,7 +281,7 @@ export default function AddStoryPage() {
await storyApi.uploadCover(story.id, coverImage);
}
router.push(`/stories/${story.id}`);
router.push(`/stories/${story.id}/detail`);
} catch (error: any) {
console.error('Failed to create story:', error);
const errorMessage = error.response?.data?.message || 'Failed to create story';
@@ -251,288 +292,191 @@ export default function AddStoryPage() {
};
return (
<AppLayout>
<div className="max-w-4xl mx-auto">
<div className="mb-8">
<h1 className="text-3xl font-bold theme-header">Add New Story</h1>
<p className="theme-text mt-2">
Add a story to your personal collection
<ImportLayout
title="Add New Story"
description="Add a story to your personal collection"
>
{/* Success Message */}
{errors.success && (
<div className="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg mb-6">
<p className="text-green-800 dark:text-green-200">{errors.success}</p>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6">
{/* Title */}
<Input
label="Title *"
value={formData.title}
onChange={handleInputChange('title')}
placeholder="Enter the story title"
error={errors.title}
required
/>
{/* Author Selector */}
<AuthorSelector
label="Author *"
value={formData.authorName}
onChange={handleAuthorChange}
placeholder="Select or enter author name"
error={errors.authorName}
required
/>
{/* Duplicate Warning */}
{duplicateWarning.show && (
<div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div className="flex items-start gap-3">
<div className="text-yellow-600 dark:text-yellow-400 mt-0.5">
</div>
<div>
<h4 className="font-medium text-yellow-800 dark:text-yellow-200">
Potential Duplicate Detected
</h4>
<p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
Found {duplicateWarning.count} existing {duplicateWarning.count === 1 ? 'story' : 'stories'} with the same title and author:
</p>
<ul className="mt-2 space-y-1">
{duplicateWarning.duplicates.map((duplicate, index) => (
<li key={duplicate.id} className="text-sm text-yellow-700 dark:text-yellow-300">
<span className="font-medium">{duplicate.title}</span> by {duplicate.authorName}
<span className="text-xs ml-2">
(added {new Date(duplicate.createdAt).toLocaleDateString()})
</span>
</li>
))}
</ul>
<p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
You can still create this story if it's different from the existing ones.
</p>
</div>
</div>
</div>
)}
{/* Checking indicator */}
{checkingDuplicates && (
<div className="flex items-center gap-2 text-sm theme-text">
<div className="animate-spin w-4 h-4 border-2 border-theme-accent border-t-transparent rounded-full"></div>
Checking for duplicates...
</div>
)}
{/* Summary */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Summary
</label>
<Textarea
value={formData.summary}
onChange={handleInputChange('summary')}
placeholder="Brief summary or description of the story..."
rows={3}
/>
<p className="text-sm theme-text mt-1">
Optional summary that will be displayed on the story detail page
</p>
</div>
{/* Import Mode Toggle */}
<div className="mb-8">
<div className="flex border-b border-gray-200 dark:border-gray-700">
<button
type="button"
onClick={() => setImportMode('manual')}
className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
importMode === 'manual'
? 'border-theme-accent text-theme-accent'
: 'border-transparent theme-text hover:text-theme-accent'
}`}
>
Manual Entry
</button>
<button
type="button"
onClick={() => setImportMode('url')}
className={`px-6 py-3 text-sm font-medium border-b-2 transition-colors ${
importMode === 'url'
? 'border-theme-accent text-theme-accent'
: 'border-transparent theme-text hover:text-theme-accent'
}`}
>
Import from URL
</button>
</div>
{/* Cover Image Upload */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Cover Image
</label>
<ImageUpload
onImageSelect={setCoverImage}
accept="image/jpeg,image/png"
maxSizeMB={5}
aspectRatio="3:4"
placeholder="Drop a cover image here or click to select"
/>
</div>
{/* URL Import Section */}
{importMode === 'url' && (
<div className="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-6 mb-8">
<h3 className="text-lg font-medium theme-header mb-4">Import Story from URL</h3>
<p className="theme-text text-sm mb-4">
Enter a URL from a supported story site to automatically extract the story content, title, author, and other metadata.
</p>
<div className="space-y-4">
<Input
label="Story URL"
type="url"
value={importUrl}
onChange={(e) => setImportUrl(e.target.value)}
placeholder="https://example.com/story-url"
error={errors.importUrl}
disabled={scraping}
/>
<div className="flex gap-3">
<Button
type="button"
onClick={handleImportFromUrl}
loading={scraping}
disabled={!importUrl.trim() || scraping}
>
{scraping ? 'Importing...' : 'Import Story'}
</Button>
<Button
type="button"
variant="ghost"
onClick={() => setImportMode('manual')}
disabled={scraping}
>
Enter Manually Instead
</Button>
</div>
<div className="border-t pt-4 mt-4">
<p className="text-sm theme-text mb-2">
Need to import multiple stories at once?
</p>
<Button
type="button"
variant="secondary"
onClick={() => router.push('/stories/import/bulk')}
disabled={scraping}
size="sm"
>
Bulk Import Multiple URLs
</Button>
</div>
<div className="text-xs theme-text">
<p className="font-medium mb-1">Supported Sites:</p>
<p>Archive of Our Own, DeviantArt, FanFiction.Net, Literotica, Royal Road, Wattpad, and more</p>
</div>
</div>
{/* Content */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Story Content *
</label>
<RichTextEditor
value={formData.contentHtml}
onChange={handleContentChange}
placeholder="Write or paste your story content here..."
error={errors.contentHtml}
/>
</div>
{/* Tags */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Tags
</label>
<TagInput
tags={formData.tags}
onChange={handleTagsChange}
placeholder="Add tags to categorize your story..."
/>
</div>
{/* Series and Volume */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<SeriesSelector
label="Series (optional)"
value={formData.seriesName}
onChange={handleSeriesChange}
placeholder="Select or enter series name if part of a series"
error={errors.seriesName}
authorId={formData.authorId}
/>
<Input
label="Volume/Part (optional)"
type="number"
min="1"
value={formData.volume}
onChange={handleInputChange('volume')}
placeholder="Enter volume/part number"
error={errors.volume}
/>
</div>
{/* Source URL */}
<Input
label="Source URL (optional)"
type="url"
value={formData.sourceUrl}
onChange={handleInputChange('sourceUrl')}
placeholder="https://example.com/original-story-url"
/>
{/* Submit Error */}
{errors.submit && (
<div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
<p className="text-red-800 dark:text-red-200">{errors.submit}</p>
</div>
)}
{/* Success Message */}
{errors.success && (
<div className="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg mb-6">
<p className="text-green-800 dark:text-green-200">{errors.success}</p>
</div>
)}
{importMode === 'manual' && (
<form onSubmit={handleSubmit} className="space-y-6">
{/* Title */}
<Input
label="Title *"
value={formData.title}
onChange={handleInputChange('title')}
placeholder="Enter the story title"
error={errors.title}
required
/>
{/* Author */}
<Input
label="Author *"
value={formData.authorName}
onChange={handleInputChange('authorName')}
placeholder="Enter the author's name"
error={errors.authorName}
required
/>
{/* Duplicate Warning */}
{duplicateWarning.show && (
<div className="p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
<div className="flex items-start gap-3">
<div className="text-yellow-600 dark:text-yellow-400 mt-0.5">
</div>
<div>
<h4 className="font-medium text-yellow-800 dark:text-yellow-200">
Potential Duplicate Detected
</h4>
<p className="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
Found {duplicateWarning.count} existing {duplicateWarning.count === 1 ? 'story' : 'stories'} with the same title and author:
</p>
<ul className="mt-2 space-y-1">
{duplicateWarning.duplicates.map((duplicate, index) => (
<li key={duplicate.id} className="text-sm text-yellow-700 dark:text-yellow-300">
<span className="font-medium">{duplicate.title}</span> by {duplicate.authorName}
<span className="text-xs ml-2">
(added {new Date(duplicate.createdAt).toLocaleDateString()})
</span>
</li>
))}
</ul>
<p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
You can still create this story if it's different from the existing ones.
</p>
</div>
</div>
</div>
)}
{/* Checking indicator */}
{checkingDuplicates && (
<div className="flex items-center gap-2 text-sm theme-text">
<div className="animate-spin w-4 h-4 border-2 border-theme-accent border-t-transparent rounded-full"></div>
Checking for duplicates...
</div>
)}
{/* Summary */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Summary
</label>
<Textarea
value={formData.summary}
onChange={handleInputChange('summary')}
placeholder="Brief summary or description of the story..."
rows={3}
/>
<p className="text-sm theme-text mt-1">
Optional summary that will be displayed on the story detail page
</p>
</div>
{/* Cover Image Upload */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Cover Image
</label>
<ImageUpload
onImageSelect={setCoverImage}
accept="image/jpeg,image/png,image/webp"
maxSizeMB={5}
aspectRatio="3:4"
placeholder="Drop a cover image here or click to select"
/>
</div>
{/* Content */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Story Content *
</label>
<RichTextEditor
value={formData.contentHtml}
onChange={handleContentChange}
placeholder="Write or paste your story content here..."
error={errors.contentHtml}
/>
</div>
{/* Tags */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Tags
</label>
<TagInput
tags={formData.tags}
onChange={handleTagsChange}
placeholder="Add tags to categorize your story..."
/>
</div>
{/* Series and Volume */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Input
label="Series (optional)"
value={formData.seriesName}
onChange={handleInputChange('seriesName')}
placeholder="Enter series name if part of a series"
error={errors.seriesName}
/>
<Input
label="Volume/Part (optional)"
type="number"
min="1"
value={formData.volume}
onChange={handleInputChange('volume')}
placeholder="Enter volume/part number"
error={errors.volume}
/>
</div>
{/* Source URL */}
<Input
label="Source URL (optional)"
type="url"
value={formData.sourceUrl}
onChange={handleInputChange('sourceUrl')}
placeholder="https://example.com/original-story-url"
/>
{/* Submit Error */}
{errors.submit && (
<div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
<p className="text-red-800 dark:text-red-200">{errors.submit}</p>
</div>
)}
{/* Actions */}
<div className="flex justify-end gap-4 pt-6">
<Button
type="button"
variant="ghost"
onClick={() => router.back()}
disabled={loading}
>
Cancel
</Button>
<Button
type="submit"
loading={loading}
disabled={!formData.title || !formData.authorName || !formData.contentHtml}
>
Add Story
</Button>
</div>
</form>
)}
</div>
</AppLayout>
{/* Actions */}
<div className="flex justify-end gap-4 pt-6">
<Button
type="button"
variant="ghost"
onClick={() => router.back()}
disabled={loading}
>
Cancel
</Button>
<Button
type="submit"
loading={loading}
disabled={!formData.title || !formData.authorName || !formData.contentHtml}
>
Add Story
</Button>
</div>
</form>
</ImportLayout>
);
}

View File

@@ -269,7 +269,7 @@ export default function EditAuthorPage() {
</label>
<ImageUpload
onImageSelect={setAvatarImage}
accept="image/jpeg,image/png,image/webp"
accept="image/jpeg,image/png"
maxSizeMB={5}
aspectRatio="1:1"
placeholder="Drop an avatar image here or click to select"

View File

@@ -14,6 +14,7 @@ export default function AuthorsPage() {
const [authors, setAuthors] = useState<Author[]>([]);
const [filteredAuthors, setFilteredAuthors] = useState<Author[]>([]);
const [loading, setLoading] = useState(true);
const [searchLoading, setSearchLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
const [sortBy, setSortBy] = useState('name');
@@ -24,50 +25,61 @@ export default function AuthorsPage() {
const ITEMS_PER_PAGE = 50; // Safe limit under Typesense's 250 limit
useEffect(() => {
const loadAuthors = async () => {
try {
setLoading(true);
const searchResults = await authorApi.searchAuthorsTypesense({
q: searchQuery || '*',
page: currentPage,
size: ITEMS_PER_PAGE,
sortBy: sortBy,
sortOrder: sortOrder
});
if (currentPage === 0) {
// First page - replace all results
setAuthors(searchResults.results || []);
setFilteredAuthors(searchResults.results || []);
} else {
// Subsequent pages - append results
setAuthors(prev => [...prev, ...(searchResults.results || [])]);
setFilteredAuthors(prev => [...prev, ...(searchResults.results || [])]);
}
setTotalHits(searchResults.totalHits);
setHasMore(searchResults.results.length === ITEMS_PER_PAGE && (currentPage + 1) * ITEMS_PER_PAGE < searchResults.totalHits);
} catch (error) {
console.error('Failed to load authors:', error);
// Fallback to regular API if Typesense fails (only for first page)
if (currentPage === 0) {
try {
const authorsResult = await authorApi.getAuthors({ page: 0, size: ITEMS_PER_PAGE });
setAuthors(authorsResult.content || []);
setFilteredAuthors(authorsResult.content || []);
setTotalHits(authorsResult.totalElements || 0);
setHasMore(authorsResult.content.length === ITEMS_PER_PAGE);
} catch (fallbackError) {
console.error('Fallback also failed:', fallbackError);
const debounceTimer = setTimeout(() => {
const loadAuthors = async () => {
try {
// Use searchLoading for background search, loading only for initial load
const isInitialLoad = authors.length === 0 && !searchQuery && currentPage === 0;
if (isInitialLoad) {
setLoading(true);
} else {
setSearchLoading(true);
}
const searchResults = await authorApi.searchAuthorsTypesense({
q: searchQuery || '*',
page: currentPage,
size: ITEMS_PER_PAGE,
sortBy: sortBy,
sortOrder: sortOrder
});
if (currentPage === 0) {
// First page - replace all results
setAuthors(searchResults.results || []);
setFilteredAuthors(searchResults.results || []);
} else {
// Subsequent pages - append results
setAuthors(prev => [...prev, ...(searchResults.results || [])]);
setFilteredAuthors(prev => [...prev, ...(searchResults.results || [])]);
}
setTotalHits(searchResults.totalHits);
setHasMore(searchResults.results.length === ITEMS_PER_PAGE && (currentPage + 1) * ITEMS_PER_PAGE < searchResults.totalHits);
} catch (error) {
console.error('Failed to load authors:', error);
// Fallback to regular API if Typesense fails (only for first page)
if (currentPage === 0) {
try {
const authorsResult = await authorApi.getAuthors({ page: 0, size: ITEMS_PER_PAGE });
setAuthors(authorsResult.content || []);
setFilteredAuthors(authorsResult.content || []);
setTotalHits(authorsResult.totalElements || 0);
setHasMore(authorsResult.content.length === ITEMS_PER_PAGE);
} catch (fallbackError) {
console.error('Fallback also failed:', fallbackError);
}
}
} finally {
setLoading(false);
setSearchLoading(false);
}
} finally {
setLoading(false);
}
};
};
loadAuthors();
loadAuthors();
}, searchQuery ? 500 : 0); // 500ms debounce for search, immediate for other changes
return () => clearTimeout(debounceTimer);
}, [searchQuery, sortBy, sortOrder, currentPage]);
// Reset pagination when search or sort changes
@@ -133,13 +145,18 @@ export default function AuthorsPage() {
{/* Search and Sort Controls */}
<div className="flex flex-col md:flex-row gap-4">
<div className="flex-1 max-w-md">
<div className="flex-1 max-w-md relative">
<Input
type="search"
placeholder="Search authors..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
{searchLoading && (
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
<div className="animate-spin h-4 w-4 border-2 border-theme-accent border-t-transparent rounded-full"></div>
</div>
)}
</div>
<div className="flex gap-2">

View File

@@ -85,13 +85,28 @@
line-height: 1.7;
}
.reading-content h1,
.reading-content h2,
.reading-content h3,
.reading-content h4,
.reading-content h5,
.reading-content h1 {
@apply text-2xl font-bold mt-8 mb-4 theme-header;
}
.reading-content h2 {
@apply text-xl font-bold mt-6 mb-3 theme-header;
}
.reading-content h3 {
@apply text-lg font-semibold mt-6 mb-3 theme-header;
}
.reading-content h4 {
@apply text-base font-semibold mt-4 mb-2 theme-header;
}
.reading-content h5 {
@apply text-sm font-semibold mt-4 mb-2 theme-header;
}
.reading-content h6 {
@apply font-bold mt-8 mb-4 theme-header;
@apply text-xs font-semibold mt-4 mb-2 theme-header uppercase tracking-wide;
}
.reading-content p {
@@ -118,4 +133,54 @@
.reading-content em {
@apply italic;
}
/* Editor content styling - same as reading content but for the rich text editor */
.editor-content h1 {
@apply text-2xl font-bold mt-8 mb-4 theme-header;
}
.editor-content h2 {
@apply text-xl font-bold mt-6 mb-3 theme-header;
}
.editor-content h3 {
@apply text-lg font-semibold mt-6 mb-3 theme-header;
}
.editor-content h4 {
@apply text-base font-semibold mt-4 mb-2 theme-header;
}
.editor-content h5 {
@apply text-sm font-semibold mt-4 mb-2 theme-header;
}
.editor-content h6 {
@apply text-xs font-semibold mt-4 mb-2 theme-header uppercase tracking-wide;
}
.editor-content p {
@apply mb-4 theme-text;
}
.editor-content blockquote {
@apply border-l-4 pl-4 italic my-6 theme-border theme-text;
}
.editor-content ul,
.editor-content ol {
@apply mb-4 pl-6 theme-text;
}
.editor-content li {
@apply mb-2;
}
.editor-content strong {
@apply font-semibold theme-header;
}
.editor-content em {
@apply italic;
}
}

View File

@@ -0,0 +1,380 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import BulkImportProgress from '@/components/BulkImportProgress';
import ImportLayout from '@/components/layout/ImportLayout';
import Button from '@/components/ui/Button';
import { Textarea } from '@/components/ui/Input';
interface ImportResult {
url: string;
status: 'imported' | 'skipped' | 'error';
reason?: string;
title?: string;
author?: string;
error?: string;
storyId?: string;
}
interface BulkImportResponse {
results: ImportResult[];
summary: {
total: number;
imported: number;
skipped: number;
errors: number;
};
combinedStory?: {
title: string;
author: string;
content: string;
summary?: string;
sourceUrl: string;
tags?: string[];
};
}
export default function BulkImportPage() {
const router = useRouter();
const [urls, setUrls] = useState('');
const [combineIntoOne, setCombineIntoOne] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [results, setResults] = useState<BulkImportResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [sessionId, setSessionId] = useState<string | null>(null);
const [showProgress, setShowProgress] = useState(false);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!urls.trim()) {
setError('Please enter at least one URL');
return;
}
setIsLoading(true);
setError(null);
setResults(null);
try {
// Parse URLs from textarea (one per line)
const urlList = urls
.split('\n')
.map(url => url.trim())
.filter(url => url.length > 0);
if (urlList.length === 0) {
setError('Please enter at least one valid URL');
setIsLoading(false);
return;
}
if (urlList.length > 200) {
setError('Maximum 200 URLs allowed per bulk import');
setIsLoading(false);
return;
}
// Generate session ID for progress tracking
const newSessionId = `bulk-import-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
setSessionId(newSessionId);
setShowProgress(true);
// Get auth token for server-side API calls
const token = localStorage.getItem('auth-token');
const response = await fetch('/scrape/bulk', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token ? `Bearer ${token}` : '',
},
body: JSON.stringify({ urls: urlList, combineIntoOne, sessionId: newSessionId }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to start bulk import');
}
const startData = await response.json();
console.log('Bulk import started:', startData);
// The progress component will handle the rest via SSE
} catch (err) {
console.error('Bulk import error:', err);
setError(err instanceof Error ? err.message : 'Failed to import stories');
} finally {
setIsLoading(false);
}
};
const handleReset = () => {
setUrls('');
setCombineIntoOne(false);
setResults(null);
setError(null);
setSessionId(null);
setShowProgress(false);
};
const handleProgressComplete = (data?: any) => {
// Progress component will handle this when the operation completes
setShowProgress(false);
setIsLoading(false);
// Handle completion data
if (data) {
if (data.combinedStory && combineIntoOne) {
// For combine mode, redirect to import page with the combined content
localStorage.setItem('pendingStory', JSON.stringify(data.combinedStory));
router.push('/add-story?from=bulk-combine');
return;
} else if (data.results && data.summary) {
// For individual mode, show the results
setResults({
results: data.results,
summary: data.summary
});
return;
}
}
// Fallback: just hide progress and let user know it completed
console.log('Import completed successfully');
};
const handleProgressError = (errorMessage: string) => {
setError(errorMessage);
setIsLoading(false);
setShowProgress(false);
};
const getStatusColor = (status: string) => {
switch (status) {
case 'imported': return 'text-green-700 bg-green-50 border-green-200';
case 'skipped': return 'text-yellow-700 bg-yellow-50 border-yellow-200';
case 'error': return 'text-red-700 bg-red-50 border-red-200';
default: return 'text-gray-700 bg-gray-50 border-gray-200';
}
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'imported': return '✓';
case 'skipped': return '⚠';
case 'error': return '✗';
default: return '';
}
};
return (
<ImportLayout
title="Bulk Import Stories"
description="Import multiple stories at once by providing a list of URLs"
>
{!results ? (
// Import Form
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="urls" className="block text-sm font-medium theme-header mb-2">
Story URLs
</label>
<p className="text-sm theme-text mb-3">
Enter one URL per line. Maximum 200 URLs per import.
</p>
<Textarea
id="urls"
value={urls}
onChange={(e) => setUrls(e.target.value)}
placeholder="https://example.com/story1
https://example.com/story2
https://example.com/story3"
rows={12}
disabled={isLoading}
/>
<p className="mt-2 text-sm theme-text">
URLs: {urls.split('\n').filter(url => url.trim().length > 0).length}
</p>
</div>
<div className="flex items-center">
<input
id="combine-into-one"
type="checkbox"
checked={combineIntoOne}
onChange={(e) => setCombineIntoOne(e.target.checked)}
className="h-4 w-4 theme-accent focus:ring-theme-accent theme-border rounded"
disabled={isLoading}
/>
<label htmlFor="combine-into-one" className="ml-2 block text-sm theme-text">
Combine all URL content into a single story
</label>
</div>
{combineIntoOne && (
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="text-sm text-blue-800 dark:text-blue-200">
<p className="font-medium mb-2">Combined Story Mode:</p>
<ul className="list-disc list-inside space-y-1 text-blue-700 dark:text-blue-300">
<li>All URLs will be scraped and their content combined into one story</li>
<li>Story title and author will be taken from the first URL</li>
<li>Import will fail if any URL has no content (title/author can be empty)</li>
<li>You'll be redirected to the story creation page to review and edit</li>
{urls.split('\n').filter(url => url.trim().length > 0).length > 50 && (
<li className="text-yellow-700 dark:text-yellow-300 font-medium">⚠️ Large imports (50+ URLs) may take several minutes and could be truncated if too large</li>
)}
</ul>
</div>
</div>
)}
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<div className="flex">
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800 dark:text-red-200">Error</h3>
<div className="mt-2 text-sm text-red-700 dark:text-red-300">
{error}
</div>
</div>
</div>
</div>
)}
<div className="flex gap-4">
<Button
type="submit"
disabled={isLoading || !urls.trim()}
loading={isLoading}
>
{isLoading ? 'Importing...' : 'Start Import'}
</Button>
<Button
type="button"
variant="secondary"
onClick={handleReset}
disabled={isLoading}
>
Clear
</Button>
</div>
{/* Progress Component */}
{showProgress && sessionId && (
<BulkImportProgress
sessionId={sessionId}
onComplete={handleProgressComplete}
onError={handleProgressError}
combineMode={combineIntoOne}
/>
)}
{/* Fallback loading indicator if progress isn't shown yet */}
{isLoading && !showProgress && (
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex items-center">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-theme-accent mr-3"></div>
<div>
<p className="text-sm font-medium text-blue-800 dark:text-blue-200">Starting import...</p>
<p className="text-sm text-blue-600 dark:text-blue-300">
Preparing to process {urls.split('\n').filter(url => url.trim().length > 0).length} URLs.
</p>
</div>
</div>
</div>
)}
</form>
) : (
// Results
<div className="space-y-6">
{/* Summary */}
<div className="theme-card theme-shadow rounded-lg p-6">
<h2 className="text-xl font-semibold theme-header mb-4">Import Summary</h2>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold theme-header">{results.summary.total}</div>
<div className="text-sm theme-text">Total URLs</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-green-600 dark:text-green-400">{results.summary.imported}</div>
<div className="text-sm theme-text">Imported</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-yellow-600 dark:text-yellow-400">{results.summary.skipped}</div>
<div className="text-sm theme-text">Skipped</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-600 dark:text-red-400">{results.summary.errors}</div>
<div className="text-sm theme-text">Errors</div>
</div>
</div>
</div>
{/* Detailed Results */}
<div className="theme-card theme-shadow rounded-lg">
<div className="px-6 py-4 border-b theme-border">
<h3 className="text-lg font-medium theme-header">Detailed Results</h3>
</div>
<div className="divide-y theme-border">
{results.results.map((result, index) => (
<div key={index} className="p-6">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${getStatusColor(result.status)}`}>
{getStatusIcon(result.status)} {result.status.charAt(0).toUpperCase() + result.status.slice(1)}
</span>
</div>
<p className="text-sm theme-header font-medium truncate mb-1">
{result.url}
</p>
{result.title && result.author && (
<p className="text-sm theme-text mb-1">
"{result.title}" by {result.author}
</p>
)}
{result.reason && (
<p className="text-sm theme-text">
{result.reason}
</p>
)}
{result.error && (
<p className="text-sm text-red-600 dark:text-red-400">
Error: {result.error}
</p>
)}
</div>
</div>
</div>
))}
</div>
</div>
{/* Actions */}
<div className="flex gap-4">
<Button onClick={handleReset}>
Import More URLs
</Button>
<Button
variant="secondary"
onClick={() => router.push('/library')}
>
View Stories
</Button>
</div>
</div>
)}
</ImportLayout>
);
}

View File

@@ -0,0 +1,409 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { DocumentArrowUpIcon } from '@heroicons/react/24/outline';
import Button from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import ImportLayout from '@/components/layout/ImportLayout';
interface EPUBImportResponse {
success: boolean;
message: string;
storyId?: string;
storyTitle?: string;
totalChapters?: number;
wordCount?: number;
readingPosition?: any;
warnings?: string[];
errors?: string[];
}
export default function EPUBImportPage() {
const router = useRouter();
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [isValidating, setIsValidating] = useState(false);
const [validationResult, setValidationResult] = useState<any>(null);
const [importResult, setImportResult] = useState<EPUBImportResponse | null>(null);
const [error, setError] = useState<string | null>(null);
// Import options
const [authorName, setAuthorName] = useState<string>('');
const [seriesName, setSeriesName] = useState<string>('');
const [seriesVolume, setSeriesVolume] = useState<string>('');
const [tags, setTags] = useState<string>('');
const [preserveReadingPosition, setPreserveReadingPosition] = useState(true);
const [overwriteExisting, setOverwriteExisting] = useState(false);
const [createMissingAuthor, setCreateMissingAuthor] = useState(true);
const [createMissingSeries, setCreateMissingSeries] = useState(true);
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
setSelectedFile(file);
setValidationResult(null);
setImportResult(null);
setError(null);
if (file.name.toLowerCase().endsWith('.epub')) {
await validateFile(file);
} else {
setError('Please select a valid EPUB file (.epub extension)');
}
}
};
const validateFile = async (file: File) => {
setIsValidating(true);
try {
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/api/stories/epub/validate', {
method: 'POST',
headers: {
'Authorization': token ? `Bearer ${token}` : '',
},
body: formData,
});
if (response.ok) {
const result = await response.json();
setValidationResult(result);
if (!result.valid) {
setError('EPUB file validation failed: ' + result.errors.join(', '));
}
} else if (response.status === 401 || response.status === 403) {
setError('Authentication required. Please log in.');
} else {
setError('Failed to validate EPUB file');
}
} catch (err) {
setError('Error validating EPUB file: ' + (err as Error).message);
} finally {
setIsValidating(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedFile) {
setError('Please select an EPUB file');
return;
}
if (validationResult && !validationResult.valid) {
setError('Cannot import invalid EPUB file');
return;
}
setIsLoading(true);
setError(null);
try {
const token = localStorage.getItem('auth-token');
const formData = new FormData();
formData.append('file', selectedFile);
if (authorName) formData.append('authorName', authorName);
if (seriesName) formData.append('seriesName', seriesName);
if (seriesVolume) formData.append('seriesVolume', seriesVolume);
if (tags) {
const tagList = tags.split(',').map(t => t.trim()).filter(t => t.length > 0);
tagList.forEach(tag => formData.append('tags', tag));
}
formData.append('preserveReadingPosition', preserveReadingPosition.toString());
formData.append('overwriteExisting', overwriteExisting.toString());
formData.append('createMissingAuthor', createMissingAuthor.toString());
formData.append('createMissingSeries', createMissingSeries.toString());
const response = await fetch('/api/stories/epub/import', {
method: 'POST',
headers: {
'Authorization': token ? `Bearer ${token}` : '',
},
body: formData,
});
const result = await response.json();
if (response.ok && result.success) {
setImportResult(result);
} else if (response.status === 401 || response.status === 403) {
setError('Authentication required. Please log in.');
} else {
setError(result.message || 'Failed to import EPUB');
}
} catch (err) {
setError('Error importing EPUB: ' + (err as Error).message);
} finally {
setIsLoading(false);
}
};
const resetForm = () => {
setSelectedFile(null);
setValidationResult(null);
setImportResult(null);
setError(null);
setAuthorName('');
setSeriesName('');
setSeriesVolume('');
setTags('');
};
if (importResult?.success) {
return (
<ImportLayout
title="EPUB Import Successful"
description="Your EPUB has been successfully imported into StoryCove"
>
<div className="space-y-6">
<div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-6">
<h2 className="text-xl font-semibold text-green-600 dark:text-green-400 mb-2">Import Completed</h2>
<p className="theme-text">
Your EPUB has been successfully imported into StoryCove.
</p>
</div>
<div className="theme-card theme-shadow rounded-lg p-6">
<div className="space-y-4">
<div>
<span className="font-semibold theme-header">Story Title:</span>
<p className="theme-text">{importResult.storyTitle}</p>
</div>
{importResult.wordCount && (
<div>
<span className="font-semibold theme-header">Word Count:</span>
<p className="theme-text">{importResult.wordCount.toLocaleString()} words</p>
</div>
)}
{importResult.totalChapters && (
<div>
<span className="font-semibold theme-header">Chapters:</span>
<p className="theme-text">{importResult.totalChapters}</p>
</div>
)}
{importResult.warnings && importResult.warnings.length > 0 && (
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
<strong className="text-yellow-800 dark:text-yellow-200">Warnings:</strong>
<ul className="list-disc list-inside mt-2 text-yellow-700 dark:text-yellow-300">
{importResult.warnings.map((warning, index) => (
<li key={index}>{warning}</li>
))}
</ul>
</div>
)}
<div className="flex gap-4 mt-6">
<Button
onClick={() => router.push(`/stories/${importResult.storyId}`)}
>
View Story
</Button>
<Button
onClick={resetForm}
variant="secondary"
>
Import Another EPUB
</Button>
</div>
</div>
</div>
</div>
</ImportLayout>
);
}
return (
<ImportLayout
title="Import EPUB"
description="Upload an EPUB file to import it as a story into your library"
>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6">
<p className="text-red-800 dark:text-red-200">{error}</p>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6">
{/* File Upload */}
<div className="theme-card theme-shadow rounded-lg p-6">
<div className="mb-4">
<h3 className="text-lg font-semibold theme-header mb-2">Select EPUB File</h3>
<p className="theme-text">
Choose an EPUB file from your device to import.
</p>
</div>
<div className="space-y-4">
<div>
<label htmlFor="epub-file" className="block text-sm font-medium theme-header mb-1">EPUB File</label>
<Input
id="epub-file"
type="file"
accept=".epub,application/epub+zip"
onChange={handleFileChange}
disabled={isLoading || isValidating}
/>
</div>
{selectedFile && (
<div className="flex items-center gap-2">
<DocumentArrowUpIcon className="h-5 w-5 theme-text" />
<span className="text-sm theme-text">
{selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
</span>
</div>
)}
{isValidating && (
<div className="text-sm theme-accent">
Validating EPUB file...
</div>
)}
{validationResult && (
<div className="text-sm">
{validationResult.valid ? (
<span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-200">
Valid EPUB
</span>
) : (
<span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-red-100 dark:bg-red-900/20 text-red-800 dark:text-red-200">
Invalid EPUB
</span>
)}
</div>
)}
</div>
</div>
{/* Import Options */}
<div className="theme-card theme-shadow rounded-lg p-6">
<div className="mb-4">
<h3 className="text-lg font-semibold theme-header mb-2">Import Options</h3>
<p className="theme-text">
Configure how the EPUB should be imported.
</p>
</div>
<div className="space-y-4">
<div>
<label htmlFor="author-name" className="block text-sm font-medium theme-header mb-1">Author Name (Override)</label>
<Input
id="author-name"
value={authorName}
onChange={(e) => setAuthorName(e.target.value)}
placeholder="Leave empty to use EPUB metadata"
/>
</div>
<div>
<label htmlFor="series-name" className="block text-sm font-medium theme-header mb-1">Series Name</label>
<Input
id="series-name"
value={seriesName}
onChange={(e) => setSeriesName(e.target.value)}
placeholder="Optional: Add to a series"
/>
</div>
{seriesName && (
<div>
<label htmlFor="series-volume" className="block text-sm font-medium theme-header mb-1">Series Volume</label>
<Input
id="series-volume"
type="number"
value={seriesVolume}
onChange={(e) => setSeriesVolume(e.target.value)}
placeholder="Volume number in series"
/>
</div>
)}
<div>
<label htmlFor="tags" className="block text-sm font-medium theme-header mb-1">Tags</label>
<Input
id="tags"
value={tags}
onChange={(e) => setTags(e.target.value)}
placeholder="Comma-separated tags (e.g., fantasy, adventure, romance)"
/>
</div>
<div className="space-y-3">
<div className="flex items-center">
<input
type="checkbox"
id="preserve-reading-position"
checked={preserveReadingPosition}
onChange={(e) => setPreserveReadingPosition(e.target.checked)}
className="mr-2"
/>
<label htmlFor="preserve-reading-position" className="text-sm theme-text">
Preserve reading position from EPUB metadata
</label>
</div>
<div className="flex items-center">
<input
type="checkbox"
id="create-missing-author"
checked={createMissingAuthor}
onChange={(e) => setCreateMissingAuthor(e.target.checked)}
className="mr-2"
/>
<label htmlFor="create-missing-author" className="text-sm theme-text">
Create author if not found
</label>
</div>
<div className="flex items-center">
<input
type="checkbox"
id="create-missing-series"
checked={createMissingSeries}
onChange={(e) => setCreateMissingSeries(e.target.checked)}
className="mr-2"
/>
<label htmlFor="create-missing-series" className="text-sm theme-text">
Create series if not found
</label>
</div>
<div className="flex items-center">
<input
type="checkbox"
id="overwrite-existing"
checked={overwriteExisting}
onChange={(e) => setOverwriteExisting(e.target.checked)}
className="mr-2"
/>
<label htmlFor="overwrite-existing" className="text-sm theme-text">
Overwrite existing story with same title and author
</label>
</div>
</div>
</div>
</div>
{/* Submit Button */}
<div className="flex justify-end">
<Button
type="submit"
disabled={!selectedFile || isLoading || isValidating || (validationResult && !validationResult.valid)}
loading={isLoading}
>
{isLoading ? 'Importing...' : 'Import EPUB'}
</Button>
</div>
</form>
</ImportLayout>
);
}

View File

@@ -0,0 +1,113 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import ImportLayout from '../../components/layout/ImportLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
export default function ImportFromUrlPage() {
const [importUrl, setImportUrl] = useState('');
const [scraping, setScraping] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const router = useRouter();
const handleImportFromUrl = async () => {
if (!importUrl.trim()) {
setErrors({ importUrl: 'URL is required' });
return;
}
setScraping(true);
setErrors({});
try {
const response = await fetch('/scrape/story', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: importUrl }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to scrape story');
}
const scrapedStory = await response.json();
// Redirect to add-story page with pre-filled data
const queryParams = new URLSearchParams({
from: 'url-import',
title: scrapedStory.title || '',
summary: scrapedStory.summary || '',
author: scrapedStory.author || '',
sourceUrl: scrapedStory.sourceUrl || importUrl,
tags: JSON.stringify(scrapedStory.tags || []),
content: scrapedStory.content || ''
});
router.push(`/add-story?${queryParams.toString()}`);
} catch (error: any) {
console.error('Failed to import story:', error);
setErrors({ importUrl: error.message });
} finally {
setScraping(false);
}
};
return (
<ImportLayout
title="Import Story from URL"
description="Import a single story from a website"
>
<div className="space-y-6">
<div className="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-6">
<h3 className="text-lg font-medium theme-header mb-4">Import Story from URL</h3>
<p className="theme-text text-sm mb-4">
Enter a URL from a supported story site to automatically extract the story content, title, author, and other metadata. After importing, you'll be able to review and edit the data before saving.
</p>
<div className="space-y-4">
<Input
label="Story URL"
type="url"
value={importUrl}
onChange={(e) => setImportUrl(e.target.value)}
placeholder="https://example.com/story-url"
error={errors.importUrl}
disabled={scraping}
/>
<div className="flex gap-3">
<Button
type="button"
onClick={handleImportFromUrl}
loading={scraping}
disabled={!importUrl.trim() || scraping}
>
{scraping ? 'Importing...' : 'Import Story'}
</Button>
<Button
type="button"
variant="ghost"
href="/add-story"
disabled={scraping}
>
Enter Manually Instead
</Button>
</div>
<div className="text-xs theme-text">
<p className="font-medium mb-1">Supported Sites:</p>
<p>Archive of Our Own, DeviantArt, FanFiction.Net, Literotica, Royal Road, Wattpad, and more</p>
</div>
</div>
</div>
</div>
</ImportLayout>
);
}

View File

@@ -1,56 +1,144 @@
'use client';
import { useState, useEffect } from 'react';
import { searchApi } from '../../lib/api';
import { Story, Tag, FacetCount } from '../../types/api';
import { useRouter, useSearchParams } from 'next/navigation';
import { searchApi, storyApi, tagApi } from '../../lib/api';
import { Story, Tag, FacetCount, AdvancedFilters } from '../../types/api';
import AppLayout from '../../components/layout/AppLayout';
import { Input } from '../../components/ui/Input';
import Button from '../../components/ui/Button';
import StoryMultiSelect from '../../components/stories/StoryMultiSelect';
import TagFilter from '../../components/stories/TagFilter';
import LoadingSpinner from '../../components/ui/LoadingSpinner';
import SidebarLayout from '../../components/library/SidebarLayout';
import ToolbarLayout from '../../components/library/ToolbarLayout';
import MinimalLayout from '../../components/library/MinimalLayout';
import { useLibraryLayout } from '../../hooks/useLibraryLayout';
type ViewMode = 'grid' | 'list';
type SortOption = 'createdAt' | 'title' | 'authorName' | 'rating' | 'wordCount';
type SortOption = 'createdAt' | 'title' | 'authorName' | 'rating' | 'wordCount' | 'lastRead';
export default function LibraryPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { layout } = useLibraryLayout();
const [stories, setStories] = useState<Story[]>([]);
const [tags, setTags] = useState<Tag[]>([]);
const [loading, setLoading] = useState(false);
const [searchLoading, setSearchLoading] = useState(false);
const [randomLoading, setRandomLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [viewMode, setViewMode] = useState<ViewMode>('list');
const [sortOption, setSortOption] = useState<SortOption>('createdAt');
const [sortOption, setSortOption] = useState<SortOption>('lastRead');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
const [page, setPage] = useState(0);
const [totalPages, setTotalPages] = useState(1);
const [totalElements, setTotalElements] = useState(0);
const [refreshTrigger, setRefreshTrigger] = useState(0);
const [urlParamsProcessed, setUrlParamsProcessed] = useState(false);
const [advancedFilters, setAdvancedFilters] = useState<AdvancedFilters>({});
// Initialize filters from URL parameters
useEffect(() => {
const tagsParam = searchParams.get('tags');
if (tagsParam) {
console.log('URL tag filter detected:', tagsParam);
// Use functional updates to ensure all state changes happen together
setSelectedTags([tagsParam]);
setPage(0); // Reset to first page when applying URL filter
}
setUrlParamsProcessed(true);
}, [searchParams]);
// Convert facet counts to Tag objects for the UI
// Convert facet counts to Tag objects for the UI, enriched with full tag data
const [fullTags, setFullTags] = useState<Tag[]>([]);
// Fetch full tag data for enrichment
useEffect(() => {
const fetchFullTags = async () => {
try {
const result = await tagApi.getTags({ size: 1000 }); // Get all tags
setFullTags(result.content || []);
} catch (error) {
console.error('Failed to fetch full tag data:', error);
setFullTags([]);
}
};
fetchFullTags();
}, []);
const convertFacetsToTags = (facets?: Record<string, FacetCount[]>): Tag[] => {
if (!facets || !facets.tagNames) {
return [];
}
return facets.tagNames.map(facet => ({
id: facet.value, // Use tag name as ID since we don't have actual IDs from search results
name: facet.value,
storyCount: facet.count
}));
return facets.tagNames.map(facet => {
// Find the full tag data by name
const fullTag = fullTags.find(tag => tag.name.toLowerCase() === facet.value.toLowerCase());
return {
id: fullTag?.id || facet.value, // Use actual ID if available, fallback to name
name: facet.value,
storyCount: facet.count,
// Include color and other metadata from the full tag data
color: fullTag?.color,
description: fullTag?.description,
aliasCount: fullTag?.aliasCount,
createdAt: fullTag?.createdAt,
aliases: fullTag?.aliases
};
});
};
// Enrich existing tags when fullTags are loaded
useEffect(() => {
if (fullTags.length > 0) {
// Use functional update to get the current tags state
setTags(currentTags => {
if (currentTags.length > 0) {
// Check if tags already have color data to avoid infinite loops
const hasColors = currentTags.some(tag => tag.color);
if (!hasColors) {
// Re-enrich existing tags with color data
return currentTags.map(tag => {
const fullTag = fullTags.find(ft => ft.name.toLowerCase() === tag.name.toLowerCase());
return {
...tag,
color: fullTag?.color,
description: fullTag?.description,
aliasCount: fullTag?.aliasCount,
createdAt: fullTag?.createdAt,
aliases: fullTag?.aliases,
id: fullTag?.id || tag.id
};
});
}
}
return currentTags; // Return unchanged if no enrichment needed
});
}
}, [fullTags]); // Only run when fullTags change
// Debounce search to avoid too many API calls
useEffect(() => {
// Don't run search until URL parameters have been processed
if (!urlParamsProcessed) return;
const debounceTimer = setTimeout(() => {
const performSearch = async () => {
try {
setLoading(true);
// Use searchLoading for background search, loading only for initial load
const isInitialLoad = stories.length === 0 && !searchQuery;
if (isInitialLoad) {
setLoading(true);
} else {
setSearchLoading(true);
}
// Always use search API for consistency - use '*' for match-all when no query
const result = await searchApi.search({
const apiParams = {
query: searchQuery.trim() || '*',
page: page, // Use 0-based pagination consistently
size: 20,
@@ -58,7 +146,12 @@ export default function LibraryPage() {
sortBy: sortOption,
sortDir: sortDirection,
facetBy: ['tagNames'], // Request tag facets for the filter UI
});
// Advanced filters
...advancedFilters
};
console.log('Performing search with params:', apiParams);
const result = await searchApi.search(apiParams);
const currentStories = result?.results || [];
setStories(currentStories);
@@ -68,66 +161,80 @@ export default function LibraryPage() {
// Update tags from facets - these represent all matching stories, not just current page
const resultTags = convertFacetsToTags(result?.facets);
setTags(resultTags);
} catch (error) {
console.error('Failed to load stories:', error);
setStories([]);
setTags([]);
} finally {
setLoading(false);
setSearchLoading(false);
}
};
performSearch();
}, searchQuery ? 300 : 0); // Debounce search, but not other changes
}, searchQuery ? 500 : 0); // Debounce search queries, but load immediately for filters/pagination
return () => clearTimeout(debounceTimer);
}, [searchQuery, selectedTags, page, sortOption, sortDirection, refreshTrigger]);
// Reset page when search or filters change
const resetPage = () => {
if (page !== 0) {
setPage(0);
}
};
const handleTagToggle = (tagName: string) => {
setSelectedTags(prev => {
const newTags = prev.includes(tagName)
? prev.filter(t => t !== tagName)
: [...prev, tagName];
resetPage();
return newTags;
});
};
}, [searchQuery, selectedTags, sortOption, sortDirection, page, refreshTrigger, urlParamsProcessed, advancedFilters]);
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
resetPage();
setPage(0);
};
const handleSortChange = (newSortOption: SortOption) => {
setSortOption(newSortOption);
// Set appropriate default direction for the sort option
if (newSortOption === 'title' || newSortOption === 'authorName') {
setSortDirection('asc'); // Alphabetical fields default to ascending
} else {
setSortDirection('desc'); // Numeric/date fields default to descending
const handleStoryUpdate = () => {
setRefreshTrigger(prev => prev + 1);
};
const handleRandomStory = async () => {
if (totalElements === 0) return;
try {
setRandomLoading(true);
const randomStory = await storyApi.getRandomStory({
searchQuery: searchQuery || undefined,
tags: selectedTags.length > 0 ? selectedTags : undefined,
...advancedFilters
});
if (randomStory) {
router.push(`/stories/${randomStory.id}`);
} else {
alert('No stories available. Please add some stories first.');
}
} catch (error) {
console.error('Failed to get random story:', error);
alert('Failed to get a random story. Please try again.');
} finally {
setRandomLoading(false);
}
resetPage();
};
const toggleSortDirection = () => {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
resetPage();
};
const clearFilters = () => {
setSearchQuery('');
setSelectedTags([]);
resetPage();
setAdvancedFilters({});
setPage(0);
setRefreshTrigger(prev => prev + 1);
};
const handleStoryUpdate = () => {
// Trigger reload by incrementing refresh trigger
const handleTagToggle = (tagName: string) => {
setSelectedTags(prev =>
prev.includes(tagName)
? prev.filter(t => t !== tagName)
: [...prev, tagName]
);
setPage(0);
setRefreshTrigger(prev => prev + 1);
};
const handleSortDirectionToggle = () => {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
};
const handleAdvancedFiltersChange = (filters: AdvancedFilters) => {
setAdvancedFilters(filters);
setPage(0);
setRefreshTrigger(prev => prev + 1);
};
@@ -141,137 +248,62 @@ export default function LibraryPage() {
);
}
return (
<AppLayout>
<div className="space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h1 className="text-3xl font-bold theme-header">Your Story Library</h1>
<p className="theme-text mt-1">
{totalElements} {totalElements === 1 ? 'story' : 'stories'}
{searchQuery || selectedTags.length > 0 ? ` found` : ` total`}
</p>
</div>
<Button href="/add-story">
Add New Story
</Button>
const handleSortChange = (option: string) => {
setSortOption(option as SortOption);
};
const layoutProps = {
stories,
tags,
totalElements,
searchQuery,
selectedTags,
viewMode,
sortOption,
sortDirection,
advancedFilters,
onSearchChange: handleSearchChange,
onTagToggle: handleTagToggle,
onViewModeChange: setViewMode,
onSortChange: handleSortChange,
onSortDirectionToggle: handleSortDirectionToggle,
onAdvancedFiltersChange: handleAdvancedFiltersChange,
onRandomStory: handleRandomStory,
onClearFilters: clearFilters,
};
const renderContent = () => {
if (stories.length === 0 && !loading) {
return (
<div className="text-center py-12 theme-card theme-shadow rounded-lg">
<p className="theme-text text-lg mb-4">
{searchQuery || selectedTags.length > 0 || Object.values(advancedFilters).some(v => v !== undefined && v !== '' && v !== 'all' && v !== false)
? 'No stories match your search criteria.'
: 'Your library is empty.'
}
</p>
{searchQuery || selectedTags.length > 0 || Object.values(advancedFilters).some(v => v !== undefined && v !== '' && v !== 'all' && v !== false) ? (
<Button variant="ghost" onClick={clearFilters}>
Clear Filters
</Button>
) : (
<Button href="/add-story">
Add Your First Story
</Button>
)}
</div>
);
}
{/* Search and Filters */}
<div className="space-y-4">
{/* Search Bar */}
<div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
<Input
type="search"
placeholder="Search by title, author, or tags..."
value={searchQuery}
onChange={handleSearchChange}
className="w-full"
/>
</div>
{/* View Mode Toggle */}
<div className="flex items-center gap-2">
<button
onClick={() => setViewMode('grid')}
className={`p-2 rounded-lg transition-colors ${
viewMode === 'grid'
? 'theme-accent-bg text-white'
: 'theme-card theme-text hover:bg-opacity-80'
}`}
aria-label="Grid view"
>
</button>
<button
onClick={() => setViewMode('list')}
className={`p-2 rounded-lg transition-colors ${
viewMode === 'list'
? 'theme-accent-bg text-white'
: 'theme-card theme-text hover:bg-opacity-80'
}`}
aria-label="List view"
>
</button>
</div>
</div>
{/* Sort and Tag Filters */}
<div className="flex flex-col sm:flex-row gap-4">
{/* Sort Options */}
<div className="flex items-center gap-2">
<label className="theme-text font-medium text-sm">Sort by:</label>
<select
value={sortOption}
onChange={(e) => handleSortChange(e.target.value as SortOption)}
className="px-3 py-1 rounded-lg theme-card theme-text theme-border border focus:outline-none focus:ring-2 focus:ring-theme-accent"
>
<option value="createdAt">Date Added</option>
<option value="title">Title</option>
<option value="authorName">Author</option>
<option value="rating">Rating</option>
<option value="wordCount">Word Count</option>
</select>
{/* Sort Direction Toggle */}
<button
onClick={toggleSortDirection}
className="p-2 rounded-lg theme-card theme-text hover:bg-opacity-80 transition-colors border theme-border"
title={`Sort ${sortDirection === 'asc' ? 'Ascending' : 'Descending'}`}
aria-label={`Toggle sort direction - currently ${sortDirection === 'asc' ? 'ascending' : 'descending'}`}
>
{sortDirection === 'asc' ? '↑' : '↓'}
</button>
</div>
{/* Clear Filters */}
{(searchQuery || selectedTags.length > 0) && (
<Button variant="ghost" size="sm" onClick={clearFilters}>
Clear Filters
</Button>
)}
</div>
{/* Tag Filter */}
<TagFilter
tags={tags}
selectedTags={selectedTags}
onTagToggle={handleTagToggle}
/>
</div>
{/* Stories Display */}
{stories.length === 0 && !loading ? (
<div className="text-center py-20">
<div className="theme-text text-lg mb-4">
{searchQuery || selectedTags.length > 0
? 'No stories match your filters'
: 'No stories in your library yet'
}
</div>
{searchQuery || selectedTags.length > 0 ? (
<Button variant="ghost" onClick={clearFilters}>
Clear Filters
</Button>
) : (
<Button href="/add-story">
Add Your First Story
</Button>
)}
</div>
) : (
<StoryMultiSelect
stories={stories}
viewMode={viewMode}
onUpdate={handleStoryUpdate}
allowMultiSelect={true}
/>
)}
return (
<>
<StoryMultiSelect
stories={stories}
viewMode={viewMode}
onUpdate={handleStoryUpdate}
allowMultiSelect={true}
/>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex justify-center gap-2 mt-8">
@@ -296,7 +328,19 @@ export default function LibraryPage() {
</Button>
</div>
)}
</div>
</>
);
};
const LayoutComponent = layout === 'sidebar' ? SidebarLayout :
layout === 'toolbar' ? ToolbarLayout :
MinimalLayout;
return (
<AppLayout>
<LayoutComponent {...layoutProps}>
{renderContent()}
</LayoutComponent>
</AppLayout>
);
}

View File

@@ -0,0 +1,93 @@
import { NextRequest } from 'next/server';
// Configure route timeout for long-running progress streams
export const maxDuration = 900; // 15 minutes (900 seconds)
interface ProgressUpdate {
type: 'progress' | 'completed' | 'error';
current: number;
total: number;
message: string;
url?: string;
title?: string;
author?: string;
wordCount?: number;
totalWordCount?: number;
error?: string;
combinedStory?: any;
results?: any[];
summary?: any;
}
// Global progress storage (in production, use Redis or database)
const progressStore = new Map<string, ProgressUpdate[]>();
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const sessionId = searchParams.get('sessionId');
if (!sessionId) {
return new Response('Session ID required', { status: 400 });
}
// Set up Server-Sent Events
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
// Send initial connection message
const data = `data: ${JSON.stringify({ type: 'connected', sessionId })}\n\n`;
controller.enqueue(encoder.encode(data));
// Check for progress updates every 500ms
const interval = setInterval(() => {
const updates = progressStore.get(sessionId);
if (updates && updates.length > 0) {
// Send all pending updates
updates.forEach(update => {
const data = `data: ${JSON.stringify(update)}\n\n`;
controller.enqueue(encoder.encode(data));
});
// Clear sent updates
progressStore.delete(sessionId);
// If this was a completion or error, close the stream
const lastUpdate = updates[updates.length - 1];
if (lastUpdate.type === 'completed' || lastUpdate.type === 'error') {
clearInterval(interval);
controller.close();
}
}
}, 500);
// Cleanup after timeout
setTimeout(() => {
clearInterval(interval);
progressStore.delete(sessionId);
controller.close();
}, 900000); // 15 minutes
}
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control',
},
});
}
// Helper function for other routes to send progress updates
export function sendProgressUpdate(sessionId: string, update: ProgressUpdate) {
if (!progressStore.has(sessionId)) {
progressStore.set(sessionId, []);
}
progressStore.get(sessionId)!.push(update);
}
// Export the helper for other modules to use
export { progressStore };

View File

@@ -1,7 +1,23 @@
import { NextRequest, NextResponse } from 'next/server';
// Configure route timeout for long-running scraping operations
export const maxDuration = 900; // 15 minutes (900 seconds)
// Import progress tracking helper
async function sendProgressUpdate(sessionId: string, update: any) {
try {
// Dynamic import to avoid circular dependency
const { sendProgressUpdate: sendUpdate } = await import('./progress/route');
sendUpdate(sessionId, update);
} catch (error) {
console.warn('Failed to send progress update:', error);
}
}
interface BulkImportRequest {
urls: string[];
combineIntoOne?: boolean;
sessionId?: string; // For progress tracking
}
interface ImportResult {
@@ -22,52 +38,430 @@ interface BulkImportResponse {
skipped: number;
errors: number;
};
combinedStory?: {
title: string;
author: string;
content: string;
summary?: string;
sourceUrl: string;
tags?: string[];
};
}
export async function POST(request: NextRequest) {
// Background processing function for combined mode
async function processCombinedMode(
urls: string[],
sessionId: string,
authorization: string,
scraper: any
) {
const results: ImportResult[] = [];
let importedCount = 0;
let errorCount = 0;
const combinedContent: string[] = [];
let baseTitle = '';
let baseAuthor = '';
let baseSummary = '';
let baseSourceUrl = '';
const combinedTags = new Set<string>();
let totalWordCount = 0;
// Send initial progress update
await sendProgressUpdate(sessionId, {
type: 'progress',
current: 0,
total: urls.length,
message: `Starting to scrape ${urls.length} URLs for combining...`,
totalWordCount: 0
});
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
console.log(`Scraping URL ${i + 1}/${urls.length} for combine: ${url}`);
// Send progress update
await sendProgressUpdate(sessionId, {
type: 'progress',
current: i,
total: urls.length,
message: `Scraping URL ${i + 1} of ${urls.length}...`,
url: url,
totalWordCount
});
try {
const trimmedUrl = url.trim();
if (!trimmedUrl) {
results.push({
url: url || 'Empty URL',
status: 'error',
error: 'Empty URL in combined mode'
});
errorCount++;
continue;
}
const scrapedStory = await scraper.scrapeStory(trimmedUrl);
// Check if we got content - this is required for combined mode
if (!scrapedStory.content || scrapedStory.content.trim() === '') {
results.push({
url: trimmedUrl,
status: 'error',
error: 'No content found - required for combined mode'
});
errorCount++;
continue;
}
// Use first URL for base metadata (title can be empty for combined mode)
if (i === 0) {
baseTitle = scrapedStory.title || 'Combined Story';
baseAuthor = scrapedStory.author || 'Unknown Author';
baseSummary = scrapedStory.summary || '';
baseSourceUrl = trimmedUrl;
}
// Add content with URL separator
combinedContent.push(`<!-- Content from: ${trimmedUrl} -->`);
if (scrapedStory.title && i > 0) {
combinedContent.push(`<h2>${scrapedStory.title}</h2>`);
}
combinedContent.push(scrapedStory.content);
combinedContent.push('<hr/>'); // Visual separator between parts
// Calculate word count for this story
const textContent = scrapedStory.content.replace(/<[^>]*>/g, ''); // Strip HTML
const wordCount = textContent.split(/\s+/).filter((word: string) => word.length > 0).length;
totalWordCount += wordCount;
// Collect tags from all stories
if (scrapedStory.tags) {
scrapedStory.tags.forEach((tag: string) => combinedTags.add(tag));
}
results.push({
url: trimmedUrl,
status: 'imported',
title: scrapedStory.title,
author: scrapedStory.author
});
importedCount++;
// Send progress update with word count
await sendProgressUpdate(sessionId, {
type: 'progress',
current: i + 1,
total: urls.length,
message: `Scraped "${scrapedStory.title}" (${wordCount.toLocaleString()} words)`,
url: trimmedUrl,
title: scrapedStory.title,
author: scrapedStory.author,
wordCount: wordCount,
totalWordCount: totalWordCount
});
} catch (error) {
console.error(`Error processing URL ${url} in combined mode:`, error);
results.push({
url: url,
status: 'error',
error: error instanceof Error ? error.message : 'Unknown error'
});
errorCount++;
}
}
// If we have any errors, fail the entire combined operation
if (errorCount > 0) {
await sendProgressUpdate(sessionId, {
type: 'error',
current: urls.length,
total: urls.length,
message: 'Combined mode failed: some URLs could not be processed',
error: `${errorCount} URLs failed to process`
});
return;
}
// Check content size to prevent response size issues
const combinedContentString = combinedContent.join('\n');
const contentSizeInMB = new Blob([combinedContentString]).size / (1024 * 1024);
console.log(`Combined content size: ${contentSizeInMB.toFixed(2)} MB`);
console.log(`Combined content character length: ${combinedContentString.length}`);
console.log(`Combined content parts count: ${combinedContent.length}`);
// Return the combined story data via progress update
const combinedStory = {
title: baseTitle,
author: baseAuthor,
content: contentSizeInMB > 10 ?
combinedContentString.substring(0, Math.floor(combinedContentString.length * (10 / contentSizeInMB))) + '\n\n<!-- Content truncated due to size limit -->' :
combinedContentString,
summary: contentSizeInMB > 10 ? baseSummary + ' (Content truncated due to size limit)' : baseSummary,
sourceUrl: baseSourceUrl,
tags: Array.from(combinedTags)
};
// Send completion notification for combine mode
await sendProgressUpdate(sessionId, {
type: 'completed',
current: urls.length,
total: urls.length,
message: `Combined scraping completed: ${totalWordCount.toLocaleString()} words from ${importedCount} stories`,
totalWordCount: totalWordCount,
combinedStory: combinedStory
});
console.log(`Combined scraping completed: ${importedCount} URLs combined into one story`);
}
// Background processing function for individual mode
async function processIndividualMode(
urls: string[],
sessionId: string,
authorization: string,
scraper: any
) {
const results: ImportResult[] = [];
let importedCount = 0;
let skippedCount = 0;
let errorCount = 0;
await sendProgressUpdate(sessionId, {
type: 'progress',
current: 0,
total: urls.length,
message: `Starting to import ${urls.length} URLs individually...`
});
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
console.log(`Processing URL ${i + 1}/${urls.length}: ${url}`);
await sendProgressUpdate(sessionId, {
type: 'progress',
current: i,
total: urls.length,
message: `Processing URL ${i + 1} of ${urls.length}...`,
url: url
});
try {
// Validate URL format
if (!url || typeof url !== 'string' || url.trim() === '') {
results.push({
url: url || 'Empty URL',
status: 'error',
error: 'Invalid URL format'
});
errorCount++;
continue;
}
const trimmedUrl = url.trim();
// Scrape the story
const scrapedStory = await scraper.scrapeStory(trimmedUrl);
// Validate required fields
if (!scrapedStory.title || !scrapedStory.author || !scrapedStory.content) {
const missingFields = [];
if (!scrapedStory.title) missingFields.push('title');
if (!scrapedStory.author) missingFields.push('author');
if (!scrapedStory.content) missingFields.push('content');
results.push({
url: trimmedUrl,
status: 'skipped',
reason: `Missing required fields: ${missingFields.join(', ')}`,
title: scrapedStory.title,
author: scrapedStory.author
});
skippedCount++;
continue;
}
// Check for duplicates using query parameters
try {
const duplicateCheckUrl = `http://backend:8080/api/stories/check-duplicate`;
const params = new URLSearchParams({
title: scrapedStory.title,
authorName: scrapedStory.author
});
const duplicateCheckResponse = await fetch(`${duplicateCheckUrl}?${params.toString()}`, {
method: 'GET',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
});
if (duplicateCheckResponse.ok) {
const duplicateResult = await duplicateCheckResponse.json();
if (duplicateResult.hasDuplicates) {
results.push({
url: trimmedUrl,
status: 'skipped',
reason: `Duplicate story found (${duplicateResult.count} existing)`,
title: scrapedStory.title,
author: scrapedStory.author
});
skippedCount++;
continue;
}
}
} catch (error) {
console.warn('Duplicate check failed:', error);
// Continue with import if duplicate check fails
}
// Create the story
try {
const storyData = {
title: scrapedStory.title,
summary: scrapedStory.summary || undefined,
contentHtml: scrapedStory.content,
sourceUrl: scrapedStory.sourceUrl || trimmedUrl,
authorName: scrapedStory.author,
tagNames: scrapedStory.tags && scrapedStory.tags.length > 0 ? scrapedStory.tags : undefined,
};
const createUrl = `http://backend:8080/api/stories`;
const createResponse = await fetch(createUrl, {
method: 'POST',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
body: JSON.stringify(storyData),
});
if (!createResponse.ok) {
const errorData = await createResponse.json();
throw new Error(errorData.message || 'Failed to create story');
}
const createdStory = await createResponse.json();
results.push({
url: trimmedUrl,
status: 'imported',
title: scrapedStory.title,
author: scrapedStory.author,
storyId: createdStory.id
});
importedCount++;
console.log(`Successfully imported: ${scrapedStory.title} by ${scrapedStory.author} (ID: ${createdStory.id})`);
// Send progress update for successful import
await sendProgressUpdate(sessionId, {
type: 'progress',
current: i + 1,
total: urls.length,
message: `Imported "${scrapedStory.title}" by ${scrapedStory.author}`,
url: trimmedUrl,
title: scrapedStory.title,
author: scrapedStory.author
});
} catch (error) {
console.error(`Failed to create story for ${trimmedUrl}:`, error);
let errorMessage = 'Failed to create story';
if (error instanceof Error) {
errorMessage = error.message;
}
results.push({
url: trimmedUrl,
status: 'error',
error: errorMessage,
title: scrapedStory.title,
author: scrapedStory.author
});
errorCount++;
}
} catch (error) {
console.error(`Error processing URL ${url}:`, error);
let errorMessage = 'Unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
results.push({
url: url,
status: 'error',
error: errorMessage
});
errorCount++;
}
}
// Send completion notification
await sendProgressUpdate(sessionId, {
type: 'completed',
current: urls.length,
total: urls.length,
message: `Bulk import completed: ${importedCount} imported, ${skippedCount} skipped, ${errorCount} errors`,
results: results,
summary: {
total: urls.length,
imported: importedCount,
skipped: skippedCount,
errors: errorCount
}
});
console.log(`Bulk import completed: ${importedCount} imported, ${skippedCount} skipped, ${errorCount} errors`);
// Trigger Typesense reindex if any stories were imported
if (importedCount > 0) {
try {
console.log('Triggering Typesense reindex after bulk import...');
const reindexUrl = `http://backend:8080/api/stories/reindex-typesense`;
const reindexResponse = await fetch(reindexUrl, {
method: 'POST',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
});
if (reindexResponse.ok) {
const reindexResult = await reindexResponse.json();
console.log('Typesense reindex completed:', reindexResult);
} else {
console.warn('Typesense reindex failed:', reindexResponse.status);
}
} catch (error) {
console.warn('Failed to trigger Typesense reindex:', error);
// Don't fail the whole request if reindex fails
}
}
}
// Background processing function
async function processBulkImport(
urls: string[],
combineIntoOne: boolean,
sessionId: string,
authorization: string
) {
try {
// Check for authentication
const authorization = request.headers.get('authorization');
if (!authorization) {
return NextResponse.json(
{ error: 'Authentication required for bulk import' },
{ status: 401 }
);
}
const body = await request.json();
const { urls } = body as BulkImportRequest;
if (!urls || !Array.isArray(urls) || urls.length === 0) {
return NextResponse.json(
{ error: 'URLs array is required and must not be empty' },
{ status: 400 }
);
}
if (urls.length > 50) {
return NextResponse.json(
{ error: 'Maximum 50 URLs allowed per bulk import' },
{ status: 400 }
);
}
// Dynamic imports to prevent client-side bundling
const { StoryScraper } = await import('@/lib/scraper/scraper');
const scraper = new StoryScraper();
const results: ImportResult[] = [];
let importedCount = 0;
let skippedCount = 0;
let errorCount = 0;
console.log(`Starting bulk scraping for ${urls.length} URLs`);
console.log(`Environment NEXT_PUBLIC_API_URL: ${process.env.NEXT_PUBLIC_API_URL}`);
// For server-side API calls in Docker, use direct backend container URL
// Client-side calls use NEXT_PUBLIC_API_URL through nginx, but server-side needs direct container access
const serverSideApiBaseUrl = 'http://backend:8080/api';
console.log(`DEBUG: serverSideApiBaseUrl variable is: ${serverSideApiBaseUrl}`);
console.log(`Starting bulk scraping for ${urls.length} URLs${combineIntoOne ? ' (combine mode)' : ''}`);
console.log(`Session ID: ${sessionId}`);
// Quick test to verify backend connectivity
try {
@@ -84,208 +478,86 @@ export async function POST(request: NextRequest) {
console.error(`Backend connectivity test failed:`, error);
}
for (const url of urls) {
console.log(`Processing URL: ${url}`);
try {
// Validate URL format
if (!url || typeof url !== 'string' || url.trim() === '') {
results.push({
url: url || 'Empty URL',
status: 'error',
error: 'Invalid URL format'
});
errorCount++;
continue;
}
const trimmedUrl = url.trim();
// Scrape the story
const scrapedStory = await scraper.scrapeStory(trimmedUrl);
// Validate required fields
if (!scrapedStory.title || !scrapedStory.author || !scrapedStory.content) {
const missingFields = [];
if (!scrapedStory.title) missingFields.push('title');
if (!scrapedStory.author) missingFields.push('author');
if (!scrapedStory.content) missingFields.push('content');
results.push({
url: trimmedUrl,
status: 'skipped',
reason: `Missing required fields: ${missingFields.join(', ')}`,
title: scrapedStory.title,
author: scrapedStory.author
});
skippedCount++;
continue;
}
// Check for duplicates using query parameters
try {
// Use hardcoded backend URL for container-to-container communication
const duplicateCheckUrl = `http://backend:8080/api/stories/check-duplicate`;
console.log(`Duplicate check URL: ${duplicateCheckUrl}`);
const params = new URLSearchParams({
title: scrapedStory.title,
authorName: scrapedStory.author
});
const duplicateCheckResponse = await fetch(`${duplicateCheckUrl}?${params.toString()}`, {
method: 'GET',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
});
if (duplicateCheckResponse.ok) {
const duplicateResult = await duplicateCheckResponse.json();
if (duplicateResult.hasDuplicates) {
results.push({
url: trimmedUrl,
status: 'skipped',
reason: `Duplicate story found (${duplicateResult.count} existing)`,
title: scrapedStory.title,
author: scrapedStory.author
});
skippedCount++;
continue;
}
}
} catch (error) {
console.warn('Duplicate check failed:', error);
// Continue with import if duplicate check fails
}
// Create the story
try {
const storyData = {
title: scrapedStory.title,
summary: scrapedStory.summary || undefined,
contentHtml: scrapedStory.content,
sourceUrl: scrapedStory.sourceUrl || trimmedUrl,
authorName: scrapedStory.author,
tagNames: scrapedStory.tags && scrapedStory.tags.length > 0 ? scrapedStory.tags : undefined,
};
// Use hardcoded backend URL for container-to-container communication
const createUrl = `http://backend:8080/api/stories`;
console.log(`Create story URL: ${createUrl}`);
const createResponse = await fetch(createUrl, {
method: 'POST',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
body: JSON.stringify(storyData),
});
if (!createResponse.ok) {
const errorData = await createResponse.json();
throw new Error(errorData.message || 'Failed to create story');
}
const createdStory = await createResponse.json();
results.push({
url: trimmedUrl,
status: 'imported',
title: scrapedStory.title,
author: scrapedStory.author,
storyId: createdStory.id
});
importedCount++;
console.log(`Successfully imported: ${scrapedStory.title} by ${scrapedStory.author} (ID: ${createdStory.id})`);
} catch (error) {
console.error(`Failed to create story for ${trimmedUrl}:`, error);
let errorMessage = 'Failed to create story';
if (error instanceof Error) {
errorMessage = error.message;
}
results.push({
url: trimmedUrl,
status: 'error',
error: errorMessage,
title: scrapedStory.title,
author: scrapedStory.author
});
errorCount++;
}
} catch (error) {
console.error(`Error processing URL ${url}:`, error);
let errorMessage = 'Unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
results.push({
url: url,
status: 'error',
error: errorMessage
});
errorCount++;
}
// Handle combined mode
if (combineIntoOne) {
await processCombinedMode(urls, sessionId, authorization, scraper);
} else {
// Normal individual processing mode
await processIndividualMode(urls, sessionId, authorization, scraper);
}
const response: BulkImportResponse = {
results,
summary: {
total: urls.length,
imported: importedCount,
skipped: skippedCount,
errors: errorCount
}
};
console.log(`Bulk import completed:`, response.summary);
// Trigger Typesense reindex if any stories were imported
if (importedCount > 0) {
try {
console.log('Triggering Typesense reindex after bulk import...');
const reindexUrl = `http://backend:8080/api/stories/reindex-typesense`;
const reindexResponse = await fetch(reindexUrl, {
method: 'POST',
headers: {
'Authorization': authorization,
'Content-Type': 'application/json',
},
});
if (reindexResponse.ok) {
const reindexResult = await reindexResponse.json();
console.log('Typesense reindex completed:', reindexResult);
} else {
console.warn('Typesense reindex failed:', reindexResponse.status);
}
} catch (error) {
console.warn('Failed to trigger Typesense reindex:', error);
// Don't fail the whole request if reindex fails
}
}
return NextResponse.json(response);
} catch (error) {
console.error('Bulk import error:', error);
console.error('Background bulk import error:', error);
await sendProgressUpdate(sessionId, {
type: 'error',
current: 0,
total: urls.length,
message: 'Bulk import failed due to an error',
error: error instanceof Error ? error.message : 'Unknown error'
});
}
}
export async function POST(request: NextRequest) {
try {
// Check for authentication
const authorization = request.headers.get('authorization');
if (!authorization) {
return NextResponse.json(
{ error: 'Authentication required for bulk import' },
{ status: 401 }
);
}
const body = await request.json();
const { urls, combineIntoOne = false, sessionId } = body as BulkImportRequest;
if (!urls || !Array.isArray(urls) || urls.length === 0) {
return NextResponse.json(
{ error: 'URLs array is required and must not be empty' },
{ status: 400 }
);
}
if (urls.length > 200) {
return NextResponse.json(
{ error: 'Maximum 200 URLs allowed per bulk import' },
{ status: 400 }
);
}
if (!sessionId) {
return NextResponse.json(
{ error: 'Session ID is required for progress tracking' },
{ status: 400 }
);
}
// Start the background processing
processBulkImport(urls, combineIntoOne, sessionId, authorization).catch(error => {
console.error('Failed to start background processing:', error);
});
// Return immediately with session info
return NextResponse.json({
message: 'Bulk import started',
sessionId: sessionId,
totalUrls: urls.length,
combineMode: combineIntoOne
});
} catch (error) {
console.error('Bulk import initialization error:', error);
if (error instanceof Error) {
return NextResponse.json(
{ error: `Bulk import failed: ${error.message}` },
{ error: `Bulk import failed to start: ${error.message}` },
{ status: 500 }
);
}
return NextResponse.json(
{ error: 'Bulk import failed due to an unknown error' },
{ error: 'Bulk import failed to start due to an unknown error' },
{ status: 500 }
);
}

View File

@@ -5,6 +5,8 @@ import AppLayout from '../../components/layout/AppLayout';
import { useTheme } from '../../lib/theme';
import Button from '../../components/ui/Button';
import { storyApi, authorApi, databaseApi } from '../../lib/api';
import { useLibraryLayout, LibraryLayoutType } from '../../hooks/useLibraryLayout';
import LibrarySettings from '../../components/library/LibrarySettings';
type FontFamily = 'serif' | 'sans' | 'mono';
type FontSize = 'small' | 'medium' | 'large' | 'extra-large';
@@ -28,6 +30,7 @@ const defaultSettings: Settings = {
export default function SettingsPage() {
const { theme, setTheme } = useTheme();
const { layout, setLayout } = useLibraryLayout();
const [settings, setSettings] = useState<Settings>(defaultSettings);
const [saved, setSaved] = useState(false);
const [typesenseStatus, setTypesenseStatus] = useState<{
@@ -40,13 +43,13 @@ export default function SettingsPage() {
const [authorsSchema, setAuthorsSchema] = useState<any>(null);
const [showSchema, setShowSchema] = useState(false);
const [databaseStatus, setDatabaseStatus] = useState<{
backup: { loading: boolean; message: string; success?: boolean };
restore: { loading: boolean; message: string; success?: boolean };
clear: { loading: boolean; message: string; success?: boolean };
completeBackup: { loading: boolean; message: string; success?: boolean };
completeRestore: { loading: boolean; message: string; success?: boolean };
completeClear: { loading: boolean; message: string; success?: boolean };
}>({
backup: { loading: false, message: '' },
restore: { loading: false, message: '' },
clear: { loading: false, message: '' }
completeBackup: { loading: false, message: '' },
completeRestore: { loading: false, message: '' },
completeClear: { loading: false, message: '' }
});
// Load settings from localStorage on mount
@@ -166,14 +169,15 @@ export default function SettingsPage() {
}
};
const handleDatabaseBackup = async () => {
const handleCompleteBackup = async () => {
setDatabaseStatus(prev => ({
...prev,
backup: { loading: true, message: 'Creating backup...', success: undefined }
completeBackup: { loading: true, message: 'Creating complete backup...', success: undefined }
}));
try {
const backupBlob = await databaseApi.backup();
const backupBlob = await databaseApi.backupComplete();
// Create download link
const url = window.URL.createObjectURL(backupBlob);
@@ -181,7 +185,7 @@ export default function SettingsPage() {
link.href = url;
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
link.download = `storycove_backup_${timestamp}.sql`;
link.download = `storycove_complete_backup_${timestamp}.zip`;
document.body.appendChild(link);
link.click();
@@ -190,12 +194,12 @@ export default function SettingsPage() {
setDatabaseStatus(prev => ({
...prev,
backup: { loading: false, message: 'Backup downloaded successfully', success: true }
completeBackup: { loading: false, message: 'Complete backup downloaded successfully', success: true }
}));
} catch (error: any) {
setDatabaseStatus(prev => ({
...prev,
backup: { loading: false, message: error.message || 'Backup failed', success: false }
completeBackup: { loading: false, message: error.message || 'Complete backup failed', success: false }
}));
}
@@ -203,42 +207,42 @@ export default function SettingsPage() {
setTimeout(() => {
setDatabaseStatus(prev => ({
...prev,
backup: { loading: false, message: '', success: undefined }
completeBackup: { loading: false, message: '', success: undefined }
}));
}, 5000);
};
const handleDatabaseRestore = async (event: React.ChangeEvent<HTMLInputElement>) => {
const handleCompleteRestore = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
// Reset the input so the same file can be selected again
event.target.value = '';
if (!file.name.endsWith('.sql')) {
if (!file.name.endsWith('.zip')) {
setDatabaseStatus(prev => ({
...prev,
restore: { loading: false, message: 'Please select a .sql file', success: false }
completeRestore: { loading: false, message: 'Please select a .zip file', success: false }
}));
return;
}
const confirmed = window.confirm(
'Are you sure you want to restore the database? This will PERMANENTLY DELETE all current data and replace it with the backup data. This action cannot be undone!'
'Are you sure you want to restore the complete backup? This will PERMANENTLY DELETE all current data AND files (cover images, avatars) and replace them with the backup data. This action cannot be undone!'
);
if (!confirmed) return;
setDatabaseStatus(prev => ({
...prev,
restore: { loading: true, message: 'Restoring database...', success: undefined }
completeRestore: { loading: true, message: 'Restoring complete backup...', success: undefined }
}));
try {
const result = await databaseApi.restore(file);
const result = await databaseApi.restoreComplete(file);
setDatabaseStatus(prev => ({
...prev,
restore: {
completeRestore: {
loading: false,
message: result.success ? result.message : result.message,
success: result.success
@@ -247,7 +251,7 @@ export default function SettingsPage() {
} catch (error: any) {
setDatabaseStatus(prev => ({
...prev,
restore: { loading: false, message: error.message || 'Restore failed', success: false }
completeRestore: { loading: false, message: error.message || 'Complete restore failed', success: false }
}));
}
@@ -255,37 +259,37 @@ export default function SettingsPage() {
setTimeout(() => {
setDatabaseStatus(prev => ({
...prev,
restore: { loading: false, message: '', success: undefined }
completeRestore: { loading: false, message: '', success: undefined }
}));
}, 10000);
};
const handleDatabaseClear = async () => {
const handleCompleteClear = async () => {
const confirmed = window.confirm(
'Are you ABSOLUTELY SURE you want to clear the entire database? This will PERMANENTLY DELETE ALL stories, authors, series, tags, and collections. This action cannot be undone!'
'Are you ABSOLUTELY SURE you want to clear the entire database AND all files? This will PERMANENTLY DELETE ALL stories, authors, series, tags, collections, AND all uploaded images (covers, avatars). This action cannot be undone!'
);
if (!confirmed) return;
const doubleConfirmed = window.confirm(
'This is your final warning! Clicking OK will DELETE EVERYTHING in your StoryCove database. Are you completely certain you want to proceed?'
'This is your final warning! Clicking OK will DELETE EVERYTHING in your StoryCove database AND all uploaded files. Are you completely certain you want to proceed?'
);
if (!doubleConfirmed) return;
setDatabaseStatus(prev => ({
...prev,
clear: { loading: true, message: 'Clearing database...', success: undefined }
completeClear: { loading: true, message: 'Clearing database and files...', success: undefined }
}));
try {
const result = await databaseApi.clear();
const result = await databaseApi.clearComplete();
setDatabaseStatus(prev => ({
...prev,
clear: {
completeClear: {
loading: false,
message: result.success
? `Database cleared successfully. Deleted ${result.deletedRecords} records.`
? `Database and files cleared successfully. Deleted ${result.deletedRecords} records.`
: result.message,
success: result.success
}
@@ -293,7 +297,7 @@ export default function SettingsPage() {
} catch (error: any) {
setDatabaseStatus(prev => ({
...prev,
clear: { loading: false, message: error.message || 'Clear operation failed', success: false }
completeClear: { loading: false, message: error.message || 'Clear operation failed', success: false }
}));
}
@@ -301,7 +305,7 @@ export default function SettingsPage() {
setTimeout(() => {
setDatabaseStatus(prev => ({
...prev,
clear: { loading: false, message: '', success: undefined }
completeClear: { loading: false, message: '', success: undefined }
}));
}, 10000);
};
@@ -349,6 +353,60 @@ export default function SettingsPage() {
</button>
</div>
</div>
{/* Library Layout */}
<div>
<label className="block text-sm font-medium theme-header mb-2">
Library Layout
</label>
<div className="space-y-3">
<div className="flex gap-4 flex-wrap">
<button
onClick={() => setLayout('sidebar')}
className={`px-4 py-2 rounded-lg border transition-colors ${
layout === 'sidebar'
? 'theme-accent-bg text-white border-transparent'
: 'theme-card theme-text theme-border hover:border-gray-400'
}`}
>
📋 Sidebar Layout
</button>
<button
onClick={() => setLayout('toolbar')}
className={`px-4 py-2 rounded-lg border transition-colors ${
layout === 'toolbar'
? 'theme-accent-bg text-white border-transparent'
: 'theme-card theme-text theme-border hover:border-gray-400'
}`}
>
🛠 Toolbar Layout
</button>
<button
onClick={() => setLayout('minimal')}
className={`px-4 py-2 rounded-lg border transition-colors ${
layout === 'minimal'
? 'theme-accent-bg text-white border-transparent'
: 'theme-card theme-text theme-border hover:border-gray-400'
}`}
>
Minimal Layout
</button>
</div>
<div className="text-sm theme-text">
<div className="grid grid-cols-1 md:grid-cols-3 gap-3 mt-3">
<div className="text-xs">
<strong>Sidebar:</strong> Filters and controls in a side panel, maximum space for stories
</div>
<div className="text-xs">
<strong>Toolbar:</strong> Everything visible at once with integrated search and tag filters
</div>
<div className="text-xs">
<strong>Minimal:</strong> Clean, content-focused design with floating controls
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@@ -616,90 +674,90 @@ export default function SettingsPage() {
<div className="theme-card theme-shadow rounded-lg p-6">
<h2 className="text-xl font-semibold theme-header mb-4">Database Management</h2>
<p className="theme-text mb-6">
Backup, restore, or clear your StoryCove database. These are powerful tools - use with caution!
Backup, restore, or clear your StoryCove database and files. These comprehensive operations include both your data and uploaded images.
</p>
<div className="space-y-6">
{/* Backup Section */}
<div className="border theme-border rounded-lg p-4">
<h3 className="text-lg font-semibold theme-header mb-3">💾 Backup Database</h3>
{/* Complete Backup Section */}
<div className="border theme-border rounded-lg p-4 border-blue-200 dark:border-blue-800">
<h3 className="text-lg font-semibold theme-header mb-3">📦 Create Backup</h3>
<p className="text-sm theme-text mb-3">
Download a complete backup of your database as an SQL file. This includes all stories, authors, tags, series, and collections.
Download a complete backup as a ZIP file. This includes your database AND all uploaded files (cover images, avatars). This is a comprehensive backup of your entire StoryCove installation.
</p>
<Button
onClick={handleDatabaseBackup}
disabled={databaseStatus.backup.loading}
loading={databaseStatus.backup.loading}
onClick={handleCompleteBackup}
disabled={databaseStatus.completeBackup.loading}
loading={databaseStatus.completeBackup.loading}
variant="primary"
className="w-full sm:w-auto"
>
{databaseStatus.backup.loading ? 'Creating Backup...' : 'Download Backup'}
{databaseStatus.completeBackup.loading ? 'Creating Backup...' : 'Download Backup'}
</Button>
{databaseStatus.backup.message && (
{databaseStatus.completeBackup.message && (
<div className={`text-sm p-2 rounded mt-3 ${
databaseStatus.backup.success
databaseStatus.completeBackup.success
? 'bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200'
: 'bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200'
}`}>
{databaseStatus.backup.message}
{databaseStatus.completeBackup.message}
</div>
)}
</div>
{/* Restore Section */}
<div className="border theme-border rounded-lg p-4 border-orange-200 dark:border-orange-800">
<h3 className="text-lg font-semibold theme-header mb-3">📥 Restore Database</h3>
<h3 className="text-lg font-semibold theme-header mb-3">📥 Restore Backup</h3>
<p className="text-sm theme-text mb-3">
<strong className="text-orange-600 dark:text-orange-400">⚠️ Warning:</strong> This will completely replace your current database with the backup file. All existing data will be permanently deleted.
<strong className="text-orange-600 dark:text-orange-400">⚠️ Warning:</strong> This will completely replace your current database AND all files with the backup. All existing data and uploaded files will be permanently deleted.
</p>
<div className="flex items-center gap-3">
<input
type="file"
accept=".sql"
onChange={handleDatabaseRestore}
disabled={databaseStatus.restore.loading}
accept=".zip"
onChange={handleCompleteRestore}
disabled={databaseStatus.completeRestore.loading}
className="flex-1 text-sm theme-text file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:theme-accent-bg file:text-white hover:file:bg-opacity-90 file:cursor-pointer"
/>
</div>
{databaseStatus.restore.message && (
{databaseStatus.completeRestore.message && (
<div className={`text-sm p-2 rounded mt-3 ${
databaseStatus.restore.success
databaseStatus.completeRestore.success
? 'bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200'
: 'bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200'
}`}>
{databaseStatus.restore.message}
{databaseStatus.completeRestore.message}
</div>
)}
{databaseStatus.restore.loading && (
{databaseStatus.completeRestore.loading && (
<div className="text-sm theme-text mt-3 flex items-center gap-2">
<div className="animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full"></div>
Restoring database...
Restoring backup...
</div>
)}
</div>
{/* Clear Section */}
<div className="border theme-border rounded-lg p-4 border-red-200 dark:border-red-800">
<h3 className="text-lg font-semibold theme-header mb-3">🗑️ Clear Database</h3>
{/* Clear Everything Section */}
<div className="border theme-border rounded-lg p-4 border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/10">
<h3 className="text-lg font-semibold theme-header mb-3">🗑️ Clear Everything</h3>
<p className="text-sm theme-text mb-3">
<strong className="text-red-600 dark:text-red-400">⚠️ Danger Zone:</strong> This will permanently delete ALL data from your database. Stories, authors, tags, series, and collections will be completely removed. This action cannot be undone!
<strong className="text-red-600 dark:text-red-400">⚠️ Danger Zone:</strong> This will permanently delete ALL data from your database AND all uploaded files (cover images, avatars). Everything will be completely removed. This action cannot be undone!
</p>
<Button
onClick={handleDatabaseClear}
disabled={databaseStatus.clear.loading}
loading={databaseStatus.clear.loading}
onClick={handleCompleteClear}
disabled={databaseStatus.completeClear.loading}
loading={databaseStatus.completeClear.loading}
variant="secondary"
className="w-full sm:w-auto bg-red-600 hover:bg-red-700 text-white border-red-600"
className="w-full sm:w-auto bg-red-700 hover:bg-red-800 text-white border-red-700"
>
{databaseStatus.clear.loading ? 'Clearing Database...' : 'Clear All Data'}
{databaseStatus.completeClear.loading ? 'Clearing Everything...' : 'Clear Everything'}
</Button>
{databaseStatus.clear.message && (
{databaseStatus.completeClear.message && (
<div className={`text-sm p-2 rounded mt-3 ${
databaseStatus.clear.success
databaseStatus.completeClear.success
? 'bg-green-50 dark:bg-green-900/20 text-green-800 dark:text-green-200'
: 'bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-200'
}`}>
{databaseStatus.clear.message}
{databaseStatus.completeClear.message}
</div>
)}
</div>
@@ -708,14 +766,33 @@ export default function SettingsPage() {
<p className="font-medium mb-1">💡 Best Practices:</p>
<ul className="text-xs space-y-1 ml-4">
<li>• <strong>Always backup</strong> before performing restore or clear operations</li>
<li>• <strong>Test restores</strong> in a development environment when possible</li>
<li>• <strong>Store backups safely</strong> in multiple locations for important data</li>
<li>• <strong>Test restores</strong> in a development environment when possible</li>
<li>• <strong>Backup files (.zip)</strong> contain both database and all uploaded files</li>
<li>• <strong>Verify backup files</strong> are complete before relying on them</li>
</ul>
</div>
</div>
</div>
{/* Library Settings */}
<LibrarySettings />
{/* Tag Management */}
<div className="theme-card theme-shadow rounded-lg p-6">
<h2 className="text-xl font-semibold theme-header mb-4">Tag Management</h2>
<p className="theme-text mb-6">
Manage your story tags with colors, descriptions, and aliases. Use the Tag Maintenance page to organize and customize your tags.
</p>
<Button
href="/settings/tag-maintenance"
variant="secondary"
className="w-full sm:w-auto"
>
🏷️ Open Tag Maintenance
</Button>
</div>
{/* Actions */}
<div className="flex justify-end gap-4">
<Button

View File

@@ -0,0 +1,799 @@
'use client';
import { useState, useEffect } from 'react';
import AppLayout from '../../../components/layout/AppLayout';
import { tagApi } from '../../../lib/api';
import { Tag } from '../../../types/api';
import Button from '../../../components/ui/Button';
import { Input } from '../../../components/ui/Input';
import LoadingSpinner from '../../../components/ui/LoadingSpinner';
import TagDisplay from '../../../components/tags/TagDisplay';
import TagEditModal from '../../../components/tags/TagEditModal';
export default function TagMaintenancePage() {
const [tags, setTags] = useState<Tag[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [sortBy, setSortBy] = useState<'name' | 'storyCount' | 'createdAt'>('name');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
const [selectedTag, setSelectedTag] = useState<Tag | null>(null);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [selectedTagIds, setSelectedTagIds] = useState<Set<string>>(new Set());
const [isMergeModalOpen, setIsMergeModalOpen] = useState(false);
const [mergeTargetTagId, setMergeTargetTagId] = useState<string>('');
const [mergePreview, setMergePreview] = useState<any>(null);
const [merging, setMerging] = useState(false);
const [isMergeSuggestionsModalOpen, setIsMergeSuggestionsModalOpen] = useState(false);
const [mergeSuggestions, setMergeSuggestions] = useState<Array<{
group: Tag[];
similarity: number;
reason: string;
}>>([]);
useEffect(() => {
loadTags();
}, []);
const loadTags = async () => {
try {
setLoading(true);
const result = await tagApi.getTags({
page: 0,
size: 1000, // Load all tags for maintenance
sortBy,
sortDir: sortDirection
});
setTags(result.content || []);
} catch (error) {
console.error('Failed to load tags:', error);
setTags([]);
} finally {
setLoading(false);
}
};
const handleTagSave = (updatedTag: Tag) => {
if (selectedTag) {
// Update existing tag
setTags(prev => prev.map(tag =>
tag.id === updatedTag.id ? updatedTag : tag
));
} else {
// Add new tag
setTags(prev => [...prev, updatedTag]);
}
setSelectedTag(null);
setIsEditModalOpen(false);
setIsCreateModalOpen(false);
};
const handleTagDelete = (deletedTag: Tag) => {
setTags(prev => prev.filter(tag => tag.id !== deletedTag.id));
setSelectedTag(null);
setIsEditModalOpen(false);
};
const handleEditTag = (tag: Tag) => {
setSelectedTag(tag);
setIsEditModalOpen(true);
};
const handleCreateTag = () => {
setSelectedTag(null);
setIsCreateModalOpen(true);
};
const handleSortChange = (newSortBy: typeof sortBy) => {
if (newSortBy === sortBy) {
setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
} else {
setSortBy(newSortBy);
setSortDirection('asc');
}
};
const handleTagSelection = (tagId: string, selected: boolean) => {
setSelectedTagIds(prev => {
const newSet = new Set(prev);
if (selected) {
newSet.add(tagId);
} else {
newSet.delete(tagId);
}
return newSet;
});
};
const handleSelectAll = (selected: boolean) => {
if (selected) {
setSelectedTagIds(new Set(filteredTags.map(tag => tag.id)));
} else {
setSelectedTagIds(new Set());
}
};
const handleSelectUnused = () => {
const unusedTags = filteredTags.filter(tag => !tag.storyCount || tag.storyCount === 0);
setSelectedTagIds(new Set(unusedTags.map(tag => tag.id)));
};
const handleDeleteSelected = async () => {
if (selectedTagIds.size === 0) return;
const confirmation = confirm(
`Are you sure you want to delete ${selectedTagIds.size} selected tag(s)? This action cannot be undone.`
);
if (!confirmation) return;
try {
const deletePromises = Array.from(selectedTagIds).map(tagId =>
tagApi.deleteTag(tagId)
);
await Promise.all(deletePromises);
// Reload tags and reset selection
await loadTags();
setSelectedTagIds(new Set());
} catch (error) {
console.error('Failed to delete tags:', error);
alert('Failed to delete some tags. Please try again.');
}
};
const generateMergeSuggestions = () => {
const suggestions: Array<{
group: Tag[];
similarity: number;
reason: string;
}> = [];
// Helper function to calculate similarity between two strings
const calculateSimilarity = (str1: string, str2: string): number => {
const s1 = str1.toLowerCase();
const s2 = str2.toLowerCase();
// Exact match
if (s1 === s2) return 1.0;
// Check for common patterns
const patterns = [
// Plural vs singular
{ regex: /(.+)s$/, match: (a: string, b: string) => a === b + 's' || b === a + 's' },
// Hyphen vs underscore vs space
{ regex: /[-_\s]/, match: (a: string, b: string) =>
a.replace(/[-_\s]/g, '') === b.replace(/[-_\s]/g, '') },
// Common abbreviations
{ regex: /\b(and|&)\b/, match: (a: string, b: string) =>
a.replace(/\band\b/g, '&') === b || a === b.replace(/\band\b/g, '&') },
];
for (const pattern of patterns) {
if (pattern.match(s1, s2)) return 0.9;
}
// Levenshtein distance for similar words
const distance = levenshteinDistance(s1, s2);
const maxLength = Math.max(s1.length, s2.length);
const similarity = 1 - (distance / maxLength);
return similarity > 0.8 ? similarity : 0;
};
// Simple Levenshtein distance implementation
const levenshteinDistance = (str1: string, str2: string): number => {
const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
for (let i = 0; i <= str1.length; i++) matrix[0][i] = i;
for (let j = 0; j <= str2.length; j++) matrix[j][0] = j;
for (let j = 1; j <= str2.length; j++) {
for (let i = 1; i <= str1.length; i++) {
const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
matrix[j][i] = Math.min(
matrix[j][i - 1] + 1,
matrix[j - 1][i] + 1,
matrix[j - 1][i - 1] + indicator
);
}
}
return matrix[str2.length][str1.length];
};
// Find similar tags
const processedTags = new Set<string>();
for (let i = 0; i < tags.length; i++) {
if (processedTags.has(tags[i].id)) continue;
const similarTags = [tags[i]];
processedTags.add(tags[i].id);
for (let j = i + 1; j < tags.length; j++) {
if (processedTags.has(tags[j].id)) continue;
const similarity = calculateSimilarity(tags[i].name, tags[j].name);
if (similarity > 0.8) {
similarTags.push(tags[j]);
processedTags.add(tags[j].id);
}
}
if (similarTags.length > 1) {
const maxSimilarity = Math.max(...similarTags.slice(1).map(tag =>
calculateSimilarity(similarTags[0].name, tag.name)
));
let reason = 'Similar names detected';
if (maxSimilarity === 0.9) {
reason = 'Likely plural/singular or formatting variations';
} else if (maxSimilarity > 0.95) {
reason = 'Very similar names, possible duplicates';
}
suggestions.push({
group: similarTags,
similarity: maxSimilarity,
reason
});
}
}
// Sort by similarity descending
suggestions.sort((a, b) => b.similarity - a.similarity);
setMergeSuggestions(suggestions);
setIsMergeSuggestionsModalOpen(true);
};
const handleMergeSelected = () => {
if (selectedTagIds.size < 2) {
alert('Please select at least 2 tags to merge');
return;
}
setIsMergeModalOpen(true);
};
const handleMergePreview = async () => {
if (!mergeTargetTagId || selectedTagIds.size < 2) return;
try {
const sourceTagIds = Array.from(selectedTagIds).filter(id => id !== mergeTargetTagId);
const preview = await tagApi.previewMerge(sourceTagIds, mergeTargetTagId);
setMergePreview(preview);
} catch (error) {
console.error('Failed to preview merge:', error);
alert('Failed to preview merge');
}
};
const handleConfirmMerge = async () => {
if (!mergeTargetTagId || selectedTagIds.size < 2) return;
try {
setMerging(true);
const sourceTagIds = Array.from(selectedTagIds).filter(id => id !== mergeTargetTagId);
await tagApi.mergeTags(sourceTagIds, mergeTargetTagId);
// Reload tags and reset state
await loadTags();
setSelectedTagIds(new Set());
setMergeTargetTagId('');
setMergePreview(null);
setIsMergeModalOpen(false);
} catch (error) {
console.error('Failed to merge tags:', error);
alert('Failed to merge tags');
} finally {
setMerging(false);
}
};
// Filter and sort tags
const filteredTags = tags
.filter(tag =>
tag.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
(tag.description && tag.description.toLowerCase().includes(searchQuery.toLowerCase()))
)
.sort((a, b) => {
let aValue, bValue;
switch (sortBy) {
case 'name':
aValue = a.name.toLowerCase();
bValue = b.name.toLowerCase();
break;
case 'storyCount':
aValue = a.storyCount || 0;
bValue = b.storyCount || 0;
break;
case 'createdAt':
aValue = new Date(a.createdAt || 0).getTime();
bValue = new Date(b.createdAt || 0).getTime();
break;
default:
return 0;
}
if (sortDirection === 'asc') {
return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
} else {
return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
}
});
const getSortIcon = (column: typeof sortBy) => {
if (sortBy !== column) return '↕️';
return sortDirection === 'asc' ? '↑' : '↓';
};
const tagStats = {
total: tags.length,
withColors: tags.filter(tag => tag.color).length,
withDescriptions: tags.filter(tag => tag.description).length,
withAliases: tags.filter(tag => tag.aliasCount && tag.aliasCount > 0).length,
unused: tags.filter(tag => !tag.storyCount || tag.storyCount === 0).length
};
if (loading) {
return (
<AppLayout>
<div className="flex items-center justify-center py-20">
<LoadingSpinner size="lg" />
</div>
</AppLayout>
);
}
return (
<AppLayout>
<div className="max-w-6xl mx-auto space-y-6">
{/* Header */}
<div className="flex justify-between items-start">
<div>
<h1 className="text-3xl font-bold theme-header">Tag Maintenance</h1>
<p className="theme-text mt-2">
Manage tag colors, descriptions, and aliases for better organization
</p>
</div>
<div className="flex gap-3">
<Button href="/settings" variant="ghost">
Back to Settings
</Button>
<Button onClick={handleCreateTag} variant="primary">
+ Create Tag
</Button>
</div>
</div>
{/* Statistics */}
<div className="theme-card theme-shadow rounded-lg p-6">
<h2 className="text-lg font-semibold theme-header mb-4">Tag Statistics</h2>
<div className="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
<div>
<div className="text-2xl font-bold theme-accent">{tagStats.total}</div>
<div className="text-sm theme-text">Total Tags</div>
</div>
<div>
<div className="text-2xl font-bold text-blue-600">{tagStats.withColors}</div>
<div className="text-sm theme-text">With Colors</div>
</div>
<div>
<div className="text-2xl font-bold text-green-600">{tagStats.withDescriptions}</div>
<div className="text-sm theme-text">With Descriptions</div>
</div>
<div>
<div className="text-2xl font-bold text-purple-600">{tagStats.withAliases}</div>
<div className="text-sm theme-text">With Aliases</div>
</div>
<div>
<div className="text-2xl font-bold text-gray-500">{tagStats.unused}</div>
<div className="text-sm theme-text">Unused</div>
</div>
</div>
</div>
{/* Controls */}
<div className="theme-card theme-shadow rounded-lg p-6">
<div className="flex flex-col md:flex-row gap-4 items-center">
<div className="flex-1">
<Input
type="search"
placeholder="Search tags by name or description..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full"
/>
</div>
<div className="flex gap-2">
<button
onClick={() => handleSortChange('name')}
className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
>
Name {getSortIcon('name')}
</button>
<button
onClick={() => handleSortChange('storyCount')}
className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
>
Usage {getSortIcon('storyCount')}
</button>
<button
onClick={() => handleSortChange('createdAt')}
className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
>
Date {getSortIcon('createdAt')}
</button>
</div>
</div>
</div>
{/* Tags List */}
<div className="theme-card theme-shadow rounded-lg p-6">
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-semibold theme-header">
Tags ({filteredTags.length})
</h2>
<div className="flex gap-2">
<Button
variant="secondary"
size="sm"
onClick={generateMergeSuggestions}
>
🔍 Merge Suggestions
</Button>
{selectedTagIds.size > 0 && (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedTagIds(new Set())}
>
Clear Selection ({selectedTagIds.size})
</Button>
<Button
variant="danger"
size="sm"
onClick={handleDeleteSelected}
>
🗑 Delete Selected
</Button>
<Button
variant="primary"
size="sm"
onClick={handleMergeSelected}
disabled={selectedTagIds.size < 2}
>
Merge Selected
</Button>
</>
)}
</div>
</div>
{filteredTags.length > 0 && (
<div className="mb-4 flex items-center gap-4">
<div className="flex items-center gap-2">
<input
type="checkbox"
checked={filteredTags.length > 0 && selectedTagIds.size === filteredTags.length}
onChange={(e) => handleSelectAll(e.target.checked)}
className="rounded"
/>
<label className="text-sm theme-text">Select All</label>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleSelectUnused}
disabled={tagStats.unused === 0}
>
Select Unused ({tagStats.unused})
</Button>
</div>
)}
{filteredTags.length === 0 ? (
<div className="text-center py-12">
<p className="theme-text text-lg mb-4">
{searchQuery ? 'No tags match your search.' : 'No tags found.'}
</p>
{!searchQuery && (
<Button onClick={handleCreateTag} variant="primary">
Create Your First Tag
</Button>
)}
</div>
) : (
<div className="space-y-3">
{filteredTags.map((tag) => (
<div
key={tag.id}
className="flex items-center justify-between p-4 border theme-border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
>
<div className="flex items-center gap-4 min-w-0 flex-1">
<input
type="checkbox"
checked={selectedTagIds.has(tag.id)}
onChange={(e) => handleTagSelection(tag.id, e.target.checked)}
className="rounded"
/>
<TagDisplay
tag={tag}
size="md"
showAliasesTooltip={true}
clickable={false}
/>
<div className="min-w-0 flex-1">
{tag.description && (
<p className="text-sm theme-text-muted mt-1 truncate">
{tag.description}
</p>
)}
<div className="flex gap-4 text-xs theme-text-muted mt-1">
<a
href={`/library?tags=${encodeURIComponent(tag.name)}`}
className="hover:theme-accent hover:underline cursor-pointer"
title={`View ${tag.storyCount || 0} stories with tag "${tag.name}"`}
>
{tag.storyCount || 0} stories
</a>
{tag.aliasCount && tag.aliasCount > 0 && (
<span>{tag.aliasCount} aliases</span>
)}
{tag.createdAt && (
<span>Created {new Date(tag.createdAt).toLocaleDateString()}</span>
)}
</div>
</div>
</div>
<div className="flex gap-2 ml-4">
<Button
variant="ghost"
size="sm"
onClick={() => handleEditTag(tag)}
>
Edit
</Button>
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Edit Modal */}
<TagEditModal
tag={selectedTag || undefined}
isOpen={isEditModalOpen}
onClose={() => {
setIsEditModalOpen(false);
setSelectedTag(null);
}}
onSave={handleTagSave}
onDelete={handleTagDelete}
/>
{/* Create Modal */}
<TagEditModal
tag={undefined}
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onSave={handleTagSave}
/>
{/* Merge Modal */}
{isMergeModalOpen && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
<h2 className="text-2xl font-bold theme-header mb-4">Merge Tags</h2>
<div className="space-y-4">
<div>
<p className="theme-text mb-2">
You have selected {selectedTagIds.size} tags to merge.
</p>
<p className="text-sm theme-text-muted mb-4">
Choose which tag should become the canonical name. All other tags will become aliases.
</p>
</div>
{/* Target Tag Selection */}
<div>
<label className="block text-sm font-medium theme-text mb-2">
Canonical Tag (keep this name):
</label>
<select
value={mergeTargetTagId}
onChange={(e) => {
setMergeTargetTagId(e.target.value);
setMergePreview(null);
}}
className="w-full p-2 border theme-border rounded-lg theme-card theme-text"
>
<option value="">Select canonical tag...</option>
{Array.from(selectedTagIds).map(tagId => {
const tag = tags.find(t => t.id === tagId);
return tag ? (
<option key={tagId} value={tagId}>
{tag.name} ({tag.storyCount || 0} stories)
</option>
) : null;
})}
</select>
</div>
{/* Preview Button */}
{mergeTargetTagId && (
<Button
onClick={handleMergePreview}
variant="secondary"
className="w-full"
>
Preview Merge
</Button>
)}
{/* Merge Preview */}
{mergePreview && (
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
<h3 className="font-medium theme-header mb-2">Merge Preview</h3>
<div className="space-y-2 text-sm theme-text">
<p>
<strong>Result:</strong> "{mergePreview.targetTagName}" with {mergePreview.totalResultStoryCount} stories
</p>
{mergePreview.aliasesToCreate && mergePreview.aliasesToCreate.length > 0 && (
<div>
<strong>Aliases to create:</strong>
<ul className="ml-4 mt-1 list-disc">
{mergePreview.aliasesToCreate.map((alias: string) => (
<li key={alias}>{alias}</li>
))}
</ul>
</div>
)}
</div>
</div>
)}
{/* Actions */}
<div className="flex gap-3 pt-4">
<Button
onClick={() => {
setIsMergeModalOpen(false);
setMergeTargetTagId('');
setMergePreview(null);
}}
variant="ghost"
className="flex-1"
>
Cancel
</Button>
<Button
onClick={handleConfirmMerge}
variant="primary"
disabled={!mergeTargetTagId || merging}
className="flex-1"
>
{merging ? 'Merging...' : 'Confirm Merge'}
</Button>
</div>
</div>
</div>
</div>
)}
{/* Merge Suggestions Modal */}
{isMergeSuggestionsModalOpen && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-4xl w-full mx-4 max-h-[80vh] overflow-y-auto">
<h2 className="text-2xl font-bold theme-header mb-4">Merge Suggestions</h2>
<div className="space-y-4">
<p className="theme-text">
Found {mergeSuggestions.length} potential merge opportunities based on similar tag names.
</p>
{mergeSuggestions.length === 0 ? (
<div className="text-center py-8">
<p className="theme-text text-lg">No similar tags found.</p>
<p className="theme-text-muted text-sm mt-2">
All your tags appear to have unique names.
</p>
</div>
) : (
<div className="space-y-4">
{mergeSuggestions.map((suggestion, index) => (
<div
key={index}
className="border theme-border rounded-lg p-4 bg-yellow-50 dark:bg-yellow-900/20"
>
<div className="flex justify-between items-start mb-3">
<div>
<h3 className="font-medium theme-header">
Suggestion {index + 1}
</h3>
<p className="text-sm theme-text-muted">
{suggestion.reason} (Similarity: {(suggestion.similarity * 100).toFixed(1)}%)
</p>
</div>
<Button
variant="primary"
size="sm"
onClick={() => {
// Pre-select these tags for merging and go directly to merge modal
const suggestedTagIds = new Set(suggestion.group.map(tag => tag.id));
setSelectedTagIds(suggestedTagIds);
setIsMergeSuggestionsModalOpen(false);
// Open merge modal directly
setIsMergeModalOpen(true);
setMergeTargetTagId('');
setMergePreview(null);
}}
>
Merge These
</Button>
</div>
<div className="flex flex-wrap gap-2">
{suggestion.group.map((tag, tagIndex) => (
<div key={tag.id} className="flex items-center gap-2">
<TagDisplay
tag={tag}
size="sm"
showAliasesTooltip={true}
clickable={false}
/>
<span className="text-xs theme-text-muted">
({tag.storyCount || 0} stories)
</span>
{tagIndex < suggestion.group.length - 1 && (
<span className="text-gray-400"></span>
)}
</div>
))}
</div>
</div>
))}
</div>
)}
{/* Actions */}
<div className="flex gap-3 pt-4 border-t theme-border">
<Button
onClick={() => setIsMergeSuggestionsModalOpen(false)}
variant="ghost"
className="flex-1"
>
Close
</Button>
{mergeSuggestions.length > 0 && (
<Button
onClick={() => {
// Select all suggested tags for batch processing
const allSuggestedTagIds = new Set<string>();
mergeSuggestions.forEach(suggestion => {
suggestion.group.forEach(tag => allSuggestedTagIds.add(tag.id));
});
setSelectedTagIds(allSuggestedTagIds);
setIsMergeSuggestionsModalOpen(false);
}}
variant="secondary"
className="flex-1"
>
Select All Suggested ({mergeSuggestions.reduce((acc, s) => acc + s.group.length, 0)} tags)
</Button>
)}
</div>
</div>
</div>
</div>
)}
</AppLayout>
);
}

View File

@@ -9,6 +9,8 @@ import { Story, Collection } from '../../../../types/api';
import AppLayout from '../../../../components/layout/AppLayout';
import Button from '../../../../components/ui/Button';
import LoadingSpinner from '../../../../components/ui/LoadingSpinner';
import TagDisplay from '../../../../components/tags/TagDisplay';
import TableOfContents from '../../../../components/stories/TableOfContents';
import { calculateReadingTime } from '../../../../lib/settings';
export default function StoryDetailPage() {
@@ -21,6 +23,7 @@ export default function StoryDetailPage() {
const [collections, setCollections] = useState<Collection[]>([]);
const [loading, setLoading] = useState(true);
const [updating, setUpdating] = useState(false);
const [isExporting, setIsExporting] = useState(false);
useEffect(() => {
const loadStoryData = async () => {
@@ -65,6 +68,53 @@ export default function StoryDetailPage() {
}
};
const handleEPUBExport = async () => {
if (!story) return;
setIsExporting(true);
try {
const token = localStorage.getItem('auth-token');
const response = await fetch(`/api/stories/${story.id}/epub`, {
method: 'GET',
headers: {
'Authorization': token ? `Bearer ${token}` : '',
},
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
// Get filename from Content-Disposition header or create default
const contentDisposition = response.headers.get('Content-Disposition');
let filename = `${story.title}.epub`;
if (contentDisposition) {
const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match && match[1]) {
filename = match[1].replace(/['"]/g, '');
}
}
link.download = filename;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(link);
} else if (response.status === 401 || response.status === 403) {
alert('Authentication required. Please log in.');
} else {
throw new Error('Failed to export EPUB');
}
} catch (error) {
console.error('Error exporting EPUB:', error);
alert('Failed to export EPUB. Please try again.');
} finally {
setIsExporting(false);
}
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
@@ -317,18 +367,27 @@ export default function StoryDetailPage() {
</div>
)}
{/* Table of Contents */}
<TableOfContents
htmlContent={story.contentHtml || ''}
onItemClick={(item) => {
// Scroll to the story reading view with the specific heading
window.location.href = `/stories/${story.id}#${item.id}`;
}}
/>
{/* Tags */}
{story.tags && story.tags.length > 0 && (
<div className="theme-card theme-shadow rounded-lg p-4">
<h3 className="font-semibold theme-header mb-3">Tags</h3>
<div className="flex flex-wrap gap-2">
{story.tags.map((tag) => (
<span
<TagDisplay
key={tag.id}
className="px-3 py-1 text-sm rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
tag={tag}
size="md"
clickable={false}
/>
))}
</div>
</div>
@@ -358,6 +417,14 @@ export default function StoryDetailPage() {
>
📚 Start Reading
</Button>
<Button
onClick={handleEPUBExport}
variant="ghost"
size="lg"
disabled={isExporting}
>
{isExporting ? 'Exporting...' : '📖 Export EPUB'}
</Button>
<Button
href={`/stories/${story.id}/edit`}
variant="ghost"

View File

@@ -6,8 +6,11 @@ import AppLayout from '../../../../components/layout/AppLayout';
import { Input, Textarea } from '../../../../components/ui/Input';
import Button from '../../../../components/ui/Button';
import TagInput from '../../../../components/stories/TagInput';
import TagSuggestions from '../../../../components/tags/TagSuggestions';
import RichTextEditor from '../../../../components/stories/RichTextEditor';
import ImageUpload from '../../../../components/ui/ImageUpload';
import AuthorSelector from '../../../../components/stories/AuthorSelector';
import SeriesSelector from '../../../../components/stories/SeriesSelector';
import LoadingSpinner from '../../../../components/ui/LoadingSpinner';
import { storyApi } from '../../../../lib/api';
import { Story } from '../../../../types/api';
@@ -26,10 +29,12 @@ export default function EditStoryPage() {
title: '',
summary: '',
authorName: '',
authorId: undefined as string | undefined,
contentHtml: '',
sourceUrl: '',
tags: [] as string[],
seriesName: '',
seriesId: undefined as string | undefined,
volume: '',
});
@@ -47,10 +52,12 @@ export default function EditStoryPage() {
title: storyData.title,
summary: storyData.summary || '',
authorName: storyData.authorName,
authorId: storyData.authorId,
contentHtml: storyData.contentHtml,
sourceUrl: storyData.sourceUrl || '',
tags: storyData.tags?.map(tag => tag.name) || [],
seriesName: storyData.seriesName || '',
seriesId: storyData.seriesId,
volume: storyData.volume?.toString() || '',
});
} catch (error) {
@@ -91,6 +98,41 @@ export default function EditStoryPage() {
setFormData(prev => ({ ...prev, tags }));
};
const handleAddSuggestedTag = (tagName: string) => {
if (!formData.tags.includes(tagName.toLowerCase())) {
setFormData(prev => ({
...prev,
tags: [...prev.tags, tagName.toLowerCase()]
}));
}
};
const handleAuthorChange = (authorName: string, authorId?: string) => {
setFormData(prev => ({
...prev,
authorName,
authorId: authorId // This will be undefined if creating new author, which clears the existing ID
}));
// Clear error when user changes author
if (errors.authorName) {
setErrors(prev => ({ ...prev, authorName: '' }));
}
};
const handleSeriesChange = (seriesName: string, seriesId?: string) => {
setFormData(prev => ({
...prev,
seriesName,
seriesId: seriesId // This will be undefined if creating new series, which clears the existing ID
}));
// Clear error when user changes series
if (errors.seriesName) {
setErrors(prev => ({ ...prev, seriesName: '' }));
}
};
const validateForm = () => {
const newErrors: Record<string, string> = {};
@@ -134,9 +176,11 @@ export default function EditStoryPage() {
summary: formData.summary || undefined,
contentHtml: formData.contentHtml,
sourceUrl: formData.sourceUrl || undefined,
volume: formData.seriesName ? parseInt(formData.volume) : undefined,
seriesName: formData.seriesName || undefined,
authorId: story.authorId, // Keep existing author ID
volume: formData.seriesName && formData.volume ? parseInt(formData.volume) : undefined,
// Send seriesId if we have it (existing series), otherwise send seriesName (new/changed series)
...(formData.seriesId ? { seriesId: formData.seriesId } : { seriesName: formData.seriesName }),
// Send authorId if we have it (existing author), otherwise send authorName (new/changed author)
...(formData.authorId ? { authorId: formData.authorId } : { authorName: formData.authorName }),
tagNames: formData.tags,
};
@@ -216,18 +260,15 @@ export default function EditStoryPage() {
required
/>
{/* Author - Display only, not editable in edit mode for simplicity */}
<Input
{/* Author Selector */}
<AuthorSelector
label="Author *"
value={formData.authorName}
onChange={handleInputChange('authorName')}
placeholder="Enter the author's name"
onChange={handleAuthorChange}
placeholder="Select or enter author name"
error={errors.authorName}
disabled
required
/>
<p className="text-sm theme-text mt-1">
Author changes should be done through Author management
</p>
{/* Summary */}
<div>
@@ -252,7 +293,7 @@ export default function EditStoryPage() {
</label>
<ImageUpload
onImageSelect={setCoverImage}
accept="image/jpeg,image/png,image/webp"
accept="image/jpeg,image/png"
maxSizeMB={5}
aspectRatio="3:4"
placeholder="Drop a new cover image here or click to select"
@@ -287,17 +328,28 @@ export default function EditStoryPage() {
onChange={handleTagsChange}
placeholder="Edit tags to categorize your story..."
/>
{/* Tag Suggestions */}
<TagSuggestions
title={formData.title}
content={formData.contentHtml}
summary={formData.summary}
currentTags={formData.tags}
onAddTag={handleAddSuggestedTag}
disabled={saving}
/>
</div>
{/* Series and Volume */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Input
<SeriesSelector
label="Series (optional)"
value={formData.seriesName}
onChange={handleInputChange('seriesName')}
placeholder="Enter series name if part of a series"
onChange={handleSeriesChange}
placeholder="Select or enter series name if part of a series"
error={errors.seriesName}
authorId={formData.authorId}
/>
</div>

View File

@@ -8,6 +8,8 @@ import { Story } from '../../../types/api';
import LoadingSpinner from '../../../components/ui/LoadingSpinner';
import Button from '../../../components/ui/Button';
import StoryRating from '../../../components/stories/StoryRating';
import TagDisplay from '../../../components/tags/TagDisplay';
import TableOfContents from '../../../components/stories/TableOfContents';
import { sanitizeHtml, preloadSanitizationConfig } from '../../../lib/sanitization';
export default function StoryReadingPage() {
@@ -20,6 +22,8 @@ export default function StoryReadingPage() {
const [readingProgress, setReadingProgress] = useState(0);
const [sanitizedContent, setSanitizedContent] = useState<string>('');
const [hasScrolledToPosition, setHasScrolledToPosition] = useState(false);
const [showToc, setShowToc] = useState(false);
const [hasHeadings, setHasHeadings] = useState(false);
const contentRef = useRef<HTMLDivElement>(null);
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
@@ -111,9 +115,20 @@ export default function StoryReadingPage() {
setStory(storyData);
// Sanitize story content
// Sanitize story content and add IDs to headings
const sanitized = await sanitizeHtml(storyData.contentHtml || '');
setSanitizedContent(sanitized);
// Parse and add IDs to headings for TOC functionality
const parser = new DOMParser();
const doc = parser.parseFromString(sanitized, 'text/html');
const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6');
headings.forEach((heading, index) => {
heading.id = `heading-${index}`;
});
setSanitizedContent(doc.body.innerHTML);
setHasHeadings(headings.length > 0);
// Load series stories if part of a series
if (storyData.seriesId) {
@@ -133,12 +148,29 @@ export default function StoryReadingPage() {
}
}, [storyId]);
// Auto-scroll to saved reading position when story content is loaded
// Auto-scroll to saved reading position or URL hash when story content is loaded
useEffect(() => {
if (story && sanitizedContent && !hasScrolledToPosition) {
// Use a small delay to ensure content is rendered
const timeout = setTimeout(() => {
console.log('Initializing reading position tracking, saved position:', story.readingPosition);
// Check if there's a hash in the URL (for TOC navigation)
const hash = window.location.hash.substring(1);
if (hash && hash.startsWith('heading-')) {
console.log('Auto-scrolling to heading from URL hash:', hash);
const element = document.getElementById(hash);
if (element) {
element.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
setHasScrolledToPosition(true);
return;
}
}
// Otherwise, use saved reading position
if (story.readingPosition && story.readingPosition > 0) {
console.log('Auto-scrolling to saved position:', story.readingPosition);
scrollToCharacterPosition(story.readingPosition);
@@ -201,6 +233,7 @@ export default function StoryReadingPage() {
}
};
const findNextStory = (): Story | null => {
if (!story?.seriesId || seriesStories.length <= 1) return null;
@@ -264,6 +297,16 @@ export default function StoryReadingPage() {
</div>
<div className="flex items-center gap-4">
{hasHeadings && (
<button
onClick={() => setShowToc(!showToc)}
className="text-sm theme-text hover:theme-accent transition-colors"
title="Table of Contents"
>
📋 TOC
</button>
)}
<StoryRating
rating={story.rating || 0}
onRatingChange={handleRatingUpdate}
@@ -278,6 +321,35 @@ export default function StoryReadingPage() {
</div>
</header>
{/* Table of Contents Modal */}
{showToc && (
<>
{/* Backdrop */}
<div
className="fixed inset-0 bg-black bg-opacity-50 z-50"
onClick={() => setShowToc(false)}
/>
{/* TOC Modal */}
<div className="fixed top-20 right-4 left-4 md:left-auto md:w-80 max-h-96 z-50">
<TableOfContents
htmlContent={sanitizedContent}
collapsible={false}
onItemClick={(item) => {
const element = document.getElementById(item.id);
if (element) {
element.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
setShowToc(false); // Close TOC after navigation
}
}}
/>
</div>
</>
)}
{/* Story Content */}
<main className="max-w-4xl mx-auto px-4 py-8">
<article data-reading-content>
@@ -313,12 +385,12 @@ export default function StoryReadingPage() {
{story.tags && story.tags.length > 0 && (
<div className="flex flex-wrap justify-center gap-2 mt-4">
{story.tags.map((tag) => (
<span
<TagDisplay
key={tag.id}
className="px-3 py-1 text-sm theme-accent-bg text-white rounded-full"
>
{tag.name}
</span>
tag={tag}
size="md"
clickable={false}
/>
))}
</div>
)}

View File

@@ -1,299 +1,20 @@
'use client';
import { useState } from 'react';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeftIcon } from '@heroicons/react/24/outline';
interface ImportResult {
url: string;
status: 'imported' | 'skipped' | 'error';
reason?: string;
title?: string;
author?: string;
error?: string;
storyId?: string;
}
interface BulkImportResponse {
results: ImportResult[];
summary: {
total: number;
imported: number;
skipped: number;
errors: number;
};
}
export default function BulkImportPage() {
export default function BulkImportRedirectPage() {
const router = useRouter();
const [urls, setUrls] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [results, setResults] = useState<BulkImportResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!urls.trim()) {
setError('Please enter at least one URL');
return;
}
setIsLoading(true);
setError(null);
setResults(null);
try {
// Parse URLs from textarea (one per line)
const urlList = urls
.split('\n')
.map(url => url.trim())
.filter(url => url.length > 0);
if (urlList.length === 0) {
setError('Please enter at least one valid URL');
setIsLoading(false);
return;
}
if (urlList.length > 50) {
setError('Maximum 50 URLs allowed per bulk import');
setIsLoading(false);
return;
}
// Get auth token for server-side API calls
const token = localStorage.getItem('auth-token');
const response = await fetch('/scrape/bulk', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token ? `Bearer ${token}` : '',
},
body: JSON.stringify({ urls: urlList }),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Bulk import failed');
}
const data: BulkImportResponse = await response.json();
setResults(data);
} catch (err) {
console.error('Bulk import error:', err);
setError(err instanceof Error ? err.message : 'Failed to import stories');
} finally {
setIsLoading(false);
}
};
const handleReset = () => {
setUrls('');
setResults(null);
setError(null);
};
const getStatusColor = (status: string) => {
switch (status) {
case 'imported': return 'text-green-700 bg-green-50 border-green-200';
case 'skipped': return 'text-yellow-700 bg-yellow-50 border-yellow-200';
case 'error': return 'text-red-700 bg-red-50 border-red-200';
default: return 'text-gray-700 bg-gray-50 border-gray-200';
}
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'imported': return '✓';
case 'skipped': return '⚠';
case 'error': return '✗';
default: return '';
}
};
useEffect(() => {
router.replace('/import/bulk');
}, [router]);
return (
<div className="container mx-auto px-4 py-6">
<div className="max-w-4xl mx-auto">
{/* Header */}
<div className="mb-6">
<div className="flex items-center gap-4 mb-4">
<Link
href="/library"
className="inline-flex items-center text-blue-600 hover:text-blue-800"
>
<ArrowLeftIcon className="h-4 w-4 mr-1" />
Back to Library
</Link>
</div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">Bulk Import Stories</h1>
<p className="text-gray-600">
Import multiple stories at once by providing a list of URLs. Each URL will be scraped
and automatically added to your story collection.
</p>
</div>
{!results ? (
// Import Form
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label htmlFor="urls" className="block text-sm font-medium text-gray-700 mb-2">
Story URLs
</label>
<p className="text-sm text-gray-500 mb-3">
Enter one URL per line. Maximum 50 URLs per import.
</p>
<textarea
id="urls"
value={urls}
onChange={(e) => setUrls(e.target.value)}
placeholder="https://example.com/story1&#10;https://example.com/story2&#10;https://example.com/story3"
className="w-full h-64 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
disabled={isLoading}
/>
<p className="mt-2 text-sm text-gray-500">
URLs: {urls.split('\n').filter(url => url.trim().length > 0).length}
</p>
</div>
{error && (
<div className="bg-red-50 border border-red-200 rounded-md p-4">
<div className="flex">
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800">Error</h3>
<div className="mt-2 text-sm text-red-700">
{error}
</div>
</div>
</div>
</div>
)}
<div className="flex gap-4">
<button
type="submit"
disabled={isLoading || !urls.trim()}
className="px-6 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? 'Importing...' : 'Start Import'}
</button>
<button
type="button"
onClick={handleReset}
disabled={isLoading}
className="px-6 py-2 bg-gray-600 text-white font-medium rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
Clear
</button>
</div>
{isLoading && (
<div className="bg-blue-50 border border-blue-200 rounded-md p-4">
<div className="flex items-center">
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-600 mr-3"></div>
<div>
<p className="text-sm font-medium text-blue-800">Processing URLs...</p>
<p className="text-sm text-blue-600">
This may take a few minutes depending on the number of URLs and response times of the source websites.
</p>
</div>
</div>
</div>
)}
</form>
) : (
// Results
<div className="space-y-6">
{/* Summary */}
<div className="bg-white border border-gray-200 rounded-lg p-6">
<h2 className="text-xl font-semibold text-gray-900 mb-4">Import Summary</h2>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-gray-900">{results.summary.total}</div>
<div className="text-sm text-gray-600">Total URLs</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-green-600">{results.summary.imported}</div>
<div className="text-sm text-gray-600">Imported</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-yellow-600">{results.summary.skipped}</div>
<div className="text-sm text-gray-600">Skipped</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-red-600">{results.summary.errors}</div>
<div className="text-sm text-gray-600">Errors</div>
</div>
</div>
</div>
{/* Detailed Results */}
<div className="bg-white border border-gray-200 rounded-lg">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-medium text-gray-900">Detailed Results</h3>
</div>
<div className="divide-y divide-gray-200">
{results.results.map((result, index) => (
<div key={index} className="p-6">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border ${getStatusColor(result.status)}`}>
{getStatusIcon(result.status)} {result.status.charAt(0).toUpperCase() + result.status.slice(1)}
</span>
</div>
<p className="text-sm text-gray-900 font-medium truncate mb-1">
{result.url}
</p>
{result.title && result.author && (
<p className="text-sm text-gray-600 mb-1">
"{result.title}" by {result.author}
</p>
)}
{result.reason && (
<p className="text-sm text-gray-500">
{result.reason}
</p>
)}
{result.error && (
<p className="text-sm text-red-600">
Error: {result.error}
</p>
)}
</div>
</div>
</div>
))}
</div>
</div>
{/* Actions */}
<div className="flex gap-4">
<button
onClick={handleReset}
className="px-6 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
>
Import More URLs
</button>
<Link
href="/stories"
className="px-6 py-2 bg-gray-600 text-white font-medium rounded-md hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
>
View Stories
</Link>
</div>
</div>
)}
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600">Redirecting...</p>
</div>
</div>
);

View File

@@ -0,0 +1,21 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
export default function EpubImportRedirectPage() {
const router = useRouter();
useEffect(() => {
router.replace('/import/epub');
}, [router]);
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600">Redirecting...</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,21 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
export default function ImportRedirectPage() {
const router = useRouter();
useEffect(() => {
router.replace('/import');
}, [router]);
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
<p className="text-gray-600">Redirecting...</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,23 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import LoadingSpinner from '../../components/ui/LoadingSpinner';
export default function StoriesRedirectPage() {
const router = useRouter();
useEffect(() => {
// Redirect to library page
router.replace('/library');
}, [router]);
return (
<div className="min-h-screen theme-bg flex items-center justify-center">
<div className="text-center">
<LoadingSpinner size="lg" />
<p className="theme-text mt-4">Redirecting to Library...</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,207 @@
'use client';
import { useEffect, useState } from 'react';
interface ProgressUpdate {
type: 'progress' | 'completed' | 'error' | 'connected';
current: number;
total: number;
message: string;
url?: string;
title?: string;
author?: string;
wordCount?: number;
totalWordCount?: number;
error?: string;
sessionId?: string;
}
interface BulkImportProgressProps {
sessionId: string;
onComplete?: (data?: any) => void;
onError?: (error: string) => void;
combineMode?: boolean;
}
export default function BulkImportProgress({
sessionId,
onComplete,
onError,
combineMode = false
}: BulkImportProgressProps) {
const [progress, setProgress] = useState<ProgressUpdate>({
type: 'progress',
current: 0,
total: 1,
message: 'Connecting...'
});
const [isConnected, setIsConnected] = useState(false);
const [recentActivities, setRecentActivities] = useState<string[]>([]);
useEffect(() => {
const eventSource = new EventSource(`/scrape/bulk/progress?sessionId=${sessionId}`);
eventSource.onmessage = (event) => {
try {
const data: ProgressUpdate = JSON.parse(event.data);
if (data.type === 'connected') {
setIsConnected(true);
return;
}
setProgress(data);
// Add to recent activities (keep last 5)
if (data.message) {
setRecentActivities(prev => [
data.message,
...prev.slice(0, 4)
]);
}
if (data.type === 'completed') {
setTimeout(() => {
onComplete?.(data);
eventSource.close();
}, 2000); // Show completion message for 2 seconds
} else if (data.type === 'error') {
onError?.(data.error || 'Unknown error occurred');
eventSource.close();
}
} catch (error) {
console.error('Failed to parse progress update:', error);
}
};
eventSource.onerror = (error) => {
console.error('EventSource error:', error);
setIsConnected(false);
onError?.('Connection to progress stream failed');
eventSource.close();
};
return () => {
eventSource.close();
};
}, [sessionId, onComplete, onError]);
const progressPercentage = progress.total > 0
? Math.round((progress.current / progress.total) * 100)
: 0;
const getStatusColor = () => {
switch (progress.type) {
case 'completed': return 'bg-green-600';
case 'error': return 'bg-red-600';
default: return 'bg-blue-600';
}
};
const getStatusIcon = () => {
switch (progress.type) {
case 'completed': return '✓';
case 'error': return '✗';
default: return null;
}
};
return (
<div className="bg-white border border-gray-200 rounded-lg p-6">
<div className="mb-4">
<div className="flex items-center justify-between mb-2">
<h3 className="text-lg font-medium text-gray-900">
{combineMode ? 'Combining Stories' : 'Bulk Import Progress'}
</h3>
<div className="flex items-center gap-2">
{!isConnected && (
<div className="h-2 w-2 bg-yellow-400 rounded-full animate-pulse"></div>
)}
<span className="text-sm text-gray-600">
{progress.current} of {progress.total}
</span>
</div>
</div>
{/* Progress Bar */}
<div className="w-full bg-gray-200 rounded-full h-3 mb-3">
<div
className={`h-3 rounded-full transition-all duration-500 ${getStatusColor()}`}
style={{ width: `${progressPercentage}%` }}
></div>
</div>
{/* Progress Percentage */}
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-900">
{progressPercentage}%
</span>
{progress.type === 'completed' && (
<span className="text-green-600 font-medium">
{getStatusIcon()} Complete
</span>
)}
{progress.type === 'error' && (
<span className="text-red-600 font-medium">
{getStatusIcon()} Error
</span>
)}
</div>
</div>
{/* Current Status Message */}
<div className="mb-4">
<div className="flex items-center gap-2">
{progress.type === 'progress' && (
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600"></div>
)}
<p className="text-sm text-gray-700">{progress.message}</p>
</div>
{/* Word Count for Combine Mode */}
{combineMode && progress.totalWordCount !== undefined && (
<p className="text-sm text-gray-500 mt-1">
Total words collected: {progress.totalWordCount.toLocaleString()}
</p>
)}
</div>
{/* Current URL being processed */}
{progress.url && (
<div className="mb-4 p-3 bg-gray-50 rounded-md">
<p className="text-sm text-gray-600 mb-1">Currently processing:</p>
<p className="text-sm font-mono text-gray-800 truncate">{progress.url}</p>
{progress.title && progress.author && (
<p className="text-sm text-gray-600 mt-1">
"{progress.title}" by {progress.author}
{progress.wordCount && (
<span className="ml-2 text-gray-500">
({progress.wordCount.toLocaleString()} words)
</span>
)}
</p>
)}
</div>
)}
{/* Recent Activities */}
{recentActivities.length > 0 && (
<div>
<h4 className="text-sm font-medium text-gray-900 mb-2">Recent Activity</h4>
<div className="space-y-1 max-h-32 overflow-y-auto">
{recentActivities.map((activity, index) => (
<p
key={index}
className={`text-xs text-gray-600 ${
index === 0 ? 'font-medium text-gray-800' : ''
}`}
>
{activity}
</p>
))}
</div>
</div>
)}
</div>
);
}

View File

@@ -1,7 +1,7 @@
'use client';
import { useState, useEffect } from 'react';
import { searchApi, tagApi } from '../../lib/api';
import { searchApi, tagApi, getImageUrl } from '../../lib/api';
import { Story, Tag } from '../../types/api';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
@@ -227,7 +227,7 @@ export default function CollectionForm({
<input
id="coverImage"
type="file"
accept="image/jpeg,image/png,image/webp"
accept="image/jpeg,image/png"
onChange={handleCoverImageChange}
className="w-full px-3 py-2 border theme-border rounded-lg theme-card theme-text focus:outline-none focus:ring-2 focus:ring-theme-accent"
/>
@@ -239,7 +239,7 @@ export default function CollectionForm({
{(coverImagePreview || initialData?.coverImagePath) && (
<div className="w-20 h-24 rounded overflow-hidden bg-gray-100">
<img
src={coverImagePreview || (initialData?.coverImagePath ? `/images/${initialData.coverImagePath}` : '')}
src={coverImagePreview || (initialData?.coverImagePath ? getImageUrl(initialData.coverImagePath) : '')}
alt="Cover preview"
className="w-full h-full object-cover"
/>

View File

@@ -2,8 +2,9 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { StoryWithCollectionContext } from '../../types/api';
import { storyApi } from '../../lib/api';
import { storyApi, getImageUrl } from '../../lib/api';
import Button from '../ui/Button';
import TagDisplay from '../tags/TagDisplay';
import Link from 'next/link';
interface CollectionReadingViewProps {
@@ -211,7 +212,7 @@ export default function CollectionReadingView({
{story.coverPath && (
<div className="flex-shrink-0">
<img
src={`/images/${story.coverPath}`}
src={getImageUrl(story.coverPath)}
alt={`${story.title} cover`}
className="w-32 h-40 object-cover rounded-lg mx-auto md:mx-0"
/>
@@ -255,12 +256,12 @@ export default function CollectionReadingView({
{story.tags && story.tags.length > 0 && (
<div className="flex flex-wrap gap-2">
{story.tags.map((tag) => (
<span
<TagDisplay
key={tag.id}
className="inline-block px-2 py-1 text-xs rounded-full theme-accent-bg text-white"
>
{tag.name}
</span>
tag={tag}
size="sm"
clickable={false}
/>
))}
</div>
)}

View File

@@ -22,12 +22,17 @@ export default function Header() {
description: 'Add a story by manually entering details'
},
{
href: '/stories/import',
href: '/import',
label: 'Import from URL',
description: 'Import a single story from a website'
},
{
href: '/stories/import/bulk',
href: '/import/epub',
label: 'Import EPUB',
description: 'Import a story from an EPUB file'
},
{
href: '/import/bulk',
label: 'Bulk Import',
description: 'Import multiple stories from a list of URLs'
}
@@ -151,27 +156,16 @@ export default function Header() {
<div className="px-2 py-1">
<div className="font-medium theme-text mb-1">Add Story</div>
<div className="pl-4 space-y-1">
<Link
href="/add-story"
className="block theme-text hover:theme-accent transition-colors text-sm py-1"
onClick={() => setIsMenuOpen(false)}
>
Manual Entry
</Link>
<Link
href="/stories/import"
className="block theme-text hover:theme-accent transition-colors text-sm py-1"
onClick={() => setIsMenuOpen(false)}
>
Import from URL
</Link>
<Link
href="/stories/import/bulk"
className="block theme-text hover:theme-accent transition-colors text-sm py-1"
onClick={() => setIsMenuOpen(false)}
>
Bulk Import
</Link>
{addStoryItems.map((item) => (
<Link
key={item.href}
href={item.href}
className="block theme-text hover:theme-accent transition-colors text-sm py-1"
onClick={() => setIsMenuOpen(false)}
>
{item.label}
</Link>
))}
</div>
</div>
<Link

View File

@@ -0,0 +1,130 @@
'use client';
import { ReactNode } from 'react';
import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';
import AppLayout from './AppLayout';
interface ImportTab {
id: string;
label: string;
href: string;
description: string;
}
interface ImportLayoutProps {
children: ReactNode;
title: string;
description?: string;
}
const importTabs: ImportTab[] = [
{
id: 'manual',
label: 'Manual Entry',
href: '/add-story',
description: 'Add a story by manually entering details'
},
{
id: 'url',
label: 'Import from URL',
href: '/import',
description: 'Import a single story from a website'
},
{
id: 'epub',
label: 'Import EPUB',
href: '/import/epub',
description: 'Import a story from an EPUB file'
},
{
id: 'bulk',
label: 'Bulk Import',
href: '/import/bulk',
description: 'Import multiple stories from a list of URLs'
}
];
export default function ImportLayout({ children, title, description }: ImportLayoutProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
const mode = searchParams.get('mode');
// Determine which tab is active
const getActiveTab = () => {
if (pathname === '/add-story') {
return 'manual';
} else if (pathname === '/import') {
return 'url';
} else if (pathname === '/import/epub') {
return 'epub';
} else if (pathname === '/import/bulk') {
return 'bulk';
}
return 'manual';
};
const activeTab = getActiveTab();
return (
<AppLayout>
<div className="max-w-4xl mx-auto space-y-6">
{/* Header */}
<div className="text-center">
<h1 className="text-3xl font-bold theme-header">{title}</h1>
{description && (
<p className="theme-text mt-2 text-lg">
{description}
</p>
)}
</div>
{/* Tab Navigation */}
<div className="theme-card theme-shadow rounded-lg overflow-hidden">
{/* Tab Headers */}
<div className="flex border-b theme-border overflow-x-auto">
{importTabs.map((tab) => (
<Link
key={tab.id}
href={tab.href}
className={`flex-1 min-w-0 px-4 py-3 text-sm font-medium text-center transition-colors whitespace-nowrap ${
activeTab === tab.id
? 'theme-accent-bg text-white border-b-2 border-transparent'
: 'theme-text hover:theme-accent-light hover:theme-accent-text'
}`}
>
<div className="truncate">
{tab.label}
</div>
</Link>
))}
</div>
{/* Tab Descriptions */}
<div className="px-6 py-4 bg-gray-50 dark:bg-gray-800/50">
<div className="flex items-center justify-center">
<p className="text-sm theme-text text-center">
{importTabs.find(tab => tab.id === activeTab)?.description}
</p>
</div>
</div>
{/* Tab Content */}
<div className="p-6">
{children}
</div>
</div>
{/* Quick Actions */}
<div className="flex justify-center">
<Link
href="/library"
className="theme-text hover:theme-accent transition-colors text-sm"
>
Back to Library
</Link>
</div>
</div>
</AppLayout>
);
}

View File

@@ -0,0 +1,554 @@
'use client';
import { useState, useEffect } from 'react';
import type { AdvancedFilters, FilterPreset } from '../../types/api';
import Button from '../ui/Button';
import { Input } from '../ui/Input';
interface AdvancedFiltersProps {
filters: AdvancedFilters;
onChange: (filters: AdvancedFilters) => void;
onReset: () => void;
className?: string;
}
// Predefined filter presets with both detailed controls and quick buttons
const FILTER_PRESETS: FilterPreset[] = [
// Length presets
{
id: 'short-stories',
label: '< 5k words',
description: 'Short stories under 5,000 words',
filters: { maxWordCount: 5000 },
category: 'length'
},
{
id: 'medium-stories',
label: '5k - 20k',
description: 'Medium length stories (5k-20k words)',
filters: { minWordCount: 5000, maxWordCount: 20000 },
category: 'length'
},
{
id: 'long-stories',
label: '> 20k words',
description: 'Long stories over 20,000 words',
filters: { minWordCount: 20000 },
category: 'length'
},
{
id: 'very-long',
label: '> 50k words',
description: 'Very long stories over 50,000 words',
filters: { minWordCount: 50000 },
category: 'length'
},
// Date presets
{
id: 'last-week',
label: 'Last 7 days',
description: 'Stories added in the last week',
filters: { createdAfter: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] },
category: 'date'
},
{
id: 'last-month',
label: 'Last 30 days',
description: 'Stories added in the last month',
filters: { createdAfter: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] },
category: 'date'
},
{
id: 'this-year',
label: 'This year',
description: 'Stories added this year',
filters: { createdAfter: `${new Date().getFullYear()}-01-01` },
category: 'date'
},
// Reading status presets
{
id: 'unread',
label: 'Unread',
description: 'Stories you haven\'t read yet',
filters: { readingStatus: 'unread' },
category: 'reading'
},
{
id: 'in-progress',
label: 'Started',
description: 'Stories you\'ve started reading',
filters: { readingStatus: 'started' },
category: 'reading'
},
{
id: 'completed',
label: 'Finished',
description: 'Stories you\'ve completed',
filters: { readingStatus: 'completed' },
category: 'reading'
},
// Rating presets
{
id: 'highly-rated',
label: '4+ stars',
description: 'Highly rated stories (4 stars or more)',
filters: { minRating: 4 },
category: 'rating'
},
{
id: 'unrated',
label: 'Unrated',
description: 'Stories without ratings',
filters: { unratedOnly: true },
category: 'rating'
},
// Content presets
{
id: 'with-covers',
label: 'Has Cover',
description: 'Stories with cover images',
filters: { hasCoverImage: true },
category: 'content'
},
{
id: 'standalone',
label: 'Standalone',
description: 'Stories not part of a series',
filters: { seriesFilter: 'standalone' },
category: 'content'
},
{
id: 'series-only',
label: 'Series',
description: 'Stories that are part of a series',
filters: { seriesFilter: 'series' },
category: 'content'
},
// Organization presets
{
id: 'well-tagged',
label: '3+ tags',
description: 'Well-tagged stories with 3 or more tags',
filters: { minTagCount: 3 },
category: 'organization'
},
{
id: 'popular',
label: 'Popular',
description: 'Stories with above-average ratings',
filters: { popularOnly: true },
category: 'organization'
},
{
id: 'hidden-gems',
label: 'Hidden Gems',
description: 'Underrated or unrated stories to discover',
filters: { hiddenGemsOnly: true },
category: 'organization'
}
];
export default function AdvancedFilters({
filters,
onChange,
onReset,
className = ''
}: AdvancedFiltersProps) {
// Prevent event bubbling when interacting with the component
const handleContainerClick = (e: React.MouseEvent) => {
e.stopPropagation();
};
const handleKeyDown = (e: React.KeyboardEvent) => {
// Prevent escape key from bubbling up (let parent handle it)
e.stopPropagation();
};
const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
length: false,
date: false,
rating: false,
reading: false,
content: false
});
// Helper functions
const updateFilter = <K extends keyof AdvancedFilters>(
key: K,
value: AdvancedFilters[K]
) => {
onChange({ ...filters, [key]: value });
};
const applyPreset = (preset: FilterPreset) => {
onChange({ ...filters, ...preset.filters });
};
const isPresetActive = (preset: FilterPreset) => {
return Object.entries(preset.filters).every(([key, value]) =>
filters[key as keyof AdvancedFilters] === value
);
};
const toggleSection = (section: string) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
};
const hasActiveFilters = Object.values(filters).some(value =>
value !== undefined && value !== '' && value !== 'all'
);
// Group presets by category
const presetsByCategory = FILTER_PRESETS.reduce((acc, preset) => {
if (!acc[preset.category]) acc[preset.category] = [];
acc[preset.category].push(preset);
return acc;
}, {} as Record<string, FilterPreset[]>);
return (
<div
className={`space-y-4 ${className}`}
onClick={handleContainerClick}
onKeyDown={handleKeyDown}
>
{/* Quick Filter Buttons */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h4 className="font-medium theme-header text-sm">Quick Filters</h4>
{hasActiveFilters && (
<Button variant="ghost" size="sm" onClick={onReset}>
Clear All
</Button>
)}
</div>
{Object.entries(presetsByCategory).map(([category, presets]) => (
<div key={category} className="space-y-1">
<div className="text-xs font-medium theme-text opacity-75 uppercase tracking-wide">
{category.charAt(0).toUpperCase() + category.slice(1)}
</div>
<div className="flex flex-wrap gap-1">
{presets.map(preset => (
<button
key={preset.id}
onClick={() => applyPreset(preset)}
className={`px-2 py-1 rounded text-xs font-medium transition-all hover:scale-105 ${
isPresetActive(preset)
? 'bg-blue-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 theme-text hover:bg-blue-100 dark:hover:bg-blue-900'
}`}
title={preset.description}
>
{preset.label}
</button>
))}
</div>
</div>
))}
</div>
<div className="border-t theme-border pt-4">
<h4 className="font-medium theme-header text-sm mb-3">Detailed Controls</h4>
{/* Word Count Section */}
<div className="space-y-2 mb-4">
<button
onClick={() => toggleSection('length')}
className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
>
<span className={`transform transition-transform ${expandedSections.length ? 'rotate-90' : ''}`}>
</span>
📏 Story Length
{(filters.minWordCount || filters.maxWordCount) && (
<span className="text-xs bg-blue-500 text-white px-1 rounded"></span>
)}
</button>
{expandedSections.length && (
<div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div className="space-y-3">
<div>
<label className="block text-xs theme-text mb-1">Min Words</label>
<Input
type="number"
value={filters.minWordCount || ''}
onChange={(e) => updateFilter('minWordCount', e.target.value ? parseInt(e.target.value) : undefined)}
placeholder="0"
className="text-xs w-full"
/>
</div>
<div>
<label className="block text-xs theme-text mb-1">Max Words</label>
<Input
type="number"
value={filters.maxWordCount || ''}
onChange={(e) => updateFilter('maxWordCount', e.target.value ? parseInt(e.target.value) : undefined)}
placeholder="∞"
className="text-xs w-full"
/>
</div>
</div>
{/* Word count range display */}
{(filters.minWordCount || filters.maxWordCount) && (
<div className="text-xs theme-text bg-white dark:bg-gray-700 p-2 rounded">
Range: {filters.minWordCount || 0} - {filters.maxWordCount || '∞'} words
</div>
)}
</div>
)}
</div>
{/* Date Section */}
<div className="space-y-2 mb-4">
<button
onClick={() => toggleSection('date')}
className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
>
<span className={`transform transition-transform ${expandedSections.date ? 'rotate-90' : ''}`}>
</span>
📅 Date Added
{(filters.createdAfter || filters.createdBefore) && (
<span className="text-xs bg-blue-500 text-white px-1 rounded"></span>
)}
</button>
{expandedSections.date && (
<div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div className="space-y-3">
<div>
<label className="block text-xs theme-text mb-1">After Date</label>
<Input
type="date"
value={filters.createdAfter || ''}
onChange={(e) => updateFilter('createdAfter', e.target.value || undefined)}
className="text-xs w-full"
/>
</div>
<div>
<label className="block text-xs theme-text mb-1">Before Date</label>
<Input
type="date"
value={filters.createdBefore || ''}
onChange={(e) => updateFilter('createdBefore', e.target.value || undefined)}
className="text-xs w-full"
/>
</div>
</div>
</div>
)}
</div>
{/* Rating Section */}
<div className="space-y-2 mb-4">
<button
onClick={() => toggleSection('rating')}
className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
>
<span className={`transform transition-transform ${expandedSections.rating ? 'rotate-90' : ''}`}>
</span>
Rating
{(filters.minRating || filters.maxRating || filters.unratedOnly) && (
<span className="text-xs bg-blue-500 text-white px-1 rounded"></span>
)}
</button>
{expandedSections.rating && (
<div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div className="space-y-2">
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={filters.unratedOnly || false}
onChange={(e) => updateFilter('unratedOnly', e.target.checked || undefined)}
/>
<span className="text-xs theme-text">Unrated stories only</span>
</label>
</div>
{!filters.unratedOnly && (
<div className="space-y-3">
<div>
<label className="block text-xs theme-text mb-1">Min Rating</label>
<select
value={filters.minRating || ''}
onChange={(e) => updateFilter('minRating', e.target.value ? parseInt(e.target.value) : undefined)}
className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
>
<option value="">No minimum</option>
<option value="1">1 star</option>
<option value="2">2 stars</option>
<option value="3">3 stars</option>
<option value="4">4 stars</option>
<option value="5">5 stars</option>
</select>
</div>
<div>
<label className="block text-xs theme-text mb-1">Max Rating</label>
<select
value={filters.maxRating || ''}
onChange={(e) => updateFilter('maxRating', e.target.value ? parseInt(e.target.value) : undefined)}
className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
>
<option value="">No maximum</option>
<option value="1">1 star</option>
<option value="2">2 stars</option>
<option value="3">3 stars</option>
<option value="4">4 stars</option>
<option value="5">5 stars</option>
</select>
</div>
</div>
)}
</div>
)}
</div>
{/* Reading Status Section */}
<div className="space-y-2 mb-4">
<button
onClick={() => toggleSection('reading')}
className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
>
<span className={`transform transition-transform ${expandedSections.reading ? 'rotate-90' : ''}`}>
</span>
👁 Reading Status
{(filters.readingStatus && filters.readingStatus !== 'all') && (
<span className="text-xs bg-blue-500 text-white px-1 rounded"></span>
)}
</button>
{expandedSections.reading && (
<div className="pl-6 space-y-2 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div className="space-y-1">
{[
{ value: 'all', label: 'All stories' },
{ value: 'unread', label: 'Unread' },
{ value: 'started', label: 'Started reading' },
{ value: 'completed', label: 'Completed' }
].map(option => (
<label key={option.value} className="flex items-center gap-2">
<input
type="radio"
name="readingStatus"
value={option.value}
checked={(filters.readingStatus || 'all') === option.value}
onChange={(e) => updateFilter('readingStatus', e.target.value as any)}
/>
<span className="text-xs theme-text">{option.label}</span>
</label>
))}
</div>
</div>
)}
</div>
{/* Content Section */}
<div className="space-y-2 mb-4">
<button
onClick={() => toggleSection('content')}
className="flex items-center gap-2 text-sm font-medium theme-text hover:theme-accent transition-colors"
>
<span className={`transform transition-transform ${expandedSections.content ? 'rotate-90' : ''}`}>
</span>
📚 Content
{(filters.hasCoverImage || filters.seriesFilter !== 'all' || filters.sourceDomain) && (
<span className="text-xs bg-blue-500 text-white px-1 rounded"></span>
)}
</button>
{expandedSections.content && (
<div className="pl-6 space-y-3 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div className="space-y-2">
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={filters.hasCoverImage || false}
onChange={(e) => updateFilter('hasCoverImage', e.target.checked || undefined)}
/>
<span className="text-xs theme-text">Has cover image</span>
</label>
</div>
<div>
<label className="block text-xs theme-text mb-1">Series Filter</label>
<select
value={filters.seriesFilter || 'all'}
onChange={(e) => updateFilter('seriesFilter', e.target.value as any)}
className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
>
<option value="all">All stories</option>
<option value="standalone">Standalone only</option>
<option value="series">Series only</option>
<option value="firstInSeries">First in series</option>
<option value="lastInSeries">Last in series</option>
</select>
</div>
<div>
<label className="block text-xs theme-text mb-1">Source Domain</label>
<Input
type="text"
value={filters.sourceDomain || ''}
onChange={(e) => updateFilter('sourceDomain', e.target.value || undefined)}
placeholder="e.g., archiveofourown.org"
className="text-xs"
/>
</div>
</div>
)}
</div>
{/* Advanced Options */}
<div className="space-y-2">
<div className="text-xs font-medium theme-text opacity-75 uppercase tracking-wide">
Advanced
</div>
<div className="space-y-2 bg-gray-50 dark:bg-gray-800 p-3 rounded">
<div>
<label className="block text-xs theme-text mb-1">Minimum Tag Count</label>
<Input
type="number"
value={filters.minTagCount || ''}
onChange={(e) => updateFilter('minTagCount', e.target.value ? parseInt(e.target.value) : undefined)}
placeholder="0"
className="text-xs"
min="0"
/>
</div>
<div className="space-y-1">
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={filters.popularOnly || false}
onChange={(e) => updateFilter('popularOnly', e.target.checked || undefined)}
/>
<span className="text-xs theme-text">Popular stories only (above average rating)</span>
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={filters.hiddenGemsOnly || false}
onChange={(e) => updateFilter('hiddenGemsOnly', e.target.checked || undefined)}
/>
<span className="text-xs theme-text">Hidden gems (underrated/unrated)</span>
</label>
</div>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,607 @@
'use client';
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Button from '../ui/Button';
import { Input } from '../ui/Input';
import LibrarySwitchLoader from '../ui/LibrarySwitchLoader';
import { useLibrarySwitch } from '../../hooks/useLibrarySwitch';
import { setCurrentLibraryId, clearLibraryCache } from '../../lib/api';
interface Library {
id: string;
name: string;
description: string;
isActive: boolean;
isInitialized: boolean;
}
export default function LibrarySettings() {
const router = useRouter();
const { state: switchState, switchLibrary, clearError, reset } = useLibrarySwitch();
const [libraries, setLibraries] = useState<Library[]>([]);
const [currentLibrary, setCurrentLibrary] = useState<Library | null>(null);
const [loading, setLoading] = useState(true);
const [switchPassword, setSwitchPassword] = useState('');
const [showSwitchForm, setShowSwitchForm] = useState(false);
const [passwordChangeForm, setPasswordChangeForm] = useState({
currentPassword: '',
newPassword: '',
confirmPassword: ''
});
const [showPasswordChangeForm, setShowPasswordChangeForm] = useState(false);
const [passwordChangeLoading, setPasswordChangeLoading] = useState(false);
const [passwordChangeMessage, setPasswordChangeMessage] = useState<{type: 'success' | 'error', text: string} | null>(null);
const [createLibraryForm, setCreateLibraryForm] = useState({
name: '',
description: '',
password: '',
confirmPassword: ''
});
const [showCreateLibraryForm, setShowCreateLibraryForm] = useState(false);
const [createLibraryLoading, setCreateLibraryLoading] = useState(false);
const [createLibraryMessage, setCreateLibraryMessage] = useState<{type: 'success' | 'error', text: string} | null>(null);
useEffect(() => {
loadLibraries();
loadCurrentLibrary();
}, []);
const loadLibraries = async () => {
try {
const response = await fetch('/api/libraries');
if (response.ok) {
const data = await response.json();
setLibraries(data);
}
} catch (error) {
console.error('Failed to load libraries:', error);
}
};
const loadCurrentLibrary = async () => {
try {
const response = await fetch('/api/libraries/current');
if (response.ok) {
const data = await response.json();
setCurrentLibrary(data);
// Set the library ID for image URL generation
setCurrentLibraryId(data.id);
}
} catch (error) {
console.error('Failed to load current library:', error);
} finally {
setLoading(false);
}
};
const handleSwitchLibrary = async (e: React.FormEvent) => {
e.preventDefault();
if (!switchPassword.trim()) {
return;
}
const success = await switchLibrary(switchPassword);
if (success) {
// The LibrarySwitchLoader will handle the rest
}
};
const handleSwitchComplete = () => {
// Clear the library cache so images use the new library
clearLibraryCache();
// Refresh the page to reload with new library context
router.refresh();
window.location.reload();
};
const handleSwitchError = (error: string) => {
console.error('Library switch error:', error);
reset();
};
const handlePasswordChange = async (e: React.FormEvent) => {
e.preventDefault();
if (passwordChangeForm.newPassword !== passwordChangeForm.confirmPassword) {
setPasswordChangeMessage({type: 'error', text: 'New passwords do not match'});
return;
}
if (passwordChangeForm.newPassword.length < 8) {
setPasswordChangeMessage({type: 'error', text: 'Password must be at least 8 characters long'});
return;
}
setPasswordChangeLoading(true);
setPasswordChangeMessage(null);
try {
const response = await fetch('/api/libraries/password', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
currentPassword: passwordChangeForm.currentPassword,
newPassword: passwordChangeForm.newPassword,
}),
});
const data = await response.json();
if (response.ok && data.success) {
setPasswordChangeMessage({type: 'success', text: 'Password changed successfully'});
setPasswordChangeForm({
currentPassword: '',
newPassword: '',
confirmPassword: ''
});
setShowPasswordChangeForm(false);
} else {
setPasswordChangeMessage({type: 'error', text: data.error || 'Failed to change password'});
}
} catch (error) {
setPasswordChangeMessage({type: 'error', text: 'Network error occurred'});
} finally {
setPasswordChangeLoading(false);
}
};
const handleCreateLibrary = async (e: React.FormEvent) => {
e.preventDefault();
if (createLibraryForm.password !== createLibraryForm.confirmPassword) {
setCreateLibraryMessage({type: 'error', text: 'Passwords do not match'});
return;
}
if (createLibraryForm.password.length < 8) {
setCreateLibraryMessage({type: 'error', text: 'Password must be at least 8 characters long'});
return;
}
if (createLibraryForm.name.trim().length < 2) {
setCreateLibraryMessage({type: 'error', text: 'Library name must be at least 2 characters long'});
return;
}
setCreateLibraryLoading(true);
setCreateLibraryMessage(null);
try {
const response = await fetch('/api/libraries/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: createLibraryForm.name.trim(),
description: createLibraryForm.description.trim(),
password: createLibraryForm.password,
}),
});
const data = await response.json();
if (response.ok && data.success) {
setCreateLibraryMessage({
type: 'success',
text: `Library "${data.library.name}" created successfully! You can now log out and log in with the new password to access it.`
});
setCreateLibraryForm({
name: '',
description: '',
password: '',
confirmPassword: ''
});
setShowCreateLibraryForm(false);
loadLibraries(); // Refresh the library list
} else {
setCreateLibraryMessage({type: 'error', text: data.error || 'Failed to create library'});
}
} catch (error) {
setCreateLibraryMessage({type: 'error', text: 'Network error occurred'});
} finally {
setCreateLibraryLoading(false);
}
};
if (loading) {
return (
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">
Library Settings
</h2>
<div className="animate-pulse">
<div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-1/4 mb-2"></div>
<div className="h-4 bg-gray-300 dark:bg-gray-600 rounded w-1/2"></div>
</div>
</div>
);
}
return (
<>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
<h2 className="text-xl font-semibold mb-4 text-gray-900 dark:text-white">
Library Settings
</h2>
{/* Current Library Info */}
{currentLibrary && (
<div className="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
<h3 className="font-medium text-blue-900 dark:text-blue-100 mb-1">
Active Library
</h3>
<p className="text-blue-700 dark:text-blue-300 text-sm">
<strong>{currentLibrary.name}</strong>
</p>
<p className="text-blue-600 dark:text-blue-400 text-xs mt-1">
{currentLibrary.description}
</p>
</div>
)}
{/* Change Password Section */}
<div className="mb-6 border-t pt-4">
<h3 className="font-medium text-gray-900 dark:text-white mb-3">
Change Library Password
</h3>
{passwordChangeMessage && (
<div className={`p-3 rounded-lg mb-4 ${
passwordChangeMessage.type === 'success'
? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
: 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'
}`}>
<p className={`text-sm ${
passwordChangeMessage.type === 'success'
? 'text-green-700 dark:text-green-300'
: 'text-red-700 dark:text-red-300'
}`}>
{passwordChangeMessage.text}
</p>
</div>
)}
{!showPasswordChangeForm ? (
<div>
<p className="text-sm text-gray-600 dark:text-gray-300 mb-3">
Change the password for the current library ({currentLibrary?.name}).
</p>
<Button
onClick={() => setShowPasswordChangeForm(true)}
variant="secondary"
>
Change Password
</Button>
</div>
) : (
<form onSubmit={handlePasswordChange} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Current Password
</label>
<Input
type="password"
value={passwordChangeForm.currentPassword}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setPasswordChangeForm(prev => ({ ...prev, currentPassword: e.target.value }))
}
placeholder="Enter current password"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
New Password
</label>
<Input
type="password"
value={passwordChangeForm.newPassword}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setPasswordChangeForm(prev => ({ ...prev, newPassword: e.target.value }))
}
placeholder="Enter new password (min 8 characters)"
required
minLength={8}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Confirm New Password
</label>
<Input
type="password"
value={passwordChangeForm.confirmPassword}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setPasswordChangeForm(prev => ({ ...prev, confirmPassword: e.target.value }))
}
placeholder="Confirm new password"
required
minLength={8}
/>
</div>
<div className="flex space-x-3">
<Button
type="submit"
disabled={passwordChangeLoading}
loading={passwordChangeLoading}
>
{passwordChangeLoading ? 'Changing...' : 'Change Password'}
</Button>
<Button
type="button"
variant="secondary"
onClick={() => {
setShowPasswordChangeForm(false);
setPasswordChangeForm({
currentPassword: '',
newPassword: '',
confirmPassword: ''
});
setPasswordChangeMessage(null);
}}
>
Cancel
</Button>
</div>
</form>
)}
</div>
{/* Available Libraries */}
<div className="mb-6">
<h3 className="font-medium text-gray-900 dark:text-white mb-3">
Available Libraries
</h3>
<div className="space-y-2">
{libraries.map((library) => (
<div
key={library.id}
className={`p-3 rounded-lg border ${
library.isActive
? 'border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-900/20'
: 'border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50'
}`}
>
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-gray-900 dark:text-white">
{library.name}
{library.isActive && (
<span className="ml-2 text-xs px-2 py-1 bg-blue-100 dark:bg-blue-800 text-blue-800 dark:text-blue-200 rounded-full">
Active
</span>
)}
</p>
<p className="text-sm text-gray-600 dark:text-gray-300">
{library.description}
</p>
</div>
{!library.isActive && (
<div className="text-xs text-gray-500 dark:text-gray-400">
ID: {library.id}
</div>
)}
</div>
</div>
))}
</div>
</div>
{/* Switch Library Section */}
<div className="border-t pt-4">
<h3 className="font-medium text-gray-900 dark:text-white mb-3">
Switch Library
</h3>
{!showSwitchForm ? (
<div>
<p className="text-sm text-gray-600 dark:text-gray-300 mb-3">
Enter the password for a different library to switch to it.
</p>
<Button
onClick={() => setShowSwitchForm(true)}
variant="secondary"
>
Switch to Different Library
</Button>
</div>
) : (
<form onSubmit={handleSwitchLibrary} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Library Password
</label>
<Input
type="password"
value={switchPassword}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSwitchPassword(e.target.value)}
placeholder="Enter password for the library you want to access"
required
/>
</div>
{switchState.error && (
<div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
<p className="text-sm text-red-700 dark:text-red-300">
{switchState.error}
</p>
</div>
)}
<div className="flex space-x-3">
<Button type="submit" disabled={switchState.isLoading}>
{switchState.isLoading ? 'Switching...' : 'Switch Library'}
</Button>
<Button
type="button"
variant="secondary"
onClick={() => {
setShowSwitchForm(false);
setSwitchPassword('');
clearError();
}}
>
Cancel
</Button>
</div>
</form>
)}
</div>
{/* Create New Library Section */}
<div className="border-t pt-4 mb-6">
<h3 className="font-medium text-gray-900 dark:text-white mb-3">
Create New Library
</h3>
{createLibraryMessage && (
<div className={`p-3 rounded-lg mb-4 ${
createLibraryMessage.type === 'success'
? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
: 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'
}`}>
<p className={`text-sm ${
createLibraryMessage.type === 'success'
? 'text-green-700 dark:text-green-300'
: 'text-red-700 dark:text-red-300'
}`}>
{createLibraryMessage.text}
</p>
</div>
)}
{!showCreateLibraryForm ? (
<div>
<p className="text-sm text-gray-600 dark:text-gray-300 mb-3">
Create a completely separate library with its own stories, authors, and password.
</p>
<Button
onClick={() => setShowCreateLibraryForm(true)}
variant="secondary"
>
Create New Library
</Button>
</div>
) : (
<form onSubmit={handleCreateLibrary} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Library Name *
</label>
<Input
type="text"
value={createLibraryForm.name}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCreateLibraryForm(prev => ({ ...prev, name: e.target.value }))
}
placeholder="e.g., Private Stories, Work Collection"
required
minLength={2}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Description
</label>
<Input
type="text"
value={createLibraryForm.description}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCreateLibraryForm(prev => ({ ...prev, description: e.target.value }))
}
placeholder="Optional description for this library"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Password *
</label>
<Input
type="password"
value={createLibraryForm.password}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCreateLibraryForm(prev => ({ ...prev, password: e.target.value }))
}
placeholder="Enter password (min 8 characters)"
required
minLength={8}
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Confirm Password *
</label>
<Input
type="password"
value={createLibraryForm.confirmPassword}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setCreateLibraryForm(prev => ({ ...prev, confirmPassword: e.target.value }))
}
placeholder="Confirm password"
required
minLength={8}
/>
</div>
<div className="flex space-x-3">
<Button
type="submit"
disabled={createLibraryLoading}
loading={createLibraryLoading}
>
{createLibraryLoading ? 'Creating...' : 'Create Library'}
</Button>
<Button
type="button"
variant="secondary"
onClick={() => {
setShowCreateLibraryForm(false);
setCreateLibraryForm({
name: '',
description: '',
password: '',
confirmPassword: ''
});
setCreateLibraryMessage(null);
}}
>
Cancel
</Button>
</div>
</form>
)}
</div>
{/* Info Box */}
<div className="mt-6 p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg">
<p className="text-sm text-yellow-800 dark:text-yellow-200">
<strong>Note:</strong> Libraries are completely separate datasets. Switching libraries
will reload the application with a different set of stories, authors, and settings.
Each library has its own password for security.
</p>
</div>
</div>
{/* Library Switch Loader */}
<LibrarySwitchLoader
isVisible={switchState.isLoading}
targetLibraryName={switchState.targetLibraryName || undefined}
onComplete={handleSwitchComplete}
onError={handleSwitchError}
/>
</>
);
}

View File

@@ -0,0 +1,319 @@
'use client';
import { useState } from 'react';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
import TagDisplay from '../tags/TagDisplay';
import AdvancedFilters from './AdvancedFilters';
import type { Story, Tag, AdvancedFilters as AdvancedFiltersType } from '../../types/api';
interface MinimalLayoutProps {
stories: Story[];
tags: Tag[];
totalElements: number;
searchQuery: string;
selectedTags: string[];
viewMode: 'grid' | 'list';
sortOption: string;
sortDirection: 'asc' | 'desc';
advancedFilters?: AdvancedFiltersType;
onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onTagToggle: (tagName: string) => void;
onViewModeChange: (mode: 'grid' | 'list') => void;
onSortChange: (option: string) => void;
onSortDirectionToggle: () => void;
onAdvancedFiltersChange?: (filters: AdvancedFiltersType) => void;
onRandomStory: () => void;
onClearFilters: () => void;
children: React.ReactNode;
}
export default function MinimalLayout({
stories,
tags,
totalElements,
searchQuery,
selectedTags,
viewMode,
sortOption,
sortDirection,
advancedFilters = {},
onSearchChange,
onTagToggle,
onViewModeChange,
onSortChange,
onSortDirectionToggle,
onAdvancedFiltersChange,
onRandomStory,
onClearFilters,
children
}: MinimalLayoutProps) {
const [tagBrowserOpen, setTagBrowserOpen] = useState(false);
const [advancedFiltersOpen, setAdvancedFiltersOpen] = useState(false);
const [tagSearch, setTagSearch] = useState('');
const popularTags = tags.slice(0, 5);
// Filter tags based on search query
const filteredTags = tagSearch
? tags.filter(tag => tag.name.toLowerCase().includes(tagSearch.toLowerCase()))
: tags;
// Count active advanced filters
const activeAdvancedFiltersCount = Object.values(advancedFilters).filter(value =>
value !== undefined && value !== '' && value !== 'all' && value !== false
).length;
const getSortDisplayText = () => {
const sortLabels: Record<string, string> = {
lastRead: 'Last Read',
createdAt: 'Date Added',
title: 'Title',
authorName: 'Author',
rating: 'Rating',
};
const direction = sortDirection === 'asc' ? '↑' : '↓';
return `Sort: ${sortLabels[sortOption] || sortOption} ${direction}`;
};
return (
<div className="max-w-6xl mx-auto p-10 max-md:p-5">
{/* Minimal Header */}
<div className="text-center mb-10">
<h1 className="text-4xl font-light theme-header mb-2">Story Library</h1>
<p className="theme-text text-lg mb-8">
Your personal collection of {totalElements} stories
</p>
<div>
<Button variant="primary" onClick={onRandomStory}>
🎲 Random Story
</Button>
</div>
</div>
{/* Floating Control Bar */}
<div className="sticky top-5 z-10 mb-8">
<div className="bg-white/95 dark:bg-gray-800/95 backdrop-blur-sm border theme-border rounded-xl p-4 shadow-lg">
<div className="grid grid-cols-3 gap-6 items-center max-md:grid-cols-1 max-md:gap-4">
{/* Search */}
<div>
<Input
type="search"
placeholder="Search stories, authors, tags..."
value={searchQuery}
onChange={onSearchChange}
className="w-full"
/>
</div>
{/* Sort & Clear */}
<div className="flex items-center gap-4">
<button
onClick={onSortDirectionToggle}
className="text-sm theme-text hover:theme-accent transition-colors border-none bg-transparent"
>
{getSortDisplayText()}
</button>
<span className="text-gray-300 dark:text-gray-600">|</span>
{/* Advanced Filters Button */}
{onAdvancedFiltersChange && (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setAdvancedFiltersOpen(true)}
className={activeAdvancedFiltersCount > 0 ? 'text-blue-600 dark:text-blue-400' : ''}
>
Advanced
{activeAdvancedFiltersCount > 0 && (
<span className="ml-1 text-xs bg-blue-500 text-white px-1 rounded">
{activeAdvancedFiltersCount}
</span>
)}
</Button>
<span className="text-gray-300 dark:text-gray-600">|</span>
</>
)}
{(searchQuery || selectedTags.length > 0 || activeAdvancedFiltersCount > 0) && (
<Button variant="ghost" size="sm" onClick={onClearFilters}>
Clear Filters
</Button>
)}
</div>
{/* View Toggle */}
<div className="justify-self-end max-md:justify-self-auto">
<div className="flex border theme-border rounded-lg overflow-hidden">
<Button
variant={viewMode === 'list' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('list')}
className="rounded-none border-0 px-3 py-2"
>
List
</Button>
<Button
variant={viewMode === 'grid' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('grid')}
className="rounded-none border-0 px-3 py-2"
>
Grid
</Button>
</div>
</div>
</div>
</div>
</div>
{/* Tag Filter */}
<div className="text-center mb-6">
<div className="inline-flex flex-wrap gap-2 justify-center mb-3">
<button
onClick={() => onClearFilters()}
className={`px-4 py-2 rounded-full text-sm font-medium transition-colors border ${
selectedTags.length === 0
? 'bg-blue-500 text-white border-blue-500'
: 'bg-white dark:bg-gray-800 theme-text border-gray-300 dark:border-gray-600 hover:border-blue-500 hover:text-blue-500'
}`}
>
All
</button>
{popularTags.map((tag) => (
<div
key={tag.id}
onClick={() => onTagToggle(tag.name)}
className={`cursor-pointer transition-all hover:scale-105 ${
selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-2' : ''
}`}
>
<TagDisplay
tag={tag}
size="md"
clickable={true}
className={`${selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : 'border-gray-300 dark:border-gray-600 hover:border-blue-500'}`}
/>
</div>
))}
</div>
<div>
<Button
variant="ghost"
size="sm"
onClick={() => setTagBrowserOpen(true)}
>
Browse All Tags ({tags.length})
</Button>
</div>
</div>
{/* Content */}
{children}
{/* Tag Browser Modal */}
{tagBrowserOpen && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto">
<div className="flex justify-between items-center mb-5">
<h3 className="text-xl font-semibold theme-header">Browse All Tags</h3>
<button
onClick={() => {
setTagBrowserOpen(false);
setTagSearch('');
}}
className="text-2xl theme-text hover:theme-accent transition-colors"
>
</button>
</div>
<div className="mb-4">
<Input
type="text"
placeholder="Search tags..."
value={tagSearch}
onChange={(e) => setTagSearch(e.target.value)}
className="w-full"
/>
</div>
<div className="grid grid-cols-4 gap-2 max-md:grid-cols-2">
{filteredTags.length === 0 && tagSearch ? (
<div className="col-span-4 text-center text-sm text-gray-500 py-4">
No tags match "{tagSearch}"
</div>
) : (
filteredTags.map((tag) => (
<div
key={tag.id}
onClick={() => onTagToggle(tag.name)}
className={`cursor-pointer transition-all hover:scale-105 ${
selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-1' : ''
}`}
>
<TagDisplay
tag={{...tag, name: `${tag.name} (${tag.storyCount})`}}
size="sm"
clickable={true}
className={`w-full text-left ${selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : 'bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 hover:border-blue-500'}`}
/>
</div>
))
)}
</div>
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={() => setTagSearch('')}>
Clear Search
</Button>
<Button variant="ghost" onClick={onClearFilters}>
Clear All
</Button>
<Button variant="primary" onClick={() => {
setTagBrowserOpen(false);
setTagSearch('');
}}>
Apply Filters
</Button>
</div>
</div>
</div>
)}
{/* Advanced Filters Modal */}
{advancedFiltersOpen && onAdvancedFiltersChange && (
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
<div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-2xl w-full max-h-[80vh] overflow-y-auto">
<div className="flex justify-between items-center mb-5">
<h3 className="text-xl font-semibold theme-header">Advanced Filters</h3>
<button
onClick={() => setAdvancedFiltersOpen(false)}
className="text-2xl theme-text hover:theme-accent transition-colors"
>
</button>
</div>
<AdvancedFilters
filters={advancedFilters}
onChange={onAdvancedFiltersChange}
onReset={() => onAdvancedFiltersChange({})}
/>
<div className="flex justify-end gap-3 mt-6">
<Button variant="ghost" onClick={() => setAdvancedFiltersOpen(false)}>
Close
</Button>
<Button
variant="primary"
onClick={() => setAdvancedFiltersOpen(false)}
>
Apply Filters
</Button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,245 @@
'use client';
import { useState } from 'react';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
import TagDisplay from '../tags/TagDisplay';
import AdvancedFilters from './AdvancedFilters';
import type { Story, Tag, AdvancedFilters as AdvancedFiltersType } from '../../types/api';
interface SidebarLayoutProps {
stories: Story[];
tags: Tag[];
totalElements: number;
searchQuery: string;
selectedTags: string[];
viewMode: 'grid' | 'list';
sortOption: string;
sortDirection: 'asc' | 'desc';
advancedFilters?: AdvancedFiltersType;
onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onTagToggle: (tagName: string) => void;
onViewModeChange: (mode: 'grid' | 'list') => void;
onSortChange: (option: string) => void;
onSortDirectionToggle: () => void;
onAdvancedFiltersChange?: (filters: AdvancedFiltersType) => void;
onRandomStory: () => void;
onClearFilters: () => void;
children: React.ReactNode;
}
export default function SidebarLayout({
stories,
tags,
totalElements,
searchQuery,
selectedTags,
viewMode,
sortOption,
sortDirection,
advancedFilters = {},
onSearchChange,
onTagToggle,
onViewModeChange,
onSortChange,
onSortDirectionToggle,
onAdvancedFiltersChange,
onRandomStory,
onClearFilters,
children
}: SidebarLayoutProps) {
const [tagSearch, setTagSearch] = useState('');
const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
// Filter tags based on search query
const filteredTags = tags.filter(tag =>
tag.name.toLowerCase().includes(tagSearch.toLowerCase())
);
// Count active advanced filters
const activeAdvancedFiltersCount = Object.values(advancedFilters).filter(value =>
value !== undefined && value !== '' && value !== 'all' && value !== false
).length;
return (
<div className="flex min-h-screen">
{/* Left Sidebar */}
<div className="w-80 min-w-80 max-w-80 bg-white dark:bg-gray-800 p-4 border-r theme-border sticky top-0 h-screen overflow-y-auto overflow-x-hidden max-md:w-full max-md:min-w-full max-md:max-w-full max-md:h-auto max-md:static max-md:border-r-0 max-md:border-b max-md:max-h-96">
{/* Random Story Button */}
<div className="mb-6">
<Button
onClick={onRandomStory}
variant="primary"
className="w-full"
>
🎲 Random Story
</Button>
</div>
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-bold theme-header">Your Library</h1>
<p className="theme-text mt-1">{totalElements} stories total</p>
</div>
{/* Search */}
<div className="mb-6">
<Input
type="search"
placeholder="Search stories..."
value={searchQuery}
onChange={onSearchChange}
className="w-full"
/>
</div>
{/* View Toggle */}
<div className="mb-6">
<div className="flex gap-2">
<Button
variant={viewMode === 'grid' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('grid')}
className="flex-1"
>
Grid
</Button>
<Button
variant={viewMode === 'list' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('list')}
className="flex-1"
>
List
</Button>
</div>
</div>
{/* Sort Controls */}
<div className="mb-6 theme-card p-4 rounded-lg">
<h3 className="text-sm font-medium theme-header mb-3">Sort By</h3>
<div className="flex gap-2 items-center">
<select
value={sortOption}
onChange={(e) => onSortChange(e.target.value)}
className="flex-1 px-3 py-2 border rounded-lg theme-card border-gray-300 dark:border-gray-600"
>
<option value="lastRead">Last Read</option>
<option value="createdAt">Date Added</option>
<option value="title">Title</option>
<option value="authorName">Author</option>
<option value="rating">Rating</option>
</select>
<Button
variant="ghost"
onClick={onSortDirectionToggle}
className="px-3 py-2"
title={`Toggle sort direction (currently ${sortDirection === 'asc' ? 'ascending' : 'descending'})`}
>
{sortDirection === 'asc' ? '↑' : '↓'}
</Button>
</div>
</div>
{/* Tag Filters */}
<div className="theme-card p-4 rounded-lg">
<h3 className="text-sm font-medium theme-header mb-3">Filter by Tags</h3>
<div className="mb-3">
<input
type="text"
placeholder="Search tags..."
value={tagSearch}
onChange={(e) => setTagSearch(e.target.value)}
className="w-full px-2 py-1 text-xs border rounded theme-card border-gray-300 dark:border-gray-600"
/>
</div>
<div className="max-h-48 overflow-y-auto border theme-border rounded p-2">
<div className="space-y-1">
<label className="flex items-center gap-2 py-1 cursor-pointer">
<input
type="checkbox"
checked={selectedTags.length === 0}
onChange={() => onClearFilters()}
/>
<span className="text-xs">All Stories ({totalElements})</span>
</label>
{filteredTags.map((tag) => (
<label
key={tag.id}
className="flex items-center gap-2 py-1 cursor-pointer"
>
<input
type="checkbox"
checked={selectedTags.includes(tag.name)}
onChange={() => onTagToggle(tag.name)}
/>
<div className="flex items-center gap-2 flex-1 min-w-0">
<TagDisplay
tag={tag}
size="sm"
clickable={false}
className="flex-shrink-0"
/>
<span className="text-xs text-gray-600 dark:text-gray-400 flex-shrink-0">
({tag.storyCount})
</span>
</div>
</label>
))}
{filteredTags.length === 0 && tagSearch && (
<div className="text-center text-xs text-gray-500 py-2">
No tags match "{tagSearch}"
</div>
)}
{filteredTags.length > 10 && !tagSearch && (
<div className="text-center text-xs text-gray-500 py-2">
... and {filteredTags.length - 10} more tags
</div>
)}
</div>
</div>
<div className="mt-2 space-y-2">
<Button
variant="ghost"
onClick={onClearFilters}
className="w-full text-xs py-1"
>
Clear All
</Button>
{/* Advanced Filters Toggle */}
{onAdvancedFiltersChange && (
<Button
variant={showAdvancedFilters || activeAdvancedFiltersCount > 0 ? "primary" : "ghost"}
onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
className={`w-full text-xs py-1 ${showAdvancedFilters || activeAdvancedFiltersCount > 0 ? '' : 'border-dashed border-2'}`}
>
Advanced Filters
{activeAdvancedFiltersCount > 0 && (
<span className="ml-1 bg-white text-blue-500 px-1 rounded text-xs">
{activeAdvancedFiltersCount}
</span>
)}
</Button>
)}
</div>
{/* Advanced Filters Section */}
{showAdvancedFilters && onAdvancedFiltersChange && (
<div className="mt-4 pt-4 border-t theme-border">
<AdvancedFilters
filters={advancedFilters}
onChange={onAdvancedFiltersChange}
onReset={() => onAdvancedFiltersChange({})}
className="space-y-3 max-w-full overflow-hidden"
/>
</div>
)}
</div>
</div>
{/* Main Content */}
<div className="flex-1 p-4 max-md:p-4">
{children}
</div>
</div>
);
}

View File

@@ -0,0 +1,316 @@
'use client';
import { useState } from 'react';
import { Input } from '../ui/Input';
import Button from '../ui/Button';
import TagDisplay from '../tags/TagDisplay';
import AdvancedFilters from './AdvancedFilters';
import { Story, Tag, AdvancedFilters as AdvancedFiltersType } from '../../types/api';
interface ToolbarLayoutProps {
stories: Story[];
tags: Tag[];
totalElements: number;
searchQuery: string;
selectedTags: string[];
viewMode: 'grid' | 'list';
sortOption: string;
sortDirection: 'asc' | 'desc';
advancedFilters?: AdvancedFiltersType;
onSearchChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onTagToggle: (tagName: string) => void;
onViewModeChange: (mode: 'grid' | 'list') => void;
onSortChange: (option: string) => void;
onSortDirectionToggle: () => void;
onAdvancedFiltersChange?: (filters: AdvancedFiltersType) => void;
onRandomStory: () => void;
onClearFilters: () => void;
children: React.ReactNode;
}
export default function ToolbarLayout({
stories,
tags,
totalElements,
searchQuery,
selectedTags,
viewMode,
sortOption,
sortDirection,
advancedFilters = {},
onSearchChange,
onTagToggle,
onViewModeChange,
onSortChange,
onSortDirectionToggle,
onAdvancedFiltersChange,
onRandomStory,
onClearFilters,
children
}: ToolbarLayoutProps) {
const [filterExpanded, setFilterExpanded] = useState(false);
const [activeTab, setActiveTab] = useState<'tags' | 'advanced'>('tags');
const [tagSearch, setTagSearch] = useState('');
const popularTags = tags.slice(0, 6);
// Filter remaining tags based on search query
const remainingTags = tags.slice(6);
const filteredRemainingTags = tagSearch
? remainingTags.filter(tag => tag.name.toLowerCase().includes(tagSearch.toLowerCase()))
: remainingTags;
const remainingTagsCount = Math.max(0, remainingTags.length);
// Count active advanced filters
const activeAdvancedFiltersCount = Object.values(advancedFilters).filter(value =>
value !== undefined && value !== '' && value !== 'all' && value !== false
).length;
return (
<div className="max-w-7xl mx-auto p-6 max-md:p-4">
{/* Integrated Header */}
<div className="theme-card theme-shadow rounded-xl p-6 mb-6 relative max-md:p-4">
{/* Title and Random Story Button */}
<div className="flex justify-between items-start mb-6 max-md:flex-col max-md:gap-4">
<div>
<h1 className="text-3xl font-bold theme-header">Your Story Library</h1>
<p className="theme-text mt-1">{totalElements} stories in your collection</p>
</div>
<div className="max-md:self-end">
<Button variant="secondary" onClick={onRandomStory}>
🎲 Random Story
</Button>
</div>
</div>
{/* Integrated Toolbar */}
<div className="grid grid-cols-4 gap-5 items-center mb-5 max-md:grid-cols-1 max-md:gap-3">
{/* Search */}
<div className="col-span-2 max-md:col-span-1">
<Input
type="search"
placeholder="Search by title, author, or tags..."
value={searchQuery}
onChange={onSearchChange}
className="w-full"
/>
</div>
{/* Sort */}
<div>
<select
value={`${sortOption}_${sortDirection}`}
onChange={(e) => {
const [option, direction] = e.target.value.split('_');
onSortChange(option);
if (sortDirection !== direction) {
onSortDirectionToggle();
}
}}
className="w-full px-3 py-2 border rounded-lg theme-card border-gray-300 dark:border-gray-600"
>
<option value="lastRead_desc">Sort: Last Read </option>
<option value="lastRead_asc">Sort: Last Read </option>
<option value="createdAt_desc">Sort: Date Added </option>
<option value="createdAt_asc">Sort: Date Added </option>
<option value="title_asc">Sort: Title </option>
<option value="title_desc">Sort: Title </option>
<option value="authorName_asc">Sort: Author </option>
<option value="authorName_desc">Sort: Author </option>
<option value="rating_desc">Sort: Rating </option>
<option value="rating_asc">Sort: Rating </option>
</select>
</div>
{/* View Toggle & Clear */}
<div className="flex gap-2">
<div className="flex border theme-border rounded-lg overflow-hidden">
<Button
variant={viewMode === 'grid' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('grid')}
className="rounded-none border-0"
>
Grid
</Button>
<Button
variant={viewMode === 'list' ? 'primary' : 'ghost'}
onClick={() => onViewModeChange('list')}
className="rounded-none border-0"
>
List
</Button>
</div>
{(searchQuery || selectedTags.length > 0) && (
<Button variant="ghost" onClick={onClearFilters}>
Clear
</Button>
)}
</div>
</div>
{/* Filter Section */}
<div className="border-t theme-border pt-5">
{/* Top row - Popular tags and expand button */}
<div className="flex flex-wrap items-center gap-2 mb-3">
<span className="font-medium theme-text text-sm">Popular Tags:</span>
<button
onClick={() => onClearFilters()}
className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${
selectedTags.length === 0 && activeAdvancedFiltersCount === 0
? 'bg-blue-500 text-white'
: 'bg-gray-100 dark:bg-gray-700 theme-text hover:bg-blue-100 dark:hover:bg-blue-900'
}`}
>
All Stories
</button>
{popularTags.map((tag) => (
<div
key={tag.id}
onClick={() => onTagToggle(tag.name)}
className={`cursor-pointer transition-all hover:scale-105 ${
selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-1' : ''
}`}
>
<TagDisplay
tag={{...tag, name: `${tag.name} (${tag.storyCount})`}}
size="sm"
clickable={true}
className={selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : ''}
/>
</div>
))}
{/* Filter expand button with counts */}
<button
onClick={() => setFilterExpanded(!filterExpanded)}
className={`px-3 py-1 rounded-full text-xs font-medium border-2 border-dashed transition-colors ${
filterExpanded || activeAdvancedFiltersCount > 0 || remainingTagsCount > 0
? 'bg-blue-50 dark:bg-blue-900/20 border-blue-500 text-blue-700 dark:text-blue-300'
: 'bg-gray-50 dark:bg-gray-800 theme-text border-gray-300 dark:border-gray-600 hover:border-blue-500'
}`}
>
{remainingTagsCount > 0 && `+${remainingTagsCount} tags`}
{remainingTagsCount > 0 && activeAdvancedFiltersCount > 0 && ' • '}
{activeAdvancedFiltersCount > 0 && `${activeAdvancedFiltersCount} filters`}
{remainingTagsCount === 0 && activeAdvancedFiltersCount === 0 && 'More Filters'}
</button>
<div className="ml-auto text-sm theme-text">
Showing {stories.length} of {totalElements} stories
</div>
</div>
{/* Expandable Filter Panel */}
{filterExpanded && (
<div className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border theme-border">
{/* Tab Navigation */}
<div className="flex gap-1 mb-4">
<button
onClick={() => setActiveTab('tags')}
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
activeTab === 'tags'
? 'bg-white dark:bg-gray-700 theme-text shadow-sm'
: 'theme-text hover:bg-white/50 dark:hover:bg-gray-700/50'
}`}
>
📋 Tags
{remainingTagsCount > 0 && (
<span className="ml-1 text-xs bg-gray-200 dark:bg-gray-600 px-1 rounded">
{remainingTagsCount}
</span>
)}
</button>
<button
onClick={() => setActiveTab('advanced')}
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
activeTab === 'advanced'
? 'bg-white dark:bg-gray-700 theme-text shadow-sm'
: 'theme-text hover:bg-white/50 dark:hover:bg-gray-700/50'
}`}
>
Advanced
{activeAdvancedFiltersCount > 0 && (
<span className="ml-1 text-xs bg-blue-500 text-white px-1 rounded">
{activeAdvancedFiltersCount}
</span>
)}
</button>
</div>
{/* Tab Content */}
{activeTab === 'tags' && (
<div className="space-y-3">
<div className="flex gap-3">
<Input
type="text"
placeholder="Search from all available tags..."
value={tagSearch}
onChange={(e) => setTagSearch(e.target.value)}
className="flex-1"
/>
{tagSearch && (
<Button variant="ghost" onClick={() => setTagSearch('')}>
Clear
</Button>
)}
</div>
<div className="grid grid-cols-4 gap-2 max-h-40 overflow-y-auto max-md:grid-cols-2">
{filteredRemainingTags.length === 0 && tagSearch ? (
<div className="col-span-4 text-center text-sm text-gray-500 py-4">
No tags match "{tagSearch}"
</div>
) : (
filteredRemainingTags.map((tag) => (
<div
key={tag.id}
onClick={() => onTagToggle(tag.name)}
className={`cursor-pointer transition-all hover:scale-105 ${
selectedTags.includes(tag.name) ? 'ring-2 ring-blue-500 ring-offset-1' : ''
}`}
>
<TagDisplay
tag={{...tag, name: `${tag.name} (${tag.storyCount})`}}
size="sm"
clickable={true}
className={`w-full ${selectedTags.includes(tag.name) ? 'bg-blue-500 text-white border-blue-500' : ''}`}
/>
</div>
))
)}
</div>
</div>
)}
{activeTab === 'advanced' && onAdvancedFiltersChange && (
<AdvancedFilters
filters={advancedFilters}
onChange={onAdvancedFiltersChange}
onReset={() => onAdvancedFiltersChange({})}
/>
)}
{/* Action buttons */}
<div className="flex justify-end gap-3 mt-4 pt-3 border-t theme-border">
<Button
variant="ghost"
onClick={() => setFilterExpanded(false)}
>
Close
</Button>
{(selectedTags.length > 0 || activeAdvancedFiltersCount > 0) && (
<Button variant="ghost" onClick={onClearFilters}>
Clear All Filters
</Button>
)}
</div>
</div>
)}
</div>
</div>
{/* Content */}
{children}
</div>
);
}

View File

@@ -0,0 +1,231 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { authorApi } from '../../lib/api';
import { Author } from '../../types/api';
interface AuthorSelectorProps {
value: string;
onChange: (authorName: string, authorId?: string) => void;
placeholder?: string;
error?: string;
disabled?: boolean;
required?: boolean;
label?: string;
}
export default function AuthorSelector({
value,
onChange,
placeholder = 'Enter or select an author',
error,
disabled = false,
required = false,
label = 'Author'
}: AuthorSelectorProps) {
const [isOpen, setIsOpen] = useState(false);
const [authors, setAuthors] = useState<Author[]>([]);
const [filteredAuthors, setFilteredAuthors] = useState<Author[]>([]);
const [loading, setLoading] = useState(false);
const [inputValue, setInputValue] = useState(value || '');
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
// Load authors when component mounts or when dropdown opens
useEffect(() => {
const loadAuthors = async () => {
try {
setLoading(true);
const result = await authorApi.getAuthors({ page: 0, size: 100 }); // Get first 100 authors
setAuthors(result.content);
} catch (error) {
console.error('Failed to load authors:', error);
} finally {
setLoading(false);
}
};
if (isOpen && authors.length === 0) {
loadAuthors();
}
}, [isOpen, authors.length]);
// Filter authors based on input value
useEffect(() => {
if (!inputValue.trim()) {
setFilteredAuthors(authors);
} else {
const filtered = authors.filter(author =>
author.name.toLowerCase().includes(inputValue.toLowerCase())
);
setFilteredAuthors(filtered);
}
}, [inputValue, authors]);
// Update input value when prop value changes
useEffect(() => {
if (value !== inputValue) {
setInputValue(value || '');
}
}, [value]);
// Handle clicking outside to close dropdown
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}
}, [isOpen]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInputValue(newValue);
setIsOpen(true);
// Call onChange for free-form text entry (new author)
onChange(newValue);
};
const handleAuthorSelect = (author: Author) => {
setInputValue(author.name);
setIsOpen(false);
onChange(author.name, author.id);
};
const handleInputFocus = () => {
setIsOpen(true);
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
setIsOpen(false);
} else if (e.key === 'ArrowDown' && !isOpen) {
setIsOpen(true);
}
};
return (
<div className="relative" ref={dropdownRef}>
{label && (
<label className="block text-sm font-medium theme-header mb-2">
{label}{required && ' *'}
</label>
)}
<div className="relative">
<input
ref={inputRef}
type="text"
value={inputValue}
onChange={handleInputChange}
onFocus={handleInputFocus}
onKeyDown={handleKeyDown}
placeholder={placeholder}
disabled={disabled}
required={required}
className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:border-transparent transition-colors ${
error
? 'border-red-300 focus:ring-red-500 theme-error'
: 'theme-border focus:ring-theme-accent focus:theme-accent-border'
} ${disabled ? 'theme-disabled' : 'theme-input'}`}
aria-expanded={isOpen}
aria-haspopup="listbox"
role="combobox"
/>
{/* Dropdown arrow */}
<div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
<svg
className={`w-4 h-4 theme-text transition-transform ${isOpen ? 'rotate-180' : ''}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</div>
</div>
{/* Dropdown */}
{isOpen && (
<div className="absolute z-50 w-full mt-1 theme-card theme-shadow border theme-border rounded-md max-h-60 overflow-auto">
{loading ? (
<div className="px-3 py-2 text-sm theme-text text-center">
Loading authors...
</div>
) : filteredAuthors.length > 0 ? (
<>
{/* Existing authors */}
<div className="py-1">
{filteredAuthors.map((author) => (
<button
key={author.id}
type="button"
className="w-full text-left px-3 py-2 text-sm theme-text hover:theme-accent-light hover:theme-accent-text transition-colors flex items-center justify-between"
onClick={() => handleAuthorSelect(author)}
>
<span>{author.name}</span>
<span className="text-xs theme-text-muted">
{author.storyCount} {author.storyCount === 1 ? 'story' : 'stories'}
</span>
</button>
))}
</div>
{/* New author option if input doesn't match exactly */}
{inputValue.trim() && !filteredAuthors.find(a => a.name.toLowerCase() === inputValue.toLowerCase()) && (
<>
<div className="border-t theme-border"></div>
<div className="py-1">
<button
type="button"
className="w-full text-left px-3 py-2 text-sm theme-text hover:theme-accent-light hover:theme-accent-text transition-colors"
onClick={() => {
setIsOpen(false);
onChange(inputValue.trim());
}}
>
<span className="font-medium">Create new author:</span> "{inputValue.trim()}"
</button>
</div>
</>
)}
</>
) : inputValue.trim() ? (
/* No matches, show create new option */
<div className="py-1">
<button
type="button"
className="w-full text-left px-3 py-2 text-sm theme-text hover:theme-accent-light hover:theme-accent-text transition-colors"
onClick={() => {
setIsOpen(false);
onChange(inputValue.trim());
}}
>
<span className="font-medium">Create new author:</span> "{inputValue.trim()}"
</button>
</div>
) : (
/* No authors loaded or empty input */
<div className="px-3 py-2 text-sm theme-text-muted text-center">
{authors.length === 0 ? 'No authors yet' : 'Type to search or create new author'}
</div>
)}
</div>
)}
{error && (
<p className="mt-1 text-sm text-red-600 dark:text-red-400">
{error}
</p>
)}
</div>
);
}

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useRef, useEffect } from 'react';
import { useState, useRef, useEffect, useCallback } from 'react';
import { Textarea } from '../ui/Input';
import Button from '../ui/Button';
import { sanitizeHtmlSync } from '../../lib/sanitization';
@@ -20,9 +20,12 @@ export default function RichTextEditor({
}: RichTextEditorProps) {
const [viewMode, setViewMode] = useState<'visual' | 'html'>('visual');
const [htmlValue, setHtmlValue] = useState(value);
const [isMaximized, setIsMaximized] = useState(false);
const [containerHeight, setContainerHeight] = useState(300); // Default height in pixels
const previewRef = useRef<HTMLDivElement>(null);
const visualTextareaRef = useRef<HTMLTextAreaElement>(null);
const visualDivRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [isUserTyping, setIsUserTyping] = useState(false);
// Utility functions for cursor position preservation
@@ -60,6 +63,187 @@ export default function RichTextEditor({
}
};
// Maximize/minimize functionality
const toggleMaximize = () => {
if (!isMaximized) {
// Store current height before maximizing
if (containerRef.current) {
setContainerHeight(containerRef.current.scrollHeight || containerHeight);
}
}
setIsMaximized(!isMaximized);
};
const formatText = useCallback((tag: string) => {
if (viewMode === 'visual') {
const visualDiv = visualDivRef.current;
if (!visualDiv) return;
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const selectedText = range.toString();
if (selectedText) {
// Wrap selected text in the formatting tag
const formattedElement = document.createElement(tag);
formattedElement.textContent = selectedText;
range.deleteContents();
range.insertNode(formattedElement);
// Move cursor to end of inserted content
range.selectNodeContents(formattedElement);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
} else {
// No selection - insert template
const template = tag === 'h1' ? 'Heading 1' :
tag === 'h2' ? 'Heading 2' :
tag === 'h3' ? 'Heading 3' :
tag === 'h4' ? 'Heading 4' :
tag === 'h5' ? 'Heading 5' :
tag === 'h6' ? 'Heading 6' :
'Formatted text';
const formattedElement = document.createElement(tag);
formattedElement.textContent = template;
range.insertNode(formattedElement);
// Select the inserted text for easy editing
range.selectNodeContents(formattedElement);
selection.removeAllRanges();
selection.addRange(range);
}
// Update the state
setIsUserTyping(true);
onChange(visualDiv.innerHTML);
setHtmlValue(visualDiv.innerHTML);
setTimeout(() => setIsUserTyping(false), 100);
}
} else {
// HTML mode - existing logic with improvements
const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selectedText = htmlValue.substring(start, end);
if (selectedText) {
const beforeText = htmlValue.substring(0, start);
const afterText = htmlValue.substring(end);
const formattedText = `<${tag}>${selectedText}</${tag}>`;
const newValue = beforeText + formattedText + afterText;
setHtmlValue(newValue);
onChange(newValue);
// Restore cursor position
setTimeout(() => {
textarea.focus();
textarea.setSelectionRange(start, start + formattedText.length);
}, 0);
} else {
// No selection - insert template at cursor
const template = tag === 'h1' ? '<h1>Heading 1</h1>' :
tag === 'h2' ? '<h2>Heading 2</h2>' :
tag === 'h3' ? '<h3>Heading 3</h3>' :
tag === 'h4' ? '<h4>Heading 4</h4>' :
tag === 'h5' ? '<h5>Heading 5</h5>' :
tag === 'h6' ? '<h6>Heading 6</h6>' :
`<${tag}>Formatted text</${tag}>`;
const newValue = htmlValue.substring(0, start) + template + htmlValue.substring(start);
setHtmlValue(newValue);
onChange(newValue);
// Position cursor inside the new tag
setTimeout(() => {
const tagLength = `<${tag}>`.length;
const newPosition = start + tagLength;
textarea.focus();
textarea.setSelectionRange(newPosition, newPosition + (tag === 'p' ? 0 : template.includes('Heading') ? template.split('>')[1].split('<')[0].length : 'Formatted text'.length));
}, 0);
}
}
}, [viewMode, htmlValue, onChange]);
// Handle manual resize when dragging resize handle
const handleMouseDown = (e: React.MouseEvent) => {
if (isMaximized) return; // Don't allow resize when maximized
e.preventDefault();
const startY = e.clientY;
const startHeight = containerHeight;
const handleMouseMove = (e: MouseEvent) => {
const deltaY = e.clientY - startY;
const newHeight = Math.max(200, Math.min(800, startHeight + deltaY)); // Min 200px, Max 800px
setContainerHeight(newHeight);
};
const handleMouseUp = () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
// Keyboard shortcuts handler
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Escape key to exit maximized mode
if (e.key === 'Escape' && isMaximized) {
setIsMaximized(false);
return;
}
// Heading shortcuts: Ctrl+Shift+1-6
if (e.ctrlKey && e.shiftKey && !e.altKey && !e.metaKey) {
const num = parseInt(e.key);
if (num >= 1 && num <= 6) {
e.preventDefault();
formatText(`h${num}`);
return;
}
}
// Additional common shortcuts
if (e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey) {
switch (e.key.toLowerCase()) {
case 'b':
e.preventDefault();
formatText('strong');
return;
case 'i':
e.preventDefault();
formatText('em');
return;
}
}
};
document.addEventListener('keydown', handleKeyDown);
if (isMaximized) {
// Prevent body from scrolling when maximized
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = '';
}
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = '';
};
}, [isMaximized, formatText]);
// Set initial content when component mounts
useEffect(() => {
const div = visualDivRef.current;
@@ -321,97 +505,6 @@ export default function RichTextEditor({
.trim();
};
const formatText = (tag: string) => {
if (viewMode === 'visual') {
const visualDiv = visualDivRef.current;
if (!visualDiv) return;
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const selectedText = range.toString();
if (selectedText) {
// Wrap selected text in the formatting tag
const formattedElement = document.createElement(tag);
formattedElement.textContent = selectedText;
range.deleteContents();
range.insertNode(formattedElement);
// Move cursor to end of inserted content
range.selectNodeContents(formattedElement);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
} else {
// No selection - insert template
const template = tag === 'h1' ? 'Heading 1' :
tag === 'h2' ? 'Heading 2' :
tag === 'h3' ? 'Heading 3' :
'Formatted text';
const formattedElement = document.createElement(tag);
formattedElement.textContent = template;
range.insertNode(formattedElement);
// Select the inserted text for easy editing
range.selectNodeContents(formattedElement);
selection.removeAllRanges();
selection.addRange(range);
}
// Update the state
setIsUserTyping(true);
onChange(visualDiv.innerHTML);
setHtmlValue(visualDiv.innerHTML);
setTimeout(() => setIsUserTyping(false), 100);
}
} else {
// HTML mode - existing logic with improvements
const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
if (!textarea) return;
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const selectedText = htmlValue.substring(start, end);
if (selectedText) {
const beforeText = htmlValue.substring(0, start);
const afterText = htmlValue.substring(end);
const formattedText = `<${tag}>${selectedText}</${tag}>`;
const newValue = beforeText + formattedText + afterText;
setHtmlValue(newValue);
onChange(newValue);
// Restore cursor position
setTimeout(() => {
textarea.focus();
textarea.setSelectionRange(start, start + formattedText.length);
}, 0);
} else {
// No selection - insert template at cursor
const template = tag === 'h1' ? '<h1>Heading 1</h1>' :
tag === 'h2' ? '<h2>Heading 2</h2>' :
tag === 'h3' ? '<h3>Heading 3</h3>' :
`<${tag}>Formatted text</${tag}>`;
const newValue = htmlValue.substring(0, start) + template + htmlValue.substring(start);
setHtmlValue(newValue);
onChange(newValue);
// Position cursor inside the new tag
setTimeout(() => {
const tagLength = `<${tag}>`.length;
const newPosition = start + tagLength;
textarea.focus();
textarea.setSelectionRange(newPosition, newPosition + (tag === 'p' ? 0 : template.includes('Heading') ? template.split('>')[1].split('<')[0].length : 'Formatted text'.length));
}, 0);
}
}
};
return (
<div className="space-y-2">
@@ -439,12 +532,23 @@ export default function RichTextEditor({
</div>
<div className="flex items-center gap-1">
<Button
type="button"
size="sm"
variant="ghost"
onClick={toggleMaximize}
title={isMaximized ? "Minimize editor" : "Maximize editor"}
className="font-mono"
>
{isMaximized ? "⊡" : "⊞"}
</Button>
<div className="w-px h-4 bg-gray-300 mx-1" />
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('strong')}
title="Bold"
title="Bold (Ctrl+B)"
className="font-bold"
>
B
@@ -454,7 +558,7 @@ export default function RichTextEditor({
size="sm"
variant="ghost"
onClick={() => formatText('em')}
title="Italic"
title="Italic (Ctrl+I)"
className="italic"
>
I
@@ -465,7 +569,7 @@ export default function RichTextEditor({
size="sm"
variant="ghost"
onClick={() => formatText('h1')}
title="Heading 1"
title="Heading 1 (Ctrl+Shift+1)"
className="text-lg font-bold"
>
H1
@@ -475,7 +579,7 @@ export default function RichTextEditor({
size="sm"
variant="ghost"
onClick={() => formatText('h2')}
title="Heading 2"
title="Heading 2 (Ctrl+Shift+2)"
className="text-base font-bold"
>
H2
@@ -485,11 +589,41 @@ export default function RichTextEditor({
size="sm"
variant="ghost"
onClick={() => formatText('h3')}
title="Heading 3"
title="Heading 3 (Ctrl+Shift+3)"
className="text-sm font-bold"
>
H3
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h4')}
title="Heading 4 (Ctrl+Shift+4)"
className="text-xs font-bold"
>
H4
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h5')}
title="Heading 5 (Ctrl+Shift+5)"
className="text-xs font-bold"
>
H5
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h6')}
title="Heading 6 (Ctrl+Shift+6)"
className="text-xs font-bold"
>
H6
</Button>
<div className="w-px h-4 bg-gray-300 mx-1" />
<Button
type="button"
@@ -504,45 +638,195 @@ export default function RichTextEditor({
</div>
{/* Editor */}
<div className="border theme-border rounded-b-lg overflow-hidden">
{viewMode === 'visual' ? (
<div className="relative">
<div
ref={visualDivRef}
contentEditable
onInput={handleVisualContentChange}
onPaste={handlePaste}
className="p-3 min-h-[300px] focus:outline-none focus:ring-0 whitespace-pre-wrap"
style={{ minHeight: '300px' }}
suppressContentEditableWarning={true}
/>
{!value && (
<div
className="absolute top-3 left-3 text-gray-500 dark:text-gray-400 pointer-events-none select-none"
style={{ minHeight: '300px' }}
>
{placeholder}
<div
className={`relative border theme-border rounded-b-lg ${
isMaximized ? 'fixed inset-4 z-50 bg-white dark:bg-gray-900 shadow-2xl' : ''
}`}
style={isMaximized ? {} : { height: containerHeight }}
>
<div
ref={containerRef}
className="h-full flex flex-col overflow-hidden"
>
{/* Maximized toolbar (shown when maximized) */}
{isMaximized && (
<div className="flex items-center justify-between p-2 theme-card border-b theme-border">
<div className="flex items-center gap-2">
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setViewMode('visual')}
className={viewMode === 'visual' ? 'theme-accent-bg text-white' : ''}
>
Visual
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => setViewMode('html')}
className={viewMode === 'html' ? 'theme-accent-bg text-white' : ''}
>
HTML
</Button>
</div>
<div className="flex items-center gap-1">
<Button
type="button"
size="sm"
variant="ghost"
onClick={toggleMaximize}
title="Minimize editor"
className="font-mono"
>
</Button>
<div className="w-px h-4 bg-gray-300 mx-1" />
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('strong')}
title="Bold (Ctrl+B)"
className="font-bold"
>
B
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('em')}
title="Italic (Ctrl+I)"
className="italic"
>
I
</Button>
<div className="w-px h-4 bg-gray-300 mx-1" />
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h1')}
title="Heading 1 (Ctrl+Shift+1)"
className="text-lg font-bold"
>
H1
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h2')}
title="Heading 2 (Ctrl+Shift+2)"
className="text-base font-bold"
>
H2
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h3')}
title="Heading 3 (Ctrl+Shift+3)"
className="text-sm font-bold"
>
H3
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h4')}
title="Heading 4 (Ctrl+Shift+4)"
className="text-xs font-bold"
>
H4
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h5')}
title="Heading 5 (Ctrl+Shift+5)"
className="text-xs font-bold"
>
H5
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('h6')}
title="Heading 6 (Ctrl+Shift+6)"
className="text-xs font-bold"
>
H6
</Button>
<div className="w-px h-4 bg-gray-300 mx-1" />
<Button
type="button"
size="sm"
variant="ghost"
onClick={() => formatText('p')}
title="Paragraph"
>
P
</Button>
</div>
</div>
)}
{/* Editor content */}
<div className="flex-1 overflow-hidden">
{viewMode === 'visual' ? (
<div className="relative h-full">
<div
ref={visualDivRef}
contentEditable
onInput={handleVisualContentChange}
onPaste={handlePaste}
className="editor-content p-3 h-full overflow-y-auto focus:outline-none focus:ring-0 whitespace-pre-wrap resize-none"
suppressContentEditableWarning={true}
/>
{!value && (
<div className="absolute top-3 left-3 text-gray-500 dark:text-gray-400 pointer-events-none select-none">
{placeholder}
</div>
)}
</div>
) : (
<Textarea
value={htmlValue}
onChange={handleHtmlChange}
placeholder="<p>Write your HTML content here...</p>"
className="border-0 rounded-none focus:ring-0 font-mono text-sm h-full resize-none"
/>
)}
</div>
) : (
<Textarea
value={htmlValue}
onChange={handleHtmlChange}
placeholder="<p>Write your HTML content here...</p>"
rows={12}
className="border-0 rounded-none focus:ring-0 font-mono text-sm"
/>
</div>
{/* Resize handle (only show when not maximized) */}
{!isMaximized && (
<div
onMouseDown={handleMouseDown}
className="absolute bottom-0 left-0 right-0 h-2 cursor-ns-resize bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors flex items-center justify-center"
title="Drag to resize"
>
<div className="w-8 h-0.5 bg-gray-400 dark:bg-gray-500 rounded-full"></div>
</div>
)}
</div>
{/* Preview for HTML mode */}
{viewMode === 'html' && value && (
{/* Preview for HTML mode (only show when not maximized) */}
{viewMode === 'html' && value && !isMaximized && (
<div className="space-y-2">
<h4 className="text-sm font-medium theme-header">Preview:</h4>
<div
ref={previewRef}
className="p-4 border theme-border rounded-lg theme-card max-h-40 overflow-y-auto"
className="editor-content p-4 border theme-border rounded-lg theme-card max-h-40 overflow-y-auto"
dangerouslySetInnerHTML={{ __html: value }}
/>
</div>
@@ -561,6 +845,13 @@ export default function RichTextEditor({
<strong>HTML mode:</strong> Edit HTML source directly for advanced formatting.
Allowed tags: p, br, div, span, strong, em, b, i, u, s, h1-h6, ul, ol, li, blockquote, and more.
</p>
<p>
<strong>Keyboard shortcuts:</strong> Ctrl+B (Bold), Ctrl+I (Italic), Ctrl+Shift+1-6 (Headings 1-6).
</p>
<p>
<strong>Tips:</strong> Use the button to maximize the editor for larger stories.
Drag the resize handle at the bottom to adjust height. Press Escape to exit maximized mode.
</p>
</div>
</div>
);

Some files were not shown because too many files have changed in this diff Show More