-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandlers.go
248 lines (211 loc) · 7.71 KB
/
handlers.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
package zenvia
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/buger/jsonparser"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/urns"
)
var (
maxMsgLength = 1152
whatsappSendURL = "https://api.zenvia.com/v2/channels/whatsapp/messages"
smsSendURL = "https://api.zenvia.com/v2/channels/sms/messages"
)
func init() {
courier.RegisterHandler(newHandler("ZVW", "Zenvia WhatsApp"))
courier.RegisterHandler(newHandler("ZVS", "Zenvia SMS"))
}
type handler struct {
handlers.BaseHandler
}
func newHandler(channelType courier.ChannelType, name string) courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(channelType, name)}
}
// 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, "status", courier.ChannelLogTypeMsgStatus, handlers.JSONPayload(h, h.receiveStatus))
return nil
}
type moContent struct {
Type string `json:"type" validate:"required"`
Text string `json:"text"`
Payload string `json:"payload"`
FileURL string `json:"fileUrl"`
FileMimeType string `json:"fileMimeType"`
FileCaption string `json:"fileCaption"`
FileName string `json:"fileName"`
Longitude float32 `json:"longitude"`
Latitude float32 `json:"latitude"`
Name string `json:"name"`
Address string `json:"address"`
URL string `json:"url"`
}
type moPayload struct {
ID string `json:"id"`
Timestamp string `json:"timestamp" validate:"required"`
Type string `json:"type" validate:"required" `
Message struct {
ID string `json:"id" validate:"required"`
From string `json:"from" validate:"required"`
To string `json:"to" validate:"required" `
Direction string `json:"direction" validate:"required" `
Channel string `json:"channel"`
Contents []moContent `json:"contents" validate:"required" `
} `json:"message"`
Visitor struct {
Name string `json:"name"`
}
}
// 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 strings.ToUpper(payload.Type) != "MESSAGE" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("unsupported event type: %s", payload.Type))
}
// create our date from the timestamp
// 2017-05-03T06:04:45Z
date, err := time.Parse("2006-01-02T15:04:05Z", payload.Timestamp)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("invalid date format: %s", payload.Timestamp))
}
if strings.ToUpper(payload.Message.Direction) != "IN" {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignoring request, not incoming messages")
}
// create our URN
urn, err := urns.NewWhatsAppURN(payload.Message.From)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
contactName := payload.Visitor.Name
msgs := []courier.MsgIn{}
for _, content := range payload.Message.Contents {
text := ""
mediaURL := ""
if content.Type == "text" {
text = content.Text
} else if content.Type == "location" {
mediaURL = fmt.Sprintf("geo:%f,%f", content.Latitude, content.Longitude)
} else if content.Type == "file" {
mediaURL = content.FileURL
} else {
// we received a message type we do not support.
courier.LogRequestError(r, channel, fmt.Errorf("unsupported message type %s", content.Type))
}
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, text, payload.Message.ID, clog).WithReceivedOn(date.UTC()).WithContactName(contactName)
if mediaURL != "" {
msg.WithAttachment(mediaURL)
}
msgs = append(msgs, msg)
}
// and finally write our messages
return handlers.WriteMsgsAndResponse(ctx, h, msgs, w, r, clog)
}
var statusMapping = map[string]courier.MsgStatus{
"REJECTED": courier.MsgStatusFailed,
"NOT_DELIVERED": courier.MsgStatusFailed,
"SENT": courier.MsgStatusSent,
"DELIVERED": courier.MsgStatusDelivered,
"READ": courier.MsgStatusRead,
}
type statusPayload struct {
ID string `json:"id"`
Type string `json:"type" validate:"required" `
MessageID string `json:"messageId"`
MessageStatus struct {
Timestamp string `json:"timestamp"`
Code string `json:"code"`
} `json:"messageStatus"`
}
// receiveStatus is our HTTP handler function for status updates
func (h *handler) receiveStatus(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request, payload *statusPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if strings.ToUpper(payload.Type) != "MESSAGE_STATUS" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("unsupported event type: %s", payload.Type))
}
msgStatus, found := statusMapping[strings.ToUpper(payload.MessageStatus.Code)]
if !found {
msgStatus = courier.MsgStatusErrored
}
// write our status
status := h.Backend().NewStatusUpdateByExternalID(channel, payload.MessageID, msgStatus, clog)
return handlers.WriteMsgStatusAndResponse(ctx, h, channel, status, w, r)
}
type mtContent struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
FileURL string `json:"fileUrl,omitempty"`
FileMimeType string `json:"fileMimeType,omitempty"`
FileCaption string `json:"fileCaption,omitempty"`
FileName string `json:"fileName,omitempty"`
}
type mtPayload struct {
From string `json:"from"`
To string `json:"to"`
Contents []mtContent `json:"contents"`
}
func (h *handler) Send(ctx context.Context, msg courier.MsgOut, res *courier.SendResult, clog *courier.ChannelLog) error {
channel := msg.Channel()
token := channel.StringConfigForKey(courier.ConfigAPIKey, "")
if token == "" {
return courier.ErrChannelConfig
}
payload := mtPayload{
From: strings.TrimLeft(channel.Address(), "+"),
To: strings.TrimLeft(msg.URN().Path(), "+"),
}
text := ""
if channel.ChannelType() == "ZVW" {
for _, attachment := range msg.Attachments() {
attType, attURL := handlers.SplitAttachment(attachment)
payload.Contents = append(payload.Contents, mtContent{
Type: "file",
FileURL: attURL,
FileMimeType: attType,
})
}
text = msg.Text()
} else if channel.ChannelType() == "ZVS" {
text = handlers.GetTextAndAttachments(msg)
}
msgParts := make([]string, 0)
if text != "" {
msgParts = handlers.SplitMsgByChannel(channel, text, maxMsgLength)
}
for _, msgPart := range msgParts {
payload.Contents = append(payload.Contents, mtContent{
Type: "text",
Text: msgPart,
})
}
jsonBody := jsonx.MustMarshal(payload)
sendURL := whatsappSendURL
if channel.ChannelType() == "ZVS" {
sendURL = smsSendURL
}
req, err := http.NewRequest(http.MethodPost, sendURL, bytes.NewReader(jsonBody))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("X-API-TOKEN", token)
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
}
externalID, err := jsonparser.GetString(respBody, "id")
if err != nil {
return courier.ErrResponseUnexpected
}
res.AddExternalID(externalID)
return nil
}