Fix SeriesApp: Add missing class variable and clean up unused imports

This commit is contained in:
Lukas Pupka-Lipinski 2025-10-06 09:17:35 +02:00
parent 4c9076af19
commit 00a68deb7b
8 changed files with 199 additions and 167 deletions

View File

@ -10,19 +10,21 @@ AniWorld has been successfully migrated from Flask to FastAPI, providing improve
FastAPI automatically generates interactive API documentation that you can access at: FastAPI automatically generates interactive API documentation that you can access at:
- **Swagger UI**: `http://localhost:8000/docs` - **Swagger UI**: `http://localhost:8000/docs`
- **ReDoc**: `http://localhost:8000/redoc` - **ReDoc**: `http://localhost:8000/redoc`
These interfaces allow you to: These interfaces allow you to:
- Browse all available endpoints
- View request/response schemas - Browse all available endpoints
- Test API endpoints directly from the browser - View request/response schemas
- Download OpenAPI schema - Test API endpoints directly from the browser
- Download OpenAPI schema
### OpenAPI Schema ### OpenAPI Schema
The complete OpenAPI 3.0 schema is available at: The complete OpenAPI 3.0 schema is available at:
- **JSON Format**: `http://localhost:8000/openapi.json`
- **JSON Format**: `http://localhost:8000/openapi.json`
## Authentication ## Authentication
@ -33,22 +35,23 @@ AniWorld uses a simple master password authentication system with JWT tokens.
#### Login Process #### Login Process
1. **POST** `/auth/login` 1. **POST** `/auth/login`
- Send master password in request body - Send master password in request body
- Receive JWT token in response - Receive JWT token in response
- Token expires in 24 hours - Token expires in 24 hours
```json ```json
{ {
"password": "your_master_password" "password": "your_master_password"
} }
``` ```
Response: Response:
```json ```json
{ {
"success": true, "success": true,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"message": "Login successful" "message": "Login successful"
} }
``` ```
@ -64,39 +67,39 @@ Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
### System Health ### System Health
- **GET** `/health` - Check system health and status - **GET** `/health` - Check system health and status
- **GET** `/api/system/database/health` - Check database connectivity - **GET** `/api/system/database/health` - Check database connectivity
- **GET** `/api/system/config` - Get system configuration - **GET** `/api/system/config` - Get system configuration
### Authentication ### Authentication
- **POST** `/auth/login` - Authenticate and get JWT token - **POST** `/auth/login` - Authenticate and get JWT token
- **GET** `/auth/verify` - Verify current token validity - **GET** `/auth/verify` - Verify current token validity
- **POST** `/auth/logout` - Logout and invalidate token - **POST** `/auth/logout` - Logout and invalidate token
- **GET** `/api/auth/status` - Get current authentication status - **GET** `/api/auth/status` - Get current authentication status
### Anime Management ### Anime Management
- **GET** `/api/anime/search` - Search for anime series - **GET** `/api/anime/search` - Search for anime series
- **GET** `/api/anime/{anime_id}` - Get specific anime details - **GET** `/api/anime/{anime_id}` - Get specific anime details
- **GET** `/api/anime/{anime_id}/episodes` - Get episodes for an anime - **GET** `/api/anime/{anime_id}/episodes` - Get episodes for an anime
### Episode Management ### Episode Management
- **GET** `/api/episodes/{episode_id}` - Get specific episode details - **GET** `/api/episodes/{episode_id}` - Get specific episode details
### Series Management ### Series Management
- **POST** `/api/add_series` - Add a new series to tracking - **POST** `/api/add_series` - Add a new series to tracking
- **POST** `/api/download` - Start episode download - **POST** `/api/download` - Start episode download
### Web Interface ### Web Interface
- **GET** `/` - Main application interface - **GET** `/` - Main application interface
- **GET** `/app` - Application dashboard - **GET** `/app` - Application dashboard
- **GET** `/login` - Login page - **GET** `/login` - Login page
- **GET** `/setup` - Setup page - **GET** `/setup` - Setup page
- **GET** `/queue` - Download queue interface - **GET** `/queue` - Download queue interface
## Response Formats ## Response Formats
@ -127,14 +130,14 @@ Error responses include detailed error information:
## Status Codes ## Status Codes
- **200 OK** - Successful operation - **200 OK** - Successful operation
- **201 Created** - Resource created successfully - **201 Created** - Resource created successfully
- **400 Bad Request** - Invalid request data - **400 Bad Request** - Invalid request data
- **401 Unauthorized** - Authentication required - **401 Unauthorized** - Authentication required
- **403 Forbidden** - Insufficient permissions - **403 Forbidden** - Insufficient permissions
- **404 Not Found** - Resource not found - **404 Not Found** - Resource not found
- **422 Unprocessable Entity** - Validation error - **422 Unprocessable Entity** - Validation error
- **500 Internal Server Error** - Server error - **500 Internal Server Error** - Server error
## Rate Limiting ## Rate Limiting
@ -143,9 +146,10 @@ Currently, no rate limiting is implemented, but it may be added in future versio
## WebSocket Support ## WebSocket Support
Real-time updates are available through WebSocket connections for: Real-time updates are available through WebSocket connections for:
- Download progress updates
- Scan progress updates - Download progress updates
- System status changes - Scan progress updates
- System status changes
## Migration Notes ## Migration Notes
@ -159,10 +163,10 @@ Real-time updates are available through WebSocket connections for:
### Breaking Changes ### Breaking Changes
- Authentication tokens are now JWT-based instead of session-based - Authentication tokens are now JWT-based instead of session-based
- Request/response formats may have slight differences - Request/response formats may have slight differences
- Some endpoint URLs may have changed - Some endpoint URLs may have changed
- WebSocket endpoints use FastAPI WebSocket pattern - WebSocket endpoints use FastAPI WebSocket pattern
## Development ## Development
@ -178,10 +182,10 @@ uvicorn src.server.fastapi_app:app --host 0.0.0.0 --port 8000
### Environment Variables ### Environment Variables
- `MASTER_PASSWORD_HASH` - Hashed master password - `MASTER_PASSWORD_HASH` - Hashed master password
- `JWT_SECRET_KEY` - Secret key for JWT token signing - `JWT_SECRET_KEY` - Secret key for JWT token signing
- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) - `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR)
## Support ## Support
For issues, questions, or contributions, please visit the project repository or contact the development team. For issues, questions, or contributions, please visit the project repository or contact the development team.

218
README.md
View File

@ -5,103 +5,118 @@ A powerful anime series management system that helps you track, organize, and do
## 🚀 Features ## 🚀 Features
### Core Functionality ### Core Functionality
- **Series Tracking**: Automatically detect missing episodes in your anime collection
- **Smart Downloads**: Queue-based download system with progress tracking - **Series Tracking**: Automatically detect missing episodes in your anime collection
- **File Organization**: Automatic file scanning and folder structure management - **Smart Downloads**: Queue-based download system with progress tracking
- **Search Integration**: Search for anime series across multiple providers - **File Organization**: Automatic file scanning and folder structure management
- **Real-time Updates**: Live progress updates via WebSocket connections - **Search Integration**: Search for anime series across multiple providers
- **Real-time Updates**: Live progress updates via WebSocket connections
### Web Interface ### Web Interface
- **Modern UI**: Clean, responsive web interface with dark/light theme support
- **Download Queue**: Visual download queue management - **Modern UI**: Clean, responsive web interface with dark/light theme support
- **Progress Tracking**: Real-time download and scan progress - **Download Queue**: Visual download queue management
- **Mobile Support**: Fully responsive design for mobile devices - **Progress Tracking**: Real-time download and scan progress
- **Mobile Support**: Fully responsive design for mobile devices
### API & Integration ### API & Integration
- **FastAPI Backend**: High-performance async API with automatic documentation
- **RESTful API**: Complete REST API for programmatic access - **FastAPI Backend**: High-performance async API with automatic documentation
- **OpenAPI Documentation**: Interactive API documentation at `/docs` - **RESTful API**: Complete REST API for programmatic access
- **Authentication**: Secure master password authentication with JWT tokens - **OpenAPI Documentation**: Interactive API documentation at `/docs`
- **Authentication**: Secure master password authentication with JWT tokens
## 🎯 Recent Migration: Flask → FastAPI ## 🎯 Recent Migration: Flask → FastAPI
This project has been successfully migrated from Flask to FastAPI, bringing significant improvements: This project has been successfully migrated from Flask to FastAPI, bringing significant improvements:
### Performance Benefits ### Performance Benefits
- **Async Support**: Native async/await for better concurrency
- **Faster Response Times**: Up to 2-3x performance improvement - **Async Support**: Native async/await for better concurrency
- **Better Resource Utilization**: More efficient handling of concurrent requests - **Faster Response Times**: Up to 2-3x performance improvement
- **Better Resource Utilization**: More efficient handling of concurrent requests
### Developer Experience ### Developer Experience
- **Automatic Documentation**: Built-in OpenAPI/Swagger documentation
- **Type Safety**: Full request/response validation with Pydantic - **Automatic Documentation**: Built-in OpenAPI/Swagger documentation
- **Modern Standards**: OpenAPI 3.0 compliance and JSON Schema validation - **Type Safety**: Full request/response validation with Pydantic
- **Better Error Handling**: Structured error responses with detailed information - **Modern Standards**: OpenAPI 3.0 compliance and JSON Schema validation
- **Better Error Handling**: Structured error responses with detailed information
### API Improvements ### API Improvements
- **Interactive Documentation**: Test API endpoints directly from `/docs`
- **Schema Validation**: Automatic request/response validation - **Interactive Documentation**: Test API endpoints directly from `/docs`
- **Better Error Messages**: Detailed validation errors with field-level feedback - **Schema Validation**: Automatic request/response validation
- **Better Error Messages**: Detailed validation errors with field-level feedback
## 🛠️ Installation & Setup ## 🛠️ Installation & Setup
### Prerequisites ### Prerequisites
- Python 3.11+
- Conda package manager - Python 3.11+
- Windows OS (currently optimized for Windows) - Conda package manager
- Windows OS (currently optimized for Windows)
### Quick Start ### Quick Start
1. **Clone the Repository** 1. **Clone the Repository**
```bash
git clone <repository-url> ```bash
cd Aniworld git clone <repository-url>
``` cd Aniworld
```
2. **Create and Activate Conda Environment** 2. **Create and Activate Conda Environment**
```bash
conda create -n AniWorld python=3.11 ```bash
conda activate AniWorld conda create -n AniWorld python=3.11
``` conda activate AniWorld
```
3. **Install Dependencies** 3. **Install Dependencies**
```bash
pip install -r requirements.txt ```bash
``` pip install -r requirements.txt
```
4. **Set Environment Variables** 4. **Set Environment Variables**
```bash
# Set your master password (will be hashed automatically) ```bash
set MASTER_PASSWORD=your_secure_password # Set your master password (will be hashed automatically)
``` set MASTER_PASSWORD=your_secure_password
```
5. **Start the FastAPI Server** 5. **Start the FastAPI Server**
```bash
# Development mode with auto-reload ```bash
uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload # Development mode with auto-reload
uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload
# Or use the VS Code task: "Run FastAPI Server"
``` # Or use the VS Code task: "Run FastAPI Server"
```
6. **Access the Application** 6. **Access the Application**
- **Web Interface**: http://localhost:8000 - **Web Interface**: http://localhost:8000
- **API Documentation**: http://localhost:8000/docs - **API Documentation**: http://localhost:8000/docs
- **Alternative API Docs**: http://localhost:8000/redoc - **Alternative API Docs**: http://localhost:8000/redoc
### Alternative: Using VS Code Tasks ### Alternative: Using VS Code Tasks
If you're using VS Code, you can use the pre-configured tasks: If you're using VS Code, you can use the pre-configured tasks:
- `Ctrl+Shift+P` → "Tasks: Run Task" → "Run FastAPI Server"
- `Ctrl+Shift+P` → "Tasks: Run Task" → "Run FastAPI Server"
## 🔧 Configuration ## 🔧 Configuration
### Environment Variables ### Environment Variables
- `MASTER_PASSWORD` - Your master password (will be hashed automatically)
- `MASTER_PASSWORD_HASH` - Pre-hashed password (alternative to MASTER_PASSWORD) - `MASTER_PASSWORD` - Your master password (will be hashed automatically)
- `JWT_SECRET_KEY` - Secret key for JWT token signing (auto-generated if not set) - `MASTER_PASSWORD_HASH` - Pre-hashed password (alternative to MASTER_PASSWORD)
- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) - `JWT_SECRET_KEY` - Secret key for JWT token signing (auto-generated if not set)
- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR)
### Directory Structure ### Directory Structure
``` ```
Aniworld/ Aniworld/
├── src/ ├── src/
@ -123,77 +138,87 @@ Aniworld/
### Authentication ### Authentication
1. **Login to get JWT token**: 1. **Login to get JWT token**:
```bash
curl -X POST "http://localhost:8000/auth/login" \ ```bash
-H "Content-Type: application/json" \ curl -X POST "http://localhost:8000/auth/login" \
-d '{"password": "your_master_password"}' -H "Content-Type: application/json" \
``` -d '{"password": "your_master_password"}'
```
2. **Use token in requests**: 2. **Use token in requests**:
```bash ```bash
curl -X GET "http://localhost:8000/api/anime/search?query=naruto" \ curl -X GET "http://localhost:8000/api/anime/search?query=naruto" \
-H "Authorization: Bearer your_jwt_token_here" -H "Authorization: Bearer your_jwt_token_here"
``` ```
### Key Endpoints ### Key Endpoints
- **Authentication**: `/auth/login`, `/auth/verify`, `/auth/logout` - **Authentication**: `/auth/login`, `/auth/verify`, `/auth/logout`
- **System**: `/health`, `/api/system/config` - **System**: `/health`, `/api/system/config`
- **Anime**: `/api/anime/search`, `/api/anime/{id}` - **Anime**: `/api/anime/search`, `/api/anime/{id}`
- **Episodes**: `/api/episodes/{id}`, `/api/anime/{id}/episodes` - **Episodes**: `/api/episodes/{id}`, `/api/anime/{id}/episodes`
- **Downloads**: `/api/download`, `/api/add_series` - **Downloads**: `/api/download`, `/api/add_series`
For complete API documentation, visit `/docs` when the server is running. For complete API documentation, visit `/docs` when the server is running.
## 🖥️ Web Interface ## 🖥️ Web Interface
### Main Features ### Main Features
- **Dashboard**: Overview of your anime collection and missing episodes
- **Search**: Find and add new anime series to track - **Dashboard**: Overview of your anime collection and missing episodes
- **Downloads**: Manage download queue and monitor progress - **Search**: Find and add new anime series to track
- **Settings**: Configure application preferences - **Downloads**: Manage download queue and monitor progress
- **Settings**: Configure application preferences
### Responsive Design ### Responsive Design
The web interface is fully responsive and supports: The web interface is fully responsive and supports:
- Desktop browsers (Chrome, Firefox, Edge, Safari)
- Mobile devices (iOS Safari, Android Chrome) - Desktop browsers (Chrome, Firefox, Edge, Safari)
- Tablet devices - Mobile devices (iOS Safari, Android Chrome)
- Dark and light themes - Tablet devices
- Dark and light themes
## 🔍 Troubleshooting ## 🔍 Troubleshooting
### Common Issues ### Common Issues
1. **Server won't start** 1. **Server won't start**
- Check that the AniWorld conda environment is activated
- Verify all dependencies are installed: `pip install -r requirements.txt` - Check that the AniWorld conda environment is activated
- Check for port conflicts (default: 8000) - Verify all dependencies are installed: `pip install -r requirements.txt`
- Check for port conflicts (default: 8000)
2. **Authentication errors** 2. **Authentication errors**
- Verify the master password is set correctly
- Check environment variables are properly configured - Verify the master password is set correctly
- Clear browser cache/cookies - Check environment variables are properly configured
- Clear browser cache/cookies
3. **Import errors** 3. **Import errors**
- Ensure all required packages are installed - Ensure all required packages are installed
- Check Python path configuration - Check Python path configuration
- Verify conda environment is activated - Verify conda environment is activated
### Logs ### Logs
Application logs are stored in the `logs/` directory: Application logs are stored in the `logs/` directory:
- `aniworld.log` - General application logs
- `errors.log` - Error-specific logs - `aniworld.log` - General application logs
- `auth_failures.log` - Authentication failure logs - `errors.log` - Error-specific logs
- `auth_failures.log` - Authentication failure logs
## 🚦 Development ## 🚦 Development
### Running in Development Mode ### Running in Development Mode
```bash ```bash
# With auto-reload for development # With auto-reload for development
uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload --log-level debug uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload --log-level debug
``` ```
### Testing ### Testing
```bash ```bash
# Run all tests # Run all tests
python -m pytest tests/ -v python -m pytest tests/ -v
@ -203,6 +228,7 @@ python -m pytest tests/ --cov=src --cov-report=html
``` ```
### Code Quality ### Code Quality
```bash ```bash
# Format code # Format code
black src/ black src/
@ -215,9 +241,9 @@ flake8 src/
## 📚 Documentation ## 📚 Documentation
- **API Documentation**: Available at `/docs` (Swagger UI) and `/redoc` (ReDoc) - **API Documentation**: Available at `/docs` (Swagger UI) and `/redoc` (ReDoc)
- **Migration Guide**: See `API_DOCUMENTATION.md` for detailed migration information - **Migration Guide**: See `API_DOCUMENTATION.md` for detailed migration information
- **FastAPI Specific**: See `src/server/README_FastAPI.md` for server-specific documentation - **FastAPI Specific**: See `src/server/README_FastAPI.md` for server-specific documentation
## 🤝 Contributing ## 🤝 Contributing
@ -233,10 +259,10 @@ This project is licensed under the MIT License - see the LICENSE file for detail
## 🙏 Acknowledgments ## 🙏 Acknowledgments
- FastAPI team for the excellent framework - FastAPI team for the excellent framework
- The original Flask implementation that served as the foundation - The original Flask implementation that served as the foundation
- All contributors and users of the AniWorld project - All contributors and users of the AniWorld project
--- ---
**Note**: This application is for personal use only. Please respect copyright laws and terms of service of content providers. **Note**: This application is for personal use only. Please respect copyright laws and terms of service of content providers.

