Exemplo n.º 1
0
async def queries():
    queries = get_query_count(request.args)

    worlds = []
    async with app.db.acquire() as conn:
        pst = await conn.prepare(GET_WORLD)
        for _ in range(queries):
            key = random.randint(1, 10000)
            number = await pst.fetchval(key)
            worlds.append({"id": key, "randomNumber": number})

    return jsonify(worlds)
Exemplo n.º 2
0
async def updates():
    queries = get_query_count(request.args)

    new_worlds = []
    async with app.db.acquire() as conn, conn.transaction():
        pst = await conn.prepare(GET_WORLD)

        for _ in range(queries):
            key = random.randint(1, 10000)
            old_number = await pst.fetchval(key)
            new_number = random.randint(1, 10000)
            new_worlds.append((key, new_number))

        await conn.executemany(UPDATE_WORLD, new_worlds)

    return jsonify(
        [{"id": key, "randomNumber": new_number} for key, new_number in new_worlds]
    )
Exemplo n.º 3
0
async def games_json():
    global games
    return jsonify([game.to_json() for game in games if not game.private])
Exemplo n.º 4
0
            if any(excess := find_excess(valid_keys=scheme.keys(), data=data)):
                return (
                    jsonify(
                        error="Bad Request",
                        message="Unexpected keyword arguments provided.",
                        data=excess,
                    ),
                    400,
                )

            if any(missing := find_missing(scheme=scheme, data=data)):
                return (
                    jsonify(
                        error="Bad Request",
                        message="Missing keyword arguments.",
                        data=missing,
                    ),
                    400,
                )

            if out := validate(scheme=scheme, data=data):
                # validate returns `False` if data matches scheme.
                return (
                    jsonify(error="Bad Request",
                            message="JSON Validation failed.",
                            data=out),
                    400,
                )

            kwargs.update(data)
Exemplo n.º 5
0
 async def put(self, id_):
     return await make_response(jsonify({"status": "not implemented"}), 200)
Exemplo n.º 6
0
async def api_lnurl_callback(link_id):
    link = await increment_pay_link(link_id, served_pr=1)
    if not link:
        return jsonify({
            "status": "ERROR",
            "reason": "LNURL-pay not found."
        }), HTTPStatus.OK

    min, max = link.min, link.max
    rate = await get_fiat_rate(link.currency) if link.currency else 1
    if link.currency:
        # allow some fluctuation (as the fiat price may have changed between the calls)
        min = rate * 995 * link.min
        max = rate * 1010 * link.max
    else:
        min = link.min * 1000
        max = link.max * 1000

    amount_received = int(request.args.get("amount"))
    if amount_received < min:
        return (
            jsonify(
                LnurlErrorResponse(
                    reason=
                    f"Amount {amount_received} is smaller than minimum {min}."
                ).dict()),
            HTTPStatus.OK,
        )
    elif amount_received > max:
        return (
            jsonify(
                LnurlErrorResponse(
                    reason=
                    f"Amount {amount_received} is greater than maximum {max}."
                ).dict()),
            HTTPStatus.OK,
        )

    comment = request.args.get("comment")
    if len(comment or "") > link.comment_chars:
        return (
            jsonify(
                LnurlErrorResponse(
                    reason=
                    f"Got a comment with {len(comment)} characters, but can only accept {link.comment_chars}"
                ).dict()),
            HTTPStatus.OK,
        )

    payment_hash, payment_request = await create_invoice(
        wallet_id=link.wallet,
        amount=int(amount_received / 1000),
        memo=link.description,
        description_hash=hashlib.sha256(
            link.lnurlpay_metadata.encode("utf-8")).digest(),
        extra={
            "tag": "lnurlp",
            "link": link.id,
            "comment": comment
        },
    )

    resp = LnurlPayActionResponse(
        pr=payment_request,
        success_action=link.success_action(payment_hash),
        routes=[],
    )

    return jsonify(resp.dict()), HTTPStatus.OK
Exemplo n.º 7
0
async def api_usermanager_users_create():
    user = await create_usermanager_user(**g.data)
    full = user._asdict()
    full["wallets"] = [wallet._asdict() for wallet in await get_usermanager_users_wallets(user.id)]
    return jsonify(full), HTTPStatus.CREATED
Exemplo n.º 8
0
async def api_usermanager_users():
    user_id = g.wallet.user
    return (
        jsonify([user._asdict() for user in await get_usermanager_users(user_id)]),
        HTTPStatus.OK,
    )
