Beispiel #1
0
    def unsubscribe_from_anime(self, anime_doc_id: str):
        try:
            anime = client.query(
                q.get(q.ref(q.collection(animes), anime_doc_id)))
            client.query(
                q.let(
                    {
                        'anime_ref':
                        q.ref(q.collection(animes), anime_doc_id),
                        'bot_user':
                        q.ref(q.collection(users), self.chat_id),
                        'followers':
                        q.select(['data', 'followers'],
                                 q.get(q.var('anime_ref'))),
                    },
                    q.do(
                        q.update(
                            q.var('anime_ref'), {
                                'data': {
                                    'followers': q.subtract(
                                        q.var('followers'), 1)
                                }
                            }),
                        q.update(
                            q.var('bot_user'), {
                                'data': {
                                    'animes_watching':
                                    q.filter_(
                                        q.lambda_(
                                            'watched_anime_ref',
                                            q.not_(
                                                q.equals(
                                                    q.var('watched_anime_ref'),
                                                    q.var('anime_ref')))),
                                        q.select(['data', 'animes_watching'],
                                                 q.get(q.var('bot_user'))))
                                }
                            }),
                        q.if_(q.equals(q.var('followers'), 1),
                              q.delete(q.var('anime_ref')), 'successful!'))))

            updater.bot.send_message(chat_id=self.chat_id,
                                     text='You have stopped following ' +
                                     anime['data']['title'])
        except errors.NotFound:
            logger.info(
                'Somehow, a user {0} almost unsubscribed from an anime that did not exist'
                .format(self.chat_id))
        except Exception as err:
            log_error(err)
Beispiel #2
0
def update_documents(sql_query: sql.SQLQuery) -> QueryExpression:
    """Update document fields with the given values.

    Params:
    -------
    table: Table object that contains the parameters for building an update query in FQL.

    Returns:
    --------
    An FQL update query for the given collection and documents.
    """
    assert len(sql_query.tables) == 1
    table = sql_query.tables[0]
    assert len(sql_query.filter_groups) <= 1
    filter_group = (None if not any(sql_query.filter_groups) else
                    sql_query.filter_groups[0])

    field_updates = {column.name: column.value for column in table.columns}
    return q.let(
        {"document_set": build_document_set_intersection(table, filter_group)},
        q.do(
            q.update(
                q.select(
                    "ref",
                    q.get(q.var("document_set")),
                ),
                {"data": field_updates},
            ),
            {"data": [{
                "count": q.count(q.var("document_set"))
            }]},
        ),
    )
Beispiel #3
0
def product(id):
    if request.method == "GET":
        try:
            response = client.query(q.get(q.ref(q.collection("products"), id)))
            return jsonify(data=response["data"])

        except errors.NotFound:
            return jsonify(data=None)

    elif request.method == "PUT":
        # update a products document
        try:
            response = client.query(
                q.update(q.ref(q.collection("products"), id),
                         {"data": response.get_json()}))
        except Exception as e:
            return jsonify(error=str(e))

    elif request.method == "DELETE":
        # delete a reviews document
        try:
            response = client.query(
                q.delete(q.ref(q.collection("products"), id)))
            return response
        except Exception as e:
            return jsonify(error=str(e))
Beispiel #4
0
def subscribe(update, context):
    chat_id = update.effective_chat.id

    try:
        client.query(
            q.if_(
                q.exists(q.ref(q.collection(users), chat_id)),
                q.update(q.ref(q.collection(users), chat_id),
                         {'data': {
                             'last_command': 'subscribe'
                         }}),
                q.create(
                    q.ref(q.collection(users), chat_id), {
                        'data': {
                            'name': update.message.chat.first_name,
                            'is_admin': False,
                            'last_command': 'subscribe',
                            'animes_watching': [],
                            'config': {
                                'resolution': Resolution.MEDIUM.value
                            }
                        }
                    })))

        context.bot.send_message(
            chat_id=chat_id,
            text='Enter the anime you want to get notifications for!')
    except Exception as err:
        log_error(err)
