/
client.go
105 lines (89 loc) · 1.95 KB
/
client.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"context"
"encoding/json"
"errors"
shell "github.com/ipfs/go-ipfs-api"
files "github.com/ipfs/go-ipfs-files"
"io"
"log"
"os"
"path/filepath"
"time"
)
type Client struct {
shell *shell.Shell
node string
pinServices map[string]*PinService
}
func NewClient(node string, remotePinServices []interface{}) (*Client, error) {
sh := shell.NewShell(node)
sh.SetTimeout(10 * time.Minute)
pinServices := buildPinServiceConfigs(remotePinServices)
client := &Client{
shell: sh,
node: node,
pinServices: pinServices,
}
return client, nil
}
func (c *Client) getHash(path string) (string, error) {
f, err := os.Open(path) //, os.O_RDWR, 0755)
if err != nil {
return "", err
}
defer f.Close()
return c.shell.Add(f, shell.OnlyHash(true))
}
func (c *Client) getHashDir(dir string) (string, error) {
stat, err := os.Lstat(dir)
if err != nil {
return "", err
}
sf, err := files.NewSerialFile(dir, false, stat)
if err != nil {
return "", err
}
slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry(filepath.Base(dir), sf)})
reader := files.NewMultiFileReader(slf, true)
resp, err := c.shell.Request("add").
Option("recursive", true).
Option("hash-only", true).
Body(reader).
Send(context.Background())
if err != nil {
return "", nil
}
defer resp.Close()
log.Println("OUT:", resp.Output)
if resp.Error != nil {
return "", resp.Error
}
dec := json.NewDecoder(resp.Output)
var final string
for {
var out object
err = dec.Decode(&out)
if err != nil {
if err == io.EOF {
break
}
return "", err
}
final = out.Hash
}
if final == "" {
return "", errors.New("no results received")
}
return final, nil
//return "", nil //c.shell.Add(f, shell.OnlyHash(true), Recursive(true))
}
type object struct {
Hash string
}
func Recursive(enabled bool) shell.AddOpts {
return func(rb *shell.RequestBuilder) error {
rb.Option("recursive", enabled)
return nil
}
}