def verify_user(connection, user_id, message):
    user = db_queries.get_user(connection, user_id)
    if not user:
        db_queries.add_user(connection, message)
        user = db_queries.get_user(connection, user_id)

    return get_user_dict(user)
def update_user_role(connection, user_id):
    db_user = get_user_dict(db_queries.get_user(connection, user_id))
    points = count_points(db_user)
    if 'user' in db_user['role']:
        if points > 15:
            db_queries.update_parameter(connection, user_id, 'role', 'user1')
        elif points > 12:
            db_queries.update_parameter(connection, user_id, 'role', 'user2')
Esempio n. 3
0
def on_new_user_page(data):
    """
    new user
    """
    print('received data from client ' + str(data['user_id']))
    user = db_queries.get_user(data['user_id'])
    print(user['email'])
    socketio.emit('user page load', {'user': user})
Esempio n. 4
0
def statistics():
    text = db_queries.get_page_content('statistics')
    statistics = db_queries.get_users_statistics(current_user.primary_email, None)

    #get user id to pass to the template to build the link to the last correctly submitted exercise
    user_id = db_queries.get_user(current_user.primary_email).user_id
    link_dir = app.config['STORAGE_FOLDER']
    return render_template("statistics.html", text=text, statistics=statistics, link_dir=link_dir, user_id=user_id)
Esempio n. 5
0
def on_fork_page(data):
    """
    on fork page
    """
    recipe = db_queries.get_recipe(data["id"])
    username = db_queries.get_user(recipe["user"])["name"]
    # namespace = "/recipe/" + str(id)
    recipe["name"] = username
    emit_recipe("load fork page", recipe)
Esempio n. 6
0
def on_recipe_page(data):
    """
    recipe page
    """
    print('received data from client ' + str(data['id']))
    recipe = db_queries.get_recipe(data['id'])
    client_id = flask.request.sid
    username = db_queries.get_user(recipe["user"])["name"]
    namespace = "/recipe/" + str(id)
    recipe['name'] = username
    emit_recipe(SEND_ONE_RECIPE_CHANNEL, recipe)
Esempio n. 7
0
def delete_user(primary_email):
    #deletes a user and their profile
    user =  db_queries.get_user(primary_email)
    #does not use the get_profile query to be sure it's the actual db
    #profile, and not the one stored in cache
    profile = models.Profile.query.get(user.user_id)
    statistics = models.Statistics.query.filter_by(profile_id=profile.profile_id).all()
    for s in statistics:
        db.session.delete(s)
    db.session.delete(profile)
    db.session.delete(user)
    db.session.commit()
Esempio n. 8
0
def delete_user(primary_email):
    #deletes a user and their profile
    user = db_queries.get_user(primary_email)
    #does not use the get_profile query to be sure it's the actual db
    #profile, and not the one stored in cache
    profile = models.Profile.query.get(user.user_id)
    statistics = models.Statistics.query.filter_by(
        profile_id=profile.profile_id).all()
    for s in statistics:
        db.session.delete(s)
    db.session.delete(profile)
    db.session.delete(user)
    db.session.commit()
Esempio n. 9
0
def emit_all_recipes(channel):
    """
    emit all recipes
    """
    recipes = db_queries.get_n_recipes(10)
    for recipe in recipes:
        user = db_queries.get_user(recipe["user"])
        username = user['name']
        recipe['name'] = username
    all_searches = recipes
    client_id = flask.request.sid
    socketio.emit(channel, {
        'all_display': all_searches,
    }, room=client_id)
Esempio n. 10
0
def process_message(bot, connection, message, markups, settings):

    answer_text = choice(const.other_answers)
    answer_markup = None

    user_id = str(message.from_user.id)
    user_text = message.text

    crimes = get_crimes(user_text)

    if user_text[1:] in const.commands:
        answer_text = const.commands[user_text[1:]]
        answer_markup = markups['Назад']
    elif user_text in const.usually_answers.keys():
        answer_text = get_answer(user_text)

    if user_text in markups.keys():
        answer_markup = markups[user_text]

    if crimes:
        answer_text = const.bad_answer

    if connection:
        db_user = verify_user(connection, user_id, message)

        if user_text == 'Обо мне':
            answer_markup = get_user_markup(db_user)
            answer_text = 'Для редакирования данных нажмите на соответствующий параметр'
        elif user_text == 'Обо всех':
            answer_text = get_role_stat(connection, db_user['role'])
        elif ': ' in user_text:
            rus_parameter = user_text.split(':')[0]
            answer_text = f'Пожалуйста введите {rus_parameter.lower()}'
            if rus_parameter in markups.keys():
                answer_markup = markups[rus_parameter]
        elif ': ' in db_user['last_message']:
            parameter = get_parameter(db_user['last_message'])
            if parameter and verify_user_parameter(parameter, user_text):
                db_queries.update_parameter(connection, user_id, parameter, user_text)
                answer_text = f'Ваш {db_user["last_message"].split(":")[0].lower()} был успешно сохранён.'
                answer_markup = get_user_markup(get_user_dict(db_queries.get_user(connection, user_id)))
                update_user_role(connection, user_id)
            else:
                answer_text = 'Параметр введён некорректно'

        db_queries.update_user(connection, user_id, user_text, db_user['num_messages']+1, db_user['crimes']+crimes)

    bot.send_message(user_id, answer_text, reply_markup=answer_markup, parse_mode=settings.parse_mode)
    print(get_log_text(message, datetime.now(), answer_text, crimes, settings))
