-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandler.go
285 lines (245 loc) · 8.39 KB
/
handler.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
package infobip
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/buger/jsonparser"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/httpx"
"github.com/nyaruka/gocommon/urns"
)
var sendURL = "https://api.infobip.com/sms/1/text/advanced"
const configTransliteration = "transliteration"
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("IB"), "Infobip")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, handlers.JSONPayload(h, h.receiveMessage))
s.AddHandlerRoute(h, http.MethodPost, "delivered", courier.ChannelLogTypeMsgStatus, handlers.JSONPayload(h, h.statusMessage))
return nil
}
var statusMapping = map[string]courier.MsgStatus{
"PENDING": courier.MsgStatusSent,
"EXPIRED": courier.MsgStatusSent,
"DELIVERED": courier.MsgStatusDelivered,
"REJECTED": courier.MsgStatusFailed,
"UNDELIVERABLE": courier.MsgStatusFailed,
}
type statusPayload struct {
Results []ibStatus `validate:"required" json:"results"`
}
type ibStatus struct {
MessageID string `validate:"required" json:"messageId"`
Status struct {
GroupName string `validate:"required" json:"groupName"`
} `validate:"required" json:"status"`
}
// statusMessage is our HTTP handler function for status updates
func (h *handler) statusMessage(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request, payload *statusPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
data := make([]any, len(payload.Results))
statuses := make([]courier.Event, len(payload.Results))
for _, s := range payload.Results {
msgStatus, found := statusMapping[s.Status.GroupName]
if !found {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("unknown status '%s', must be one of PENDING, DELIVERED, EXPIRED, REJECTED or UNDELIVERABLE", s.Status.GroupName))
}
// write our status
status := h.Backend().NewStatusUpdateByExternalID(channel, s.MessageID, msgStatus, clog)
err := h.Backend().WriteStatusUpdate(ctx, status)
if err != nil {
return nil, err
}
data = append(data, courier.NewStatusData(status))
statuses = append(statuses, status)
}
return statuses, courier.WriteDataResponse(w, http.StatusOK, "statuses handled", data)
}
// {
// "results": [
// {
// "messageId": "817790313235066447",
// "from": "385916242493",
// "to": "385921004026",
// "text": "QUIZ Correct answer is Paris",
// "cleanText": "Correct answer is Paris",
// "keyword": "QUIZ",
// "receivedAt": "2016-10-06T09:28:39.220+0000",
// "smsCount": 1,
// "price": {
// "pricePerMessage": 0,
// "currency": "EUR"
// },
// "callbackData": "callbackData"
// }
// ],
// "messageCount": 1,
// "pendingMessageCount": 0
// }
type moPayload struct {
PendingMessageCount int `json:"pendingMessageCount"`
MessageCount int `json:"messageCount"`
Results []moMessage `validate:"required" json:"results"`
}
type moMessage struct {
MessageID string `json:"messageId"`
From string `json:"from" validate:"required"`
Text string `json:"text"`
ReceivedAt string `json:"receivedAt"`
}
// receiveMessage is our HTTP handler function for incoming messages
func (h *handler) receiveMessage(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request, payload *moPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if payload.MessageCount == 0 {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignoring request, no message")
}
msgs := []courier.MsgIn{}
for _, infobipMessage := range payload.Results {
messageID := infobipMessage.MessageID
text := infobipMessage.Text
dateString := infobipMessage.ReceivedAt
if text == "" {
continue
}
date := time.Now()
var err error
if dateString != "" {
date, err = time.Parse("2006-01-02T15:04:05.999999999-0700", dateString)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
}
// create our URN
urn, err := urns.ParsePhone(infobipMessage.From, channel.Country(), true, false)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// build our infobipMessage
msg := h.Backend().NewIncomingMsg(channel, urn, text, messageID, clog).WithReceivedOn(date)
msgs = append(msgs, msg)
}
if len(msgs) == 0 {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignoring request, no message")
}
return handlers.WriteMsgsAndResponse(ctx, h, msgs, w, r, clog)
}
func (h *handler) Send(ctx context.Context, msg courier.MsgOut, res *courier.SendResult, clog *courier.ChannelLog) error {
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if username == "" || password == "" {
return courier.ErrChannelConfig
}
transliteration := msg.Channel().StringConfigForKey(configTransliteration, "")
callbackDomain := msg.Channel().CallbackDomain(h.Server().Config().Domain)
statusURL := fmt.Sprintf("https://%s%s%s/delivered", callbackDomain, "/c/ib/", msg.Channel().UUID())
ibMsg := mtPayload{
Messages: []mtMessage{
{
From: msg.Channel().Address(),
Destinations: []mtDestination{
{
To: strings.TrimLeft(msg.URN().Path(), "+"),
MessageID: msg.ID().String(),
},
},
Text: handlers.GetTextAndAttachments(msg),
NotifyContentType: "application/json",
IntermediateReport: true,
NotifyURL: statusURL,
Transliteration: transliteration,
},
},
}
requestBody := &bytes.Buffer{}
err := json.NewEncoder(requestBody).Encode(ibMsg)
if err != nil {
return err
}
// build our request
req, err := http.NewRequest(http.MethodPost, sendURL, requestBody)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(username, password)
resp, respBody, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 == 5 {
return courier.ErrConnectionFailed
} else if resp.StatusCode/100 != 2 {
return courier.ErrResponseStatus
}
groupID, err := jsonparser.GetInt(respBody, "messages", "[0]", "status", "groupId")
if err != nil || (groupID != 1 && groupID != 3) {
return courier.ErrResponseContent
}
externalID, err := jsonparser.GetString(respBody, "messages", "[0]", "messageId")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("messageId"))
} else {
res.AddExternalID(externalID)
}
return nil
}
func (h *handler) RedactValues(ch courier.Channel) []string {
return []string{
httpx.BasicAuth(ch.StringConfigForKey(courier.ConfigUsername, ""), ch.StringConfigForKey(courier.ConfigPassword, "")),
}
}
// {
// "bulkId":"BULK-ID-123-xyz",
// "messages":[
// {
// "from":"InfoSMS",
// "destinations":[
// {
// "to":"41793026727",
// "messageId":"MESSAGE-ID-123-xyz"
// },
// {
// "to":"41793026731"
// }
// ],
// "text":"Artık Ulusal Dil Tanımlayıcısı ile Türkçe karakterli smslerinizi rahatlıkla iletebilirsiniz.",
// "flash":false,
// "language":{
// "languageCode":"TR"
// },
// "transliteration":"TURKISH",
// "intermediateReport":true,
// "notifyUrl":"http://www.example.com/sms/advanced",
// "notifyContentType":"application/json",
// "callbackData":"DLR callback data",
// "validityPeriod": 720
// }
// ]
// }
//
// API docs from https://dev.infobip.com/docs/fully-featured-textual-message
type mtPayload struct {
Messages []mtMessage `json:"messages"`
}
type mtMessage struct {
From string `json:"from"`
Destinations []mtDestination `json:"destinations"`
Text string `json:"text"`
NotifyContentType string `json:"notifyContentType"`
IntermediateReport bool `json:"intermediateReport"`
NotifyURL string `json:"notifyUrl"`
Transliteration string `json:"transliteration,omitempty"`
}
type mtDestination struct {
To string `json:"to"`
MessageID string `json:"messageId"`
}