resizing 1.2.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. checksums.yaml +4 -4
  2. data/.devcontainer/Dockerfile +73 -0
  3. data/.devcontainer/compose.yaml +61 -0
  4. data/.devcontainer/devcontainer-lock.json +9 -0
  5. data/.devcontainer/devcontainer.json +32 -0
  6. data/.devcontainer/post-create.sh +41 -0
  7. data/.github/copilot-instructions.md +1 -0
  8. data/.github/dependabot.yml +23 -0
  9. data/.github/labeler.yml +28 -0
  10. data/.github/release.yml +35 -0
  11. data/.github/tools/actionlint/Dockerfile +3 -0
  12. data/.github/tools/gitleaks/Dockerfile +2 -0
  13. data/.github/workflows/actionlint.yml +27 -0
  14. data/.github/workflows/actions.lock +54 -0
  15. data/.github/workflows/labeler.yml +22 -0
  16. data/.github/workflows/lint.yml +37 -0
  17. data/.github/workflows/secret-scan.yml +29 -0
  18. data/.github/workflows/test.yml +51 -13
  19. data/.github/workflows/verify-lockfile.yml +28 -0
  20. data/AGENTS.md +1 -0
  21. data/CHANGELOG.md +3 -0
  22. data/CLAUDE.md +68 -0
  23. data/Gemfile +12 -3
  24. data/README.ja.md +241 -0
  25. data/README.md +196 -2
  26. data/Rakefile +5 -7
  27. data/bin/setup +3 -0
  28. data/docker-compose.yml +7 -0
  29. data/git-hooks/pre-push +6 -0
  30. data/git-hooks/pre-push-ruby.sh +53 -0
  31. data/lib/resizing/carrier_wave/callback_file.rb +88 -0
  32. data/lib/resizing/carrier_wave/storage/file.rb +105 -38
  33. data/lib/resizing/carrier_wave/storage/remote.rb +25 -16
  34. data/lib/resizing/carrier_wave.rb +109 -6
  35. data/lib/resizing/client.rb +47 -4
  36. data/lib/resizing/configurable.rb +1 -1
  37. data/lib/resizing/configuration.rb +40 -10
  38. data/lib/resizing/mock_client.rb +48 -9
  39. data/lib/resizing/public_id.rb +3 -2
  40. data/lib/resizing/version.rb +1 -1
  41. data/lib/resizing.rb +4 -1
  42. data/resizing.gemspec +3 -3
  43. data/test/rails_app/app/views/users/new.html.erb +6 -0
  44. data/test/rails_app/rails_app.rb +86 -0
  45. data/test/resizing/carrier_wave/storage/file_test.rb +495 -9
  46. data/test/resizing/carrier_wave/storage/remote_test.rb +151 -12
  47. data/test/resizing/carrier_wave_cache_callbacks_test.rb +224 -0
  48. data/test/resizing/carrier_wave_callback_file_test.rb +77 -0
  49. data/test/resizing/carrier_wave_rails_integration_test.rb +94 -0
  50. data/test/resizing/carrier_wave_temporary_image_test.rb +280 -0
  51. data/test/resizing/carrier_wave_test.rb +214 -30
  52. data/test/resizing/carrier_wave_uploader_test.rb +225 -0
  53. data/test/resizing/client_test.rb +419 -30
  54. data/test/resizing/configuration_test.rb +235 -10
  55. data/test/resizing/http_clientable_test.rb +27 -0
  56. data/test/resizing/mock_client_test.rb +145 -1
  57. data/test/resizing/public_id_test.rb +96 -0
  58. data/test/resizing_module_test.rb +126 -0
  59. data/test/resizing_test.rb +8 -0
  60. data/test/test_helper.rb +318 -9
  61. data/test/vcr/carrier_wave_test/confirm.yml +23 -0
  62. data/test/vcr/carrier_wave_test/retrieve_from_cache.yml +23 -0
  63. data/test/vcr/carrier_wave_test/save.yml +1 -1
  64. data/test/vcr/carrier_wave_test/update_image.yml +42 -2
  65. metadata +47 -9
