예제 #1
0
async def setu_v2(tag: str = Query('', max_length=45),
                  num: int = Query(1, ge=1, le=10),
                  r18: bool = False):
    print('{0}SETU_V2: tag:[{1}] r18:[{2}] num:[{3}]{4}'.format(
        '>' * 20, tag, r18, num, '<' * 20))
    condition = {}
    try:
        if (len(tag) != 0) and (not tag.isspace()):  # 如果tag不为空(字符串字数不为零且不为空)
            condition['tags'] = re.compile(tag.strip(), re.I)
        if r18:
            condition['type'] = 'p**n'
            setu = await find(condition, num)
        else:
            condition['type'] = 'sexy'
            setu = await find(condition, num)
        setus_num = len(setu)
        if setus_num != 0:
            for i in range(setus_num):  # 兼容v2
                setu[i]['page'] = 'p{}'.format(setu[i]['page'])
            setu_full = {'code': 200}
            setu_full['data'] = setu
            return setu_full
        else:
            return ORJSONResponse(status_code=404,
                                  content={
                                      'code': 404,
                                      'msg': '色图库中没找到色图~'
                                  })
    except Exception as error:
        return ORJSONResponse(status_code=500,
                              content={
                                  'code': 500,
                                  'msg': '爆炸啦~',
                                  'error': str(error)
                              })
예제 #2
0
async def setu_v1(tag: str = Query('', max_length=35), r18: bool = False):
    print('{0}SETU_V1: tag:[{1}] r18:[{2}]{3}'.format('>' * 20, tag, r18,
                                                      '<' * 20))
    condition = {}
    try:
        if (len(tag) != 0) and (not tag.isspace()):  # 如果tag不为空(字符串字数不为零且不为空)
            condition['tags'] = re.compile(tag.strip(), re.I)  # 正则并去掉字符两边空格
        if r18:
            condition['type'] = 'p**n'
            setu = await find(condition, 1)
        else:
            condition['type'] = 'sexy'
            setu = await find(condition, 1)
        setus_num = len(setu)
        if setus_num != 0:
            setu_full = setu[0]
            setu_full['code'] = 200
            return setu_full
        else:
            return ORJSONResponse(status_code=404,
                                  content={
                                      'code': 404,
                                      'msg': '色图库中没找到色图~'
                                  })
    except Exception as error:
        return ORJSONResponse(status_code=500,
                              content={
                                  'code': 500,
                                  'msg': '爆炸啦~',
                                  'error': str(error)
                              })
예제 #3
0
파일: routes.py 프로젝트: Svirex/assistant
async def register(registration_data: Registration):
    try:
        existed_user = await get_user_by_username(registration_data.username)
        if existed_user:
            return ORJSONResponse(status_code=status.HTTP_400_BAD_REQUEST,
                                  content={'error': 'username already exist'})
    except DocumentParsingError:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
    password_hash = hash_password(
        registration_data.password.get_secret_value())
    user = User(username=registration_data.username,
                password_hash=password_hash)
    try:
        await db.save(user)
    except BaseEngineException:
        return ORJSONResponse(status_code=status.HTTP_400_BAD_REQUEST,
                              content={'error': 'username already exist'})
    access_token, refresh_token, expire_access = create_tokens(
        {'sub': str(user.id)})
    return {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'expire': expire_access,
        'token_type': 'bearer'
    }
예제 #4
0
async def setu_v3(tag: str = Query('', max_length=45),
                  num: int = Query(1, ge=1, le=10),
                  type: int = Query(0, ge=0, le=3)):
    print('{0}SETU_V3: tag:[{1}] type:[{2}] num:[{3}]{4}'.format(
        '>' * 20, tag, type, num, '<' * 20))
    try:
        condition = ways_v3[type].copy()
        if (len(tag) != 0) and (not tag.isspace()):  # 如果tag不为空(字符串字数不为零且不为空)
            condition['tags'] = re.compile(tag.strip(), re.I)
        setu = await find(condition, num)
        setus_num = len(setu)
        if setus_num != 0:
            setu_full = {'code': 200, 'count': setus_num}
            setu_full['data'] = setu
            return setu_full
        else:
            return ORJSONResponse(status_code=404,
                                  content={
                                      'code': 404,
                                      'count': 0,
                                      'msg': '色图库中没找到色图~'
                                  })
    except Exception as error:
        return ORJSONResponse(status_code=500,
                              content={
                                  'code': 500,
                                  'count': 0,
                                  'msg': '爆炸啦~',
                                  'error': str(error)
                              })
