Module: Upload

Extended by:
Helper::Upload
Included in:
Skynet
Defined in:
lib/skynet/upload.rb

Overview

Module for handling outbound requests

Instance Method Summary collapse

Methods included from Helper::Upload

default_options, strip_dotslash_path

Instance Method Details

#http_post_header(data = {}) ⇒ Object

Default headers provided for uploading files, any argument provided is merged with the default values



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/skynet/upload.rb', line 11

def http_post_header(data = {})
  default_data = {
    headers: {
      'Accept' => 'application/octet-stream',
      'Content-Type' => 'application/octet-stream',
      'Transfer-Encoding' => 'gzip, chunked'
    }
  }

  default_data.merge(data) unless data.empty?
end

#upload_file(file_path, override_options = {}) ⇒ Object

Uploads file to the skynet, file_path is required but options are optional since default values are provided



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/skynet/upload.rb', line 24

def upload_file(file_path, override_options = {})
  options = Helper::Upload.default_options
  options = Helper::Upload.default_options.merge(override_options) unless override_options.empty?
  return "File #{file_path} does not exist!" unless File.exist?(file_path)

  host = options[:portal_url]
  path = options[:portal_upload_path]
  filename = options[:custom_filename] || file_path
  filename = Helper::Upload.strip_dotslash_path(filename)

  url = "#{host}#{path}?filename=#{filename}"
  binary_content = File.readlines(file_path, mode: 'rb').join

  header_data = http_post_header({
                                   headers: {
                                     'Content-Disposition' => "attachment; filename='#{filename}'"
                                   },
                                   body: binary_content,
                                   options[:portal_file_fieldname] => filename
                                 })

  upload_request = HTTParty.post(url, header_data)
  parsed_request = upload_request.to_hash
  "Upload successful, skylink: #{parsed_request['skylink']}"
end