-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathhandler.go
214 lines (185 loc) · 6.48 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
204
205
206
207
208
209
210
211
212
213
214
package justcall
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/buger/jsonparser"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/urns"
)
var (
sendURL = "https://api.justcall.io/v1/texts/new"
maxMsgLength = 160
)
type handler struct {
handlers.BaseHandler
}
func newHandler() courier.ChannelHandler {
return &handler{handlers.NewBaseHandler(courier.ChannelType("JCL"), "JustCall")}
}
func init() {
courier.RegisterHandler(newHandler())
}
// Initialize implements courier.ChannelHandler
func (h *handler) Initialize(s courier.Server) error {
h.SetServer(s)
s.AddHandlerRoute(h, http.MethodPost, "receive", courier.ChannelLogTypeMsgReceive, handlers.JSONPayload(h, h.receiveMessage))
s.AddHandlerRoute(h, http.MethodPost, "status", courier.ChannelLogTypeMsgStatus, handlers.JSONPayload(h, h.statusMessage))
return nil
}
// {
// "data": {
// "type": "sms",
// "direction": "0",
// "justcall_number": "192XXXXXXXX",
// "contact_name": "Sushant Tripathi",
// "contact_number": "+91810XXXXXXX",
// "contact_email": "[email protected]",
// "is_contact": 1,
// "content": "Hey !",
// "signature": "35e89fc56b497xxxxxxxxxx8f7b27fe49d",
// "datetime": "2020-12-03 13:35:13",
// "delivery_status": "sent",
// "requestid": "1229153",
// "messageid": 26523491,
// "is_mms": "1",
// "mms": [
// {
// "media_url": "https://www.filepicker.io/api/file/p6j9ExQNWMCCYOQvHI",
// "content_type": "image/jpeg"
// },
// {
// "media_url": "https://www.filepicker.io/api/file/axNH43SFm7inN3iKDz",
// "content_type": "image/png"
// },
// {
// "media_url": "https://www.filepicker.io/api//file/cN95JZSM2ScSXGamlh",
// "content_type": "image/jpeg"
// }
// ],
// "agent_name": "Sales JustCall",
// "agent_id": 10636
// }
// }
type moPayload struct {
Data struct {
Type string `json:"type"`
Direction string `json:"direction"`
To string `json:"justcall_number"`
From string `json:"contact_number"`
Name string `json:"contact_name"`
Content string `json:"content"`
Datetime string `json:"datetime"`
Status string `json:"delivery_status"`
MessageID int32 `json:"messageid"`
MMS []struct {
MediaURL string `json:"media_url"`
ContentType string `json:"content_type"`
} `json:"mms"`
} `json:"data"`
}
func (h *handler) receiveMessage(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request, payload *moPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if payload.Data.Type != "sms" || payload.Data.Direction != "I" {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, c, w, r, "Ignoring request, no message")
}
dateString := payload.Data.Datetime
date := time.Now()
var err error
if dateString != "" {
date, err = time.Parse("2006-01-02 15:04:05", dateString)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, c, w, r, errors.New("invalid date format, must be RFC 3339"))
}
date = date.UTC()
}
urn, err := urns.ParsePhone(payload.Data.From, c.Country(), true, false)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, c, w, r, err)
}
// build our msg
msg := h.Backend().NewIncomingMsg(c, urn, payload.Data.Content, fmt.Sprint(payload.Data.MessageID), clog).WithReceivedOn(date)
if len(payload.Data.MMS) > 0 {
msg.WithAttachment(payload.Data.MMS[0].MediaURL)
}
// and finally write our message
return handlers.WriteMsgsAndResponse(ctx, h, []courier.MsgIn{msg}, w, r, clog)
}
var statusMapping = map[string]courier.MsgStatus{
"delivered": courier.MsgStatusDelivered,
"sent": courier.MsgStatusSent,
"undelivered": courier.MsgStatusErrored,
"failed": courier.MsgStatusFailed,
}
func (h *handler) statusMessage(ctx context.Context, c courier.Channel, w http.ResponseWriter, r *http.Request, payload *moPayload, clog *courier.ChannelLog) ([]courier.Event, error) {
if payload.Data.Type != "sms" || payload.Data.Direction != "O" {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, c, w, r, "Ignoring request, no message")
}
msgStatus, found := statusMapping[payload.Data.Status]
if !found {
return nil, handlers.WriteAndLogRequestError(ctx, h, c, w, r, fmt.Errorf("unknown status '%s', must be one of send, delivered, undelivered, failed", payload.Data.Status))
}
// write our status
status := h.Backend().NewStatusUpdateByExternalID(c, fmt.Sprint(payload.Data.MessageID), msgStatus, clog)
return handlers.WriteMsgStatusAndResponse(ctx, h, c, status, w, r)
}
type mtPayload struct {
From string `json:"from"`
To string `json:"to"`
Body string `json:"body"`
MediaURL string `json:"media_url,omitempty"`
}
func (h *handler) Send(ctx context.Context, msg courier.MsgOut, res *courier.SendResult, clog *courier.ChannelLog) error {
apiKey := msg.Channel().StringConfigForKey(courier.ConfigAPIKey, "")
apiSecret := msg.Channel().StringConfigForKey(courier.ConfigSecret, "")
if apiKey == "" || apiSecret == "" {
return courier.ErrChannelConfig
}
mediaURLs := make([]string, 0, 5)
text := msg.Text()
if len(msg.Attachments()) <= 5 {
for _, a := range msg.Attachments() {
_, url := handlers.SplitAttachment(a)
mediaURLs = append(mediaURLs, url)
}
} else {
text = handlers.GetTextAndAttachments(msg)
}
payload := mtPayload{From: msg.Channel().Address(), To: msg.URN().Path(), Body: text}
if len(mediaURLs) > 0 {
payload.MediaURL = strings.Join(mediaURLs, ",")
}
req, err := http.NewRequest(http.MethodPost, sendURL, bytes.NewReader(jsonx.MustMarshal(payload)))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("%s:%s", apiKey, apiSecret))
resp, respBody, err := h.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 == 5 {
return courier.ErrConnectionFailed
} else if resp.StatusCode/100 != 2 {
return courier.ErrResponseStatus
}
respStatus, err := jsonparser.GetString(respBody, "status")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("status"))
}
if respStatus != "success" {
return courier.ErrResponseContent
}
externalID, err := jsonparser.GetInt(respBody, "id")
if err != nil {
clog.Error(courier.ErrorResponseValueMissing("id"))
} else {
res.AddExternalID(strconv.Itoa(int(externalID)))
}
return nil
}