refactor: history processing

1. fixes issue when some chats/messages are not synced
2. adds info about whether the history chunk is the latest
This commit is contained in:
Adhiraj Singh
2022-01-16 12:51:08 +05:30
parent f09e0f85cc
commit 793b23cb21
3 changed files with 78 additions and 62 deletions

View File

@@ -1,7 +1,8 @@
import { downloadContentFromMessage } from "./messages-media";
import { proto } from "../../WAProto";
import { downloadContentFromMessage } from "./messages-media"
import { proto } from "../../WAProto"
import { promisify } from 'util'
import { inflate } from "zlib";
import { inflate } from "zlib"
import { Chat, Contact } from "../Types"
const inflatePromise = promisify(inflate)
@@ -16,4 +17,66 @@ export const downloadHistory = async(msg: proto.IHistorySyncNotification) => {
const syncData = proto.HistorySync.decode(buffer)
return syncData
}
export const processHistoryMessage = (item: proto.IHistorySync, historyCache: Set<string>) => {
const isLatest = historyCache.size === 0
const messages: proto.IWebMessageInfo[] = []
const contacts: Contact[] = []
const chats: Chat[] = []
switch(item.syncType) {
case proto.HistorySync.HistorySyncHistorySyncType.INITIAL_BOOTSTRAP:
case proto.HistorySync.HistorySyncHistorySyncType.RECENT:
for(const chat of item.conversations) {
const contactId = `c:${chat.id}`
if(chat.name && !historyCache.has(contactId)) {
contacts.push({
id: chat.id,
name: chat.name
})
historyCache.add(contactId)
}
for(const { message } of chat.messages || []) {
const uqId = `${message?.key.remoteJid}:${message.key.id}`
if(message && !historyCache.has(uqId)) {
messages.push(message)
historyCache.add(uqId)
}
}
delete chat.messages
if(!historyCache.has(chat.id)) {
chats.push(chat)
historyCache.add(chat.id)
}
}
break
case proto.HistorySync.HistorySyncHistorySyncType.PUSH_NAME:
for(const c of item.pushnames) {
const contactId = `c:${c.id}`
if(historyCache.has(contactId)) {
contacts.push({ notify: c.pushname, id: c.id })
historyCache.add(contactId)
}
}
break
case proto.HistorySync.HistorySyncHistorySyncType.INITIAL_STATUS_V3:
// TODO
break
}
if(chats.length || contacts.length || messages.length) {
return {
chats,
contacts,
messages,
isLatest,
}
}
}
export const downloadAndProcessHistorySyncNotification = async(msg: proto.IHistorySyncNotification, historyCache: Set<string>) => {
const historyMsg = await downloadHistory(msg)
return processHistoryMessage(historyMsg, historyCache)
}