cdnconnect-api 0.2.5 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9fe3b2da7a7be09a4ea5f6102eb34ee9334a429b
4
+ data.tar.gz: 0bbaee45ba2c37405aadf16393a26ebcf7e24794
5
+ SHA512:
6
+ metadata.gz: a2f4116913c9ba0510e53b9ef636cf71c14d78e37a17560b25f99a4fb0325cec89c74846987cf15b837676958dd8671173561db2442ec87dbe456b62c5643678
7
+ data.tar.gz: d6f5598b6154100cef57e72558084a09a7657738edaaced8d7cc5446854eece8a4678958d1f71aaeec049ad11a0c703d2e98cff68349d6f6e3581d92b22f08f3
data/LICENSE CHANGED
@@ -1,202 +1,20 @@
1
-
2
- Apache License
3
- Version 2.0, January 2004
4
- http://www.apache.org/licenses/
5
-
6
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
-
8
- 1. Definitions.
9
-
10
- "License" shall mean the terms and conditions for use, reproduction,
11
- and distribution as defined by Sections 1 through 9 of this document.
12
-
13
- "Licensor" shall mean the copyright owner or entity authorized by
14
- the copyright owner that is granting the License.
15
-
16
- "Legal Entity" shall mean the union of the acting entity and all
17
- other entities that control, are controlled by, or are under common
18
- control with that entity. For the purposes of this definition,
19
- "control" means (i) the power, direct or indirect, to cause the
20
- direction or management of such entity, whether by contract or
21
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
- outstanding shares, or (iii) beneficial ownership of such entity.
23
-
24
- "You" (or "Your") shall mean an individual or Legal Entity
25
- exercising permissions granted by this License.
26
-
27
- "Source" form shall mean the preferred form for making modifications,
28
- including but not limited to software source code, documentation
29
- source, and configuration files.
30
-
31
- "Object" form shall mean any form resulting from mechanical
32
- transformation or translation of a Source form, including but
33
- not limited to compiled object code, generated documentation,
34
- and conversions to other media types.
35
-
36
- "Work" shall mean the work of authorship, whether in Source or
37
- Object form, made available under the License, as indicated by a
38
- copyright notice that is included in or attached to the work
39
- (an example is provided in the Appendix below).
40
-
41
- "Derivative Works" shall mean any work, whether in Source or Object
42
- form, that is based on (or derived from) the Work and for which the
43
- editorial revisions, annotations, elaborations, or other modifications
44
- represent, as a whole, an original work of authorship. For the purposes
45
- of this License, Derivative Works shall not include works that remain
46
- separable from, or merely link (or bind by name) to the interfaces of,
47
- the Work and Derivative Works thereof.
48
-
49
- "Contribution" shall mean any work of authorship, including
50
- the original version of the Work and any modifications or additions
51
- to that Work or Derivative Works thereof, that is intentionally
52
- submitted to Licensor for inclusion in the Work by the copyright owner
53
- or by an individual or Legal Entity authorized to submit on behalf of
54
- the copyright owner. For the purposes of this definition, "submitted"
55
- means any form of electronic, verbal, or written communication sent
56
- to the Licensor or its representatives, including but not limited to
57
- communication on electronic mailing lists, source code control systems,
58
- and issue tracking systems that are managed by, or on behalf of, the
59
- Licensor for the purpose of discussing and improving the Work, but
60
- excluding communication that is conspicuously marked or otherwise
61
- designated in writing by the copyright owner as "Not a Contribution."
62
-
63
- "Contributor" shall mean Licensor and any individual or Legal Entity
64
- on behalf of whom a Contribution has been received by Licensor and
65
- subsequently incorporated within the Work.
66
-
67
- 2. Grant of Copyright License. Subject to the terms and conditions of
68
- this License, each Contributor hereby grants to You a perpetual,
69
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
- copyright license to reproduce, prepare Derivative Works of,
71
- publicly display, publicly perform, sublicense, and distribute the
72
- Work and such Derivative Works in Source or Object form.
73
-
74
- 3. Grant of Patent License. Subject to the terms and conditions of
75
- this License, each Contributor hereby grants to You a perpetual,
76
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
- (except as stated in this section) patent license to make, have made,
78
- use, offer to sell, sell, import, and otherwise transfer the Work,
79
- where such license applies only to those patent claims licensable
80
- by such Contributor that are necessarily infringed by their
81
- Contribution(s) alone or by combination of their Contribution(s)
82
- with the Work to which such Contribution(s) was submitted. If You
83
- institute patent litigation against any entity (including a
84
- cross-claim or counterclaim in a lawsuit) alleging that the Work
85
- or a Contribution incorporated within the Work constitutes direct
86
- or contributory patent infringement, then any patent licenses
87
- granted to You under this License for that Work shall terminate
88
- as of the date such litigation is filed.
89
-
90
- 4. Redistribution. You may reproduce and distribute copies of the
91
- Work or Derivative Works thereof in any medium, with or without
92
- modifications, and in Source or Object form, provided that You
93
- meet the following conditions:
94
-
95
- (a) You must give any other recipients of the Work or
96
- Derivative Works a copy of this License; and
97
-
98
- (b) You must cause any modified files to carry prominent notices
99
- stating that You changed the files; and
100
-
101
- (c) You must retain, in the Source form of any Derivative Works
102
- that You distribute, all copyright, patent, trademark, and
103
- attribution notices from the Source form of the Work,
104
- excluding those notices that do not pertain to any part of
105
- the Derivative Works; and
106
-
107
- (d) If the Work includes a "NOTICE" text file as part of its
108
- distribution, then any Derivative Works that You distribute must
109
- include a readable copy of the attribution notices contained
110
- within such NOTICE file, excluding those notices that do not
111
- pertain to any part of the Derivative Works, in at least one
112
- of the following places: within a NOTICE text file distributed
113
- as part of the Derivative Works; within the Source form or
114
- documentation, if provided along with the Derivative Works; or,
115
- within a display generated by the Derivative Works, if and
116
- wherever such third-party notices normally appear. The contents
117
- of the NOTICE file are for informational purposes only and
118
- do not modify the License. You may add Your own attribution
119
- notices within Derivative Works that You distribute, alongside
120
- or as an addendum to the NOTICE text from the Work, provided
121
- that such additional attribution notices cannot be construed
122
- as modifying the License.
123
-
124
- You may add Your own copyright statement to Your modifications and
125
- may provide additional or different license terms and conditions
126
- for use, reproduction, or distribution of Your modifications, or
127
- for any such Derivative Works as a whole, provided Your use,
128
- reproduction, and distribution of the Work otherwise complies with
129
- the conditions stated in this License.
130
-
131
- 5. Submission of Contributions. Unless You explicitly state otherwise,
132
- any Contribution intentionally submitted for inclusion in the Work
133
- by You to the Licensor shall be under the terms and conditions of
134
- this License, without any additional terms or conditions.
135
- Notwithstanding the above, nothing herein shall supersede or modify
136
- the terms of any separate license agreement you may have executed
137
- with Licensor regarding such Contributions.
138
-
139
- 6. Trademarks. This License does not grant permission to use the trade
140
- names, trademarks, service marks, or product names of the Licensor,
141
- except as required for reasonable and customary use in describing the
142
- origin of the Work and reproducing the content of the NOTICE file.
143
-
144
- 7. Disclaimer of Warranty. Unless required by applicable law or
145
- agreed to in writing, Licensor provides the Work (and each
146
- Contributor provides its Contributions) on an "AS IS" BASIS,
147
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
- implied, including, without limitation, any warranties or conditions
149
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
- PARTICULAR PURPOSE. You are solely responsible for determining the
151
- appropriateness of using or redistributing the Work and assume any
152
- risks associated with Your exercise of permissions under this License.
153
-
154
- 8. Limitation of Liability. In no event and under no legal theory,
155
- whether in tort (including negligence), contract, or otherwise,
156
- unless required by applicable law (such as deliberate and grossly
157
- negligent acts) or agreed to in writing, shall any Contributor be
158
- liable to You for damages, including any direct, indirect, special,
159
- incidental, or consequential damages of any character arising as a
160
- result of this License or out of the use or inability to use the
161
- Work (including but not limited to damages for loss of goodwill,
162
- work stoppage, computer failure or malfunction, or any and all
163
- other commercial damages or losses), even if such Contributor
164
- has been advised of the possibility of such damages.
165
-
166
- 9. Accepting Warranty or Additional Liability. While redistributing
167
- the Work or Derivative Works thereof, You may choose to offer,
168
- and charge a fee for, acceptance of support, warranty, indemnity,
169
- or other liability obligations and/or rights consistent with this
170
- License. However, in accepting such obligations, You may act only
171
- on Your own behalf and on Your sole responsibility, not on behalf
172
- of any other Contributor, and only if You agree to indemnify,
173
- defend, and hold each Contributor harmless for any liability
174
- incurred by, or claims asserted against, such Contributor by reason
175
- of your accepting any such warranty or additional liability.
176
-
177
- END OF TERMS AND CONDITIONS
178
-
179
- APPENDIX: How to apply the Apache License to your work.
180
-
181
- To apply the Apache License to your work, attach the following
182
- boilerplate notice, with the fields enclosed by brackets "[]"
183
- replaced with your own identifying information. (Don't include
184
- the brackets!) The text should be enclosed in the appropriate
185
- comment syntax for the file format. We also recommend that a
186
- file or class name and description of purpose be included on the
187
- same "printed page" as the copyright notice for easier
188
- identification within third-party archives.
189
-
190
- Copyright [yyyy] [name of copyright owner]
191
-
192
- Licensed under the Apache License, Version 2.0 (the "License");
193
- you may not use this file except in compliance with the License.
194
- You may obtain a copy of the License at
195
-
196
- http://www.apache.org/licenses/LICENSE-2.0
197
-
198
- Unless required by applicable law or agreed to in writing, software
199
- distributed under the License is distributed on an "AS IS" BASIS,
200
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
- See the License for the specific language governing permissions and
202
- limitations under the License.
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # CDN Connect API Ruby Client, v0.2.5
1
+ # CDN Connect API Ruby Client, v0.3.0
2
2
 