예제 #5
0
파일: api.py 프로젝트: Varkaria/gulag
async def api_get_score_info(
    score_id: int = Query(..., alias="id", ge=0, le=9_223_372_036_854_775_807),
    db_conn: databases.core.Connection = Depends(acquire_db_conn),
):
    """Return information about a given score."""

    if SCOREID_BORDERS[0] > score_id >= 1:
        scores_table = "scores_vn"
    elif SCOREID_BORDERS[1] > score_id >= SCOREID_BORDERS[0]:
        scores_table = "scores_rx"
    elif SCOREID_BORDERS[2] > score_id >= SCOREID_BORDERS[1]:
        scores_table = "scores_ap"
    else:
        return ORJSONResponse(
            {"status": "Invalid score id."},
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    row = await db_conn.fetch_one(
        "SELECT map_md5, score, pp, acc, max_combo, mods, "
        "n300, n100, n50, nmiss, ngeki, nkatu, grade, status, "
        "mode, play_time, time_elapsed, perfect "
        f"FROM {scores_table} "
        "WHERE id = :score_id",
        {"score_id": score_id},
    )

    if not row:
        return ORJSONResponse(
            {"status": "Score not found."},
            status_code=status.HTTP_404_NOT_FOUND,
        )

    return ORJSONResponse({"status": "success", "score": dict(row)})
예제 #6
0
async def setu_v4(
        tag: Optional[List[str]] = Query([''], max_length=30),  # 不用None
        num: int = Query(1, ge=1, le=10),
        level: int = Query(0, ge=0, le=3)):
    print('{0}SETU_V4: tag:{1} type:[{2}] num:[{3}]{4}'.format(
        '>' * 20, tag, level, num, '<' * 20))
    try:
        condition = ways_v3[level].copy()
        if len(tag) != 1 or (len(tag[0]) != 0
                             and not tag[0].isspace()):  # tag不为空时
            condition['$and'] = []
            for tag_one in tag:
                condition['$and'].append(
                    {'tags': re.compile(tag_one.strip(), re.I)})
        setu = await find(condition, num)
        setus_num = len(setu)
        if setus_num != 0:
            setu_full = {'code': 200, 'count': setus_num}
            setu_full['data'] = setu
            return setu_full
        else:
            return ORJSONResponse(status_code=404,
                                  content={
                                      'code': 404,
                                      'count': 0,
                                      'msg': '色图库中没找到色图~'
                                  })
    except Exception as error:
        print(error)
        return ORJSONResponse(status_code=500,
                              content={
                                  'code': 500,
                                  'count': 0,
                                  'msg': '爆炸啦~'
                              })
예제 #7
0
async def confirm_login(request: Request, code: str, state: str):
    if "userid" in request.session.keys():
        return RedirectResponse("https://ula.fateslist.xyz")
    else:
        # Validate the state first
        if request.session.get("state") != state:
            return ORJSONResponse({"detail": "Invalid State"}, status_code=400)
    try:
        del request.session["state"]
    except:
        pass
    access_token = await discord_o.get_access_token(code, [
        'identify',
    ])
    request.session["access_token"] = access_token
    userjson = requests.get(
        config.ula_api_url +
        f"/login?access_token={access_token['access_token']}")
    if userjson.status_code == 400:
        return ORJSONResponse(userjson.json(), status_code=400)
    userjson = userjson.json()
    request.session["userid"] = userjson["id"]
    print(userjson)
    request.session["api_token"] = userjson["api_token"]
    request.session["disc"] = userjson["dash"]
    request.session["username"] = str(userjson["name"])
    if userjson.get("avatar"):
        request.session["avatar"] = "https://cdn.discordapp.com/avatars/" + \
        userjson["id"] + "/" + userjson["avatar"]
    else:
        # No avatar in user
        request.session[
            "avatar"] = "https://s3.us-east-1.amazonaws.com/files.tvisha.aws/posts/crm/panel/attachments/1580985653/discord-logo.jpg"
    return RedirectResponse("https://ula.fateslist.xyz")
예제 #8
0
파일: views.py 프로젝트: kant/test-api
async def sentiment_check(
    myfile: UploadFile = File(..., description="File to get sentiment"),
    delay: int = Query(
        None,
        title=title,
        description="Seconds to delay (max 121)",
        ge=1,
        le=121,
        alias="delay",
    ),
) -> dict:
    # sleep if delay option is used
    if delay is not None:
        logger.info(f"Delay of {delay} seconds invoked")
        await asyncio.sleep(delay)
        logger.info(f"Delay of {delay} seconds completed")

    file_text = await myfile.read()
    tb = TextBlob(file_text.decode("utf-8"))
    original_text = file_text.decode("utf-8")

    if len(original_text) == 0:
        error: dict = {"error": "The file is empty or unreadable"}
        logger.warning(error)
        return ORJSONResponse(status_code=400, content=error)

    data: dict = {
        "original": original_text,
        "sentiment": {
            "polarity": tb.sentiment.polarity,
            "subjectivity": tb.sentiment.subjectivity,
        },
    }
    # return data
    return ORJSONResponse(status_code=201, content=data)
예제 #9
0
파일: api.py 프로젝트: Varkaria/gulag
async def api_get_map_info(
    map_id: Optional[int] = Query(None, alias="id", ge=3, le=2_147_483_647),
    md5: Optional[str] = Query(None, alias="md5", min_length=32, max_length=32),
):
    """Return information about a given beatmap."""
    if map_id is not None:
        bmap = await Beatmap.from_bid(map_id)
    elif md5 is not None:
        bmap = await Beatmap.from_md5(md5)
    else:
        return ORJSONResponse(
            {"status": "Must provide either id or md5!"},
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    if not bmap:
        return ORJSONResponse(
            {"status": "Map not found."},
            status_code=status.HTTP_404_NOT_FOUND,
        )

    return ORJSONResponse(
        {
            "status": "success",
            "map": bmap.as_dict,
        },
    )
예제 #10
0
async def get_image(
    *, Authorization: str = Header(None), image_type: str = None, payload: ImageData = None
):
    if Authorization is None or Authorization != "nope":
        return ORJSONResponse(
            content={"success": False, "message": "Not authorized."}, status_code=401
        )
    if image_type is None:
        return ORJSONResponse(
            content={"success": False, "message": "image_type arg is missing."}, status_code=400
        )
    if payload is None:
        return ORJSONResponse(
            content={"success": False, "message": "Image data payload is missing."},
            status_code=400,
        )

    data = await draw_image(image_type, payload)
    if data is None:
        return ORJSONResponse(
            content={
                "success": False,
                "message": "bruh idk man something f****d up there is no image.",
            },
            status_code=410,
        )
    return StreamingResponse(content=data, media_type="image/png", status_code=201)
예제 #11
0
class Errors():
    HTTP_500_INTERNAL_SERVER_ERROR = ORJSONResponse(
        ErrorResponse('Internal Server Error'),
        status.HTTP_500_INTERNAL_SERVER_ERROR)
    HTTP_404_NOT_FOUND = ORJSONResponse(
        ErrorResponse('Content not found on DB'), status.HTTP_404_NOT_FOUND)
    HTTP_400_BAD_REQUEST = lambda message: ORJSONResponse(
        ErrorResponse(message), status.HTTP_400_BAD_REQUEST)
예제 #12
0
def _make_service_status(
    health_checks: Iterable[HealthCheckCallback], ) -> ORJSONResponse:
    for check in health_checks:
        failure_message = check()
        if failure_message:
            s = ServiceStatus.make(ok=False, message=failure_message)
            return ORJSONResponse(content=s.dict(), status_code=503)

    return ORJSONResponse(content=ServiceStatus.make(ok=True).dict(),
                          status_code=200)
예제 #13
0
파일: auth.py 프로젝트: nbashev/noc
async def auth_cookie(request: Request, jwt_cookie: str) -> ORJSONResponse:
    """
    Authorize against JWT token contained in cookie
    """
    try:
        user = get_user_from_jwt(jwt_cookie, audience="auth")
        return ORJSONResponse({"status": True}, status_code=200, headers={"Remote-User": user})
    except ValueError as e:
        logger.error("[Cookie][%s] Denied: %s", request.client.host, str(e) or "Unspecified reason")
        return ORJSONResponse({"status": False}, status_code=401)
예제 #14
0
async def redirect_latest(request: Request, call_next):
    """Redirect all GET requests using latest version to actual version number.

    Redirect only POST requests to for query and download endpoints, as
    other POST endpoints will require to list version number explicitly.
    """

    if (request.method == "GET" and "latest" in request.url.path) or (
        request.method == "POST"
        and "latest" in request.url.path
        and ("query" in request.url.path or "download" in request.url.path)
    ):
        try:
            path_items = request.url.path.split("/")

            i = 0
            for i, item in enumerate(path_items):
                if item == "latest":
                    break
            if i == 0:

                raise BadRequestError("Invalid URI")
            path_items[i] = await get_latest_version(path_items[i - 1])
            url = "/".join(path_items)
            if request.query_params:
                url = f"{url}?{request.query_params}"
            return RedirectResponse(url=url)

        except BadRequestError as e:
            return ORJSONResponse(
                status_code=400, content={"status": "failed", "message": str(e)}
            )

        except RecordNotFoundError as e:
            return ORJSONResponse(
                status_code=404, content={"status": "failed", "message": str(e)}
            )

        except HTTPException as e:
            return http_error_handler(e)

        except Exception as e:
            logger.exception(str(e))
            return ORJSONResponse(
                status_code=500,
                content={
                    "status": "error",
                    "message": "Internal Server Error. Could not process request.",
                },
            )
    else:
        response = await call_next(request)
        return response
예제 #15
0
파일: api.py 프로젝트: Varkaria/gulag
async def api_get_player_most_played(
    user_id: Optional[int] = Query(None, alias="id", ge=3, le=2_147_483_647),
    username: Optional[str] = Query(None, alias="name", regex=regexes.USERNAME.pattern),
    mode_arg: int = Query(0, alias="mode", ge=0, le=7),
    limit: int = Query(25, ge=1, le=100),
    db_conn: databases.core.Connection = Depends(acquire_db_conn),
):
    """Return the most played beatmaps of a given player."""
    # NOTE: this will almost certainly not scale well, lol.

    if user_id is not None:
        p = await app.state.sessions.players.from_cache_or_sql(id=user_id)
    elif username is not None:
        p = await app.state.sessions.players.from_cache_or_sql(name=username)
    else:
        return ORJSONResponse(
            {"status": "Must provide either id or name."},
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    if not p:
        return ORJSONResponse(
            {"status": "Player not found."},
            status_code=status.HTTP_404_NOT_FOUND,
        )

    # parse args (mode, limit)

    mode = GameMode(mode_arg)

    # fetch & return info from sql
    rows = await db_conn.fetch_all(
        "SELECT m.md5, m.id, m.set_id, m.status, "
        "m.artist, m.title, m.version, m.creator, COUNT(*) plays "
        f"FROM {mode.scores_table} s "
        "INNER JOIN maps m ON m.md5 = s.map_md5 "
        "WHERE s.userid = :user_id "
        "AND s.mode = :mode_vn "
        "GROUP BY s.map_md5 "
        "ORDER BY plays DESC "
        "LIMIT :limit",
        {"user_id": p.id, "mode_vn": mode.as_vanilla, "limit": limit},
    )

    return ORJSONResponse(
        {
            "status": "success",
            "maps": [dict(row) for row in rows],
        },
    )
예제 #16
0
async def validation_exception_handler(request, exc):
    print(request.headers)
    if isinstance(exc, UnicornException):
        return ORJSONResponse({
            "code": exc.code,
            "message": exc.msg,
            "data": exc.error
        })
    if isinstance(exc, StarletteHTTPException):
        """
        HTTP错误
        """
        headers = request.headers["User-Agent"]
        data = exc.detail
        for i in ["Mozilla", "Chrome", "Safari"]:
            if i in headers:
                return templates.TemplateResponse("404.html", {
                    "request": request,
                    "id": id
                })
        return ORJSONResponse({
            "code": 500,
            "message": "失败",
            "data": str(data)
        })
    elif isinstance(exc, RequestValidationError):
        """
        参数验证错误
        """
        data = exc.errors()[0]["msg"]
        logger.error(
            f"{str(request.url).replace(str(request.base_url),'/')}  {str(exc.errors()[0]['loc'])} {str(data)} param=>{str(exc.body)}"
        )
        return ORJSONResponse({
            "code":
            500,
            "message":
            "失败",
            "data":
            f"{str(exc.errors()[0]['loc'])} {str(data)}"
        })
    else:
        """
        未知错误
        """
        data = "内部异常"
        logger.error(
            f"{str(request.url).replace(str(request.base_url), '/')}  {data}")
        return ORJSONResponse({"code": 500, "message": "失败", "data": data})
예제 #17
0
    async def get_collection(self, id: str, **kwargs) -> ORJSONResponse:
        """Get collection by id.

        Called with `GET /collections/{collectionId}`.

        Args:
            id: Id of the collection.

        Returns:
            Collection.
        """
        request = kwargs["request"]
        pool = kwargs["request"].app.state.readpool
        async with pool.acquire() as conn:
            q, p = render(
                """
                SELECT * FROM get_collection(:id::text);
                """,
                id=id,
            )
            collection = await conn.fetchval(q, *p)
        if collection is None:
            raise NotFoundError
        links = await CollectionLinks(collection_id=id,
                                      request=request).get_links()
        collection["links"] = links
        return ORJSONResponse(
            Collection.construct(**collection).dict(exclude_none=True))
예제 #18
0
 def response_404(cls, id: str) -> JSONResponse:
     """
     return JSON response
     """
     return ORJSONResponse(content=dict(
         ok=False, error=f"No items found with id {id}"),
                           status_code=404)
예제 #19
0
 async def all_exception_handler(request: Request, exc: Exception):
     logger.error(f"程序异常\n{request.method} | URL:{request.url}\n \
         Headers:{request.headers}\n{traceback.format_exc()}")
     return ORJSONResponse(
         status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
         content="服务器内部错误",
     )
예제 #20
0
 async def validation_exception_handler(request: Request,
                                        exc: RequestValidationError):
     logger.debug(f"参数异常\n{request.method} | URL:{request.url}\n{exc}")
     return ORJSONResponse(
         status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
         content=exc._error_cache,
     )
예제 #21
0
 async def http_exception_handler(request: Request, exc: HTTPException):
     logger.debug(
         f"HTTP异常\n{request.method} | URL:{request.url} | {exc.detail}")
     return ORJSONResponse(
         status_code=status.HTTP_400_BAD_REQUEST,
         content=exc.detail,
     )
예제 #22
0
def resp_500(data: str = None) -> Response:
    return ORJSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                          content={
                              'code': "500",
                              'message': "Server internal error",
                              'data': data,
                          })
예제 #23
0
def resp_404(data: str = None) -> Response:
    return ORJSONResponse(status_code=status.HTTP_404_NOT_FOUND,
                          content={
                              'code': 404,
                              'message': "Page Not Found",
                              'data': data,
                          })
예제 #24
0
def resp_403(data: str = None) -> Response:
    return ORJSONResponse(status_code=status.HTTP_403_FORBIDDEN,
                          content={
                              'code': 403,
                              'message': "Forbidden",
                              'data': data,
                          })
예제 #25
0
 def response_already_exist(cls, name: str) -> ORJSONResponse:
     """
     return ORJSON respone
     """
     return ORJSONResponse(content=dict(
         ok=False, error=f"Item already exist with given name f{name}"),
                           status_code=403)
예제 #26
0
async def get_statistics(
        realm_access_roles: List[str] = Depends(extraction_auth),
        extraction: InputJSONExtraction = Body(...),
):
    """
    This endpoint provides ways to let external users and applications to request for
    information collected on the platform.\n
    This interface enables external organization to gather aggregated meta-data on citizens mobility.\n
    Within the API boundaries, it is possible to parametrize requests by selecting timeframes, area of interests,
    mobility types and other details.\n
    To preserve user’s privacy, it has been defined a lower threshold for the area selected.\n
    In addition, it has been enabled the possibility to extract, with other requests,
    the list of positions for the collected journeys.\n
    Furthermore, external organization can exploit an embedded mechanism that limit the visibility
    of their data with respect to the other users enabled to interact with the platform.\n
    The following diagram shows the final software design of the data extraction service.\n
    ![image](https:/serengeti/static/get_statistics.png)
    """

    if extraction.company_code:
        if extraction.company_code not in realm_access_roles:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                                detail="invalid_bearer_token")

    status_code, content = await extract_user_info(
        extraction.dict(exclude_unset=True))
    return ORJSONResponse(status_code=status_code, content=content)
예제 #27
0
async def http_exception_handler(request, exc):
    return ORJSONResponse(
        {
            "detail": exc.detail,
        },
        status_code=exc.status_code,
    )
예제 #28
0
 def dump2response(self):
     return ORJSONResponse({
         'result_detail': self.interface_result,
         'time_cost(seconds)': self.cost_time,
         'code': self.return_code,
         'message': self.return_message,
     })
예제 #29
0
    async def handle_post(self, request: Request) -> ORJSONResponse:
        """On POST works sign in logic."""
        code: Optional[str] = request.query_params.get("code")

        if not code:
            raise BadRequestError

        user_id: Optional[str] = request.scope.get("user_id")
        access_token, refresh_token, expires = await self.code_auth(code=code)
        account_info: Dict[str, Any] = await self.get_account_info(
            access_token=access_token)
        account_info["provider"] = self.provider
        account_info["access_token"] = access_token
        account_info["refresh_token"] = refresh_token
        account_info["expires"] = expires

        auth_account: Optional[AuthAccount] = await AuthAccount.filter(
            _id=account_info["_id"]).first().prefetch_related("user")

        user: Optional[User] = await User.get(id=user_id) if user_id else None

        if auth_account:
            await auth_account.update_from_dict(data=account_info)
            await auth_account.save()
        else:
            if not user:
                user = await User.create()

            auth_account = await AuthAccount.create(**account_info, user=user)

        tokens: Dict[str, Union[str, int]] = await create_tokens(
            user_id=str(auth_account.user.id)  # type: ignore
        )

        return ORJSONResponse(tokens)
예제 #30
0
파일: api.py 프로젝트: Varkaria/gulag
async def api_get_global_leaderboard(
    sort: Literal["tscore", "rscore", "pp", "acc"] = "pp",
    mode_arg: int = Query(0, alias="mode", ge=0, le=7),
    limit: int = Query(25, ge=1, le=100),
    offset: int = Query(0, min=0, max=2_147_483_647),
    country: Optional[str] = Query(None, min_length=2, max_length=2),
    db_conn: databases.core.Connection = Depends(acquire_db_conn),
):
    mode = GameMode(mode_arg)

    query_conditions = ["s.mode = :mode", "u.priv & 1", f"s.{sort} > 0"]
    query_parameters: dict[str, object] = {"mode": mode}

    if country is not None:
        query_conditions.append("u.country = :country")
        query_parameters["country"] = country

    rows = await db_conn.fetch_all(
        "SELECT u.id as player_id, u.name, u.country, s.tscore, s.rscore, "
        "s.pp, s.plays, s.playtime, s.acc, s.max_combo, "
        "s.xh_count, s.x_count, s.sh_count, s.s_count, s.a_count, "
        "c.id as clan_id, c.name as clan_name, c.tag as clan_tag "
        "FROM stats s "
        "LEFT JOIN users u USING (id) "
        "LEFT JOIN clans c ON u.clan_id = c.id "
        f"WHERE {' AND '.join(query_conditions)} "
        f"ORDER BY s.{sort} DESC LIMIT :offset, :limit",
        query_parameters | {"offset": offset, "limit": limit},
    )

    return ORJSONResponse(
        {"status": "success", "leaderboard": [dict(row) for row in rows]},
    )