/
main.go
107 lines (91 loc) · 2.5 KB
/
main.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
106
107
package tortugasync
import (
"bytes"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
type Bay struct {
*sftp.Client
}
func Connect(url string, key, hostKey []byte) (Bay, error) {
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return Bay{}, fmt.Errorf("Connect: ssh.ParsePrivateKey: %w", err)
}
clientCfg := &ssh.ClientConfig{
User: "tortuga",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
Timeout: 5 * time.Second,
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
if !bytes.Equal(key.Marshal(), hostKey) {
return errors.New("HostKeyCallback: invalid host key")
}
return nil
},
}
// Connect to the remote server.
conn, err := ssh.Dial("tcp", url, clientCfg)
if err != nil {
return Bay{}, fmt.Errorf("Connect: ssh.Dial: %w", err)
}
// Open an SFTP session over the SSH connection.
client, err := sftp.NewClient(conn)
if err != nil {
return Bay{}, fmt.Errorf("Connect: %w", err)
}
return Bay{Client: client}, nil
}
// Metadata returns a map of MD5 hashes as keys and file paths as values read from the server.
func (b Bay) Metadata(path string) (Cache, error) {
meta, err := b.Open(path)
if err != nil {
return nil, fmt.Errorf("b.metadata: b.Open: %w", err)
}
defer meta.Close()
ret := make(Cache)
cnt, err := io.ReadAll(meta)
if err != nil {
return nil, fmt.Errorf("b.metadata: io.ReadAll: %w", err)
}
if err := json.Unmarshal(cnt, &ret); err != nil {
return nil, fmt.Errorf("b.metadata: json.Unmarshal: %w", err)
}
return ret, nil
}
// Fetch downloads a book from tortuga@{remote}:{remotePath} to localPath and
// returns its just calculated MD5SUM and an error if any.
func (b Bay) Fetch(localPath, remotePath string) ([]byte, error) {
rbook, err := b.Open(remotePath)
if err != nil {
return nil, fmt.Errorf("b.fetch: b.Open: %w", err)
}
defer rbook.Close()
// lpath := filepath.Join(koboHome, filepath.Base(path))
lbook, err := os.Create(localPath)
if err != nil {
return nil, fmt.Errorf("b.fetch: os.Create: %w", err)
}
defer lbook.Close()
// Write the book locally.
if _, err := io.Copy(lbook, rbook); err != nil {
return nil, fmt.Errorf("b.fetch: io.Copy: %w", err)
}
lbook.Seek(0, 0)
// Calculate MD5 of the downloaded book.
hash := md5.New()
if _, err := io.Copy(hash, lbook); err != nil {
return nil, fmt.Errorf("b.fetch: io.Copy: %w", err)
}
// b.cache[hex.EncodeToString(hash.Sum(nil))] = localPath
return hash.Sum(nil), nil
}