3
3
  CDN Connect makes it easier to manage production assets for teams of developers and designers, all while serving files from a fast content delivery network. Features include image optimization, resizing, cropping, filters, changing output formats, convert to WebP image format, etc. The CDN Connect API Ruby Client makes it easier to upload files and interact with the API with only a few lines of code.
4
4
 
@@ -16,6 +16,7 @@ require 'faraday'
16
16
  require 'faraday/utils'
17
17
  require 'signet/oauth_2/client'
18
18
  require 'cdnconnect_api/response'
19
+ require 'logger'
19
20
 
20
21
 
21
22
  module CDNConnect
@@ -25,7 +26,7 @@ module CDNConnect
25
26
  class APIClient
26
27
 
27
28
  @@application_name = 'cdnconnect-api-ruby'
28
- @@application_version = '0.2.5'
29
+ @@application_version = '0.3.0'
29
30
  @@user_agent = @@application_name + ' v' + @@application_version
30
31
  @@api_host = 'https://api.cdnconnect.com'
31
32
  @@api_version = 'v1'
@@ -68,40 +69,48 @@ module CDNConnect
68
69
  # - <code>:app_host</code> -
69
70
  # The CDN Connect App host. For example, demo.cdnconnect.com is a CDN Connect
70
71
  # app host. The app host should not include https://, http:// or a URL path.
