bridgestate.go 7.2 KB

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