Esempio n. 1
0
def my_wishes():
    id_ = current_user.id
    wishes = Wish.get_user_wishes(id_)
    isbn_list = [_.isbn for _ in wishes]
    # how many people want for each book in the isbn list
    count_list = Wish.get_gift_counts(isbn_list)
    # reuse MyTransactions as MyWishes view model
    view_model = MyTransactions(wishes, count_list)
    return render_template("my_wishes.html", wishes=view_model.transactions)
Esempio n. 2
0
def save_to_wish(isbn):
    if current_user.can_saveto_list(isbn):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.uid = current_user.id
            db.session.add(wish)
    else:
        flash('这本书已存在于你的心愿单或者赠送清单,请勿重复添加')
    # 视图函数必须要返回值
    return redirect(url_for('web.book_detail', isbn=isbn))
    pass
Esempio n. 3
0
def save_to_wishes(book_id):
    note = current_user.can_save_list(book_id)

    if note['can_save']:
        with db.auto_commit():
            wish = Wish()
            wish.uid = current_user.id
            wish.book_id = note['book'].id
            db.session.add(wish)
    else:
        flash('这本书已添加至你的赠送清单或已存在于你的心愿清单,请不要重复添加')
    flash('成功加入心愿清单!')

    return redirect(url_for('web.book_detail', number=note['book'].number))
Esempio n. 4
0
def add_game(message):
    """ добавить игру в вишлист, пример:
`/add https://store.playstation.com/ru-ru/concept/10000237`
или
`/add 10000237`
добавить в вишлист Assassin's Creed Valhalla """
    try:
        with session_scope() as session:
            wish, is_created = Wish.get_or_create(user_id=message.chat.id,
                                                  game_id=message.text.split(
                                                      ' ', maxsplit=1)[1],
                                                  session=session)
            game = Game.get(id=wish.game_id, session=session)
            if is_created:
                response = f'Игра успешно добавлена в твой вишлист: {game}.'
            else:
                response = f'Эта игра уже есть в твоём вишлисте: {game}.'
            if game.poster_url:
                bot.send_photo(chat_id=message.chat.id,
                               photo=get_image_bytes(game.poster_url),
                               parse_mode='MARKDOWN',
                               caption=response)
                return
    except ValueError as ve:
        response = str(ve)
    bot.send_message(message.chat.id, response, parse_mode='MARKDOWN')
Esempio n. 5
0
def watch_wishlist_inline(chosen_inline_result):
    """
    inline-метод, позволяющий публиковать в чате игры из своего вишлиста
    :param chosen_inline_result: пустая строка
    """
    print('общий инлайнер')
    try:
        with session_scope() as session:
            wishes = Wish.get_all(user_id=chosen_inline_result.from_user.id,
                                  session=session)
            games = [
                Game.get(id=wish.game_id, session=session) for wish in wishes
            ]

            bot.answer_inline_query(
                inline_query_id=chosen_inline_result.id,
                results=[
                    types.InlineQueryResultPhoto(
                        id=game.id,
                        title=game.name,
                        photo_url=game.poster_url,
                        thumb_url=game.poster_url,
                        caption=str(game),
                        parse_mode='MARKDOWN',
                        input_message_content=types.InputMediaPhoto(
                            caption=str(game),
                            parse_mode='MARKDOWN',
                            media=get_image_bytes(game.poster_url)),
                    ) for i, game in enumerate(
                        sorted(games, key=lambda x: x.name))
                ],
                switch_pm_text='Добавить игр?',
                switch_pm_parameter='start')
    except Exception as e:
        print(e)
