Пример #1
0
async def get_profile(
    email: str = Body(..., embed=True),
    password: str = Body(..., embed=True),
    account_service: AccountService = Depends(
        Provide[AppContainer.launcher.account_service]),
) -> Account:
    return account_service.find(email, password)
Пример #2
0
 def __init__(
         self,
         useremail: str = Body(...),
         password: str = Body(...),
 ):
     self.useremail = useremail
     self.password = password
Пример #3
0
def create_profile(
    profile_id: str = Cookie(..., alias="PHPSESSID"),
    side: str = Body(..., embed=True),
    nickname: str = Body(..., embed=True),
    profile_service: ProfileService = Depends(Provide[AppContainer.profile.service]),
) -> TarkovSuccessResponse[dict]:
    profile = profile_service.create_profile(
        profile_id=profile_id,
        nickname=nickname,
        side=side,
    )
    return TarkovSuccessResponse(data={"uid": profile.id})
Пример #4
0
def login(
    email: str = Body(..., embed=True),
    password: str = Body(..., embed=True),
    account_service: AccountService = Depends(
        Provide[AppContainer.launcher.account_service]),
) -> PlainTextResponse:
    try:
        account_service.find(email=email, password=password)
        return PlainTextResponse(content=zlib.compress("OK".encode("utf8")))
    except NotFoundError:
        return PlainTextResponse(
            content=zlib.compress("FAILED".encode("utf8")))
Пример #5
0
async def update_audio_data(audioType: str,
                            id: str,
                            req: UpdateAudioModel = Body(...)):

    if audioType.lower() == 'song':
        req = {k: v for k, v in req.dict().items() if v is not None}
        updated_audio = await update_song(id, req)
        if updated_audio:
            return ResponseModel(
                "Audio with ID: {} name update is successful".format(id),
                "Audio name updated successfully",
            )
    elif audioType.lower() == 'podcast':
        req = {k: v for k, v in req.dict().items() if v is not None}
        updated_audio = await update_podcast(id, req)
        if updated_audio:
            return ResponseModel(
                "Audio with ID: {} name update is successful".format(id),
                "Audio name updated successfully",
            )
    elif audioType.lower() == 'audiobook':
        req = {k: v for k, v in req.dict().items() if v is not None}
        updated_audio = await update_audiobook(id, req)
        if updated_audio:
            return ResponseModel(
                "Audio with ID: {} name update is successful".format(id),
                "Audio name updated successfully",
            )
    return ErrorResponseModel(
        "An error occurred",
        400,
        "There was an error updating the Audio data.",
    )
Пример #6
0
async def read_items(item_id: UUID,
                     start_datetime: Optional[datetime] = Body(None),
                     end_datetime: Optional[datetime] = Body(None),
                     repeat_at: Optional[time] = Body(None),
                     process_after: Optional[timedelta] = Body(None)):
    start_process = start_datetime + process_after
    duration = end_datetime - start_process
    return {
        "item_id": item_id,
        "start_datetime": start_datetime,
        "end_datetime": end_datetime,
        "repeat_at": repeat_at,
        "process_after": process_after,
        "start_process": start_process,
        "duration": duration
    }
Пример #7
0
def client_game_profile_item_move(
    profile: Profile = Depends(with_profile),
    body: dict = Body(...),
) -> Union[TarkovSuccessResponse[DispatcherResponse], TarkovErrorResponse]:
    dispatcher = DispatcherManager(profile)
    response = dispatcher.dispatch(body["data"])
    return TarkovSuccessResponse(data=response)
Пример #8
0
async def reset_password(
        token: str = Header(..., alias="x-token"),
        password_data: PasswordInWrite = Body(...),
):
    check_token(token)
    user_data = await async_user_collection.find_one(
        {'password_reset_token': token})
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    new_hash = create_password(password_data.password)
    updated_at = int(time.time())
    await async_user_collection.update_one({'_id': user_data['_id']}, {
        '$set': {
            'password': new_hash,
            'updated_at': updated_at,
        },
        '$unset': {
            'password_reset_token': ''
        },
    })
    await async_client_user_cache_collection.update_many(
        {'user_id': user_data['_id']},
        {'$set': {
            'last_modified': updated_at
        }},
    )
