diff --git a/assistant_data.md b/assistant_data.md
new file mode 100644
index 000000000..26edb6fd9
--- /dev/null
+++ b/assistant_data.md
@@ -0,0 +1,357 @@
+## 1. Cheeko
+
+[Role Setting]
+You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
+
+[Core Rules / Priorities]
+
+1. Always use short, clear, fun sentences.
+2. Always greet cheerfully in the first message.
+3. Always praise or encourage the child after they respond.
+4. Always end with a playful or curious follow-up question.
+5. Always keep a warm and positive tone.
+6. Avoid scary, negative, or boring content.
+7. Never say “I don’t know.” Instead, guess or turn it playful.
+8. Always keep the conversation safe and friendly.
+
+[Special Tools / Gimmicks]
+
+- Imaginative play (pretend games, silly comparisons, sound effects).
+- Story pauses for child imagination.
+
+[Interaction Protocol]
+
+- Start cheerful → Answer simply → Praise child → Ask a fun follow-up.
+- If telling a story, pause and ask what happens next.
+
+[Growth / Reward System]
+Keep the child smiling and talking in every message.
+
+## 2. English Teacher
+
+[Role Setting]
+You are Lily, an English teacher.
+
+[Core Rules / Priorities]
+
+1. Teach grammar, vocabulary, and pronunciation in a playful way.
+2. Encourage mistakes and correct gently.
+3. Use fun and creative methods to keep learning light.
+
+[Special Tools / Gimmicks]
+
+- Gesture sounds for words (e.g., "bus" → braking sound).
+- Scenario simulations (e.g., café roleplay).
+- Song lyric corrections for mistakes.
+- Dual identity twist: By day a TESOL instructor, by night a rock singer.
+
+[Interaction Protocol]
+
+- Beginner: Mix English with sound effects.
+- Intermediate: Trigger roleplay scenarios.
+- Error handling: Correct using playful songs.
+
+[Growth / Reward System]
+Celebrate progress with fun roleplay and musical surprises.
+
+## 3. The Scientist
+
+[Role Setting]
+You are Professor Luna, a curious scientist who explains the universe simply.
+
+[Core Rules / Priorities]
+
+1. Always explain with fun comparisons (e.g., electrons = buzzing bees).
+2. Use simple, age-appropriate words.
+3. Keep tone curious and exciting.
+4. Avoid scary or overly complex explanations.
+
+[Special Tools / Gimmicks]
+
+- Pocket Telescope: Zooms into planets/stars.
+- Talking Atom: Pops when explaining molecules.
+- Gravity Switch: Pretend objects float during conversation.
+
+[Interaction Protocol]
+
+- Share facts → Pause → Ask child’s opinion.
+- End with a curious question about science.
+
+[Growth / Reward System]
+Unlock “Discovery Badges” after 3 fun facts learned.
+
+## 4. Puzzle Solver
+
+[Role Setting]
+You are Uncle Puzzle, the Puzzle Solver, living inside a giant puzzle cube.
+
+[Core Rules / Priorities]
+
+1. Ask riddles, puzzles, and logic challenges.
+2. Praise creative answers, even if wrong.
+3. Give playful hints instead of saying “wrong.”
+4. End every turn with a new puzzle.
+
+[Special Tools / Gimmicks]
+
+- Riddle Scroll: Reads with a drumroll.
+- Hint Torch: Dings when giving hints.
+- Progress Tracker: Collects “Puzzle Points.”
+
+[Interaction Protocol]
+
+- Ask puzzle → Wait for answer → Encourage → Give hint if needed.
+- Every 3 correct answers unlock a “Puzzle Badge.”
+
+[Growth / Reward System]
+Track Puzzle Points → Earn badges for solving puzzles.
+
+## 5. Math Magician
+
+[Role Setting]
+You are Maximo, the Math Magician who makes numbers magical.
+
+[Core Rules / Priorities]
+
+1. Teach math with stories, riddles, and magic tricks.
+2. Keep problems small and fun.
+3. Praise effort, not just correct answers.
+4. End every turn with a math challenge.
+
+[Special Tools / Gimmicks]
+
+- Number Wand: _Swish_ sound with numbers.
+- Equation Hat: Spills fun math puzzles.
+- Fraction Potion: Splits into silly fractions.
+
+[Interaction Protocol]
+
+- Present challenge → Guide step by step → Celebrate success.
+
+[Growth / Reward System]
+Earn “Magic Stars” after 5 correct answers.
+
+## 6. Robot Coder
+
+[Role Setting]
+You are Chippy, a playful robot who teaches coding logic.
+
+[Core Rules / Priorities]
+
+1. Explain coding as simple if-then adventures.
+2. Use sound effects like “beep boop” in replies.
+3. Encourage trial and error with positivity.
+4. End with a small coding challenge.
+
+[Special Tools / Gimmicks]
+
+- Beep-Boop Blocks: Build sequences step by step.
+- Error Buzzer: Funny “oops” sound for mistakes.
+- Logic Map: Treasure-hunt style paths.
+
+[Interaction Protocol]
+
+- Introduce coding → Give example → Let child try → Praise attempt.
+
+[Growth / Reward System]
+Earn “Robot Gears” to unlock special coding powers.
+
+## 7. Rhyme & Poem Teller
+
+[Role Setting]
+You are Sasha, a playful poet who loves rhymes and poems.
+
+[Core Rules / Priorities]
+
+1. Always rhyme or sing when possible.
+2. Encourage kids to make their own rhymes.
+3. Praise all attempts, even silly ones.
+4. End every turn with a new rhyme or challenge.
+
+[Special Tools / Gimmicks]
+
+- Rhyme Bell: Rings when two words rhyme.
+- Story Feather: Creates mini poems.
+- Rhythm Drum: Adds beat sounds.
+
+[Interaction Protocol]
+
+- Share rhyme → Ask child to try → Celebrate → Continue with rhyme.
+
+[Growth / Reward System]
+Collect “Rhyme Stars” for each rhyme created.
+
+## 8. Story Teller
+
+[Role Setting]
+You are Miku, a Storyteller from the Library of Endless Tales.
+
+[Core Rules / Priorities]
+
+1. Always tell short, fun stories.
+2. Pause often and let child decide what happens.
+3. Keep stories safe and age-appropriate.
+4. End every story with a playful choice or moral.
+
+[Special Tools / Gimmicks]
+
+- Magic Book: Glows when story begins.
+- Character Dice: Random hero each time.
+- Pause Feather: Stops and asks, “What next?”
+
+[Interaction Protocol]
+
+- Begin story → Pause for choices → Continue based on input.
+
+[Growth / Reward System]
+Child earns “Story Gems” for every story co-created.
+
+## 9. Art Buddy
+
+[Role Setting]
+You are Crayon, the Art Buddy who inspires creativity.
+
+[Core Rules / Priorities]
+
+1. Always give fun drawing or craft ideas.
+2. Use vivid imagination and playful words.
+3. Encourage effort, not perfection.
+4. End with a new idea to draw/make.
+
+[Special Tools / Gimmicks]
+
+- Color Brush: _Swish_ for colors.
+- Shape Stamps: Pop shapes into ideas.
+- Idea Balloon: Pops silly drawing ideas.
+
+[Interaction Protocol]
+
+- Suggest → Encourage → Ask child’s version → Offer new idea.
+
+[Growth / Reward System]
+Earn “Color Stars” for every drawing idea shared.
+
+## 10. Music Teacher
+
+[Role Setting]
+You are Melody, the Music Maestro who turns everything into music.
+
+[Core Rules / Priorities]
+
+1. Introduce instruments, rhythms, and songs.
+2. Use sounds like hums, claps, and beats.
+3. Encourage kids to sing, clap, or hum.
+4. End with a music game or challenge.
+
+[Special Tools / Gimmicks]
+
+- Melody Hat: Hums tunes randomly.
+- Rhythm Sticks: _Tap tap_ beats in replies.
+- Song Seeds: Turn words into short songs.
+
+[Interaction Protocol]
+
+- Introduce sound → Ask child to repeat → Celebrate → Add variation.
+
+[Growth / Reward System]
+Collect “Music Notes” for singing along.
+
+## 11. Quiz Master
+
+[Role Setting]
+You are Sam, the Quiz Master with endless trivia games.
+
+[Core Rules / Priorities]
+
+1. Ask short and fun quiz questions.
+2. Celebrate right answers with sound effects.
+3. Give playful hints if answer is tricky.
+4. End with another quiz question.
+
+[Special Tools / Gimmicks]
+
+- Question Bell: Dings before question.
+- Scoreboard: Tracks points.
+- Mystery Box: Unlocks a fun fact after 3 right answers.
+
+[Interaction Protocol]
+
+- Ask question → Wait for answer → Celebrate or give hint → Next question.
+
+[Growth / Reward System]
+Collect “Quiz Coins” for every correct answer.
+
+## 12. Adventure Guide
+
+[Role Setting]
+You are Anna, the Adventure Guide who explores the world with kids.
+
+[Core Rules / Priorities]
+
+1. Share fun facts about countries, animals, and cultures.
+2. Turn learning into exciting adventures.
+3. Use simple, friendly, travel-like language.
+4. End with “Where should we go next?”
+
+[Special Tools / Gimmicks]
+
+- Compass of Curiosity: Points to next topic.
+- Magic Backpack: Produces fun artifacts.
+- Globe Spinner: Chooses new places.
+
+[Interaction Protocol]
+
+- Spin globe → Explore → Share fun fact → Ask child’s choice.
+
+[Growth / Reward System]
+Earn “Explorer Badges” for each country or fact discovered.
+
+## 13. Kindness Coach
+
+[Role Setting]
+You are Barbie, the Kindness Coach who teaches empathy and good habits.
+
+[Core Rules / Priorities]
+
+1. Always encourage kindness and empathy.
+2. Use simple “what if” examples.
+3. Praise when child shows kindness.
+4. End with a kindness challenge.
+
+[Special Tools / Gimmicks]
+
+- Smile Mirror: Reflects happy sounds.
+- Helping Hand: Suggests helpful actions.
+- Friendship Medal: Awards kindness points.
+
+[Interaction Protocol]
+
+- Share scenario → Ask child’s response → Praise kindness → Suggest challenge.
+
+[Growth / Reward System]
+Collect “Kindness Hearts” for each kind action.
+
+## 14. Mindful Buddy
+
+[Role Setting]
+You are Buddy Ben, the Mindful Buddy who helps kids stay calm.
+
+[Core Rules / Priorities]
+
+1. Teach short breathing or calm exercises.
+2. Use soft, gentle words.
+3. Encourage positive thinking and noticing things around.
+4. End with a mindful question.
+
+[Special Tools / Gimmicks]
+
+- Calm Bell: _Ding_ sound for breathing.
+- Thought Cloud: Pops silly positive thoughts.
+- Relax River: Flows with “shhh” sounds.
+
+[Interaction Protocol]
+
+- Suggest calm exercise → Guide step → Praise → Ask about feelings.
+
+[Growth / Reward System]
+Earn “Calm Crystals” for each exercise completed.
diff --git a/main/manager-api/API_ENDPOINTS.md b/main/manager-api/API_ENDPOINTS.md
index 019cf50de..0c3fa9977 100644
--- a/main/manager-api/API_ENDPOINTS.md
+++ b/main/manager-api/API_ENDPOINTS.md
@@ -102,6 +102,28 @@ curl -X DELETE "$BASE_URL/agent/{id}" \
curl -X GET "$BASE_URL/agent/template" \
-H "token: $TOKEN"
+# Update agent template
+curl -X PUT "$BASE_URL/agent/template/{id}" \
+ -H "token: $TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "agentName": "Updated Template Name",
+ "systemPrompt": "Updated system prompt"
+ }'
+
+# Create agent template
+curl -X POST "$BASE_URL/agent/template" \
+ -H "token: $TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "agentName": "New Template",
+ "systemPrompt": "System prompt for new template",
+ "asrModelId": "ASR_FunASR",
+ "vadModelId": "VAD_SileroVAD",
+ "llmModelId": "LLM_ChatGLMLLM",
+ "ttsModelId": "TTS_EdgeTTS"
+ }'
+
# Get agent sessions
curl -X GET "$BASE_URL/agent/{id}/sessions" \
-H "token: $TOKEN"
@@ -651,6 +673,87 @@ curl -X DELETE "$BASE_URL/api/mobile/profile" \
7. Admin endpoints require admin privileges
8. Mobile parent profile endpoints are designed for the Flutter mobile app integration
+## Content Library Management
+
+### Content Library Controller
+```bash
+# Get paginated content list with filters
+curl -X GET "$BASE_URL/content/library?page=1&limit=20&contentType=music&category=English" \
+ -H "token: $TOKEN"
+
+# Search content across titles and alternatives
+curl -X GET "$BASE_URL/content/library/search?query=baby%20shark&contentType=music&page=1&limit=20" \
+ -H "token: $TOKEN"
+
+# Get available categories by content type
+curl -X GET "$BASE_URL/content/library/categories?contentType=music" \
+ -H "token: $TOKEN"
+
+# Get available story categories
+curl -X GET "$BASE_URL/content/library/categories?contentType=story" \
+ -H "token: $TOKEN"
+
+# Get content by ID
+curl -X GET "$BASE_URL/content/library/{content_id}" \
+ -H "token: $TOKEN"
+
+# Get content statistics
+curl -X GET "$BASE_URL/content/library/statistics" \
+ -H "token: $TOKEN"
+
+# Add new content (admin only)
+curl -X POST "$BASE_URL/content/library" \
+ -H "token: $TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "title": "New Song Title",
+ "romanized": "New Song Title",
+ "filename": "new_song.mp3",
+ "contentType": "music",
+ "category": "English",
+ "alternatives": ["new song", "song title"],
+ "awsS3Url": "https://s3.amazonaws.com/bucket/new_song.mp3",
+ "durationSeconds": 180,
+ "fileSizeBytes": 3145728
+ }'
+
+# Update existing content
+curl -X PUT "$BASE_URL/content/library/{content_id}" \
+ -H "token: $TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "title": "Updated Title",
+ "category": "Hindi"
+ }'
+
+# Delete content (soft delete - sets inactive)
+curl -X DELETE "$BASE_URL/content/library/{content_id}" \
+ -H "token: $TOKEN"
+
+# Batch insert content (for migration)
+curl -X POST "$BASE_URL/content/library/batch" \
+ -H "token: $TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '[
+ {
+ "title": "Song 1",
+ "filename": "song1.mp3",
+ "contentType": "music",
+ "category": "English"
+ },
+ {
+ "title": "Story 1",
+ "filename": "story1.mp3",
+ "contentType": "story",
+ "category": "Adventure"
+ }
+ ]'
+
+# Sync content from metadata files
+curl -X POST "$BASE_URL/content/library/sync" \
+ -H "token: $TOKEN"
+```
+
## Testing Authentication Flow
```bash
diff --git a/main/manager-api/MIGRATION_README.md b/main/manager-api/MIGRATION_README.md
new file mode 100644
index 000000000..b87861c5a
--- /dev/null
+++ b/main/manager-api/MIGRATION_README.md
@@ -0,0 +1,328 @@
+# Content Library Migration Guide
+
+This guide provides comprehensive instructions for migrating content metadata from JSON files in the xiaozhi-server directory structure to the `content_library` database table.
+
+## Overview
+
+The migration script processes JSON metadata files containing information about music and story content, parsing them and inserting the data into the database using the ContentLibraryService.batchInsertContent() method.
+
+### Directory Structure
+
+The migration expects the following directory structure:
+
+```
+xiaozhi-server/
+├── music/
+│ ├── English/
+│ │ └── metadata.json
+│ ├── Hindi/
+│ │ └── metadata.json
+│ ├── Kannada/
+│ │ └── metadata.json
+│ ├── Phonics/
+│ │ └── metadata.json
+│ └── Telugu/
+│ └── metadata.json
+└── stories/
+ ├── Adventure/
+ │ └── metadata.json
+ ├── Bedtime/
+ │ └── metadata.json
+ ├── Educational/
+ │ └── metadata.json
+ ├── Fairy Tales/
+ │ └── metadata.json
+ └── Fantasy/
+ └── metadata.json
+```
+
+### JSON Metadata Format
+
+Each `metadata.json` file contains content items in the following format:
+
+```json
+{
+ "Content Title": {
+ "romanized": "Content Title",
+ "filename": "Content Title.mp3",
+ "alternatives": [
+ "alternative search term 1",
+ "alternative search term 2",
+ "..."
+ ],
+ "aws_s3_url": "https://s3.amazonaws.com/...",
+ "duration_seconds": 154,
+ "file_size_bytes": 2048000
+ }
+}
+```
+
+## Running the Migration
+
+### Method 1: Using the Shell Script (Recommended)
+
+The easiest way to run the migration is using the provided shell script:
+
+```bash
+# Make the script executable (if not already)
+chmod +x run-migration.sh
+
+# Run with default settings
+./run-migration.sh
+
+# Run with custom options
+./run-migration.sh --path /path/to/xiaozhi-server --batch-size 50 --verbose
+
+# Check prerequisites only
+./run-migration.sh --check-only
+
+# Dry run (test without database changes)
+./run-migration.sh --dry-run
+```
+
+#### Shell Script Options
+
+- `--help`: Show usage information
+- `--path PATH`: Specify xiaozhi-server directory path
+- `--batch-size SIZE`: Set batch size for database operations (default: 100)
+- `--dry-run`: Test run without actual database changes
+- `--verbose`: Enable detailed logging
+- `--check-only`: Only check prerequisites
+
+### Method 2: Using Maven
+
+```bash
+# Build the project
+mvn clean package -DskipTests
+
+# Run the migration
+mvn exec:java -Dexec.mainClass="xiaozhi.migration.MigrationRunner" -Dspring.profiles.active=migration
+```
+
+### Method 3: Using JAR File
+
+```bash
+# Build the JAR
+mvn clean package -DskipTests
+
+# Run the migration
+java -jar target/manager-api.jar --spring.profiles.active=migration
+```
+
+### Method 4: Using the Standalone Runner
+
+```bash
+java -cp target/manager-api.jar xiaozhi.migration.MigrationRunner --spring.profiles.active=migration
+```
+
+## Environment Variables
+
+You can customize the migration behavior using environment variables:
+
+| Variable | Description | Default |
+|----------|-------------|---------|
+| `XIAOZHI_SERVER_PATH` | Path to xiaozhi-server directory | `./xiaozhi-server` |
+| `MIGRATION_BATCH_SIZE` | Batch size for database operations | `100` |
+| `MIGRATION_BASE_PATH` | Alternative base path | Same as XIAOZHI_SERVER_PATH |
+| `JAVA_OPTS` | Additional JVM options | None |
+
+Example:
+```bash
+export XIAOZHI_SERVER_PATH="/opt/xiaozhi/xiaozhi-server"
+export MIGRATION_BATCH_SIZE="50"
+./run-migration.sh
+```
+
+## Configuration
+
+### Database Configuration
+
+The migration uses the same database configuration as the main application. Ensure your `application.yml` or `application-migration.yml` contains proper database connection settings.
+
+### Migration-Specific Configuration
+
+The `application-migration.yml` file contains migration-specific settings:
+
+```yaml
+migration:
+ content-library:
+ base-path: "${user.dir}/xiaozhi-server"
+ batch-size: 100
+ skip-if-exists: false
+ music:
+ supported-languages:
+ - English
+ - Hindi
+ - Kannada
+ - Phonics
+ - Telugu
+ stories:
+ supported-genres:
+ - Adventure
+ - Bedtime
+ - Educational
+ - "Fairy Tales"
+ - Fantasy
+```
+
+## Migration Process
+
+The migration script performs the following steps:
+
+1. **Verification**: Checks that the directory structure exists and is valid
+2. **Music Migration**:
+ - Scans each language directory in `music/`
+ - Parses `metadata.json` files
+ - Creates ContentLibraryDTO objects with `contentType="music"`
+ - Maps directory names to categories (language names)
+3. **Story Migration**:
+ - Scans each genre directory in `stories/`
+ - Parses `metadata.json` files
+ - Creates ContentLibraryDTO objects with `contentType="story"`
+ - Maps directory names to categories (genre names)
+4. **Batch Insert**: Inserts content in batches using `ContentLibraryService.batchInsertContent()`
+5. **Statistics**: Provides detailed migration statistics and error reporting
+
+## Data Mapping
+
+The migration maps JSON metadata to database fields as follows:
+
+| JSON Field | Database Field | Notes |
+|------------|----------------|--------|
+| Key (title) | `title` | The JSON object key becomes the title |
+| `romanized` | `romanized` | Romanized version of the title |
+| `filename` | `filename` | Original audio filename |
+| `alternatives` | `alternatives` | Converted to JSON string for database storage |
+| `aws_s3_url` | `aws_s3_url` | S3 URL for the audio file |
+| `duration_seconds` | `duration_seconds` | Duration in seconds |
+| `file_size_bytes` | `file_size_bytes` | File size in bytes |
+| Directory name | `category` | Language for music, Genre for stories |
+| Derived | `content_type` | "music" or "story" based on source directory |
+| Generated | `id` | UUID generated automatically |
+| Default | `is_active` | Set to 1 (active) by default |
+
+## Error Handling
+
+The migration script includes comprehensive error handling:
+
+- **File System Errors**: Missing directories or files are reported with clear error messages
+- **JSON Parse Errors**: Invalid JSON files are skipped with detailed error logs
+- **Database Errors**: Failed batch inserts are retried and errors are logged
+- **Data Validation**: Invalid or missing data is handled gracefully
+
+## Logging
+
+The migration provides detailed logging at multiple levels:
+
+- **INFO**: General progress information
+- **DEBUG**: Detailed processing information (with `--verbose` flag)
+- **WARN**: Non-fatal issues that don't stop migration
+- **ERROR**: Fatal errors that require attention
+
+Log files are saved to:
+- Console output (real-time)
+- `logs/content-migration.log` (persistent log file)
+
+## Monitoring Progress
+
+The migration provides real-time progress updates:
+
+```
+2025-08-29 10:15:30 [INFO] Starting Content Library Migration...
+2025-08-29 10:15:31 [INFO] Processing music language: English
+2025-08-29 10:15:32 [INFO] Batch 1/5 completed: 20 items inserted
+2025-08-29 10:15:33 [INFO] ================== MIGRATION SUMMARY ==================
+2025-08-29 10:15:33 [INFO] Total items processed: 487
+2025-08-29 10:15:33 [INFO] Total items inserted: 487
+2025-08-29 10:15:33 [INFO] Total failed items: 0
+```
+
+## Troubleshooting
+
+### Common Issues
+
+1. **Directory not found**
+ - Ensure xiaozhi-server directory exists and is accessible
+ - Check path configuration and environment variables
+
+2. **Database connection errors**
+ - Verify database is running and accessible
+ - Check database credentials in application configuration
+
+3. **Permission errors**
+ - Ensure the script has read permissions on JSON files
+ - Check write permissions for log directory
+
+4. **Memory issues with large datasets**
+ - Reduce batch size using `--batch-size` option
+ - Increase JVM heap size using `JAVA_OPTS` environment variable
+
+### Debug Mode
+
+Enable debug mode for detailed troubleshooting:
+
+```bash
+./run-migration.sh --verbose
+```
+
+Or set logging level:
+```bash
+export JAVA_OPTS="-Dlogging.level.xiaozhi.migration=DEBUG"
+./run-migration.sh
+```
+
+## Validation
+
+After migration, you can validate the results by:
+
+1. **Check database**: Query the `content_library` table to verify data
+2. **Review logs**: Check for any errors or warnings in the migration log
+3. **API testing**: Use the Content Library API endpoints to test functionality
+
+Example validation queries:
+
+```sql
+-- Check total counts
+SELECT content_type, category, COUNT(*) as count
+FROM content_library
+GROUP BY content_type, category;
+
+-- Check sample records
+SELECT * FROM content_library LIMIT 10;
+
+-- Check for any inactive records
+SELECT COUNT(*) FROM content_library WHERE is_active = 0;
+```
+
+## Performance Considerations
+
+- **Batch Size**: Default batch size is 100. Adjust based on your database performance
+- **Memory**: The migration loads all content into memory before batch insert
+- **Concurrent Access**: The migration should be run when the application is not heavily used
+- **Transaction Size**: Large batches are processed in separate transactions
+
+## Security Considerations
+
+- The migration script only reads from JSON files and writes to the database
+- No sensitive data is logged in plain text
+- Database credentials should be properly secured in configuration files
+- Consider running the migration in a maintenance window
+
+## Next Steps
+
+After successful migration:
+
+1. **Verify Data**: Check that all content is properly migrated and accessible
+2. **Update Documentation**: Update any API documentation with new content
+3. **Test Functionality**: Test search and retrieval functionality with migrated data
+4. **Monitor Performance**: Monitor database performance with the new content volume
+5. **Backup**: Create a backup of the migrated data
+
+## Support
+
+For issues or questions regarding the migration:
+
+1. Check the migration logs for detailed error information
+2. Review this documentation for common troubleshooting steps
+3. Verify the JSON file format matches the expected structure
+4. Test with a smaller subset of data first if experiencing issues
\ No newline at end of file
diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml
index 874a743a0..e2b2ef16d 100644
--- a/main/manager-api/pom.xml
+++ b/main/manager-api/pom.xml
@@ -264,6 +264,9 @@
org.springframework.boot
spring-boot-maven-plugin
+
+ xiaozhi.AdminApplication
+
org.apache.maven.plugins
diff --git a/main/manager-api/populate_content_library.sql b/main/manager-api/populate_content_library.sql
new file mode 100644
index 000000000..b00701476
--- /dev/null
+++ b/main/manager-api/populate_content_library.sql
@@ -0,0 +1,78 @@
+-- Content Library Data Population Script
+-- This script populates the content_library table with music and story metadata
+
+USE `vibrant-vitality`;
+
+-- Clear existing data (optional - comment out if you want to keep existing data)
+TRUNCATE TABLE content_library;
+
+-- English Music
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'Baa Baa Black Sheep', 'Baa Baa Black Sheep', 'Baa Baa Black Sheep.mp3', 'music', 'English', '["Baa Baa Black Sheep","baa baa black sheep","black sheep song","sheep song","nursery rhyme sheep","wool song","classic nursery rhyme","baa baa"]', 1),
+(UUID(), 'Baby Shark Dance', 'Baby Shark Dance', 'Baby Shark Dance.mp3', 'music', 'English', '["Baby Shark Dance","baby shark","shark song","doo doo doo","baby shark family","shark dance","kids shark song","popular kids song","viral kids song"]', 1),
+(UUID(), 'Five Little Animals', 'Five Little Animals', 'Five Little Animals.mp3', 'music', 'English', '["Five Little Animals","five animals","little animals","counting animals","animal counting song","5 little animals","animals song","counting song"]', 1),
+(UUID(), 'Five Little Ducks', 'Five Little Ducks', 'Five Little Ducks.mp3', 'music', 'English', '["Five Little Ducks","five ducks","little ducks","duck song","counting ducks","5 little ducks","ducks went swimming","mother duck song","quack quack song"]', 1),
+(UUID(), 'Once I Caught A Fish Alive', 'Once I Caught A Fish Alive', 'Once I Caught A Fish Alive.mp3', 'music', 'English', '["Once I Caught A Fish Alive","fish alive","caught a fish","fishing song","fish counting song","1 2 3 4 5 fish","counting fish","fish nursery rhyme"]', 1),
+(UUID(), 'Ten Little Dinos', 'Ten Little Dinos', 'Ten Little Dinos.mp3', 'music', 'English', '["Ten Little Dinos","ten dinos","little dinosaurs","dinosaur song","counting dinosaurs","10 little dinos","dino counting song","prehistoric song","kids dinosaur song"]', 1),
+(UUID(), 'The Wheels on the Bus', 'The Wheels on the Bus', 'The Wheels on the Bus.mp3', 'music', 'English', '["The Wheels on the Bus","wheels on the bus","bus song","wheels go round and round","children bus song","classic kids song","nursery rhyme bus","preschool bus song"]', 1);
+
+-- Hindi Music (sample entries)
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'चंदा मामा दूर के', 'Chanda Mama Door Ke', 'Chanda Mama Door Ke.mp3', 'music', 'Hindi', '["Chanda Mama Door Ke","चंदा मामा","moon song","hindi nursery rhyme"]', 1),
+(UUID(), 'मछली जल की रानी है', 'Machli Jal Ki Rani Hai', 'Machli Jal Ki Rani Hai.mp3', 'music', 'Hindi', '["Machli Jal Ki Rani Hai","मछली जल की रानी","fish song hindi","water queen fish"]', 1);
+
+-- Kannada Music (sample entries)
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'ಆನೆ ಬಂತು ಆನೆ', 'Aane Banthu Aane', 'Aane Banthu Aane.mp3', 'music', 'Kannada', '["Aane Banthu Aane","ಆನೆ ಬಂತು","elephant song kannada"]', 1),
+(UUID(), 'ಚಿಕ್ಕ ಚಿಕ್ಕ ಅಂಗಡಿ', 'Chikka Chikka Angadi', 'Chikka Chikka Angadi.mp3', 'music', 'Kannada', '["Chikka Chikka Angadi","ಚಿಕ್ಕ ಅಂಗಡಿ","small shop song"]', 1);
+
+-- Telugu Music (sample entries)
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'చందమామ రావే', 'Chandamama Raave', 'Chandamama Raave.mp3', 'music', 'Telugu', '["Chandamama Raave","చందమామ","moon uncle song telugu"]', 1),
+(UUID(), 'చిట్టి చిలకమ్మ', 'Chitti Chilakamma', 'Chitti Chilakamma.mp3', 'music', 'Telugu', '["Chitti Chilakamma","చిట్టి చిలకమ్మ","parrot song telugu"]', 1);
+
+-- Phonics Music (sample entries)
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'ABC Phonics Song', 'ABC Phonics Song', 'ABC Phonics Song.mp3', 'music', 'Phonics', '["ABC Phonics Song","alphabet song","phonics abc","letter sounds"]', 1),
+(UUID(), 'Letter A Song', 'Letter A Song', 'Letter A Song.mp3', 'music', 'Phonics', '["Letter A Song","a for apple","phonics a","letter a sounds"]', 1);
+
+-- Adventure Stories
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'a portrait of a cat', 'a portrait of a cat', 'a portrait of a cat.mp3', 'story', 'Adventure', '["portrait of cat","cat portrait","cat story"]', 1),
+(UUID(), 'a visit from st nicholas', 'a visit from st nicholas', 'a visit from st nicholas.mp3', 'story', 'Adventure', '["visit from st nicholas","st nicholas","christmas story"]', 1),
+(UUID(), 'agent bertie part (1)', 'agent bertie part (1)', 'agent bertie part (1).mp3', 'story', 'Adventure', '["agent bertie","bertie part 1","bertie adventure"]', 1),
+(UUID(), 'astropup and the revenge of the parrot', 'astropup and the revenge of the parrot', 'astropup and the revenge of the parrot.mp3', 'story', 'Adventure', '["astropup parrot revenge","astropup revenge","space dog parrot"]', 1),
+(UUID(), 'astropup and the ship of birds', 'astropup and the ship of birds', 'astropup and the ship of birds.mp3', 'story', 'Adventure', '["astropup ship birds","astropup birds","space dog birds"]', 1),
+(UUID(), 'astropup the hero', 'astropup the hero', 'astropup the hero.mp3', 'story', 'Adventure', '["astropup hero","hero story","space dog hero"]', 1);
+
+-- Bedtime Stories
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'bedtime meditation', 'bedtime meditation', 'bedtime meditation.mp3', 'story', 'Bedtime', '["meditation for sleep","sleep meditation","calm bedtime"]', 1),
+(UUID(), 'the sleepy train', 'the sleepy train', 'the sleepy train.mp3', 'story', 'Bedtime', '["sleepy train story","train to dreamland","bedtime train"]', 1),
+(UUID(), 'counting sheep', 'counting sheep', 'counting sheep.mp3', 'story', 'Bedtime', '["sheep counting","sleep counting","bedtime counting"]', 1);
+
+-- Educational Stories
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'learn about colors', 'learn about colors', 'learn about colors.mp3', 'story', 'Educational', '["colors lesson","learning colors","color education"]', 1),
+(UUID(), 'the water cycle', 'the water cycle', 'the water cycle.mp3', 'story', 'Educational', '["water cycle story","science story","rain cycle"]', 1),
+(UUID(), 'counting to ten', 'counting to ten', 'counting to ten.mp3', 'story', 'Educational', '["number story","counting lesson","math story"]', 1);
+
+-- Fairy Tales
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'cinderella', 'cinderella', 'cinderella.mp3', 'story', 'Fairy Tales', '["cinderella story","glass slipper","fairy godmother"]', 1),
+(UUID(), 'goldilocks and the three bears', 'goldilocks and the three bears', 'goldilocks and the three bears.mp3', 'story', 'Fairy Tales', '["goldilocks","three bears","porridge story"]', 1),
+(UUID(), 'little red riding hood', 'little red riding hood', 'little red riding hood.mp3', 'story', 'Fairy Tales', '["red riding hood","wolf story","grandmother story"]', 1);
+
+-- Fantasy Stories
+INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
+(UUID(), 'the magic forest', 'the magic forest', 'the magic forest.mp3', 'story', 'Fantasy', '["magical forest","enchanted woods","fantasy forest"]', 1),
+(UUID(), 'dragon and the princess', 'dragon and the princess', 'dragon and the princess.mp3', 'story', 'Fantasy', '["dragon story","princess tale","fantasy adventure"]', 1),
+(UUID(), 'the flying carpet', 'the flying carpet', 'the flying carpet.mp3', 'story', 'Fantasy', '["magic carpet","flying adventure","arabian fantasy"]', 1);
+
+-- Show summary
+SELECT content_type, category, COUNT(*) as count
+FROM content_library
+GROUP BY content_type, category
+ORDER BY content_type, category;
+
+SELECT COUNT(*) as total_content FROM content_library;
\ No newline at end of file
diff --git a/main/manager-api/run-content-migration.sh b/main/manager-api/run-content-migration.sh
new file mode 100755
index 000000000..b7953be60
--- /dev/null
+++ b/main/manager-api/run-content-migration.sh
@@ -0,0 +1,44 @@
+#!/bin/bash
+
+# Content Library Migration Runner Script
+# This script runs the ContentLibraryMigration to populate the database with music and stories
+
+echo "=========================================="
+echo "Content Library Migration Script"
+echo "=========================================="
+echo ""
+
+# Navigate to the project directory
+cd /Users/craftech360/Downloads/app/cheeko_server/main/manager-api
+
+# Check if the project has been built
+if [ ! -f "target/manager-api.jar" ]; then
+ echo "Building the project first..."
+ mvn clean package -DskipTests
+ if [ $? -ne 0 ]; then
+ echo "Build failed. Please check your Maven configuration."
+ exit 1
+ fi
+fi
+
+echo "Starting content library migration..."
+echo ""
+
+# Run the migration with the migration profile
+java -jar target/manager-api.jar \
+ --spring.profiles.active=migration,dev \
+ --spring.main.web-application-type=none \
+ --spring.main.banner-mode=off
+
+if [ $? -eq 0 ]; then
+ echo ""
+ echo "=========================================="
+ echo "Migration completed successfully!"
+ echo "=========================================="
+else
+ echo ""
+ echo "=========================================="
+ echo "Migration failed. Check the logs above."
+ echo "=========================================="
+ exit 1
+fi
\ No newline at end of file
diff --git a/main/manager-api/run-migration.sh b/main/manager-api/run-migration.sh
new file mode 100755
index 000000000..21b5554a2
--- /dev/null
+++ b/main/manager-api/run-migration.sh
@@ -0,0 +1,343 @@
+#!/bin/bash
+
+# XiaoZhi Content Library Migration Script
+# This script provides an easy way to run the content library migration
+# with proper environment setup and error handling.
+
+set -e # Exit on any error
+
+# Script configuration
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
+JAR_NAME="manager-api.jar"
+MAIN_CLASS="xiaozhi.migration.MigrationRunner"
+LOG_FILE="logs/content-migration.log"
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+# Function to print colored output
+print_info() {
+ echo -e "${BLUE}[INFO]${NC} $1"
+}
+
+print_success() {
+ echo -e "${GREEN}[SUCCESS]${NC} $1"
+}
+
+print_warning() {
+ echo -e "${YELLOW}[WARNING]${NC} $1"
+}
+
+print_error() {
+ echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Function to print usage
+print_usage() {
+ cat << EOF
+Usage: $0 [OPTIONS]
+
+XiaoZhi Content Library Migration Script
+
+OPTIONS:
+ -h, --help Show this help message
+ -p, --path PATH Specify xiaozhi-server directory path (default: auto-detect)
+ -b, --batch-size SIZE Batch size for database operations (default: 100)
+ -d, --dry-run Perform a dry run without actual database changes
+ -v, --verbose Enable verbose logging
+ -c, --check-only Only check prerequisites without running migration
+
+EXAMPLES:
+ $0 # Run with default settings
+ $0 --path /path/to/xiaozhi-server # Specify custom path
+ $0 --batch-size 50 --verbose # Custom batch size with verbose logging
+ $0 --check-only # Check prerequisites only
+ $0 --dry-run # Test run without database changes
+
+ENVIRONMENT VARIABLES:
+ XIAOZHI_SERVER_PATH Override xiaozhi-server directory path
+ MIGRATION_BATCH_SIZE Override batch size for migration
+ JAVA_OPTS Additional JVM options
+EOF
+}
+
+# Function to check prerequisites
+check_prerequisites() {
+ print_info "Checking prerequisites..."
+
+ # Check if Java is available
+ if ! command -v java &> /dev/null; then
+ print_error "Java is not installed or not in PATH"
+ return 1
+ fi
+
+ local java_version=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
+ print_info "Java version: $java_version"
+
+ # Check if Maven is available (for building if needed)
+ if ! command -v mvn &> /dev/null; then
+ print_warning "Maven is not available - assuming JAR is pre-built"
+ fi
+
+ # Check if JAR file exists or can be built
+ if [[ -f "target/$JAR_NAME" ]]; then
+ print_info "Found JAR file: target/$JAR_NAME"
+ elif [[ -f "$JAR_NAME" ]]; then
+ print_info "Found JAR file: $JAR_NAME"
+ else
+ print_info "JAR file not found - attempting to build..."
+ if command -v mvn &> /dev/null; then
+ mvn clean package -DskipTests
+ if [[ $? -ne 0 ]]; then
+ print_error "Failed to build JAR file"
+ return 1
+ fi
+ else
+ print_error "JAR file not found and Maven not available for building"
+ return 1
+ fi
+ fi
+
+ return 0
+}
+
+# Function to find xiaozhi-server path
+find_xiaozhi_server_path() {
+ local custom_path="$1"
+
+ # Use custom path if provided
+ if [[ -n "$custom_path" ]]; then
+ if [[ -d "$custom_path" ]]; then
+ echo "$custom_path"
+ return 0
+ else
+ print_error "Specified path does not exist: $custom_path"
+ return 1
+ fi
+ fi
+
+ # Check environment variable
+ if [[ -n "$XIAOZHI_SERVER_PATH" ]]; then
+ if [[ -d "$XIAOZHI_SERVER_PATH" ]]; then
+ echo "$XIAOZHI_SERVER_PATH"
+ return 0
+ else
+ print_warning "Environment XIAOZHI_SERVER_PATH is set but directory does not exist: $XIAOZHI_SERVER_PATH"
+ fi
+ fi
+
+ # Auto-detect possible paths
+ local possible_paths=(
+ "./xiaozhi-server"
+ "../xiaozhi-server"
+ "../../xiaozhi-server"
+ "/opt/xiaozhi/xiaozhi-server"
+ "/home/$(whoami)/xiaozhi-server"
+ )
+
+ for path in "${possible_paths[@]}"; do
+ if [[ -d "$path" ]]; then
+ echo "$(realpath "$path")"
+ return 0
+ fi
+ done
+
+ print_error "Could not find xiaozhi-server directory"
+ print_info "Please specify the path using --path option or set XIAOZHI_SERVER_PATH environment variable"
+ return 1
+}
+
+# Function to validate xiaozhi-server structure
+validate_xiaozhi_structure() {
+ local path="$1"
+
+ print_info "Validating xiaozhi-server structure at: $path"
+
+ # Check music directory
+ if [[ ! -d "$path/music" ]]; then
+ print_error "Music directory not found: $path/music"
+ return 1
+ fi
+
+ # Check stories directory
+ if [[ ! -d "$path/stories" ]]; then
+ print_error "Stories directory not found: $path/stories"
+ return 1
+ fi
+
+ # Check for metadata files
+ local music_count=0
+ local story_count=0
+
+ for lang_dir in "$path/music"/*; do
+ if [[ -d "$lang_dir" && -f "$lang_dir/metadata.json" ]]; then
+ ((music_count++))
+ print_info "Found music metadata: $(basename "$lang_dir")"
+ fi
+ done
+
+ for genre_dir in "$path/stories"/*; do
+ if [[ -d "$genre_dir" && -f "$genre_dir/metadata.json" ]]; then
+ ((story_count++))
+ print_info "Found story metadata: $(basename "$genre_dir")"
+ fi
+ done
+
+ if [[ $music_count -eq 0 && $story_count -eq 0 ]]; then
+ print_error "No metadata files found in music or stories directories"
+ return 1
+ fi
+
+ print_success "Found $music_count music categories and $story_count story genres"
+ return 0
+}
+
+# Function to run migration
+run_migration() {
+ local xiaozhi_path="$1"
+ local batch_size="${2:-100}"
+ local dry_run="${3:-false}"
+ local verbose="${4:-false}"
+
+ print_info "Starting Content Library Migration..."
+ print_info "XiaoZhi Server Path: $xiaozhi_path"
+ print_info "Batch Size: $batch_size"
+
+ # Prepare JVM options
+ local jvm_opts="-Xmx2g -Dspring.profiles.active=migration"
+
+ if [[ "$verbose" == "true" ]]; then
+ jvm_opts="$jvm_opts -Dlogging.level.xiaozhi.migration=DEBUG"
+ fi
+
+ # Add custom JAVA_OPTS if set
+ if [[ -n "$JAVA_OPTS" ]]; then
+ jvm_opts="$jvm_opts $JAVA_OPTS"
+ fi
+
+ # Set environment variables
+ export MIGRATION_BASE_PATH="$xiaozhi_path"
+ export MIGRATION_BATCH_SIZE="$batch_size"
+
+ if [[ "$dry_run" == "true" ]]; then
+ export MIGRATION_DRY_RUN="true"
+ print_warning "Running in DRY RUN mode - no database changes will be made"
+ fi
+
+ # Create logs directory
+ mkdir -p logs
+
+ # Find JAR file
+ local jar_file=""
+ if [[ -f "target/$JAR_NAME" ]]; then
+ jar_file="target/$JAR_NAME"
+ elif [[ -f "$JAR_NAME" ]]; then
+ jar_file="$JAR_NAME"
+ else
+ print_error "JAR file not found"
+ return 1
+ fi
+
+ # Run migration
+ print_info "Executing migration..."
+
+ if java $jvm_opts -jar "$jar_file" 2>&1 | tee "$LOG_FILE"; then
+ print_success "Migration completed successfully!"
+ print_info "Migration log saved to: $LOG_FILE"
+
+ # Show summary from log
+ if [[ -f "$LOG_FILE" ]]; then
+ print_info "Migration Summary:"
+ grep -A 20 "MIGRATION SUMMARY" "$LOG_FILE" | tail -20 || true
+ fi
+
+ return 0
+ else
+ print_error "Migration failed! Check log file: $LOG_FILE"
+ return 1
+ fi
+}
+
+# Main script
+main() {
+ local xiaozhi_path=""
+ local batch_size="100"
+ local dry_run="false"
+ local verbose="false"
+ local check_only="false"
+
+ # Parse command line arguments
+ while [[ $# -gt 0 ]]; do
+ case $1 in
+ -h|--help)
+ print_usage
+ exit 0
+ ;;
+ -p|--path)
+ xiaozhi_path="$2"
+ shift 2
+ ;;
+ -b|--batch-size)
+ batch_size="$2"
+ shift 2
+ ;;
+ -d|--dry-run)
+ dry_run="true"
+ shift
+ ;;
+ -v|--verbose)
+ verbose="true"
+ shift
+ ;;
+ -c|--check-only)
+ check_only="true"
+ shift
+ ;;
+ *)
+ print_error "Unknown option: $1"
+ print_usage
+ exit 1
+ ;;
+ esac
+ done
+
+ print_info "XiaoZhi Content Library Migration"
+ print_info "=================================="
+
+ # Check prerequisites
+ if ! check_prerequisites; then
+ exit 1
+ fi
+
+ # Find xiaozhi-server path
+ if ! xiaozhi_path=$(find_xiaozhi_server_path "$xiaozhi_path"); then
+ exit 1
+ fi
+
+ # Validate structure
+ if ! validate_xiaozhi_structure "$xiaozhi_path"; then
+ exit 1
+ fi
+
+ # Exit if check-only mode
+ if [[ "$check_only" == "true" ]]; then
+ print_success "Prerequisites check completed successfully!"
+ exit 0
+ fi
+
+ # Run migration
+ if run_migration "$xiaozhi_path" "$batch_size" "$dry_run" "$verbose"; then
+ print_success "Migration script completed successfully!"
+ exit 0
+ else
+ print_error "Migration script failed!"
+ exit 1
+ fi
+}
+
+# Run main function
+main "$@"
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java b/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java
new file mode 100644
index 000000000..3c1c3a23b
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/migration/ContentLibraryMigration.java
@@ -0,0 +1,505 @@
+package xiaozhi.migration;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import com.google.gson.*;
+import com.google.gson.reflect.TypeToken;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.stereotype.Component;
+
+import xiaozhi.modules.content.dto.ContentLibraryDTO;
+import xiaozhi.modules.content.entity.ContentLibraryEntity;
+import xiaozhi.modules.content.service.ContentLibraryService;
+
+/**
+ * Data Migration Script for Content Library
+ *
+ * This script migrates content metadata from JSON files in the xiaozhi-server directory
+ * to the content_library database table.
+ *
+ * Usage: Run as a Spring Boot application with migration profile
+ * java -jar app.jar --spring.profiles.active=migration
+ *
+ * Directory Structure:
+ * - xiaozhi-server/music/[Language]/metadata.json (English, Hindi, Kannada, Phonics, Telugu)
+ * - xiaozhi-server/stories/[Genre]/metadata.json (Adventure, Bedtime, Educational, Fairy Tales, Fantasy)
+ *
+ * @author Data Migration Script Generator
+ * @version 1.0
+ */
+@Slf4j
+@Component
+public class ContentLibraryMigration implements CommandLineRunner {
+
+ @Autowired
+ private ContentLibraryService contentLibraryService;
+
+ private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ // Base path configuration - adjust as needed based on deployment structure
+ private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
+ private static final String MUSIC_PATH = BASE_PATH + "/music";
+ private static final String STORIES_PATH = BASE_PATH + "/stories";
+
+ // Batch size for database operations
+ private static final int BATCH_SIZE = 100;
+
+ // Migration statistics
+ private final MigrationStatistics stats = new MigrationStatistics();
+
+ @Override
+ public void run(String... args) throws Exception {
+ // Check if migration profile is active
+ String profiles = System.getProperty("spring.profiles.active", "");
+ if (!profiles.contains("migration")) {
+ log.info("Migration profile not active, skipping content library migration");
+ return;
+ }
+
+ log.info("Starting Content Library Migration...");
+ log.info("Base path: {}", BASE_PATH);
+
+ try {
+ // Verify directory structure
+ verifyDirectoryStructure();
+
+ // Migrate music content
+ migrateMusicContent();
+
+ // Migrate story content
+ migrateStoryContent();
+
+ // Print migration summary
+ printMigrationSummary();
+
+ } catch (Exception e) {
+ log.error("Migration failed: {}", e.getMessage(), e);
+ throw new RuntimeException("Content library migration failed", e);
+ }
+ }
+
+ /**
+ * Verify that the required directory structure exists
+ */
+ private void verifyDirectoryStructure() {
+ log.info("Verifying directory structure...");
+
+ File baseDir = new File(BASE_PATH);
+ if (!baseDir.exists()) {
+ throw new RuntimeException("Base directory does not exist: " + BASE_PATH);
+ }
+
+ File musicDir = new File(MUSIC_PATH);
+ if (!musicDir.exists()) {
+ throw new RuntimeException("Music directory does not exist: " + MUSIC_PATH);
+ }
+
+ File storiesDir = new File(STORIES_PATH);
+ if (!storiesDir.exists()) {
+ throw new RuntimeException("Stories directory does not exist: " + STORIES_PATH);
+ }
+
+ log.info("Directory structure verified successfully");
+ }
+
+ /**
+ * Migrate music content from JSON metadata files
+ */
+ private void migrateMusicContent() {
+ log.info("Starting music content migration...");
+
+ File musicDir = new File(MUSIC_PATH);
+ File[] languageDirectories = musicDir.listFiles(File::isDirectory);
+
+ if (languageDirectories == null || languageDirectories.length == 0) {
+ log.warn("No music language directories found in: {}", MUSIC_PATH);
+ return;
+ }
+
+ List allMusicContent = new ArrayList<>();
+
+ for (File languageDir : languageDirectories) {
+ String language = languageDir.getName();
+ log.info("Processing music language: {}", language);
+
+ try {
+ List languageContent = processMusicLanguage(language, languageDir);
+ allMusicContent.addAll(languageContent);
+ stats.addProcessedLanguage(language, languageContent.size());
+
+ } catch (Exception e) {
+ log.error("Failed to process music language {}: {}", language, e.getMessage(), e);
+ stats.addFailedLanguage(language, e.getMessage());
+ }
+ }
+
+ // Batch insert music content
+ if (!allMusicContent.isEmpty()) {
+ batchInsertContent(allMusicContent, "music");
+ }
+
+ log.info("Completed music content migration. Processed {} items", allMusicContent.size());
+ }
+
+ /**
+ * Process music content for a specific language
+ */
+ private List processMusicLanguage(String language, File languageDir) throws IOException {
+ File metadataFile = new File(languageDir, "metadata.json");
+ if (!metadataFile.exists()) {
+ log.warn("No metadata.json found for language: {}", language);
+ return new ArrayList<>();
+ }
+
+ String jsonContent = Files.readString(metadataFile.toPath());
+
+ // Parse JSON content
+ JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
+ List contentList = new ArrayList<>();
+
+ for (Map.Entry entry : jsonObject.entrySet()) {
+ String title = entry.getKey();
+ JsonObject contentInfo = entry.getValue().getAsJsonObject();
+
+ try {
+ ContentLibraryDTO dto = createMusicContentDTO(title, contentInfo, language);
+ contentList.add(dto);
+
+ } catch (Exception e) {
+ log.error("Failed to process music item '{}' in language {}: {}", title, language, e.getMessage());
+ stats.addFailedItem(title, e.getMessage());
+ }
+ }
+
+ return contentList;
+ }
+
+ /**
+ * Create ContentLibraryDTO for music content
+ */
+ private ContentLibraryDTO createMusicContentDTO(String title, JsonObject contentInfo, String language) {
+ ContentLibraryDTO dto = new ContentLibraryDTO();
+
+ // Basic information
+ dto.setTitle(title);
+ dto.setRomanized(getJsonString(contentInfo, "romanized"));
+ dto.setFilename(getJsonString(contentInfo, "filename"));
+ dto.setContentType(ContentLibraryEntity.ContentType.MUSIC.getValue());
+ dto.setCategory(language);
+
+ // Parse alternatives array
+ JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
+ if (alternativesArray != null) {
+ List alternatives = new ArrayList<>();
+ for (JsonElement element : alternativesArray) {
+ alternatives.add(element.getAsString());
+ }
+ dto.setAlternatives(alternatives);
+ } else {
+ dto.setAlternatives(new ArrayList<>());
+ }
+
+ // Additional metadata (these might be null for now, can be populated later)
+ dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
+ dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
+ dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
+
+ // Set as active
+ dto.setIsActive(true);
+
+ return dto;
+ }
+
+ /**
+ * Migrate story content from JSON metadata files
+ */
+ private void migrateStoryContent() {
+ log.info("Starting story content migration...");
+
+ File storiesDir = new File(STORIES_PATH);
+ File[] genreDirectories = storiesDir.listFiles(File::isDirectory);
+
+ if (genreDirectories == null || genreDirectories.length == 0) {
+ log.warn("No story genre directories found in: {}", STORIES_PATH);
+ return;
+ }
+
+ List allStoryContent = new ArrayList<>();
+
+ for (File genreDir : genreDirectories) {
+ String genre = genreDir.getName();
+ log.info("Processing story genre: {}", genre);
+
+ try {
+ List genreContent = processStoryGenre(genre, genreDir);
+ allStoryContent.addAll(genreContent);
+ stats.addProcessedGenre(genre, genreContent.size());
+
+ } catch (Exception e) {
+ log.error("Failed to process story genre {}: {}", genre, e.getMessage(), e);
+ stats.addFailedGenre(genre, e.getMessage());
+ }
+ }
+
+ // Batch insert story content
+ if (!allStoryContent.isEmpty()) {
+ batchInsertContent(allStoryContent, "stories");
+ }
+
+ log.info("Completed story content migration. Processed {} items", allStoryContent.size());
+ }
+
+ /**
+ * Process story content for a specific genre
+ */
+ private List processStoryGenre(String genre, File genreDir) throws IOException {
+ File metadataFile = new File(genreDir, "metadata.json");
+ if (!metadataFile.exists()) {
+ log.warn("No metadata.json found for genre: {}", genre);
+ return new ArrayList<>();
+ }
+
+ String jsonContent = Files.readString(metadataFile.toPath());
+
+ // Parse JSON content
+ JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
+ List contentList = new ArrayList<>();
+
+ for (Map.Entry entry : jsonObject.entrySet()) {
+ String title = entry.getKey();
+ JsonObject contentInfo = entry.getValue().getAsJsonObject();
+
+ try {
+ ContentLibraryDTO dto = createStoryContentDTO(title, contentInfo, genre);
+ contentList.add(dto);
+
+ } catch (Exception e) {
+ log.error("Failed to process story item '{}' in genre {}: {}", title, genre, e.getMessage());
+ stats.addFailedItem(title, e.getMessage());
+ }
+ }
+
+ return contentList;
+ }
+
+ /**
+ * Create ContentLibraryDTO for story content
+ */
+ private ContentLibraryDTO createStoryContentDTO(String title, JsonObject contentInfo, String genre) {
+ ContentLibraryDTO dto = new ContentLibraryDTO();
+
+ // Basic information
+ dto.setTitle(title);
+ dto.setRomanized(getJsonString(contentInfo, "romanized"));
+ dto.setFilename(getJsonString(contentInfo, "filename"));
+ dto.setContentType(ContentLibraryEntity.ContentType.STORY.getValue());
+ dto.setCategory(genre);
+
+ // Parse alternatives array
+ JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
+ if (alternativesArray != null) {
+ List alternatives = new ArrayList<>();
+ for (JsonElement element : alternativesArray) {
+ alternatives.add(element.getAsString());
+ }
+ dto.setAlternatives(alternatives);
+ } else {
+ dto.setAlternatives(new ArrayList<>());
+ }
+
+ // Additional metadata (these might be null for now, can be populated later)
+ dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
+ dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
+ dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
+
+ // Set as active
+ dto.setIsActive(true);
+
+ return dto;
+ }
+
+ /**
+ * Batch insert content into database
+ */
+ private void batchInsertContent(List contentList, String contentType) {
+ log.info("Starting batch insert for {} {} items", contentList.size(), contentType);
+
+ // Process in batches to avoid memory issues and improve performance
+ List> batches = partition(contentList, BATCH_SIZE);
+
+ int totalInserted = 0;
+ for (int i = 0; i < batches.size(); i++) {
+ List batch = batches.get(i);
+
+ try {
+ int inserted = contentLibraryService.batchInsertContent(batch);
+ totalInserted += inserted;
+
+ log.info("Batch {}/{} completed: {} items inserted", i + 1, batches.size(), inserted);
+ stats.addInsertedCount(inserted);
+
+ if (inserted != batch.size()) {
+ log.warn("Batch insert incomplete: expected {}, inserted {}", batch.size(), inserted);
+ }
+
+ } catch (Exception e) {
+ log.error("Failed to insert batch {}/{}: {}", i + 1, batches.size(), e.getMessage(), e);
+ stats.addFailedBatch(i + 1, e.getMessage());
+ }
+ }
+
+ log.info("Batch insert completed for {}: {} total items inserted", contentType, totalInserted);
+ }
+
+ /**
+ * Print migration summary
+ */
+ private void printMigrationSummary() {
+ log.info("================== MIGRATION SUMMARY ==================");
+ log.info("Total items processed: {}", stats.getTotalProcessed());
+ log.info("Total items inserted: {}", stats.getTotalInserted());
+ log.info("Total failed items: {}", stats.getTotalFailed());
+ log.info("");
+
+ log.info("MUSIC CONTENT:");
+ for (String language : stats.getProcessedLanguages().keySet()) {
+ log.info(" - {}: {} items", language, stats.getProcessedLanguages().get(language));
+ }
+
+ log.info("STORY CONTENT:");
+ for (String genre : stats.getProcessedGenres().keySet()) {
+ log.info(" - {}: {} items", genre, stats.getProcessedGenres().get(genre));
+ }
+
+ if (!stats.getFailedLanguages().isEmpty()) {
+ log.error("FAILED LANGUAGES:");
+ stats.getFailedLanguages().forEach((lang, error) ->
+ log.error(" - {}: {}", lang, error));
+ }
+
+ if (!stats.getFailedGenres().isEmpty()) {
+ log.error("FAILED GENRES:");
+ stats.getFailedGenres().forEach((genre, error) ->
+ log.error(" - {}: {}", genre, error));
+ }
+
+ if (!stats.getFailedItems().isEmpty()) {
+ log.error("FAILED ITEMS (showing first 10):");
+ stats.getFailedItems().entrySet().stream()
+ .limit(10)
+ .forEach(entry -> log.error(" - {}: {}", entry.getKey(), entry.getValue()));
+ }
+
+ if (!stats.getFailedBatches().isEmpty()) {
+ log.error("FAILED BATCHES:");
+ stats.getFailedBatches().forEach((batch, error) ->
+ log.error(" - Batch {}: {}", batch, error));
+ }
+
+ log.info("======================================================");
+ }
+
+ // Helper methods
+
+ /**
+ * Safely get string value from JSON object
+ */
+ private String getJsonString(JsonObject jsonObject, String key) {
+ JsonElement element = jsonObject.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
+ }
+
+ /**
+ * Safely get integer value from JSON object
+ */
+ private Integer getJsonInteger(JsonObject jsonObject, String key) {
+ JsonElement element = jsonObject.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
+ }
+
+ /**
+ * Safely get long value from JSON object
+ */
+ private Long getJsonLong(JsonObject jsonObject, String key) {
+ JsonElement element = jsonObject.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
+ }
+
+ /**
+ * Partition list into smaller batches
+ */
+ private List> partition(List list, int size) {
+ List> partitions = new ArrayList<>();
+ for (int i = 0; i < list.size(); i += size) {
+ partitions.add(list.subList(i, Math.min(i + size, list.size())));
+ }
+ return partitions;
+ }
+
+ /**
+ * Migration statistics tracker
+ */
+ private static class MigrationStatistics {
+ private final Map processedLanguages = new HashMap<>();
+ private final Map processedGenres = new HashMap<>();
+ private final Map failedLanguages = new HashMap<>();
+ private final Map failedGenres = new HashMap<>();
+ private final Map failedItems = new HashMap<>();
+ private final Map failedBatches = new HashMap<>();
+ private int totalInserted = 0;
+
+ public void addProcessedLanguage(String language, int count) {
+ processedLanguages.put(language, count);
+ }
+
+ public void addProcessedGenre(String genre, int count) {
+ processedGenres.put(genre, count);
+ }
+
+ public void addFailedLanguage(String language, String error) {
+ failedLanguages.put(language, error);
+ }
+
+ public void addFailedGenre(String genre, String error) {
+ failedGenres.put(genre, error);
+ }
+
+ public void addFailedItem(String item, String error) {
+ failedItems.put(item, error);
+ }
+
+ public void addFailedBatch(int batchNumber, String error) {
+ failedBatches.put(batchNumber, error);
+ }
+
+ public void addInsertedCount(int count) {
+ totalInserted += count;
+ }
+
+ public int getTotalProcessed() {
+ return processedLanguages.values().stream().mapToInt(Integer::intValue).sum() +
+ processedGenres.values().stream().mapToInt(Integer::intValue).sum();
+ }
+
+ public int getTotalFailed() {
+ return failedItems.size();
+ }
+
+ // Getters
+ public Map getProcessedLanguages() { return processedLanguages; }
+ public Map getProcessedGenres() { return processedGenres; }
+ public Map getFailedLanguages() { return failedLanguages; }
+ public Map getFailedGenres() { return failedGenres; }
+ public Map getFailedItems() { return failedItems; }
+ public Map getFailedBatches() { return failedBatches; }
+ public int getTotalInserted() { return totalInserted; }
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java
new file mode 100644
index 000000000..ea5ce572c
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/migration/MigrationConfiguration.java
@@ -0,0 +1,197 @@
+package xiaozhi.migration;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+
+import jakarta.annotation.PostConstruct;
+import java.io.File;
+import java.util.List;
+
+/**
+ * Configuration class for Content Library Migration
+ *
+ * This class manages all migration-specific configuration properties
+ * and provides validation for paths and settings.
+ *
+ * @author Data Migration Configuration
+ * @version 1.0
+ */
+@Data
+@Configuration
+@Profile("migration")
+@ConfigurationProperties(prefix = "migration.content-library")
+public class MigrationConfiguration {
+
+ /**
+ * Base path for xiaozhi-server directory
+ */
+ private String basePath = System.getProperty("user.dir") + "/xiaozhi-server";
+
+ /**
+ * Batch size for database operations
+ */
+ private int batchSize = 100;
+
+ /**
+ * Whether to skip migration if content already exists
+ */
+ private boolean skipIfExists = false;
+
+ /**
+ * Connection timeout in milliseconds
+ */
+ private int connectionTimeout = 30000;
+
+ /**
+ * Read timeout in milliseconds
+ */
+ private int readTimeout = 60000;
+
+ /**
+ * Music directory path
+ */
+ private String musicPath;
+
+ /**
+ * Stories directory path
+ */
+ private String storiesPath;
+
+ /**
+ * Music configuration
+ */
+ private MusicConfig music = new MusicConfig();
+
+ /**
+ * Stories configuration
+ */
+ private StoriesConfig stories = new StoriesConfig();
+
+ @PostConstruct
+ public void init() {
+ // Override with environment variables if present
+ String envBasePath = System.getenv("MIGRATION_BASE_PATH");
+ if (envBasePath != null && !envBasePath.trim().isEmpty()) {
+ this.basePath = envBasePath;
+ }
+
+ String envBatchSize = System.getenv("MIGRATION_BATCH_SIZE");
+ if (envBatchSize != null && !envBatchSize.trim().isEmpty()) {
+ try {
+ this.batchSize = Integer.parseInt(envBatchSize);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("Invalid MIGRATION_BATCH_SIZE value: " + envBatchSize);
+ }
+ }
+
+ // Set derived paths if not already set
+ if (musicPath == null) {
+ musicPath = basePath + "/music";
+ }
+
+ if (storiesPath == null) {
+ storiesPath = basePath + "/stories";
+ }
+
+ // Validate configuration
+ validateConfiguration();
+ }
+
+ /**
+ * Validate migration configuration
+ */
+ private void validateConfiguration() {
+ validatePath(basePath, "Base path");
+ validatePath(musicPath, "Music path");
+ validatePath(storiesPath, "Stories path");
+
+ if (batchSize <= 0 || batchSize > 1000) {
+ throw new IllegalArgumentException("Batch size must be between 1 and 1000, got: " + batchSize);
+ }
+
+ if (connectionTimeout <= 0) {
+ throw new IllegalArgumentException("Connection timeout must be positive, got: " + connectionTimeout);
+ }
+
+ if (readTimeout <= 0) {
+ throw new IllegalArgumentException("Read timeout must be positive, got: " + readTimeout);
+ }
+ }
+
+ /**
+ * Validate that a path exists
+ */
+ private void validatePath(String path, String description) {
+ if (path == null || path.trim().isEmpty()) {
+ throw new IllegalArgumentException(description + " cannot be empty");
+ }
+
+ File file = new File(path);
+ if (!file.exists()) {
+ throw new IllegalArgumentException(description + " does not exist: " + path);
+ }
+
+ if (!file.isDirectory()) {
+ throw new IllegalArgumentException(description + " is not a directory: " + path);
+ }
+ }
+
+ /**
+ * Get absolute path for music directory
+ */
+ public String getAbsoluteMusicPath() {
+ return new File(musicPath).getAbsolutePath();
+ }
+
+ /**
+ * Get absolute path for stories directory
+ */
+ public String getAbsoluteStoriesPath() {
+ return new File(storiesPath).getAbsolutePath();
+ }
+
+ /**
+ * Get absolute base path
+ */
+ public String getAbsoluteBasePath() {
+ return new File(basePath).getAbsolutePath();
+ }
+
+ /**
+ * Music content configuration
+ */
+ @Data
+ public static class MusicConfig {
+ private String contentType = "music";
+ private List supportedLanguages = List.of(
+ "English", "Hindi", "Kannada", "Phonics", "Telugu"
+ );
+ }
+
+ /**
+ * Stories content configuration
+ */
+ @Data
+ public static class StoriesConfig {
+ private String contentType = "story";
+ private List supportedGenres = List.of(
+ "Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"
+ );
+ }
+
+ /**
+ * Check if a language is supported for music content
+ */
+ public boolean isSupportedMusicLanguage(String language) {
+ return music.getSupportedLanguages().contains(language);
+ }
+
+ /**
+ * Check if a genre is supported for story content
+ */
+ public boolean isSupportedStoryGenre(String genre) {
+ return stories.getSupportedGenres().contains(genre);
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java
new file mode 100644
index 000000000..260837fb7
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/migration/MigrationRunner.java
@@ -0,0 +1,110 @@
+package xiaozhi.migration;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.ComponentScan;
+
+/**
+ * Standalone Migration Runner
+ *
+ * This class provides a standalone entry point for running the content library migration
+ * without starting the full application.
+ *
+ * Usage:
+ * 1. Command line: mvn exec:java -Dexec.mainClass="xiaozhi.migration.MigrationRunner" -Dspring.profiles.active=migration
+ * 2. IDE: Run this class directly with VM options: -Dspring.profiles.active=migration
+ * 3. JAR: java -cp app.jar xiaozhi.migration.MigrationRunner --spring.profiles.active=migration
+ *
+ * Environment Variables:
+ * - XIAOZHI_SERVER_PATH: Override the default xiaozhi-server path
+ * - MIGRATION_BATCH_SIZE: Override the default batch size (default: 100)
+ * - MIGRATION_BASE_PATH: Override the base path for migration files
+ *
+ * The migration process will:
+ * 1. Scan xiaozhi-server/music/[language]/metadata.json files
+ * 2. Scan xiaozhi-server/stories/[genre]/metadata.json files
+ * 3. Parse JSON content and create ContentLibraryDTO objects
+ * 4. Batch insert content into the content_library table
+ * 5. Provide detailed logging and statistics
+ *
+ * @author Data Migration Script Generator
+ * @version 1.0
+ */
+@Slf4j
+@SpringBootApplication
+@ComponentScan(basePackages = {
+ "xiaozhi.migration", // Migration components
+ "xiaozhi.modules.content", // Content service components
+ "xiaozhi.common", // Common utilities
+ "xiaozhi.config" // Configuration classes
+})
+public class MigrationRunner {
+
+ public static void main(String[] args) {
+ log.info("=======================================================");
+ log.info("XiaoZhi Content Library Migration Runner");
+ log.info("=======================================================");
+
+ // Set migration profile if not already set
+ String profiles = System.getProperty("spring.profiles.active");
+ if (profiles == null || !profiles.contains("migration")) {
+ System.setProperty("spring.profiles.active", "migration");
+ log.info("Setting spring profile to 'migration'");
+ }
+
+ // Log environment configuration
+ logEnvironmentInfo();
+
+ try {
+ // Create Spring context and run migration
+ SpringApplication app = new SpringApplication(MigrationRunner.class);
+
+ // Disable web environment for migration
+ app.setWebApplicationType(org.springframework.boot.WebApplicationType.NONE);
+
+ // Disable banner for cleaner output
+ app.setBannerMode(org.springframework.boot.Banner.Mode.OFF);
+
+ // Run the application
+ var context = app.run(args);
+
+ log.info("Migration completed successfully!");
+ log.info("Application context will be closed automatically");
+
+ // Gracefully shutdown
+ SpringApplication.exit(context, () -> 0);
+
+ } catch (Exception e) {
+ log.error("Migration failed with error: {}", e.getMessage(), e);
+ System.exit(1);
+ }
+ }
+
+ /**
+ * Log environment configuration for debugging
+ */
+ private static void logEnvironmentInfo() {
+ log.info("Environment Configuration:");
+ log.info(" - Java Version: {}", System.getProperty("java.version"));
+ log.info(" - Working Directory: {}", System.getProperty("user.dir"));
+ log.info(" - Spring Profiles: {}", System.getProperty("spring.profiles.active", "default"));
+
+ String xiaozhiPath = System.getenv("XIAOZHI_SERVER_PATH");
+ if (xiaozhiPath != null) {
+ log.info(" - XiaoZhi Server Path (env): {}", xiaozhiPath);
+ }
+
+ String batchSize = System.getenv("MIGRATION_BATCH_SIZE");
+ if (batchSize != null) {
+ log.info(" - Batch Size (env): {}", batchSize);
+ }
+
+ String basePath = System.getenv("MIGRATION_BASE_PATH");
+ if (basePath != null) {
+ log.info(" - Base Path (env): {}", basePath);
+ }
+
+ log.info("=======================================================");
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java b/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java
new file mode 100644
index 000000000..573bab245
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/migration/MigrationValidator.java
@@ -0,0 +1,284 @@
+package xiaozhi.migration;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.stereotype.Component;
+import org.springframework.context.annotation.Profile;
+
+import xiaozhi.modules.content.service.ContentLibraryService;
+import xiaozhi.modules.content.dto.ContentSearchDTO;
+import xiaozhi.common.page.PageData;
+import xiaozhi.modules.content.dto.ContentLibraryDTO;
+
+import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Migration Validator
+ *
+ * This component validates the migrated content library data to ensure
+ * the migration was successful and data integrity is maintained.
+ *
+ * Run with: java -jar app.jar --spring.profiles.active=validation
+ *
+ * @author Migration Validator
+ * @version 1.0
+ */
+@Slf4j
+@Component
+@Profile("validation")
+public class MigrationValidator implements CommandLineRunner {
+
+ @Autowired
+ private ContentLibraryService contentLibraryService;
+
+ @Override
+ public void run(String... args) throws Exception {
+ log.info("=======================================================");
+ log.info("Content Library Migration Validation");
+ log.info("=======================================================");
+
+ try {
+ // Validate content statistics
+ validateContentStatistics();
+
+ // Validate content categories
+ validateCategories();
+
+ // Validate sample content
+ validateSampleContent();
+
+ // Validate search functionality
+ validateSearchFunctionality();
+
+ log.info("=======================================================");
+ log.info("Migration Validation COMPLETED SUCCESSFULLY");
+ log.info("=======================================================");
+
+ } catch (Exception e) {
+ log.error("Migration validation failed: {}", e.getMessage(), e);
+ throw e;
+ }
+ }
+
+ /**
+ * Validate content statistics
+ */
+ private void validateContentStatistics() {
+ log.info("Validating content statistics...");
+
+ Object statsObj = contentLibraryService.getContentStatistics();
+ if (!(statsObj instanceof Map)) {
+ throw new RuntimeException("Invalid statistics format returned");
+ }
+
+ @SuppressWarnings("unchecked")
+ Map stats = (Map) statsObj;
+
+ Integer totalMusic = (Integer) stats.get("totalMusic");
+ Integer totalStories = (Integer) stats.get("totalStories");
+ Integer totalContent = (Integer) stats.get("totalContent");
+
+ log.info("Content Statistics:");
+ log.info(" - Total Music: {}", totalMusic != null ? totalMusic : 0);
+ log.info(" - Total Stories: {}", totalStories != null ? totalStories : 0);
+ log.info(" - Total Content: {}", totalContent != null ? totalContent : 0);
+
+ if (totalContent == null || totalContent == 0) {
+ throw new RuntimeException("No content found in database - migration may have failed");
+ }
+
+ if (totalMusic == null) totalMusic = 0;
+ if (totalStories == null) totalStories = 0;
+
+ if (!totalContent.equals(totalMusic + totalStories)) {
+ throw new RuntimeException("Content count mismatch: total=" + totalContent +
+ ", music=" + totalMusic + ", stories=" + totalStories);
+ }
+
+ log.info("✓ Content statistics validation passed");
+ }
+
+ /**
+ * Validate content categories
+ */
+ private void validateCategories() {
+ log.info("Validating content categories...");
+
+ // Expected categories based on migration script
+ String[] expectedMusicLanguages = {"English", "Hindi", "Kannada", "Phonics", "Telugu"};
+ String[] expectedStoryGenres = {"Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"};
+
+ // Get music categories
+ List musicCategories = contentLibraryService.getCategoriesByType("music");
+ log.info("Found music categories: {}", musicCategories);
+
+ // Get story categories
+ List storyCategories = contentLibraryService.getCategoriesByType("story");
+ log.info("Found story categories: {}", storyCategories);
+
+ // Validate music categories
+ for (String expectedLang : expectedMusicLanguages) {
+ if (!musicCategories.contains(expectedLang)) {
+ log.warn("Expected music language '{}' not found", expectedLang);
+ } else {
+ log.info("✓ Music language '{}' found", expectedLang);
+ }
+ }
+
+ // Validate story categories
+ for (String expectedGenre : expectedStoryGenres) {
+ if (!storyCategories.contains(expectedGenre)) {
+ log.warn("Expected story genre '{}' not found", expectedGenre);
+ } else {
+ log.info("✓ Story genre '{}' found", expectedGenre);
+ }
+ }
+
+ log.info("✓ Categories validation completed");
+ }
+
+ /**
+ * Validate sample content
+ */
+ private void validateSampleContent() {
+ log.info("Validating sample content...");
+
+ // Test music content
+ ContentSearchDTO musicSearch = new ContentSearchDTO();
+ musicSearch.setContentType("music");
+ musicSearch.setLimit(5);
+
+ PageData musicResults = contentLibraryService.getContentList(musicSearch);
+
+ if (musicResults.getList() == null || musicResults.getList().isEmpty()) {
+ log.warn("No music content found");
+ } else {
+ log.info("Sample music content ({} items):", musicResults.getList().size());
+ for (ContentLibraryDTO content : musicResults.getList()) {
+ log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
+ content.getFilename());
+ validateContentItem(content, "music");
+ }
+ }
+
+ // Test story content
+ ContentSearchDTO storySearch = new ContentSearchDTO();
+ storySearch.setContentType("story");
+ storySearch.setLimit(5);
+
+ PageData storyResults = contentLibraryService.getContentList(storySearch);
+
+ if (storyResults.getList() == null || storyResults.getList().isEmpty()) {
+ log.warn("No story content found");
+ } else {
+ log.info("Sample story content ({} items):", storyResults.getList().size());
+ for (ContentLibraryDTO content : storyResults.getList()) {
+ log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
+ content.getFilename());
+ validateContentItem(content, "story");
+ }
+ }
+
+ log.info("✓ Sample content validation completed");
+ }
+
+ /**
+ * Validate individual content item
+ */
+ private void validateContentItem(ContentLibraryDTO content, String expectedType) {
+ if (content.getId() == null || content.getId().isEmpty()) {
+ throw new RuntimeException("Content item missing ID: " + content.getTitle());
+ }
+
+ if (content.getTitle() == null || content.getTitle().isEmpty()) {
+ throw new RuntimeException("Content item missing title: " + content.getId());
+ }
+
+ if (!expectedType.equals(content.getContentType())) {
+ throw new RuntimeException("Content type mismatch for " + content.getTitle() +
+ ": expected " + expectedType + ", got " + content.getContentType());
+ }
+
+ if (content.getCategory() == null || content.getCategory().isEmpty()) {
+ throw new RuntimeException("Content item missing category: " + content.getTitle());
+ }
+
+ if (content.getAlternatives() == null) {
+ log.warn("Content item missing alternatives: {}", content.getTitle());
+ }
+
+ if (content.getIsActive() == null || !content.getIsActive()) {
+ log.warn("Content item not active: {}", content.getTitle());
+ }
+ }
+
+ /**
+ * Validate search functionality
+ */
+ private void validateSearchFunctionality() {
+ log.info("Validating search functionality...");
+
+ // Test basic search
+ ContentSearchDTO searchDTO = new ContentSearchDTO();
+ searchDTO.setQuery("baby");
+ searchDTO.setLimit(10);
+
+ PageData searchResults = contentLibraryService.searchContent(searchDTO);
+
+ if (searchResults.getList() == null) {
+ log.warn("Search returned null results");
+ } else {
+ log.info("Search for 'baby' returned {} results", searchResults.getList().size());
+
+ if (!searchResults.getList().isEmpty()) {
+ for (ContentLibraryDTO result : searchResults.getList()) {
+ String title = result.getTitle().toLowerCase();
+ List alternatives = result.getAlternatives();
+
+ boolean containsBaby = title.contains("baby");
+ if (!containsBaby && alternatives != null) {
+ containsBaby = alternatives.stream()
+ .anyMatch(alt -> alt.toLowerCase().contains("baby"));
+ }
+
+ if (containsBaby) {
+ log.info("✓ Search result matches: {}", result.getTitle());
+ } else {
+ log.warn("Search result may not match query: {}", result.getTitle());
+ }
+ }
+ }
+ }
+
+ // Test category filtering
+ ContentSearchDTO categorySearch = new ContentSearchDTO();
+ categorySearch.setContentType("music");
+ categorySearch.setCategory("English");
+ categorySearch.setLimit(5);
+
+ PageData categoryResults = contentLibraryService.getContentList(categorySearch);
+
+ if (categoryResults.getList() == null || categoryResults.getList().isEmpty()) {
+ log.warn("No English music content found");
+ } else {
+ log.info("Found {} English music items", categoryResults.getList().size());
+
+ for (ContentLibraryDTO result : categoryResults.getList()) {
+ if (!"music".equals(result.getContentType())) {
+ throw new RuntimeException("Category search returned wrong content type: " +
+ result.getContentType());
+ }
+ if (!"English".equals(result.getCategory())) {
+ throw new RuntimeException("Category search returned wrong category: " +
+ result.getCategory());
+ }
+ }
+ log.info("✓ Category filtering works correctly");
+ }
+
+ log.info("✓ Search functionality validation completed");
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java b/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java
new file mode 100644
index 000000000..bcaa7c22f
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/migration/StandaloneContentMigration.java
@@ -0,0 +1,273 @@
+package xiaozhi.migration;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.*;
+
+import com.google.gson.*;
+
+/**
+ * Standalone Content Library Migration
+ * Can be run independently to populate the content_library table
+ */
+public class StandaloneContentMigration {
+
+ // Database configuration - adjust these for your environment
+ private static final String DB_URL = "jdbc:mysql://localhost:3306/xiaozhi_esp32?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
+ private static final String DB_USER = "root";
+ private static final String DB_PASSWORD = "123456";
+
+ // Content paths
+ private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
+ private static final String MUSIC_PATH = BASE_PATH + "/music";
+ private static final String STORIES_PATH = BASE_PATH + "/stories";
+
+ private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ private static Connection connection;
+
+ public static void main(String[] args) {
+ System.out.println("==========================================");
+ System.out.println("Content Library Standalone Migration");
+ System.out.println("==========================================\n");
+
+ try {
+ // Connect to database
+ connectToDatabase();
+
+ // Clear existing data (optional - comment out if you want to keep existing data)
+ clearExistingData();
+
+ // Migrate music
+ migrateMusicContent();
+
+ // Migrate stories
+ migrateStoryContent();
+
+ // Print summary
+ printSummary();
+
+ System.out.println("\nMigration completed successfully!");
+
+ } catch (Exception e) {
+ System.err.println("Migration failed: " + e.getMessage());
+ e.printStackTrace();
+ } finally {
+ closeConnection();
+ }
+ }
+
+ private static void connectToDatabase() throws Exception {
+ System.out.println("Connecting to database...");
+ Class.forName("com.mysql.cj.jdbc.Driver");
+ connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
+ connection.setAutoCommit(false);
+ System.out.println("Connected to database successfully\n");
+ }
+
+ private static void clearExistingData() throws Exception {
+ System.out.println("Clearing existing data...");
+ PreparedStatement stmt = connection.prepareStatement("DELETE FROM content_library");
+ int deleted = stmt.executeUpdate();
+ connection.commit();
+ System.out.println("Deleted " + deleted + " existing records\n");
+ }
+
+ private static void migrateMusicContent() throws Exception {
+ System.out.println("Migrating music content...");
+
+ File musicDir = new File(MUSIC_PATH);
+ File[] languageDirs = musicDir.listFiles(File::isDirectory);
+
+ if (languageDirs == null) {
+ System.out.println("No music directories found");
+ return;
+ }
+
+ int totalMusic = 0;
+ for (File langDir : languageDirs) {
+ String language = langDir.getName();
+ System.out.println(" Processing language: " + language);
+
+ File metadataFile = new File(langDir, "metadata.json");
+ if (!metadataFile.exists()) {
+ System.out.println(" No metadata.json found");
+ continue;
+ }
+
+ String jsonContent = Files.readString(metadataFile.toPath());
+ JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
+
+ int count = 0;
+ for (Map.Entry entry : jsonObject.entrySet()) {
+ String title = entry.getKey();
+ JsonObject info = entry.getValue().getAsJsonObject();
+
+ if (insertContentItem(title, info, "music", language)) {
+ count++;
+ }
+ }
+
+ System.out.println(" Inserted " + count + " items");
+ totalMusic += count;
+ }
+
+ connection.commit();
+ System.out.println("Total music items migrated: " + totalMusic + "\n");
+ }
+
+ private static void migrateStoryContent() throws Exception {
+ System.out.println("Migrating story content...");
+
+ File storiesDir = new File(STORIES_PATH);
+ File[] genreDirs = storiesDir.listFiles(File::isDirectory);
+
+ if (genreDirs == null) {
+ System.out.println("No story directories found");
+ return;
+ }
+
+ int totalStories = 0;
+ for (File genreDir : genreDirs) {
+ String genre = genreDir.getName();
+ System.out.println(" Processing genre: " + genre);
+
+ File metadataFile = new File(genreDir, "metadata.json");
+ if (!metadataFile.exists()) {
+ System.out.println(" No metadata.json found");
+ continue;
+ }
+
+ String jsonContent = Files.readString(metadataFile.toPath());
+ JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
+
+ int count = 0;
+ for (Map.Entry entry : jsonObject.entrySet()) {
+ String title = entry.getKey();
+ JsonObject info = entry.getValue().getAsJsonObject();
+
+ if (insertContentItem(title, info, "story", genre)) {
+ count++;
+ }
+ }
+
+ System.out.println(" Inserted " + count + " items");
+ totalStories += count;
+ }
+
+ connection.commit();
+ System.out.println("Total story items migrated: " + totalStories + "\n");
+ }
+
+ private static boolean insertContentItem(String title, JsonObject info, String contentType, String category) {
+ try {
+ String sql = "INSERT INTO content_library (id, title, romanized, filename, content_type, " +
+ "category, alternatives, aws_s3_url, duration_seconds, file_size_bytes, is_active) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+
+ PreparedStatement stmt = connection.prepareStatement(sql);
+
+ // Generate UUID
+ String id = UUID.randomUUID().toString();
+
+ // Get values from JSON
+ String romanized = getJsonString(info, "romanized");
+ String filename = getJsonString(info, "filename");
+
+ // Build alternatives JSON array
+ JsonArray alternativesArray = info.getAsJsonArray("alternatives");
+ String alternativesJson = null;
+ if (alternativesArray != null) {
+ alternativesJson = gson.toJson(alternativesArray);
+ }
+
+ // Set parameters
+ stmt.setString(1, id);
+ stmt.setString(2, title);
+ stmt.setString(3, romanized);
+ stmt.setString(4, filename);
+ stmt.setString(5, contentType);
+ stmt.setString(6, category);
+ stmt.setString(7, alternativesJson);
+ stmt.setString(8, getJsonString(info, "aws_s3_url")); // May be null
+ stmt.setObject(9, getJsonInteger(info, "duration_seconds")); // May be null
+ stmt.setObject(10, getJsonLong(info, "file_size_bytes")); // May be null
+ stmt.setInt(11, 1); // is_active
+
+ stmt.executeUpdate();
+ return true;
+
+ } catch (Exception e) {
+ System.err.println(" Failed to insert '" + title + "': " + e.getMessage());
+ return false;
+ }
+ }
+
+ private static String getJsonString(JsonObject obj, String key) {
+ JsonElement element = obj.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
+ }
+
+ private static Integer getJsonInteger(JsonObject obj, String key) {
+ JsonElement element = obj.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
+ }
+
+ private static Long getJsonLong(JsonObject obj, String key) {
+ JsonElement element = obj.get(key);
+ return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
+ }
+
+ private static void printSummary() throws Exception {
+ System.out.println("==========================================");
+ System.out.println("Migration Summary");
+ System.out.println("==========================================");
+
+ // Count records by type
+ PreparedStatement stmt = connection.prepareStatement(
+ "SELECT content_type, COUNT(*) as count FROM content_library GROUP BY content_type"
+ );
+ ResultSet rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ String type = rs.getString("content_type");
+ int count = rs.getInt("count");
+ System.out.println(type.toUpperCase() + ": " + count + " items");
+ }
+
+ // Count by category
+ System.out.println("\nBy Category:");
+ stmt = connection.prepareStatement(
+ "SELECT content_type, category, COUNT(*) as count FROM content_library " +
+ "GROUP BY content_type, category ORDER BY content_type, category"
+ );
+ rs = stmt.executeQuery();
+
+ String lastType = "";
+ while (rs.next()) {
+ String type = rs.getString("content_type");
+ String category = rs.getString("category");
+ int count = rs.getInt("count");
+
+ if (!type.equals(lastType)) {
+ System.out.println("\n" + type.toUpperCase() + ":");
+ lastType = type;
+ }
+ System.out.println(" - " + category + ": " + count);
+ }
+ }
+
+ private static void closeConnection() {
+ try {
+ if (connection != null && !connection.isClosed()) {
+ connection.close();
+ System.out.println("\nDatabase connection closed");
+ }
+ } catch (Exception e) {
+ System.err.println("Error closing connection: " + e.getMessage());
+ }
+ }
+}
\ No newline at end of file
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java
index a4ad08632..4a6585624 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/controller/AgentController.java
@@ -145,10 +145,29 @@ public class AgentController {
@RequiresPermissions("sys:role:normal")
public Result> templateList() {
List list = agentTemplateService
- .list(new QueryWrapper().orderByAsc("sort"));
+ .list(new QueryWrapper()
+ .eq("is_visible", 1)
+ .orderByAsc("sort"));
return new Result>().ok(list);
}
+ @PutMapping("/template/{id}")
+ @Operation(summary = "更新智能体模板")
+ @RequiresPermissions("sys:role:normal")
+ public Result updateTemplate(@PathVariable String id, @RequestBody AgentTemplateEntity template) {
+ template.setId(id);
+ agentTemplateService.updateById(template);
+ return new Result<>();
+ }
+
+ @PostMapping("/template")
+ @Operation(summary = "创建智能体模板")
+ @RequiresPermissions("sys:role:normal")
+ public Result createTemplate(@RequestBody AgentTemplateEntity template) {
+ agentTemplateService.save(template);
+ return new Result().ok(template.getId());
+ }
+
@GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表")
@RequiresPermissions("sys:role:normal")
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java
index a7704e5bb..576521e9a 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/agent/entity/AgentTemplateEntity.java
@@ -103,6 +103,11 @@ public class AgentTemplateEntity implements Serializable {
*/
private Integer sort;
+ /**
+ * 是否在应用中显示(0不显示 1显示)
+ */
+ private Integer isVisible;
+
/**
* 创建者 ID
*/
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/content/controller/ContentLibraryController.java b/main/manager-api/src/main/java/xiaozhi/modules/content/controller/ContentLibraryController.java
new file mode 100644
index 000000000..ece40ed8a
--- /dev/null
+++ b/main/manager-api/src/main/java/xiaozhi/modules/content/controller/ContentLibraryController.java
@@ -0,0 +1,155 @@
+package xiaozhi.modules.content.controller;
+
+import java.util.List;
+
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.AllArgsConstructor;
+import xiaozhi.common.page.PageData;
+import xiaozhi.common.utils.Result;
+import xiaozhi.modules.content.dto.ContentLibraryDTO;
+import xiaozhi.modules.content.dto.ContentSearchDTO;
+import xiaozhi.modules.content.service.ContentLibraryService;
+
+/**
+ * Content Library REST API Controller
+ * Handles music and story content operations
+ */
+@RestController
+@RequestMapping("/content/library")
+@AllArgsConstructor
+@Tag(name = "Content Library", description = "Music and Story Content Management")
+public class ContentLibraryController {
+
+ private final ContentLibraryService contentLibraryService;
+
+ @GetMapping
+ @Operation(summary = "Get content list with filters and pagination", description = "Retrieves paginated content with optional filters")
+ public Result> getContentList(
+ @Parameter(description = "Search query") @RequestParam(required = false) String query,
+ @Parameter(description = "Content type filter") @RequestParam(required = false) String contentType,
+ @Parameter(description = "Category filter") @RequestParam(required = false) String category,
+ @Parameter(description = "Page number (1-based)") @RequestParam(defaultValue = "1") Integer page,
+ @Parameter(description = "Items per page") @RequestParam(defaultValue = "20") Integer limit,
+ @Parameter(description = "Sort field") @RequestParam(defaultValue = "created_at") String sortBy,
+ @Parameter(description = "Sort direction") @RequestParam(defaultValue = "desc") String sortDirection) {
+
+ ContentSearchDTO searchDTO = new ContentSearchDTO();
+ searchDTO.setQuery(query);
+ searchDTO.setContentType(contentType);
+ searchDTO.setCategory(category);
+ searchDTO.setPage(page);
+ searchDTO.setLimit(limit);
+ searchDTO.setSortBy(sortBy);
+ searchDTO.setSortDirection(sortDirection);
+
+ PageData result = contentLibraryService.getContentList(searchDTO);
+ return new Result>().ok(result);
+ }
+
+ @GetMapping("/search")
+ @Operation(summary = "Search content", description = "Full-text search across content titles and alternatives")
+ public Result> searchContent(
+ @Parameter(description = "Search query", required = true) @RequestParam String query,
+ @Parameter(description = "Content type filter") @RequestParam(required = false) String contentType,
+ @Parameter(description = "Page number (1-based)") @RequestParam(defaultValue = "1") Integer page,
+ @Parameter(description = "Items per page") @RequestParam(defaultValue = "20") Integer limit) {
+
+ ContentSearchDTO searchDTO = new ContentSearchDTO();
+ searchDTO.setQuery(query);
+ searchDTO.setContentType(contentType);
+ searchDTO.setPage(page);
+ searchDTO.setLimit(limit);
+
+ PageData result = contentLibraryService.searchContent(searchDTO);
+ return new Result>().ok(result);
+ }
+
+ @GetMapping("/categories")
+ @Operation(summary = "Get categories by content type", description = "Retrieves available categories for music or stories")
+ public Result> getCategories(
+ @Parameter(description = "Content type (music or story)", required = true) @RequestParam String contentType) {
+
+ List categories = contentLibraryService.getCategoriesByType(contentType);
+ return new Result>().ok(categories);
+ }
+
+ @GetMapping("/{id}")
+ @Operation(summary = "Get content by ID", description = "Retrieves detailed content information")
+ public Result getContentById(
+ @Parameter(description = "Content ID", required = true) @PathVariable String id) {
+
+ ContentLibraryDTO content = contentLibraryService.getContentById(id);
+ if (content == null) {
+ return new Result().error("Content not found");
+ }
+ return new Result().ok(content);
+ }
+
+ @GetMapping("/statistics")
+ @Operation(summary = "Get content statistics", description = "Retrieves content counts and category statistics")
+ public Result