activestorage_legacy 0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (136) hide show
  1. checksums.yaml +7 -0
  2. data/.babelrc +5 -0
  3. data/.codeclimate.yml +7 -0
  4. data/.eslintrc +19 -0
  5. data/.github/workflows/gem-push.yml +29 -0
  6. data/.github/workflows/ruby-tests.yml +37 -0
  7. data/.gitignore +9 -0
  8. data/.rubocop.yml +125 -0
  9. data/.travis.yml +25 -0
  10. data/Gemfile +33 -0
  11. data/Gemfile.lock +271 -0
  12. data/MIT-LICENSE +20 -0
  13. data/README.md +160 -0
  14. data/Rakefile +12 -0
  15. data/activestorage.gemspec +27 -0
  16. data/app/assets/javascripts/activestorage.js +1 -0
  17. data/app/controllers/active_storage/blobs_controller.rb +22 -0
  18. data/app/controllers/active_storage/direct_uploads_controller.rb +21 -0
  19. data/app/controllers/active_storage/disk_controller.rb +52 -0
  20. data/app/controllers/active_storage/variants_controller.rb +28 -0
  21. data/app/helpers/active_storage/file_field_with_direct_upload_helper.rb +18 -0
  22. data/app/javascript/activestorage/blob_record.js +54 -0
  23. data/app/javascript/activestorage/blob_upload.js +34 -0
  24. data/app/javascript/activestorage/direct_upload.js +42 -0
  25. data/app/javascript/activestorage/direct_upload_controller.js +67 -0
  26. data/app/javascript/activestorage/direct_uploads_controller.js +50 -0
  27. data/app/javascript/activestorage/file_checksum.js +53 -0
  28. data/app/javascript/activestorage/helpers.js +42 -0
  29. data/app/javascript/activestorage/index.js +11 -0
  30. data/app/javascript/activestorage/ujs.js +74 -0
  31. data/app/jobs/active_storage/purge_attachment_worker.rb +9 -0
  32. data/app/jobs/active_storage/purge_blob_worker.rb +9 -0
  33. data/app/models/active_storage/attachment.rb +33 -0
  34. data/app/models/active_storage/blob.rb +198 -0
  35. data/app/models/active_storage/filename.rb +49 -0
  36. data/app/models/active_storage/variant.rb +82 -0
  37. data/app/models/active_storage/variation.rb +53 -0
  38. data/config/routes.rb +9 -0
  39. data/config/storage_services.yml +34 -0
  40. data/lib/active_storage/attached/macros.rb +86 -0
  41. data/lib/active_storage/attached/many.rb +51 -0
  42. data/lib/active_storage/attached/one.rb +56 -0
  43. data/lib/active_storage/attached.rb +38 -0
  44. data/lib/active_storage/engine.rb +81 -0
  45. data/lib/active_storage/gem_version.rb +15 -0
  46. data/lib/active_storage/log_subscriber.rb +48 -0
  47. data/lib/active_storage/messages_metadata.rb +64 -0
  48. data/lib/active_storage/migration.rb +27 -0
  49. data/lib/active_storage/patches/active_record.rb +19 -0
  50. data/lib/active_storage/patches/delegation.rb +98 -0
  51. data/lib/active_storage/patches/secure_random.rb +26 -0
  52. data/lib/active_storage/patches.rb +4 -0
  53. data/lib/active_storage/service/azure_service.rb +115 -0
  54. data/lib/active_storage/service/configurator.rb +28 -0
  55. data/lib/active_storage/service/disk_service.rb +124 -0
  56. data/lib/active_storage/service/gcs_service.rb +79 -0
  57. data/lib/active_storage/service/mirror_service.rb +46 -0
  58. data/lib/active_storage/service/s3_service.rb +96 -0
  59. data/lib/active_storage/service.rb +113 -0
  60. data/lib/active_storage/verifier.rb +113 -0
  61. data/lib/active_storage/version.rb +8 -0
  62. data/lib/active_storage.rb +34 -0
  63. data/lib/tasks/activestorage.rake +20 -0
  64. data/package.json +33 -0
  65. data/test/controllers/direct_uploads_controller_test.rb +123 -0
  66. data/test/controllers/disk_controller_test.rb +57 -0
  67. data/test/controllers/variants_controller_test.rb +21 -0
  68. data/test/database/create_users_migration.rb +7 -0
  69. data/test/database/setup.rb +6 -0
  70. data/test/dummy/Rakefile +3 -0
  71. data/test/dummy/app/assets/config/manifest.js +5 -0
  72. data/test/dummy/app/assets/images/.keep +0 -0
  73. data/test/dummy/app/assets/javascripts/application.js +13 -0
  74. data/test/dummy/app/assets/stylesheets/application.css +15 -0
  75. data/test/dummy/app/controllers/application_controller.rb +3 -0
  76. data/test/dummy/app/controllers/concerns/.keep +0 -0
  77. data/test/dummy/app/helpers/application_helper.rb +2 -0
  78. data/test/dummy/app/jobs/application_job.rb +2 -0
  79. data/test/dummy/app/models/application_record.rb +3 -0
  80. data/test/dummy/app/models/concerns/.keep +0 -0
  81. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  82. data/test/dummy/bin/bundle +3 -0
  83. data/test/dummy/bin/rails +4 -0
  84. data/test/dummy/bin/rake +4 -0
  85. data/test/dummy/bin/yarn +11 -0
  86. data/test/dummy/config/application.rb +22 -0
  87. data/test/dummy/config/boot.rb +5 -0
  88. data/test/dummy/config/database.yml +25 -0
  89. data/test/dummy/config/environment.rb +5 -0
  90. data/test/dummy/config/environments/development.rb +49 -0
  91. data/test/dummy/config/environments/production.rb +82 -0
  92. data/test/dummy/config/environments/test.rb +33 -0
  93. data/test/dummy/config/initializers/application_controller_renderer.rb +6 -0
  94. data/test/dummy/config/initializers/assets.rb +14 -0
  95. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  96. data/test/dummy/config/initializers/cookies_serializer.rb +5 -0
  97. data/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  98. data/test/dummy/config/initializers/inflections.rb +16 -0
  99. data/test/dummy/config/initializers/mime_types.rb +4 -0
  100. data/test/dummy/config/initializers/secret_key.rb +3 -0
  101. data/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  102. data/test/dummy/config/routes.rb +2 -0
  103. data/test/dummy/config/secrets.yml +32 -0
  104. data/test/dummy/config/spring.rb +6 -0
  105. data/test/dummy/config/storage_services.yml +3 -0
  106. data/test/dummy/config.ru +5 -0
  107. data/test/dummy/db/.keep +0 -0
  108. data/test/dummy/lib/assets/.keep +0 -0
  109. data/test/dummy/log/.keep +0 -0
  110. data/test/dummy/package.json +5 -0
  111. data/test/dummy/public/404.html +67 -0
  112. data/test/dummy/public/422.html +67 -0
  113. data/test/dummy/public/500.html +66 -0
  114. data/test/dummy/public/apple-touch-icon-precomposed.png +0 -0
  115. data/test/dummy/public/apple-touch-icon.png +0 -0
  116. data/test/dummy/public/favicon.ico +0 -0
  117. data/test/filename_test.rb +36 -0
  118. data/test/fixtures/files/racecar.jpg +0 -0
  119. data/test/models/attachments_test.rb +122 -0
  120. data/test/models/blob_test.rb +47 -0
  121. data/test/models/variant_test.rb +27 -0
  122. data/test/service/.gitignore +1 -0
  123. data/test/service/azure_service_test.rb +14 -0
  124. data/test/service/configurations-example.yml +31 -0
  125. data/test/service/configurator_test.rb +14 -0
  126. data/test/service/disk_service_test.rb +12 -0
  127. data/test/service/gcs_service_test.rb +42 -0
  128. data/test/service/mirror_service_test.rb +62 -0
  129. data/test/service/s3_service_test.rb +52 -0
  130. data/test/service/shared_service_tests.rb +66 -0
  131. data/test/sidekiq/minitest_support.rb +6 -0
  132. data/test/support/assertions.rb +20 -0
  133. data/test/test_helper.rb +69 -0
  134. data/webpack.config.js +27 -0
  135. data/yarn.lock +3164 -0
  136. metadata +330 -0
