Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions server/src/api/v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const batchAction = z.object({

const threadBatch = z.object({
threadIds: z.array(z.string().min(1)).min(1).max(500),
action: z.enum(['read', 'unread', 'star', 'unstar', 'archive', 'trash', 'delete']),
action: z.enum(['read', 'unread', 'star', 'unstar', 'archive', 'inbox', 'trash', 'delete']),
});

const FLAG_ACTIONS = {
Expand All @@ -73,7 +73,7 @@ async function body(c: { req: { json: () => Promise<unknown> } }) {
return c.req.json().catch(() => ({}));
}

const VIEWS = new Set<View>(['inbox', 'important', 'sent', 'starred', 'unread', 'all']);
const VIEWS = new Set<View>(['inbox', 'important', 'sent', 'junk', 'starred', 'unread', 'all']);
// 等回复是按会话算的,只给会话列表用
const THREAD_VIEWS = new Set<View>([...VIEWS, 'waiting']);

Expand Down Expand Up @@ -286,7 +286,7 @@ export const v1Routes = new Hono<AppEnv>()
let result: object;
if (action in FLAG_ACTIONS) result = await setFlags(scope, ids, FLAG_ACTIONS[action as keyof typeof FLAG_ACTIONS]);
else {
result = action === 'delete' ? await deleteMessages(scope, ids) : await moveMessages(scope, ids, action as 'archive' | 'trash');
result = action === 'delete' ? await deleteMessages(scope, ids) : await moveMessages(scope, ids, action as 'archive' | 'inbox' | 'trash');
audit(actorOf(c.var.auth), `messages.${action}`, { detail: { ids, threadIds } });
}
return c.json(result);
Expand Down
7 changes: 5 additions & 2 deletions server/src/services/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,11 +267,11 @@ export async function deleteMessages(scope: Scope, ids: number[]) {
return { deleted };
}

export type ThreadAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'trash' | 'delete';
export type ThreadAction = 'read' | 'unread' | 'star' | 'unstar' | 'archive' | 'inbox' | 'trash' | 'delete';

/**
* 按会话批量操作时,每个会话里实际要处理的邮件,和会话详情页按钮的语义一致:
* 已读处理所有未读;标未读、加星标只处理最新一封;归档只移收件箱里的;删除跳过已在废纸篓的;彻底删除只删废纸篓里的。
* 已读处理所有未读;标未读、加星标只处理最新一封;归档只移收件箱里的;移回收件箱只移垃圾邮件里的;删除跳过已在废纸篓的;彻底删除只删废纸篓里的。
*/
export async function threadMessageIds(scope: Scope, threadIds: string[], action: ThreadAction): Promise<number[]> {
if (!threadIds.length) return [];
Expand Down Expand Up @@ -318,6 +318,9 @@ export async function threadMessageIds(scope: Scope, threadIds: string[], action
case 'archive':
ids.push(...list.filter((r) => r.specialUse === '\\Inbox' || r.path.toUpperCase() === 'INBOX').map((r) => r.id));
break;
case 'inbox':
ids.push(...list.filter((r) => r.specialUse === '\\Junk').map((r) => r.id));
break;
case 'trash':
ids.push(...list.filter((r) => r.specialUse !== '\\Trash').map((r) => r.id));
break;
Expand Down
31 changes: 20 additions & 11 deletions server/src/services/mail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { completeMessage } from './message-source.js';
/** 访问范围:API Key 可以限定只能看某些账户,null 表示全部 */
export type Scope = { accountIds: number[] | null };

export type View = 'inbox' | 'important' | 'sent' | 'starred' | 'unread' | 'all' | 'waiting';
export type View = 'inbox' | 'important' | 'sent' | 'junk' | 'starred' | 'unread' | 'all' | 'waiting';

export type ListOptions = {
scope: Scope;
Expand Down Expand Up @@ -43,6 +43,8 @@ function isInbox() {
return sql`(${folders.specialUse} = '\\Inbox' OR upper(${folders.path}) = 'INBOX')`;
}

const onlyVerification = (categories: string[]) => categories.length > 0 && categories.every((c) => c === 'verification');

function buildFilters(opts: ListOptions): SQL[] {
const conds: SQL[] = [];
const { scope } = opts;
Expand All @@ -57,7 +59,10 @@ function buildFilters(opts: ListOptions): SQL[] {
if (!hasFolderFilter) {
if (view === 'inbox' || view === 'important') conds.push(isInbox());
else if (view === 'sent') conds.push(sql`${folders.specialUse} = '\\Sent'`);
// 跨文件夹的视图和搜索不含垃圾箱、垃圾邮件,要看用 folder:trash / folder:junk
else if (view === 'junk') conds.push(sql`${folders.specialUse} = '\\Junk'`);
// 跨文件夹的视图和搜索不含垃圾箱、垃圾邮件,要看用 folder:trash / folder:junk;
// 只看验证码分类时算上垃圾邮件,验证码常被误判进去
else if (onlyVerification(q.category)) conds.push(sql`coalesce(${folders.specialUse}, '') <> '\\Trash'`);
else conds.push(sql`coalesce(${folders.specialUse}, '') NOT IN ('\\Trash', '\\Junk')`);
}
if (view === 'starred') conds.push(eq(messages.flagged, true));
Expand Down Expand Up @@ -594,27 +599,30 @@ export async function getStats(scope: Scope) {
`)
).rows
: [];
// 各视图的数量,口径和 buildFilters 一致:跨文件夹的视图不含垃圾箱和垃圾邮件
// 各视图的数量,口径和 buildFilters 一致:跨文件夹的视图不含垃圾箱和垃圾邮件,垃圾邮件单独计数
const [views] = ids.length
? (
await db.execute<{ unread: string; starred: string; sent: string; total: string }>(sql`
SELECT count(*) FILTER (WHERE NOT m.seen) AS unread,
count(*) FILTER (WHERE m.flagged) AS starred,
await db.execute<{ unread: string; starred: string; sent: string; total: string; junk: string }>(sql`
SELECT count(*) FILTER (WHERE NOT junk AND NOT m.seen) AS unread,
count(*) FILTER (WHERE NOT junk AND m.flagged) AS starred,
count(*) FILTER (WHERE f.special_use = '\\Sent') AS sent,
count(*) AS total
FROM messages m JOIN folders f ON f.id = m.folder_id
WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') NOT IN ('\\Trash', '\\Junk')
count(*) FILTER (WHERE NOT junk) AS total,
count(*) FILTER (WHERE junk) AS junk
FROM messages m JOIN folders f ON f.id = m.folder_id,
LATERAL (SELECT coalesce(f.special_use, '') = '\\Junk' AS junk) j
WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') <> '\\Trash'
`)
).rows
: [];
// AI 分类的数量,口径和点分类进去的列表一致(全部邮件视图,不含垃圾箱和垃圾邮件)
// AI 分类的数量,口径和点分类进去的列表一致(全部邮件视图,不含垃圾箱和垃圾邮件;验证码算上垃圾邮件)
const categories = ids.length
? (
await db.execute<{ category: string; total: number; unread: number }>(sql`
SELECT i.category, count(*)::int AS total, (count(*) FILTER (WHERE NOT m.seen))::int AS unread
FROM messages m JOIN folders f ON f.id = m.folder_id
JOIN message_insights i ON i.message_id = m.id
WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') NOT IN ('\\Trash', '\\Junk')
WHERE m.account_id = ANY(${sql.param(ids)}::int[]) AND coalesce(f.special_use, '') <> '\\Trash'
AND (coalesce(f.special_use, '') <> '\\Junk' OR i.category = 'verification')
GROUP BY i.category
`)
).rows
Expand Down Expand Up @@ -650,6 +658,7 @@ export async function getStats(scope: Scope) {
unreadTotal: Number(views?.unread ?? 0),
starredTotal: Number(views?.starred ?? 0),
sentTotal: Number(views?.sent ?? 0),
junkTotal: Number(views?.junk ?? 0),
allTotal: Number(views?.total ?? 0),
waitingTotal: waiting,
// 草稿、待发和发送失败的,不含待审批(单独提醒)和已发送
Expand Down
26 changes: 18 additions & 8 deletions server/src/services/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,9 @@ async function processMessage(m: Message, payload: Record<string, unknown>, last
}
if (payload.analyzeOnly) return result;

// 垃圾邮件里的新邮件只为了不漏掉验证码:不执行规则,也只推送验证码,免得垃圾邮件触发动作、刷屏
const junk = await inJunk(m.folderId);

// 2. 规则:移动、标记这些动作每个邮箱的副本各自执行;推送按渠道去重,同一封邮件只推一次
const notified = new Set<number>(await notifiedForCopies(copies));
const already = new Set(notified);
Expand All @@ -280,7 +283,7 @@ async function processMessage(m: Message, payload: Record<string, unknown>, last
db.query.accounts.findFirst({ columns: { email: true }, where: eq(accounts.id, m.accountId) }),
]);
const mailbox = acc?.email;
for (const rule of (await listRules()).filter((r) => r.enabled)) {
for (const rule of junk ? [] : (await listRules()).filter((r) => r.enabled)) {
if (!ruleMatches(rule, { message: m, insight, labelIds, knownLabels })) continue;
const actions = await runActions(rule, m, insight, notified, mailbox);
matched.push(`${rule.name}: ${actions.join(', ')}`);
Expand All @@ -294,13 +297,15 @@ async function processMessage(m: Message, payload: Record<string, unknown>, last
if (matched.length) result.rules = matched;

// 3. 订阅了事件的渠道:每个渠道只推送一次,取最具体的事件
const events: EventName[] = ['message.received'];
if (insight?.priority === 'high') events.unshift('message.important');
const events: EventName[] = junk ? [] : ['message.received'];
if (!junk && insight?.priority === 'high') events.unshift('message.important');
if (insight?.extracted.codes.length) events.unshift('message.verification');
const subscribed = await db
.select({ id: channels.id, events: channels.events })
.from(channels)
.where(and(eq(channels.enabled, true), arrayOverlaps(channels.events, events)));
const subscribed = events.length
? await db
.select({ id: channels.id, events: channels.events })
.from(channels)
.where(and(eq(channels.enabled, true), arrayOverlaps(channels.events, events)))
: [];
for (const ch of subscribed) {
if (notified.has(ch.id)) continue;
const event = events.find((e) => ch.events.includes(e))!;
Expand All @@ -318,7 +323,12 @@ async function processMessage(m: Message, payload: Record<string, unknown>, last
return result;
}

/** 同步到新邮件时调用:只处理收件箱里的、近期的邮件(首次回溯和移回收件箱的旧邮件不触发) */
async function inJunk(folderId: number) {
const f = await db.query.folders.findFirst({ columns: { specialUse: true }, where: eq(folders.id, folderId) });
return f?.specialUse === '\\Junk';
}

/** 同步到新邮件时调用:只处理收件箱和垃圾邮件里的、近期的邮件(首次回溯和移回收件箱的旧邮件不触发) */
export async function onNewMessage(messageId: number, date: Date) {
if (Date.now() - date.getTime() > 3 * 86400_000) return;
await enqueue('process_message', { messageId });
Expand Down
50 changes: 44 additions & 6 deletions server/src/sync/account-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import { isMessageDataError } from '../lib/db-errors.js';
const BATCH = 25;
const TRUNCATED_BYTES = 2 * 1024 * 1024;
const FLAG_WINDOW = 500;
// 垃圾邮件没有 IDLE 推送,每分钟用 STATUS 看一眼(验证码常被误判进垃圾邮件,不能等 pollInterval)
const JUNK_POLL_MS = 60_000;

type SyncKind = 'none' | 'inbox' | 'all';
const rank: Record<SyncKind, number> = { none: 0, inbox: 1, all: 2 };
Expand All @@ -30,6 +32,7 @@ function sleep(ms: number, signal: AbortSignal) {
/**
* 每个邮箱账户一个常驻 worker:
* - 维持一条 IMAP 连接,选中 INBOX 后由 imapflow 自动 IDLE,收到 EXISTS 立即增量同步
* - 垃圾邮件每分钟用 STATUS 检查一次,有新邮件和收件箱一样进入自动化流程
* - 其他文件夹按 pollInterval 轮询;断线指数退避重连
* - 同步连接全程以 EXAMINE(只读)打开文件夹;标记、移动、APPEND 等写操作走 imap-writer 的独立连接
*/
Expand All @@ -39,7 +42,10 @@ export class AccountWorker {
private pending: SyncKind = 'none';
private draining: Promise<void> | null = null;
private pollTimer: NodeJS.Timeout | null = null;
private junkTimer: NodeJS.Timeout | null = null;
private inboxPath = 'INBOX';
/** 上次同步垃圾邮件时的 UIDNEXT,STATUS 返回的值变了才去同步 */
private junkUidNext: number | undefined;

constructor(readonly accountId: number) {
this.status = new StatusReporter(accountId);
Expand All @@ -51,7 +57,7 @@ export class AccountWorker {

async stop() {
this.abort.abort();
if (this.pollTimer) clearInterval(this.pollTimer);
this.clearTimers();
const client = this.client;
this.client = null;
if (client) await client.logout().catch(() => client.close());
Expand All @@ -65,6 +71,12 @@ export class AccountWorker {
if (!this.draining && this.client?.usable) this.draining = this.drain().finally(() => (this.draining = null));
}

private clearTimers() {
if (this.pollTimer) clearInterval(this.pollTimer);
if (this.junkTimer) clearInterval(this.junkTimer);
this.pollTimer = this.junkTimer = null;
}

private setStatus(status: string, error: string | null = null) {
return this.status.set(status, error);
}
Expand Down Expand Up @@ -105,13 +117,14 @@ export class AccountWorker {
backoff = 0;
this.requestSync('all');
this.pollTimer = setInterval(() => this.requestSync('all'), pollIntervalMsOf(account));
this.junkTimer = setInterval(() => void this.pollJunk(), JUNK_POLL_MS);
await closed;
if (this.pollTimer) clearInterval(this.pollTimer);
this.clearTimers();
if (!this.abort.signal.aborted) await this.setStatus('connecting', L('连接已断开,正在重连', 'Connection lost; reconnecting'));
} catch (err) {
const message = describeImapError(err);
console.warn(`[sync:${this.accountId}] ${message}`);
if (this.pollTimer) clearInterval(this.pollTimer);
this.clearTimers();
this.client?.close();
if (!this.abort.signal.aborted) await this.setStatus('error', message);
}
Expand Down Expand Up @@ -157,9 +170,32 @@ export class AccountWorker {
where: and(eq(folders.accountId, this.accountId), eq(folders.path, this.inboxPath)),
});
if (inbox?.syncEnabled) await this.syncFolder(client, inbox, true);
const junk = await this.junkWithNewMail(client);
if (junk) await this.syncFolder(client, junk, false);
await this.selectInbox(client);
}

/** 垃圾邮件有新邮件时才排一次收件箱同步(会顺带同步垃圾邮件),没变化不切换「同步中」 */
private async pollJunk() {
const client = this.client;
if (!client?.usable || this.draining) return;
try {
if (await this.junkWithNewMail(client)) this.requestSync('inbox');
} catch (err) {
console.warn(`[sync:${this.accountId}] 检查垃圾邮件失败: ${describeImapError(err)}`);
}
}

/** 用 STATUS 检查垃圾邮件文件夹的 UIDNEXT,变了就返回这个文件夹;首次回溯交给全量同步 */
private async junkWithNewMail(client: ImapFlow): Promise<Folder | null> {
const junk = await db.query.folders.findFirst({
where: and(eq(folders.accountId, this.accountId), eq(folders.specialUse, '\\Junk')),
});
if (!junk?.syncEnabled || junk.lastUid === 0) return null;
const st = await client.status(junk.path, { uidNext: true });
return st && st.uidNext !== undefined && st.uidNext !== this.junkUidNext ? junk : null;
}

/** 让连接停在 INBOX 上,imapflow 空闲时会自动发 IDLE */
private async selectInbox(client: ImapFlow) {
const lock = await client.getMailboxLock(this.inboxPath, { readOnly: true });
Expand Down Expand Up @@ -220,9 +256,9 @@ export class AccountWorker {
uids = uids.filter((u) => u > lastUid);
}
const started = Date.now();
// 只有收件箱的增量新邮件进入自动化流程;首次回溯、UIDVALIDITY 重建不触发
const isInbox = folder.specialUse === '\\Inbox' || folder.path.toUpperCase() === 'INBOX';
const done = await this.downloadNew(client, folder, uids, isInbox && lastUid !== 0);
// 只有收件箱和垃圾邮件的增量新邮件进入自动化流程;首次回溯、UIDVALIDITY 重建不触发
const hot = folder.specialUse === '\\Inbox' || folder.specialUse === '\\Junk' || folder.path.toUpperCase() === 'INBOX';
const done = await this.downloadNew(client, folder, uids, hot && lastUid !== 0);
// 中途被停止时不推进 lastUid,下次从头补齐(已入库的会跳过)
if (done) for (const u of uids) if (u > maxUid) maxUid = u;
if (uids.length) {
Expand All @@ -249,6 +285,8 @@ export class AccountWorker {
lastSyncAt: new Date(),
})
.where(eq(folders.id, folder.id));
// 刚选中的文件夹 uidNext 是准的
if (folder.specialUse === '\\Junk') this.junkUidNext = mb.uidNext;
} finally {
lock.release();
}
Expand Down
22 changes: 14 additions & 8 deletions server/src/sync/graph-worker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { and, eq, isNull, notInArray, or } from 'drizzle-orm';
import { and, eq, inArray, isNull, notInArray, or } from 'drizzle-orm';
import { config, pollIntervalMsOf } from '../config.js';
import { db } from '../db/index.js';
import { accounts, folders, messages, type Account, type Folder } from '../db/schema.js';
Expand All @@ -11,8 +11,10 @@ import { isDefaultSynced, nextUid, StatusReporter } from './status.js';
import { isMessageDataError } from '../lib/db-errors.js';

const TRUNCATED_BYTES = 2 * 1024 * 1024;
// Graph 没有 IDLE,收件箱靠轮询;其他文件夹按 pollInterval
// Graph 没有 IDLE,收件箱和垃圾邮件靠轮询(验证码常被误判进垃圾邮件,不能等 pollInterval);其他文件夹按 pollInterval
const INBOX_POLL_MS = 60_000;
// 和收件箱一起高频同步、新邮件进自动化流程的文件夹
const HOT_FOLDERS = ['\\Inbox', '\\Junk'];

const WELL_KNOWN: Record<string, string> = {
inbox: '\\Inbox',
Expand Down Expand Up @@ -45,7 +47,7 @@ function graphFlags(item: DeltaItem, answered = false) {
* 微软 Graph 账户的同步 worker,对外接口和 IMAP 的 AccountWorker 一致:
* - 文件夹用 mailFolders 列出,按 wellKnownName 识别收件箱、已发送等
* - 每个文件夹用 messages/delta 增量同步:新邮件取原始 MIME 走同一套入库流程,已读/旗标变化和删除直接改本地
* - 收件箱每分钟轮询一次,其他文件夹按 pollInterval
* - 收件箱和垃圾邮件每分钟轮询一次,其他文件夹按 pollInterval
*/
export class GraphWorker {
private abort = new AbortController();
Expand Down Expand Up @@ -125,11 +127,15 @@ export class GraphWorker {
}
}

/** 收件箱和垃圾邮件 */
private async syncInbox(account: Account) {
const inbox = await db.query.folders.findFirst({
where: and(eq(folders.accountId, this.accountId), eq(folders.specialUse, '\\Inbox')),
const list = await db.query.folders.findMany({
where: and(eq(folders.accountId, this.accountId), inArray(folders.specialUse, HOT_FOLDERS)),
});
if (inbox?.syncEnabled && inbox.remoteId) await this.syncFolder(account, inbox);
for (const f of list.sort((a, b) => HOT_FOLDERS.indexOf(a.specialUse!) - HOT_FOLDERS.indexOf(b.specialUse!))) {
if (this.abort.signal.aborted) return;
if (f.syncEnabled && f.remoteId) await this.syncFolder(account, f);
}
}

private async refreshFolders(account: Account): Promise<Folder[]> {
Expand Down Expand Up @@ -194,8 +200,8 @@ export class GraphWorker {
private async syncFolder(account: Account, folder: Folder) {
if (!folder.remoteId) return;
const initial = !folder.deltaLink;
// 只有收件箱的增量新邮件进入自动化流程;首次回溯不触发
const automate = folder.specialUse === '\\Inbox' && !initial;
// 只有收件箱和垃圾邮件的增量新邮件进入自动化流程;首次回溯不触发
const automate = HOT_FOLDERS.includes(folder.specialUse ?? '') && !initial;
let url: string | undefined = folder.deltaLink ?? this.initialDeltaUrl(folder);
let deltaLink: string | undefined;
let added = 0;
Expand Down
Loading
Loading