condo 1.0.4 → 1.0.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (32) hide show
  1. checksums.yaml +7 -0
  2. data/README.textile +133 -133
  3. data/app/assets/javascripts/condo.js +9 -6
  4. data/app/assets/javascripts/condo/amazon.js +403 -406
  5. data/app/assets/javascripts/condo/condo.js +184 -0
  6. data/app/assets/javascripts/condo/config.js +69 -80
  7. data/app/assets/javascripts/condo/google.js +338 -255
  8. data/app/assets/javascripts/condo/md5/hash.worker.emulator.js +23 -23
  9. data/app/assets/javascripts/condo/md5/hash.worker.js +11 -11
  10. data/app/assets/javascripts/condo/md5/hasher.js +119 -100
  11. data/app/assets/javascripts/condo/md5/spark-md5.js +276 -161
  12. data/app/assets/javascripts/condo/rackspace.js +326 -329
  13. data/app/assets/javascripts/condo/{abstract-md5.js.erb → services/abstract-md5.js.erb} +86 -93
  14. data/app/assets/javascripts/condo/{base64.js → services/base64.js} +2 -10
  15. data/app/assets/javascripts/condo/services/broadcaster.js +26 -0
  16. data/app/assets/javascripts/condo/services/uploader.js +302 -0
  17. data/app/assets/javascripts/core/core.js +4 -0
  18. data/app/assets/javascripts/core/services/1-safe-apply.js +17 -0
  19. data/app/assets/javascripts/core/services/2-messaging.js +171 -0
  20. data/lib/condo.rb +269 -269
  21. data/lib/condo/configuration.rb +137 -139
  22. data/lib/condo/errors.rb +8 -8
  23. data/lib/condo/strata/amazon_s3.rb +301 -301
  24. data/lib/condo/strata/google_cloud_storage.rb +315 -314
  25. data/lib/condo/strata/rackspace_cloud_files.rb +245 -223
  26. data/lib/condo/version.rb +1 -1
  27. metadata +21 -44
  28. data/app/assets/javascripts/condo/broadcaster.js +0 -60
  29. data/app/assets/javascripts/condo/controller.js +0 -194
  30. data/app/assets/javascripts/condo/uploader.js +0 -310
  31. data/test/dummy/db/test.sqlite3 +0 -0
  32. data/test/dummy/log/test.log +0 -25