Пример #9
0
async def mail_dialog_info(
    dialogue_id: str = Body(..., alias="dialogId", embed=True),
    profile: Profile = Depends(profile_manager.with_profile),
) -> Union[TarkovSuccessResponse[dict], TarkovErrorResponse]:
    dialogue_preview = profile.mail.view.view_dialog_preview(
        dialogue_id=dialogue_id)
    return TarkovSuccessResponse(data=dialogue_preview)
Пример #10
0
async def create_user(user: schemas.UserBase = Body(..., embed=True)):
    db_user = crud.get_user_by_email(email=user.email)
    db_user1 = crud.get_user_by_username(username=user.username)
    if db_user:
        raise HTTPException(status_code=400, detail="Cet Email existe deja")
    if db_user1:
        raise HTTPException(status_code=400,
                            detail="Ce nom d'utilisateur existe deja")
    return crud.create_user(user=user)
Пример #11
0
async def post_topic(
        body: dict = Body(
            ...,
            example={
                "message":
                "Post your message here, it will be relayed to twitch chat"
            }),
        api_key: APIKey = Depends(get_api_key),
):
    """Manual testing
    curl --header "Content-Type: application/json" --header "access_token: testKey" --request POST --data '{"topic":"Test topic sent from a json post"}' http://localhost:5000/topic
    curl --header "Content-Type: application/json" --request POST --data '{"topic":"Test"}' http://localhost:5000/topic?access_token=testKey
    """  # noqa E501
    if body.get("topic", False):
        uri = "ws://bot:13337"
        try:
            async with websockets.connect(uri) as s:

                # We don't actually need this, but we have to read it before the bot will accept commands
                await s.recv()

                # There are two entries returned, and we need to retrieve both
                await s.recv()

                topic = f"set {body['topic']}".split(
                )  # 'set' is the subcommand and needs to be sent as part of the args
                msg = dict(
                    type="run_command",
                    command="!topic",
                    channel=getenv("TWITCH_CHANNEL"),
                    args=topic,
                    silent=True,
                )
                msg_txt = json.dumps(msg) + "\n"
                await s.send(msg_txt.encode("utf8"))
                await s.send("\n".encode("utf8"))
                # Check if the message was successful
                resp = json.loads(await s.recv())
                print(resp)
                if resp.get("type", "fail") != "success":
                    return JSONResponse({
                        "success": False,
                        "detail": "Error sending bot message."
                    })

                return JSONResponse({"success": True})

        except ConnectionRefusedError:
            print("Unable to connect to bot.")
            return JSONResponse({
                "success": False,
                "detail": "Unable to connect to bot."
            })

        except Exception as e:
            print(f"Unknown exception trying to send message to bot. {e}")
            return JSONResponse({"success": False, "detail": str(e)})
Пример #12
0
async def add_item_to_list(id: str, request: Request, item: Item = Body(...)):
    """
    add item to a list
    """
    item = jsonable_encoder(item)
    await request.app.mongodb["lists"].update_one({"_id": id},
                                                  {"$push": {
                                                      "items": item
                                                  }})
    return JSONResponse(status_code=status.HTTP_200_OK)
Пример #13
0
async def create_client(
        client_data: ClientInCreate = Body(...),
        user: UserInfo = Depends(Authentication()),
):
    """Creates a client."""
    if 'admin' not in user['roles']:
        raise HTTPException(401)
    new_client = Client.validate(client_data)
    await async_client_collection.insert_one(
        new_client.dict(exclude_none=True, by_alias=True))
Пример #14
0
async def screenshot(body: ChromeTask = Body(...)) -> StreamingResponse:
    results = await get_files([body])

    if not len(results):
        raise HTTPException(status_code=400, detail=f"Bad URL in task")

    file = results[0]

    return StreamingResponse(BytesIO(file.content),
                             media_type="application/pdf")
Пример #15
0
def make_installments(
    installments: List[scraper.InstallmentAccount],
    payMode: scraper.PayMode = Body(scraper.PayMode.CASH),
    auth_token: scraper.AuthToken = Depends(get_auth_token),
):
    reference_number = scraper.prepare_installments(
        auth_token,
        installments,
        payMode,
    )
    return InstallmentsResponse(reference_number=reference_number)
