Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

175 lignes
6.8KB

  1. from flask_restful import Resource, reqparse
  2. from flask import jsonify,request,json
  3. from common import redis_helper,utils
  4. from wechat import gewe_chat,biz
  5. from common.log import logger, log_exception
  6. import time
  7. import threading
  8. from model import Models
  9. from common import kafka_helper
  10. class GetLoginInfoResource(Resource):
  11. def __init__(self):
  12. self.parser = reqparse.RequestParser()
  13. self.wxchat = gewe_chat.wxchat
  14. def post(self):
  15. req = request.get_json()
  16. tel = req.get("tel")
  17. config=self.wxchat.get_login_info_from_cache(tel)
  18. return jsonify(config)
  19. class LoginWxCaptchCodeResource(Resource):
  20. def __init__(self):
  21. self.parser = reqparse.RequestParser()
  22. self.wxchat = gewe_chat.wxchat
  23. def post(self):
  24. req = request.get_json()
  25. token_id = req.get("token_id")
  26. captch_code= req.get("captch_code")
  27. res=self.wxchat.save_login_wx_captch_code_to_cache(token_id,captch_code)
  28. return jsonify({'message': '操作成功'})
  29. class GetLoginWxQRCodeResource(Resource):
  30. def __init__(self):
  31. self.parser = reqparse.RequestParser()
  32. self.wxchat = gewe_chat.wxchat
  33. def post(self):
  34. req = request.get_json()
  35. token_id = req.get("tokenId")
  36. tel= req.get("tel")
  37. region_id= req.get("regionId")
  38. agent_token_id= req.get("agentTokenId")
  39. loginfo=gewe_chat.wxchat.get_login_info_from_cache(tel)
  40. status=loginfo.get('status','0')
  41. if status=='1':
  42. msg=f'手机号{tel},wx_token{token_id} 已经微信登录,终止登录流程'
  43. logger.info(msg)
  44. response=jsonify({'code': 501, 'message': msg})
  45. response.status_code = 501
  46. return response
  47. now=time.time()
  48. expried_time=int(now)+150
  49. flag=gewe_chat.wxchat.acquire_login_lock(token_id,150)
  50. if not flag:
  51. msg=f'手机号{tel}, wx_token{token_id} 登录进行中,稍后再试'
  52. logger.info(msg)
  53. response=jsonify({'code': 501, 'message': msg})
  54. response.status_code = 501
  55. return response
  56. app_id=loginfo.get('appId','')
  57. qr_code = gewe_chat.wxchat.get_login_qr_code(token_id, app_id,region_id)
  58. if not qr_code:
  59. msg=f"获取二维码失败,qr_code: {qr_code}"
  60. gewe_chat.wxchat.release_login_lock(token_id)
  61. logger.info(msg)
  62. response=jsonify({'code': 501, 'message': msg})
  63. response.status_code = 501
  64. return response
  65. uuid = qr_code.get('uuid',None)
  66. if not uuid:
  67. msg=f"uuid获取二维码失败,uuid: {uuid}"
  68. gewe_chat.wxchat.release_login_lock(token_id)
  69. logger.info(msg)
  70. response=jsonify({'code': 501, 'message': msg})
  71. response.status_code = 501
  72. return response
  73. app_id = app_id or qr_code.get('appId')
  74. base64_string = qr_code.get('qrImgBase64',None)
  75. gewe_chat.wxchat.qrCallback(uuid,base64_string)
  76. hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
  77. thread = threading.Thread(target=waitting_login_result, args=(gewe_chat.wxchat,token_id, app_id,region_id, agent_token_id,hash_key, uuid,now))
  78. thread.daemon = True
  79. thread.start()
  80. data={
  81. "tokenId": token_id,
  82. "tel": tel,
  83. "base64Img": base64_string,
  84. "expiredTime": expried_time,
  85. }
  86. return jsonify(data)
  87. def waitting_login_result(wxchat:gewe_chat.GeWeChatCom, token_id, app_id,region_id, agent_token_id,hash_key, uuid,start_time):
  88. agent_tel=hash_key.split(":")[-1]
  89. try:
  90. while True:
  91. now = time.time()
  92. if now - start_time > 150:
  93. logger.info(f'{token_id} 使用 {app_id} 扫二维码登录超时')
  94. break
  95. logger.info(f"{token_id} 使用 {app_id},等待扫码登录,二维码有效时间 {150 - int(now - start_time)} 秒")
  96. captch_code = wxchat.get_login_wx_captch_code_from_cache(token_id)
  97. captch_code= captch_code if captch_code else ''
  98. logger.info(f"{token_id} 使用 {app_id} 的验证码 {captch_code}")
  99. ret,msg,res = wxchat.check_login(token_id, app_id, uuid,captch_code)
  100. if ret == 200:
  101. flag = res.get('status')
  102. if flag == 2:
  103. logger.info(f"登录成功: {res}")
  104. head_img_url=res.get('headImgUrl','')
  105. login_info = res.get('loginInfo', {})
  106. wxid=login_info.get('wxid',agent_tel)
  107. login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id,'status': 1,'headImgUrl':head_img_url,'regionId':region_id})
  108. cache_login_info=redis_helper.redis_helper.get_hash(hash_key)
  109. if 'appId' not in cache_login_info:
  110. login_info.update({"create_at":int(time.time()),"modify_at":int(time.time())})
  111. # 默认配置
  112. config=Models.AgentConfig.model_validate({
  113. "chatroomIdWhiteList": [],
  114. "agentTokenId": agent_token_id,
  115. "agentEnabled": False,
  116. "addContactsFromChatroomIdWhiteList": [],
  117. "chatWaitingMsgEnabled": True
  118. })
  119. else:
  120. login_info.update({"modify_at":int(time.time())})
  121. # 已有配置
  122. config_cache=wxchat.get_wxchat_config_from_cache(wxid)
  123. config=Models.AgentConfig.model_validate(config_cache)
  124. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  125. #wxid=cleaned_login_info.get('wxid',agent_tel)
  126. # 保存配置信息
  127. config_dict=config.model_dump()
  128. wxchat.save_wxchat_config(wxid,config_dict)
  129. # 保存登录信息
  130. redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
  131. wxchat.release_login_lock(token_id)
  132. # 登录结果推送到kafka
  133. k_message=utils.login_result_message(token_id,agent_tel,region_id,agent_token_id,wxid)
  134. kafka_helper.kafka_client.produce_message(k_message)
  135. break
  136. else:
  137. logger.info(f"登录检查中: {ret}-{msg}-{res}")
  138. time.sleep(5)
  139. finally:
  140. wxchat.release_login_lock(token_id)