71
- # - <code>:debug</code> -
72
- # Print out any debugging information. Default is false.
72
+ # - <code>:log_device</code> -
73
+ # Ruby Logger logdev argument in Logger.new(logdev). Defaults to STDOUT.
73
74
  def initialize(options={})
74
- # Normalize key to String to allow indifferent access.
75
- options = options.inject({}) { |accu, (k, v)| accu[k.to_s] = v; accu }
76
-
77
- # Initialize all of the options
78
- @client_id = options["client_id"]
79
- @client_secret = options["client_secret"]
80
- @scope = options["scope"]
81
- @state = options["state"]
82
- @code = options["code"]
83
- @redirect_uri = options["redirect_uri"]
84
- options["access_token"] = options["access_token"] || options["api_key"] # both work
85
- @access_token = options["access_token"]
86
- @app_host = options["app_host"]
87
- @debug = options["debug"] || false
88
- @prefetched_upload_urls = {}
89
- @upload_queue = {}
90
- @failed_uploads = []
91
-
92
- if options["api_key"] != nil and options["app_host"] == nil
93
- raise ArgumentError, 'app_host option required when using api_key option'
94
- end
75
+ # Normalize key to String to allow indifferent access.
76
+ options = options.inject({}) { |accu, (k, v)| accu[k.to_s] = v; accu }
77
+
78
+ # Initialize all of the options
79
+ @client_id = options["client_id"]
80
+ @client_secret = options["client_secret"]
81
+ @scope = options["scope"]
82
+ @state = options["state"]
83
+ @code = options["code"]
84
+ @redirect_uri = options["redirect_uri"]
85
+ options["access_token"] = options["access_token"] || options["api_key"] # both work
86
+ @access_token = options["access_token"]
87
+ @app_host = options["app_host"]
88
+ @@api_host = options["api_host"] || @@api_host
89
+ @prefetched_upload_urls = {}
90
+ @upload_queue = {}
91
+ @failed_uploads = []
92
+
93
+ log_device = options["log_device"] || STDOUT
94
+ @logger = Logger.new(log_device, 10, 1024000)
95
+ @logger.sev_threshold = options["log_sev_threshold"] || Logger::WARN
96
+
97
+ if options["api_key"] != nil and options["app_host"] == nil
98
+ err_msg = 'app_host option required when using api_key option'
99
+ @logger.error(err_msg)
100
+ raise ArgumentError, err_msg
101
+ end
95
102
 
96
- # Create the OAuth2 client which will be used to authorize the requests
97
- @client = Signet::OAuth2::Client.new(:client_id => client_id,
98
- :client_secret => @client_secret,
99
- :scope => @scope,
100
- :state => @state,
101
- :code => @code,
102
- :redirect_uri => @redirect_uri,
103
- :access_token => @access_token)
104
- return self
103
+ @logger.debug("#{@@user_agent}, #{@@api_host}")
104
+
105
+ # Create the OAuth2 client which will be used to authorize the requests
106
+ @client = Signet::OAuth2::Client.new(:client_id => client_id,
107
+ :client_secret => @client_secret,
108
+ :scope => @scope,
109
+ :state => @state,
110
+ :code => @code,
111
+ :redirect_uri => @redirect_uri,
112
+ :access_token => @access_token)
113
+ return self
105
114
  end
106
115
 
107
116
 
@@ -183,40 +192,38 @@ module CDNConnect
183
192
 
184
193
  # Get the destination_path in the list of upload queues
185
194
  destination_path = @upload_queue.keys[0]
186
- if @debug
187
- puts "Upload destination_path: #{destination_path}"
188
- end
195
+ @logger.debug("destination_path: #{destination_path}")
189
196
 
