Class: Cloudinary::Uploader

Inherits:
Object show all
Defined in:
lib/cloudinary/uploader.rb

Constant Summary collapse

REMOTE_URL_REGEX =
Cloudinary::Utils::REMOTE_URL_REGEX
TEXT_PARAMS =
[:public_id, :font_family, :font_size, :font_color, :text_align, :font_weight, :font_style, :background, :opacity, :text_decoration, :line_spacing]

Class Method Summary collapse

Class Method Details

.add_tag(tag, public_ids = [], options = {}) ⇒ Object

options may include 'exclusive' (boolean) which causes clearing this tag from all other resources


259
260
261
262
263
# File 'lib/cloudinary/uploader.rb', line 259

def self.add_tag(tag, public_ids = [], options = {})
  exclusive = options.delete(:exclusive)
  command   = exclusive ? "set_exclusive" : "add"
  return self.call_tags_api(tag, command, public_ids, options)
end

.build_eager(eager) ⇒ Object

Deprecated.

10
11
12
# File 'lib/cloudinary/uploader.rb', line 10

def self.build_eager(eager)
  Cloudinary::Utils.build_eager(eager)
end

.build_upload_params(options) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/cloudinary/uploader.rb', line 15

def self.build_upload_params(options)
  #symbolize keys
  options = options.clone
  options.keys.each { |key| options[key.to_sym] = options.delete(key) if key.is_a?(String) }

  params = {
    :access_control            => Cloudinary::Utils.json_array_param(options[:access_control]),
    :access_mode               => options[:access_mode],
    :allowed_formats           => Cloudinary::Utils.build_array(options[:allowed_formats]).join(","),
    :async                     => Cloudinary::Utils.as_safe_bool(options[:async]),
    :auto_tagging              => options[:auto_tagging] && options[:auto_tagging].to_f,
    :background_removal        => options[:background_removal],
    :backup                    => Cloudinary::Utils.as_safe_bool(options[:backup]),
    :callback                  => options[:callback],
    :categorization            => options[:categorization],
    :cinemagraph_analysis      => Cloudinary::Utils.as_safe_bool(options[:cinemagraph_analysis]),
    :colors                    => Cloudinary::Utils.as_safe_bool(options[:colors]),
    :context                   => Cloudinary::Utils.encode_context(options[:context]),
    :custom_coordinates        => Cloudinary::Utils.encode_double_array(options[:custom_coordinates]),
    :detection                 => options[:detection],
    :discard_original_filename => Cloudinary::Utils.as_safe_bool(options[:discard_original_filename]),
    :eager                     => Cloudinary::Utils.build_eager(options[:eager]),
    :eager_async               => Cloudinary::Utils.as_safe_bool(options[:eager_async]),
    :eager_notification_url    => options[:eager_notification_url],
    :exif                      => Cloudinary::Utils.as_safe_bool(options[:exif]),
    :eval                      => options[:eval],
    :face_coordinates          => Cloudinary::Utils.encode_double_array(options[:face_coordinates]),
    :faces                     => Cloudinary::Utils.as_safe_bool(options[:faces]),
    :folder                    => options[:folder],
    :format                    => options[:format],
    :filename_override         => options[:filename_override],
    :headers                   => build_custom_headers(options[:headers]),
    :image_metadata            => Cloudinary::Utils.as_safe_bool(options[:image_metadata]),
    :invalidate                => Cloudinary::Utils.as_safe_bool(options[:invalidate]),
    :moderation                => options[:moderation],
    :notification_url          => options[:notification_url],
    :ocr                       => options[:ocr],
    :overwrite                 => Cloudinary::Utils.as_safe_bool(options[:overwrite]),
    :phash                     => Cloudinary::Utils.as_safe_bool(options[:phash]),
    :proxy                     => options[:proxy],
    :public_id                 => options[:public_id],
    :quality_analysis          => Cloudinary::Utils.as_safe_bool(options[:quality_analysis]),
    :quality_override          => options[:quality_override],
    :raw_convert               => options[:raw_convert],
    :responsive_breakpoints    => Cloudinary::Utils.generate_responsive_breakpoints_string(options[:responsive_breakpoints]),
    :return_delete_token       => Cloudinary::Utils.as_safe_bool(options[:return_delete_token]),
    :similarity_search         => options[:similarity_search],
    :tags                      => options[:tags] && Cloudinary::Utils.build_array(options[:tags]).join(","),
    :timestamp                 => (options[:timestamp] || Time.now.to_i),
    :transformation            => Cloudinary::Utils.generate_transformation_string(options.clone),
    :type                      => options[:type],
    :unique_filename           => Cloudinary::Utils.as_safe_bool(options[:unique_filename]),
    :upload_preset             => options[:upload_preset],
    :use_filename              => Cloudinary::Utils.as_safe_bool(options[:use_filename]),
    :accessibility_analysis    => Cloudinary::Utils.as_safe_bool(options[:accessibility_analysis]),
    :metadata                  => Cloudinary::Utils.encode_context(options[:metadata])
  }
  params
