This commit is contained in:
parent
587a20e05a
commit
a59400a77e
6 changed files with 152 additions and 22 deletions
|
|
@ -33,6 +33,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
private client: ImapFlow
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private closeCallback: (() => 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
|
||||
|
|
@ -53,6 +54,29 @@ export class ImapProvider implements IEmailProvider {
|
|||
},
|
||||
logger: false
|
||||
})
|
||||
// Без слушателя 'error' обрыв сокета превращается в uncaught exception в main
|
||||
this.client.on('error', (err: Error) => {
|
||||
console.warn('[IMAP] connection error:', err.message)
|
||||
this.connected = false
|
||||
})
|
||||
this.client.on('close', () => {
|
||||
this.connected = false
|
||||
this.closeCallback?.()
|
||||
})
|
||||
}
|
||||
|
||||
onClose(callback: () => void): void {
|
||||
this.closeCallback = callback
|
||||
}
|
||||
|
||||
getUnseenCounts(): Map<string, number> {
|
||||
return new Map(this.lastUnseenCount)
|
||||
}
|
||||
|
||||
seedUnseenCounts(counts: Map<string, number>): void {
|
||||
for (const [path, count] of counts) {
|
||||
if (!this.lastUnseenCount.has(path)) this.lastUnseenCount.set(path, count)
|
||||
}
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
|
|
@ -75,6 +99,7 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.closeCallback = null // штатное закрытие не должно запускать реконнект
|
||||
this.offNewMail()
|
||||
if (this.connected) {
|
||||
try {
|
||||
|
|
@ -571,12 +596,10 @@ export class ImapProvider implements IEmailProvider {
|
|||
|
||||
async pollNewMessages(): Promise<void> {
|
||||
if (!this.newMailCallback) return
|
||||
try {
|
||||
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||
await this.pollFolderTree(tree.folders ?? [])
|
||||
} catch (err) {
|
||||
console.warn('[IMAP] pollNewMessages error:', (err as Error).message)
|
||||
}
|
||||
// Ошибки не глотаем: AccountManager по ним переподключается (withAutoReconnect)
|
||||
if (!this.connected) throw Object.assign(new Error('IMAP connection lost'), { code: 'NoConnection' })
|
||||
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
|
||||
await this.pollFolderTree(tree.folders ?? [])
|
||||
}
|
||||
|
||||
// Немедленная проверка одной папки — вызывается из exists-события
|
||||
|
|
@ -621,6 +644,8 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Соединение умерло — не перебираем остальные папки с той же ошибкой
|
||||
if (!this.connected) throw err
|
||||
console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import { BrowserWindow, powerMonitor } from 'electron'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
import { AccountType } from '@shared/types/account'
|
||||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
||||
|
|
@ -16,6 +16,8 @@ interface AccountStoreSchema {
|
|||
|
||||
// Коды ошибок imapflow при потере соединения
|
||||
const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'])
|
||||
// Паузы между фоновыми попытками реконнекта; на последнем значении остаёмся
|
||||
const RECONNECT_BACKOFF_MS = [5_000, 30_000, 120_000, 300_000]
|
||||
|
||||
export class AccountManager {
|
||||
private providers = new Map<string, IEmailProvider>()
|
||||
|
|
@ -23,6 +25,9 @@ export class AccountManager {
|
|||
private store: Store<AccountStoreSchema>
|
||||
private credentialStore: CredentialStore
|
||||
private mainWindow: BrowserWindow | null = null
|
||||
// Одна попытка реконнекта на аккаунт: параллельные вызовы ждут общий промис
|
||||
private reconnecting = new Map<string, Promise<void>>()
|
||||
private reconnectTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
||||
|
||||
constructor() {
|
||||
this.store = new Store<AccountStoreSchema>({
|
||||
|
|
@ -30,6 +35,10 @@ export class AccountManager {
|
|||
defaults: { accounts: [] }
|
||||
})
|
||||
this.credentialStore = new CredentialStore()
|
||||
// После сна соединения обычно мертвы: проверяем сразу, не дожидаясь таймера опроса
|
||||
powerMonitor.on('resume', () => {
|
||||
for (const accountId of this.providers.keys()) void this.pollNewMessages(accountId)
|
||||
})
|
||||
}
|
||||
|
||||
setMainWindow(win: BrowserWindow): void {
|
||||
|
|
@ -70,6 +79,7 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
async removeAccount(accountId: string): Promise<void> {
|
||||
this.cancelScheduledReconnect(accountId)
|
||||
const provider = this.providers.get(accountId)
|
||||
if (provider) {
|
||||
provider.offNewMail()
|
||||
|
|
@ -134,10 +144,9 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
async pollNewMessages(accountId: string): Promise<void> {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (!provider) return
|
||||
if (!this.providers.has(accountId)) return
|
||||
try {
|
||||
await provider.pollNewMessages()
|
||||
await this.withAutoReconnect(accountId, () => this.getProvider(accountId).pollNewMessages())
|
||||
} catch (err) {
|
||||
console.warn(`[AccountManager] poll error for ${accountId}:`, (err as Error).message)
|
||||
}
|
||||
|
|
@ -312,22 +321,37 @@ export class AccountManager {
|
|||
} catch (err) {
|
||||
originalError = err
|
||||
const code = (err as { code?: string }).code ?? ''
|
||||
if (!RECONNECT_CODES.has(code)) throw err
|
||||
const isDead = this.providers.get(accountId)?.isConnected() === false
|
||||
if (!RECONNECT_CODES.has(code) && !isDead) throw err
|
||||
}
|
||||
|
||||
try {
|
||||
await this.reconnectAccount(accountId)
|
||||
} catch (reconnectErr) {
|
||||
console.error(`[AccountManager] reconnect failed for ${accountId}:`, reconnectErr)
|
||||
// Провайдер удалён — без фонового повтора аккаунт остался бы отключённым
|
||||
this.scheduleReconnect(accountId, 1)
|
||||
throw new Error(`Reconnect failed: ${(reconnectErr as Error).message}`, { cause: originalError })
|
||||
}
|
||||
|
||||
return await fn()
|
||||
}
|
||||
|
||||
private async reconnectAccount(accountId: string): Promise<void> {
|
||||
// Убиваем старый провайдер
|
||||
private reconnectAccount(accountId: string): Promise<void> {
|
||||
const inFlight = this.reconnecting.get(accountId)
|
||||
if (inFlight) return inFlight
|
||||
|
||||
const attempt = this.doReconnect(accountId).finally(() => this.reconnecting.delete(accountId))
|
||||
this.reconnecting.set(accountId, attempt)
|
||||
return attempt
|
||||
}
|
||||
|
||||
private async doReconnect(accountId: string): Promise<void> {
|
||||
this.cancelScheduledReconnect(accountId)
|
||||
|
||||
// Убиваем старый провайдер, забирая его счётчики непрочитанных
|
||||
const old = this.providers.get(accountId)
|
||||
const unseenCounts = old?.getUnseenCounts()
|
||||
if (old) {
|
||||
old.offNewMail()
|
||||
try { await old.disconnect() } catch { /* уже отвалился */ }
|
||||
|
|
@ -351,10 +375,37 @@ export class AccountManager {
|
|||
const config: AccountConfig = { ...accMeta, credentials }
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
// Без этого первое письмо после реконнекта не даст уведомления
|
||||
if (unseenCounts) provider.seedUnseenCounts(unseenCounts)
|
||||
this.providers.set(accountId, provider)
|
||||
this.setupNewMailListener(accountId, provider)
|
||||
}
|
||||
|
||||
// Фоновый реконнект после обрыва, с нарастающей паузой
|
||||
private scheduleReconnect(accountId: string, attempt = 0): void {
|
||||
if (this.reconnectTimers.has(accountId) || !this.isKnownAccount(accountId)) return
|
||||
const delay = RECONNECT_BACKOFF_MS[Math.min(attempt, RECONNECT_BACKOFF_MS.length - 1)]
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimers.delete(accountId)
|
||||
this.reconnectAccount(accountId).catch((err) => {
|
||||
console.warn(`[AccountManager] background reconnect failed for ${accountId}:`, (err as Error).message)
|
||||
// Провайдер уже удалён в doReconnect — планируем следующую попытку
|
||||
this.scheduleReconnect(accountId, attempt + 1)
|
||||
})
|
||||
}, delay)
|
||||
this.reconnectTimers.set(accountId, timer)
|
||||
}
|
||||
|
||||
private cancelScheduledReconnect(accountId: string): void {
|
||||
const timer = this.reconnectTimers.get(accountId)
|
||||
if (timer) clearTimeout(timer)
|
||||
this.reconnectTimers.delete(accountId)
|
||||
}
|
||||
|
||||
private isKnownAccount(accountId: string): boolean {
|
||||
return this.store.get('accounts', []).some((a) => a.id === accountId)
|
||||
}
|
||||
|
||||
// ── Private helpers ─────────────────────────────────────
|
||||
|
||||
private getProvider(accountId: string): IEmailProvider {
|
||||
|
|
@ -401,6 +452,7 @@ export class AccountManager {
|
|||
this.store.set('accounts', accounts)
|
||||
|
||||
// Reconnect if currently connected
|
||||
this.cancelScheduledReconnect(config.id)
|
||||
const existingProvider = this.providers.get(config.id)
|
||||
if (existingProvider) {
|
||||
existingProvider.offNewMail()
|
||||
|
|
@ -425,5 +477,11 @@ export class AccountManager {
|
|||
this.mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
||||
}
|
||||
})
|
||||
provider.onClose(() => {
|
||||
// Игнорируем close устаревшего провайдера (его уже заменили)
|
||||
if (this.providers.get(accountId) !== provider) return
|
||||
console.warn(`[AccountManager] connection closed for ${accountId}, scheduling reconnect`)
|
||||
this.scheduleReconnect(accountId)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { ref, computed } from 'vue'
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { startOfWeek, endOfWeek, addWeeks, subWeeks, startOfDay, isSameDay, isSameWeek } from 'date-fns'
|
||||
import { useIpc } from '../composables/useIpc'
|
||||
import { useAccountsStore } from './accounts.store'
|
||||
import { useSettingsStore } from './settings.store'
|
||||
import type { CalendarInfo, CalendarEvent } from '@shared/types/calendar'
|
||||
|
||||
const CAL_COLORS = ['#a8e600', '#38bdf8', '#a78bfa', '#f472b6', '#fb923c', '#4ade80', '#f87171']
|
||||
|
|
@ -18,6 +19,7 @@ export { CAL_COLORS }
|
|||
export const useCalendarStore = defineStore('calendar', () => {
|
||||
const { invoke } = useIpc()
|
||||
const accountsStore = useAccountsStore()
|
||||
const settingsStore = useSettingsStore()
|
||||
|
||||
// ── State ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -85,12 +87,19 @@ export const useCalendarStore = defineStore('calendar', () => {
|
|||
|
||||
// ── Events ─────────────────────────────────────────────────────────────────
|
||||
|
||||
async function loadEvents(): Promise<void> {
|
||||
// Номер последнего запроса: устаревший ответ (например, фоновое обновление
|
||||
// прошлой недели) не должен перезаписывать данные текущей
|
||||
let loadSeq = 0
|
||||
|
||||
async function loadEvents({ silent = false }: { silent?: boolean } = {}): Promise<void> {
|
||||
const accountId = accountsStore.activeAccountId
|
||||
if (!accountId || calendars.value.length === 0) return
|
||||
|
||||
loading.value = true
|
||||
error.value = null
|
||||
const seq = ++loadSeq
|
||||
if (!silent) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
}
|
||||
|
||||
try {
|
||||
const start = currentWeekStart.value.toISOString()
|
||||
|
|
@ -98,6 +107,8 @@ export const useCalendarStore = defineStore('calendar', () => {
|
|||
const end = new Date(currentWeekEnd.value.getTime() + 24 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
const allEvents: CalendarEvent[] = []
|
||||
let failed = 0
|
||||
let lastError: unknown = null
|
||||
for (const cal of calendars.value) {
|
||||
try {
|
||||
const calEvents = await invoke('calendar:events', {
|
||||
|
|
@ -107,18 +118,39 @@ export const useCalendarStore = defineStore('calendar', () => {
|
|||
end
|
||||
})
|
||||
allEvents.push(...calEvents)
|
||||
} catch {
|
||||
// Skip calendars that fail individually
|
||||
} catch (err) {
|
||||
// Отдельный упавший календарь пропускаем
|
||||
failed++
|
||||
lastError = err
|
||||
}
|
||||
}
|
||||
if (seq !== loadSeq) return
|
||||
if (failed === calendars.value.length) throw lastError
|
||||
events.value = allEvents
|
||||
} catch (err) {
|
||||
error.value = (err as Error).message
|
||||
// Фоновое обновление не должно затирать UI ошибкой — оставляем прежние события
|
||||
if (!silent && seq === loadSeq) error.value = (err as Error).message
|
||||
} finally {
|
||||
loading.value = false
|
||||
// Сбрасываем и в silent: он мог вытеснить обычную загрузку, и спиннер завис бы
|
||||
if (seq === loadSeq) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Автообновление ─────────────────────────────────────────────────────────
|
||||
// Store — синглтон, поэтому таймер живёт всё время работы приложения
|
||||
|
||||
let refreshTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
function restartRefreshTimer(minutes: number): void {
|
||||
if (refreshTimer) clearInterval(refreshTimer)
|
||||
refreshTimer = null
|
||||
if (minutes > 0) {
|
||||
refreshTimer = setInterval(() => void loadEvents({ silent: true }), minutes * 60_000)
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => settingsStore.calendarRefreshInterval, restartRefreshTimer, { immediate: true })
|
||||
|
||||
// ── Navigation ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function goToToday(): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -93,6 +93,7 @@ function load(): {
|
|||
swipeRightAction?: SwipeAction
|
||||
accentColor?: string
|
||||
autoCheckInterval?: number
|
||||
calendarRefreshInterval?: number
|
||||
uiScale?: number
|
||||
downloadFolder?: string
|
||||
designSystem?: DesignSystem
|
||||
|
|
@ -112,6 +113,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||
const swipeRightAction = ref<SwipeAction>(saved.swipeRightAction ?? 'toggleRead')
|
||||
const accentColor = ref<string>(saved.accentColor ?? '#a8e600')
|
||||
const autoCheckInterval = ref<number>(saved.autoCheckInterval ?? 1)
|
||||
const calendarRefreshInterval = ref<number>(saved.calendarRefreshInterval ?? 5)
|
||||
const uiScale = ref<number>(saved.uiScale ?? 1.0)
|
||||
const downloadFolder = ref<string>(saved.downloadFolder ?? '')
|
||||
const designSystem = ref<DesignSystem>(saved.designSystem ?? 'liquid-glass')
|
||||
|
|
@ -144,7 +146,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||
persist()
|
||||
})
|
||||
|
||||
watch([swipeLeftAction, swipeRightAction, autoCheckInterval, downloadFolder], persist)
|
||||
watch([swipeLeftAction, swipeRightAction, autoCheckInterval, calendarRefreshInterval, downloadFolder], persist)
|
||||
|
||||
function persist(): void {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
||||
|
|
@ -152,6 +154,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||
swipeRightAction: swipeRightAction.value,
|
||||
accentColor: accentColor.value,
|
||||
autoCheckInterval: autoCheckInterval.value,
|
||||
calendarRefreshInterval: calendarRefreshInterval.value,
|
||||
uiScale: uiScale.value,
|
||||
downloadFolder: downloadFolder.value,
|
||||
designSystem: designSystem.value,
|
||||
|
|
@ -164,6 +167,7 @@ export const useSettingsStore = defineStore('settings', () => {
|
|||
swipeRightAction,
|
||||
accentColor,
|
||||
autoCheckInterval,
|
||||
calendarRefreshInterval,
|
||||
uiScale,
|
||||
downloadFolder,
|
||||
designSystem,
|
||||
|
|
|
|||
|
|
@ -201,6 +201,12 @@ function folderDisplayName(path: string): string {
|
|||
<CustomSelect v-model="settingsStore.autoCheckInterval" :options="AUTO_CHECK_INTERVALS" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span class="col-label">Календарь</span>
|
||||
<div class="col-value">
|
||||
<CustomSelect v-model="settingsStore.calendarRefreshInterval" :options="AUTO_CHECK_INTERVALS" />
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="reminderSettings">
|
||||
<div class="row">
|
||||
<span class="col-label">Встречи</span>
|
||||
|
|
|
|||
|
|
@ -32,6 +32,11 @@ export interface IEmailProvider {
|
|||
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
|
||||
offNewMail(): void
|
||||
/** Вызывается, когда соединение закрылось не по инициативе приложения. */
|
||||
onClose(callback: () => void): void
|
||||
/** Счётчики непрочитанных по папкам — переносятся в новый провайдер при реконнекте. */
|
||||
getUnseenCounts(): Map<string, number>
|
||||
seedUnseenCounts(counts: Map<string, number>): void
|
||||
pollNewMessages(): Promise<void>
|
||||
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
|
||||
sendMessage(compose: ComposeData): Promise<void>
|
||||
|
|
|
|||
Loading…
Reference in a new issue