Module: Balloon::Download

Extended by:
ActiveSupport::Concern
Defined in:
lib/balloon/download.rb

Instance Method Summary collapse

Instance Method Details

#down_url(uri) ⇒ Object



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
36
37
38
39
40
# File 'lib/balloon/download.rb', line 8

def down_url(uri)
  connection = ::Faraday.new({:ssl => {:verify => false}})
  response = connection.get(uri)
  generate_down_cache_directory
  path = File.join down_cache_path, generate_down_id

  if response.status != 200
    raise Balloon::DownloadError, I18n.translate(:"errors.messages.response_error")
  end

  if content_type = MIME::Types[response.headers["content-type"]][0]
    mime_type = content_type.content_type
    if self.respond_to?(:uploader_mimetype_white)
       if !uploader_mimetype_white.include?(mime_type)
         raise Balloon::DownloadError, I18n.translate(:"errors.messages.down_mime_error")
       end
    elsif self.respond_to?(:uploader_mimetype_black)
       if !uploader_mimetype_black.include?(mime_type)
         raise Balloon::DownloadError, I18n.translate(:"errors.messages.down_mime_error")
       end
    end
  end

  File.open(path, "wb") do |f|
    f.write(response.body)
  end

  return path
rescue Faraday::ConnectionFailed => e
  raise Balloon::DownloadError, I18n.translate(:"errors.messages.connection_failed")
rescue Faraday::TimeoutError => e
  raise Ballloon::DownloadError, I18n.translate(:"errors.messages.timeout_error")
end