|
- from flask_restful import Resource, reqparse
- from flask import jsonify,request,json
- from common import redis_helper,utils
- from wechat import gewe_chat,biz
- from common.log import logger, log_exception
- import time
- import threading
-
- from model import Models
-
- from common import kafka_helper
-
-
-
- class GetLoginInfoResource(Resource):
- def __init__(self):
- self.parser = reqparse.RequestParser()
- self.wxchat = gewe_chat.wxchat
-
- def post(self):
- req = request.get_json()
- tel = req.get("tel")
- config=self.wxchat.get_login_info_from_cache(tel)
- return jsonify(config)
-
-
- class LoginWxCaptchCodeResource(Resource):
- def __init__(self):
- self.parser = reqparse.RequestParser()
- self.wxchat = gewe_chat.wxchat
-
- def post(self):
- req = request.get_json()
- token_id = req.get("token_id")
- captch_code= req.get("captch_code")
- res=self.wxchat.save_login_wx_captch_code_to_cache(token_id,captch_code)
- return jsonify({'message': '操作成功'})
-
- class GetLoginWxQRCodeResource(Resource):
- def __init__(self):
- self.parser = reqparse.RequestParser()
- self.wxchat = gewe_chat.wxchat
-
- def post(self):
- req = request.get_json()
- token_id = req.get("tokenId")
- tel= req.get("tel")
- region_id= req.get("regionId")
- agent_token_id= req.get("agentTokenId")
-
- loginfo=gewe_chat.wxchat.get_login_info_from_cache(tel)
- status=loginfo.get('status','0')
-
- if status=='1':
- msg=f'手机号{tel},wx_token{token_id} 已经微信登录,终止登录流程'
- logger.info(msg)
- response=jsonify({'code': 501, 'message': msg})
- response.status_code = 501
- return response
- now=time.time()
- expried_time=int(now)+150
- flag=gewe_chat.wxchat.acquire_login_lock(token_id,150)
- if not flag:
- msg=f'手机号{tel}, wx_token{token_id} 登录进行中,稍后再试'
- logger.info(msg)
- response=jsonify({'code': 501, 'message': msg})
- response.status_code = 501
- return response
-
- app_id=loginfo.get('appId','')
- qr_code = gewe_chat.wxchat.get_login_qr_code(token_id, app_id,region_id)
-
- if not qr_code:
- msg=f"获取二维码失败,qr_code: {qr_code}"
- gewe_chat.wxchat.release_login_lock(token_id)
- logger.info(msg)
- response=jsonify({'code': 501, 'message': msg})
- response.status_code = 501
- return response
-
- uuid = qr_code.get('uuid',None)
- if not uuid:
- msg=f"uuid获取二维码失败,uuid: {uuid}"
- gewe_chat.wxchat.release_login_lock(token_id)
- logger.info(msg)
- response=jsonify({'code': 501, 'message': msg})
- response.status_code = 501
- return response
-
-
-
- app_id = app_id or qr_code.get('appId')
-
- base64_string = qr_code.get('qrImgBase64',None)
- gewe_chat.wxchat.qrCallback(uuid,base64_string)
- hash_key = f"__AI_OPS_WX__:LOGININFO:{tel}"
- thread = threading.Thread(target=waitting_login_result, args=(gewe_chat.wxchat,token_id, app_id,region_id, agent_token_id,hash_key, uuid,now))
- thread.daemon = True
- thread.start()
-
- data={
- "tokenId": token_id,
- "tel": tel,
- "base64Img": base64_string,
- "expiredTime": expried_time,
- }
- return jsonify(data)
-
-
-
-
- def waitting_login_result(wxchat:gewe_chat.GeWeChatCom, token_id, app_id,region_id, agent_token_id,hash_key, uuid,start_time):
- agent_tel=hash_key.split(":")[-1]
- try:
- while True:
- now = time.time()
- if now - start_time > 150:
- logger.info(f'{token_id} 使用 {app_id} 扫二维码登录超时')
- break
-
- logger.info(f"{token_id} 使用 {app_id},等待扫码登录,二维码有效时间 {150 - int(now - start_time)} 秒")
- captch_code = wxchat.get_login_wx_captch_code_from_cache(token_id)
- captch_code= captch_code if captch_code else ''
- logger.info(f"{token_id} 使用 {app_id} 的验证码 {captch_code}")
- ret,msg,res = wxchat.check_login(token_id, app_id, uuid,captch_code)
-
- if ret == 200:
- flag = res.get('status')
- if flag == 2:
- logger.info(f"登录成功: {res}")
- head_img_url=res.get('headImgUrl','')
- login_info = res.get('loginInfo', {})
-
- wxid=login_info.get('wxid',agent_tel)
-
- cache_login_info=wxchat.get_login_info_from_cache(agent_tel)
- cache_wxid=cache_login_info.get('wxid','')
- if not cache_login_info and cache_wxid!=wxid:
- logger.warning(f"agent_tel {agent_tel} , wxid {wxid} 与 cache_wxid {cache_wxid} 不匹配,登录失败")
- wxchat.logout(token_id,app_id)
- # k_message=utils.login_result_message(token_id,agent_tel,region_id,agent_token_id,'')
- # kafka_helper.kafka_client.produce_message(k_message)
- break
-
-
- login_info.update({'appId': app_id, 'uuid': uuid, 'tokenId': token_id,'status': 1,'headImgUrl':head_img_url,'regionId':region_id})
- cache_login_info=redis_helper.redis_helper.get_hash(hash_key)
-
- if 'appId' not in cache_login_info:
- login_info.update({"create_at":int(time.time()),"modify_at":int(time.time())})
- # 默认配置
- config=Models.AgentConfig.model_validate({
- "chatroomIdWhiteList": [],
- "agentTokenId": agent_token_id,
- "agentEnabled": False,
- "addContactsFromChatroomIdWhiteList": [],
- "chatWaitingMsgEnabled": True
- })
- else:
- login_info.update({"modify_at":int(time.time())})
- # 已有配置
- config_cache=wxchat.get_wxchat_config_from_cache(wxid)
- config=Models.AgentConfig.model_validate(config_cache)
-
- cleaned_login_info = {k: (v if v is not None else '') for k, v in login_info.items()}
- #wxid=cleaned_login_info.get('wxid',agent_tel)
- # 保存配置信息
- config_dict=config.model_dump()
- wxchat.save_wxchat_config(wxid,config_dict)
-
- # 保存登录信息
- redis_helper.redis_helper.set_hash(hash_key, cleaned_login_info)
- wxchat.release_login_lock(token_id)
- # 登录结果推送到kafka
- k_message=utils.login_result_message(token_id,agent_tel,region_id,agent_token_id,wxid)
- kafka_helper.kafka_client.produce_message(k_message)
- break
- else:
- logger.info(f"登录检查中: {ret}-{msg}-{res}")
-
- time.sleep(5)
- finally:
- wxchat.release_login_lock(token_id)
|