end

.create_archive(options = {}, target_format = nil) ⇒ Object

Creates a new archive in the server and returns information in JSON format


187
188
189
190
191
192
193
# File 'lib/cloudinary/uploader.rb', line 187

def self.create_archive(options={}, target_format = nil)
  call_api("generate_archive", options) do
    params                 = Cloudinary::Utils.archive_params(options)
    params[:target_format] = target_format if target_format
    params
  end
end

.create_zip(options = {}) ⇒ Object

Creates a new zip archive in the server and returns information in JSON format


196
197
198
# File 'lib/cloudinary/uploader.rb', line 196

def self.create_zip(options={})
  create_archive(options, "zip")
end

.destroy(public_id, options = {}) ⇒ Object


142
143
144
145
146
147
148
149
150
151
# File 'lib/cloudinary/uploader.rb', line 142

def self.destroy(public_id, options={})
  call_api("destroy", options) do
    {
      :timestamp  => (options[:timestamp] || Time.now.to_i),
      :type       => options[:type],
      :public_id  => public_id,
      :invalidate => options[:invalidate],
    }
  end
end

.exists?(public_id, options = {}) ⇒ Boolean

Returns:

  • (Boolean)

167
168
169
170
171
172
173
174
175
176
# File 'lib/cloudinary/uploader.rb', line 167

def self.exists?(public_id, options={})
  cloudinary_url = Cloudinary::Utils.cloudinary_url(public_id, options)
  begin
    code = RestClient::Request.execute(:method => :head, :url => cloudinary_url, :timeout => 5).code
    code >= 200 && code < 300
  rescue RestClient::ResourceNotFound
    return false
  end

end

.explicit(public_id, options = {}) ⇒ Object


178
179
180
181
182
183
184
# File 'lib/cloudinary/uploader.rb', line 178

def self.explicit(public_id, options={})
  call_api("explicit", options) do
    params             = build_upload_params(options)
    params[:public_id] = public_id
    params
  end
end

.explode(public_id, options = {}) ⇒ Object


245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/cloudinary/uploader.rb', line 245

def self.explode(public_id, options={})
  call_api("explode", options) do
    {
      :timestamp        => (options[:timestamp] || Time.now.to_i),
      :public_id        => public_id,
      :type             => options[:type],
      :format           => options[:format],
      :notification_url => options[:notification_url],
      :transformation   => Cloudinary::Utils.generate_transformation_string(options.clone)
    }
  end
end

.generate_sprite(tag, options = {}) ⇒ Object


210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/cloudinary/uploader.rb', line 210

def self.generate_sprite(tag, options={})
  version_store = options.delete(:version_store)

  result = call_api("sprite", options) do
    {
      :timestamp        => (options[:timestamp] || Time.now.to_i),
      :tag              => tag,
      :async            => options[:async],
      :notification_url => options[:notification_url],
      :transformation   => Cloudinary::Utils.generate_transformation_string(options.merge(:fetch_format => options[:format]))
    }
  end

  if version_store == :file && result && result["version"]
    if defined?(Rails) && defined?(Rails.root)
      FileUtils.mkdir_p("#{Rails.root}/tmp/cloudinary")
      File.open("#{Rails.root}/tmp/cloudinary/cloudinary_sprite_#{tag}.version", "w") { |file| file.print result["version"].to_s }
    end
  end
  return result
end

.multi(tag, options = {}) ⇒ Object


232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/cloudinary/uploader.rb', line 232

def self.multi(tag, options={})
  call_api("multi", options) do
    {
      :timestamp        => (options[:timestamp] || Time.now.to_i),
      :tag              => tag,
      :format           => options[:format],
      :async            => options[:async],
      :notification_url => options[:notification_url],
      :transformation   => Cloudinary::Utils.generate_transformation_string(options.clone)
    }
  end
end

.remove_all_tags(public_ids = [], options = {}) ⇒ Object


273
274
275
# File 'lib/cloudinary/uploader.rb', line 273

def self.remove_all_tags(public_ids = [], options = {})
  return self.call_tags_api(nil, "remove_all", public_ids, options)
end

.remove_tag(tag, public_ids = [], options = {}) ⇒ Object


265
266
267
# File 'lib/cloudinary/uploader.rb', line 265

def self.remove_tag(tag, public_ids = [], options = {})
  return self.call_tags_api(tag, "remove", public_ids, options)
end

.rename(from_public_id, to_public_id, options = {}) ⇒ Object


153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/cloudinary/uploader.rb', line 153

