asmux.go 4.9 KB

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