forked from nyaruka/courier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
288 lines (243 loc) · 7.61 KB
/
base.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package handlers
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
"github.com/gorilla/schema"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/utils"
"github.com/nyaruka/gocommon/urns"
validator "gopkg.in/go-playground/validator.v9"
)
var base64Regex, _ = regexp.Compile("^([a-zA-Z0-9+/=]{4})+$")
var base64Encoding = base64.StdEncoding.Strict()
// BaseHandler is the base class for most handlers, it just stored the server, name and channel type for the handler
type BaseHandler struct {
channelType courier.ChannelType
name string
server courier.Server
backend courier.Backend
}
// NewBaseHandler returns a newly constructed BaseHandler with the passed in parameters
func NewBaseHandler(channelType courier.ChannelType, name string) BaseHandler {
return BaseHandler{channelType: channelType, name: name}
}
// SetServer can be used to change the server on a BaseHandler
func (h *BaseHandler) SetServer(server courier.Server) {
h.server = server
h.backend = server.Backend()
}
// Server returns the server instance on the BaseHandler
func (h *BaseHandler) Server() courier.Server {
return h.server
}
// Backend returns the backend instance on the BaseHandler
func (h *BaseHandler) Backend() courier.Backend {
return h.backend
}
// ChannelType returns the channel type that this handler deals with
func (h *BaseHandler) ChannelType() courier.ChannelType {
return h.channelType
}
// ChannelName returns the name of the channel this handler deals with
func (h *BaseHandler) ChannelName() string {
return h.name
}
var (
decoder = schema.NewDecoder()
validate = validator.New()
)
func init() {
decoder.IgnoreUnknownKeys(true)
decoder.SetAliasTag("name")
}
// NameFromFirstLastUsername is a utility function to build a contact's name from the passed
// in values, all of which can be empty
func NameFromFirstLastUsername(first string, last string, username string) string {
if first != "" && last != "" {
return fmt.Sprintf("%s %s", first, last)
} else if first != "" {
return first
} else if last != "" {
return last
} else if username != "" {
return username
}
return ""
}
// Validate validates the passe din struct using our shared validator instance
func Validate(form interface{}) error {
return validate.Struct(form)
}
// DecodeAndValidateForm takes the passed in form and attempts to parse and validate it from the
// POST parameters of the passed in request
func DecodeAndValidateForm(form interface{}, r *http.Request) error {
err := r.ParseForm()
if err != nil {
return err
}
err = decoder.Decode(form, r.Form)
if err != nil {
return err
}
// check our input is valid
err = validate.Struct(form)
if err != nil {
return err
}
return nil
}
// DecodeAndValidateQueryParams takes the passed in form and attempts to parse and validate it from the
// GET parameters of the passed in request
func DecodeAndValidateQueryParams(form interface{}, r *http.Request) error {
err := decoder.Decode(form, r.URL.Query())
if err != nil {
return err
}
// check our input is valid
err = validate.Struct(form)
if err != nil {
return err
}
return nil
}
// DecodeAndValidateJSON takes the passed in envelope and tries to unmarshal it from the body
// of the passed in request, then validating it
func DecodeAndValidateJSON(envelope interface{}, r *http.Request) error {
// read our body
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 100000))
defer r.Body.Close()
if err != nil {
return fmt.Errorf("unable to read request body: %s", err)
}
// try to decode our envelope
if err = json.Unmarshal(body, envelope); err != nil {
return fmt.Errorf("unable to parse request JSON: %s", err)
}
// check our input is valid
err = validate.Struct(envelope)
if err != nil {
return fmt.Errorf("request JSON doesn't match required schema: %s", err)
}
return nil
}
// DecodeAndValidateXML takes the passed in envelope and tries to unmarshal it from the body
// of the passed in request, then validating it
func DecodeAndValidateXML(envelope interface{}, r *http.Request) error {
// read our body
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 100000))
defer r.Body.Close()
if err != nil {
return fmt.Errorf("unable to read request body: %s", err)
}
// try to decode our envelope
if err = xml.Unmarshal(body, envelope); err != nil {
return fmt.Errorf("unable to parse request XML: %s", err)
}
// check our input is valid
err = validate.Struct(envelope)
if err != nil {
return fmt.Errorf("request XML doesn't match required schema: %s", err)
}
return nil
}
/*
DecodePossibleBase64 detects and decodes a possibly base64 encoded messages by doing:
* check it's at least 60 characters
* check its length is divisible by 4
* check that there's no whitespace
* check the decoded string contains at least 50% ascii
*/
func DecodePossibleBase64(original string) string {
stripped := strings.TrimSpace(strings.Replace(strings.Replace(original, "\r", "", -1), "\n", "", -1))
length := len([]rune(stripped))
if length < 60 || length%4 != 0 {
return original
}
if !base64Regex.MatchString(stripped[:length-4]) {
return original
}
decodedBytes, err := base64Encoding.DecodeString(stripped)
if err != nil {
return original
}
decoded := utils.DecodeUTF8(decodedBytes)
numASCIIChars := 0
for _, c := range decoded {
if c <= 127 {
numASCIIChars++
}
}
if float32(numASCIIChars)/float32(len([]rune(decoded))) < 0.5 {
return original
}
return decoded
}
// SplitMsg splits the passed in string into segments that are at most max length
func SplitMsg(text string, max int) []string {
// smaller than our max, just return it
if len(text) <= max {
return []string{text}
}
parts := make([]string, 0, 2)
part := bytes.Buffer{}
for _, r := range text {
part.WriteRune(r)
if part.Len() == max || (part.Len() > max-6 && r == ' ') {
parts = append(parts, strings.TrimSpace(part.String()))
part.Reset()
}
}
if part.Len() > 0 {
parts = append(parts, strings.TrimSpace(part.String()))
}
return parts
}
// NewTelQueryReceiveHandler creates a new receive handler given the passed in text and from fields
func NewTelQueryReceiveHandler(h BaseHandler, fromField string, textField string) courier.ChannelHandleFunc {
// ReceiveMessage is our HTTP handler function for incoming messages
return func(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
text := r.URL.Query().Get(textField)
from := r.URL.Query().Get(fromField)
if from == "" {
return nil, courier.WriteAndLogRequestError(ctx, w, r, c, fmt.Errorf("missing required field '%s'", fromField))
}
// create our URN
urn := urns.NewTelURNForCountry(from, c.Country())
// build our msg
msg := h.Backend().NewIncomingMsg(c, urn, text).WithReceivedOn(time.Now().UTC())
// and finally queue our message
err := h.Backend().WriteMsg(ctx, msg)
if err != nil {
return nil, err
}
return []courier.Event{msg}, courier.WriteMsgSuccess(ctx, w, r, []courier.Msg{msg})
}
}
// GetTextAndAttachments returns both the text of our message as well as any attachments, newline delimited
func GetTextAndAttachments(m courier.Msg) string {
buf := bytes.NewBuffer([]byte(m.Text()))
for _, a := range m.Attachments() {
_, url := SplitAttachment(a)
buf.WriteString("\n")
buf.WriteString(url)
}
return buf.String()
}
// SplitAttachment takes an attachment string and returns the media type and URL for the attachment
func SplitAttachment(attachment string) (string, string) {
parts := strings.SplitN(attachment, ":", 2)
if len(parts) < 2 {
return "", parts[0]
}
return parts[0], parts[1]
}