-
Notifications
You must be signed in to change notification settings - Fork 63
/
files_send_file.go
282 lines (222 loc) · 6.94 KB
/
files_send_file.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
package pubnub
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"github.com/pubnub/go/v7/pnerr"
)
var emptySendFileResponse *PNSendFileResponse
const sendFilePath = "/v1/files/%s/channels/%s/generate-upload-url"
type sendFileBuilder struct {
opts *sendFileOpts
}
func newSendFileBuilder(pubnub *PubNub) *sendFileBuilder {
return newSendFileBuilderWithContext(pubnub, pubnub.ctx)
}
func newSendFileOpts(pubnub *PubNub, ctx Context) *sendFileOpts {
return &sendFileOpts{endpointOpts: endpointOpts{pubnub: pubnub, ctx: ctx}}
}
func newSendFileBuilderWithContext(pubnub *PubNub,
context Context) *sendFileBuilder {
builder := sendFileBuilder{
opts: newSendFileOpts(pubnub, context)}
return &builder
}
// TTL sets the TTL (hours) for the Publish request.
func (b *sendFileBuilder) TTL(ttl int) *sendFileBuilder {
b.opts.TTL = ttl
return b
}
// Meta sets the Meta Payload for the Publish request.
func (b *sendFileBuilder) Meta(meta interface{}) *sendFileBuilder {
b.opts.Meta = meta
return b
}
// ShouldStore if true the messages are stored in History
func (b *sendFileBuilder) ShouldStore(store bool) *sendFileBuilder {
b.opts.ShouldStore = store
return b
}
func (b *sendFileBuilder) CipherKey(cipher string) *sendFileBuilder {
b.opts.CipherKey = cipher
return b
}
func (b *sendFileBuilder) Channel(channel string) *sendFileBuilder {
b.opts.Channel = channel
return b
}
func (b *sendFileBuilder) Name(name string) *sendFileBuilder {
b.opts.Name = name
return b
}
func (b *sendFileBuilder) Message(message string) *sendFileBuilder {
b.opts.Message = message
return b
}
func (b *sendFileBuilder) File(f *os.File) *sendFileBuilder {
b.opts.File = f
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 *sendFileBuilder) QueryParam(queryParam map[string]string) *sendFileBuilder {
b.opts.QueryParam = queryParam
return b
}
// Transport sets the Transport for the sendFile request.
func (b *sendFileBuilder) Transport(tr http.RoundTripper) *sendFileBuilder {
b.opts.Transport = tr
return b
}
// CustomMessageType sets the User-specified message type string - limited by 3-50 case-sensitive alphanumeric characters
// with only `-` and `_` special characters allowed.
func (b *sendFileBuilder) CustomMessageType(messageType string) *sendFileBuilder {
b.opts.CustomMessageType = messageType
return b
}
// Execute runs the sendFile request.
func (b *sendFileBuilder) Execute() (*PNSendFileResponse, StatusResponse, error) {
rawJSON, status, err := executeRequest(b.opts)
if err != nil {
return emptySendFileResponse, status, err
}
return newPNSendFileResponse(rawJSON, b.opts, status)
}
type sendFileOpts struct {
endpointOpts
Channel string
Name string
Message string
File *os.File
CipherKey string
TTL int
Meta interface{}
ShouldStore bool
QueryParam map[string]string
CustomMessageType string
Transport http.RoundTripper
}
func (o *sendFileOpts) isCustomMessageTypeCorrect() bool {
return isCustomMessageTypeValid(o.CustomMessageType)
}
func (o *sendFileOpts) validate() error {
if o.config().SubscribeKey == "" {
return newValidationError(o, StrMissingSubKey)
}
if o.Channel == "" {
return newValidationError(o, StrMissingChannel)
}
if o.Name == "" {
return newValidationError(o, StrMissingFileName)
}
if !o.isCustomMessageTypeCorrect() {
return newValidationError(o, StrInvalidCustomMessageType)
}
return nil
}
func (o *sendFileOpts) buildPath() (string, error) {
return fmt.Sprintf(sendFilePath,
o.pubnub.Config.SubscribeKey, o.Channel), nil
}
func (o *sendFileOpts) buildQuery() (*url.Values, error) {
q := defaultQuery(o.pubnub.Config.UUID, o.pubnub.telemetryManager)
SetQueryParam(q, o.QueryParam)
if len(o.CustomMessageType) > 0 {
q.Set("custom_message_type", o.CustomMessageType)
}
return q, nil
}
// PNSendFileBody is used to create the body of the request
type PNSendFileBody struct {
Name string `json:"name"`
}
func (o *sendFileOpts) buildBody() ([]byte, error) {
b := &PNSendFileBody{
Name: o.Name,
}
jsonEncBytes, errEnc := json.Marshal(b)
if errEnc != nil {
o.pubnub.Config.Log.Printf("ERROR: Serialization error: %s\n", errEnc.Error())
return []byte{}, errEnc
}
return jsonEncBytes, nil
}
func (o *sendFileOpts) httpMethod() string {
return "POST"
}
func (o *sendFileOpts) operationType() OperationType {
return PNSendFileOperation
}
// PNSendFileResponseForS3 is the File Upload API Response for SendFile.
type PNSendFileResponseForS3 struct {
status int `json:"status"`
Data PNFileData `json:"data"`
FileUploadRequest PNFileUploadRequest `json:"file_upload_request"`
}
// PNSendFileResponse is the type used to store the response info of Send File.
type PNSendFileResponse struct {
Timestamp int64
status int `json:"status"`
Data PNFileData `json:"data"`
}
// TODO Add retry on publish failure
func newPNSendFileResponse(jsonBytes []byte, o *sendFileOpts,
status StatusResponse) (*PNSendFileResponse, StatusResponse, error) {
respForS3 := &PNSendFileResponseForS3{}
err := json.Unmarshal(jsonBytes, &respForS3)
if err != nil {
e := pnerr.NewResponseParsingError("Error unmarshalling response",
ioutil.NopCloser(bytes.NewBufferString(string(jsonBytes))), err)
return emptySendFileResponse, status, e
}
var s *sendFileToS3Builder
if o.context() != nil {
s = newSendFileToS3BuilderWithContext(o.pubnub, o.context())
} else {
s = newSendFileToS3Builder(o.pubnub)
}
_, s3ResponseStatus, errS3Response := s.File(o.File).CipherKey(o.CipherKey).FileUploadRequestData(respForS3.FileUploadRequest).Execute()
if s3ResponseStatus.StatusCode != 204 {
o.pubnub.Config.Log.Printf("s3ResponseStatus: %d", s3ResponseStatus.StatusCode)
return emptySendFileResponse, s3ResponseStatus, errS3Response
}
m := &PNPublishMessage{
Text: o.Message,
}
file := &PNFileInfoForPublish{
ID: respForS3.Data.ID,
Name: o.Name,
}
message := PNPublishFileMessage{
PNFile: file,
PNMessage: m,
}
sent := false
tryCount := 0
var timestamp int64
maxCount := o.config().FileMessagePublishRetryLimit
for !sent && tryCount < maxCount {
tryCount++
pubFileMessageResponse, pubFileResponseStatus, errPubFileResponse := o.pubnub.PublishFileMessage().TTL(o.TTL).Meta(o.Meta).ShouldStore(o.ShouldStore).Channel(o.Channel).Message(message).Execute()
if errPubFileResponse != nil {
if tryCount >= maxCount {
pubFileResponseStatus.AdditionalData = file
return emptySendFileResponse, pubFileResponseStatus, errPubFileResponse
}
continue
} else {
timestamp = pubFileMessageResponse.Timestamp
sent = true
break
}
}
resp := &PNSendFileResponse{}
d := PNFileData{}
d.ID = respForS3.Data.ID
resp.Data = d
resp.Timestamp = timestamp
return resp, status, nil
}