forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
blackmyna.go
155 lines (126 loc) · 4.31 KB
/
blackmyna.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
package blackmyna
import (
"fmt"
"net/http"
"net/url"
"strings"
"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"
)
var sendURL = "http://api.blackmyna.com/2/smsmessaging/outbound"
type handler struct {
handlers.BaseHandler
}
// NewHandler returns a new Blackmyna Handler
func NewHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("BM"), "Blackmyna")}
}
func init() {
courier.RegisterHandler(NewHandler())
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
err := s.AddReceiveMsgRoute(h, "GET", "receive", h.ReceiveMessage)
if err != nil {
return err
}
return s.AddUpdateStatusRoute(h, "GET", "status", h.StatusMessage)
}
// ReceiveMessage is our HTTP handler function for incoming messages
func (h *handler) ReceiveMessage(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.ReceiveEvent, error) {
// get our params
bmMsg := &bmMessage{}
err := handlers.DecodeAndValidateForm(bmMsg, r)
if err != nil {
return nil, err
}
// create our URN
urn := urns.NewTelURNForCountry(bmMsg.From, channel.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, bmMsg.Text)
// and finally queue our message
err = h.Backend().WriteMsg(msg)
if err != nil {
return nil, err
}
return []courier.ReceiveEvent{msg}, courier.WriteMsgSuccess(w, r, msg)
}
type bmMessage struct {
To string `validate:"required" name:"to"`
Text string `validate:"required" name:"text"`
From string `validate:"required" name:"from"`
}
var bmStatusMapping = map[int]courier.MsgStatusValue{
1: courier.MsgDelivered,
2: courier.MsgFailed,
8: courier.MsgSent,
16: courier.MsgFailed,
}
// StatusMessage is our HTTP handler function for status updates
func (h *handler) StatusMessage(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.MsgStatus, error) {
// get our params
bmStatus := &bmStatus{}
err := handlers.DecodeAndValidateForm(bmStatus, r)
if err != nil {
return nil, err
}
msgStatus, found := bmStatusMapping[bmStatus.Status]
if !found {
return nil, fmt.Errorf("unknown status '%d', must be one of 1, 2, 8 or 16", bmStatus.Status)
}
// write our status
status := h.Backend().NewMsgStatusForExternalID(channel, bmStatus.ID, msgStatus)
err = h.Backend().WriteMsgStatus(status)
if err != nil {
return nil, err
}
return []courier.MsgStatus{status}, courier.WriteStatusSuccess(w, r, status)
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(msg courier.Msg) (courier.MsgStatus, error) {
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
if username == "" {
return nil, fmt.Errorf("no username set for BM channel")
}
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if password == "" {
return nil, fmt.Errorf("no password set for BM channel")
}
apiKey := msg.Channel().StringConfigForKey(courier.ConfigAPIKey, "")
if apiKey == "" {
return nil, fmt.Errorf("no API key set for BM channel")
}
// build our request
form := url.Values{
"address": []string{msg.URN().Path()},
"senderaddress": []string{msg.Channel().Address()},
"message": []string{courier.GetTextAndAttachments(msg)},
}
req, err := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(username, password)
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
}
// get our external id
externalID, _ := jsonparser.GetString([]byte(rr.Body), "[0]", "id")
if externalID == "" {
return status, errors.Errorf("no external id returned in body")
}
status.SetStatus(courier.MsgWired)
status.SetExternalID(externalID)
return status, nil
}
type bmStatus struct {
ID string `validate:"required" name:"id"`
Status int `validate:"required" name:"status"`
}