bridgestate.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. "sync/atomic"
  26. "time"
  27. "github.com/Rhymen/go-whatsapp"
  28. "maunium.net/go/mautrix/id"
  29. )
  30. type BridgeErrorCode string
  31. const (
  32. WANotLoggedIn BridgeErrorCode = "wa-not-logged-in"
  33. WANotConnected BridgeErrorCode = "wa-not-connected"
  34. WAConnecting BridgeErrorCode = "wa-connecting"
  35. WATimeout BridgeErrorCode = "wa-timeout"
  36. WAPingFalse BridgeErrorCode = "wa-ping-false"
  37. WAPingError BridgeErrorCode = "wa-ping-error"
  38. )
  39. var bridgeHumanErrors = map[BridgeErrorCode]string{
  40. WANotLoggedIn: "You're not logged into WhatsApp",
  41. WANotConnected: "You're not connected to WhatsApp",
  42. WAConnecting: "Trying to reconnect to WhatsApp. Please make sure WhatsApp is running on your phone and connected to the internet.",
  43. WATimeout: "WhatsApp on your phone is not responding. Please make sure it is running and connected to the internet.",
  44. WAPingFalse: "WhatsApp returned an error, reconnecting. Please make sure WhatsApp is running on your phone and connected to the internet.",
  45. WAPingError: "WhatsApp returned an unknown error",
  46. }
  47. type BridgeState struct {
  48. OK bool `json:"ok"`
  49. Timestamp int64 `json:"timestamp"`
  50. TTL int `json:"ttl"`
  51. ErrorSource string `json:"error_source,omitempty"`
  52. Error BridgeErrorCode `json:"error,omitempty"`
  53. Message string `json:"message,omitempty"`
  54. UserID id.UserID `json:"user_id"`
  55. }
  56. func (pong *BridgeState) fill() {
  57. pong.Timestamp = time.Now().Unix()
  58. if !pong.OK {
  59. pong.TTL = 60
  60. pong.ErrorSource = "bridge"
  61. pong.Message = bridgeHumanErrors[pong.Error]
  62. } else {
  63. pong.TTL = 240
  64. }
  65. }
  66. func (pong *BridgeState) shouldDeduplicate(newPong *BridgeState) bool {
  67. if pong == nil || pong.OK != newPong.OK || pong.Error != newPong.Error {
  68. return false
  69. }
  70. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  71. }
  72. func (user *User) setupAdminTestHooks() {
  73. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  74. return
  75. }
  76. user.Conn.AdminTestHook = func(err error) {
  77. if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  78. user.sendBridgeState(BridgeState{Error: WATimeout})
  79. } else if errors.Is(err, whatsapp.ErrPingFalse) {
  80. user.sendBridgeState(BridgeState{Error: WAPingFalse})
  81. } else if err == nil {
  82. user.sendBridgeState(BridgeState{OK: true})
  83. } else {
  84. user.sendBridgeState(BridgeState{Error: WAPingError})
  85. }
  86. }
  87. user.Conn.CountTimeoutHook = func() {
  88. user.sendBridgeState(BridgeState{Error: WATimeout})
  89. }
  90. }
  91. func (user *User) createBridgeStateRequest(ctx context.Context, state *BridgeState) (req *http.Request, err error) {
  92. var body bytes.Buffer
  93. if err = json.NewEncoder(&body).Encode(&state); err != nil {
  94. return nil, fmt.Errorf("failed to encode bridge state JSON: %w", err)
  95. }
  96. req, err = http.NewRequestWithContext(ctx, http.MethodPost, user.bridge.Config.Homeserver.StatusEndpoint, &body)
  97. if err != nil {
  98. return
  99. }
  100. req.Header.Set("Authorization", "Bearer "+user.bridge.Config.AppService.ASToken)
  101. req.Header.Set("Content-Type", "application/json")
  102. return
  103. }
  104. func (user *User) sendBridgeState(state BridgeState) {
  105. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  106. return
  107. }
  108. state.UserID = user.MXID
  109. state.fill()
  110. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  111. return
  112. }
  113. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  114. defer cancel()
  115. var resp *http.Response
  116. if req, err := user.createBridgeStateRequest(ctx, &state); err != nil {
  117. user.log.Warnln("Failed to prepare bridge state update request:", err)
  118. } else if resp, err = http.DefaultClient.Do(req); err != nil {
  119. user.log.Warnln("Failed to send bridge state update:", err)
  120. } else if resp.StatusCode < 200 || resp.StatusCode > 299 {
  121. respBody, _ := ioutil.ReadAll(resp.Body)
  122. if respBody != nil {
  123. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  124. }
  125. user.log.Warnfln("Unexpected status code %d sending bridge state update: %s", resp.StatusCode, respBody)
  126. } else {
  127. user.prevBridgeStatus = &state
  128. user.log.Debugfln("Sent new bridge state %+v", state)
  129. }
  130. if resp != nil && resp.Body != nil {
  131. _ = resp.Body.Close()
  132. }
  133. }
  134. var bridgeStatePingID uint32 = 0
  135. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  136. if !prov.bridge.AS.CheckServerToken(w, r) {
  137. return
  138. }
  139. userID := r.URL.Query().Get("user_id")
  140. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  141. var resp BridgeState
  142. if user.Conn == nil {
  143. if user.Session == nil {
  144. resp.Error = WANotLoggedIn
  145. } else {
  146. resp.Error = WANotConnected
  147. }
  148. } else {
  149. if user.Conn.IsConnected() && user.Conn.IsLoggedIn() {
  150. pingID := atomic.AddUint32(&bridgeStatePingID, 1)
  151. user.log.Debugfln("Pinging WhatsApp mobile due to bridge status /ping API request (ID %d)", pingID)
  152. err := user.Conn.AdminTestWithSuppress(true)
  153. if errors.Is(r.Context().Err(), context.Canceled) {
  154. user.log.Warnfln("Ping request %d was canceled before we responded (response was %v)", pingID, err)
  155. user.prevBridgeStatus = nil
  156. return
  157. }
  158. user.log.Debugfln("Ping %d response: %v", pingID, err)
  159. if err == whatsapp.ErrPingFalse {
  160. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  161. go user.HandleError(err)
  162. resp.Error = WAPingFalse
  163. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  164. resp.Error = WATimeout
  165. } else if err != nil {
  166. resp.Error = WAPingError
  167. } else {
  168. resp.OK = true
  169. }
  170. } else if user.Conn.IsLoginInProgress() {
  171. resp.Error = WAConnecting
  172. } else if user.Conn.IsConnected() {
  173. resp.Error = WANotLoggedIn
  174. } else {
  175. resp.Error = WANotConnected
  176. }
  177. }
  178. resp.UserID = user.MXID
  179. resp.fill()
  180. user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
  181. jsonResponse(w, http.StatusOK, &resp)
  182. user.prevBridgeStatus = &resp
  183. }