Пример #1
0
def edit_room(room_id):
    room = get_room(room_id)
    if room and is_room_admin(room_id, current_user.username):
        existing_room_members = [
            member["_id"]["username"] for member in get_room_members(room_id)
        ]
        room_members_str = ",".join(existing_room_members)
        message = ""
        if request.method == "POST":
            room_name = request.form.get("room_name")
            room["name"] = room_name
            update_room(room_id, room_name)

            new_members = [
                username.strip() for username in request.form.get("members").split(",")
            ]
            members_to_add = list(set(new_members) - set(existing_room_members))
            members_to_remove = list(set(existing_room_members) - set(new_members))
            if len(members_to_add):
                add_room_members(
                    room_id, room_name, members_to_add, current_user.username
                )
            if len(members_to_remove):
                remove_room_members(room_id, members_to_remove)
            message = "Room edited successfully"
            room_members_str = ",".join(new_members)
        return render_template(
            "edit_room.html",
            room=room,
            room_members_str=room_members_str,
            message=message,
        )
    else:
        return "Room not found", 404
Пример #2
0
def single_room_members(room_id):
    user_id = get_jwt_identity()
    current_app.logger.info('{} requested members for {}'.format(
        user_id, room_id))

    members_raw = get_room_members(room_id)
    members = []

    if not is_room_member(room_id, user_id):
        return jsonify(
            {'Error': 'You are not a member of the requested room.'}), 403

    for member in members_raw:
        try:
            # this is really messy, can this be improved?
            this_user = get_user(str(member['_id']['user_id']))
        except KeyError as e:
            continue
        except TypeError as e:
            return jsonify({'Error': e}), 400
        if not this_user:
            continue

        new_member = get_user(this_user.ID)
        members.append(new_member.create_json())

    return jsonify(members), 200
Пример #3
0
def edit_room(room_id):
    room = get_room(room_id)
    if room and is_room_admin(room_id, current_user.username):
        existing_room_members = [
            member['_id']['username'] for member in get_room_members(room_id)
        ]
        room_members_str = ",".join(existing_room_members)
        message = ''
        if request.method == 'POST':
            room_name = request.form.get('room_name')
            room['name'] = room_name
            update_room(room_id, room_name)

            new_members = [
                username.strip()
                for username in request.form.get('members').split(',')
            ]
            members_to_add = list(
                set(new_members) - set(existing_room_members))
            members_to_remove = list(
                set(existing_room_members) - set(new_members))
            if len(members_to_add):
                add_room_members(room_id, room_name, members_to_add,
                                 current_user.username)
            if len(members_to_remove):
                remove_room_members(room_id, members_to_remove)
            message = 'Room edited successfully'
            room_members_str = ",".join(new_members)
        return render_template('edit_room.html',
                               room=room,
                               room_members_str=room_members_str,
                               message=message)
    else:
        return "Room not found", 404
Пример #4
0
def view_room():
    if (in_like_table()):
        room_name = get_all_room(session['username'])
        print(room_name)
        room_id = get_id(room_name['room_name'])
        room = get_room(room_id['_id'])
        room_members = get_room_members(room_id['_id'])
        books = get_all_books()
        print(room_id)
        print(room_members)
        messages = get_messages(room_id['_id'])
        #book_id=get_group(session['username'])[2]
        #book_name=book_id_to_name(book_id)
        songs = ''  #os.listdir('./static/music/'+book_name[0])
        return render_template('view_room.html',
                               username=session['username'],
                               room=room,
                               room_members=room_members,
                               songs=songs,
                               messages=messages,
                               books=books)

    else:
        books = get_all_books()
        return render_template('books.html', books=books)
Пример #5
0
def view_room(room_id):
    room = get_room(room_id)
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        return render_template('view_room.html', username=current_user.username,room=room, room_members=room_members, messages=messages) 
    else:
        return "Room not found", 404
