aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/app/models/active_storage/identification.rb
blob: 8d334ae1ea9befaa2616a0bafda731d2895481d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# frozen_string_literal: true

require "net/http"

class ActiveStorage::Identification #:nodoc:
  attr_reader :blob

  def initialize(blob)
    @blob = blob
  end

  def content_type
    Marcel::MimeType.for(identifiable_chunk, name: filename, declared_type: declared_content_type)
  end

  private
    def identifiable_chunk
      Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |client|
        client.get(uri, "Range" => "bytes=0-4095").body
      end
    end

    def uri
      @uri ||= URI.parse(blob.service_url)
    end


    def filename
      blob.filename.to_s
    end

    def declared_content_type
      blob.content_type
    end
end