@@ -0,0 +1,53 @@
1
+ #!/bin/sh
2
+ # pre-push-ruby.sh
3
+ # Runs the same checks as CI (RuboCop and the test suite) before pushing.
4
+ # Called from git-hooks/pre-push. Aborts the push if any check fails.
5
+ #
6
+ # The checks run wherever the gems are installed: the current shell when it
7
+ # already has them (inside the devcontainer, or a host with `bundle install`
8
+ # done), otherwise the devcontainer started for this checkout.
9
+ #
10
+ # PRE_PUSH_SKIP_TESTS=1 git push # lint only, skip the test suite
11
+ # git push --no-verify # skip every check (not recommended)
12
+ ROOT="$(git rev-parse --show-toplevel)"
13
+ cd "$ROOT" || exit 1
14
+
15
+ if bundle check >/dev/null 2>&1; then
16
+ MODE=local
17
+ else
18
+ # The devcontainer CLI and VS Code label the container with the host folder it
19
+ # was started for. Looking it up by that label never picks a container started
20
+ # for another worktree, which mounts other files: the checks would then pass
21
+ # or fail for code that is not the one being pushed.
22
+ CONTAINER="$(docker ps --quiet --filter "label=devcontainer.local_folder=$ROOT" 2>/dev/null | head -n 1)"
23
+ if [ -z "$CONTAINER" ]; then
24
+ echo "No environment with the gems installed was found."
25
+ echo "No devcontainer is running for $ROOT."
26
+ echo "Run 'devcontainer up --workspace-folder .' (or 'bundle install') first."
27
+ echo "To skip this check (not recommended): git push --no-verify"
28
+ exit 1
29
+ fi
30
+ MODE=devcontainer
31
+ fi
32
+
33
+ run() {
34
+ case "$MODE" in
35
+ local) bundle exec "$@" ;;
36
+ # User and folder as in .devcontainer/devcontainer.json (remoteUser, workspaceFolder)
37
+ devcontainer) docker exec -u vscode -w /workspaces/resizing-gem "$CONTAINER" bundle exec "$@" ;;
38
+ esac
39
+ }
40
+
41
+ if [ -n "${PRE_PUSH_SKIP_TESTS:-}" ]; then
42
+ echo "Running RuboCop ($MODE)..."
43
+ run rake rubocop
44
+ else
45
+ echo "Running RuboCop and tests ($MODE)..."
46
+ run rake ci
47
+ fi
48
+
49
+ if [ $? -ne 0 ]; then
50
+ echo "Pre-push checks failed. Push aborted."
51
+ echo "To skip this check (not recommended): git push --no-verify"
52
+ exit 1
53
+ fi
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Resizing
4
+ module CarrierWave
5
+ # The file handed to CarrierWave's :cache callbacks (extension_allowlist /
6
+ # extension_denylist / content_type_allowlist / content_type_denylist / size_range).
7
+ #
8
+ # The extension used by the callbacks is derived from the content type whenever the
9
+ # content type is known, instead of being taken from the file name as plain
10
+ # CarrierWave does.
11
+ #
12
+ # A file downloaded from a Resizing URL (e.g. when it is assigned through
13
+ # `remote_<column>_url=`) is the typical case: the last segment of the URL is the
14
+ # version string (`.../images/<image_id>/v<version>`), which contains dots, so the
15
+ # "extension" CarrierWave finds in the file name is a meaningless part of the version
16
+ # (`Fv_Q` for `/v0cRq7Yb2mZt9LxA3wN8eKd5pHs1.Fv_Q`), and extension_allowlist would
17
+ # reject every such file. The HTTP response carries the real content type, so it is
18
+ # the reliable source.
19
+ #
20
+ # When the content type is unknown (`application/octet-stream`, or a type that no
21
+ # extension is registered for), the file name is used as is, as in plain CarrierWave.
22
+ class CallbackFile < ::CarrierWave::SanitizedFile
23
+ # Content type given to files whose real type could not be determined.
24
+ # Carries no information about the extension, so it is treated as unknown.
25
+ UNKNOWN_CONTENT_TYPE = 'application/octet-stream'
26
+
27
+ def original_filename
28
+ name = super
29
+ return name if name.nil?
30
+
31
+ extension = extension_for_content_type
32
+ return name if extension.nil?
33
+
34
+ basename, current_extension = split_extension(name)
35
+ return name if extensions_for_content_type.include?(current_extension.downcase)
36
+
37
+ "#{basename}.#{extension}"
38
+ end
39
+
40
+ private
41
+
42
+ # The preferred extension of the content type, or nil when the content type is unknown.
43
+ def extension_for_content_type
44
+ extensions_for_content_type.first
45
+ end
46
+
47
+ # Every extension registered for the content type (lower case), or [] when unknown.
48
+ # Neither library raises on an unregistered or malformed content type: MIME::Types
49
+ # returns an empty list and MiniMime returns nil.
50
+ #
51
+ # MIME::Types (a dependency of CarrierWave 1.x and of fog) is preferred because it
52
+ # knows every alias of an extension (jpeg / jpg / jpe for image/jpeg); MiniMime
53
+ # (a dependency of CarrierWave 2.x+) knows only one extension per content type.
54
+ def extensions_for_content_type
55
+ @extensions_for_content_type ||= begin
56
+ # Drop the parameters (`image/jpeg; charset=binary`), which MiniMime cannot handle
57
+ type = content_type.to_s.split(';').first.to_s.strip.downcase
58
+ if type.empty? || type == UNKNOWN_CONTENT_TYPE
59
+ []
60
+ else
61
+ lookup_extensions(type)
62
+ end
63
+ end
64
+ end
65
+
66
+ def lookup_extensions(type)
67
+ if mime_types_available?
68
+ ::MIME::Types[type].flat_map(&:extensions).map(&:downcase).uniq
69
+ elsif mini_mime_available?
70
+ extension = ::MiniMime.lookup_by_content_type(type)&.extension
71
+ extension.nil? ? [] : [extension.downcase]
72
+ else
73
+ []
74
+ end
75
+ end
76
+
77
+ # Which lookup library is loaded depends on the application (CarrierWave 1.x loads
78
+ # MIME::Types, 2.x+ loads MiniMime); the tests stub these to exercise each path.
79
+ def mime_types_available?
80
+ !defined?(::MIME::Types).nil?
81
+ end
82
+
83
+ def mini_mime_available?
84
+ !defined?(::MiniMime).nil?
85
+ end
86
+ end
87
+ end
88
+ end
@@ -7,26 +7,37 @@ module Resizing
7
7
  class File
