Фильтр непрочитанных загружает письма с сервера через IMAP SEARCH UNSEEN
Ранее фильтр работал только по уже загруженным 50 сообщениям. Теперь при включении фильтра выполняется SEARCH UNSEEN — возвращает UID всех непрочитанных, пагинация работает по этому списку. Добавлен unseenOnly в MessageListOptions и toggleUnreadOnly() в store. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
068ba4144e
commit
3d3f6f4a29
6 changed files with 60 additions and 16 deletions
|
|
@ -2,8 +2,8 @@ import { registerHandler } from './registry'
|
||||||
import type { AccountManager } from '../services/account-manager'
|
import type { AccountManager } from '../services/account-manager'
|
||||||
|
|
||||||
export function registerMessageHandlers(manager: AccountManager): void {
|
export function registerMessageHandlers(manager: AccountManager): void {
|
||||||
registerHandler('messages:list', async ({ accountId, folderId, offset, limit }) => {
|
registerHandler('messages:list', async ({ accountId, folderId, offset, limit, unseenOnly }) => {
|
||||||
return manager.listMessages(accountId, folderId, offset, limit)
|
return manager.listMessages(accountId, folderId, offset, limit, unseenOnly ?? false)
|
||||||
})
|
})
|
||||||
|
|
||||||
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
registerHandler('messages:body', async ({ accountId, folderId, messageId }) => {
|
||||||
|
|
|
||||||
|
|
@ -94,16 +94,18 @@ export class ImapProvider implements IEmailProvider {
|
||||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||||
const lock = await this.client.getMailboxLock(options.folderId)
|
const lock = await this.client.getMailboxLock(options.folderId)
|
||||||
try {
|
try {
|
||||||
|
if (options.unseenOnly) {
|
||||||
|
return await this.listUnseenMessages(options)
|
||||||
|
}
|
||||||
|
|
||||||
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
|
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
|
||||||
if (total === 0) return { messages: [], total: 0 }
|
if (total === 0) return { messages: [], total: 0, unseen: 0 }
|
||||||
|
|
||||||
// IMAP sequence numbers are 1-based, newest = highest number
|
// IMAP sequence numbers are 1-based, newest = highest number
|
||||||
const end = Math.max(1, total - options.offset)
|
const end = Math.max(1, total - options.offset)
|
||||||
const start = Math.max(1, end - options.limit + 1)
|
const start = Math.max(1, end - options.limit + 1)
|
||||||
|
|
||||||
if (start > total) return { messages: [], total }
|
if (start > total) return { messages: [], total, unseen: 0 }
|
||||||
|
|
||||||
const unseen = (this.client.mailbox as { unseen?: number })?.unseen ?? 0
|
|
||||||
|
|
||||||
const messages: MessageEnvelope[] = []
|
const messages: MessageEnvelope[] = []
|
||||||
|
|
||||||
|
|
@ -119,12 +121,39 @@ export class ImapProvider implements IEmailProvider {
|
||||||
// Newest first
|
// Newest first
|
||||||
messages.reverse()
|
messages.reverse()
|
||||||
|
|
||||||
return { messages, total, unseen }
|
return { messages, total, unseen: 0 }
|
||||||
} finally {
|
} finally {
|
||||||
lock.release()
|
lock.release()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async listUnseenMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||||
|
// Mailbox lock is already held by listMessages caller
|
||||||
|
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
|
||||||
|
if (!uids || uids.length === 0) return { messages: [], total: 0, unseen: 0 }
|
||||||
|
|
||||||
|
const total = uids.length
|
||||||
|
// Sort descending — higher UID = newer message
|
||||||
|
const sorted = [...uids].sort((a, b) => b - a)
|
||||||
|
const page = sorted.slice(options.offset, options.offset + options.limit)
|
||||||
|
if (page.length === 0) return { messages: [], total, unseen: total }
|
||||||
|
|
||||||
|
const uidSet = page.join(',')
|
||||||
|
const messages: MessageEnvelope[] = []
|
||||||
|
for await (const msg of this.client.fetch(uidSet, {
|
||||||
|
uid: true,
|
||||||
|
envelope: true,
|
||||||
|
flags: true,
|
||||||
|
bodyStructure: true
|
||||||
|
}, { uid: true })) {
|
||||||
|
messages.push(this.convertMessage(msg, options.folderId))
|
||||||
|
}
|
||||||
|
// Fetch returns ascending order → reverse to newest first
|
||||||
|
messages.sort((a, b) => Number(b.id) - Number(a.id))
|
||||||
|
|
||||||
|
return { messages, total, unseen: total }
|
||||||
|
}
|
||||||
|
|
||||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||||
const lock = await this.client.getMailboxLock(folderId)
|
const lock = await this.client.getMailboxLock(folderId)
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
|
|
@ -125,10 +125,11 @@ export class AccountManager {
|
||||||
accountId: string,
|
accountId: string,
|
||||||
folderId: string,
|
folderId: string,
|
||||||
offset: number,
|
offset: number,
|
||||||
limit: number
|
limit: number,
|
||||||
|
unseenOnly = false
|
||||||
): Promise<MessageListResult> {
|
): Promise<MessageListResult> {
|
||||||
const provider = this.getProvider(accountId)
|
const provider = this.getProvider(accountId)
|
||||||
return provider.listMessages({ folderId, offset, limit })
|
return provider.listMessages({ folderId, offset, limit, unseenOnly })
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetchMessageBody(
|
async fetchMessageBody(
|
||||||
|
|
|
||||||
|
|
@ -146,7 +146,7 @@ async function handleSwipeAction(action: SwipeAction, messageId: string): Promis
|
||||||
class="message-count"
|
class="message-count"
|
||||||
:class="{ 'unread-active': messagesStore.unreadOnly }"
|
:class="{ 'unread-active': messagesStore.unreadOnly }"
|
||||||
title="Только непрочитанные"
|
title="Только непрочитанные"
|
||||||
@click="messagesStore.unreadOnly = !messagesStore.unreadOnly"
|
@click="messagesStore.toggleUnreadOnly()"
|
||||||
>
|
>
|
||||||
{{ activeUnread }}
|
{{ activeUnread }}
|
||||||
</button>
|
</button>
|
||||||
|
|
|
||||||
|
|
@ -58,22 +58,26 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
accountId,
|
accountId,
|
||||||
folderId,
|
folderId,
|
||||||
offset,
|
offset,
|
||||||
limit: PAGE_SIZE
|
limit: PAGE_SIZE,
|
||||||
|
unseenOnly: unreadOnly.value
|
||||||
})
|
})
|
||||||
|
|
||||||
if (offset === 0) {
|
if (offset === 0) {
|
||||||
messages.value = result.messages
|
messages.value = result.messages
|
||||||
if (result.messages.length >= result.total) {
|
if (unreadOnly.value) {
|
||||||
|
// result.total — это точное число непрочитанных из SEARCH UNSEEN
|
||||||
|
foldersStore.setFolderUnread(accountId, folderId, result.total)
|
||||||
|
} else if (result.messages.length >= result.total) {
|
||||||
// Все письма загружены — считаем точно из флагов
|
// Все письма загружены — считаем точно из флагов
|
||||||
const exactUnread = result.messages.filter((m) => !m.flags.seen).length
|
const exactUnread = result.messages.filter((m) => !m.flags.seen).length
|
||||||
foldersStore.setFolderUnread(accountId, folderId, exactUnread)
|
foldersStore.setFolderUnread(accountId, folderId, exactUnread)
|
||||||
}
|
}
|
||||||
// Для частичной загрузки не трогаем счётчик — он уже выставлен через IMAP STATUS
|
// Для частичной загрузки не трогаем счётчик — он уже выставлен через IMAP STATUS
|
||||||
// в populateUnreadCounts при старте. Gmail не возвращает [UNSEEN n] в SELECT,
|
|
||||||
// поэтому client.mailbox.unseen ненадёжен.
|
|
||||||
|
|
||||||
// Предзагрузка тел первых 10 писем в фоне
|
// Предзагрузка тел первых 10 писем в фоне (только в обычном режиме)
|
||||||
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
|
if (!unreadOnly.value) {
|
||||||
|
setTimeout(() => prefetchBodies(accountId, folderId, 10), 600)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
messages.value.push(...result.messages)
|
messages.value.push(...result.messages)
|
||||||
}
|
}
|
||||||
|
|
@ -185,6 +189,14 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
selectedIds.value = new Set()
|
selectedIds.value = new Set()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function toggleUnreadOnly(): Promise<void> {
|
||||||
|
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId) return
|
||||||
|
unreadOnly.value = !unreadOnly.value
|
||||||
|
messages.value = []
|
||||||
|
totalCount.value = 0
|
||||||
|
await loadMessages(accountsStore.activeAccountId, foldersStore.activeFolderId, 0)
|
||||||
|
}
|
||||||
|
|
||||||
async function deleteSelected(): Promise<void> {
|
async function deleteSelected(): Promise<void> {
|
||||||
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
if (!accountsStore.activeAccountId || !foldersStore.activeFolderId || selectedIds.value.size === 0) return
|
||||||
const ids = [...selectedIds.value]
|
const ids = [...selectedIds.value]
|
||||||
|
|
@ -338,6 +350,7 @@ export const useMessagesStore = defineStore('messages', () => {
|
||||||
toggleSelect,
|
toggleSelect,
|
||||||
selectAll,
|
selectAll,
|
||||||
clearSelected,
|
clearSelected,
|
||||||
|
toggleUnreadOnly,
|
||||||
deleteSelected,
|
deleteSelected,
|
||||||
markSelectedAsRead,
|
markSelectedAsRead,
|
||||||
deleteOne,
|
deleteOne,
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ export interface MessageListOptions {
|
||||||
folderId: string
|
folderId: string
|
||||||
offset: number
|
offset: number
|
||||||
limit: number
|
limit: number
|
||||||
|
unseenOnly?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MessageListResult {
|
export interface MessageListResult {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue