Exemple #1
0
    def post(self):
        # метод post с помощью ChatParticipants

        # args = post_parser.parse_args()
        # chat_participants = args['chat_participants']
        # chat = Chats(
        #     title=args.get('title')
        # )
        # session = db_session.create_session()
        # session.add(chat)
        # for user in chat_participants:
        #     chat_participants_obj = ChatParticipants(
        #         user_id=user.id,
        #         chat_id=chat.id
        #     )
        #     session.add(chat_participants_obj)
        # session.commit()
        # return jsonify({'success': 'OK'})

        args = post_parser.parse_args()
        session = db_session.create_session()
        users = []
        for alt_id in [args.first_author_id, args.second_author_id]:
            abort_if_user_not_found(alt_id)
            users += [user_by_alt_id(session, alt_id)]
        # chat = Chats(
        #     # title=args.get('title'),
        #     first_author_id=args['first_author_id'],
        #     second_author_id=args['second_author_id']
        # )
        create_chat(session, *users)
        return jsonify({'success': 'OK'})
Exemple #2
0
 def get(user_id=None):
     identity = get_jwt_identity()
     user_id = user_id or identity
     if not user_id:
         abort(400, message='User not specified')
     abort_if_user_not_found(user_id)
     session = db_session.create_session()
     user = user_by_alt_id(session, user_id)
     if current_user and user_id == current_user.user_id:
         return jsonify({'user': user.to_dict(only=USERS_PRIVATE_ONLY)})
     elif identity and user in current_user_from_db(session).friends:
         return jsonify({'user': user.to_dict(only=USERS_PRIVATE_ONLY)})
     return jsonify({'user': user.to_dict(only=USERS_PUBLIC_ONLY)})
Exemple #3
0
 def get():
     args = list_get_parser.parse_args()
     receiver_id = args.receiver_id
     chat_id = args.chat_id
     session = db_session.create_session()
     cur_user = current_user_from_db(session)
     if receiver_id or chat_id:
         if receiver_id:
             receiver = user_by_alt_id(session, receiver_id)
             chat = get_chat(session, cur_user, receiver)
         else:
             chat = session.query(Chats).filter(Chats.id == chat_id).first()
         if not chat:
             return jsonify({'messages': []})
         query = session.query(Messages)
         date = datetime.datetime.fromtimestamp(args.date)
         messages = query.filter((Messages.sending_date > date)
                                 & (Messages.chat_id == chat.id)).order_by(
                                     Messages.sending_date).all()
         messages_serialized = [msg.to_dict() for msg in messages]
         return jsonify({'messages': messages_serialized})
     else:
         chats_ids = list(
             map(
                 itemgetter(0),
                 session.query(ChatParticipants.chat_id).filter(
                     ChatParticipants.user_id == cur_user.id).all()))
         chats_query = session.query(Chats)
         msg_query = session.query(Messages).order_by(
             Messages.sending_date.desc())
         messages = []
         users_query = session.query(Users)
         for chat_id in chats_ids:
             chat: Chats = chats_query.get(chat_id)
             if chat.first_author_id == cur_user.id:
                 chat_with = users_query.get(
                     chat.second_author_id).alternative_id
             else:
                 chat_with = users_query.get(
                     chat.first_author_id).alternative_id
             if last_msg := msg_query.filter(
                     Messages.chat_id == chat_id).first():
                 last_message_dict = last_msg.to_dict()
                 last_message_dict['chat_with'] = chat_with
                 messages += [last_message_dict]
         return jsonify({'messages': messages})
Exemple #4
0
 def delete():
     args = delete_parser.parse_args()
     alt_id = args.friend_id
     abort_if_user_not_found(alt_id)
     session = db_session.create_session()
     user = user_by_alt_id(session, alt_id)
     cur_user = current_user_from_db(session)
     request = session.query(UsersFriends).filter(
         (UsersFriends.inviter_id == cur_user.id)
         & (UsersFriends.invitee_id == user.id)).first()
     if request:
         session.delete(request)
         session.commit()
         return jsonify({'success': 'OK'})
     else:
         return jsonify(
             {'error': f'You didn\'t send friend request to user {alt_id}'})
