Advertisement
Mochinov

Untitled

Aug 2nd, 2023
1,233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.33 KB | None | 0 0
  1. import json
  2.  
  3. from sqlalchemy.future import select
  4. from starlette.endpoints import HTTPEndpoint
  5. from starlette.requests import Request
  6. from starlette.responses import JSONResponse
  7. from starlette.status import HTTP_200_OK
  8. from starlette.status import HTTP_201_CREATED
  9. from starlette.status import HTTP_400_BAD_REQUEST
  10. from starlette.status import HTTP_404_NOT_FOUND
  11. from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
  12.  
  13. from mixins import RequestIdentificationMixin
  14. from services import ExceptionResponse
  15. from services import ParserController
  16. from services import Serializer
  17. from services import TelegramController
  18. from services import ValidateSchema
  19. from settings.config import caches
  20. from src.models import Applications
  21. from src.schemas import ApplicationSchema
  22. from src.schemas import ApplicationVerificationSchema
  23. from src.schemas import ReverifyApplication
  24.  
  25.  
  26. class Application(HTTPEndpoint):
  27.     @RequestIdentificationMixin.protected_request
  28.     async def post(self, request: Request) -> JSONResponse:
  29.         """
  30.        {
  31.            "responses": {
  32.                201: {
  33.                    "description": "A note was create",
  34.                },
  35.                400: {
  36.                    "description": "Bad request",
  37.                }
  38.            },
  39.            "parameters": [
  40.                {
  41.                    "name": "app_id",
  42.                    "in": "query",
  43.                    "description": "Application id",
  44.                    "required": true,
  45.                    "schema": {
  46.                        "type": "integer",
  47.                        "items": {
  48.                            "type": "integer",
  49.                            "format": "int64"
  50.                        }
  51.                    },
  52.                    "style": "simple"
  53.                },
  54.                {
  55.                    "name": "app_hash",
  56.                    "in": "query",
  57.                    "description": "Hash string",
  58.                    "required": true,
  59.                    "schema": {
  60.                        "type": "string",
  61.                        "items": {
  62.                            "type": "string",
  63.                            "format": "str"
  64.                        }
  65.                    },
  66.                    "style": "simple"
  67.                },
  68.                {
  69.                    "name": "phone",
  70.                    "in": "query",
  71.                    "description": "id applications or list if parameters was null",
  72.                    "required": true,
  73.                    "schema": {
  74.                        "type": "string",
  75.                        "items": {
  76.                            "type": "string",
  77.                            "format": "str"
  78.                        }
  79.                    },
  80.                    "style": "simple"
  81.                },
  82.            ],
  83.        }
  84.        """
  85.         query_params = await request.json()
  86.         if query_params:
  87.             applications_data = ValidateSchema(
  88.                 schema=ApplicationSchema,
  89.                 query_params=query_params,
  90.             )
  91.  
  92.             if applications_data.is_valid():
  93.                 applications_data = applications_data.get_data()
  94.                 (
  95.                     is_valid,
  96.                     errors,
  97.                     application,
  98.                 ) = await Applications.get_object_from_field(
  99.                     select_value=applications_data.app_id,
  100.                     session=self.session,
  101.                     field="app_id",
  102.                 )
  103.                 if is_valid:
  104.                     return JSONResponse(
  105.                         content={
  106.                             "message": "Applications is already exists!",
  107.                         },
  108.                         status_code=HTTP_400_BAD_REQUEST,
  109.                     )
  110.  
  111.                 application = Applications(**dict(applications_data))
  112.                 telegram_client = TelegramController(
  113.                     api_id=application.app_id,
  114.                     api_hash=application.app_hash,
  115.                     phone=application.phone,
  116.                 )
  117.                 await telegram_client.client.connect()
  118.                 connection = await caches.set_connection(
  119.                     application.app_id,
  120.                     telegram_client,
  121.                 )
  122.                 if connection:
  123.                     send_code = await telegram_client.send_code()
  124.                     if send_code:
  125.                         try:
  126.                             self.session.add(application)
  127.                             application.phone_code_hash = send_code
  128.                             await caches.set_send_code(application.app_id, True)
  129.                             application.user_id = self.user.id
  130.                             await self.session.commit()
  131.                             await self.session.close()
  132.                             return JSONResponse(
  133.                                 content=json.dumps(
  134.                                     {
  135.                                         "application_id": application.id,
  136.                                         "status": HTTP_201_CREATED,
  137.                                     }
  138.                                 ),
  139.                                 status_code=HTTP_201_CREATED,
  140.                             )
  141.  
  142.                         except Exception as exception:
  143.                             print(exception)
  144.  
  145.                 await self.session.close()
  146.                 return JSONResponse(
  147.                     content="Code is already send!",
  148.                     status_code=HTTP_400_BAD_REQUEST,
  149.                 )
  150.  
  151.             else:
  152.                 await self.session.close()
  153.                 return JSONResponse(
  154.                     content=applications_data.error,
  155.                     status_code=HTTP_400_BAD_REQUEST
  156.                 )
  157.  
  158.         await self.session.close()
  159.         return JSONResponse(HTTP_400_BAD_REQUEST)
  160.  
  161.     @RequestIdentificationMixin.protected_request
  162.     async def get(self, request: Request) -> JSONResponse:
  163.         """
  164.        {
  165.            "responses": {
  166.                200: {
  167.                    "description": "Get list applications",
  168.                },
  169.                400: {
  170.                    "description": "Bad request",
  171.                }
  172.            },
  173.            "parameters": [],
  174.        }
  175.        """
  176.  
  177.         query = await self.session.execute(select(Applications).options())
  178.         json_data = Serializer(
  179.             data=query.scalars().all(),
  180.         )
  181.         await self.session.close()
  182.         return JSONResponse(content=json_data.data)
  183.  
  184.  
  185. class ApplicationRestoreAccount(HTTPEndpoint):
  186.     @RequestIdentificationMixin.protected_request
  187.     async def post(self, request: Request) -> JSONResponse:
  188.         """
  189.        {
  190.            "responses": {
  191.                200: {
  192.                    "description": "A note was reverify",
  193.                },
  194.                400: {
  195.                    "description": "A note not found",
  196.                },
  197.                422: {
  198.                    "description": "Code is already send!",
  199.                },
  200.            },
  201.            "parameters": [
  202.                {
  203.                    "name": "app_id",
  204.                    "in": "body",
  205.                    "description": "app_id application field was passed",
  206.                    "required": true,
  207.                    "schema": {
  208.                        "type": "integer",
  209.                        "items": {
  210.                            "type": "integer",
  211.                            "format": "int64"
  212.                        }
  213.                    },
  214.                    "style": "simple"
  215.                },
  216.            ],
  217.        }
  218.  
  219.        """
  220.         query_params = await request.json()
  221.         if query_params:
  222.             applications_data_verify = ValidateSchema(
  223.                 schema=ReverifyApplication,
  224.                 query_params=query_params,
  225.             )
  226.  
  227.             if applications_data_verify.is_valid():
  228.                 applications_data = applications_data_verify.get_data()
  229.                 (
  230.                     is_valid,
  231.                     errors,
  232.                     application,
  233.                 ) = await Applications.get_object_from_field(
  234.                     select_value=applications_data.app_id,
  235.                     session=self.session,
  236.                     field="app_id",
  237.                 )
  238.                 if application:
  239.                     if (application.state == Applications.ApplicationStateType.READY.name
  240.                             and application.string_authentication
  241.                     ):
  242.                         is_valid, errors, application_ = await Applications.dynamic_update(
  243.                             column=application,
  244.                             dynamic_column={
  245.                                 "state": Applications.ApplicationStateType.WAIT_AUTHORIZATION_CODE.name,
  246.                             },
  247.                             session=self.session,
  248.                         )
  249.                         telegram_client = TelegramController(
  250.                             api_id=application_.app_id,
  251.                             api_hash=application_.app_hash,
  252.                             phone=application_.phone,
  253.                         )
  254.                         await telegram_client.client.connect()
  255.                         await telegram_client.client.log_out() # Logout session
  256.                         await caches.remove_connections(key=application.app_id)
  257.  
  258.  
  259.                 new_telegram_client = TelegramController(
  260.                     api_id=application.app_id,
  261.                     api_hash=application.app_hash,
  262.                     phone=application.phone,
  263.                 )
  264.                 await new_telegram_client.client.connect()
  265.                 connection = await caches.set_connection(
  266.                     application.app_id,
  267.                     new_telegram_client,
  268.                 )
  269.                 if connection:
  270.                     send_code = await new_telegram_client.send_code()
  271.                     if send_code:
  272.                         try:
  273.                             self.session.add(application)
  274.                             application.phone_code_hash = send_code
  275.                             application.user_id = self.user.id
  276.                             await caches.set_send_code(application.app_id, True)
  277.                             await caches.display_cashes()
  278.                             await self.session.commit()
  279.                             await self.session.close()
  280.                             return JSONResponse(
  281.                                 content=json.dumps(
  282.                                     {
  283.                                         "application_id": application.id,
  284.                                         "status": HTTP_200_OK,
  285.                                     }
  286.                                 ),
  287.                                 status_code=HTTP_200_OK,
  288.                             )
  289.  
  290.                         except Exception as exception:
  291.                             print(exception)
  292.                             await self.session.close()
  293.                             error = ExceptionResponse(
  294.                                 message="Account is blocked !",
  295.                                 error=ExceptionResponse.ExceptionResponseType.VALIDATION_ERROR.name,
  296.                             ).to_json()
  297.                             return JSONResponse(
  298.                                 content=error,
  299.                                 status_code=HTTP_422_UNPROCESSABLE_ENTITY,
  300.                             )
  301.  
  302.                 await self.session.close()
  303.                 error = ExceptionResponse(
  304.                     message="Code is already send!",
  305.                     error=ExceptionResponse.ExceptionResponseType.VALIDATION_ERROR.name,
  306.                 ).to_json()
  307.                 return JSONResponse(
  308.                     content=error,
  309.                     status_code=HTTP_422_UNPROCESSABLE_ENTITY,
  310.                 )
  311.             else:
  312.                 await self.session.close()
  313.                 return JSONResponse(
  314.                     content=applications_data.error,
  315.                     status_code=HTTP_400_BAD_REQUEST
  316.                 )
  317.  
  318.         await self.session.close()
  319.         return JSONResponse(
  320.             content="Bad request!",
  321.             status_code=HTTP_400_BAD_REQUEST,
  322.         )
  323.  
  324.  
  325. class ApplicationDelete(HTTPEndpoint):
  326.     @RequestIdentificationMixin.protected_request
  327.     async def delete(self, request: Request) -> JSONResponse:
  328.         """
  329.        {
  330.            "responses": {
  331.                200: {
  332.                    "description": "A note was delete",
  333.                },
  334.                404: {
  335.                    "description": "A note not found",
  336.                }
  337.            },
  338.            "parameters": [
  339.                {
  340.                    "name": "id",
  341.                    "in": "path",
  342.                    "description": "id application for delete",
  343.                    "required": true,
  344.                    "schema": {
  345.                        "type": "integer",
  346.                        "items": {
  347.                            "type": "integer",
  348.                            "format": "int64"
  349.                        }
  350.                    },
  351.                    "style": "simple"
  352.                },
  353.            ],
  354.        }
  355.        """
  356.         application_id = request.path_params.get("id")
  357.         result = await Applications.delete(
  358.             column_id=application_id,
  359.             session=self.session,
  360.         )
  361.         if result:
  362.             await self.session.close()
  363.             return JSONResponse(
  364.                 content="OK",
  365.                 status_code=HTTP_200_OK
  366.             )
  367.  
  368.         await self.session.close()
  369.         return JSONResponse(
  370.             content=ExceptionResponse(
  371.                 message="Record missing",
  372.                 error=ExceptionResponse.ExceptionResponseType.NOT_FOUND.name,
  373.             ).to_json(),
  374.             status_code=HTTP_400_BAD_REQUEST,
  375.         )
  376.  
  377.  
  378. class ApplicationVerification(HTTPEndpoint):
  379.     @RequestIdentificationMixin.protected_request
  380.     async def post(self, request) -> JSONResponse:
  381.         """
  382.        {
  383.            "responses": {
  384.                200: {
  385.                    "description": "A note was verify",
  386.                },
  387.                404: {
  388.                    "description": "A note not found",
  389.                }
  390.            },
  391.            "parameters": [
  392.                {
  393.                    "name": "code",
  394.                    "in": "path",
  395.                    "description": "Code from message",
  396.                    "required": true,
  397.                    "schema": {
  398.                        "type": "integer",
  399.                        "items": {
  400.                            "type": "integer",
  401.                            "format": "int64"
  402.                        }
  403.                    },
  404.                    "style": "simple"
  405.                },
  406.                {
  407.                    "name": "app_id",
  408.                    "in": "path",
  409.                    "description": "id application",
  410.                    "required": true,
  411.                    "schema": {
  412.                        "type": "integer",
  413.                        "items": {
  414.                            "type": "integer",
  415.                            "format": "int64"
  416.                        }
  417.                    },
  418.                    "style": "simple"
  419.                },
  420.            ],
  421.        }
  422.  
  423.        """
  424.         query_params = await request.json()
  425.         if query_params:
  426.             applications_data_verify = ValidateSchema(
  427.                 schema=ApplicationVerificationSchema,
  428.                 query_params=query_params,
  429.             )
  430.             if applications_data_verify.is_valid():
  431.                 applications_data = applications_data_verify.get_data()
  432.                 (
  433.                     is_valid,
  434.                     errors,
  435.                     application,
  436.                 ) = await Applications.get_object_from_field(
  437.                     select_value=applications_data.app_id,
  438.                     session=self.session,
  439.                     field="app_id",
  440.                 )
  441.  
  442.                 if (
  443.                     application.state == Applications.ApplicationStateType.READY.name
  444.                         and application.string_authentication
  445.                 ):
  446.                     await self.session.close()
  447.                     return JSONResponse(
  448.                         content={
  449.                             "message": "Application is verify",
  450.                         },
  451.                         status_code=HTTP_400_BAD_REQUEST,
  452.                     )
  453.  
  454.                 if not is_valid:
  455.                     await self.session.close()
  456.                     return JSONResponse(
  457.                         content=errors,
  458.                         status_code=HTTP_404_NOT_FOUND,
  459.                     )
  460.  
  461.                 telegram_client = await caches.get_connection(
  462.                     key=application.app_id,
  463.                 )
  464.                 if telegram_client.get("code_send"):
  465.                     telegram_client = telegram_client.get("_object")
  466.                     await telegram_client.client.sign_in(
  467.                         application.phone,
  468.                     )
  469.                     telegram_client_is_authorized = await telegram_client.verify_session(
  470.                         code=applications_data.code,
  471.                         phone_code_hash=application.phone_code_hash,
  472.                     )
  473.                     if telegram_client_is_authorized:
  474.                         session_string = await telegram_client.create_string_session()
  475.                         is_valid, errors, application_ = await Applications.dynamic_update(
  476.                             column=application,
  477.                             dynamic_column={
  478.                                 "state": Applications.ApplicationStateType.READY.name,
  479.                                 "string_authentication": session_string,
  480.                             },
  481.                             session=self.session,
  482.                         )
  483.                         await self.session.close()
  484.                         if is_valid:
  485.                             await caches.remove_connections(key=application.app_id)
  486.                             await ParserController.sync_sources_applications()
  487.                             await self.session.close()
  488.                             return JSONResponse(
  489.                                 content=json.dumps(
  490.                                     {
  491.                                         "application_id": application_.id,
  492.                                         "status": HTTP_200_OK,
  493.                                     }
  494.                                 ),
  495.                                 status_code=HTTP_200_OK,
  496.                             )
  497.  
  498.                         return JSONResponse(
  499.                             content=errors,
  500.                             status_code=HTTP_404_NOT_FOUND,
  501.                         )
  502.  
  503.                 else:
  504.                     await self.session.close()
  505.                     return JSONResponse(
  506.                         content="Application is not send code",
  507.                         status_code=HTTP_404_NOT_FOUND,
  508.                     )
  509.  
  510.         await self.session.close()
  511.         return JSONResponse(
  512.             content="Not found",
  513.             status_code=HTTP_404_NOT_FOUND,
  514.         )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement