# 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.** --- ## � Credentials **Admin Login:** - Username: `admin` - Password: `Hallo123!` --- ## �📚 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 and other docs - [ ] Changes committed to git; keep your messages in git short and clear - [ ] Take the next task --- ## TODO List: All tasks completed! Recent issues have been resolved. ## Recently Fixed Issues: ### ✅ Fixed: NFO Folder Naming Without Year (2026-01-18) **Issue:** After creating NFO files, the folder name is created as "" but should be " ()" to properly distinguish series with the same name but different years (e.g., "Perfect Blue" vs "Perfect Blue (1997)"). **Root Cause:** The NFO endpoints were using `serie.folder` directly without ensuring it includes the year. The `Serie` class already had a `sanitized_folder` property that creates proper folder names with year format, but it wasn't being used consistently during NFO creation. **Solution:** 1. Added `Serie.ensure_folder_with_year()` method that checks if the folder name includes the year and updates it if needed 2. Updated all NFO API endpoints (`create`, `update`, `check`, `view`, `download_media`, `batch_create`, `get_series_without_nfo`) to call `ensure_folder_with_year()` before any NFO operations 3. This ensures there's a single code location responsible for folder name generation with year format 4. The NFO service creates folders using the updated folder name **Files Modified:** - [src/core/entities/series.py](../src/core/entities/series.py) - Added `ensure_folder_with_year()` method - [src/server/api/nfo.py](../src/server/api/nfo.py) - Updated all endpoints to use `ensure_folder_with_year()` **Tests Added:** - [tests/unit/test_serie_folder_with_year.py](../tests/unit/test_serie_folder_with_year.py) - 5 comprehensive tests covering all scenarios **Verification:** - All 5 unit tests pass - Folder names now consistently use "Name (Year)" format when year is available - Existing folders without year are automatically updated when NFO operations are performed - Single centralized method ensures consistency across the application --- ### ✅ Fixed: NFO JavaScript JSON Parsing Error (2026-01-18) **Issue:** Browser console shows `Error creating NFO: Error: Failed to create NFO` from [nfo-manager.js](../src/server/web/static/js/index/nfo-manager.js) and [series-manager.js](../src/server/web/static/js/index/series-manager.js). The API calls were failing because the code was trying to access response properties directly without parsing the JSON. **Root Cause:** The `AniWorld.ApiClient.request()` function returns a native `Response` object from the Fetch API, not the parsed JSON data. The code was attempting to access properties like `response.message` and `response.content` directly without first calling `response.json()` to parse the response body. **Solution:** Updated all NFO-related API calls in the JavaScript modules to: 1. Check if response exists (`if (!response)`) 2. Parse the JSON response (`const data = await response.json()`) 3. Access properties on the parsed data object (`data.message`, `data.content`, etc.) **Files Modified:** - [src/server/web/static/js/index/nfo-manager.js](../src/server/web/static/js/index/nfo-manager.js) - Fixed `createNFO()`, `refreshNFO()`, `viewNFO()`, `getSeriesWithoutNFO()` - [src/server/web/static/js/index/nfo-config.js](../src/server/web/static/js/index/nfo-config.js) - Fixed `load()`, `testTMDBConnection()` **Verification:** - NFO creation now works correctly from the web UI - Error messages are properly displayed with details from the API - All NFO operations (create, refresh, view) function as expected --- ### ✅ Fixed: NFO 503 Error After Server Reload (2026-01-18) **Issue:** POST http://127.0.0.1:8000/api/nfo/blue-exorcist/create returns 503 (Service Unavailable) with "NFO service not configured. TMDB API key required." even though TMDB API key is configured in config.json. This occurred after server reloads in development mode (--reload). **Root Cause:** The `settings` singleton is recreated on each module reload by uvicorn in development mode. The TMDB API key loaded from config.json during startup was lost when modules were reloaded, causing `settings.tmdb_api_key` to be None again. **Solution:** Modified `get_nfo_service()` dependency function to check `settings.tmdb_api_key` first, and if not found, fall back to loading from `config.json` directly. This ensures the TMDB API key is always available even after hot reloads in development. **Files Modified:** - [src/server/api/nfo.py](../src/server/api/nfo.py) **Tests Added:** - [tests/unit/test_nfo_dependency.py](../tests/unit/test_nfo_dependency.py) - Tests for config fallback behavior **Verification:** - All 4 unit tests pass - NFO endpoints work correctly even after server reloads - Falls back gracefully to config.json when settings are reset --- ### ✅ Fixed: NFO Creation 500 Error - Missing Folder (2026-01-18) **Issue:** POST http://127.0.0.1:8000/api/nfo/blue-period/create returns 500 (Internal Server Error) with message "Series folder not found: /home/lukas/Volume/serien/Blue Period" **Root Cause:** The NFO service was checking if the series folder existed before creating NFO files, and raising a FileNotFoundError if it didn't. This prevented users from creating NFO files for newly added series where no episodes had been downloaded yet. **Solution:** Modified `create_tvshow_nfo()` in `nfo_service.py` to automatically create the series folder (with `mkdir(parents=True, exist_ok=True)`) if it doesn't exist, instead of raising an error. **Files Modified:** - [src/core/services/nfo_service.py](../src/core/services/nfo_service.py) **Tests Added:** - [tests/unit/test_nfo_service_folder_creation.py](../tests/unit/test_nfo_service_folder_creation.py) - Unit test verifying folder creation - [tests/integration/test_nfo_folder_creation.py](../tests/integration/test_nfo_folder_creation.py) - Integration test for end-to-end verification **Verification:** - Unit and integration tests pass - NFO files can now be created for series even when the folder doesn't exist - Folder is automatically created when needed --- ### ✅ Fixed: NFO Service 503 Error (2026-01-18) **Issue:** Failed to load resource: the server responded with a status of 503 (Service Unavailable) when creating NFO files. **Root Cause:** The TMDB API key configured in `data/config.json` was not being loaded into the application settings during startup. The NFO service dependency check was failing because `settings.tmdb_api_key` was None. **Solution:** Updated `fastapi_app.py` startup code to sync NFO configuration (including TMDB API key) from `data/config.json` to `settings` object, similar to how `anime_directory` was already being synced. **Files Modified:** - [src/server/fastapi_app.py](../src/server/fastapi_app.py) **Verification:** NFO endpoints now return 200 OK instead of 503, and NFO creation is functional. --- ### ✅ Fixed: NFO Database Query Error (2026-01-18) **Issue:** WARNING: Could not fetch NFO data from database: '\_AsyncGeneratorContextManager' object has no attribute 'query' **Root Cause:** 1. Synchronous code in `anime.py` was calling `get_db_session()` which returns an async context manager, but wasn't using `async with`. 2. Async methods in `anime_service.py` were calling `get_db_session()` without using `async with`. 3. Incorrect attribute name: used `folder_name` instead of `folder`. **Solution:** 1. Changed `anime.py` line ~323 to use `get_sync_session()` instead of `get_db_session()` for synchronous database access. 2. Updated three async methods in `anime_service.py` to properly use `async with get_db_session()`: - `update_nfo_status()` - `get_series_without_nfo()` - `get_nfo_statistics()` 3. Fixed attribute name from `db_series.folder_name` to `db_series.folder` in `anime.py`. **Files Modified:** - [src/server/api/anime.py](../src/server/api/anime.py) - [src/server/services/anime_service.py](../src/server/services/anime_service.py) **Verification:** Server now starts without warnings, and NFO metadata can be fetched from the database correctly.