Beispiel #5
0
def start_quiz(update, context):
    '''
    Starts the quiz and gets the questions from aloc API, then saves to database
    '''
    chat_id = update.effective_chat.id
    message = update.message.text
    try:
        name = update["message"]["chat"]["first_name"]
    except:
        name = update["message"]["chat"]["username"]
    subject = message.split('_')[1]
    questions = get_questions(subject=subject, mode='utme')

    quiz = client.query(
        q.create(
            q.collection("quiz"), {
                "data": {
                    "user_id": chat_id,
                    "subject": subject,
                    "answered": 0,
                    "score": 0,
                    "id_": random.randint(0, 100),
                    'completed': False,
                    'questions': questions,
                }
            }))

    user = client.query(q.get(q.match(q.index("users"), chat_id)))
    client.query(
        q.update(q.ref(q.collection("users"), user["ref"].id()),
                 {"data": {
                     "last_command": "start_quiz"
                 }}))
    msg = f"{subject.upper()}\n\n10 questions, enter 'q' to continue\n\n/end_quiz to end the quiz session."
    context.bot.send_message(chat_id=chat_id, text=msg)
Beispiel #6
0
def echo(update, context):
    chat_id = update.effective_chat.id
    message = update.message.text

    user = client.query(q.get(q.match(q.index("users"), chat_id)))
    last_command = user["data"]["last_command"]

    if last_command == "add_todo":
        todo = client.query(
            q.create(
                q.collection("todo"), {
                    "data": {
                        "user_id": chat_id,
                        "todo": message,
                        "completed": False,
                        "date": datetime.now(pytz.UTC)
                    }
                }))
        client.query(
            q.update(q.ref(q.collection("users"), user["ref"].id()),
                     {"data": {
                         "last_command": ""
                     }}))
        context.bot.send_message(
            chat_id=chat_id,
            text=
            "Successfully added todo task 👍\n\nSee all your todo with /list_todo"
        )
Beispiel #7
0
def dashboard(user):
    if request.method == "POST":
        old_password = request.form.get("old-password").strip()
        new_password = request.form.get("new-password").strip()

        try:
            result = client.query(
                q.identify(q.ref(q.collection("users"), user.id()),
                           old_password))

            if not result:
                raise Exception()

            result = client.query(
                q.update(q.ref(q.collection("users"), user.id()),
                         {"credentials": {
                             "password": new_password
                         }}))
        except Exception as e:
            flash("You have supplied an invalid password!", "danger")
            return redirect(url_for("dashboard"))

        flash("You have successfully changed your account password!",
              "success")
        return redirect(url_for("dashboard"))

    user_details = client.query(q.get(q.ref(q.collection("users"), user.id())))

    return render_template("dashboard.html", user_details=user_details)
Beispiel #8
0
def update_loan():
    action = request.form.get("action")
    amount = request.form.get("amount")
    loan_id = request.form.get("loanID")

    loan_data = client.query(
        q.get(
            q.ref(q.collection("loans"), int(loan_id))
        )
    )

    old_amount = loan_data["data"]["amount"]
    if action == "Borrow More":
        new_amount = old_amount + float(amount)
    elif action == "Repay Loan":
        new_amount = old_amount - float(amount)

    client.query(
        q.update(
            q.ref(q.collection("loans"), int(loan_id)), {
                "data": {
                    "amount": new_amount
                }
            }
        )
    )

    flash("You have successfully updated loan information!", "success")
    return redirect(url_for("loans"))
 def on_start(event):
     self.assertEqual(event.type, 'start')
     self.assertTrue(self.client.get_last_txn_time() > last_txn_time)
     #for start event, last_txn_time maybe be updated to response X-Txn-Time header
     # or event.txn. What is guaranteed is the most recent is used- hence >=.
     self.assertTrue(self.client.get_last_txn_time() >= event.txn)
     self._q(query.update(ref, {"data": {"k": "v"}}))
Beispiel #10
0
def vote(election_id):
    try:
        election = client.query(
            q.get(q.ref(q.collection("Elections"), election_id)))

        if session["user"]["username"] in election["data"]["voters"]:
            flash("You have voted for this election before!", 'info')
            return redirect(url_for('view_other_election'))

    except:
        return render_template('404.html')

    if request.method == "POST":
        vote = request.form.get("vote").strip()
        election["data"]["voting_options"][vote] += 1
        election["data"]["voters"].append(session["user"]["username"])
        client.query(
            q.update(
                q.ref(q.collection("Elections"), election_id), {
                    "data": {
                        "voting_options": election["data"]["voting_options"],
                        "voters": election["data"]["voters"]
                    }
                }))
        flash("Your vote was successfully recorded!", "success")
        return redirect(url_for("view_other_election"))

    return render_template("vote.html", election=election["data"])
