Class: Service::CloudinaryService

Inherits:
Service
  • Object
show all
Defined in:
lib/active_storage/service/cloudinary_service.rb

Defined Under Namespace

Modules: Headers

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ CloudinaryService

Returns a new instance of CloudinaryService.



39
40
41
# File 'lib/active_storage/service/cloudinary_service.rb', line 39

def initialize(**options)
  @options = options
end

Instance Attribute Details

#upload_optionsObject (readonly)

Returns the value of attribute upload_options.



37
38
39
# File 'lib/active_storage/service/cloudinary_service.rb', line 37

def upload_options
  @upload_options
end

Class Method Details

.fetch_service_instance_and_config(source, options) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/active_storage/service/cloudinary_service.rb', line 199

def self.fetch_service_instance_and_config(source, options)
  return [nil, options] unless defined?(ActiveStorage::BlobKey) && source.is_a?(ActiveStorage::BlobKey) &&
    source.respond_to?(:attributes) && source.attributes.key?(:service_name)

  service_name = source.attributes[:service_name]

  begin
    service_instance = ActiveStorage::Blob.services.fetch(service_name.to_sym)

    unless service_instance.instance_of?(ActiveStorage::Service::CloudinaryService)
      Rails.logger.error "Expected service instance #{service_instance.class.name} to be of type ActiveStorage::Service::CloudinaryService."
      return [nil, options]
    end

    service_config = Rails.application.config.active_storage.service_configurations.fetch(service_name)
    options        = service_config.merge(options)
  rescue NameError => e
    Rails.logger.error "Failed to retrieve the service instance for #{service_name}: #{e.message}"
    return [nil, options]
  rescue => e
    Rails.logger.error "An unexpected error occurred: #{e.message}"
    return [nil, options]
  end

  [service_instance, options]
end

Instance Method Details

#delete(key) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
# File 'lib/active_storage/service/cloudinary_service.rb', line 108

def delete(key)
  key = find_blob_or_use_key(key)
  instrument :delete, key: key do
    options = {
      resource_type: resource_type(nil, key),
      type: @options[:type]
    }.compact

    Cloudinary::Uploader.destroy public_id(key), **options
  end
end

#delete_prefixed(prefix) ⇒ Object



120
121
122
123
# File 'lib/active_storage/service/cloudinary_service.rb', line 120

def delete_prefixed(prefix)
  # This method is used by ActiveStorage to delete derived resources after the main resource was deleted.
  # In Cloudinary, the derived resources are deleted automatically when the main resource is deleted.
end

#download(key, &block) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/active_storage/service/cloudinary_service.rb', line 142

def download(key, &block)
  uri = URI(url(key))
  if block_given?
    instrument :streaming_download, key: key do
      Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
        request = Net::HTTP::Get.new uri
        http.request request do |response|
          response.read_body &block
        end
      end
    end
  else
    instrument :download, key: key do
      res = Net::HTTP::get_response(uri)
      res.body
    end
  end
end

#download_chunk(key, range) ⇒ Object

Return the partial content in the byte range of the file at the key.



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/active_storage/service/cloudinary_service.rb', line 162

def download_chunk(key, range)
  uri = URI(url(key))
  instrument :download, key: key do
    req = Net::HTTP::Get.new(uri)
    range_end = case
                when range.end.nil? then ''
                when range.exclude_end? then range.end - 1
                else range.end
                end
    req['range'] = "bytes=#{[range.begin, range_end].join('-')}"
    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(req)
    end
    res.body.force_encoding(Encoding::BINARY)
  end

end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/active_storage/service/cloudinary_service.rb', line 125

def exist?(key)
  key = find_blob_or_use_key(key)
  instrument :exist, key: key do |payload|
    begin
      options = {
        resource_type: resource_type(nil, key),
        type: @options[:type]
      }.compact

      Cloudinary::Api.resource public_id(key), **options
      true
    rescue Cloudinary::Api::NotFound => e
      false
    end
  end
