-
Notifications
You must be signed in to change notification settings - Fork 2
/
ipfsclient.go
67 lines (52 loc) · 1.59 KB
/
ipfsclient.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package ipfs
import (
"context"
"fmt"
"strings"
"github.com/avislash/nftstamper/lib/image"
"github.com/ipfs/boxo/files"
httpapi "github.com/ipfs/go-ipfs-http-client"
ipfsClient "github.com/ipfs/go-ipfs-http-client"
"github.com/ipfs/interface-go-ipfs-core/path"
multiAddr "github.com/multiformats/go-multiaddr"
)
var _ Client = (*IPFSClient)(nil)
type IPFSClient struct {
*httpapi.HttpApi
ImageDecoder image.Decoder
}
//endpoint must be in MultiAddr Format as specified under https://github.com/multiformats/multiaddr#encoding
func NewIPFSClient(endpoint string, options ...Option) (*IPFSClient, error) {
addr, err := multiAddr.NewMultiaddr(endpoint)
if err != nil {
return nil, fmt.Errorf("Error creating client: %w", err)
}
client, err := ipfsClient.NewApi(addr)
if err != nil {
return nil, fmt.Errorf("Error creating client: %w", err)
}
c := &IPFSClient{client, &image.DefaultDecoder{}}
for _, applyOpt := range options {
applyOpt(c)
}
return c, nil
}
func (c *IPFSClient) GetImageFromIPFS(imagePath string) (image.Image, error) {
// Image CID
cid := path.New(strings.TrimPrefix(imagePath, "ipfs://"))
// Retrieve the file from IPFS
node, err := c.Unixfs().Get(context.Background(), cid)
if err != nil {
return nil, fmt.Errorf("Error retrieving centinel from IPFS Hash %s: %w", cid, err)
}
file := files.ToFile((node))
defer file.Close()
img, err := c.ImageDecoder.Decode(file)
if err != nil {
return nil, fmt.Errorf("Error decoding IPFS File as image: %w", err)
}
return img, nil
}
func (c *IPFSClient) setImageDecoder(decoder image.Decoder) {
c.ImageDecoder = decoder
}