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

160 lines
6.2KB

  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=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(wxchat:gewe_chat.GeWeChatCom, token_id, app_id,region_id, agent_token_id,hash_key, uuid,start_time):
  80. agent_tel=hash_key.split(":")[-1]
  81. try:
  82. while True:
  83. now = time.time()
  84. if now - start_time > 150:
  85. logger.info(f'{token_id} 使用 {app_id} 扫二维码登录超时')
  86. break
  87. logger.info(f"{token_id} 使用 {app_id},等待扫码登录,二维码有效时间 {150 - int(now - start_time)} 秒")
  88. captch_code = wxchat.get_login_wx_captch_code_from_cache(token_id)
  89. captch_code= captch_code if captch_code else ''
  90. logger.info(f"{token_id} 使用 {app_id} 的验证码 {captch_code}")
  91. ret,msg,res = wxchat.check_login(token_id, app_id, uuid,captch_code)
  92. if ret == 200:
  93. flag = res.get('status')
  94. if flag == 2:
  95. logger.info(f"登录成功: {res}")
  96. head_img_url=res.get('headImgUrl','')
  97. login_info = res.get('loginInfo', {})
  98. wxid=login_info.get('wxid',agent_tel)
  99. login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id,'status': 1,'headImgUrl':head_img_url,'regionId':region_id})
  100. cache_login_info=redis_helper.redis_helper.get_hash(hash_key)
  101. if 'appId' not in cache_login_info:
  102. login_info.update({"create_at":int(time.time()),"modify_at":int(time.time())})
  103. # 默认配置
  104. config=Models.AgentConfig.model_validate({
  105. "chatroomIdWhiteList": [],
  106. "agentTokenId": agent_token_id,
  107. "agentEnabled": False,
  108. "addContactsFromChatroomIdWhiteList": [],
  109. "chatWaitingMsgEnabled": True
  110. })
  111. else:
  112. login_info.update({"modify_at":int(time.time())})
  113. # 已有配置
  114. config_cache=wxchat.get_wxchat_config_from_cache(wxid)
  115. config=Models.AgentConfig.model_validate(config_cache)
  116. cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
  117. #wxid=cleaned_login_info.get('wxid',agent_tel)
  118. # 保存配置信息
  119. config_dict=config.model_dump()
  120. wxchat.save_wxchat_config(wxid,config_dict)
  121. # 保存登录信息
  122. redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
  123. wxchat.release_login_lock(token_id)
  124. break
  125. else:
  126. logger.info(f"登录检查中: {ret}-{msg}-{res}")
  127. time.sleep(5)
  128. finally:
  129. wxchat.release_login_lock(token_id)