Aniworld/docs/instructions.md
Lukas a24f07a36e Add MP4 scan progress visibility in UI
- Add broadcast_scan_started, broadcast_scan_progress, broadcast_scan_completed to WebSocketService
- Inject WebSocketService into AnimeService for real-time scan progress broadcasts
- Add CSS styles for scan progress overlay with spinner, stats, and completion state
- Update app.js to handle scan events and display progress overlay
- Add unit tests for new WebSocket broadcast methods
- All 1022 tests passing
2025-12-23 18:24:32 +01:00

268 lines
10 KiB
Markdown

# 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
```bash
# 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
1. **Incremental Development**: Implement features incrementally, testing each component thoroughly before moving to the next
2. **Code Review**: Review all generated code for adherence to project standards
3. **Documentation**: Document all public APIs and complex logic
4. **Testing**: Maintain test coverage above 80% for all new code
5. **Performance**: Profile and optimize critical paths, especially download and streaming operations
6. **Security**: Regular security audits and dependency updates
7. **Monitoring**: Implement comprehensive monitoring and alerting
8. **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
- [ ] Changes committed to git; keep your messages in git short and clear
- [ ] Take the next task
---
### Prerequisites
1. Server is running: `conda run -n AniWorld python -m uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload`
2. Password: `Hallo123!`
3. 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
---
## 🔧 Current Task: Make MP4 Scanning Progress Visible in UI
### Problem Statement
When users trigger a library rescan (via the "Rescan Library" button on the anime page), the MP4 file scanning happens silently in the background. Users only see a brief toast message, but there's no visual feedback showing:
1. That scanning is actively happening
2. How many files/directories have been scanned
3. The progress through the scan operation
4. When scanning is complete with results
Currently, the only indication is in server logs:
```
INFO: Starting directory rescan
INFO: Scanning for .mp4 files
```
### Desired Outcome
Users should see real-time progress in the UI during library scanning with:
1. **Progress overlay** showing scan is active with a spinner animation
2. **Live counters** showing directories scanned and files found
3. **Current directory display** showing which folder is being scanned (truncated if too long)
4. **Completion summary** showing total files found, directories scanned, and elapsed time
5. **Auto-dismiss** the overlay after showing completion summary
### Files to Modify
#### 1. `src/server/services/websocket_service.py`
Add three new broadcast methods for scan events:
- **broadcast_scan_started**: Notify clients that a scan has begun, include the root directory path
- **broadcast_scan_progress**: Send periodic updates with directories scanned count, files found count, and current directory name
- **broadcast_scan_completed**: Send final summary with total directories, total files, and elapsed time in seconds
Follow the existing pattern used by `broadcast_download_progress` for message structure consistency.
#### 2. `src/server/services/scanner_service.py`
Modify the scanning logic to emit progress via WebSocket:
- Inject `WebSocketService` dependency into the scanner service
- At scan start, call `broadcast_scan_started`
- During directory traversal, track directories scanned and files found
- Every 10 directories (to avoid WebSocket spam), call `broadcast_scan_progress`
- Track elapsed time using `time.time()`
- At scan completion, call `broadcast_scan_completed` with summary statistics
- Ensure the scan still works correctly even if WebSocket broadcast fails (wrap in try/except)
#### 3. `src/server/static/css/style.css`
Add styles for the scan progress overlay:
- Full-screen semi-transparent overlay (z-index high enough to be on top)
- Centered container with background matching theme (use CSS variables)
- Spinner animation using CSS keyframes
- Styling for current directory text (truncated with ellipsis)
- Styling for statistics display
- Success state styling for completion
- Ensure it works in both light and dark mode themes
#### 4. `src/server/static/js/anime.js`
Add WebSocket message handlers and UI functions:
- Handle `scan_started` message: Create and show progress overlay with spinner
- Handle `scan_progress` message: Update directory count, file count, and current directory text
- Handle `scan_completed` message: Show completion summary, then auto-remove overlay after 3 seconds
- Ensure overlay is properly cleaned up if page navigates away
- Update the existing rescan button handler to work with the new progress system
### WebSocket Message Types
Define three new message types following the existing project patterns:
1. **scan_started**: type, directory path, timestamp
2. **scan_progress**: type, directories_scanned, files_found, current_directory, timestamp
3. **scan_completed**: type, total_directories, total_files, elapsed_seconds, timestamp
### Implementation Steps
1. First modify `websocket_service.py` to add the three new broadcast methods
2. Add unit tests for the new WebSocket methods
3. Modify `scanner_service.py` to use the new broadcast methods during scanning
4. Add CSS styles to `style.css` for the progress overlay
5. Update `anime.js` to handle the new WebSocket messages and display the UI
6. Test the complete flow manually
7. Verify all existing tests still pass
### Testing Requirements
**Unit Tests:**
- Test each new WebSocket broadcast method
- Test that scanner service calls WebSocket methods at appropriate times
- Mock WebSocket service in scanner tests
**Manual Testing:**
- Start server and login
- Navigate to anime page
- Click "Rescan Library" button
- Verify overlay appears immediately with spinner
- Verify counters update during scan
- Verify current directory updates
- Verify completion summary appears
- Verify overlay auto-dismisses after 3 seconds
- Test in both light and dark mode
- Verify no JavaScript console errors
### Acceptance Criteria
- [x] Progress overlay appears immediately when scan starts
- [x] Spinner animation is visible during scanning
- [x] Directory counter updates periodically (every ~10 directories)
- [x] Files found counter updates as MP4 files are discovered
- [x] Current directory name is displayed (truncated if path is too long)
- [x] Scan completion shows total directories, files, and elapsed time
- [x] Overlay auto-dismisses 3 seconds after completion
- [x] Works correctly in both light and dark mode
- [x] No JavaScript errors in browser console
- [x] All existing tests continue to pass
- [x] New unit tests added and passing
- [x] Code follows project coding standards
### Edge Cases to Handle
- Empty directory with no MP4 files
- Very large directory structure (ensure UI remains responsive)
- WebSocket connection lost during scan (scan should still complete)
- User navigates away during scan (cleanup overlay properly)
- Rapid consecutive scan requests (debounce or queue)
### Notes
- Keep progress updates throttled to avoid overwhelming the WebSocket connection
- Use existing CSS variables for colors to maintain theme consistency
- Follow existing JavaScript patterns in the codebase
- The scan functionality must continue to work even if WebSocket fails
---