| 1 |
// Package twilio talks to the Twilio API to make phone calls (for the "Call" feature) and to |
| 2 |
// verify phone numbers. It holds the Twilio configuration, so that this functionality is |
| 3 |
// decoupled from the ntfy server. |
| 4 |
package twilio |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"strings" |
| 13 |
|
| 14 |
"heckel.io/ntfy/v2/log" |
| 15 |
"heckel.io/ntfy/v2/util" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
tagTwilio = "twilio" |
| 20 |
) |
| 21 |
|
| 22 |
// Client is the Twilio API client |
| 23 |
type Client struct { |
| 24 |
config *Config |
| 25 |
} |
| 26 |
|
| 27 |
// NewClient creates a new Twilio Client with the given config |
| 28 |
func NewClient(config *Config) *Client { |
| 29 |
return &Client{config: config} |
| 30 |
} |
| 31 |
|
| 32 |
// Call calls the Twilio API to make a phone call to the given phone number, using the given data |
| 33 |
func (c *Client) Call(to string, data *CallData) error { |
| 34 |
tmpl := defaultCallFormatTemplate |
| 35 |
if c.config.CallFormat != nil { |
| 36 |
tmpl = c.config.CallFormat |
| 37 |
} |
| 38 |
var bodyBuf bytes.Buffer |
| 39 |
if err := tmpl.Execute(&bodyBuf, data.escaped()); err != nil { |
| 40 |
log.Tag(tagTwilio).Err(err).Warn("Error executing Twilio call format template") |
| 41 |
return err |
| 42 |
} |
| 43 |
body := bodyBuf.String() |
| 44 |
form := url.Values{} |
| 45 |
form.Set("From", c.config.PhoneNumber) |
| 46 |
form.Set("To", to) |
| 47 |
form.Set("Twiml", body) |
| 48 |
ev := log.Tag(tagTwilio). |
| 49 |
Field("twilio_to", to). |
| 50 |
FieldIf("twilio_body", body, log.TraceLevel). |
| 51 |
Debug("Sending Twilio request") |
| 52 |
requestURL := fmt.Sprintf("%s/2010-04-01/Accounts/%s/Calls.json", c.config.CallsBaseURL, c.config.Account) |
| 53 |
response, code, err := c.request(requestURL, form) |
| 54 |
if err != nil { |
| 55 |
ev.Field("twilio_response", response).Err(err).Warn("Error sending Twilio request") |
| 56 |
return err |
| 57 |
} else if !success(code) { |
| 58 |
// Twilio rejects calls with a 4xx, e.g. for an invalid phone number, or if the account |
| 59 |
// is out of funds. Without this check, a rejected call would be counted as a success. |
| 60 |
ev.Field("twilio_status", code).Field("twilio_response", response).Warn("Twilio call failed with status code %d", code) |
| 61 |
return fmt.Errorf("twilio call failed with status code %d", code) |
| 62 |
} |
| 63 |
ev.FieldIf("twilio_response", response, log.TraceLevel).Debug("Received successful Twilio response") |
| 64 |
return nil |
| 65 |
} |
| 66 |
|
| 67 |
// Verify calls the Twilio Verify API to send a verification code to the given phone |
| 68 |
// number, via the given channel ("sms" or "call") |
| 69 |
func (c *Client) Verify(phoneNumber, channel string) error { |
| 70 |
ev := log.Tag(tagTwilio).Field("twilio_to", phoneNumber).Field("twilio_channel", channel).Debug("Sending phone verification") |
| 71 |
form := url.Values{} |
| 72 |
form.Set("To", phoneNumber) |
| 73 |
form.Set("Channel", channel) |
| 74 |
requestURL := fmt.Sprintf("%s/v2/Services/%s/Verifications", c.config.VerifyBaseURL, c.config.VerifyService) |
| 75 |
response, code, err := c.request(requestURL, form) |
| 76 |
if err != nil { |
| 77 |
ev.Err(err).Warn("Error sending Twilio phone verification request") |
| 78 |
return err |
| 79 |
} else if !success(code) { |
| 80 |
// Without this check, a rejected verification would look like a success to the caller, |
| 81 |
// and the user would be told to wait for an SMS that was never sent. |
| 82 |
ev.Field("twilio_status", code).Field("twilio_response", response).Warn("Twilio phone verification request failed with status code %d", code) |
| 83 |
return fmt.Errorf("twilio phone verification request failed with status code %d", code) |
| 84 |
} |
| 85 |
ev.FieldIf("twilio_response", response, log.TraceLevel).Debug("Received Twilio phone verification response") |
| 86 |
return nil |
| 87 |
} |
| 88 |
|
| 89 |
// CheckVerify calls the Twilio Verify API to check the verification code for the given |
| 90 |
// phone number. It returns ErrVerificationExpired if the code has expired or never existed. |
| 91 |
func (c *Client) CheckVerify(phoneNumber, code string) error { |
| 92 |
ev := log.Tag(tagTwilio).Field("twilio_to", phoneNumber).Debug("Checking phone verification") |
| 93 |
form := url.Values{} |
| 94 |
form.Set("To", phoneNumber) |
| 95 |
form.Set("Code", code) |
| 96 |
requestURL := fmt.Sprintf("%s/v2/Services/%s/VerificationCheck", c.config.VerifyBaseURL, c.config.VerifyService) |
| 97 |
req, err := c.newRequest(requestURL, form) |
| 98 |
if err != nil { |
| 99 |
return err |
| 100 |
} |
| 101 |
resp, err := http.DefaultClient.Do(req) |
| 102 |
if err != nil { |
| 103 |
return err |
| 104 |
} |
| 105 |
defer resp.Body.Close() |
| 106 |
if resp.StatusCode != http.StatusOK { |
| 107 |
if ev.IsTrace() { |
| 108 |
response, err := io.ReadAll(resp.Body) |
| 109 |
if err != nil { |
| 110 |
return err |
| 111 |
} |
| 112 |
ev.Field("twilio_response", string(response)) |
| 113 |
} |
| 114 |
ev.Warn("Twilio phone verification failed with status code %d", resp.StatusCode) |
| 115 |
if resp.StatusCode == http.StatusNotFound { |
| 116 |
return ErrVerificationExpired |
| 117 |
} |
| 118 |
return fmt.Errorf("twilio phone verification failed with status code %d", resp.StatusCode) |
| 119 |
} |
| 120 |
response, err := io.ReadAll(resp.Body) |
| 121 |
if err != nil { |
| 122 |
return err |
| 123 |
} |
| 124 |
if ev.IsTrace() { |
| 125 |
ev.Field("twilio_response", string(response)).Trace("Received successful Twilio phone verification response") |
| 126 |
} else if ev.IsDebug() { |
| 127 |
ev.Debug("Received successful Twilio phone verification response") |
| 128 |
} |
| 129 |
return nil |
| 130 |
} |
| 131 |
|
| 132 |
// request POSTs the given form to the given Twilio API URL, and returns the raw response body |
| 133 |
// and status code. It does not treat a non-2xx status code as an error; that is up to the |
| 134 |
// caller. The response body is returned even if the request failed, so that it can be logged. |
| 135 |
func (c *Client) request(requestURL string, form url.Values) (string, int, error) { |
| 136 |
req, err := c.newRequest(requestURL, form) |
| 137 |
if err != nil { |
| 138 |
return "", 0, err |
| 139 |
} |
| 140 |
resp, err := http.DefaultClient.Do(req) |
| 141 |
if err != nil { |
| 142 |
return "", 0, err |
| 143 |
} |
| 144 |
defer resp.Body.Close() |
| 145 |
response, err := io.ReadAll(resp.Body) |
| 146 |
if err != nil { |
| 147 |
return "", resp.StatusCode, err |
| 148 |
} |
| 149 |
return string(response), resp.StatusCode, nil |
| 150 |
} |
| 151 |
|
| 152 |
// success reports whether the given HTTP status code indicates success. Note that the Twilio |
| 153 |
// Calls API returns 201 Created (not 200 OK) for a successfully queued call. |
| 154 |
func success(code int) bool { |
| 155 |
return code >= 200 && code <= 299 |
| 156 |
} |
| 157 |
|
| 158 |
// newRequest creates a form-encoded POST request against the Twilio API, with the auth and |
| 159 |
// User-Agent headers set |
| 160 |
func (c *Client) newRequest(requestURL string, form url.Values) (*http.Request, error) { |
| 161 |
req, err := http.NewRequest(http.MethodPost, requestURL, strings.NewReader(form.Encode())) |
| 162 |
if err != nil { |
| 163 |
return nil, err |
| 164 |
} |
| 165 |
req.Header.Set("User-Agent", "ntfy/"+c.config.BuildVersion) |
| 166 |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 167 |
req.Header.Set("Authorization", util.BasicAuth(c.config.Account, c.config.AuthToken)) |
| 168 |
return req, nil |
| 169 |
} |