-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsushitrain.go
1300 lines (1102 loc) · 34.3 KB
/
sushitrain.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2024 Tommy van der Vorst
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package sushitrain
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path"
"slices"
"strings"
"sync"
"time"
"github.com/syncthing/syncthing/lib/build"
"github.com/syncthing/syncthing/lib/config"
"github.com/syncthing/syncthing/lib/db/backend"
"github.com/syncthing/syncthing/lib/events"
"github.com/syncthing/syncthing/lib/locations"
"github.com/syncthing/syncthing/lib/logger"
"github.com/syncthing/syncthing/lib/model"
"github.com/syncthing/syncthing/lib/osutil"
"github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/svcutil"
"github.com/syncthing/syncthing/lib/syncthing"
)
type Client struct {
app *syncthing.App
backend backend.Backend
cancel context.CancelFunc
cert tls.Certificate
config config.Wrapper
ctx context.Context
Delegate ClientDelegate
evLogger events.Logger
filesPath string
IgnoreEvents bool
IsUsingCustomConfiguration bool
Server *StreamingServer
connectedDeviceAddresses map[string]string
downloadProgress map[string]map[string]*model.PullerProgress // folderID, path => progress
uploadProgress map[string]map[string]map[string]int // deviceID, folderID, path => block count
foldersDownloading map[string]bool
ResolvedListenAddresses map[string][]string
mutex sync.Mutex
extraneousIgnored []string
}
type Change struct {
FolderID string
Path string
Action string
ShortID string
Time *Date
}
type ClientDelegate interface {
OnEvent(event string)
OnDeviceDiscovered(deviceID string, addresses *ListOfStrings)
OnListenAddressesChanged(addresses *ListOfStrings)
OnChange(change *Change)
}
var (
ErrStillLoading = errors.New("still loading")
)
const (
ConfigFileName = "config.xml"
ExportConfigFileName = "exported-config.xml"
CertFileName = "cert.pem"
KeyFileName = "key.pem"
bookmarkFileName = "sushitrain-bookmark.dat"
)
func NewClient(configPath string, filesPath string, saveLog bool) (*Client, error) {
// Set version info
build.Version = "v1.29.2"
build.Host = "t-shaped.nl"
build.User = "sushitrain"
// Log to file
if saveLog {
logFilePath := path.Join(filesPath, fmt.Sprintf("%s.log", time.Now().UTC().Format("synctrain-2006-2-1-15-04-05")))
logFile, err := os.Create(logFilePath)
if err != nil {
fmt.Println(err)
}
writer := bufio.NewWriter(logFile)
logger.DefaultLogger.AddHandler(logger.LevelVerbose, func(l logger.LogLevel, msg string) {
timeStamp := time.Now().UTC().Format("2006-02-01 15:04:05")
var level string
switch l {
case logger.LevelDebug:
level = "DEBUG"
case logger.LevelInfo:
level = "INFO"
case logger.LevelWarn:
level = "WARN"
case logger.LevelVerbose:
level = "VERBO"
default:
level = "OTHER"
}
_, err := writer.WriteString(fmt.Sprintf("%s\t%s: %s\n", level, timeStamp, msg))
if err != nil {
return
}
err = writer.Flush()
if err != nil {
return
}
})
}
// Some early chores
osutil.MaximizeOpenFileLimit()
// Set up logging and context for cancellation
ctx, cancel := context.WithCancel(context.Background())
evLogger := events.NewLogger()
go evLogger.Serve(ctx)
// Set up default locations
locations.SetBaseDir(locations.DataBaseDir, configPath)
locations.SetBaseDir(locations.ConfigBaseDir, configPath)
locations.SetBaseDir(locations.UserHomeBaseDir, filesPath)
Logger.Infof("Database dir: %s\n", configPath)
Logger.Infof("Files dir: %s\n", filesPath)
// Check for custom user-provided config file
isUsingCustomConfiguration := false
customConfigFilePath := path.Join(filesPath, ConfigFileName)
if info, err := os.Stat(customConfigFilePath); err == nil {
if !info.IsDir() {
Logger.Infoln("Config XML exists in files dir, using it at", customConfigFilePath)
locations.Set(locations.ConfigFile, customConfigFilePath)
isUsingCustomConfiguration = true
}
}
// Check for custom user-provided identity
customCertPath := path.Join(filesPath, CertFileName)
customKeyPath := path.Join(filesPath, KeyFileName)
if keyInfo, err := os.Stat(customKeyPath); err == nil {
if !keyInfo.IsDir() {
if certInfo, err := os.Stat(customCertPath); err == nil {
if !certInfo.IsDir() {
Logger.Infoln("Found user-provided identity files, using those")
locations.Set(locations.CertFile, customCertPath)
locations.Set(locations.KeyFile, customKeyPath)
isUsingCustomConfiguration = true
}
}
}
}
// Print final locations
Logger.Infof("Config file: %s\n", locations.Get(locations.ConfigFile))
Logger.Infof("Cert file: %s key file: %s\n", locations.Get(locations.CertFile), locations.Get(locations.KeyFile))
// Ensure that we have a certificate and key.
cert, err := syncthing.LoadOrGenerateCertificate(
locations.Get(locations.CertFile),
locations.Get(locations.KeyFile),
)
if err != nil {
cancel()
return nil, err
}
// Load or create the config
devID := protocol.NewDeviceID(cert.Certificate[0])
Logger.Infof("Loading config file from %s\n", locations.Get(locations.ConfigFile))
config, err := loadOrDefaultConfig(devID, ctx, evLogger, filesPath)
if err != nil {
cancel()
return nil, err
}
// Load database
dbFile := locations.Get(locations.Database)
ldb, err := syncthing.OpenDBBackend(dbFile, config.Options().DatabaseTuning)
if err != nil {
cancel()
return nil, err
}
appOpts := syncthing.Options{
NoUpgrade: false,
ProfilerAddr: "",
ResetDeltaIdxs: false,
Verbose: false,
DBRecheckInterval: 0,
DBIndirectGCInterval: 0,
}
app, err := syncthing.New(config, ldb, evLogger, cert, appOpts)
if err != nil {
cancel()
return nil, err
}
server, err := NewServer(app, ctx)
if err != nil {
cancel()
return nil, err
}
return &Client{
Delegate: nil,
cert: cert,
config: config,
cancel: cancel,
ctx: ctx,
backend: ldb,
app: app,
evLogger: evLogger,
Server: server,
foldersDownloading: make(map[string]bool, 0),
connectedDeviceAddresses: make(map[string]string, 0),
IsUsingCustomConfiguration: isUsingCustomConfiguration,
filesPath: filesPath,
IgnoreEvents: false,
uploadProgress: make(map[string]map[string]map[string]int),
ResolvedListenAddresses: make(map[string][]string),
extraneousIgnored: make([]string, 0),
}, nil
}
func (clt *Client) SetExtraneousIgnored(names []string) {
clt.extraneousIgnored = names
}
func (clt *Client) SetExtraneousIgnoredJSON(js []byte) error {
var names []string
if err := json.Unmarshal(js, &names); err != nil {
return err
}
clt.SetExtraneousIgnored(names)
return nil
}
func (clt *Client) isExtraneousIgnored(name string) bool {
// Always ignore files that are prefixed with .syncthing. or ~syncthing~, these are considered 'Syncthing private'
// See https://docs.syncthing.net/users/syncing.html#temporary-files
if strings.HasPrefix(name, ".syncthing.") || strings.HasPrefix(name, "~syncthing~") {
return true
}
// Must be an equal match for now
return slices.Contains(clt.extraneousIgnored, name)
}
func (clt *Client) CurrentConfigDirectory() string {
return locations.GetBaseDir(locations.ConfigBaseDir)
}
func (clt *Client) ExportConfigurationFile() error {
cfg := clt.config.RawCopy()
homeDir := locations.GetBaseDir(locations.UserHomeBaseDir)
customConfigFilePath := path.Join(homeDir, ExportConfigFileName)
fd, err := osutil.CreateAtomic(customConfigFilePath)
if err != nil {
return err
}
if err := cfg.WriteXML(osutil.LineEndingsWriter(fd)); err != nil {
fd.Close()
return err
}
if err := fd.Close(); err != nil {
return err
}
return nil
}
func (clt *Client) Stop() {
clt.app.Stop(svcutil.ExitSuccess)
clt.cancel()
clt.app.Wait()
}
func (clt *Client) handleEvent(evt events.Event) {
clt.mutex.Lock()
defer clt.mutex.Unlock()
switch evt.Type {
case events.DeviceDiscovered:
if !clt.IgnoreEvents && clt.Delegate != nil {
data := evt.Data.(map[string]interface{})
devID := data["device"].(string)
addresses := data["addrs"].([]string)
clt.Delegate.OnDeviceDiscovered(devID, &ListOfStrings{data: addresses})
}
case events.FolderRejected:
// FolderRejected is deprecated
break
case events.StateChanged:
// Keep track of which folders are in syncing state. We need to know whether we are idling or not
data := evt.Data.(map[string]interface{})
folder := data["folder"].(string)
state := data["to"].(string)
folderTransferring := (state == model.FolderSyncing.String() || state == model.FolderSyncWaiting.String() || state == model.FolderSyncPreparing.String())
clt.foldersDownloading[folder] = folderTransferring
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnEvent(evt.Type.String())
}
case events.ListenAddressesChanged:
if !clt.IgnoreEvents && clt.Delegate != nil {
addrs := make([]string, 0)
data := evt.Data.(map[string]interface{})
addressSpec := data["address"].(*url.URL)
wanAddresses := data["wan"].([]*url.URL)
lanAddresses := data["lan"].([]*url.URL)
for _, wa := range wanAddresses {
addrs = append(addrs, wa.String())
}
for _, la := range lanAddresses {
addrs = append(addrs, la.String())
}
clt.ResolvedListenAddresses[addressSpec.String()] = addrs
// Get all current addresses and send to client
currentResolved := make([]string, 0)
for _, addrs := range clt.ResolvedListenAddresses {
currentResolved = append(currentResolved, addrs...)
}
clt.Delegate.OnListenAddressesChanged(List(currentResolved))
}
case events.DeviceConnected:
data := evt.Data.(map[string]string)
devID := data["id"]
address := data["addr"]
clt.connectedDeviceAddresses[devID] = address
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnEvent(evt.Type.String())
}
case events.LocalChangeDetected, events.RemoteChangeDetected:
data := evt.Data.(map[string]string)
modifiedBy, ok := data["modifiedBy"]
if !ok {
modifiedBy = clt.DeviceID()
}
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnChange(&Change{
FolderID: data["folder"],
ShortID: modifiedBy,
Action: data["action"],
Path: data["path"],
Time: &Date{time: evt.Time},
})
clt.Delegate.OnEvent(evt.Type.String())
}
case events.LocalIndexUpdated, events.DeviceDisconnected, events.ConfigSaved,
events.ClusterConfigReceived, events.FolderResumed, events.FolderPaused:
// Just deliver the event
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnEvent(evt.Type.String())
}
case events.DownloadProgress:
clt.downloadProgress = evt.Data.(map[string]map[string]*model.PullerProgress)
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnEvent(evt.Type.String())
}
case events.RemoteDownloadProgress:
peerData := evt.Data.(map[string]interface{})
peerID := peerData["device"].(string)
folderID := peerData["folder"].(string)
state := peerData["state"].(map[string]int) // path: number of blocks downloaded
if _, ok := clt.uploadProgress[peerID]; !ok {
clt.uploadProgress[peerID] = make(map[string]map[string]int)
}
if _, ok := clt.uploadProgress[peerID][folderID]; !ok {
clt.uploadProgress[peerID][folderID] = make(map[string]int)
}
clt.uploadProgress[peerID][folderID] = state
if !clt.IgnoreEvents && clt.Delegate != nil {
clt.Delegate.OnEvent(evt.Type.String())
}
case events.ItemFinished, events.ItemStarted:
// Ignore these events
break
default:
Logger.Debugln("EVENT", evt.Type.String(), evt)
}
}
func (clt *Client) startEventListener() {
sub := clt.evLogger.Subscribe(events.AllEvents)
defer sub.Unsubscribe()
for {
select {
case <-clt.ctx.Done():
return
case evt := <-sub.C():
clt.handleEvent(evt)
}
}
}
func (clt *Client) IsUploading() bool {
clt.mutex.Lock()
defer clt.mutex.Unlock()
for devID, uploadsPerFolder := range clt.uploadProgress {
// Skip peers that are not connected
peer := clt.PeerWithID(devID)
if peer == nil || !peer.IsConnected() {
continue
}
for _, uploads := range uploadsPerFolder {
if len(uploads) > 0 {
return true
}
}
}
return false
}
func (clt *Client) UploadingToPeers() *ListOfStrings {
clt.mutex.Lock()
defer clt.mutex.Unlock()
peers := make([]string, 0)
for peerID, uploadsPerFolder := range clt.uploadProgress {
// Skip peers that are not connected
peer := clt.PeerWithID(peerID)
if peer == nil || !peer.IsConnected() {
continue
}
peerHasUploads := false
for _, uploads := range uploadsPerFolder {
if len(uploads) > 0 {
peerHasUploads = true
break
}
}
if peerHasUploads {
peers = append(peers, peerID)
break
}
}
return List(peers)
}
func (clt *Client) UploadingFilesForPeerAndFolder(deviceID string, folderID string) *ListOfStrings {
clt.mutex.Lock()
defer clt.mutex.Unlock()
// Skip peers that are not connected
peer := clt.PeerWithID(deviceID)
if peer == nil || !peer.IsConnected() {
return &ListOfStrings{}
}
if uploads, ok := clt.uploadProgress[deviceID]; ok {
if files, ok := uploads[folderID]; ok {
return List(KeysOf(files))
}
}
return &ListOfStrings{}
}
func (clt *Client) UploadingFoldersForPeer(deviceID string) *ListOfStrings {
clt.mutex.Lock()
defer clt.mutex.Unlock()
// Skip peers that are not connected
peer := clt.PeerWithID(deviceID)
if peer == nil || !peer.IsConnected() {
return &ListOfStrings{}
}
if uploads, ok := clt.uploadProgress[deviceID]; ok {
return List(KeysOf(uploads))
}
return &ListOfStrings{}
}
func (clt *Client) GetLastPeerAddress(deviceID string) string {
clt.mutex.Lock()
defer clt.mutex.Unlock()
if addr, ok := clt.connectedDeviceAddresses[deviceID]; ok {
return addr
}
return ""
}
func (clt *Client) IsDownloading() bool {
clt.mutex.Lock()
defer clt.mutex.Unlock()
for _, isTransferring := range clt.foldersDownloading {
if isTransferring {
return true
}
}
return false
}
func (clt *Client) Start() error {
// Subscribe to events
go clt.startEventListener()
if err := clt.app.Start(); err != nil {
return err
}
return nil
}
func (clt *Client) SetFSWatchingEnabledForAllFolders(enabled bool) {
clt.changeConfiguration(func(cfg *config.Configuration) {
for _, fc := range clt.config.FolderList() {
fc.FSWatcherEnabled = enabled
cfg.SetFolder(fc)
}
})
}
func loadOrDefaultConfig(devID protocol.DeviceID, ctx context.Context, logger events.Logger, filesPath string) (config.Wrapper, error) {
cfgFile := locations.Get(locations.ConfigFile)
cfg, _, err := config.Load(cfgFile, devID, logger)
if err != nil {
newCfg := config.New(devID)
newCfg.GUI.Enabled = false
cfg = config.Wrap(cfgFile, newCfg, devID, logger)
}
go cfg.Serve(ctx)
// Always override the following options in config
waiter, err := cfg.Modify(func(conf *config.Configuration) {
conf.GUI.Enabled = false // Don't need the web UI, we have our own :-)
conf.Options.CREnabled = false // No crash reporting for now
conf.Options.URAccepted = -1 // No usage reporting for now
conf.Options.ProgressUpdateIntervalS = 1 // We want to update the user often, it improves the experience and is worth the compute cost
conf.Options.CRURL = "" // No crash reporting for now
conf.Options.URURL = "" // No usage reporting for now
conf.Options.ReleasesURL = "" // Disable auto update, we can't do so on iOS anyway
conf.Options.InsecureAllowOldTLSVersions = false // Never allow insecure TLS
conf.Defaults.Folder.IgnorePerms = true // iOS doesn't expose permissions to users
conf.Defaults.Folder.RescanIntervalS = 3600 // Force default rescan interval
conf.Options.RelayReconnectIntervalM = 1 // Set this to one minute (from the default 10) because on mobile networks this is more often necessary
conf.Defaults.Folder.FSWatcherEnabled = !build.IsIOS // Enable watching by default but not on iOS
// On iOS and probably macOS, the absolute path to the apps container that has the synchronized folders changes on each
// run. Therefore we re-set the absolute folder path here to [app documents directory]/[folder ID] if we don't have
// a folder marker in the old location but do have one in the new.
for _, folderConfig := range conf.Folders {
standardPath := path.Join(filesPath, folderConfig.ID)
if folderConfig.Path != standardPath {
Logger.Warnln("Configured folder path differs from expected path:", folderConfig.Path, standardPath)
oldMarkerPath := path.Join(folderConfig.Path, folderConfig.MarkerName)
if _, err := os.Stat(oldMarkerPath); errors.Is(err, os.ErrNotExist) {
newMarkerPath := path.Join(standardPath, folderConfig.MarkerName)
if _, err := os.Stat(newMarkerPath); errors.Is(err, os.ErrNotExist) {
Logger.Warnln("Marker does not exist at either old or new location, not changing anything", oldMarkerPath, newMarkerPath)
} else {
Logger.Warnln("Marker does not exist at old location and exists at new location, resetting standard path", oldMarkerPath, newMarkerPath, standardPath)
folderConfig.Path = standardPath
conf.SetFolder(folderConfig)
}
}
}
}
})
if err != nil {
return nil, err
}
waiter.Wait()
err = cfg.Save()
if err != nil {
return nil, err
}
return cfg, err
}
/** Returns our node's device ID */
func (clt *Client) DeviceID() string {
return protocol.NewDeviceID(clt.cert.Certificate[0]).String()
}
/** Returns our node's short device ID */
func (clt *Client) ShortDeviceID() string {
return protocol.NewDeviceID(clt.cert.Certificate[0]).Short().String()
}
func (clt *Client) deviceID() protocol.DeviceID {
return protocol.NewDeviceID(clt.cert.Certificate[0])
}
func (clt *Client) Folders() *ListOfStrings {
if clt.config == nil {
return nil
}
return List(Map(clt.config.FolderList(), func(folder config.FolderConfiguration) string {
return folder.ID
}))
}
func (clt *Client) FolderWithID(id string) *Folder {
if clt.config == nil {
return nil
}
fi, ok := clt.config.Folders()[id]
if !ok {
return nil // Folder with this ID does not exist
}
return &Folder{
client: clt,
FolderID: fi.ID,
}
}
func (clt *Client) ConnectedPeerCount() int {
if clt.app == nil || clt.app.Internals == nil {
return 0
}
if clt.config == nil || clt.app == nil || clt.app.Internals == nil {
return 0
}
devIDs := clt.config.Devices()
connected := 0
for devID := range devIDs {
if devID == clt.deviceID() {
continue
}
if clt.app.Internals.IsConnectedTo(devID) {
connected++
}
}
return connected
}
func (clt *Client) Peers() *ListOfStrings {
if clt.config == nil {
return nil
}
return List(Map(clt.config.DeviceList(), func(device config.DeviceConfiguration) string {
return device.DeviceID.String()
}))
}
func (clt *Client) PeerWithID(deviceID string) *Peer {
devID, err := protocol.DeviceIDFromString(deviceID)
if err != nil {
return nil
}
return &Peer{
client: clt,
deviceID: devID,
}
}
func (clt *Client) PeerWithShortID(shortID string) *Peer {
for _, dc := range clt.config.DeviceList() {
if dc.DeviceID.Short().String() == shortID {
return &Peer{
client: clt,
deviceID: dc.DeviceID,
}
}
}
return nil
}
func (clt *Client) SuspendPeers() (*ListOfStrings, error) {
suspended := make([]string, 0)
clt.changeConfiguration(func(cfg *config.Configuration) {
for _, dc := range clt.config.DeviceList() {
if !dc.Paused {
dc.Paused = true
cfg.SetDevice(dc)
suspended = append(suspended, dc.DeviceID.String())
}
}
})
Logger.Infoln("Suspended devices", suspended)
return List(suspended), nil
}
func (clt *Client) Unsuspend(peers *ListOfStrings) error {
ids := peers.data
Logger.Infoln("Unsuspend IDs", ids)
clt.changeConfiguration(func(cfg *config.Configuration) {
for _, dc := range clt.config.DeviceList() {
Logger.Infoln("Unsuspend?", dc.Paused, dc.DeviceID.String())
if dc.Paused && slices.ContainsFunc(ids, func(v string) bool {
did, err := protocol.DeviceIDFromString(v)
return err == nil && dc.DeviceID.Equals(did)
}) {
dc.Paused = false
cfg.SetDevice(dc)
Logger.Infoln("Unsuspend", dc.DeviceID.String())
}
}
})
return nil
}
func (clt *Client) changeConfiguration(block config.ModifyFunction) error {
waiter, err := clt.config.Modify(block)
if err != nil {
return err
}
waiter.Wait()
err = clt.config.Save()
return err
}
func (clt *Client) AddPeer(deviceID string) error {
addedDevice, err := protocol.DeviceIDFromString(deviceID)
if err != nil {
return err
}
deviceConfig := clt.config.DefaultDevice()
deviceConfig.DeviceID = addedDevice
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.SetDevice(deviceConfig)
})
}
// Leave path empty to add folder at default location
func (clt *Client) AddFolder(folderID string, folderPath string, createAsOnDemand bool) error {
if clt.app == nil || clt.app.Internals == nil {
return ErrStillLoading
}
folderConfig := clt.config.DefaultFolder()
folderConfig.ID = folderID
folderConfig.Label = folderID
if len(folderPath) == 0 {
folderConfig.Path = path.Join(clt.filesPath, folderID)
} else {
folderConfig.Path = folderPath
}
folderConfig.Paused = false
// Add to configuration
err := clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.SetFolder(folderConfig)
})
if err != nil {
return err
}
// Set default ignores for on-demand sync
if createAsOnDemand {
return clt.app.Internals.SetIgnores(folderID, []string{"*"})
} else {
// Create empty .stignore anyway because there may be an old one lingering around
return clt.app.Internals.SetIgnores(folderID, []string{})
}
}
func (clt *Client) SetNATEnabled(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.NATEnabled = enabled
})
}
func (clt *Client) IsNATEnabled() bool {
return clt.config.Options().NATEnabled
}
func (clt *Client) SetSTUNEnabled(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
if enabled {
cfg.Options.StunKeepaliveMinS = 20
} else {
cfg.Options.StunKeepaliveMinS = 0
}
})
}
func (clt *Client) IsSTUNEnabled() bool {
return clt.config.Options().StunKeepaliveMinS > 0
}
func (clt *Client) SetRelaysEnabled(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.RelaysEnabled = enabled
})
}
func (clt *Client) IsRelaysEnabled() bool {
return clt.config.Options().RelaysEnabled
}
func (clt *Client) SetLocalAnnounceEnabled(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.LocalAnnEnabled = enabled
})
}
func (clt *Client) IsLocalAnnounceEnabled() bool {
return clt.config.Options().LocalAnnEnabled
}
func (clt *Client) SetGlobalAnnounceEnabled(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.GlobalAnnEnabled = enabled
})
}
func (clt *Client) IsGlobalAnnounceEnabled() bool {
return clt.config.Options().GlobalAnnEnabled
}
func (clt *Client) SetAnnounceLANAddresses(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.AnnounceLANAddresses = enabled
})
}
func (clt *Client) IsAnnounceLANAddressesEnabled() bool {
return clt.config.Options().AnnounceLANAddresses
}
func (clt *Client) IsBandwidthLimitedInLAN() bool {
return clt.config.Options().LimitBandwidthInLan
}
func (clt *Client) SetBandwidthLimitedInLAN(enabled bool) error {
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.LimitBandwidthInLan = enabled
})
}
func (clt *Client) GetBandwidthLimitUpMbitsPerSec() int {
return clt.config.Options().MaxSendKbps / 1000
}
func (clt *Client) GetBandwidthLimitDownMbitsPerSec() int {
return clt.config.Options().MaxRecvKbps / 1000
}
func (clt *Client) SetBandwidthLimitsMbitsPerSec(down int, up int) error {
if down < 0 {
down = 0
}
if up < 0 {
up = 0
}
return clt.changeConfiguration(func(cfg *config.Configuration) {
cfg.Options.MaxRecvKbps = down * 1000
cfg.Options.MaxSendKbps = up * 1000
})
}
type Progress struct {
BytesTotal int64
BytesDone int64
FilesTotal int64
Percentage float32
}
func (clt *Client) UploadProgressForPeerFolderPath(deviceID string, folderID string, path string) *Progress {
clt.mutex.Lock()
defer clt.mutex.Unlock()
if uploads, ok := clt.uploadProgress[deviceID]; ok {
if files, ok := uploads[folderID]; ok {
if blocksTransferred, ok := files[path]; ok {
info, ok, err := clt.app.Internals.GlobalFileInfo(folderID, path)
if !ok || err != nil {
return nil
}
bytesTotal := info.FileSize()
if bytesTotal == 0 {
return nil
}
bytesDone := min(bytesTotal, int64(blocksTransferred)*int64(info.BlockSize()))
return &Progress{
BytesTotal: bytesTotal,
BytesDone: bytesDone,
FilesTotal: 1,
Percentage: float32(float64(bytesDone) / float64(bytesTotal)),
}
}
}
}
return nil
}
func (clt *Client) GetTotalUploadProgress() *Progress {
clt.mutex.Lock()
defer clt.mutex.Unlock()
if clt.uploadProgress == nil {
return nil
}
var totalBytes int64 = 0
var transferredBytes int64 = 0
var totalFiles int64 = 0
for _, info := range clt.uploadProgress {
for folderID, finfo := range info {
for path, blocksTransferred := range finfo {
info, ok, err := clt.app.Internals.GlobalFileInfo(folderID, path)
if !ok || err != nil {
continue
}
totalBytes += info.Size
bytesDone := min(info.Size, int64(blocksTransferred)*int64(info.BlockSize()))
transferredBytes += bytesDone
totalFiles += 1
}
}
}
if totalBytes == 0 {
return nil
}
return &Progress{
BytesTotal: totalBytes,
BytesDone: transferredBytes,
FilesTotal: totalFiles,
Percentage: float32(float64(transferredBytes) / float64(totalBytes)),
}
}
func (clt *Client) GetTotalDownloadProgress() *Progress {
clt.mutex.Lock()
defer clt.mutex.Unlock()
if clt.downloadProgress == nil {
return nil
}
var doneBytes, totalBytes int64
doneBytes = 0
totalBytes = 0
fileCount := 0
for _, info := range clt.downloadProgress {
for _, fileInfo := range info {
doneBytes += fileInfo.BytesDone
totalBytes += fileInfo.BytesTotal
fileCount++
}
}
if totalBytes == 0 {
return nil