コード例 #1
0
ファイル: articles.py プロジェクト: Taller-2/app-server
def create_question(_id):
    try:
        article = Article.get_one(_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400

    if not article:
        return response(message=f"Article {_id} not found", ok=False), 400

    account = Account.current()
    resp, status_code = create(Question,
                               additional_fields={
                                   'created_at': datetime.utcnow(),
                                   'article_id': _id,
                                   'user_id': account.get_id()
                               })

    if status_code == 200:
        question = Question.get_one(resp.json['_id'])
        FirebaseMessage(
            {
                'title': f'Nueva pregunta de {account["name"]}',
                'message': f'{question["question"]}',
                'question': question.get_id(),
                'type': 'new_question'
            },
            to=article.account()).send()

    return resp, status_code
コード例 #2
0
def subscription_loop():
    bestblockhash = None
    mempool = []

    while True:
        data = General().info()
        if "result" in data:
            if "bestblockhash" in data["result"]:
                if data["result"]["bestblockhash"] != bestblockhash:
                    bestblockhash = data["result"]["bestblockhash"]

                    sio.emit("block.update",
                             utils.response({
                                 "height": data["result"]["blocks"],
                                 "hash": bestblockhash
                             }),
                             room="blocks")

                    updates = Block().inputs(bestblockhash)
                    for address in updates:
                        mempool = list(set(mempool) - set(updates[address]))

                        sio.emit("address.update",
                                 utils.response({
                                     "address":
                                     address,
                                     "tx":
                                     updates[address],
                                     "height":
                                     data["result"]["blocks"],
                                     "hash":
                                     bestblockhash
                                 }),
                                 room=address)

                data = General().mempool()
                temp_mempool = []

                if not data["error"]:
                    updates = Transaction.addresses(data["result"]["tx"])
                    for address in updates:
                        updates[address] = list(
                            set(updates[address]) - set(mempool))
                        temp_mempool += updates[address]

                        if len(updates[address]) > 0:
                            sio.emit("address.update",
                                     utils.response({
                                         "address": address,
                                         "tx": updates[address],
                                         "height": None,
                                         "hash": None
                                     }),
                                     room=address)

                mempool = list(set(mempool + temp_mempool))

        sio.sleep(0)
コード例 #3
0
ファイル: purchases.py プロジェクト: Taller-2/app-server
def get_article(body):
    article_id = body.get('article_id')
    try:
        article = Article.get_one(article_id)
        if article is None:
            return None, response("article was not found", ok=False), 400
    except ValueError:
        return None, response(f"article_id not specified", ok=False), 400
    return article, None
コード例 #4
0
ファイル: purchases.py プロジェクト: Taller-2/app-server
def check_required_fields(body):
    if body is None:
        return response("Request body is null", ok=False), 400
    if not body.get('units'):
        return response("units not specified", ok=False), 400
    if not body.get('price'):
        return response("price not specified", ok=False), 400
    if not body.get('payment_method'):
        return response("payment_method not specified", ok=False), 400
    return None
コード例 #5
0
ファイル: articles.py プロジェクト: Taller-2/app-server
def questions(_id):
    try:
        article = Article.get_one(_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400

    if not article:
        return response(message=f"Article {_id} not found", ok=False), 400

    return jsonify({
        'data': [q.to_json() for q in Question.get_many(article_id=_id)],
        'ok':
        True
    })
コード例 #6
0
ファイル: accounts.py プロジェクト: Taller-2/app-server
def update_current_account():
    body = request.get_json(silent=True)

    if not body:
        return response("Invalid or empty request body", ok=False), 400

    account = Account.current()
    account['email'] = body.get('email')
    account['name'] = body.get('name')
    account['profile_picture_url'] = body.get('profile_picture_url')
    account['instance_id'] = body.get('instance_id')
    account.save()

    return response(message="Successfully updated current account!", ok=True)
コード例 #7
0
def get():
    try:
        questions = QuestionController(**request.args).get_questions()
    except ValueError as e:
        return response(message=f"Error parsing querystring parameters. "
                        f"{e}",
                        ok=False), 400
    except KeyError as e:
        keys = ', '.join(Question.schema.keys())
        return response(message=f"Invalid key {e}. "
                        f"Valid parameters are {keys}",
                        ok=False), 400

    return jsonify({'data': questions, 'ok': True})
コード例 #8
0
ファイル: login_required.py プロジェクト: Taller-2/app-server
 def decorated_function(*args, **kwargs):
     if current_app.config['SKIP_AUTH']:
         get_or_create_mock_account()
         return func(*args, **kwargs)
     if 'HTTP_AUTHORIZATION' not in request.headers.environ:
         return response(message='Unauthorized', ok=False), 401
     claims = google.oauth2.id_token.verify_firebase_token(
         request.headers.environ['HTTP_AUTHORIZATION'],
         google.auth.transport.requests.Request())
     if not claims:
         g.user_id = None
         return response(message='Unauthorized', ok=False), 401
     g.user_id = claims['user_id']
     get_or_create_account(claims)
     return func(*args, **kwargs)
コード例 #9
0
ファイル: article_stats.py プロジェクト: Taller-2/app-server
 def get_article_stats(cls):
     try:
         articles_statistics = ArticleStatistics.get_many(**request.args)
     except ValueError:
         received = request.query_string.decode('utf-8')
         return response(message=f"Error parsing querystring parameters. "
                                 f"Received '{received}'",
                         ok=False), 400
     except KeyError as e:
         keys = ', '.join(ArticleStatistics.schema.keys())
         return response(message=f"Invalid key {e}. "
                                 f"Valid parameters are {keys}",
                         ok=False), 400
     data = [article.to_json() for article in articles_statistics]
     return jsonify({"ok": True, "data": data}), 200
コード例 #10
0
ファイル: rest.py プロジェクト: widecoin-project/api-server
def blocks_by_range(args, height):
    offset = args["offset"]

    if offset > 100:
        offset = 100

    result = Block().range(height, offset)
    return jsonify(utils.response(result))
コード例 #11
0
ファイル: purchases.py プロジェクト: Taller-2/app-server
def buy():
    body = request.json

    error_response = check_required_fields(body)
    if error_response:
        return error_response

    article, error_response = get_article(body)
    if error_response:
        return error_response

    account = Account.current()
    account_id = account.get_id()

    if user_id() == article['user']:
        return response("You can't purchase your own article", ok=False), 400

    article['available_units'] -= body.get('units')
    if article['available_units'] < 0:
        return response("not enough units", ok=False), 400
    article.save()

    resp, status_code = create(Purchase,
                               additional_fields={
                                   'user_id':
                                   account_id,
                                   'requested_shipment':
                                   bool(body.get('shipment_address'))
                               },
                               after_save=after_purchase(
                                   body.get('price'),
                                   body.get('payment_method'),
                                   body.get('shipment_address')))

    if status_code == 200:
        msg = f'Vendiste {body.get("units")} de ' \
              f'{article["name"]} a {account["name"]})'
        FirebaseMessage(
            {
                'title': "Artículo vendido",
                "message": msg,
                "type": "product_sold",
            },
            to=Purchase.get_one(resp.json['_id']).seller()).send()

    return resp, status_code
コード例 #12
0
def init():
    bestblockhash = None

    while True:
        data = General().info()
        if data['result']['bestblockhash'] != bestblockhash:
            bestblockhash = data['result']['bestblockhash']
            sio.emit('block.update',
                     utils.response({
                         'height': data['result']['blocks'],
                         'hash': bestblockhash
                     }),
                     room='blocks')

            updates = Block().inputs(bestblockhash)
            for address in updates:
                mempool = list(set(state.mempool) - set(updates[address]))
                if address in state.rooms:
                    sio.emit('address.update',
                             utils.response({
                                 'address': address,
                                 'tx': updates[address],
                                 'height': data['result']['blocks'],
                                 'hash': bestblockhash
                             }),
                             room=address)

        data = General().mempool()
        updates = Transaction().addresses(data['result']['tx'])
        temp_mempool = []
        for address in updates:
            updates[address] = list(set(updates[address]) - set(mempool))
            temp_mempool += updates[address]
            if address in state.rooms:
                if len(updates[address]) > 0:
                    sio.emit('address.update',
                             utils.response({
                                 'address': address,
                                 'tx': updates[address],
                                 'height': None,
                                 'hash': None
                             }),
                             room=address)

        mempool = list(set(mempool + temp_mempool))
コード例 #13
0
def blocks_by_range(height):
    offset = request.args.get("offset")
    offset = int(0 if offset is None else offset)

    if offset > 100:
        offset = 100

    result = Block().range(height, offset)
    return jsonify(utils.response(result))
コード例 #14
0
    def fee(cls):
        #data = utils.make_request('estimatesmartfee', [6])

        #if data['error'] is None:
        #	data['result']['feerate'] = utils.satoshis(data['result']['feerate'])

        #return data

        return utils.response({'feerate': utils.satoshis(0.001), 'blocks': 6})
コード例 #15
0
    def check(cls, addresses: list):
        addresses = list(set(addresses))
        result = []
        for address in addresses:
            data = utils.make_request("getaddresstxids", [address])
            if len(data["result"]) > 0:
                result.append(address)

        return utils.response(result)
コード例 #16
0
    def get(self, height):
        parser = reqparse.RequestParser()
        parser.add_argument('offset', type=int, default=30)
        args = parser.parse_args()

        if args['offset'] > 100:
            args['offset'] = 100

        result = Block().range(height, args['offset'])
        return utils.response(result)
コード例 #17
0
ファイル: articles.py プロジェクト: Taller-2/app-server
def delete_article(_id):
    try:
        article = Article.get_one(_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400

    if not article:
        return response(message=f"Article {_id} not found", ok=False), 400

    if article['user'] != user_id():
        return response(message=f"User {user_id()} is not the "
                        f"owner of article {_id}",
                        ok=False), 401

    deleted = article.delete()
    if not deleted.deleted_count:
        return response(message=f"Error deleting article", ok=False), 500
    return response(message=f"Successfully deleted article {_id}",
                    ok=True), 200
コード例 #18
0
    def fee(cls):
        # ToDo: Fix me

        # data = utils.make_request("estimatesmartfee", [6])

        # if data["error"] is None:
        #   data["result"]["feerate"] = utils.satoshis(data["result"]["feerate"])

        # return data

        return utils.response({"feerate": utils.satoshis(0.0001), "blocks": 6})
コード例 #19
0
    def fee(cls):
        data = utils.make_request("estimatesmartfee", [6])

        if "errors" in data["result"]:
            return utils.response({
                "feerate": utils.satoshis(0.0001),
                "blocks": 6
            })

        data["result"]["feerate"] = utils.satoshis(data["result"]["feerate"])

        return data
コード例 #20
0
ファイル: articles.py プロジェクト: Taller-2/app-server
def answer_question(article_id, question_id):
    try:
        article = Article.get_one(article_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400

    if not article:
        return response(message=f"Article {article_id} not found",
                        ok=False), 400

    try:
        question = Question.get_one(question_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400

    body = request.get_json(silent=True)
    if not body:
        return response("Invalid or empty request body", ok=False), 400

    answer = body.get('answer')
    if not answer:
        return response("No answer specified", ok=False), 400

    answered_at = datetime.utcnow()

    question.update(**{'answer': answer, 'answered_at': answered_at})
    account = Account.current()
    FirebaseMessage(
        {
            'title': f'Nueva respuesta de {account["name"]}',
            'message': f'{question["answer"]}',
            'article_id': article_id,
            'type': 'new_answer'
        },
        to=Account.get_one(question['user_id'])).send()

    return jsonify({"ok": True, "data": question.to_json()}), 200
コード例 #21
0
    def fee(cls):
        # ToDo: Fix me
        # https://github.com/sugarchain-project/sugarchain/issues/34

        # data = utils.make_request('estimatesmartfee', [6])

        # if data['error'] is None:
        # 	data['result']['feerate'] = utils.satoshis(data['result']['feerate'])

        # return data

        return utils.response({
            'feerate': utils.satoshis(0.00001),
            'blocks': 6
        })
コード例 #22
0
ファイル: articles.py プロジェクト: Taller-2/app-server
def shipment_cost(_id):
    args = request.args
    lat = args.get('my_lat')
    lon = args.get('my_lon')
    if not (lat and lon):
        return response(message=f"latitude and longitude missing",
                        ok=False), 400
    try:
        lat = float(lat)
        lon = float(lon)
    except ValueError:
        return response(message="latitude and longitude must be numbers",
                        ok=False), 400
    try:
        article = Article.get_one(_id)
    except ValueError as e:
        return response(message=str(e), ok=False), 400
    if not article:
        return response(message=f"Article {_id} not found", ok=False), 400
    cash_response = shared_server.shipment_cost(article, lat, lon, 'cash')
    credit_response = shared_server.shipment_cost(article, lat, lon, 'credit')
    debit_response = shared_server.shipment_cost(article, lat, lon, 'debit')
    cash_data = cash_response.json()
    credit_data = credit_response.json()
    debit_data = debit_response.json()
    success = cash_data["success"]
    success = success and credit_data["success"]
    success = success and debit_data["success"]
    return jsonify({
        'ok': success,
        'data': {
            'cash': cash_data["cost"],
            'credit': credit_data["cost"],
            'debit': debit_data["cost"]
        }
    }), 200 if success else 500
コード例 #23
0
ファイル: general.py プロジェクト: nooncoin/api-server
    def fee(cls):
        # ToDo: Fix me
        # https://github.com/nooncoin/api-server/issue/

        # data = utils.make_request("estimatesmartfee", [6])

        # if data["error"] is None:
        #   data["result"]["feerate"] = utils.satoshis(data["result"]["feerate"])

        # return data

        return utils.response({
            "feerate": utils.satoshis(0.00001),
            "blocks": 6
        })
コード例 #24
0
ファイル: purchases.py プロジェクト: Taller-2/app-server
def add_payment_and_shipment_status(purchases):
    purchase_with_status = []
    for purchase in purchases:
        _response = shared_server.status(purchase['_id']).json()
        if not _response['success']:
            return response(f"shared server: {_response['error']}",
                            ok=False), 400
        purchase_with_status.append({
            **purchase,
            **{
                'payment_status': _response['payment_status'],
                'shipment_status': _response['shipment_status']
            }
        })
    return purchase_with_status
コード例 #25
0
    def fee(cls):
        # ToDo: Fix me
        # https://github.com/sugarchain-project/sugarchain/issues/34

        # data = utils.make_request("estimatesmartfee", [6])

        # if data["error"] is None:
        #   data["result"]["feerate"] = utils.satoshis(data["result"]["feerate"])

        # return data

        return utils.response({
            "feerate": utils.satoshis(0.00001),
            "blocks": 6
        })
コード例 #26
0
    def price(cls, currency="RPD"):
        slugs = {"RPD": "rapids", "PRCY": "prcy-coin", "DAPS": "daps-token"}

        if currency not in slugs:
            return utils.dead_response("Currency not found")

        slug = slugs[currency]
        link = f"https://api.coingecko.com/api/v3/simple/price?ids={slug}&vs_currencies=usd,btc,gbp,eur"
        data = requests.get(link).json()

        return utils.response({
            "usd": str(data[slug]["usd"]),
            "btc": str(data[slug]["btc"]),
            "gbp": str(data[slug]["gbp"]),
            "eur": str(data[slug]["eur"])
        })
コード例 #27
0
def TransactionBatch(hashes=[]):
    result = []
    for thash in hashes:
        result.append(Transaction.info(thash))

    return utils.response(result)
コード例 #28
0
 def get(self):
     data = General().supply()
     return utils.response(data)
コード例 #29
0
 def fee(cls):
     return utils.response({"feerate": utils.satoshis(0.001), "blocks": 6})
コード例 #30
0
ファイル: rest.py プロジェクト: bdcashdev/api-server
 def get(self):
     data = General().price()
     return utils.response(data["sugarchain"])