-
Notifications
You must be signed in to change notification settings - Fork 0
/
nanobot.py
186 lines (150 loc) · 5.61 KB
/
nanobot.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
import time
import threading
import http.client
import json
from urllib.parse import urlsplit
import sublime
from .nanobot_state import NanoBotState
class NanoBot:
@staticmethod
def stop():
NanoBotState.instance().stop()
@staticmethod
def perform(config, params, callback):
cartridge = NanoBot.cartridge(config, params['cartridge'])
NanoBot.stop()
if config['NANO_BOTS_STREAM']:
threading.Thread(
target=NanoBot.stream_request,
args=(config, params, cartridge, callback)).start()
else:
threading.Thread(
target=NanoBot.non_stream_request,
args=(config, params, cartridge, callback)).start()
@staticmethod
def cartridges(config):
response = NanoBot.send_request(
config, None, 'GET', '/cartridges',
None, None, 1)
return response
@staticmethod
def cartridge(config, cartridge_id):
return NanoBot.send_request(
config, {'id': cartridge_id},
'POST', '/cartridges/source')
@staticmethod
def non_stream_request(config, params, cartridge, callback):
def thread_callback(response):
if NanoBotState.instance().state['status'] != 'stopped':
NanoBotState.instance().update(
cartridge, {'status': 'finished', 'thread': None})
callback(response)
thread_event = threading.Event()
thread = threading.Thread(
target=NanoBot.send_request,
args=(config, params, 'POST', '/cartridges',
thread_callback, thread_event))
NanoBotState.instance().update(
cartridge,
{'status': 'pending', 'started_at': time.time(),
'thread': thread_event})
thread.start()
@staticmethod
def stream_request(config, params, cartridge, callback):
NanoBotState.instance().update(
cartridge,
{'status': 'pending', 'started_at': time.time(), 'thread': None})
response = NanoBot.send_request(
config, params, 'POST', '/cartridges/stream')
stream_id = response.get('id', '')
if not stream_id:
sublime.error_message('No Stream ID received.')
return
state = ''
while NanoBotState.instance().state['status'] != 'stopped':
response = NanoBot.send_request(
config, None, 'GET', '/cartridges/stream/' + stream_id)
output = response.get('output')
if state != output:
response['fragment'] = output[len(state):]
state = output
callback(response)
if response.get('state') == 'finished':
NanoBotState.instance().update(
cartridge, {'status': 'finished', 'thread': None})
break
response['fragment'] = ''
callback(response)
@staticmethod
def send_request(
config, params, method, path,
thread_callback=None, thread_event=None, timeout=None,
retries=0
):
try:
conn = NanoBot.create_connection(
config['NANO_BOTS_API_ADDRESS'], timeout)
headers = NanoBot.create_headers(config)
json_str = NanoBot.create_json(params)
conn.request(method, path, json_str, headers)
response = NanoBot.get_response(conn)
conn.close()
if thread_callback is not None and thread_event is not None:
if not thread_event.is_set():
thread_callback(response)
return response
except Exception as error:
if retries < 2:
return NanoBot.send_request(
config, params, method, path,
thread_callback, thread_event,
timeout, retries+1)
sublime.error_message(
'Error: {} - {}'.format(
config['NANO_BOTS_API_ADDRESS'], str(error)))
return {}
@staticmethod
def get_host_port(api_address):
parsed_url = urlsplit(api_address)
hostname = parsed_url.hostname
port = parsed_url.port or 80 # Default port if not specified
return hostname, port
@staticmethod
def get_url(api_address, path):
return api_address + path
@staticmethod
def create_connection(api_address, timeout):
parsed_url = urlsplit(api_address)
hostname = parsed_url.hostname
port = parsed_url.port
scheme = parsed_url.scheme
if scheme == "https":
if not port:
port = 443
return http.client.HTTPSConnection(hostname, port, timeout=timeout)
if not port:
port = 80
return http.client.HTTPConnection(hostname, port, timeout=timeout)
@staticmethod
def create_headers(config):
return {
'Content-type': 'application/json',
'NANO_BOTS_END_USER':
'sublime-text-' + config['NANO_BOTS_END_USER']}
@staticmethod
def create_json(params):
return json.dumps(params)
@staticmethod
def get_response(conn):
response = conn.getresponse()
output = {}
if response.status == 200:
try:
output = json.loads(response.read().decode())
except json.JSONDecodeError:
output = {'output': 'Invalid JSON response.'}
else:
output = {
'output': 'Request failed with status code: {}'.format(
response.status)}
return output