server_twilio.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "heckel.io/ntfy/v2/log"
  7. "heckel.io/ntfy/v2/user"
  8. "heckel.io/ntfy/v2/util"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. )
  14. const (
  15. twilioCallFormat = `
  16. <Response>
  17. <Pause length="1"/>
  18. <Say loop="3">
  19. You have a message from notify on topic %s. Message:
  20. <break time="1s"/>
  21. %s
  22. <break time="1s"/>
  23. End of message.
  24. <break time="1s"/>
  25. This message was sent by user %s. It will be repeated three times.
  26. To unsubscribe from calls like this, remove your phone number in the notify web app.
  27. <break time="3s"/>
  28. </Say>
  29. <Say>Goodbye.</Say>
  30. </Response>`
  31. )
  32. // convertPhoneNumber checks if the given phone number is verified for the given user, and if so, returns the verified
  33. // phone number. It also converts a boolean string ("yes", "1", "true") to the first verified phone number.
  34. // If the user is anonymous, it will return an error.
  35. func (s *Server) convertPhoneNumber(u *user.User, phoneNumber string) (string, *errHTTP) {
  36. if u == nil {
  37. return "", errHTTPBadRequestAnonymousCallsNotAllowed
  38. }
  39. phoneNumbers, err := s.userManager.PhoneNumbers(u.ID)
  40. if err != nil {
  41. return "", errHTTPInternalError
  42. } else if len(phoneNumbers) == 0 {
  43. return "", errHTTPBadRequestPhoneNumberNotVerified
  44. }
  45. if toBool(phoneNumber) {
  46. return phoneNumbers[0], nil
  47. } else if util.Contains(phoneNumbers, phoneNumber) {
  48. return phoneNumber, nil
  49. }
  50. for _, p := range phoneNumbers {
  51. if p == phoneNumber {
  52. return phoneNumber, nil
  53. }
  54. }
  55. return "", errHTTPBadRequestPhoneNumberNotVerified
  56. }
  57. // callPhone calls the Twilio API to make a phone call to the given phone number, using the given message.
  58. // Failures will be logged, but not returned to the caller.
  59. func (s *Server) callPhone(v *visitor, r *http.Request, m *message, to string) {
  60. u, sender := v.User(), m.Sender.String()
  61. if u != nil {
  62. sender = u.Name
  63. }
  64. body := fmt.Sprintf(twilioCallFormat, xmlEscapeText(m.Topic), xmlEscapeText(m.Message), xmlEscapeText(sender))
  65. data := url.Values{}
  66. data.Set("From", s.config.TwilioPhoneNumber)
  67. data.Set("To", to)
  68. data.Set("Twiml", body)
  69. ev := logvrm(v, r, m).Tag(tagTwilio).Field("twilio_to", to).FieldIf("twilio_body", body, log.TraceLevel).Debug("Sending Twilio request")
  70. response, err := s.callPhoneInternal(data)
  71. if err != nil {
  72. ev.Field("twilio_response", response).Err(err).Warn("Error sending Twilio request")
  73. minc(metricCallsMadeFailure)
  74. return
  75. }
  76. ev.FieldIf("twilio_response", response, log.TraceLevel).Debug("Received successful Twilio response")
  77. minc(metricCallsMadeSuccess)
  78. }
  79. func (s *Server) callPhoneInternal(data url.Values) (string, error) {
  80. requestURL := fmt.Sprintf("%s/2010-04-01/Accounts/%s/Calls.json", s.config.TwilioCallsBaseURL, s.config.TwilioAccount)
  81. req, err := http.NewRequest(http.MethodPost, requestURL, strings.NewReader(data.Encode()))
  82. if err != nil {
  83. return "", err
  84. }
  85. req.Header.Set("User-Agent", "ntfy/"+s.config.Version)
  86. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  87. req.Header.Set("Authorization", util.BasicAuth(s.config.TwilioAccount, s.config.TwilioAuthToken))
  88. resp, err := http.DefaultClient.Do(req)
  89. if err != nil {
  90. return "", err
  91. }
  92. response, err := io.ReadAll(resp.Body)
  93. if err != nil {
  94. return "", err
  95. }
  96. return string(response), nil
  97. }
  98. func (s *Server) verifyPhoneNumber(v *visitor, r *http.Request, phoneNumber, channel string) error {
  99. ev := logvr(v, r).Tag(tagTwilio).Field("twilio_to", phoneNumber).Field("twilio_channel", channel).Debug("Sending phone verification")
  100. data := url.Values{}
  101. data.Set("To", phoneNumber)
  102. data.Set("Channel", channel)
  103. requestURL := fmt.Sprintf("%s/v2/Services/%s/Verifications", s.config.TwilioVerifyBaseURL, s.config.TwilioVerifyService)
  104. req, err := http.NewRequest(http.MethodPost, requestURL, strings.NewReader(data.Encode()))
  105. if err != nil {
  106. return err
  107. }
  108. req.Header.Set("User-Agent", "ntfy/"+s.config.Version)
  109. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  110. req.Header.Set("Authorization", util.BasicAuth(s.config.TwilioAccount, s.config.TwilioAuthToken))
  111. resp, err := http.DefaultClient.Do(req)
  112. if err != nil {
  113. return err
  114. }
  115. response, err := io.ReadAll(resp.Body)
  116. if err != nil {
  117. ev.Err(err).Warn("Error sending Twilio phone verification request")
  118. return err
  119. }
  120. ev.FieldIf("twilio_response", string(response), log.TraceLevel).Debug("Received Twilio phone verification response")
  121. return nil
  122. }
  123. func (s *Server) verifyPhoneNumberCheck(v *visitor, r *http.Request, phoneNumber, code string) error {
  124. ev := logvr(v, r).Tag(tagTwilio).Field("twilio_to", phoneNumber).Debug("Checking phone verification")
  125. data := url.Values{}
  126. data.Set("To", phoneNumber)
  127. data.Set("Code", code)
  128. requestURL := fmt.Sprintf("%s/v2/Services/%s/VerificationCheck", s.config.TwilioVerifyBaseURL, s.config.TwilioVerifyService)
  129. req, err := http.NewRequest(http.MethodPost, requestURL, strings.NewReader(data.Encode()))
  130. if err != nil {
  131. return err
  132. }
  133. req.Header.Set("User-Agent", "ntfy/"+s.config.Version)
  134. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  135. req.Header.Set("Authorization", util.BasicAuth(s.config.TwilioAccount, s.config.TwilioAuthToken))
  136. resp, err := http.DefaultClient.Do(req)
  137. if err != nil {
  138. return err
  139. } else if resp.StatusCode != http.StatusOK {
  140. if ev.IsTrace() {
  141. response, err := io.ReadAll(resp.Body)
  142. if err != nil {
  143. return err
  144. }
  145. ev.Field("twilio_response", string(response))
  146. }
  147. ev.Warn("Twilio phone verification failed with status code %d", resp.StatusCode)
  148. if resp.StatusCode == http.StatusNotFound {
  149. return errHTTPGonePhoneVerificationExpired
  150. }
  151. return errHTTPInternalError
  152. }
  153. response, err := io.ReadAll(resp.Body)
  154. if err != nil {
  155. return err
  156. }
  157. if ev.IsTrace() {
  158. ev.Field("twilio_response", string(response)).Trace("Received successful Twilio phone verification response")
  159. } else if ev.IsDebug() {
  160. ev.Debug("Received successful Twilio phone verification response")
  161. }
  162. return nil
  163. }
  164. func xmlEscapeText(text string) string {
  165. var buf bytes.Buffer
  166. _ = xml.EscapeText(&buf, []byte(text))
  167. return buf.String()
  168. }