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

import (
	"encoding/json"

	"strings"

	"fmt"

	"github.com/Sirupsen/logrus"
	"github.com/iotbzh/xds-server/lib/common"
	"github.com/syncthing/syncthing/lib/config"
)

// SyncThing .
type SyncThing struct {
	BaseURL string
	client  *common.HTTPClient
	log     *logrus.Logger
}

// NewSyncThing creates a new instance of Syncthing
func NewSyncThing(url string, apikey string, log *logrus.Logger) *SyncThing {
	cl, err := common.HTTPNewClient(url,
		common.HTTPClientConfig{
			URLPrefix:           "/rest",
			HeaderClientKeyName: "X-Syncthing-ID",
		})
	if err != nil {
		msg := ": " + err.Error()
		if strings.Contains(err.Error(), "connection refused") {
			msg = fmt.Sprintf("(url: %s)", url)
		}
		log.Debugf("ERROR: cannot connect to Syncthing %s", msg)
		return nil
	}

	s := SyncThing{
		BaseURL: url,
		client:  cl,
		log:     log,
	}

	return &s
}

// IDGet returns the Syncthing ID of Syncthing instance running locally
func (s *SyncThing) IDGet() (string, error) {
	var data []byte
	if err := s.client.HTTPGet("system/status", &data); err != nil {
		return "", err
	}
	status := make(map[string]interface{})
	json.Unmarshal(data, &status)
	return status["myID"].(string), nil
}

// ConfigGet returns the current Syncthing configuration
func (s *SyncThing) ConfigGet() (config.Configuration, error) {
	var data []byte
	config := config.Configuration{}
	if err := s.client.HTTPGet("system/config", &data); err != nil {
		return config, err
	}
	err := json.Unmarshal(data, &config)
	return config, err
}

// ConfigSet set Syncthing configuration
func (s *SyncThing) ConfigSet(cfg config.Configuration) error {
	body, err := json.Marshal(cfg)
	if err != nil {
		return err
	}
	return s.client.HTTPPost("system/config", string(body))
}