Esempio n. 6
0
def wishes(userid):
    if request.method == "GET":
        user = db.session.query(User).filter_by(id=userid).first()
        wishes = db.session.query(Wish).filter_by(userid=user.id).all()
        wishlist = []
        for wish in wishes:
            wishlist.append({
                'title': wish.name,
                'url': wish.url,
                'thumbnail': wish.thumbnail,
                'description': wish.description,
                'addon': timeinfo(wish.addon)
            })
        if (len(wishlist) > 0):
            response = jsonify({
                "error": "null",
                "data": {
                    "user": user.first_name + " " + user.last_name,
                    "wishes": wishlist
                },
                "message": "Success"
            })
        else:
            response = jsonify({
                "error": "1",
                "data": {},
                "message": "Unable to get wishes"
            })
        return response
    else:
        user = db.session.query(User).filter_by(id=userid).first()
        json_data = json.loads(request.data)
        wish = Wish(user.id, json_data.get('url'), json_data.get('thumbnail'),
                    json_data.get('title'), json_data.get('description'),
                    datetime.now())
        if wish:
            db.session.add(wish)
            db.session.commit()
            response = jsonify({
                "error": "null",
                "data": {
                    'userid': userid,
                    'url': json_data.get('url'),
                    'thumbnail': wish.thumbnail,
                    'title': json_data.get('title'),
                    'description': json_data.get('description')
                },
                "message": "Success"
            })
        else:
            response = jsonify({
                "error": "1",
                "data": {},
                'message': 'did not create wish'
            })
        return response
Esempio n. 7
0
def save_to_wish(isbn):
    # 判断书籍isbn是否有效,同时防止用户钻洞子自己送书给自己
    if current_user.check_before_save_to_list(isbn=isbn):
        with db.auto_commit():
            wish = Wish(recipient=current_user._get_current_object(), isbn=isbn)
            db.session.add(wish)
        flash("本书已添加至您的心愿清单中")
    else:
        flash("本书已存在于您的赠送清单或心愿清单中!")
    return redirect(url_for(".book_detail", isbn=isbn))
Esempio n. 8
0
def wish_add_edit(id=None):

    form = AddOrEditWish()
    form.category.choices = get_unique_categories("wish")

    if id:
        wish = Wish.query.filter_by(id=int(id)).first()
        title = "Edit wish"
        edit = True
    else:
        wish = Wish()
        title = "Add wish"
        edit = False

    if request.method == 'POST' and form.validate_on_submit():

        wish.category = form.category.data
        if wish.category and form.add_category.data:
            wish.category = form.add_category.data

        wish.web_url = form.web_url.data
        wish.description = form.description.data
        wish.title = form.title.data
        wish.website = form.website.data
        wish.picture_url = "![picture](" + form.picture_url.data + ")"

        if id:
            db.session.commit()
            flash(f"Your changes on '{wish.title}' have been saved.")
        else:
            db.session.add(wish)
            db.session.commit()
            flash(f"The wish '{form.title.data}' was successfully added.")

        return redirect(url_for("wishes"))

    elif id and request.method == "GET":

        form.category.data = wish.category
        form.web_url.data = wish.web_url
        form.description.data = wish.description
        form.title.data = wish.title
        form.year.data = wish.year
        form.website.data = wish.website

    return render_template("wish.html", title=title, form=form, edit=edit)
