Beispiel #1
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')
Beispiel #2
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)
Beispiel #3
0
def create_new_audit_log(user_id: str, favorite_thing_id: str, msg: str):
    audit_log_record = Audit(user_id=user_id,
                             favorite_thing_id=favorite_thing_id,
                             text=msg)
    audit_log_record.id = str(uuid1())
    with session_scope() as db_session:
        db_session.add(audit_log_record)
Beispiel #4
0
    def get_all_by_t_id(cls, thread_id):
        with session_scope() as session:
            rows = session.query(cls).filter(cls.thread_id == thread_id).all()

            result = [row_to_dict(row) for row in rows]

            return result
Beispiel #5
0
def get_categories_of_a_user(user_id):
    with session_scope() as db_session:
        return [
            category[0]
            for category in db_session.query(FavoriteCategory.category).filter(
                FavoriteCategory.user_id == user_id).all()
        ]
Beispiel #6
0
def get_all_favorite_items(user_id: str):
    with session_scope() as db_session:
        return [
            serialize(item)
            for item in db_session.query(FavoriteThings).filter(
                FavoriteThings.user_id == user_id).all()
        ]
Beispiel #7
0
def get_logs_of_favorite_thing(user_id: str, favorite_thing_id: str):
    with session_scope() as db_session:
        return [
            serialize(_log) for _log in db_session.query(Audit).filter(
                Audit.user_id == user_id, Audit.favorite_thing_id ==
                favorite_thing_id).all()
        ]
Beispiel #8
0
    def get_user_secret(cls, user_id):
        '''user_idに紐づくuser情報(すべて)取得
        '''
        with session_scope() as session:
            row = session.query(cls).filter(cls.user_id == user_id).first()

            return row_to_dict(row)
Beispiel #9
0
    def login(cls, email, password):
        '''emailとpasswordが一致するuser情報を取得
        Args:
            email:      学番メール
            password:   パスワード
        Returns:
            dict: user情報
        '''
        with session_scope() as session:
            rows = session.query(
                cls.user_id,
                cls.email,
                cls.username,
                cls.description,
                cls.thumbnail
            ).filter(
                cls.email == email,
                cls.password == password
            ).order_by(
                cls.user_id.desc()
            ).first()

            if not rows:
                return None

            return rows._asdict()
Beispiel #10
0
def get_all_categories_of_user(user_id):
    with session_scope() as db_session:
        return [
            serialize(item)
            for item in db_session.query(FavoriteCategory).filter(
                FavoriteCategory.user_id == user_id).all()
        ]
Beispiel #11
0
    def get_all(cls):
        with session_scope() as session:
            rows = session.query(cls).all()

            result = [row_to_dict(row) for row in rows]

            return result
Beispiel #12
0
def get_all_favorite_items_of_category(user_id: str, category: str):
    with session_scope() as db_session:
        return [
            serialize(item)
            for item in db_session.query(FavoriteThings).filter(
                FavoriteThings.user_id == user_id, FavoriteThings.category ==
                category).all()
        ]
Beispiel #13
0
    def get(cls, flip_id):
        with session_scope() as session:
            rows = session.query(cls).filter(cls.flip_id == flip_id).first()

            if not rows:
                return None

            return row_to_dict(rows)
Beispiel #14
0
def create_tables():
    '''全テーブル作成
    '''
    db_modules = __import__(models_path, fromlist=[''])

    with session_scope() as session:
        Base = getattr(db_modules, 'Base')
        Base.metadata.create_all(bind=session.bind)
Beispiel #15
0
def drop_tables():
    '''全テーブル初期化
    '''
    db_modules = __import__(models_path, fromlist=[''])

    with session_scope() as session:
        Base = getattr(db_modules, 'Base')
        for table in reversed(Base.metadata.sorted_tables):
            session.execute(table.delete())
Beispiel #16
0
    def get_by_login_token(cls, login_token):
        '''仮登録ユーザをlogin_tokenから取得
        '''
        with session_scope() as session:
            # prov_user = session.
            row = session.query(cls).filter(
                cls.login_token == login_token).first()

            if not row:
                return None

            return row_to_dict(row)
Beispiel #17
0
    def get_by_title(cls, title):
        with session_scope() as session:
            rows = session.query(
                cls
            ).join(
                Category, cls.category_id == Category.category_id
            ).filter(
                cls.title.like(title + '%')
            )

            result = [row_to_dict(row) for row in rows]

            return result
Beispiel #18
0
    def get(cls, email):
        '''仮登録ユーザの最新のカラムを取得
        Args:
            email:  学番メール
        Returns:
            dict:
                ProvisionalUser:    仮登録ユーザ情報
        '''
        with session_scope() as session:
            # prov_user = session.
            rows = session.query(cls).filter(cls.email == email).order_by(
                cls.provisional_user_id.desc()).first()

            return row_to_dict(rows)
Beispiel #19
0
    def put(cls, user_id, params):
        '''userの基本情報(password以外)を更新
        '''
        cls._check_length(params)

        with session_scope() as session:
            data = cls(
                user_id=user_id,
                **params
            )

            # mergeして1回commit
            session.merge(data)
            session.commit()
