-
Notifications
You must be signed in to change notification settings - Fork 4
/
items.go
80 lines (71 loc) · 2.4 KB
/
items.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
package thingscloud
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
// Item is an event in thingscloud. Every action inside things generates an Item.
// Common items are the creation of a task, area or checklist, as well as modifying attributes
// or marking things as done.
type Item struct {
UUID string `json:"-"`
P json.RawMessage `json:"p"`
Kind ItemKind `json:"e"`
Action ItemAction `json:"t"`
}
type itemsResponse struct {
Items []map[string]Item `json:"items"`
LatestTotalContentSize int `json:"latest-total-content-size"`
StartTotalContentSize int `json:"start-total-content-size"`
EndTotalContentSize int `json:"end-total-content-size"`
SchemaVersion int `json:"schema"`
CurrentItemIndex int `json:"current-item-index"`
}
// ItemsOptions allows a client to pickup changes from a specific index
type ItemsOptions struct {
StartIndex int
}
// Items fetches changes from thingscloud. Every change contains multiple items which have been modified.
// The Items method unwraps these objects and returns a list instead.
//
// Note that if a item was changed multiple times it will be present multiple times in the result too.
func (h *History) Items(opts ItemsOptions) ([]Item, bool, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("/version/1/history/%s/items", h.ID), nil)
values := req.URL.Query()
values.Set("start-index", strconv.Itoa(opts.StartIndex))
req.URL.RawQuery = values.Encode()
if err != nil {
return nil, false, err
}
resp, err := h.Client.do(req)
if err != nil {
return nil, false, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, false, fmt.Errorf("http response code: %s", resp.Status)
}
bs, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, false, err
}
var v itemsResponse
if err := json.Unmarshal(bs, &v); err != nil {
return nil, false, err
}
var items = []Item{}
for _, m := range v.Items {
for id, item := range m {
item.UUID = id
items = append(items, item)
}
}
h.LoadedServerIndex = h.LoadedServerIndex + len(v.Items)
h.LatestServerIndex = v.CurrentItemIndex
h.EndTotalContentSize = v.EndTotalContentSize
h.LatestTotalContentSize = v.LatestTotalContentSize
hasMoreItems := h.LoadedServerIndex < h.LatestServerIndex
return items, hasMoreItems, nil
}