def self.rename(from_public_id, to_public_id, options={})
  call_api("rename", options) do
    {
      :timestamp      => (options[:timestamp] || Time.now.to_i),
      :type           => options[:type],
      :overwrite      => Cloudinary::Utils.as_safe_bool(options[:overwrite]),
      :from_public_id => from_public_id,
      :to_public_id   => to_public_id,
      :to_type        => options[:to_type],
      :invalidate     => Cloudinary::Utils.as_safe_bool(options[:invalidate])
    }
  end
end

.replace_tag(tag, public_ids = [], options = {}) ⇒ Object


269
270
271
# File 'lib/cloudinary/uploader.rb', line 269

def self.replace_tag(tag, public_ids = [], options = {})
  return self.call_tags_api(tag, "replace", public_ids, options)
end

.text(text, options = {}) ⇒ Object


202
203
204
205
206
207
208
# File 'lib/cloudinary/uploader.rb', line 202

def self.text(text, options={})
  call_api("text", options) do
    params = { :timestamp => Time.now.to_i, :text => text }
    TEXT_PARAMS.each { |k| params[k] = options[k] unless options[k].nil? }
    params
  end
end

.unsigned_upload(file, upload_preset, options = {}) ⇒ Object


75
76
77
# File 'lib/cloudinary/uploader.rb', line 75

def self.unsigned_upload(file, upload_preset, options={})
  upload(file, options.merge(:unsigned => true, :upload_preset => upload_preset))
end

.update_metadata(metadata, public_ids, options = {}) ⇒ Object

Populates metadata fields with the given values. Existing values will be overwritten.

Any metadata-value pairs given are merged with any existing metadata-value pairs (an empty value for an existing metadata field clears the value).

Parameters:

  • metadata (Hash)

    A list of custom metadata fields (by external_id) and the values to assign to each of them.

  • public_ids (Array)

    An array of Public IDs of assets uploaded to Cloudinary.

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :resource_type (String)

    The type of file. Default: image. Valid values: image, raw, video.

  • :type (String)

    The storage type. Default: upload. Valid values: upload, private, authenticated

Returns:

  • mixed a list of public IDs that were updated

Raises:

  • (Cloudinary::Api:Error)

289
290
291
292
293
294
295
296
297
298
# File 'lib/cloudinary/uploader.rb', line 289

def self.(, public_ids, options = {})
  self.call_api("metadata", options) do
    {
      timestamp: (options[:timestamp] || Time.now.to_i),
      type: options[:type],
      public_ids: Cloudinary::Utils.build_array(public_ids),
      metadata: Cloudinary::Utils.encode_context()
    }
  end
end

.upload(file, options = {}) ⇒ Object


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/cloudinary/uploader.rb', line 79

def self.upload(file, options={})
  call_api("upload", options) do
    params = build_upload_params(options)
    if file.is_a?(Pathname)
      params[:file] = File.open(file, "rb")
    elsif file.is_a?(StringIO)
      file.rewind
      params[:file] = Cloudinary::Blob.new(file.read, options)
    elsif file.respond_to?(:read) || Cloudinary::Utils.is_remote?(file)
      params[:file] = file
    else
      params[:file] = File.open(file, "rb")
    end
    [params, [:file]]
  end
end

.upload_large(file, public_id_or_options = {}, old_options = {}) ⇒ Object

Upload large files. Note that public_id should include an extension for best results.


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/cloudinary/uploader.rb', line 97

def self.upload_large(file, public_id_or_options={}, old_options={})
  if public_id_or_options.is_a?(Hash)
    options   = public_id_or_options
    public_id = options[:public_id]
  else
    public_id = public_id_or_options
    options   = old_options
  end
  if Cloudinary::Utils.is_remote?(file)
    return upload(file, options.merge(:public_id => public_id))
  elsif file.is_a?(Pathname) || !file.respond_to?(:read)
    filename = file
    file     = File.open(file, "rb")
  else
    filename = "cloudinaryfile"
  end
  unique_upload_id = Cloudinary::Utils.random_public_id
  upload     = nil
  index      = 0
  chunk_size = options[:chunk_size] || 20_000_000
  until file.eof?
    buffer      = file.read(chunk_size)
    current_loc = index*chunk_size
    range       = "bytes #{current_loc}-#{current_loc+buffer.size - 1}/#{file.size}"
    upload      = upload_large_part(Cloudinary::Blob.new(buffer, :original_filename => filename), options.merge(:public_id => public_id, :unique_upload_id => unique_upload_id, :content_range => range))
    index       += 1
  end
  upload
end

.upload_large_part(file, options = {}) ⇒ Object

Upload large files. Note that public_id should include an extension for best results.


129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/cloudinary/uploader.rb', line 129

def self.upload_large_part(file, options={})
  options[:resource_type] ||= :raw
  call_api("upload", options) do
    params = build_upload_params(options)
    if file.is_a?(Pathname) || !file.respond_to?(:read)
      params[:file] = File.open(file, "rb")
    else
      params[:file] = file
    end
    [params, [:file]]
  end
end