summaryrefslogtreecommitdiffstats
path: root/lib/syncthing/stfolder.go
blob: d79e579eb6d4e2c5f022a83d5fe288ce14528802 (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
package st

import (
	"path/filepath"
	"strings"

	"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
}

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

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

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

	newDevice := config.DeviceConfiguration{
		DeviceID:  devID,
		Name:      f.SyncThingID,
		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 = f.SyncThingID[0:15] + "_" + label
	}

	folder := config.FolderConfiguration{
		ID:      id,
		Label:   label,
		RawPath: filepath.Join(f.ShareRootDir, f.RelativePath),
	}

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

	found = false
	var fld config.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 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
}