/
main.go
619 lines (514 loc) · 13.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//
// main.go --- e3db command line tool.
//
// Copyright (C) 2017, Tozny, LLC.
// All Rights Reserved.
//
package main
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/mail"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/jawher/mow.cli"
"github.com/tozny/e3db-go"
)
type cliOptions struct {
Logging *bool
Profile *string
}
// MaxFileSize is the maximum number of bytes allowed for writefile commands.
const MaxFileSize int64 = 1000000
func dieErr(err error) {
fmt.Fprintf(os.Stderr, "e3db-cli: %s\n", err)
cli.Exit(1)
}
func dieFmt(format string, args ...interface{}) {
fmt.Fprint(os.Stderr, "e3db-cli: ")
fmt.Fprintf(os.Stderr, format, args)
fmt.Fprint(os.Stderr, "\n")
cli.Exit(1)
}
func (o *cliOptions) getClient() *e3db.Client {
var client *e3db.Client
var err error
opts, err := e3db.GetConfig(*o.Profile)
if err != nil {
dieErr(err)
}
if *o.Logging {
opts.Logging = true
}
client, err = e3db.GetClient(*opts)
if err != nil {
dieErr(err)
}
return client
}
func getClientID(client *e3db.Client, maybeEmail string) (string, error) {
_, err := mail.ParseAddress(maybeEmail)
if err != nil {
// If the string isn't an email, it must be an ID. Return it.
return maybeEmail, nil
}
ci, err := client.GetClientInfo(context.Background(), maybeEmail)
if err != nil {
return "", err
}
return ci.ClientID, nil
}
var options cliOptions
func doQuery(client *e3db.Client, useJSON bool, q *e3db.Q) {
cursor := client.Query(context.Background(), *q)
first := true
for {
record, err := cursor.Next()
if err == e3db.Done {
break
} else if err != nil {
dieErr(err)
}
if useJSON {
if first {
first = false
fmt.Println("[")
} else {
fmt.Printf(",\n")
}
buffer := bytes.Buffer{}
encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent(" ", " ")
encoder.Encode(record)
fmt.Printf(" %s", buffer.Bytes())
} else {
fmt.Printf("%-40s %s\n", record.Meta.RecordID, record.Meta.Type)
}
}
if useJSON {
fmt.Println("\n]")
}
}
func cmdRead(cmd *cli.Cmd) {
recordIDs := cmd.Strings(cli.StringsArg{
Name: "RECORD_ID",
Value: nil,
Desc: "record IDs to read",
HideValue: true,
})
cmd.Spec = "RECORD_ID..."
cmd.Action = func() {
client := options.getClient()
doQuery(client, true, &e3db.Q{
RecordIDs: *recordIDs,
IncludeData: true,
IncludeAllWriters: true,
})
}
}
func cmdList(cmd *cli.Cmd) {
data := cmd.BoolOpt("d data", false, "include data in JSON format")
outputJSON := cmd.BoolOpt("j json", false, "output in JSON format")
contentTypes := cmd.StringsOpt("t type", nil, "record content types")
writerIDs := cmd.StringsOpt("w writer", nil, "record writer IDs or email addresses")
userIDs := cmd.StringsOpt("u user", nil, "record user IDs")
var allWritersSpecified bool = false
allWriters := cmd.Bool(cli.BoolOpt{
Name: "a all-writers",
Value: false,
Desc: "include records from all writers (including those shared with you).",
EnvVar: "",
SetByUser: &allWritersSpecified,
})
recordIDs := cmd.Strings(cli.StringsArg{
Name: "RECORD_ID",
Value: nil,
Desc: "record IDs to read",
HideValue: true,
})
cmd.Spec = "[OPTIONS] [RECORD_ID...]"
cmd.Action = func() {
client := options.getClient()
ctx := context.Background()
// We assume user wants records from all writers if no writer IDs
// were given on command line (and they did not specify --all-writers
// explicitly).
var allWritersFlag bool = false
if allWritersSpecified {
allWritersFlag = *allWriters
} else if len(*writerIDs) == 0 {
allWritersFlag = true
}
// Convert e-mail addresses in write list to writer IDs.
for ix, writerID := range *writerIDs {
if strings.Contains(writerID, "@") {
info, err := client.GetClientInfo(ctx, writerID)
if err != nil {
dieErr(err)
}
(*writerIDs)[ix] = info.ClientID
}
}
doQuery(client, *outputJSON, &e3db.Q{
ContentTypes: *contentTypes,
RecordIDs: *recordIDs,
WriterIDs: *writerIDs,
UserIDs: *userIDs,
IncludeData: *data,
IncludeAllWriters: allWritersFlag,
})
}
}
func cmdWrite(cmd *cli.Cmd) {
recordType := cmd.String(cli.StringArg{
Name: "TYPE",
Desc: "type of record to write",
Value: "",
HideValue: true,
})
data := cmd.String(cli.StringArg{
Name: "DATA",
Desc: "json data or @FILENAME",
Value: "",
HideValue: true,
})
cmd.Action = func() {
client := options.getClient()
var recordData string
dataRunes := []rune(*data)
if dataRunes[0] == '@' {
b, err := ioutil.ReadFile(string(dataRunes[1:]))
if err != nil {
dieErr(err)
}
recordData = string(b)
} else {
recordData = *data
}
jsonData := make(map[string]string)
err := json.NewDecoder(strings.NewReader(recordData)).Decode(&jsonData)
if err != nil {
dieErr(err)
}
record, err := client.Write(context.Background(), *recordType, jsonData, nil)
if err != nil {
dieErr(err)
}
fmt.Println(record.Meta.RecordID)
}
}
func cmdWriteFile(cmd *cli.Cmd) {
recordType := cmd.String(cli.StringArg{
Name: "TYPE",
Desc: "type of record to write",
Value: "",
HideValue: true,
})
filename := cmd.String(cli.StringArg{
Name: "FILENAME",
Desc: "path to file to write to e3db",
Value: "",
HideValue: true,
})
cmd.Action = func() {
client := options.getClient()
data := make(map[string]string)
f, err := os.Open(*filename)
if err != nil {
dieErr(err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
dieErr(err)
}
// If the file is larger than 1MB, err
if fi.Size() > MaxFileSize {
dieErr(errors.New("Files must be less than 1MB in size."))
}
// Get the file itself
buf := new(bytes.Buffer)
buf.ReadFrom(f)
data["filename"] = fi.Name()
data["contents"] = base64.RawURLEncoding.EncodeToString(buf.Bytes())
data["size"] = strconv.FormatInt(fi.Size(), 10)
record, err := client.Write(context.Background(), *recordType, data, nil)
if err != nil {
dieErr(err)
}
fmt.Println(record.Meta.RecordID)
}
}
func cmdReadFile(cmd *cli.Cmd) {
recordID := cmd.String(cli.StringArg{
Name: "RECORD_ID",
Desc: "record ID to read",
Value: "",
HideValue: true,
})
cmd.Action = func() {
client := options.getClient()
record, err := client.Read(context.Background(), *recordID)
if err != nil {
dieErr(err)
}
filename := filepath.Base(record.Data["filename"])
f, err := os.Create(filename)
if err != nil {
dieErr(err)
}
defer f.Close()
contents, err := base64.RawURLEncoding.DecodeString(record.Data["contents"])
if err != nil {
dieErr(err)
}
n, err := f.Write(contents)
if err != nil {
dieErr(err)
}
fmt.Printf("Wrote %d bytes to file: %-20s\n", n, filename)
}
}
func cmdDelete(cmd *cli.Cmd) {
recordIDs := cmd.Strings(cli.StringsArg{
Name: "RECORD_ID",
Desc: "record IDs to delete",
Value: nil,
HideValue: true,
})
cmd.Spec = "RECORD_ID..."
cmd.Action = func() {
client := options.getClient()
for _, recordID := range *recordIDs {
err := client.Delete(context.Background(), recordID)
if err != nil {
dieErr(err)
}
}
}
}
func cmdInfo(cmd *cli.Cmd) {
clientID := cmd.String(cli.StringArg{
Name: "CLIENT_ID",
Desc: "client unique id or email",
Value: "",
HideValue: true,
})
cmd.Spec = "[CLIENT_ID]"
cmd.Action = func() {
client := options.getClient()
if *clientID == "" {
fmt.Printf("Client ID: %s\n", client.Options.ClientID)
fmt.Printf("Client Email: %s\n", client.Options.ClientEmail)
fmt.Printf("Public Key: %s\n", base64.RawURLEncoding.EncodeToString(client.Options.PublicKey[:]))
fmt.Printf("API Key ID: %s\n", client.Options.APIKeyID)
fmt.Printf("API Secret: %s\n", client.Options.APISecret)
} else {
info, err := client.GetClientInfo(context.Background(), *clientID)
if err != nil {
dieErr(err)
}
fmt.Printf("Client ID: %s\n", info.ClientID)
fmt.Printf("Public Key: %s\n", info.PublicKey.Curve25519)
}
}
}
func cmdShare(cmd *cli.Cmd) {
recordType := cmd.String(cli.StringArg{
Name: "TYPE",
Desc: "type of records to share",
Value: "",
HideValue: true,
})
clientID := cmd.String(cli.StringArg{
Name: "CLIENT_ID",
Desc: "client unique id or email",
Value: "",
HideValue: true,
})
cmd.Action = func() {
client := options.getClient()
realClientID, e := getClientID(client, *clientID)
if e != nil {
dieErr(e)
}
err := client.Share(context.Background(), *recordType, realClientID)
if err != nil {
dieErr(err)
}
fmt.Printf("Records of type '%s' are now shared with client '%s'\n", *recordType, *clientID)
}
}
func cmdUnshare(cmd *cli.Cmd) {
recordType := cmd.String(cli.StringArg{
Name: "TYPE",
Desc: "type of records to share",
Value: "",
HideValue: true,
})
clientID := cmd.String(cli.StringArg{
Name: "CLIENT_ID",
Desc: "client unique id or email",
Value: "",
HideValue: true,
})
cmd.Action = func() {
client := options.getClient()
realClientID, e := getClientID(client, *clientID)
if e != nil {
dieErr(e)
}
err := client.Unshare(context.Background(), *recordType, realClientID)
if err != nil {
dieErr(err)
}
fmt.Printf("Records of type '%s' are no longer shared with client '%s'\n", *recordType, *clientID)
}
}
func cmdSubscribe(cmd *cli.Cmd) {
app := cmd.String(cli.StringArg{
Name: "APP",
Desc: "application name",
Value: "e3db",
HideValue: true,
})
eventType := cmd.String(cli.StringArg{
Name: "TYPE",
Desc: "channel type",
Value: "",
HideValue: true,
})
clientID := cmd.String(cli.StringArg{
Name: "CLIENT_ID",
Desc: "client unique id or email",
Value: "",
HideValue: true,
})
cmd.Spec = "APP [TYPE] [CLIENT_ID]"
cmd.Action = func() {
client := options.getClient()
if *clientID == "" {
*clientID = client.Options.ClientID
}
if *eventType == "" {
*eventType = "producer"
}
channel := e3db.Channel{
Application: *app,
Type: *eventType,
Subject: *clientID,
}
source, err := client.NewEventSource(context.Background())
if err != nil {
dieErr(err)
}
defer source.Close()
source.Subscribe(channel)
go func() {
for event := range source.Events() {
b, _ := json.MarshalIndent(event, " ", " ")
log.Println(string(b))
}
}()
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
}
func cmdFeedback(cmd *cli.Cmd) {
cmd.Action = func() {
client := options.getClient()
// Get input from the user
reader := bufio.NewReader(os.Stdin)
fmt.Print("What's your impression so far?\n")
text, _ := reader.ReadString('\n')
toznyClientID, e := getClientID(client, "ijones+feedback@tozny.com")
if e != nil {
dieErr(errors.New("Feedback address not registered."))
}
// Write feedback to the database
data := make(map[string]string)
data["comment"] = text
id, err := client.Write(context.Background(), "feedback", data, nil)
if err != nil {
dieErr(err)
}
// Share with Tozny
shareErr := client.Share(context.Background(), "feedback", toznyClientID)
if shareErr != nil {
dieErr(err)
}
// Done!
fmt.Printf("Your record ID: %s\n", id)
}
}
func cmdPolicyOutgoing(cmd *cli.Cmd) {
cmd.Action = func() {
client := options.getClient()
osps, err := client.GetOutgoingSharing(context.Background())
if err != nil {
dieErr(err)
}
for _, osp := range osps {
var displayName *string
if osp.ReaderName != "" {
displayName = &osp.ReaderName
} else {
displayName = &osp.ReaderID
}
fmt.Printf("%-40s %s\n", *displayName, osp.Type)
}
}
}
func cmdPolicyIncoming(cmd *cli.Cmd) {
cmd.Action = func() {
client := options.getClient()
isps, err := client.GetIncomingSharing(context.Background())
if err != nil {
dieErr(err)
}
for _, isp := range isps {
var displayName *string
if isp.WriterName != "" {
displayName = &isp.WriterName
} else {
displayName = &isp.WriterID
}
fmt.Printf("%-40s %s\n", *displayName, isp.Type)
}
}
}
func main() {
app := cli.App("e3db-cli", "E3DB Command Line Interface")
app.Version("v version", "e3db-cli 2.0.0")
options.Logging = app.BoolOpt("d debug", false, "enable debug logging")
options.Profile = app.StringOpt("p profile", "", "e3db configuration profile")
app.Command("info", "get client information", cmdInfo)
app.Command("ls", "list records", cmdList)
app.Command("write", "write a record", cmdWrite)
app.Command("read", "read records by ID", cmdRead)
app.Command("delete", "delete a record", cmdDelete)
app.Command("share", "share records with another client", cmdShare)
app.Command("unshare", "stop sharing records with another client", cmdUnshare)
app.Command("policy", "operations on sharing policy", func(cmd *cli.Cmd) {
cmd.Command("incoming", "list incoming sharing policy (who shares with me?)", cmdPolicyIncoming)
cmd.Command("outgoing", "list outgoing sharing policy (who have I shared with?)", cmdPolicyOutgoing)
})
app.Command("subscribe", "subscribe to a stream of events produced by a client", cmdSubscribe)
app.Command("feedback", "provde e3db feedback to Tozny", cmdFeedback)
app.Command("file", "work with small files", func(cmd *cli.Cmd) {
cmd.Command("read", "read a small file", cmdReadFile)
cmd.Command("write", "write a small file", cmdWriteFile)
})
app.Run(os.Args)
}