@@ -1,140 +1,138 @@
1
- require 'singleton'
2
-
3
- module Condo
4
-
5
- class Configuration
6
- include Singleton
7
-
8
- @@callbacks = {
9
- #:resident_id # Must be defined by the including class
10
- :bucket_name => proc {"#{Rails.application.class.parent_name}#{instance_eval @@callbacks[:resident_id]}"},
11
- :object_key => proc {
12
- if params[:file_path]
13
- params[:file_path] + params[:file_name]
14
- else
15
- params[:file_name]
16
- end
17
- },
18
- :object_options => proc {{:permissions => :private}},
19
- :pre_validation => proc {true}, # To respond with errors use: lambda {return false, {:errors => {:param_name => 'wtf are you doing?'}}}
20
- :sanitize_filename => proc {
21
- params[:file_name].tap do |filename|
22
- filename.gsub!(/^.*(\\|\/)/, '') # get only the filename (just in case)
23
- filename.gsub!(/[^\w\.\-]/,'_') # replace all non alphanumeric or periods with underscore
24
- end
25
- },
26
- :sanitize_filepath => proc {
27
- params[:file_path].tap do |filepath|
28
- filepath.gsub!(/[^\w\.\-\/]/,'_') # replace all non alphanumeric or periods with underscore
29
- end
30
- }
31
- #:upload_complete # Must be defined by the including class
32
- #:destroy_upload # the actual delete should be done by the application
33
- #:dynamic_residence # If the data stores are dynamically stored by the application
34
- }
35
-
36
- @@dynamics = {}
37
-
38
- def self.callbacks
39
- @@callbacks
40
- end
41
-
42
- def self.set_callback(name, callback = nil, &block)
43
- if callback.is_a?(Proc)
44
- @@callbacks[name.to_sym] = callback
45
- elsif block.present?
46
- @@callbacks[name.to_sym] = block
47
- else
48
- raise ArgumentError, 'Condo callbacks must be defined with a Proc or Proc (lamba) object present'
49
- end
50
- end
51
-
52
-
53
- #
54
- # Provides a callback whenever attempting to select a provider for the current request
55
- # => Allows multiple providers for different users / controllers or dynamic providers
56
- #
57
- def self.set_dynamic_provider(namespace, callback = nil, &block)
58
- if callback.is_a?(Proc)
59
- @@dynamics[namespace.to_sym] = callback
60
- elsif block.present?
61
- @@dynamics[namespace.to_sym] = block
62
- else
63
- raise ArgumentError, 'Condo callbacks must be defined with a Proc or Proc (lamba) object present'
64
- end
65
- end
66
-
67
- def dynamic_provider_present?(namespace)
68
- return false if @@dynamics.nil? || @@dynamics[namespace.to_sym].nil?
69
- true
70
- end
71
-
72
-
73
- #
74
- # Allows for predefined storage providers (maybe you only use Amazon?)
75
- #
76
- def self.add_residence(name, options = {})
77
- @@residencies ||= []
78
- @@residencies << ("Condo::Strata::#{name.to_s.camelize}".constantize.new(options)).tap do |res|
79
- name = name.to_sym
80
- namespace = (options[:namespace] || :global).to_sym
81
-
82
- @@locations ||= {}
83
- @@locations[namespace] ||= {}
84
- @@locations[namespace][name] ||= {}
85
-
86
- if options[:location].present?
87
- @@locations[namespace][name][options[:location].to_sym] = res
88
- else
89
- @@locations[namespace][name][:default] = res
90
- @@locations[namespace][name][res.location.to_sym] = res
91
- end
92
- end
93
- end
94
-
95
-
96
- def residencies
97
- @@residencies
98
- end
99
-
100
-
101
- #
102
- # Storage provider selection routine
103
- # => pass in :dynamic => true with :name and connection options to create a new instance
104
- #
105
- def set_residence(name, options)
106
- if options[:namespace].present? && dynamic_provider_present?(options[:namespace])
107
- if options[:upload].present?
108
- upload = options[:upload]
109
- params = {
110
- :user_id => upload.user_id,
111
- :file_name => upload.file_name,
112
- :file_size => upload.file_size,
113
- :custom_params => upload.custom_params,
114
- :provider_name => upload.provider_name,
115
- :provider_location => upload.provider_location,
116
- :provider_namespace => upload.provider_namespace
117
- }
118
- return instance_exec params, &@@dynamics[upload.provider_namespace]
119
- else
120
- params = {
121
- :user_id => options[:resident],
122
- :file_name => options[:params][:file_name],
123
- :file_size => options[:params][:file_size],
124
- :custom_params => options[:params][:custom_params],
125
- :provider_namespace => options[:namespace]
126
- }
127
- return instance_exec params, &@@dynamics[options[:namespace]]
128
- end
129
- else
130
- if !!options[:dynamic]
131
- return "Condo::Strata::#{name.to_s.camelize}".constantize.new(options)
132
- else
133
- return options[:location].present? ? @@locations[options[:namespace]][name.to_sym][options[:location].to_sym] : @@locations[options[:namespace]][name.to_sym][:default]
134
- end
135
- end
136
- end
137
-
138
- end
139
-
1
+ require 'singleton'
2
+
3
+ module Condo
4
+
5
+ class Configuration
6
+ include Singleton
7
+
8
+ @@callbacks = {
9
+ #:resident_id # Must be defined by the including class
10
+ :bucket_name => proc {"#{Rails.application.class.parent_name}#{instance_eval @@callbacks[:resident_id]}"},
11
+ :object_key => proc { |upload|
12
+ if upload[:file_path]
13
+ upload[:file_path] + upload[:file_name]
14
+ else
15
+ upload[:file_name]
16
+ end
17
+ },
18
+ :object_options => proc { |upload|
19
+ {:permissions => :private}
20
+ },
21
+ :pre_validation => proc { |upload|
22
+ true
23
+ }, # To respond with errors use: lambda {return false, {:errors => {:param_name => 'wtf are you doing?'}}}
24
+ :sanitize_filename => proc { |filename|
25
+ filename.gsub!(/^.*(\\|\/)/, '') # get only the filename (just in case)
26
+ filename.gsub!(/[^\w\.\-]/, '_') # replace all non alphanumeric or periods with underscore
27
+ filename
28
+ },
29
+ :sanitize_filepath => proc { |filepath|
30
+ filepath.gsub!(/[^\w\.\-\/]/, '_') # replace all non alphanumeric or periods with underscore
31
+ filepath
32
+ }
33
+ #:upload_complete # Must be defined by the including class
34
+ #:destroy_upload # the actual delete should be done by the application
35
+ #:dynamic_residence # If the data stores are dynamically stored by the application
36
+ }
37
+
38
+ @@dynamics = {}
39
+
40
+ def self.callbacks
41
+ @@callbacks
42
+ end
43
+
44
+ def self.set_callback(name, callback = nil, &block)
45
+ callback ||= block
46
+ if callback.respond_to?(:call)
47
+ @@callbacks[name.to_sym] = callback
48
+ else
49
+ raise ArgumentError, 'No callback provided'
50
+ end
51
+ end
52
+
53
+
54
+ #
55
+ # Provides a callback whenever attempting to select a provider for the current request
56
+ # => Allows multiple providers for different users / controllers or dynamic providers
57
+ #
58
+ def self.set_dynamic_provider(namespace, callback = nil, &block)
59
+ callback ||= block
60
+ if callback.respond_to?(:call)
61
+ @@callbacks[name.to_sym] = callback
62
+ else
63
+ raise ArgumentError, 'No callback provided'
64
+ end
65
+ end
66
+
67
+ def dynamic_provider_present?(namespace)
68
+ return false if @@dynamics.nil? || @@dynamics[namespace.to_sym].nil?
69
+ true
70
+ end
71
+
72
+
73
+ #
74
+ # Allows for predefined storage providers (maybe you only use Amazon?)
75
+ #
76
+ def self.add_residence(name, options = {})
77
+ @@residencies ||= []
78
+ @@residencies << ("Condo::Strata::#{name.to_s.camelize}".constantize.new(options)).tap do |res|
79
+ name = name.to_sym
80
+ namespace = (options[:namespace] || :global).to_sym
81
+
82
+ @@locations ||= {}
83
+ @@locations[namespace] ||= {}
84
+ @@locations[namespace][name] ||= {}
85
+
86
+ if options[:location].present?
87
+ @@locations[namespace][name][options[:location].to_sym] = res
88
+ else
89
+ @@locations[namespace][name][:default] = res
90
+ @@locations[namespace][name][res.location.to_sym] = res
91
+ end
92
+ end
93
+ end
94
+
95
+
96
+ def residencies
97
+ @@residencies
98
+ end
99
+
100
+
101
+ #
102
+ # Storage provider selection routine
103
+ # => pass in :dynamic => true with :name and connection options to create a new instance
104
+ #
105
+ def set_residence(name, options)
106
+ if options[:namespace].present? && dynamic_provider_present?(options[:namespace])
107
+ if options[:upload].present?
108
+ upload = options[:upload]
109
+ params = {
110
+ :user_id => upload.user_id,
111
+ :file_name => upload.file_name,
112
+ :file_size => upload.file_size,
113
+ :provider_name => upload.provider_name,
114
+ :provider_location => upload.provider_location,
115
+ :provider_namespace => upload.provider_namespace
116
+ }
117
+ return instance_exec params, &@@dynamics[upload.provider_namespace]
118
+ else
119
+ params = {
120
+ :user_id => options[:resident],
121
+ :file_name => options[:params][:file_name],
122
+ :file_size => options[:params][:file_size],
123
+ :provider_namespace => options[:namespace]
124
+ }
125
+ return instance_exec params, &@@dynamics[options[:namespace]]
126
+ end
127
+ else
128
+ if options[:dynamic]
129
+ return "Condo::Strata::#{name.to_s.camelize}".constantize.new(options)
130
+ else
131
+ return options[:location].present? ? @@locations[:global][name.to_sym][options[:location].to_sym] : @@locations[:global][name.to_sym][:default]
132
+ end
133
+ end
134
+ end
135
+
136
+ end
137
+
140
138
  end