Exemplo n.º 9
0
async def api_usermanager_wallets_create():
    user = await create_usermanager_wallet(
        g.data["user_id"], g.data["wallet_name"], g.data["admin_id"]
    )
    return jsonify(user._asdict()), HTTPStatus.CREATED
Exemplo n.º 10
0
async def index():
    return jsonify({"Welcome": "This is a proxy pool system."})
Exemplo n.º 11
0
async def get_user_settings():
    """Get the current user's settings."""
    user_id = await token_check()
    settings = await app.user_storage.get_user_settings(user_id)
    return jsonify(settings)
Exemplo n.º 12
0
async def lndhub_auth():
    token = (g.data["refresh_token"] if "refresh_token" in g.data
             and g.data["refresh_token"] else urlsafe_b64encode(
                 (g.data["login"] + ":" +
                  g.data["password"]).encode("utf-8")).decode("ascii"))
    return jsonify({"refresh_token": token, "access_token": token})
Exemplo n.º 13
0
async def lndhub_decodeinvoice():
    invoice = request.args.get("invoice")
    inv = bolt11.decode(invoice)
    return jsonify(decoded_as_lndhub(inv))
Exemplo n.º 14
0
async def lndhub_getpending():
    "pending onchain transactions"
    return jsonify([])
Exemplo n.º 15
0
 async def get_danmaku_data(token, episode):
     """解析视频的弹幕库信息, 返回 DPlayer 支持的弹幕格式"""
     data = await self._agent.get_danmaku_data(token, int(episode))
     ret = {"code": 0, "data": data.data, "num": data.num}
     return jsonify(ret)
Exemplo n.º 16
0
async def pop_proxy():
    proxy = redis_conn.pop_proxy().decode("utf8")
    if proxy[:5] == "https":
        return jsonify({"https": proxy})
    else:
        return jsonify({"http": proxy})
Exemplo n.º 17
0
async def db():
    async with app.db.acquire() as conn:
        key = random.randint(1, 10000)
        number = await conn.fetchval(GET_WORLD, key)
        return jsonify({"id": key, "randomNumber": number})
Exemplo n.º 18
0
async def count_all_proxies():
    count = redis_conn.count_all_proxies()
    return jsonify({"count": str(count)})
Exemplo n.º 19
0
async def api_usermanager_wallet_transactions(wallet_id):
    return jsonify(await get_usermanager_wallet_transactions(wallet_id)), HTTPStatus.OK
Exemplo n.º 20
0
async def count_score_proxies(score):
    count = redis_conn.count_score_proxies(score)
    return jsonify({"count": str(count)})
Exemplo n.º 21
0
async def api_usermanager_user(user_id):
    user = await get_usermanager_user(user_id)
    return (
        jsonify(user._asdict()),
        HTTPStatus.OK,
    )
Exemplo n.º 22
0
async def clear_proxies(score):
    if redis_conn.clear_proxies(score):
        return jsonify({"Clear": "Successful"})
    return jsonify({"Clear": "Score should >= 0 and <= 10"})
Exemplo n.º 23
0
async def api_usermanager_users_delete(user_id):
    user = await get_usermanager_user(user_id)
    if not user:
        return jsonify({"message": "User does not exist."}), HTTPStatus.NOT_FOUND
    await delete_usermanager_user(user_id)
    return "", HTTPStatus.NO_CONTENT
Exemplo n.º 24
0
async def broadcast():
    data = await request.get_json()
    for queue in app.clients:
        await queue.put(data['message'])
    return jsonify(True)
Exemplo n.º 25
0
async def stop_websocket():
    print("Stoppsing")
    socket_manager = PoloniexWS()
    socket_manager.stop_ws()
    return jsonify({"response": True})
