asmux.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "context"
  19. "errors"
  20. "net/http"
  21. "sync/atomic"
  22. "time"
  23. "github.com/Rhymen/go-whatsapp"
  24. "maunium.net/go/mautrix/id"
  25. )
  26. type AsmuxError string
  27. const (
  28. AsmuxWANotLoggedIn AsmuxError = "wa-not-logged-in"
  29. AsmuxWANotConnected AsmuxError = "wa-not-connected"
  30. AsmuxWAConnecting AsmuxError = "wa-connecting"
  31. AsmuxWATimeout AsmuxError = "wa-timeout"
  32. AsmuxWAPingFalse AsmuxError = "wa-ping-false"
  33. AsmuxWAPingError AsmuxError = "wa-ping-error"
  34. )
  35. var asmuxHumanErrors = map[AsmuxError]string{
  36. AsmuxWANotLoggedIn: "You're not logged into WhatsApp",
  37. AsmuxWANotConnected: "You're not connected to WhatsApp",
  38. AsmuxWAConnecting: "Trying to reconnect to WhatsApp. Please make sure WhatsApp is running on your phone and connected to the internet.",
  39. AsmuxWATimeout: "WhatsApp on your phone is not responding. Please make sure it is running and connected to the internet.",
  40. AsmuxWAPingFalse: "WhatsApp returned an error, reconnecting. Please make sure WhatsApp is running on your phone and connected to the internet.",
  41. AsmuxWAPingError: "WhatsApp returned an unknown error",
  42. }
  43. type AsmuxPong struct {
  44. OK bool `json:"ok"`
  45. Timestamp int64 `json:"timestamp"`
  46. TTL int `json:"ttl"`
  47. ErrorSource string `json:"error_source,omitempty"`
  48. Error AsmuxError `json:"error,omitempty"`
  49. Message string `json:"message,omitempty"`
  50. }
  51. func (pong *AsmuxPong) fill() {
  52. pong.Timestamp = time.Now().Unix()
  53. if !pong.OK {
  54. pong.TTL = 60
  55. pong.ErrorSource = "bridge"
  56. pong.Message = asmuxHumanErrors[pong.Error]
  57. } else {
  58. pong.TTL = 240
  59. }
  60. }
  61. func (pong *AsmuxPong) shouldDeduplicate(newPong *AsmuxPong) bool {
  62. if pong == nil || pong.OK != newPong.OK || pong.Error != newPong.Error {
  63. return false
  64. }
  65. return pong.Timestamp+int64(pong.TTL/5) > time.Now().Unix()
  66. }
  67. func (user *User) setupAdminTestHooks() {
  68. if !user.bridge.Config.Homeserver.Asmux {
  69. return
  70. }
  71. user.Conn.AdminTestHook = func(err error) {
  72. if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  73. user.sendBridgeStatus(AsmuxPong{Error: AsmuxWATimeout})
  74. } else if errors.Is(err, whatsapp.ErrPingFalse) {
  75. user.sendBridgeStatus(AsmuxPong{Error: AsmuxWAPingFalse})
  76. } else if err == nil {
  77. user.sendBridgeStatus(AsmuxPong{OK: true})
  78. } else {
  79. user.sendBridgeStatus(AsmuxPong{Error: AsmuxWAPingError})
  80. }
  81. }
  82. user.Conn.CountTimeoutHook = func() {
  83. user.sendBridgeStatus(AsmuxPong{Error: AsmuxWATimeout})
  84. }
  85. }
  86. func (user *User) sendBridgeStatus(state AsmuxPong) {
  87. if !user.bridge.Config.Homeserver.Asmux {
  88. return
  89. }
  90. state.fill()
  91. if user.prevBridgeStatus != nil && user.prevBridgeStatus.shouldDeduplicate(&state) {
  92. return
  93. }
  94. cli := user.bridge.AS.BotClient()
  95. url := cli.BuildBaseURL("_matrix", "client", "unstable", "com.beeper.asmux", "pong")
  96. user.log.Debugfln("Sending bridge state to asmux: %+v", state)
  97. _, err := cli.MakeRequest("POST", url, &state, nil)
  98. if err != nil {
  99. user.log.Warnln("Failed to update bridge state in asmux:", err)
  100. } else {
  101. user.prevBridgeStatus = &state
  102. }
  103. }
  104. var asmuxPingID uint32 = 0
  105. func (prov *ProvisioningAPI) AsmuxPing(w http.ResponseWriter, r *http.Request) {
  106. if !prov.bridge.AS.CheckServerToken(w, r) {
  107. return
  108. }
  109. userID := r.URL.Query().Get("user_id")
  110. user := prov.bridge.GetUserByMXID(id.UserID(userID))
  111. var resp AsmuxPong
  112. if user.Conn == nil {
  113. if user.Session == nil {
  114. resp.Error = AsmuxWANotLoggedIn
  115. } else {
  116. resp.Error = AsmuxWANotConnected
  117. }
  118. } else {
  119. if user.Conn.IsConnected() && user.Conn.IsLoggedIn() {
  120. pingID := atomic.AddUint32(&asmuxPingID, 1)
  121. user.log.Debugfln("Pinging WhatsApp mobile due to asmux /ping API request (ID %d)", pingID)
  122. err := user.Conn.AdminTestWithSuppress(true)
  123. if errors.Is(r.Context().Err(), context.Canceled) {
  124. user.log.Warnfln("Ping request %d was canceled before we responded (response was %v)", pingID, err)
  125. user.prevBridgeStatus = nil
  126. return
  127. }
  128. user.log.Debugfln("Ping %d response: %v", pingID, err)
  129. if err == whatsapp.ErrPingFalse {
  130. user.log.Debugln("Forwarding ping false error from provisioning API to HandleError")
  131. go user.HandleError(err)
  132. resp.Error = AsmuxWAPingFalse
  133. } else if errors.Is(err, whatsapp.ErrConnectionTimeout) {
  134. resp.Error = AsmuxWATimeout
  135. } else if err != nil {
  136. resp.Error = AsmuxWAPingError
  137. } else {
  138. resp.OK = true
  139. }
  140. } else if user.Conn.IsLoginInProgress() {
  141. resp.Error = AsmuxWAConnecting
  142. } else if user.Conn.IsConnected() {
  143. resp.Error = AsmuxWANotLoggedIn
  144. } else {
  145. resp.Error = AsmuxWANotConnected
  146. }
  147. }
  148. resp.fill()
  149. user.log.Debugfln("Responding bridge state to asmux: %+v", resp)
  150. jsonResponse(w, http.StatusOK, &resp)
  151. user.prevBridgeStatus = &resp
  152. }