forked from njern/gonexmo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
336 lines (279 loc) · 8.67 KB
/
server.go
File metadata and controls
336 lines (279 loc) · 8.67 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package nexmo
import (
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"time"
)
// MessageType can be one of the following:
// - TextMessage
// - UnicodeMessage
// - BinaryMessage
type MessageType int
// Message types
const (
TextMessage = iota + 1
UnicodeMessage
BinaryMessage
)
var messageTypeMap = map[string]MessageType{
"text": TextMessage,
"unicode": UnicodeMessage,
"binary": BinaryMessage,
}
var messageTypeIntMap = map[MessageType]string{
TextMessage: "text",
UnicodeMessage: "unicode",
BinaryMessage: "binary",
}
func (m MessageType) String() string {
if m < 1 || m > 3 {
return "undefined"
}
return messageTypeIntMap[m]
}
// ReceivedMessage represents a message that was received from the Nexmo API.
type ReceivedMessage struct {
// Expected values are "text" or "binary".
Type MessageType
// Recipient number (your long virtual number).
To string
// Sender ID.
MSISDN string
// Optional unique identifier of a mobile network MCCMNC.
NetworkCode string
// Nexmo message ID.
ID string
// Time when Nexmo started to push the message to you.
Timestamp time.Time
// Parameters for conactenated messages:
Concatenated bool // Set to true if a MO concatenated message is detected.
Concat struct {
// Transaction reference. All message parts will share the same
//transaction reference.
Reference string
// Total number of parts in this concatenated message set.
Total int
// The part number of this message withing the set (starts at 1).
Part int
}
// When Type == text:
Text string // Content of the message
Keyword string // First word in the message body, typically used with short codes
// When type == binary:
// Content of the message.
Data []byte
// User Data Header.
UDH []byte
}
// DeliveryReceipt is a delivery receipt for a single SMS sent via the Nexmo API
type DeliveryReceipt struct {
To string `json:"to"`
NetworkCode string `json:"network-code"`
MessageID string `json:"messageId"`
MSISDN string `json:"msisdn"`
Status string `json:"status"`
ErrorCode string `json:"err-code"`
Price string `json:"price"`
SCTS time.Time `json:"scts"`
Timestamp time.Time `json:"message-timestamp"`
ClientReference string `json:"client-ref"`
}
// ParseReceivedMessage unmarshals and processes the form data in a Nexmo request
// and returns a DeliveryReceipt struct.
func ParseDeliveryReceipt(req *http.Request) (*DeliveryReceipt, error) {
err := req.ParseForm()
if err != nil {
return nil, fmt.Errorf("failed to parse form data: %v", err)
}
// Decode the form data
m := new(DeliveryReceipt)
m.To = req.FormValue("to")
m.NetworkCode = req.FormValue("network-code")
m.MessageID = req.FormValue("messageId")
m.MSISDN = req.FormValue("msisdn")
m.Status = req.FormValue("status")
m.ErrorCode = req.FormValue("err-code")
m.Price = req.FormValue("price")
m.ClientReference = req.FormValue("client-ref")
{
t, err := url.QueryUnescape(req.FormValue("scts"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'scts': %v", err)
}
m.SCTS, err = parseSCTS(t)
if err != nil {
return nil, err
}
}
{
t, err := url.QueryUnescape(req.FormValue("message-timestamp"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'message-timestamp': %v", err)
}
m.Timestamp, err = parseMessageTimestamp(t)
if err != nil {
return nil, err
}
}
return m, nil
}
func parseSCTS(t string) (time.Time, error) {
if t == "" {
return time.Time{}, nil
}
timestamp, err := time.Parse("0601021504", t)
if err != nil {
return time.Time{}, fmt.Errorf("failed to parse timestamp for field 'scts': %v", err)
}
return timestamp, nil
}
func parseMessageTimestamp(t string) (time.Time, error) {
if t == "" {
return time.Time{}, nil
}
// nexmo is just doing some crazy stuff lately
formats := []string{
"2006-01-02 15:04:05 -0700", // actually valid
"2006-01-02 15:04:05 0000", // where did the plus go
"2006-01-02 15:04:05 0000", // oh you forgot to URL encode it? very cool
"2006-01-02 15:04:05", // you know what, forget timezones
}
for _, f := range formats {
timestamp, err := time.Parse(f, t)
if err == nil {
return timestamp, nil
}
}
return time.Time{}, fmt.Errorf("failed to parse timestamp '%s' for field 'message-timestamp'", t)
}
// NewDeliveryHandler creates a new http.HandlerFunc that can be used to listen
// for delivery receipts from the Nexmo server. Any receipts received will be
// decoded and passed to the out chan.
func NewDeliveryHandler(out chan *DeliveryReceipt, verifyIPs bool) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if verifyIPs {
// Check if the request came from Nexmo
host, _, err := net.SplitHostPort(req.RemoteAddr)
if !IsTrustedIP(host) || err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
}
// Check if the query is empty. If it is, it's just Nexmo
// making sure our service is up, so we don't want to return
// an error.
if req.URL.RawQuery == "" {
return
}
receipt, err := ParseDeliveryReceipt(req)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
// Pass it out on the chan
out <- receipt
}
}
// ParseReceivedMessage unmarshals and processes the form data in a Nexmo request
// and returns a ReceivedMessage struct.
func ParseReceivedMessage(req *http.Request) (*ReceivedMessage, error) {
err := req.ParseForm()
if err != nil {
return nil, fmt.Errorf("failed to parse form data: %v", err)
}
// Decode the form data
m := new(ReceivedMessage)
switch t := req.FormValue("type"); t {
case "text":
m.Text, err = url.QueryUnescape(req.FormValue("text"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'text': %v", err)
}
m.Type = TextMessage
case "unicode":
m.Text, err = url.QueryUnescape(req.FormValue("text"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'text': %v", err)
}
m.Type = UnicodeMessage
case "binary":
// TODO: I have no idea if this data stuff works, as I'm unable to
// send data SMS messages.
data, err := url.QueryUnescape(req.FormValue("data"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'data': %v", err)
}
m.Data = []byte(data)
udh, err := url.QueryUnescape(req.FormValue("udh"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'udh': %v", err)
}
m.UDH = []byte(udh)
m.Type = BinaryMessage
default:
//error
return nil, fmt.Errorf("unrecognized message type %s", t)
}
m.To = req.FormValue("to")
m.MSISDN = req.FormValue("msisdn")
m.NetworkCode = req.FormValue("network-code")
m.ID = req.FormValue("messageId")
m.Keyword = req.FormValue("keyword")
t, err := url.QueryUnescape(req.FormValue("message-timestamp"))
if err != nil {
return nil, fmt.Errorf("failed to unescape field 'message-timestamp': %v", err)
}
// Convert the timestamp to a time.Time.
timestamp, err := time.Parse("2006-01-02 15:04:05", t)
if err != nil {
return nil, fmt.Errorf("failed to parse timestamp for field 'message-timestamp': %v", err)
}
m.Timestamp = timestamp
// TODO: I don't know if this works as I've been unable to send an SMS
// message longer than 160 characters that doesn't get concatenated
// automatically.
if req.FormValue("concat") == "true" {
m.Concatenated = true
m.Concat.Reference = req.FormValue("concat-ref")
m.Concat.Total, err = strconv.Atoi(req.FormValue("concat-total"))
if err != nil {
return nil, fmt.Errorf("failed to convert field 'concat-total' to int: %v", err)
}
m.Concat.Part, err = strconv.Atoi(req.FormValue("concat-part"))
if err != nil {
return nil, fmt.Errorf("failed to convert field 'concat-part' to int: %v", err)
}
}
return m, nil
}
// NewMessageHandler creates a new http.HandlerFunc that can be used to listen
// for new messages from the Nexmo server. Any new messages received will be
// decoded and passed to the out chan.
func NewMessageHandler(out chan *ReceivedMessage, verifyIPs bool) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if verifyIPs {
// Check if the request came from Nexmo
host, _, err := net.SplitHostPort(req.RemoteAddr)
if !IsTrustedIP(host) || err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
}
// Check if the query is empty. If it is, it's just Nexmo
// making sure our service is up, so we don't want to return
// an error.
if req.URL.RawQuery == "" {
return
}
message, err := ParseReceivedMessage(req)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
// Pass it out on the chan
out <- message
}
}