@@ -1,9 +1,9 @@
1
- module Condo
2
-
3
- module Errors
4
- class LostTheKeys < RuntimeError; end # Authentication
5
- class NotYourPlace < RuntimeError; end # Authorisation
6
- class MissingFurniture < RuntimeError; end # File not found
7
- end
8
-
1
+ module Condo
2
+
3
+ module Errors
4
+ class LostTheKeys < RuntimeError; end # Authentication
5
+ class NotYourPlace < RuntimeError; end # Authorisation
6
+ class MissingFurniture < RuntimeError; end # File not found
7
+ end
8
+
9
9
  end
@@ -1,301 +1,301 @@
1
- module Condo; end
2
- module Condo::Strata; end
3
-
4
-
5
- class Condo::Strata::AmazonS3
6
-
7
- def initialize(options)
8
- @options = {
9
- :name => :AmazonS3,
10
- :location => :'us-east-1',
11
- :fog => {
12
- :provider => :AWS,
13
- :aws_access_key_id => options[:access_id],
14
- :aws_secret_access_key => options[:secret_key],
15
- :region => (options[:location] || 'us-east-1')
16
- }
17
- }.merge!(options)
18
-
19
-
20
- raise ArgumentError, 'Amazon Access ID missing' if @options[:access_id].nil?
21
- raise ArgumentError, 'Amazon Secret Key missing' if @options[:secret_key].nil?
22
-
23
-
24
- @options[:location] = @options[:location].to_sym
25
- @options[:region] = @options[:location] == :'us-east-1' ? 's3.amazonaws.com' : "s3-#{@options[:location]}.amazonaws.com"
26
- end
27
-
28
-
29
- def name
30
- @options[:name]
31
- end
32
-
33
-
34
- def location
35
- @options[:location]
36
- end
37
-
38
-
39
-
40
- #
41
- # Create a signed URL for accessing a private file
42
- #
43
- def get_object(options)
44
- options = {}.merge!(options) # Need to deep copy here
45
- options[:object_options] = {
46
- :expires => 5.minutes.from_now,
47
- :date => Time.now,
48
- :verb => :get, # Post for multi-part uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html
49
- :headers => {},
50
- :parameters => {},
51
- :protocol => :https
52
- }.merge!(options[:object_options] || {})
53
- options.merge!(@options)
54
-
55
- #
56
- # provide the signed request
57
- #
58
- sign_request(options)[:url]
59
- end
60
-
61
-
62
- #
63
- # Creates a new upload request (either single shot or multi-part)
64
- # => Passed: bucket_name, object_key, object_options, file_size
65
- #
66
- def new_upload(options)
67
- options = {}.merge!(options) # Need to deep copy here
68
- options[:object_options] = {
69
- :permissions => :private,
70
- :expires => 5.minutes.from_now,
71
- :date => Time.now,
72
- :verb => :post, # Post for multi-part uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html
73
- :headers => {},
74
- :parameters => {},
75
- :protocol => :https
76
- }.merge!(options[:object_options])
77
- options.merge!(@options)
78
-
79
- #
80
- # Set the access control headers
81
- #
82
- if options[:object_options][:headers]['x-amz-acl'].nil?
83
- options[:object_options][:headers]['x-amz-acl'] = case options[:object_options][:permissions]
84
- when :public
85
- :'public-read'
86
- else
87
- :private
88
- end
89
- end
90
-
91
- #
92
- # Decide what type of request is being sent
93
- #
94
- request = {}
95
- if options[:file_size] > 5.megabytes # 5 mb (minimum chunk size)
96
- options[:object_options][:parameters][:uploads] = '' # Customise the request to be a chunked upload
97
- options.delete(:file_id) # Does not apply to chunked uploads
98
-
99
- request[:type] = :chunked_upload
100
- else
101
- if options[:file_id].present? && options[:object_options][:headers]['Content-Md5'].nil?
102
- #
103
- # The client side is sending hex formatted ids that will match the amazon etag
104
- # => We need this to be base64 for the md5 header (this is now done at the client side)
105
- #
106
- # options[:file_id] = [[options[:file_id]].pack("H*")].pack("m0") # (the 0 avoids the call to strip - now done client side)
107
- # [ options[:file_id] ].pack('m').strip # This wasn't correct
108
- # Base64.encode64(options[:file_id]).strip # This also wasn't correct
109
- #
110
- options[:object_options][:headers]['Content-Md5'] = options[:file_id]
111
- end
112
- options[:object_options][:headers]['Content-Type'] = 'binary/octet-stream' if options[:object_options][:headers]['Content-Type'].nil?
113
- options[:object_options][:verb] = :put # Put for direct uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPUT.html
114
-
115
- request[:type] = :direct_upload
116
- end
117
-
118
-
119
- #
120
- # provide the signed request
121
- #
122
- request[:signature] = sign_request(options)
123
- request
124
- end
125
-
126
-
127
- #
128
- # Returns the request to get the parts of a resumable upload
129
- #
130
- def get_parts(options)
131
- options[:object_options] = {
132
- :expires => 5.minutes.from_now,
133
- :date => Time.now,
134
- :verb => :get,
135
- :headers => {},
136
- :parameters => {},
137
- :protocol => :https
138
- }.merge!(options[:object_options])
139
- options.merge!(@options)
140
-
141
- #
142
- # Set the upload
143
- #
144
- options[:object_options][:parameters]['uploadId'] = options[:resumable_id]
145
-
146
- #
147
- # provide the signed request
148
- #
149
- {
150
- :type => :parts,
151
- :signature => sign_request(options)
152
- }
153
- end
154
-
155
-
156
- #
157
- # Returns the requests for uploading parts and completing a resumable upload
158
- #
159
- def set_part(options)
160
- options[:object_options] = {
161
- :expires => 5.minutes.from_now,
162
- :date => Time.now,
163
- :headers => {},
164
- :parameters => {},
165
- :protocol => :https
166
- }.merge!(options[:object_options])
167
- options.merge!(@options)
168
-
169
-
170
- request = {}
171
- if options[:part] == 'finish'
172
- #
173
- # Send the commitment response
174
- #
175
- options[:object_options][:headers]['Content-Type'] = 'application/xml; charset=UTF-8' if options[:object_options][:headers]['Content-Type'].nil?
176
- options[:object_options][:verb] = :post
177
- request[:type] = :finish
178
- else
179
- #
180
- # Send the part upload request
181
- #
182
- options[:object_options][:headers]['Content-Md5'] = options[:file_id] if options[:file_id].present? && options[:object_options][:headers]['Content-Md5'].nil?
183
- options[:object_options][:headers]['Content-Type'] = 'binary/octet-stream' if options[:object_options][:headers]['Content-Type'].nil?
184
- options[:object_options][:parameters]['partNumber'] = options[:part]
185
- options[:object_options][:verb] = :put
186
- request[:type] = :part_upload
187
- end
188
-
189
-
190
- #
191
- # Set the upload
192
- #
193
- options[:object_options][:parameters]['uploadId'] = options[:resumable_id]
194
-
195
-
196
- #
197
- # provide the signed request
198
- #
199
- request[:signature] = sign_request(options)
200
- request
201
- end
202
-
203
-
204
- def fog_connection
205
- @fog = @fog || Fog::Storage.new(@options[:fog])
206
- return @fog
207
- end
208
-
209
-
210
- def destroy(upload)
211
- connection = fog_connection
212
- directory = connection.directories.get(upload.bucket_name) # it is assumed this exists - if not then the upload wouldn't have taken place
213
- file = directory.files.get(upload.object_key)
214
-
215
- if upload.resumable
216
- return file.destroy unless file.nil?
217
- begin
218
- if upload.resumable_id.present?
219
- connection.abort_multipart_upload(upload.bucket_name, upload.object_key, upload.resumable_id)
220
- return true
221
- end
222
- rescue
223
- # In-case resumable_id was invalid or did not match the object key
224
- end
225
-
226
- #
227
- # The user may have provided an invalid upload key, we'll need to search for the upload and destroy it
228
- #
229
- begin
230
- resp = connection.list_multipart_uploads(upload.bucket_name, {'prefix' => upload.object_key})
231
- resp.body['Upload'].each do |file|
232
- #
233
- # TODO:: BUGBUG:: there is an edge case where there may be more multi-part uploads with this this prefix then will be provided in a single request
234
- # => We'll need to handle this edge case to avoid abuse and dangling objects
235
- #
236
- connection.abort_multipart_upload(upload.bucket_name, upload.object_key, file['UploadId']) if file['Key'] == upload.object_key # Ensure an exact match
237
- end
238
- return true # The upload was either never initialised or has been destroyed
239
- rescue
240
- return false
241
- end
242
- else
243
- return true if file.nil?
244
- return file.destroy
245
- end
246
- end
247
-
248
-
249
-
250
- protected
251
-
252
-
253
-
254
- def sign_request(options)
255
-
256
- #
257
- # Build base URL
258
- #
259
- options[:object_options][:date] = options[:object_options][:date].utc.httpdate
260
- options[:object_options][:expires] = options[:object_options][:expires].utc.to_i
261
- url = "/#{options[:bucket_name]}/#{options[:object_key]}"
262
-
263
- #
264
- # Add request params
265
- #
266
- url << '?'
267
- options[:object_options][:parameters].each do |key, value|
268
- url += value.empty? ? "#{key}&" : "#{key}=#{value}&"
269
- end
270
- url.chop!
271
-
272
- #
273
- # Build a request signature
274
- #
275
- signature = "#{options[:object_options][:verb].to_s.upcase}\n#{options[:file_id]}\n#{options[:object_options][:headers]['Content-Type']}\n#{options[:object_options][:expires]}\n"
276
- options[:object_options][:headers].each do |key, value|
277
- signature << "#{key}:#{value}\n" if key =~ /x-amz-/
278
- end
279
- signature << url
280
-
281
-
282
- #
283
- # Encode the request signature
284
- #
285
- signature = CGI::escape(Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), @options[:secret_key], signature)).gsub("\n",""))
286
-
287
-
288
- #
289
- # Finish building the request
290
- #
291
- url += options[:object_options][:parameters].present? ? '&' : '?'
292
- return {
293
- :verb => options[:object_options][:verb].to_s.upcase,
294
- :url => "#{options[:object_options][:protocol]}://#{options[:region]}#{url}AWSAccessKeyId=#{@options[:access_id]}&Expires=#{options[:object_options][:expires]}&Signature=#{signature}",
295
- :headers => options[:object_options][:headers]
296
- }
297
- end
298
-
299
-
300
- end
301
-
1
+ module Condo; end
2
+ module Condo::Strata; end
3
+
4
+
5
+ class Condo::Strata::AmazonS3
6
+
7
+ def initialize(options)
8
+ @options = {
9
+ :name => :AmazonS3,
10
+ :location => :'us-east-1',
11
+ :fog => {
12
+ :provider => :AWS,
13
+ :aws_access_key_id => options[:access_id],
14
+ :aws_secret_access_key => options[:secret_key],
15
+ :region => (options[:location] || 'us-east-1')
16
+ }
17
+ }.merge!(options)
18
+
19
+
20
+ raise ArgumentError, 'Amazon Access ID missing' if @options[:access_id].nil?
21
+ raise ArgumentError, 'Amazon Secret Key missing' if @options[:secret_key].nil?
22
+
23
+
24
+ @options[:location] = @options[:location].to_sym
25
+ @options[:region] = @options[:location] == :'us-east-1' ? 's3.amazonaws.com' : "s3-#{@options[:location]}.amazonaws.com"
26
+ end
27
+
28
+
29
+ def name
30
+ @options[:name]
31
+ end
32
+
33
+
34
+ def location
35
+ @options[:location]
36
+ end
37
+
38
+
39
+
40
+ #
41
+ # Create a signed URL for accessing a private file
42
+ #
43
+ def get_object(options)
44
+ options = {}.merge!(options) # Need to deep copy here
45
+ options[:object_options] = {
46
+ :expires => 5.minutes.from_now,
47
+ :date => Time.now,
48
+ :verb => :get, # Post for multi-part uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html
49
+ :headers => {},
50
+ :parameters => {},
51
+ :protocol => :https
52
+ }.merge!(options[:object_options] || {})
53
+ options.merge!(@options)
54
+
55
+ #
56
+ # provide the signed request
57
+ #
58
+ sign_request(options)[:url]
59
+ end
60
+
61
+
62
+ #
63
+ # Creates a new upload request (either single shot or multi-part)
64
+ # => Passed: bucket_name, object_key, object_options, file_size
65
+ #
66
+ def new_upload(options)
67
+ options = {}.merge!(options) # Need to deep copy here
68
+ options[:object_options] = {
69
+ :permissions => :private,
70
+ :expires => 5.minutes.from_now,
71
+ :date => Time.now,
72
+ :verb => :post, # Post for multi-part uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/mpUploadInitiate.html
73
+ :headers => {},
74
+ :parameters => {},
75
+ :protocol => :https
76
+ }.merge!(options[:object_options])
77
+ options.merge!(@options)
78
+
79
+ #
80
+ # Set the access control headers
81
+ #
82
+ if options[:object_options][:headers]['x-amz-acl'].nil?
83
+ options[:object_options][:headers]['x-amz-acl'] = case options[:object_options][:permissions]
84
+ when :public
85
+ :'public-read'
86
+ else
87
+ :private
88
+ end
89
+ end
90
+
91
+ #
92
+ # Decide what type of request is being sent
93
+ #
94
+ request = {}
95
+ if options[:file_size] > 5.megabytes # 5 mb (minimum chunk size)
96
+ options[:object_options][:parameters][:uploads] = '' # Customise the request to be a chunked upload
97
+ options.delete(:file_id) # Does not apply to chunked uploads
98
+
99
+ request[:type] = :chunked_upload
100
+ else
101
+ if options[:file_id].present? && options[:object_options][:headers]['Content-Md5'].nil?
102
+ #
103
+ # The client side is sending hex formatted ids that will match the amazon etag
104
+ # => We need this to be base64 for the md5 header (this is now done at the client side)
105
+ #
106
+ # options[:file_id] = [[options[:file_id]].pack("H*")].pack("m0") # (the 0 avoids the call to strip - now done client side)
107
+ # [ options[:file_id] ].pack('m').strip # This wasn't correct
108
+ # Base64.encode64(options[:file_id]).strip # This also wasn't correct
109
+ #
110
+ options[:object_options][:headers]['Content-Md5'] = options[:file_id]
111
+ end
112
+ options[:object_options][:headers]['Content-Type'] = 'binary/octet-stream' if options[:object_options][:headers]['Content-Type'].nil?
113
+ options[:object_options][:verb] = :put # Put for direct uploads http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectPUT.html
114
+
115
+ request[:type] = :direct_upload
116
+ end
117
+
118
+
119
+ #
120
+ # provide the signed request
121
+ #
122
+ request[:signature] = sign_request(options)
123
+ request
124
+ end
125
+
126
+
127
+ #
128
+ # Returns the request to get the parts of a resumable upload
129
+ #
130
+ def get_parts(options)
131
+ options[:object_options] = {
132
+ :expires => 5.minutes.from_now,
133
+ :date => Time.now,
134
+ :verb => :get,
135
+ :headers => {},
136
+ :parameters => {},
137
+ :protocol => :https
138
+ }.merge!(options[:object_options])
139
+ options.merge!(@options)
140
+
141
+ #
142
+ # Set the upload
143
+ #
144
+ options[:object_options][:parameters]['uploadId'] = options[:resumable_id]
145
+
146
+ #
147
+ # provide the signed request
148
+ #
149
+ {
150
+ :type => :parts,
151
+ :signature => sign_request(options)
152
+ }
153
+ end
154
+
155
+
156
+ #
157
+ # Returns the requests for uploading parts and completing a resumable upload
158
+ #
159
+ def set_part(options)
160
+ options[:object_options] = {
161
+ :expires => 5.minutes.from_now,
162
+ :date => Time.now,
163
+ :headers => {},
164
+ :parameters => {},
165
+ :protocol => :https
166
+ }.merge!(options[:object_options])
167
+ options.merge!(@options)
168
+
169
+
170
+ request = {}
171
+ if options[:part] == 'finish'
172
+ #
173
+ # Send the commitment response
174
+ #
175
+ options[:object_options][:headers]['Content-Type'] = 'application/xml; charset=UTF-8' if options[:object_options][:headers]['Content-Type'].nil?
176
+ options[:object_options][:verb] = :post
177
+ request[:type] = :finish
178
+ else
179
+ #
180
+ # Send the part upload request
181
+ #
182
+ options[:object_options][:headers]['Content-Md5'] = options[:file_id] if options[:file_id].present? && options[:object_options][:headers]['Content-Md5'].nil?
183
+ options[:object_options][:headers]['Content-Type'] = 'binary/octet-stream' if options[:object_options][:headers]['Content-Type'].nil?
184
+ options[:object_options][:parameters]['partNumber'] = options[:part]
185
+ options[:object_options][:verb] = :put
186
+ request[:type] = :part_upload
187
+ end
188
+
189
+
190
+ #
191
+ # Set the upload
192
+ #
193
+ options[:object_options][:parameters]['uploadId'] = options[:resumable_id]
194
+
195
+
196
+ #
197
+ # provide the signed request
198
+ #
199
+ request[:signature] = sign_request(options)
200
+ request
201
+ end
202
+
203
+
204
+ def fog_connection
205
+ @fog = @fog || Fog::Storage.new(@options[:fog])
206
+ return @fog
207
+ end
208
+
209
+
210
+ def destroy(upload)
211
+ connection = fog_connection
212
+ directory = connection.directories.get(upload.bucket_name) # it is assumed this exists - if not then the upload wouldn't have taken place
213
+ file = directory.files.get(upload.object_key)
214
+
215
+ if upload.resumable
216
+ return file.destroy unless file.nil?
217
+ begin
218
+ if upload.resumable_id.present?
219
+ connection.abort_multipart_upload(upload.bucket_name, upload.object_key, upload.resumable_id)
220
+ return true
221
+ end
222
+ rescue
223
+ # In-case resumable_id was invalid or did not match the object key
224
+ end
225
+
226
+ #
227
+ # The user may have provided an invalid upload key, we'll need to search for the upload and destroy it
228
+ #
229
+ begin
230
+ resp = connection.list_multipart_uploads(upload.bucket_name, {'prefix' => upload.object_key})
231
+ resp.body['Upload'].each do |file|
232
+ #
233
+ # TODO:: BUGBUG:: there is an edge case where there may be more multi-part uploads with this this prefix then will be provided in a single request
234
+ # => We'll need to handle this edge case to avoid abuse and dangling objects
235
+ #
236
+ connection.abort_multipart_upload(upload.bucket_name, upload.object_key, file['UploadId']) if file['Key'] == upload.object_key # Ensure an exact match
237
+ end
238
+ return true # The upload was either never initialised or has been destroyed
239
+ rescue
240
+ return false
241
+ end
242
+ else
243
+ return true if file.nil?
244
+ return file.destroy
245
+ end
246
+ end
247
+
248
+
249
+
250
+ protected
251
+
252
+
253
+
254
+ def sign_request(options)
255
+
256
+ #
257
+ # Build base URL
258
+ #
259
+ options[:object_options][:date] = options[:object_options][:date].utc.httpdate
260
+ options[:object_options][:expires] = options[:object_options][:expires].utc.to_i
261
+ url = "/#{options[:bucket_name]}/#{options[:object_key]}"
262
+
263
+ #
264
+ # Add request params
265
+ #
266
+ url << '?'
267
+ options[:object_options][:parameters].each do |key, value|
268
+ url += value.empty? ? "#{key}&" : "#{key}=#{value}&"
269
+ end
270
+ url.chop!
271
+
272
+ #
273
+ # Build a request signature
274
+ #
275
+ signature = "#{options[:object_options][:verb].to_s.upcase}\n#{options[:file_id]}\n#{options[:object_options][:headers]['Content-Type']}\n#{options[:object_options][:expires]}\n"
276
+ options[:object_options][:headers].each do |key, value|
277
+ signature << "#{key}:#{value}\n" if key =~ /x-amz-/
278
+ end
279
+ signature << url
280
+
281
+
282
+ #
283
+ # Encode the request signature
284
+ #
285
+ signature = CGI::escape(Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha1'), @options[:secret_key], signature)).gsub("\n",""))
286
+
287
+
288
+ #
289
+ # Finish building the request
290
+ #
291
+ url += options[:object_options][:parameters].present? ? '&' : '?'
292
+ return {
293
+ :verb => options[:object_options][:verb].to_s.upcase,
294
+ :url => "#{options[:object_options][:protocol]}://#{options[:region]}#{url}AWSAccessKeyId=#{@options[:access_id]}&Expires=#{options[:object_options][:expires]}&Signature=#{signature}",
295
+ :headers => options[:object_options][:headers]
296
+ }
297
+ end
298
+
299
+
300
+ end
301
+