# frozen_string_literal: true require 'net/http' require 'signpost/signer' module Hobgoblin class Client ClientError = Class.new(StandardError) UploadForbiddenError = Class.new(ClientError) FileNotFoundError = Class.new(ClientError) def initialize(options) @options = options end def download(remote_source, path) remote_path = "/#{remote_source}" unless remote_source[0] == '/' uri = URI.parse("#{@options['server']}#{remote_source}") req = Net::HTTP::Get.new(uri) Signpost::Signer.sign_request(req) res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 10) do |http| http.request(req) end case res when Net::HTTPRedirection location_uri = URI.parse(res['Location']) location_req = Net::HTTP::Get.new(location_uri) rsp = Net::HTTP.start(location_uri.host, location_uri.port, use_ssl: true, read_timeout: 10) do |http| http.request(location_req) end File.binwrite(path, rsp.body.force_encoding('UTF-8')) File.chmod(0755, path) puts <<-STR = Downloaded: Source: #{remote_source} Destination: #{path} STR else raise "#{res.code} #{res.message}" end end def upload(source, remote_path) extended_source_path = File.expand_path(source) raise FileNotFoundError unless File.exist?(extended_source_path) remote_path = "/#{remote_path}" unless remote_path[0] == '/' uri = URI.parse("#{@options['server']}#{remote_path}") headers = { 'Host' => uri.host, 'User-Agent' => "Hobgoblin/#{Hobgoblin::VERSION}" } req = Net::HTTP::Post.new(uri) req.body = File.binread(extended_source_path) req.content_type = 'multipart/form-data' req.initialize_http_header(headers) Signpost::Signer.sign_request(req) res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(req) end if res.code == '401' puts 'You are not authorized to upload assets' exit 1 else puts <<-STR = Uploaded: Source: #{extended_source_path} Destination: #{uri.to_s} STR end end end end