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.



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

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

Instance Attribute Details

#upload_optionsObject (readonly)

Returns the value of attribute upload_options.



31
32
33
# File 'lib/active_storage/service/cloudinary_service.rb', line 31

def upload_options
  @upload_options
end

Instance Method Details

#delete(key) ⇒ Object



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

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



112
113
114
115
# File 'lib/active_storage/service/cloudinary_service.rb', line 112

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



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

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.



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

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)


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

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



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

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.



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

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



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

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



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

def url(key, filename: nil, content_type: '', **options)
  instrument :url, key: key do |payload|
    url = Cloudinary::Utils.cloudinary_url(
      full_public_id_internal(key),
      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



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

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