|
| 1 | +require "json" |
| 2 | +require "net/http" |
| 3 | +require "net/http/post/multipart" |
| 4 | + |
| 5 | +if ARGV.empty? |
| 6 | + puts "Usage: #{$0} file1 file2 file3..." |
| 7 | + Process.exit 1 |
| 8 | +end |
| 9 | + |
| 10 | +def request(host: "localhost:3000", path:, method: :get, payload: nil, access_token: nil) |
| 11 | + uri = URI("http://#{host}/api/v1/#{path}") |
| 12 | + http = Net::HTTP.new(uri.host, uri.port) |
| 13 | + req = case method |
| 14 | + when :get |
| 15 | + Net::HTTP::Get.new(uri.path) |
| 16 | + when :post |
| 17 | + Net::HTTP::Post.new(uri.path, "Content-Type" => "application/json") |
| 18 | + else |
| 19 | + raise "unknown method" |
| 20 | + end |
| 21 | + if access_token |
| 22 | + req["Authorization"] = "Bearer #{access_token}" |
| 23 | + end |
| 24 | + if !%i(get head).include?(method) && payload |
| 25 | + req.body = payload.to_json |
| 26 | + end |
| 27 | + JSON.parse(http.request(req).body, symbolize_names: true) |
| 28 | +end |
| 29 | + |
| 30 | +def login |
| 31 | + request path: "sessions", method: :post, payload: { username: "test", password: "test" } |
| 32 | +end |
| 33 | + |
| 34 | +def upload_file(access_token:) |
| 35 | + request path: "objects", method: :post, access_token: access_token |
| 36 | +end |
| 37 | + |
| 38 | +def upload_file_to_cell(access_token:, upload_token:, cell_ip:, filename:) |
| 39 | + uri = URI.parse("http://#{cell_ip}:6000/api/v1/objects/?upload_token=#{upload_token}") |
| 40 | + File.open(filename) do |file| |
| 41 | + req = Net::HTTP::Post::Multipart.new uri.request_uri, |
| 42 | + "object[payload]" => UploadIO.new(file, "application/data", filename) |
| 43 | + req["Authorization"] = "Bearer #{access_token}" |
| 44 | + res = Net::HTTP.start(uri.host, uri.port) do |http| |
| 45 | + http.request req |
| 46 | + end |
| 47 | + puts res.inspect |
| 48 | + end |
| 49 | +end |
| 50 | + |
| 51 | +access_token = login[:access_token] |
| 52 | + |
| 53 | +uploads = Array.new |
| 54 | +ARGV.count.times do |
| 55 | + uploads << upload_file(access_token: access_token) |
| 56 | +end |
| 57 | + |
| 58 | +uploads.each_with_index do |upload_info, i| |
| 59 | + upload_token = upload_info[:upload_token] |
| 60 | + cell_ip = upload_info[:cell][:ip_address] |
| 61 | + |
| 62 | + puts "Uploading file #{ARGV[i]}..." |
| 63 | + upload_file_to_cell access_token: access_token, upload_token: upload_token, cell_ip: cell_ip, |
| 64 | + filename: ARGV[i] |
| 65 | +end |
0 commit comments