Class: Ipfs::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ipfs/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_endpoint, gateway_endpoint) ⇒ Client

Returns a new instance of Client.



13
14
15
16
17
# File 'lib/ipfs/client.rb', line 13

def initialize(api_endpoint, gateway_endpoint)
  @api_endpoint = api_endpoint
  @gateway_endpoint = gateway_endpoint
  @http_client = HTTP
end

Instance Attribute Details

#api_endpointObject (readonly)

Returns the value of attribute api_endpoint.



11
12
13
# File 'lib/ipfs/client.rb', line 11

def api_endpoint
  @api_endpoint
end

#gateway_endpointObject (readonly)

Returns the value of attribute gateway_endpoint.



11
12
13
# File 'lib/ipfs/client.rb', line 11

def gateway_endpoint
  @gateway_endpoint
end

#http_clientObject (readonly)

Returns the value of attribute http_client.



11
12
13
# File 'lib/ipfs/client.rb', line 11

def http_client
  @http_client
end

Instance Method Details

#add(path) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ipfs/client.rb', line 19

def add(path)
  res = @http_client.post(
    "#{@api_endpoint}/api/v0/add",
    form: {
      file: HTTP::FormData::File.new(path)
    }
  )

  if res.code >= 200 && res.code <= 299
    JSON.parse(res.body)
  else
    raise Error, res.body
  end
end

#build_file_url(hash, filename = '') ⇒ Object



63
64
65
66
# File 'lib/ipfs/client.rb', line 63

def build_file_url(hash, filename = '')
  query = filename.empty? ? '' : "?filename=#{filename}"
  "#{@gateway_endpoint}/ipfs/#{hash}#{query}"
end

#cat(hash, offset, length) ⇒ Object



34
35
36
37
# File 'lib/ipfs/client.rb', line 34

def cat(hash, offset, length)
  res = @http_client.get("#{@api_endpoint}/api/v0/cat?arg#{hash}&offset=#{offset}&length=#{length}")
  res.body
end

#dht_findProvs(hash, &block) ⇒ Object



39
40
41
42
# File 'lib/ipfs/client.rb', line 39

def dht_findProvs(hash, &block)
  res = @http_client.post("#{@api_endpoint}/api/v0/dht/findprovs?arg=#{hash}")
  res.body.each(&block)
end

#download(hash, &block) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/ipfs/client.rb', line 44

def download(hash, &block)
  url = build_file_url(hash)
  res = @http_client.get(url)

  if block_given?
    res.body.each(&block)
  else
    res.body
  end
end

#file_exists?(key) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/ipfs/client.rb', line 55

def file_exists?(key)
  dht_findProvs(key) do |chunk|
    res = chunk.split("\n")[0]
    res_json = JSON.parse res
    return res_json['Type'] == 4
  end
end