File size: 6,241 Bytes
1e92f2d |
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 |
package mocktwilio
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"sync"
"time"
"github.com/target/goalert/notification/twilio"
"github.com/target/goalert/validation/validate"
)
// SMS represents an SMS message.
type SMS struct {
s *Server
msg twilio.Message
body string
statusURL string
destURL string
start time.Time
mx sync.Mutex
acceptCh chan bool
doneCh chan struct{}
}
func (s *Server) sendSMS(fromValue, to, body, statusURL, destURL string) (*SMS, error) {
fromNumber := s.getFromNumber(fromValue)
if statusURL != "" {
err := validate.URL("StatusCallback", statusURL)
if err != nil {
return nil, twilio.Exception{
Code: 11100,
Message: err.Error(),
}
}
s.mx.RLock()
_, hasCallback := s.callbacks["SMS:"+fromNumber]
s.mx.RUnlock()
if !hasCallback {
return nil, twilio.Exception{
Code: 21606,
Message: `The "From" phone number provided is not a valid, SMS-capable inbound phone number for your account.`,
}
}
}
if destURL != "" {
err := validate.URL("Callback", destURL)
if err != nil {
return nil, twilio.Exception{
Code: 11100,
Message: err.Error(),
}
}
}
// Use the RCS ID for the rest of the processing
s.mx.RLock()
rcsID := s.rcs[fromValue]
if rcsID != "" {
fromNumber = "rcs:" + rcsID
}
s.mx.RUnlock()
if strings.HasPrefix(fromNumber, "rcs:") {
to = "rcs:" + to
}
sms := &SMS{
s: s,
msg: twilio.Message{
To: to,
From: fromNumber,
Status: twilio.MessageStatusAccepted,
SID: s.id("SM"),
},
statusURL: statusURL,
destURL: destURL,
start: time.Now(),
body: body,
acceptCh: make(chan bool, 1),
doneCh: make(chan struct{}),
}
if strings.HasPrefix(fromValue, "MG") {
sms.msg.MessagingServiceSID = fromValue
} else {
sms.msg.From = fromValue
}
s.mx.Lock()
s.messages[sms.msg.SID] = sms
s.mx.Unlock()
s.smsInCh <- sms
return sms, nil
}
func (s *Server) serveNewMessage(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
sms, err := s.sendSMS(req.FormValue("From"), req.FormValue("To"), req.FormValue("Body"), req.FormValue("StatusCallback"), "")
if e := (twilio.Exception{}); errors.As(err, &e) {
apiError(400, w, &e)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data, err := json.Marshal(sms.cloneMessage())
if err != nil {
panic(err)
}
w.WriteHeader(201)
_, err = w.Write(data)
if err != nil {
panic(err)
}
}
func (s *Server) serveMessageStatus(w http.ResponseWriter, req *http.Request) {
id := strings.TrimSuffix(path.Base(req.URL.Path), ".json")
sms := s.sms(id)
if sms == nil {
http.NotFound(w, req)
return
}
err := json.NewEncoder(w).Encode(sms.cloneMessage())
if err != nil {
panic(err)
}
}
func (sms *SMS) updateStatus(stat twilio.MessageStatus) {
sms.mx.Lock()
sms.msg.Status = stat
switch stat {
case twilio.MessageStatusAccepted, twilio.MessageStatusQueued:
default:
if sms.msg.MessagingServiceSID == "" {
break
}
sms.msg.From = sms.s.getFromNumber(sms.msg.MessagingServiceSID)
}
sms.mx.Unlock()
if sms.statusURL == "" {
return
}
// attempt post to status callback
_, err := sms.s.post(sms.statusURL, sms.values(false))
if err != nil {
sms.s.errs <- err
}
}
func (sms *SMS) cloneMessage() *twilio.Message {
sms.mx.Lock()
defer sms.mx.Unlock()
msg := sms.msg
return &msg
}
func (s *Server) sms(id string) *SMS {
s.mx.RLock()
defer s.mx.RUnlock()
return s.messages[id]
}
func (sms *SMS) values(body bool) url.Values {
v := make(url.Values)
msg := sms.cloneMessage()
v.Set("MessageStatus", string(msg.Status))
v.Set("MessageSid", msg.SID)
v.Set("To", msg.To)
v.Set("From", msg.From)
if body {
v.Set("Body", sms.body)
}
return v
}
// SMS will return a channel that will be fed incoming SMS messages as they arrive.
func (s *Server) SMS() chan *SMS {
return s.smsCh
}
// SendSMS will cause an SMS to be sent to the given number with the contents of body.
//
// The to parameter must match a value passed to RegisterSMSCallback or an error is returned.
func (s *Server) SendSMS(from, to, body string) error {
s.mx.RLock()
cbURL := s.callbacks["SMS:"+to]
s.mx.RUnlock()
if cbURL == "" {
return fmt.Errorf(`unknown/unregistered destination (to) number "%s"`, to)
}
sms, err := s.sendSMS(from, to, body, "", cbURL)
if err != nil {
return err
}
<-sms.doneCh
return nil
}
func (sms *SMS) process() {
defer sms.s.workers.Done()
defer close(sms.doneCh)
if sms.s.wait(sms.s.cfg.MinQueueTime) {
return
}
sms.updateStatus(twilio.MessageStatusQueued)
if sms.s.wait(sms.s.cfg.MinQueueTime) {
return
}
sms.updateStatus(twilio.MessageStatusSending)
if sms.destURL != "" {
// inbound SMS
_, err := sms.s.post(sms.destURL, sms.values(true))
if err != nil {
sms.s.errs <- err
sms.updateStatus(twilio.MessageStatusUndelivered)
} else {
sms.updateStatus(twilio.MessageStatusDelivered)
}
return
}
select {
case <-sms.s.shutdown:
return
case sms.s.smsCh <- sms:
}
select {
case <-sms.s.shutdown:
return
case accepted := <-sms.acceptCh:
if accepted {
if strings.HasPrefix(sms.To(), "rcs:") {
sms.updateStatus(twilio.MessageStatusRead)
} else {
sms.updateStatus(twilio.MessageStatusDelivered)
}
} else {
sms.updateStatus(twilio.MessageStatusFailed)
}
}
}
// ID will return the unique ID for this SMS.
func (sms *SMS) ID() string {
return sms.msg.SID
}
// From returns the phone number the SMS was sent from.
func (sms *SMS) From() string {
return sms.msg.From
}
// To returns the phone number the SMS is being sent to.
func (sms *SMS) To() string {
return sms.msg.To
}
// Body returns the contents of the SMS message.
func (sms *SMS) Body() string {
return sms.body
}
// Accept will cause the SMS to be marked as delivered.
func (sms *SMS) Accept() {
sms.acceptCh <- true
close(sms.acceptCh)
}
// Reject will cause the SMS to be marked as failed.
func (sms *SMS) Reject() {
sms.acceptCh <- false
close(sms.acceptCh)
}
|