Exemple #5
0
 def post():
     args = post_parser.parse_args()
     session = db_session.create_session()
     cur_user = current_user_from_db(session)
     receiver_id = args.receiver_id
     chat_id = args.chat_id
     if not (chat_id or receiver_id) or (chat_id and receiver_id):
         return jsonify(
             {'error': 'You must specify chat_id OR receiver_id'})
     query = session.query(Chats)
     if receiver_id:
         receiver = user_by_alt_id(session, receiver_id)
         chat = get_chat(session, cur_user, receiver)
         if not chat:
             if cur_user not in receiver.friends:
                 return jsonify({
                     'error':
                     'User {0} isn\' your friend'.format(
                         cur_user.alternative_id)
                 })
             create_chat(session, cur_user, receiver)
     else:
         chat = query.filter(Chats.id == chat_id).first()
         if not chat:
             return jsonify(
                 {'error': 'Chat with id {0} not found'.format(chat_id)})
     message = Messages(sender_id=cur_user.id,
                        chat_id=chat.id,
                        text=args.text)
     session.add(message)
     session.commit()
     emit('new_message',
          message.to_dict(),
          room=f'chat_{chat.id}',
          namespace='/')
     return jsonify({'success': 'OK'})
Exemple #6
0
        if not (chat_id or chat_with) or (chat_id and chat_with):
            return jsonify(
                {'error': 'You must specify chat_id OR chat_with param'})
        session = db_session.create_session()
        cur_user = current_user_from_db(session)
        if chat_id:
            chat = session.query(Chats).filter(Chats.id == chat_id).first()
            chat: Chats
            if error := error_if_user_not_chat_member(cur_user, chat):
                return error
            if not chat:
                abort(404, message=f'Chat {chat_id} not found')
                return
        else:
            abort_if_user_not_found(chat_with)
            interlocutor = user_by_alt_id(session, chat_with)
            chat = get_chat(session, cur_user, interlocutor)
            if not chat:
                abort(
                    404,
                    message=f'Chat between you and user {chat_with} not found')
                return
        return jsonify({'chat': chat.to_dict()})

    @jwt_required
    def post(self):
        # метод post с помощью ChatParticipants

        # args = post_parser.parse_args()
        # chat_participants = args['chat_participants']
        # chat = Chats(
Exemple #7
0
 def post():
     args = post_parser.parse_args()
     abort_if_user_not_found(args.friend_id)
     session = db_session.create_session()
     cur_user = current_user_from_db(session)
     friend = user_by_alt_id(session, args.friend_id)
     action = args.action
     if action in ('accept', 'deny'):
         request_from_friend = session.query(UsersFriends).filter(
             (UsersFriends.inviter_id == friend.id)
             & (UsersFriends.invitee_id == cur_user.id)).first()
         request_from_cur_user = session.query(UsersFriends).filter(
             (UsersFriends.inviter_id == cur_user.id)
             & (UsersFriends.invitee_id == friend.id)).first()
         if request_from_friend:
             if action == 'accept':
                 if request_from_friend.is_accepted is True:
                     return jsonify({
                         'error':
                         f'Friend request from '
                         f'{friend.alternative_id} already accepted'
                     })
                 request_from_friend.is_accepted = True
                 # Создаём чат между пользователями сразу, т.к. иначе на
                 # главной странице пользователь не будет добавлен в
                 # комнату SocketIO с чатом между этими пользователями, и
                 # соответственно не будет получать сообщения от этого
                 # пользователя
                 create_chat(session, cur_user, friend)
             else:
                 if request_from_friend.is_accepted is False:
                     return jsonify({
                         'error':
                         f'Friend request from {friend.id} already '
                         f'denied'
                     })
                 request_from_friend.is_accepted = False
         elif request_from_cur_user:
             if action == 'deny':
                 request = UsersFriends()
                 request.inviter_id = friend.id
                 request.invitee_id = cur_user.id
                 request.is_accepted = False
                 session.add(request)
                 session.delete(request_from_cur_user)
             else:
                 return jsonify(
                     {'error': 'Only invitee can accept friend request'})
         else:
             if not (request_from_friend or request_from_cur_user):
                 return jsonify({
                     'error':
                     '{0} didn\'t send friend request to {1}'.format(
                         friend.alternative_id, cur_user.alternative_id)
                 })
     elif action == 'add':
         request = session.query(UsersFriends).filter(
             (UsersFriends.inviter_id == cur_user.id)
             & (UsersFriends.invitee_id == friend.id)).first()
         if request:
             return jsonify({
                 'error':
                 'Friend request to {0} already sent'.format(
                     friend.alternative_id)
             })
         users_friends_obj = UsersFriends(inviter_id=cur_user.id,
                                          invitee_id=friend.id)
         session.add(users_friends_obj)
     session.commit()
     return jsonify({'success': 'OK'})