8
8
  include ::CarrierWave::Utilities::Uri
9
9
 
10
+ # Fallback content type used when the type cannot be determined from the file name.
11
+ DEFAULT_CONTENT_TYPE = 'application/octet-stream'
12
+
10
13
  attr_reader :public_id
11
14
 
12
15
  def initialize(uploader, identifier = nil)
13
16
  @uploader = uploader
14
17
  @content_type = nil
15
18
  @public_id = Resizing::PublicId.new(identifier)
16
- @file = nil
17
19
  @metadata = nil
20
+ @metadata_fetched = false
18
21
  end
19
22
 
23
+ # Metadata of the stored image, as returned by the Resizing metadata API.
24
+ #
25
+ # === Returns
26
+ #
27
+ # [Hash, nil] metadata hash, or nil when the image is unknown/unreachable
20
28
  def attributes
21
- file.attributes
29
+ metadata
22
30
  end
23
31
 
24
32
  def authenticated_url(_options = {})
25
33
  nil
26
34
  end
27
35
 
36
+ # NOTE: Called through CarrierWave's Uploader::Proxy#content_type, so it must not
37
+ # raise. Falls back to the metadata API when the content type is not known locally
38
+ # (e.g. the model was reloaded from the DB), and returns nil if it cannot be fetched.
28
39
  def content_type
29
- @content_type || file.try(:content_type)
40
+ @content_type ||= metadata && metadata['content_type']
30
41
  end
31
42
 
32
43
  # rubocop:disable Metrics/AbcSize
@@ -73,29 +84,25 @@ module Resizing
73
84
  ##
74
85
  # Read content of file from service
75
86
  #
76
- # === Returns
77
- #
78
- # [String] contents of file
87
+ # NOTE: Resizing keeps no local copy of the stored image and this gem has no API to
88
+ # download the binary (Resizing::Client#get is not implemented either), so reading the
89
+ # content would require a new download API. It is not called by the regular CarrierWave
90
+ # flow (only through Uploader::Proxy#read, i.e. explicitly by the application), so it
91
+ # raises instead of silently returning nil.
79
92
  def read
