forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
zenvia.go
232 lines (199 loc) · 7.05 KB
/
zenvia.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
package zenvia
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/courier/utils"
"github.com/nyaruka/gocommon/urns"
"github.com/pkg/errors"
)
var maxMsgLength = 1152
var sendURL = "https://api-rest.zenvia360.com.br/services"
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("ZV"), "Zenvia")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
err := s.AddHandlerRoute(h, http.MethodPost, "receive", h.ReceiveMessage)
if err != nil {
return err
}
return s.AddHandlerRoute(h, http.MethodPost, "status", h.StatusMessage)
}
// {
// "callbackMoRequest": {
// "id": "20690090",
// "mobile": "555191951711",
// "shortCode": "40001",
// "account": "zenvia.envio",
// "body": "Content of reply SMS",
// "received": "2014-08-26T12:27:08.488-03:00",
// "correlatedMessageSmsId": "hs765939061"
// }
// }
type moRequest struct {
CallbackMORequest struct {
ID string `json:"id" validate:"required" `
From string `json:"mobile" validate:"required" `
Text string `json:"body"`
Date string `json:"received" validate:"required" `
ExternalID string `json:"correlatedMessageSmsId" validate:"required" `
} `json:"callbackMoRequest"`
}
// {
// "callbackMtRequest": {
// "status": "03",
// "statusMessage": "Delivered",
// "statusDetail": "120",
// "statusDetailMessage": "Message received by mobile",
// "id": "hs765939216",
// "received": "2014-08-26T12:55:48.593-03:00",
// "mobileOperatorName": "Claro"
// }
// }
type statusRequest struct {
CallbackMTRequest struct {
StatusCode string `json:"status" validate:"required"`
ID string `json:"id" validate:"required" `
}
}
// {
// "sendSmsRequest": {
// "from": "Sender",
// "to": "555199999999",
// "schedule": "2014-08-22T14:55:00",
// "msg": "Test message.",
// "callbackOption": "NONE",
// "id": "002",
// "aggregateId": "1111"
// }
// }
type mtRequest struct {
SendSMSRequest struct {
From string `json:"from"`
To string `json:"to"`
Schedule string `json:"schedule"`
Msg string `json:"msg"`
CallbackOption string `json:"callbackOption"`
ID string `json:"id"`
AggregateID string `json:"aggregateId"`
} `json:"sendSmsRequest"`
}
var statusMapping = map[string]courier.MsgStatusValue{
"00": courier.MsgSent,
"01": courier.MsgSent,
"02": courier.MsgSent,
"03": courier.MsgDelivered,
"04": courier.MsgErrored,
"05": courier.MsgErrored,
"06": courier.MsgErrored,
"07": courier.MsgErrored,
"08": courier.MsgErrored,
"09": courier.MsgErrored,
"10": courier.MsgErrored,
}
// 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) ([]courier.Event, error) {
// get our params
zvMsg := &moRequest{}
err := handlers.DecodeAndValidateJSON(zvMsg, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, err)
}
// create our date from the timestamp
// 2017-05-03T06:04:45.345-03:00
date, err := time.Parse("2006-01-02T15:04:05.000-07:00", zvMsg.CallbackMORequest.Date)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, fmt.Errorf("invalid date format: %s", zvMsg.CallbackMORequest.Date))
}
// create our URN
urn := urns.NewTelURNForCountry(zvMsg.CallbackMORequest.From, channel.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, zvMsg.CallbackMORequest.Text).WithExternalID(zvMsg.CallbackMORequest.ExternalID).WithReceivedOn(date.UTC())
// and finally queue our message
err = h.Backend().WriteMsg(ctx, msg)
if err != nil {
return nil, err
}
return []courier.Event{msg}, courier.WriteMsgSuccess(ctx, w, r, []courier.Msg{msg})
}
// 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) ([]courier.Event, error) {
// get our params
zvStatus := &statusRequest{}
err := handlers.DecodeAndValidateJSON(zvStatus, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, err)
}
msgStatus, found := statusMapping[zvStatus.CallbackMTRequest.StatusCode]
if !found {
msgStatus = courier.MsgErrored
}
// write our status
status := h.Backend().NewMsgStatusForExternalID(channel, zvStatus.CallbackMTRequest.ID, msgStatus)
err = h.Backend().WriteMsgStatus(ctx, status)
if err == courier.ErrMsgNotFound {
return nil, courier.WriteAndLogStatusMsgNotFound(ctx, w, r, channel)
}
if err != nil {
return nil, err
}
return []courier.Event{status}, courier.WriteStatusSuccess(ctx, w, r, []courier.MsgStatus{status})
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStatus, error) {
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
if username == "" {
return nil, fmt.Errorf("no username set for ZV channel")
}
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if password == "" {
return nil, fmt.Errorf("no password set for ZV channel")
}
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
parts := handlers.SplitMsg(handlers.GetTextAndAttachments(msg), maxMsgLength)
for _, part := range parts {
zvMsg := mtRequest{}
zvMsg.SendSMSRequest.From = "Sender"
zvMsg.SendSMSRequest.To = strings.TrimLeft(msg.URN().Path(), "+")
zvMsg.SendSMSRequest.Msg = part
zvMsg.SendSMSRequest.ID = msg.ID().String()
zvMsg.SendSMSRequest.CallbackOption = "1"
requestBody := new(bytes.Buffer)
json.NewEncoder(requestBody).Encode(zvMsg)
// build our request
req, err := http.NewRequest(http.MethodPost, sendURL, requestBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.SetBasicAuth(username, password)
rr, err := utils.MakeHTTPRequest(req)
// record our status and log
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)
status.AddLog(log)
if err != nil {
return status, err
}
// was this request successful?
responseMsgStatus, _ := jsonparser.GetString(rr.Body, "sendSmsResponse", "statusCode")
msgStatus, found := statusMapping[responseMsgStatus]
if msgStatus == courier.MsgErrored || !found {
return status, errors.Errorf("received non-success response from Zenvia '%s'", responseMsgStatus)
}
status.SetStatus(courier.MsgWired)
}
return status, nil
}