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

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ CloudinaryService

Returns a new instance of CloudinaryService.



35
36
37
# File 'lib/active_storage/service/cloudinary_service.rb', line 35

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

Instance Attribute Details

#upload_optionsObject (readonly)

Returns the value of attribute upload_options.



33
34
35
# File 'lib/active_storage/service/cloudinary_service.rb', line 33

def upload_options
  @upload_options
end

Instance Method Details

#delete(key) ⇒ Object



103
104
105
106
107
108
109
110
111
112
# File 'lib/active_storage/service/cloudinary_service.rb', line 103

def delete(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



114
115
116
117
# File 'lib/active_storage/service/cloudinary_service.rb', line 114

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



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/active_storage/service/cloudinary_service.rb', line 135

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.



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/active_storage/service/cloudinary_service.rb', line 155

def download_chunk(key, range)
  url = Cloudinary::Utils.cloudinary_url(public_id(key), resource_type: resource_type(nil, key))
  uri = URI(url)
  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)


119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/active_storage/service/cloudinary_service.rb', line 119

def exist?(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



96
97
98
99
100
101
# File 'lib/active_storage/service/cloudinary_service.rb', line 96

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.



184
185
186
187
188
189
190
191
# File 'lib/active_storage/service/cloudinary_service.rb', line 184

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/active_storage/service/cloudinary_service.rb', line 39

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



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/active_storage/service/cloudinary_service.rb', line 60

def url(key, filename: nil, content_type: '', **options)
  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



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/active_storage/service/cloudinary_service.rb', line 75

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