-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
76 lines (66 loc) · 2.29 KB
/
sync.go
File metadata and controls
76 lines (66 loc) · 2.29 KB
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 main
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
)
// ─── Sync status handler ───────────────────────────────────────────────────────
type SyncStatus struct {
Available bool `json:"available"`
State string `json:"state"` // "synced", "syncing", "error", "unknown"
Message string `json:"message,omitempty"`
}
var syncHTTPClient = &http.Client{
Timeout: 3 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
func (s *server) handleSyncStatus(w http.ResponseWriter, r *http.Request) {
apiKey := os.Getenv("SYNCTHING_API_KEY")
apiURL := os.Getenv("SYNCTHING_API_URL") // e.g. https://172.10.0.5:8384
if apiKey == "" || apiURL == "" {
jsonResponse(w, SyncStatus{Available: false, State: "unknown"})
return
}
req, err := http.NewRequest("GET", apiURL+"/rest/db/completion", nil)
if err != nil {
jsonResponse(w, SyncStatus{Available: false, State: "error", Message: err.Error()})
return
}
req.Header.Set("X-API-Key", apiKey)
resp, err := syncHTTPClient.Do(req)
if err != nil {
jsonResponse(w, SyncStatus{Available: false, State: "error", Message: "unreachable"})
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
// 401/403 means the API key is wrong or unset — that's a config
// issue, not a real sync error. Suppress the indicator instead of
// permanently lighting it red.
if resp.StatusCode == 401 || resp.StatusCode == 403 {
jsonResponse(w, SyncStatus{Available: false, State: "unknown"})
return
}
jsonResponse(w, SyncStatus{Available: true, State: "error", Message: fmt.Sprintf("HTTP %d", resp.StatusCode)})
return
}
var completion struct {
Completion float64 `json:"completion"`
NeedBytes int64 `json:"needBytes"`
}
if err := json.NewDecoder(resp.Body).Decode(&completion); err != nil {
jsonResponse(w, SyncStatus{Available: true, State: "error", Message: "parse error"})
return
}
if completion.NeedBytes == 0 {
jsonResponse(w, SyncStatus{Available: true, State: "synced", Message: "Up to date"})
} else {
jsonResponse(w, SyncStatus{Available: true, State: "syncing",
Message: fmt.Sprintf("%.0f%%", completion.Completion)})
}
}