Beispiel #20
0
def save_new_favorite_thing(user_id,
                            title: str,
                            ranking: int,
                            category: str,
                            description: str = None):
    log.debug(f"Check if rank:{ranking} is present for category:{category}")
    _ranking = ranking

    favorite_thing_id = str(uuid1())
    with session_scope() as db_session:
        # if rank assigned to new favorite thing is already in db
        if ranking is not None and rank_present_for_category(
                ranking, category):

            old_fav_things = db_session.query(FavoriteThings).filter(
                and_(FavoriteThings.user_id == user_id,
                     FavoriteThings.category == category,
                     FavoriteThings.ranking >= ranking))
            if old_fav_things:
                old_fav_things.update({"ranking": FavoriteThings.ranking + 1})
        if ranking is None:
            _ranking = db_session.query(FavoriteThings).filter(
                FavoriteThings.user_id == user_id, FavoriteThings.category
                == category).count() + 1
        favorite_thing = FavoriteThings(user_id=user_id,
                                        title=title,
                                        ranking=_ranking,
                                        category=category,
                                        description=description)
        favorite_thing.id = favorite_thing_id
        if category not in get_categories_of_a_user(user_id):
            log.debug(f"creating new category:{category} for user:{user_id}")
            create_a_new_category_for_a_user(user_id, category)
        db_session.add(favorite_thing)

    create_new_audit_log(user_id=user_id,
                         favorite_thing_id=favorite_thing_id,
                         msg=f"Created new entry: {title}")

    # get by id did not work
    return {
        "id": favorite_thing_id,
        "title": title,
        "description": description,
        "ranking": ranking,
        "category": category,
        "created": datetime.datetime.now(),
        "updated": datetime.datetime.now(),
        "user_id": user_id
    }
Beispiel #21
0
def save_new_user(email: str, password: str):
    new_user = User(email=email, password=password)
    user_id = str(uuid1())
    new_user.id = user_id
    categories = ["person", "place", "food"]
    with session_scope() as db_session:
        db_session.add(new_user)

        # initialize user categories
        for category in categories:
            fav_cat = FavoriteCategory(category, new_user.id)
            fav_cat.id = str(uuid1())
            db_session.add(fav_cat)

        return {"id": user_id, "email": email}
Beispiel #22
0
def load_fixtures(fixtures_root, tables):
    '''テストデータ読み込み
    '''
    if not tables:
        return

    fixtures_data_path = ['%s.yaml' % table for table in tables]

    for table in fixtures_data_path:
        # fixtures_dataを読み込み
        fixture_data = ss_load_fixture_files(fixtures_root, [table])

        with session_scope() as session:
            # fixtures_dataをテーブルに格納
            ss_load_fixtures(session, fixture_data)
Beispiel #23
0
    def get_users_all(cls):
        '''すべてのuser取得
        '''
        with session_scope() as session:
            rows = session.query(
                cls.user_id,
                cls.email,
                cls.username,
                cls.description,
                cls.thumbnail
            ).all()

            result = [row._asdict() for row in rows]

            return result
Beispiel #24
0
    def get_users_all(cls):
        '''すべてのuser取得
        '''
        with session_scope() as session:
            rows = session.query(
                cls.user_id,
                cls.email,
                cls.nick_name,
                cls.profile,
                cls.twitter_name
            ).all()

            result = [row._asdict() for row in rows]

            return result
Beispiel #25
0
    def put_password(cls, user_id, password, new_password):
        '''userのpassword更新
        '''
        with session_scope() as session:
            user = cls.get_user_secret(user_id)

            if user.get('password') != password:
                raise Exception('invalid password')

            data = cls(
                user_id=user_id,
                password=new_password
            )

            # mergeして1回commit
            session.merge(data)
            session.commit()
Beispiel #26
0
    def post(cls, params):
        # length_check
        text = params.get('text')
        if len(text) > 200:
            raise Exception('over text length')

        with session_scope() as session:
            if not params.get('create_at'):
                params.update({'create_at': datetime.now(JST)})

            data = cls(**params)
            session.add(data)
            session.flush()

            # thread_idに紐づくthreadのcomment_count加算
            cls.update_thread(session=session,
                              thread_id=params.get('thread_id'))
Beispiel #27
0
    def get_user_all(cls, user_id):
        '''user_idに紐づくuser情報(password以外)の取得
        '''
        with session_scope() as session:
            rows = session.query(
                cls.user_id,
                cls.email,
                cls.username,
                cls.description,
                cls.thumbnail
            ).filter(
                cls.user_id == user_id
            ).first()

            if not rows:
                return None

            return rows._asdict()
Beispiel #28
0
    def get_email(cls, user_id):
        '''user_idに紐づくemail取得
        Args:
            user_id:    ユーザID
        Returns:
            email:      学番メール
        '''
        with session_scope() as session:
            rows = session.query(
                cls.email,
            ).filter(
                cls.user_id == user_id
            ).first()

            if not rows:
                return None

            return rows._asdict()
Beispiel #29
0
    def is_exist_by_username(cls, username):
        '''同じニックネームのユーザが存在するかどうかをboolで返却
        Args:
            nike_name:  ニックネーム
        Returns:
            bool:
        '''
        with session_scope() as session:
            count = session.query(
                cls
            ).filter(
                cls.username == username
            ).count()

            if count > 0:
                return True
            else:
                return False
Beispiel #30
0
    def is_exist_by_email(cls, email):
        '''同じ学番メールのユーザが存在するかどうかをboolで返却
        Args:
            email:  学番メール
        Returns:
            bool:
        '''
        with session_scope() as session:
            count = session.query(
                cls
            ).filter(
                cls.email == email
            ).count()

            if count > 0:
                return True
            else:
                return False