80
- file_body = file.body
81
-
82
- return if file_body.nil?
83
- return file_body unless file_body.is_a?(::File)
84
-
85
- # Fog::Storage::XXX::File#body could return the source file which was upoloaded to the remote server.
86
- read_source_file(file_body) if ::File.exist?(file_body.path)
87
-
88
- # If the source file doesn't exist, the remote content is read
89
- @file = nil
90
- file.body
93
+ raise NotImplementedError, 'Resizing does not support reading the stored image content'
91
94
  end
92
95
 
96
+ # NOTE: Called through CarrierWave's Uploader::Proxy#size, so it must not raise.
97
+ # The size is only known to the Resizing service, so it comes from the metadata API.
98
+ # Returns 0 when it cannot be fetched, following Uploader::Proxy#size, which itself
99
+ # falls back to 0, so that the return value is always an Integer.
93
100
  def size
94
- file.nil? ? 0 : file.content_length
101
+ (metadata && metadata['size']) || 0
95
102
  end
96
103
 
97
104
  def exists?
98
- !!file
105
+ !metadata.nil?
99
106
  end
100
107
 
101
108
  def current_path
@@ -107,9 +114,17 @@ module Resizing
107
114
  end
108
115
  alias path current_path
109
116
 
117
+ # Uploads new_file to Resizing and writes its public id to the model column.
118
+ #
119
+ # === Options
120
+ #
121
+ # [:temporary] uploads it as a temporary image, which Resizing deletes at its
122
+ # expires_at unless it is confirmed with #confirm
123
+ # [:expires_in] seconds until the temporary image expires (Resizing's default when nil)
124
+ #
110
125
  # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
111
126
  # rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
112
- def store(new_file)
127
+ def store(new_file, options = {})
113
128
  if new_file.is_a?(self.class)
114
129
  # new_file.copy_to(path)
115
130
  raise NotImplementedError, 'new file is required duplicating'
@@ -118,8 +133,10 @@ module Resizing
118
133
  @content_type ||= if new_file.respond_to? :content_type
119
134
  new_file.content_type
120
135
  else
121
- # guess content-type from extension
122
- MIME::Types.type_for(new_file.path).first.content_type
136
+ # Guess content-type from extension. MIME::Types returns an empty
137
+ # list for extensions it does not know (e.g. `.url`), so fall back
138
+ # to the generic binary type instead of raising NoMethodError.
139
+ guess_content_type(new_file.path)
123
140
  end
124
141
 
125
142
  original_filename = new_file.try(:original_filename) || new_file.try(:filename) || new_file.try(:path)
@@ -135,7 +152,9 @@ module Resizing
135
152
  new_file
136
153
  end
137
154
 
138
- @response = Resizing.post(content, { content_type: @content_type, filename: original_filename })
155
+ post_options = { content_type: @content_type, filename: original_filename }
156
+ post_options.merge!(temporary: true, expires_in: options[:expires_in]) if options[:temporary]
157
+ @response = Resizing.post(content, post_options)
139
158
  @public_id = Resizing::PublicId.new(@response['public_id'])
140
159
  @content_type = @response['content_type']
141
160
 
@@ -155,6 +174,15 @@ module Resizing
155
174
  # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity
156
175
  # rubocop:enable Metrics/MethodLength, Metrics/PerceivedComplexity
157
176
 
177
+ # Confirms the temporary image uploaded by #store with temporary: true, so that
178
+ # Resizing keeps it after its expires_at. Raises APIError when it has already
179
+ # expired or been deleted.
180
+ def confirm
181
+ return if @public_id.empty?
182
+
183
+ client.confirm(@public_id.image_id)
184
+ end
185
+
158
186
  def name(_options = {})
159
187
  @public_id = PublicId.new(model.send(:read_attribute, serialization_column))
160
188
  CGI.unescape(@public_id.filename)
@@ -164,8 +192,12 @@ module Resizing
164
192
  # CarrierWave::Storage::Fog::File.new(@uploader, @base, new_path)
165
193
  # end
166
194
 
195
+ # NOTE: Resizing::CarrierWave#file calls this on every access, so the cached metadata
196
+ # is only dropped when the identifier actually changes.
167
197
  def retrieve(identifier)
168
- @public_id = Resizing::PublicId.new(identifier)
198
+ new_public_id = Resizing::PublicId.new(identifier)
199
+ reset_metadata unless new_public_id.to_s == @public_id.to_s
200
+ @public_id = new_public_id
169
201
  end