data/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # Active Storage (Rails 3 compatible)
2
+
3
+ [![Maintainability](https://api.codeclimate.com/v1/badges/08cd6d56a89a29295a83/maintainability)](https://codeclimate.com/github/iagopiimenta/activestorage_legacy/maintainability)
4
+ [![Test Coverage](https://api.codeclimate.com/v1/badges/08cd6d56a89a29295a83/test_coverage)](https://codeclimate.com/github/iagopiimenta/activestorage_legacy/test_coverage)
5
+
6
+ ## Forked to work with Rails 3
7
+
8
+ See the complete list of changes in https://github.com/rails/activestorage/compare/archive...iagopiimenta:activestorage_legacy:main
9
+
10
+ ## Installation
11
+
12
+ 1. Add `gem "activestorage_legacy", git: "https://github.com/rails/activestorage.git"` to your Gemfile.
13
+ 2. Add `require "active_storage"` to config/application.rb, after `require "rails/all"` line.
14
+ 3. Run `rake activestorage:install` to create needed directories, migrations, and configuration.
15
+ 4. Configure the storage service in `config/environments/*` with `config.active_storage.service = :local`
16
+ that references the services configured in `config/storage_services.yml`.
17
+ 5. Optional: Add `gem "aws-sdk", "~> 2"` to your Gemfile if you want to use AWS S3.
18
+ 6. Optional: Add `gem "google-cloud-storage", "~> 1.3"` to your Gemfile if you want to use Google Cloud Storage.
19
+ 7. Optional: Add `gem "mini_magick"` to your Gemfile if you want to use variants.
20
+
21
+ ## Overview
22
+
23
+ Active Storage makes it simple to upload and reference files in cloud services, like Amazon S3 or Google Cloud Storage,
24
+ and attach those files to Active Records. It also provides a disk service for testing or local deployments, but the
25
+ focus is on cloud storage.
26
+
27
+ Files can uploaded from the server to the cloud or directly from the client to the cloud.
28
+
29
+ Image files can further more be transformed using on-demand variants for quality, aspect ratio, size, or any other
30
+ MiniMagick supported transformation.
31
+
32
+ ## Compared to other storage solutions
33
+
34
+ A key difference to how Active Storage works compared to other attachment solutions in Rails is through the use of built-in [Blob](https://github.com/rails/activestorage/blob/master/app/models/active_storage/blob.rb) and [Attachment](https://github.com/rails/activestorage/blob/master/app/models/active_storage/attachment.rb) models (backed by Active Record). This means existing application models do not need to be modified with additional columns to associate with files. Active Storage uses polymorphic associations via the join model of `Attachment`, which then connects to the actual `Blob`.
35
+
36
+ These `Blob` models are intended to be immutable in spirit. One file, one blob. You can associate the same blob with multiple application models as well. And if you want to do transformations of a given `Blob`, the idea is that you'll simply create a new one, rather than attempt to mutate the existing (though of course you can delete that later if you don't need it).
37
+
38
+ ## Examples
39
+
40
+ One attachment:
41
+
42
+ ```ruby
43
+ class User < ApplicationRecord
44
+ has_one_attached :avatar
45
+ end
46
+
47
+ user.avatar.attach io: File.open("~/face.jpg"), filename: "avatar.jpg", content_type: "image/jpg"
48
+ user.avatar.attached? # => true
49
+
50
+ user.avatar.purge
51
+ user.avatar.attached? # => false
52
+
53
+ url_for(user.avatar) # Generate a permanent URL for the blob, which upon access will redirect to a temporary service URL.
54
+
55
+ class AvatarsController < ApplicationController
56
+ def update
57
+ # params[:avatar] contains a ActionDispatch::Http::UploadedFile object
58
+ Current.user.avatar.attach(params.require(:avatar))
59
+ redirect_to Current.user
60
+ end
61
+ end
62
+ ```
63
+
64
+ Many attachments:
65
+
66
+ ```ruby
67
+ class Message < ApplicationRecord
68
+ has_many_attached :images
69
+ end
70
+ ```
71
+
72
+ ```erb
73
+ <%= form_with model: @message do |form| %>
74
+ <%= form.text_field :title, placeholder: "Title" %><br>
75
+ <%= form.text_area :content %><br><br>
76
+
77
+ <%= form.file_field :images, multiple: true %><br>
78
+ <%= form.submit %>
79
+ <% end %>
80
+ ```
81
+
82
+ ```ruby
83
+ class MessagesController < ApplicationController
84
+ def index
85
+ # Use the built-in with_attached_images scope to avoid N+1
86
+ @messages = Message.all.with_attached_images
87
+ end
88
+
89
+ def create
90
+ message = Message.create! params.require(:message).permit(:title, :content)
91
+ message.images.attach(params[:message][:images])
92
+ redirect_to message
93
+ end
94
+
95
+ def show
96
+ @message = Message.find(params[:id])
97
+ end
98
+ end
99
+ ```
100
+
101
+ Variation of image attachment:
102
+
103
+ ```erb
104
+ <%# Hitting the variant URL will lazy transform the original blob and then redirect to its new service location %>
105
+ <%= image_tag url_for(user.avatar.variant(resize: "100x100")) %>
106
+ ```
107
+
108
+ ## Direct uploads
109
+
110
+ Active Storage, with its included JavaScript library, supports uploading directly from the client to the cloud.
111
+
112
+ ### Direct upload installation
113
+
114
+ 1. Include `activestorage.js` in your application's JavaScript bundle.
115
+
116
+ Using the asset pipeline:
117
+ ```js
118
+ //= require activestorage
119
+ ```
120
+ Using the npm package:
121
+ ```js
122
+ import * as ActiveStorage from "activestorage"
123
+ ActiveStorage.start()
124
+ ```
125
+ 2. Annotate file inputs with the direct upload URL.
126
+
127
+ ```ruby
128
+ <%= form.file_field :attachments, multiple: true, direct_upload: true %>
129
+ ```
130
+ 3. That's it! Uploads begin upon form submission.
131
+
132
+ ### Direct upload JavaScript events
133
+
134
+ | Event name | Event target | Event data (`event.detail`) | Description |
135
+ | --- | --- | --- | --- |
136
+ | `direct-uploads:start` | `<form>` | None | A form containing files for direct upload fields was submit. |
137
+ | `direct-upload:initialize` | `<input>` | `{id, file}` | Dispatched for every file after form submission. |
138
+ | `direct-upload:start` | `<input>` | `{id, file}` | A direct upload is starting. |
139
+ | `direct-upload:before-blob-request` | `<input>` | `{id, file, xhr}` | Before making a request to your application for direct upload metadata. |
140
+ | `direct-upload:before-storage-request` | `<input>` | `{id, file, xhr}` | Before making a request to store a file. |
141
+ | `direct-upload:progress` | `<input>` | `{id, file, progress}` | As requests to store files progress. |
142
+ | `direct-upload:error` | `<input>` | `{id, file, error}` | An error occurred. An `alert` will display unless this event is canceled. |
143
+ | `direct-upload:end` | `<input>` | `{id, file}` | A direct upload has ended. |
144
+ | `direct-uploads:end` | `<form>` | None | All direct uploads have ended. |
145
+
146
+ ## Compatibility & Expectations
147
+
148
+ Active Storage only works with the development version of Rails 5.2+ (as of July 19, 2017). This separate repository is a staging ground for the upcoming inclusion in rails/rails prior to the Rails 5.2 release. It is not intended to be a long-term stand-alone repository.
149
+
150
+ Furthermore, this repository is likely to be in heavy flux prior to the merge to rails/rails. You're heartedly encouraged to follow along and even use Active Storage in this phase, but don't be surprised if the API suffers frequent breaking changes prior to the merge.
151
+
152
+ ## Todos
153
+
154
+ - Convert MirrorService to use threading
155
+ - Read metadata via Marcel?
156
+ - Add Migrator to copy/move between services
157
+
158
+ ## License
159
+
160
+ Active Storage is released under the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require "bundler/setup"
2
+ require "bundler/gem_tasks"
3
+ require "rake/testtask"
4
+
5
+ Rake::TestTask.new do |test|
6
+ test.libs << "app/controllers"
7
+ test.libs << "test"
8
+ test.test_files = FileList["test/**/*_test.rb"]
9
+ test.warning = false
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,27 @@
1
+ %w(models contollers helpers jobs).each do |dir|
2
+ path = File.expand_path("../app/#{dir}", __FILE__)
3
+ $LOAD_PATH.unshift(path) unless $LOAD_PATH.include?(path)
4
+ end
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "activestorage_legacy"
8
+ s.version = "0.1"
9
+ s.authors = "David Heinemeier Hansson"
10
+ s.email = "david@basecamp.com"
11
+ s.summary = "Attach cloud and local files in Rails applications"
12
+ s.homepage = "https://github.com/rails/activestorage"
13
+ s.license = "MIT"
14
+
15
+ s.required_ruby_version = ">= 2.2.2"
16
+
17
+ s.add_dependency "rails", ">= 3.2.22.4"
18
+ s.add_dependency "sidekiq", ">= 4.2.0"
19
+ s.add_dependency "strong_parameters"
20
+ s.add_dependency "mini_magick", ">= 4.0"
21
+ s.add_dependency "marcel", ">= 1.0"
22
+
23
+ s.add_development_dependency "bundler", "~> 1.15"
24
+
25
+ s.files = `git ls-files`.split("\n")
26
+ s.test_files = `git ls-files -- test/*`.split("\n")
27
+ end
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ActiveStorage=e():t.ActiveStorage=e()}(this,function(){return function(t){function e(n){if(r[n])return r[n].exports;var i=r[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var r={};return e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=2)}([function(t,e,r){"use strict";function n(t){var e=a(document.head,'meta[name="'+t+'"]');if(e)return e.getAttribute("content")}function i(t,e){return"string"==typeof t&&(e=t,t=document),o(t.querySelectorAll(e))}function a(t,e){return"string"==typeof t&&(e=t,t=document),t.querySelector(e)}function u(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.bubbles,i=r.cancelable,a=r.detail,u=document.createEvent("Event");return u.initEvent(e,n||!0,i||!0),u.detail=a||{},t.dispatchEvent(u),u}function o(t){return Array.isArray(t)?t:Array.from?Array.from(t):[].slice.call(t)}e.d=n,e.c=i,e.b=a,e.a=u,e.e=o},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(t&&"function"==typeof t[e]){for(var r=arguments.length,n=Array(r>2?r-2:0),i=2;i<r;i++)n[i-2]=arguments[i];return t[e].apply(t,n)}}r.d(e,"a",function(){return c});var a=r(6),u=r(8),o=r(9),s=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),f=0,c=function(){function t(e,r,i){n(this,t),this.id=++f,this.file=e,this.url=r,this.delegate=i}return s(t,[{key:"create",value:function(t){var e=this;a.a.create(this.file,function(r,n){var a=new u.a(e.file,n,e.url);i(e.delegate,"directUploadWillCreateBlobWithXHR",a.xhr),a.create(function(r){if(r)t(r);else{var n=new o.a(a);i(e.delegate,"directUploadWillStoreFileWithXHR",n.xhr),n.create(function(e){e?t(e):t(null,a.toJSON())})}})})}}]),t}()},function(t,e,r){"use strict";function n(){window.ActiveStorage&&Object(i.a)()}Object.defineProperty(e,"__esModule",{value:!0});var i=r(3),a=r(1);r.d(e,"start",function(){return i.a}),r.d(e,"DirectUpload",function(){return a.a}),setTimeout(n,1)},function(t,e,r){"use strict";function n(){d||(d=!0,document.addEventListener("submit",i),document.addEventListener("ajax:before",a))}function i(t){u(t)}function a(t){"FORM"==t.target.tagName&&u(t)}function u(t){var e=t.target;if(e.hasAttribute(l))return void t.preventDefault();var r=new c.a(e),n=r.inputs;n.length&&(t.preventDefault(),e.setAttribute(l,""),n.forEach(s),r.start(function(t){e.removeAttribute(l),t?n.forEach(f):o(e)}))}function o(t){var e=Object(h.b)(t,"input[type=submit]");if(e){var r=e,n=r.disabled;e.disabled=!1,e.click(),e.disabled=n}else e=document.createElement("input"),e.type="submit",e.style="display:none",t.appendChild(e),e.click(),t.removeChild(e)}function s(t){t.disabled=!0}function f(t){t.disabled=!1}e.a=n;var c=r(4),h=r(0),l="data-direct-uploads-processing",d=!1},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"a",function(){return s});var i=r(5),a=r(0),u=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),o="input[type=file][data-direct-upload-url]:not([disabled])",s=function(){function t(e){n(this,t),this.form=e,this.inputs=Object(a.c)(e,o).filter(function(t){return t.files.length})}return u(t,[{key:"start",value:function(t){var e=this,r=this.createDirectUploadControllers();this.dispatch("start"),function n(){var i=r.shift();i?i.start(function(r){r?(t(r),e.dispatch("end")):n()}):(t(),e.dispatch("end"))}()}},{key:"createDirectUploadControllers",value:function(){var t=[];return this.inputs.forEach(function(e){Object(a.e)(e.files).forEach(function(r){var n=new i.a(e,r);t.push(n)})}),t}},{key:"dispatch",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object(a.a)(this.form,"direct-uploads:"+t,{detail:e})}}]),t}()},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"a",function(){return o});var i=r(1),a=r(0),u=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),o=function(){function t(e,r){n(this,t),this.input=e,this.file=r,this.directUpload=new i.a(this.file,this.url,this),this.dispatch("initialize")}return u(t,[{key:"start",value:function(t){var e=this,r=document.createElement("input");r.type="hidden",r.name=this.input.name,this.input.insertAdjacentElement("beforebegin",r),this.dispatch("start"),this.directUpload.create(function(n,i){n?(r.parentNode.removeChild(r),e.dispatchError(n)):r.value=i.signed_id,e.dispatch("end"),t(n)})}},{key:"uploadRequestDidProgress",value:function(t){var e=t.loaded/t.total*100;e&&this.dispatch("progress",{progress:e})}},{key:"dispatch",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.file=this.file,e.id=this.directUpload.id,Object(a.a)(this.input,"direct-upload:"+t,{detail:e})}},{key:"dispatchError",value:function(t){this.dispatch("error",{error:t}).defaultPrevented||alert(t)}},{key:"directUploadWillCreateBlobWithXHR",value:function(t){this.dispatch("before-blob-request",{xhr:t})}},{key:"directUploadWillStoreFileWithXHR",value:function(t){var e=this;this.dispatch("before-storage-request",{xhr:t}),t.upload.addEventListener("progress",function(t){return e.uploadRequestDidProgress(t)})}},{key:"url",get:function(){return this.input.getAttribute("data-direct-upload-url")}}]),t}()},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"a",function(){return s});var i=r(7),a=r.n(i),u=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),o=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice,s=function(){function t(e){n(this,t),this.file=e,this.chunkSize=2097152,this.chunkCount=Math.ceil(this.file.size/this.chunkSize),this.chunkIndex=0}return u(t,null,[{key:"create",value:function(e,r){new t(e).create(r)}}]),u(t,[{key:"create",value:function(t){var e=this;this.callback=t,this.md5Buffer=new a.a.ArrayBuffer,this.fileReader=new FileReader,this.fileReader.addEventListener("load",function(t){return e.fileReaderDidLoad(t)}),this.fileReader.addEventListener("error",function(t){return e.fileReaderDidError(t)}),this.readNextChunk()}},{key:"fileReaderDidLoad",value:function(t){if(this.md5Buffer.append(t.target.result),!this.readNextChunk()){var e=this.md5Buffer.end(!0),r=btoa(e);this.callback(null,r)}}},{key:"fileReaderDidError",value:function(t){this.callback("Error reading "+this.file.name)}},{key:"readNextChunk",value:function(){if(this.chunkIndex<this.chunkCount){var t=this.chunkIndex*this.chunkSize,e=Math.min(t+this.chunkSize,this.file.size),r=o.call(this.file,t,e);return this.fileReader.readAsArrayBuffer(r),this.chunkIndex++,!0}return!1}}]),t}()},function(t,e,r){!function(e){t.exports=e()}(function(t){"use strict";function e(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];r+=(n&i|~n&a)+e[0]-680876936|0,r=(r<<7|r>>>25)+n|0,a+=(r&n|~r&i)+e[1]-389564586|0,a=(a<<12|a>>>20)+r|0,i+=(a&r|~a&n)+e[2]+606105819|0,i=(i<<17|i>>>15)+a|0,n+=(i&a|~i&r)+e[3]-1044525330|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&a)+e[4]-176418897|0,r=(r<<7|r>>>25)+n|0,a+=(r&n|~r&i)+e[5]+1200080426|0,a=(a<<12|a>>>20)+r|0,i+=(a&r|~a&n)+e[6]-1473231341|0,i=(i<<17|i>>>15)+a|0,n+=(i&a|~i&r)+e[7]-45705983|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&a)+e[8]+1770035416|0,r=(r<<7|r>>>25)+n|0,a+=(r&n|~r&i)+e[9]-1958414417|0,a=(a<<12|a>>>20)+r|0,i+=(a&r|~a&n)+e[10]-42063|0,i=(i<<17|i>>>15)+a|0,n+=(i&a|~i&r)+e[11]-1990404162|0,n=(n<<22|n>>>10)+i|0,r+=(n&i|~n&a)+e[12]+1804603682|0,r=(r<<7|r>>>25)+n|0,a+=(r&n|~r&i)+e[13]-40341101|0,a=(a<<12|a>>>20)+r|0,i+=(a&r|~a&n)+e[14]-1502002290|0,i=(i<<17|i>>>15)+a|0,n+=(i&a|~i&r)+e[15]+1236535329|0,n=(n<<22|n>>>10)+i|0,r+=(n&a|i&~a)+e[1]-165796510|0,r=(r<<5|r>>>27)+n|0,a+=(r&i|n&~i)+e[6]-1069501632|0,a=(a<<9|a>>>23)+r|0,i+=(a&n|r&~n)+e[11]+643717713|0,i=(i<<14|i>>>18)+a|0,n+=(i&r|a&~r)+e[0]-373897302|0,n=(n<<20|n>>>12)+i|0,r+=(n&a|i&~a)+e[5]-701558691|0,r=(r<<5|r>>>27)+n|0,a+=(r&i|n&~i)+e[10]+38016083|0,a=(a<<9|a>>>23)+r|0,i+=(a&n|r&~n)+e[15]-660478335|0,i=(i<<14|i>>>18)+a|0,n+=(i&r|a&~r)+e[4]-405537848|0,n=(n<<20|n>>>12)+i|0,r+=(n&a|i&~a)+e[9]+568446438|0,r=(r<<5|r>>>27)+n|0,a+=(r&i|n&~i)+e[14]-1019803690|0,a=(a<<9|a>>>23)+r|0,i+=(a&n|r&~n)+e[3]-187363961|0,i=(i<<14|i>>>18)+a|0,n+=(i&r|a&~r)+e[8]+1163531501|0,n=(n<<20|n>>>12)+i|0,r+=(n&a|i&~a)+e[13]-1444681467|0,r=(r<<5|r>>>27)+n|0,a+=(r&i|n&~i)+e[2]-51403784|0,a=(a<<9|a>>>23)+r|0,i+=(a&n|r&~n)+e[7]+1735328473|0,i=(i<<14|i>>>18)+a|0,n+=(i&r|a&~r)+e[12]-1926607734|0,n=(n<<20|n>>>12)+i|0,r+=(n^i^a)+e[5]-378558|0,r=(r<<4|r>>>28)+n|0,a+=(r^n^i)+e[8]-2022574463|0,a=(a<<11|a>>>21)+r|0,i+=(a^r^n)+e[11]+1839030562|0,i=(i<<16|i>>>16)+a|0,n+=(i^a^r)+e[14]-35309556|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^a)+e[1]-1530992060|0,r=(r<<4|r>>>28)+n|0,a+=(r^n^i)+e[4]+1272893353|0,a=(a<<11|a>>>21)+r|0,i+=(a^r^n)+e[7]-155497632|0,i=(i<<16|i>>>16)+a|0,n+=(i^a^r)+e[10]-1094730640|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^a)+e[13]+681279174|0,r=(r<<4|r>>>28)+n|0,a+=(r^n^i)+e[0]-358537222|0,a=(a<<11|a>>>21)+r|0,i+=(a^r^n)+e[3]-722521979|0,i=(i<<16|i>>>16)+a|0,n+=(i^a^r)+e[6]+76029189|0,n=(n<<23|n>>>9)+i|0,r+=(n^i^a)+e[9]-640364487|0,r=(r<<4|r>>>28)+n|0,a+=(r^n^i)+e[12]-421815835|0,a=(a<<11|a>>>21)+r|0,i+=(a^r^n)+e[15]+530742520|0,i=(i<<16|i>>>16)+a|0,n+=(i^a^r)+e[2]-995338651|0,n=(n<<23|n>>>9)+i|0,r+=(i^(n|~a))+e[0]-198630844|0,r=(r<<6|r>>>26)+n|0,a+=(n^(r|~i))+e[7]+1126891415|0,a=(a<<10|a>>>22)+r|0,i+=(r^(a|~n))+e[14]-1416354905|0,i=(i<<15|i>>>17)+a|0,n+=(a^(i|~r))+e[5]-57434055|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~a))+e[12]+1700485571|0,r=(r<<6|r>>>26)+n|0,a+=(n^(r|~i))+e[3]-1894986606|0,a=(a<<10|a>>>22)+r|0,i+=(r^(a|~n))+e[10]-1051523|0,i=(i<<15|i>>>17)+a|0,n+=(a^(i|~r))+e[1]-2054922799|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~a))+e[8]+1873313359|0,r=(r<<6|r>>>26)+n|0,a+=(n^(r|~i))+e[15]-30611744|0,a=(a<<10|a>>>22)+r|0,i+=(r^(a|~n))+e[6]-1560198380|0,i=(i<<15|i>>>17)+a|0,n+=(a^(i|~r))+e[13]+1309151649|0,n=(n<<21|n>>>11)+i|0,r+=(i^(n|~a))+e[4]-145523070|0,r=(r<<6|r>>>26)+n|0,a+=(n^(r|~i))+e[11]-1120210379|0,a=(a<<10|a>>>22)+r|0,i+=(r^(a|~n))+e[2]+718787259|0,i=(i<<15|i>>>17)+a|0,n+=(a^(i|~r))+e[9]-343485551|0,n=(n<<21|n>>>11)+i|0,t[0]=r+t[0]|0,t[1]=n+t[1]|0,t[2]=i+t[2]|0,t[3]=a+t[3]|0}function r(t){var e,r=[];for(e=0;e<64;e+=4)r[e>>2]=t.charCodeAt(e)+(t.charCodeAt(e+1)<<8)+(t.charCodeAt(e+2)<<16)+(t.charCodeAt(e+3)<<24);return r}function n(t){var e,r=[];for(e=0;e<64;e+=4)r[e>>2]=t[e]+(t[e+1]<<8)+(t[e+2]<<16)+(t[e+3]<<24);return r}function i(t){var n,i,a,u,o,s,f=t.length,c=[1732584193,-271733879,-1732584194,271733878];for(n=64;n<=f;n+=64)e(c,r(t.substring(n-64,n)));for(t=t.substring(n-64),i=t.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0;n<i;n+=1)a[n>>2]|=t.charCodeAt(n)<<(n%4<<3);if(a[n>>2]|=128<<(n%4<<3),n>55)for(e(c,a),n=0;n<16;n+=1)a[n]=0;return u=8*f,u=u.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(u[2],16),s=parseInt(u[1],16)||0,a[14]=o,a[15]=s,e(c,a),c}function a(t){var r,i,a,u,o,s,f=t.length,c=[1732584193,-271733879,-1732584194,271733878];for(r=64;r<=f;r+=64)e(c,n(t.subarray(r-64,r)));for(t=r-64<f?t.subarray(r-64):new Uint8Array(0),i=t.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=0;r<i;r+=1)a[r>>2]|=t[r]<<(r%4<<3);if(a[r>>2]|=128<<(r%4<<3),r>55)for(e(c,a),r=0;r<16;r+=1)a[r]=0;return u=8*f,u=u.toString(16).match(/(.*?)(.{0,8})$/),o=parseInt(u[2],16),s=parseInt(u[1],16)||0,a[14]=o,a[15]=s,e(c,a),c}function u(t){var e,r="";for(e=0;e<4;e+=1)r+=p[t>>8*e+4&15]+p[t>>8*e&15];return r}function o(t){var e;for(e=0;e<t.length;e+=1)t[e]=u(t[e]);return t.join("")}function s(t){return/[\u0080-\uFFFF]/.test(t)&&(t=unescape(encodeURIComponent(t))),t}function f(t,e){var r,n=t.length,i=new ArrayBuffer(n),a=new Uint8Array(i);for(r=0;r<n;r+=1)a[r]=t.charCodeAt(r);return e?a:i}function c(t){return String.fromCharCode.apply(null,new Uint8Array(t))}function h(t,e,r){var n=new Uint8Array(t.byteLength+e.byteLength);return n.set(new Uint8Array(t)),n.set(new Uint8Array(e),t.byteLength),r?n:n.buffer}function l(t){var e,r=[],n=t.length;for(e=0;e<n-1;e+=2)r.push(parseInt(t.substr(e,2),16));return String.fromCharCode.apply(String,r)}function d(){this.reset()}var p=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return"5d41402abc4b2a76b9719d911017c592"!==o(i("hello"))&&function(t,e){var r=(65535&t)+(65535&e);return(t>>16)+(e>>16)+(r>>16)<<16|65535&r},"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function e(t,e){return t=0|t||0,t<0?Math.max(t+e,0):Math.min(t,e)}ArrayBuffer.prototype.slice=function(r,n){var i,a,u,o,s=this.byteLength,f=e(r,s),c=s;return n!==t&&(c=e(n,s)),f>c?new ArrayBuffer(0):(i=c-f,a=new ArrayBuffer(i),u=new Uint8Array(a),o=new Uint8Array(this,f,i),u.set(o),a)}}(),d.prototype.append=function(t){return this.appendBinary(s(t)),this},d.prototype.appendBinary=function(t){this._buff+=t,this._length+=t.length;var n,i=this._buff.length;for(n=64;n<=i;n+=64)e(this._hash,r(this._buff.substring(n-64,n)));return this._buff=this._buff.substring(n-64),this},d.prototype.end=function(t){var e,r,n=this._buff,i=n.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e<i;e+=1)a[e>>2]|=n.charCodeAt(e)<<(e%4<<3);return this._finish(a,i),r=o(this._hash),t&&(r=l(r)),this.reset(),r},d.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},d.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},d.prototype.setState=function(t){return this._buff=t.buff,this._length=t.length,this._hash=t.hash,this},d.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},d.prototype._finish=function(t,r){var n,i,a,u=r;if(t[u>>2]|=128<<(u%4<<3),u>55)for(e(this._hash,t),u=0;u<16;u+=1)t[u]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(n[2],16),a=parseInt(n[1],16)||0,t[14]=i,t[15]=a,e(this._hash,t)},d.hash=function(t,e){return d.hashBinary(s(t),e)},d.hashBinary=function(t,e){var r=i(t),n=o(r);return e?l(n):n},d.ArrayBuffer=function(){this.reset()},d.ArrayBuffer.prototype.append=function(t){var r,i=h(this._buff.buffer,t,!0),a=i.length;for(this._length+=t.byteLength,r=64;r<=a;r+=64)e(this._hash,n(i.subarray(r-64,r)));return this._buff=r-64<a?new Uint8Array(i.buffer.slice(r-64)):new Uint8Array(0),this},d.ArrayBuffer.prototype.end=function(t){var e,r,n=this._buff,i=n.length,a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(e=0;e<i;e+=1)a[e>>2]|=n[e]<<(e%4<<3);return this._finish(a,i),r=o(this._hash),t&&(r=l(r)),this.reset(),r},d.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},d.ArrayBuffer.prototype.getState=function(){var t=d.prototype.getState.call(this);return t.buff=c(t.buff),t},d.ArrayBuffer.prototype.setState=function(t){return t.buff=f(t.buff,!0),d.prototype.setState.call(this,t)},d.ArrayBuffer.prototype.destroy=d.prototype.destroy,d.ArrayBuffer.prototype._finish=d.prototype._finish,d.ArrayBuffer.hash=function(t,e){var r=a(new Uint8Array(t)),n=o(r);return e?l(n):n},d})},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"a",function(){return u});var i=r(0),a=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),u=function(){function t(e,r,a){var u=this;n(this,t),this.file=e,this.attributes={filename:e.name,content_type:e.type,byte_size:e.size,checksum:r},this.xhr=new XMLHttpRequest,this.xhr.open("POST",a,!0),this.xhr.responseType="json",this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.setRequestHeader("Accept","application/json"),this.xhr.setRequestHeader("X-Requested-With","XMLHttpRequest"),this.xhr.setRequestHeader("X-CSRF-Token",Object(i.d)("csrf-token")),this.xhr.addEventListener("load",function(t){return u.requestDidLoad(t)}),this.xhr.addEventListener("error",function(t){return u.requestDidError(t)})}return a(t,[{key:"create",value:function(t){this.callback=t,this.xhr.send(JSON.stringify({blob:this.attributes}))}},{key:"requestDidLoad",value:function(t){var e=this.xhr,r=e.status,n=e.response;if(r>=200&&r<300){var i=n.direct_upload;delete n.direct_upload,this.attributes=n,this.directUploadData=i,this.callback(null,this.toJSON())}else this.requestDidError(t)}},{key:"requestDidError",value:function(t){this.callback('Error creating Blob for "'+this.file.name+'". Status: '+this.xhr.status)}},{key:"toJSON",value:function(){var t={};for(var e in this.attributes)t[e]=this.attributes[e];return t}}]),t}()},function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.d(e,"a",function(){return a});var i=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),a=function(){function t(e){var r=this;n(this,t),this.blob=e,this.file=e.file;var i=e.directUploadData,a=i.url,u=i.headers;this.xhr=new XMLHttpRequest,this.xhr.open("PUT",a,!0);for(var o in u)this.xhr.setRequestHeader(o,u[o]);this.xhr.addEventListener("load",function(t){return r.requestDidLoad(t)}),this.xhr.addEventListener("error",function(t){return r.requestDidError(t)})}return i(t,[{key:"create",value:function(t){this.callback=t,this.xhr.send(this.file)}},{key:"requestDidLoad",value:function(t){var e=this.xhr,r=e.status,n=e.response;r>=200&&r<300?this.callback(null,n):this.requestDidError(t)}},{key:"requestDidError",value:function(t){this.callback('Error storing "'+this.file.name+'". Status: '+this.xhr.status)}}]),t}()}])});
@@ -0,0 +1,22 @@
1
+ # Take a signed permanent reference for a blob and turn it into an expiring service URL for download.
2
+ # Note: These URLs are publicly accessible. If you need to enforce access protection beyond the
3
+ # security-through-obscurity factor of the signed blob references, you'll need to implement your own
4
+ # authenticated redirection controller.
5
+ class ActiveStorage::BlobsController < ActionController::Base
6
+ def show
7
+ if blob = find_signed_blob
8
+ redirect_to blob.service_url(disposition: disposition_param)
9
+ else
10
+ head :not_found
11
+ end
12
+ end
13
+
14
+ private
15
+ def find_signed_blob
16
+ ActiveStorage::Blob.find_signed(params[:signed_id])
17
+ end
18
+
19
+ def disposition_param
20
+ params[:disposition].in?(%w(inline attachment)) ? params[:disposition] : 'inline'
21
+ end
22
+ end
@@ -0,0 +1,21 @@
1
+ # Creates a new blob on the server side in anticipation of a direct-to-service upload from the client side.
2
+ # When the client-side upload is completed, the signed_blob_id can be submitted as part of the form to reference
3
+ # the blob that was created up front.
4
+ class ActiveStorage::DirectUploadsController < ActionController::Base
5
+ def create
6
+ blob = ActiveStorage::Blob.create_before_direct_upload!(blob_args)
7
+ render json: direct_upload_json(blob)
8
+ end
9
+
10
+ private
11
+ def blob_args
12
+ params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type, :metadata).to_h.symbolize_keys
13
+ end
14
+
15
+ def direct_upload_json(blob)
16
+ blob.as_json(methods: :signed_id).merge(direct_upload: {
17
+ url: blob.service_url_for_direct_upload,
18
+ headers: blob.service_headers_for_direct_upload
19
+ })
20
+ end
21
+ end
@@ -0,0 +1,52 @@
1
+ # Serves files stored with the disk service in the same way that the cloud services do.
2
+ # This means using expiring, signed URLs that are meant for immediate access, not permanent linking.
3
+ # Always go through the BlobsController, or your own authenticated controller, rather than directly
4
+ # to the service url.
5
+ class ActiveStorage::DiskController < ActionController::Base
6
+ def show
7
+ if key = decode_verified_key
8
+ send_data disk_service.download(key),
9
+ filename: params[:filename], disposition: disposition_param, content_type: params[:content_type]
10
+ else
11
+ head :not_found
12
+ end
13
+ end
14
+
15
+ def update
16
+ if token = decode_verified_token
17
+ if acceptable_content?(token)
18
+ disk_service.upload token[:key], request.body, checksum: token[:checksum]
19
+ head :no_content
20
+ else
21
+ head :unprocessable_entity
22
+ end
23
+ else
24
+ head :not_found
25
+ end
26
+ rescue ActiveStorage::IntegrityError
27
+ head :unprocessable_entity
28
+ end
29
+
30
+ private
31
+ def disk_service
32
+ ActiveStorage::Blob.service
33
+ end
34
+
35
+
36
+ def decode_verified_key
37
+ ActiveStorage.verifier.verified(params[:encoded_key], purpose: :blob_key)
38
+ end
39
+
40
+ def disposition_param
41
+ params[:disposition].in?(%w(inline attachment)) ? params[:disposition] : 'inline'
42
+ end
43
+
44
+
45
+ def decode_verified_token
46
+ ActiveStorage.verifier.verified(params[:encoded_token], purpose: :blob_token)
47
+ end
48
+
49
+ def acceptable_content?(token)
50
+ token[:content_type] == request.content_type && token[:content_length] == request.content_length
51
+ end
52
+ end
@@ -0,0 +1,28 @@
1
+ require "active_storage/variant"
2
+
3
+ # Take a signed permanent reference for a variant and turn it into an expiring service URL for download.
4
+ # Note: These URLs are publicly accessible. If you need to enforce access protection beyond the
5
+ # security-through-obscurity factor of the signed blob and variation reference, you'll need to implement your own
6
+ # authenticated redirection controller.
7
+ class ActiveStorage::VariantsController < ActionController::Base
8
+ def show
9
+ if blob = find_signed_blob
10
+ redirect_to ActiveStorage::Variant.new(blob, decoded_variation).processed.service_url(disposition: disposition_param)
11
+ else
12
+ head :not_found
13
+ end
14
+ end
15
+
16
+ private
17
+ def find_signed_blob
18
+ ActiveStorage::Blob.find_signed(params[:signed_blob_id])
19
+ end
20
+
21
+ def decoded_variation
22
+ ActiveStorage::Variation.decode(params[:variation_key])
23
+ end
24
+
25
+ def disposition_param
26
+ params[:disposition].in?(%w(inline attachment)) ? params[:disposition] : 'inline'
27
+ end
28
+ end
@@ -0,0 +1,18 @@
1
+ module ActiveStorage
2
+ # Temporary hack to overwrite the default file_field_tag and Form#file_field to accept a direct_upload: true option
3
+ # that then gets replaced with a data-direct-upload-url attribute with the route prefilled.
4
+ module FileFieldWithDirectUploadHelper
5
+ def file_field_tag(name, options = {})
6
+ text_field_tag(name, nil, convert_direct_upload_option_to_url(options.merge(type: :file)))
7
+ end
8
+
9
+ def file_field(object_name, method, options = {})
10
+ ActionView::Helpers::Tags::FileField.new(object_name, method, self, convert_direct_upload_option_to_url(options)).render
11
+ end
12
+
13
+ private
14
+ def convert_direct_upload_option_to_url(options)
15
+ options.merge('data-direct-upload-url': options.delete(:direct_upload) ? rails_direct_uploads_url : nil).compact
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,54 @@
1
+ import { getMetaValue } from "./helpers"
2
+
3
+ export class BlobRecord {
4
+ constructor(file, checksum, url) {
5
+ this.file = file
6
+
7
+ this.attributes = {
8
+ filename: file.name,
9
+ content_type: file.type,
10
+ byte_size: file.size,
11
+ checksum: checksum
12
+ }
13
+
14
+ this.xhr = new XMLHttpRequest
15
+ this.xhr.open("POST", url, true)
16
+ this.xhr.responseType = "json"
17
+ this.xhr.setRequestHeader("Content-Type", "application/json")
18
+ this.xhr.setRequestHeader("Accept", "application/json")
19
+ this.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
20
+ this.xhr.setRequestHeader("X-CSRF-Token", getMetaValue("csrf-token"))
21
+ this.xhr.addEventListener("load", event => this.requestDidLoad(event))
22
+ this.xhr.addEventListener("error", event => this.requestDidError(event))
23
+ }
24
+
25
+ create(callback) {
26
+ this.callback = callback
27
+ this.xhr.send(JSON.stringify({ blob: this.attributes }))
28
+ }
29
+
30
+ requestDidLoad(event) {
31
+ const { status, response } = this.xhr
32
+ if (status >= 200 && status < 300) {
33
+ const { direct_upload } = response
34
+ delete response.direct_upload
35
+ this.attributes = response
36
+ this.directUploadData = direct_upload
37
+ this.callback(null, this.toJSON())
38
+ } else {
39
+ this.requestDidError(event)
40
+ }
41
+ }
42
+
43
+ requestDidError(event) {
44
+ this.callback(`Error creating Blob for "${this.file.name}". Status: ${this.xhr.status}`)
45
+ }
46
+
47
+ toJSON() {
48
+ const result = {}
49
+ for (const key in this.attributes) {
50
+ result[key] = this.attributes[key]
51
+ }
52
+ return result
53
+ }
54
+ }
@@ -0,0 +1,34 @@
1
+ export class BlobUpload {
2
+ constructor(blob) {
3
+ this.blob = blob
4
+ this.file = blob.file
5
+
6
+ const { url, headers } = blob.directUploadData
7
+
8
+ this.xhr = new XMLHttpRequest
9
+ this.xhr.open("PUT", url, true)
10
+ for (const key in headers) {
11
+ this.xhr.setRequestHeader(key, headers[key])
12
+ }
13
+ this.xhr.addEventListener("load", event => this.requestDidLoad(event))
14
+ this.xhr.addEventListener("error", event => this.requestDidError(event))
15
+ }
16
+
17
+ create(callback) {
18
+ this.callback = callback
19
+ this.xhr.send(this.file)
20
+ }
21
+
22
+ requestDidLoad(event) {
23
+ const { status, response } = this.xhr
24
+ if (status >= 200 && status < 300) {
25
+ this.callback(null, response)
26
+ } else {
27
+ this.requestDidError(event)
28
+ }
29
+ }
30
+
31
+ requestDidError(event) {
32
+ this.callback(`Error storing "${this.file.name}". Status: ${this.xhr.status}`)
33
+ }
34
+ }
@@ -0,0 +1,42 @@
1
+ import { FileChecksum } from "./file_checksum"
2
+ import { BlobRecord } from "./blob_record"
3
+ import { BlobUpload } from "./blob_upload"
4
+
5
+ let id = 0
6
+
7
+ export class DirectUpload {
8
+ constructor(file, url, delegate) {
9
+ this.id = ++id
10
+ this.file = file
11
+ this.url = url
12
+ this.delegate = delegate
13
+ }
14
+
15
+ create(callback) {
16
+ FileChecksum.create(this.file, (error, checksum) => {
17
+ const blob = new BlobRecord(this.file, checksum, this.url)
18
+ notify(this.delegate, "directUploadWillCreateBlobWithXHR", blob.xhr)
19
+ blob.create(error => {
20
+ if (error) {
21
+ callback(error)
22
+ } else {
23
+ const upload = new BlobUpload(blob)
24
+ notify(this.delegate, "directUploadWillStoreFileWithXHR", upload.xhr)
25
+ upload.create(error => {
26
+ if (error) {
27
+ callback(error)
28
+ } else {
29
+ callback(null, blob.toJSON())
30
+ }
31
+ })
32
+ }
33
+ })
34
+ })
35
+ }
36
+ }
37
+
38
+ function notify(object, methodName, ...messages) {
39
+ if (object && typeof object[methodName] == "function") {
40
+ return object[methodName](...messages)
41
+ }
42
+ }
@@ -0,0 +1,67 @@
1
+ import { DirectUpload } from "./direct_upload"
2
+ import { dispatchEvent } from "./helpers"
3
+
4
+ export class DirectUploadController {
5
+ constructor(input, file) {
6
+ this.input = input
7
+ this.file = file
8
+ this.directUpload = new DirectUpload(this.file, this.url, this)
9
+ this.dispatch("initialize")
10
+ }
11
+
12
+ start(callback) {
13
+ const hiddenInput = document.createElement("input")
14
+ hiddenInput.type = "hidden"
15
+ hiddenInput.name = this.input.name
16
+ this.input.insertAdjacentElement("beforebegin", hiddenInput)
17
+
18
+ this.dispatch("start")
19
+
20
+ this.directUpload.create((error, attributes) => {
21
+ if (error) {
22
+ hiddenInput.parentNode.removeChild(hiddenInput)
23
+ this.dispatchError(error)
24
+ } else {
25
+ hiddenInput.value = attributes.signed_id
26
+ }
27
+
28
+ this.dispatch("end")
29
+ callback(error)
30
+ })
31
+ }
32
+
33
+ uploadRequestDidProgress(event) {
34
+ const progress = event.loaded / event.total * 100
35
+ if (progress) {
36
+ this.dispatch("progress", { progress })
37
+ }
38
+ }
39
+
40
+ get url() {
41
+ return this.input.getAttribute("data-direct-upload-url")
42
+ }
43
+
44
+ dispatch(name, detail = {}) {
45
+ detail.file = this.file
46
+ detail.id = this.directUpload.id
47
+ return dispatchEvent(this.input, `direct-upload:${name}`, { detail })
48
+ }
49
+
50
+ dispatchError(error) {
51
+ const event = this.dispatch("error", { error })
52
+ if (!event.defaultPrevented) {
53
+ alert(error)
54
+ }
55
+ }
56
+
57
+ // DirectUpload delegate
58
+
59
+ directUploadWillCreateBlobWithXHR(xhr) {
60
+ this.dispatch("before-blob-request", { xhr })
61
+ }
62
+
63
+ directUploadWillStoreFileWithXHR(xhr) {
64
+ this.dispatch("before-storage-request", { xhr })
65
+ xhr.upload.addEventListener("progress", event => this.uploadRequestDidProgress(event))
66
+ }
67
+ }
@@ -0,0 +1,50 @@
1
+ import { DirectUploadController } from "./direct_upload_controller"
2
+ import { findElements, dispatchEvent, toArray } from "./helpers"
3
+
4
+ const inputSelector = "input[type=file][data-direct-upload-url]:not([disabled])"
5
+
6
+ export class DirectUploadsController {
7
+ constructor(form) {
8
+ this.form = form
9
+ this.inputs = findElements(form, inputSelector).filter(input => input.files.length)
10
+ }
11
+
12
+ start(callback) {
13
+ const controllers = this.createDirectUploadControllers()
14
+
15
+ const startNextController = () => {
16
+ const controller = controllers.shift()
17
+ if (controller) {
18
+ controller.start(error => {
19
+ if (error) {
20
+ callback(error)
21
+ this.dispatch("end")
22
+ } else {
23
+ startNextController()
24
+ }
25
+ })
26
+ } else {
27
+ callback()
28
+ this.dispatch("end")
29
+ }
30
+ }
31
+
32
+ this.dispatch("start")
33
+ startNextController()
34
+ }
35
+
36
+ createDirectUploadControllers() {
37
+ const controllers = []
38
+ this.inputs.forEach(input => {
39
+ toArray(input.files).forEach(file => {
40
+ const controller = new DirectUploadController(input, file)
41
+ controllers.push(controller)
42
+ })
43
+ })
44
+ return controllers
45
+ }
46
+
47
+ dispatch(name, detail = {}) {
48
+ return dispatchEvent(this.form, `direct-uploads:${name}`, { detail })
49
+ }
50
+ }