forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
dart.go
206 lines (170 loc) · 6.37 KB
/
dart.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 dart
/*
GET /handlers/dartmedia/received/uuid?userid=username&password=xxxxxxxx&original=6285218761111&sendto=93456&messagetype=0&messageid=170503131327@170504131327@93456SMS9755064&message=Msg&date=20170503131559&dcs=0&udhl=0&charset=utf-8
*/
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
)
var (
sendURL = "http://202.43.169.11/APIhttpU/receive2waysms.php"
maxMsgLength = 160
)
type handler struct {
handlers.BaseHandler
sendURL string
maxLength int
}
// NewHandler returns a new DartMedia ready to be registered
func NewHandler(channelType string, name string, sendURL string, maxLength int) courier.ChannelHandler {
return &handler{
handlers.NewBaseHandler(courier.ChannelType(channelType), name),
sendURL,
maxLength,
}
}
func init() {
courier.RegisterHandler(NewHandler("DA", "DartMedia", sendURL, maxMsgLength))
}
// 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.MethodGet, "receive", h.ReceiveMessage)
if err != nil {
return err
}
return s.AddHandlerRoute(h, http.MethodGet, "delivered", h.StatusMessage)
}
type dartMessage struct {
Message string `name:"message"`
Original string `name:"original"`
SendTo string `name:"sendto"`
}
// 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) {
daMessage := &dartMessage{}
err := handlers.DecodeAndValidateForm(daMessage, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, err)
}
if daMessage.Original == "" || daMessage.SendTo == "" {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, fmt.Errorf("missing required parameters original and sendto"))
}
// create our URN
urn := urns.NewTelURNForCountry(daMessage.Original, channel.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, daMessage.Message)
// and finally queue our message
err = h.Backend().WriteMsg(ctx, msg)
if err != nil {
return nil, err
}
return []courier.Event{msg}, h.writeReceiveSuccess(ctx, w, r, msg)
}
type dartStatus struct {
MessageID string `name:"messageid"`
Status string `name:"status"`
}
// 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) {
daStatus := &dartStatus{}
err := handlers.DecodeAndValidateForm(daStatus, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, err)
}
if daStatus.Status == "" || daStatus.MessageID == "" {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, fmt.Errorf("parameters messageid and status should not be empty"))
}
statusInt, err := strconv.Atoi(daStatus.Status)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, fmt.Errorf("parsing failed: status '%s' is not an integer", daStatus.Status))
}
msgStatus := courier.MsgSent
if statusInt >= 10 && statusInt <= 12 {
msgStatus = courier.MsgDelivered
}
if statusInt > 20 {
msgStatus = courier.MsgFailed
}
msgID, err := strconv.ParseInt(daStatus.MessageID, 10, 64)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, fmt.Errorf("parsing failed: messageid '%s' is not an integer", daStatus.MessageID))
}
// write our status
status := h.Backend().NewMsgStatusForID(channel, courier.NewMsgID(msgID), msgStatus)
err = h.Backend().WriteMsgStatus(ctx, status)
if err != nil && err != courier.ErrMsgNotFound {
return nil, err
}
return []courier.Event{status}, h.writeStatusSuccess(ctx, w, r, status)
}
// DartMedia expects "000" from a message receive request
func (h *handler) writeReceiveSuccess(ctx context.Context, w http.ResponseWriter, r *http.Request, msg courier.Msg) error {
w.WriteHeader(200)
_, err := fmt.Fprint(w, "000")
return err
}
// DartMedia expects "000" from a status request
func (h *handler) writeStatusSuccess(ctx context.Context, w http.ResponseWriter, r *http.Request, status courier.MsgStatus) error {
w.WriteHeader(200)
_, err := fmt.Fprint(w, "000")
return err
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStatus, error) {
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
if username == "" {
return nil, fmt.Errorf("no username set for %s channel", msg.Channel().ChannelType())
}
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if password == "" {
return nil, fmt.Errorf("no password set for %s channel", msg.Channel().ChannelType())
}
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
parts := handlers.SplitMsg(courier.GetTextAndAttachments(msg), h.maxLength)
for _, part := range parts {
form := url.Values{
"userid": []string{username},
"password": []string{password},
"sendto": []string{strings.TrimPrefix(msg.URN().Path(), "+")},
"original": []string{strings.TrimPrefix(msg.Channel().Address(), "+")},
"messageid": []string{msg.ID().String()},
"udhl": []string{"0"},
"dcs": []string{"0"},
"message": []string{part},
}
partSendURL, _ := url.Parse(h.sendURL)
partSendURL.RawQuery = form.Encode()
req, err := http.NewRequest(http.MethodGet, partSendURL.String(), nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr, err := utils.MakeHTTPRequest(req)
// record our status and log
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Send Error", err)
status.AddLog(log)
if err != nil {
return status, nil
}
responseText := fmt.Sprintf("%s", rr.Body)
if responseText != "000" {
errorMessage := "Unknown error"
if responseText == "001" {
errorMessage = "Error 001: Authentication Error"
}
if responseText == "101" {
errorMessage = "Error 101: Account expired or invalid parameters"
}
log.WithError("Send Error", fmt.Errorf(errorMessage))
return status, nil
}
status.SetStatus(courier.MsgWired)
}
return status, nil
}