-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhistories.go
256 lines (236 loc) · 6.38 KB
/
histories.go
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package thingscloud
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"strconv"
)
// History represents a synchronization stream. It's identified with a uuid v4
type History struct {
ID string
Client *Client
LatestServerIndex int
LoadedServerIndex int
LatestSchemaVersion int
EndTotalContentSize int
LatestTotalContentSize int
}
type historyResponse struct {
LatestSchemaVersion int `json:"latest-schema-version"`
LatestTotalContentSize int `json:"latest-total-content-size"`
IsEmpty bool `json:"is-empty"`
LatestServerIndex int `json:"latest-server-index"`
}
// Sync ensures the history object is able to write to things
func (h *History) Sync() error {
req, err := http.NewRequest("GET", fmt.Sprintf("/version/1/history/%s/items", h.ID), nil)
if err != nil {
return err
}
query := req.URL.Query()
query.Add("start-index", strconv.Itoa(h.LatestServerIndex))
req.URL.RawQuery = query.Encode()
resp, err := h.Client.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http response code: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var v itemsResponse
json.Unmarshal(bs, &v)
h.LatestServerIndex = v.CurrentItemIndex
h.LatestSchemaVersion = v.SchemaVersion
h.LatestTotalContentSize = v.LatestTotalContentSize
return nil
}
// History requests a specific history
func (c *Client) History(id string) (*History, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("/version/1/history/%s", id), nil)
if err != nil {
return nil, err
}
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusUnauthorized {
return nil, ErrUnauthorized
}
return nil, fmt.Errorf("http response code: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
h := historyResponse{}
if err := json.Unmarshal(bs, &h); err != nil {
return nil, err
}
return &History{
Client: c,
ID: id,
LatestServerIndex: h.LatestServerIndex,
LatestSchemaVersion: h.LatestSchemaVersion,
LatestTotalContentSize: h.LatestTotalContentSize,
}, nil
}
type v1historyResponse struct {
Key string `json:"history-key"`
LatestServerIndex int `json:"latest-server-index"`
IsEmpty bool `json:"is-empty"`
LatestSchemaVersion int `json:"latest-schema-version"`
}
// OwnHistory returns the clients own history
func (c *Client) OwnHistory() (*History, error) {
resp, err := c.Verify()
if err != nil {
return nil, err
}
return &History{
Client: c,
ID: resp.HistoryKey,
}, nil
}
// Histories requests all known history keys
func (c *Client) Histories() ([]*History, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("/version/1/account/%s/own-history-keys", c.EMail), nil)
if err != nil {
return nil, err
}
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusUnauthorized {
return nil, ErrUnauthorized
}
return nil, fmt.Errorf("http response code: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var keys []string
json.Unmarshal(bs, &keys)
var histories = make([]*History, len(keys))
for i, key := range keys {
histories[i] = &History{
Client: c,
ID: key,
}
}
return histories, nil
}
type createHistoryResponse struct {
Key string `json:"new-history-key"`
}
// CreateHistory requests a new history key
func (c *Client) CreateHistory() (*History, error) {
req, err := http.NewRequest("POST", fmt.Sprintf("/version/1/account/%s/own-history-keys", c.EMail), nil)
if err != nil {
return nil, err
}
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusUnauthorized {
return nil, ErrUnauthorized
}
return nil, fmt.Errorf("http response code: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var v createHistoryResponse
json.Unmarshal(bs, &v)
return &History{
Client: c,
ID: v.Key,
}, nil
}
// Delete destroys a history
// Note that thingscloud will always return 202, even if the key is unknown
func (h *History) Delete() error {
req, err := http.NewRequest("DELETE", fmt.Sprintf("/version/1/account/%s/own-history-keys/%s", h.Client.EMail, h.ID), nil)
if err != nil {
return err
}
resp, err := h.Client.do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("http response code: %s", resp.Status)
}
return nil
}
type commitResponse struct {
ServerHeadIndex int `json:"server-head-index"`
}
// Identifiable abstracts different thingscloud write requests. As we need to provide a map
// indexed by UUID, all we care about is the ID of the change, not the change itself
type Identifiable interface {
UUID() string
}
func (h *History) Write(items ...Identifiable) error {
m := map[string]interface{}{}
for _, item := range items {
m[item.UUID()] = item
}
bs, err := json.Marshal(m)
if err != nil {
return err
}
req, err := http.NewRequest("POST", fmt.Sprintf("/version/1/history/%s/commit", h.ID), bytes.NewReader(bs))
req.Header.Add("Schema", "301")
req.Header.Add("Push-Priority", "5")
req.Header.Add("App-Instance-Id", "-com.culturedcode.ThingsMac")
req.Header.Add("App-Id", "com.culturedcode.ThingsMac")
req.Header.Add("Content-Encoding", "UTF-8")
req.Header.Add("Host", "cloud.culturedcode.com")
req.Header.Add("Accept", "application/json")
query := req.URL.Query()
query.Add("ancestor-index", strconv.Itoa(h.LatestServerIndex))
query.Add("_cnt", "1")
req.URL.RawQuery = query.Encode()
if err != nil {
return err
}
resp, err := h.Client.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bs, _ := httputil.DumpResponse(resp, true)
log.Println(string(bs))
return fmt.Errorf("Write failed: %d", resp.StatusCode)
}
rs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var w commitResponse
json.Unmarshal(rs, &w)
h.LatestServerIndex = w.ServerHeadIndex
return nil
}