Esempio n. 9
0
def createWish(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if 'WISH' in response:
            wish = Wish()
            wish.user = user
            wish.text = strip_tags(str(response['WISH']))
            wish.status = 0  # Not done; 1 Refused; 2 Accepted
            wish.save()
            data = errorCheckMessage(True, None)
        else:
            data = errorCheckMessage(False, "badFormat")
    else:
        data = errorCheckMessage(False, "badRequest")
    return JsonResponse(data)
Esempio n. 10
0
def get_wishlist(message):
    """просто получить вишлист"""
    with session_scope() as session:
        wishlist = Wish.get_all(user_id=message.chat.id, session=session)
        games = [
            Game.get(id=wish.game_id, session=session) for wish in wishlist
        ]
        if games:
            response = '\n'.join([
                f'{i}) {game}'
                for i, game in enumerate(sorted(games, key=lambda x: x.name),
                                         start=1)
            ])
        else:
            response = 'Твой вишлист пуст :('
        bot.send_message(chat_id=message.chat.id,
                         text=response,
                         parse_mode='MARKDOWN')
Esempio n. 11
0
def createWish(request):
    if request.method == 'POST':
        user = request.user
        response = json.loads(request.body)
        if checkPermission(["WISH"], user):
            if 'WISH' in response:
                wish = Wish()
                wish.user = user
                wish.text = strip_tags(str(response['WISH']))
                wish.status = 0  # Not done; 1 Refused; 2 Accepted; 3 Read
                wish.save()
                data = errorCheckMessage(True, None, createWish)
            else:
                data = errorCheckMessage(False, ErrorEnum.BAD_FORMAT,
                                         createWish)
        else:
            data = errorCheckMessage(False, ErrorEnum.PERMISSION_ERROR,
                                     createWish, user)
    else:
        data = errorCheckMessage(False, ErrorEnum.BAD_REQUEST, createWish)
    return JsonResponse(data)
Esempio n. 12
0
def del_game(message):
    """ удалить игру из вишлиста, пример:
`/del https://store.playstation.com/ru-ru/product/EP3862-CUSA10484_00-DEADCELLS0000000`
или
`/del EP3862-CUSA10484_00-DEADCELLS0000000`
удалить из вишлиста Dead Cells """
    game_id = message.text.split(' ', maxsplit=1)[1]
    try:
        with session_scope() as session:
            game, game_is_new = Game.get_or_create(game_id, session=session)
            was_deleted = Wish.delete(user_id=message.chat.id,
                                      game_id=game_id,
                                      session=session)
        if was_deleted:
            response = f'Игра была успешно удалена: {game}'
        elif game_is_new or game and not was_deleted:
            response = f'Игра отсутствует в вашем вишлисте: {game}'
        else:
            response = f'Игра с таким идентификатором не найдена: {game.name}'
    except ValueError as ve:
        response = str(ve)

    bot.send_message(message.chat.id, response, parse_mode='MARKDOWN')
Esempio n. 13
0
def add_game_wish(game_id):
    db.session.add(Wish(user_id=current_user.id, game_id=game_id))
    db.session.commit()
    return redirect(request.referrer)
Esempio n. 14
0
def wishlist(uid):
    user = db.session.query(User).filter_by(uid=uid).first()

    if request.method == "POST":
        if not request.json:
            flash("Something went wrong on our side please give us a moment")
            abort(400)
        exp = ('name' not in request.json
               and 'thumbnail_url' not in request.json
               and 'description' not in request.json
               and 'url' not in request.json)
        if exp:
            flash("Something went wrong on our side please give us a moment")
            abort(400)
        while True:
            pid = randint(450000, 470000)
            if not db.session.query(
                    exists().where(Wish.pid == str(pid))).scalar():
                break
        name = request.json['name']
        description = request.json['description']
        url = request.json['url']
        thumbnail = request.json['thumbnaill']
        if user:
            wish = Wish(pid, name, description, url, thumbnail)
            db.session.add(wish)
            db.session.commit()
            err = None
            info = {
                'pid': wish.pid,
                'name': wish.name,
                'description': wish.description,
                'url': wish.url,
                'thumbnail': wish.thumbnail
            }
        else:
            flash("Something went wrong on our side please give us a moment")
            abort(404)
        return jsonify(error=None,
                       data={'info': info},
                       message="Everything is fine")
    elif request.method == "GET":
        if user:
            wishlst = []

            #FIGURE THIS OUT
            query = text(
                """SELECT wish.item_id, wish.title, wish.description, wish.url, wish.thumbnail FROM wish INNER JOIN users_wishes ON users_wishes.wish_id = wish.item_id WHERE users_wishes.user_id = :id"""
            )
            wishes = db.session.get_bind().execute(query, id=user.id)
            if wishes:
                for i in wishes:
                    wish = {
                        'pid': wish["pid"],
                        'name': wish["name"],
                        'description': wish["description"],
                        'url': wish["url"],
                        'thumbnail': wish["thumbnail"]
                    }
                    wishlst.append(wish)
                errors = None
                message = "Success"
                info = {"wishes": wishlst}
            else:
                errors = True
                message = "No wishes found"
                info = {"wishes": wishlst}
        else:
            flash("Something went wrong on our side please give us a moment")
            abort(404)
        return jsonify(error=errors, info=info, message=message)