Esempio n. 11
0
def on_new_user_page(data):
    """
    new user
    """
    user = db_queries.get_user(data["user_id"])
    saved_recipes = []
    saved_recipes_id = user["saved_recipes"]
    for recipe_id in saved_recipes_id:
        recipe = db_queries.get_recipe(recipe_id)
        username = db_queries.get_user(recipe["user"])["name"]
        recipe["name"] = username
        saved_recipes.append(recipe)
    owned_recipes = []
    owned_recipes_id = user["owned_recipes"]
    for recipe_id in owned_recipes_id:
        recipe = db_queries.get_recipe(recipe_id)
        username = db_queries.get_user(recipe["user"])["name"]
        recipe["name"] = username
        owned_recipes.append(recipe)
    favorite_recipes = []
    favorite_recipes_id = user["favorite_recipes"]
    for recipe_id in favorite_recipes_id:
        recipe = db_queries.get_recipe(recipe_id)
        username = db_queries.get_user(recipe["user"])["name"]
        recipe["name"] = username
        favorite_recipes.append(recipe)
    socketio.emit(
        "user page load",
        {
            "user": user,
            "owned_recipes": owned_recipes,
            "saved_recipes": saved_recipes,
            "favorite_recipes": favorite_recipes,
        },
        room=flask.request.sid,
    )
Esempio n. 12
0
def on_new_search(data):
    """
    search for recipe
    """
    print("Got an event for new search input with data:", data)
    client_id = flask.request.sid
    search_filter = data['filter']
    if search_filter == "name":
        search_query = db_queries.search_with_name(data['search'])
    if search_filter == "tag":
        search_query = db_queries.search_by_tag(data['search'])
    if search_filter == "difficulty":
        search_query = db_queries.search_by_difficulty(data['search'])
    for recipe in search_query:
        username = db_queries.get_user(recipe["user"])['name']
        recipe['name'] = username
    socketio.emit(SEARCHES_RECEIVED_CHANNEL, {'search_output': search_query},
                  room=client_id)
Esempio n. 13
0
def getPage(page, type):
    dbwrapper = db_queries.DBWrapper(type)
    user = db_queries.get_user(session["user_id"])
    if user:
        devices_id, devices_dss = user["devices_id"], user["devices_dss"]
        dss_dict = {}  # ????
    else:  # there is no such user in our db
        del session["user_id"]
        devices_id, devices_dss, dss_dict = [], [], {}  # nothing to return
    first_comp_index = (int(page) - 1) * COMPUTERS_ON_PAGE
    last_comp_index = min(int(page) * COMPUTERS_ON_PAGE, len(devices_id))
    devices_id_on_page = devices_id[first_comp_index:last_comp_index]
    devices_dss_on_page = devices_dss[first_comp_index:last_comp_index]

    pretty_devices = pretty_data.small_devices(devices_id_on_page, devices_dss_on_page, dbwrapper)
    resp = jsonify({"pretty_devices": pretty_devices})
    resp.status_code = 200
    return resp
Esempio n. 14
0
def getPage(page, type):
    dbwrapper = db_queries.DBWrapper(type)
    user = db_queries.get_user(session['user_id'])
    if user:
        devices_id, devices_dss = user['devices_id'], user['devices_dss']
        dss_dict = {}  # ????
    else:  # there is no such user in our db
        del session['user_id']
        devices_id, devices_dss, dss_dict = [], [], {}  # nothing to return
    first_comp_index = (int(page) - 1) * COMPUTERS_ON_PAGE
    last_comp_index = min(int(page) * COMPUTERS_ON_PAGE, len(devices_id))
    devices_id_on_page = devices_id[first_comp_index:last_comp_index]
    devices_dss_on_page = devices_dss[first_comp_index:last_comp_index]

    pretty_devices = pretty_data.small_devices(devices_id_on_page,
                                               devices_dss_on_page, dbwrapper)
    resp = jsonify({"pretty_devices": pretty_devices})
    resp.status_code = 200
    return resp
Esempio n. 15
0
def on_recipe_page(data):
    """
    recipe page
    """
    recipe = db_queries.get_recipe(data["id"])
    username = db_queries.get_user(recipe["user"])["name"]
    start_adding = False
    video_parsed = ""
    for video in recipe["videos"]:
        for character in video:
            if character == "=":
                start_adding = True
                continue
            if start_adding is True:
                video_parsed += character
    recipe["name"] = username
    emit_recipe(SEND_ONE_RECIPE_CHANNEL, recipe)
    if start_adding:  # If there is a youtube video in the recipe
        socketio.emit("video available", video_parsed)
