historysync.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. "fmt"
  19. "time"
  20. waProto "go.mau.fi/whatsmeow/binary/proto"
  21. "go.mau.fi/whatsmeow/types"
  22. "maunium.net/go/mautrix"
  23. "maunium.net/go/mautrix/appservice"
  24. "maunium.net/go/mautrix/event"
  25. "maunium.net/go/mautrix/id"
  26. "maunium.net/go/mautrix-whatsapp/database"
  27. )
  28. // region User history sync handling
  29. type wrappedInfo struct {
  30. *types.MessageInfo
  31. Type database.MessageType
  32. Error database.MessageErrorType
  33. MediaKey []byte
  34. ExpirationStart uint64
  35. ExpiresIn uint32
  36. }
  37. func (user *User) handleHistorySyncsLoop() {
  38. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  39. return
  40. }
  41. reCheckQueue := make(chan bool, 1)
  42. // Start the backfill queue.
  43. user.BackfillQueue = &BackfillQueue{
  44. BackfillQuery: user.bridge.DB.BackfillQuery,
  45. ImmediateBackfillRequests: make(chan *database.Backfill, 1),
  46. DeferredBackfillRequests: make(chan *database.Backfill, 1),
  47. ReCheckQueue: make(chan bool, 1),
  48. log: user.log.Sub("BackfillQueue"),
  49. }
  50. reCheckQueue = user.BackfillQueue.ReCheckQueue
  51. // Immediate backfills can be done in parallel
  52. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  53. go user.handleBackfillRequestsLoop(user.BackfillQueue.ImmediateBackfillRequests)
  54. }
  55. // Deferred backfills should be handled synchronously so as not to
  56. // overload the homeserver. Users can configure their backfill stages
  57. // to be more or less aggressive with backfilling at this stage.
  58. go user.handleBackfillRequestsLoop(user.BackfillQueue.DeferredBackfillRequests)
  59. go user.BackfillQueue.RunLoop(user)
  60. // Always save the history syncs for the user. If they want to enable
  61. // backfilling in the future, we will have it in the database.
  62. for evt := range user.historySyncs {
  63. user.handleHistorySync(reCheckQueue, evt.Data)
  64. }
  65. }
  66. func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Backfill) {
  67. for req := range backfillRequests {
  68. user.log.Infofln("Handling backfill request %s", req)
  69. conv := user.bridge.DB.HistorySyncQuery.GetConversation(user.MXID, req.Portal)
  70. if conv == nil {
  71. user.log.Debugfln("Could not find history sync conversation data for %s", req.Portal.String())
  72. continue
  73. }
  74. portal := user.GetPortalByJID(conv.PortalKey.JID)
  75. // Update the client store with basic chat settings.
  76. if conv.MuteEndTime.After(time.Now()) {
  77. user.Client.Store.ChatSettings.PutMutedUntil(conv.PortalKey.JID, conv.MuteEndTime)
  78. }
  79. if conv.Archived {
  80. user.Client.Store.ChatSettings.PutArchived(conv.PortalKey.JID, true)
  81. }
  82. if conv.Pinned > 0 {
  83. user.Client.Store.ChatSettings.PutPinned(conv.PortalKey.JID, true)
  84. }
  85. if conv.EphemeralExpiration != nil && portal.ExpirationTime != *conv.EphemeralExpiration {
  86. portal.ExpirationTime = *conv.EphemeralExpiration
  87. portal.Update()
  88. }
  89. user.backfillInChunks(req, conv, portal)
  90. }
  91. }
  92. func (user *User) backfillInChunks(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
  93. portal.backfillLock.Lock()
  94. defer portal.backfillLock.Unlock()
  95. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  96. return
  97. }
  98. var forwardPrevID id.EventID
  99. if req.BackfillType == database.BackfillForward {
  100. // TODO this overrides the TimeStart set when enqueuing the backfill
  101. // maybe the enqueue should instead include the prev event ID
  102. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  103. forwardPrevID = lastMessage.MXID
  104. start := lastMessage.Timestamp.Add(1 * time.Second)
  105. req.TimeStart = &start
  106. } else {
  107. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  108. if firstMessage != nil && (req.TimeEnd == nil || firstMessage.Timestamp.Before(*req.TimeEnd)) {
  109. end := firstMessage.Timestamp.Add(-1 * time.Second)
  110. req.TimeEnd = &end
  111. user.log.Debugfln("Limiting backfill to end at %v", end)
  112. }
  113. }
  114. allMsgs := user.bridge.DB.HistorySyncQuery.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, req.TimeEnd, req.MaxTotalEvents)
  115. sendDisappearedNotice := false
  116. // If expired messages are on, and a notice has not been sent to this chat
  117. // about it having disappeared messages at the conversation timestamp, send
  118. // a notice indicating so.
  119. if len(allMsgs) == 0 && conv.EphemeralExpiration != nil && *conv.EphemeralExpiration > 0 {
  120. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  121. if lastMessage == nil || !conv.LastMessageTimestamp.Equal(lastMessage.Timestamp) {
  122. sendDisappearedNotice = true
  123. }
  124. }
  125. if !sendDisappearedNotice && len(allMsgs) == 0 {
  126. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  127. return
  128. }
  129. if len(portal.MXID) == 0 {
  130. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  131. err := portal.CreateMatrixRoom(user, nil, true, false)
  132. if err != nil {
  133. user.log.Errorfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  134. return
  135. }
  136. }
  137. if sendDisappearedNotice {
  138. user.log.Debugfln("Sending notice to %s that there are disappeared messages ending at %v", portal.Key.JID, conv.LastMessageTimestamp)
  139. resp, err := portal.sendMessage(portal.MainIntent(), event.EventMessage, &event.MessageEventContent{
  140. MsgType: event.MsgNotice,
  141. Body: portal.formatDisappearingMessageNotice(),
  142. }, nil, conv.LastMessageTimestamp.UnixMilli())
  143. if err != nil {
  144. portal.log.Errorln("Error sending disappearing messages notice event")
  145. return
  146. }
  147. msg := portal.bridge.DB.Message.New()
  148. msg.Chat = portal.Key
  149. msg.MXID = resp.EventID
  150. msg.JID = types.MessageID(resp.EventID)
  151. msg.Timestamp = conv.LastMessageTimestamp
  152. msg.Sent = true
  153. msg.Insert()
  154. return
  155. }
  156. user.log.Infofln("Backfilling %d messages in %s, %d messages at a time (queue ID: %d)", len(allMsgs), portal.Key.JID, req.MaxBatchEvents, req.QueueID)
  157. toBackfill := allMsgs[0:]
  158. var insertionEventIds []id.EventID
  159. for len(toBackfill) > 0 {
  160. var msgs []*waProto.WebMessageInfo
  161. if len(toBackfill) <= req.MaxBatchEvents || req.MaxBatchEvents < 0 {
  162. msgs = toBackfill
  163. toBackfill = nil
  164. } else {
  165. msgs = toBackfill[:req.MaxBatchEvents]
  166. toBackfill = toBackfill[req.MaxBatchEvents:]
  167. }
  168. if len(msgs) > 0 {
  169. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  170. user.log.Debugfln("Backfilling %d messages in %s (queue ID: %d)", len(msgs), portal.Key.JID, req.QueueID)
  171. resp := portal.backfill(user, msgs, req.BackfillType == database.BackfillForward, forwardPrevID)
  172. if resp != nil {
  173. insertionEventIds = append(insertionEventIds, resp.BaseInsertionEventID)
  174. }
  175. }
  176. }
  177. user.log.Debugfln("Finished backfilling %d messages in %s (queue ID: %d)", len(allMsgs), portal.Key.JID, req.QueueID)
  178. if len(insertionEventIds) > 0 {
  179. portal.sendPostBackfillDummy(
  180. time.Unix(int64(allMsgs[0].GetMessageTimestamp()), 0),
  181. insertionEventIds[0])
  182. }
  183. user.log.Debugfln("Deleting %d history sync messages after backfilling (queue ID: %d)", len(allMsgs), req.QueueID)
  184. err := user.bridge.DB.HistorySyncQuery.DeleteMessages(user.MXID, conv.ConversationID, allMsgs)
  185. if err != nil {
  186. user.log.Warnfln("Failed to delete %d history sync messages after backfilling (queue ID: %d): %v", len(allMsgs), req.QueueID, err)
  187. }
  188. if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
  189. user.markSelfReadFull(portal)
  190. }
  191. }
  192. func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
  193. if len(portal.MXID) > 0 {
  194. user.log.Debugfln("Portal for %s already exists, ensuring user is invited", portal.Key.JID)
  195. portal.ensureUserInvited(user)
  196. // Portal exists, let backfill continue
  197. return true
  198. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  199. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  200. } else {
  201. // Portal doesn't exist, but should be created
  202. return true
  203. }
  204. // Portal shouldn't be created, reason logged above
  205. return false
  206. }
  207. func (user *User) handleHistorySync(reCheckQueue chan bool, evt *waProto.HistorySync) {
  208. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  209. return
  210. }
  211. description := fmt.Sprintf("type %s, %d conversations, chunk order %d, progress: %d", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder(), evt.GetProgress())
  212. user.log.Infoln("Storing history sync with", description)
  213. for _, conv := range evt.GetConversations() {
  214. jid, err := types.ParseJID(conv.GetId())
  215. if err != nil {
  216. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  217. continue
  218. } else if jid.Server == types.BroadcastServer {
  219. user.log.Debugfln("Skipping broadcast list %s in history sync", jid)
  220. continue
  221. }
  222. portal := user.GetPortalByJID(jid)
  223. historySyncConversation := user.bridge.DB.HistorySyncQuery.NewConversationWithValues(
  224. user.MXID,
  225. conv.GetId(),
  226. &portal.Key,
  227. getConversationTimestamp(conv),
  228. conv.GetMuteEndTime(),
  229. conv.GetArchived(),
  230. conv.GetPinned(),
  231. conv.GetDisappearingMode().GetInitiator(),
  232. conv.GetEndOfHistoryTransferType(),
  233. conv.EphemeralExpiration,
  234. conv.GetMarkedAsUnread(),
  235. conv.GetUnreadCount())
  236. historySyncConversation.Upsert()
  237. for _, rawMsg := range conv.GetMessages() {
  238. // Don't store messages that will just be skipped.
  239. wmi := rawMsg.GetMessage()
  240. msg := wmi.GetMessage()
  241. if msg.GetEphemeralMessage().GetMessage() != nil {
  242. msg = msg.GetEphemeralMessage().GetMessage()
  243. }
  244. if msg.GetViewOnceMessage().GetMessage() != nil {
  245. msg = msg.GetViewOnceMessage().GetMessage()
  246. }
  247. msgType := getMessageType(msg)
  248. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  249. continue
  250. }
  251. // Don't store unsupported messages.
  252. if !containsSupportedMessage(msg) {
  253. continue
  254. }
  255. message, err := user.bridge.DB.HistorySyncQuery.NewMessageWithValues(user.MXID, conv.GetId(), wmi.GetKey().GetId(), rawMsg)
  256. if err != nil {
  257. user.log.Warnfln("Failed to save message %s in %s. Error: %+v", wmi.GetKey().Id, conv.GetId(), err)
  258. continue
  259. }
  260. message.Insert()
  261. }
  262. }
  263. // If this was the initial bootstrap, enqueue immediate backfills for the
  264. // most recent portals. If it's the last history sync event, start
  265. // backfilling the rest of the history of the portals.
  266. if user.bridge.Config.Bridge.HistorySync.Backfill {
  267. if evt.GetSyncType() != waProto.HistorySync_INITIAL_BOOTSTRAP && evt.GetProgress() < 98 {
  268. return
  269. }
  270. nMostRecent := user.bridge.DB.HistorySyncQuery.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  271. if len(nMostRecent) > 0 {
  272. // Find the portals for all of the conversations.
  273. portals := []*Portal{}
  274. for _, conv := range nMostRecent {
  275. jid, err := types.ParseJID(conv.ConversationID)
  276. if err != nil {
  277. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  278. continue
  279. }
  280. portals = append(portals, user.GetPortalByJID(jid))
  281. }
  282. switch evt.GetSyncType() {
  283. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  284. // Enqueue immediate backfills for the most recent messages first.
  285. user.EnqueueImmedateBackfills(portals)
  286. case waProto.HistorySync_FULL, waProto.HistorySync_RECENT:
  287. user.EnqueueForwardBackfills(portals)
  288. // Enqueue deferred backfills as configured.
  289. user.EnqueueDeferredBackfills(portals)
  290. }
  291. // Tell the queue to check for new backfill requests.
  292. reCheckQueue <- true
  293. }
  294. }
  295. }
  296. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  297. convTs := conv.GetConversationTimestamp()
  298. if convTs == 0 && len(conv.GetMessages()) > 0 {
  299. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  300. }
  301. return convTs
  302. }
  303. func (user *User) EnqueueImmedateBackfills(portals []*Portal) {
  304. for priority, portal := range portals {
  305. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  306. initialBackfill := user.bridge.DB.BackfillQuery.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, nil, maxMessages, maxMessages, 0)
  307. initialBackfill.Insert()
  308. }
  309. }
  310. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  311. numPortals := len(portals)
  312. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  313. for portalIdx, portal := range portals {
  314. var startDate *time.Time = nil
  315. if backfillStage.StartDaysAgo > 0 {
  316. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  317. startDate = &startDaysAgo
  318. }
  319. backfillMessages := user.bridge.DB.BackfillQuery.NewWithValues(
  320. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, nil, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  321. backfillMessages.Insert()
  322. }
  323. }
  324. }
  325. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  326. for priority, portal := range portals {
  327. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  328. if lastMsg == nil {
  329. continue
  330. }
  331. backfill := user.bridge.DB.BackfillQuery.NewWithValues(
  332. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, nil, -1, -1, 0)
  333. backfill.Insert()
  334. }
  335. }
  336. // endregion
  337. // region Portal backfilling
  338. var (
  339. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  340. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  341. BackfillEndDummyEvent = event.Type{Type: "fi.mau.dummy.backfill_end", Class: event.MessageEventType}
  342. HistorySyncMarker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  343. )
  344. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward bool, prevEventID id.EventID) *mautrix.RespBatchSend {
  345. var req mautrix.ReqBatchSend
  346. var infos []*wrappedInfo
  347. if !isForward {
  348. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  349. req.PrevEventID = portal.FirstEventID
  350. req.BatchID = portal.NextBatchID
  351. } else {
  352. portal.log.Warnfln("Can't backfill %d messages through %s to chat: first event ID not known", len(messages), source.MXID)
  353. return nil
  354. }
  355. } else {
  356. req.PrevEventID = prevEventID
  357. }
  358. beforeFirstMessageTimestampMillis := (int64(messages[len(messages)-1].GetMessageTimestamp()) * 1000) - 1
  359. req.StateEventsAtStart = make([]*event.Event, 0)
  360. addedMembers := make(map[id.UserID]struct{})
  361. addMember := func(puppet *Puppet) {
  362. if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  363. return
  364. }
  365. mxid := puppet.MXID.String()
  366. content := event.MemberEventContent{
  367. Membership: event.MembershipJoin,
  368. Displayname: puppet.Displayname,
  369. AvatarURL: puppet.AvatarURL.CUString(),
  370. }
  371. inviteContent := content
  372. inviteContent.Membership = event.MembershipInvite
  373. req.StateEventsAtStart = append(req.StateEventsAtStart, &event.Event{
  374. Type: event.StateMember,
  375. Sender: portal.MainIntent().UserID,
  376. StateKey: &mxid,
  377. Timestamp: beforeFirstMessageTimestampMillis,
  378. Content: event.Content{Parsed: &inviteContent},
  379. }, &event.Event{
  380. Type: event.StateMember,
  381. Sender: puppet.MXID,
  382. StateKey: &mxid,
  383. Timestamp: beforeFirstMessageTimestampMillis,
  384. Content: event.Content{Parsed: &content},
  385. })
  386. addedMembers[puppet.MXID] = struct{}{}
  387. }
  388. portal.log.Infofln("Processing history sync with %d messages (forward: %t)", len(messages), isForward)
  389. // The messages are ordered newest to oldest, so iterate them in reverse order.
  390. for i := len(messages) - 1; i >= 0; i-- {
  391. webMsg := messages[i]
  392. msg := webMsg.GetMessage()
  393. if msg.GetEphemeralMessage().GetMessage() != nil {
  394. msg = msg.GetEphemeralMessage().GetMessage()
  395. }
  396. if msg.GetViewOnceMessage().GetMessage() != nil {
  397. msg = msg.GetViewOnceMessage().GetMessage()
  398. }
  399. msgType := getMessageType(msg)
  400. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  401. if msgType != "ignore" {
  402. portal.log.Debugfln("Skipping message %s with unknown type in backfill", webMsg.GetKey().GetId())
  403. }
  404. continue
  405. }
  406. info := portal.parseWebMessageInfo(source, webMsg)
  407. if info == nil {
  408. continue
  409. }
  410. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  411. existingContact, _ := source.Client.Store.Contacts.GetContact(info.Sender)
  412. if !existingContact.Found || existingContact.PushName == "" {
  413. changed, _, err := source.Client.Store.Contacts.PutPushName(info.Sender, webMsg.GetPushName())
  414. if err != nil {
  415. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", info.Sender, err)
  416. } else if changed {
  417. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), info.Sender)
  418. }
  419. }
  420. }
  421. puppet := portal.getMessagePuppet(source, info)
  422. intent := puppet.IntentFor(portal)
  423. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  424. intent = puppet.DefaultIntent()
  425. }
  426. converted := portal.convertMessage(intent, source, info, msg, true)
  427. if converted == nil {
  428. portal.log.Debugfln("Skipping unsupported message %s in backfill", info.ID)
  429. continue
  430. }
  431. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  432. addMember(puppet)
  433. }
  434. // TODO this won't work for history
  435. if len(converted.ReplyTo) > 0 {
  436. portal.SetReply(converted.Content, converted.ReplyTo)
  437. }
  438. err := portal.appendBatchEvents(converted, info, webMsg.GetEphemeralStartTimestamp(), &req.Events, &infos)
  439. if err != nil {
  440. portal.log.Errorfln("Error handling message %s during backfill: %v", info.ID, err)
  441. }
  442. }
  443. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  444. if len(req.Events) == 0 {
  445. return nil
  446. }
  447. if len(req.BatchID) == 0 || isForward {
  448. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  449. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  450. if err != nil {
  451. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  452. }
  453. }
  454. resp, err := portal.MainIntent().BatchSend(portal.MXID, &req)
  455. if err != nil {
  456. portal.log.Errorln("Error batch sending messages:", err)
  457. return nil
  458. } else {
  459. portal.finishBatch(resp.EventIDs, infos)
  460. portal.NextBatchID = resp.NextBatchID
  461. portal.Update()
  462. if portal.bridge.Config.Bridge.HistorySync.AutoRequestMedia {
  463. go portal.requestMediaRetries(source, infos)
  464. }
  465. return resp
  466. }
  467. }
  468. func (portal *Portal) requestMediaRetries(source *User, infos []*wrappedInfo) {
  469. for _, info := range infos {
  470. if info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  471. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  472. if err != nil {
  473. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  474. } else {
  475. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  476. }
  477. }
  478. }
  479. }
  480. func (portal *Portal) parseWebMessageInfo(source *User, webMsg *waProto.WebMessageInfo) *types.MessageInfo {
  481. info := types.MessageInfo{
  482. MessageSource: types.MessageSource{
  483. Chat: portal.Key.JID,
  484. IsFromMe: webMsg.GetKey().GetFromMe(),
  485. IsGroup: portal.Key.JID.Server == types.GroupServer,
  486. },
  487. ID: webMsg.GetKey().GetId(),
  488. PushName: webMsg.GetPushName(),
  489. Timestamp: time.Unix(int64(webMsg.GetMessageTimestamp()), 0),
  490. }
  491. var err error
  492. if info.IsFromMe {
  493. info.Sender = source.JID.ToNonAD()
  494. } else if portal.IsPrivateChat() {
  495. info.Sender = portal.Key.JID
  496. } else if webMsg.GetParticipant() != "" {
  497. info.Sender, err = types.ParseJID(webMsg.GetParticipant())
  498. } else if webMsg.GetKey().GetParticipant() != "" {
  499. info.Sender, err = types.ParseJID(webMsg.GetKey().GetParticipant())
  500. }
  501. if info.Sender.IsEmpty() {
  502. portal.log.Warnfln("Failed to get sender of message %s (parse error: %v)", info.ID, err)
  503. return nil
  504. }
  505. return &info
  506. }
  507. func (portal *Portal) appendBatchEvents(converted *ConvertedMessage, info *types.MessageInfo, expirationStart uint64, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  508. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra)
  509. if err != nil {
  510. return err
  511. }
  512. if converted.Caption != nil {
  513. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil)
  514. if err != nil {
  515. return err
  516. }
  517. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  518. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn}, nil)
  519. } else {
  520. *eventsArray = append(*eventsArray, mainEvt)
  521. *infoArray = append(*infoArray, &wrappedInfo{info, database.MsgNormal, converted.Error, converted.MediaKey, expirationStart, converted.ExpiresIn})
  522. }
  523. if converted.MultiEvent != nil {
  524. for _, subEvtContent := range converted.MultiEvent {
  525. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil)
  526. if err != nil {
  527. return err
  528. }
  529. *eventsArray = append(*eventsArray, subEvt)
  530. *infoArray = append(*infoArray, nil)
  531. }
  532. }
  533. return nil
  534. }
  535. const backfillIDField = "fi.mau.whatsapp.backfill_msg_id"
  536. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}) (*event.Event, error) {
  537. if extraContent == nil {
  538. extraContent = map[string]interface{}{}
  539. }
  540. extraContent[backfillIDField] = info.ID
  541. if intent.IsCustomPuppet {
  542. extraContent[doublePuppetKey] = doublePuppetValue
  543. }
  544. wrappedContent := event.Content{
  545. Parsed: content,
  546. Raw: extraContent,
  547. }
  548. newEventType, err := portal.encrypt(&wrappedContent, eventType)
  549. if err != nil {
  550. return nil, err
  551. }
  552. if newEventType == event.EventEncrypted {
  553. // Clear other custom keys if the event was encrypted, but keep the double puppet identifier
  554. wrappedContent.Raw = map[string]interface{}{backfillIDField: info.ID}
  555. if intent.IsCustomPuppet {
  556. wrappedContent.Raw[doublePuppetKey] = doublePuppetValue
  557. }
  558. }
  559. return &event.Event{
  560. Sender: intent.UserID,
  561. Type: newEventType,
  562. Timestamp: info.Timestamp.UnixMilli(),
  563. Content: wrappedContent,
  564. }, nil
  565. }
  566. func (portal *Portal) finishBatch(eventIDs []id.EventID, infos []*wrappedInfo) {
  567. if len(eventIDs) != len(infos) {
  568. portal.log.Errorfln("Length of event IDs (%d) and message infos (%d) doesn't match! Using slow path for mapping event IDs", len(eventIDs), len(infos))
  569. infoMap := make(map[types.MessageID]*wrappedInfo, len(infos))
  570. for _, info := range infos {
  571. infoMap[info.ID] = info
  572. }
  573. for _, eventID := range eventIDs {
  574. if evt, err := portal.MainIntent().GetEvent(portal.MXID, eventID); err != nil {
  575. portal.log.Warnfln("Failed to get event %s to register it in the database: %v", eventID, err)
  576. } else if msgID, ok := evt.Content.Raw[backfillIDField].(string); !ok {
  577. portal.log.Warnfln("Event %s doesn't include the WhatsApp message ID", eventID)
  578. } else if info, ok := infoMap[types.MessageID(msgID)]; !ok {
  579. portal.log.Warnfln("Didn't find info of message %s (event %s) to register it in the database", msgID, eventID)
  580. } else {
  581. portal.finishBatchEvt(info, eventID)
  582. }
  583. }
  584. } else {
  585. for i := 0; i < len(infos); i++ {
  586. portal.finishBatchEvt(infos[i], eventIDs[i])
  587. }
  588. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  589. }
  590. }
  591. func (portal *Portal) finishBatchEvt(info *wrappedInfo, eventID id.EventID) {
  592. if info == nil {
  593. return
  594. }
  595. portal.markHandled(nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  596. if info.ExpiresIn > 0 {
  597. if info.ExpirationStart > 0 {
  598. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  599. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  600. portal.MarkDisappearing(eventID, uint32(remainingSeconds), true)
  601. } else {
  602. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  603. portal.MarkDisappearing(eventID, info.ExpiresIn, false)
  604. }
  605. }
  606. }
  607. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  608. // TODO remove after clients stop using this
  609. _, _ = portal.MainIntent().SendMessageEvent(portal.MXID, BackfillEndDummyEvent, struct{}{})
  610. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, HistorySyncMarker, map[string]interface{}{
  611. "org.matrix.msc2716.marker.insertion": insertionEventId,
  612. //"m.marker.insertion": insertionEventId,
  613. })
  614. if err != nil {
  615. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  616. return
  617. }
  618. msg := portal.bridge.DB.Message.New()
  619. msg.Chat = portal.Key
  620. msg.MXID = resp.EventID
  621. msg.JID = types.MessageID(resp.EventID)
  622. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  623. msg.Sent = true
  624. msg.Insert()
  625. }
  626. // endregion