Пример #6
0
def edit_room(room_id):
    room = get_room(room_id)
    room_members = [
        member['_id']['username'] for member in get_room_members(room_id)
    ]
    print('room members are ==', room_members)
    is_room_admin = check_if_room_admin(room_id, current_user.username)

    if request.method == 'POST':

        new_room_name = request.form.get('new_room_name')
        change_room_name(room_id, new_room_name)
        room['room_name'] = new_room_name

        new_room_members = [
            username.strip()
            for username in request.form.get('members').split(',')
        ]

        members_to_add = list(set(new_room_members) - set(room_members))
        members_to_remove = list(set(room_members) - set(new_room_members))

        if members_to_add:
            add_room_members(room_id, new_room_name, members_to_add,
                             current_user.username)
        if members_to_remove:
            remove_room_members(room_id, members_to_remove)

        room_members = get_room_members(room_id)
        return render_template('view_room.html',
                               username=current_user.username,
                               room=room,
                               room_members=room_members,
                               is_room_admin=is_room_admin)

    else:
        room_members = ','.join(room_members)
        if room and is_room_member(room_id, current_user.username):
            return render_template('edit_room.html',
                                   username=current_user.username,
                                   room=room,
                                   room_members=room_members)
        else:
            return redirect(url_for('home'))
Пример #7
0
def view_room(room_id):
    room = get_room(room_id)
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        return render_template('vr1.html',
                               username=current_user.username,
                               room=room,
                               room_members=room_members,
                               messages=messages,
                               room_id=room_id)
Пример #8
0
def edit_room(room_id):
    room = get_room(room_id)
    if room and is_room_admin(room_id, current_user.username):
        existing_room_members = [
            member['_id']['username'] for member in get_room_members(room_id)
        ]
        room_members_str = ",".join(existing_room_members)
        message = ''
        if request.method == 'POST':
            room_name = request.form.get('room_name')
            if (len(request.form.get('room_name'))) == 0:
                message = "Room name cannot be empty"
                return render_template('edit_room.html',
                                       room=room,
                                       room_members_str=room_members_str,
                                       message=message)
            room['name'] = room_name
            update_room(room_id, room_name)
            if len(request.form.get('members')) == 0:
                message = "Edit unsuccessful"
                return render_template('edit_room.html',
                                       room=room,
                                       room_members_str=room_members_str,
                                       message=message)
            new_members = [
                username.strip()
                for username in request.form.get('members').split(',')
            ]
            members_to_add = list(
                set(new_members) - set(existing_room_members))
            members_to_remove = list(
                set(existing_room_members) - set(new_members))
            if current_user.username in members_to_remove:
                message = "Cannot remove admin from room"
                return render_template('edit_room.html',
                                       room=room,
                                       room_members_str=room_members_str,
                                       message=message)
            if len(members_to_add):
                add_room_members(room_id, room_name, members_to_add,
                                 current_user.username)
            if len(members_to_remove):
                remove_room_members(room_id, members_to_remove)
            message = 'Room edited successfully'
            room_members_str = ",".join(new_members)
            return redirect(url_for('view_room', room_id=room_id))

        return render_template('edit_room.html',
                               room=room,
                               room_members_str=room_members_str,
                               message=message)
    else:
        message = "Not the admin for this room"
        return render_template('error.html', message=message)
Пример #9
0
def view_room(room_id):
    room = [i for i in db.get_room(room_id)]
    if room and db.is_room_member(room_id, current_user.username):
        room_members = [i for i in db.get_room_members(room_id)]
        messages = [i for i in db.get_messages(room_id)]
        return render_template('view-room.html',
                               user=current_user.username,
                               room=room[0],
                               room_members=room_members[0],
                               messages=messages[0])
    return 'Room not fould', 404
