| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134 |
- from app.app import mongo
- from app.libs.redprint import Redprint
- from flask import jsonify, request
- from bson.objectid import ObjectId
- from pymongo.errors import PyMongoError
- import traceback
-
- api = Redprint('chatMsg')
-
-
- @api.route('/get/all')
- def get_all_msg():
- # mongo.db.chatAll.delete_many({})
- msg_infos = list(mongo.db.chatAll.find())
- for msg_info in msg_infos:
- msg_info["_id"] = str(msg_info["_id"])
- return jsonify(msg_infos)
-
-
- @api.route('/get/one2one/<sendId>/<rspId>')
- def get_o2o_msg(sendId, rspId):
- # mongo.db.chatOne2One.delete_many({})
- msg_infos = list(mongo.db.chatOne2One.find())
- # 使用列表推导式过滤掉 resUserId 等于 chaterId 的元素
- msg_infos = [msg_info for msg_info in msg_infos if (sendId == msg_info["sendUserId"] and rspId == msg_info["resUserId"] or rspId == msg_info["sendUserId"] and sendId == msg_info["resUserId"])]
-
- for msg_info in msg_infos:
- msg_info["_id"] = str(msg_info["_id"])
-
- return jsonify(msg_infos)
-
-
- @api.route('/get/more2more')
- def get_m2m_msg():
- msg_infos = list(mongo.db.chatMore2More.find())
- for msg_info in msg_infos:
- msg_info["_id"] = str(msg_info["_id"])
- return jsonify(msg_infos)
-
-
- def InitItem(item, id):
- user_id_obj = ObjectId(id)
- user = mongo.db.users.find_one({"_id": user_id_obj})
- if user:
- item["userId"] = id
- item["username"] = user["username"]
- item["avatar"] = user["avatar_url"]
- item["lastMsgContent"] = "您有一条新信息..."
- item["time"] = "2024-09-18 12:36:09"
- item["unreadCount"] = 1
-
-
- @api.route('/get/chatItems/<user_id>')
- def get_msg_list(user_id):
- user_id_obj = ObjectId(user_id) # 尝试将user_id转化为ObjectId
- # mongo.db.chatList.delete_many({})
- try:
- # 从chatUsers数组中找到对应的用户聊天信息
- result = mongo.db.chatList.find_one(
- {"userId": user_id_obj},
- )
- except Exception as e:
- return jsonify({"message": f"Database error: {str(e)}"}), 500
-
- if result is None:
- # 文档未找到或用户未找到,返回 404 和提示信息
- return jsonify({"message": f"Chat items for user {user_id} do not exist."}), 404
-
- # 从结果中提取用户的聊天列表
- user_chat_info_ids = result.get('chatUsers', [])
-
- user_chat_list_info = []
- for user_chat_info_id in user_chat_info_ids:
- item = {}
- InitItem(item, user_chat_info_id)
- user_chat_list_info.append(item)
-
- # 返回数组
- return jsonify(user_chat_list_info), 200
-
-
- @api.route('/appendChatUser', methods=['POST'])
- def append_msg_list():
- data = request.get_json()
-
- user_id = data["userId"]
- to_append_id = data["id"]
-
- # 将字符串形式的user_id转换为ObjectId
- user_id_obj = ObjectId(user_id)
-
- try:
- # 使用update_one,如果文档存在则更新,不存在则插入
- result = mongo.db.chatList.update_one(
- {"userId": user_id_obj},
- {
- "$addToSet": {"chatUsers": to_append_id},
- "$setOnInsert": {"userId": user_id_obj}
- },
- upsert=True
- )
-
- if result.matched_count > 0:
- return jsonify({"message": "ID added successfully to existing user."}), 201
- else:
- return jsonify({"message": "New user created and ID added."}), 201
-
- except PyMongoError as e:
- return jsonify({"error": f"Database error: {str(e)}", "traceback": traceback.format_exc()}), 500
-
- # id: obj.a2bId,
- # name: obj.username,
- # avatarList: obj.avatar,
- # note: obj.lastMsgContent,
- # time: obj.time,
- # unreadCount: obj.unreadCount
-
-
- # {
- # {
- # "userId": ObjectId("61d679a12e4d4e348a103c79"),
- # "chatUsers": [
- # ObjectId("61d679a12e4d4e348a103c7a"),
- # ObjectId("61d679a12e4d4e348a103c7b")
- # ]
- # },
- # {
- # "userId": ObjectId("61d679a12e4d4e348a103c7c"),
- # "chatUsers": [
- # ObjectId("61d679a12e4d4e348a103c7a"),
- # ObjectId("61d679a12e4d4e348a103c7d")
- # ]
- # }
- # }
|