-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlanying_connector.py
184 lines (167 loc) · 6.96 KB
/
lanying_connector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import os
from flask import Flask, request, render_template
import requests
import logging
import json
from concurrent.futures import ThreadPoolExecutor
import importlib
import sys
import lanying_config
import copy
from redis import StrictRedis, ConnectionPool
import time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
executor = ThreadPoolExecutor(8)
sys.path.append("services")
lanying_config.init()
app = Flask(__name__)
if os.environ.get("FLASK_DEBUG"):
app.debug = True
redisServer = os.getenv('LANYING_CONNECTOR_REDIS_SERVER')
redisPool = None
if redisServer:
redisPool = ConnectionPool.from_url(redisServer)
accessToken = os.getenv('LANYING_CONNECTOR_ACCESS_TOKEN')
@app.route("/", methods=["GET"])
def index():
service = lanying_config.get_lanying_connector_service('')
return render_template("index.html", msgReceivedCnt=getMsgReceivedCnt(), msgSentCnt=getMsgSentCnt(), service=service)
@app.route("/messages", methods=["POST"])
def messages():
addMsgReceivedCnt(1)
text = request.get_data(as_text=True)
data = json.loads(text)
logging.debug(data)
fromUserId = data['from']['uid']
toUserId = data['to']['uid']
type = data['type']
ctype = data['ctype']
appId = data['appId']
now = time.time()
config = lanying_config.get_lanying_connector(appId)
productId = 0
if config and 'product_id' in config:
productId = config['product_id']
ExpireTime = lanying_config.get_lanying_connector_expire_time(appId)
if productId == 0 and (ExpireTime == None or (ExpireTime > 0 and now > ExpireTime)):
logging.debug(f"service is expired: appId={appId}")
resp = app.make_response('service is expired')
return resp
callbackSignature = lanying_config.get_lanying_callback_signature(appId)
if callbackSignature and len(callbackSignature) > 0:
headSignature = request.headers.get('signature')
if callbackSignature != headSignature:
logging.info(f'callback signature not match: appId={appId}')
resp = app.make_response('callback signature not match')
return resp
myUserId = lanying_config.get_lanying_user_id(appId)
logging.debug(f'lanying_user_id:{myUserId}')
if myUserId != None and toUserId == myUserId and fromUserId != myUserId and type == 'CHAT' and ctype == 'TEXT':
executor.submit(queryAndSendMessage, data)
resp = app.make_response('')
return resp
@app.route("/config", methods=["POST"])
def saveConfig():
headerToken = request.headers.get('access-token', "")
if accessToken and accessToken == headerToken:
text = request.get_data(as_text=True)
data = json.loads(text)
appId = data['app_id']
key = data.get('key', 'lanying_connector')
value = data['value']
if key.startswith('lanying_connector'):
lanying_config.save_config(appId, key, value)
resp = app.make_response('success')
return resp
else:
resp = app.make_response('not_allowed')
return resp
resp = app.make_response('fail')
return resp
@app.route("/config", methods=["GET"])
def getConfig():
showConfigAppId = os.getenv('LANYING_CONNECTOR_SHOW_CONFIG_APP_ID')
if showConfigAppId:
config = lanying_config.get_lanying_connector(showConfigAppId)
resp = app.make_response(json.dumps(config['preset']['messages'], ensure_ascii=False))
return resp
resp = app.make_response('')
return resp
def queryAndSendMessage(data):
appId = data['appId']
fromUserId = data['from']['uid']
toUserId = data['to']['uid']
content = data['content']
try:
service = lanying_config.get_lanying_connector_service(appId)
if service:
service_module = importlib.import_module(f"{service}_service")
config = lanying_config.get_lanying_connector(appId)
if config:
newConfig = copy.deepcopy(config)
newConfig['from_user_id'] = fromUserId
newConfig['to_user_id'] = toUserId
newConfig['ext'] = data['ext']
newConfig['app_id'] = data['appId']
newConfig['msg_id'] = data['msgId']
responseText = service_module.handle_chat_message(content, newConfig)
logging.debug(f"responseText:{responseText}")
if len(responseText) > 0:
sendMessage(appId, toUserId, fromUserId, responseText)
addMsgSentCnt(1)
except Exception as e:
logging.exception(e)
message_404 = lanying_config.get_message_404(appId)
sendMessage(appId, toUserId, fromUserId, message_404)
addMsgSentCnt(1)
def sendMessage(appId, fromUserId, toUserId, content):
adminToken = lanying_config.get_lanying_admin_token(appId)
apiEndpoint = lanying_config.get_lanying_api_endpoint(appId)
message_antispam = lanying_config.get_message_antispam(appId)
if adminToken:
sendResponse = requests.post(apiEndpoint + '/message/send',
headers={'app_id': appId, 'access-token': adminToken},
json={'type':1, 'from_user_id':fromUserId,'targets':[toUserId],'content_type':0, 'content': content, 'config': json.dumps({'antispam_prompt':message_antispam}, ensure_ascii=False)})
logging.debug(sendResponse)
def sendReadAck(appId, fromUserId, toUserId, relatedMid):
adminToken = lanying_config.get_lanying_admin_token(appId)
apiEndpoint = lanying_config.get_lanying_api_endpoint(appId)
message_antispam = lanying_config.get_message_antispam(appId)
if adminToken:
sendResponse = requests.post(apiEndpoint + '/message/send',
headers={'app_id': appId, 'access-token': adminToken},
json={'type':1, 'from_user_id':fromUserId,'targets':[toUserId],'content_type':9, 'content': '', 'config': json.dumps({'antispam_prompt':message_antispam}, ensure_ascii=False),'related_mid':relatedMid})
logging.debug(sendResponse)
def getRedisConnection():
conn = None
if redisPool:
conn = StrictRedis(connection_pool=redisPool)
if not conn:
logging.warning(f"getRedisConnection: fail to get connection")
return conn
def addMsgSentCnt(num):
redis = getRedisConnection()
if redis:
redis.incrby(msgSentCntKey(), num)
def addMsgReceivedCnt(num):
redis = getRedisConnection()
if redis:
redis.incrby(msgReceivedCntKey(), num)
def getMsgSentCnt():
redis = getRedisConnection()
if redis:
str = redis.get(msgSentCntKey())
if str:
return int(str)
return 0
def getMsgReceivedCnt():
redis = getRedisConnection()
if redis:
str = redis.get(msgReceivedCntKey())
if str:
return int(str)
return 0
def msgSentCntKey():
return "lanying:connector:msg:sent:cnt"
def msgReceivedCntKey():
return "lanying:connector:msg:received:cnt"