View File

@ -1,17 +1,13 @@
import sys
import os
import logging
from src.core.SerieScanner import SerieScanner from src.core.SerieScanner import SerieScanner
from src.core.entities.SerieList import SerieList from src.core.entities.SerieList import SerieList
from src.core.providers.provider_factory import Loaders from src.core.providers.provider_factory import Loaders
class SeriesApp: class SeriesApp:
_initialization_count = 0
def __init__(self, directory_to_search: str): def __init__(self, directory_to_search: str):
SeriesApp._initialization_count += 1 # Only show initialization message for the first instance
# Only show initialization message for the first instance
if SeriesApp._initialization_count <= 1: if SeriesApp._initialization_count <= 1:
print("Please wait while initializing...") print("Please wait while initializing...")
@ -27,7 +23,7 @@ class SeriesApp:
def __InitList__(self): def __InitList__(self):
self.series_list = self.List.GetMissingEpisode() self.series_list = self.List.GetMissingEpisode()
def search(self, words :str) -> list: def search(self, words: str) -> list:
return self.loader.Search(words) return self.loader.Search(words)
def download(self, serieFolder: str, season: int, episode: int, key: str, callback) -> bool: def download(self, serieFolder: str, season: int, episode: int, key: str, callback) -> bool:

View File

@ -36,8 +36,10 @@ from pydantic_settings import BaseSettings
# Import our custom middleware # Import our custom middleware
from src.server.web.middleware.fastapi_auth_middleware import AuthMiddleware from src.server.web.middleware.fastapi_auth_middleware import AuthMiddleware
from src.server.web.middleware.fastapi_logging_middleware import (
EnhancedLoggingMiddleware,
)
from src.server.web.middleware.fastapi_validation_middleware import ValidationMiddleware from src.server.web.middleware.fastapi_validation_middleware import ValidationMiddleware
from src.server.web.middleware.fastapi_logging_middleware import EnhancedLoggingMiddleware
# Configure logging # Configure logging
logging.basicConfig( logging.basicConfig(

View File

@ -6,8 +6,9 @@ using FastAPI patterns and dependency injection.
""" """
import logging import logging
from typing import Callable, Optional, Dict, Any from typing import Any, Callable, Dict, Optional
from fastapi import Request, Response, HTTPException, status
from fastapi import HTTPException, Request, Response, status
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse

View File

@ -12,10 +12,11 @@ import json
import logging import logging
import time import time
import traceback import traceback
from typing import Callable, Dict, Any, Optional
from fastapi import Request, Response, HTTPException, status
from fastapi.responses import JSONResponse
from datetime import datetime, timezone from datetime import datetime, timezone
from typing import Any, Callable, Dict, Optional
from fastapi import HTTPException, Request, Response, status
from fastapi.responses import JSONResponse
class EnhancedLoggingMiddleware: class EnhancedLoggingMiddleware:

View File

@ -5,13 +5,14 @@ This module provides middleware for handling request validation logic
using FastAPI patterns and dependency injection. using FastAPI patterns and dependency injection.
""" """
import html
import json import json
import logging import logging
from typing import Callable, Dict, Any, Optional, Union
from fastapi import Request, Response, HTTPException, status
from fastapi.responses import JSONResponse
import html
import re import re
from typing import Any, Callable, Dict, Optional, Union
from fastapi import HTTPException, Request, Response, status
from fastapi.responses import JSONResponse
class ValidationMiddleware: class ValidationMiddleware:

View File

@ -6,12 +6,13 @@ This script provides a convenient way to start the AniWorld FastAPI server
with proper configuration for both development and production environments. with proper configuration for both development and production environments.
""" """
import argparse
import os import os
import sys import sys
import argparse
import uvicorn
from pathlib import Path from pathlib import Path
import uvicorn
# Add the project root to Python path # Add the project root to Python path
project_root = Path(__file__).parent project_root = Path(__file__).parent
sys.path.insert(0, str(project_root)) sys.path.insert(0, str(project_root))