Пример #10
0
def audio_book():
    if request.method == 'POST':
        book_name = request.form.get('books', None)
        room_name = get_all_room(session['username'])
        print(room_name)
        room_id = get_id(room_name['room_name'])
        room = get_room(room_id['_id'])
        room_members = get_room_members(room_id['_id'])
        books = get_all_books()
        print(room_id)
        print(room_members)
        messages = get_messages(room_id['_id'])
        ready_audio(book_name)
        songs = os.listdir('./static/music/' + book_name)
        return render_template('view_room.html',
                               username=session['username'],
                               room=room,
                               room_members=room_members,
                               songs=songs,
                               messages=messages,
                               books=books)
    else:
        room_name = get_all_room(session['username'])
        print(room_name)
        room_id = get_id(room_name['room_name'])
        room = get_room(room_id['_id'])
        room_members = get_room_members(room_id['_id'])
        books = get_all_books()
        print(room_id)
        print(room_members)
        messages = get_messages(room_id['_id'])
        #book_id=get_group(session['username'])[2]
        #book_name=book_id_to_name(book_id)
        songs = ''  #os.listdir('./static/music/'+book_name[0])
        return render_template('view_room.html',
                               username=session['username'],
                               room=room,
                               room_members=room_members,
                               songs=songs,
                               messages=messages,
                               books=books)
Пример #11
0
def view_room(room_id):
    room = get_room(room_id)
    if current_user.is_authenticated:
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        return render_template('chatroom.html',
                               username=current_user.username,
                               room=room,
                               room_members=room_members,
                               messages=messages)
    else:
        return "You are unauthorized. Please login.", 404
Пример #12
0
def chat(room_id):
    room = get_room(room_id)
    room_members = get_room_members(room_id)
    if room and is_room_member(room_id, current_user.username):
        is_room_admin = check_if_room_admin(room_id, current_user.username)
        return render_template('view_room.html',
                               username=current_user.username,
                               room=room,
                               room_members=room_members,
                               is_room_admin=is_room_admin)
    else:
        return redirect(url_for('home'))
Пример #13
0
def view_room(room_id):
    room = get_room(room_id)
    print("here")
    print(is_room_member(room_id, current_user.username))
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        print(messages)
        return render_template('view_room.html',
                               messages=messages,
                               username=current_user.username,
                               room=room,
                               room_members=room_members)

    return "Room not found", 404
Пример #14
0
def view_room(room_id):
    room = get_room(room_id)
    print(room)
    print(room_id)
    print(current_user.username)
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        print(room_members)
        # 2020.07.17 여기까지 완료
        # username 부분이 채팅화면으로 들어갔을 때, 제대로 데아터를 가지고 오지 못하는 오류가 발생
        return render_template('view_room.html',
                               room=room,
                               room_members=room_members,
                               username=username)
    else:
        return "Room not found", 404
Пример #15
0
def view_room(room_id):
    room = get_room(room_id)

    if room and is_room_member(room_id, current_user.username):
        room_rule = get_room_rules(room_id)
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        return render_template('view_room.html',
                               username=current_user.username,
                               room=room,
                               room_rule=room_rule,
                               room_members=room_members,
                               messages=messages)
    #username = request.args.get('username')
    #room = request.args.get('room')
    else:
        return "Room not found", 404
Пример #16
0
def chat_room(room_id):
    rooms = get_rooms_for_user(current_user.username)
    room = get_room(room_id)
    email = get_email(current_user.username)
    admins = []
    not_admin = []
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        for member in room_members:
            if is_room_admin(room_id, member['_id']['username']):
                admins.append(member['_id']['username'])
            else:
                not_admin.append(member['_id']['username'])

        messages = get_messages(room_id)
        return render_template('chat.html', admins=admins, rooms=rooms, username=current_user.username, not_admin=not_admin, email=email, room=room, room_members=room_members, room_id=room_id, messages=messages)
    else:

        return render_template('404.html', message='Room does not exist')