Beispiel #11
0
async def get_pypi_data(package_name: str) -> dict:
    console.log(f"Requesting PyPi data for {package_name}.")
    request_url = f"https://pypi.org/pypi/{package_name}/json"
    response = requests.get(request_url)

    if response.status_code == 404:
        raise PyPiPackageNotFound

    assert response.status_code == 200
    package_data = response.json()
    package_data["normalized_name"] = normalize(package_data["info"]["name"])

    console.log(f"Logging PyPi data for {package_name} to FaunaDB.")

    client = FaunaClient(secret=settings.FAUNADB_KEY.get_secret_value())
    try:
        client.query(
            q.create(
                q.collection("packages"),
                {"data": package_data},
            ))
    except BadRequest:
        package = await get_package_by_name(package_name)
        ref = package["ref"]
        client.query(q.update(ref, {"data": package_data}))

    return package_data
def echo(update, context):
    chat_id = update.effective_chat.id
    message = update.message.text

    user = client.query(q.get(q.match(q.index("users_index"), chat_id)))
    last_command = user["data"]["last_command"]

    if last_command == "add_appointment":
        events = client.query(
            q.create(
                q.collection("Appointments"), {
                    "data": {
                        "user_id": chat_id,
                        "event": message.split(",")[0],
                        "completed": False,
                        "date_due": message.split(",")[1]
                    }
                }))
        client.query(
            q.update(q.ref(q.collection("Users"), user["ref"].id()),
                     {"data": {
                         "last_command": ""
                     }}))
        context.bot.send_message(chat_id=chat_id,
                                 text="Successfully added appointment event 👍")
def get_latest(update: Update, context: CallbackContext):
    chat_id = update.effective_chat.id

    try:
        client.query(
            q.if_(
                q.exists(q.ref(q.collection(users), chat_id)),
                q.update(q.ref(q.collection(users), chat_id),
                         {'data': {
                             'last_command': 'getlatest'
                         }}),
                q.create(
                    q.ref(q.collection(users), chat_id), {
                        'data': {
                            'name': update.message.chat.first_name,
                            'last_command': 'getlatest',
                            'animes_watching': [],
                            'config': {
                                'resolution': Resolution.MEDIUM.value
                            }
                        }
                    })))
        context.bot.send_message(chat_id=chat_id,
                                 text='Enter the anime you want to get!')
    except Exception as err:
        log_error(err)
Beispiel #14
0
def create_user(data):
    try:
        current_identity = get_current_identity()
        email_hash = md5(
            current_identity['data']['username'].encode('utf-8')).hexdigest()
        return current_app.fauna_client.query(
            q.if_(
                q.is_ref(
                    q.select_with_default(['data', 'user'],
                                          q.get(q.current_identity()), None)),
                q.abort('exists'),
                q.let(
                    {
                        'userMetaRef': q.new_id(),
                        'userRef': q.new_id()
                    },
                    q.do(
                        q.create(
                            q.ref(q.collection('user_metas'),
                                  q.var('userMetaRef')),
                            {
                                'data': {
                                    'name':
                                    data.get('name'),
                                    'email':
                                    q.select(['data', 'username'],
                                             q.get(q.current_identity())),
                                    'dob':
                                    parser.parse(data.get('dob')).date()
                                }
                            }),
                        q.create(
                            q.ref(q.collection('users'),
                                  q.var('userRef')),
                            {
                                'data': {
                                    'alias':
                                    data.get('alias'),
                                    'avatar':
                                    f'https://www.gravatar.com/avatar/{email_hash}',
                                    'public':
                                    False,
                                    'meta':
                                    q.ref(q.collection('user_metas'),
                                          q.var('userMetaRef')),
                                }
                            }),
                        q.update(
                            q.current_identity(), {
                                'data': {
                                    'user':
                                    q.ref(q.collection('users'),
                                          q.var('userRef'))
                                }
                            }), q.call('current_user', [])))))
    except Exception as e:
        if str(e) == 'exists':
            abort(409, 'User for current identity already exists.')
        print(e)
 def test_update(self):
     json = ('{"params":{"object":{"data":{"object":{"name":"Laptop"}}}},'
             '"update":{"collection":"widget"}}')
     self.assertJson(
         query.update(query.collection("widget"),
                      {"data": {
                          "name": "Laptop"
                      }}), json)
Beispiel #16
0
def update(collection, id, data):
    try:
        serverClient = FaunaClient(secret=os.environ.get("FAUNA_SERVER_SECRET"))
        res = serverClient.query(q.update(q.ref(q.collection(collection), id), {"data": data}))
        res["data"]["id"] = res["ref"].id()
        return res["data"]
    except Exception as ex:
        raise ex
