refactor: удалён мёртвый код Gmail/Exchange, оптимизация производительности, обновлён README
- Удалены gmail.provider.ts, exchange.provider.ts, oauth.handler.ts, oauth.service.ts - AccountType упрощён до IMAP, удалены ExchangeCredentials/GmailCredentials - prefetchBodies: параллельная загрузка через Promise.all вместо цикла - populateUnreadCounts: параллельные STATUS запросы пакетами по 5 - MessageList: searchDebounce очищается при onUnmounted - Исправлены pre-existing TS ошибки (InlineImage/Attachment импорт, focusedWindow → getFocusedWindow) - README переработан в полный технический документ (архитектура, IPC, data flow, stores) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
62648ac76e
commit
121cc3dd9a
14 changed files with 340 additions and 728 deletions
360
README.md
360
README.md
|
|
@ -1,6 +1,6 @@
|
|||
# Aero Mail
|
||||
|
||||
Десктопный почтовый клиент с поддержкой IMAP, стеклянным UI и динамическим ambient-свечением от контента письма.
|
||||
Десктопный почтовый клиент на Electron + Vue 3. Работает по протоколам **IMAP** (чтение) и **SMTP** (отправка).
|
||||
|
||||
**Стек:** Electron 35 · Vue 3 · Pinia · TypeScript · electron-vite
|
||||
|
||||
|
|
@ -8,56 +8,32 @@
|
|||
|
||||
## Возможности
|
||||
|
||||
- Подключение любого IMAP-ящика
|
||||
- Подключение любого IMAP/SMTP ящика
|
||||
- Жидкое стекло (liquid glass) в интерфейсе с анимированными переходами
|
||||
- Динамическое фоновое свечение — цвет берётся из открытого письма
|
||||
- Фильтрация непрочитанных через IMAP `SEARCH UNSEEN`
|
||||
- Бейджи непрочитанных в сайдбаре (IMAP STATUS)
|
||||
- Бейджи непрочитанных в сайдбаре (IMAP `STATUS`)
|
||||
- Свайп-жесты на письмах (мышь и трекпад)
|
||||
- Пагинация, предзагрузка тел писем, TTL-кэш
|
||||
- Встроенный sanitizer HTML-писем
|
||||
- Пагинация, параллельная предзагрузка тел писем, LRU-кэш (100 записей, TTL 3ч)
|
||||
- Поиск по теме и отправителю через IMAP SEARCH
|
||||
- Тредирование по заголовкам RFC 2822 + subject-based fallback
|
||||
- Встроенный sanitizer HTML-писем (sanitize-html + DOMPurify)
|
||||
- Отдельное окно для написания / ответа / пересылки
|
||||
- Уведомления о новых письмах
|
||||
|
||||
---
|
||||
|
||||
## Установка из исходников
|
||||
## Быстрый старт
|
||||
|
||||
### Требования
|
||||
|
||||
- **Node.js** ≥ 20
|
||||
- **npm** ≥ 10
|
||||
- **Git**
|
||||
|
||||
### 1. Клонировать репозиторий
|
||||
|
||||
```bash
|
||||
git clone https://github.com/your-username/aero-mail.git
|
||||
cd aero-mail
|
||||
```
|
||||
|
||||
### 2. Установить зависимости
|
||||
### Запуск
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 3. Настроить переменные окружения
|
||||
|
||||
Скопируй `.env.example` в `.env` и заполни, если планируешь использовать Gmail OAuth:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
```env
|
||||
GMAIL_CLIENT_ID=your-client-id.apps.googleusercontent.com
|
||||
GMAIL_CLIENT_SECRET=your-client-secret
|
||||
```
|
||||
|
||||
> Для обычных IMAP-ящиков (Яндекс, Mail.ru, Fastmail и др.) `.env` не нужен — данные вводятся в интерфейсе приложения.
|
||||
|
||||
### 4. Запустить в режиме разработки
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
|
|
@ -67,27 +43,15 @@ npm run dev
|
|||
|
||||
## Сборка
|
||||
|
||||
### Проверка типов
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
npm run typecheck # проверка типов
|
||||
npm run build:linux # AppImage + .deb
|
||||
npm run build:win # NSIS installer
|
||||
npm run build:mac # .dmg
|
||||
npm run build:unpack # распакованная сборка (для отладки)
|
||||
```
|
||||
|
||||
### Собрать под текущую платформу
|
||||
|
||||
```bash
|
||||
npm run build:linux # AppImage + .deb
|
||||
npm run build:win # NSIS installer
|
||||
npm run build:mac # .dmg
|
||||
```
|
||||
|
||||
Артефакты появятся в папке `dist/`.
|
||||
|
||||
### Распакованная сборка (без инсталлятора, для отладки)
|
||||
|
||||
```bash
|
||||
npm run build:unpack
|
||||
```
|
||||
Артефакты — в папке `dist/`.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -95,32 +59,292 @@ npm run build:unpack
|
|||
|
||||
```
|
||||
src/
|
||||
├── main/ # Electron main process
|
||||
│ ├── ipc/ # IPC-обработчики (папки, письма, аккаунты)
|
||||
│ ├── providers/ # IMAP-провайдер (imapflow)
|
||||
│ ├── services/ # AccountManager
|
||||
│ └── lib/ # HTML sanitizer
|
||||
├── renderer/ # Vue 3 приложение
|
||||
├── main/ # Electron main process
|
||||
│ ├── index.ts # Точка входа приложения, создание окон
|
||||
│ ├── ipc/
|
||||
│ │ ├── accounts.handler.ts # IPC: управление аккаунтами
|
||||
│ │ ├── folders.handler.ts # IPC: список папок
|
||||
│ │ ├── messages.handler.ts # IPC: письма, вложения, отправка
|
||||
│ │ └── registry.ts # Утилита registerHandler()
|
||||
│ ├── providers/
|
||||
│ │ └── imap.provider.ts # Единственный провайдер: IMAP + SMTP
|
||||
│ ├── services/
|
||||
│ │ ├── account-manager.ts # Управление провайдерами, IPC-роутинг
|
||||
│ │ └── credential-store.ts # Зашифрованное хранение паролей
|
||||
│ └── lib/
|
||||
│ └── html-sanitizer.ts # Санитизация HTML писем
|
||||
│
|
||||
├── renderer/
|
||||
│ └── src/
|
||||
│ ├── components/ # UI-компоненты
|
||||
│ ├── stores/ # Pinia stores
|
||||
│ ├── main.ts # Точка входа Vue + vue-router
|
||||
│ ├── App.vue # Корневой компонент
|
||||
│ ├── views/
|
||||
│ │ ├── MailView.vue # Главный экран (список + просмотр)
|
||||
│ │ ├── ComposeView.vue # Окно написания письма
|
||||
│ │ └── SettingsView.vue # Настройки аккаунтов и приложения
|
||||
│ ├── stores/
|
||||
│ │ ├── accounts.store.ts # Аккаунты, статус соединений
|
||||
│ │ ├── messages.store.ts # Список писем, кэш тел, поиск, флаги
|
||||
│ │ ├── folders.store.ts # Дерево папок, счётчики непрочитанных
|
||||
│ │ ├── compose.store.ts # Сессии написания (new/reply/forward)
|
||||
│ │ ├── notifications.store.ts
|
||||
│ │ └── settings.store.ts # Настройки UI, свайп-действия, зум
|
||||
│ ├── components/ # ~30 Vue компонентов
|
||||
│ │ ├── messages/
|
||||
│ │ │ ├── MessageList.vue # Список тредов со свайпами
|
||||
│ │ │ ├── MessageListItem.vue # Элемент списка
|
||||
│ │ │ ├── ThreadListItem.vue # Заголовок треда
|
||||
│ │ │ └── MessagePreview.vue # Просмотр письма
|
||||
│ │ ├── sidebar/ # Левая панель: аккаунты + папки
|
||||
│ │ └── settings/ # Компоненты страницы настроек
|
||||
│ ├── composables/
|
||||
│ └── assets/
|
||||
└── shared/ # Общие типы (main + renderer)
|
||||
│ │ └── useIpc.ts # Типобезопасные обёртки invoke/on
|
||||
│ └── utils/
|
||||
│ ├── threading.ts # Алгоритм тредирования RFC 2822
|
||||
│ └── date.ts # Форматирование дат
|
||||
│
|
||||
├── preload/
|
||||
│ ├── index.ts # contextBridge: exposing window.api
|
||||
│ └── index.d.ts # Типы window.api для renderer
|
||||
│
|
||||
└── shared/
|
||||
└── types/
|
||||
├── account.ts # AccountConfig, ImapCredentials
|
||||
├── folder.ts # Folder, SpecialFolderRole
|
||||
├── message.ts # MessageEnvelope, MessageBody, ComposeData
|
||||
├── provider.ts # IEmailProvider interface
|
||||
└── ipc.ts # IpcChannelMap, IpcEventMap
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Архитектура
|
||||
|
||||
### Три процесса Electron
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Main Process (Node.js) │
|
||||
│ ┌─────────────────┐ ┌────────────────────────┐ │
|
||||
│ │ AccountManager │ │ IPC Handlers │ │
|
||||
│ │ providers Map │ │ accounts/folders/ │ │
|
||||
│ │ ImapProvider │ │ messages handlers │ │
|
||||
│ └────────┬────────┘ └───────────┬────────────┘ │
|
||||
└───────────┼───────────────────────┼────────────────┘
|
||||
│ IMAP/SMTP │ ipcMain.handle / webContents.send
|
||||
▼ ▼
|
||||
Mail server ┌───────────────┐
|
||||
│ Preload │
|
||||
│ contextBridge │
|
||||
│ window.api │
|
||||
└───────┬───────┘
|
||||
│ invoke / on
|
||||
▼
|
||||
┌────────────────────────────────┐
|
||||
│ Renderer Process (Vue 3) │
|
||||
│ Pinia stores ↔ Vue components │
|
||||
└────────────────────────────────┘
|
||||
```
|
||||
|
||||
### IPC паттерн
|
||||
|
||||
**Renderer → Main** (promise-based):
|
||||
```typescript
|
||||
const result = await invoke('messages:list', { accountId, folderId, offset, limit })
|
||||
```
|
||||
|
||||
**Main → Renderer** (события):
|
||||
```typescript
|
||||
mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
||||
```
|
||||
|
||||
### IPC каналы
|
||||
|
||||
**invoke (Renderer → Main):**
|
||||
|
||||
| Канал | Описание |
|
||||
|-------|---------|
|
||||
| `accounts:list` | Список сохранённых аккаунтов |
|
||||
| `accounts:add` | Добавить аккаунт (подключение + сохранение) |
|
||||
| `accounts:remove` | Удалить аккаунт |
|
||||
| `accounts:test` | Проверить соединение без сохранения |
|
||||
| `accounts:connect` | Переподключить аккаунт |
|
||||
| `accounts:update` | Обновить настройки аккаунта |
|
||||
| `folders:list` | Дерево папок с счётчиками |
|
||||
| `messages:list` | Список писем с пагинацией |
|
||||
| `messages:body` | Тело письма (HTML/text + вложения) |
|
||||
| `messages:setFlags` | Изменить флаги (seen, flagged, deleted) |
|
||||
| `messages:delete` | Удалить письма |
|
||||
| `messages:attachment:download` | Скачать вложение |
|
||||
| `messages:poll` | Принудительный poll новых писем |
|
||||
| `messages:search` | Поиск по теме и отправителю |
|
||||
| `messages:send` | Отправить письмо через SMTP |
|
||||
| `compose:open` | Открыть окно написания |
|
||||
| `compose:getData` | Получить данные сессии compose |
|
||||
| `compose:pickFiles` | Диалог выбора файлов для вложений |
|
||||
| `app:getDownloadsFolder` | Путь к Downloads |
|
||||
| `app:chooseFolder` | Диалог выбора папки |
|
||||
| `app:openFile` | Открыть файл в ОС |
|
||||
| `app:setZoom` | Масштаб окна |
|
||||
|
||||
**events (Main → Renderer):**
|
||||
|
||||
| Событие | Описание |
|
||||
|---------|---------|
|
||||
| `mail:new` | Пришло новое письмо |
|
||||
| `account:status` | Изменился статус соединения |
|
||||
| `attachment:progress` | Прогресс скачивания вложения |
|
||||
| `notification:click` | Пользователь кликнул по уведомлению |
|
||||
|
||||
---
|
||||
|
||||
## Поток данных
|
||||
|
||||
### Загрузка писем
|
||||
|
||||
```
|
||||
1. Пользователь выбирает папку
|
||||
→ watch(activeFolderId) в messages.store
|
||||
→ loadMessages(accountId, folderId)
|
||||
|
||||
2. invoke('messages:list') → AccountManager → ImapProvider
|
||||
→ IMAP getMailboxLock → client.fetch (envelope + flags)
|
||||
→ { messages[], total }
|
||||
|
||||
3. messages.store: messages.value = result.messages
|
||||
→ setTimeout 600ms → prefetchBodies(10) параллельно
|
||||
|
||||
4. Пользователь кликает письмо
|
||||
→ selectMessage(id)
|
||||
→ проверка LRU кэша (100 записей, TTL 3ч)
|
||||
→ при miss: invoke('messages:body') → simpleParser → sanitizeHtml
|
||||
→ invoke('messages:setFlags', { seen: true })
|
||||
```
|
||||
|
||||
### Обнаружение новых писем
|
||||
|
||||
```
|
||||
ImapProvider слушает событие 'exists' от imapflow
|
||||
→ data.count > data.prevCount
|
||||
→ mainWindow.webContents.send('mail:new', { accountId, folderId, envelope })
|
||||
→ messages.store: messages.value.unshift(envelope)
|
||||
→ foldersStore.updateFolderUnread(+1)
|
||||
→ notifications.store показывает уведомление
|
||||
```
|
||||
|
||||
### Отправка письма
|
||||
|
||||
```
|
||||
1. composeStore.openNew() / openReply() / openForward()
|
||||
→ invoke('compose:open', session)
|
||||
→ main: createComposeWindow() с hash '#/compose'
|
||||
|
||||
2. Окно compose читает сессию:
|
||||
→ invoke('compose:getData')
|
||||
|
||||
3. Пользователь нажимает Send:
|
||||
→ invoke('messages:send', { accountId, compose })
|
||||
→ ImapProvider.sendMessage() → nodemailer transporter
|
||||
→ SMTP отправка
|
||||
→ best-effort: append в папку Sent через IMAP
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Provider Pattern
|
||||
|
||||
Интерфейс `IEmailProvider` (`src/shared/types/provider.ts`):
|
||||
|
||||
```typescript
|
||||
interface IEmailProvider {
|
||||
connect(): Promise<void>
|
||||
disconnect(): Promise<void>
|
||||
isConnected(): boolean
|
||||
listFolders(): Promise<FolderListResult>
|
||||
listMessages(options: MessageListOptions): Promise<MessageListResult>
|
||||
fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody>
|
||||
downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise<Buffer>
|
||||
updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void>
|
||||
deleteMessages(folderId: string, messageIds: string[]): Promise<void>
|
||||
sendMessage(compose: ComposeData): Promise<void>
|
||||
searchMessages(query: string, limit: number): Promise<MessageEnvelope[]>
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void
|
||||
offNewMail(): void
|
||||
pollNewMessages(): Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
Сейчас реализован только `ImapProvider`. Для добавления нового провайдера:
|
||||
1. Создать класс в `src/main/providers/`
|
||||
2. Реализовать `IEmailProvider`
|
||||
3. Добавить тип в `AccountType` (`src/shared/types/account.ts`)
|
||||
4. Добавить ветку в `AccountManager.createProvider()`
|
||||
|
||||
---
|
||||
|
||||
## State Management (Pinia)
|
||||
|
||||
```
|
||||
useAccountsStore useSettingsStore
|
||||
activeAccountId ←──────────────────────
|
||||
accounts[] swipeLeftAction
|
||||
│ swipeRightAction
|
||||
▼ zoomFactor
|
||||
useFoldersStore
|
||||
foldersByAccount{}
|
||||
activeFolderId
|
||||
unreadCounts{}
|
||||
│
|
||||
▼
|
||||
useMessagesStore
|
||||
messages[] ← paginated list (PAGE_SIZE=50)
|
||||
filteredMessages ← computed (unreadOnly filter)
|
||||
selectedMessageId
|
||||
messageBody ← LRU cache 100 entries / 3h TTL
|
||||
searchResults[]
|
||||
│
|
||||
▼
|
||||
useComposeStore
|
||||
sessions Map<windowId, ComposeSession>
|
||||
|
||||
useNotificationsStore
|
||||
pending notifications queue
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Кэширование и производительность
|
||||
|
||||
| Механизм | Реализация | Параметры |
|
||||
|----------|-----------|-----------|
|
||||
| LRU body cache | `Map` в messages.store | 100 записей, TTL 3ч |
|
||||
| Prefetch тел | `Promise.all()` в фоне | 10 писем, delay 600ms |
|
||||
| Пагинация | IMAP sequence range | PAGE_SIZE = 50 |
|
||||
| Unread filter | IMAP `SEARCH UNSEEN` | точный список UID |
|
||||
| STATUS параллельно | `Promise.all` batch=5 | при listFolders |
|
||||
| Тредирование | `computed` в MessageList | RFC 2822 + subject |
|
||||
|
||||
---
|
||||
|
||||
## Добавление почтового ящика
|
||||
|
||||
1. Запусти приложение
|
||||
2. Нажми **+** в левой панели
|
||||
3. Введи IMAP-данные:
|
||||
- **Хост** — например `imap.gmail.com`
|
||||
- **Порт** — `993` (SSL) или `143` (STARTTLS)
|
||||
- **Логин** и **пароль** (для Gmail используй пароль приложения)
|
||||
3. Введи IMAP/SMTP данные:
|
||||
- **IMAP хост** — например `imap.gmail.com`
|
||||
- **IMAP порт** — `993` (TLS) или `143` (STARTTLS)
|
||||
- **Логин** и **пароль**
|
||||
- SMTP настройки — опционально; если не указаны, выводятся из IMAP хоста
|
||||
|
||||
> Gmail: перед подключением включи IMAP в настройках аккаунта и создай [пароль приложения](https://myaccount.google.com/apppasswords).
|
||||
> Gmail: включи IMAP в настройках аккаунта и создай [пароль приложения](https://myaccount.google.com/apppasswords).
|
||||
|
||||
---
|
||||
|
||||
## Известные ограничения
|
||||
|
||||
- Поиск идёт по всем папкам последовательно — медленно на ящиках с 50+ папок
|
||||
- `onNewMail` через imapflow `exists` не возвращает реальный envelope нового письма (только заглушку); полные данные подгружаются при следующем poll
|
||||
- Inline-изображения в письмах рендерятся только если сервер передаёт их как base64 в теле
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -28,8 +28,6 @@
|
|||
"dompurify": "^3.2.4",
|
||||
"dotenv": "^17.3.1",
|
||||
"electron-store": "^8.2.0",
|
||||
"ews-javascript-api": "^0.11.0",
|
||||
"googleapis": "^144.0.0",
|
||||
"imapflow": "^1.0.171",
|
||||
"jsdom": "^29.0.1",
|
||||
"mailparser": "^3.9.6",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { AccountManager } from './services/account-manager'
|
|||
import { registerAccountHandlers } from './ipc/accounts.handler'
|
||||
import { registerFolderHandlers } from './ipc/folders.handler'
|
||||
import { registerMessageHandlers } from './ipc/messages.handler'
|
||||
import { registerOAuthHandlers } from './ipc/oauth.handler'
|
||||
import type { ComposeSession } from '@shared/types/message'
|
||||
|
||||
const accountManager = new AccountManager()
|
||||
|
|
@ -59,7 +58,7 @@ ipcMain.handle('compose:getData', (event) => {
|
|||
|
||||
ipcMain.handle('compose:pickFiles', async (event) => {
|
||||
const win = BrowserWindow.fromWebContents(event.sender)
|
||||
const result = await dialog.showOpenDialog(win ?? app.focusedWindow() ?? BrowserWindow.getAllWindows()[0], {
|
||||
const result = await dialog.showOpenDialog(win ?? BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], {
|
||||
properties: ['openFile', 'multiSelections'],
|
||||
title: 'Прикрепить файлы'
|
||||
})
|
||||
|
|
@ -143,7 +142,6 @@ app.whenReady().then(async () => {
|
|||
registerAccountHandlers(accountManager)
|
||||
registerFolderHandlers(accountManager)
|
||||
registerMessageHandlers(accountManager)
|
||||
registerOAuthHandlers()
|
||||
|
||||
createWindow()
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
import { registerHandler } from './registry'
|
||||
import { performGmailOAuth } from '../services/oauth.service'
|
||||
|
||||
export function registerOAuthHandlers(): void {
|
||||
registerHandler('oauth:gmail', async () => {
|
||||
return await performGmailOAuth()
|
||||
})
|
||||
}
|
||||
|
|
@ -1,206 +0,0 @@
|
|||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope } from '@shared/types/message'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { AccountConfig, ExchangeCredentials } from '@shared/types/account'
|
||||
import { sanitizeHtml } from '../lib/html-sanitizer'
|
||||
|
||||
// EWS imports
|
||||
import {
|
||||
ExchangeService,
|
||||
ExchangeVersion,
|
||||
WebCredentials,
|
||||
Uri,
|
||||
WellKnownFolderName,
|
||||
FolderView,
|
||||
ItemView,
|
||||
PropertySet,
|
||||
BasePropertySet,
|
||||
EmailMessageSchema,
|
||||
FolderSchema,
|
||||
Folder as EwsFolder,
|
||||
EmailMessage,
|
||||
ItemId,
|
||||
FolderId as EwsFolderId,
|
||||
SortDirection
|
||||
} from 'ews-javascript-api'
|
||||
|
||||
export class ExchangeProvider implements IEmailProvider {
|
||||
private service: ExchangeService
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private pollInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as ExchangeCredentials
|
||||
this.service = new ExchangeService(ExchangeVersion.Exchange2013)
|
||||
this.service.Credentials = new WebCredentials(creds.username, creds.password, creds.domain)
|
||||
this.service.Url = new Uri(creds.serverUrl)
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
const view = new FolderView(1)
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view), timeout])
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.offNewMail()
|
||||
this.connected = false
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this.connected
|
||||
}
|
||||
|
||||
async listFolders(): Promise<FolderListResult> {
|
||||
const view = new FolderView(100)
|
||||
view.PropertySet = new PropertySet(
|
||||
BasePropertySet.IdOnly,
|
||||
FolderSchema.DisplayName,
|
||||
FolderSchema.UnreadCount,
|
||||
FolderSchema.TotalCount,
|
||||
FolderSchema.ParentFolderId
|
||||
)
|
||||
|
||||
const result = await this.service.FindFolders(WellKnownFolderName.MsgFolderRoot, view)
|
||||
const folders: Folder[] = result.Folders.map((f: EwsFolder) => ({
|
||||
id: f.Id.UniqueId,
|
||||
name: f.DisplayName,
|
||||
role: this.detectRole(f.DisplayName),
|
||||
parentId: null,
|
||||
unreadCount: f.UnreadCount ?? 0,
|
||||
totalCount: f.TotalCount ?? 0,
|
||||
children: []
|
||||
}))
|
||||
|
||||
return { folders }
|
||||
}
|
||||
|
||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||
const view = new ItemView(options.limit, options.offset)
|
||||
view.PropertySet = new PropertySet(
|
||||
BasePropertySet.IdOnly,
|
||||
EmailMessageSchema.Subject,
|
||||
EmailMessageSchema.From,
|
||||
EmailMessageSchema.ToRecipients,
|
||||
EmailMessageSchema.CcRecipients,
|
||||
EmailMessageSchema.DateTimeReceived,
|
||||
EmailMessageSchema.IsRead,
|
||||
EmailMessageSchema.HasAttachments,
|
||||
EmailMessageSchema.Importance
|
||||
)
|
||||
view.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending)
|
||||
|
||||
const folderId = new EwsFolderId(options.folderId)
|
||||
const result = await this.service.FindItems(folderId, view)
|
||||
|
||||
const messages: MessageEnvelope[] = result.Items.map((item: EmailMessage) => ({
|
||||
id: item.Id.UniqueId,
|
||||
folderId: options.folderId,
|
||||
subject: item.Subject ?? '(no subject)',
|
||||
from: {
|
||||
name: item.From?.Name ?? '',
|
||||
email: item.From?.Address ?? ''
|
||||
},
|
||||
to: (item.ToRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
|
||||
name: r.Name ?? '',
|
||||
email: r.Address ?? ''
|
||||
})),
|
||||
cc: (item.CcRecipients?.GetEnumerator() ?? []).map((r: { Name: string; Address: string }) => ({
|
||||
name: r.Name ?? '',
|
||||
email: r.Address ?? ''
|
||||
})),
|
||||
date: item.DateTimeReceived?.toISOString() ?? new Date().toISOString(),
|
||||
flags: {
|
||||
seen: item.IsRead ?? false,
|
||||
flagged: false,
|
||||
answered: false,
|
||||
deleted: false
|
||||
},
|
||||
hasAttachments: item.HasAttachments ?? false,
|
||||
snippet: ''
|
||||
}))
|
||||
|
||||
return { messages, total: result.TotalCount ?? messages.length }
|
||||
}
|
||||
|
||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId), new PropertySet(
|
||||
BasePropertySet.FirstClassProperties
|
||||
))
|
||||
|
||||
let html: string | null = null
|
||||
let text: string | null = null
|
||||
|
||||
const body = msg.Body?.Text ?? ''
|
||||
if (msg.Body?.BodyType === 0) { // HTML
|
||||
html = sanitizeHtml(body)
|
||||
} else {
|
||||
text = body
|
||||
}
|
||||
|
||||
return {
|
||||
id: messageId,
|
||||
html,
|
||||
text,
|
||||
inlineImages: [],
|
||||
attachments: []
|
||||
}
|
||||
}
|
||||
|
||||
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
|
||||
if (flags.seen !== undefined) {
|
||||
msg.IsRead = flags.seen
|
||||
}
|
||||
await msg.Update(1) // ConflictResolutionMode.AutoResolve
|
||||
}
|
||||
}
|
||||
|
||||
async downloadAttachment(_folderId: string, _messageId: string, _attachmentId: string): Promise<Buffer> {
|
||||
throw new Error('Attachment download not supported for Exchange accounts')
|
||||
}
|
||||
|
||||
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
const msg = await EmailMessage.Bind(this.service, new ItemId(messageId))
|
||||
await msg.Delete(1) // DeleteMode.HardDelete
|
||||
}
|
||||
}
|
||||
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
// EWS doesn't support push natively from JS — poll every 60s
|
||||
this.pollInterval = setInterval(async () => {
|
||||
// Simplified polling — in production would track last known count
|
||||
}, 60_000)
|
||||
}
|
||||
|
||||
offNewMail(): void {
|
||||
this.newMailCallback = null
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval)
|
||||
this.pollInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
async pollNewMessages(): Promise<void> { /* Exchange использует свой polling через onNewMail */ }
|
||||
async searchMessages(_query: string, _limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> { return [] }
|
||||
async sendMessage(_compose: import('@shared/types/message').ComposeData): Promise<void> { throw new Error('Send not implemented for Exchange') }
|
||||
|
||||
private detectRole(name: string): SpecialFolderRole {
|
||||
const n = name.toLowerCase()
|
||||
if (n === 'inbox') return SpecialFolderRole.Inbox
|
||||
if (n === 'sent items' || n === 'sent') return SpecialFolderRole.Sent
|
||||
if (n === 'drafts') return SpecialFolderRole.Drafts
|
||||
if (n === 'deleted items' || n === 'trash') return SpecialFolderRole.Trash
|
||||
if (n === 'junk email' || n === 'spam') return SpecialFolderRole.Spam
|
||||
if (n === 'archive') return SpecialFolderRole.Archive
|
||||
return SpecialFolderRole.None
|
||||
}
|
||||
}
|
||||
|
|
@ -1,314 +0,0 @@
|
|||
import { google, gmail_v1 } from 'googleapis'
|
||||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address, InlineImage, Attachment } from '@shared/types/message'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { AccountConfig, GmailCredentials } from '@shared/types/account'
|
||||
import { sanitizeHtml } from '../lib/html-sanitizer'
|
||||
|
||||
const GMAIL_CLIENT_ID = process.env.GMAIL_CLIENT_ID ?? ''
|
||||
const GMAIL_CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET ?? ''
|
||||
|
||||
export class GmailProvider implements IEmailProvider {
|
||||
private gmail: gmail_v1.Gmail
|
||||
private connected = false
|
||||
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
|
||||
private pollInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
constructor(private config: AccountConfig) {
|
||||
const creds = config.credentials as GmailCredentials
|
||||
const oauth2 = new google.auth.OAuth2(GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET)
|
||||
oauth2.setCredentials({
|
||||
access_token: creds.accessToken,
|
||||
refresh_token: creds.refreshToken
|
||||
})
|
||||
this.gmail = google.gmail({ version: 'v1', auth: oauth2 })
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
const timeout = new Promise<never>((_, reject) =>
|
||||
setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
|
||||
)
|
||||
await Promise.race([this.gmail.users.getProfile({ userId: 'me' }), timeout])
|
||||
this.connected = true
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.offNewMail()
|
||||
this.connected = false
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
return this.connected
|
||||
}
|
||||
|
||||
async listFolders(): Promise<FolderListResult> {
|
||||
const res = await this.gmail.users.labels.list({ userId: 'me' })
|
||||
const labels = res.data.labels ?? []
|
||||
|
||||
const folders: Folder[] = labels
|
||||
.filter((l) => l.type === 'system' || l.labelListVisibility === 'labelShow')
|
||||
.map((label) => {
|
||||
const details = label as gmail_v1.Schema$Label
|
||||
return {
|
||||
id: details.id ?? '',
|
||||
name: details.name ?? '',
|
||||
role: this.detectRole(details.id ?? ''),
|
||||
parentId: null,
|
||||
unreadCount: details.messagesUnread ?? 0,
|
||||
totalCount: details.messagesTotal ?? 0,
|
||||
children: []
|
||||
}
|
||||
})
|
||||
|
||||
return { folders }
|
||||
}
|
||||
|
||||
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
|
||||
const res = await this.gmail.users.messages.list({
|
||||
userId: 'me',
|
||||
labelIds: [options.folderId],
|
||||
maxResults: options.limit
|
||||
})
|
||||
|
||||
const messageRefs = res.data.messages ?? []
|
||||
const total = res.data.resultSizeEstimate ?? messageRefs.length
|
||||
|
||||
const messages: MessageEnvelope[] = []
|
||||
|
||||
for (const ref of messageRefs) {
|
||||
if (!ref.id) continue
|
||||
try {
|
||||
const msg = await this.gmail.users.messages.get({
|
||||
userId: 'me',
|
||||
id: ref.id,
|
||||
format: 'metadata',
|
||||
metadataHeaders: ['From', 'To', 'Cc', 'Subject', 'Date']
|
||||
})
|
||||
messages.push(this.convertMessage(msg.data, options.folderId))
|
||||
} catch {
|
||||
// Skip messages that fail to load
|
||||
}
|
||||
}
|
||||
|
||||
return { messages, total }
|
||||
}
|
||||
|
||||
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
|
||||
const msg = await this.gmail.users.messages.get({
|
||||
userId: 'me',
|
||||
id: messageId,
|
||||
format: 'full'
|
||||
})
|
||||
|
||||
const { html, text, inlineImages, attachments } = this.extractBody(msg.data)
|
||||
|
||||
return {
|
||||
id: messageId,
|
||||
html: html ? sanitizeHtml(html) : null,
|
||||
text,
|
||||
inlineImages,
|
||||
attachments
|
||||
}
|
||||
}
|
||||
|
||||
async downloadAttachment(_folderId: string, messageId: string, attachmentId: string): Promise<Buffer> {
|
||||
const res = await this.gmail.users.messages.attachments.get({
|
||||
userId: 'me',
|
||||
messageId,
|
||||
id: attachmentId
|
||||
})
|
||||
const data = res.data.data
|
||||
if (!data) throw new Error('Attachment not found')
|
||||
return Buffer.from(data, 'base64url')
|
||||
}
|
||||
|
||||
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
|
||||
const addLabels: string[] = []
|
||||
const removeLabels: string[] = []
|
||||
|
||||
if (flags.seen === true) removeLabels.push('UNREAD')
|
||||
if (flags.seen === false) addLabels.push('UNREAD')
|
||||
if (flags.flagged === true) addLabels.push('STARRED')
|
||||
if (flags.flagged === false) removeLabels.push('STARRED')
|
||||
if (flags.deleted === true) addLabels.push('TRASH')
|
||||
|
||||
if (addLabels.length > 0 || removeLabels.length > 0) {
|
||||
for (const messageId of messageIds) {
|
||||
await this.gmail.users.messages.modify({
|
||||
userId: 'me',
|
||||
id: messageId,
|
||||
requestBody: { addLabelIds: addLabels, removeLabelIds: removeLabels }
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
|
||||
for (const messageId of messageIds) {
|
||||
await this.gmail.users.messages.trash({ userId: 'me', id: messageId })
|
||||
}
|
||||
}
|
||||
|
||||
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
|
||||
this.newMailCallback = callback
|
||||
this.pollInterval = setInterval(async () => {
|
||||
// Poll for new messages in INBOX
|
||||
try {
|
||||
const res = await this.gmail.users.messages.list({
|
||||
userId: 'me',
|
||||
labelIds: ['INBOX'],
|
||||
maxResults: 1,
|
||||
q: 'is:unread'
|
||||
})
|
||||
// In production: track historyId to detect actual new messages
|
||||
} catch {
|
||||
// Ignore polling errors
|
||||
}
|
||||
}, 60_000)
|
||||
}
|
||||
|
||||
offNewMail(): void {
|
||||
this.newMailCallback = null
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval)
|
||||
this.pollInterval = null
|
||||
}
|
||||
}
|
||||
|
||||
async pollNewMessages(): Promise<void> { /* Gmail использует свой polling через onNewMail */ }
|
||||
|
||||
async searchMessages(query: string, limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> {
|
||||
try {
|
||||
const res = await this.gmail.users.messages.list({
|
||||
userId: 'me',
|
||||
q: query,
|
||||
maxResults: limit
|
||||
})
|
||||
const items = res.data.messages ?? []
|
||||
const results: import('@shared/types/message').MessageEnvelope[] = []
|
||||
for (const item of items) {
|
||||
if (!item.id) continue
|
||||
const msg = await this.gmail.users.messages.get({ userId: 'me', id: item.id, format: 'metadata',
|
||||
metadataHeaders: ['Subject', 'From', 'To', 'Date'] })
|
||||
results.push(this.convertMessage(msg.data, 'INBOX'))
|
||||
}
|
||||
return results
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private detectRole(labelId: string): SpecialFolderRole {
|
||||
switch (labelId) {
|
||||
case 'INBOX': return SpecialFolderRole.Inbox
|
||||
case 'SENT': return SpecialFolderRole.Sent
|
||||
case 'DRAFT': return SpecialFolderRole.Drafts
|
||||
case 'TRASH': return SpecialFolderRole.Trash
|
||||
case 'SPAM': return SpecialFolderRole.Spam
|
||||
default: return SpecialFolderRole.None
|
||||
}
|
||||
}
|
||||
|
||||
private convertMessage(msg: gmail_v1.Schema$Message, folderId: string): MessageEnvelope {
|
||||
const headers = msg.payload?.headers ?? []
|
||||
const getHeader = (name: string): string =>
|
||||
headers.find((h) => h.name?.toLowerCase() === name.toLowerCase())?.value ?? ''
|
||||
|
||||
const labels = msg.labelIds ?? []
|
||||
|
||||
return {
|
||||
id: msg.id ?? '',
|
||||
folderId,
|
||||
subject: getHeader('Subject') || '(no subject)',
|
||||
from: this.parseAddress(getHeader('From')),
|
||||
to: this.parseAddressList(getHeader('To')),
|
||||
cc: this.parseAddressList(getHeader('Cc')),
|
||||
date: new Date(parseInt(msg.internalDate ?? '0')).toISOString(),
|
||||
flags: {
|
||||
seen: !labels.includes('UNREAD'),
|
||||
flagged: labels.includes('STARRED'),
|
||||
answered: false,
|
||||
deleted: labels.includes('TRASH')
|
||||
},
|
||||
hasAttachments: this.checkHasAttachments(msg.payload),
|
||||
snippet: msg.snippet ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
private parseAddress(raw: string): Address {
|
||||
const match = raw.match(/^(.*?)\s*<(.+?)>$/)
|
||||
if (match) {
|
||||
return { name: match[1].replace(/^"|"$/g, '').trim(), email: match[2] }
|
||||
}
|
||||
return { name: '', email: raw.trim() }
|
||||
}
|
||||
|
||||
private parseAddressList(raw: string): Address[] {
|
||||
if (!raw) return []
|
||||
return raw.split(',').map((s) => this.parseAddress(s.trim()))
|
||||
}
|
||||
|
||||
private checkHasAttachments(payload?: gmail_v1.Schema$MessagePart | null): boolean {
|
||||
if (!payload) return false
|
||||
if (payload.filename && payload.filename.length > 0) return true
|
||||
if (payload.parts) {
|
||||
return payload.parts.some((p) => this.checkHasAttachments(p))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private extractBody(msg: gmail_v1.Schema$Message): {
|
||||
html: string | null
|
||||
text: string | null
|
||||
inlineImages: InlineImage[]
|
||||
attachments: Attachment[]
|
||||
} {
|
||||
let html: string | null = null
|
||||
let text: string | null = null
|
||||
const inlineImages: InlineImage[] = []
|
||||
const attachments: Attachment[] = []
|
||||
|
||||
const processPart = (part: gmail_v1.Schema$MessagePart) => {
|
||||
if (part.mimeType === 'text/html' && part.body?.data) {
|
||||
html = Buffer.from(part.body.data, 'base64url').toString('utf-8')
|
||||
} else if (part.mimeType === 'text/plain' && part.body?.data && !text) {
|
||||
text = Buffer.from(part.body.data, 'base64url').toString('utf-8')
|
||||
} else if (part.filename && part.filename.length > 0) {
|
||||
const headers = part.headers ?? []
|
||||
const contentId = headers.find((h) => h.name?.toLowerCase() === 'content-id')?.value
|
||||
const disposition = headers.find((h) => h.name?.toLowerCase() === 'content-disposition')?.value
|
||||
|
||||
if (disposition?.includes('inline') && contentId) {
|
||||
// Inline image — would need to fetch attachment data
|
||||
inlineImages.push({
|
||||
cid: contentId.replace(/[<>]/g, ''),
|
||||
contentType: part.mimeType ?? 'application/octet-stream',
|
||||
data: '' // Would need separate API call to fetch
|
||||
})
|
||||
} else {
|
||||
attachments.push({
|
||||
id: part.body?.attachmentId ?? '',
|
||||
filename: part.filename,
|
||||
contentType: part.mimeType ?? 'application/octet-stream',
|
||||
size: part.body?.size ?? 0
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (part.parts) {
|
||||
part.parts.forEach(processPart)
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.payload) {
|
||||
processPart(msg.payload)
|
||||
}
|
||||
|
||||
return { html, text, inlineImages, attachments }
|
||||
}
|
||||
|
||||
async sendMessage(_compose: import('@shared/types/message').ComposeData): Promise<void> {
|
||||
throw new Error('Отправка для Gmail не реализована')
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ import { ImapFlow } from 'imapflow'
|
|||
import { simpleParser } from 'mailparser'
|
||||
import nodemailer from 'nodemailer'
|
||||
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData } from '@shared/types/message'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, Address, ComposeData, InlineImage, Attachment } from '@shared/types/message'
|
||||
import { SpecialFolderRole } from '@shared/types/folder'
|
||||
import type { Folder } from '@shared/types/folder'
|
||||
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
|
||||
|
|
@ -80,20 +80,30 @@ export class ImapProvider implements IEmailProvider {
|
|||
}
|
||||
|
||||
private async populateUnreadCounts(folders: Folder[]): Promise<void> {
|
||||
for (const folder of folders) {
|
||||
try {
|
||||
const status = await this.client.status(folder.id, { unseen: true, messages: true }) as
|
||||
{ unseen?: number; messages?: number } | null
|
||||
if (status) {
|
||||
folder.unreadCount = status.unseen ?? 0
|
||||
folder.totalCount = status.messages ?? 0
|
||||
}
|
||||
} catch {
|
||||
// Некоторые папки (виртуальные, [Gmail]) могут не поддерживать STATUS
|
||||
}
|
||||
if (folder.children.length > 0) {
|
||||
await this.populateUnreadCounts(folder.children)
|
||||
}
|
||||
// Собираем все папки в плоский список (включая вложенные)
|
||||
const flatten = (list: Folder[]): Folder[] =>
|
||||
list.flatMap((f) => [f, ...flatten(f.children)])
|
||||
|
||||
const all = flatten(folders)
|
||||
|
||||
// Параллельные STATUS запросы с concurrency limit 5
|
||||
const CONCURRENCY = 5
|
||||
for (let i = 0; i < all.length; i += CONCURRENCY) {
|
||||
const batch = all.slice(i, i + CONCURRENCY)
|
||||
await Promise.all(
|
||||
batch.map(async (folder) => {
|
||||
try {
|
||||
const status = await this.client.status(folder.id, { unseen: true, messages: true }) as
|
||||
{ unseen?: number; messages?: number } | null
|
||||
if (status) {
|
||||
folder.unreadCount = status.unseen ?? 0
|
||||
folder.totalCount = status.messages ?? 0
|
||||
}
|
||||
} catch {
|
||||
// Некоторые папки могут не поддерживать STATUS
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ import { AccountType } from '@shared/types/account'
|
|||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData } from '@shared/types/message'
|
||||
import { ImapProvider } from '../providers/imap.provider'
|
||||
import { ExchangeProvider } from '../providers/exchange.provider'
|
||||
import { GmailProvider } from '../providers/gmail.provider'
|
||||
import { CredentialStore } from './credential-store'
|
||||
import Store from 'electron-store'
|
||||
|
||||
|
|
@ -266,16 +264,10 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
private createProvider(config: AccountConfig): IEmailProvider {
|
||||
switch (config.type) {
|
||||
case AccountType.IMAP:
|
||||
return new ImapProvider(config)
|
||||
case AccountType.Exchange:
|
||||
return new ExchangeProvider(config)
|
||||
case AccountType.Gmail:
|
||||
return new GmailProvider(config)
|
||||
default:
|
||||
throw new Error(`Unknown account type: ${config.type}`)
|
||||
if (config.type !== AccountType.IMAP) {
|
||||
throw new Error(`Unsupported account type: ${config.type}`)
|
||||
}
|
||||
return new ImapProvider(config)
|
||||
}
|
||||
|
||||
async updateAccount(config: AccountConfig): Promise<{ success: boolean; error?: string }> {
|
||||
|
|
|
|||
|
|
@ -1,71 +0,0 @@
|
|||
import { BrowserWindow } from 'electron'
|
||||
import { google } from 'googleapis'
|
||||
|
||||
const GMAIL_CLIENT_ID = process.env.GMAIL_CLIENT_ID ?? ''
|
||||
const GMAIL_CLIENT_SECRET = process.env.GMAIL_CLIENT_SECRET ?? ''
|
||||
const REDIRECT_URI = 'http://localhost'
|
||||
|
||||
export interface OAuthTokens {
|
||||
email: string
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
export async function performGmailOAuth(): Promise<OAuthTokens | null> {
|
||||
const oauth2Client = new google.auth.OAuth2(GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET, REDIRECT_URI)
|
||||
|
||||
const authUrl = oauth2Client.generateAuthUrl({
|
||||
access_type: 'offline',
|
||||
prompt: 'consent',
|
||||
scope: [
|
||||
'https://www.googleapis.com/auth/gmail.readonly',
|
||||
'https://www.googleapis.com/auth/gmail.modify',
|
||||
'https://www.googleapis.com/auth/userinfo.email'
|
||||
]
|
||||
})
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const authWindow = new BrowserWindow({
|
||||
width: 600,
|
||||
height: 700,
|
||||
show: true,
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true
|
||||
}
|
||||
})
|
||||
|
||||
authWindow.loadURL(authUrl)
|
||||
|
||||
authWindow.webContents.on('will-redirect', async (_event, url) => {
|
||||
const urlObj = new URL(url)
|
||||
const code = urlObj.searchParams.get('code')
|
||||
|
||||
if (code) {
|
||||
try {
|
||||
const { tokens } = await oauth2Client.getToken(code)
|
||||
oauth2Client.setCredentials(tokens)
|
||||
|
||||
// Get user email
|
||||
const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client })
|
||||
const userInfo = await oauth2.userinfo.get()
|
||||
|
||||
authWindow.close()
|
||||
resolve({
|
||||
email: userInfo.data.email ?? '',
|
||||
accessToken: tokens.access_token ?? '',
|
||||
refreshToken: tokens.refresh_token ?? ''
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('OAuth token exchange failed:', error)
|
||||
authWindow.close()
|
||||
resolve(null)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
authWindow.on('closed', () => {
|
||||
resolve(null)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
@ -17,7 +17,8 @@ const api: Api = {
|
|||
invoke(channel: string, ...args: unknown[]) {
|
||||
return ipcRenderer.invoke(channel, ...args)
|
||||
},
|
||||
on(channel: string, callback: (data: unknown) => void) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
on(channel: string, callback: (data: any) => void) {
|
||||
const listener = (_event: Electron.IpcRendererEvent, data: unknown) => callback(data as never)
|
||||
ipcRenderer.on(channel, listener)
|
||||
return () => {
|
||||
|
|
|
|||
|
|
@ -88,7 +88,10 @@ function onGlobalKeydown(e: KeyboardEvent): void {
|
|||
}
|
||||
}
|
||||
onMounted(() => document.addEventListener('keydown', onGlobalKeydown))
|
||||
onUnmounted(() => document.removeEventListener('keydown', onGlobalKeydown))
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('keydown', onGlobalKeydown)
|
||||
if (searchDebounce) clearTimeout(searchDebounce)
|
||||
})
|
||||
|
||||
const folderName = computed(() => foldersStore.activeFolder?.name ?? '')
|
||||
const hasSelected = computed(() => messagesStore.selectedIds.size > 0)
|
||||
|
|
|
|||
|
|
@ -126,15 +126,17 @@ export const useMessagesStore = defineStore('messages', () => {
|
|||
.slice(0, count)
|
||||
.filter((m) => !getCachedBody(`${accountId}:${folderId}:${m.id}`))
|
||||
|
||||
for (const msg of toFetch) {
|
||||
const key = `${accountId}:${folderId}:${msg.id}`
|
||||
try {
|
||||
const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id })
|
||||
setCachedBody(key, body)
|
||||
} catch {
|
||||
// фоновая предзагрузка — ошибки не критичны
|
||||
}
|
||||
}
|
||||
await Promise.all(
|
||||
toFetch.map(async (msg) => {
|
||||
const key = `${accountId}:${folderId}:${msg.id}`
|
||||
try {
|
||||
const body = await invoke('messages:body', { accountId, folderId, messageId: msg.id })
|
||||
setCachedBody(key, body)
|
||||
} catch {
|
||||
// фоновая предзагрузка — ошибки не критичны
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
async function loadMore(): Promise<void> {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
export enum AccountType {
|
||||
IMAP = 'imap',
|
||||
Exchange = 'exchange',
|
||||
Gmail = 'gmail'
|
||||
IMAP = 'imap'
|
||||
}
|
||||
|
||||
export interface ImapCredentials {
|
||||
|
|
@ -18,20 +16,7 @@ export interface ImapCredentials {
|
|||
smtpAllowSelfSigned?: boolean
|
||||
}
|
||||
|
||||
export interface ExchangeCredentials {
|
||||
serverUrl: string
|
||||
domain: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
export interface GmailCredentials {
|
||||
email: string
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
}
|
||||
|
||||
export type AccountCredentials = ImapCredentials | ExchangeCredentials | GmailCredentials
|
||||
export type AccountCredentials = ImapCredentials
|
||||
|
||||
export interface AccountConfig {
|
||||
id: string
|
||||
|
|
|
|||
|
|
@ -37,8 +37,6 @@ export interface IpcChannelMap {
|
|||
'app:chooseFolder': [void, string | null]
|
||||
'app:openFile': [{ path: string }, { success: boolean; error?: string }]
|
||||
|
||||
'oauth:gmail': [void, { email: string; accessToken: string; refreshToken: string } | null]
|
||||
|
||||
'messages:poll': [{ accountId: string }, void]
|
||||
'messages:search': [{ accountId: string; query: string; limit: number }, MessageEnvelope[]]
|
||||
'messages:send': [{ accountId: string; compose: ComposeData }, { success: boolean; error?: string }]
|
||||
|
|
|
|||
Loading…
Reference in a new issue