Пример #16
0
async def create_new_checklist(request: Request,
                               checklist: Checklist = Body(...)):
    """
    create a new checklist
    """
    clist = jsonable_encoder(checklist)
    new_clist = await request.app.mongodb["lists"].insert_one(clist)
    created_list = await request.app.mongodb["lists"].find_one(
        {"_id": new_clist.inserted_id})
    return JSONResponse(status_code=status.HTTP_201_CREATED,
                        content=created_list)
Пример #17
0
async def terminate(
    msisdn: str,
    programcode: ProgramCode,
    ctsversion: CtsVersion,
    request: dict = Body(...),
):
    """
    Terminate msisdn with ctsversion picks a service based on client telematics version and terminate the call associated with msisdn.
    """
    logger.info(
        "Terminate: Payload received for msisdn:{}".format(msisdn),
        extra={
            "msisdn": msisdn,
            "programcode": programcode,
            "cts-version": ctsversion,
            "payload": request,
            "action": "Terminate",
        },
    )

    service_manager = setup_service_manager(programcode, ctsversion)
    dataresponse = service_manager.client_service.terminate(
        msisdn, programcode, request
    )
    if dataresponse.status == InternalStatusType.SUCCESS:
        mappedresponse = CreateTerminateResponse(msisdn=msisdn, status=Status.CREATED)
        logger.info(
            "Terminate: Success for msisdn:{}".format(msisdn),
            extra={
                "msisdn": msisdn,
                "programcode": programcode,
                "cts-version": ctsversion,
                "payload": request,
                "status-code": mappedresponse.status,
                "action": "Terminate",
            },
        )
        return JSONApiSuccessResponse[CreateTerminateResponse](data=mappedresponse)
    else:
        exceptiontype = handle_error_responsestatus(dataresponse.status)
        logger.error(
            "Terminate: Failed for msisdn:{} status:{} reason:{}".format(
                msisdn, dataresponse.status, dataresponse.responsemessage
            ),
            extra={
                "msisdn": msisdn,
                "programcode": programcode,
                "cts-version": ctsversion,
                "payload": request,
                "status-code": exceptiontype().status_code,
                "action": "Terminate",
            },
        )
        raise exceptiontype(dataresponse.responsemessage)
Пример #18
0
async def save_vehicledata(
    msisdn: str,
    programcode: ProgramCode,
    ctsversion: CtsVersion,
    request: dict = Body(...),
):
    """
    Save_VehicleData msisdn with ctsversion picks a service based on client telematics version and saves the vehicle data.
    """
    logger.info(
        "SaveVehicleData: Payload received for msisdn:{} data:{}".format(
            msisdn, request
        ),
        extra={
            "msisdn": msisdn,
            "programcode": programcode,
            "cts-version": ctsversion,
            "action": "SaveVehicleData",
        },
    )

    service_manager = setup_service_manager(programcode, ctsversion)

    saveresponse = service_manager.client_service.save_vehicledata(
        msisdn, programcode, request
    )
    if saveresponse.status == InternalStatusType.SUCCESS:
        mappedresponse = CreateSaveVehicleDataResponse(
            msisdn=msisdn,
            status=Status.CREATED,
            responsemessage=saveresponse.responsemessage,
        )
        logger.info(
            "SaveVehicleData: Success for msisdn:{}".format(msisdn),
            extra={
                "msisdn": msisdn,
                "programcode": programcode,
                "cts-version": ctsversion,
                "status-code": mappedresponse.status,
                "action": "SaveVehicleData",
            },
        )
        return JSONApiSuccessResponse[CreateSaveVehicleDataResponse](
            data=mappedresponse
        )
    else:
        raise save_msisdn_error(
            saveresponse.status,
            saveresponse.responsemessage,
            msisdn,
            programcode,
            ctsversion,
        )
Пример #19
0
def nickname_validate(
    nickname: str = Body(..., embed=True),
    account_service: AccountService = Depends(
        Provide[AppContainer.launcher.account_service]),
) -> Union[TarkovSuccessResponse, TarkovErrorResponse]:
    if len(nickname) < 3:
        return TarkovErrorResponse(errmsg="Nickname is too short", err=256)

    if account_service.is_nickname_taken(nickname):
        return TarkovErrorResponse(errmsg="Nickname is taken", err=255)

    return TarkovSuccessResponse(data={"status": "ok"})
