bridgestate.go 7.7 KB

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