fix(whatsapp): reconcile orphaned lid conversations

This commit is contained in:
wmq
2026-08-03 01:21:46 +08:00
parent 82f00ffb43
commit 9017c26f5b
+18 -9
View File
@@ -3506,23 +3506,29 @@ async function mergeLegacyWhatsAppConversations(tenantId, channel, jid, aliasJid
return imported
}
async function migrateDeviceQualifiedWhatsAppConversations() {
async function migrateLegacyWhatsAppIdentityConversations() {
const { rows } = await pool.query(
`SELECT tenant_id, data
FROM resources
WHERE kind='conversations'
AND data->>'channel'='whatsapp'
AND data->>'whatsappJid' LIKE '%:%@s.whatsapp.net'`,
AND (
data->>'whatsappJid' LIKE '%:%@s.whatsapp.net'
OR data->>'whatsappJid' LIKE '%@lid'
)`,
)
let migrated = 0
for (const row of rows) {
const tenantId = String(row.tenant_id)
const source = row.data
const rawJid = String(source.whatsappJid || '')
const jid = canonicalWhatsAppJid(rawJid)
if (!jid || jid === rawJid) continue
const channel = await getResource(tenantId, 'channels', source.channelId)
if (!channel || channel.type !== 'whatsapp') continue
const identity = rawJid.endsWith('@lid')
? await fetchWhatsAppIdentity(channel, rawJid, { includeProfile: false })
: null
const jid = canonicalWhatsAppJid(rawJid, identity || {})
if (!jid || jid === rawJid) continue
const targetId = `${channel.id}:${jid}`
if (await getResource(tenantId, 'conversation-tombstones', targetId)) continue
let target = await getResource(tenantId, 'conversations', targetId)
@@ -3547,7 +3553,7 @@ async function migrateDeviceQualifiedWhatsAppConversations() {
conversation: updated,
})
}
if (migrated) console.log(`已迁移 ${migrated} 个 WhatsApp 设备 JID 会话或消息`)
if (migrated) console.log(`已迁移 ${migrated} 个 WhatsApp 历史身份会话或消息`)
return migrated
}
@@ -5437,14 +5443,17 @@ for (const row of existingWhatsAppChannels.rows) {
})
})
}
setTimeout(() => {
void migrateDeviceQualifiedWhatsAppConversations().catch((error) => {
function runWhatsAppIdentityMigration() {
void migrateLegacyWhatsAppIdentityConversations().catch((error) => {
console.error(JSON.stringify({
message: 'WhatsApp 设备 JID 历史迁移失败',
message: 'WhatsApp 历史身份会话迁移失败',
error: error.message,
}))
})
}, 2_000).unref?.()
}
setTimeout(runWhatsAppIdentityMigration, 2_000).unref?.()
setTimeout(runWhatsAppIdentityMigration, 30_000).unref?.()
setInterval(runWhatsAppIdentityMigration, 10 * 60_000).unref?.()
async function reconcileFailedChannelWebhooks() {
const { rows } = await pool.query(