-
Notifications
You must be signed in to change notification settings - Fork 14
/
documents.go
97 lines (80 loc) · 2.09 KB
/
documents.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
package main
import (
"context"
"fmt"
"os"
cli "github.com/jawher/mow.cli"
"github.com/monax/hoard/v6"
"github.com/monax/hoard/v6/grant"
"github.com/monax/hoard/v6/meta"
"github.com/h2non/filetype"
)
// Upload a document with metadata to hoard
func (client *Client) Upload(cmd *cli.Cmd) {
chunk := addIntOpt(cmd, "chunk", chunkOpt, chunkSize)
file := addStringOpt(cmd, "file", fileOpt)
salt := addStringOpt(cmd, "salt", saltOpt)
cmd.Action = func() {
validateChunkSize(*chunk)
file, err := openFile(file)
if err != nil {
fatalf("Error reading file: %v", err)
}
data := readData(file)
kind, err := filetype.Match(data)
if err != nil {
fatalf("Error inspecting file: %v", err)
}
upload, err := client.documents.Upload(context.Background())
if err != nil {
fatalf("Error starting client: %v", err)
}
spec := &grant.Spec{Plaintext: &grant.PlaintextSpec{}}
err = hoard.SendDocumentAndGrant(upload, &meta.Document{
Meta: &meta.Meta{
Name: file.Name(),
MimeType: kind.MIME.Type,
},
Data: data,
}, parseSalt(salt), spec, *chunk)
if err != nil {
fatalf("Error sending data: %v", err)
}
grant, err := upload.CloseAndRecv()
if err != nil {
fatalf("Error closing client: %v", err)
}
fmt.Printf("%s\n", jsonString(grant))
}
}
// Download a document and print the metadata or body
func (client *Client) Download(cmd *cli.Cmd) {
cmd.Command("head", "get metadata", func(cmd *cli.Cmd) {
cmd.Action = func() {
doc := client.getFile()
fmt.Printf("%s\n", jsonString(doc.Meta))
}
})
cmd.Command("body", "get data", func(cmd *cli.Cmd) {
cmd.Action = func() {
doc := client.getFile()
os.Stdout.Write(doc.Data)
}
})
}
func (client *Client) getFile() *meta.Document {
grt := readGrant()
download, err := client.documents.Download(context.Background(), grt)
if err != nil {
fatalf("Error starting client: %v", err)
}
doc, _, err := hoard.ReceiveDocument(download)
if err != nil {
fatalf("Error sending data: %v", err)
}
err = download.CloseSend()
if err != nil {
fatalf("Error closing client: %v", err)
}
return doc
}