uniapp,h5

chatMsg.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. from app.app import mongo
  2. from app.libs.redprint import Redprint
  3. from flask import jsonify, request
  4. from bson.objectid import ObjectId
  5. from pymongo.errors import PyMongoError
  6. import traceback
  7. api = Redprint('chatMsg')
  8. @api.route('/get/all')
  9. def get_all_msg():
  10. # mongo.db.chatAll.delete_many({})
  11. msg_infos = list(mongo.db.chatAll.find())
  12. for msg_info in msg_infos:
  13. msg_info["_id"] = str(msg_info["_id"])
  14. return jsonify(msg_infos)
  15. @api.route('/get/one2one/<sendId>/<rspId>')
  16. def get_o2o_msg(sendId, rspId):
  17. # mongo.db.chatOne2One.delete_many({})
  18. msg_infos = list(mongo.db.chatOne2One.find())
  19. # 使用列表推导式过滤掉 resUserId 等于 chaterId 的元素
  20. 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"])]
  21. for msg_info in msg_infos:
  22. msg_info["_id"] = str(msg_info["_id"])
  23. return jsonify(msg_infos)
  24. @api.route('/get/more2more')
  25. def get_m2m_msg():
  26. msg_infos = list(mongo.db.chatMore2More.find())
  27. for msg_info in msg_infos:
  28. msg_info["_id"] = str(msg_info["_id"])
  29. return jsonify(msg_infos)
  30. def InitItem(item, id):
  31. user_id_obj = ObjectId(id)
  32. user = mongo.db.users.find_one({"_id": user_id_obj})
  33. if user:
  34. item["userId"] = id
  35. item["username"] = user["username"]
  36. item["avatar"] = user["avatar_url"]
  37. item["lastMsgContent"] = "您有一条新信息..."
  38. item["time"] = "2024-09-18 12:36:09"
  39. item["unreadCount"] = 1
  40. @api.route('/get/chatItems/<user_id>')
  41. def get_msg_list(user_id):
  42. user_id_obj = ObjectId(user_id) # 尝试将user_id转化为ObjectId
  43. # mongo.db.chatList.delete_many({})
  44. try:
  45. # 从chatUsers数组中找到对应的用户聊天信息
  46. result = mongo.db.chatList.find_one(
  47. {"userId": user_id_obj},
  48. )
  49. except Exception as e:
  50. return jsonify({"message": f"Database error: {str(e)}"}), 500
  51. if result is None:
  52. # 文档未找到或用户未找到,返回 404 和提示信息
  53. return jsonify({"message": f"Chat items for user {user_id} do not exist."}), 404
  54. # 从结果中提取用户的聊天列表
  55. user_chat_info_ids = result.get('chatUsers', [])
  56. user_chat_list_info = []
  57. for user_chat_info_id in user_chat_info_ids:
  58. item = {}
  59. InitItem(item, user_chat_info_id)
  60. user_chat_list_info.append(item)
  61. # 返回数组
  62. return jsonify(user_chat_list_info), 200
  63. @api.route('/appendChatUser', methods=['POST'])
  64. def append_msg_list():
  65. data = request.get_json()
  66. user_id = data["userId"]
  67. to_append_id = data["id"]
  68. # 将字符串形式的user_id转换为ObjectId
  69. user_id_obj = ObjectId(user_id)
  70. try:
  71. # 使用update_one,如果文档存在则更新,不存在则插入
  72. result = mongo.db.chatList.update_one(
  73. {"userId": user_id_obj},
  74. {
  75. "$addToSet": {"chatUsers": to_append_id},
  76. "$setOnInsert": {"userId": user_id_obj}
  77. },
  78. upsert=True
  79. )
  80. if result.matched_count > 0:
  81. return jsonify({"message": "ID added successfully to existing user."}), 201
  82. else:
  83. return jsonify({"message": "New user created and ID added."}), 201
  84. except PyMongoError as e:
  85. return jsonify({"error": f"Database error: {str(e)}", "traceback": traceback.format_exc()}), 500
  86. # id: obj.a2bId,
  87. # name: obj.username,
  88. # avatarList: obj.avatar,
  89. # note: obj.lastMsgContent,
  90. # time: obj.time,
  91. # unreadCount: obj.unreadCount
  92. # {
  93. # {
  94. # "userId": ObjectId("61d679a12e4d4e348a103c79"),
  95. # "chatUsers": [
  96. # ObjectId("61d679a12e4d4e348a103c7a"),
  97. # ObjectId("61d679a12e4d4e348a103c7b")
  98. # ]
  99. # },
  100. # {
  101. # "userId": ObjectId("61d679a12e4d4e348a103c7c"),
  102. # "chatUsers": [
  103. # ObjectId("61d679a12e4d4e348a103c7a"),
  104. # ObjectId("61d679a12e4d4e348a103c7d")
  105. # ]
  106. # }
  107. # }