- Add sanitize_folder_name utility for filesystem-safe folder names - Add sanitized_folder property to Serie entity - Update SerieList.add() to use sanitized display names for folders - Add scan_single_series() method for targeted episode scanning - Enhance add_series endpoint: DB save -> folder create -> targeted scan - Update response to include missing_episodes and total_missing - Add comprehensive unit tests for new functionality - Update API tests with proper mock support
9.4 KiB
Aniworld Web Application Development Instructions
This document provides detailed tasks for AI agents to implement a modern web application for the Aniworld anime download manager. All tasks should follow the coding guidelines specified in the project's copilot instructions.
Project Overview
The goal is to create a FastAPI-based web application that provides a modern interface for the existing Aniworld anime download functionality. The core anime logic should remain in SeriesApp.py while the web layer provides REST API endpoints and a responsive UI.
Architecture Principles
- Single Responsibility: Each file/class has one clear purpose
- Dependency Injection: Use FastAPI's dependency system
- Clean Separation: Web layer calls core logic, never the reverse
- File Size Limit: Maximum 500 lines per file
- Type Hints: Use comprehensive type annotations
- Error Handling: Proper exception handling and logging
Additional Implementation Guidelines
Code Style and Standards
- Type Hints: Use comprehensive type annotations throughout all modules
- Docstrings: Follow PEP 257 for function and class documentation
- Error Handling: Implement custom exception classes with meaningful messages
- Logging: Use structured logging with appropriate log levels
- Security: Validate all inputs and sanitize outputs
- Performance: Use async/await patterns for I/O operations
📞 Escalation
If you encounter:
- Architecture issues requiring design decisions
- Tests that conflict with documented requirements
- Breaking changes needed
- Unclear requirements or expectations
Document the issue and escalate rather than guessing.
📚 Helpful Commands
# Run all tests
conda run -n AniWorld python -m pytest tests/ -v --tb=short
# Run specific test file
conda run -n AniWorld python -m pytest tests/unit/test_websocket_service.py -v
# Run specific test class
conda run -n AniWorld python -m pytest tests/unit/test_websocket_service.py::TestWebSocketService -v
# Run specific test
conda run -n AniWorld python -m pytest tests/unit/test_websocket_service.py::TestWebSocketService::test_broadcast_download_progress -v
# Run with extra verbosity
conda run -n AniWorld python -m pytest tests/ -vv
# Run with full traceback
conda run -n AniWorld python -m pytest tests/ -v --tb=long
# Run and stop at first failure
conda run -n AniWorld python -m pytest tests/ -v -x
# Run tests matching pattern
conda run -n AniWorld python -m pytest tests/ -v -k "auth"
# Show all print statements
conda run -n AniWorld python -m pytest tests/ -v -s
#Run app
conda run -n AniWorld python -m uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload
Implementation Notes
- Incremental Development: Implement features incrementally, testing each component thoroughly before moving to the next
- Code Review: Review all generated code for adherence to project standards
- Documentation: Document all public APIs and complex logic
- Testing: Maintain test coverage above 80% for all new code
- Performance: Profile and optimize critical paths, especially download and streaming operations
- Security: Regular security audits and dependency updates
- Monitoring: Implement comprehensive monitoring and alerting
- Maintenance: Plan for regular maintenance and updates
Task Completion Checklist
For each task completed:
- Implementation follows coding standards
- Unit tests written and passing
- Integration tests passing
- Documentation updated
- Error handling implemented
- Logging added
- Security considerations addressed
- Performance validated
- Code reviewed
- Task marked as complete in instructions.md
- Infrastructure.md updated and other docs
- Changes committed to git; keep your messages in git short and clear
- Take the next task
Prerequisites
- Server is running:
conda run -n AniWorld python -m uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload - Password:
Hallo123! - Login via browser at
http://127.0.0.1:8000/login
Notes
- This is a simplification that removes complexity while maintaining core functionality
- Improves user experience with explicit manual control
- Easier to understand, test, and maintain
- Good foundation for future enhancements if needed
Task: Enhanced Anime Add Flow
Overview
Enhance the anime addition workflow to automatically persist anime to the database, scan for missing episodes immediately, and create folders using the anime display name instead of the internal key.
Requirements
- After anime add → Save to database: Ensure the anime is persisted to the database via
AnimeDBService.create_series()immediately after validation - After anime add → Scan for missing episodes: Trigger a targeted episode scan for only the newly added anime (not the entire library)
- After anime add → Create folder with anime name: Use the anime display name (sanitized) for the folder, not the anime key
Implementation Steps
Step 1: Examine Current Implementation
- Open and read
src/server/routes/anime_routes.py- find theadd_seriesendpoint - Open and read
src/core/SerieScanner.py- understand how scanning works - Open and read
src/core/entities/Serie.pyandsrc/core/entities/SerieList.py- understand folder handling - Open and read
src/database/services/anime_db_service.py- understand database operations - Open and read
src/core/providers/AniWorldProvider.py- understand how folders are created
Step 2: Create Utility Function for Folder Name Sanitization
- Create or update utility module at
src/utils/filesystem.py - Implement
sanitize_folder_name(name: str) -> strfunction that:- Removes/replaces characters invalid for filesystems:
< > : " / \ | ? * - Trims leading/trailing whitespace and dots
- Handles edge cases (empty string, only invalid chars)
- Preserves Unicode characters (for Japanese titles, etc.)
- Removes/replaces characters invalid for filesystems:
Step 3: Update Serie Entity
- Open
src/core/entities/Serie.py - Add a
folderproperty that returns sanitized display name instead of key - Ensure backward compatibility with existing series
Step 4: Update SerieList to Use Display Name for Folders
- Open
src/core/entities/SerieList.py - In the
add()method, useserie.folder(display name) instead ofserie.keywhen creating directories - Ensure the folder path is correctly stored in the Serie object
Step 5: Add Targeted Episode Scan Method to SerieScanner
- Open
src/core/SerieScanner.py - Add new method
scan_single_series(self, key: str) -> List[Episode]:- Fetches the specific anime from database/SerieList by key
- Calls the provider to get available episodes
- Compares with local files to find missing episodes
- Returns list of missing episodes
- Does NOT trigger a full library rescan
Step 6: Update add_series Endpoint
- Open
src/server/routes/anime_routes.py - Modify the
add_seriesendpoint to:- Step A: Validate the request (existing)
- Step B: Create Serie object with sanitized folder name
- Step C: Save to database via
AnimeDBService.create_series() - Step D: Add to SerieList (which creates the folder)
- Step E: Call
SerieScanner.scan_single_series(key)for targeted scan - Step F: Return response including:
- Success status
- Created folder path
- List of missing episodes found (if any)
Step 7: Update Provider Folder Handling
- Open
src/core/providers/AniWorldProvider.py - Ensure download operations use
serie.folderfor filesystem paths - If
EnhancedProvider.pyexists, update it similarly
Acceptance Criteria
- When adding a new anime, it is immediately saved to the database
- When adding a new anime, only that anime is scanned for missing episodes (not full library)
- Folder is created using the sanitized display name (e.g., "Attack on Titan" not "attack-on-titan")
- Special characters in anime names are properly handled (
:,?, etc.) - Existing anime entries continue to work (backward compatibility)
- API response includes the created folder path and missing episodes count
- Unit tests cover the new functionality
- No regressions in existing tests
Testing Requirements
-
Unit Tests:
- Test
sanitize_folder_name()with various inputs (special chars, Unicode, edge cases) - Test
Serie.folderproperty returns sanitized name - Test
SerieScanner.scan_single_series()only scans the specified anime - Test database persistence on anime add
- Test
-
Integration Tests:
- Test full add flow: request → database → folder creation → scan
- Test that folder is created with correct name
- Test API response contains expected fields
Error Handling
- If database save fails, return appropriate error and don't create folder
- If folder creation fails (permissions, disk full), return error and rollback database entry
- If scan fails, still return success for add but indicate scan failure in response
- Log all operations with appropriate log levels
Security Considerations
- Sanitize folder names to prevent path traversal attacks
- Validate anime name length to prevent filesystem issues
- Ensure folder is created within the configured library path only