Added Copyright header.
[src/xds/xds-server.git] / lib / syncthing / stfolder.go
1 /*
2  * Copyright (C) 2017 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package st
19
20 import (
21         "encoding/json"
22         "fmt"
23         "path/filepath"
24         "strings"
25
26         "github.com/iotbzh/xds-server/lib/xsapiv1"
27         stconfig "github.com/syncthing/syncthing/lib/config"
28         "github.com/syncthing/syncthing/lib/protocol"
29 )
30
31 // FolderLoadFromStConfig Load/Retrieve folder config from syncthing database
32 func (s *SyncThing) FolderLoadFromStConfig(f *[]xsapiv1.FolderConfig) error {
33
34         defaultSdk := "" // cannot know which was the default sdk
35
36         stCfg, err := s.ConfigGet()
37         if err != nil {
38                 return err
39         }
40         if len(stCfg.Devices) < 1 {
41                 return fmt.Errorf("Cannot load syncthing config: no device defined")
42         }
43         devID := stCfg.Devices[0].DeviceID.String()
44         if devID == s.MyID {
45                 if len(stCfg.Devices) < 2 {
46                         return fmt.Errorf("Cannot load syncthing config: no valid device found")
47                 }
48                 devID = stCfg.Devices[1].DeviceID.String()
49         }
50
51         for _, stFld := range stCfg.Folders {
52                 cliPath := strings.TrimPrefix(stFld.Path, s.conf.FileConf.ShareRootDir)
53                 if cliPath == "" {
54                         cliPath = stFld.Path
55                 }
56                 *f = append(*f, xsapiv1.FolderConfig{
57                         ID:            stFld.ID,
58                         Label:         stFld.Label,
59                         ClientPath:    strings.TrimRight(cliPath, "/"),
60                         Type:          xsapiv1.TypeCloudSync,
61                         Status:        xsapiv1.StatusDisable,
62                         DefaultSdk:    defaultSdk,
63                         RootPath:      s.conf.FileConf.ShareRootDir,
64                         DataCloudSync: xsapiv1.CloudSyncConfig{SyncThingID: devID},
65                 })
66         }
67
68         return nil
69 }
70
71 // FolderChange is called when configuration has changed
72 func (s *SyncThing) FolderChange(f xsapiv1.FolderConfig) (string, error) {
73
74         // Get current config
75         stCfg, err := s.ConfigGet()
76         if err != nil {
77                 s.log.Errorln(err)
78                 return "", err
79         }
80
81         stClientID := f.DataCloudSync.SyncThingID
82         // Add new Device if needed
83         var devID protocol.DeviceID
84         if err := devID.UnmarshalText([]byte(stClientID)); err != nil {
85                 s.log.Errorf("not a valid device id (err %v)", err)
86                 return "", err
87         }
88
89         newDevice := stconfig.DeviceConfiguration{
90                 DeviceID:  devID,
91                 Name:      stClientID,
92                 Addresses: []string{"dynamic"},
93         }
94
95         var found = false
96         for _, device := range stCfg.Devices {
97                 if device.DeviceID == devID {
98                         found = true
99                         break
100                 }
101         }
102         if !found {
103                 stCfg.Devices = append(stCfg.Devices, newDevice)
104         }
105
106         // Add or update Folder settings
107         var label, id string
108         if label = f.Label; label == "" {
109                 label = strings.Split(id, "/")[0]
110         }
111         if id = f.ID; id == "" {
112                 id = stClientID[0:15] + "_" + label
113         }
114
115         folder := stconfig.FolderConfiguration{
116                 ID:    id,
117                 Label: label,
118                 Path:  filepath.Join(s.conf.FileConf.ShareRootDir, f.ClientPath),
119         }
120
121         if s.conf.FileConf.SThgConf.RescanIntervalS > 0 {
122                 folder.RescanIntervalS = s.conf.FileConf.SThgConf.RescanIntervalS
123         }
124
125         folder.Devices = append(folder.Devices, stconfig.FolderDeviceConfiguration{
126                 DeviceID: newDevice.DeviceID,
127         })
128
129         found = false
130         var fld stconfig.FolderConfiguration
131         for _, fld = range stCfg.Folders {
132                 if folder.ID == fld.ID {
133                         fld = folder
134                         found = true
135                         break
136                 }
137         }
138         if !found {
139                 stCfg.Folders = append(stCfg.Folders, folder)
140                 fld = stCfg.Folders[0]
141         }
142
143         err = s.ConfigSet(stCfg)
144         if err != nil {
145                 s.log.Errorln(err)
146         }
147
148         return id, nil
149 }
150
151 // FolderDelete is called to delete a folder config
152 func (s *SyncThing) FolderDelete(id string) error {
153         // Get current config
154         stCfg, err := s.ConfigGet()
155         if err != nil {
156                 s.log.Errorln(err)
157                 return err
158         }
159
160         for i, fld := range stCfg.Folders {
161                 if id == fld.ID {
162                         stCfg.Folders = append(stCfg.Folders[:i], stCfg.Folders[i+1:]...)
163                         err = s.ConfigSet(stCfg)
164                         if err != nil {
165                                 s.log.Errorln(err)
166                                 return err
167                         }
168                 }
169         }
170
171         return nil
172 }
173
174 // FolderConfigGet Returns the configuration of a specific folder
175 func (s *SyncThing) FolderConfigGet(folderID string) (stconfig.FolderConfiguration, error) {
176         fc := stconfig.FolderConfiguration{}
177         if folderID == "" {
178                 return fc, fmt.Errorf("folderID not set")
179         }
180         cfg, err := s.ConfigGet()
181         if err != nil {
182                 return fc, err
183         }
184         for _, f := range cfg.Folders {
185                 if f.ID == folderID {
186                         fc = f
187                         return fc, nil
188                 }
189         }
190         return fc, fmt.Errorf("id not found")
191 }
192
193 // FolderStatus Returns all information about the current
194 func (s *SyncThing) FolderStatus(folderID string) (*FolderStatus, error) {
195         var data []byte
196         var res FolderStatus
197         if folderID == "" {
198                 return nil, fmt.Errorf("folderID not set")
199         }
200         if err := s.client.HTTPGet("db/status?folder="+folderID, &data); err != nil {
201                 return nil, err
202         }
203         if err := json.Unmarshal(data, &res); err != nil {
204                 return nil, err
205         }
206         return &res, nil
207 }
208
209 // IsFolderInSync Returns true when folder is in sync
210 func (s *SyncThing) IsFolderInSync(folderID string) (bool, error) {
211         sts, err := s.FolderStatus(folderID)
212         if err != nil {
213                 return false, err
214         }
215         return sts.NeedBytes == 0 && sts.State == "idle", nil
216 }
217
218 // FolderScan Request immediate folder scan.
219 // Scan all folders if folderID param is empty
220 func (s *SyncThing) FolderScan(folderID string, subpath string) error {
221         url := "db/scan"
222         if folderID != "" {
223                 url += "?folder=" + folderID
224
225                 if subpath != "" {
226                         url += "&sub=" + subpath
227                 }
228         }
229         return s.client.HTTPPost(url, "")
230 }