170
202
 
171
203
  private
@@ -213,25 +245,60 @@ module Resizing
213
245
  end
214
246
 
215
247
  ##
216
- # lookup file
248
+ # Metadata of the stored image, fetched lazily from the Resizing metadata API
249
+ # and memoized (including a failed lookup, so it is fetched at most once).
217
250
  #
218
- # === Returns
251
+ # This replaces the Fog-derived `file` method (`directory.files.head(path)`) that this
252
+ # class used to rely on: Resizing has no equivalent of a remote file handle, and the
253
+ # metadata endpoint is the only source of size / content_type / filename.
219
254
  #
220
- # [Fog::#{provider}::File] file data from remote service
255
+ # === Returns
221
256
  #
222
- # def file
223
- # @file ||= directory.files.head(path)
224
- # end
257
+ # [Hash, nil] metadata hash, or nil when there is no image or it cannot be fetched
258
+ def metadata
259
+ return @metadata if @metadata_fetched
225
260
 
226
- def read_source_file(file_body)
227
- return unless ::File.exist?(file_body.path)
261
+ @metadata_fetched = true
262
+ @metadata = fetch_metadata
263
+ end
228
264
 
229
- begin
230
- file_body = ::File.open(file_body.path) if file_body.closed? # Reopen if it's already closed
231
- file_body.read
232
- ensure
233
- file_body.close
234
- end
265
+ def reset_metadata
266
+ @metadata = nil
267
+ @metadata_fetched = false
268
+ end
269
+
270
+ # NOTE: Never raises. These values are read on ordinary code paths (CarrierWave's
271
+ # Uploader::Proxy delegates size / content_type to this object), so a transient API
272
+ # failure must not break the caller; the absence of metadata is reported as nil.
273
+ def fetch_metadata
274
+ image_id = metadata_image_id
275
+ return nil if image_id.nil? || image_id.empty?
276
+
277
+ result = Resizing.metadata(image_id, {})
278
+ return nil if !result.is_a?(Hash) || result['error']
279
+
280
+ result
281
+ rescue StandardError
282
+ nil
283
+ end
284
+
285
+ # The image to look up: the identifier this instance was built with/retrieved,
286
+ # falling back to the value currently stored in the model column.
287
+ def metadata_image_id
288
+ return @public_id.image_id if @public_id.present?
289
+
290
+ Resizing::PublicId.new(model.send(:read_attribute, serialization_column)).image_id
291
+ rescue StandardError
292
+ nil
293
+ end
294
+
295
+ # Guess the content type from a file name/path.
296
+ # Returns DEFAULT_CONTENT_TYPE when the extension is unknown to MIME::Types,
297
+ # which is the same convention CarrierWave/Rack use for unidentifiable files.
298
+ def guess_content_type(path)
299
+ return DEFAULT_CONTENT_TYPE if path.nil?
300
+
301
+ MIME::Types.type_for(path.to_s).first&.content_type || DEFAULT_CONTENT_TYPE
235
302
  end
236
303
 
237
304
  def url_options_supported?(local_file)
@@ -6,15 +6,26 @@ module Resizing
6
6
  # ref.
7
7
  # https://github.com/carrierwaveuploader/carrierwave/blob/master/lib/carrierwave/storage/abstract.rb
8
8
  class Remote < ::CarrierWave::Storage::Abstract
9
+ # A file cached by #cache! has already been uploaded as a temporary image, so
10
+ # storing it only confirms it instead of uploading it again.
9
11
  def store!(file)
12
+ if file.is_a?(Resizing::CarrierWave::Storage::File)
13
+ file.confirm
14
+ return file
15
+ end
16
+
10
17
  f = Resizing::CarrierWave::Storage::File.new(uploader)
11
18
  f.store(file)
12
19
  f
13
20
  end
14
21
 
15
- def remove!(file)
16
- f = Resizing::CarrierWave::Storage::File.new(uploader)
17
- f.delete(file)
22
+ # NOTE: CarrierWave 2.2.x never reaches here (Uploader::Remove#remove! calls
23
+ # @file.delete directly), but newer versions may remove through the storage.
24
+ # File#delete takes no argument and resolves the image to delete by itself, so
25
+ # reuse the given file when it is already ours instead of building a new one.
26
+ def remove!(file = nil)
27
+ f = file.is_a?(Resizing::CarrierWave::Storage::File) ? file : Resizing::CarrierWave::Storage::File.new(uploader)
28
+ f.delete
18
29
  f
