forked from pubnub/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
history_request.go
326 lines (260 loc) · 7.4 KB
/
history_request.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package pubnub
import (
"bytes"
"encoding/json"
"fmt"
"github.com/pubnub/go/pnerr"
"github.com/pubnub/go/utils"
"io/ioutil"
"reflect"
"strconv"
"net/http"
"net/url"
)
const historyPath = "/v2/history/sub-key/%s/channel/%s"
const maxCount = 100
var emptyHistoryResp *HistoryResponse
type historyBuilder struct {
opts *historyOpts
}
func newHistoryBuilder(pubnub *PubNub) *historyBuilder {
builder := historyBuilder{
opts: &historyOpts{
pubnub: pubnub,
},
}
return &builder
}
func newHistoryBuilderWithContext(pubnub *PubNub,
context Context) *historyBuilder {
builder := historyBuilder{
opts: &historyOpts{
pubnub: pubnub,
ctx: context,
},
}
return &builder
}
// Channel sets the Channel for the History request.
func (b *historyBuilder) Channel(ch string) *historyBuilder {
b.opts.Channel = ch
return b
}
// Start sets the Start Timetoken for the History request.
func (b *historyBuilder) Start(start int64) *historyBuilder {
b.opts.Start = start
b.opts.setStart = true
return b
}
// End sets the End Timetoken for the History request.
func (b *historyBuilder) End(end int64) *historyBuilder {
b.opts.End = end
b.opts.setEnd = true
return b
}
// Count sets the number of items to return in the History request.
func (b *historyBuilder) Count(count int) *historyBuilder {
b.opts.Count = count
return b
}
// Reverse sets the order of messages in the History request.
func (b *historyBuilder) Reverse(r bool) *historyBuilder {
b.opts.Reverse = r
return b
}
// IncludeTimetoken tells the server to send the timetoken associated with each history item.
func (b *historyBuilder) IncludeTimetoken(i bool) *historyBuilder {
b.opts.IncludeTimetoken = i
return b
}
// Transport sets the Transport for the History request.
func (b *historyBuilder) Transport(tr http.RoundTripper) *historyBuilder {
b.opts.Transport = tr
return b
}
// Execute runs the History request.
func (b *historyBuilder) Execute() (*HistoryResponse, StatusResponse, error) {
rawJSON, status, err := executeRequest(b.opts)
if err != nil {
return emptyHistoryResp, status, err
}
return newHistoryResponse(rawJSON, b.opts, status)
}
type historyOpts struct {
pubnub *PubNub
Channel string
Start int64
End int64
// defualt: 100
Count int
// default: false
Reverse bool
// default: false
IncludeTimetoken bool
// nil hacks
setStart bool
setEnd bool
Transport http.RoundTripper
ctx Context
}
func (o *historyOpts) config() Config {
return *o.pubnub.Config
}
func (o *historyOpts) client() *http.Client {
return o.pubnub.GetClient()
}
func (o *historyOpts) context() Context {
return o.ctx
}
func (o *historyOpts) validate() error {
if o.config().SubscribeKey == "" {
return newValidationError(o, StrMissingSubKey)
}
if o.Channel == "" {
return newValidationError(o, StrMissingChannel)
}
return nil
}
func (o *historyOpts) buildPath() (string, error) {
return fmt.Sprintf(historyPath,
o.pubnub.Config.SubscribeKey,
utils.URLEncode(o.Channel)), nil
}
func (o *historyOpts) buildQuery() (*url.Values, error) {
q := defaultQuery(o.pubnub.Config.UUID, o.pubnub.telemetryManager)
if o.setStart {
q.Set("start", strconv.FormatInt(o.Start, 10))
}
if o.setEnd {
q.Set("end", strconv.FormatInt(o.End, 10))
}
if o.Count > 0 && o.Count <= maxCount {
q.Set("count", strconv.Itoa(o.Count))
} else {
q.Set("count", "100")
}
q.Set("reverse", strconv.FormatBool(o.Reverse))
q.Set("include_token", strconv.FormatBool(o.IncludeTimetoken))
return q, nil
}
func (o *historyOpts) buildBody() ([]byte, error) {
return []byte{}, nil
}
func (o *historyOpts) httpMethod() string {
return "GET"
}
func (o *historyOpts) isAuthRequired() bool {
return true
}
func (o *historyOpts) requestTimeout() int {
return o.pubnub.Config.NonSubscribeRequestTimeout
}
func (o *historyOpts) connectTimeout() int {
return o.pubnub.Config.ConnectTimeout
}
func (o *historyOpts) operationType() OperationType {
return PNHistoryOperation
}
func (o *historyOpts) telemetryManager() *TelemetryManager {
return o.pubnub.telemetryManager
}
// HistoryResponse is used to store the response from the History request.
type HistoryResponse struct {
Messages []HistoryResponseItem
StartTimetoken int64
EndTimetoken int64
}
// parseInterface umarshals the response data, marshals the data again in a
// different format and returns the json string. It also unescapes the data.
//
// parameters:
// vv: interface array to parse and extract data from.
// o : historyOpts
//
// returns []HistoryResponseItem.
func parseInterface(vv []interface{}, o *historyOpts) []HistoryResponseItem {
o.pubnub.Config.Log.Println(vv)
items := make([]HistoryResponseItem, len(vv))
for i := range vv {
val := vv[i]
o.pubnub.Config.Log.Println("reflect.TypeOf(val).Kind()", reflect.TypeOf(val).Kind())
switch v := val.(type) {
case map[string]interface{}:
o.pubnub.Config.Log.Println("Map", v)
if v["timetoken"] != nil {
o.pubnub.Config.Log.Println("timetoken:", v["timetoken"])
if f, ok := v["timetoken"].(float64); ok {
s := fmt.Sprintf("%.0f", f)
o.pubnub.Config.Log.Println("s:", s)
if tt, err := strconv.Atoi(s); err == nil {
o.pubnub.Config.Log.Println("tt:", tt)
items[i].Timetoken = int64(tt)
} else {
o.pubnub.Config.Log.Println(f, s, err)
}
} else {
o.pubnub.Config.Log.Println("v[timetoken].(int64)", ok, items[i].Timetoken)
}
items[i].Message, _ = parseCipherInterface(v["message"], o.pubnub.Config)
} else {
o.pubnub.Config.Log.Println("value", v)
items[i].Message, _ = parseCipherInterface(v, o.pubnub.Config)
o.pubnub.Config.Log.Println("items[i]", items[i])
}
break
default:
o.pubnub.Config.Log.Println(v)
items[i].Message, _ = parseCipherInterface(v, o.pubnub.Config)
break
}
}
return items
}
func newHistoryResponse(jsonBytes []byte, o *historyOpts,
status StatusResponse) (*HistoryResponse, StatusResponse, error) {
resp := &HistoryResponse{}
var value interface{}
err := json.Unmarshal(jsonBytes, &value)
if err != nil {
e := pnerr.NewResponseParsingError("Error unmarshalling response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptyHistoryResp, status, e
}
switch v := value.(type) {
case []interface{}:
startTimetoken, ok := v[1].(float64)
if !ok {
e := pnerr.NewResponseParsingError("Error parsing response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptyHistoryResp, status, e
}
endTimetoken, ok := v[2].(float64)
if !ok {
e := pnerr.NewResponseParsingError("Error parsing response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptyHistoryResp, status, e
}
msgs := v[0].([]interface{})
o.pubnub.Config.Log.Println(msgs)
items := parseInterface(msgs, o)
if items != nil {
resp.Messages = items
o.pubnub.Config.Log.Printf("returning []interface, %v\n", items)
} else {
o.pubnub.Config.Log.Println("items nil")
}
resp.StartTimetoken = int64(startTimetoken)
resp.EndTimetoken = int64(endTimetoken)
break
default:
e := pnerr.NewResponseParsingError("Error parsing response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptyHistoryResp, status, e
}
return resp, status, nil
}
// HistoryResponseItem is used to store the Message and the associated timetoken from the History request.
type HistoryResponseItem struct {
Message interface{}
Timetoken int64
}