-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarrier_telnyx.go
469 lines (413 loc) · 11.6 KB
/
carrier_telnyx.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
// TelnyxHandler implements CarrierHandler for Telnyx
type TelnyxHandler struct {
BaseCarrierHandler
gateway *Gateway
carrier *Carrier
password string
}
// NewTelnyxHandler initializes a new TelnyxHandler
func NewTelnyxHandler(gateway *Gateway, carrier *Carrier, decryptedUsername string, decryptedPassword string) *TelnyxHandler {
return &TelnyxHandler{
BaseCarrierHandler: BaseCarrierHandler{name: "telnyx"},
gateway: gateway,
carrier: carrier,
password: decryptedPassword,
}
}
// TelnyxMessage represents the structure of Telnyx outbound messages
type TelnyxMessage struct {
From string `json:"from"`
To string `json:"to"`
Text string `json:"text,omitempty"`
Subject string `json:"subject,omitempty"`
MediaUrls []string `json:"media_urls,omitempty"`
MessagingProfileID string `json:"messaging_profile_id,omitempty"`
WebhookURL string `json:"webhook_url,omitempty"`
WebhookFailoverURL string `json:"webhook_failover_url,omitempty"`
}
// TelnyxResponse represents the response from Telnyx API
type TelnyxResponse struct {
Data TelnyxMessageData `json:"data"`
}
type TelnyxMessageData struct {
ID string `json:"id"`
// Add other relevant fields as needed
}
// Inbound handles incoming Telnyx webhooks for MMS and SMS messages.
func (h *TelnyxHandler) Inbound(c iris.Context) error {
// Parse the Telnyx webhook JSON payload
var webhookPayload TelnyxWebhookPayload
if err := c.ReadBody(&webhookPayload); err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.Inbound.Telnyx",
"GenericError",
logrus.ErrorLevel,
nil,
err,
))
c.StatusCode(http.StatusBadRequest)
return nil
}
if len(webhookPayload.Data.Payload.To) <= 0 {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.Inbound.Telnyx",
"CarrierNoDestinations",
logrus.ErrorLevel,
nil,
))
c.StatusCode(http.StatusBadRequest)
return nil
}
if webhookPayload.Data.EventType != "message.received" {
// ignore delivery?? or log it?? todo
c.StatusCode(http.StatusOK)
return nil
}
// Extract necessary fields
from := webhookPayload.Data.Payload.From.PhoneNumber
to := webhookPayload.Data.Payload.To[0].PhoneNumber
body := webhookPayload.Data.Payload.Text
messageID := webhookPayload.Data.Payload.ID
// messagingProfileID := webhookPayload.Data.Payload.MessagingProfileID // if needed
numMedia := len(webhookPayload.Data.Payload.Media)
var files []MsgFile
if numMedia > 0 {
ff := h.fetchTelnyxMediaFiles(webhookPayload.Data.Payload.Media, messageID)
if len(ff) <= 0 {
c.StatusCode(http.StatusBadRequest)
return nil
}
files = ff
}
// Handle MMS if media files are present
if numMedia > 0 && len(files) > 0 {
msg := MsgQueueItem{
To: to,
From: from,
ReceivedTimestamp: time.Now(),
Type: MsgQueueItemType.MMS,
Files: files,
SkipNumberCheck: false,
LogID: messageID,
}
//h.gateway.MM4Server.msgToClientChannel <- mm4Message
h.gateway.Router.CarrierMsgChan <- msg
}
// Handle SMS if body is present
if strings.TrimSpace(body) != "" {
smsMessages := splitSMS(body, 140)
for _, smsBody := range smsMessages {
sms := MsgQueueItem{
To: to,
From: from,
ReceivedTimestamp: time.Now(),
Type: MsgQueueItemType.SMS,
Message: smsBody,
LogID: messageID,
}
h.gateway.Router.CarrierMsgChan <- sms
}
}
// Respond with HTTP 200 OK
c.StatusCode(http.StatusOK)
return nil
}
// TelnyxWebhookPayload represents the structure of Telnyx inbound webhook
type TelnyxWebhookPayload struct {
Data TelnyxEventData `json:"data"`
}
type TelnyxEventData struct {
EventType string `json:"event_type"`
ID string `json:"id"`
OccurredAt string `json:"occurred_at"`
Payload TelnyxMessagePayload `json:"payload"`
RecordType string `json:"record_type"`
}
type TelnyxMessagePayload struct {
Direction string `json:"direction"`
ID string `json:"id"`
From TelnyxPhoneNumber `json:"from"`
To []TelnyxPhoneNumber `json:"to"`
Text string `json:"text"`
Media []TelnyxMedia `json:"media"`
// Add other relevant fields as needed
}
type TelnyxPhoneNumber struct {
PhoneNumber string `json:"phone_number"`
Carrier string `json:"carrier"`
LineType string `json:"line_type"`
Status string `json:"status"`
}
type TelnyxMedia struct {
ContentType string `json:"content_type"`
URL string `json:"url"`
}
// fetchTelnyxMediaFiles retrieves media files from Telnyx webhook payload
func (h *TelnyxHandler) fetchTelnyxMediaFiles(media []TelnyxMedia, messageID string) []MsgFile {
var files []MsgFile
for _, m := range media {
contentType := m.ContentType
mediaURL := m.URL
parts := strings.Split(contentType, "/")
if len(parts) != 2 {
// todo?
continue
}
/*extension := parts[1]*/
mediaSid := path.Base(mediaURL)
filename := fmt.Sprintf("%s" /*.%s"*/, mediaSid /*, extension*/) // e.g., mediaSid.jpg
// Fetch the media content
contentBytes, err := fetchMediaContentTelnyx(mediaURL)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.FetchMedia.Telnyx",
"CarrierFetchMediaError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": messageID,
}, mediaURL,
))
continue
}
// Create the MsgFile struct
file := MsgFile{
Filename: filename,
ContentType: contentType,
Content: contentBytes,
}
files = append(files, file)
}
return files
}
// fetchMediaContentTelnyx retrieves media content from Telnyx URL
func fetchMediaContentTelnyx(mediaURL string) ([]byte, error) {
req, err := http.NewRequest("GET", mediaURL, nil)
if err != nil {
return nil, err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Non-OK HTTP status: %s", resp.Status)
}
contentBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading media content: %w", err)
}
return contentBytes, nil
}
// SendSMS sends an SMS message via Telnyx API
func (h *TelnyxHandler) SendSMS(sms *MsgQueueItem) error {
// Construct the TelnyxMessage payload
message := TelnyxMessage{
From: sms.From,
To: sms.To,
Text: sms.Message,
// MessagingProfileID: os.Getenv("TELNYX_MESSAGING_PROFILE_ID"), // If needed
// WebhookURL: "https://yourwebhook.url", // Optional
}
// Serialize to JSON
payloadBytes, err := json.Marshal(message)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return err
}
// Create HTTP request
req, err := http.NewRequest("POST", "https://api.telnyx.com/v2/messages", bytes.NewBuffer(payloadBytes))
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return err
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+h.password)
// Perform the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return err
}
defer resp.Body.Close()
// Read and parse response
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return errors.New("failed to send SMS via Telnyx")
}
// Optionally, parse the response to get message ID
var telnyxResp TelnyxResponse
if err := json.Unmarshal(bodyBytes, &telnyxResp); err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendSMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": sms.LogID,
}, err,
))
return err
}
/*logf.Level = logrus.InfoLevel
logf.Message = fmt.Sprintf(LogMessages.Transaction, "outbound", "telnyx", sms.From, sms.To)
logf.AddField("telnyxMessageID", telnyxResp.Data.ID)
logf.AddField("from", sms.From)
logf.AddField("to", sms.To)
logf.Print()*/
return nil
}
// SendMMS sends an MMS message via Telnyx API
func (h *TelnyxHandler) SendMMS(mms *MsgQueueItem) error {
// Construct the TelnyxMessage payload
message := TelnyxMessage{
From: mms.From,
To: mms.To,
Text:/*string(mms.Msg)*/ "",
Subject: "Picture", // Or derive from your context
MediaUrls: []string{},
}
var mediaUrls []string
if len(mms.Files) > 0 {
for _, i := range mms.Files {
if strings.Contains(i.ContentType, "application/smil") {
continue
}
id, err := h.gateway.saveMsgFileMedia(i)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendMMS.Telnyx",
"SaveMediaError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": mms.LogID,
}, err,
))
return err
}
mediaUrls = append(mediaUrls, os.Getenv("SERVER_ADDRESS")+"/media/"+strconv.Itoa(int(id)))
}
message.MediaUrls = mediaUrls
}
// Optionally, set MessagingProfileID if sending alphanumeric messages
messagingProfileID := os.Getenv("TELNYX_MESSAGING_PROFILE_ID")
if messagingProfileID != "" {
message.MessagingProfileID = messagingProfileID
}
// Serialize to JSON
payloadBytes, err := json.Marshal(message)
if err != nil {
return err
}
// Create HTTP request
req, err := http.NewRequest("POST", "https://api.telnyx.com/v2/messages", bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+h.password)
// Perform the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
var lm = h.gateway.LogManager
lm.SendLog(lm.BuildLog(
"Carrier.SendMMS.Telnyx",
"GenericError",
logrus.ErrorLevel,
map[string]interface{}{
"logID": mms.LogID,
}, err,
))
return err
}
defer resp.Body.Close()
// Read and parse response
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.New("failed to read response from Telnyx")
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return errors.New("failed to send MMS via Telnyx")
}
// Optionally, parse the response to get message ID
var telnyxResp TelnyxResponse
if err := json.Unmarshal(bodyBytes, &telnyxResp); err != nil {
return err
}
/*logf.AddField("telnyxMessageID", telnyxResp.Data.ID)
logf.AddField("from", mms.From)
logf.AddField("to", mms.To)
logf.Print()*/
return nil
}