forked from mi8882255/3dprinteros-client
/
http_client.py
216 lines (190 loc) · 8.76 KB
/
http_client.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
#Copyright (c) 2015 3D Control Systems LTD
#3DPrinterOS client is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#3DPrinterOS client is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#You should have received a copy of the GNU Affero General Public License
#along with 3DPrinterOS client. If not, see <http://www.gnu.org/licenses/>.
# Author: Oleg Panasevych <panasevychol@gmail.com>, Vladimir Avdeev <another.vic@yandex.ru>
import re
import sys
import time
import json
import uuid
import httplib
import logging
import urllib2
from subprocess import Popen, PIPE
import config
import version
from checker_waiter import CheckerWaiter
CONNECTION_TIMEOUT = 6
# machine id is mac address, but on RPi we use machine serial
def get_machine_id():
if sys.platform.startswith('linux'):
call = Popen(['cat', '/proc/cpuinfo'], stdout=PIPE, stderr=PIPE)
stdout, stderr = call.communicate()
stdout = stdout.replace('\t', '').split('\n')
for item in stdout:
if 'Serial: ' in item:
return item.replace('Serial: ', '')
return hex(uuid.getnode())
class HTTPClient:
URL = config.get_settings()['URL']
HTTPS_MODE = config.get_settings()['HTTPS']
MAX_HTTP_FAILS = 5
MACHINE_ID = get_machine_id()
streamer_prefix = "/streamerapi"
user_login_path = streamer_prefix + "/user_login"
printer_login_path = streamer_prefix + "/printer_login"
command_path = streamer_prefix + "/command"
camera_path = streamer_prefix + "/camera" #json['image': base64_image ]
cloudsync_path = "/autoupload"
token_send_logs_path = streamer_prefix + "/sendLogs"
get_last_version_path = '/a/lastclientver/get'
domain_path_re = re.compile("https?:\/\/(.+)(\/.*)")
def __init__(self, keep_connection_flag = False, parent_usb_info=None, debug = False):
self.logger = logging.getLogger('app.' +__name__)
self.parent_usb_info = parent_usb_info
if debug:
self.logger.setLevel('DEBUG')
else:
self.logger.setLevel('INFO')
self.keep_connection_flag = keep_connection_flag
self.parent_usb_info = parent_usb_info
if keep_connection_flag:
self.connection = self.connect()
else:
self.connection = None
self.fails = 0
def connect(self):
self.logger.debug("{ Connecting...")
try:
if self.HTTPS_MODE:
connection = httplib.HTTPSConnection(self.URL, port = 443, timeout = CONNECTION_TIMEOUT)
else:
connection = httplib.HTTPConnection(self.URL, port = 80, timeout = CONNECTION_TIMEOUT)
connection.connect()
except Exception as e:
config.create_error_report(5, "Error during HTTP connection: " + str(e),
self.parent_usb_info, self.logger, is_blocking=False)
self.logger.debug("...failed }")
self.logger.warning("Warning: connection to %s failed." % self.URL)
else:
self.logger.debug("...success }")
return connection
def load_json(self, jdata):
try:
data = json.loads(jdata)
except ValueError:
config.create_error_report(2, "Received data is not valid json: "
+ jdata, self.parent_usb_info, self.logger, is_blocking=False)
else:
if data and type(data) == dict:
return data
else:
config.create_error_report(3, "Error parsing http message, data should be not empty dictionary: " +
str(data), self.parent_usb_info, self.logger, is_blocking=False)
def request(self, method, connection, path, payload, headers=None):
self.logger.debug("{ Requesting...")
if headers is None:
headers = {"Content-Type": "application/json", "Content-Length": str(len(payload))}
if self.keep_connection_flag:
headers["Connection"] = "keep-alive"
try:
connection.request(method, path, payload, headers)
resp = connection.getresponse()
except Exception as e:
config.create_error_report(6,"Error during HTTP request:" + str(e), self.parent_usb_info, self.logger, is_blocking=False)
else:
#self.logger.debug("Request status: %s %s" % (resp.status, resp.reason))
try:
received = resp.read()
except httplib.error as e:
config.create_error_report(7, "Error reading response: " + str(e), self.parent_usb_info, self.logger, is_blocking=False)
else:
if resp.status == httplib.OK and resp.reason == "OK":
self.logger.debug("...success }")
return received
else:
config.create_error_report(8, "Error: server responded with non 200 OK\nFull response: %s" %
received, self.parent_usb_info, self.logger, is_blocking=False)
self.logger.debug("...failed }")
self.logger.warning("Warning: HTTP request failed!")
def pack_and_send(self, target, *payloads, **kwargs_payloads):
path, packed_message = self.pack(target, *payloads, **kwargs_payloads)
return self.send(path, packed_message)
def send(self, path, data):
while True:
if not self.connection:
self.connection = self.connect()
if self.connection:
answer = self.request("POST", self.connection, path, data)
if not self.keep_connection_flag:
self.connection.close()
self.connection = None
if answer:
self.fails = 0
return self.load_json(answer)
self.fails += 1
time.sleep(1)
if self.fails > self.MAX_HTTP_FAILS:
self.fails = 0
if self.connection:
self.connection.close()
self.connection = None
config.create_error_report(9, 'HTTP error: max request retry.', None, self.logger, is_blocking=False)
break
def pack(self, target, *args, **kwargs):
if target == 'user_login':
data = { 'login': {'user': args[0], 'password': args[1]}, "platform": sys.platform,
'host_mac': self.MACHINE_ID, "version": version.version }
path = self.user_login_path
elif target == 'printer_login':
data = { 'user_token': args[0], 'printer': args[1], "version": version.version,
"data_time": time.ctime(), "camera": config.get_app().camera_controller.get_current_camera_name()}
path = self.printer_login_path
elif target == 'command':
data = { 'printer_token': args[0], 'report': args[1], 'command_ack': args[2] }
if not data['command_ack']:
data.pop('command_ack')
path = self.command_path
elif target == 'camera':
data = { 'user_token': args[0], 'camera_number': args[1], 'camera_name': args[2],
'file_data': args[3], 'host_mac': self.MACHINE_ID }
path = self.camera_path
elif target == 'cloudsync':
data = { 'user_token': args[0], 'file_data': args[1] }
path = self.cloudsync_path
else:
config.create_error_report(4, 'No such target for packaging: ' + target, None,
self.logger, is_blocking=False)
data, path = None, None
for key, value in kwargs.items():
data[key] = value
return path, json.dumps(data)
def close(self):
if self.connection:
self.connection.close()
class NetworkConnectionChecker(CheckerWaiter):
NAME_FOR_LOGGING = 'network connection check'
def __init__(self, app):
CheckerWaiter.__init__(self, app, self.check_connection)
def check_connection(self):
if HTTPClient.HTTPS_MODE:
prefix = 'https://'
else:
prefix = 'http://'
# urllib2 used because other libs don't give us expected result
# in case when internet connection appears while waiting
try:
urllib2.urlopen(prefix + HTTPClient.URL, timeout=CONNECTION_TIMEOUT)
return True
except:
time.sleep(0.1)
if __name__ == '__main__':
http_client = HTTPClient()