bridgestate.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bytes"
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io/ioutil"
  24. "net/http"
  25. "strings"
  26. "sync/atomic"
  27. "time"
  28. "github.com/Rhymen/go-whatsapp"
  29. "maunium.net/go/mautrix/id"
  30. )
  31. type BridgeErrorCode string
  32. const (
  33. WANotLoggedIn BridgeErrorCode = "logged-out"
  34. WANotConnected BridgeErrorCode = "wa-not-connected"
  35. WAConnecting BridgeErrorCode = "wa-connecting"
  36. WATimeout BridgeErrorCode = "wa-timeout"
  37. WAPingFalse BridgeErrorCode = "wa-ping-false"
  38. WAPingError BridgeErrorCode = "wa-ping-error"
  39. )
  40. var bridgeHumanErrors = map[BridgeErrorCode]string{
  41. WANotLoggedIn: "You're not logged into WhatsApp",
  42. WANotConnected: "You're not connected to WhatsApp",
  43. WAConnecting: "Trying to reconnect to WhatsApp. Please make sure WhatsApp is running on your phone and connected to the internet.",
  44. WATimeout: "WhatsApp on your phone is not responding. Please make sure it is running and connected to the internet.",
  45. WAPingFalse: "WhatsApp returned an error, reconnecting. Please make sure WhatsApp is running on your phone and connected to the internet.",
  46. WAPingError: "WhatsApp returned an unknown error",
  47. }
  48. type BridgeState struct {
  49. OK bool `json:"ok"`
  50. Timestamp int64 `json:"timestamp"`
  51. TTL int `json:"ttl"`
  52. ErrorSource string `json:"error_source,omitempty"`
  53. Error BridgeErrorCode `json:"error,omitempty"`
  54. Message string `json:"message,omitempty"`
  55. UserID id.UserID `json:"user_id"`
  56. RemoteID string `json:"remote_id"`
  57. RemoteName string `json:"remote_name"`
  58. }
  59. func (pong *BridgeState) fill(user *User) {
  60. pong.UserID = user.MXID
  61. pong.RemoteID = strings.TrimSuffix(user.JID, whatsapp.NewUserSuffix)
  62. pong.RemoteName = fmt.Sprintf("+%s", pong.RemoteID)
  63. pong.Timestamp = time.Now().Unix()
  64. if !pong.OK {
  65. pong.TTL = 60
  66. pong.ErrorSource = "bridge"
  67. pong.Message = bridgeHumanErrors[pong.Error]
  68. } else {
  69. pong.TTL = 240
  70. }
  71. }
  72. func (pong *BridgeState) shouldDeduplicate(newPong *BridgeState) bool {
  73. if pong == nil || pong.OK != newPong.OK || pong.Error != newPong.Error {
  74. return false
  75. }
  76. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  77. }
  78. func (user *User) setupAdminTestHooks() {
  79. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  80. return
  81. }
  82. user.Conn.AdminTestHook = func(err error) {
  83. if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  84. user.sendBridgeState(BridgeState{Error: WATimeout})
  85. } else if errors.Is(err, whatsapp.ErrPingFalse) {
  86. user.sendBridgeState(BridgeState{Error: WAPingFalse})
  87. } else if err == nil {
  88. user.sendBridgeState(BridgeState{OK: true})
  89. } else {
  90. user.sendBridgeState(BridgeState{Error: WAPingError})
  91. }
  92. }
  93. user.Conn.CountTimeoutHook = func() {
  94. user.sendBridgeState(BridgeState{Error: WATimeout})
  95. }
  96. }
  97. func (user *User) createBridgeStateRequest(ctx context.Context, state *BridgeState) (req *http.Request, err error) {
  98. var body bytes.Buffer
  99. if err = json.NewEncoder(&body).Encode(&state); err != nil {
  100. return nil, fmt.Errorf("failed to encode bridge state JSON: %w", err)
  101. }
  102. req, err = http.NewRequestWithContext(ctx, http.MethodPost, user.bridge.Config.Homeserver.StatusEndpoint, &body)
  103. if err != nil {
  104. return
  105. }
  106. req.Header.Set("Authorization", "Bearer "+user.bridge.Config.AppService.ASToken)
  107. req.Header.Set("Content-Type", "application/json")
  108. return
  109. }
  110. func (user *User) sendBridgeState(state BridgeState) {
  111. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  112. return
  113. }
  114. state.fill(user)
  115. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  116. return
  117. }
  118. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  119. defer cancel()
  120. var resp *http.Response
  121. if req, err := user.createBridgeStateRequest(ctx, &state); err != nil {
  122. user.log.Warnln("Failed to prepare bridge state update request:", err)
  123. } else if resp, err = http.DefaultClient.Do(req); err != nil {
  124. user.log.Warnln("Failed to send bridge state update:", err)
  125. } else if resp.StatusCode < 200 || resp.StatusCode > 299 {
  126. respBody, _ := ioutil.ReadAll(resp.Body)
  127. if respBody != nil {
  128. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  129. }
  130. user.log.Warnfln("Unexpected status code %d sending bridge state update: %s", resp.StatusCode, respBody)
  131. } else {
  132. user.prevBridgeStatus = &state
  133. user.log.Debugfln("Sent new bridge state %+v", state)
  134. }
  135. if resp != nil && resp.Body != nil {
  136. _ = resp.Body.Close()
  137. }
  138. }
  139. var bridgeStatePingID uint32 = 0
  140. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  141. if !prov.bridge.AS.CheckServerToken(w, r) {
  142. return
  143. }
  144. userID := r.URL.Query().Get("user_id")
  145. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  146. var resp BridgeState
  147. if user.Conn == nil {
  148. if user.Session == nil {
  149. resp.Error = WANotLoggedIn
  150. } else {
  151. resp.Error = WANotConnected
  152. }
  153. } else {
  154. if user.Conn.IsConnected() && user.Conn.IsLoggedIn() {
  155. pingID := atomic.AddUint32(&bridgeStatePingID, 1)
  156. user.log.Debugfln("Pinging WhatsApp mobile due to bridge status /ping API request (ID %d)", pingID)
  157. err := user.Conn.AdminTestWithSuppress(true)
  158. if errors.Is(r.Context().Err(), context.Canceled) {
  159. user.log.Warnfln("Ping request %d was canceled before we responded (response was %v)", pingID, err)
  160. user.prevBridgeStatus = nil
  161. return
  162. }
  163. user.log.Debugfln("Ping %d response: %v", pingID, err)
  164. if err == whatsapp.ErrPingFalse {
  165. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  166. go user.HandleError(err)
  167. resp.Error = WAPingFalse
  168. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  169. resp.Error = WATimeout
  170. } else if err != nil {
  171. resp.Error = WAPingError
  172. } else {
  173. resp.OK = true
  174. }
  175. } else if user.Conn.IsLoginInProgress() {
  176. resp.Error = WAConnecting
  177. } else if user.Conn.IsConnected() {
  178. resp.Error = WANotLoggedIn
  179. } else {
  180. resp.Error = WANotConnected
  181. }
  182. }
  183. resp.fill(user)
  184. user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
  185. jsonResponse(w, http.StatusOK, &resp)
  186. user.prevBridgeStatus = &resp
  187. }