diff --git a/media_manager/exceptions.py b/media_manager/exceptions.py index cc800a2..48a0f70 100644 --- a/media_manager/exceptions.py +++ b/media_manager/exceptions.py @@ -1,16 +1,57 @@ -class MediaAlreadyExists(ValueError): +from fastapi import Request, HTTPException +from fastapi.responses import JSONResponse + + +class MediaAlreadyExists(Exception): """Raised when a show already exists""" + def __init__( + self, message: str = "Entity with this ID or other identifier already exists" + ): + super().__init__(message) + self.message = message + pass class NotFoundError(Exception): """Custom exception for when an entity is not found.""" - + def __init__(self, message: str = "The requested entity was not found."): + super().__init__(message) + self.message = message pass class InvalidConfigError(Exception): """Custom exception for when an entity is not found.""" - + def __init__(self, message: str = "The server is improperly configured."): + super().__init__(message) + self.message = message pass + + +async def media_already_exists_exception_handler( + request: Request, exc: MediaAlreadyExists | Exception +) -> JSONResponse: + return JSONResponse( + status_code=401, + content={"detail": exc.message}, + ) + + +async def not_found_error_exception_handler( + request: Request, exc: NotFoundError | Exception +) -> JSONResponse: + return JSONResponse( + status_code=404, + content={"detail": exc.message}, + ) + + +async def invalid_config_error_exception_handler( + request: Request, exc: InvalidConfigError | Exception +) -> JSONResponse: + return JSONResponse( + status_code=500, + content={"detail": exc.message}, + ) \ No newline at end of file diff --git a/media_manager/main.py b/media_manager/main.py index ebaedf7..ed9b07f 100644 --- a/media_manager/main.py +++ b/media_manager/main.py @@ -3,10 +3,8 @@ import os import sys from logging.config import dictConfig from pathlib import Path - from pythonjsonlogger.json import JsonFormatter - LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, @@ -48,21 +46,17 @@ logging.basicConfig( log = logging.getLogger(__name__) from media_manager.database import init_db # noqa: E402 - -import media_manager.tv.router as tv_router # noqa: E402 +from media_manager.config import BasicConfig # noqa: E402 import media_manager.torrent.router as torrent_router # noqa: E402 import media_manager.movies.router as movies_router # noqa: E402 - +import media_manager.tv.router as tv_router # noqa: E402 from media_manager.tv.service import ( # noqa: E402 auto_download_all_approved_season_requests, import_all_torrents, update_all_non_ended_shows_metadata, ) -from media_manager.config import BasicConfig # noqa: E402 import shutil # noqa: E402 - - from fastapi import FastAPI # noqa: E402 from fastapi.middleware.cors import CORSMiddleware # noqa: E402 from datetime import datetime # noqa: E402 @@ -143,9 +137,19 @@ from media_manager.auth.users import ( # noqa: E402 cookie_auth_backend, openid_cookie_auth_backend, ) +from media_manager.exceptions import ( + NotFoundError, + not_found_error_exception_handler, + MediaAlreadyExists, + media_already_exists_exception_handler, + InvalidConfigError, + invalid_config_error_exception_handler, +) - +# ---------------------------- # Standard Auth Routers +# ---------------------------- + app.include_router( fastapi_users.get_auth_router(bearer_auth_backend), prefix="/auth/jwt", @@ -171,17 +175,24 @@ app.include_router( prefix="/auth", tags=["auth"], ) -# All users route router + +# ---------------------------- +# User Management Routers +# ---------------------------- + app.include_router(custom_users_router, tags=["users"]) -# OAuth Metadata Router -app.include_router(auth_metadata_router, tags=["openid"]) -# User Router app.include_router( fastapi_users.get_users_router(UserRead, UserUpdate), prefix="/users", tags=["users"], ) -# OAuth2 Routers + +# ---------------------------- +# OpenID Connect Routers +# ---------------------------- + +app.include_router(auth_metadata_router, tags=["openid"]) + if openid_client is not None: app.include_router( get_oauth_router( @@ -205,9 +216,18 @@ app.mount( name="static-images", ) +# ---------------------------- +# Custom Exception Handlers +# ---------------------------- + +app.add_exception_handler(NotFoundError, not_found_error_exception_handler) +app.add_exception_handler(MediaAlreadyExists, media_already_exists_exception_handler) +app.add_exception_handler(InvalidConfigError, invalid_config_error_exception_handler) log.info("Hello World!") +# ---------------------------- # Startup filesystem checks +# ---------------------------- try: test_dir = basic_config.tv_directory / Path(".media_manager_test_dir") test_dir.mkdir(parents=True, exist_ok=True)