forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
junebug.go
233 lines (197 loc) · 6.99 KB
/
junebug.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
package junebug
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"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 (
msgLength = 1530
)
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("JN"), "Junebug")}
}
// 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, "event", h.ReceiveEvent)
if err != nil {
return err
}
return s.AddHandlerRoute(h, http.MethodPost, "inbound", h.ReceiveInbound)
}
// {
// "from": "+27123456789",
// "timestamp": "2017-01-01 00:00:00.00",
// "content": "content",
// "to": "to-addr",
// "reply_to": null,
// "message_id": "message-id"
// }
type moPayload struct {
From string `json:"from" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
Content string `json:"content"`
To string `json:"to" validate:"required"`
ReplyTo string `json:"reply_to"`
MessageID string `json:"message_id" validate:"required"`
}
// ReceiveInbound is our HTTP handler function for incoming messages
func (h *handler) ReceiveInbound(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
payload := &moPayload{}
err := handlers.DecodeAndValidateJSON(payload, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, err)
}
// check authentication
secret := c.StringConfigForKey(courier.ConfigSecret, "")
if secret != "" {
authorization := r.Header.Get("Authorization")
if authorization != fmt.Sprintf("Token %s", secret) {
return nil, courier.WriteAndLogUnauthorized(ctx, w, r, c, fmt.Errorf("invalid Authorization header"))
}
}
// parse our date
date, err := time.Parse("2006-01-02 15:04:05", payload.Timestamp)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, fmt.Errorf("unable to parse date: %s", payload.Timestamp))
}
urn := urns.NewTelURNForCountry(payload.From, c.Country())
msg := h.Backend().NewIncomingMsg(c, urn, payload.Content).WithExternalID(payload.MessageID).WithReceivedOn(date.UTC())
err = h.Backend().WriteMsg(ctx, msg)
if err != nil {
return nil, err
}
return []courier.Event{msg}, courier.WriteMsgSuccess(ctx, w, r, []courier.Msg{msg})
}
// {
// 'event_type': 'submitted',
// 'message_id': 'message-id',
// 'timestamp': '2017-01-01 00:00:00+0000',
// }
type eventPayload struct {
EventType string `json:"event_type" validate:"required"`
MessageID string `json:"message_id" validate:"required"`
}
var statusMapping = map[string]courier.MsgStatusValue{
"submitted": courier.MsgSent,
"delivery_pending": courier.MsgWired,
"delivery_succeeded": courier.MsgDelivered,
"delivery_failed": courier.MsgFailed,
"rejected": courier.MsgFailed,
}
// ReceiveEvent is our HTTP handler function for incoming events
func (h *handler) ReceiveEvent(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
payload := &eventPayload{}
err := handlers.DecodeAndValidateJSON(payload, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, err)
}
// check authentication
secret := c.StringConfigForKey(courier.ConfigSecret, "")
if secret != "" {
authorization := r.Header.Get("Authorization")
if authorization != fmt.Sprintf("Token %s", secret) {
return nil, courier.WriteAndLogUnauthorized(ctx, w, r, c, fmt.Errorf("invalid Authorization header"))
}
}
// look up our status
msgStatus, found := statusMapping[payload.EventType]
if !found {
return nil, courier.WriteAndLogRequestIgnored(ctx, w, r, c, "ignoring unknown event_type")
}
// ignore pending, same status we are already in
if msgStatus == courier.MsgWired {
return nil, courier.WriteAndLogRequestIgnored(ctx, w, r, c, "ignoring existing pending status")
}
status := h.Backend().NewMsgStatusForExternalID(c, payload.MessageID, msgStatus)
err = h.Backend().WriteMsgStatus(ctx, status)
if err == courier.ErrMsgNotFound {
return nil, courier.WriteAndLogStatusMsgNotFound(ctx, w, r, c)
}
if err != nil {
return nil, err
}
return []courier.Event{status}, courier.WriteStatusSuccess(ctx, w, r, []courier.MsgStatus{status})
}
// {
// "event_url": "https://callback.com/event",
// "content": "hello world",
// "from": "2020",
// "to": "+250788383383",
// "event_auth_token": "secret",
// }
type mtPayload struct {
EventURL string `json:"event_url"`
Content string `json:"content"`
From string `json:"from"`
To string `json:"to"`
EventAuthToken string `json:"event_auth_token,omitempty"`
}
func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStatus, error) {
sendURL := msg.Channel().StringConfigForKey(courier.ConfigSendURL, "")
if sendURL == "" {
return nil, fmt.Errorf("No send_url set for JN channel")
}
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if username == "" || password == "" {
return nil, fmt.Errorf("Missing username or password for JN channel")
}
secret := msg.Channel().StringConfigForKey(courier.ConfigSecret, "")
callbackDomain := msg.Channel().CallbackDomain(h.Server().Config().Domain)
eventURL := fmt.Sprintf("https://%s/c/jn/%s/event", callbackDomain, msg.Channel().UUID())
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
for i, part := range handlers.SplitMsg(handlers.GetTextAndAttachments(msg), msgLength) {
payload := mtPayload{
EventURL: eventURL,
Content: part,
From: msg.Channel().Address(),
To: msg.URN().Path(),
}
if secret != "" {
payload.EventAuthToken = secret
}
jsonBody, err := json.Marshal(payload)
if err != nil {
return status, err
}
req, err := http.NewRequest(http.MethodPost, sendURL, bytes.NewReader(jsonBody))
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, nil
}
externalID, err := jsonparser.GetString(rr.Body, "result", "message_id")
if err != nil {
log.WithError("Message Send Error", errors.Errorf("unable to get result.message_id from body"))
return status, nil
}
// if this is our first message, record the external id
if i == 0 {
status.SetExternalID(externalID)
}
}
// this was wired successfully
status.SetStatus(courier.MsgWired)
return status, nil
}