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.

162 lignes
6.3KB

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