bridgestate.go 6.4 KB

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