190
197
  # Check if we have a prefetched upload url before requesting a new one
191
198
  upload_url = get_prefetched_upload_url(destination_path)
192
199
  if upload_url == nil
193
- # We do not already have an upload url created. The first upload request
194
- # will need to make a request for an upload url. After the first upload
195
- # each upload response will also include a new upload url which can be used
196
- # for the next upload when uploading to the same folder.
197
- upload_url_response = self.get_upload_url(destination_path)
198
- if upload_url_response.is_error
199
- return upload_url_response
200
- end
201
- upload_url = upload_url_response.get_result('upload_url')
202
- if @debug
203
- puts "Received upload url"
204
- end
200
+ # We do not already have an upload url created. The first upload request
201
+ # will need to make a request for an upload url. After the first upload
202
+ # each upload response will also include a new upload url which can be used
203
+ # for the next upload when uploading to the same folder.
204
+ upload_url_response = self.get_upload_url(destination_path)
205
+ if upload_url_response.is_error
206
+ return upload_url_response
207
+ end
208
+ upload_url = upload_url_response.get_result('upload_url')
209
+ @logger.debug("Received new upload url")
210
+ else
211
+ @logger.debug("Use prefetched upload url")
205
212
  end
206
213
 
207
214
  # Build the data that gets sent in the POST request
208
- post_data = build_post_data(destination_path,
209
- destination_file_name = options[:destination_file_name],
210
- max_files_per_request = 25,
211
- max_request_size = 25165824,
212
- queue_processing = options.fetch(:queue_processing, false),
213
- webhook_url = options[:webhook_url],
214
- webhook_format = options[:webhook_format])
215
+ post_data = build_post_data(:destination_path => destination_path,
216
+ :destination_file_name => options[:destination_file_name],
217
+ :queue_processing => options.fetch(:queue_processing, true),
218
+ :webhook_url => options[:webhook_url],
219
+ :webhook_format => options[:webhook_format])
215
220
 
216
221
  # Build the request to send to the API
217
222
  # Uses the Faraday: https://github.com/lostisland/faraday
218
223
  conn = Faraday.new() do |req|
219
- req.headers['User-Agent'] = @@user_agent
224
+ req.headers = {
225
+ 'User-Agent' => @@user_agent
226
+ }
220
227
  req.request :multipart
221
228
  req.adapter :net_http
222
229
  end
@@ -226,10 +233,8 @@ module CDNConnect
226
233
 
227
234
  # w00t! Convert the http response into APIResponse and see what's up
228
235
  upload_response = APIResponse.new(http_response)
229
- if @debug
230
- for msg in upload_response.msgs
231
- puts "Upload " + msg["status"] + ": " + msg["text"]
232
- end
236
+ for msg in upload_response.msgs
237
+ @logger.info("Upload " + msg["status"] + ": " + msg["text"])
233
238
  end
234
239
 
235
240
  # merge the two together so we build one awesome response
@@ -239,13 +244,19 @@ module CDNConnect
239
244
  # Read the response and see what we got
240
245
  if upload_response.is_server_error
241
246
  # There was a server error, empty the active upload queue
242
- failed_upload_attempt(destination_path)
243
-
247
+ failed_upload_attempt(destination_path)
248
+ @logger.error(upload_response.body)
249
+
250
+ # put the upload url back in the list
251
+ # of prefetched urls so it can be reused
252
+ set_prefetched_upload_url(destination_path, upload_url)
244
253
  else
245
254
  # successful upload, clear out the active upload queue
246
255
  # and remove uploaded files from the upload queue
247
256
  successful_upload_attempt(destination_path)
248
257
 
258
+ @logger.info("Successful upload")
259
+
249
260
  # an upload response also contains a new upload url.
250
261
  # Save it for the next upload to the same destination.
