bridgestate.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 !user.bridge.Config.Homeserver.Asmux {
  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 resp, err = http.DefaultClient.Do(req); err != nil {
  112. user.log.Warnln("Failed to send bridge state update:", err)
  113. } else if resp.StatusCode < 200 || resp.StatusCode > 299 {
  114. respBody, _ := ioutil.ReadAll(resp.Body)
  115. if respBody != nil {
  116. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  117. }
  118. user.log.Warnfln("Unexpected status code %d sending bridge state update: %s", respBody)
  119. } else {
  120. user.prevBridgeStatus = &state
  121. }
  122. if resp != nil && resp.Body != nil {
  123. _ = resp.Body.Close()
  124. }
  125. }
  126. var bridgeStatePingID uint32 = 0
  127. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  128. if !prov.bridge.AS.CheckServerToken(w, r) {
  129. return
  130. }
  131. userID := r.URL.Query().Get("user_id")
  132. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  133. var resp BridgeState
  134. if user.Conn == nil {
  135. if user.Session == nil {
  136. resp.Error = WANotLoggedIn
  137. } else {
  138. resp.Error = WANotConnected
  139. }
  140. } else {
  141. if user.Conn.IsConnected() && user.Conn.IsLoggedIn() {
  142. pingID := atomic.AddUint32(&bridgeStatePingID, 1)
  143. user.log.Debugfln("Pinging WhatsApp mobile due to asmux /ping API request (ID %d)", pingID)
  144. err := user.Conn.AdminTestWithSuppress(true)
  145. if errors.Is(r.Context().Err(), context.Canceled) {
  146. user.log.Warnfln("Ping request %d was canceled before we responded (response was %v)", pingID, err)
  147. user.prevBridgeStatus = nil
  148. return
  149. }
  150. user.log.Debugfln("Ping %d response: %v", pingID, err)
  151. if err == whatsapp.ErrPingFalse {
  152. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  153. go user.HandleError(err)
  154. resp.Error = WAPingFalse
  155. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  156. resp.Error = WATimeout
  157. } else if err != nil {
  158. resp.Error = WAPingError
  159. } else {
  160. resp.OK = true
  161. }
  162. } else if user.Conn.IsLoginInProgress() {
  163. resp.Error = WAConnecting
  164. } else if user.Conn.IsConnected() {
  165. resp.Error = WANotLoggedIn
  166. } else {
  167. resp.Error = WANotConnected
  168. }
  169. }
  170. resp.UserID = user.MXID
  171. resp.fill()
  172. user.log.Debugfln("Responding bridge state to asmux: %+v", resp)
  173. jsonResponse(w, http.StatusOK, &resp)
  174. user.prevBridgeStatus = &resp
  175. }