Пример #17
0
def view_room(room_id):
    room = get_room(room_id)
    try:
        is_dm = room['is_dm']
    except KeyError:
        is_dm = False
    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        rooms = get_rooms_for_user(current_user.username)
        return render_template('view_room.html',
                               username=current_user.username,
                               this_room=room,
                               messages=messages,
                               room_members=room_members,
                               other_rooms=rooms,
                               is_dm=is_dm)
    else:
        return "Room not found", 404
Пример #18
0
def books():
    if request.method == "POST":
        books = get_all_books()
        val = []
        for i in books:
            option = request.form[i[0] + i[1]]
            val.append(option)
        for i, book in enumerate(books):
            if (val[i] == '1'):
                print("liked", book[2])
                like(session['username'], book[2], like=1)
            elif (val[i] == '-1'):
                print("disliked", book[2])
                like(session['username'], book[2], like=-1)
            elif (val[i] == '0'):
                print("No Reaction", book[2])
                like(session['username'], book[2], like=0)

        book_id_to_new_book_id = get_book_id_to_new_book_id(get_book_ids())
        gid = get_group_id_of_new_user(
            clf, clusters, session['username'],
            get_like_dislike(session['username'], 'Like'),
            get_like_dislike(session['username'], 'DisLike'),
            book_id_to_new_book_id)
        group_new_user(session['username'], gid)
        room_id = get_id(gid)['_id']
        add_room_members(room_id, gid, [session['username']], 'system')
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        books = get_all_books()
        return render_template('view_room.html',
                               username=session['username'],
                               room=gid,
                               room_members=room_members,
                               books=books,
                               messages=messages)
    else:
        books = get_all_books()
        return render_template('books.html', books=books)
Пример #19
0
def edit_room(room_id):
    room = get_room(room_id)
    print(room)
    print(is_room_admin(room_id, current_user.username))
    if room and is_room_admin(room_id, current_user.username):
        existing_room_members = [
            member['_id']['username'] for member in get_room_members(room_id)
        ]

        message = ''
        if request.method == 'POST':
            room_name = request.form.get('room_name')

            update_room(room_id, room_name)
            new_members = [
                username.strip()
                for username in request.form.get('members').split(',')
            ]
            print(new_members)
            members_to_add = list(
                set(new_members) - set(existing_room_members))
            members_to_remove = list(
                set(existing_room_members) - set(new_members))
            print(members_to_remove, members_to_remove)
            if len(members_to_add):
                add_room_members(room_id, room_name, members_to_add,
                                 current_user.username)
            if len(members_to_remove):
                remove_room_members(room_id, members_to_remove)
            return redirect(url_for('home'))
        room_members_str = ",".join(existing_room_members)
        print(room_members_str)
        return render_template('edit_room.html',
                               message=message,
                               room=room,
                               room_members_str=room_members_str)

    return "Room not found", 404
Пример #20
0
def single_room_members_test(room_id):
    user_id = get_jwt_identity()
    current_app.logger.info('{} requested members for {}'.format(
        user_id, room_id))

    members_from_db = get_room_members(room_id)
    this_room = get_room(room_id)
    members = []

    if not this_room or not members_from_db:
        return jsonify({'Error': 'Room not found.'}), 404

    if not is_room_member(room_id, user_id):
        return jsonify(
            {'Error': 'You are not a member of the requested room.'}), 403

    if request.method == 'GET':
        for member in members_from_db:
            try:
                some_user = get_user(str(member['_id']['user_id']))
            except KeyError as e:
                continue
            except TypeError as e:
                return jsonify({'Error': e}), 400
            if not some_user:
                continue

            members.append(some_user.create_json())

        return jsonify(members), 200
    elif request.method == 'POST':
        json_input = request.get_json(force=True)

        try:
            new_members = json_input['add_members']
        except Exception as e:
            return jsonify({'Error': 'Bad input'}), 400
