Debian Codegraph @

ipfs/client/client.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package client
18
19 import (
20 "encoding/json"
21 "fmt"
22 "io"
23 "mime/multipart"
24 "net/http"
25 "net/url"
26 "os"
27 "path/filepath"
28 "strings"
29
30 "github.com/mitchellh/go-homedir"
31 ma "github.com/multiformats/go-multiaddr"
32 manet "github.com/multiformats/go-multiaddr/net"
33 )
34
35 // Client is an IPFS API client.
36 type Client struct {
37 // Address is URL of IPFS API to connect to.
38 Address string
39
40 // Client is http client to use for connecting to IPFS API
41 Client *http.Client
42 }
43
44 // New creates a new IPFS API client of the specified address.
45 func New(ipfsAPIAddress string) *Client {
46 return &Client{Address: ipfsAPIAddress, Client: http.DefaultClient}
47 }
48
49 // FileInfo represents the information provided by "/api/v0/files/stat" API of IPFS.
50 // Please see details at: https://docs.ipfs.tech/reference/kubo/rpc/#api-v0-files-stat
51 type FileInfo struct {
52 Blocks int `json:"Blocks"`
53 CumulativeSize uint64 `json:"CumulativeSize": "<uint64>"`
54 Hash string `json:"Hash": "<string>"`
55 Local bool `json:"Local": "<bool>"`
56 Size uint64 `json:"Size"`
57 SizeLocal uint64 `json:"SizeLocal"`
58 Type string `json:"Type"`
59 WithLocality bool `json:"WithLocality"`
60 }
61
62 // StatCID gets and returns information of the file specified by the cid.
63 func (c *Client) StatCID(cid string) (info *FileInfo, retErr error) {
64 if c.Address == "" {
65 return nil, fmt.Errorf("specify IPFS API address")
66 }
67 client := c.Client
68 if client == nil {
69 client = http.DefaultClient
70 }
71 ipfsAPIFilesStat := c.Address + "/api/v0/files/stat"
72 req, err := http.NewRequest("POST", ipfsAPIFilesStat, nil)
73 if err != nil {
74 return nil, err
75 }
76 q := req.URL.Query()
77 q.Add("arg", "/ipfs/"+cid)
78 req.URL.RawQuery = q.Encode()
79 resp, err := client.Do(req)
80 if err != nil {
81 return nil, err
82 }
83 defer func() {
84 if retErr != nil {
85 io.Copy(io.Discard, resp.Body)
86 resp.Body.Close()
87 }
88 }()
89 if resp.StatusCode/100 != 2 {
90 return nil, fmt.Errorf("failed to stat %v; status code: %v", cid, resp.StatusCode)
91 }
92 var rs FileInfo
93 if err := json.NewDecoder(resp.Body).Decode(&rs); err != nil {
94 return nil, err
95 }
96 return &rs, nil
97 }
98
99 // Get get the reader of the data specified by the IPFS path and optionally with
100 // the offset and length.
101 func (c *Client) Get(p string, offset *int, length *int) (_ io.ReadCloser, retErr error) {
102 if c.Address == "" {
103 return nil, fmt.Errorf("specify IPFS API address")
104 }
105 client := c.Client
106 if client == nil {
107 client = http.DefaultClient
108 }
109 ipfsAPICat := c.Address + "/api/v0/cat"
110 req, err := http.NewRequest("POST", ipfsAPICat, nil)
111 if err != nil {
112 return nil, err
113 }
114 q := req.URL.Query()
115 q.Add("arg", p)
116 if offset != nil {
117 q.Add("offset", fmt.Sprintf("%d", *offset))
118 }
119 if length != nil {
120 q.Add("length", fmt.Sprintf("%d", *length))
121 }
122 req.URL.RawQuery = q.Encode()
123 resp, err := client.Do(req)
124 if err != nil {
125 return nil, err
126 }
127 defer func() {
128 if retErr != nil {
129 io.Copy(io.Discard, resp.Body)
130 resp.Body.Close()
131 }
132 }()
133 if resp.StatusCode/100 != 2 {
134 return nil, fmt.Errorf("failed to cat %v; status code: %v", p, resp.StatusCode)
135 }
136 return resp.Body, nil
137 }
138
139 // Add adds the provided data to IPFS and returns its CID (v1).
140 func (c *Client) Add(r io.Reader) (cidv1 string, retErr error) {
141 if c.Address == "" {
142 return "", fmt.Errorf("specify IPFS API address")
143 }
144 client := c.Client
145 if client == nil {
146 client = http.DefaultClient
147 }
148 ipfsAPIAdd := c.Address + "/api/v0/add"
149 pr, pw := io.Pipe()
150 mw := multipart.NewWriter(pw)
151 contentType := mw.FormDataContentType()
152 go func() {
153 fw, err := mw.CreateFormFile("file", "file")
154 if err != nil {
155 pw.CloseWithError(err)
156 return
157 }
158 if _, err := io.Copy(fw, r); err != nil {
159 pw.CloseWithError(err)
160 return
161 }
162 if err := mw.Close(); err != nil {
163 pw.CloseWithError(err)
164 return
165 }
166 pw.Close()
167 }()
168 req, err := http.NewRequest("POST", ipfsAPIAdd, pr)
169 if err != nil {
170 return "", err
171 }
172 req.Header.Add("Content-Type", contentType)
173 q := req.URL.Query()
174 q.Add("cid-version", "1")
175 q.Add("pin", "true")
176 req.URL.RawQuery = q.Encode()
177 resp, err := client.Do(req)
178 if err != nil {
179 return "", err
180 }
181 defer func() {
182 io.Copy(io.Discard, resp.Body)
183 resp.Body.Close()
184 }()
185 if resp.StatusCode/100 != 2 {
186 return "", fmt.Errorf("failed to add; status code: %v", resp.StatusCode)
187 }
188 var rs struct {
189 Hash string `json:"Hash"`
190 }
191 if err := json.NewDecoder(resp.Body).Decode(&rs); err != nil {
192 return "", err
193 }
194 if rs.Hash == "" {
195 return "", fmt.Errorf("got empty hash")
196 }
197 return rs.Hash, nil
198 }
199
200 // GetIPFSAPIAddress get IPFS API URL from the specified IPFS repository.
201 // If ipfsPath == "", then it's default is "~/.ipfs".
202 // This is compatible to IPFS client behaviour: https://github.com/ipfs/go-ipfs-http-client/blob/171fcd55e3b743c38fb9d78a34a3a703ee0b5e89/api.go#L69-L81
203 func GetIPFSAPIAddress(ipfsPath string, scheme string) (string, error) {
204 if ipfsPath == "" {
205 ipfsPath = "~/.ipfs"
206 }
207 baseDir, err := homedir.Expand(ipfsPath)
208 if err != nil {
209 return "", err
210 }
211 api, err := os.ReadFile(filepath.Join(baseDir, "api"))
212 if err != nil {
213 return "", err
214 }
215 a, err := ma.NewMultiaddr(strings.TrimSpace(string(api)))
216 if err != nil {
217 return "", err
218 }
219 _, iurl, err := manet.DialArgs(a)
220 if err != nil {
221 return "", err
222 }
223 iurl = scheme + "://" + iurl
224 if _, err := url.Parse(iurl); err != nil {
225 return "", err
226 }
227 return iurl, nil
228 }