-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandler.go
159 lines (130 loc) · 5.13 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
package mblox
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/urns"
)
var (
sendURL = "https://api.mblox.com/xms/v1"
maxMsgLength = 459
)
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("MB"), "Mblox")}
}
// 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.ChannelLogTypeUnknown, handlers.JSONPayload(h, h.receiveEvent))
return nil
}
type eventPayload struct {
Type string `json:"type" validate:"required"`
BatchID string `json:"batch_id"`
Status string `json:"status"`
ID string `json:"id"`
From string `json:"from"`
To string `json:"to"`
Body string `json:"body"`
ReceivedAt string `json:"received_at"`
}
var statusMapping = map[string]courier.MsgStatus{
"Delivered": courier.MsgStatusDelivered,
"Dispatched": courier.MsgStatusSent,
"Aborted": courier.MsgStatusFailed,
"Rejected": courier.MsgStatusFailed,
"Failed": courier.MsgStatusFailed,
"Expired": courier.MsgStatusFailed,
}
// receiveEvent is our HTTP handler function for incoming messages
func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request, payload *eventPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if payload.Type == "recipient_delivery_report_sms" {
clog.SetType(courier.ChannelLogTypeMsgStatus)
if payload.BatchID == "" || payload.Status == "" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("missing one of 'batch_id' or 'status' in request body"))
}
msgStatus, found := statusMapping[payload.Status]
if !found {
return nil, fmt.Errorf(`unknown status '%s', must be one of 'Delivered', 'Dispatched', 'Aborted', 'Rejected', 'Failed' or 'Expired'`, payload.Status)
}
// write our status
status := h.Backend().NewStatusUpdateByExternalID(channel, payload.BatchID, msgStatus, clog)
return handlers.WriteMsgStatusAndResponse(ctx, h, channel, status, w, r)
} else if payload.Type == "mo_text" {
clog.SetType(courier.ChannelLogTypeMsgReceive)
if payload.ID == "" || payload.From == "" || payload.To == "" || payload.Body == "" || payload.ReceivedAt == "" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("missing one of 'id', 'from', 'to', 'body' or 'received_at' in request body"))
}
date, err := time.Parse("2006-01-02T15:04:05.000Z", payload.ReceivedAt)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// create our URN
urn, err := urns.ParsePhone(payload.From, channel.Country())
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// build our Message
msg := h.Backend().NewIncomingMsg(channel, urn, payload.Body, payload.ID, clog).WithReceivedOn(date.UTC())
// and finally write our message
return handlers.WriteMsgsAndResponse(ctx, h, []courier.MsgIn{msg}, w, r, clog)
}
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("not handled, unknown type: %s", payload.Type))
}
type mtPayload struct {
From string `json:"from"`
To []string `json:"to"`
Body string `json:"body"`
DeliveryReport string `json:"delivery_report"`
}
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
}
parts := handlers.SplitMsgByChannel(msg.Channel(), handlers.GetTextAndAttachments(msg), maxMsgLength)
for _, part := range parts {
payload := &mtPayload{}
payload.From = strings.TrimPrefix(msg.Channel().Address(), "+")
payload.To = []string{strings.TrimPrefix(msg.URN().Path(), "+")}
payload.Body = part
payload.DeliveryReport = "per_recipient"
requestBody := &bytes.Buffer{}
json.NewEncoder(requestBody).Encode(payload)
// build our request
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/%s/batches", sendURL, username), requestBody)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", 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
}
externalID, err := jsonparser.GetString(respBody, "id")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("id"))
} else {
res.AddExternalID(externalID)
}
}
return nil
}