Пример #21
0
def edit_room(room_id):
    room = [i for i in db.get_room(room_id)]
    if room and db.is_room_admin(room_id, current_user.username):
        existing_room_members = [
            member for member in db.get_room_members(room_id)
        ]
        existing_members = [
            str(member['_id']['username'])
            for member in existing_room_members[0]
        ]

        if request.method == 'POST':
            room_name = request.form['room_name']
            db.update_room(room_id, room_name)

            new_members = [
                username.strip()
                for username in request.form['members'].split(',')
            ]
            members_to_add = list(set(new_members) - set(existing_members))
            members_to_remove = list(set(existing_members) - set(new_members))

            if len(members_to_add):
                db.add_room_members(room_id, room_name, members_to_add,
                                    current_user.username)

            if len(members_to_remove):
                db.remove_room_members(room_id, members_to_remove)

            return redirect('/')

        room_members_str = ', '.join(existing_members)
        return render_template('edit-room.html',
                               room=room[0],
                               room_members_str=room_members_str)
    return 'Room not fould', 404
Пример #22
0
def get_rooms(user_id):
    room_list_raw = get_rooms_for_user(user_id)
    room_list = []
    user = get_user(user_id)

    for item in room_list_raw:
        # parse the room
        room_parsed = parse_json(item)
        room_id = str(room_parsed['_id']['room_id']['$oid'])

        # get room members
        members_raw = get_room_members(room_id)
        members = list(
            map(lambda m: get_user(str(m['_id']['user_id'])).create_json(),
                members_raw))
        # ignoring check for is_room_member, some bug for me to complain about later

        # get room
        room_object = get_room(room_id)
        this_room = return_enumerated_room(room_object, user.username, user_id,
                                           members)
        room_list.append(this_room)

    return room_list  # returns an array of rooms
Пример #23
0
def edit_room(room_id):
    room = get_room(room_id)
    admins = []
    not_admin = []
    error_msg = ''
    message = ''
    if room and is_room_admin(room_id, current_user.username):

        members = get_room_members(room_id)
        members_list = [username['_id']['username'] for username in members]
        for member in members:
            if is_room_admin(room_id, member['_id']['username']):
                admins.append(member['_id']['username'])
            else:
                not_admin.append(member['_id']['username'])
        if request.method == "POST":
            room_name = request.form.get('room_name')
            room['name'] = room_name
            update_room(room_id, room_name)
            make_admin = request.form.get('makeAdmin')
            removeAdmin = request.form.get('removeAdmin')
            add_member = request.form.get('addmember')
            rem_mem = request.form.get('remove_user')
            rem_room = request.form.get('delete_room')

            if make_admin:
                try:
                    update_admin(room_id, make_admin)
                    message = '{} is now an Admin🥳'.format(make_admin)
                except:
                    error_msg = 'Some error occured'

            if removeAdmin:
                try:
                    if len(admins) > 1:
                        remove_admin(room_id, removeAdmin)
                        message = '{} is no longer an Admin'.format(
                            removeAdmin)
                    else:
                        message = 'Atleast one admin should be present'
                except:
                    error_msg = 'Some error occured'

            if add_member:
                try:
                    user = check_user(add_member)
                    if user:
                        if add_member not in members_list:
                            add_mems = [username.strip()
                                        for username in add_member.split(',')]
                            add_room_members(room_id, room_name, add_mems,
                                             current_user.username)
                            message = '\"{}\" added successfully'.format(
                                add_member)
                        else:
                            message = "\"{}\" already in room".format(
                                add_member)
                    else:
                        message = "\"{}\" does not exist :(".format(add_member)
                except:
                    error_msg = "Some error occured"

            if rem_mem:
                is_admin = is_room_admin(room_id, rem_mem)
                try:
                    if len(members_list) > 1:
                        if is_admin and len(admins) == 1:
                            message = 'Atleast one Admin should be present '
                        else:
                            remove_room_member(room_id, rem_mem)
                            message = '{} removed successfully'.format(rem_mem)
                    else:
                        message = 'Atleast one member should be present'
                except:
                    error_msg = "Some error occured"
            if rem_room == 'Remove':
                try:
                    for member in members_list:
                        print("hi")
                        remove_room_member(room_id, member)
                    delete_room(room_id)
                    return redirect(url_for('home'))

                except:
                    error_msg = "Some error oocured"

                # return redirect(url_for('edit_room',room_id=room_id,message = message))

        return render_template('edit_room.html', not_admin=not_admin, admins=admins, room=room, members=members, error_msg=error_msg, room_id=room_id, message=message)

    else:
        return render_template('404.html', message='Only admins can Edit Room', room_id=room_id)