Пример #20
0
def download_pretrained_model(pid: str,
                              response: Response,
                              pretrained_model: PretrainedModel = Body(...)):
    project_loc = os.path.join(config['storage'], pid)
    print(pretrained_model)
    if not os.path.exists(project_loc):
        response.status_code = status.HTTP_406_NOT_ACCEPTABLE
        return {"message": "Project [{}] did not exist".format(pid)}

    job = ioJob.download_model.delay(
        pretrained_model.url,
        os.path.join(project_loc, 'models', pretrained_model.name), True)
    return {"jobId": job.id}
Пример #21
0
async def create_user(no_registration: bool = Query(False),
                      create_data: Dict[str, Any] = Body(...),
                      user: UserInfo = Depends(Authentication())):
    """Updates user data."""
    is_admin = 'admin' in user['roles']
    if not is_admin:
        raise HTTPException(401)

    user_data = DotDict()
    await _update_user(user_data,
                       create_data,
                       is_new=True,
                       is_admin=True,
                       no_registration=no_registration)
Пример #22
0
async def user_login(user: UserLoginSchema = Body(...)):
    u = json.loads(user.json())
    # u["password"] = get_password_hash(u["password"])
    data = UserSchema(username=u["username"], password=u["password"])
    user_ = check_user(data)
    if user_ is not None:
        # token = get_routes_from_cache('users_id:' + str(user_[0]))
        # if token is not None:
        #     d = token.decode('utf8').replace("'", '"')
        #     return json.loads(d)
        if not verify_password(u["password"], user_[5]):
            return False
        return sign_jwt(user_[0])
    return {"error": "Wrong login details!"}
Пример #23
0
async def create_group(
        group_data: GroupInCreate = Body(...),
        user: UserInfo = Depends(Authentication()),
):
    """Creates a group."""
    if 'admin' not in user['roles']:
        raise HTTPException(401)
    new_group = UserGroup.validate(group_data)
    new_group.id = new_group.id.lower()
    if not new_group.enable_email:
        new_group.email_forward_members = []
        new_group.email_allowed_forward_members = []
    if not new_group.enable_postbox:
        new_group.email_postbox_access_members = []
    await async_user_group_collection.insert_one(new_group.dict(exclude_none=True, by_alias=True))
    timestamp = int(time.time())
    if new_group.members:
        await async_client_user_cache_collection.delete_many({'user_id': {'$in': new_group.members}})
        await async_user_collection.update_many(
            {'_id': {'$in': new_group.members}},
            {
                '$addToSet': {'groups': new_group.id},
                '$set': {'updated_at': timestamp},
            }
        )
    if new_group.email_forward_members:
        await async_user_collection.update_many(
            {'_id': {'$in': new_group.email_forward_members}},
            {
                '$addToSet': {'email_forward_groups': new_group.id},
                '$set': {'updated_at': timestamp},
            }
        )
    if new_group.email_allowed_forward_members:
        await async_user_collection.update_many(
            {'_id': {'$in': new_group.email_allowed_forward_members}},
            {
                '$addToSet': {'email_allowed_forward_groups': new_group.id},
                '$set': {'updated_at': timestamp},
            }
        )
    if new_group.email_postbox_access_members:
        await async_user_collection.update_many(
            {'_id': {'$in': new_group.email_postbox_access_members}},
            {
                '$addToSet': {'email_postbox_access_groups': new_group.id},
                '$set': {'updated_at': timestamp},
            }
        )
Пример #24
0
def infer(pid: str,
          model: str,
          train: str,
          response: Response,
          params: InferenceRequestModel = Body(...)):
    project_loc = os.path.join(config['storage'], pid)
    if not os.path.exists(project_loc):
        response.status_code = status.HTTP_406_NOT_ACCEPTABLE
        return {"message": "Project [{}] did not exist".format(pid)}
    # try:
    mlJob.inference_model.delay(
        os.path.join(project_loc, 'models', model, 'customs', train,
                     'exported_model', 'saved_model'),
        os.path.join(project_loc, 'data', params.label_map_dir),
        os.path.join(project_loc, 'data', params.input_dir),
        os.path.join(project_loc, 'data', params.output_dir))
    return {"message": "Done"}