Esempio n. 16
0
def on_new_search(data):
    """
    search for recipe
    """
    client_id = flask.request.sid
    search_filter = data["filter"]
    if search_filter == "name":
        search_query = db_queries.search_with_name(data["search"])

    if search_filter == "tag":
        search_query = db_queries.search_by_tag(data["search"])
    if search_filter == "difficulty":
        search_query = db_queries.search_by_difficulty(data["search"])
    for recipe in search_query:
        username = db_queries.get_user(recipe["user"])["name"]
        recipe["name"] = username
    socketio.emit(
        SEARCHES_RECEIVED_CHANNEL, {"search_output": search_query}, room=client_id
    )
Esempio n. 17
0
def on_new_google_user(data):
    """
    login using google
    """
    print("Got an event for new google user input with data:", data)
    user = db_queries.add_user(data)
    print("USER IS: " + str(user))
    user_obj = db_queries.get_user(user)
    username = user_obj['name']
    user_email = user_obj['email']
    shopping_list = db_queries.get_shopping_list(user_obj["id"])
    cart_num_items = len(shopping_list)
    print("THIS IS " + str(username))
    socketio.emit(
        'logged in', {
            'username': username,
            'email': user_email,
            'cartNumItems': cart_num_items,
        })
Esempio n. 18
0
def on_new_google_user(data):
    """
    login using google
    """
    user = db_queries.add_user(data)
    user_obj = db_queries.get_user(user)
    username = user_obj["name"]
    user_email = user_obj["email"]
    client_id = flask.request.sid
    shopping_list = db_queries.get_shopping_list(user_obj["id"])
    cart_num_items = len(shopping_list)
    socketio.emit(
        "logged in",
        {
            "userId": user,
            "username": username,
            "email": user_email,
            "cartNumItems": cart_num_items,
        },
        room=client_id,
    )
Esempio n. 19
0
def log(provider_name):
    #clears any previously stored login cache info
    app_cache.clear_cache()

    #function to actually login the user with oauth requests
    if g.user is not None and g.user.is_authenticated():
        #check to see if the user is already logged in
        return redirect(url_for('login'))

    #get the result from the oauth provider
    response = make_response()
    result = authomatic.login(WerkzeugAdapter(request, response),
                              provider_name)

    if result:
        #a result was returned from the oauth provider
        if result.user:
            result.user.update()

        if result.user.email is None or result.user.email == "":
            #An error occured, produce error message to user
            return redirect(url_for('login'))

        #at this point, the user oauth information should be valid
        #check the database to see if it is an existing user
        user = db_queries.get_user(result.user.email)
        if user is None:
            #user was not in the database, a new entry will be registered for them
            #first_name = result.user.first_name
            #last_name = result.user.last_name
            email = result.user.email
            user = db_posts.add_user(email)

        #user is valid, log the user in
        login_user(user, remember=False)
        return redirect(request.args.get('next') or url_for('index'))

    #if it is the first call, return the reponse
    #user info is handled on the second call
    return response
Esempio n. 20
0
def log(provider_name):
    #clears any previously stored login cache info
    app_cache.clear_cache()

    #function to actually login the user with oauth requests
    if g.user is not None and g.user.is_authenticated():
        #check to see if the user is already logged in
        return redirect(url_for('login'))

    #get the result from the oauth provider
    response = make_response()
    result = authomatic.login(WerkzeugAdapter(request, response), provider_name)

    if result:
        #a result was returned from the oauth provider
        if result.user:
            result.user.update()

        if result.user.email is None or result.user.email == "":
            #An error occured, produce error message to user
            return redirect(url_for('login'))

        #at this point, the user oauth information should be valid
        #check the database to see if it is an existing user
        user = db_queries.get_user(result.user.email)
        if user is None:
            #user was not in the database, a new entry will be registered for them
            #first_name = result.user.first_name
            #last_name = result.user.last_name
            email = result.user.email
            user = db_posts.add_user(email)

        #user is valid, log the user in
        login_user(user, remember=False)
        return redirect(request.args.get('next') or url_for('index'))

    #if it is the first call, return the reponse
    #user info is handled on the second call
    return response
Esempio n. 21
0
    def test_get_user(self):
        db.session.add(
            models.Users(
                id=self.TEST_ID,
                email=self.TEST_USER["email"],
                name=self.TEST_USER["name"],
                shopping_list=[],
                shared_recipes=[],
                saved_recipes=[],
                profile_pic=self.TEST_USER["imageURL"],
            )
        )

        db_user = db_queries.get_user(self.TEST_ID)

        self.assertEqual(self.TEST_USER["name"], db_user["name"])
        self.assertEqual(self.TEST_USER["email"], db_user["email"])
        self.assertEqual(self.TEST_USER["imageURL"], db_user["profile_pic"])
        self.assertEqual(db_user["shopping_list"], [])
        self.assertEqual(db_user["saved_recipes"], [])
        self.assertEqual(db_user["shared_recipes"], [])
        self.assertEqual(db_user["owned_recipes"], [])
Esempio n. 22
0
def load_user(email):
    return db_queries.get_user(email)
Esempio n. 23
0
def load_user(email):
    return db_queries.get_user(email)