19
30
  end
20
31
 
@@ -26,33 +37,31 @@ module Resizing
26
37
  f
27
38
  end
28
39
 
40
+ # Uploads the file as a temporary image. It is confirmed by #store! when the
41
+ # model is saved; otherwise Resizing deletes it at its expires_at, so a file
42
+ # assigned to a model that is never saved (e.g. on a validation error) does not
43
+ # leave an orphan image behind.
29
44
  def cache!(new_file)
30
45
  f = Resizing::CarrierWave::Storage::File.new(uploader)
31
- f.store(new_file)
46
+ f.store(new_file, temporary: true, expires_in: uploader.cache_expires_in)
32
47
  f
33
48
  end
34
49
 
50
+ # The cache name of a Resizing uploader is the public id of the temporary image
51
+ # (see Resizing::CarrierWave#cache_name).
35
52
  def retrieve_from_cache!(identifier)
36
- # NOP
37
- # Resizing::CarrierWave::Storage::File..new(uploader, uploader.cache_path(identifier))
53
+ return nil if identifier.blank?
54
+
55
+ Resizing::CarrierWave::Storage::File.new(uploader, identifier)
38
56
  end
39
57
 
40
58
  def delete_dir!(path)
41
59
  # do nothing, because there's no such things as 'empty directory'
42
60
  end
43
61
 
62
+ # Resizing deletes the expired temporary images by itself.
44
63
  def clean_cache!(seconds)
45
64
  # do nothing
46
- #
47
- # connection.directories.new(
48
- # :key => uploader.fog_directory,
49
- # :public => uploader.fog_public
50
- # ).files.all(:prefix => uploader.cache_dir).each do |file|
51
- # # generate_cache_id returns key formated TIMEINT-PID(-COUNTER)-RND
52
- # time = file.key.scan(/(\d+)-\d+-\d+(?:-\d+)?/).first.map { |t| t.to_i }
53
- # time = Time.at(*time)
54
- # file.destroy if time < (Time.now.utc - seconds)
55
- # end
56
65
  end
57
66
  end
58
67
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'resizing/carrier_wave/callback_file'
3
4
  require 'resizing/carrier_wave/storage/file'
4
5
  require 'resizing/carrier_wave/storage/remote'
5
6
 
@@ -104,16 +105,98 @@ module Resizing
104
105
  @transform.push(:resize_to_fit, *args)
105
106
  end
106
107
 
108
+ # Resizing has no cache storage, so the file is uploaded to Resizing here as a
109
+ # temporary image instead of being copied to a local workfile. The temporary image
110
+ # is confirmed by #store! when the model is saved (after commit with ActiveRecord);
111
+ # when the model is never saved, e.g. on a validation error, Resizing deletes it at
112
+ # its expires_at (see #cache_expires_in).
113
+ #
114
+ # The :cache callbacks are still run, so that the uploader settings hooked on them
115
+ # (extension_allowlist / extension_denylist / content_type_allowlist /
116
+ # content_type_denylist / size_range) are honoured before the upload happens.
117
+ # The callbacks that do not fit the Resizing flow (process! and cache_versions!)
118
+ # are disabled below.
107
119
  def cache!(new_file)
108
120
  return if new_file.nil?
109
121
 
