bridgestate.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. "fmt"
  22. "io"
  23. "net/http"
  24. "time"
  25. log "maunium.net/go/maulogger/v2"
  26. "maunium.net/go/mautrix/id"
  27. )
  28. type BridgeStateEvent string
  29. const (
  30. StateUnconfigured BridgeStateEvent = "UNCONFIGURED"
  31. StateRunning BridgeStateEvent = "RUNNING"
  32. StateConnecting BridgeStateEvent = "CONNECTING"
  33. StateBackfilling BridgeStateEvent = "BACKFILLING"
  34. StateConnected BridgeStateEvent = "CONNECTED"
  35. StateTransientDisconnect BridgeStateEvent = "TRANSIENT_DISCONNECT"
  36. StateBadCredentials BridgeStateEvent = "BAD_CREDENTIALS"
  37. StateUnknownError BridgeStateEvent = "UNKNOWN_ERROR"
  38. StateLoggedOut BridgeStateEvent = "LOGGED_OUT"
  39. )
  40. type BridgeErrorCode string
  41. const (
  42. WALoggedOut BridgeErrorCode = "wa-logged-out"
  43. WAAccountBanned BridgeErrorCode = "wa-account-banned"
  44. WAUnknownLogout BridgeErrorCode = "wa-unknown-logout"
  45. WANotConnected BridgeErrorCode = "wa-not-connected"
  46. WAConnecting BridgeErrorCode = "wa-connecting"
  47. WAServerTimeout BridgeErrorCode = "wa-server-timeout"
  48. WAPhoneOffline BridgeErrorCode = "wa-phone-offline"
  49. )
  50. var bridgeHumanErrors = map[BridgeErrorCode]string{
  51. WALoggedOut: "You were logged out from another device. Relogin to continue using the bridge.",
  52. WAAccountBanned: "Your account was banned from WhatsApp. You can contact support from the WhatsApp mobile app on your phone.",
  53. WAUnknownLogout: "You were logged out for an unknown reason. Relogin to continue using the bridge.",
  54. WANotConnected: "You're not connected to WhatsApp",
  55. WAConnecting: "Reconnecting to WhatsApp...",
  56. WAServerTimeout: "The WhatsApp web servers are not responding. The bridge will try to reconnect.",
  57. WAPhoneOffline: "Your phone hasn't been seen in over 12 days. The bridge is currently connected, but will get disconnected if you don't open the app soon.",
  58. }
  59. type BridgeState struct {
  60. StateEvent BridgeStateEvent `json:"state_event"`
  61. Timestamp int64 `json:"timestamp"`
  62. TTL int `json:"ttl"`
  63. Source string `json:"source,omitempty"`
  64. Error BridgeErrorCode `json:"error,omitempty"`
  65. Message string `json:"message,omitempty"`
  66. UserID id.UserID `json:"user_id,omitempty"`
  67. RemoteID string `json:"remote_id,omitempty"`
  68. RemoteName string `json:"remote_name,omitempty"`
  69. }
  70. type GlobalBridgeState struct {
  71. RemoteStates map[string]BridgeState `json:"remoteState"`
  72. BridgeState BridgeState `json:"bridgeState"`
  73. }
  74. func (pong BridgeState) fill(user *User) BridgeState {
  75. if user != nil {
  76. pong.UserID = user.MXID
  77. pong.RemoteID = fmt.Sprintf("%s_a%d_d%d", user.JID.User, user.JID.Agent, user.JID.Device)
  78. pong.RemoteName = fmt.Sprintf("+%s", user.JID.User)
  79. }
  80. pong.Timestamp = time.Now().Unix()
  81. pong.Source = "bridge"
  82. if len(pong.Error) > 0 {
  83. pong.TTL = 60
  84. pong.Message = bridgeHumanErrors[pong.Error]
  85. } else {
  86. pong.TTL = 240
  87. }
  88. return pong
  89. }
  90. func (pong *BridgeState) shouldDeduplicate(newPong *BridgeState) bool {
  91. if pong == nil || pong.StateEvent != newPong.StateEvent || pong.Error != newPong.Error {
  92. return false
  93. }
  94. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  95. }
  96. func (bridge *Bridge) createBridgeStateRequest(ctx context.Context, state *BridgeState) (req *http.Request, err error) {
  97. var body bytes.Buffer
  98. if err = json.NewEncoder(&body).Encode(&state); err != nil {
  99. return nil, fmt.Errorf("failed to encode bridge state JSON: %w", err)
  100. }
  101. req, err = http.NewRequestWithContext(ctx, http.MethodPost, bridge.Config.Homeserver.StatusEndpoint, &body)
  102. if err != nil {
  103. return
  104. }
  105. req.Header.Set("Authorization", "Bearer "+bridge.Config.AppService.ASToken)
  106. req.Header.Set("Content-Type", "application/json")
  107. return
  108. }
  109. func sendPreparedBridgeStateRequest(logger log.Logger, req *http.Request) bool {
  110. resp, err := http.DefaultClient.Do(req)
  111. if err != nil {
  112. logger.Warnln("Failed to send bridge state update:", err)
  113. return false
  114. }
  115. defer resp.Body.Close()
  116. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  117. respBody, _ := io.ReadAll(resp.Body)
  118. if respBody != nil {
  119. respBody = bytes.ReplaceAll(respBody, []byte("\n"), []byte("\\n"))
  120. }
  121. logger.Warnfln("Unexpected status code %d sending bridge state update: %s", resp.StatusCode, respBody)
  122. return false
  123. }
  124. return true
  125. }
  126. func (bridge *Bridge) sendGlobalBridgeState(state BridgeState) {
  127. if len(bridge.Config.Homeserver.StatusEndpoint) == 0 {
  128. return
  129. }
  130. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  131. defer cancel()
  132. if req, err := bridge.createBridgeStateRequest(ctx, &state); err != nil {
  133. bridge.Log.Warnln("Failed to prepare global bridge state update request:", err)
  134. } else if ok := sendPreparedBridgeStateRequest(bridge.Log, req); ok {
  135. bridge.Log.Debugfln("Sent new global bridge state %+v", state)
  136. }
  137. }
  138. func (user *User) sendBridgeState(state BridgeState) {
  139. if len(user.bridge.Config.Homeserver.StatusEndpoint) == 0 {
  140. return
  141. }
  142. state = state.fill(user)
  143. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  144. return
  145. }
  146. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  147. defer cancel()
  148. if req, err := user.bridge.createBridgeStateRequest(ctx, &state); err != nil {
  149. user.log.Warnln("Failed to prepare bridge state update request:", err)
  150. } else if ok := sendPreparedBridgeStateRequest(user.log, req); ok {
  151. user.prevBridgeStatus = &state
  152. user.log.Debugfln("Sent new bridge state %+v", state)
  153. }
  154. }
  155. func (user *User) GetPrevBridgeState() BridgeState {
  156. if user.prevBridgeStatus != nil {
  157. return *user.prevBridgeStatus
  158. }
  159. return BridgeState{}
  160. }
  161. func (prov *ProvisioningAPI) BridgeStatePing(w http.ResponseWriter, r *http.Request) {
  162. if !prov.bridge.AS.CheckServerToken(w, r) {
  163. return
  164. }
  165. userID := r.URL.Query().Get("user_id")
  166. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  167. var global BridgeState
  168. global.StateEvent = StateRunning
  169. var remote BridgeState
  170. if user.IsConnected() {
  171. if user.Client.IsLoggedIn() {
  172. remote.StateEvent = StateConnected
  173. } else if user.Session != nil {
  174. remote.StateEvent = StateConnecting
  175. remote.Error = WAConnecting
  176. } // else: unconfigured
  177. } else if user.Session != nil {
  178. remote.StateEvent = StateBadCredentials
  179. remote.Error = WANotConnected
  180. } // else: unconfigured
  181. global = global.fill(nil)
  182. resp := GlobalBridgeState{
  183. BridgeState: global,
  184. RemoteStates: map[string]BridgeState{},
  185. }
  186. if len(remote.StateEvent) > 0 {
  187. remote = remote.fill(user)
  188. resp.RemoteStates[remote.RemoteID] = remote
  189. }
  190. user.log.Debugfln("Responding bridge state in bridge status endpoint: %+v", resp)
  191. jsonResponse(w, http.StatusOK, &resp)
  192. if len(resp.RemoteStates) > 0 {
  193. user.prevBridgeStatus = &remote
  194. }
  195. }