fix: восстановление уведомлений — реальные данные, дедупликация, все аккаунты
- exists-событие больше не шлёт фиктивный envelope (id:'', 'Новое письмо'); вместо этого оно немедленно запускает pollSingleFolder, которая получает реальные данные сообщения — клик по тосту корректно открывает письмо - UID-дедупликация (TTL 5 мин): одно и то же письмо не даёт два тоста, даже если exists + polling сработали почти одновременно - pollFolderTree при ошибке STATUS не обнуляет сохранённый счётчик (lastUnseenCount), чтобы не потерять точку отсчёта - refresh() опрашивает все подключённые аккаунты, а не только активный — пользователи с несколькими ящиками получают уведомления по каждому Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
4c3b14c7a9
commit
19f73efde2
2 changed files with 69 additions and 34 deletions
|
|
@ -34,6 +34,9 @@ export class ImapProvider implements IEmailProvider {
|
|||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
// folderId → last known unseen count for polling
|
||||
private lastUnseenCount = new Map<string, number>()
|
||||
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
|
||||
private notifiedUids = new Map<string, number>()
|
||||
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as ImapCredentials
|
||||
|
|
@ -367,19 +370,9 @@ export class ImapProvider implements IEmailProvider {
|
|||
this.newMailCallback = callback
|
||||
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
|
||||
// Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо)
|
||||
if (this.newMailCallback && data.prevCount > 0 && data.count > data.prevCount) {
|
||||
this.newMailCallback(data.path, {
|
||||
id: '',
|
||||
folderId: data.path,
|
||||
subject: 'Новое сообщение',
|
||||
from: { name: 'Новое письмо', email: '' },
|
||||
to: [],
|
||||
cc: [],
|
||||
date: new Date().toISOString(),
|
||||
flags: { seen: false, flagged: false, answered: false, deleted: false },
|
||||
hasAttachments: false,
|
||||
snippet: ''
|
||||
})
|
||||
if (data.prevCount > 0 && data.count > data.prevCount) {
|
||||
// Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
|
||||
this.pollSingleFolder(data.path).catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -462,36 +455,55 @@ export class ImapProvider implements IEmailProvider {
|
|||
try {
|
||||
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||
await this.pollFolderTree(tree.folders ?? [])
|
||||
} catch { /* ignore poll errors */ }
|
||||
} catch (err) {
|
||||
console.warn('[IMAP] pollNewMessages error:', (err as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
// Немедленная проверка одной папки — вызывается из exists-события
|
||||
private async pollSingleFolder(folderPath: string): Promise<void> {
|
||||
if (!this.newMailCallback) return
|
||||
try {
|
||||
await this.pollFolderTree([{ name: folderPath, path: folderPath }])
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
|
||||
for (const folder of folders) {
|
||||
try {
|
||||
const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null
|
||||
const unseen = status?.unseen ?? 0
|
||||
const prev = this.lastUnseenCount.get(folder.path)
|
||||
this.lastUnseenCount.set(folder.path, unseen)
|
||||
// Если STATUS вернул null или упал — не трогаем сохранённый счётчик
|
||||
if (status) {
|
||||
const unseen = status.unseen ?? 0
|
||||
const prev = this.lastUnseenCount.get(folder.path)
|
||||
this.lastUnseenCount.set(folder.path, unseen)
|
||||
|
||||
if (prev !== undefined && unseen > prev && this.newMailCallback) {
|
||||
// Получаем последнее непрочитанное письмо для уведомления
|
||||
const lock = await this.client.getMailboxLock(folder.path)
|
||||
try {
|
||||
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
|
||||
if (uids?.length) {
|
||||
const latestUid = Math.max(...uids).toString()
|
||||
for await (const msg of this.client.fetch(latestUid, {
|
||||
uid: true, envelope: true, flags: true
|
||||
}, { uid: true })) {
|
||||
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path))
|
||||
break
|
||||
if (prev !== undefined && unseen > prev && this.newMailCallback) {
|
||||
// Получаем последнее непрочитанное письмо для уведомления
|
||||
const lock = await this.client.getMailboxLock(folder.path)
|
||||
try {
|
||||
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
|
||||
if (uids?.length) {
|
||||
const latestUid = Math.max(...uids).toString()
|
||||
const dedupKey = `${folder.path}:${latestUid}`
|
||||
if (!this.isRecentlyNotified(dedupKey)) {
|
||||
for await (const msg of this.client.fetch(latestUid, {
|
||||
uid: true, envelope: true, flags: true
|
||||
}, { uid: true })) {
|
||||
this.markNotified(dedupKey)
|
||||
this.newMailCallback(folder.path, this.convertMessage(msg, folder.path))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
} catch { /* некоторые папки не поддерживают STATUS */ }
|
||||
} catch (err) {
|
||||
console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message)
|
||||
}
|
||||
|
||||
if (folder.folders?.length) {
|
||||
await this.pollFolderTree(folder.folders)
|
||||
|
|
@ -499,6 +511,25 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
}
|
||||
|
||||
private isRecentlyNotified(key: string): boolean {
|
||||
const expiry = this.notifiedUids.get(key)
|
||||
if (expiry === undefined) return false
|
||||
if (Date.now() < expiry) return true
|
||||
this.notifiedUids.delete(key)
|
||||
return false
|
||||
}
|
||||
|
||||
private markNotified(key: string): void {
|
||||
// Чистим старые записи при росте кэша
|
||||
if (this.notifiedUids.size > 200) {
|
||||
const now = Date.now()
|
||||
for (const [k, exp] of this.notifiedUids) {
|
||||
if (now >= exp) this.notifiedUids.delete(k)
|
||||
}
|
||||
}
|
||||
this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS)
|
||||
}
|
||||
|
||||
// ---- Private helpers ----
|
||||
|
||||
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
|
||||
|
|
|
|||
|
|
@ -214,8 +214,12 @@ function onExpandAfterLeave(el: Element): void {
|
|||
// ── Refresh ───────────────────────────────────────────────
|
||||
async function refresh(): Promise<void> {
|
||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||
// Проверяем новые письма во всех папках (для уведомлений)
|
||||
invoke('messages:poll', { accountId: accountsStore.activeAccountId }).catch(() => {})
|
||||
// Проверяем новые письма во всех подключённых аккаунтах (не только активном)
|
||||
for (const acc of accountsStore.accounts) {
|
||||
if (accountsStore.connectionStatus[acc.id]?.connected) {
|
||||
invoke('messages:poll', { accountId: acc.id }).catch(() => {})
|
||||
}
|
||||
}
|
||||
// Последовательно: loadMessages держит mailboxLock, STATUS упадёт если папка залочена параллельно
|
||||
await messagesStore.loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
||||
await foldersStore.refreshUnreadCounts(accountsStore.activeAccountId)
|
||||
|
|
|
|||
Loading…
Reference in a new issue