This repository has been archived by the owner on Mar 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
importio.rb
255 lines (204 loc) · 5.24 KB
/
importio.rb
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
'''
import.io client library
Dependencies=> Ruby 1.9, http-cookie
@author=> import.io
'''
require "net/http"
require "uri"
require "thread"
require "http-cookie"
require "cgi"
require "json"
require "securerandom"
class Query
def initialize(callback, query)
@query = query
@jobsSpawned = 0
@jobsStarted = 0
@jobsCompleted = 0
@_finished = false
@_callback = callback
end
def _onMessage(data)
msgType = data["type"]
if msgType == "SPAWN"
@jobsSpawned+=1
elsif msgType == "INIT" or msgType == "START"
@jobsStarted+=1
elsif msgType == "STOP"
@jobsCompleted+=1
end
@_finished = (@jobsStarted == @jobsCompleted and @jobsSpawned + 1 == @jobsStarted and @jobsStarted > 0)
# if there is an error or the user is not authorised correctly then allow isFinished to return true by setting jobs to -1
if msgType == "ERROR" or msgType == "UNAUTH" or msgType == "CANCEL"
@_finished = True
end
@_callback.call(self, data)
end
def finished
return @_finished
end
end
class ImportIO
def initialize(userId=nil, apiKey=nil, host="https://query.import.io")
@host = host
@proxyHost = nil
@proxyPort = nil
@msgId = 1
@clientId = nil
@url = "#{host}/query/comet/"
@messagingChannel = "/messaging"
@queries = Hash.new
@userId = userId
@apiKey = apiKey
@cj = HTTP::CookieJar.new
@queue = Queue.new
@connected = false
end
def proxy(host,port)
@proxyHost = host
@proxyPort = port
end
def makeRequest(url, data)
uri = URI(url)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = data
http = Net::HTTP.new(uri.host, uri.port, @proxyHost, @proxyPort)
http.use_ssl = uri.scheme == "https"
return uri, http, request
end
def open(uri, http, request)
response = http.request(request)
cookies = response.get_fields("set-cookie")
if cookies != nil
cookies.each { |value|
@cj.parse(value, uri)
}
end
return response
end
def encode(dict)
dict.map{|k,v| "#{CGI.escape(k)}=#{CGI.escape(v)}"}.join("&")
end
def login(username, password, host="https://api.import.io")
data = encode({'username' => username, 'password'=> password})
uri, http, req = makeRequest("#{host}/auth/login", data )
r = open(uri, http, req)
if r.code != "200"
raise "Could not log in, code #{r.code}"
end
end
def request(channel, path="", data={}, throw=true)
# add in the common values
data["channel"] = channel
data["connectionType"] = "long-polling"
data["id"] = @msgId
@msgId += 1
if @clientId != nil
data["clientId"] = @clientId
end
url = "#{@url}#{path}"
if @apiKey != nil
q = encode({ "_user" => @userId, "_apikey" => @apiKey })
url = "#{url}?#{q}"
end
body = JSON.dump([data])
uri, http, request = makeRequest(url, body)
request.content_type = "application/json;charset=UTF-8"
request["Cookie"] = HTTP::Cookie.cookie_value(@cj.cookies(uri))
response = open(uri, http, request)
if response.code != "200"
raise "Connect failed, status #{response.code}"
end
response.body = JSON.parse(response.body)
for msg in response.body do
if msg.has_key?("successful") and msg["successful"] != true
msg = "Unsuccessful request=> %s", msg
if throw
raise msg
else
print msg
end
next
end
if msg["channel"] != @messagingChannel
next
end
@queue.push(msg["data"])
end
return response
end
def handshake
handshake = request("/meta/handshake", path="handshake", data={"version"=>"1.0","minimumVersion"=>"0.9","supportedConnectionTypes"=>["long-polling"],"advice"=>{"timeout"=>60000,"interval"=>0}})
@clientId = handshake.body[0]["clientId"]
end
def connect
if @connected
return
end
handshake
request("/meta/subscribe", "", {"subscription"=>@messagingChannel})
@connected = true
@threads = []
@threads << Thread.new(self) { |io|
io.poll
}
@threads << Thread.new(self) { |io|
io.pollQueue
}
end
def disconnect
request("/meta/disconnect");
@connected = false
end
def stop
@threads.each { |thread|
thread.terminate
}
end
def join
while @connected
if @queries.length == 0
stop
return
end
sleep 1
end
end
def pollQueue
while @connected
begin
processMessage @queue.pop
rescue => exception
puts exception.backtrace
end
end
end
def poll
while @connected
request("/meta/connect", "connect", {}, false)
end
end
def processMessage(data)
begin
reqId = data["requestId"]
query = @queries[reqId]
if query == nil
puts "No open query #{query}:"
puts JSON.pretty_generate(data)
return
end
query._onMessage(data)
if query.finished
@queries.delete(reqId)
end
rescue => exception
puts exception.backtrace
end
end
def query(query, callback)
query["requestId"] = SecureRandom.uuid
@queries[query["requestId"]] = Query::new(callback, query)
request("/service/query", "", { "data"=>query })
end
end