forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 2
/
shaqodoon.go
191 lines (157 loc) · 5.55 KB
/
shaqodoon.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
package shaqodoon
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"
"github.com/pkg/errors"
)
/*
POST /api/v1/shaqodoon/received/uuid/
from=252634101111&text=Msg
*/
func init() {
courier.RegisterHandler(NewHandler())
}
type handler struct {
handlers.BaseHandler
}
// NewHandler returns a new External handler
func NewHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("SQ"), "Shaqodoon")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddReceiveMsgRoute(h, "POST", "receive", h.ReceiveMessage)
return nil
}
// 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) {
shaqodoonMessage := &shaqodoonMessage{}
handlers.DecodeAndValidateQueryParams(shaqodoonMessage, r)
// if this is a post, also try to parse the form body
if r.Method == http.MethodPost {
handlers.DecodeAndValidateForm(shaqodoonMessage, r)
}
// validate whether our required fields are present
err := handlers.Validate(shaqodoonMessage)
if err != nil {
return nil, courier.WriteError(w, r, err)
}
// must have one of from or sender set, error if neither
sender := shaqodoonMessage.From
if sender == "" {
return nil, courier.WriteError(w, r, errors.New("must have one of 'sender' or 'from' set"))
}
// if we have a date, parse it
dateString := shaqodoonMessage.Date
if dateString == "" {
dateString = shaqodoonMessage.Time
}
date := time.Now()
if dateString != "" {
date, err = time.Parse(time.RFC3339Nano, dateString)
if err != nil {
return nil, courier.WriteError(w, r, errors.New("invalid date format, must be RFC 3339"))
}
}
// create our URN
urn := urns.NewTelURNForCountry(sender, channel.Country())
if err != nil {
return nil, courier.WriteError(w, r, err)
}
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, shaqodoonMessage.Text).WithReceivedOn(date)
// and write it
err = h.Backend().WriteMsg(msg)
if err != nil {
return nil, err
}
return []courier.ReceiveEvent{msg}, courier.WriteMsgSuccess(w, r, msg)
}
type shaqodoonMessage struct {
From string `name:"from"`
Text string `name:"text"`
Date string `name:"date"`
Time string `name:"time"`
}
// buildStatusHandler deals with building a handler that takes what status is received in the URL
func (h *handler) buildStatusHandler(status string) courier.ChannelUpdateStatusFunc {
return func(channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.MsgStatus, error) {
return h.StatusMessage(status, channel, w, r)
}
}
// StatusMessage is our HTTP handler function for status updates
func (h *handler) StatusMessage(statusString string, channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.MsgStatus, error) {
statusForm := &statusForm{}
handlers.DecodeAndValidateQueryParams(statusForm, r)
// if this is a post, also try to parse the form body
if r.Method == http.MethodPost {
handlers.DecodeAndValidateForm(statusForm, r)
}
// validate whether our required fields are present
err := handlers.Validate(statusForm)
if err != nil {
return nil, courier.WriteError(w, r, err)
}
// get our id
msgStatus, found := statusMappings[strings.ToLower(statusString)]
if !found {
return nil, courier.WriteError(w, r, fmt.Errorf("unknown status '%s', must be one failed, sent or delivered", statusString))
}
// write our status
status := h.Backend().NewMsgStatusForID(channel, courier.NewMsgID(statusForm.ID), msgStatus)
err = h.Backend().WriteMsgStatus(status)
if err != nil {
return nil, err
}
return []courier.MsgStatus{status}, courier.WriteStatusSuccess(w, r, status)
}
type statusForm struct {
ID int64 `name:"id" validate:"required"`
}
var statusMappings = map[string]courier.MsgStatusValue{
"failed": courier.MsgFailed,
"sent": courier.MsgSent,
"delivered": courier.MsgDelivered,
}
// SendMsg sends the passed in message, returning any error
func (h *handler) SendMsg(msg courier.Msg) (courier.MsgStatus, error) {
sendURL := msg.Channel().StringConfigForKey(courier.ConfigSendURL, "")
if sendURL == "" {
return nil, fmt.Errorf("no send url set for SQ channel")
}
username := msg.Channel().StringConfigForKey(courier.ConfigUsername, "")
if username == "" {
return nil, fmt.Errorf("no username set for SQ channel")
}
password := msg.Channel().StringConfigForKey(courier.ConfigPassword, "")
if password == "" {
return nil, fmt.Errorf("no password set for SQ channel")
}
// build our request
form := url.Values{
"from": []string{strings.TrimPrefix(msg.Channel().Address(), "+")},
"msg": []string{courier.GetTextAndAttachments(msg)},
"to": []string{strings.TrimPrefix(msg.URN().Path(), "+")},
"username": []string{username},
"password": []string{password},
}
encodedForm := form.Encode()
sendURL = fmt.Sprintf("%s?%s", sendURL, encodedForm)
req, err := http.NewRequest(http.MethodGet, sendURL, nil)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr, err := utils.MakeInsecureHTTPRequest(req)
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 {
status.SetStatus(courier.MsgWired)
}
return status, nil
}