def processHeroInformation(match_data):
    radiant_win = match_data['result']['radiant_win']
    players = match_data['result']['players']

    win_heros = []
    heros_in_game = []

    for player in players:
        win_flag = getWinFlag(player, radiant_win)

        heros_in_game.append(player['hero_id'])
        if win_flag:
            win_heros.append(player['hero_id'])

    hero_list=client.query(
        q.map_(
            q.lambda_(
                'hero',
                q.get(q.ref(q.collection('heroes'), q.var('hero')))
            ),
            heros_in_game
        )
    )

    update_hero_list = []
    for hero_info in hero_list:
        ref = hero_info['ref']
        data = hero_info['data']

        if data['id'] in win_heros:
            data['wins'] += 1
            data['games'] += 1
        else:
            data['games'] += 1

        for player in players:
            if player['hero_id'] == data['id']:
                getItemsData(player, data)

        update_info = {}
        update_info['ref'] = ref
        update_info['data'] = data

        update_hero_list.append(update_info)

    client.query(
        q.map_(
            q.lambda_(
                'hero',
                q.update(
                    q.select(['ref'], q.var('hero')),
                    { 'data': q.select(['data'], q.var('hero')) }
                )
            ),
            update_hero_list
        )
    )
Beispiel #18
0
 def resolution(self, resolution: Resolution):
     # update user's config in db
     client.query(
         q.update(q.ref(q.collection(users), self.chat_id),
                  {'data': {
                      'config': {
                          'resolution': resolution.value
                      }
                  }}))
Beispiel #19
0
 def update_days_by_lms_id(self, id, new_number_of_days):
     self.clientf.query(
         query.update(
             query.select(
                 'ref',
                 query.get(
                     query.match(query.index("students_by_lms_id"), id))),
             {'data': {
                 'days': new_number_of_days
             }}))
Beispiel #20
0
 def freeze_student_by_lms_id(self, id):
     self.clientf.query(
         query.update(
             query.select(
                 'ref',
                 query.get(
                     query.match(query.index("students_by_lms_id"), id))),
             {'data': {
                 'freezed': True
             }}))
Beispiel #21
0
def create_transaction(client, num_customers, max_txn_amount):
    #
    # This method is going to create a random transaction that moves a random amount
    # from a source customer to a destination customer. Prior to committing the transaction
    # a check will be performed to insure that the source customer has a sufficient balance
    # to cover the amount and not go into an overdrawn state.
    #
    uuid = uuid4().urn[9:]

    source_id = randint(1, num_customers)
    dest_id = randint(1, num_customers)
    while dest_id == source_id:
        dest_id = randint(1, num_customers)
    amount = randint(1, max_txn_amount)

    transaction = {"uuid": uuid, "sourceCust": source_id, "destCust": dest_id , "amount": amount}

    res = client.query(
        q.let(
            {"source_customer": q.get(q.match(q.index("customer_by_id"), source_id)),
             "dest_customer": q.get(q.match(q.index("customer_by_id"), dest_id))},
            q.let(
                {"source_balance": q.select(["data", "balance"], q.var("source_customer")),
                 "dest_balance": q.select(["data", "balance"], q.var("dest_customer"))},
                q.let(
                    {"new_source_balance": q.subtract(q.var("source_balance"), amount),
                     "new_dest_balance": q.add(q.var("dest_balance"), amount)},
                    q.if_(
                        q.gte(q.var("new_source_balance"), 0),
                        q.do(
                            q.create(q.class_("transactions"), {"data": transaction}),
                            q.update(q.select("ref", q.var("source_customer")),
                                     {"data": {"txnID": uuid, "balance": q.var("new_source_balance")}}),
                            q.update(q.select("ref", q.var("dest_customer")),
                                     {"data": {"txnID": uuid, "balance": q.var("new_dest_balance")}})
                        ),
                        "Error. Insufficient funds."
                    )
                )
            )
        )
    )
Beispiel #22
0
def create_or_update_role(client, payload={}):
    try:
        response = client.query(q.create_role(payload))
    except BadRequest as err:

        if str(err) == 'Role already exists.':
            role_name = payload.pop("name")
            response = client.query(q.update(q.role(role_name), payload))
        else:
            raise err
    return response
    def update_tweet(self, data: dict, tweet_id):
        """ UPDATE - Update tweet based on tweet_id """
        try:
            id = self.get_tweet(tweet_id)['ref'].id()
            updated_tweet = client.query(
                q.update(q.ref(q.collection(self.collection), id),
                         {'data': data}))
        except (Exception, NotFound) as e:
            return None

        return updated_tweet['data']
