forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
africastalking.go
173 lines (142 loc) · 5.16 KB
/
africastalking.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
package africastalking
import (
"context"
"fmt"
"net/http"
"net/url"
"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"
)
const configIsShared = "is_shared"
var sendURL = "https://api.africastalking.com/version1/messaging"
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("AT"), "Africas Talking")}
}
type messageRequest struct {
ID string `validate:"required" name:"id"`
Text string `validate:"required" name:"text"`
From string `validate:"required" name:"from"`
To string `validate:"required" name:"to"`
Date string `validate:"required" name:"date"`
}
type statusRequest struct {
ID string `validate:"required" name:"id"`
Status string `validate:"required" name:"status"`
}
var statusMapping = map[string]courier.MsgStatusValue{
"Success": courier.MsgDelivered,
"Sent": courier.MsgSent,
"Buffered": courier.MsgSent,
"Rejected": courier.MsgFailed,
"Failed": courier.MsgFailed,
}
// 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)
}
// 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
atMsg := &messageRequest{}
err := handlers.DecodeAndValidateForm(atMsg, r)
if err != nil {
return nil, err
}
// create our date from the timestamp
// 2017-05-03T06:04:45Z
date, err := time.Parse("2006-01-02T15:04:05Z", atMsg.Date)
if err != nil {
return nil, fmt.Errorf("invalid date format: %s", atMsg.Date)
}
// create our URN
urn := urns.NewTelURNForCountry(atMsg.From, channel.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, atMsg.Text).WithExternalID(atMsg.ID).WithReceivedOn(date)
// 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
atStatus := &statusRequest{}
err := handlers.DecodeAndValidateForm(atStatus, r)
if err != nil {
return nil, err
}
msgStatus, found := statusMapping[atStatus.Status]
if !found {
return nil, fmt.Errorf("unknown status '%s', must be one of 'Success','Sent','Buffered','Rejected' or 'Failed'", atStatus.Status)
}
// write our status
status := h.Backend().NewMsgStatusForExternalID(channel, atStatus.ID, msgStatus)
err = h.Backend().WriteMsgStatus(ctx, status)
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(_ context.Context, msg courier.Msg) (courier.MsgStatus, error) {
isSharedStr := msg.Channel().ConfigForKey(configIsShared, false)
isShared, _ := isSharedStr.(bool)
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
if username == "" {
return nil, fmt.Errorf("no username set for AT channel")
}
apiKey := msg.Channel().StringConfigForKey(courier.ConfigAPIKey, "")
if apiKey == "" {
return nil, fmt.Errorf("no API key set for AT channel")
}
// build our request
form := url.Values{
"username": []string{username},
"to": []string{msg.URN().Path()},
"message": []string{handlers.GetTextAndAttachments(msg)},
}
// if this isn't shared, include our from
if !isShared {
form["from"] = []string{msg.Channel().Address()}
}
req, err := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("apikey", apiKey)
rr, err := utils.MakeHTTPRequest(req)
// record our status and log
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
status.AddLog(courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err))
if err != nil {
return status, nil
}
// was this request successful?
msgStatus, _ := jsonparser.GetString([]byte(rr.Body), "SMSMessageData", "Recipients", "[0]", "status")
if msgStatus != "Success" {
return status, errors.Errorf("received non-success status '%s'", msgStatus)
}
// grab the external id if we can
externalID, _ := jsonparser.GetString([]byte(rr.Body), "SMSMessageData", "Recipients", "[0]", "messageId")
status.SetStatus(courier.MsgWired)
status.SetExternalID(externalID)
return status, nil
}