diff --git a/print_service/exceptions.py b/print_service/exceptions.py index 99ed16a..3acc213 100644 --- a/print_service/exceptions.py +++ b/print_service/exceptions.py @@ -42,7 +42,7 @@ def __init__(self): class InvalidPageRequest(Exception): def __init__(self): - super().__init__(f'Invalid format') + super().__init__(f'The number of requested pages exceeds the number of pages') class UnionStudentDuplicate(Exception): @@ -62,13 +62,13 @@ def __init__(self): class FileIsNotReceived(Exception): def __init__(self): - super().__init__(f'No file was recieved') + super().__init__(f'No file was received') class InvalidType(Exception): def __init__(self, content_type: str): super().__init__( - f'Only {", ".join(settings.CONTENT_TYPES)} files allowed, but {content_type} was recieved' + f'Only {", ".join(settings.CONTENT_TYPES)} files allowed, but {content_type} was received' ) @@ -90,3 +90,18 @@ def __init__(self): class UnprocessableFileInstance(Exception): def __init__(self): super().__init__(f'Unprocessable file instance') + + +class TokenAlreadyUsed(Exception): + def __init__(self): + super().__init__(f'Token already used') + + +class Unauthorized(Exception): + def __init__(self): + super().__init__(f'Unauthorized') + + +class NotAuthenticated(Exception): + def __init__(self): + super().__init__(f'Not authenticated') diff --git a/print_service/routes/admin.py b/print_service/routes/admin.py index da2b7b1..d783222 100644 --- a/print_service/routes/admin.py +++ b/print_service/routes/admin.py @@ -2,7 +2,7 @@ import logging from auth_lib.fastapi import UnionAuth -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, Depends from redis import Redis from print_service.exceptions import TerminalTokenNotFound @@ -67,3 +67,13 @@ async def reboot_terminal( return {'status': 'ok'} sender.redis.close() raise TerminalTokenNotFound() + + +@router.get("/settings") +async def setting_to_bot(user=Depends(UnionAuth(scopes=["print.print_bot.settings"]))): + logger.info(f"Bot {user} clone settings") + return { + "MAX_SIZE": settings.MAX_SIZE, + "MAX_PAGE_COUNT": settings.MAX_PAGE_COUNT, + "CONTENT_TYPES": settings.CONTENT_TYPES, + } diff --git a/print_service/routes/exc_handlers.py b/print_service/routes/exc_handlers.py index ecb8aeb..306244b 100644 --- a/print_service/routes/exc_handlers.py +++ b/print_service/routes/exc_handlers.py @@ -1,4 +1,3 @@ -import requests.models import starlette.requests from starlette.responses import JSONResponse @@ -54,7 +53,7 @@ async def too_many_pages(req: starlette.requests.Request, exc: TooManyPages): @app.exception_handler(InvalidPageRequest) -async def invalid_format(req: starlette.requests.Request, exc: TooManyPages): +async def invalid_format(req: starlette.requests.Request, exc: InvalidPageRequest): return JSONResponse( content=StatusResponseModel( status="Error", @@ -81,7 +80,7 @@ async def terminal_not_found_by_token(req: starlette.requests.Request, exc: Term content=StatusResponseModel( status="Error", message="Terminal not found by token", ru="Токен не найден" ).model_dump(), - status_code=400, + status_code=404, ) @@ -167,7 +166,7 @@ async def already_upload(req: starlette.requests.Request, exc: AlreadyUploaded): content=StatusResponseModel( status="Error", message=f"{exc}", ru="Файл уже загружен" ).model_dump(), - status_code=415, + status_code=409, ) @@ -175,7 +174,7 @@ async def already_upload(req: starlette.requests.Request, exc: AlreadyUploaded): async def is_corrupted(req: starlette.requests.Request, exc: IsCorrupted): return JSONResponse( content=StatusResponseModel(status="Error", message=f"{exc}", ru="Файл повреждён").model_dump(), - status_code=415, + status_code=422, ) @@ -205,5 +204,5 @@ async def not_uploaded(req: starlette.requests.Request, exc: IsNotUploaded): content=StatusResponseModel( status="Error", message=f"{exc}", ru="Файл не загружен" ).model_dump(), - status_code=415, + status_code=404, ) diff --git a/print_service/routes/file.py b/print_service/routes/file.py index 21e3570..9c28991 100644 --- a/print_service/routes/file.py +++ b/print_service/routes/file.py @@ -6,7 +6,6 @@ import aiofiles.os from auth_lib.fastapi import UnionAuth from fastapi import APIRouter, File, UploadFile -from fastapi.exceptions import HTTPException from fastapi.params import Depends from fastapi_sqlalchemy import db from pydantic import Field, field_validator @@ -24,8 +23,6 @@ PINNotFound, TooLargeSize, TooManyPages, - UnprocessableFileInstance, - UserNotFound, ) from print_service.models import File as FileModel from print_service.models import UnionMember @@ -258,7 +255,7 @@ async def update_file_options( .order_by(FileModel.created_at.desc()) .one_or_none() ) - print(options) + if not file_model: raise PINNotFound(pin) file_model.option_pages = options.get('pages') or file_model.option_pages @@ -269,7 +266,7 @@ async def update_file_options( db.session.commit() if file_model.flatten_pages: if file_model.number_of_pages < max(file_model.flatten_pages): - raise InvalidPageRequest + raise InvalidPageRequest() if file_model.sheets_count > settings.MAX_PAGE_COUNT: raise TooManyPages() return { diff --git a/print_service/routes/qrprint.py b/print_service/routes/qrprint.py index fe6dfab..005de4f 100644 --- a/print_service/routes/qrprint.py +++ b/print_service/routes/qrprint.py @@ -13,7 +13,7 @@ from starlette.status import WS_1000_NORMAL_CLOSURE from typing_extensions import Annotated -from print_service.exceptions import TerminalQRNotFound +from print_service.exceptions import NotAuthenticated, TerminalQRNotFound, TokenAlreadyUsed, Unauthorized from print_service.schema import BaseModel from print_service.settings import Settings, get_settings from print_service.utils import get_file @@ -89,7 +89,7 @@ async def check_token(self): me = await auth.check_token(self.terminal_token) if me is None: logger.error("Not authenticated") - raise Exception("Not authenticated") + raise NotAuthenticated for scope in me['session_scopes']: if scope['name'] == "print.qr_task.get": @@ -97,14 +97,14 @@ async def check_token(self): else: logger.error("Unauthorized") logger.debug(me) - raise Exception("Unauthorized") + raise Unauthorized # Token shouldn't be used yet for key in self.redis.keys(): value = self.redis.get(key) if self.redis.get(key) == self.terminal_token.encode(): logger.error("Token already used") - raise Exception("Token already used") + raise TokenAlreadyUsed def __aiter__(self): return self diff --git a/print_service/routes/user.py b/print_service/routes/user.py index 34a3a3c..eed84a9 100644 --- a/print_service/routes/user.py +++ b/print_service/routes/user.py @@ -3,9 +3,8 @@ from auth_lib.fastapi import UnionAuth from fastapi import APIRouter, Depends -from fastapi.exceptions import HTTPException from fastapi_sqlalchemy import db -from pydantic import constr, validate_call +from pydantic import constr from sqlalchemy import and_, func, or_ from print_service import __version__ @@ -51,7 +50,6 @@ async def check_union_member( ): """Проверяет наличие пользователя в списке.""" - surname = surname.upper() user = db.session.query(UnionMember) if not settings.ALLOW_STUDENT_NUMBER: user = user.filter(UnionMember.union_number != None) diff --git a/print_service/settings.py b/print_service/settings.py index c7de741..1755fac 100644 --- a/print_service/settings.py +++ b/print_service/settings.py @@ -4,7 +4,7 @@ from typing import List from auth_lib.fastapi import UnionAuthSettings -from pydantic import AnyUrl, ConfigDict, DirectoryPath, PostgresDsn, RedisDsn +from pydantic import ConfigDict, DirectoryPath, PostgresDsn, RedisDsn from pydantic_settings import BaseSettings diff --git a/print_service/utils/__init__.py b/print_service/utils/__init__.py index 1c44b33..70a9bb7 100644 --- a/print_service/utils/__init__.py +++ b/print_service/utils/__init__.py @@ -1,12 +1,10 @@ import io -import math import random import re from datetime import date, datetime, timedelta from os.path import abspath, exists from fastapi import File -from fastapi.exceptions import HTTPException from PyPDF4 import PdfFileReader from sqlalchemy import func from sqlalchemy.orm.session import Session @@ -20,7 +18,6 @@ from print_service.models import File from print_service.models import File as FileModel from print_service.models import PrintFact -from print_service.routes import exc_handlers from print_service.settings import Settings, get_settings