-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandler.go
206 lines (175 loc) · 6.32 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
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
package macrokiosk
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/gsm7"
"github.com/nyaruka/gocommon/urns"
"github.com/buger/jsonparser"
)
const (
configMacrokioskSenderID = "macrokiosk_sender_id"
configMacrokioskServiceID = "macrokiosk_service_id"
)
var (
sendURL = "https://www.etracker.cc/bulksms/send"
maxMsgLength = 1600
)
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("MK"), "Macrokiosk")}
}
// 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, "status", courier.ChannelLogTypeMsgStatus, h.receiveStatus)
s.AddHandlerRoute(h, http.MethodGet, "status", courier.ChannelLogTypeMsgStatus, h.receiveStatus)
s.AddHandlerRoute(h, http.MethodGet, "receive", courier.ChannelLogTypeMsgReceive, h.receiveMessage)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, h.receiveMessage)
return nil
}
type statusForm struct {
MsgID string `name:"msgid" validate:"required"`
Status string `name:"status" validate:"required"`
}
var statusMapping = map[string]courier.MsgStatus{
"ACCEPTED": courier.MsgStatusSent,
"DELIVERED": courier.MsgStatusDelivered,
"UNDELIVERED": courier.MsgStatusFailed,
"PROCESSING": courier.MsgStatusWired,
}
// 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, clog *courier.ChannelLog) ([]courier.Event, error) {
form := &statusForm{}
err := handlers.DecodeAndValidateForm(form, r)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
msgStatus, found := statusMapping[form.Status]
if !found {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, fmt.Sprintf("ignoring unknown status '%s'", form.Status))
}
// write our status
status := h.Backend().NewStatusUpdateByExternalID(channel, form.MsgID, msgStatus, clog)
return handlers.WriteMsgStatusAndResponse(ctx, h, channel, status, w, r)
}
type moForm struct {
Longcode string `name:"longcode"`
Shortcode string `name:"shortcode"`
MSISDN string `name:"msisdn"`
From string `name:"from"`
Text string `name:"text"`
MsgID string `name:"msgId"`
Time string `name:"time"`
}
// 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, clog *courier.ChannelLog) ([]courier.Event, error) {
form := &moForm{}
err := handlers.DecodeAndValidateForm(form, r)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
recipient := form.Longcode
sender := form.MSISDN
if form.Shortcode != "" {
recipient = form.Shortcode
sender = form.From
}
if recipient == "" || sender == "" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("missing shortcode, longcode, from or msisdn parameters"))
}
if channel.Address() != recipient {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("invalid to number [%s], expecting [%s]", recipient, channel.Address()))
}
loc, err := time.LoadLocation("Asia/Kuala_Lumpur")
if err != nil {
return nil, err
}
date, err := time.ParseInLocation("2006-01-0215:04:05", form.Time, loc)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// create our URN
urn, err := urns.ParsePhone(sender, channel.Country())
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// create and write the message
msg := h.Backend().NewIncomingMsg(channel, urn, form.Text, form.MsgID, clog).WithReceivedOn(date.UTC())
return handlers.WriteMsgsAndResponse(ctx, h, []courier.MsgIn{msg}, w, r, clog)
}
// WriteMsgSuccessResponse
func (h *handler) WriteMsgSuccessResponse(ctx context.Context, w http.ResponseWriter, msgs []courier.MsgIn) error {
w.WriteHeader(200)
_, err := fmt.Fprint(w, "-1") // MacroKiosk expects "-1" back for successful requests
return err
}
type mtPayload struct {
User string `json:"user"`
Pass string `json:"pass"`
To string `json:"to"`
Text string `json:"text"`
From string `json:"from"`
ServID string `json:"servid"`
Type string `json:"type"`
}
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, "")
servID := msg.Channel().StringConfigForKey(configMacrokioskServiceID, "")
senderID := msg.Channel().StringConfigForKey(configMacrokioskSenderID, "")
if username == "" || password == "" || servID == "" || senderID == "" {
return courier.ErrChannelConfig
}
// figure out if we need to send as unicode (encoding 5)
text := gsm7.ReplaceSubstitutions(handlers.GetTextAndAttachments(msg))
encoding := "0"
if !gsm7.IsValid(text) {
encoding = "5"
}
parts := handlers.SplitMsgByChannel(msg.Channel(), text, maxMsgLength)
for _, part := range parts {
payload := &mtPayload{
From: senderID,
ServID: servID,
To: strings.TrimPrefix(msg.URN().Path(), "+"),
Text: part,
User: username,
Pass: password,
Type: encoding,
}
requestBody := &bytes.Buffer{}
json.NewEncoder(requestBody).Encode(payload)
// build our request
req, err := http.NewRequest(http.MethodPost, sendURL, requestBody)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
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, "MsgID")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("MsgID"))
} else {
res.AddExternalID(externalID)
}
}
return nil
}