251
262
  set_prefetched_upload_url(destination_path,
@@ -261,10 +272,14 @@ module CDNConnect
261
272
  ##
262
273
  # Build the POST data that gets sent in the request
263
274
  # @!visibility private
264
- def build_post_data(destination_path, destination_file_name = nil, max_files_per_request = 25, max_request_size = 25165824, queue_processing = false, webhook_url = nil, webhook_format = nil)
275
+ def build_post_data(options)
265
276
  # @active_uploads will hold all of the upload keys
266
277
  # which are actively being uploaded.
267
278
  @active_uploads = []
279
+
280
+ # set defaults
281
+ max_files_per_request = options[:max_files_per_request] || 25
282
+ max_request_size = options[:max_request_size] || 25165824
268
283
 
269
284
  # post_data will contain all of the data that gets sent
270
285
  post_data = {}
@@ -274,18 +289,20 @@ module CDNConnect
274
289
 
275
290
  # the set what the file name will be. By default it will be named the same as
276
291
  # the uploaded file. This will only work for single file uploads.
277
- post_data[:destination_file_name] = destination_file_name
292
+ post_data[:destination_file_name] = options[:destination_file_name]
278
293
 
279
294
  # Processing of the data can be queued. However, an `queue_processing` response
280
295
  # will not contain any information about the data uploaded.
281
- post_data[:queue_processing] = queue_processing
296
+ if options[:queue_processing] == true
297
+ post_data[:queue_processing] = 'true'
298
+ end
282
299
 
283
300
  # send with the post data the webhook_url if there is one
284
- if webhook_url != nil
285
- post_data[:webhook_url] = webhook_url
301
+ if options[:webhook_url] != nil
302
+ post_data[:webhook_url] = options[:webhook_url]
286
303
  # send in the webhook_format, but defaults to json if nothing sent
287
- if webhook_format != nil
288
- post_data[:webhook_format] = webhook_format
304
+ if options[:webhook_format] != nil
305
+ post_data[:webhook_format] = options[:webhook_format]
289
306
  end
290
307
  end
291
308
 
@@ -302,19 +319,21 @@ module CDNConnect
302
319
  total_files = 0
303
320
 
304
321
  # Add each source file in the queue to the request as multipart-post data
305
- @upload_queue[destination_path].each_pair do |source_file_path, value|
322
+ @upload_queue[ options[:destination_path] ].each_pair do |source_file_path, value|
306
323
 
307
324
  # Figure out how large this file is
308
325
  file_size = File.stat(source_file_path).size
309
326
 
327
+ @logger.debug(" - #{source_file_path} (#{human_file_size(file_size)})")
328
+
310
329
  # Add this file's size to the overall request size total
311
330
  total_request_size += file_size
312
331
 
313
332
  # Increment the upload attempts for this file
314
- @upload_queue[destination_path][source_file_path]['attempts'] += 1
333
+ @upload_queue[ options[:destination_path] ][source_file_path]['attempts'] += 1
315
334
 
316
335
  # Set that this file is actively being uploaded
317
- @upload_queue[destination_path][source_file_path]['active'] = true
336
+ @upload_queue[ options[:destination_path] ][source_file_path]['active'] = true
318
337
 
319
338
  # Add the source file it to the request's post data
320
339
  post_data[:file].push( Faraday::UploadIO.new(source_file_path, mime_type) )
@@ -324,17 +343,17 @@ module CDNConnect
324
343
  if total_request_size > max_request_size
325
344
  # If the total request size is larger than the max
326
345
  # then do not add any more files
346
+ @logger.debug(" - Reached max request size per request")
327
347
  break
328
348
  elsif total_files >= max_files_per_request
329
349
  # only add XX files per post request
330
350
  # any left over will be picked up in the next upload
351
+ @logger.debug(" - Reached max files per request")
331
352
  break
332
353
  end
333
354
  end
334
355
 
335
- if @debug
336
- puts "Upload request, File Count: #{total_files}, File Size: #{total_request_size} bytes"
337
- end
356
+ @logger.info(" - Upload, File Count: #{total_files}, File Size: #{human_file_size(total_request_size)}")
338
357
 
339
358
  return post_data
340
359
  end
@@ -362,9 +381,8 @@ module CDNConnect
362
381
  # If it was attempted too many times then remove it from the queue.
363
382
  # @!visibility private
364
383
  def failed_upload_attempt(destination_path)
365
- if @debug
366
- puts "failed_upload_attempt: #{destination_path}"
367
- end
384
+ @logger.error("failed_upload_attempt: #{destination_path}")
385
+
368
386
  # Loop through each active upload for the destination folder url
369
387
  if @upload_queue.has_key?(destination_path)
370
388
  # Loop through each file for this destination folder
@@ -550,10 +568,10 @@ module CDNConnect
550
568
  # already have an upload url ready to go for the folder we're uploading to.
551
569
  # @!visibility private
552
570
  def get_prefetched_upload_url(destination_path)
553
- # Build a unique key for the folder which was used to save an new upload url
554
- rtn_url = @prefetched_upload_urls[destination_path]
555
- @prefetched_upload_urls[destination_path] = nil
556
- return rtn_url
571
+ # Build a unique key for the folder which was used to save an new upload url
572
+ rtn_url = @prefetched_upload_urls[destination_path]
573
+ @prefetched_upload_urls[destination_path] = nil
574
+ return rtn_url
557
575
  end
558
576
 
559
577
 
@@ -562,8 +580,8 @@ module CDNConnect
562
580
  # for the next upload to this folder.
563
581
  # @!visibility private
564
582
  def set_prefetched_upload_url(destination_path, upload_url)
565
- # Build a unique key for the folder to save an new upload url value to
566
- @prefetched_upload_urls[destination_path] = upload_url
583
+ # Build a unique key for the folder to save an new upload url value to
584
+ @prefetched_upload_urls[destination_path] = upload_url
567
585
  end
568
586
 
569
587
 
@@ -573,16 +591,26 @@ module CDNConnect
573
591
  # used to eliminate the need to do seperate requests for an upload url.
574
592
  # @!visibility private
575
593
  def get_upload_url(destination_path)
576
- api_path = destination_path + '/upload.json'
577
-
578
- i = 1
579
- begin
580
- response = get(api_path)
581
- if not response.is_server_error or i > 2
582
- return response
594
+ if destination_path == "/"
595
+ destination_path = ""
583
596
  end
584
- i += 1
585
- end while i <= 3
597
+ upload_id = Random.new.rand(1_000_000..9_999_999)
598
+ api_path = "#{destination_path}/upload-#{upload_id}.json"
599
+
600
+ @logger.debug("get_upload_url: #{api_path}")
601
+
602
+ i = 1
603
+ begin
604
+ response = get(api_path)
605
+ if not response.is_server_error
606
+ return response
607
+ elsif i > 2
608
+ @logger.error("Too many get_upload_url attempts")
609
+ return response
610
+ end
611
+ @logger.error(response.body)
612
+ i += 1
613
+ end while i <= 3
586
614
  end
587
615
 
588
616
 
@@ -660,7 +688,7 @@ module CDNConnect
660
688
  # @param data [Hash] Data which will be placed in the GET request's querystring. (Optional)
661
689
  # @return [APIResponse] A response object with helper methods to read the response.
662
690
  def get(api_path, data={})
663
- fetch(:api_path => api_path, :method => 'GET', :data => data)
691
+ fetch(:api_path => api_path, :method => 'GET', :data => data)
664
692
  end
665
693
 
666
694
 
@@ -672,7 +700,7 @@ module CDNConnect
672
700
  # @param data [Hash] Data which will be sent in the POST request.
673
701
  # @return [APIResponse] A response object with helper methods to read the response.
674
702
  def post(api_path, data)
675
- fetch(:api_path => api_path, :method => 'POST', :data => data)
703
+ fetch(:api_path => api_path, :method => 'POST', :data => data)
676
704
  end
677
705
 
678
706
 
@@ -684,7 +712,7 @@ module CDNConnect
684
712
  # @param data [Hash] Data which will be sent in the PUT request.
685
713
  # @return [APIResponse] A response object with helper methods to read the response.
686
714
  def put(api_path, data)
687
- fetch(:api_path => api_path, :method => 'PUT', :data => data)
715
+ fetch(:api_path => api_path, :method => 'PUT', :data => data)
688
716
  end
689
717
 
690
718
 
@@ -695,7 +723,7 @@ module CDNConnect
695
723
  # @param api_path [String] The API path to send the DELETE request to.
696
724
  # @return [APIResponse] A response object with helper methods to read the response.
697
725
  def delete(api_path)
698
- fetch(:api_path => api_path, :method => 'DELETE')
726
+ fetch(:api_path => api_path, :method => 'DELETE')
699
727
  end
700
728
 
701
729
 
@@ -704,26 +732,26 @@ module CDNConnect
704
732
  # and make it all pretty before firing off the request to the API.
705
733
  # @!visibility private
706
734
  def prepare(options={})
707
- if options[:api_path] == nil
708
- raise ArgumentError, 'missing api path'
709
- end
735
+ if options[:api_path] == nil
736
+ raise ArgumentError, 'missing api path'
737
+ end
710
738
 
711
- options[:headers] = { 'User-Agent' => @@user_agent }
712
- options[:uri] = "#{@@api_host}/#{@@api_version}/#{@app_host}#{options[:api_path]}"
739
+ options[:headers] = { 'User-Agent' => @@user_agent }
740
+ options[:uri] = "#{@@api_host}/#{@@api_version}/#{@app_host}#{options[:api_path]}"
713
741
 
714
- options[:method] = options[:method] || 'GET'
742
+ options[:method] = options[:method] || 'GET'
715
743
 
716
- if options[:method] == 'GET' and options[:data] != nil and options[:data].length > 0
717
- require "addressable/uri"
718
- uri = Addressable::URI.new
719
- uri.query_values = options[:data]
720
- options[:uri] = "#{options[:uri]}?#{uri.query}"
721
- options[:data] = nil
722
- end
744
+ if options[:method] == 'GET' and options[:data] != nil and options[:data].length > 0
745
+ require "addressable/uri"
746
+ uri = Addressable::URI.new
747
+ uri.query_values = options[:data]
748
+ options[:uri] = "#{options[:uri]}?#{uri.query}"
749
+ options[:data] = nil
750
+ end
723
751
 
724
- options[:url] = options[:uri]
725
-
726
- options
752
+ options[:url] = options[:uri]
753
+
754
+ options
727
755
  end
728
756
 
729
757
 
@@ -731,37 +759,30 @@ module CDNConnect
731
759
  # Guts of an authorized request. Do not call this directly.
732
760
  # @!visibility private
733
761
  def fetch(options={})
734
- # Prepare the data to be shipped in the request
735
- options = prepare(options)
762
+ # Prepare the data to be shipped in the request
763
+ options = prepare(options)
736
764
 
737
- if @debug
738
- puts options[:method] + ': ' + options[:uri]
739
- end
765
+ @logger.debug(options[:method] + ': ' + options[:uri])
740
766
 
741
- begin
742
- # Send the request and get the response
743
- options[:body] = options[:data]
744
- http_response = @client.fetch_protected_resource(options)
767
+ begin
768
+ # Send the request and get the response
769
+ options[:body] = options[:data]
770
+ http_response = @client.fetch_protected_resource(options)
745
771
 
746
- # Return the API response
747
- api_response = APIResponse.new(http_response)
772
+ # Return the API response
773
+ api_response = APIResponse.new(http_response)
748
774
 
749
- if @debug
750
775
  for msg in api_response.msgs
751
- puts msg["status"] + ": " + msg["text"]
776
+ @logger.debug(msg["status"] + ": " + msg["text"])
752
777
  end
753
- end
754
778
 
755
- return api_response
756
- rescue Signet::AuthorizationError => authorization_error
757
- # whoopsy doodle. Probably an incorrect API Key or App Host.
758
- # Validate your authorization info.
759
- if @debug
760
- puts authorization_error
779
+ return api_response
780
+ rescue Signet::AuthorizationError => authorization_error
781
+ # whoopsy doodle. Probably an incorrect API Key or App Host.
782
+ # Validate your authorization info.
783
+ @logger.error(authorization_error)
784
+ return APIResponse.new(authorization_error.response)
761
785
  end
762
- return APIResponse.new(authorization_error.response)
763
- end
764
-
765
786
  end
766
787
 
767
788
 
@@ -772,7 +793,7 @@ module CDNConnect
772
793
  #
773
794
  # @return [String]
774
795
  def client_id
775
- @client_id
796
+ @client_id
776
797
  end
777
798
 
778
799
 
@@ -784,7 +805,7 @@ module CDNConnect
784
805
  #
785
806
  # @return [String]
786
807
  def client_secret
787
- @client_secret
808
+ @client_secret
788
809
  end
789
810
 
790
811
 
@@ -795,7 +816,7 @@ module CDNConnect
795
816
  #
796
817
  # @return [String]
797
818
  def scope
798
- @scope
819
+ @scope
799
820
  end
800
821
 
801
822
 
@@ -806,7 +827,7 @@ module CDNConnect
806
827
  #
807
828
  # @return [String]
808
829
  def state
809
- @state
830
+ @state
810
831
  end
811
832
 
812
833
 
@@ -814,7 +835,7 @@ module CDNConnect
814
835
  # OAuth2 value. The authorization code received from the authorization server.
815
836
  # @return [String]
816
837
  def code
817
- @code
838
+ @code
818
839
  end
819
840
 
820
841
 
@@ -822,7 +843,7 @@ module CDNConnect
822
843
  # OAuth2 value. The redirection URI used in the initial request.
823
844
  # @return [String]
824
845
  def redirect_uri
825
- @redirect_uri
846
+ @redirect_uri
826
847
  end
827
848
 
828
849
 
@@ -832,7 +853,7 @@ module CDNConnect
832
853
  #
833
854
  # @return [String]
834
855
  def access_token
835
- @access_token
856
+ @access_token
836
857
  end
837
858
 
838
859
 
@@ -842,7 +863,7 @@ module CDNConnect
842
863
  #
843
864
  # @return [String]
844
865
  def app_host
845
- @app_host
866
+ @app_host
846
867
  end
847
868
 
848
869
 
@@ -852,7 +873,7 @@ module CDNConnect
852
873
  # @return [Hash]
853
874
  # @!visibility private
854
875
  def upload_queue
855
- @upload_queue
876
+ @upload_queue
856
877
  end
857
878
 
858
879
  ##
@@ -860,7 +881,14 @@ module CDNConnect
860
881
  #
861
882
  # @return [Array]
862
883
  def failed_uploads
863
- @failed_uploads
884
+ @failed_uploads
885
+ end
886
+
887
+ def human_file_size(bytes)
888
+ units = %w{B KB MB GB TB}
889
+ e = (Math.log(bytes)/Math.log(1024)).floor
890
+ s = "%.2f" % (bytes.to_f / 1024**e)
891
+ s.sub(/\.?0*$/, units[e])
864
892
  end
865
893
 
866
894
  end
@@ -28,9 +28,11 @@ module CDNConnect
28
28
  if http_response != nil
29
29
  @status = http_response.status
30
30
  @data = nil
31
+ @body = nil
31
32
  else
32
33
  @status = 0
33
34
  @data = {"results" => {}, "msgs" => []}
35
+ @body = nil
34
36
  end
35
37
  return self
36
38
  end
@@ -69,9 +71,9 @@ module CDNConnect
69
71
  # @return [String]
70
72
  def body
71
73
  if @http_response != nil
72
- return @http_response.body
74
+ @body = @http_response.body
73
75
  end
74
- nil
76
+ @body
75
77
  end
76
78
 
77
79
 
@@ -170,7 +172,15 @@ module CDNConnect
170
172
  @data = updating_response.data
171
173
  return self
172
174
  end
173
-
175
+
176
+ if updating_response.body != nil
177
+ if @body == nil
178
+ @body = updating_response.body
179
+ else
180
+ @body += updating_response.body
181
+ end
182
+ end
183
+
174
184
  @data['msgs'] += updating_response.msgs
175
185
 
176
186
  if updating_response.files != nil
@@ -195,7 +205,7 @@ module CDNConnect
195
205
  ##
196
206
  # @return [bool]
197
207
  def is_success
198
- status >= 200 and status < 300 and not has_errors
208
+ @body != nil and status >= 200 and status < 300 and not has_errors
199
209
  end
200
210
 
201
211
  ##
metadata CHANGED
@@ -1,114 +1,97 @@
1
- --- !ruby/object:Gem::Specification
1
+ --- !ruby/object:Gem::Specification
2
2
  name: cdnconnect-api
3
- version: !ruby/object:Gem::Version
4
- hash: 29
5
- prerelease:
6
- segments:
7
- - 0
8
- - 2
9
- - 5
10
- version: 0.2.5
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
11
5
  platform: ruby
12
- authors:
6
+ authors:
13
7
  - Adam Bradley
14
8
  autorequire:
15
9
  bindir: bin
16
10
  cert_chain: []
17
-
18
- date: 2013-08-04 00:00:00 Z
19
- dependencies:
20
- - !ruby/object:Gem::Dependency
11
+ date: 2013-09-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
21
14
  name: faraday
22
- prerelease: false
23
- requirement: &id001 !ruby/object:Gem::Requirement
24
- none: false
25
- requirements:
26
- - - ">="
27
- - !ruby/object:Gem::Version
28
- hash: 49
29
- segments:
30
- - 0
31
- - 8
32
- - 7
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
33
19
  version: 0.8.7
34
20
  type: :runtime
35
- version_requirements: *id001
36
- - !ruby/object:Gem::Dependency
37
- name: signet
38
21
  prerelease: false
39
- requirement: &id002 !ruby/object:Gem::Requirement
40
- none: false
41
- requirements:
42
- - - ">="
43
- - !ruby/object:Gem::Version
44
- hash: 5
45
- segments:
46
- - 0
47
- - 4
48
- - 5
49
- version: 0.4.5
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: 0.8.7
27
+ - !ruby/object:Gem::Dependency
28
+ name: signet
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: 0.5.0
50
34
  type: :runtime
51
- version_requirements: *id002
52
- - !ruby/object:Gem::Dependency
53
- name: json
54
35
  prerelease: false
55
- requirement: &id003 !ruby/object:Gem::Requirement
56
- none: false
57
- requirements:
58
- - - ">="
59
- - !ruby/object:Gem::Version
60
- hash: 3
61
- segments:
62
- - 0
63
- version: "0"
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: 0.5.0
41
+ - !ruby/object:Gem::Dependency
42
+ name: json
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '>='
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
64
48
  type: :runtime
65
- version_requirements: *id003
66
- description: CDN Connect makes it easier to manage production assets for teams of developers and designers, all while serving files from a fast content delivery network. Features include image optimization, resizing, cropping, filters, etc. The CDN Connect API Ruby Client makes it easier to upload files and interact with the API. Most interactions with CDN Connect APIs require users to authorize applications via OAuth 2.0. This library simplifies the communication with CDN Connect even further allowing you to easily upload files and get information with only a few lines of code.
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '>='
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: CDN Connect makes it easier to manage production assets for teams of
56
+ developers and designers, all while serving files from a fast content delivery network.
57
+ Features include image optimization, resizing, cropping, filters, etc. The CDN Connect
58
+ API Ruby Client makes it easier to upload files and interact with the API. Most
59
+ interactions with CDN Connect APIs require users to authorize applications via OAuth
60
+ 2.0. This library simplifies the communication with CDN Connect even further allowing
61
+ you to easily upload files and get information with only a few lines of code.
67
62
  email: developer@cdnconnect.com
68
63
  executables: []
69
-
70
64
  extensions: []
71
-
72
- extra_rdoc_files:
65
+ extra_rdoc_files:
73
66
  - README.md
74
- files:
67
+ files:
75
68
  - lib/cdnconnect_api.rb
76
69
  - lib/cdnconnect_api/response.rb
77
70
  - LICENSE
78
71
  - README.md
79
72
  homepage: http://www.cdnconnect.com/
80
- licenses: []
81
-
73
+ licenses:
74
+ - MIT
75
+ metadata: {}
82
76
  post_install_message:
83
77
  rdoc_options: []
84
-
85
- require_paths:
78
+ require_paths:
86
79
  - lib
87
- required_ruby_version: !ruby/object:Gem::Requirement
88
- none: false
89
- requirements:
90
- - - ">="
91
- - !ruby/object:Gem::Version
92
- hash: 3
93
- segments:
94
- - 0
95
- version: "0"
96
- required_rubygems_version: !ruby/object:Gem::Requirement
97
- none: false
98
- requirements:
99
- - - ">="
100
- - !ruby/object:Gem::Version
101
- hash: 3
102
- segments:
103
- - 0
104
- version: "0"
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - '>='
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - '>='
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
105
90
  requirements: []
106
-
107
91
  rubyforge_project:
108
- rubygems_version: 1.8.24
92
+ rubygems_version: 2.0.0
109
93
  signing_key:
110
- specification_version: 3
94
+ specification_version: 4
111
95
  summary: Package Summary
112
96
  test_files: []
113
-
114
97
  has_rdoc: