Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

156 lines
6.4KB

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