forked from textileio/go-textile
/
textile.go
656 lines (616 loc) · 16.1 KB
/
textile.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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package main
import (
"errors"
"fmt"
"github.com/fatih/color"
"github.com/jessevdk/go-flags"
"github.com/mitchellh/go-homedir"
"github.com/op/go-logging"
"github.com/textileio/textile-go/cafe"
"github.com/textileio/textile-go/cafe/dao"
"github.com/textileio/textile-go/cmd"
"github.com/textileio/textile-go/core"
rconfig "github.com/textileio/textile-go/repo/config"
"github.com/textileio/textile-go/wallet"
"gopkg.in/abiosoft/ishell.v2"
icore "gx/ipfs/Qmb8jW1F6ZVyYPW1epc2GFRipmd3S8tJ48pZKBVPzVqj9T/go-ipfs/core"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
)
type Opts struct {
Version bool `short:"v" long:"version" description:"print the version number and exit"`
// repo location
RepoPath string `short:"r" long:"repo-dir" description:"specify a custom repository path"`
// logging options
LogLevel string `short:"l" long:"log-level" description:"set the logging level [debug, info, notice, warning, error, critical]" default:"debug"`
NoLogFiles bool `short:"n" long:"no-log-files" description:"do not save logs on disk"`
// modes
DaemonMode bool `short:"d" long:"daemon" description:"start in a non-interactive daemon mode"`
ServerMode bool `short:"s" long:"server" description:"start in server mode"`
// gateway settings
GatewayBindAddr string `short:"g" long:"gateway-bind-addr" description:"set the gateway address" default:"127.0.0.1:random"`
// swarm settings
SwarmPorts string `long:"swarm-ports" description:"set the swarm ports (tcp,ws)" default:"random"`
// cafe client settings
CafeAddr string `short:"c" long:"cafe" description:"cafe host address"`
// cafe host settings
CafeBindAddr string `long:"cafe-bind-addr" description:"set the cafe address"`
CafeDBHosts string `long:"cafe-db-hosts" description:"set the cafe mongo db hosts uri"`
CafeDBName string `long:"cafe-db-name" description:"set the cafe mongo db name"`
CafeDBUser string `long:"cafe-db-user" description:"set the cafe mongo db user"`
CafeDBPassword string `long:"cafe-db-password" description:"set the cafe mongo db user password"`
CafeDBTLS bool `long:"cafe-db-tls" description:"use TLS for the cafe mongo db connection"`
CafeTokenSecret string `long:"cafe-token-secret" description:"set the cafe token secret"`
CafeReferralKey string `long:"cafe-referral-key" description:"set the cafe referral key"`
}
var Options Opts
var parser = flags.NewParser(&Options, flags.Default)
var shell *ishell.Shell
func main() {
// parse flags
if _, err := parser.Parse(); err != nil {
return
}
// handle version flag
if Options.Version {
fmt.Println(core.Version)
return
}
// handle repo path
repoPath := Options.RepoPath
if len(Options.RepoPath) == 0 {
// get homedir
home, err := homedir.Dir()
if err != nil {
fmt.Println(fmt.Errorf("get homedir failed: %s", err.Error()))
return
}
// ensure app folder is created
appDir := filepath.Join(home, ".textile")
if err := os.MkdirAll(appDir, 0755); err != nil {
fmt.Println(fmt.Errorf("create repo directory failed: %s", err.Error()))
return
}
repoPath = filepath.Join(appDir, "repo")
}
// determine log level
level, err := logging.LogLevel(strings.ToUpper(Options.LogLevel))
if err != nil {
fmt.Println(fmt.Errorf("determine log level failed: %s", err))
return
}
// node setup
config := core.NodeConfig{
WalletConfig: wallet.Config{
RepoPath: repoPath,
SwarmPorts: Options.SwarmPorts,
IsMobile: false,
IsServer: Options.ServerMode,
CafeAddr: Options.CafeAddr,
},
LogLevel: level,
LogFiles: !Options.NoLogFiles,
}
// create a desktop node
node, _, err := core.NewNode(config)
if err != nil {
fmt.Println(fmt.Errorf("create desktop node failed: %s", err))
return
}
core.Node = node
// check cafe mode
if Options.CafeBindAddr != "" {
cafe.Host = &cafe.Cafe{
Ipfs: func() *icore.IpfsNode {
return core.Node.Wallet.Ipfs()
},
Dao: &dao.DAO{
Hosts: Options.CafeDBHosts,
Name: Options.CafeDBName,
User: Options.CafeDBUser,
Password: Options.CafeDBPassword,
TLS: Options.CafeDBTLS,
},
TokenSecret: Options.CafeTokenSecret,
ReferralKey: Options.CafeReferralKey,
NodeVersion: core.Version,
}
}
// auto start it
if err := start(); err != nil {
fmt.Println(fmt.Errorf("start desktop node failed: %s", err))
}
// welcome
printSplashScreen()
// run it
if Options.DaemonMode {
// handle interrupt
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
fmt.Println("interrupted")
fmt.Printf("shutting down...")
if err := stop(); err != nil && err != wallet.ErrStopped {
fmt.Println(err.Error())
} else {
fmt.Print("done\n")
}
os.Exit(1)
} else {
// create a new shell
shell = ishell.New()
shell.SetHomeHistoryPath(".ishell_history")
// handle interrupt
shell.Interrupt(func(c *ishell.Context, count int, input string) {
if count == 1 {
shell.Println("input Ctrl-C once more to exit")
return
}
shell.Println("interrupted")
shell.Printf("shutting down...")
if err := stop(); err != nil && err != wallet.ErrStopped {
c.Err(err)
} else {
shell.Printf("done\n")
}
os.Exit(1)
})
// add commands
shell.AddCmd(&ishell.Cmd{
Name: "start",
Help: "start the node",
Func: func(c *ishell.Context) {
if core.Node.Wallet.Started() {
c.Println("already started")
return
}
if err := start(); err != nil {
c.Println(fmt.Errorf("start desktop node failed: %s", err))
return
}
c.Println("ok, started")
},
})
shell.AddCmd(&ishell.Cmd{
Name: "stop",
Help: "stop the node",
Func: func(c *ishell.Context) {
if !core.Node.Wallet.Started() {
c.Println("already stopped")
return
}
if err := stop(); err != nil {
c.Println(fmt.Errorf("stop desktop node failed: %s", err))
return
}
c.Println("ok, stopped")
},
})
shell.AddCmd(&ishell.Cmd{
Name: "id",
Help: "show node id",
Func: cmd.ShowId,
})
shell.AddCmd(&ishell.Cmd{
Name: "ping",
Help: "ping another peer",
Func: func(c *ishell.Context) {
if !core.Node.Wallet.IsOnline() {
c.Println("not online yet")
return
}
if len(c.Args) == 0 {
c.Err(errors.New("missing peer id"))
return
}
status, err := core.Node.Wallet.GetPeerStatus(c.Args[0])
if err != nil {
c.Println(fmt.Errorf("ping failed: %s", err))
return
}
c.Println(status)
},
})
shell.AddCmd(&ishell.Cmd{
Name: "fetch-messages",
Help: "fetch offline messages from the DHT",
Func: func(c *ishell.Context) {
if !core.Node.Wallet.IsOnline() {
c.Println("not online yet")
return
}
if err := core.Node.Wallet.FetchMessages(); err != nil {
c.Println(fmt.Errorf("fetch messages failed: %s", err))
return
}
c.Println("ok, fetching")
},
})
{
cafeCmd := &ishell.Cmd{
Name: "cafe",
Help: "manage cafe session",
LongHelp: "Mange your cafe user session.",
}
cafeCmd.AddCmd(&ishell.Cmd{
Name: "add-referral",
Help: "add cafe referrals",
Func: cmd.CafeReferral,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "referrals",
Help: "list cafe referrals",
Func: cmd.ListCafeReferrals,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "register",
Help: "cafe register",
Func: cmd.CafeRegister,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "login",
Help: "cafe login",
Func: cmd.CafeLogin,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "status",
Help: "cafe status",
Func: cmd.CafeStatus,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "tokens",
Help: "cafe tokens",
Func: cmd.CafeTokens,
})
cafeCmd.AddCmd(&ishell.Cmd{
Name: "logout",
Help: "cafe logout",
Func: cmd.CafeLogout,
})
shell.AddCmd(cafeCmd)
}
{
profileCmd := &ishell.Cmd{
Name: "profile",
Help: "manage cafe profiles",
LongHelp: "Resolve other profiles, get and publish local profile.",
}
profileCmd.AddCmd(&ishell.Cmd{
Name: "publish",
Help: "publish local profile",
Func: cmd.PublishProfile,
})
profileCmd.AddCmd(&ishell.Cmd{
Name: "resolve",
Help: "resolve profiles",
Func: cmd.ResolveProfile,
})
profileCmd.AddCmd(&ishell.Cmd{
Name: "get",
Help: "get peer profiles",
Func: cmd.GetProfile,
})
profileCmd.AddCmd(&ishell.Cmd{
Name: "set-avatar",
Help: "set local profile avatar",
Func: cmd.SetAvatarId,
})
shell.AddCmd(profileCmd)
}
{
swarmCmd := &ishell.Cmd{
Name: "swarm",
Help: "same as ipfs swarm",
LongHelp: "Inspect IPFS swarm peers.",
}
swarmCmd.AddCmd(&ishell.Cmd{
Name: "peers",
Help: "show connected peers (same as `ipfs swarm peers`)",
Func: cmd.SwarmPeers,
})
swarmCmd.AddCmd(&ishell.Cmd{
Name: "ping",
Help: "ping a peer (same as `ipfs ping`)",
Func: cmd.SwarmPing,
})
swarmCmd.AddCmd(&ishell.Cmd{
Name: "connect",
Help: "connect to a peer (same as `ipfs swarm connect`)",
Func: cmd.SwarmConnect,
})
shell.AddCmd(swarmCmd)
}
{
photoCmd := &ishell.Cmd{
Name: "photo",
Help: "manage photos",
LongHelp: "Add, list, and get info about photos.",
}
photoCmd.AddCmd(&ishell.Cmd{
Name: "add",
Help: "add a new photo",
Func: cmd.AddPhoto,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "share",
Help: "share a photo to a different thread",
Func: cmd.SharePhoto,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "get",
Help: "save a photo to a local file",
Func: cmd.GetPhoto,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "key",
Help: "decrypt and print the key for a photo",
Func: cmd.GetPhotoKey,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "meta",
Help: "get photo metadata",
Func: cmd.GetPhotoMetadata,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "ls",
Help: "list photos from a thread",
Func: cmd.ListPhotos,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "comment",
Help: "comment on a photo (terminate input w/ ';'",
Func: cmd.AddPhotoComment,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "like",
Help: "like a photo",
Func: cmd.AddPhotoLike,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "comments",
Help: "list photo comments",
Func: cmd.ListPhotoComments,
})
photoCmd.AddCmd(&ishell.Cmd{
Name: "likes",
Help: "list photo likes",
Func: cmd.ListPhotoLikes,
})
shell.AddCmd(photoCmd)
}
{
threadCmd := &ishell.Cmd{
Name: "thread",
Help: "manage threads",
LongHelp: "Add, remove, list, invite to, and get info about textile threads.",
}
threadCmd.AddCmd(&ishell.Cmd{
Name: "add",
Help: "add a new thread",
Func: cmd.AddThread,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "rm",
Help: "remove a thread by name",
Func: cmd.RemoveThread,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "ls",
Help: "list threads",
Func: cmd.ListThreads,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "blocks",
Help: "list blocks",
Func: cmd.ListThreadBlocks,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "head",
Help: "show current HEAD",
Func: cmd.GetThreadHead,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "ignore",
Help: "ignore a block",
Func: cmd.IgnoreBlock,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "peers",
Help: "list peers",
Func: cmd.ListThreadPeers,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "invite",
Help: "invite a peer to a thread",
Func: cmd.AddThreadInvite,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "accept",
Help: "accept a thread invite",
Func: cmd.AcceptThreadInvite,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "invite-external",
Help: "create an external invite link",
Func: cmd.AddExternalThreadInvite,
})
threadCmd.AddCmd(&ishell.Cmd{
Name: "accept-external",
Help: "accept an external thread invite",
Func: cmd.AcceptExternalThreadInvite,
})
shell.AddCmd(threadCmd)
}
{
deviceCmd := &ishell.Cmd{
Name: "device",
Help: "manage connected devices",
LongHelp: "Add, remove, and list connected devices.",
}
deviceCmd.AddCmd(&ishell.Cmd{
Name: "add",
Help: "add a new device",
Func: cmd.AddDevice,
})
deviceCmd.AddCmd(&ishell.Cmd{
Name: "rm",
Help: "remove a device by name",
Func: cmd.RemoveDevice,
})
deviceCmd.AddCmd(&ishell.Cmd{
Name: "ls",
Help: "list devices",
Func: cmd.ListDevices,
})
shell.AddCmd(deviceCmd)
}
{
notificationCmd := &ishell.Cmd{
Name: "notification",
Help: "manage notifications",
LongHelp: "List and read notifications.",
}
notificationCmd.AddCmd(&ishell.Cmd{
Name: "read",
Help: "mark a notification as read",
Func: cmd.ReadNotification,
})
notificationCmd.AddCmd(&ishell.Cmd{
Name: "readall",
Help: "mark all notifications as read",
Func: cmd.ReadAllNotifications,
})
notificationCmd.AddCmd(&ishell.Cmd{
Name: "ls",
Help: "list notifications",
Func: cmd.ListNotifications,
})
notificationCmd.AddCmd(&ishell.Cmd{
Name: "accept",
Help: "accept an invite via notification",
Func: cmd.AcceptThreadInviteViaNotification,
})
shell.AddCmd(notificationCmd)
}
shell.Run()
}
}
func start() error {
if err := core.Node.StartWallet(); err != nil {
return err
}
<-core.Node.Wallet.Online()
// subscribe to wallet updates
go func() {
for {
select {
case update, ok := <-core.Node.Wallet.Updates():
if !ok {
return
}
switch update.Type {
case wallet.ThreadAdded:
break
case wallet.ThreadRemoved:
break
case wallet.DeviceAdded:
break
case wallet.DeviceRemoved:
break
}
}
}
}()
// subscribe to thread updates
go func() {
green := color.New(color.FgHiGreen).SprintFunc()
for {
select {
case update, ok := <-core.Node.Wallet.ThreadUpdates():
if !ok {
return
}
msg := fmt.Sprintf("new %s block in thread '%s'", update.Block.Type.Description(), update.ThreadName)
fmt.Println(green(msg))
}
}
}()
// subscribe to notifications
go func() {
yellow := color.New(color.FgHiYellow).SprintFunc()
for {
select {
case notification, ok := <-core.Node.Wallet.Notifications():
if !ok {
return
}
var username string
if notification.ActorUsername != "" {
username = notification.ActorUsername
} else {
username = notification.ActorId
}
note := fmt.Sprintf("#%s: %s %s.", notification.Subject, username, notification.Body)
fmt.Println(yellow(note))
}
}
}()
// start the gateway
core.Node.StartGateway(resolveAddress(Options.GatewayBindAddr))
// start cafe server
if Options.CafeBindAddr != "" {
cafe.Host.Start(resolveAddress(Options.CafeBindAddr))
}
return nil
}
func stop() error {
if err := core.Node.StopGateway(); err != nil {
return err
}
if Options.CafeBindAddr != "" {
if err := cafe.Host.Stop(); err != nil {
return err
}
}
return core.Node.StopWallet()
}
func printSplashScreen() {
cyan := color.New(color.FgCyan).SprintFunc()
green := color.New(color.FgHiGreen).SprintFunc()
yellow := color.New(color.FgHiYellow).SprintFunc()
blue := color.New(color.FgHiBlue).SprintFunc()
grey := color.New(color.FgHiBlack).SprintFunc()
fmt.Println(cyan("Textile"))
fmt.Println(grey("version: ") + blue(core.Version))
fmt.Println(grey("repo: ") + blue(core.Node.Wallet.GetRepoPath()))
fmt.Println(grey("gateway: ") + yellow(core.Node.GetGatewayAddr()))
if Options.CafeBindAddr != "" {
fmt.Println(grey("cafe: ") + yellow(Options.CafeBindAddr))
}
if Options.CafeAddr != "" {
fmt.Println(grey("cafe api: ") + yellow(core.Node.Wallet.GetCafeApiAddr()))
}
if Options.ServerMode {
fmt.Println(grey("server mode: ") + green("enabled"))
}
if Options.DaemonMode {
fmt.Println(grey("daemon mode: ") + green("enabled"))
} else {
fmt.Println(grey("type 'help' for available commands"))
}
}
func resolveAddress(addr string) string {
parts := strings.Split(addr, ":")
if len(parts) != 2 {
log.Fatalf("invalid address: %s", addr)
}
port := parts[1]
if port == "random" {
port = strconv.Itoa(rconfig.GetRandomPort())
}
return fmt.Sprintf("%s:%s", parts[0], port)
}