s3_private_direct_upload 0.1.6

Sign up to get free protection for your applications and to get access to all the features.
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Wayne
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,274 @@
1
+ # S3DirectUpload
2
+
3
+ Easily generate a form that allows you to upload directly to Amazon S3.
4
+ Multi file uploading supported by jquery-fileupload.
5
+
6
+ Code extracted from Ryan Bates' [gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload).
7
+
8
+ ## Installation
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 's3_direct_upload'
12
+
13
+ Then add a new initalizer with your AWS credentials:
14
+
15
+ **config/initializers/s3_direct_upload.rb**
16
+ ```ruby
17
+ S3DirectUpload.config do |c|
18
+ c.access_key_id = "" # your access key id
19
+ c.secret_access_key = "" # your secret access key
20
+ c.bucket = "" # your bucket name
21
+ c.region = nil # region prefix of your bucket url (optional), eg. "s3-eu-west-1"
22
+ c.url = nil # S3 API endpoint (optional), eg. "https://#{c.bucket}.s3.amazonaws.com/"
23
+ end
24
+ ```
25
+
26
+ Make sure your AWS S3 CORS settings for your bucket look something like this:
27
+ ```xml
28
+ <CORSConfiguration>
29
+ <CORSRule>
30
+ <AllowedOrigin>http://0.0.0.0:3000</AllowedOrigin>
31
+ <AllowedMethod>GET</AllowedMethod>
32
+ <AllowedMethod>POST</AllowedMethod>
33
+ <AllowedMethod>PUT</AllowedMethod>
34
+ <MaxAgeSeconds>3000</MaxAgeSeconds>
35
+ <AllowedHeader>*</AllowedHeader>
36
+ </CORSRule>
37
+ </CORSConfiguration>
38
+ ```
39
+ In production the AllowedOrigin key should be your domain.
40
+
41
+ Add the following js and css to your asset pipeline:
42
+
43
+ **application.js.coffee**
44
+ ```coffeescript
45
+ #= require s3_direct_upload
46
+ ```
47
+
48
+ **application.css**
49
+ ```css
50
+ //= require s3_direct_upload_progress_bars
51
+ ```
52
+
53
+ ## Usage
54
+ Create a new view that uses the form helper `s3_uploader_form`:
55
+ ```ruby
56
+ <%= s3_uploader_form callback_url: model_url, callback_param: "model[image_url]", id: "myS3Uploader" do %>
57
+ <%= file_field_tag :file, multiple: true %>
58
+ <% end %>
59
+ ```
60
+
61
+ Note: Its required that the file_field_tag is named 'file'.
62
+
63
+ Then in your application.js.coffee, call the S3Uploader jQuery plugin on the element you created above:
64
+ ```coffeescript
65
+ jQuery ->
66
+ $("#myS3Uploader").S3Uploader()
67
+ ```
68
+
69
+ Optionally, you can also place this template in the same view for the progress bars:
70
+ ```js+erb
71
+ <script id="template-upload" type="text/x-tmpl">
72
+ <div id="file-{%=o.unique_id%}" class="upload">
73
+ {%=o.name%}
74
+ <div class="progress"><div class="bar" style="width: 0%"></div></div>
75
+ </div>
76
+ </script>
77
+ ```
78
+
79
+ ## Options for form helper
80
+ * `callback_url:` url that is POST'd to after file is uploaded to S3. If you don't specify this option, no callback to the server will be made after the file has uploaded to S3.
81
+ * `callback_method:` Defaults to POST. Use PUT and remove the multiple option from your file field to update a model.
82
+ * `callback_param:` parameter value for the POST in which the key will be the URL of the file on S3. If for example this is set to "model[image_url]" then the data posted would be `model[image_url] : http://bucketname.s3.amazonws.com/filename.ext`
83
+ * `key:` key on s3. defaults to `"uploads/{timestamp}-{unique_id}-#{SecureRandom.hex}/${filename}"`. `{timestamp}` and `{unique_id}` are special substitution params that will be populated by the javascript with values for the current upload. `${filename}` is a special s3 param that will be populated with the original upload file name. Needs to be at least `"${filename}"`. It is highly recommended to use both `{unique_id}`, which will prevent collisions when uploading files with the same name (such as from a mobile device, where every photo is named image.jpg), and a server-generated random value such as `#{SecureRandom.hex}`, which adds further collision protection with other uploaders.
84
+ * `key_starts_with:` constraint on key on s3. Defaults to `uploads/`. if you change the `key` option, make sure this starts with what you put there. If you set this as a blank string the upload path to s3 can be anything - not recommended!
85
+ * `acl:` acl for files uploaded to s3, defaults to "public-read"
86
+ * `max_file_size:` maximum file size, defaults to 500.megabytes
87
+ * `id:` html id for the form, its recommended that you give the form an id so you can reference with the jQuery plugin.
88
+ * `class:` optional html class for the form.
89
+ * `data:` Optional html data
90
+
91
+ ### Persisting the S3 url
92
+ It is recommended that you persist the image_url that is sent back from the POST request (to the url given to the `post` option and as the key given in the `as` option). So to access your files later.
93
+
94
+ One way to do this is to make sure you have `resources model` in your routes file, and add the `image_url` (or whatever you would like to name it) attribute to your model, and then make sure you have the create action in your controller for that model.
95
+
96
+ You could then have your create action render a javascript file like this:
97
+ **create.js.erb**
98
+ ```ruby
99
+ <% if @model.new_record? %>
100
+ alert("Failed to upload model: <%= j @model.errors.full_messages.join(', ').html_safe %>");
101
+ <% else %>
102
+ $("#container").append("<%= j render(@model) %>");
103
+ <% end %>
104
+ ```
105
+ So that javascript code would be executed after the model instance is created, without a page refresh. See [@rbates's gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload)) for an example of that method.
106
+
107
+ Note: the POST request to the rails app also includes the following parameters `filesize`, `filetype`, `filename` and `filepath`.
108
+
109
+ ### Advanced Customizations
110
+ Feel free to override the styling for the progress bars in s3_direct_upload_progress_bars.css, look at the source for inspiration.
111
+
112
+ Also feel free to write your own js to interface with jquery-file-upload. You might want to do this to do custom validations on the files before it is sent to S3 for example.
113
+ To do this remove `s3_direct_upload` from your application.js and include the necessary jquery-file-upload scripts in your asset pipeline (they are included in this gem automatically):
114
+ ```cofeescript
115
+ #= require jquery-fileupload/basic
116
+ #= require jquery-fileupload/vendor/tmpl
117
+ ```
118
+ Use the javascript in `s3_direct_upload` as a guide.
119
+
120
+
121
+ ## Options for S3Upload jQuery Plugin
122
+
123
+ * `path:` manual path for the files on your s3 bucket. Example: `path/to/my/files/on/s3`
124
+ Note: Your path MUST start with the option you put in your form builder for `key_starts_with`, or else you will get S3 permission errors. The file path in your s3 bucket will be `path + key`.
125
+ * `additional_data:` You can send additional data to your rails app in the persistence POST request. This would be accessible in your params hash as `params[:key][:value]`
126
+ Example: `{key: value}`
127
+ * `remove_completed_progress_bar:` By default, the progress bar will be removed once the file has been successfully uploaded. You can set this to `false` if you want to keep the progress bar.
128
+ * `remove_failed_progress_bar:` By default, the progress bar will not be removed when uploads fail. You can set this to `true` if you want to remove the progress bar.
129
+ * `before_add:` Callback function that executes before a file is added to the queue. It is passed file object and expects `true` or `false` to be returned. This could be useful if you would like to validate the filenames of files to be uploaded for example. If true is returned file will be uploaded as normal, false will cancel the upload.
130
+ * `progress_bar_target:` The jQuery selector for the element where you want the progress bars to be appended to. Default is the form element.
131
+ * `click_submit_target:` The jQuery selector for the element you wish to add a click handler to do the submitting instead of submiting on file open.
132
+
133
+ ### Example with all options.
134
+ ```coffeescript
135
+ jQuery ->
136
+ $("#myS3Uploader").S3Uploader
137
+ path: 'path/to/my/files/on/s3'
138
+ additional_data: {key: 'value'}
139
+ remove_completed_progress_bar: false
140
+ before_add: myCallBackFunction() # must return true or false if set
141
+ progress_bar_target: $('.js-progress-bars')
142
+ click_submit_target: $('.submit-target')
143
+ ```
144
+ ### Example with single file upload bar without script template
145
+
146
+ This demonstrates how to use progress_bar_target and allow_multiple_files (only works with false option - single file) to show only one progress bar without script template.
147
+
148
+ ```coffeescript
149
+ jQuery ->
150
+ $("#myS3Uploader").S3Uploader
151
+ progress_bar_target: $('.js-progress-bars')
152
+ allow_multiple_files: false
153
+ ```
154
+
155
+ Target for progress bar
156
+
157
+ ```html
158
+ <div class="upload js-progress-bars">
159
+ <div class="progress">
160
+ <div class="bars"> </div>
161
+ </div>
162
+ </div>
163
+ ```
164
+
165
+
166
+
167
+
168
+ ### Public methods
169
+ You can change the settings on your form later on by accessing the jQuery instance:
170
+
171
+ ```coffeescript
172
+ jQuery ->
173
+ v = $("#myS3Uploader").S3Uploader()
174
+ ...
175
+ v.path("new/path/") #only works when the key_starts_with option is blank. Not recommended.
176
+ v.additional_data("newdata")
177
+ ```
178
+
179
+ ### Javascript Events Hooks
180
+
181
+ #### First upload started
182
+ `s3_uploads_start` is fired once when any batch of uploads is starting.
183
+ ```coffeescript
184
+ $('#myS3Uploader').bind 's3_uploads_start', (e) ->
185
+ alert("Uploads have started")
186
+ ```
187
+
188
+ #### Successfull upload
189
+ When a file has been successfully uploaded to S3, the `s3_upload_complete` is triggered on the form. A `content` object is passed along with the following attributes :
190
+
191
+ * `url` The full URL to the uploaded file on S3.
192
+ * `filename` The original name of the uploaded file.
193
+ * `filepath` The path to the file (without the filename or domain)
194
+ * `filesize` The size of the uploaded file.
195
+ * `filetype` The type of the uploaded file.
196
+
197
+ This hook could be used for example to fill a form hidden field with the returned S3 url :
198
+ ```coffeescript
199
+ $('#myS3Uploader').bind "s3_upload_complete", (e, content) ->
200
+ $('#someHiddenField').val(content.url)
201
+ ```
202
+
203
+ #### Failed upload
204
+ When an error occured during the transferm the `s3_upload_failed` is triggered on the form with the same `content` object is passed for the successful upload with the addition of the `error_thrown` attribute. The most basic way to handle this error would be to display an alert message to the user in case the upload fails :
205
+ ```coffeescript
206
+ $('#myS3Uploader').bind "s3_upload_failed", (e, content) ->
207
+ alert("#{content.filename} failed to upload : #{content.error_thrown}")
208
+ ```
209
+
210
+ #### All uploads completed
211
+ When all uploads finish in a batch an `s3_uploads_complete` event will be triggered on `document`, so you could do something like:
212
+ ```coffeescript
213
+ $(document).bind 's3_uploads_complete', ->
214
+ alert("All Uploads completed")
215
+ ```
216
+
217
+ #### Rails AJAX Callbacks
218
+
219
+ In addition, the regular rails ajax callbacks will trigger on the form with regards to the POST to the server.
220
+
221
+ ```coffeescript
222
+ $('#myS3Uploader').bind "ajax:success", (e, data) ->
223
+ alert("server was notified of new file on S3; responded with '#{data}")
224
+ ```
225
+
226
+ ## Cleaning old uploads on S3
227
+ You may be processing the files upon upload and reuploading them to another
228
+ bucket or directory. If so you can remove the originali files by running a
229
+ rake task.
230
+
231
+ First, add the fog gem to your `Gemfile` and run `bundle`:
232
+ ```ruby
233
+ require 'fog'
234
+ ```
235
+
236
+ Then, run the rake task to delete uploads older than 2 days:
237
+ ```
238
+ $ rake s3_direct_upload:clean_remote_uploads
239
+ Deleted file with key: "uploads/20121210T2139Z_03846cb0329b6a8eba481ec689135701/06 - PCR_RYA014-25.jpg"
240
+ Deleted file with key: "uploads/20121210T2139Z_03846cb0329b6a8eba481ec689135701/05 - PCR_RYA014-24.jpg"
241
+ $
242
+ ```
243
+
244
+ Optionally customize the prefix used for cleaning (default is `uploads/#{2.days.ago.strftime('%Y%m%d')}`):
245
+ **config/initalizers/s3_direct_upload.rb**
246
+ ```ruby
247
+ S3DirectUpload.config do |c|
248
+ # ...
249
+ c.prefix_to_clean = "my_path/#{1.week.ago.strftime('%y%m%d')}"
250
+ end
251
+ ```
252
+
253
+ Alternately, if you'd prefer for S3 to delete your old uploads automatically, you can do
254
+ so by setting your bucket's
255
+ [Lifecycle Configuration](http://docs.aws.amazon.com/AmazonS3/latest/UG/LifecycleConfiguration.html).
256
+
257
+ ## Contributing / TODO
258
+ This is just a simple gem that only really provides some javascript and a form helper.
259
+ This gem could go all sorts of ways based on what people want and how people contribute.
260
+ Ideas:
261
+ * More specs!
262
+ * More options to control file types, ability to batch upload.
263
+ * More convention over configuration on rails side
264
+ * Create generators.
265
+ * Model methods.
266
+ * Model method to delete files from s3
267
+
268
+
269
+ ## Credit
270
+ This gem is basically a small wrapper around code that [Ryan Bates](http://github.com/rbates) wrote for [Railscast#383](http://railscasts.com/episodes/383-uploading-to-amazon-s3). Most of the code in this gem was extracted from [gallery-jquery-fileupload](https://github.com/railscasts/383-uploading-to-amazon-s3/tree/master/gallery-jquery-fileupload).
271
+
272
+ Thank you Ryan Bates!
273
+
274
+ This code also uses the excellecnt [jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload), which is included in this gem by its rails counterpart [jquery-fileupload-rails](https://github.com/tors/jquery-fileupload-rails)
@@ -0,0 +1,153 @@
1
+ #= require jquery-fileupload/basic
2
+ #= require jquery-fileupload/vendor/tmpl
3
+
4
+ $ = jQuery
5
+
6
+ $.fn.S3Uploader = (options) ->
7
+
8
+ # support multiple elements
9
+ if @length > 1
10
+ @each ->
11
+ $(this).S3Uploader options
12
+
13
+ return this
14
+
15
+ $uploadForm = this
16
+
17
+ settings =
18
+ path: ''
19
+ additional_data: null
20
+ before_add: null
21
+ remove_completed_progress_bar: true
22
+ remove_failed_progress_bar: false
23
+ progress_bar_target: null
24
+ click_submit_target: null
25
+ allow_multiple_files: true
26
+
27
+ $.extend settings, options
28
+
29
+ current_files = []
30
+ forms_for_submit = []
31
+ if settings.click_submit_target
32
+ settings.click_submit_target.click ->
33
+ form.submit() for form in forms_for_submit
34
+ false
35
+
36
+ setUploadForm = ->
37
+ $uploadForm.fileupload
38
+
39
+ add: (e, data) ->
40
+ file = data.files[0]
41
+ file.unique_id = Math.random().toString(36).substr(2,16)
42
+
43
+ unless settings.before_add and not settings.before_add(file)
44
+ current_files.push data
45
+ if $('#template-upload').length > 0
46
+ data.context = $($.trim(tmpl("template-upload", file)))
47
+ $(data.context).appendTo(settings.progress_bar_target || $uploadForm)
48
+ else if !settings.allow_multiple_files
49
+ data.context = settings.progress_bar_target
50
+ if settings.click_submit_target
51
+ if settings.allow_multiple_files
52
+ forms_for_submit.push data
53
+ else
54
+ forms_for_submit = [data]
55
+ else
56
+ data.submit()
57
+
58
+ start: (e) ->
59
+ $uploadForm.trigger("s3_uploads_start", [e])
60
+
61
+ progress: (e, data) ->
62
+ if data.context
63
+ progress = parseInt(data.loaded / data.total * 100, 10)
64
+ data.context.find('.bar').css('width', progress + '%')
65
+
66
+ done: (e, data) ->
67
+ content = build_content_object $uploadForm, data.files[0], data.result
68
+
69
+ callback_url = $uploadForm.data('callback-url')
70
+ if callback_url
71
+ content[$uploadForm.data('callback-param')] = content.url
72
+
73
+ $.ajax
74
+ type: $uploadForm.data('callback-method')
75
+ url: callback_url
76
+ data: content
77
+ beforeSend: ( xhr, settings ) -> $uploadForm.trigger( 'ajax:beforeSend', [xhr, settings] )
78
+ complete: ( xhr, status ) -> $uploadForm.trigger( 'ajax:complete', [xhr, status] )
79
+ success: ( data, status, xhr ) -> $uploadForm.trigger( 'ajax:success', [data, status, xhr] )
80
+ error: ( xhr, status, error ) -> $uploadForm.trigger( 'ajax:error', [xhr, status, error] )
81
+
82
+ data.context.remove() if data.context && settings.remove_completed_progress_bar # remove progress bar
83
+ $uploadForm.trigger("s3_upload_complete", [content])
84
+
85
+ current_files.splice($.inArray(data, current_files), 1) # remove that element from the array
86
+ $uploadForm.trigger("s3_uploads_complete", [content]) unless current_files.length
87
+
88
+ fail: (e, data) ->
89
+ content = build_content_object $uploadForm, data.files[0], data.result
90
+ content.error_thrown = data.errorThrown
91
+
92
+ data.context.remove() if data.context && settings.remove_failed_progress_bar # remove progress bar
93
+ $uploadForm.trigger("s3_upload_failed", [content])
94
+
95
+ formData: (form) ->
96
+ data = form.serializeArray()
97
+ fileType = ""
98
+ if "type" of @files[0]
99
+ fileType = @files[0].type
100
+ data.push
101
+ name: "content-type"
102
+ value: fileType
103
+
104
+ key = $uploadForm.data("key").replace('{timestamp}', new Date().getTime()).replace('{unique_id}', @files[0].unique_id)
105
+
106
+ # substitute upload timestamp and unique_id into key
107
+ data[1].value = settings.path + key
108
+
109
+ # IE <= 9 doesn't have XHR2 hence it can't use formData
110
+ # replace 'key' field to submit form
111
+ unless 'FormData' of window
112
+ $uploadForm.find("input[name='key']").val(settings.path + key)
113
+ data
114
+
115
+ build_content_object = ($uploadForm, file, result) ->
116
+ content = {}
117
+ if result # Use the S3 response to set the URL to avoid character encodings bugs
118
+ content.url = $(result).find("Location").text()
119
+ content.filepath = $('<a />').attr('href', content.url)[0].pathname
120
+ else # IE <= 9 return a null result object so we use the file object instead
121
+ domain = $uploadForm.attr('action')
122
+ content.filepath = $uploadForm.find('input[name=key]').val().replace('/${filename}', '')
123
+ content.url = domain + content.filepath + '/' + encodeURIComponent(file.name)
124
+
125
+ content.filename = file.name
126
+ content.filesize = file.size if 'size' of file
127
+ content.filetype = file.type if 'type' of file
128
+ content.unique_id = file.unique_id if 'unique_id' of file
129
+ content.relativePath = build_relativePath(file) if has_relativePath(file)
130
+ content = $.extend content, settings.additional_data if settings.additional_data
131
+ content
132
+
133
+ has_relativePath = (file) ->
134
+ file.relativePath || file.webkitRelativePath
135
+
136
+ build_relativePath = (file) ->
137
+ file.relativePath || (file.webkitRelativePath.split("/")[0..-2].join("/") + "/" if file.webkitRelativePath)
138
+
139
+ #public methods
140
+ @initialize = ->
141
+ # Save key for IE9 Fix
142
+ $uploadForm.data("key", $uploadForm.find("input[name='key']").val())
143
+
144
+ setUploadForm()
145
+ this
146
+
147
+ @path = (new_path) ->
148
+ settings.path = new_path
149
+
150
+ @additional_data = (new_data) ->
151
+ settings.additional_data = new_data
152
+
153
+ @initialize()
@@ -0,0 +1,17 @@
1
+ .upload {
2
+ border-top: solid 1px #CCC;
3
+ width: 400px;
4
+ padding-top: 10px;
5
+ margin-top: 10px;
6
+
7
+ .progress {
8
+ margin-top: 8px;
9
+ border: solid 1px #555;
10
+ border-radius: 3px;
11
+ -moz-border-radius: 3px;
12
+ .bar {
13
+ height: 10px;
14
+ background: #3EC144;
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,18 @@
1
+ require "singleton"
2
+
3
+ module S3DirectUpload
4
+ class Config
5
+ include Singleton
6
+
7
+ ATTRIBUTES = [:access_key_id, :secret_access_key, :bucket, :prefix_to_clean, :region, :url]
8
+
9
+ attr_accessor *ATTRIBUTES
10
+ end
11
+
12
+ def self.config
13
+ if block_given?
14
+ yield Config.instance
15
+ end
16
+ Config.instance
17
+ end
18
+ end
@@ -0,0 +1,4 @@
1
+ module S3DirectUpload
2
+ class Engine < ::Rails::Engine
3
+ end
4
+ end
@@ -0,0 +1,96 @@
1
+ module S3DirectUpload
2
+ module UploadHelper
3
+ def s3_uploader_form(options = {}, &block)
4
+ uploader = S3Uploader.new(options)
5
+ form_tag(uploader.url, uploader.form_options) do
6
+ uploader.fields.map do |name, value|
7
+ hidden_field_tag(name, value)
8
+ end.join.html_safe + capture(&block)
9
+ end
10
+ end
11
+
12
+ class S3Uploader
13
+ def initialize(options)
14
+ @key_starts_with = options[:key_starts_with] || "uploads/"
15
+ @options = options.reverse_merge(
16
+ aws_access_key_id: S3DirectUpload.config.access_key_id,
17
+ aws_secret_access_key: S3DirectUpload.config.secret_access_key,
18
+ bucket: S3DirectUpload.config.bucket,
19
+ region: S3DirectUpload.config.region || "s3",
20
+ url: S3DirectUpload.config.url,
21
+ ssl: true,
22
+ expiration: 10.hours.from_now.utc.iso8601,
23
+ max_file_size: 500.megabytes,
24
+ callback_method: "POST",
25
+ callback_param: "file",
26
+ key_starts_with: @key_starts_with,
27
+ key: key
28
+ )
29
+ end
30
+
31
+ def form_options
32
+ {
33
+ id: @options[:id],
34
+ class: @options[:class],
35
+ method: "post",
36
+ authenticity_token: false,
37
+ multipart: true,
38
+ data: {
39
+ callback_url: @options[:callback_url],
40
+ callback_method: @options[:callback_method],
41
+ callback_param: @options[:callback_param]
42
+ }.reverse_merge(@options[:data] || {})
43
+ }
44
+ end
45
+
46
+ def fields
47
+ {
48
+ :key => @options[:key] || key,
49
+ :acl => @options[:acl],
50
+ "AWSAccessKeyId" => @options[:aws_access_key_id],
51
+ :policy => policy,
52
+ :signature => signature,
53
+ :success_action_status => "201",
54
+ 'X-Requested-With' => 'xhr'
55
+ }
56
+ end
57
+
58
+ def key
59
+ @key ||= "#{@key_starts_with}{timestamp}-{unique_id}-#{SecureRandom.hex}/${filename}"
60
+ end
61
+
62
+ def url
63
+ @options[:url] || "http#{@options[:ssl] ? 's' : ''}://#{@options[:region]}.amazonaws.com/#{@options[:bucket]}/"
64
+ end
65
+
66
+ def policy
67
+ Base64.encode64(policy_data.to_json).gsub("\n", "")
68
+ end
69
+
70
+ def policy_data
71
+ {
72
+ expiration: @options[:expiration],
73
+ conditions: [
74
+ ["starts-with", "$utf8", ""],
75
+ ["starts-with", "$key", @options[:key_starts_with]],
76
+ ["starts-with", "$x-requested-with", ""],
77
+ ["content-length-range", 0, @options[:max_file_size]],
78
+ ["starts-with","$content-type", @options[:content_type_starts_with] ||""],
79
+ {bucket: @options[:bucket]},
80
+ {acl: @options[:acl]},
81
+ {success_action_status: "201"}
82
+ ] + (@options[:conditions] || [])
83
+ }
84
+ end
85
+
86
+ def signature
87
+ Base64.encode64(
88
+ OpenSSL::HMAC.digest(
89
+ OpenSSL::Digest::Digest.new('sha1'),
90
+ @options[:aws_secret_access_key], policy
91
+ )
92
+ ).gsub("\n", "")
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,7 @@
1
+ module S3DirectUpload
2
+ class Railtie < Rails::Railtie
3
+ initializer "railtie.configure_rails_initialization" do |app|
4
+ app.middleware.use JQuery::FileUpload::Rails::Middleware
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ module S3DirectUpload
2
+ VERSION = "0.1.6"
3
+ end
@@ -0,0 +1,13 @@
1
+ require 's3_direct_upload/version'
2
+ require 'jquery-fileupload-rails' if defined?(Rails)
3
+
4
+ require 'base64'
5
+ require 'openssl'
6
+ require 'digest/sha1'
7
+
8
+ require 's3_direct_upload/config_aws'
9
+ require 's3_direct_upload/form_helper'
10
+ require 's3_direct_upload/engine' if defined?(Rails)
11
+ require 's3_direct_upload/railtie' if defined?(Rails)
12
+
13
+ ActionView::Base.send(:include, S3DirectUpload::UploadHelper) if defined?(ActionView::Base)
@@ -0,0 +1,57 @@
1
+ namespace :s3_direct_upload do
2
+ desc "Removes old uploads from specified s3 bucket/directory -- Useful when uploads are processed into another directory"
3
+ task :clean_remote_uploads => :environment do
4
+ require 'thread'
5
+ require 'fog'
6
+
7
+ s3 = Fog::Storage::AWS.new(aws_access_key_id: S3DirectUpload.config.access_key_id, aws_secret_access_key: S3DirectUpload.config.secret_access_key)
8
+ bucket = S3DirectUpload.config.bucket
9
+ prefix = S3DirectUpload.config.prefix_to_clean || "uploads/#{2.days.ago.strftime('%Y%m%d')}"
10
+
11
+ queue = Queue.new
12
+ semaphore = Mutex.new
13
+ threads = []
14
+ thread_count = 20
15
+ total_listed = 0
16
+ total_deleted = 0
17
+
18
+ threads << Thread.new do
19
+ Thread.current[:name] = "get files"
20
+ # Get all the files from this bucket. Fog handles pagination internally.
21
+ s3.directories.get("#{bucket}").files.all({prefix: prefix}).each do |file|
22
+ queue.enq(file)
23
+ total_listed += 1
24
+ end
25
+ # Add a final EOF message to signal the deletion threads to stop.
26
+ thread_count.times { queue.enq(:EOF) }
27
+ end
28
+
29
+ # Delete all the files in the queue until EOF with N threads.
30
+ thread_count.times do |count|
31
+ threads << Thread.new(count) do |number|
32
+ Thread.current[:name] = "delete files(#{number})"
33
+ # Dequeue until EOF.
34
+ file = nil
35
+ while file != :EOF
36
+ # Dequeue the latest file and delete it. (Will block until it gets a new file.)
37
+ file = queue.deq
38
+ unless file == :EOF
39
+ file.destroy
40
+ puts %Q{Deleted file with key: "#{file.key}"}
41
+ end
42
+ # Increment the global synchronized counter.
43
+ semaphore.synchronize {total_deleted += 1}
44
+ end
45
+ end
46
+ end
47
+
48
+ # Wait for the threads to finish.
49
+ threads.each do |t|
50
+ begin
51
+ t.join
52
+ rescue RuntimeError => e
53
+ puts "Failure on thread #{t[:name]}: #{e.message}"
54
+ end
55
+ end
56
+ end
57
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: s3_private_direct_upload
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.6
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Wayne Hoover
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2013-07-16 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rails
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '3.2'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '3.2'
30
+ - !ruby/object:Gem::Dependency
31
+ name: coffee-rails
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: 3.2.1
38
+ type: :runtime
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: 3.2.1
46
+ - !ruby/object:Gem::Dependency
47
+ name: sass-rails
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: 3.2.5
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: 3.2.5
62
+ - !ruby/object:Gem::Dependency
63
+ name: jquery-fileupload-rails
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ~>
68
+ - !ruby/object:Gem::Version
69
+ version: 0.4.1
70
+ type: :runtime
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ~>
76
+ - !ruby/object:Gem::Version
77
+ version: 0.4.1
78
+ description: Direct Upload to Amazon S3 With CORS and jquery-file-upload
79
+ email:
80
+ - w@waynehoover.com
81
+ executables: []
82
+ extensions: []
83
+ extra_rdoc_files: []
84
+ files:
85
+ - lib/s3_direct_upload/config_aws.rb
86
+ - lib/s3_direct_upload/engine.rb
87
+ - lib/s3_direct_upload/form_helper.rb
88
+ - lib/s3_direct_upload/railtie.rb
89
+ - lib/s3_direct_upload/version.rb
90
+ - lib/s3_direct_upload.rb
91
+ - lib/tasks/s3_direct_upload.rake
92
+ - app/assets/javascripts/s3_direct_upload.js.coffee
93
+ - app/assets/stylesheets/s3_direct_upload_progress_bars.css.scss
94
+ - LICENSE
95
+ - README.md
96
+ homepage: ''
97
+ licenses: []
98
+ post_install_message:
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ none: false
104
+ requirements:
105
+ - - ! '>='
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ required_rubygems_version: !ruby/object:Gem::Requirement
109
+ none: false
110
+ requirements:
111
+ - - ! '>='
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubyforge_project:
116
+ rubygems_version: 1.8.23
117
+ signing_key:
118
+ specification_version: 3
119
+ summary: Gives a form helper for Rails which allows direct uploads to s3. Based on
120
+ RailsCast#383. Makes files private on S3
121
+ test_files: []