semantria_sdk 3.8.79 → 4.0.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: f94ace4447c0a66bf0ca837d811d8b3f561b75e6
4
- data.tar.gz: f8dde0dde185ba41e357bad8ad6668cbd8faa379
3
+ metadata.gz: 8448dbb7e3d86d056b581ab753e7cbaff125f5b9
4
+ data.tar.gz: 876e4e2441cbefce1f2a1645b693a7c628ea973f
5
5
  SHA512:
6
- metadata.gz: 0ae88c6812d0df02ceb4eaca45882246b17de7cda129de6ce4bb55d18073c6a0db6b68471e559acf1cfc84286d5660508ad44b2795ed36630294bdade21a397d
7
- data.tar.gz: f6591933889697d66ddc942d2dc943caf5f1c93d38e66f8c103495ab479eecba9de1c5b25c369eca303800003c41be83ca27cf2ad31711e3f54516f8f8af10f4
6
+ metadata.gz: 4e0c43d3ec66073d117302a84a048c335ef38a4ebfbc7b1181ee2b221d8e981bfeb95c498c15d13e81be9d24e8c5dac17b177ff5cafb5bfdc6e87bcf8e45a135
7
+ data.tar.gz: 5e1eafde0d0e91b9e984cd3af02e4c2db9e5ea05d0ffbf21a37dd2b5ee486cbb5dfd5c1e2d51d8bbb8b66d50e4f1b6decdcf84190bedc1d126054b1863393de8
data/lib/semantria.rb CHANGED
@@ -1,9 +1,9 @@
1
- # encoding: utf-8
2
-
3
- module Semantria
4
- VERSION = '3.5.76'
5
- end
6
-
7
- require_relative 'semantria/session'
8
- require_relative 'semantria/authrequest'
9
- require_relative 'semantria/jsonserializer'
1
+ # encoding: utf-8
2
+
3
+ module Semantria
4
+ VERSION = '4.1.84'
5
+ end
6
+
7
+ require_relative 'semantria/session'
8
+ require_relative 'semantria/authrequest'
9
+ require_relative 'semantria/jsonserializer'
@@ -1,167 +1,169 @@
1
- # encoding: utf-8
2
- require 'uri'
3
- require 'base64'
4
- require 'cgi'
5
- require 'digest/md5'
6
- require 'openssl'
7
- require 'digest/sha1'
8
- require 'net/http'
9
- require 'net/https'
10
-
11
- module Semantria
12
- OAUTH_VERSION = '1.0'
13
- OAUTH_KEY_PREFIX = "oauth_"
14
- OAUTH_CONSUMER_KEY = "oauth_consumer_key"
15
- OAUTH_VERSION_KEY = "oauth_version"
16
- OAUTH_SIGNATURE_METHOD_KEY = "oauth_signature_method"
17
- OAUTH_SIGNATURE_KEY = "oauth_signature"
18
- OAUTH_TIMESTAMP_KEY = "oauth_timestamp"
19
- OAUTH_NONCE_KEY = "oauth_nonce"
20
-
21
- class AuthRequest
22
- # Create a new instance
23
- def initialize(consumer_key, consumer_secret, application_name, use_compression = false)
24
- @consumer_key = consumer_key
25
- @consumer_secret = consumer_secret
26
- @application_name = application_name
27
- @use_compression = use_compression
28
- end
29
-
30
- def authWebRequest(method, url, post_data = nil)
31
- nonce = generateNonce()
32
- timestamp = generateTimestamp()
33
- query = generate_query(method, url, timestamp, nonce)
34
- auth_header = generate_auth_header(query, timestamp, nonce)
35
- headers = {'Authorization' => auth_header}
36
-
37
- headers['Content-type'] = 'application/x-www-form-urlencoded' if method == 'POST'
38
- headers['x-api-version'] = '3.8'
39
- headers['x-app-name'] = @application_name
40
-
41
- headers['Accept-Encoding'] = 'gzip' if @use_compression
42
-
43
- uri = URI.parse(query)
44
- conn = Net::HTTP.new(uri.host, 443)
45
- conn.use_ssl = true
46
- conn.verify_mode = OpenSSL::SSL::VERIFY_NONE
47
-
48
- path = uri.request_uri #'%s?%s' % [qpath, qquery]
49
- request = get_request(method, path, headers, post_data)
50
- response = conn.request(request)
51
-
52
- data = nil
53
- if response.header['Content-Encoding'].eql? 'gzip'
54
- sio = StringIO.new( response.body )
55
- gz = Zlib::GzipReader.new( sio )
56
- data = gz.read()
57
- else
58
- data = response.body
59
- end
60
-
61
- {status: response.code.to_i, reason: response.message, data: data}
62
- end
63
-
64
- private
65
- # create the http request object for a given http_method and path
66
- def get_request(method, path, headers, post_data = nil)
67
- request = nil
68
- case method
69
- when 'POST'
70
- request = Net::HTTP::Post.new(path, headers)
71
- when 'PUT'
72
- request = Net::HTTP::Put.new(path, headers)
73
- when 'GET'
74
- request = Net::HTTP::Get.new(path, headers)
75
- when 'DELETE'
76
- request = Net::HTTP::Delete.new(path, headers)
77
- else
78
- fail ArgumentError, "Don't know how to handle method: :#{method}"
79
- end
80
-
81
- unless post_data.nil?
82
- request.body = post_data
83
- request['Content-Length'] = request.body.length.to_s
84
- end
85
-
86
- request
87
- end
88
-
89
- def generate_query(method, url, timestamp, nonce)
90
- uri = URI.parse(url)
91
- np = get_normalized_parameters(timestamp, nonce)
92
-
93
- if uri.query
94
- uri.query = '%s&%s' % [uri.query, np]
95
- else
96
- uri.query = '%s' % np
97
- end
98
-
99
- uri.to_s
100
- end
101
-
102
- def generate_auth_header(query, timestamp, nonce)
103
- md5cs = get_md5_hash(@consumer_secret)
104
- esc_query = escape(query)
105
- hash = get_sha1(md5cs, esc_query)
106
- hash = escape(hash)
107
-
108
- items = Hash.new()
109
- items['OAuth realm'] = ''
110
- items[OAUTH_VERSION_KEY] = "%s" % OAUTH_VERSION
111
- items[OAUTH_TIMESTAMP_KEY] = "%s" % timestamp
112
- items[OAUTH_NONCE_KEY] = "%s" % nonce
113
- items[OAUTH_SIGNATURE_METHOD_KEY] = "HMAC-SHA1"
114
- items[OAUTH_CONSUMER_KEY] = "%s" % @consumer_key
115
- items[OAUTH_SIGNATURE_KEY] = "%s" % hash
116
-
117
- params = []
118
- items.keys.sort.each do |key|
119
- params.push('%s="%s"' % [key, items[key]])
120
- end
121
-
122
- params.join(',')
123
- end
124
-
125
- def get_normalized_parameters(timestamp, nonce)
126
- items = Hash.new()
127
- items[OAUTH_VERSION_KEY] = OAUTH_VERSION
128
- items[OAUTH_TIMESTAMP_KEY] = timestamp
129
- items[OAUTH_NONCE_KEY] = nonce
130
- items[OAUTH_SIGNATURE_METHOD_KEY] = "HMAC-SHA1"
131
- items[OAUTH_CONSUMER_KEY] = @consumer_key
132
-
133
- params = []
134
- for key in items.keys.sort
135
- params.push('%s=%s' % [key, items[key]])
136
- end
137
-
138
- np = params.join('&')
139
- # Encode signature parameters per Oauth Core 1.0 protocol
140
- # Spaces must be encoded with "%20" instead of "+"
141
- return np.gsub('+', '%20').gsub('%7E', '~')
142
- end
143
-
144
- def get_md5_hash(str)
145
- Digest::MD5.hexdigest(str)
146
- end
147
-
148
- def get_sha1(md5cs, query)
149
- digest = OpenSSL::Digest.new('sha1')
150
- # our composite signing key now has the token secret after the ampersand
151
- sha1res = OpenSSL::HMAC.digest(digest, md5cs, query)
152
- Base64.encode64(sha1res).chomp.gsub(/\n/, '')
153
- end
154
-
155
- def generateTimestamp()
156
- Time.now.to_i.to_s
157
- end
158
-
159
- def generateNonce(length = 20)
160
- rand(10 ** length).to_s.rjust(length, '0')
161
- end
162
-
163
- def escape(s)
164
- CGI::escape(s)
165
- end
166
- end
167
- end
1
+ # encoding: utf-8
2
+ require 'uri'
3
+ require 'base64'
4
+ require 'cgi'
5
+ require 'digest/md5'
6
+ require 'openssl'
7
+ require 'digest/sha1'
8
+ require 'net/http'
9
+ require 'net/https'
10
+
11
+ module Semantria
12
+ OAUTH_VERSION = '1.0'
13
+ OAUTH_KEY_PREFIX = "oauth_"
14
+ OAUTH_CONSUMER_KEY = "oauth_consumer_key"
15
+ OAUTH_VERSION_KEY = "oauth_version"
16
+ OAUTH_SIGNATURE_METHOD_KEY = "oauth_signature_method"
17
+ OAUTH_SIGNATURE_KEY = "oauth_signature"
18
+ OAUTH_TIMESTAMP_KEY = "oauth_timestamp"
19
+ OAUTH_NONCE_KEY = "oauth_nonce"
20
+
21
+ class AuthRequest
22
+ attr_accessor :api_version
23
+
24
+ # Create a new instance
25
+ def initialize(consumer_key, consumer_secret, application_name, use_compression = false)
26
+ @consumer_key = consumer_key
27
+ @consumer_secret = consumer_secret
28
+ @application_name = application_name
29
+ @use_compression = use_compression
30
+ end
31
+
32
+ def authWebRequest(method, url, post_data = nil)
33
+ nonce = generateNonce()
34
+ timestamp = generateTimestamp()
35
+ query = generate_query(method, url, timestamp, nonce)
36
+ auth_header = generate_auth_header(query, timestamp, nonce)
37
+ headers = {'Authorization' => auth_header}
38
+
39
+ headers['Content-type'] = 'application/x-www-form-urlencoded' if method == 'POST'
40
+ headers['x-api-version'] = @api_version
41
+ headers['x-app-name'] = @application_name
42
+
43
+ headers['Accept-Encoding'] = 'gzip' if @use_compression
44
+
45
+ uri = URI.parse(query)
46
+ conn = Net::HTTP.new(uri.host, 443)
47
+ conn.use_ssl = true
48
+ conn.verify_mode = OpenSSL::SSL::VERIFY_NONE
49
+
50
+ path = uri.request_uri #'%s?%s' % [qpath, qquery]
51
+ request = get_request(method, path, headers, post_data)
52
+ response = conn.request(request)
53
+
54
+ data = nil
55
+ if response.header['Content-Encoding'].eql? 'gzip'
56
+ sio = StringIO.new( response.body )
57
+ gz = Zlib::GzipReader.new( sio )
58
+ data = gz.read()
59
+ else
60
+ data = response.body
61
+ end
62
+
63
+ {status: response.code.to_i, reason: response.message, data: data}
64
+ end
65
+
66
+ private
67
+ # create the http request object for a given http_method and path
68
+ def get_request(method, path, headers, post_data = nil)
69
+ request = nil
70
+ case method
71
+ when 'POST'
72
+ request = Net::HTTP::Post.new(path, headers)
73
+ when 'PUT'
74
+ request = Net::HTTP::Put.new(path, headers)
75
+ when 'GET'
76
+ request = Net::HTTP::Get.new(path, headers)
77
+ when 'DELETE'
78
+ request = Net::HTTP::Delete.new(path, headers)
79
+ else
80
+ fail ArgumentError, "Don't know how to handle method: :#{method}"
81
+ end
82
+
83
+ unless post_data.nil?
84
+ request.body = post_data
85
+ request['Content-Length'] = request.body.length.to_s
86
+ end
87
+
88
+ request
89
+ end
90
+
91
+ def generate_query(method, url, timestamp, nonce)
92
+ uri = URI.parse(url)
93
+ np = get_normalized_parameters(timestamp, nonce)
94
+
95
+ if uri.query
96
+ uri.query = '%s&%s' % [uri.query, np]
97
+ else
98
+ uri.query = '%s' % np
99
+ end
100
+
101
+ uri.to_s
102
+ end
103
+
104
+ def generate_auth_header(query, timestamp, nonce)
105
+ md5cs = get_md5_hash(@consumer_secret)
106
+ esc_query = escape(query)
107
+ hash = get_sha1(md5cs, esc_query)
108
+ hash = escape(hash)
109
+
110
+ items = Hash.new()
111
+ items['OAuth realm'] = ''
112
+ items[OAUTH_VERSION_KEY] = "%s" % OAUTH_VERSION
113
+ items[OAUTH_TIMESTAMP_KEY] = "%s" % timestamp
114
+ items[OAUTH_NONCE_KEY] = "%s" % nonce
115
+ items[OAUTH_SIGNATURE_METHOD_KEY] = "HMAC-SHA1"
116
+ items[OAUTH_CONSUMER_KEY] = "%s" % @consumer_key
117
+ items[OAUTH_SIGNATURE_KEY] = "%s" % hash
118
+
119
+ params = []
120
+ items.keys.sort.each do |key|
121
+ params.push('%s="%s"' % [key, items[key]])
122
+ end
123
+
124
+ params.join(',')
125
+ end
126
+
127
+ def get_normalized_parameters(timestamp, nonce)
128
+ items = Hash.new()
129
+ items[OAUTH_VERSION_KEY] = OAUTH_VERSION
130
+ items[OAUTH_TIMESTAMP_KEY] = timestamp
131
+ items[OAUTH_NONCE_KEY] = nonce
132
+ items[OAUTH_SIGNATURE_METHOD_KEY] = "HMAC-SHA1"
133
+ items[OAUTH_CONSUMER_KEY] = @consumer_key
134
+
135
+ params = []
136
+ for key in items.keys.sort
137
+ params.push('%s=%s' % [key, items[key]])
138
+ end
139
+
140
+ np = params.join('&')
141
+ # Encode signature parameters per Oauth Core 1.0 protocol
142
+ # Spaces must be encoded with "%20" instead of "+"
143
+ return np.gsub('+', '%20').gsub('%7E', '~')
144
+ end
145
+
146
+ def get_md5_hash(str)
147
+ Digest::MD5.hexdigest(str)
148
+ end
149
+
150
+ def get_sha1(md5cs, query)
151
+ digest = OpenSSL::Digest.new('sha1')
152
+ # our composite signing key now has the token secret after the ampersand
153
+ sha1res = OpenSSL::HMAC.digest(digest, md5cs, query)
154
+ Base64.encode64(sha1res).chomp.gsub(/\n/, '')
155
+ end
156
+
157
+ def generateTimestamp()
158
+ Time.now.to_i.to_s
159
+ end
160
+
161
+ def generateNonce(length = 20)
162
+ rand(10 ** length).to_s.rjust(length, '0')
163
+ end
164
+
165
+ def escape(s)
166
+ CGI::escape(s)
167
+ end
168
+ end
169
+ end
@@ -1,20 +1,20 @@
1
- # encoding: utf-8
2
- require 'json'
3
-
4
- module Semantria
5
- class JsonSerializer
6
- def gettype
7
- 'json'
8
- end
9
-
10
- def serialize(obj, wrapper = nil)
11
- str = JSON.generate(obj)
12
-
13
- str.encoding.name != 'UTF-8' ? str.encode('UTF-8') : str
14
- end
15
-
16
- def deserialize(str, handler = nil)
17
- JSON.parse(str)
18
- end
19
- end
20
- end
1
+ # encoding: utf-8
2
+ require 'json'
3
+
4
+ module Semantria
5
+ class JsonSerializer
6
+ def gettype
7
+ 'json'
8
+ end
9
+
10
+ def serialize(obj, wrapper = nil)
11
+ str = JSON.generate(obj)
12
+
13
+ str.encoding.name != 'UTF-8' ? str.encode('UTF-8') : str
14
+ end
15
+
16
+ def deserialize(str, handler = nil)
17
+ JSON.parse(str)
18
+ end
19
+ end
20
+ end
@@ -1,587 +1,699 @@
1
- # encoding: utf-8
2
- #$LOAD_PATH << File.dirname(__FILE__) unless $LOAD_PATH.include?(File.dirname(__FILE__))
3
- #require_relative 'version'
4
- #require_relative 'authrequest'
5
- #require_relative 'jsonserializer'
6
-
7
- module Semantria
8
- class Session
9
- attr_accessor :host
10
-
11
- # Create a new instance
12
- def initialize(consumer_key, consumer_secret, application_name = nil, use_compression = false, serializer = nil)
13
- @host = 'https://api.semantria.com'
14
- @wrapper_name = "Ruby/#{Semantria::VERSION}"
15
- @consumer_key = consumer_key
16
- @consumer_secret = consumer_secret
17
- @use_compression = use_compression
18
-
19
- if application_name.nil?
20
- @application_name = @wrapper_name
21
- else
22
- @application_name = '%s/%s' % [application_name, @wrapper_name]
23
- end
24
-
25
- if serializer.nil?
26
- #set default json serializer
27
- @serializer = JsonSerializer.new()
28
- @format = @serializer.gettype()
29
- else
30
- @serializer = serializer
31
- @format = @serializer.gettype()
32
- end
33
- end
34
-
35
- def registerSerializer(serializer)
36
- fail 'Serializer can\'t be null' if serializer.nil?
37
-
38
- @serializer = serializer
39
- @format = serializer.gettype()
40
- end
41
-
42
- def setCallbackHandler(callback)
43
- if callback.class < CallbackHandler
44
- @callback = callback
45
- else
46
- fail "Parameter is not subclass of CallbackHandler #{callback}"
47
- end
48
- end
49
-
50
- def getStatus
51
- url = "#{@host}/status.#{@format}"
52
- runRequest('GET', url, 'get_status')
53
- end
54
-
55
- def getSupportedFeatures(language)
56
- if language.nil?
57
- url = "#{@host}/features.#{@format}"
58
- else
59
- url = "#{@host}/features.#{@format}?language=#{language}"
60
- end
61
-
62
- runRequest('GET', url, 'get_features')
63
- end
64
-
65
- def getSubscription
66
- url = "#{@host}/subscription.#{@format}"
67
- runRequest('GET', url, 'get_subscription')
68
- end
69
-
70
- def getStatistics
71
- url = "#{@host}/statistics.#{@format}"
72
- runRequest('GET', url, 'get_statistics')
73
- end
74
-
75
- def getConfigurations
76
- url = "#{@host}/configurations.#{@format}"
77
- runRequest('GET', url, 'get_configurations') || []
78
- end
79
-
80
- def addConfigurations(items)
81
- updateConfigurations(items)
82
- end
83
-
84
- def updateConfigurations(items)
85
- url = "#{@host}/configurations.#{@format}"
86
- wrapper = get_type_wrapper('update_configurations')
87
- data = @serializer.serialize(items, wrapper)
88
- runRequest('POST', url, nil, data)
89
- end
90
-
91
- def deleteConfigurations(items)
92
- url = "#{@host}/configurations.#{@format}"
93
-
94
- wrapper = get_type_wrapper('delete_configurations')
95
- data = @serializer.serialize(items, wrapper)
96
- runRequest('DELETE', url, nil, data)
97
- end
98
-
99
- def getBlacklist(config_id = nil)
100
- if config_id.nil?
101
- url = "#{@host}/blacklist.#{@format}"
102
- else
103
- url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
104
- end
105
-
106
- runRequest('GET', url, 'get_blacklist') || []
107
- end
108
-
109
- def addBlacklist(items, config_id = nil)
110
- updateBlacklist(items, config_id)
111
- end
112
-
113
- def updateBlacklist(items, config_id = nil)
114
- if config_id.nil?
115
- url = "#{@host}/blacklist.#{@format}"
116
- else
117
- url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
118
- end
119
-
120
- wrapper = get_type_wrapper('update_blacklist')
121
- data = @serializer.serialize(items, wrapper)
122
- runRequest('POST', url, nil, data)
123
- end
124
-
125
- def removeBlacklist(items, config_id = nil)
126
- if config_id.nil?
127
- url = "#{@host}/blacklist.#{@format}"
128
- else
129
- url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
130
- end
131
-
132
- wrapper = get_type_wrapper('remove_blacklist')
133
- data = @serializer.serialize(items, wrapper)
134
- runRequest('DELETE', url, nil, data)
135
- end
136
-
137
- def getCategories(config_id = nil)
138
- if config_id.nil?
139
- url = "#{@host}/categories.#{@format}"
140
- else
141
- url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
142
- end
143
-
144
- runRequest('GET', url, 'get_categories') || []
145
- end
146
-
147
- def addCategories(items, config_id = nil)
148
- updateCategories(items, config_id)
149
- end
150
-
151
- def updateCategories(items, config_id = nil)
152
- if config_id.nil?
153
- url = "#{@host}/categories.#{@format}"
154
- else
155
- url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
156
- end
157
-
158
- wrapper = get_type_wrapper('update_categories')
159
- data = @serializer.serialize(items, wrapper)
160
- runRequest('POST', url, nil, data)
161
- end
162
-
163
- def removeCategories(items, config_id = nil)
164
- if config_id.nil?
165
- url = "#{@host}/categories.#{@format}"
166
- else
167
- url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
168
- end
169
-
170
- wrapper = get_type_wrapper('remove_categories')
171
- data = @serializer.serialize(items, wrapper)
172
- runRequest('DELETE', url, nil, data)
173
- end
174
-
175
- def getQueries(config_id = nil)
176
- if config_id.nil?
177
- url = "#{@host}/queries.#{@format}"
178
- else
179
- url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
180
- end
181
-
182
- runRequest('GET', url, 'get_queries') || []
183
- end
184
-
185
- def addQueries(items, config_id = nil)
186
- updateQueries(items, config_id)
187
- end
188
-
189
- def updateQueries(items, config_id = nil)
190
- if config_id.nil?
191
- url = "#{@host}/queries.#{@format}"
192
- else
193
- url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
194
- end
195
-
196
- wrapper = get_type_wrapper('update_queries')
197
- data = @serializer.serialize(items, wrapper)
198
- runRequest('POST', url, nil, data)
199
- end
200
-
201
- def removeQueries(items, config_id = nil)
202
- if config_id.nil?
203
- url = "#{@host}/queries.#{@format}"
204
- else
205
- url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
206
- end
207
-
208
- wrapper = get_type_wrapper('remove_queries')
209
- data = @serializer.serialize(items, wrapper)
210
- runRequest('DELETE', url, nil, data)
211
- end
212
-
213
- def getPhrases(config_id = nil)
214
- if config_id.nil?
215
- url = "#{@host}/phrases.#{@format}"
216
- else
217
- url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
218
- end
219
-
220
- runRequest('GET', url, 'get_sentiment_phrases') || []
221
- end
222
-
223
- def addPhrases(items, config_id = nil)
224
- updatePhrases(items, config_id)
225
- end
226
-
227
- def updatePhrases(items, config_id = nil)
228
- if config_id.nil?
229
- url = "#{@host}/phrases.#{@format}"
230
- else
231
- url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
232
- end
233
-
234
- wrapper = get_type_wrapper('update_sentiment_phrases')
235
- data = @serializer.serialize(items, wrapper)
236
- runRequest('POST', url, nil, data)
237
- end
238
-
239
- def removePhrases(items, config_id = nil)
240
- if config_id.nil?
241
- url = "#{@host}/phrases.#{@format}"
242
- else
243
- url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
244
- end
245
-
246
- wrapper = get_type_wrapper('remove_phrases')
247
- data = @serializer.serialize(items, wrapper)
248
- runRequest('DELETE', url, nil, data)
249
- end
250
-
251
- def getEntities(config_id = nil)
252
- if config_id.nil?
253
- url = "#{@host}/entities.#{@format}"
254
- else
255
- url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
256
- end
257
-
258
- runRequest('GET', url, 'get_entities') || []
259
- end
260
-
261
- def addEntities(items, config_id = nil)
262
- updateEntities(items, config_id)
263
- end
264
-
265
- def updateEntities(items, config_id = nil)
266
- if config_id.nil?
267
- url = "#{@host}/entities.#{@format}"
268
- else
269
- url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
270
- end
271
-
272
- wrapper = get_type_wrapper('update_entities')
273
- data = @serializer.serialize(items, wrapper)
274
- runRequest('POST', url, nil, data)
275
- end
276
-
277
- def removeEntities(items, config_id = nil)
278
- if config_id.nil?
279
- url = "#{@host}/entities.#{@format}"
280
- else
281
- url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
282
- end
283
-
284
- wrapper = get_type_wrapper('remove_entities')
285
- data = @serializer.serialize(items, wrapper)
286
- runRequest('DELETE', url, nil, data)
287
- end
288
-
289
- def queueDocument(task, config_id = nil)
290
- if config_id.nil?
291
- url = "#{@host}/document.#{@format}"
292
- else
293
- url = "#{@host}/document.#{@format}?config_id=#{config_id}"
294
- end
295
-
296
- wrapper = get_type_wrapper('queue_document')
297
- data = @serializer.serialize(task, wrapper)
298
- result = runRequest('POST', url, 'get_processed_documents', data)
299
- if result != nil && result.is_a?(Array)
300
- onDocsAutoResponse(result)
301
- 200
302
- else
303
- result
304
- end
305
- end
306
-
307
- def queueBatch(batch, config_id = nil)
308
- if config_id.nil?
309
- url = "#{@host}/document/batch.#{@format}"
310
- else
311
- url = "#{@host}/document/batch.#{@format}?config_id=#{config_id}"
312
- end
313
-
314
- wrapper = get_type_wrapper('queue_batch_documents')
315
- data = @serializer.serialize(batch, wrapper)
316
- result = runRequest('POST', url, 'get_processed_documents', data)
317
- if result != nil && result.is_a?(Array)
318
- onDocsAutoResponse(result)
319
- 200
320
- else
321
- result
322
- end
323
- end
324
-
325
- def getDocument(doc_id, config_id = nil)
326
- fail 'Document ID is nil or empty' if doc_id.nil?
327
-
328
- if config_id.nil?
329
- url = "#{@host}/document/#{doc_id}.#{@format}"
330
- else
331
- url = "#{@host}/document/#{doc_id}.#{@format}?config_id=#{config_id}"
332
- end
333
-
334
- runRequest('GET', url, 'get_document')
335
- end
336
-
337
- def cancelDocument(doc_id, config_id = nil)
338
- fail 'Document ID is nil or empty' if doc_id.nil?
339
-
340
- if config_id.nil?
341
- url = "#{@host}/document/#{doc_id}.#{@format}"
342
- else
343
- url = "#{@host}/document/#{doc_id}.#{@format}?config_id=#{config_id}"
344
- end
345
-
346
- runRequest('DELETE', url)
347
- end
348
-
349
- def getProcessedDocuments(config_id = nil)
350
- if config_id.nil?
351
- url = "#{@host}/document/processed.#{@format}"
352
- else
353
- url = "#{@host}/document/processed.#{@format}?config_id=#{config_id}"
354
- end
355
-
356
- result = runRequest('GET', url, 'get_processed_documents')
357
- result ||= []
358
- end
359
-
360
- def getProcessedDocumentsByJobId(job_id)
361
- url = "#{@host}/document/processed.#{@format}?job_id=#{job_id}"
362
-
363
- result = runRequest('GET', url, 'get_processed_documents_by_job_id')
364
- result ||= []
365
- end
366
-
367
- def queueCollection(task, config_id = nil)
368
- if config_id.nil?
369
- url = "#{@host}/collection.#{@format}"
370
- else
371
- url = "#{@host}/collection.#{@format}?config_id=#{config_id}"
372
- end
373
-
374
- wrapper = get_type_wrapper('queue_collection')
375
- data = @serializer.serialize(task, wrapper)
376
- result = runRequest('POST', url, 'get_processed_collections', data)
377
- if result != nil && result.is_a?(Array)
378
- onCollsAutoResponse(result)
379
- 200
380
- else
381
- result
382
- end
383
- end
384
-
385
- def getCollection(id, config_id = nil)
386
- fail 'Collection ID is nil or empty' if id.nil?
387
-
388
- if config_id.nil?
389
- url = "#{@host}/collection/#{id}.#{@format}"
390
- else
391
- url = "#{@host}/collection/#{id}.#{@format}?config_id=#{config_id}"
392
- end
393
-
394
- runRequest('GET', url, 'get_collection')
395
- end
396
-
397
- def cancelCollection(id, config_id = nil)
398
- fail 'Collection ID is nil or empty' if id.nil?
399
-
400
- if config_id.nil?
401
- url = "#{@host}/collection/#{id}.#{@format}"
402
- else
403
- url = "#{@host}/collection/#{id}.#{@format}?config_id=#{config_id}"
404
- end
405
-
406
- runRequest('DELETE', url)
407
- end
408
-
409
- def getProcessedCollections(config_id = nil)
410
- if config_id.nil?
411
- url = "#{@host}/collection/processed.#{@format}"
412
- else
413
- url = "#{@host}/collection/processed.#{@format}?config_id=#{config_id}"
414
- end
415
-
416
- result = runRequest('GET', url, 'get_processed_collections')
417
- result ||= []
418
- end
419
-
420
- def getProcessedCollectionsByJobId(job_id)
421
- url = "#{@host}/collection/processed.#{@format}?job_id=#{job_id}"
422
-
423
- result = runRequest('GET', url, 'get_processed_collections_by_job_id')
424
- result ||= []
425
- end
426
-
427
- private
428
- def runRequest(method, url, type = nil, post_data = nil)
429
- request = AuthRequest.new(@consumer_key, @consumer_secret, @application_name, @use_compression)
430
-
431
- onRequest({'method' => method, 'url' => url, 'message' => post_data})
432
-
433
- response = request.authWebRequest(method, url, post_data)
434
-
435
- onResponse({'status' => response[:status], 'reason' => response[:reason], 'message' => response[:data]})
436
-
437
- status = response[:status]
438
- message = response[:reason]
439
-
440
- message = response[:data] unless response[:data].to_s.empty?
441
-
442
- if method == 'DELETE'
443
- if status == 200 || status == 202
444
- return status
445
- else
446
- resolve_error(status, message)
447
- return status
448
- end
449
- else
450
- if status == 200
451
- handler = get_type_handler(type)
452
- message = @serializer.deserialize(response[:data], handler)
453
- return message
454
- elsif status == 202
455
- if method == 'POST'
456
- return status
457
- else
458
- return nil
459
- end
460
- else
461
- resolve_error(status, message)
462
- end
463
- end
464
- end
465
-
466
- def get_type_handler(type)
467
- if @serializer.gettype() == 'json'
468
- return nil
469
- end
470
-
471
- #only for xml serializer
472
- case
473
- when type == 'get_status' then return GetStatusHandler.new()
474
- when type == 'get_subscription' then return GetSubscriptionHandler.new()
475
- when type == 'get_configurations' then return GetConfigurationsHandler.new()
476
- when type == 'get_blacklist' then return GetBlacklistHandler.new()
477
- when type == 'get_categories' then return GetCategoriesHandler.new()
478
- when type == 'get_queries' then return GetQueriesHandler.new()
479
- when type == 'get_sentiment_phrases' then return GetSentimentPhrasesHandler.new()
480
- when type == 'get_entities' then return GetEntitiesHandler.new()
481
- when type == 'get_document' then return GetDocumentHandler.new()
482
- when type == 'get_processed_documents' then return GetProcessedDocumentsHandler.new()
483
- when type == 'get_collection' then return GetCollectionHandler.new()
484
- when type == 'get_processed_collections' then return GetProcessedCollectionsHandler.new()
485
- else return nil
486
- end
487
- end
488
-
489
- def get_type_wrapper(type)
490
- if @serializer.gettype() == 'json'
491
- nil
492
- end
493
-
494
- #only for xml serializer
495
- #if type == "update_configurations"
496
- # return {"root" => "configurations", "added" => "configuration", "removed" => "configuration"}
497
- #elsif type == "update_blacklist"
498
- # return {"root" => "blacklist", "added" => "item", "removed" => "item"}
499
- #elsif type == "update_categories"
500
- # return {"root" => "categories", "added" => "category", "removed" => "category", "samples" => "sample"}
501
- #elsif type == "update_queries"
502
- # return {"root" => "queries", "added" => "query", "removed" => "query"}
503
- #elsif type == "update_sentiment_phrases"
504
- # return {"root" => "phrases", "added" => "phrase", "removed" => "phrase"}
505
- #elsif type == "update_entities"
506
- # return {"root" => "entities", "added" => "entity", "removed" => "entity"}
507
- #elsif type == "queue_document"
508
- # return {"root" => "document"}
509
- #elsif type == "queue_batch_documents"
510
- # return {"root" => "documents", "item" => "document"}
511
- #elsif type == "queue_collection"
512
- # return {"root" => "collection", "documents" => "document"}
513
- #else
514
- # return nil
515
- #end
516
- end
517
-
518
- def resolve_error(status, message = nil)
519
- if status == 400 || status == 401 || status == 402 || status == 403 || status == 406 || status == 500
520
- onError({'status' => status, 'message' => message})
521
- else
522
- fail "HTTP error was found with status: #{status} and message: #{message}"
523
- end
524
- end
525
-
526
- def onRequest(request)
527
- unless @callback.nil?
528
- @callback.onRequest(self, request)
529
- end
530
- end
531
-
532
- def onResponse(response)
533
- unless @callback.nil?
534
- @callback.onResponse(self, response)
535
- end
536
- end
537
-
538
- def onError(response)
539
- unless @callback.nil?
540
- @callback.onError(self, response)
541
- end
542
- end
543
-
544
- def onDocsAutoResponse(response)
545
- unless @callback.nil?
546
- @callback.onDocsAutoResponse(self, response)
547
- end
548
- end
549
-
550
- def onCollsAutoResponse(response)
551
- unless @callback.nil?
552
- @callback.onCollsAutoResponse(self, response)
553
- end
554
- end
555
- end
556
-
557
- class CallbackHandler
558
- def initialize
559
- fail 'Don\'t instantiate me!' if abstract_class?
560
- end
561
-
562
- private
563
- def abstract_class?
564
- self.class == CallbackHandler
565
- end
566
-
567
- def onRequest(sender, args)
568
- fail 'Abstract method onRequest'
569
- end
570
-
571
- def onResponse(sender, args)
572
- fail 'Abstract method onResponse'
573
- end
574
-
575
- def onError(sender, args)
576
- fail 'Abstract method onError'
577
- end
578
-
579
- def onDocsAutoResponse(sender, args)
580
- fail 'Abstract method onDocsAutoResponse'
581
- end
582
-
583
- def onCollsAutoResponse(sender, args)
584
- fail 'Abstract method onCollsAutoResponse'
585
- end
586
- end
587
- end
1
+ # encoding: utf-8
2
+ #$LOAD_PATH << File.dirname(__FILE__) unless $LOAD_PATH.include?(File.dirname(__FILE__))
3
+ #require_relative 'version'
4
+ #require_relative 'authrequest'
5
+ #require_relative 'jsonserializer'
6
+ #require_relative 'fileutils'
7
+
8
+ module Semantria
9
+ class Session
10
+ attr_accessor :host
11
+ attr_accessor :api_version
12
+
13
+ # Create a new instance
14
+ def initialize(consumer_key = nil, consumer_secret = nil, application_name = nil, use_compression = false, serializer = nil, username = nil, password = nil, session_file = '/tmp/session.dat')
15
+ @host = 'https://api.semantria.com'
16
+ @key_url = 'https://semantria.com/auth/session'
17
+ @app_key = 'cd954253-acaf-4dfa-a417-0a8cfb701f12'
18
+ @wrapper_name = "Ruby/#{Semantria::VERSION}"
19
+ @consumer_key = consumer_key
20
+ @consumer_secret = consumer_secret
21
+ @use_compression = use_compression
22
+ @api_version = '4.2'
23
+
24
+ if serializer.nil?
25
+ #set default json serializer
26
+ @serializer = JsonSerializer.new()
27
+ @format = @serializer.gettype()
28
+ else
29
+ @serializer = serializer
30
+ @format = @serializer.gettype()
31
+ end
32
+
33
+ if consumer_key.nil? && consumer_secret.nil?
34
+ @consumer_key, @consumer_secret = obtainKeys(username, password, session_file)
35
+ if @consumer_key.nil? || @consumer_secret.nil?
36
+ fail "Cannot obtain Semantria keys. Wrong username or password"
37
+ end
38
+ end
39
+
40
+ if application_name.nil?
41
+ @application_name = @wrapper_name
42
+ else
43
+ @application_name = '%s/%s' % [application_name, @wrapper_name]
44
+ end
45
+
46
+ end
47
+
48
+ def obtainKeys(username, password, session_file = '/tmp/sematria-session.dat')
49
+ if File.exist?(session_file)
50
+ session_id = File.read(session_file)
51
+ url = "#{@key_url}/#{session_id}.json?appkey=#{@app_key}"
52
+ uri = URI.parse url
53
+ http = Net::HTTP.new(uri.host, uri.port)
54
+ http.use_ssl = true
55
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
56
+ request = Net::HTTP::Get.new(uri.request_uri)
57
+ response = http.request(request)
58
+ if response.code.to_i == 200
59
+ body = @serializer.deserialize(response.body)
60
+ if body[:custom_params][:key].present && body[:custom_params][:secret].present
61
+ return [body[:custom_params][:key], body[:custom_params][:secret]]
62
+ end
63
+ end
64
+ end
65
+
66
+ url = "#{@key_url}.json?appkey=#{@app_key}";
67
+ post = {
68
+ username: username,
69
+ password: password
70
+ }
71
+ uri = URI.parse url
72
+ http = Net::HTTP.new(uri.host, uri.port)
73
+ http.use_ssl = true
74
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
75
+ request = Net::HTTP::Post.new(uri.request_uri)
76
+ request.body = post.to_json
77
+ response = http.request(request)
78
+
79
+ if response.code.to_i != 200
80
+ return [nil, nil]
81
+ end
82
+
83
+ body = @serializer.deserialize(response.body)
84
+ session_id = body[:id].to_s
85
+ if !session_file.to_s.empty? && !session_id.empty?
86
+ File.open(session_file, 'w') { |file| file.write(session_id) }
87
+ end
88
+
89
+ [body[:custom_params][:key], body[:custom_params][:secret]]
90
+ end
91
+
92
+ def registerSerializer(serializer)
93
+ fail 'Serializer can\'t be null' if serializer.nil?
94
+
95
+ @serializer = serializer
96
+ @format = serializer.gettype()
97
+ end
98
+
99
+ def setCallbackHandler(callback)
100
+ if callback.class < CallbackHandler
101
+ @callback = callback
102
+ else
103
+ fail "Parameter is not subclass of CallbackHandler #{callback}"
104
+ end
105
+ end
106
+
107
+ def getStatus
108
+ url = "#{@host}/status.#{@format}"
109
+ runRequest('GET', url, 'get_status')
110
+ end
111
+
112
+ def getSupportedFeatures(language)
113
+ if language.nil?
114
+ url = "#{@host}/features.#{@format}"
115
+ else
116
+ url = "#{@host}/features.#{@format}?language=#{language}"
117
+ end
118
+
119
+ runRequest('GET', url, 'get_features')
120
+ end
121
+
122
+ def getSubscription
123
+ url = "#{@host}/subscription.#{@format}"
124
+ runRequest('GET', url, 'get_subscription')
125
+ end
126
+
127
+ def getStatistics
128
+ url = "#{@host}/statistics.#{@format}"
129
+ runRequest('GET', url, 'get_statistics')
130
+ end
131
+
132
+ def getConfigurations
133
+ url = "#{@host}/configurations.#{@format}"
134
+ runRequest('GET', url, 'get_configurations') || []
135
+ end
136
+
137
+ def addConfigurations(items)
138
+ updateConfigurations(items, true)
139
+ end
140
+
141
+ def updateConfigurations(items, create = false)
142
+ url = "#{@host}/configurations.#{@format}"
143
+ wrapper = get_type_wrapper('update_configurations')
144
+ data = @serializer.serialize(items, wrapper)
145
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
146
+ end
147
+
148
+ def cloneConfigurations(name, template)
149
+ items = {
150
+ 'name' => name,
151
+ 'template' => template
152
+ }
153
+ updateConfigurations([items])
154
+ end
155
+
156
+ def deleteConfigurations(items)
157
+ url = "#{@host}/configurations.#{@format}"
158
+
159
+ wrapper = get_type_wrapper('delete_configurations')
160
+ data = @serializer.serialize(items, wrapper)
161
+ runRequest('DELETE', url, nil, data)
162
+ end
163
+
164
+ def getBlacklist(config_id = nil)
165
+ if config_id.nil?
166
+ url = "#{@host}/blacklist.#{@format}"
167
+ else
168
+ url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
169
+ end
170
+
171
+ runRequest('GET', url, 'get_blacklist') || []
172
+ end
173
+
174
+ def addBlacklist(items, config_id = nil)
175
+ updateBlacklist(items, config_id, true)
176
+ end
177
+
178
+ def updateBlacklist(items, config_id = nil, create = false)
179
+ if config_id.nil?
180
+ url = "#{@host}/blacklist.#{@format}"
181
+ else
182
+ url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
183
+ end
184
+
185
+ wrapper = get_type_wrapper('update_blacklist')
186
+ data = @serializer.serialize(items, wrapper)
187
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
188
+ end
189
+
190
+ def removeBlacklist(items, config_id = nil)
191
+ if config_id.nil?
192
+ url = "#{@host}/blacklist.#{@format}"
193
+ else
194
+ url = "#{@host}/blacklist.#{@format}?config_id=#{config_id}"
195
+ end
196
+
197
+ wrapper = get_type_wrapper('remove_blacklist')
198
+ data = @serializer.serialize(items, wrapper)
199
+ runRequest('DELETE', url, nil, data)
200
+ end
201
+
202
+ def getCategories(config_id = nil)
203
+ if config_id.nil?
204
+ url = "#{@host}/categories.#{@format}"
205
+ else
206
+ url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
207
+ end
208
+
209
+ runRequest('GET', url, 'get_categories') || []
210
+ end
211
+
212
+ def addCategories(items, config_id = nil)
213
+ updateCategories(items, config_id, true)
214
+ end
215
+
216
+ def updateCategories(items, config_id = nil, create = false)
217
+ if config_id.nil?
218
+ url = "#{@host}/categories.#{@format}"
219
+ else
220
+ url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
221
+ end
222
+
223
+ wrapper = get_type_wrapper('update_categories')
224
+ data = @serializer.serialize(items, wrapper)
225
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
226
+ end
227
+
228
+ def removeCategories(items, config_id = nil)
229
+ if config_id.nil?
230
+ url = "#{@host}/categories.#{@format}"
231
+ else
232
+ url = "#{@host}/categories.#{@format}?config_id=#{config_id}"
233
+ end
234
+
235
+ wrapper = get_type_wrapper('remove_categories')
236
+ data = @serializer.serialize(items, wrapper)
237
+ runRequest('DELETE', url, nil, data)
238
+ end
239
+
240
+ def getQueries(config_id = nil)
241
+ if config_id.nil?
242
+ url = "#{@host}/queries.#{@format}"
243
+ else
244
+ url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
245
+ end
246
+
247
+ runRequest('GET', url, 'get_queries') || []
248
+ end
249
+
250
+ def addQueries(items, config_id = nil)
251
+ updateQueries(items, config_id, true)
252
+ end
253
+
254
+ def updateQueries(items, config_id = nil, create = false)
255
+ if config_id.nil?
256
+ url = "#{@host}/queries.#{@format}"
257
+ else
258
+ url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
259
+ end
260
+
261
+ wrapper = get_type_wrapper('update_queries')
262
+ data = @serializer.serialize(items, wrapper)
263
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
264
+ end
265
+
266
+ def removeQueries(items, config_id = nil)
267
+ if config_id.nil?
268
+ url = "#{@host}/queries.#{@format}"
269
+ else
270
+ url = "#{@host}/queries.#{@format}?config_id=#{config_id}"
271
+ end
272
+
273
+ wrapper = get_type_wrapper('remove_queries')
274
+ data = @serializer.serialize(items, wrapper)
275
+ runRequest('DELETE', url, nil, data)
276
+ end
277
+
278
+ def getPhrases(config_id = nil)
279
+ if config_id.nil?
280
+ url = "#{@host}/phrases.#{@format}"
281
+ else
282
+ url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
283
+ end
284
+
285
+ runRequest('GET', url, 'get_sentiment_phrases') || []
286
+ end
287
+
288
+ def addPhrases(items, config_id = nil)
289
+ updatePhrases(items, config_id, true)
290
+ end
291
+
292
+ def updatePhrases(items, config_id = nil, create = false)
293
+ if config_id.nil?
294
+ url = "#{@host}/phrases.#{@format}"
295
+ else
296
+ url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
297
+ end
298
+
299
+ wrapper = get_type_wrapper('update_sentiment_phrases')
300
+ data = @serializer.serialize(items, wrapper)
301
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
302
+ end
303
+
304
+ def removePhrases(items, config_id = nil)
305
+ if config_id.nil?
306
+ url = "#{@host}/phrases.#{@format}"
307
+ else
308
+ url = "#{@host}/phrases.#{@format}?config_id=#{config_id}"
309
+ end
310
+
311
+ wrapper = get_type_wrapper('remove_phrases')
312
+ data = @serializer.serialize(items, wrapper)
313
+ runRequest('DELETE', url, nil, data)
314
+ end
315
+
316
+ def getEntities(config_id = nil)
317
+ if config_id.nil?
318
+ url = "#{@host}/entities.#{@format}"
319
+ else
320
+ url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
321
+ end
322
+
323
+ runRequest('GET', url, 'get_entities') || []
324
+ end
325
+
326
+ def addEntities(items, config_id = nil)
327
+ updateEntities(items, config_id, true)
328
+ end
329
+
330
+ def updateEntities(items, config_id = nil, create = false)
331
+ if config_id.nil?
332
+ url = "#{@host}/entities.#{@format}"
333
+ else
334
+ url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
335
+ end
336
+
337
+ wrapper = get_type_wrapper('update_entities')
338
+ data = @serializer.serialize(items, wrapper)
339
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
340
+ end
341
+
342
+ def removeEntities(items, config_id = nil)
343
+ if config_id.nil?
344
+ url = "#{@host}/entities.#{@format}"
345
+ else
346
+ url = "#{@host}/entities.#{@format}?config_id=#{config_id}"
347
+ end
348
+
349
+ wrapper = get_type_wrapper('remove_entities')
350
+ data = @serializer.serialize(items, wrapper)
351
+ runRequest('DELETE', url, nil, data)
352
+ end
353
+
354
+ def getTaxonomy(config_id = nil)
355
+ if config_id.nil?
356
+ url = "#{@host}/taxonomy.#{@format}"
357
+ else
358
+ url = "#{@host}/taxonomy.#{@format}?config_id=#{config_id}"
359
+ end
360
+
361
+ runRequest('GET', url, 'get_taxonomy') || []
362
+ end
363
+
364
+ def addTaxonomy(items, config_id = nil)
365
+ updateTaxonomy(items, config_id, true)
366
+ end
367
+
368
+ def updateTaxonomy(items, config_id = nil, create = false)
369
+ if config_id.nil?
370
+ url = "#{@host}/taxonomy.#{@format}"
371
+ else
372
+ url = "#{@host}/taxonomy.#{@format}?config_id=#{config_id}"
373
+ end
374
+
375
+ wrapper = get_type_wrapper('update_taxonomy')
376
+ data = @serializer.serialize(items, wrapper)
377
+ runRequest((create ? 'POST' : 'PUT'), url, nil, data)
378
+ end
379
+
380
+ def removeTaxonomy(items, config_id = nil)
381
+ if config_id.nil?
382
+ url = "#{@host}/taxonomy.#{@format}"
383
+ else
384
+ url = "#{@host}/taxonomy.#{@format}?config_id=#{config_id}"
385
+ end
386
+
387
+ wrapper = get_type_wrapper('remove_taxonomy')
388
+ data = @serializer.serialize(items, wrapper)
389
+ runRequest('DELETE', url, nil, data)
390
+ end
391
+
392
+ def queueDocument(task, config_id = nil)
393
+ if config_id.nil?
394
+ url = "#{@host}/document.#{@format}"
395
+ else
396
+ url = "#{@host}/document.#{@format}?config_id=#{config_id}"
397
+ end
398
+
399
+ wrapper = get_type_wrapper('queue_document')
400
+ data = @serializer.serialize(task, wrapper)
401
+ result = runRequest('POST', url, 'get_processed_documents', data)
402
+ if result != nil && result.is_a?(Array)
403
+ onDocsAutoResponse(result)
404
+ 200
405
+ else
406
+ result
407
+ end
408
+ end
409
+
410
+ def queueBatch(batch, config_id = nil)
411
+ if config_id.nil?
412
+ url = "#{@host}/document/batch.#{@format}"
413
+ else
414
+ url = "#{@host}/document/batch.#{@format}?config_id=#{config_id}"
415
+ end
416
+
417
+ wrapper = get_type_wrapper('queue_batch_documents')
418
+ data = @serializer.serialize(batch, wrapper)
419
+ result = runRequest('POST', url, 'get_processed_documents', data)
420
+ if result != nil && result.is_a?(Array)
421
+ onDocsAutoResponse(result)
422
+ 200
423
+ else
424
+ result
425
+ end
426
+ end
427
+
428
+ def getDocument(doc_id, config_id = nil)
429
+ fail 'Document ID is nil or empty' if doc_id.nil?
430
+
431
+ doc_id = URI.encode doc_id
432
+
433
+ if config_id.nil?
434
+ url = "#{@host}/document/#{doc_id}.#{@format}"
435
+ else
436
+ url = "#{@host}/document/#{doc_id}.#{@format}?config_id=#{config_id}"
437
+ end
438
+
439
+ runRequest('GET', url, 'get_document')
440
+ end
441
+
442
+ def cancelDocument(doc_id, config_id = nil)
443
+ fail 'Document ID is nil or empty' if doc_id.nil?
444
+
445
+ doc_id = URI.encode doc_id
446
+
447
+ if config_id.nil?
448
+ url = "#{@host}/document/#{doc_id}.#{@format}"
449
+ else
450
+ url = "#{@host}/document/#{doc_id}.#{@format}?config_id=#{config_id}"
451
+ end
452
+
453
+ runRequest('DELETE', url)
454
+ end
455
+
456
+ def getProcessedDocuments(config_id = nil)
457
+ if config_id.nil?
458
+ url = "#{@host}/document/processed.#{@format}"
459
+ else
460
+ url = "#{@host}/document/processed.#{@format}?config_id=#{config_id}"
461
+ end
462
+
463
+ result = runRequest('GET', url, 'get_processed_documents')
464
+ result ||= []
465
+ end
466
+
467
+ def getProcessedDocumentsByJobId(job_id)
468
+ url = "#{@host}/document/processed.#{@format}?job_id=#{job_id}"
469
+
470
+ result = runRequest('GET', url, 'get_processed_documents_by_job_id')
471
+ result ||= []
472
+ end
473
+
474
+ def queueCollection(task, config_id = nil)
475
+ if config_id.nil?
476
+ url = "#{@host}/collection.#{@format}"
477
+ else
478
+ url = "#{@host}/collection.#{@format}?config_id=#{config_id}"
479
+ end
480
+
481
+ wrapper = get_type_wrapper('queue_collection')
482
+ data = @serializer.serialize(task, wrapper)
483
+ result = runRequest('POST', url, 'get_processed_collections', data)
484
+ if result != nil && result.is_a?(Array)
485
+ onCollsAutoResponse(result)
486
+ 200
487
+ else
488
+ result
489
+ end
490
+ end
491
+
492
+ def getCollection(id, config_id = nil)
493
+ fail 'Collection ID is nil or empty' if id.nil?
494
+
495
+ id = URI.encode id
496
+
497
+ if config_id.nil?
498
+ url = "#{@host}/collection/#{id}.#{@format}"
499
+ else
500
+ url = "#{@host}/collection/#{id}.#{@format}?config_id=#{config_id}"
501
+ end
502
+
503
+ runRequest('GET', url, 'get_collection')
504
+ end
505
+
506
+ def cancelCollection(id, config_id = nil)
507
+ fail 'Collection ID is nil or empty' if id.nil?
508
+
509
+ id = URI.encode id
510
+
511
+ if config_id.nil?
512
+ url = "#{@host}/collection/#{id}.#{@format}"
513
+ else
514
+ url = "#{@host}/collection/#{id}.#{@format}?config_id=#{config_id}"
515
+ end
516
+
517
+ runRequest('DELETE', url)
518
+ end
519
+
520
+ def getProcessedCollections(config_id = nil)
521
+ if config_id.nil?
522
+ url = "#{@host}/collection/processed.#{@format}"
523
+ else
524
+ url = "#{@host}/collection/processed.#{@format}?config_id=#{config_id}"
525
+ end
526
+
527
+ result = runRequest('GET', url, 'get_processed_collections')
528
+ result ||= []
529
+ end
530
+
531
+ def getProcessedCollectionsByJobId(job_id)
532
+ url = "#{@host}/collection/processed.#{@format}?job_id=#{job_id}"
533
+
534
+ result = runRequest('GET', url, 'get_processed_collections_by_job_id')
535
+ result ||= []
536
+ end
537
+
538
+ private
539
+ def runRequest(method, url, type = nil, post_data = nil)
540
+ request = AuthRequest.new(@consumer_key, @consumer_secret, @application_name, @use_compression)
541
+ request.api_version=(@api_version)
542
+
543
+ onRequest({'method' => method, 'url' => url, 'message' => post_data})
544
+
545
+ response = request.authWebRequest(method, url, post_data)
546
+
547
+ onResponse({'status' => response[:status], 'reason' => response[:reason], 'message' => response[:data]})
548
+
549
+ status = response[:status]
550
+ message = response[:reason]
551
+
552
+ message = response[:data] unless response[:data].to_s.empty?
553
+
554
+ if method == 'DELETE'
555
+ if status == 200 || status == 202
556
+ return status
557
+ else
558
+ resolve_error(status, message)
559
+ return status
560
+ end
561
+ else
562
+ if status == 200
563
+ handler = get_type_handler(type)
564
+ message = @serializer.deserialize(response[:data], handler)
565
+ return message
566
+ elsif status == 202
567
+ if method == 'POST'
568
+ return status
569
+ else
570
+ return nil
571
+ end
572
+ else
573
+ resolve_error(status, message)
574
+ end
575
+ end
576
+ end
577
+
578
+ def get_type_handler(type)
579
+ if @serializer.gettype() == 'json'
580
+ return nil
581
+ end
582
+
583
+ #only for xml serializer
584
+ case
585
+ when type == 'get_status' then return GetStatusHandler.new()
586
+ when type == 'get_subscription' then return GetSubscriptionHandler.new()
587
+ when type == 'get_configurations' then return GetConfigurationsHandler.new()
588
+ when type == 'get_blacklist' then return GetBlacklistHandler.new()
589
+ when type == 'get_categories' then return GetCategoriesHandler.new()
590
+ when type == 'get_queries' then return GetQueriesHandler.new()
591
+ when type == 'get_sentiment_phrases' then return GetSentimentPhrasesHandler.new()
592
+ when type == 'get_entities' then return GetEntitiesHandler.new()
593
+ when type == 'get_document' then return GetDocumentHandler.new()
594
+ when type == 'get_processed_documents' then return GetProcessedDocumentsHandler.new()
595
+ when type == 'get_collection' then return GetCollectionHandler.new()
596
+ when type == 'get_processed_collections' then return GetProcessedCollectionsHandler.new()
597
+ else return nil
598
+ end
599
+ end
600
+
601
+ def get_type_wrapper(type)
602
+ if @serializer.gettype() == 'json'
603
+ nil
604
+ end
605
+
606
+ #only for xml serializer
607
+ #if type == "update_configurations"
608
+ # return {"root" => "configurations", "added" => "configuration", "removed" => "configuration"}
609
+ #elsif type == "update_blacklist"
610
+ # return {"root" => "blacklist", "added" => "item", "removed" => "item"}
611
+ #elsif type == "update_categories"
612
+ # return {"root" => "categories", "added" => "category", "removed" => "category", "samples" => "sample"}
613
+ #elsif type == "update_queries"
614
+ # return {"root" => "queries", "added" => "query", "removed" => "query"}
615
+ #elsif type == "update_sentiment_phrases"
616
+ # return {"root" => "phrases", "added" => "phrase", "removed" => "phrase"}
617
+ #elsif type == "update_entities"
618
+ # return {"root" => "entities", "added" => "entity", "removed" => "entity"}
619
+ #elsif type == "queue_document"
620
+ # return {"root" => "document"}
621
+ #elsif type == "queue_batch_documents"
622
+ # return {"root" => "documents", "item" => "document"}
623
+ #elsif type == "queue_collection"
624
+ # return {"root" => "collection", "documents" => "document"}
625
+ #else
626
+ # return nil
627
+ #end
628
+ end
629
+
630
+ def resolve_error(status, message = nil)
631
+ if status == 400 || status == 401 || status == 402 || status == 403 || status == 406 || status == 500
632
+ onError({'status' => status, 'message' => message})
633
+ else
634
+ fail "HTTP error was found with status: #{status} and message: #{message}"
635
+ end
636
+ end
637
+
638
+ def onRequest(request)
639
+ unless @callback.nil?
640
+ @callback.onRequest(self, request)
641
+ end
642
+ end
643
+
644
+ def onResponse(response)
645
+ unless @callback.nil?
646
+ @callback.onResponse(self, response)
647
+ end
648
+ end
649
+
650
+ def onError(response)
651
+ unless @callback.nil?
652
+ @callback.onError(self, response)
653
+ end
654
+ end
655
+
656
+ def onDocsAutoResponse(response)
657
+ unless @callback.nil?
658
+ @callback.onDocsAutoResponse(self, response)
659
+ end
660
+ end
661
+
662
+ def onCollsAutoResponse(response)
663
+ unless @callback.nil?
664
+ @callback.onCollsAutoResponse(self, response)
665
+ end
666
+ end
667
+ end
668
+
669
+ class CallbackHandler
670
+ def initialize
671
+ fail 'Don\'t instantiate me!' if abstract_class?
672
+ end
673
+
674
+ private
675
+ def abstract_class?
676
+ self.class == CallbackHandler
677
+ end
678
+
679
+ def onRequest(sender, args)
680
+ fail 'Abstract method onRequest'
681
+ end
682
+
683
+ def onResponse(sender, args)
684
+ fail 'Abstract method onResponse'
685
+ end
686
+
687
+ def onError(sender, args)
688
+ fail 'Abstract method onError'
689
+ end
690
+
691
+ def onDocsAutoResponse(sender, args)
692
+ fail 'Abstract method onDocsAutoResponse'
693
+ end
694
+
695
+ def onCollsAutoResponse(sender, args)
696
+ fail 'Abstract method onCollsAutoResponse'
697
+ end
698
+ end
699
+ end