Class: Agave::Upload::File

Inherits:
Object
  • Object
show all
Defined in:
lib/agave/upload/file.rb

Constant Summary collapse

IMAGE_FORMATS =
%w(png jpg jpeg gif)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, source) ⇒ File

Returns a new instance of File.



15
16
17
18
# File 'lib/agave/upload/file.rb', line 15

def initialize(client, source)
  @client = client
  @source = source
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



13
14
15
# File 'lib/agave/upload/file.rb', line 13

def client
  @client
end

#sourceObject (readonly)

Returns the value of attribute source.



13
14
15
# File 'lib/agave/upload/file.rb', line 13

def source
  @source
end

Instance Method Details

#fileObject



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/agave/upload/file.rb', line 20

def file
  @file ||= if http_source?
              uri = Addressable::URI.parse(source)
              ext = ::File.extname(uri.path)
              Tempfile.new(['file', ext]).tap do |file|
                Downloadr::HTTP.new(source, file).download
              end
            else
              ::File.new(::File.expand_path(source))
            end
end

#filenameObject



39
40
41
42
43
44
45
# File 'lib/agave/upload/file.rb', line 39

def filename
  if http_source?
    ::File.basename(source)
  else
    ::File.basename(file.path)
  end
end

#format_resource(upload_request) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/agave/upload/file.rb', line 69

def format_resource(upload_request)
  extension = ::File.extname(::File.basename(file.path)).delete('.')

  base_format = {
    path: upload_request[:id],
    size: ::File.size(file.path),
    format: extension
  }

  if IMAGE_FORMATS.include?(extension)
    width, height = FastImage.size(file.path)

    base_format.merge(
      width: width,
      height: height,
      format: FastImage.type(file.path).to_s
    )
  else
    base_format
  end
end

#http_source?Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
# File 'lib/agave/upload/file.rb', line 32

def http_source?
  uri = Addressable::URI.parse(source)
  uri.scheme == 'http' || uri.scheme == 'https'
rescue Addressable::URI::InvalidURIError
  false
end

#uploadObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/agave/upload/file.rb', line 47

def upload
  upload_request = client.upload_request.create(filename: filename)
  uri = URI.parse(upload_request[:url])

  request = Net::HTTP::Put.new(
    uri,
    'x-amz-acl' => 'public-read'
  )
  request.body = file.read

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  http.request(request)

  uploads = client.uploads.create(
    format_resource(upload_request)
  )

  uploads["id"]
end