-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustomerServer.py
More file actions
240 lines (190 loc) · 9.58 KB
/
Copy pathcustomerServer.py
File metadata and controls
240 lines (190 loc) · 9.58 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import json
import requests
import multiprocessing
import time
import pickle
import subprocess
from flask import Flask, jsonify , request
from customerAgent import customerAgent
class WebHookHandler:
def __init__(self, app , mainServer_UserManagerPipe=None):
self.app = app
self.mainServer_UserManagerPipe = mainServer_UserManagerPipe
self.app.add_url_rule('/requestSessionCreation', 'requestSessionCreation', self.createSession, methods=['POST'])
self.app.add_url_rule('/initializeSession', 'initializeSession', self.initialize_session_callback, methods=['POST'])
self.app.add_url_rule('/handleSessionRequests', 'handleSessionRequests', self.handle_session_requests_callback, methods=['PUT'])
self.app.add_url_rule('/serverRunning', 'serverRunning', self.server_running_callback, methods=['GET'])
self.app.add_url_rule('/sessionSTATUS', 'sessionSTATUS', self.session_status_callback, methods=['GET'])
self.app.add_url_rule('/updateSessionStatus', 'updateSessionStatus', self.update_session_status_callback, methods=['PUT'])
def handle_session_creation_request(self , data):
if data["EMAIL"] not in session_status.keys():
session_creation_requests[data['EMAIL']] = data["DATA"]
session_status[data['EMAIL']] = "PENDING"
# print()
# print(session_creation_requests.keys())
# print()
return jsonify({'message': 'Request Submitted'}), 200
else:
return jsonify({'message': 'Session Already Running'}), 403
# @app.route('/requestSessionCreation', methods=['POST'])
def createSession(self):
f = open("customerServerLog.txt" , "a")
if request.method == 'POST':
f.write("Session Creation Called !!!")
print("Session Creation Called !!!")
# data = json.dumps(request.get_json())
content_type = request.headers['Content-Type']
data = None
if(content_type == 'application/json'):
print("JSON Data")
data = request.get_json()
elif(content_type == 'application/bytes'):
data=request.get_data()
data = pickle.loads(data)
jsMsg = json.dumps({"EMAIL" : data['EMAIL'] , "PASSWORD" : data['PASSWORD'] , "TYPE" : data['TYPE']})
global ipAddress
print("Checking If Node Exists")
requestURL = f"http://127.0.0.1:5555/check_node?message={jsMsg}"
response = requests.get(requestURL)
if response.status_code == 200:
if(response.json()['message'] == "Registered"):
return self.handle_session_creation_request(data)
else:
return jsonify({'message': 'Invalid Email or Password'}), 200
else:
return jsonify({'message': 'Session Creation Failed'}), 404
pass
else:
return jsonify({'message': 'Method not allowed'}), 405
def initialize_customer_session(self , customerEmail):
print(f"Session Inititalized for the Customer : {customerEmail}")
global customerAgentsList
sessionSupervisorPipe , userManagerPipe = multiprocessing.Pipe()
self.mainServer_UserManagerPipe.send({"TYPE" : "NEW_SESSION" , "EMAIL" : customerEmail , "SUPERVISOR_PIPE" : sessionSupervisorPipe})
currentSessionCustomerAgent = customerAgent(userManagerPipe)
customerAgentsList[customerEmail] = currentSessionCustomerAgent
messageForCustomerAgent = {"EMAIL" : customerEmail , "DATA" : session_creation_requests[customerEmail] , "DATETIME" : time.strftime("%Y-%m-%d : %H:%M:%S")}
currentSessionCustomerAgent.initializeSession(messageForCustomerAgent)
return True
# @app.route('/initializeSession', methods=['POST'])
def initialize_session_callback(self):
# f = open("customerServerLog.txt" , "w")
print("Initiate Session Called !!!")
# f.write("Initiate Session Called !!!")
if request.method == 'POST':
global session_creation_requests
global session_status
data = request.get_json()
#print(data)
email = data['EMAIL']
print(email)
#print(email)
if email in session_creation_requests.keys():
if(self.initialize_customer_session(email) == True):
print(len(customerAgentsList))
# f.write(len(customerAgentsList))
del session_creation_requests[email]
session_status[email] = "RUNNING"
print(session_status[email])
# f.write(session_status[email])
print("Session Succefully Created and Status Updated !!!")
# f.write("Session Succefully Created and Status Updated !!!")
return jsonify({'message': 'Created'}), 200
else:
print("Session Creation Failed")
return jsonify({'message': 'Failed'}), 404
else:
print("No Session Pending for the customer")
return jsonify({'message': 'NO_PENDING_SESSION'}), 404
else:
return jsonify({'message': 'Method not allowed'}), 405
# @app.route('/handleSessionRequests', methods=['PUT'])
def handle_session_requests_callback(self):
if request.method == 'PUT':
data = request.get_json()
email = data['EMAIL']
agent = customerAgentsList[email]
agent.handleSessionRequests(data)
return jsonify({'message': 'Request Handled'}), 200
else:
return jsonify({'message': 'Method not allowed'}), 405
# @app.route('/serverRunning' , methods=['GET'])
def server_running_callback(self):
print("Server Running Called !!!")
if request.method == 'GET':
return jsonify({'message': 'Running'}), 200
else:
return jsonify({'message': 'Method not allowed'}), 405
# @app.route('/sessionSTATUS', methods=['GET'])
def session_status_callback(self):
print("Session Status Called !!!")
if request.method == 'GET':
message = request.args.get('message')
data = json.loads(message)
if data["TYPE"] == "CUSTOMERS":
email = data["EMAIL"]
global session_status
if email in session_status.keys():
return jsonify({'message': session_status[email]}), 200
else:
return jsonify({'message': 'IDLE'}), 200
else:
return jsonify({'message': 'Not a Valid Request'}), 400
else:
return jsonify({'message': 'Method not allowed'}), 405
# @app.route('/updateSessionStatus', methods=['PUT'])
def update_session_status_callback(self):
if request.method == 'PUT':
data = request.get_json()
email = data['EMAIL']
status = data['STATUS']
global session_status
session_status[email] = status
if session_status[email] == "IDLE":
del session_status[email]
return jsonify({'message': 'Status Updated'}), 200
else:
return jsonify({'message': 'Method not allowed'}), 405
class CustomerServer():
def __init__(self):
self.userManager = None
self.mainServer_UserManagerPipe = None
# self.socketio = socketio
def startServer(self , mainServer_UserManagerPipe = None):
app = Flask(__name__)
# app.config['SECRET_KEY'] = 'secret!'
# self.socketio = SocketIO(app)
self.mainServer_UserManagerPipe = mainServer_UserManagerPipe
print("User Manager Pipe : " , self.mainServer_UserManagerPipe)
global ipAddress
ipAddress = "0.0.0.0"
global session_creation_requests
global session_status
global customerAgentsList
session_creation_requests = {}
customerAgentsList = {}
session_status = {}
# serverUserManager = userManager()
# self.mainServer_UserManagerPipe , userManagerPipe = multiprocessing.Pipe()
# userManager_Process = multiprocessing.Process(target=serverUserManager.Start , args=(userManagerPipe,))
# userManager_Process.start()
webhook_handler = WebHookHandler(app , self.mainServer_UserManagerPipe)
print("Customer Server Starting !!!")
Flask.run(app, host=ipAddress, port=5500 , debug=False)
# ipAddressAndPort = '0.0.0.0:5500'
# command = [
# 'gunicorn',
# '--bind', ipAddressAndPort,
# '--workers', str(1),
# 'credentialServer:app', # Replace 'app' with your Flask application module name
# '--error-logfile' , 'customerServerLog.log',
# '--log-level' , 'debug'
# ]
# subprocess.run(command)
def userMessageHandler(self , sid , message):
self.socketio.emit('response', 'Message Received', room=sid)
self.mainServer_UserManagerPipe.send({"TYPE" : "USER_MESSAGE" , "MESSAGE" : message , "USER_ID" : sid})
print("User Message Send to User Manager !!!")
if __name__ == "__main__":
mainServer = CustomerServer()
mainServer.startServer()