bridgestate.go 6.6 KB

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