forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
external.go
256 lines (208 loc) · 7.56 KB
/
external.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
package external
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"strings"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
"github.com/pkg/errors"
)
const contentURLEncoded = "application/x-www-form-urlencoded"
const contentJSON = "application/json"
const contentXML = "text/xml; charset=utf-8"
func init() {
courier.RegisterHandler(NewHandler())
}
type handler struct {
handlers.BaseHandler
}
// NewHandler returns a new External handler
func NewHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("EX"), "External")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddReceiveMsgRoute(h, "POST", "receive", h.ReceiveMessage)
s.AddReceiveMsgRoute(h, "GET", "receive", h.ReceiveMessage)
sentHandler := h.buildStatusHandler("sent")
s.AddUpdateStatusRoute(h, "GET", "sent", sentHandler)
s.AddUpdateStatusRoute(h, "POST", "sent", sentHandler)
deliveredHandler := h.buildStatusHandler("delivered")
s.AddUpdateStatusRoute(h, "GET", "delivered", deliveredHandler)
s.AddUpdateStatusRoute(h, "POST", "delivered", deliveredHandler)
failedHandler := h.buildStatusHandler("failed")
s.AddUpdateStatusRoute(h, "GET", "failed", failedHandler)
s.AddUpdateStatusRoute(h, "POST", "failed", failedHandler)
return nil
}
// ReceiveMessage is our HTTP handler function for incoming messages
func (h *handler) ReceiveMessage(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.ReceiveEvent, error) {
externalMessage := &externalMessage{}
handlers.DecodeAndValidateQueryParams(externalMessage, r)
// if this is a post, also try to parse the form body
if r.Method == http.MethodPost {
handlers.DecodeAndValidateForm(externalMessage, r)
}
// validate whether our required fields are present
err := handlers.Validate(externalMessage)
if err != nil {
return nil, err
}
// must have one of from or sender set, error if neither
sender := externalMessage.Sender
if sender == "" {
sender = externalMessage.From
}
if sender == "" {
return nil, errors.New("must have one of 'sender' or 'from' set")
}
// if we have a date, parse it
dateString := externalMessage.Date
if dateString == "" {
dateString = externalMessage.Time
}
date := time.Now()
if dateString != "" {
date, err = time.Parse(time.RFC3339Nano, dateString)
if err != nil {
return nil, errors.New("invalid date format, must be RFC 3339")
}
}
// create our URN
urn := urns.NewURNFromParts(channel.Schemes()[0], sender, "").Normalize("")
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, externalMessage.Text).WithReceivedOn(date)
// and write it
err = h.Backend().WriteMsg(msg)
if err != nil {
return nil, err
}
return []courier.ReceiveEvent{msg}, courier.WriteMsgSuccess(w, r, msg)
}
type externalMessage struct {
From string `name:"from"`
Sender string `name:"sender"`
Text string `validate:"required" name:"text"`
Date string `name:"date"`
Time string `name:"time"`
}
// buildStatusHandler deals with building a handler that takes what status is received in the URL
func (h *handler) buildStatusHandler(status string) courier.ChannelUpdateStatusFunc {
return func(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.MsgStatus, error) {
return h.StatusMessage(status, channel, w, r)
}
}
// StatusMessage is our HTTP handler function for status updates
func (h *handler) StatusMessage(statusString string, channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.MsgStatus, error) {
statusForm := &statusForm{}
handlers.DecodeAndValidateQueryParams(statusForm, r)
// if this is a post, also try to parse the form body
if r.Method == http.MethodPost {
handlers.DecodeAndValidateForm(statusForm, r)
}
// validate whether our required fields are present
err := handlers.Validate(statusForm)
if err != nil {
return nil, err
}
// get our id
msgStatus, found := statusMappings[strings.ToLower(statusString)]
if !found {
return nil, fmt.Errorf("unknown status '%s', must be one failed, sent or delivered", statusString)
}
// write our status
status := h.Backend().NewMsgStatusForID(channel, courier.NewMsgID(statusForm.ID), msgStatus)
err = h.Backend().WriteMsgStatus(status)
if err != nil {
return nil, err
}
return []courier.MsgStatus{status}, courier.WriteStatusSuccess(w, r, status)
}
type statusForm struct {
ID int64 `name:"id" validate:"required"`
}
var statusMappings = map[string]courier.MsgStatusValue{
"failed": courier.MsgFailed,
"sent": courier.MsgSent,
"delivered": courier.MsgDelivered,
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(msg courier.Msg) (courier.MsgStatus, error) {
sendURL := msg.Channel().StringConfigForKey(courier.ConfigSendURL, "")
if sendURL == "" {
return nil, fmt.Errorf("no send url set for EX channel")
}
sendMethod := msg.Channel().StringConfigForKey(courier.ConfigSendMethod, http.MethodPost)
sendBody := msg.Channel().StringConfigForKey(courier.ConfigSendBody, "")
contentType := msg.Channel().StringConfigForKey(courier.ConfigContentType, contentURLEncoded)
maxLengthStr := msg.Channel().StringConfigForKey(courier.ConfigMaxLength, "160")
maxLength, err := strconv.Atoi(maxLengthStr)
if err != nil {
return nil, fmt.Errorf("invalid value for max length on EX channel %s: %s", msg.Channel().UUID(), maxLengthStr)
}
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
parts := handlers.SplitMsg(courier.GetTextAndAttachments(msg), maxLength)
for _, part := range parts {
// build our request
form := map[string]string{
"id": msg.ID().String(),
"text": part,
"to": msg.URN().Path(),
"to_no_plus": strings.TrimPrefix(msg.URN().Path(), "+"),
"from": msg.Channel().Address(),
"from_no_plus": strings.TrimPrefix(msg.Channel().Address(), "+"),
"channel": msg.Channel().UUID().String(),
}
url := replaceVariables(sendURL, form, contentURLEncoded)
var body io.Reader
if sendMethod == http.MethodPost || sendMethod == http.MethodPut {
body = strings.NewReader(replaceVariables(sendBody, form, contentType))
}
req, err := http.NewRequest(sendMethod, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
authorization := msg.Channel().StringConfigForKey(courier.ConfigSendAuthorization, "")
if authorization != "" {
req.Header.Set("Authorization", authorization)
}
rr, err := utils.MakeHTTPRequest(req)
// record our status and log
status.AddLog(courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err))
if err != nil {
return status, nil
}
status.SetStatus(courier.MsgWired)
}
return status, nil
}
func replaceVariables(text string, variables map[string]string, contentType string) string {
for k, v := range variables {
// encode according to our content type
switch contentType {
case contentJSON:
marshalled, _ := json.Marshal(v)
v = string(marshalled)
case contentURLEncoded:
v = url.QueryEscape(v)
case contentXML:
buf := &bytes.Buffer{}
xml.EscapeText(buf, []byte(v))
v = buf.String()
}
text = strings.Replace(text, fmt.Sprintf("{{%s}}", k), v, -1)
}
return text
}
const defaultSendBody = `id={{id}}&text={{text}}&to={{to}}&to_no_plus={{to_no_plus}}&from={{from}}&from_no_plus={{from_no_plus}}&channel={{channel}}`