-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
257 lines (225 loc) · 10.9 KB
/
server.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
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import sys
import json
import requests
import jwt
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from order import Order
from customer import Customer
from utils.mongoutils import initMongo
from plugintype import PluginType
from urllib import parse
from os import getenv
from dotenv import load_dotenv
from orderstatus import OrderStatus
load_dotenv()
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
version = '0.3.0'
# Reads the POST data from the HTTP header
def extract_POST_Body(self):
try:
postBodyLength = int(self.headers['content-length'])
postBodyString = self.rfile.read(postBodyLength)
postBodyDict = json.loads(postBodyString)
return postBodyDict
except:
print("There was an error parsing POST body")
return {}
# handle post requests
def do_POST(self):
status = 400 # HTTPS: Bad request
postData = self.extract_POST_Body() # store POST data into a dictionary
path = self.path
client = initMongo()
db = client['wego-db']
responseBody = {
'status': 'failed',
'message': 'Bad request'
}
customer = self.fetch_customer_from_token(db)
if '/order' in path:
status = 401 # HTTPS: Unauthenticated
responseBody["message"] = "No user authenticated"
if customer is not None:
postData["customerId"] = customer.id
try:
order = Order(postData)
except:
order = None
status = 400
responseBody["message"] = "Invalid order data."
if order is not None:
status = 403 # Forbitten to change
responseBody["message"] = "Order cannot be added since the specified plugin is unavailable."
plugin_data = db.Plugin.find_one({"name": order.plugin.name, "available": True})
if plugin_data is not None:
vType = plugin_data["vType"]
dispatch_request_data = {
"orderId": order.id,
"orderDestination": order.orderDestination,
"vehicleType": vType
}
dispatch_response = requests.post("https://supply.team22.sweispring21.tk/api/v1/supply/dispatch", json=dispatch_request_data, timeout=10)
dispatch_response_body = json.loads(dispatch_response.text)
if dispatch_response.status_code == 201:
data = {
"_id": order.id,
"customerId": order.customerId,
"plugin": order.plugin.name,
"timeStamp": order.timeStamp,
"paymentType": order.paymentType,
"orderDestination": order.orderDestination,
"items": order.items
}
db.Order.insert_one(data)
status = 201
dispatch_status = dispatch_response_body["dispatchStatus"]
if dispatch_status == "processing":
order_status = OrderStatus.PROCESSING
elif dispatch_status == "in progress":
order_status = OrderStatus.SHIPPED
elif dispatch_status == 'complete':
order_status == OrderStatus.DELIVERED
else:
order_status = OrderStatus.ERROR
responseBody = {
'status': 'success',
'message': 'successfully created order',
'orderId': order.id,
'orderStatus': order_status.name,
'vehicleId': dispatch_response_body["vehicleId"]
}
elif dispatch_response.status_code == 409:
# if user resubmitting order
status = 409
responseBody["message"] = "Order has already been submitted."
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.end_headers()
responseString = json.dumps(responseBody).encode('utf-8')
self.wfile.write(responseString)
client.close()
def do_GET(self):
path = self.path
status = 400
client = initMongo()
db = client['wego-db']
responseBody = {
'status': 'failed',
'message': 'request not found'
}
# Parse values after path and get it as dictionary
parameters = dict(parse.parse_qsl(parse.urlsplit(path).query))
customer = self.fetch_customer_from_token(db)
if '/orders' in path:
status = 401 # Unauthorized, not known to user
responseBody["message"] = "No user authenticated."
if customer is not None:
single_order_id = parameters.get("orderId", None)
if single_order_id is not None:
orders_data = list(db.Order.find({ "customerId": customer.id, "_id": single_order_id }))
else:
orders_data = list(db.Order.find({ "customerId": customer.id }))
if len(orders_data) != 0:
orders = list(map(lambda x: Order(x), orders_data))
url_order_ids = ""
for order in orders:
if url_order_ids != "":
url_order_ids += "&"
url_order_ids += f"orderId={order.id}"
order_dispatch_response = requests.get(f"https://supply.team22.sweispring21.tk/api/v1/supply/status?{url_order_ids}", timeout=10)
if order_dispatch_response.status_code == 200:
dispatches_data = json.loads(order_dispatch_response.text).get("dispatches")
orders_array = []
for order in orders:
dispatch_data = next(filter(lambda x: x.get("orderId") == order.id, dispatches_data), None)
if (dispatch_data == None):
dispatch_data = {}
dispatch_status = dispatch_data.get("dispatchStatus")
if dispatch_status == "processing":
order_status = OrderStatus.PROCESSING
elif dispatch_status == "in progress":
order_status = OrderStatus.SHIPPED
elif dispatch_status == "complete":
order_status = OrderStatus.DELIVERED
else:
order_status = OrderStatus.ERROR
orders_array.append({
"orderId": order.id,
"orderStatus": order_status.name,
"plugin": order.plugin.name,
"paymentType": order.paymentType,
"timeStamp": order.timeStamp.isoformat(),
"items": order.items,
"orderDestination": order.orderDestination,
"vehicleLocation": dispatch_data.get("vehicleLocation", ""),
"destinationCoordinate": dispatch_data.get("destinationCoordinate", ""),
"geometry": dispatch_data.get("geometry", ""),
"eta": dispatch_data.get("eta", ""),
"dock": dispatch_data.get("dock", "")
})
status = 200
responseBody["status"] = "success"
responseBody["message"] = "Successfully got orders"
responseBody["orders"] = orders_array
else:
status = 400
responseBody["message"] = "There was an error getting order statuses."
else:
status = 200 # No orders found
responseBody["message"] = "No orders found."
responseBody["orders"] = orders_data
elif '/plugins':
# Returns plugins with availability
plugin_name = parameters.get("name", None)
if plugin_name is not None:
if plugin_name == "all":
plugins = list(db.Plugin.find({}))
plugins_array = []
for plugin in plugins:
items = list(db.Item.find({ "pluginId": plugin["_id"] }))
plugin["items"] = items
plugins_array.append(plugin)
status = 200
responseBody = {
'status': 'successful',
'plugins': plugins_array
}
else:
plugin = db.Plugin.find_one({ "name": plugin_name })
if plugin is None:
plugin = {}
else:
items = list(db.Item.find({ "pluginId": plugin["_id"] }))
plugin["items"] = items
status = 200
responseBody = {
'status': 'successful',
'plugin': plugin
}
self.send_response(status)
self.send_header('Content-type', 'application/json')
self.end_headers()
responseString = json.dumps(responseBody).encode('utf-8')
self.wfile.write(responseString)
client.close()
def fetch_customer_from_token(self, db):
try:
tokenStr = self.headers["Cookie"]
if tokenStr is not None:
token = tokenStr.split('token=')[1].split(";")[0]
if token != "":
token_secret = getenv("TOKEN_SECRET")
token_decoded = jwt.decode(token, token_secret, algorithms="HS256")
user_data = db.Customer.find_one({ "_id": token_decoded["user_id"]})
return Customer(user_data)
except:
pass
return None
def main():
port = 4001
server = HTTPServer(('', port), SimpleHTTPRequestHandler)
print('Server is starting... Use <Ctrl+C> to cancel. Running on Port 8080')
server.serve_forever()
if __name__ == "__main__":
main()