Пример #24
0
def view_room(room_id):
    room = get_room(room_id)
    a=emoji.emojize(":grinning_face_with_big_eyes:")
    b=emoji.emojize(":winking_face_with_tongue:")
    c=emoji.emojize(":zipper-mouth_face:")
    d=emoji.emojize(":nauseated_face:")
    e=emoji.emojize(":face_with_head-bandage:")
    f=emoji.emojize(":sleepy_face:")
    g=emoji.emojize(":face_with_rolling_eyes:")
    h=emoji.emojize(":lying_face:")
    i=emoji.emojize(":relieved_face:")
    j=emoji.emojize(":pensive_face:")
    k=emoji.emojize(":smirking_face:")
    l=emoji.emojize(":expressionless_face:")
    m=emoji.emojize(":shushing_face:")
    n=emoji.emojize(":thinking_face:")
    o=emoji.emojize(":face_with_raised_eyebrow:")
    p = emoji.emojize(":grinning_face:")
    q = emoji.emojize(":grinning_face_with_smiling_eyes:")
    r = emoji.emojize(":beaming_face_with_smiling_eyes:")
    s = emoji.emojize(":grinning_squinting_face:")
    t = emoji.emojize(":rolling_on_the_floor_laughing:")
    u = emoji.emojize(":grinning_face_with_sweat:")
    v = emoji.emojize(":face_with_tears_of_joy:")
    w = emoji.emojize(":slightly_smiling_face:")
    x = emoji.emojize(":upside-down_face:")
    y = emoji.emojize(":winking_face:")
    a1= emoji.emojize(":smiling_face_with_smiling_eyes:")
    b1= emoji.emojize(":smiling_face_with_halo:")
    c1= emoji.emojize(":face_blowing_a_kiss:")
    d1= emoji.emojize(":smiling_face_with_heart-eyes:")
    e1= emoji.emojize(":star-struck:")
    f1= emoji.emojize(":kissing_face:")
    g1= emoji.emojize(":kissing_face_with_closed_eyes:")
    h1= emoji.emojize(":kissing_face_with_smiling_eyes:")
    i1= emoji.emojize(":face_savoring_food:")
    j1= emoji.emojize(":zany_face:")
    k1= emoji.emojize(":sunglasses:")
    l1= emoji.emojize(":kiss:")
    m1= emoji.emojize(":collision:")
    n1= emoji.emojize(":princess:")
    o1= emoji.emojize(":eyes:")
    q1= emoji.emojize(":pizza:")
    p1= emoji.emojize(":memo:")
    r1= emoji.emojize(":poultry_leg:")
    s1= emoji.emojize(":custard:")
    t1= emoji.emojize(":cookie:")
    u1=emoji.emojize(":sushi:")
    v1=emoji.emojize(":pear:")
    w1=emoji.emojize(":cherries:")
    x1=emoji.emojize(":chocolate_bar:")
    y1=emoji.emojize(":musical_note:")
    a2 = emoji.emojize(":video_game:")
    b2 = emoji.emojize(":family:")
    c2 = emoji.emojize(":hotel:")
    d2 = emoji.emojize(":boy:")
    e2 = emoji.emojize(":girl:")
    f2 = emoji.emojize(":school:")
    g2 = emoji.emojize(":house:")
    h2 = emoji.emojize(":hospital:")
    i2 = emoji.emojize(":bank:")
    j2 = emoji.emojize(":cinema:")
    k2 = emoji.emojize(":station:")
    l2 = emoji.emojize(":ambulance:")
    m2 = emoji.emojize(":airplane:")
    n2 = emoji.emojize(":taxi:")
    o2 = emoji.emojize(":oncoming_automobile:")




    if room and is_room_member(room_id, current_user.username):
        room_members = get_room_members(room_id)
        messages = get_messages(room_id)
        return render_template('view_room.html', username=current_user.username, room_id=room_id, room=room, room_members=room_members,
                                messages=messages,a=a,b=b,c=c,d=d,e=e,f=f,g=g,h=h,i=i,j=j,k=k,l=l,m=m,n=n,o=o,p=p,q=q,r=r,s=s,t=t,u=u,
                               v=v,w=w,x=x,y=y,a1=a1,b1=b1,c1=c1,d1=d1,e1=e1,f1=f1,g1=g1,h1=h1,i1=i1,j1=j1,k1=k1,l1=l1,m1=m1,n1=n1,o1=o1,p1=p1,q1=q1,r1=r1,
                               s1=s1,t1=t1,u1=u1,v1=v1,w1=w1,x1=x1,y1=y1,a2=a2,b2=b2,c2=c2,d2=d2,e2=e2,f2=f2,g2=g2,h2=h2,i2=i2,j2=j2,k2=k2,l2=l2,m2=m2,n2=n2,o2=o2)
    else:
        return "Room not found", 404
