-
Notifications
You must be signed in to change notification settings - Fork 62
/
history_request.go
325 lines (255 loc) · 8.48 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
package pubnub
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"github.com/pubnub/go/v7/pnerr"
"github.com/pubnub/go/v7/utils"
"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 {
return newHistoryBuilderWithContext(pubnub, pubnub.ctx)
}
func newHistoryOpts(pubnub *PubNub, ctx Context) *historyOpts {
return &historyOpts{endpointOpts: endpointOpts{pubnub: pubnub, ctx: ctx}}
}
func newHistoryBuilderWithContext(pubnub *PubNub,
context Context) *historyBuilder {
builder := historyBuilder{
opts: newHistoryOpts(pubnub, 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
}
// IncludeMeta fetches the meta data associated with the message
func (b *historyBuilder) IncludeMeta(withMeta bool) *historyBuilder {
b.opts.WithMeta = withMeta
return b
}
// QueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.
func (b *historyBuilder) QueryParam(queryParam map[string]string) *historyBuilder {
b.opts.QueryParam = queryParam
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 {
endpointOpts
Channel string
Start int64
End int64
QueryParam map[string]string
WithMeta bool
// default: 100
Count int
// default: false
Reverse bool
// default: false
IncludeTimetoken bool
// nil hacks
setStart bool
setEnd bool
Transport http.RoundTripper
}
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))
q.Set("include_meta", strconv.FormatBool(o.WithMeta))
SetQueryParam(q, o.QueryParam)
return q, nil
}
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
}
// HistoryResponse is used to store the response from the History request.
type HistoryResponse struct {
Messages []HistoryResponseItem
StartTimetoken int64
EndTimetoken int64
}
// HistoryResponseItem is used to store the Message and the associated timetoken from the History request.
type HistoryResponseItem struct {
Message interface{}
Meta interface{}
Timetoken int64
Error error
}
func logAndCreateNewResponseParsingError(o *historyOpts, err error, jsonBody string, message string) *pnerr.ResponseParsingError {
o.pubnub.Config.Log.Println(err.Error())
e := pnerr.NewResponseParsingError(message,
ioutil.NopCloser(bytes.NewBufferString(jsonBody)), err)
return e
}
func getHistoryItemsWithoutTimetoken(historyResponseRaw []byte, o *historyOpts, err1 error, jsonBytes []byte) ([]HistoryResponseItem, *pnerr.ResponseParsingError) {
var historyResponseItems []interface{}
err0 := json.Unmarshal(historyResponseRaw, &historyResponseItems)
if err0 != nil {
e := logAndCreateNewResponseParsingError(o, fmt.Errorf("%e, %e, %s", err0, err1, string(jsonBytes)), string(jsonBytes), "Error unmarshalling response")
return nil, e
}
items := make([]HistoryResponseItem, len(historyResponseItems))
for i, v := range historyResponseItems {
o.pubnub.Config.Log.Println(v)
items[i].Message, items[i].Error = parseCipherInterface(v, o.pubnub.Config, o.pubnub.getCryptoModule())
}
return items, nil
}
func getHistoryItemsWithTimetoken(historyResponseItems []HistoryResponseItem, o *historyOpts, historyResponseRaw []byte, jsonBytes []byte) ([]HistoryResponseItem, *pnerr.ResponseParsingError) {
items := make([]HistoryResponseItem, len(historyResponseItems))
b := false
for i, v := range historyResponseItems {
if v.Message != nil {
o.pubnub.Config.Log.Println(v.Message)
items[i].Message, items[i].Error = parseCipherInterface(v.Message, o.pubnub.Config, o.pubnub.getCryptoModule())
o.pubnub.Config.Log.Println(v.Timetoken)
items[i].Timetoken = v.Timetoken
o.pubnub.Config.Log.Println(v.Meta)
items[i].Meta = v.Meta
} else {
b = true
break
}
}
if b {
items, e := getHistoryItemsWithoutTimetoken(historyResponseRaw, o, nil, jsonBytes)
return items, e
}
return items, nil
}
func newHistoryResponse(jsonBytes []byte, o *historyOpts,
status StatusResponse) (*HistoryResponse, StatusResponse, error) {
resp := &HistoryResponse{}
var historyResponseRaw []json.RawMessage
err := json.Unmarshal(jsonBytes, &historyResponseRaw)
if err != nil {
e := logAndCreateNewResponseParsingError(o, err, string(jsonBytes), "Error unmarshalling response")
return emptyHistoryResp, status, e
}
if historyResponseRaw != nil && len(historyResponseRaw) > 2 {
o.pubnub.Config.Log.Println("M", string(historyResponseRaw[0]))
o.pubnub.Config.Log.Println("T1", string(historyResponseRaw[1]))
o.pubnub.Config.Log.Println("T2", string(historyResponseRaw[2]))
var historyResponseItems []HistoryResponseItem
var items []HistoryResponseItem
err1 := json.Unmarshal(historyResponseRaw[0], &historyResponseItems)
var e *pnerr.ResponseParsingError
if err1 != nil {
o.pubnub.Config.Log.Println(err1.Error())
items, e = getHistoryItemsWithoutTimetoken(historyResponseRaw[0], o, err1, jsonBytes)
if e != nil {
return emptyHistoryResp, status, e
}
} else {
items, e = getHistoryItemsWithTimetoken(historyResponseItems, o, historyResponseRaw[0], jsonBytes)
if e != nil {
return emptyHistoryResp, status, e
}
}
if items != nil {
resp.Messages = items
o.pubnub.Config.Log.Printf("returning []interface, %v\n", items)
} else {
o.pubnub.Config.Log.Println("items nil")
}
startTimetoken, err := strconv.ParseInt(string(historyResponseRaw[1]), 10, 64)
if err == nil {
resp.StartTimetoken = startTimetoken
}
endTimetoken, err := strconv.ParseInt(string(historyResponseRaw[2]), 10, 64)
if err == nil {
resp.EndTimetoken = endTimetoken
}
} else if historyResponseRaw != nil && len(historyResponseRaw) > 0 {
e := logAndCreateNewResponseParsingError(o, err, string(jsonBytes), "Error unmarshalling response")
return emptyHistoryResp, status, e
} else {
e := logAndCreateNewResponseParsingError(o, err, string(jsonBytes), "Error unmarshalling response")
return emptyHistoryResp, status, e
}
return resp, status, nil
}