end

#headers_for_direct_upload(key, content_type:, checksum:) ⇒ Object



101
102
103
104
105
106
# File 'lib/active_storage/service/cloudinary_service.rb', line 101

def headers_for_direct_upload(key, content_type:, checksum:, **)
  {
    Headers::CONTENT_TYPE => content_type,
    Headers::CONTENT_MD5 => checksum,
  }
end

#public_id(key, filename = nil, content_type = '') ⇒ string

Returns the public id of the asset.

Public id includes both folder(defined globally in the configuration) and the active storage key. For raw files it also includes the file extension, since that’s how Cloudinary stores raw files.

Parameters:

  • key (ActiveStorage::BlobKey)

    The blob key with attributes.

  • filename (ActiveStorage::Filename) (defaults to: nil)

    The original filename.

  • content_type (string) (defaults to: '')

    The content type of the file.

Returns:

  • (string)

    The public id of the asset.



190
191
192
193
194
195
196
197
# File 'lib/active_storage/service/cloudinary_service.rb', line 190

def public_id(key, filename = nil, content_type = '')
  public_id = key
  if resource_type(nil, key) == 'raw'
    public_id = [key, ext_for_file(key, filename, content_type)].reject(&:blank?).join('.')
  end

  full_public_id_internal(public_id)
end

#upload(key, io, filename: nil, checksum: nil, **options) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/active_storage/service/cloudinary_service.rb', line 43

def upload(key, io, filename: nil, checksum: nil, **options)
  instrument :upload, key: key, checksum: checksum do
    begin
      extra_headers = checksum.nil? ? {} : {Headers::CONTENT_MD5 => checksum}
      options = @options.merge(options)
      resource_type = resource_type(io, key)
      options[:format] = ext_for_file(key) if resource_type == "raw"
      Cloudinary::Uploader.upload_large(
        io,
        public_id: public_id_internal(key),
        resource_type: resource_type,
        context: {active_storage_key: key, checksum: checksum},
        extra_headers: extra_headers,
        **options
      )
    rescue CloudinaryException => e
      raise ActiveStorage::IntegrityError, e.message, e.backtrace
    end
  end
end

#url(key, filename: nil, content_type: '', **options) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/active_storage/service/cloudinary_service.rb', line 64

def url(key, filename: nil, content_type: '', **options)
  key = find_blob_or_use_key(key)
  instrument :url, key: key do |payload|
    url = Cloudinary::Utils.cloudinary_url(
      full_public_id_internal(key, options),
      resource_type: resource_type(nil, key, content_type),
      format: ext_for_file(key, filename, content_type),
      **@options.merge(options.symbolize_keys)
    )

    payload[:url] = url

    url
  end
end

#url_for_direct_upload(key, **options) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/active_storage/service/cloudinary_service.rb', line 80

def url_for_direct_upload(key, **options)
  instrument :url, key: key do |payload|
    options = @options.merge(options.symbolize_keys)
    options[:resource_type] ||= resource_type(nil, key, options[:content_type])
    options[:public_id] = public_id_internal(key)
    # Provide file format for raw files, since js client does not include original file name.
    #
    # When the file is uploaded from the server, the request includes original filename. That allows Cloudinary
    # to identify file extension and append it to the public id of the file (raw files include file extension
    # in their public id, opposed to transformable assets (images/video) that use only basename). When uploading
    # through direct upload (client side js), filename is missing, and that leads to inconsistent/broken URLs.
    # To avoid that, we explicitly pass file format in options.
    options[:format] = ext_for_file(key) if options[:resource_type] == "raw"
    context = options.delete(:context)
    options[:context] = {active_storage_key: key}
    options[:context].reverse_merge!(context) if context.respond_to?(:merge)
    options.delete(:file)
    payload[:url] = api_uri("upload", options)
  end
end