Exemplo n.º 26
0
 async def yobot_users_api():
     if 'yobot_user' not in session:
         return jsonify(
             code=10,
             message='Not logged in',
         )
     user = User.get_by_id(session['yobot_user'])
     if user.authority_group >= 10:
         return jsonify(
             code=11,
             message='Insufficient authority',
         )
     try:
         req = await request.get_json()
         if req is None:
             return jsonify(
                 code=30,
                 message='Invalid payload',
             )
         if req.get('csrf_token') != session['csrf_token']:
             return jsonify(
                 code=15,
                 message='Invalid csrf_token',
             )
         action = req['action']
         if action == 'get_data':
             users = []
             for user in User.select().where(User.deleted == False, ):
                 users.append({
                     'qqid':
                     user.qqid,
                     'nickname':
                     user.nickname,
                     'clan_group_id':
                     user.clan_group_id,
                     'authority_group':
                     user.authority_group,
                     'last_login_time':
                     user.last_login_time,
                     'last_login_ipaddr':
                     user.last_login_ipaddr,
                 })
             return jsonify(code=0, data=users)
         elif action == 'modify_user':
             data = req['data']
             user = User.get_or_none(qqid=data['qqid'])
             if user is None:
                 return jsonify(code=21, message='user not exist')
             for key in data.keys():
                 setattr(user, key, data[key])
             user.save()
             return jsonify(code=0, message='success')
         elif action == 'delete_user':
             user = User.get_or_none(qqid=req['data']['qqid'])
             if user is None:
                 return jsonify(code=21, message='user not exist')
             user.clan_group_id = None
             user.authority_group = 999
             user.password = None
             user.deleted = True
             user.save()
             return jsonify(code=0, message='success')
         else:
             return jsonify(code=32, message='unknown action')
     except KeyError as e:
         return jsonify(code=31, message=str(e))
Exemplo n.º 27
0
async def index():
    a = request.args.get("a")
    session["a"] = a
    return jsonify(dict(session))
Exemplo n.º 28
0
 async def yobot_users_api():
     if 'yobot_user' not in session:
         return jsonify(
             code=10,
             message='Not logged in',
         )
     user = User.get_by_id(session['yobot_user'])
     if user.authority_group >= 10:
         return jsonify(
             code=11,
             message='Insufficient authority',
         )
     try:
         req = await request.get_json()
         if req is None:
             return jsonify(
                 code=30,
                 message='Invalid payload',
             )
         if req.get('csrf_token') != session['csrf_token']:
             return jsonify(
                 code=15,
                 message='Invalid csrf_token',
             )
         action = req['action']
         if action == 'get_data':
             return await asyncio.get_event_loop().run_in_executor(
                 None,
                 self._get_users_json,
                 req['querys'],
             )
             
         elif action == 'modify_user':
             data = req['data']
             m_user: User = User.get_or_none(qqid=data['qqid'])
             if ((m_user.authority_group <= user.authority_group) or
                     (data.get('authority_group', 999)) <= user.authority_group):
                 return jsonify(code=12, message='Exceed authorization is not allowed')
             if data.get('authority_group') == 1:
                 self.setting['super-admin'].append(data['qqid'])
                 save_setting = self.setting.copy()
                 del save_setting['dirname']
                 del save_setting['verinfo']
                 config_path = os.path.join(
                     self.setting['dirname'], 'yobot_config.json')
                 with open(config_path, 'w', encoding='utf-8') as f:
                     json.dump(save_setting, f, indent=4)
             if m_user is None:
                 return jsonify(code=21, message='user not exist')
             for key in data.keys():
                 setattr(m_user, key, data[key])
             m_user.save()
             return jsonify(code=0, message='success')
         elif action == 'delete_user':
             user = User.get_or_none(qqid=req['data']['qqid'])
             if user is None:
                 return jsonify(code=21, message='user not exist')
             user.clan_group_id = None
             user.authority_group = 999
             user.password = None
             user.deleted = True
             user.save()
             return jsonify(code=0, message='success')
         else:
             return jsonify(code=32, message='unknown action')
     except KeyError as e:
         return jsonify(code=31, message=str(e))
Exemplo n.º 29
0
async def post(service_name: str):
    if service_name not in rpc_services:
        abort(404)

    return jsonify(await handle_rpc_request(rpc_services[service_name], await
                                            request.get_json()))
Exemplo n.º 30
0
 def wrapper(*args, **kwargs):
     try:
         UUID(kwargs["GUID"])
     except Exception:
         return jsonify({}), 400
     return func(*args, **kwargs)
Exemplo n.º 31
0
async def deleteUser(current_user):
    db = getDB()
    cur = db.execute("""DELETE FROM Users WHERE username=?""",
                     [current_user["username"]])
    db.commit()
    return jsonify({"message": "User has been deleted."}), 200
Exemplo n.º 32
0
async def get_me_relationships():
    user_id = await token_check()
    return jsonify(await app.user_storage.get_relationships(user_id))
Exemplo n.º 33
0
 async def show_system_version():
     return jsonify(self._config.get_version())
Exemplo n.º 34
0
def json():
    return jsonify(message="Hello, World!")