messagetracking.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2022 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. "fmt"
  21. "sync"
  22. "time"
  23. log "maunium.net/go/maulogger/v2"
  24. "go.mau.fi/whatsmeow"
  25. "maunium.net/go/mautrix"
  26. "maunium.net/go/mautrix/bridge"
  27. "maunium.net/go/mautrix/event"
  28. "maunium.net/go/mautrix/id"
  29. )
  30. var (
  31. errUserNotConnected = errors.New("you are not connected to WhatsApp")
  32. errDifferentUser = errors.New("user is not the recipient of this private chat portal")
  33. errUserNotLoggedIn = errors.New("user is not logged in and chat has no relay bot")
  34. errMNoticeDisabled = errors.New("bridging m.notice messages is disabled")
  35. errUnexpectedParsedContentType = errors.New("unexpected parsed content type")
  36. errInvalidGeoURI = errors.New("invalid `geo:` URI in message")
  37. errUnknownMsgType = errors.New("unknown msgtype")
  38. errMediaDownloadFailed = errors.New("failed to download media")
  39. errMediaDecryptFailed = errors.New("failed to decrypt media")
  40. errMediaConvertFailed = errors.New("failed to convert media")
  41. errMediaWhatsAppUploadFailed = errors.New("failed to upload media to WhatsApp")
  42. errTargetNotFound = errors.New("target event not found")
  43. errReactionDatabaseNotFound = errors.New("reaction database entry not found")
  44. errReactionTargetNotFound = errors.New("reaction target message not found")
  45. errTargetIsFake = errors.New("target is a fake event")
  46. errTargetSentBySomeoneElse = errors.New("target is a fake event")
  47. errBroadcastReactionNotSupported = errors.New("reacting to status messages is not currently supported")
  48. errBroadcastSendDisabled = errors.New("sending status messages is disabled")
  49. errMessageDisconnected = &whatsmeow.DisconnectedError{Action: "message send"}
  50. errMessageRetryDisconnected = &whatsmeow.DisconnectedError{Action: "message send (retry)"}
  51. errMessageTakingLong = errors.New("bridging the message is taking longer than usual")
  52. errTimeoutBeforeHandling = errors.New("message timed out before handling was started")
  53. )
  54. func errorToStatusReason(err error) (reason event.MessageStatusReason, status event.MessageStatus, isCertain, sendNotice bool, humanMessage string) {
  55. switch {
  56. case errors.Is(err, whatsmeow.ErrBroadcastListUnsupported),
  57. errors.Is(err, errUnexpectedParsedContentType),
  58. errors.Is(err, errUnknownMsgType),
  59. errors.Is(err, errInvalidGeoURI),
  60. errors.Is(err, whatsmeow.ErrUnknownServer),
  61. errors.Is(err, whatsmeow.ErrRecipientADJID),
  62. errors.Is(err, errBroadcastReactionNotSupported),
  63. errors.Is(err, errBroadcastSendDisabled):
  64. return event.MessageStatusUnsupported, event.MessageStatusFail, true, true, ""
  65. case errors.Is(err, errTimeoutBeforeHandling):
  66. return event.MessageStatusTooOld, event.MessageStatusRetriable, true, true, "the message was too old when it reached the bridge, so it was not handled"
  67. case errors.Is(err, context.DeadlineExceeded):
  68. return event.MessageStatusTooOld, event.MessageStatusRetriable, false, true, "handling the message took too long and was cancelled"
  69. case errors.Is(err, errMessageTakingLong):
  70. return event.MessageStatusTooOld, event.MessageStatusPending, false, true, err.Error()
  71. case errors.Is(err, errTargetNotFound),
  72. errors.Is(err, errTargetIsFake),
  73. errors.Is(err, errReactionDatabaseNotFound),
  74. errors.Is(err, errReactionTargetNotFound),
  75. errors.Is(err, errTargetSentBySomeoneElse):
  76. return event.MessageStatusGenericError, event.MessageStatusFail, true, false, ""
  77. case errors.Is(err, whatsmeow.ErrNotConnected),
  78. errors.Is(err, errUserNotConnected):
  79. return event.MessageStatusGenericError, event.MessageStatusRetriable, true, true, ""
  80. case errors.Is(err, errUserNotLoggedIn),
  81. errors.Is(err, errDifferentUser):
  82. return event.MessageStatusGenericError, event.MessageStatusRetriable, true, false, ""
  83. case errors.Is(err, errMessageDisconnected),
  84. errors.Is(err, errMessageRetryDisconnected):
  85. return event.MessageStatusGenericError, event.MessageStatusRetriable, false, true, ""
  86. default:
  87. return event.MessageStatusGenericError, event.MessageStatusRetriable, false, true, ""
  88. }
  89. }
  90. func (portal *Portal) sendErrorMessage(evt *event.Event, err error, confirmed bool, editID id.EventID) id.EventID {
  91. if !portal.bridge.Config.Bridge.MessageErrorNotices {
  92. return ""
  93. }
  94. certainty := "may not have been"
  95. if confirmed {
  96. certainty = "was not"
  97. }
  98. msg := fmt.Sprintf("\u26a0 Your message %s bridged: %v", certainty, err)
  99. if errors.Is(err, errMessageTakingLong) {
  100. msg = "\u26a0 Bridging your message is taking longer than usual"
  101. }
  102. content := &event.MessageEventContent{
  103. MsgType: event.MsgNotice,
  104. Body: msg,
  105. }
  106. if editID != "" {
  107. content.SetEdit(editID)
  108. } else {
  109. content.SetReply(evt)
  110. }
  111. resp, err := portal.sendMainIntentMessage(content)
  112. if err != nil {
  113. portal.log.Warnfln("Failed to send bridging error message:", err)
  114. return ""
  115. }
  116. return resp.EventID
  117. }
  118. func (portal *Portal) sendStatusEvent(evtID, lastRetry id.EventID, err error) {
  119. if !portal.bridge.Config.Bridge.MessageStatusEvents {
  120. return
  121. }
  122. if lastRetry == evtID {
  123. lastRetry = ""
  124. }
  125. intent := portal.bridge.Bot
  126. if !portal.Encrypted {
  127. // Bridge bot isn't present in unencrypted DMs
  128. intent = portal.MainIntent()
  129. }
  130. content := event.BeeperMessageStatusEventContent{
  131. Network: portal.getBridgeInfoStateKey(),
  132. RelatesTo: event.RelatesTo{
  133. Type: event.RelReference,
  134. EventID: evtID,
  135. },
  136. LastRetry: lastRetry,
  137. }
  138. if err == nil {
  139. content.Status = event.MessageStatusSuccess
  140. } else {
  141. content.Reason, content.Status, _, _, content.Message = errorToStatusReason(err)
  142. content.Error = err.Error()
  143. }
  144. content.FillLegacyBooleans()
  145. _, err = intent.SendMessageEvent(portal.MXID, event.BeeperMessageStatus, &content)
  146. if err != nil {
  147. portal.log.Warnln("Failed to send message status event:", err)
  148. }
  149. }
  150. func (portal *Portal) sendDeliveryReceipt(eventID id.EventID) {
  151. if portal.bridge.Config.Bridge.DeliveryReceipts {
  152. err := portal.bridge.Bot.MarkRead(portal.MXID, eventID)
  153. if err != nil {
  154. portal.log.Debugfln("Failed to send delivery receipt for %s: %v", eventID, err)
  155. }
  156. }
  157. }
  158. func (portal *Portal) sendMessageMetrics(evt *event.Event, err error, part string, ms *metricSender) {
  159. var msgType string
  160. switch evt.Type {
  161. case event.EventMessage:
  162. msgType = "message"
  163. case event.EventReaction:
  164. msgType = "reaction"
  165. case event.EventRedaction:
  166. msgType = "redaction"
  167. default:
  168. msgType = "unknown event"
  169. }
  170. evtDescription := evt.ID.String()
  171. if evt.Type == event.EventRedaction {
  172. evtDescription += fmt.Sprintf(" of %s", evt.Redacts)
  173. }
  174. origEvtID := evt.ID
  175. if retryMeta := evt.Content.AsMessage().MessageSendRetry; retryMeta != nil {
  176. origEvtID = retryMeta.OriginalEventID
  177. }
  178. if err != nil {
  179. level := log.LevelError
  180. if part == "Ignoring" {
  181. level = log.LevelDebug
  182. }
  183. portal.log.Logfln(level, "%s %s %s from %s: %v", part, msgType, evtDescription, evt.Sender, err)
  184. reason, status, isCertain, sendNotice, _ := errorToStatusReason(err)
  185. checkpointStatus := bridge.ReasonToCheckpointStatus(reason, status)
  186. portal.bridge.SendMessageCheckpoint(evt, bridge.MsgStepRemote, err, checkpointStatus, ms.getRetryNum())
  187. if sendNotice {
  188. ms.setNoticeID(portal.sendErrorMessage(evt, err, isCertain, ms.getNoticeID()))
  189. }
  190. portal.sendStatusEvent(origEvtID, evt.ID, err)
  191. } else {
  192. portal.log.Debugfln("Handled Matrix %s %s", msgType, evtDescription)
  193. portal.sendDeliveryReceipt(evt.ID)
  194. portal.bridge.SendMessageSuccessCheckpoint(evt, bridge.MsgStepRemote, ms.getRetryNum())
  195. portal.sendStatusEvent(origEvtID, evt.ID, nil)
  196. if prevNotice := ms.popNoticeID(); prevNotice != "" {
  197. _, _ = portal.MainIntent().RedactEvent(portal.MXID, prevNotice, mautrix.ReqRedact{
  198. Reason: "error resolved",
  199. })
  200. }
  201. }
  202. if ms != nil {
  203. portal.log.Debugfln("Timings for %s: %s", evt.ID, ms.timings.String())
  204. }
  205. }
  206. type messageTimings struct {
  207. initReceive time.Duration
  208. decrypt time.Duration
  209. implicitRR time.Duration
  210. portalQueue time.Duration
  211. totalReceive time.Duration
  212. preproc time.Duration
  213. convert time.Duration
  214. whatsmeow whatsmeow.MessageDebugTimings
  215. totalSend time.Duration
  216. }
  217. func niceRound(dur time.Duration) time.Duration {
  218. switch {
  219. case dur < time.Millisecond:
  220. return dur
  221. case dur < time.Second:
  222. return dur.Round(100 * time.Microsecond)
  223. default:
  224. return dur.Round(time.Millisecond)
  225. }
  226. }
  227. func (mt *messageTimings) String() string {
  228. mt.initReceive = niceRound(mt.initReceive)
  229. mt.decrypt = niceRound(mt.decrypt)
  230. mt.portalQueue = niceRound(mt.portalQueue)
  231. mt.totalReceive = niceRound(mt.totalReceive)
  232. mt.implicitRR = niceRound(mt.implicitRR)
  233. mt.preproc = niceRound(mt.preproc)
  234. mt.convert = niceRound(mt.convert)
  235. mt.whatsmeow.Queue = niceRound(mt.whatsmeow.Queue)
  236. mt.whatsmeow.Marshal = niceRound(mt.whatsmeow.Marshal)
  237. mt.whatsmeow.GetParticipants = niceRound(mt.whatsmeow.GetParticipants)
  238. mt.whatsmeow.GetDevices = niceRound(mt.whatsmeow.GetDevices)
  239. mt.whatsmeow.GroupEncrypt = niceRound(mt.whatsmeow.GroupEncrypt)
  240. mt.whatsmeow.PeerEncrypt = niceRound(mt.whatsmeow.PeerEncrypt)
  241. mt.whatsmeow.Send = niceRound(mt.whatsmeow.Send)
  242. mt.whatsmeow.Resp = niceRound(mt.whatsmeow.Resp)
  243. mt.whatsmeow.Retry = niceRound(mt.whatsmeow.Retry)
  244. mt.totalSend = niceRound(mt.totalSend)
  245. whatsmeowTimings := "N/A"
  246. if mt.totalSend > 0 {
  247. format := "queue: %[1]s, marshal: %[2]s, ske: %[3]s, pcp: %[4]s, dev: %[5]s, encrypt: %[6]s, send: %[7]s, resp: %[8]s"
  248. if mt.whatsmeow.GetParticipants == 0 && mt.whatsmeow.GroupEncrypt == 0 {
  249. format = "queue: %[1]s, marshal: %[2]s, dev: %[5]s, encrypt: %[6]s, send: %[7]s, resp: %[8]s"
  250. }
  251. if mt.whatsmeow.Retry > 0 {
  252. format += ", retry: %[9]s"
  253. }
  254. whatsmeowTimings = fmt.Sprintf(format, mt.whatsmeow.Queue, mt.whatsmeow.Marshal, mt.whatsmeow.GroupEncrypt, mt.whatsmeow.GetParticipants, mt.whatsmeow.GetDevices, mt.whatsmeow.PeerEncrypt, mt.whatsmeow.Send, mt.whatsmeow.Resp, mt.whatsmeow.Retry)
  255. }
  256. return fmt.Sprintf("BRIDGE: receive: %s, decrypt: %s, queue: %s, total hs->portal: %s, implicit rr: %s -- PORTAL: preprocess: %s, convert: %s, total send: %s -- WHATSMEOW: %s", mt.initReceive, mt.decrypt, mt.implicitRR, mt.portalQueue, mt.totalReceive, mt.preproc, mt.convert, mt.totalSend, whatsmeowTimings)
  257. }
  258. type metricSender struct {
  259. portal *Portal
  260. previousNotice id.EventID
  261. lock sync.Mutex
  262. completed bool
  263. retryNum int
  264. timings *messageTimings
  265. }
  266. func (ms *metricSender) getRetryNum() int {
  267. if ms != nil {
  268. return ms.retryNum
  269. }
  270. return 0
  271. }
  272. func (ms *metricSender) getNoticeID() id.EventID {
  273. if ms == nil {
  274. return ""
  275. }
  276. return ms.previousNotice
  277. }
  278. func (ms *metricSender) popNoticeID() id.EventID {
  279. if ms == nil {
  280. return ""
  281. }
  282. evtID := ms.previousNotice
  283. ms.previousNotice = ""
  284. return evtID
  285. }
  286. func (ms *metricSender) setNoticeID(evtID id.EventID) {
  287. if ms != nil && ms.previousNotice == "" {
  288. ms.previousNotice = evtID
  289. }
  290. }
  291. func (ms *metricSender) sendMessageMetrics(evt *event.Event, err error, part string, completed bool) {
  292. ms.lock.Lock()
  293. defer ms.lock.Unlock()
  294. if !completed && ms.completed {
  295. return
  296. }
  297. ms.portal.sendMessageMetrics(evt, err, part, ms)
  298. ms.retryNum++
  299. ms.completed = completed
  300. }