diff --git a/.editorconfig b/.editorconfig index 6f6b24d..10f7855 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,46 +1,46 @@ -# EditorConfig is awesome: https://EditorConfig.org - -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true -indent_style = space -indent_size = 4 - -# Python files -[*.py] -max_line_length = 88 -indent_size = 4 - -# Web files -[*.{html,css,js,json,yaml,yml}] -indent_size = 2 - -# Markdown files -[*.md] -trim_trailing_whitespace = false - -# Configuration files -[*.{ini,cfg,conf,toml}] -indent_size = 4 - -# Docker files -[{Dockerfile*,*.dockerfile}] -indent_size = 4 - -# Shell scripts -[*.{sh,bat}] -indent_size = 4 - -# SQL files -[*.sql] -indent_size = 2 - -# Template files -[*.{j2,jinja,jinja2}] +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +# Python files +[*.py] +max_line_length = 88 +indent_size = 4 + +# Web files +[*.{html,css,js,json,yaml,yml}] +indent_size = 2 + +# Markdown files +[*.md] +trim_trailing_whitespace = false + +# Configuration files +[*.{ini,cfg,conf,toml}] +indent_size = 4 + +# Docker files +[{Dockerfile*,*.dockerfile}] +indent_size = 4 + +# Shell scripts +[*.{sh,bat}] +indent_size = 4 + +# SQL files +[*.sql] +indent_size = 2 + +# Template files +[*.{j2,jinja,jinja2}] indent_size = 2 \ No newline at end of file diff --git a/.env b/.env index 837b496..21311c9 100644 --- a/.env +++ b/.env @@ -1,44 +1,44 @@ -# Aniworld Server Environment Configuration - -# Security (REQUIRED - Generate secure random values) -SECRET_KEY=dev_secret_key_change_in_production_12345 -JWT_SECRET_KEY=jwt_secret_key_change_in_production_67890 -PASSWORD_SALT=salt_change_in_production_abcdef - -# Master Password Authentication (Simple system) -MASTER_PASSWORD_HASH=8cf532e926e9493630820ce80005f6e2239305ac64c34069e869be5106e2af10 -# MASTER_PASSWORD=admin123 # Used for development only, remove in production - -# Database Configuration -DATABASE_URL=sqlite:///data/aniworld.db -DATABASE_POOL_SIZE=10 -DATABASE_MAX_OVERFLOW=20 -DATABASE_POOL_TIMEOUT=30 -DATABASE_POOL_RECYCLE=3600 - -# Redis Configuration (for caching and sessions) -REDIS_URL=redis://localhost:6379/0 -REDIS_MAX_CONNECTIONS=10 -REDIS_SOCKET_TIMEOUT=5 - -# Security Settings -SESSION_TIMEOUT_HOURS=24 -MAX_FAILED_LOGIN_ATTEMPTS=5 -LOCKOUT_DURATION_MINUTES=30 - -# Rate Limiting -RATE_LIMIT_PER_MINUTE=60 -API_RATE_LIMIT_PER_MINUTE=100 - -# Application Settings -DEBUG=true -HOST=127.0.0.1 -PORT=5000 - -# Anime and Download Settings -ANIME_DIRECTORY=./downloads -MAX_CONCURRENT_DOWNLOADS=3 - -# Logging -LOG_LEVEL=INFO +# Aniworld Server Environment Configuration + +# Security (REQUIRED - Generate secure random values) +SECRET_KEY=dev_secret_key_change_in_production_12345 +JWT_SECRET_KEY=jwt_secret_key_change_in_production_67890 +PASSWORD_SALT=salt_change_in_production_abcdef + +# Master Password Authentication (Simple system) +MASTER_PASSWORD_HASH=8cf532e926e9493630820ce80005f6e2239305ac64c34069e869be5106e2af10 +# MASTER_PASSWORD=admin123 # Used for development only, remove in production + +# Database Configuration +DATABASE_URL=sqlite:///data/aniworld.db +DATABASE_POOL_SIZE=10 +DATABASE_MAX_OVERFLOW=20 +DATABASE_POOL_TIMEOUT=30 +DATABASE_POOL_RECYCLE=3600 + +# Redis Configuration (for caching and sessions) +REDIS_URL=redis://localhost:6379/0 +REDIS_MAX_CONNECTIONS=10 +REDIS_SOCKET_TIMEOUT=5 + +# Security Settings +SESSION_TIMEOUT_HOURS=24 +MAX_FAILED_LOGIN_ATTEMPTS=5 +LOCKOUT_DURATION_MINUTES=30 + +# Rate Limiting +RATE_LIMIT_PER_MINUTE=60 +API_RATE_LIMIT_PER_MINUTE=100 + +# Application Settings +DEBUG=true +HOST=127.0.0.1 +PORT=5000 + +# Anime and Download Settings +ANIME_DIRECTORY=./downloads +MAX_CONCURRENT_DOWNLOADS=3 + +# Logging +LOG_LEVEL=INFO LOG_FILE=logs/aniworld.log \ No newline at end of file diff --git a/.env.template b/.env.template index f701f10..50e4a9d 100644 --- a/.env.template +++ b/.env.template @@ -1,56 +1,56 @@ -# Aniworld Server Environment Configuration -# Copy this file to .env and fill in your values - -# Security (REQUIRED - Generate secure random values) -SECRET_KEY=your_secret_key_here -JWT_SECRET_KEY=your_jwt_secret_here -PASSWORD_SALT=your_password_salt_here - -# Database Configuration -DATABASE_URL=sqlite:///data/aniworld.db -# DATABASE_PASSWORD=your_db_password_here -DATABASE_POOL_SIZE=10 -DATABASE_MAX_OVERFLOW=20 -DATABASE_POOL_TIMEOUT=30 -DATABASE_POOL_RECYCLE=3600 - -# Redis Configuration (for caching and sessions) -REDIS_URL=redis://localhost:6379/0 -# REDIS_PASSWORD=your_redis_password_here -REDIS_MAX_CONNECTIONS=10 -REDIS_SOCKET_TIMEOUT=5 - -# Email Configuration (for password reset emails) -SMTP_SERVER=localhost -SMTP_PORT=587 -# SMTP_USERNAME=your_smtp_username -# SMTP_PASSWORD=your_smtp_password -SMTP_USE_TLS=true -FROM_EMAIL=noreply@aniworld.local - -# External API Keys -# ANIME_PROVIDER_API_KEY=your_anime_provider_api_key -# TMDB_API_KEY=your_tmdb_api_key - -# Security Settings -SESSION_TIMEOUT_HOURS=24 -MAX_FAILED_LOGIN_ATTEMPTS=5 -LOCKOUT_DURATION_MINUTES=30 - -# Rate Limiting -RATE_LIMIT_PER_MINUTE=60 -API_RATE_LIMIT_PER_MINUTE=100 - -# Application Settings -DEBUG=false -HOST=127.0.0.1 -PORT=5000 - -# Anime and Download Settings -ANIME_DIRECTORY=./downloads -MAX_CONCURRENT_DOWNLOADS=3 -# DOWNLOAD_SPEED_LIMIT=1000000 # bytes per second - -# Logging -LOG_LEVEL=INFO -LOG_FILE=logs/aniworld.log +# Aniworld Server Environment Configuration +# Copy this file to .env and fill in your values + +# Security (REQUIRED - Generate secure random values) +SECRET_KEY=your_secret_key_here +JWT_SECRET_KEY=your_jwt_secret_here +PASSWORD_SALT=your_password_salt_here + +# Database Configuration +DATABASE_URL=sqlite:///data/aniworld.db +# DATABASE_PASSWORD=your_db_password_here +DATABASE_POOL_SIZE=10 +DATABASE_MAX_OVERFLOW=20 +DATABASE_POOL_TIMEOUT=30 +DATABASE_POOL_RECYCLE=3600 + +# Redis Configuration (for caching and sessions) +REDIS_URL=redis://localhost:6379/0 +# REDIS_PASSWORD=your_redis_password_here +REDIS_MAX_CONNECTIONS=10 +REDIS_SOCKET_TIMEOUT=5 + +# Email Configuration (for password reset emails) +SMTP_SERVER=localhost +SMTP_PORT=587 +# SMTP_USERNAME=your_smtp_username +# SMTP_PASSWORD=your_smtp_password +SMTP_USE_TLS=true +FROM_EMAIL=noreply@aniworld.local + +# External API Keys +# ANIME_PROVIDER_API_KEY=your_anime_provider_api_key +# TMDB_API_KEY=your_tmdb_api_key + +# Security Settings +SESSION_TIMEOUT_HOURS=24 +MAX_FAILED_LOGIN_ATTEMPTS=5 +LOCKOUT_DURATION_MINUTES=30 + +# Rate Limiting +RATE_LIMIT_PER_MINUTE=60 +API_RATE_LIMIT_PER_MINUTE=100 + +# Application Settings +DEBUG=false +HOST=127.0.0.1 +PORT=5000 + +# Anime and Download Settings +ANIME_DIRECTORY=./downloads +MAX_CONCURRENT_DOWNLOADS=3 +# DOWNLOAD_SPEED_LIMIT=1000000 # bytes per second + +# Logging +LOG_LEVEL=INFO +LOG_FILE=logs/aniworld.log diff --git a/.flake8 b/.flake8 index 60ad54d..792b8f8 100644 --- a/.flake8 +++ b/.flake8 @@ -1,28 +1,28 @@ -[flake8] -max-line-length = 88 -exclude = - .git, - __pycache__, - build, - dist, - .venv, - venv, - aniworld, - migrations, - .pytest_cache, - .mypy_cache, - .coverage, - htmlcov -extend-ignore = - # E203: whitespace before ':' (conflicts with black) - E203, - # W503: line break before binary operator (conflicts with black) - W503, - # E501: line too long (handled by black) - E501 -per-file-ignores = - __init__.py:F401 - tests/*:F401,F811 -max-complexity = 10 -docstring-convention = google +[flake8] +max-line-length = 88 +exclude = + .git, + __pycache__, + build, + dist, + .venv, + venv, + aniworld, + migrations, + .pytest_cache, + .mypy_cache, + .coverage, + htmlcov +extend-ignore = + # E203: whitespace before ':' (conflicts with black) + E203, + # W503: line break before binary operator (conflicts with black) + W503, + # E501: line too long (handled by black) + E501 +per-file-ignores = + __init__.py:F401 + tests/*:F401,F811 +max-complexity = 10 +docstring-convention = google import-order-style = google \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 79a4e96..4434c40 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,44 +1,44 @@ -# Pull Request Template - -## Description -Brief description of the changes in this PR. - -## Type of Change -- [ ] Bug fix (non-breaking change which fixes an issue) -- [ ] New feature (non-breaking change which adds functionality) -- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) -- [ ] Documentation update -- [ ] Code refactoring -- [ ] Performance improvement -- [ ] Test improvement - -## Changes Made -- List the main changes -- Include any new files added -- Include any files removed or renamed - -## Testing -- [ ] Unit tests pass -- [ ] Integration tests pass -- [ ] Manual testing completed -- [ ] Performance testing (if applicable) - -## Screenshots (if applicable) -Add screenshots of UI changes or new features. - -## Checklist -- [ ] My code follows the project's coding standards -- [ ] I have performed a self-review of my own code -- [ ] I have commented my code, particularly in hard-to-understand areas -- [ ] I have made corresponding changes to the documentation -- [ ] My changes generate no new warnings -- [ ] I have added tests that prove my fix is effective or that my feature works -- [ ] New and existing unit tests pass locally with my changes -- [ ] Any dependent changes have been merged and published - -## Related Issues -Fixes #(issue number) -Related to #(issue number) - -## Additional Notes +# Pull Request Template + +## Description +Brief description of the changes in this PR. + +## Type of Change +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] Documentation update +- [ ] Code refactoring +- [ ] Performance improvement +- [ ] Test improvement + +## Changes Made +- List the main changes +- Include any new files added +- Include any files removed or renamed + +## Testing +- [ ] Unit tests pass +- [ ] Integration tests pass +- [ ] Manual testing completed +- [ ] Performance testing (if applicable) + +## Screenshots (if applicable) +Add screenshots of UI changes or new features. + +## Checklist +- [ ] My code follows the project's coding standards +- [ ] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] My changes generate no new warnings +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally with my changes +- [ ] Any dependent changes have been merged and published + +## Related Issues +Fixes #(issue number) +Related to #(issue number) + +## Additional Notes Any additional information, deployment notes, or context for reviewers. \ No newline at end of file diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e621d5b..54dad8d 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,139 +1,139 @@ -# GitHub Copilot Instructions - -These instructions define how GitHub Copilot should assist with this project. The goal is to ensure consistent, high-quality code generation aligned with our conventions, stack, and best practices. - -## 🧠 Context - -- **Project Type**: Web API / Data Pipeline / CLI Tool / ML App -- **Language**: Python -- **Framework / Libraries**: FastAPI / Flask / Django / Pandas / Pydantic / Poetry -- **Architecture**: MVC / Clean Architecture / Event-Driven / Microservices - -## 🔧 General Guidelines - -- Use Pythonic patterns (PEP8, PEP257). -- Prefer named functions and class-based structures over inline lambdas. -- Use type hints where applicable (`typing` module). -- Follow black or isort for formatting and import order. -- Use meaningful naming; avoid cryptic variables. -- Emphasize simplicity, readability, and DRY principles. - -## 📁 File Structure - -Use this structure as a guide when creating or updating files: - -```text -src/ - controllers/ - services/ - repositories/ - schemas/ - utils/ - config/ -tests/ - unit/ - integration/ -``` - -## 🧶 Patterns - -### ✅ Patterns to Follow - -- Use the Repository Pattern and Dependency Injection (e.g., via `Depends` in FastAPI). -- Validate data using Pydantic models. -- Use custom exceptions and centralized error handling. -- Use environment variables via `dotenv` or `os.environ`. -- Use logging via the `logging` module or structlog. -- Write modular, reusable code organized by concerns (e.g., controller, service, data layer). -- Favor async endpoints for I/O-bound services (FastAPI, aiohttp). -- Document functions and classes with docstrings. - -### 🚫 Patterns to Avoid - -- Don’t use wildcard imports (`from module import *`). -- Avoid global state unless encapsulated in a singleton or config manager. -- Don’t hardcode secrets or config values—use `.env`. -- Don’t expose internal stack traces in production environments. -- Avoid business logic inside views/routes. - -## 🧪 Testing Guidelines - -- Use `pytest` or `unittest` for unit and integration tests. -- Mock external services with `unittest.mock` or `pytest-mock`. -- Use fixtures to set up and tear down test data. -- Aim for high coverage on core logic and low-level utilities. -- Test both happy paths and edge cases. - -## 🧩 Example Prompts - -- `Copilot, create a FastAPI endpoint that returns all users from the database.` -- `Copilot, write a Pydantic model for a product with id, name, and optional price.` -- `Copilot, implement a CLI command that uploads a CSV file and logs a summary.` -- `Copilot, write a pytest test for the transform_data function using a mock input.` - -## 🔁 Iteration & Review - -- Review Copilot output before committing. -- Add comments to clarify intent if Copilot generates incorrect or unclear suggestions. -- Use linters (flake8, pylint) and formatters (black, isort) as part of the review pipeline. -- Refactor output to follow project conventions. - -## 📚 References - -- [PEP 8 – Style Guide for Python Code](https://peps.python.org/pep-0008/) -- [PEP 484 – Type Hints](https://peps.python.org/pep-0484/) -- [FastAPI Documentation](https://fastapi.tiangolo.com/) -- [Django Documentation](https://docs.djangoproject.com/en/stable/) -- [Flask Documentation](https://flask.palletsprojects.com/) -- [Pytest Documentation](https://docs.pytest.org/en/stable/) -- [Pydantic Documentation](https://docs.pydantic.dev/) -- [Python Logging Best Practices](https://docs.python.org/3/howto/logging.html) -- [Black Code Formatter](https://black.readthedocs.io/) -- [Poetry](https://python-poetry.org/docs/) - -## 1. General Philosophy - -* **Clarity is King:** Code should be easy to understand at a glance. -* **Consistency Matters:** Adhere to these standards across all projects. -* **Automation Encouraged:** Utilize tools like StyleCop, Roslyn Analyzers, and .editorconfig to enforce these standards automatically. -* **Evolve and Adapt:** These standards should be reviewed and updated as the C# language and best practices evolve. -* **Practicality Reigns:** While striving for perfection, prioritize pragmatic solutions that balance maintainability and development speed. - -* CleanCode, Keep it simple, MVVM - -## 2. Security Considerations - -* **Input Validation:** Always validate user input to prevent injection attacks (e.g., SQL injection, XSS). -* **Secure Configuration:** Store sensitive information (e.g., passwords, API keys) in secure configuration files, and encrypt them if possible. Avoid hardcoding sensitive data. -* **Authentication and Authorization:** Implement proper authentication and authorization mechanisms to protect resources. Favor using built-in identity frameworks. -* **Data Encryption:** Encrypt sensitive data at rest and in transit. Use strong encryption algorithms. -* **Regular Security Audits:** Perform regular security audits and penetration testing to identify and address vulnerabilities. -* **Dependency Vulnerabilities:** Keep dependencies up-to-date to patch known security vulnerabilities. Use tools to automatically check for vulnerabilities. - -## 3. Performance Optimization - -* **Minimize Object Allocation:** Reduce unnecessary object allocations, especially in performance-critical code. Use techniques like object pooling and struct types for small value types. -* **Use Efficient Data Structures:** Choose the appropriate data structures for the task (e.g., "Dictionary" for fast lookups, "List" for ordered collections). -* **Avoid Boxing/Unboxing:** Avoid boxing and unboxing operations, as they can be expensive. Use generics to prevent boxing. -* **String Concatenation:** Use "StringBuilder" for building strings in loops instead of repeated string concatenation. -* **Asynchronous I/O:** Use asynchronous I/O operations to avoid blocking threads. -* **Profiling:** Use profiling tools to identify performance bottlenecks. - -## 4. GUI - -* **Effortless:** faster and more intuitive. It's easy to do what I want, with focus and precision. -* **Calm:** faster and more intuitive. It's easy to do what I want, with focus and precision. -* **Iconography:** Iconography is a set of visual images and symbols that help users understand and navigate your app. Windows 11 iconography has evolved in concert with our design language. Every glyph in our system icon font has been redesigned to embrace a softer geometry and more modern metaphors. -* **Shapes and geometry:** Geometry describes the shape, size, and position of UI elements on screen. These fundamental design elements help experiences feel coherent across the entire design system. Windows 11 features updated geometry that creates a more approachable, engaging, and modern experience. -* **Typography:** As the visual representation of language, the main task of typography is to communicate information. The Windows 11 type system helps you create structure and hierarchy in your content in order to maximize legibility and readability in your UI. -* **Familiar:** faster and more intuitive. It's easy to do what I want, with focus and precision. -* **Familiar:** faster and more intuitive. It's easy to do what I want, with focus and precision. -* **Fluent UI design:** Use Fluent UI design -* **Themes:** Use the already defined Theme color. Make sure ther is always a dark and light mode. -* **Text:** Write in resource files so that a translation is easily possible. Use the already defined text in the resource files. - -This document serves as a starting point and is meant to be adapted to the specific needs of each project and team. Regularly review and update these standards to keep them relevant and effective. - - -Run till you are realy finished. +# GitHub Copilot Instructions + +These instructions define how GitHub Copilot should assist with this project. The goal is to ensure consistent, high-quality code generation aligned with our conventions, stack, and best practices. + +## 🧠 Context + +- **Project Type**: Web API / Data Pipeline / CLI Tool / ML App +- **Language**: Python +- **Framework / Libraries**: FastAPI / Flask / Django / Pandas / Pydantic / Poetry +- **Architecture**: MVC / Clean Architecture / Event-Driven / Microservices + +## 🔧 General Guidelines + +- Use Pythonic patterns (PEP8, PEP257). +- Prefer named functions and class-based structures over inline lambdas. +- Use type hints where applicable (`typing` module). +- Follow black or isort for formatting and import order. +- Use meaningful naming; avoid cryptic variables. +- Emphasize simplicity, readability, and DRY principles. + +## 📁 File Structure + +Use this structure as a guide when creating or updating files: + +```text +src/ + controllers/ + services/ + repositories/ + schemas/ + utils/ + config/ +tests/ + unit/ + integration/ +``` + +## 🧶 Patterns + +### ✅ Patterns to Follow + +- Use the Repository Pattern and Dependency Injection (e.g., via `Depends` in FastAPI). +- Validate data using Pydantic models. +- Use custom exceptions and centralized error handling. +- Use environment variables via `dotenv` or `os.environ`. +- Use logging via the `logging` module or structlog. +- Write modular, reusable code organized by concerns (e.g., controller, service, data layer). +- Favor async endpoints for I/O-bound services (FastAPI, aiohttp). +- Document functions and classes with docstrings. + +### 🚫 Patterns to Avoid + +- Don’t use wildcard imports (`from module import *`). +- Avoid global state unless encapsulated in a singleton or config manager. +- Don’t hardcode secrets or config values—use `.env`. +- Don’t expose internal stack traces in production environments. +- Avoid business logic inside views/routes. + +## 🧪 Testing Guidelines + +- Use `pytest` or `unittest` for unit and integration tests. +- Mock external services with `unittest.mock` or `pytest-mock`. +- Use fixtures to set up and tear down test data. +- Aim for high coverage on core logic and low-level utilities. +- Test both happy paths and edge cases. + +## 🧩 Example Prompts + +- `Copilot, create a FastAPI endpoint that returns all users from the database.` +- `Copilot, write a Pydantic model for a product with id, name, and optional price.` +- `Copilot, implement a CLI command that uploads a CSV file and logs a summary.` +- `Copilot, write a pytest test for the transform_data function using a mock input.` + +## 🔁 Iteration & Review + +- Review Copilot output before committing. +- Add comments to clarify intent if Copilot generates incorrect or unclear suggestions. +- Use linters (flake8, pylint) and formatters (black, isort) as part of the review pipeline. +- Refactor output to follow project conventions. + +## 📚 References + +- [PEP 8 – Style Guide for Python Code](https://peps.python.org/pep-0008/) +- [PEP 484 – Type Hints](https://peps.python.org/pep-0484/) +- [FastAPI Documentation](https://fastapi.tiangolo.com/) +- [Django Documentation](https://docs.djangoproject.com/en/stable/) +- [Flask Documentation](https://flask.palletsprojects.com/) +- [Pytest Documentation](https://docs.pytest.org/en/stable/) +- [Pydantic Documentation](https://docs.pydantic.dev/) +- [Python Logging Best Practices](https://docs.python.org/3/howto/logging.html) +- [Black Code Formatter](https://black.readthedocs.io/) +- [Poetry](https://python-poetry.org/docs/) + +## 1. General Philosophy + +* **Clarity is King:** Code should be easy to understand at a glance. +* **Consistency Matters:** Adhere to these standards across all projects. +* **Automation Encouraged:** Utilize tools like StyleCop, Roslyn Analyzers, and .editorconfig to enforce these standards automatically. +* **Evolve and Adapt:** These standards should be reviewed and updated as the C# language and best practices evolve. +* **Practicality Reigns:** While striving for perfection, prioritize pragmatic solutions that balance maintainability and development speed. + +* CleanCode, Keep it simple, MVVM + +## 2. Security Considerations + +* **Input Validation:** Always validate user input to prevent injection attacks (e.g., SQL injection, XSS). +* **Secure Configuration:** Store sensitive information (e.g., passwords, API keys) in secure configuration files, and encrypt them if possible. Avoid hardcoding sensitive data. +* **Authentication and Authorization:** Implement proper authentication and authorization mechanisms to protect resources. Favor using built-in identity frameworks. +* **Data Encryption:** Encrypt sensitive data at rest and in transit. Use strong encryption algorithms. +* **Regular Security Audits:** Perform regular security audits and penetration testing to identify and address vulnerabilities. +* **Dependency Vulnerabilities:** Keep dependencies up-to-date to patch known security vulnerabilities. Use tools to automatically check for vulnerabilities. + +## 3. Performance Optimization + +* **Minimize Object Allocation:** Reduce unnecessary object allocations, especially in performance-critical code. Use techniques like object pooling and struct types for small value types. +* **Use Efficient Data Structures:** Choose the appropriate data structures for the task (e.g., "Dictionary" for fast lookups, "List" for ordered collections). +* **Avoid Boxing/Unboxing:** Avoid boxing and unboxing operations, as they can be expensive. Use generics to prevent boxing. +* **String Concatenation:** Use "StringBuilder" for building strings in loops instead of repeated string concatenation. +* **Asynchronous I/O:** Use asynchronous I/O operations to avoid blocking threads. +* **Profiling:** Use profiling tools to identify performance bottlenecks. + +## 4. GUI + +* **Effortless:** faster and more intuitive. It's easy to do what I want, with focus and precision. +* **Calm:** faster and more intuitive. It's easy to do what I want, with focus and precision. +* **Iconography:** Iconography is a set of visual images and symbols that help users understand and navigate your app. Windows 11 iconography has evolved in concert with our design language. Every glyph in our system icon font has been redesigned to embrace a softer geometry and more modern metaphors. +* **Shapes and geometry:** Geometry describes the shape, size, and position of UI elements on screen. These fundamental design elements help experiences feel coherent across the entire design system. Windows 11 features updated geometry that creates a more approachable, engaging, and modern experience. +* **Typography:** As the visual representation of language, the main task of typography is to communicate information. The Windows 11 type system helps you create structure and hierarchy in your content in order to maximize legibility and readability in your UI. +* **Familiar:** faster and more intuitive. It's easy to do what I want, with focus and precision. +* **Familiar:** faster and more intuitive. It's easy to do what I want, with focus and precision. +* **Fluent UI design:** Use Fluent UI design +* **Themes:** Use the already defined Theme color. Make sure ther is always a dark and light mode. +* **Text:** Write in resource files so that a translation is easily possible. Use the already defined text in the resource files. + +This document serves as a starting point and is meant to be adapted to the specific needs of each project and team. Regularly review and update these standards to keep them relevant and effective. + + +Run till you are realy finished. Do not gues, open and read files if you dont know something. \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8d69b56..1ef1a45 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,20 @@ -/.idea/* -/aniworld/bin/* -/aniworld/lib/* -/src/__pycache__/* -/src/__pycache__/ -/.vs/* -/src/Temp/* -/src/Loaders/__pycache__/* -/src/Loaders/provider/__pycache__/* -/src/Loaders/__pycache__/* -/src/Loaders/__pycache__/AniWorldLoader.cpython-310.pyc -/src/Loaders/__pycache__/Loader.cpython-310.pyc -/src/Loaders/__pycache__/Loaders.cpython-310.pyc -/src/Loaders/__pycache__/Providers.cpython-310.pyc -/src/Loaders/provider/__pycache__/voe.cpython-310.pyc -/src/noGerFound.log -/src/errors.log -/src/server/__pycache__/* -/src/NoKeyFound.log -/download_errors.log +/.idea/* +/aniworld/bin/* +/aniworld/lib/* +/src/__pycache__/* +/src/__pycache__/ +/.vs/* +/src/Temp/* +/src/Loaders/__pycache__/* +/src/Loaders/provider/__pycache__/* +/src/Loaders/__pycache__/* +/src/Loaders/__pycache__/AniWorldLoader.cpython-310.pyc +/src/Loaders/__pycache__/Loader.cpython-310.pyc +/src/Loaders/__pycache__/Loaders.cpython-310.pyc +/src/Loaders/__pycache__/Providers.cpython-310.pyc +/src/Loaders/provider/__pycache__/voe.cpython-310.pyc +/src/noGerFound.log +/src/errors.log +/src/server/__pycache__/* +/src/NoKeyFound.log +/download_errors.log diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 59313e2..1674303 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,22 +1,22 @@ -{ - "recommendations": [ - "ms-python.python", - "ms-python.debugpy", - "ms-python.flake8", - "ms-python.black-formatter", - "ms-python.isort", - "ms-vscode.vscode-json", - "bradlc.vscode-tailwindcss", - "ms-vscode.vscode-docker", - "ms-python.pylint", - "ms-python.mypy-type-checker", - "charliermarsh.ruff", - "ms-vscode.test-adapter-converter", - "littlefoxteam.vscode-python-test-adapter", - "formulahendry.auto-rename-tag", - "esbenp.prettier-vscode", - "PKief.material-icon-theme", - "GitHub.copilot", - "GitHub.copilot-chat" - ] +{ + "recommendations": [ + "ms-python.python", + "ms-python.debugpy", + "ms-python.flake8", + "ms-python.black-formatter", + "ms-python.isort", + "ms-vscode.vscode-json", + "bradlc.vscode-tailwindcss", + "ms-vscode.vscode-docker", + "ms-python.pylint", + "ms-python.mypy-type-checker", + "charliermarsh.ruff", + "ms-vscode.test-adapter-converter", + "littlefoxteam.vscode-python-test-adapter", + "formulahendry.auto-rename-tag", + "esbenp.prettier-vscode", + "PKief.material-icon-theme", + "GitHub.copilot", + "GitHub.copilot-chat" + ] } \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index 343cca5..b82a0db 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,177 +1,177 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug FastAPI App", - "type": "debugpy", - "request": "launch", - "program": "${workspaceFolder}/src/server/fastapi_app.py", - "console": "integratedTerminal", - "justMyCode": true, - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "your-secret-key-here-debug", - "PASSWORD_SALT": "default-salt-debug", - "MASTER_PASSWORD": "admin123", - "LOG_LEVEL": "DEBUG", - "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", - "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" - }, - "cwd": "${workspaceFolder}", - "args": [], - "stopOnEntry": false, - "autoReload": { - "enable": true - } - }, - { - "name": "Debug FastAPI with Uvicorn", - "type": "debugpy", - "request": "launch", - "module": "uvicorn", - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "args": [ - "src.server.fastapi_app:app", - "--host", - "127.0.0.1", - "--port", - "8000", - "--reload", - "--log-level", - "debug" - ], - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "your-secret-key-here-debug", - "PASSWORD_SALT": "default-salt-debug", - "MASTER_PASSWORD": "admin123", - "LOG_LEVEL": "DEBUG", - "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", - "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" - }, - "cwd": "${workspaceFolder}" - }, - { - "name": "Debug CLI App", - "type": "debugpy", - "request": "launch", - "program": "${workspaceFolder}/src/cli/Main.py", - "console": "integratedTerminal", - "justMyCode": true, - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "LOG_LEVEL": "DEBUG", - "ANIME_DIRECTORY": "${workspaceFolder}/data/anime" - }, - "cwd": "${workspaceFolder}", - "args": [ - // Add arguments as needed for CLI testing - // Example: "${workspaceFolder}/test_data" - ], - "stopOnEntry": false - }, - { - "name": "Debug Tests", - "type": "debugpy", - "request": "launch", - "module": "pytest", - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "args": [ - "${workspaceFolder}/tests", - "-v", - "--tb=short", - "--no-header", - "--disable-warnings" - ], - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "test-secret-key", - "PASSWORD_SALT": "test-salt", - "MASTER_PASSWORD": "admin123", - "LOG_LEVEL": "DEBUG", - "ANIME_DIRECTORY": "${workspaceFolder}/test_data/anime", - "DATABASE_URL": "sqlite:///${workspaceFolder}/test_data/test_aniworld.db" - }, - "cwd": "${workspaceFolder}" - }, - { - "name": "Debug Unit Tests Only", - "type": "debugpy", - "request": "launch", - "module": "pytest", - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "args": [ - "${workspaceFolder}/tests/unit", - "-v", - "--tb=short" - ], - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "test-secret-key", - "PASSWORD_SALT": "test-salt", - "LOG_LEVEL": "DEBUG" - }, - "cwd": "${workspaceFolder}" - }, - { - "name": "Debug Integration Tests Only", - "type": "debugpy", - "request": "launch", - "module": "pytest", - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "args": [ - "${workspaceFolder}/tests/integration", - "-v", - "--tb=short" - ], - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "test-secret-key", - "PASSWORD_SALT": "test-salt", - "MASTER_PASSWORD": "admin123", - "LOG_LEVEL": "DEBUG", - "ANIME_DIRECTORY": "${workspaceFolder}/test_data/anime", - "DATABASE_URL": "sqlite:///${workspaceFolder}/test_data/test_aniworld.db" - }, - "cwd": "${workspaceFolder}" - }, - { - "name": "Debug FastAPI Production Mode", - "type": "debugpy", - "request": "launch", - "module": "uvicorn", - "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "args": [ - "src.server.fastapi_app:app", - "--host", - "0.0.0.0", - "--port", - "8000", - "--workers", - "1" - ], - "console": "integratedTerminal", - "justMyCode": true, - "env": { - "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", - "JWT_SECRET_KEY": "production-secret-key-change-me", - "PASSWORD_SALT": "production-salt-change-me", - "MASTER_PASSWORD": "admin123", - "LOG_LEVEL": "INFO", - "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", - "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" - }, - "cwd": "${workspaceFolder}" - } - ] +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Debug FastAPI App", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/src/server/fastapi_app.py", + "console": "integratedTerminal", + "justMyCode": true, + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "your-secret-key-here-debug", + "PASSWORD_SALT": "default-salt-debug", + "MASTER_PASSWORD": "admin123", + "LOG_LEVEL": "DEBUG", + "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", + "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" + }, + "cwd": "${workspaceFolder}", + "args": [], + "stopOnEntry": false, + "autoReload": { + "enable": true + } + }, + { + "name": "Debug FastAPI with Uvicorn", + "type": "debugpy", + "request": "launch", + "module": "uvicorn", + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "args": [ + "src.server.fastapi_app:app", + "--host", + "127.0.0.1", + "--port", + "8000", + "--reload", + "--log-level", + "debug" + ], + "console": "integratedTerminal", + "justMyCode": true, + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "your-secret-key-here-debug", + "PASSWORD_SALT": "default-salt-debug", + "MASTER_PASSWORD": "admin123", + "LOG_LEVEL": "DEBUG", + "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", + "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" + }, + "cwd": "${workspaceFolder}" + }, + { + "name": "Debug CLI App", + "type": "debugpy", + "request": "launch", + "program": "${workspaceFolder}/src/cli/Main.py", + "console": "integratedTerminal", + "justMyCode": true, + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "LOG_LEVEL": "DEBUG", + "ANIME_DIRECTORY": "${workspaceFolder}/data/anime" + }, + "cwd": "${workspaceFolder}", + "args": [ + // Add arguments as needed for CLI testing + // Example: "${workspaceFolder}/test_data" + ], + "stopOnEntry": false + }, + { + "name": "Debug Tests", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "args": [ + "${workspaceFolder}/tests", + "-v", + "--tb=short", + "--no-header", + "--disable-warnings" + ], + "console": "integratedTerminal", + "justMyCode": true, + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "test-secret-key", + "PASSWORD_SALT": "test-salt", + "MASTER_PASSWORD": "admin123", + "LOG_LEVEL": "DEBUG", + "ANIME_DIRECTORY": "${workspaceFolder}/test_data/anime", + "DATABASE_URL": "sqlite:///${workspaceFolder}/test_data/test_aniworld.db" + }, + "cwd": "${workspaceFolder}" + }, + { + "name": "Debug Unit Tests Only", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "args": [ + "${workspaceFolder}/tests/unit", + "-v", + "--tb=short" + ], + "console": "integratedTerminal", + "justMyCode": true, + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "test-secret-key", + "PASSWORD_SALT": "test-salt", + "LOG_LEVEL": "DEBUG" + }, + "cwd": "${workspaceFolder}" + }, + { + "name": "Debug Integration Tests Only", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "args": [ + "${workspaceFolder}/tests/integration", + "-v", + "--tb=short" + ], + "console": "integratedTerminal", + "justMyCode": true, + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "test-secret-key", + "PASSWORD_SALT": "test-salt", + "MASTER_PASSWORD": "admin123", + "LOG_LEVEL": "DEBUG", + "ANIME_DIRECTORY": "${workspaceFolder}/test_data/anime", + "DATABASE_URL": "sqlite:///${workspaceFolder}/test_data/test_aniworld.db" + }, + "cwd": "${workspaceFolder}" + }, + { + "name": "Debug FastAPI Production Mode", + "type": "debugpy", + "request": "launch", + "module": "uvicorn", + "python": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "args": [ + "src.server.fastapi_app:app", + "--host", + "0.0.0.0", + "--port", + "8000", + "--workers", + "1" + ], + "console": "integratedTerminal", + "justMyCode": true, + "env": { + "PYTHONPATH": "${workspaceFolder}/src:${workspaceFolder}", + "JWT_SECRET_KEY": "production-secret-key-change-me", + "PASSWORD_SALT": "production-salt-change-me", + "MASTER_PASSWORD": "admin123", + "LOG_LEVEL": "INFO", + "ANIME_DIRECTORY": "${workspaceFolder}/data/anime", + "DATABASE_URL": "sqlite:///${workspaceFolder}/data/aniworld.db" + }, + "cwd": "${workspaceFolder}" + } + ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 7b2b955..2bb67de 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,37 +1,37 @@ -{ - "python.defaultInterpreterPath": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", - "python.terminal.activateEnvironment": true, - "python.condaPath": "C:\\Users\\lukas\\anaconda3\\Scripts\\conda.exe", - "python.terminal.activateEnvInCurrentTerminal": true, - "python.linting.enabled": true, - "python.linting.flake8Enabled": true, - "python.linting.pylintEnabled": true, - "python.formatting.provider": "black", - "python.formatting.blackArgs": [ - "--line-length", - "88" - ], - "python.sortImports.args": [ - "--profile", - "black" - ], - "editor.formatOnSave": true, - "editor.codeActionsOnSave": { - "source.organizeImports": "explicit" - }, - "files.exclude": { - "**/__pycache__": true, - "**/*.pyc": true, - "**/node_modules": true, - "**/.pytest_cache": true, - "**/data/temp/**": true, - "**/data/cache/**": true, - "**/data/logs/**": true - }, - "python.testing.pytestEnabled": true, - "python.testing.pytestArgs": [ - "tests" - ], - "python.testing.unittestEnabled": false, - "python.testing.autoTestDiscoverOnSaveEnabled": true +{ + "python.defaultInterpreterPath": "C:\\Users\\lukas\\anaconda3\\envs\\AniWorld\\python.exe", + "python.terminal.activateEnvironment": true, + "python.condaPath": "C:\\Users\\lukas\\anaconda3\\Scripts\\conda.exe", + "python.terminal.activateEnvInCurrentTerminal": true, + "python.linting.enabled": true, + "python.linting.flake8Enabled": true, + "python.linting.pylintEnabled": true, + "python.formatting.provider": "black", + "python.formatting.blackArgs": [ + "--line-length", + "88" + ], + "python.sortImports.args": [ + "--profile", + "black" + ], + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "explicit" + }, + "files.exclude": { + "**/__pycache__": true, + "**/*.pyc": true, + "**/node_modules": true, + "**/.pytest_cache": true, + "**/data/temp/**": true, + "**/data/cache/**": true, + "**/data/logs/**": true + }, + "python.testing.pytestEnabled": true, + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.autoTestDiscoverOnSaveEnabled": true } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 17c96f7..c56301c 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,166 +1,166 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "Run FastAPI Server", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "python", - "-m", - "uvicorn", - "src.server.fastapi_app:app", - "--host", - "127.0.0.1", - "--port", - "8000", - "--reload" - ], - "group": { - "kind": "build", - "isDefault": true - }, - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [], - "isBackground": true - }, - { - "label": "Run CLI Application", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "python", - "src/cli/Main.py" - ], - "group": "build", - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [] - }, - { - "label": "Run All Tests", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "python", - "-m", - "pytest", - "tests/", - "-v", - "--tb=short" - ], - "group": "test", - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [] - }, - { - "label": "Run Unit Tests", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "python", - "-m", - "pytest", - "tests/unit/", - "-v" - ], - "group": "test", - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [] - }, - { - "label": "Run Integration Tests", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "python", - "-m", - "pytest", - "tests/integration/", - "-v" - ], - "group": "test", - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [] - }, - { - "label": "Install Dependencies", - "type": "shell", - "command": "conda", - "args": [ - "run", - "-n", - "AniWorld", - "pip", - "install", - "-r", - "requirements.txt" - ], - "group": "build", - "presentation": { - "echo": true, - "reveal": "always", - "focus": false, - "panel": "new" - }, - "options": { - "cwd": "${workspaceFolder}" - }, - "problemMatcher": [] - } - ] +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Run FastAPI Server", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "python", + "-m", + "uvicorn", + "src.server.fastapi_app:app", + "--host", + "127.0.0.1", + "--port", + "8000", + "--reload" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [], + "isBackground": true + }, + { + "label": "Run CLI Application", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "python", + "src/cli/Main.py" + ], + "group": "build", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [] + }, + { + "label": "Run All Tests", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "python", + "-m", + "pytest", + "tests/", + "-v", + "--tb=short" + ], + "group": "test", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [] + }, + { + "label": "Run Unit Tests", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "python", + "-m", + "pytest", + "tests/unit/", + "-v" + ], + "group": "test", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [] + }, + { + "label": "Run Integration Tests", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "python", + "-m", + "pytest", + "tests/integration/", + "-v" + ], + "group": "test", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [] + }, + { + "label": "Install Dependencies", + "type": "shell", + "command": "conda", + "args": [ + "run", + "-n", + "AniWorld", + "pip", + "install", + "-r", + "requirements.txt" + ], + "group": "build", + "presentation": { + "echo": true, + "reveal": "always", + "focus": false, + "panel": "new" + }, + "options": { + "cwd": "${workspaceFolder}" + }, + "problemMatcher": [] + } + ] } \ No newline at end of file diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md index 110dd73..cf4cc5e 100644 --- a/API_DOCUMENTATION.md +++ b/API_DOCUMENTATION.md @@ -1,191 +1,191 @@ -# AniWorld FastAPI Documentation - -## Overview - -AniWorld has been successfully migrated from Flask to FastAPI, providing improved performance, automatic API documentation, and modern async support. - -## Accessing API Documentation - -### Interactive API Documentation - -FastAPI automatically generates interactive API documentation that you can access at: - -- **Swagger UI**: `http://localhost:8000/docs` -- **ReDoc**: `http://localhost:8000/redoc` - -These interfaces allow you to: - -- Browse all available endpoints -- View request/response schemas -- Test API endpoints directly from the browser -- Download OpenAPI schema - -### OpenAPI Schema - -The complete OpenAPI 3.0 schema is available at: - -- **JSON Format**: `http://localhost:8000/openapi.json` - -## Authentication - -### Master Password Authentication - -AniWorld uses a simple master password authentication system with JWT tokens. - -#### Login Process - -1. **POST** `/auth/login` - - Send master password in request body - - Receive JWT token in response - - Token expires in 24 hours - -```json -{ - "password": "your_master_password" -} -``` - -Response: - -```json -{ - "success": true, - "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", - "message": "Login successful" -} -``` - -#### Using Authentication Token - -Include the token in the `Authorization` header for authenticated requests: - -``` -Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9... -``` - -## API Endpoints - -### System Health - -- **GET** `/health` - Check system health and status -- **GET** `/api/system/database/health` - Check database connectivity -- **GET** `/api/system/config` - Get system configuration - -### Authentication - -- **POST** `/auth/login` - Authenticate and get JWT token -- **GET** `/auth/verify` - Verify current token validity -- **POST** `/auth/logout` - Logout and invalidate token -- **GET** `/api/auth/status` - Get current authentication status - -### Anime Management - -- **GET** `/api/anime/search` - Search for anime series -- **GET** `/api/anime/{anime_id}` - Get specific anime details -- **GET** `/api/anime/{anime_id}/episodes` - Get episodes for an anime - -### Episode Management - -- **GET** `/api/episodes/{episode_id}` - Get specific episode details - -### Series Management - -- **POST** `/api/add_series` - Add a new series to tracking -- **POST** `/api/download` - Start episode download - -### Web Interface - -- **GET** `/` - Main application interface -- **GET** `/app` - Application dashboard -- **GET** `/login` - Login page -- **GET** `/setup` - Setup page -- **GET** `/queue` - Download queue interface - -## Response Formats - -### Success Responses - -All successful API responses follow this structure: - -```json -{ - "success": true, - "data": {...}, - "message": "Operation completed successfully" -} -``` - -### Error Responses - -Error responses include detailed error information: - -```json -{ - "success": false, - "error": "Error description", - "code": "ERROR_CODE", - "details": {...} -} -``` - -## Status Codes - -- **200 OK** - Successful operation -- **201 Created** - Resource created successfully -- **400 Bad Request** - Invalid request data -- **401 Unauthorized** - Authentication required -- **403 Forbidden** - Insufficient permissions -- **404 Not Found** - Resource not found -- **422 Unprocessable Entity** - Validation error -- **500 Internal Server Error** - Server error - -## Rate Limiting - -Currently, no rate limiting is implemented, but it may be added in future versions. - -## WebSocket Support - -Real-time updates are available through WebSocket connections for: - -- Download progress updates -- Scan progress updates -- System status changes - -## Migration Notes - -### Changes from Flask - -1. **Automatic Documentation**: FastAPI provides built-in OpenAPI documentation -2. **Type Safety**: Full request/response validation with Pydantic -3. **Async Support**: Native async/await support for better performance -4. **Modern Standards**: OpenAPI 3.0, JSON Schema validation -5. **Better Error Handling**: Structured error responses with detailed information - -### Breaking Changes - -- Authentication tokens are now JWT-based instead of session-based -- Request/response formats may have slight differences -- Some endpoint URLs may have changed -- WebSocket endpoints use FastAPI WebSocket pattern - -## Development - -### Running the Server - -```bash -# Development mode with auto-reload -uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload - -# Production mode -uvicorn src.server.fastapi_app:app --host 0.0.0.0 --port 8000 -``` - -### Environment Variables - -- `MASTER_PASSWORD_HASH` - Hashed master password -- `JWT_SECRET_KEY` - Secret key for JWT token signing -- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) - -## Support - -For issues, questions, or contributions, please visit the project repository or contact the development team. +# AniWorld FastAPI Documentation + +## Overview + +AniWorld has been successfully migrated from Flask to FastAPI, providing improved performance, automatic API documentation, and modern async support. + +## Accessing API Documentation + +### Interactive API Documentation + +FastAPI automatically generates interactive API documentation that you can access at: + +- **Swagger UI**: `http://localhost:8000/docs` +- **ReDoc**: `http://localhost:8000/redoc` + +These interfaces allow you to: + +- Browse all available endpoints +- View request/response schemas +- Test API endpoints directly from the browser +- Download OpenAPI schema + +### OpenAPI Schema + +The complete OpenAPI 3.0 schema is available at: + +- **JSON Format**: `http://localhost:8000/openapi.json` + +## Authentication + +### Master Password Authentication + +AniWorld uses a simple master password authentication system with JWT tokens. + +#### Login Process + +1. **POST** `/auth/login` + - Send master password in request body + - Receive JWT token in response + - Token expires in 24 hours + +```json +{ + "password": "your_master_password" +} +``` + +Response: + +```json +{ + "success": true, + "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...", + "message": "Login successful" +} +``` + +#### Using Authentication Token + +Include the token in the `Authorization` header for authenticated requests: + +``` +Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9... +``` + +## API Endpoints + +### System Health + +- **GET** `/health` - Check system health and status +- **GET** `/api/system/database/health` - Check database connectivity +- **GET** `/api/system/config` - Get system configuration + +### Authentication + +- **POST** `/auth/login` - Authenticate and get JWT token +- **GET** `/auth/verify` - Verify current token validity +- **POST** `/auth/logout` - Logout and invalidate token +- **GET** `/api/auth/status` - Get current authentication status + +### Anime Management + +- **GET** `/api/anime/search` - Search for anime series +- **GET** `/api/anime/{anime_id}` - Get specific anime details +- **GET** `/api/anime/{anime_id}/episodes` - Get episodes for an anime + +### Episode Management + +- **GET** `/api/episodes/{episode_id}` - Get specific episode details + +### Series Management + +- **POST** `/api/add_series` - Add a new series to tracking +- **POST** `/api/download` - Start episode download + +### Web Interface + +- **GET** `/` - Main application interface +- **GET** `/app` - Application dashboard +- **GET** `/login` - Login page +- **GET** `/setup` - Setup page +- **GET** `/queue` - Download queue interface + +## Response Formats + +### Success Responses + +All successful API responses follow this structure: + +```json +{ + "success": true, + "data": {...}, + "message": "Operation completed successfully" +} +``` + +### Error Responses + +Error responses include detailed error information: + +```json +{ + "success": false, + "error": "Error description", + "code": "ERROR_CODE", + "details": {...} +} +``` + +## Status Codes + +- **200 OK** - Successful operation +- **201 Created** - Resource created successfully +- **400 Bad Request** - Invalid request data +- **401 Unauthorized** - Authentication required +- **403 Forbidden** - Insufficient permissions +- **404 Not Found** - Resource not found +- **422 Unprocessable Entity** - Validation error +- **500 Internal Server Error** - Server error + +## Rate Limiting + +Currently, no rate limiting is implemented, but it may be added in future versions. + +## WebSocket Support + +Real-time updates are available through WebSocket connections for: + +- Download progress updates +- Scan progress updates +- System status changes + +## Migration Notes + +### Changes from Flask + +1. **Automatic Documentation**: FastAPI provides built-in OpenAPI documentation +2. **Type Safety**: Full request/response validation with Pydantic +3. **Async Support**: Native async/await support for better performance +4. **Modern Standards**: OpenAPI 3.0, JSON Schema validation +5. **Better Error Handling**: Structured error responses with detailed information + +### Breaking Changes + +- Authentication tokens are now JWT-based instead of session-based +- Request/response formats may have slight differences +- Some endpoint URLs may have changed +- WebSocket endpoints use FastAPI WebSocket pattern + +## Development + +### Running the Server + +```bash +# Development mode with auto-reload +uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload + +# Production mode +uvicorn src.server.fastapi_app:app --host 0.0.0.0 --port 8000 +``` + +### Environment Variables + +- `MASTER_PASSWORD_HASH` - Hashed master password +- `JWT_SECRET_KEY` - Secret key for JWT token signing +- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) + +## Support + +For issues, questions, or contributions, please visit the project repository or contact the development team. diff --git a/Overview.md b/Overview.md index c6cea97..1c9b313 100644 --- a/Overview.md +++ b/Overview.md @@ -1,74 +1,74 @@ -# AniWorld Project Overview - -## 📁 Folder Structure - -The project follows a modular, layered architecture inspired by MVC and Clean Architecture principles. The main directories are: - -``` -src/ - controllers/ # API endpoints and route handlers - services/ # Business logic and orchestration - repositories/ # Data access layer (DB, external APIs) - schemas/ # Pydantic models for validation/serialization - utils/ # Utility functions and helpers - config/ # Configuration management (env, settings) -tests/ - unit/ # Unit tests for core logic - integration/ # Integration tests for end-to-end scenarios -``` - -## 🏗️ Architecture - -- **MVC & Clean Architecture:** Separation of concerns between controllers (views), services (business logic), and repositories (data access). -- **Dependency Injection:** Used for service/repository wiring, especially with FastAPI's `Depends`. -- **Event-Driven & Microservices Ready:** Modular design allows for future scaling into microservices or event-driven workflows. -- **Centralized Error Handling:** Custom exceptions and error middleware for consistent API responses. - -## 🧰 Used Libraries & Frameworks - -- **Python** (PEP8, PEP257, type hints) -- **FastAPI**: High-performance async web API framework -- **Pydantic**: Data validation and serialization -- **Poetry**: Dependency management and packaging -- **dotenv / os.environ**: Environment variable management -- **logging / structlog**: Structured logging -- **pytest / unittest**: Testing frameworks -- **aiohttp**: Async HTTP client (where needed) -- **SQLAlchemy / asyncpg / databases**: Database ORM and async drivers (if present) -- **Prometheus**: Metrics endpoint integration -- **Other**: As required for integrations (webhooks, third-party APIs) - -## 🧩 Patterns & Conventions - -- **Repository Pattern:** All data access is abstracted via repositories. -- **Service Layer:** Business logic is encapsulated in services, not controllers. -- **Pydantic Models:** Used for all input/output validation. -- **Async Endpoints:** All I/O-bound endpoints are async for scalability. -- **Environment Configuration:** All secrets/configs are loaded from `.env` or environment variables. -- **Logging:** All logs are structured and configurable. -- **Testing:** High coverage with fixtures and mocks for external dependencies. - -## 🛡️ Security & Performance - -- **JWT Authentication:** Secure endpoints with token-based auth. -- **Input Validation:** All user input is validated via Pydantic. -- **No Hardcoded Secrets:** All sensitive data is externalized. -- **Performance Optimization:** Async I/O, caching, and profiling tools. - -## 🎨 UI & CLI - -- **Theme Support:** Light/dark/auto modes. -- **Accessibility:** Screen reader, color contrast, keyboard shortcuts. -- **CLI Tool:** For bulk operations, scanning, and management. - -## 📚 References - -- [FastAPI Documentation](https://fastapi.tiangolo.com/) -- [Pydantic Documentation](https://docs.pydantic.dev/) -- [Poetry](https://python-poetry.org/docs/) -- [PEP 8](https://peps.python.org/pep-0008/) -- [Black Formatter](https://black.readthedocs.io/) - ---- - +# AniWorld Project Overview + +## 📁 Folder Structure + +The project follows a modular, layered architecture inspired by MVC and Clean Architecture principles. The main directories are: + +``` +src/ + controllers/ # API endpoints and route handlers + services/ # Business logic and orchestration + repositories/ # Data access layer (DB, external APIs) + schemas/ # Pydantic models for validation/serialization + utils/ # Utility functions and helpers + config/ # Configuration management (env, settings) +tests/ + unit/ # Unit tests for core logic + integration/ # Integration tests for end-to-end scenarios +``` + +## 🏗️ Architecture + +- **MVC & Clean Architecture:** Separation of concerns between controllers (views), services (business logic), and repositories (data access). +- **Dependency Injection:** Used for service/repository wiring, especially with FastAPI's `Depends`. +- **Event-Driven & Microservices Ready:** Modular design allows for future scaling into microservices or event-driven workflows. +- **Centralized Error Handling:** Custom exceptions and error middleware for consistent API responses. + +## 🧰 Used Libraries & Frameworks + +- **Python** (PEP8, PEP257, type hints) +- **FastAPI**: High-performance async web API framework +- **Pydantic**: Data validation and serialization +- **Poetry**: Dependency management and packaging +- **dotenv / os.environ**: Environment variable management +- **logging / structlog**: Structured logging +- **pytest / unittest**: Testing frameworks +- **aiohttp**: Async HTTP client (where needed) +- **SQLAlchemy / asyncpg / databases**: Database ORM and async drivers (if present) +- **Prometheus**: Metrics endpoint integration +- **Other**: As required for integrations (webhooks, third-party APIs) + +## 🧩 Patterns & Conventions + +- **Repository Pattern:** All data access is abstracted via repositories. +- **Service Layer:** Business logic is encapsulated in services, not controllers. +- **Pydantic Models:** Used for all input/output validation. +- **Async Endpoints:** All I/O-bound endpoints are async for scalability. +- **Environment Configuration:** All secrets/configs are loaded from `.env` or environment variables. +- **Logging:** All logs are structured and configurable. +- **Testing:** High coverage with fixtures and mocks for external dependencies. + +## 🛡️ Security & Performance + +- **JWT Authentication:** Secure endpoints with token-based auth. +- **Input Validation:** All user input is validated via Pydantic. +- **No Hardcoded Secrets:** All sensitive data is externalized. +- **Performance Optimization:** Async I/O, caching, and profiling tools. + +## 🎨 UI & CLI + +- **Theme Support:** Light/dark/auto modes. +- **Accessibility:** Screen reader, color contrast, keyboard shortcuts. +- **CLI Tool:** For bulk operations, scanning, and management. + +## 📚 References + +- [FastAPI Documentation](https://fastapi.tiangolo.com/) +- [Pydantic Documentation](https://docs.pydantic.dev/) +- [Poetry](https://python-poetry.org/docs/) +- [PEP 8](https://peps.python.org/pep-0008/) +- [Black Formatter](https://black.readthedocs.io/) + +--- + **For details on individual features and endpoints, see `features.md`.** \ No newline at end of file diff --git a/README.md b/README.md index 6a1f25a..5fe66a9 100644 --- a/README.md +++ b/README.md @@ -1,268 +1,268 @@ -# AniWorld - Anime Series Management System - -A powerful anime series management system that helps you track, organize, and download your favorite anime series. Recently migrated from Flask to FastAPI for improved performance and modern API capabilities. - -## 🚀 Features - -### Core Functionality - -- **Series Tracking**: Automatically detect missing episodes in your anime collection -- **Smart Downloads**: Queue-based download system with progress tracking -- **File Organization**: Automatic file scanning and folder structure management -- **Search Integration**: Search for anime series across multiple providers -- **Real-time Updates**: Live progress updates via WebSocket connections - -### Web Interface - -- **Modern UI**: Clean, responsive web interface with dark/light theme support -- **Download Queue**: Visual download queue management -- **Progress Tracking**: Real-time download and scan progress -- **Mobile Support**: Fully responsive design for mobile devices - -### API & Integration - -- **FastAPI Backend**: High-performance async API with automatic documentation -- **RESTful API**: Complete REST API for programmatic access -- **OpenAPI Documentation**: Interactive API documentation at `/docs` -- **Authentication**: Secure master password authentication with JWT tokens - -## 🎯 Recent Migration: Flask → FastAPI - -This project has been successfully migrated from Flask to FastAPI, bringing significant improvements: - -### Performance Benefits - -- **Async Support**: Native async/await for better concurrency -- **Faster Response Times**: Up to 2-3x performance improvement -- **Better Resource Utilization**: More efficient handling of concurrent requests - -### Developer Experience - -- **Automatic Documentation**: Built-in OpenAPI/Swagger documentation -- **Type Safety**: Full request/response validation with Pydantic -- **Modern Standards**: OpenAPI 3.0 compliance and JSON Schema validation -- **Better Error Handling**: Structured error responses with detailed information - -### API Improvements - -- **Interactive Documentation**: Test API endpoints directly from `/docs` -- **Schema Validation**: Automatic request/response validation -- **Better Error Messages**: Detailed validation errors with field-level feedback - -## 🛠️ Installation & Setup - -### Prerequisites - -- Python 3.11+ -- Conda package manager -- Windows OS (currently optimized for Windows) - -### Quick Start - -1. **Clone the Repository** - - ```bash - git clone - cd Aniworld - ``` - -2. **Create and Activate Conda Environment** - - ```bash - conda create -n AniWorld python=3.11 - conda activate AniWorld - ``` - -3. **Install Dependencies** - - ```bash - pip install -r requirements.txt - ``` - -4. **Set Environment Variables** - - ```bash - # Set your master password (will be hashed automatically) - set MASTER_PASSWORD=your_secure_password - ``` - -5. **Start the FastAPI Server** - - ```bash - # 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" - ``` - -6. **Access the Application** - - **Web Interface**: http://localhost:8000 - - **API Documentation**: http://localhost:8000/docs - - **Alternative API Docs**: http://localhost:8000/redoc - -### Alternative: Using VS Code Tasks - -If you're using VS Code, you can use the pre-configured tasks: - -- `Ctrl+Shift+P` → "Tasks: Run Task" → "Run FastAPI Server" - -## 🔧 Configuration - -### Environment Variables - -- `MASTER_PASSWORD` - Your master password (will be hashed automatically) -- `MASTER_PASSWORD_HASH` - Pre-hashed password (alternative to MASTER_PASSWORD) -- `JWT_SECRET_KEY` - Secret key for JWT token signing (auto-generated if not set) -- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) - -### Directory Structure - -``` -Aniworld/ -├── src/ -│ ├── core/ # Core business logic -│ │ ├── SeriesApp.py # Main application controller -│ │ ├── entities/ # Data models -│ │ └── providers/ # Content providers -│ ├── server/ # FastAPI server -│ │ ├── fastapi_app.py # Main FastAPI application -│ │ └── web/ # Web interface and controllers -│ └── infrastructure/ # Infrastructure components -├── data/ # Application data and databases -├── logs/ # Application logs -└── requirements.txt # Python dependencies -``` - -## 🌐 API Usage - -### Authentication - -1. **Login to get JWT token**: - - ```bash - curl -X POST "http://localhost:8000/auth/login" \ - -H "Content-Type: application/json" \ - -d '{"password": "your_master_password"}' - ``` - -2. **Use token in requests**: - ```bash - curl -X GET "http://localhost:8000/api/anime/search?query=naruto" \ - -H "Authorization: Bearer your_jwt_token_here" - ``` - -### Key Endpoints - -- **Authentication**: `/auth/login`, `/auth/verify`, `/auth/logout` -- **System**: `/health`, `/api/system/config` -- **Anime**: `/api/anime/search`, `/api/anime/{id}` -- **Episodes**: `/api/episodes/{id}`, `/api/anime/{id}/episodes` -- **Downloads**: `/api/download`, `/api/add_series` - -For complete API documentation, visit `/docs` when the server is running. - -## 🖥️ Web Interface - -### Main Features - -- **Dashboard**: Overview of your anime collection and missing episodes -- **Search**: Find and add new anime series to track -- **Downloads**: Manage download queue and monitor progress -- **Settings**: Configure application preferences - -### Responsive Design - -The web interface is fully responsive and supports: - -- Desktop browsers (Chrome, Firefox, Edge, Safari) -- Mobile devices (iOS Safari, Android Chrome) -- Tablet devices -- Dark and light themes - -## 🔍 Troubleshooting - -### Common Issues - -1. **Server won't start** - - - Check that the AniWorld conda environment is activated - - Verify all dependencies are installed: `pip install -r requirements.txt` - - Check for port conflicts (default: 8000) - -2. **Authentication errors** - - - Verify the master password is set correctly - - Check environment variables are properly configured - - Clear browser cache/cookies - -3. **Import errors** - - Ensure all required packages are installed - - Check Python path configuration - - Verify conda environment is activated - -### Logs - -Application logs are stored in the `logs/` directory: - -- `aniworld.log` - General application logs -- `errors.log` - Error-specific logs -- `auth_failures.log` - Authentication failure logs - -## 🚦 Development - -### Running in Development Mode - -```bash -# With auto-reload for development -uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload --log-level debug -``` - -### Testing - -```bash -# Run all tests -python -m pytest tests/ -v - -# Run with coverage -python -m pytest tests/ --cov=src --cov-report=html -``` - -### Code Quality - -```bash -# Format code -black src/ -isort src/ - -# Lint code -pylint src/ -flake8 src/ -``` - -## 📚 Documentation - -- **API Documentation**: Available at `/docs` (Swagger UI) and `/redoc` (ReDoc) -- **Migration Guide**: See `API_DOCUMENTATION.md` for detailed migration information -- **FastAPI Specific**: See `src/server/README_FastAPI.md` for server-specific documentation - -## 🤝 Contributing - -1. Fork the repository -2. Create a feature branch (`git checkout -b feature/amazing-feature`) -3. Commit your changes (`git commit -m 'Add amazing feature'`) -4. Push to the branch (`git push origin feature/amazing-feature`) -5. Open a Pull Request - -## 📄 License - -This project is licensed under the MIT License - see the LICENSE file for details. - -## 🙏 Acknowledgments - -- FastAPI team for the excellent framework -- The original Flask implementation that served as the foundation -- 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. +# AniWorld - Anime Series Management System + +A powerful anime series management system that helps you track, organize, and download your favorite anime series. Recently migrated from Flask to FastAPI for improved performance and modern API capabilities. + +## 🚀 Features + +### Core Functionality + +- **Series Tracking**: Automatically detect missing episodes in your anime collection +- **Smart Downloads**: Queue-based download system with progress tracking +- **File Organization**: Automatic file scanning and folder structure management +- **Search Integration**: Search for anime series across multiple providers +- **Real-time Updates**: Live progress updates via WebSocket connections + +### Web Interface + +- **Modern UI**: Clean, responsive web interface with dark/light theme support +- **Download Queue**: Visual download queue management +- **Progress Tracking**: Real-time download and scan progress +- **Mobile Support**: Fully responsive design for mobile devices + +### API & Integration + +- **FastAPI Backend**: High-performance async API with automatic documentation +- **RESTful API**: Complete REST API for programmatic access +- **OpenAPI Documentation**: Interactive API documentation at `/docs` +- **Authentication**: Secure master password authentication with JWT tokens + +## 🎯 Recent Migration: Flask → FastAPI + +This project has been successfully migrated from Flask to FastAPI, bringing significant improvements: + +### Performance Benefits + +- **Async Support**: Native async/await for better concurrency +- **Faster Response Times**: Up to 2-3x performance improvement +- **Better Resource Utilization**: More efficient handling of concurrent requests + +### Developer Experience + +- **Automatic Documentation**: Built-in OpenAPI/Swagger documentation +- **Type Safety**: Full request/response validation with Pydantic +- **Modern Standards**: OpenAPI 3.0 compliance and JSON Schema validation +- **Better Error Handling**: Structured error responses with detailed information + +### API Improvements + +- **Interactive Documentation**: Test API endpoints directly from `/docs` +- **Schema Validation**: Automatic request/response validation +- **Better Error Messages**: Detailed validation errors with field-level feedback + +## 🛠️ Installation & Setup + +### Prerequisites + +- Python 3.11+ +- Conda package manager +- Windows OS (currently optimized for Windows) + +### Quick Start + +1. **Clone the Repository** + + ```bash + git clone + cd Aniworld + ``` + +2. **Create and Activate Conda Environment** + + ```bash + conda create -n AniWorld python=3.11 + conda activate AniWorld + ``` + +3. **Install Dependencies** + + ```bash + pip install -r requirements.txt + ``` + +4. **Set Environment Variables** + + ```bash + # Set your master password (will be hashed automatically) + set MASTER_PASSWORD=your_secure_password + ``` + +5. **Start the FastAPI Server** + + ```bash + # 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" + ``` + +6. **Access the Application** + - **Web Interface**: http://localhost:8000 + - **API Documentation**: http://localhost:8000/docs + - **Alternative API Docs**: http://localhost:8000/redoc + +### Alternative: Using VS Code Tasks + +If you're using VS Code, you can use the pre-configured tasks: + +- `Ctrl+Shift+P` → "Tasks: Run Task" → "Run FastAPI Server" + +## 🔧 Configuration + +### Environment Variables + +- `MASTER_PASSWORD` - Your master password (will be hashed automatically) +- `MASTER_PASSWORD_HASH` - Pre-hashed password (alternative to MASTER_PASSWORD) +- `JWT_SECRET_KEY` - Secret key for JWT token signing (auto-generated if not set) +- `LOG_LEVEL` - Logging level (DEBUG, INFO, WARNING, ERROR) + +### Directory Structure + +``` +Aniworld/ +├── src/ +│ ├── core/ # Core business logic +│ │ ├── SeriesApp.py # Main application controller +│ │ ├── entities/ # Data models +│ │ └── providers/ # Content providers +│ ├── server/ # FastAPI server +│ │ ├── fastapi_app.py # Main FastAPI application +│ │ └── web/ # Web interface and controllers +│ └── infrastructure/ # Infrastructure components +├── data/ # Application data and databases +├── logs/ # Application logs +└── requirements.txt # Python dependencies +``` + +## 🌐 API Usage + +### Authentication + +1. **Login to get JWT token**: + + ```bash + curl -X POST "http://localhost:8000/auth/login" \ + -H "Content-Type: application/json" \ + -d '{"password": "your_master_password"}' + ``` + +2. **Use token in requests**: + ```bash + curl -X GET "http://localhost:8000/api/anime/search?query=naruto" \ + -H "Authorization: Bearer your_jwt_token_here" + ``` + +### Key Endpoints + +- **Authentication**: `/auth/login`, `/auth/verify`, `/auth/logout` +- **System**: `/health`, `/api/system/config` +- **Anime**: `/api/anime/search`, `/api/anime/{id}` +- **Episodes**: `/api/episodes/{id}`, `/api/anime/{id}/episodes` +- **Downloads**: `/api/download`, `/api/add_series` + +For complete API documentation, visit `/docs` when the server is running. + +## 🖥️ Web Interface + +### Main Features + +- **Dashboard**: Overview of your anime collection and missing episodes +- **Search**: Find and add new anime series to track +- **Downloads**: Manage download queue and monitor progress +- **Settings**: Configure application preferences + +### Responsive Design + +The web interface is fully responsive and supports: + +- Desktop browsers (Chrome, Firefox, Edge, Safari) +- Mobile devices (iOS Safari, Android Chrome) +- Tablet devices +- Dark and light themes + +## 🔍 Troubleshooting + +### Common Issues + +1. **Server won't start** + + - Check that the AniWorld conda environment is activated + - Verify all dependencies are installed: `pip install -r requirements.txt` + - Check for port conflicts (default: 8000) + +2. **Authentication errors** + + - Verify the master password is set correctly + - Check environment variables are properly configured + - Clear browser cache/cookies + +3. **Import errors** + - Ensure all required packages are installed + - Check Python path configuration + - Verify conda environment is activated + +### Logs + +Application logs are stored in the `logs/` directory: + +- `aniworld.log` - General application logs +- `errors.log` - Error-specific logs +- `auth_failures.log` - Authentication failure logs + +## 🚦 Development + +### Running in Development Mode + +```bash +# With auto-reload for development +uvicorn src.server.fastapi_app:app --host 127.0.0.1 --port 8000 --reload --log-level debug +``` + +### Testing + +```bash +# Run all tests +python -m pytest tests/ -v + +# Run with coverage +python -m pytest tests/ --cov=src --cov-report=html +``` + +### Code Quality + +```bash +# Format code +black src/ +isort src/ + +# Lint code +pylint src/ +flake8 src/ +``` + +## 📚 Documentation + +- **API Documentation**: Available at `/docs` (Swagger UI) and `/redoc` (ReDoc) +- **Migration Guide**: See `API_DOCUMENTATION.md` for detailed migration information +- **FastAPI Specific**: See `src/server/README_FastAPI.md` for server-specific documentation + +## 🤝 Contributing + +1. Fork the repository +2. Create a feature branch (`git checkout -b feature/amazing-feature`) +3. Commit your changes (`git commit -m 'Add amazing feature'`) +4. Push to the branch (`git push origin feature/amazing-feature`) +5. Open a Pull Request + +## 📄 License + +This project is licensed under the MIT License - see the LICENSE file for details. + +## 🙏 Acknowledgments + +- FastAPI team for the excellent framework +- The original Flask implementation that served as the foundation +- 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. diff --git a/ServerTodo.md b/ServerTodo.md index 0aadbe9..dca2ba6 100644 --- a/ServerTodo.md +++ b/ServerTodo.md @@ -1,227 +1,227 @@ -# Web Migration TODO: Flask to FastAPI - -This document contains tasks for migrating the web application from Flask to FastAPI. Each task should be marked as completed with [x] when finished. - -## 📋 Project Analysis and Setup - -### Initial Assessment - -- [x] Review current Flask application structure in `/src/web/` directory -- [x] Identify all Flask routes and their HTTP methods -- [x] Document current template engine usage (Jinja2) -- [x] List all static file serving requirements -- [x] Inventory all middleware and extensions currently used -- [x] Document current error handling patterns -- [x] Review authentication/authorization mechanisms - -### FastAPI Setup - -- [x] Install FastAPI dependencies: `pip install fastapi uvicorn jinja2 python-multipart` -- [x] Update `requirements.txt` or `pyproject.toml` with new dependencies -- [x] Remove Flask dependencies: `flask`, `flask-*` packages -- [x] Create new FastAPI application entry point - -## 🔧 Core Application Migration - -### Main Application Structure - -- [x] Create new `main.py` or update existing app entry point with FastAPI app instance -- [x] Migrate Flask app configuration to FastAPI settings using Pydantic BaseSettings -- [x] Convert Flask blueprints to FastAPI routers -- [x] Update CORS configuration from Flask-CORS to FastAPI CORS middleware - -### Route Conversion - -- [x] Convert all `@app.route()` decorators to FastAPI route decorators (`@app.get()`, `@app.post()`, etc.) -- [x] Update route parameter syntax from `` to `{id: int}` format -- [x] Convert Flask request object usage (`request.form`, `request.json`) to FastAPI request models -- [x] Update response handling from Flask `jsonify()` to FastAPI automatic JSON serialization -- [x] Convert Flask `redirect()` and `url_for()` to FastAPI equivalents - -### Request/Response Models - -- [x] Create Pydantic models for request bodies (replace Flask request parsing) -- [x] Create Pydantic models for response schemas -- [x] Update form handling to use FastAPI Form dependencies -- [x] Convert file upload handling to FastAPI UploadFile - -## 🎨 Template and Static Files Migration - -### Template Engine Setup - -- [x] Configure Jinja2Templates in FastAPI application -- [x] Set up template directory structure -- [x] Create templates directory configuration in FastAPI app - -### HTML Template Migration - -- [x] Review all `.html` files in templates directory -- [x] Update template rendering from Flask `render_template()` to FastAPI `templates.TemplateResponse()` -- [x] Verify Jinja2 syntax compatibility (should be mostly unchanged) -- [x] Update template context passing to match FastAPI pattern -- [x] Test all template variables and filters still work correctly - -### Static Files Configuration - -- [x] Configure StaticFiles mount in FastAPI for CSS, JS, images -- [x] Update static file URL generation in templates -- [x] Verify all CSS file references work correctly -- [x] Verify all JavaScript file references work correctly -- [x] Test image and other asset serving - -## 💻 JavaScript and Frontend Migration - -### Inline JavaScript Review - -- [x] Scan all HTML templates for inline `') -VIDEO_URL_REGEX = re.compile(r'file:\s*"([^"]+\.m3u8[^"]*)"') - -# TODO Implement this script fully - - -def get_direct_link_from_filemoon(embeded_filemoon_link: str): - session = requests.Session() - session.verify = False - - headers = { - "User-Agent": config.RANDOM_USER_AGENT, - "Referer": embeded_filemoon_link, - } - - response = session.get(embeded_filemoon_link, headers=headers) - source = response.text - - match = REDIRECT_REGEX.search(source) - if match: - redirect_url = match.group(1) or match.group(2) - response = session.get(redirect_url, headers=headers) - source = response.text - - for script_match in SCRIPT_REGEX.finditer(source): - script_content = script_match.group(1).strip() - - if not script_content.startswith("eval("): - continue - - if packer.detect(script_content): - unpacked = packer.unpack(script_content) - video_match = VIDEO_URL_REGEX.search(unpacked) - if video_match: - return video_match.group(1) - - raise Exception("No Video link found!") - - -if __name__ == '__main__': - url = input("Enter Filemoon Link: ") - print(get_direct_link_from_filemoon(url)) +import re +import requests +# import jsbeautifier.unpackers.packer as packer + +from aniworld import config + +REDIRECT_REGEX = re.compile( + r'