-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandler.go
203 lines (166 loc) · 6.02 KB
/
handler.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
package discord
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/urns"
)
const (
jsonMimeTypeType = "application/json"
urlEncodedMimeType = "application/x-www-form-urlencoded"
)
func init() {
courier.RegisterHandler(newHandler())
}
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("DS"), "Discord")}
}
// Initialize is called by the engine once everything is loaded
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, h.receiveMessage)
sentHandler := h.buildStatusHandler("sent")
s.AddHandlerRoute(h, http.MethodPost, "sent", courier.ChannelLogTypeMsgStatus, sentHandler)
deliveredHandler := h.buildStatusHandler("delivered")
s.AddHandlerRoute(h, http.MethodPost, "delivered", courier.ChannelLogTypeMsgStatus, deliveredHandler)
failedHandler := h.buildStatusHandler("failed")
s.AddHandlerRoute(h, http.MethodPost, "failed", courier.ChannelLogTypeMsgStatus, failedHandler)
return nil
}
// utility function to grab the form value for either the passed in name (if non-empty) or the first set
// value from defaultNames
func getFormField(form url.Values, name string) string {
if name != "" {
values, found := form[name]
if found {
return values[0]
}
}
return ""
}
// 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, clog *courier.ChannelLog) ([]courier.Event, error) {
var err error
var from, text string
// parse our form
err = r.ParseForm()
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("invalid request: %w", err))
}
from = getFormField(r.Form, "from")
text = getFormField(r.Form, "text")
// must have from field
if from == "" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("must have one of 'sender' or 'from' set"))
}
if text == "" {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("must have 'text' set"))
}
// if we have a date, parse it
date := time.Now()
// create our URN
urn, err := urns.New(urns.Discord, from)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// build our msg
msg := h.Backend().NewIncomingMsg(channel, urn, text, "", clog).WithReceivedOn(date)
for _, attachment := range r.Form["attachments"] {
msg.WithAttachment(attachment)
}
// and finally write our message
return handlers.WriteMsgsAndResponse(ctx, h, []courier.MsgIn{msg}, w, r, clog)
}
// buildStatusHandler deals with building a handler that takes what status is received in the URL
func (h *handler) buildStatusHandler(status string) courier.ChannelHandleFunc {
return func(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request, clog *courier.ChannelLog) ([]courier.Event, error) {
return h.receiveStatus(ctx, status, channel, w, r, clog)
}
}
type statusForm struct {
ID int64 `name:"id" validate:"required"`
}
var statusMappings = map[string]courier.MsgStatus{
"failed": courier.MsgStatusFailed,
"sent": courier.MsgStatusSent,
"delivered": courier.MsgStatusDelivered,
}
// receiveStatus is our HTTP handler function for status updates
func (h *handler) receiveStatus(ctx context.Context, statusString string, channel courier.Channel, w http.ResponseWriter, r *http.Request, clog *courier.ChannelLog) ([]courier.Event, error) {
form := &statusForm{}
err := handlers.DecodeAndValidateForm(form, r)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
// get our status
msgStatus, found := statusMappings[strings.ToLower(statusString)]
if !found {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, fmt.Errorf("unknown status '%s', must be one failed, sent or delivered", statusString))
}
// write our status
status := h.Backend().NewStatusUpdate(channel, courier.MsgID(form.ID), msgStatus, clog)
return handlers.WriteMsgStatusAndResponse(ctx, h, channel, status, w, r)
}
func (h *handler) Send(ctx context.Context, msg courier.MsgOut, res *courier.SendResult, clog *courier.ChannelLog) error {
sendURL := msg.Channel().StringConfigForKey(courier.ConfigSendURL, "")
if sendURL == "" {
return courier.ErrChannelConfig
}
sendMethod := http.MethodPost
contentTypeHeader := jsonMimeTypeType
attachmentURLs := []string{}
for _, attachment := range msg.Attachments() {
_, attachmentURL := handlers.SplitAttachment(attachment)
attachmentURLs = append(attachmentURLs, attachmentURL)
}
// build our request
type OutputMessage struct {
ID string `json:"id"`
Text string `json:"text"`
To string `json:"to"`
Channel string `json:"channel"`
Attachments []string `json:"attachments"`
QuickReplies []string `json:"quick_replies"`
}
ourMessage := OutputMessage{
ID: msg.ID().String(),
Text: msg.Text(),
To: msg.URN().Path(),
Channel: string(msg.Channel().UUID()),
Attachments: attachmentURLs,
QuickReplies: handlers.TextOnlyQuickReplies(msg.QuickReplies()),
}
var body io.Reader
marshalled, err := json.Marshal(ourMessage)
if err != nil {
return err
}
body = bytes.NewReader(marshalled)
req, err := http.NewRequest(sendMethod, sendURL, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", contentTypeHeader)
authorization := msg.Channel().StringConfigForKey(courier.ConfigSendAuthorization, "")
if authorization != "" {
req.Header.Set("Authorization", authorization)
}
resp, _, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 == 5 {
return courier.ErrConnectionFailed
} else if resp.StatusCode/100 != 2 {
return courier.ErrResponseStatus
}
return nil
}