110
- file = storage.store!(new_file)
111
- # do not assign @cache_id, bacause resizing do not support cache
112
- # save to resizing directly
113
- # @cache_id = file.public_id
122
+ # CallbackFile responds to #extension / #content_type / #size, which the
123
+ # before :cache callbacks need, with the extension derived from the content type
124
+ # (see CallbackFile). The original object is handed to the storage, because it
125
+ # carries the original filename sent to Resizing.
126
+ sanitized = CallbackFile.new(new_file)
127
+ return if sanitized.empty?
128
+
129
+ with_callbacks(:cache, sanitized) do
130
+ file = storage.cache!(new_file)
131
+ # The public id of the temporary image serves as the cache id, so that
132
+ # store! confirms it and #cache_name can restore it.
133
+ @cache_id = file.public_id.to_s
134
+ @staged = true
135
+ @filename = file.public_id.to_s
136
+ @file = file
137
+ end
138
+ end
139
+
140
+ # The public id of the temporary image while it is cached, nil otherwise.
141
+ # It is what `<column>_cache` returns, to be sent back with a form that is shown
142
+ # again (e.g. on a validation error) so that the image need not be uploaded again.
143
+ def cache_name
144
+ @cache_id
145
+ end
146
+
147
+ # Restores the temporary image from its cache name (see #cache_name).
148
+ #
149
+ # The cache name comes from the request, so only a temporary image of the
150
+ # configured project that has not expired is accepted; a confirmed image, which
151
+ # may belong to another record, must not be attached through it. Anything else
152
+ # raises CarrierWave::InvalidParameter, which CarrierWave ignores as it does an
153
+ # invalid cache name.
154
+ def retrieve_from_cache!(cache_name)
155
+ with_callbacks(:retrieve_from_cache, cache_name) do
156
+ public_id = temporary_public_id_from(cache_name)
157
+ @cache_id = public_id
158
+ @staged = true
159
+ @file = storage.retrieve_from_cache!(public_id)
160
+ model.send :write_attribute, serialization_column, public_id
161
+ end
162
+ end
163
+
164
+ # Seconds until a temporary image uploaded by #cache! expires. nil uses the default
165
+ # of Resizing. Override this to change it, e.g. when a form may be kept open for a
166
+ # long time before it is submitted.
167
+ def cache_expires_in
168
+ nil
169
+ end
170
+
171
+ # The file cached by #cache! is the temporary image, which becomes the stored image
172
+ # when it is confirmed, so it must not be deleted after storing it.
173
+ def delete_tmp_file_after_storage
174
+ false
175
+ end
176
+
177
+ # process! is called before :cache
178
+ # Disable on Resizing, because `process` is repurposed as a definition of the
179
+ # transformation applied when the browser fetches the image URL (see #transform_string),
180
+ # so the processors must not be run as actual image processing on upload.
181
+ # https://github.com/carrierwaveuploader/carrierwave/blob/28190e99299a6131c0424a5d10205f471e39f3cd/lib/carrierwave/uploader/processing.rb#L12
182
+ def process!(*args)
183
+ # NOP
184
+ end
114
185
 
115
- @filename = file.public_id.to_s
116
- @file = file
186
+ # cache_versions! is called after :cache
187
+ # Disable on Resizing, because each version would upload the same image again and
188
+ # the resulting public_id would be stored nowhere, leaving orphan images behind.
189
+ # https://github.com/carrierwaveuploader/carrierwave/blob/28190e99299a6131c0424a5d10205f471e39f3cd/lib/carrierwave/uploader/versions.rb#L17
190
+ def cache_versions!(*args)
191
+ # NOP
192
+ end
193
+
194
+ # retrieve_versions_from_cache! is called after :retrieve_from_cache
195
+ # Disable on Resizing, because the versions have no image of their own; each version
196
+ # would only look up the same temporary image again.
197
+ # https://github.com/carrierwaveuploader/carrierwave/blob/28190e99299a6131c0424a5d10205f471e39f3cd/lib/carrierwave/uploader/versions.rb#L20
198
+ def retrieve_versions_from_cache!(*args)
199
+ # NOP
117
200
  end
118
201
 
119
202
  def filename
@@ -157,6 +240,26 @@ module Resizing
157
240
 
158
241
  private
159
242
 
243
+ def temporary_public_id_from(cache_name)
244
+ public_id = begin
245
+ Resizing::PublicId.new(cache_name)
246
+ rescue StandardError
247
+ nil
248
+ end
249
+ raise_invalid_cache_name if public_id.nil? || public_id.empty? ||
250
+ public_id.project_id != Resizing.configure.project_id
251
+
252
+ # Resizing answers 404 for an expired temporary image even before deleting it
253
+ metadata = Resizing.metadata(public_id.image_id, {})
254
+ raise_invalid_cache_name unless metadata['temporary'] == true && metadata['public_id'].present?
255
+
256
+ metadata['public_id']
257
+ end
258
+
259
+ def raise_invalid_cache_name
260
+ raise ::CarrierWave::InvalidParameter, 'invalid cache name'
261
+ end
262
+
160
263
  # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
161
264
  def transform_string_from(processor)
162
265
  action = processor.first
@@ -6,7 +6,6 @@ module Resizing
6
6
  # usage.
