bridgestate.go 7.0 KB

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