aboutsummaryrefslogtreecommitdiffstats
path: root/lib/syncthing/stfolder.go
blob: 2ad6859ac792557bb9f1b07a01750834938b8caa (plain)
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
package st

import (
	"encoding/json"
	"fmt"
	"strings"

	common "github.com/iotbzh/xds-common/golib"
	"github.com/iotbzh/xds-server/lib/folder"
	stconfig "github.com/syncthing/syncthing/lib/config"
	"github.com/syncthing/syncthing/lib/protocol"
)

// FIXME remove and use an interface on xdsconfig.FolderConfig
type FolderChangeArg struct {
	ID           string
	Label        string
	RelativePath string
	SyncThingID  string
	ShareRootDir string
}

// FolderLoadFromStConfig Load/Retrieve folder config from syncthing database
func (s *SyncThing) FolderLoadFromStConfig(f *[]folder.FolderConfig) error {

	defaultSdk := "" // cannot know which was the default sdk

	stCfg, err := s.ConfigGet()
	if err != nil {
		return err
	}
	if len(stCfg.Devices) < 1 {
		return fmt.Errorf("Cannot load syncthing config: no device defined")
	}
	devID := stCfg.Devices[0].DeviceID.String()
	if devID == s.MyID {
		if len(stCfg.Devices) < 2 {
			return fmt.Errorf("Cannot load syncthing config: no valid device found")
		}
		devID = stCfg.Devices[1].DeviceID.String()
	}

	for _, stFld := range stCfg.Folders {
		/*
			cliPath := strings.TrimPrefix(stFld.Path, s.conf.FileConf.ShareRootDir)
			if cliPath == "" {
				cliPath = stFld.Path
			}*/
		cliPath := stFld.Path
		*f = append(*f, folder.FolderConfig{
			ID:            stFld.ID,
			Label:         stFld.Label,
			ClientPath:    strings.TrimRight(cliPath, "/"),
			Type:          folder.TypeCloudSync,
			Status:        folder.StatusDisable,
			DefaultSdk:    defaultSdk,
			RootPath:      "", //s.conf.FileConf.ShareRootDir,
			DataCloudSync: folder.CloudSyncConfig{SyncThingID: devID},
		})
	}

	return nil
}

// FolderChange is called when configuration has changed
func (s *SyncThing) FolderChange(f FolderChangeArg) (string, error) {

	// Get current config
	stCfg, err := s.ConfigGet()
	if err != nil {
		s.log.Errorln(err)
		return "", err
	}

	stClientID := f.SyncThingID
	// Add new Device if needed
	var devID protocol.DeviceID
	if err := devID.UnmarshalText([]byte(stClientID)); err != nil {
		s.log.Errorf("not a valid device id (err %v)", err)
		return "", err
	}

	newDevice := stconfig.DeviceConfiguration{
		DeviceID:  devID,
		Name:      stClientID,
		Addresses: []string{"dynamic"},
	}

	var found = false
	for _, device := range stCfg.Devices {
		if device.DeviceID == devID {
			found = true
			break
		}
	}
	if !found {
		stCfg.Devices = append(stCfg.Devices, newDevice)
	}

	// Add or update Folder settings
	var label, id string
	if label = f.Label; label == "" {
		label = strings.Split(id, "/")[0]
	}
	if id = f.ID; id == "" {
		id = stClientID[0:15] + "_" + label
	}

	// Resolve local path
	pathCli, err := common.ResolveEnvVar(f.RelativePath)
	if err != nil {
		pathCli = f.RelativePath
	}
	// SEB still need ShareRootDir ? a sup
	// pathCli := filepath.Join(f.ShareRootDir, f.RelativePath)

	folder := stconfig.FolderConfiguration{
		ID:            id,
		Label:         label,
		Path:          pathCli,
		AutoNormalize: true,
	}

	/* TODO - add it ?
	if s.conf.FileConf.SThgConf.RescanIntervalS > 0 {
		folder.RescanIntervalS = s.conf.FileConf.SThgConf.RescanIntervalS
	}
	*/

	folder.Devices = append(folder.Devices, stconfig.FolderDeviceConfiguration{
		DeviceID: newDevice.DeviceID,
	})

	found = false
	var fld stconfig.FolderConfiguration
	for _, fld = range stCfg.Folders {
		if folder.ID == fld.ID {
			fld = folder
			found = true
			break
		}
	}
	if !found {
		stCfg.Folders = append(stCfg.Folders, folder)
		fld = stCfg.Folders[0]
	}

	err = s.ConfigSet(stCfg)
	if err != nil {
		s.log.Errorln(err)
	}

	return id, nil
}

// FolderDelete is called to delete a folder config
func (s *SyncThing) FolderDelete(id string) error {
	// Get current config
	stCfg, err := s.ConfigGet()
	if err != nil {
		s.log.Errorln(err)
		return err
	}

	for i, fld := range stCfg.Folders {
		if id == fld.ID {
			stCfg.Folders = append(stCfg.Folders[:i], stCfg.Folders[i+1:]...)
			err = s.ConfigSet(stCfg)
			if err != nil {
				s.log.Errorln(err)
				return err
			}
		}
	}

	return nil
}

// FolderConfigGet Returns the configuration of a specific folder
func (s *SyncThing) FolderConfigGet(folderID string) (stconfig.FolderConfiguration, error) {
	fc := stconfig.FolderConfiguration{}
	if folderID == "" {
		return fc, fmt.Errorf("folderID not set")
	}
	cfg, err := s.ConfigGet()
	if err != nil {
		return fc, err
	}
	for _, f := range cfg.Folders {
		if f.ID == folderID {
			fc = f
			return fc, nil
		}
	}
	return fc, fmt.Errorf("id not found")
}

// FolderStatus Returns all information about the current
func (s *SyncThing) FolderStatus(folderID string) (*FolderStatus, error) {
	var data []byte
	var res FolderStatus
	if folderID == "" {
		return nil, fmt.Errorf("folderID not set")
	}
	if err := s.client.HTTPGet("db/status?folder="+folderID, &data); err != nil {
		return nil, err
	}
	if err := json.Unmarshal(data, &res); err != nil {
		return nil, err
	}
	return &res, nil
}

// IsFolderInSync Returns true when folder is in sync
func (s *SyncThing) IsFolderInSync(folderID string) (bool, error) {
	sts, err := s.FolderStatus(folderID)
	if err != nil {
		return false, err
	}
	return sts.NeedBytes == 0 && sts.State == "idle", nil
}

// FolderScan Request immediate folder scan.
// Scan all folders if folderID param is empty
func (s *SyncThing) FolderScan(folderID string, subpath string) error {
	url := "db/scan"
	if folderID != "" {
		url += "?folder=" + folderID

		if subpath != "" {
			url += "&sub=" + subpath
		}
	}
	return s.client.HTTPPost(url, "")
}