7
7
  # options = {
8
8
  # image_host: 'https://img.resizing.net',
9
- # video_host: 'https://video.resizing.net',
10
9
  # project_id: '098a2a0d-0000-0000-0000-000000000000',
11
10
  # secret_token: '4g1cshg......rbs6'
12
11
  # }
@@ -30,6 +29,10 @@ module Resizing
30
29
  include Resizing::Configurable
31
30
  include Resizing::HttpClientable
32
31
 
32
+ DEPRECATED_PUT_MESSAGE = '[resizing] Resizing::Client#put is deprecated: ' \
33
+ 'the image update API is deprecated on Resizing. ' \
34
+ 'Upload a new image with #post instead. It will be deleted in a future version.'
35
+
33
36
  def initialize(*attrs)
34
37
  initialize_config(*attrs)
35
38
  end
@@ -38,15 +41,23 @@ module Resizing
38
41
  raise NotImplementedError
39
42
  end
40
43
 
44
+ # Uploads an image.
45
+ #
46
+ # === Options
47
+ #
48
+ # [:content_type] content type of the image (required)
49
+ # [:filename] file name sent to Resizing (defaults to the basename of the path)
50
+ # [:temporary] uploads the image as a temporary image when true. It is deleted by
51
+ # Resizing at its expires_at unless it is confirmed with #confirm.
52
+ # [:expires_in] seconds until a temporary image expires (Integer or
53
+ # ActiveSupport::Duration). Resizing applies its default when omitted.
41
54
  def post(filename_or_io, options = {})
42
55
  ensure_content_type(options)
43
56
  ensure_filename_or_io(filename_or_io)
44
57
  filename = gather_filename filename_or_io, options
45
58
 
46
59
  url = build_post_url
47
- params = {
48
- image: Faraday::Multipart::FilePart.new(filename_or_io, options[:content_type], filename)
49
- }
60
+ params = build_post_params(filename_or_io, options, filename)
50
61
 
51
62
  response = handle_faraday_error do
52
63
  http_client.post(url, params) do |request|
@@ -57,7 +68,9 @@ module Resizing
57
68
  handle_create_response(response)
58
69
  end
59
70
 
71
+ # @deprecated Use {#post} to upload a new image instead.
60
72
  def put(image_id, filename_or_io, options)
73
+ warn DEPRECATED_PUT_MESSAGE
61
74
  ensure_content_type(options)
62
75
  ensure_filename_or_io(filename_or_io)
63
76
  filename = gather_filename filename_or_io, options
@@ -76,6 +89,21 @@ module Resizing
76
89
  handle_create_response(response)
77
90
  end
78
91
 
92
+ # Confirms a temporary image, so that Resizing no longer deletes it at its expires_at.
93
+ # Confirming an image that is already confirmed succeeds without changing it.
94
+ # Raises APIError when the image is not found, deleted or already expired.
95
+ def confirm(image_id)
96
+ url = build_confirm_url(image_id)
97
+
98
+ response = handle_faraday_error do
99
+ http_client.put(url) do |request|
100
+ request.headers['X-ResizingToken'] = config.generate_auth_header
101
+ end
102
+ end
103
+
104
+ handle_create_response(response)
105
+ end
106
+
79
107
  def delete(image_id)
80
108
  url = build_delete_url(image_id)
81
109
 
@@ -126,6 +154,21 @@ module Resizing
126
154
  "#{config.image_host}/projects/#{config.project_id}/upload/images/#{image_id}/metadata"
127
155
  end
128
156
 
157
+ def build_confirm_url(image_id)
158
+ "#{config.image_host}/projects/#{config.project_id}/upload/images/#{image_id}/confirm"
159
+ end
160
+
161
+ def build_post_params(filename_or_io, options, filename)
162
+ params = {
163
+ image: Faraday::Multipart::FilePart.new(filename_or_io, options[:content_type], filename)
164
+ }
165
+ return params unless options[:temporary]
166
+
167
+ params[:temporary] = 'true'
168
+ params[:expires_in] = options[:expires_in].to_i.to_s unless options[:expires_in].nil?
169
+ params
170
+ end
171
+
129
172
  def ensure_content_type(options)
130
173
  raise ArgumentError, "need options[:content_type] for #{options.inspect}" unless options[:content_type]
131
174
  end