Пример #25
0
async def save_register_user(
        token: str = Header(..., alias="x-token"),
        update_data: Dict[str, Any] = Body(...),
):
    """Gets user data for registration."""
    check_token(token)
    user_data = DotDict.from_obj(await async_user_collection.find_one({
        'registration_token':
        token,
    }))
    if user_data is None:
        raise HTTPException(401, "Invalid token")
    del user_data['registration_token']
    await _update_user(user_data,
                       update_data,
                       is_registering=True,
                       is_self=True)
Пример #26
0
def post_items_all_params(
    item_id: str = Path(...),
    body: Item = Body(...),
    query_a: int = Query(None),
    query_b=Query(None),
    coo: str = Cookie(None),
    x_head: int = Header(None),
    x_under: str = Header(None, convert_underscores=False),
):
    return {
        "item_id": item_id,
        "body": body,
        "query_a": query_a,
        "query_b": query_b,
        "coo": coo,
        "x_head": x_head,
        "x_under": x_under,
    }
Пример #27
0
async def update_user(user_id: str,
                      update_data: Dict[str, Any] = Body(...),
                      user: UserInfo = Depends(Authentication())):
    """Updates user data."""
    is_admin = 'admin' in user['roles']
    is_self = user.sub == user_id
    if not is_self and not is_admin:
        raise HTTPException(401)
    user_data = DotDict.from_obj(await async_user_collection.find_one(
        {'_id': user_id}))
    if user_data is None:
        raise HTTPException(404)
    if not update_data:
        return
    await _update_user(user_data,
                       update_data,
                       is_admin=is_admin,
                       is_self=is_self)
Пример #28
0
async def request_reset_password(password_reset: PasswordReset = Body(...), ):
    user_data = DotDict.from_obj(await async_user_collection.find_one(
        {'email': password_reset.email}))
    if user_data is None:
        return
    if user_data.get('registration_token'):
        await update_resend_registration(user_data)
    else:
        token_valid_until = int(time.time() +
                                config.manager.token_valid.password_reset)
        user_data['password_reset_token'] = create_token(
            user_data['_id'], token_valid_until)

        await async_user_collection.update_one({'_id': user_data['_id']}, {
            '$set': {
                'password_reset_token': user_data['password_reset_token']
            },
        })
        await async_send_mail_reset_password(user_data, token_valid_until)
Пример #29
0
def edit_pipeline(pid: str,
                  model: str,
                  train: str,
                  response: Response,
                  cfg: ConfigPipelineRequestModel = Body(...)):
    project_loc = os.path.join(config['storage'], pid)
    if not os.path.exists(project_loc):
        response.status_code = status.HTTP_406_NOT_ACCEPTABLE
        return {"message": "Project [{}] did not exist".format(pid)}
    if not os.path.exists(os.path.join(project_loc, 'models', model)):
        response.status_code = status.HTTP_406_NOT_ACCEPTABLE
        return {"message": "Model [{}] not found".format(model)}
    try:
        with open(
                os.path.join(project_loc, 'models', model, 'customs', train,
                             '{}.config'.format(train)), 'w') as pipeline_conf:
            pipeline_conf.write(cfg.config)
        return {'message': 'Set new config'}
    except:
        return {'message': 'Cannot edit config'}
Пример #30
0
def gen_tfrecord(pid: str,
                 response: Response,
                 data_path: DatasetPath = Body(...)):
    project_loc = os.path.join(config['storage'], pid)
    if not os.path.exists(project_loc):
        response.status_code = status.HTTP_406_NOT_ACCEPTABLE
        return {"message": "Project [{}] did not exist".format(pid)}
    data_path.path_to_annotation = os.path.join(project_loc, 'data',
                                                data_path.path_to_annotation)
    data_path.path_to_images = os.path.join(project_loc, 'data',
                                            data_path.path_to_images)
    data_path.path_to_label_map = os.path.join(project_loc, 'data',
                                               data_path.path_to_label_map)
    data_path.path_to_tfrecord = os.path.join(project_loc, 'data',
                                              data_path.path_to_tfrecord)
    job = mlJob.gen_tfrecord.delay(pid, data_path.path_to_images,
                                   data_path.path_to_annotation,
                                   data_path.path_to_label_map,
                                   data_path.path_to_tfrecord)
    return {"jobId": job.id}