Пример #25
0
def handle_send_message_event(data):
    current_app.logger.info('Caught message from client.')
    user_id = get_jwt_identity()

    username = data['username']
    room_id = data['room']  # client must pass room id here
    message = data['text']
    
    try:
        image_id = data['image_id']
    except Exception as e:
        image_id = None

    if len(message) == 0 and not image_id:
        return None
    
    time_sent = time.time()
    data['time_sent'] = time_sent
    user = get_user(user_id)
    room = get_room(room_id)
    data['user_id'] = user_id
    # data['avatar_id'] = user.avatar
    data['room_name'] = room.name

    if user_id not in connected_sockets:
        current_app.logger.info('!!: {} tried to send a message without being connected to a room.'.format(username))

    room_member_ids = []
    room_member_objects = get_room_members(room_id)  # determine who should receive this message
    for db_item in room_member_objects:
        room_member_ids.append(str(db_item['_id']['user_id']))

    if user_id in room_member_ids:  # if the author/sender is in the room they are trying to send to
        current_app.logger.info("{} ({}) has sent message to the room {} at {}".format(user_id, username, room, time_sent))
        apns_targets = []

        for member in room_member_ids:  # for person in room
            member_id = get_user(member).ID
            if member_id in connected_sockets and len(connected_sockets[member_id]) != 0:
                target_socket_ids = connected_sockets[member_id]
                try:
                    for socket in target_socket_ids:
                        socketio.emit('receive_message', data, room=socket)  # emit to specific user
                        current_app.logger.info('Sent to {}'.format(socket))
                except TypeError as e:
                    current_app.logger.info('Failed to emit message to {}, connected on {}. They may not have an open '
                                            'connection. {}'.format(member_id, connected_sockets[member_id], e))
            else:  # send push notifications for anyone offline
                user_apn_tokens = get_apn(member)
                if not user_apn_tokens:
                    continue
                else:
                    apns_targets.extend(user_apn_tokens)
        # room_id, text, sender, bucket_number=0, image_id=None
        current_app.logger.info("Emitting APNS and storing message".format())
        apns_thread = threading.Thread(target=handle_apns_load, args=(apns_targets, data, room.is_dm))
        # current_app.logger.info("SAVING MESSAGE")
        db_thread = threading.Thread(target=save_message, args=(room_id, message, user_id, image_id))  # to db
        apns_thread.start()
        db_thread.start()
        current_app.logger.info("{} {}".format(apns_thread, db_thread))
    else:
        current_app.logger.info("{} not authorized to send to {}".format(username, room))