forked from pubnub/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch_request.go
387 lines (305 loc) · 9.92 KB
/
fetch_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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package pubnub
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"strconv"
"github.com/pubnub/go/pnerr"
"github.com/pubnub/go/utils"
"net/http"
"net/url"
)
var emptyFetchResp *FetchResponse
const fetchPath = "/v3/history/sub-key/%s/channel/%s"
const historyWithMessageActionsPath = "/v3/history-with-actions/sub-key/%s/channel/%s"
const maxCountFetch = 25
const maxCountHistoryWithMessageActions = 100
type fetchBuilder struct {
opts *fetchOpts
}
func newFetchBuilder(pubnub *PubNub) *fetchBuilder {
builder := fetchBuilder{
opts: &fetchOpts{
pubnub: pubnub,
},
}
return &builder
}
func newFetchBuilderWithContext(pubnub *PubNub,
context Context) *fetchBuilder {
builder := fetchBuilder{
opts: &fetchOpts{
pubnub: pubnub,
ctx: context,
},
}
return &builder
}
// Channels sets the Channels for the Fetch request.
func (b *fetchBuilder) Channels(channels []string) *fetchBuilder {
b.opts.Channels = channels
return b
}
// Start sets the Start Timetoken for the Fetch request.
func (b *fetchBuilder) Start(start int64) *fetchBuilder {
b.opts.Start = start
b.opts.setStart = true
return b
}
// End sets the End Timetoken for the Fetch request.
func (b *fetchBuilder) End(end int64) *fetchBuilder {
b.opts.End = end
b.opts.setEnd = true
return b
}
// Count sets the number of items to return in the Fetch request.
func (b *fetchBuilder) Count(count int) *fetchBuilder {
b.opts.Count = count
return b
}
// Reverse sets the order of messages in the Fetch request.
func (b *fetchBuilder) Reverse(r bool) *fetchBuilder {
b.opts.Reverse = r
return b
}
// IncludeMeta fetches the meta data associated with the message
func (b *fetchBuilder) IncludeMeta(withMeta bool) *fetchBuilder {
b.opts.WithMeta = withMeta
return b
}
// IncludeMessageActions fetches the actions associated with the message
func (b *fetchBuilder) IncludeMessageActions(withMessageActions bool) *fetchBuilder {
b.opts.WithMessageActions = withMessageActions
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 *fetchBuilder) QueryParam(queryParam map[string]string) *fetchBuilder {
b.opts.QueryParam = queryParam
return b
}
// Transport sets the Transport for the Fetch request.
func (b *fetchBuilder) Transport(tr http.RoundTripper) *fetchBuilder {
b.opts.Transport = tr
return b
}
// Execute runs the Fetch request.
func (b *fetchBuilder) Execute() (*FetchResponse, StatusResponse, error) {
rawJSON, status, err := executeRequest(b.opts)
if err != nil {
return emptyFetchResp, status, err
}
return newFetchResponse(rawJSON, b.opts, status)
}
type fetchOpts struct {
pubnub *PubNub
Channels []string
Start int64
End int64
WithMessageActions bool
WithMeta bool
// default: 100
Count int
// default: false
Reverse bool
QueryParam map[string]string
// nil hacks
setStart bool
setEnd bool
Transport http.RoundTripper
ctx Context
}
func (o *fetchOpts) config() Config {
return *o.pubnub.Config
}
func (o *fetchOpts) client() *http.Client {
return o.pubnub.GetClient()
}
func (o *fetchOpts) context() Context {
return o.ctx
}
func (o *fetchOpts) validate() error {
if o.config().SubscribeKey == "" {
return newValidationError(o, StrMissingSubKey)
}
if len(o.Channels) <= 0 {
return newValidationError(o, StrMissingChannel)
}
if o.WithMessageActions && len(o.Channels) > 1 {
return newValidationError(o, "Only one channel is supported when WithMessageActions is true")
}
return nil
}
func (o *fetchOpts) buildPath() (string, error) {
channels := utils.JoinChannels(o.Channels)
if o.WithMessageActions {
return fmt.Sprintf(historyWithMessageActionsPath,
o.pubnub.Config.SubscribeKey,
channels), nil
}
return fmt.Sprintf(fetchPath,
o.pubnub.Config.SubscribeKey,
channels), nil
}
func (o *fetchOpts) 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 <= maxCountFetch {
q.Set("max", strconv.Itoa(o.Count))
} else {
q.Set("max", strconv.Itoa(maxCountFetch))
}
q.Set("reverse", strconv.FormatBool(o.Reverse))
q.Set("include_meta", strconv.FormatBool(o.WithMeta))
SetQueryParam(q, o.QueryParam)
return q, nil
}
func (o *fetchOpts) jobQueue() chan *JobQItem {
return o.pubnub.jobQueue
}
func (o *fetchOpts) buildBody() ([]byte, error) {
return []byte{}, nil
}
func (o *fetchOpts) httpMethod() string {
return "GET"
}
func (o *fetchOpts) isAuthRequired() bool {
return true
}
func (o *fetchOpts) requestTimeout() int {
return o.pubnub.Config.NonSubscribeRequestTimeout
}
func (o *fetchOpts) connectTimeout() int {
return o.pubnub.Config.ConnectTimeout
}
func (o *fetchOpts) operationType() OperationType {
return PNFetchMessagesOperation
}
func (o *fetchOpts) telemetryManager() *TelemetryManager {
return o.pubnub.telemetryManager
}
func (o *fetchOpts) parseMessageActions(actions interface{}) map[string]PNHistoryMessageActionsTypeMap {
o.pubnub.Config.Log.Println(actions)
resp := make(map[string]PNHistoryMessageActionsTypeMap)
if actions != nil {
actionsMap := actions.(map[string]interface{})
for actionType, action := range actionsMap {
o.pubnub.Config.Log.Println("action:", action)
o.pubnub.Config.Log.Println("actionType:", actionType) //reaction2
actionMap := action.(map[string]interface{})
if actionMap != nil {
messageActionsTypeMap := PNHistoryMessageActionsTypeMap{}
messageActionsTypeMap.ActionsTypeValues = make(map[string][]PNHistoryMessageActionTypeVal, len(actionMap))
for actionVal, val := range actionMap {
o.pubnub.Config.Log.Println("actionVal:", actionVal) // smiley_face
o.pubnub.Config.Log.Println("val:", val)
actionValInt := val.([]interface{})
if actionValInt != nil {
params := make([]PNHistoryMessageActionTypeVal, len(actionValInt))
pCount := 0
for _, actionParam := range actionValInt {
pv := PNHistoryMessageActionTypeVal{}
for actionParamName, actionParamVal := range actionParam.(map[string]interface{}) {
o.pubnub.Config.Log.Println("actionParamName", actionParamName)
o.pubnub.Config.Log.Println("actionParamVal", actionParamVal)
switch actionParamName {
case "uuid":
pv.UUID = actionParamVal.(string)
case "actionTimetoken":
pv.ActionTimetoken = actionParamVal.(string)
}
}
params[pCount] = pv
pCount++
}
messageActionsTypeMap.ActionsTypeValues[actionVal] = params
}
}
resp[actionType] = messageActionsTypeMap
}
}
}
return resp
}
func (o *fetchOpts) fetchMessages(channels map[string]interface{}) map[string][]FetchResponseItem {
messages := make(map[string][]FetchResponseItem, len(channels))
for channel, histResponseSliceMap := range channels {
if histResponseMap, ok2 := histResponseSliceMap.([]interface{}); ok2 {
o.pubnub.Config.Log.Printf("Channel:%s, count:%d\n", channel, len(histResponseMap))
items := make([]FetchResponseItem, len(histResponseMap))
count := 0
for _, val := range histResponseMap {
if histResponse, ok3 := val.(map[string]interface{}); ok3 {
msg, _ := parseCipherInterface(histResponse["message"], o.pubnub.Config)
histItem := FetchResponseItem{
Message: msg,
Timetoken: histResponse["timetoken"].(string),
Meta: histResponse["meta"],
}
histItem.MessageActions = o.parseMessageActions(histResponse["actions"])
items[count] = histItem
o.pubnub.Config.Log.Printf("Channel:%s, count:%d %d\n", channel, count, len(items))
count++
} else {
o.pubnub.Config.Log.Printf("histResponse not a map %v\n", histResponse)
continue
}
}
messages[channel] = items
o.pubnub.Config.Log.Printf("Channel:%s, count:%d\n", channel, len(messages[channel]))
} else {
o.pubnub.Config.Log.Printf("histResponseSliceMap not an []interface %v\n", histResponseSliceMap)
continue
}
}
return messages
}
func newFetchResponse(jsonBytes []byte, o *fetchOpts,
status StatusResponse) (*FetchResponse, StatusResponse, error) {
resp := &FetchResponse{}
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 emptyFetchResp, status, e
}
if result, ok := value.(map[string]interface{}); ok {
o.pubnub.Config.Log.Println(result["channels"])
if channels, ok1 := result["channels"].(map[string]interface{}); ok1 {
if channels != nil {
resp.Messages = o.fetchMessages(channels)
} else {
o.pubnub.Config.Log.Printf("type assertion to map failed %v\n", result)
}
}
} else {
o.pubnub.Config.Log.Printf("type assertion to map failed %v\n", value)
}
return resp, status, nil
}
// FetchResponse is the response to Fetch request. It contains a map of type FetchResponseItem
type FetchResponse struct {
Messages map[string][]FetchResponseItem
}
// FetchResponseItem contains the message and the associated timetoken.
type FetchResponseItem struct {
Message interface{} `json:"message"`
Meta interface{} `json:"meta"`
MessageActions map[string]PNHistoryMessageActionsTypeMap `json:"actions"`
Timetoken string `json:"timetoken"`
}
// PNHistoryMessageActionsTypeMap is the struct used in the Fetch request that includes Message Actions
type PNHistoryMessageActionsTypeMap struct {
ActionsTypeValues map[string][]PNHistoryMessageActionTypeVal `json:"-"`
}
// PNHistoryMessageActionTypeVal is the struct used in the Fetch request that includes Message Actions
type PNHistoryMessageActionTypeVal struct {
UUID string `json:"uuid"`
ActionTimetoken string `json:"actionTimetoken"`
}