Beispiel #24
0
def update_status(secret, order_ref, status):
    client = FaunaClient(secret=secret)
    return client.query(
        q.update(
            q.ref(q.collection('orders'), order_ref),
            {"data": {
                "status": status,
                "statusAt": q.now()
            }}
        )
    )
Beispiel #25
0
def add_todo(update, context):
    chat_id = update.effective_chat.id

    user = client.query(q.get(q.match(q.index("users"), chat_id)))
    client.query(
        q.update(q.ref(q.collection("users"), user["ref"].id()),
                 {"data": {
                     "last_command": "add_todo"
                 }}))
    context.bot.send_message(chat_id=chat_id,
                             text="Enter the todo task you want to add 😁")
Beispiel #26
0
def create_or_update_function(client, payload):
    try:
        response = client.query(q.create_function(payload))
    except BadRequest as e:
        if e._get_description() == 'Function already exists.':
            function_name = payload.pop('name')
            response = client.query(
                q.update(q.function(function_name), payload))
        else:
            raise e
    return response
Beispiel #27
0
 def delete_idea_list_by_telegram_id(self, user_id):
     result = self.get_info_by_telegram_id(user_id)
     result2 = {k: None for k in result['ideas']}
     self.clf.query(
         query.update(
             query.select(
                 'ref',
                 query.get(
                     query.match(query.index('people_by_telegram_id'),
                                 user_id))), {'data': {
                                     'ideas': result2
                                 }}))
    def update_user(self, data: dict, user_id: str):
        """ UPDATE - Update a user's profile details. """
        try:
            id = self.get_user(user_id)['ref'].id()
            updated_user = client.query(
                q.update(q.ref(q.collection(self.collection), id),
                         {'data': data}))
        except (Exception, NotFound) as e:
            print(e)
            return None

        return updated_user['data']
Beispiel #29
0
def end_quiz(update, context):
    chat_id = update.effective_chat.id
    message = update.message.text
    try:
        name = update["message"]["chat"]["first_name"]
    except:
        name = update["message"]["chat"]["username"]

    quizzes = client.query(q.paginate(q.match(q.index("quiz"), chat_id)))
    user = client.query(q.get(q.match(q.index("users"), chat_id)))

    #Gets uncompleted quiz

    quizzz = []
    for i in quizzes["data"]:
        quiz_ = client.query(q.get(q.ref(q.collection("quiz"), i.id())))
        if not quiz_["data"]["completed"]:
            quizzz.append(quiz_)

    quiz = quizzz[-1]

    client.query(
        q.update(q.ref(q.collection("users"), user["ref"].id()),
                 {"data": {
                     "last_command": "end_quiz"
                 }}))

    client.query(
        q.update(q.ref(q.collection("quiz"), quiz["ref"].id()),
                 {"data": {
                     "completed": True
                 }}))
    context.bot.send_message(
        chat_id=chat_id,
        text=f"Quiz completed\nScore: {int(quiz['data']['score'])}/10 ",
        reply_markup=telegram.ReplyKeyboardRemove())

    botler = Botler().get()
    msg = messenger.get(name, botler)
    context.bot.send_message(chat_id=chat_id, text=msg)
Beispiel #30
0
def update_customer(client, cust_id, new_balance):
    #
    # Update the customer we just created
    #
    balance = 200.0
    res = client.query(
        q.update(
            q.select("ref", q.get(q.match(q.index("customer_by_id"),
                                          cust_id))),
            {"data": {
                "balance": new_balance
            }}))
    print('Update \'customer\' {0}: {1}'.format(cust_id, res))
Beispiel #31
0
def update(event, context):
    data = json.loads(event['body'])
    if 'text' not in data or 'checked' not in data:
        logging.error("Validation Failed")
        raise Exception("Couldn't update the todo item.")

    data = {
        'text': data['text'],
        'checked': data['checked'],
        'updatedAt': query.time('now')
    }

    # update the todo in the database
    ref = Ref(TODOS, event['pathParameters']['id'])
    updated = client.query(query.update(ref, {'data': data}))

    # create a response
    response = {
        "statusCode": 200,
        "body": json.dumps(make_result(updated))
    }

    return response