def message(id): if not UserConnect.is_friend(id): return redirect(url_for('app.home')) form = MessageForm(request.form) # 自分と相手のやり取りのメッセージを取得 messages = Message.get_friend_messages(current_user.get_id(), id) user = User.select_user_by_id(id) # まだ読まれていないが、新たに読まれるメッセージ read_message_ids = [message.id for message in messages if (not message.is_read) and (message.from_user_id == int(id))] # すでに読まれていて、かつまだチェックしていない自分のメッセージをチェック not_checked_message_ids = [message.id for message in messages if message.is_read and (not message.is_checked) and (message.from_user_id == int(current_user.get_id()))] if not_checked_message_ids: with db.session.begin(subtransactions=True): Message.update_is_checked_by_ids(not_checked_message_ids) db.session.commit() # read_message_idsのis_readをTrueに変更 if read_message_ids: with db.session.begin(subtransactions=True): Message.update_is_read_by_ids(read_message_ids) db.session.commit() if request.method == 'POST' and form.validate(): new_message = Message(current_user.get_id(), id, form.message.data) with db.session.begin(subtransactions=True): new_message.create_message() db.session.commit() return redirect(url_for('app.message', id=id)) return render_template( 'message.html', form=form, messages=messages, to_user_id=id, user=user )
def message_ajax(): user_id = request.args.get('user_id', -1, type=int) # まだ読んでいない相手からのメッセージを取得 user = User.select_user_by_id(user_id) not_read_messages = Message.select_not_read_messages(user_id, current_user.get_id()) not_read_message_ids = [message.id for message in not_read_messages] if not_read_message_ids: with db.session.begin(subtransactions=True): Message.update_is_read_by_ids(not_read_message_ids) db.session.commit() # すでに読まれた自分のメッセージでまだチェックしていないものを取得 not_checked_messages = Message.select_not_checked_messages(current_user.get_id(), user_id) not_checked_message_ids = [not_checked_message.id for not_checked_message in not_checked_messages] if not_checked_message_ids: with db.session.begin(subtransactions=True): Message.update_is_checked_by_ids(not_checked_message_ids) db.session.commit() return jsonify(data=make_message_format(user, not_read_messages), checked_message_ids = not_checked_message_ids)