forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
yo.go
159 lines (130 loc) · 4.34 KB
/
yo.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 yo
/*
GET /handlers/yo/received/uuid?account=12345&dest=8500&message=Msg&sender=256778021111
*/
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
"github.com/pkg/errors"
)
var sendURLs = []string{
"http://smgw1.yo.co.ug:9100/sendsms",
"http://41.220.12.201:9100/sendsms",
"http://164.40.148.210:9100/sendsms",
}
var maxMsgLength = 1600
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("YO"), "YO!")}
}
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
return s.AddHandlerRoute(h, http.MethodGet, "receive", h.ReceiveMessage)
}
type moMsg struct {
From string `name:"from"`
Sender string `name:"sender"`
Message string `name:"message"`
Date string `name:"date"`
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) ([]courier.Event, error) {
msg := &moMsg{}
err := handlers.DecodeAndValidateForm(msg, r)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, err)
}
// must have one of from or sender set, error if neither
sender := msg.Sender
if sender == "" {
sender = msg.From
}
if sender == "" {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, errors.New("must have one of 'sender' or 'from'"))
}
// if we have a date, parse it
dateString := msg.Date
if dateString == "" {
dateString = msg.Time
}
date := time.Now()
if dateString != "" {
date, err = time.Parse(time.RFC3339Nano, dateString)
if err != nil {
return nil, courier.WriteAndLogRequestError(ctx, w, r, channel, errors.New("invalid date format, must be RFC 3339"))
}
}
// create our URN
urn := urns.NewTelURNForCountry(sender, channel.Country())
// build our msg
dbMsg := h.Backend().NewIncomingMsg(channel, urn, msg.Message).WithReceivedOn(date)
// and write it
err = h.Backend().WriteMsg(ctx, dbMsg)
if err != nil {
return nil, err
}
return []courier.Event{dbMsg}, courier.WriteMsgSuccess(ctx, w, r, []courier.Msg{dbMsg})
}
// 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 YO channel")
}
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if password == "" {
return nil, fmt.Errorf("no password set for YO channel")
}
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
var err error
for _, part := range handlers.SplitMsg(handlers.GetTextAndAttachments(msg), maxMsgLength) {
form := url.Values{
"origin": []string{strings.TrimPrefix(msg.Channel().Address(), "+")},
"sms_content": []string{part},
"destinations": []string{strings.TrimPrefix(msg.URN().Path(), "+")},
"ybsacctno": []string{username},
"password": []string{password},
}
for _, sendURL := range sendURLs {
sendURL, _ := url.Parse(sendURL)
sendURL.RawQuery = form.Encode()
req, err := http.NewRequest(http.MethodGet, sendURL.String(), nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr, err := utils.MakeHTTPRequest(req)
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)
status.AddLog(log)
if err != nil {
continue
}
responseQS, _ := url.ParseQuery(string(rr.Body))
// check whether we were blacklisted
createMessage, _ := responseQS["ybs_autocreate_message"]
if len(createMessage) > 0 && strings.Contains(createMessage[0], "BLACKLISTED") {
status.SetStatus(courier.MsgFailed)
h.Backend().StopMsgContact(ctx, msg)
return status, nil
}
// finally check that we were sent
createStatus, _ := responseQS["ybs_autocreate_status"]
if len(createStatus) > 0 && createStatus[0] == "OK" {
status.SetStatus(courier.MsgWired)
return status, nil
}
}
}
return status, err
}