historysync.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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. "crypto/sha256"
  19. "encoding/base64"
  20. "fmt"
  21. "time"
  22. "maunium.net/go/mautrix/util/variationselector"
  23. waProto "go.mau.fi/whatsmeow/binary/proto"
  24. "go.mau.fi/whatsmeow/types"
  25. "maunium.net/go/mautrix"
  26. "maunium.net/go/mautrix/appservice"
  27. "maunium.net/go/mautrix/bridge/bridgeconfig"
  28. "maunium.net/go/mautrix/event"
  29. "maunium.net/go/mautrix/id"
  30. "maunium.net/go/mautrix/util/dbutil"
  31. "maunium.net/go/mautrix-whatsapp/config"
  32. "maunium.net/go/mautrix-whatsapp/database"
  33. )
  34. // region User history sync handling
  35. type wrappedInfo struct {
  36. *types.MessageInfo
  37. Type database.MessageType
  38. Error database.MessageErrorType
  39. ReactionTarget types.MessageID
  40. MediaKey []byte
  41. ExpirationStart uint64
  42. ExpiresIn uint32
  43. }
  44. func (user *User) handleHistorySyncsLoop() {
  45. if !user.bridge.Config.Bridge.HistorySync.Backfill {
  46. return
  47. }
  48. // Start the backfill queue.
  49. user.BackfillQueue = &BackfillQueue{
  50. BackfillQuery: user.bridge.DB.Backfill,
  51. reCheckChannels: []chan bool{},
  52. log: user.log.Sub("BackfillQueue"),
  53. }
  54. forwardAndImmediate := []database.BackfillType{database.BackfillImmediate, database.BackfillForward}
  55. // Immediate backfills can be done in parallel
  56. for i := 0; i < user.bridge.Config.Bridge.HistorySync.Immediate.WorkerCount; i++ {
  57. go user.HandleBackfillRequestsLoop(forwardAndImmediate, []database.BackfillType{})
  58. }
  59. // Deferred backfills should be handled synchronously so as not to
  60. // overload the homeserver. Users can configure their backfill stages
  61. // to be more or less aggressive with backfilling at this stage.
  62. go user.HandleBackfillRequestsLoop([]database.BackfillType{database.BackfillDeferred}, forwardAndImmediate)
  63. if user.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia &&
  64. user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod == config.MediaRequestMethodLocalTime {
  65. go user.dailyMediaRequestLoop()
  66. }
  67. // Always save the history syncs for the user. If they want to enable
  68. // backfilling in the future, we will have it in the database.
  69. for evt := range user.historySyncs {
  70. user.handleHistorySync(user.BackfillQueue, evt.Data)
  71. }
  72. }
  73. func (user *User) dailyMediaRequestLoop() {
  74. // Calculate when to do the first set of media retry requests
  75. now := time.Now()
  76. userTz, err := time.LoadLocation(user.Timezone)
  77. if err != nil {
  78. userTz = now.Local().Location()
  79. }
  80. tonightMidnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, userTz)
  81. midnightOffset := time.Duration(user.bridge.Config.Bridge.HistorySync.MediaRequests.RequestLocalTime) * time.Minute
  82. requestStartTime := tonightMidnight.Add(midnightOffset)
  83. // If the request time for today has already happened, we need to start the
  84. // request loop tomorrow instead.
  85. if requestStartTime.Before(now) {
  86. requestStartTime = requestStartTime.AddDate(0, 0, 1)
  87. }
  88. // Wait to start the loop
  89. user.log.Infof("Waiting until %s to do media retry requests", requestStartTime)
  90. time.Sleep(time.Until(requestStartTime))
  91. for {
  92. mediaBackfillRequests := user.bridge.DB.MediaBackfillRequest.GetMediaBackfillRequestsForUser(user.MXID)
  93. user.log.Infof("Sending %d media retry requests", len(mediaBackfillRequests))
  94. // Send all of the media backfill requests for the user at once
  95. for _, req := range mediaBackfillRequests {
  96. portal := user.GetPortalByJID(req.PortalKey.JID)
  97. _, err := portal.requestMediaRetry(user, req.EventID, req.MediaKey)
  98. if err != nil {
  99. user.log.Warnf("Failed to send media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  100. req.Status = database.MediaBackfillRequestStatusRequestFailed
  101. req.Error = err.Error()
  102. } else {
  103. user.log.Debugfln("Sent media retry request for %s / %s", req.PortalKey.String(), req.EventID)
  104. req.Status = database.MediaBackfillRequestStatusRequested
  105. }
  106. req.MediaKey = nil
  107. req.Upsert()
  108. }
  109. // Wait for 24 hours before making requests again
  110. time.Sleep(24 * time.Hour)
  111. }
  112. }
  113. func (user *User) backfillInChunks(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
  114. portal.backfillLock.Lock()
  115. defer portal.backfillLock.Unlock()
  116. if !user.shouldCreatePortalForHistorySync(conv, portal) {
  117. return
  118. }
  119. backfillState := user.bridge.DB.Backfill.GetBackfillState(user.MXID, &portal.Key)
  120. if backfillState == nil {
  121. backfillState = user.bridge.DB.Backfill.NewBackfillState(user.MXID, &portal.Key)
  122. }
  123. backfillState.SetProcessingBatch(true)
  124. defer backfillState.SetProcessingBatch(false)
  125. var forwardPrevID id.EventID
  126. var timeEnd *time.Time
  127. var isLatestEvents bool
  128. portal.latestEventBackfillLock.Lock()
  129. if req.BackfillType == database.BackfillForward {
  130. // TODO this overrides the TimeStart set when enqueuing the backfill
  131. // maybe the enqueue should instead include the prev event ID
  132. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  133. forwardPrevID = lastMessage.MXID
  134. start := lastMessage.Timestamp.Add(1 * time.Second)
  135. req.TimeStart = &start
  136. // Sending events at the end of the room (= latest events)
  137. isLatestEvents = true
  138. } else {
  139. firstMessage := portal.bridge.DB.Message.GetFirstInChat(portal.Key)
  140. if firstMessage != nil {
  141. end := firstMessage.Timestamp.Add(-1 * time.Second)
  142. timeEnd = &end
  143. user.log.Debugfln("Limiting backfill to end at %v", end)
  144. } else {
  145. // Portal is empty -> events are latest
  146. isLatestEvents = true
  147. }
  148. }
  149. if !isLatestEvents {
  150. // We'll use normal batch sending, so no need to keep blocking new message processing
  151. portal.latestEventBackfillLock.Unlock()
  152. } else {
  153. // This might involve sending events at the end of the room as non-historical events,
  154. // make sure we don't process messages until this is done.
  155. defer portal.latestEventBackfillLock.Unlock()
  156. }
  157. allMsgs := user.bridge.DB.HistorySync.GetMessagesBetween(user.MXID, conv.ConversationID, req.TimeStart, timeEnd, req.MaxTotalEvents)
  158. sendDisappearedNotice := false
  159. // If expired messages are on, and a notice has not been sent to this chat
  160. // about it having disappeared messages at the conversation timestamp, send
  161. // a notice indicating so.
  162. if len(allMsgs) == 0 && conv.EphemeralExpiration != nil && *conv.EphemeralExpiration > 0 {
  163. lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
  164. if lastMessage == nil || conv.LastMessageTimestamp.After(lastMessage.Timestamp) {
  165. sendDisappearedNotice = true
  166. }
  167. }
  168. if !sendDisappearedNotice && len(allMsgs) == 0 {
  169. user.log.Debugfln("Not backfilling %s: no bridgeable messages found", portal.Key.JID)
  170. return
  171. }
  172. if len(portal.MXID) == 0 {
  173. user.log.Debugln("Creating portal for", portal.Key.JID, "as part of history sync handling")
  174. err := portal.CreateMatrixRoom(user, nil, true, false)
  175. if err != nil {
  176. user.log.Errorfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  177. return
  178. }
  179. }
  180. // Update the backfill status here after the room has been created.
  181. portal.updateBackfillStatus(backfillState)
  182. if sendDisappearedNotice {
  183. user.log.Debugfln("Sending notice to %s that there are disappeared messages ending at %v", portal.Key.JID, conv.LastMessageTimestamp)
  184. resp, err := portal.sendMessage(portal.MainIntent(), event.EventMessage, &event.MessageEventContent{
  185. MsgType: event.MsgNotice,
  186. Body: portal.formatDisappearingMessageNotice(),
  187. }, nil, conv.LastMessageTimestamp.UnixMilli())
  188. if err != nil {
  189. portal.log.Errorln("Error sending disappearing messages notice event")
  190. return
  191. }
  192. msg := portal.bridge.DB.Message.New()
  193. msg.Chat = portal.Key
  194. msg.MXID = resp.EventID
  195. msg.JID = types.MessageID(resp.EventID)
  196. msg.Timestamp = conv.LastMessageTimestamp
  197. msg.Sent = true
  198. msg.Type = database.MsgFake
  199. msg.Insert(nil)
  200. user.markSelfReadFull(portal)
  201. return
  202. }
  203. 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)
  204. toBackfill := allMsgs[0:]
  205. var insertionEventIds []id.EventID
  206. for len(toBackfill) > 0 {
  207. var msgs []*waProto.WebMessageInfo
  208. if len(toBackfill) <= req.MaxBatchEvents || req.MaxBatchEvents < 0 {
  209. msgs = toBackfill
  210. toBackfill = nil
  211. } else {
  212. msgs = toBackfill[:req.MaxBatchEvents]
  213. toBackfill = toBackfill[req.MaxBatchEvents:]
  214. }
  215. if len(msgs) > 0 {
  216. time.Sleep(time.Duration(req.BatchDelay) * time.Second)
  217. user.log.Debugfln("Backfilling %d messages in %s (queue ID: %d)", len(msgs), portal.Key.JID, req.QueueID)
  218. resp := portal.backfill(user, msgs, req.BackfillType == database.BackfillForward, isLatestEvents, forwardPrevID)
  219. if resp != nil && (resp.BaseInsertionEventID != "" || !isLatestEvents) {
  220. insertionEventIds = append(insertionEventIds, resp.BaseInsertionEventID)
  221. }
  222. }
  223. }
  224. user.log.Debugfln("Finished backfilling %d messages in %s (queue ID: %d)", len(allMsgs), portal.Key.JID, req.QueueID)
  225. if len(insertionEventIds) > 0 {
  226. portal.sendPostBackfillDummy(
  227. time.Unix(int64(allMsgs[0].GetMessageTimestamp()), 0),
  228. insertionEventIds[0])
  229. }
  230. user.log.Debugfln("Deleting %d history sync messages after backfilling (queue ID: %d)", len(allMsgs), req.QueueID)
  231. err := user.bridge.DB.HistorySync.DeleteMessages(user.MXID, conv.ConversationID, allMsgs)
  232. if err != nil {
  233. user.log.Warnfln("Failed to delete %d history sync messages after backfilling (queue ID: %d): %v", len(allMsgs), req.QueueID, err)
  234. }
  235. if req.TimeStart == nil {
  236. // If the time start is nil, then there's no more history to backfill.
  237. backfillState.BackfillComplete = true
  238. if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_BUT_MORE_MESSAGES_REMAIN_ON_PRIMARY {
  239. // Since there are more messages on the phone, but we can't
  240. // backfill any more of them, indicate that the last timestamp
  241. // that we expect to be backfilled is the oldest one that was just
  242. // backfilled.
  243. backfillState.FirstExpectedTimestamp = allMsgs[len(allMsgs)-1].GetMessageTimestamp()
  244. } else if conv.EndOfHistoryTransferType == waProto.Conversation_COMPLETE_AND_NO_MORE_MESSAGE_REMAIN_ON_PRIMARY {
  245. // Since there are no more messages left on the phone, we've
  246. // backfilled everything. Indicate so by setting the expected
  247. // timestamp to 0 which means that the backfill goes to the
  248. // beginning of time.
  249. backfillState.FirstExpectedTimestamp = 0
  250. }
  251. backfillState.Upsert()
  252. portal.updateBackfillStatus(backfillState)
  253. }
  254. if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
  255. user.markSelfReadFull(portal)
  256. } else if user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold > 0 && conv.LastMessageTimestamp.Before(time.Now().Add(time.Duration(-user.bridge.Config.Bridge.HistorySync.UnreadHoursThreshold)*time.Hour)) {
  257. user.markSelfReadFull(portal)
  258. } else if user.bridge.Config.Bridge.SyncManualMarkedUnread {
  259. user.markUnread(portal, true)
  260. }
  261. }
  262. func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
  263. if len(portal.MXID) > 0 {
  264. if !user.bridge.AS.StateStore.IsInRoom(portal.MXID, user.MXID) {
  265. portal.ensureUserInvited(user)
  266. }
  267. // Portal exists, let backfill continue
  268. return true
  269. } else if !user.bridge.Config.Bridge.HistorySync.CreatePortals {
  270. user.log.Debugfln("Not creating portal for %s: creating rooms from history sync is disabled", portal.Key.JID)
  271. return false
  272. } else {
  273. // Portal doesn't exist, but should be created
  274. return true
  275. }
  276. }
  277. func (user *User) handleHistorySync(backfillQueue *BackfillQueue, evt *waProto.HistorySync) {
  278. if evt == nil || evt.SyncType == nil || evt.GetSyncType() == waProto.HistorySync_INITIAL_STATUS_V3 || evt.GetSyncType() == waProto.HistorySync_PUSH_NAME {
  279. return
  280. }
  281. description := fmt.Sprintf("type %s, %d conversations, chunk order %d, progress: %d", evt.GetSyncType(), len(evt.GetConversations()), evt.GetChunkOrder(), evt.GetProgress())
  282. user.log.Infoln("Storing history sync with", description)
  283. for _, conv := range evt.GetConversations() {
  284. jid, err := types.ParseJID(conv.GetId())
  285. if err != nil {
  286. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  287. continue
  288. } else if jid.Server == types.BroadcastServer {
  289. user.log.Debugfln("Skipping broadcast list %s in history sync", jid)
  290. continue
  291. }
  292. portal := user.GetPortalByJID(jid)
  293. historySyncConversation := user.bridge.DB.HistorySync.NewConversationWithValues(
  294. user.MXID,
  295. conv.GetId(),
  296. &portal.Key,
  297. getConversationTimestamp(conv),
  298. conv.GetMuteEndTime(),
  299. conv.GetArchived(),
  300. conv.GetPinned(),
  301. conv.GetDisappearingMode().GetInitiator(),
  302. conv.GetEndOfHistoryTransferType(),
  303. conv.EphemeralExpiration,
  304. conv.GetMarkedAsUnread(),
  305. conv.GetUnreadCount())
  306. historySyncConversation.Upsert()
  307. for _, rawMsg := range conv.GetMessages() {
  308. // Don't store messages that will just be skipped.
  309. msgEvt, err := user.Client.ParseWebMessage(portal.Key.JID, rawMsg.GetMessage())
  310. if err != nil {
  311. user.log.Warnln("Dropping historical message due to info parse error:", err)
  312. continue
  313. }
  314. msgType := getMessageType(msgEvt.Message)
  315. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  316. continue
  317. }
  318. // Don't store unsupported messages.
  319. if !containsSupportedMessage(msgEvt.Message) {
  320. continue
  321. }
  322. message, err := user.bridge.DB.HistorySync.NewMessageWithValues(user.MXID, conv.GetId(), msgEvt.Info.ID, rawMsg)
  323. if err != nil {
  324. user.log.Warnfln("Failed to save message %s in %s. Error: %+v", msgEvt.Info.ID, conv.GetId(), err)
  325. continue
  326. }
  327. message.Insert()
  328. }
  329. }
  330. // If this was the initial bootstrap, enqueue immediate backfills for the
  331. // most recent portals. If it's the last history sync event, start
  332. // backfilling the rest of the history of the portals.
  333. if user.bridge.Config.Bridge.HistorySync.Backfill {
  334. if evt.GetSyncType() != waProto.HistorySync_INITIAL_BOOTSTRAP && evt.GetProgress() < 98 {
  335. return
  336. }
  337. nMostRecent := user.bridge.DB.HistorySync.GetNMostRecentConversations(user.MXID, user.bridge.Config.Bridge.HistorySync.MaxInitialConversations)
  338. if len(nMostRecent) > 0 {
  339. // Find the portals for all of the conversations.
  340. portals := []*Portal{}
  341. for _, conv := range nMostRecent {
  342. jid, err := types.ParseJID(conv.ConversationID)
  343. if err != nil {
  344. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.ConversationID, err)
  345. continue
  346. }
  347. portals = append(portals, user.GetPortalByJID(jid))
  348. }
  349. switch evt.GetSyncType() {
  350. case waProto.HistorySync_INITIAL_BOOTSTRAP:
  351. // Enqueue immediate backfills for the most recent messages first.
  352. user.EnqueueImmediateBackfills(portals)
  353. case waProto.HistorySync_FULL, waProto.HistorySync_RECENT:
  354. user.EnqueueForwardBackfills(portals)
  355. // Enqueue deferred backfills as configured.
  356. user.EnqueueDeferredBackfills(portals)
  357. }
  358. // Tell the queue to check for new backfill requests.
  359. backfillQueue.ReCheck()
  360. }
  361. }
  362. }
  363. func getConversationTimestamp(conv *waProto.Conversation) uint64 {
  364. convTs := conv.GetConversationTimestamp()
  365. if convTs == 0 && len(conv.GetMessages()) > 0 {
  366. convTs = conv.Messages[0].GetMessage().GetMessageTimestamp()
  367. }
  368. return convTs
  369. }
  370. func (user *User) EnqueueImmediateBackfills(portals []*Portal) {
  371. for priority, portal := range portals {
  372. maxMessages := user.bridge.Config.Bridge.HistorySync.Immediate.MaxEvents
  373. initialBackfill := user.bridge.DB.Backfill.NewWithValues(user.MXID, database.BackfillImmediate, priority, &portal.Key, nil, maxMessages, maxMessages, 0)
  374. initialBackfill.Insert()
  375. }
  376. }
  377. func (user *User) EnqueueDeferredBackfills(portals []*Portal) {
  378. numPortals := len(portals)
  379. for stageIdx, backfillStage := range user.bridge.Config.Bridge.HistorySync.Deferred {
  380. for portalIdx, portal := range portals {
  381. var startDate *time.Time = nil
  382. if backfillStage.StartDaysAgo > 0 {
  383. startDaysAgo := time.Now().AddDate(0, 0, -backfillStage.StartDaysAgo)
  384. startDate = &startDaysAgo
  385. }
  386. backfillMessages := user.bridge.DB.Backfill.NewWithValues(
  387. user.MXID, database.BackfillDeferred, stageIdx*numPortals+portalIdx, &portal.Key, startDate, backfillStage.MaxBatchEvents, -1, backfillStage.BatchDelay)
  388. backfillMessages.Insert()
  389. }
  390. }
  391. }
  392. func (user *User) EnqueueForwardBackfills(portals []*Portal) {
  393. for priority, portal := range portals {
  394. lastMsg := user.bridge.DB.Message.GetLastInChat(portal.Key)
  395. if lastMsg == nil {
  396. continue
  397. }
  398. backfill := user.bridge.DB.Backfill.NewWithValues(
  399. user.MXID, database.BackfillForward, priority, &portal.Key, &lastMsg.Timestamp, -1, -1, 0)
  400. backfill.Insert()
  401. }
  402. }
  403. // endregion
  404. // region Portal backfilling
  405. func (portal *Portal) deterministicEventID(sender types.JID, messageID types.MessageID, partName string) id.EventID {
  406. data := fmt.Sprintf("%s/whatsapp/%s/%s", portal.MXID, sender.User, messageID)
  407. if partName != "" {
  408. data += "/" + partName
  409. }
  410. sum := sha256.Sum256([]byte(data))
  411. return id.EventID(fmt.Sprintf("$%s:whatsapp.com", base64.RawURLEncoding.EncodeToString(sum[:])))
  412. }
  413. var (
  414. PortalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
  415. PreBackfillDummyEvent = event.Type{Type: "fi.mau.dummy.pre_backfill", Class: event.MessageEventType}
  416. HistorySyncMarker = event.Type{Type: "org.matrix.msc2716.marker", Class: event.MessageEventType}
  417. BackfillStatusEvent = event.Type{Type: "com.beeper.backfill_status", Class: event.StateEventType}
  418. )
  419. func (portal *Portal) backfill(source *User, messages []*waProto.WebMessageInfo, isForward, isLatest bool, prevEventID id.EventID) *mautrix.RespBatchSend {
  420. var req mautrix.ReqBatchSend
  421. var infos []*wrappedInfo
  422. if !isForward {
  423. if portal.FirstEventID != "" || portal.NextBatchID != "" {
  424. req.PrevEventID = portal.FirstEventID
  425. req.BatchID = portal.NextBatchID
  426. } else {
  427. portal.log.Warnfln("Can't backfill %d messages through %s to chat: first event ID not known", len(messages), source.MXID)
  428. return nil
  429. }
  430. } else {
  431. req.PrevEventID = prevEventID
  432. }
  433. req.BeeperNewMessages = isLatest && req.BatchID == ""
  434. beforeFirstMessageTimestampMillis := (int64(messages[len(messages)-1].GetMessageTimestamp()) * 1000) - 1
  435. req.StateEventsAtStart = make([]*event.Event, 0)
  436. addedMembers := make(map[id.UserID]struct{})
  437. addMember := func(puppet *Puppet) {
  438. if portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  439. // Hungryserv doesn't need state_events_at_start, it can figure out memberships automatically
  440. return
  441. } else if _, alreadyAdded := addedMembers[puppet.MXID]; alreadyAdded {
  442. return
  443. }
  444. mxid := puppet.MXID.String()
  445. content := event.MemberEventContent{
  446. Membership: event.MembershipJoin,
  447. Displayname: puppet.Displayname,
  448. AvatarURL: puppet.AvatarURL.CUString(),
  449. }
  450. inviteContent := content
  451. inviteContent.Membership = event.MembershipInvite
  452. req.StateEventsAtStart = append(req.StateEventsAtStart, &event.Event{
  453. Type: event.StateMember,
  454. Sender: portal.MainIntent().UserID,
  455. StateKey: &mxid,
  456. Timestamp: beforeFirstMessageTimestampMillis,
  457. Content: event.Content{Parsed: &inviteContent},
  458. }, &event.Event{
  459. Type: event.StateMember,
  460. Sender: puppet.MXID,
  461. StateKey: &mxid,
  462. Timestamp: beforeFirstMessageTimestampMillis,
  463. Content: event.Content{Parsed: &content},
  464. })
  465. addedMembers[puppet.MXID] = struct{}{}
  466. }
  467. portal.log.Infofln("Processing history sync with %d messages (forward: %t, latest: %t, prev: %s, batch: %s)", len(messages), isForward, isLatest, req.PrevEventID, req.BatchID)
  468. // The messages are ordered newest to oldest, so iterate them in reverse order.
  469. for i := len(messages) - 1; i >= 0; i-- {
  470. webMsg := messages[i]
  471. msgEvt, err := source.Client.ParseWebMessage(portal.Key.JID, webMsg)
  472. if err != nil {
  473. continue
  474. }
  475. msgType := getMessageType(msgEvt.Message)
  476. if msgType == "unknown" || msgType == "ignore" || msgType == "unknown_protocol" {
  477. if msgType != "ignore" {
  478. portal.log.Debugfln("Skipping message %s with unknown type in backfill", msgEvt.Info.ID)
  479. }
  480. continue
  481. }
  482. if webMsg.GetPushName() != "" && webMsg.GetPushName() != "-" {
  483. existingContact, _ := source.Client.Store.Contacts.GetContact(msgEvt.Info.Sender)
  484. if !existingContact.Found || existingContact.PushName == "" {
  485. changed, _, err := source.Client.Store.Contacts.PutPushName(msgEvt.Info.Sender, webMsg.GetPushName())
  486. if err != nil {
  487. source.log.Errorfln("Failed to save push name of %s from historical message in device store: %v", msgEvt.Info.Sender, err)
  488. } else if changed {
  489. source.log.Debugfln("Got push name %s for %s from historical message", webMsg.GetPushName(), msgEvt.Info.Sender)
  490. }
  491. }
  492. }
  493. puppet := portal.getMessagePuppet(source, &msgEvt.Info)
  494. if puppet == nil {
  495. continue
  496. }
  497. intent := puppet.IntentFor(portal)
  498. if intent.IsCustomPuppet && !portal.bridge.Config.CanDoublePuppetBackfill(puppet.CustomMXID) {
  499. intent = puppet.DefaultIntent()
  500. }
  501. converted := portal.convertMessage(intent, source, &msgEvt.Info, msgEvt.Message, true)
  502. if converted == nil {
  503. portal.log.Debugfln("Skipping unsupported message %s in backfill", msgEvt.Info.ID)
  504. continue
  505. }
  506. if !intent.IsCustomPuppet && !portal.bridge.StateStore.IsInRoom(portal.MXID, puppet.MXID) {
  507. addMember(puppet)
  508. }
  509. if converted.ReplyTo != nil {
  510. portal.SetReply(converted.Content, converted.ReplyTo, true)
  511. }
  512. err = portal.appendBatchEvents(source, converted, &msgEvt.Info, webMsg, &req.Events, &infos)
  513. if err != nil {
  514. portal.log.Errorfln("Error handling message %s during backfill: %v", msgEvt.Info.ID, err)
  515. }
  516. }
  517. portal.log.Infofln("Made %d Matrix events from messages in batch", len(req.Events))
  518. if len(req.Events) == 0 {
  519. return nil
  520. }
  521. if len(req.BatchID) == 0 || isForward {
  522. portal.log.Debugln("Sending a dummy event to avoid forward extremity errors with backfill")
  523. _, err := portal.MainIntent().SendMessageEvent(portal.MXID, PreBackfillDummyEvent, struct{}{})
  524. if err != nil {
  525. portal.log.Warnln("Error sending pre-backfill dummy event:", err)
  526. }
  527. }
  528. resp, err := portal.MainIntent().BatchSend(portal.MXID, &req)
  529. if err != nil {
  530. portal.log.Errorln("Error batch sending messages:", err)
  531. return nil
  532. } else {
  533. txn, err := portal.bridge.DB.Begin()
  534. if err != nil {
  535. portal.log.Errorln("Failed to start transaction to save batch messages:", err)
  536. return nil
  537. }
  538. // Do the following block in the transaction
  539. {
  540. portal.finishBatch(txn, resp.EventIDs, infos)
  541. portal.NextBatchID = resp.NextBatchID
  542. portal.Update(txn)
  543. }
  544. err = txn.Commit()
  545. if err != nil {
  546. portal.log.Errorln("Failed to commit transaction to save batch messages:", err)
  547. return nil
  548. }
  549. if portal.bridge.Config.Bridge.HistorySync.MediaRequests.AutoRequestMedia {
  550. go portal.requestMediaRetries(source, resp.EventIDs, infos)
  551. }
  552. return resp
  553. }
  554. }
  555. func (portal *Portal) requestMediaRetries(source *User, eventIDs []id.EventID, infos []*wrappedInfo) {
  556. for i, info := range infos {
  557. if info != nil && info.Error == database.MsgErrMediaNotFound && info.MediaKey != nil {
  558. switch portal.bridge.Config.Bridge.HistorySync.MediaRequests.RequestMethod {
  559. case config.MediaRequestMethodImmediate:
  560. err := source.Client.SendMediaRetryReceipt(info.MessageInfo, info.MediaKey)
  561. if err != nil {
  562. portal.log.Warnfln("Failed to send post-backfill media retry request for %s: %v", info.ID, err)
  563. } else {
  564. portal.log.Debugfln("Sent post-backfill media retry request for %s", info.ID)
  565. }
  566. case config.MediaRequestMethodLocalTime:
  567. req := portal.bridge.DB.MediaBackfillRequest.NewMediaBackfillRequestWithValues(source.MXID, &portal.Key, eventIDs[i], info.MediaKey)
  568. req.Upsert()
  569. }
  570. }
  571. }
  572. }
  573. func (portal *Portal) appendBatchEvents(source *User, converted *ConvertedMessage, info *types.MessageInfo, raw *waProto.WebMessageInfo, eventsArray *[]*event.Event, infoArray *[]*wrappedInfo) error {
  574. if portal.bridge.Config.Bridge.CaptionInMessage {
  575. converted.MergeCaption()
  576. }
  577. mainEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Content, converted.Extra, "")
  578. if err != nil {
  579. return err
  580. }
  581. expirationStart := raw.GetEphemeralStartTimestamp()
  582. mainInfo := &wrappedInfo{
  583. MessageInfo: info,
  584. Type: database.MsgNormal,
  585. Error: converted.Error,
  586. MediaKey: converted.MediaKey,
  587. ExpirationStart: expirationStart,
  588. ExpiresIn: converted.ExpiresIn,
  589. }
  590. if converted.Caption != nil {
  591. captionEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, converted.Caption, nil, "caption")
  592. if err != nil {
  593. return err
  594. }
  595. *eventsArray = append(*eventsArray, mainEvt, captionEvt)
  596. *infoArray = append(*infoArray, mainInfo, nil)
  597. } else {
  598. *eventsArray = append(*eventsArray, mainEvt)
  599. *infoArray = append(*infoArray, mainInfo)
  600. }
  601. if converted.MultiEvent != nil {
  602. for i, subEvtContent := range converted.MultiEvent {
  603. subEvt, err := portal.wrapBatchEvent(info, converted.Intent, converted.Type, subEvtContent, nil, fmt.Sprintf("multi-%d", i))
  604. if err != nil {
  605. return err
  606. }
  607. *eventsArray = append(*eventsArray, subEvt)
  608. *infoArray = append(*infoArray, nil)
  609. }
  610. }
  611. // Sending reactions in the same batch requires deterministic event IDs, so only do it on hungryserv
  612. if portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  613. for _, reaction := range raw.GetReactions() {
  614. reactionEvent, reactionInfo := portal.wrapBatchReaction(source, reaction, mainEvt.ID, info.Timestamp)
  615. if reactionEvent != nil {
  616. *eventsArray = append(*eventsArray, reactionEvent)
  617. *infoArray = append(*infoArray, &wrappedInfo{
  618. MessageInfo: reactionInfo,
  619. ReactionTarget: info.ID,
  620. Type: database.MsgReaction,
  621. })
  622. }
  623. }
  624. }
  625. return nil
  626. }
  627. func (portal *Portal) wrapBatchReaction(source *User, reaction *waProto.Reaction, mainEventID id.EventID, mainEventTS time.Time) (reactionEvent *event.Event, reactionInfo *types.MessageInfo) {
  628. var senderJID types.JID
  629. if reaction.GetKey().GetFromMe() {
  630. senderJID = source.JID.ToNonAD()
  631. } else if reaction.GetKey().GetParticipant() != "" {
  632. senderJID, _ = types.ParseJID(reaction.GetKey().GetParticipant())
  633. } else if portal.IsPrivateChat() {
  634. senderJID = portal.Key.JID
  635. }
  636. if senderJID.IsEmpty() {
  637. return
  638. }
  639. reactionInfo = &types.MessageInfo{
  640. MessageSource: types.MessageSource{
  641. Chat: portal.Key.JID,
  642. Sender: senderJID,
  643. IsFromMe: reaction.GetKey().GetFromMe(),
  644. IsGroup: portal.IsGroupChat(),
  645. },
  646. ID: reaction.GetKey().GetId(),
  647. Timestamp: mainEventTS,
  648. }
  649. puppet := portal.getMessagePuppet(source, reactionInfo)
  650. if puppet == nil {
  651. return
  652. }
  653. intent := puppet.IntentFor(portal)
  654. content := event.ReactionEventContent{
  655. RelatesTo: event.RelatesTo{
  656. Type: event.RelAnnotation,
  657. EventID: mainEventID,
  658. Key: variationselector.Add(reaction.GetText()),
  659. },
  660. }
  661. if rawTS := reaction.GetSenderTimestampMs(); rawTS >= mainEventTS.UnixMilli() && rawTS <= time.Now().UnixMilli() {
  662. reactionInfo.Timestamp = time.UnixMilli(rawTS)
  663. }
  664. reactionEvent = &event.Event{
  665. ID: portal.deterministicEventID(senderJID, reactionInfo.ID, ""),
  666. Type: event.EventReaction,
  667. Content: event.Content{Parsed: content},
  668. Sender: intent.UserID,
  669. Timestamp: reactionInfo.Timestamp.UnixMilli(),
  670. }
  671. return
  672. }
  673. func (portal *Portal) wrapBatchEvent(info *types.MessageInfo, intent *appservice.IntentAPI, eventType event.Type, content *event.MessageEventContent, extraContent map[string]interface{}, partName string) (*event.Event, error) {
  674. wrappedContent := event.Content{
  675. Parsed: content,
  676. Raw: extraContent,
  677. }
  678. newEventType, err := portal.encrypt(intent, &wrappedContent, eventType)
  679. if err != nil {
  680. return nil, err
  681. }
  682. if newEventType != eventType {
  683. intent.AddDoublePuppetValue(&wrappedContent)
  684. }
  685. var eventID id.EventID
  686. if portal.bridge.Config.Homeserver.Software == bridgeconfig.SoftwareHungry {
  687. eventID = portal.deterministicEventID(info.Sender, info.ID, partName)
  688. }
  689. return &event.Event{
  690. ID: eventID,
  691. Sender: intent.UserID,
  692. Type: newEventType,
  693. Timestamp: info.Timestamp.UnixMilli(),
  694. Content: wrappedContent,
  695. }, nil
  696. }
  697. func (portal *Portal) finishBatch(txn dbutil.Transaction, eventIDs []id.EventID, infos []*wrappedInfo) {
  698. for i, info := range infos {
  699. if info == nil {
  700. continue
  701. }
  702. eventID := eventIDs[i]
  703. portal.markHandled(txn, nil, info.MessageInfo, eventID, true, false, info.Type, info.Error)
  704. if info.Type == database.MsgReaction {
  705. portal.upsertReaction(txn, nil, info.ReactionTarget, info.Sender, eventID, info.ID)
  706. }
  707. if info.ExpiresIn > 0 {
  708. if info.ExpirationStart > 0 {
  709. remainingSeconds := time.Unix(int64(info.ExpirationStart), 0).Add(time.Duration(info.ExpiresIn) * time.Second).Sub(time.Now()).Seconds()
  710. portal.log.Debugfln("Disappearing history sync message: expires in %d, started at %d, remaining %d", info.ExpiresIn, info.ExpirationStart, int(remainingSeconds))
  711. portal.MarkDisappearing(txn, eventID, uint32(remainingSeconds), true)
  712. } else {
  713. portal.log.Debugfln("Disappearing history sync message: expires in %d (not started)", info.ExpiresIn)
  714. portal.MarkDisappearing(txn, eventID, info.ExpiresIn, false)
  715. }
  716. }
  717. }
  718. portal.log.Infofln("Successfully sent %d events", len(eventIDs))
  719. }
  720. func (portal *Portal) sendPostBackfillDummy(lastTimestamp time.Time, insertionEventId id.EventID) {
  721. resp, err := portal.MainIntent().SendMessageEvent(portal.MXID, HistorySyncMarker, map[string]interface{}{
  722. "org.matrix.msc2716.marker.insertion": insertionEventId,
  723. //"m.marker.insertion": insertionEventId,
  724. })
  725. if err != nil {
  726. portal.log.Errorln("Error sending post-backfill dummy event:", err)
  727. return
  728. }
  729. msg := portal.bridge.DB.Message.New()
  730. msg.Chat = portal.Key
  731. msg.MXID = resp.EventID
  732. msg.JID = types.MessageID(resp.EventID)
  733. msg.Timestamp = lastTimestamp.Add(1 * time.Second)
  734. msg.Sent = true
  735. msg.Type = database.MsgFake
  736. msg.Insert(nil)
  737. }
  738. func (portal *Portal) updateBackfillStatus(backfillState *database.BackfillState) {
  739. backfillStatus := "backfilling"
  740. if backfillState.BackfillComplete {
  741. backfillStatus = "complete"
  742. }
  743. _, err := portal.MainIntent().SendStateEvent(portal.MXID, BackfillStatusEvent, "", map[string]interface{}{
  744. "status": backfillStatus,
  745. "first_timestamp": backfillState.FirstExpectedTimestamp * 1000,
  746. })
  747. if err != nil {
  748. portal.log.Errorln("Error sending backfill status event:", err)
  749. }
  750. }
  751. // endregion