forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
dmark.go
155 lines (127 loc) · 4.55 KB
/
dmark.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 dmark
import (
"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"
)
var sendURL = "https://smsapi1.dmarkmobile.com/sms"
// DMark supports up to 3 segment messages
const maxMsgLength = 453
func init() {
courier.RegisterHandler(NewHandler())
}
type handler struct {
handlers.BaseHandler
}
// NewHandler returns a new DMark Handler
func NewHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("DK"), "dmark")}
}
type receiveRequest struct {
MSISDN string `validate:"required" name:"msisdn"`
Text string `validate:"required" name:"text"`
ShortCode string `validate:"required" name:"short_code"`
TStamp string `validate:"required" name:"tstamp"`
}
type statusRequest struct {
ID string `validate:"required" name:"id"`
Status string `validate:"required" name:"status"`
}
var statusMapping = map[string]courier.MsgStatusValue{
"1": courier.MsgDelivered,
"2": courier.MsgErrored,
"4": courier.MsgSent,
"8": courier.MsgSent,
"16": courier.MsgErrored,
}
// 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, "POST", "receive", h.ReceiveMessage)
if err != nil {
return err
}
return s.AddUpdateStatusRoute(h, "POST", "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
dkMsg := &receiveRequest{}
err := handlers.DecodeAndValidateForm(dkMsg, r)
if err != nil {
return nil, err
}
// create our date from the timestamp "2017-10-26T15:51:32.906335Z"
date, err := time.Parse("2006-01-02T15:04:05.999999Z", dkMsg.TStamp)
if err != nil {
return nil, fmt.Errorf("invalid tstamp: %s", dkMsg.TStamp)
}
// create our URN
urn := urns.NewTelURNForCountry(dkMsg.MSISDN, channel.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, dkMsg.Text).WithReceivedOn(date)
// 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)
}
// 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
dkStatus := &statusRequest{}
err := handlers.DecodeAndValidateForm(dkStatus, r)
if err != nil {
return nil, err
}
msgStatus, found := statusMapping[dkStatus.Status]
if !found {
return nil, fmt.Errorf("unknown status '%s', must be one of '1','2','4','8' or '16'", dkStatus.Status)
}
// write our status
status := h.Backend().NewMsgStatusForExternalID(channel, dkStatus.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) {
// get our authentication token
auth := msg.Channel().StringConfigForKey(courier.ConfigAuthToken, "")
if auth == "" {
return nil, fmt.Errorf("no authorization token set for DK channel")
}
dlrURL := fmt.Sprintf("%s%s%s/status?id=%s&status=%%s", h.Server().Config().BaseURL, "/c/dk/", msg.Channel().UUID(), msg.ID().String())
status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)
parts := handlers.SplitMsg(msg.Text(), maxMsgLength)
for _, part := range parts {
form := url.Values{
"sender": []string{strings.TrimLeft(msg.Channel().Address(), "+")},
"receiver": []string{strings.TrimLeft(msg.URN().Path(), "+")},
"text": []string{part},
"dlr_url": []string{dlrURL},
}
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("Authorization", fmt.Sprintf("Token %s", auth))
rr, err := utils.MakeHTTPRequest(req)
// record our status and log
status.AddLog(courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err))
if err != nil {
return status, nil
}
// this was wired successfully
status.SetStatus(courier.MsgWired)
}
return status, nil
}