You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

165 lines
6.5KB

  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. base64_string = qr_code.get('qrImgBase64',None)
  59. uuid = qr_code.get('uuid',None)
  60. if not uuid:
  61. msg=f"uuid获取二维码失败,uuid: {uuid}"
  62. gewe_chat.wxchat.release_login_lock(token_id)
  63. logger.info(msg)
  64. response=jsonify({'code': 501, 'message': msg})
  65. response.status_code = 501
  66. return response
  67. app_id = app_id or qr_code.get('appId')
  68. gewe_chat.wxchat.qrCallback(uuid,base64_string)
  69. hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
  70. thread = threading.Thread(target=waitting_login_result, args=(gewe_chat.wxchat,token_id, app_id,region_id, agent_token_id,hash_key, uuid,now))
  71. thread.daemon = True
  72. thread.start()
  73. data={
  74. "tokenId": token_id,
  75. "tel": tel,
  76. "base64Img": base64_string,
  77. "expiredTime": expried_time,
  78. }
  79. return jsonify(data)
  80. def waitting_login_result(wxchat:gewe_chat.GeWeChatCom, token_id, app_id,region_id, agent_token_id,hash_key, uuid,start_time):
  81. agent_tel=hash_key.split(":")[-1]
  82. try:
  83. while True:
  84. now = time.time()
  85. if now - start_time > 150:
  86. logger.info(f'{token_id} 使用 {app_id} 扫二维码登录超时')
  87. break
  88. logger.info(f"{token_id} 使用 {app_id},等待扫码登录,二维码有效时间 {150 - int(now - start_time)} 秒")
  89. captch_code = wxchat.get_login_wx_captch_code_from_cache(token_id)
  90. captch_code= captch_code if captch_code else ''
  91. logger.info(f"{token_id} 使用 {app_id} 的验证码 {captch_code}")
  92. ret,msg,res = wxchat.check_login(token_id, app_id, uuid,captch_code)
  93. if ret == 200:
  94. flag = res.get('status')
  95. if flag == 2:
  96. logger.info(f"登录成功: {res}")
  97. head_img_url=res.get('headImgUrl','')
  98. login_info = res.get('loginInfo', {})
  99. wxid=login_info.get('wxid',agent_tel)
  100. login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id,'status': 1,'headImgUrl':head_img_url,'regionId':region_id})
  101. cache_login_info=redis_helper.redis_helper.get_hash(hash_key)
  102. if 'appId' not in cache_login_info:
  103. login_info.update({"create_at":int(time.time()),"modify_at":int(time.time())})
  104. # 默认配置
  105. config=Models.AgentConfig.model_validate({
  106. "chatroomIdWhiteList": [],
  107. "agentTokenId": agent_token_id,
  108. "agentEnabled": False,
  109. "addContactsFromChatroomIdWhiteList": [],
  110. "chatWaitingMsgEnabled": True
  111. })
  112. else:
  113. login_info.update({"modify_at":int(time.time())})
  114. # 已有配置
  115. config_cache=wxchat.get_wxchat_config_from_cache(wxid)
  116. config=Models.AgentConfig.model_validate(config_cache)
  117. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  118. #wxid=cleaned_login_info.get('wxid',agent_tel)
  119. # 保存配置信息
  120. config_dict=config.model_dump()
  121. wxchat.save_wxchat_config(wxid,config_dict)
  122. # 保存登录信息
  123. redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
  124. wxchat.release_login_lock(token_id)
  125. # 登录结果推送到kafka
  126. k_message=utils.login_result_message(token_id,agent_tel,region_id,agent_token_id,wxid)
  127. kafka_helper.kafka_client.produce_message(k_message)
  128. break
  129. else:
  130. logger.info(f"登录检查中: {ret}-{msg}-{res}")
  131. time.sleep(5)
  132. finally:
  133. wxchat.release_login_lock(token_id)