diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 52092d5..5d24827 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -186,6 +186,10 @@ class AppStrings { String get syncRange => _ko ? '동기화 범위' : 'Sync range'; String get comingSoon => _ko ? '준비 중' : 'Coming soon'; String get noAccountSelected => _ko ? '계정을 선택하세요' : 'Select an account'; + String get categoryAll => _ko ? '전체' : 'All'; + String get categoryPerson => _ko ? '사람' : 'People'; + String get categoryNotification => _ko ? '알림' : 'Notifications'; + String get categoryNewsletter => _ko ? '뉴스레터' : 'Newsletters'; String get searchMail => _ko ? '메일 검색' : 'Search mail'; String get searchHint => _ko ? '검색: 제목·보낸 사람, from: subject: after: before:' diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index b03329e..36f1044 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -61,6 +61,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { bool _refreshing = false; final _searchController = TextEditingController(); Future>? _search; + String? _category; static bool _busy(MailAccountSummary account) => account.threadBackfilling || @@ -286,6 +287,25 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ), ), ), + Wrap( + spacing: 8, + children: [ + for (final (value, label) in [ + (null, strings.categoryAll), + ('person', strings.categoryPerson), + ('notification', strings.categoryNotification), + ('newsletter', strings.categoryNewsletter), + ]) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6), + child: ChoiceChip( + label: Text(label), + selected: _category == value, + onSelected: (_) => setState(() => _category = value), + ), + ), + ], + ), Expanded( child: _search != null ? FutureBuilder>( @@ -299,7 +319,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { if (snapshot.hasError) { return Center(child: Text(strings.searchFailedTitle)); } - final results = snapshot.data!; + final results = filterByCategory(snapshot.data!, _category); if (results.isEmpty) { return Center(child: Text(strings.noSearchResults)); } @@ -308,7 +328,9 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { ) : messages.when( data: (all) { - final items = threaded ? groupByThread(all) : all; + // Filter first so a thread row shows its newest mail in the category. + final filtered = filterByCategory(all, _category); + final items = threaded ? groupByThread(filtered) : filtered; if (items.isEmpty) { return Center( child: Column( diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index cb40966..1426402 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -408,11 +408,14 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, + this.category, this.threadId, this.threadCount = 1, this.flagged = false, }); + /// Null until the server has classified the message. + final String? category; final String id; final String sender; final String subject; @@ -430,6 +433,7 @@ class MailSummary { subject: json['subject'] as String? ?? '', snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), + category: json['category'] as String?, threadId: json['threadId'] as String?, threadCount: json['threadCount'] as int? ?? 1, unread: !(json['seen'] as bool? ?? false), @@ -438,6 +442,12 @@ class MailSummary { } } +/// Unclassified mail (null category) shows only under "All". +List filterByCategory(List items, String? category) => + category == null + ? items + : items.where((m) => m.category == category).toList(); + /// Keeps the first (newest) message of each thread. Mail without a thread id /// stays as its own row. List groupByThread(List items) { diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index dc57d3f..5ce92a1 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -249,6 +249,53 @@ void main() { expect(find.text('invoice'), findsNothing); }); + testWidgets('category chips also filter search results', + (WidgetTester tester) async { + const account = MailAccountSummary( + id: 'account-a', + providerId: 'gmail', + emailAddress: 'first@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + await tester.binding.setSurfaceSize(const Size(1200, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(_SearchApi()), + accountsProvider.overrideWith((ref) async => const [account]), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, accountId) async => const []), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text(account.emailAddress).first); + await tester.pumpAndSettle(); + await tester.enterText( + find.descendant( + of: find.byType(Scaffold).last, + matching: find.byType(TextField), + ).first, + 'invoice', + ); + await tester.testTextInput.receiveAction(TextInputAction.search); + await tester.pumpAndSettle(); + expect(find.text(_SearchApi.resultSubject), findsOneWidget); + + // The result is unclassified, so the newsletter chip hides it. + await tester.tap(find.byType(ChoiceChip).at(3)); + await tester.pumpAndSettle(); + expect(find.text(_SearchApi.resultSubject), findsNothing); + }); + testWidgets('shows loading instead of previous results for a new search', (WidgetTester tester) async { const account = MailAccountSummary( @@ -846,6 +893,22 @@ void main() { ]); }); + test('unclassified mail appears only under All', () { + MailSummary mail(String id, String? category) => MailSummary( + id: id, + sender: '', + subject: '', + snippet: '', + receivedAtLabel: '', + unread: true, + category: category, + ); + final items = [mail('1', null), mail('2', 'person'), mail('3', 'newsletter')]; + + expect(filterByCategory(items, null).map((m) => m.id), ['1', '2', '3']); + expect(filterByCategory(items, 'person').map((m) => m.id), ['2']); + }); + test('groups mail by thread id and keeps unthreaded mail', () { MailSummary mail(String id, String? thread) => MailSummary( id: id, diff --git a/apps/server/package.json b/apps/server/package.json index 61558ef..ec4c0a5 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/sendQueue.test.ts test/threading.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/messageFlags.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/imapCapabilities.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.test.ts test/sendQueue.test.ts test/threading.test.ts test/classifyMessage.test.ts test/existsQueue.test.ts test/pop3Unsupported.test.ts test/deletedAccountSync.test.ts test/oauthSessionExpiry.test.ts test/noopPushNotifier.test.ts test/serverExposure.test.ts test/uidValidity.test.ts test/accountScopedMessage.test.ts test/customServerAccount.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index be727ba..4f1b4b4 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -98,6 +98,7 @@ export interface IncomingMessageSummary { // receivedAt, which is the sender-set Date header. arrivedAt?: Date; hasAttachments: boolean; + category?: "person" | "notification" | "newsletter"; messageId?: string; inReplyTo?: string; references?: string[]; diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index a009694..320e4f3 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -30,6 +30,11 @@ import { newestFirstUidBatches } from "./imapSequenceRanges.js"; import { isAuthenticationFailure } from "./authenticationFailure.js"; +import { + classificationHeaderNames, + classifyMessage, + parseRawHeaders +} from "./classifyMessage.js"; import { Readable } from "node:stream"; import { decodeTransferEncoding, @@ -512,7 +517,7 @@ export class ImapReceiver implements MailReceiver { internalDate: true, uid: true, threadId: true, - headers: ["references"] + headers: [...classificationHeaderNames, "references"] }, { uid: true })) { const summary = toIncomingMessage(account, mailbox, message); if (summary) batch.push(summary); @@ -546,23 +551,25 @@ function toIncomingMessage( const envelope = message.envelope; if (!envelope) return null; + const from = envelope.from?.map((item) => item.address).filter(Boolean).join(", ") ?? ""; + const headers = parseRawHeaders(message.headers?.subarray(0, MAX_HEADER_BYTES)); return { accountId: account.id, providerMessageId: String(message.uid), mailbox, - from: envelope.from?.map((item) => item.address).filter(Boolean).join(", ") ?? "", + from, subject: envelope.subject ?? "", receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), arrivedAt: message.internalDate instanceof Date ? message.internalDate : undefined, hasAttachments: false, messageId: boundMessageId(envelope.messageId), inReplyTo: boundMessageId(envelope.inReplyTo), - references: parseMessageIds( - message.headers?.subarray(0, MAX_HEADER_BYTES).toString("utf8") - ), + // Only the References value: List-Id/List-Unsubscribe also carry <...> tokens. + references: parseMessageIds(headers["references"]), gmailThreadId: message.threadId, seen: message.flags?.has("\\Seen") ?? false, - flagged: message.flags?.has("\\Flagged") ?? false + flagged: message.flags?.has("\\Flagged") ?? false, + category: classifyMessage(headers, from) }; } diff --git a/apps/server/src/mail/classifyMessage.ts b/apps/server/src/mail/classifyMessage.ts new file mode 100644 index 0000000..5b230f5 --- /dev/null +++ b/apps/server/src/mail/classifyMessage.ts @@ -0,0 +1,45 @@ +export type MessageCategory = "person" | "notification" | "newsletter"; + +export const classificationHeaderNames = [ + "list-unsubscribe", + "list-id", + "precedence", + "auto-submitted" +]; + +// Parses a raw RFC 5322 header block into lowercase-name -> value (folded lines joined). +export function parseRawHeaders(raw: Buffer | string | undefined): Record { + const headers: Record = {}; + if (!raw) return headers; + const unfolded = raw.toString("utf8").replace(/\r?\n[ \t]+/g, " "); + for (const line of unfolded.split(/\r?\n/)) { + const index = line.indexOf(":"); + if (index <= 0) continue; + headers[line.slice(0, index).trim().toLowerCase()] = line.slice(index + 1).trim(); + } + return headers; +} + +const automatedLocalPart = + /^(no[-_.]?reply|do[-_.]?not[-_.]?reply|notifications?|alerts?|mailer-daemon|postmaster|bounces?)([-_.+].*)?$/i; + +export function classifyMessage( + headers: Record, + from: string +): MessageCategory { + const autoSubmitted = headers["auto-submitted"]?.toLowerCase(); + if (autoSubmitted && autoSubmitted !== "no") return "notification"; + + const precedence = headers["precedence"]?.toLowerCase(); + if ( + headers["list-unsubscribe"] || + headers["list-id"] || + (precedence && ["bulk", "list", "junk"].includes(precedence)) + ) { + return "newsletter"; + } + + const localPart = from.split(",")[0]?.split("@")[0]?.trim() ?? ""; + if (automatedLocalPart.test(localPart)) return "notification"; + return "person"; +} diff --git a/apps/server/src/workers/MailSyncWorker.ts b/apps/server/src/workers/MailSyncWorker.ts index b675996..5885afb 100644 --- a/apps/server/src/workers/MailSyncWorker.ts +++ b/apps/server/src/workers/MailSyncWorker.ts @@ -365,10 +365,12 @@ export class MailSyncWorker { await this.backfills.get(accountId)?.done; } - // Messages stored before threading existed have no header metadata and the - // 25-message sync never revisits them. Backfill runs in the background in + // Messages stored before threading or classification existed have no header + // metadata (or no category) and the 25-message sync never revisits them. One + // fetch fills both. Backfill runs in the background in // 50-message batches until none is left. Progress is the stored metadata - // itself (a message the server no longer has gets `references: []`), so a + // itself (a message the server no longer has gets `references: []` and + // category "person"), so a // restart or the next sync simply continues with what is still missing. private startBackfill(account: MailAccount): void { if (this.backfills.has(account.id)) return; @@ -404,12 +406,14 @@ export class MailSyncWorker { entry: { saving?: Promise } ): Promise { const active = () => this.backfills.get(account.id)?.token === token; + const needsThread = (message: IncomingMessageSummary) => + message.messageId === undefined && + message.gmailThreadId === undefined && + message.references === undefined; const pending = (await this.accounts.listInbox(account.userId)) .filter((message) => message.accountId === account.id && - message.messageId === undefined && - message.gmailThreadId === undefined && - message.references === undefined && + (needsThread(message) || message.category === undefined) && /^\d+$/.test(message.providerMessageId)); const byMailbox = new Map(); @@ -436,7 +440,7 @@ export class MailSyncWorker { expectedUidValidity ??= uidValidity; // Same UIDs under a new UIDVALIDITY are other messages; never copy their headers. if (uidValidity !== expectedUidValidity) { - throw new Error("Mailbox UIDVALIDITY changed during thread backfill"); + throw new Error("Mailbox UIDVALIDITY changed during backfill"); } const fetched = new Map(messages.map((m) => [m.providerMessageId, m])); if (!active()) return; @@ -447,10 +451,15 @@ export class MailSyncWorker { const found = fetched.get(message.providerMessageId); return this.accounts.saveIncomingMessage({ ...message, - messageId: found?.messageId, - inReplyTo: found?.inReplyTo, - references: found?.references ?? [], - gmailThreadId: found?.gmailThreadId, + // Only the missing part is filled, so each marker stays exact. + ...(needsThread(message) && { + messageId: found?.messageId, + inReplyTo: found?.inReplyTo, + references: found?.references ?? [], + gmailThreadId: found?.gmailThreadId + }), + // Gone from the server: "person", so it is not fetched again. + category: message.category ?? found?.category ?? "person", // The snapshot predates this batch; the server's flags are newer. seen: found?.seen ?? message.seen, flagged: found?.flagged ?? message.flagged diff --git a/apps/server/test/classifyMessage.test.ts b/apps/server/test/classifyMessage.test.ts new file mode 100644 index 0000000..22f309c --- /dev/null +++ b/apps/server/test/classifyMessage.test.ts @@ -0,0 +1,53 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { classifyMessage, parseRawHeaders } from "../src/mail/classifyMessage.js"; + +test("parses folded headers case-insensitively", () => { + const h = parseRawHeaders("List-ID: \r\nPrecedence:\r\n bulk\r\n\r\n"); + assert.equal(h["list-id"], ""); + assert.equal(h["precedence"], "bulk"); +}); + +test("newsletter by List-Unsubscribe, List-Id or bulk precedence", () => { + assert.equal(classifyMessage({ "list-unsubscribe": "" }, "news@example.test"), "newsletter"); + assert.equal(classifyMessage({ "list-id": "" }, "a@example.test"), "newsletter"); + assert.equal(classifyMessage({ precedence: "Bulk" }, "a@example.test"), "newsletter"); +}); + +test("notification by Auto-Submitted or automated sender", () => { + assert.equal(classifyMessage({ "auto-submitted": "auto-generated" }, "a@example.test"), "notification"); + assert.equal(classifyMessage({ "auto-submitted": "no" }, "a@example.test"), "person"); + assert.equal(classifyMessage({}, "noreply@example.test"), "notification"); + assert.equal(classifyMessage({}, "no-reply+x@example.test"), "notification"); +}); + +test("person otherwise", () => { + assert.equal(classifyMessage({}, "alice@example.test"), "person"); + assert.equal(classifyMessage({}, ""), "person"); +}); + +test("one fetch requests both header sets; references ignore List-* tokens", async () => { + const { ImapReceiver } = await import("../src/mail/ImapReceiver.js"); + let requested: string[] = []; + const client = { + async *fetch(_uids: number[], query: { headers: string[] }) { + requested = query.headers; + yield { + uid: 7, + flags: new Set(), + envelope: { from: [{ address: "news@example.test" }], subject: "s", date: new Date(0) }, + headers: Buffer.from( + "List-Unsubscribe: \r\nList-Id: \r\n" + + "References: \r\n \r\n\r\n" + ) + }; + } + }; + const receiver = new ImapReceiver({} as never, {} as never) as unknown as { + fetchUids: (c: unknown, a: unknown, m: string, u: number[]) => Promise>; + }; + const [summary] = await receiver.fetchUids(client, { id: "a" }, "INBOX", [7]); + assert.ok(requested.includes("references") && requested.includes("list-unsubscribe")); + assert.equal(summary?.category, "newsletter"); + assert.deepEqual(summary?.references, ["", ""]); +}); diff --git a/apps/server/test/mailSyncWorker.test.ts b/apps/server/test/mailSyncWorker.test.ts index d40adce..c4f16dd 100644 --- a/apps/server/test/mailSyncWorker.test.ts +++ b/apps/server/test/mailSyncWorker.test.ts @@ -3,13 +3,13 @@ import test from "node:test"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { LocalFileAccountRepository } from "../src/workers/LocalFileAccountRepository.js"; import type { IncomingMessageSummary, MailAccount } from "../src/domain/types.js"; import type { ImapReceiver } from "../src/mail/ImapReceiver.js"; import type { Pop3Receiver } from "../src/mail/Pop3Receiver.js"; import type { PushNotifier } from "../src/notifications/PushNotifier.js"; import { authenticationFailure } from "../src/mail/authenticationFailure.js"; import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; +import { LocalFileAccountRepository } from "../src/workers/LocalFileAccountRepository.js"; import { MailSyncWorker } from "../src/workers/MailSyncWorker.js"; function account(): MailAccount { @@ -28,7 +28,7 @@ function account(): MailAccount { }; } -function worker(repository: InMemoryAccountRepository, imap: object) { +function worker(repository: InMemoryAccountRepository | LocalFileAccountRepository, imap: object) { return new MailSyncWorker( repository, imap as ImapReceiver, @@ -854,6 +854,65 @@ test("a reconnect during a running import queues another sync", async () => { } }); +test("one backfill fetch fills missing categories and thread metadata separately", async () => { + const repository = new InMemoryAccountRepository(); + const mailAccount = account(); + await repository.addAccount(mailAccount); + const stored = (uid: number): IncomingMessageSummary => ({ + accountId: mailAccount.id, + providerMessageId: String(uid), + mailbox: "INBOX", + from: "a@example.com", + subject: "old", + receivedAt: new Date(uid * 1000), + hasAttachments: false + }); + // 1..100: neither; 101..110: thread done, no category; 111..120: category done, no thread. + for (let uid = 1; uid <= 120; uid += 1) { + await repository.saveIncomingMessage({ + ...stored(uid), + ...(uid > 100 && uid <= 110 && { messageId: ``, references: [] }), + ...(uid > 110 && { category: "notification" as const }) + }); + } + const requests: number[][] = []; + const imap = { + fetchLatestBatches: async () => undefined, + fetchSummariesByUid: async (_a: MailAccount, _m: string, uids: number[]) => { + requests.push(uids); + // uid 1 is gone from the server; even uids are newsletters. + return { uidValidity: "1", messages: uids.filter((uid) => uid !== 1).map((uid) => ({ + ...stored(uid), + messageId: ``, + references: [""], + category: uid % 2 === 0 ? "newsletter" as const : "person" as const + })) }; + } + }; + const syncWorker = worker(repository, imap); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.deepEqual(requests.map((r) => r.length), [50, 50, 20]); + const byUid = new Map( + (await repository.listInbox(mailAccount.userId)).map((m) => [m.providerMessageId, m]) + ); + assert.equal(byUid.get("2")?.category, "newsletter"); + assert.equal(byUid.get("2")?.messageId, ""); + assert.equal(byUid.get("1")?.category, "person"); + assert.deepEqual(byUid.get("1")?.references, []); + // Thread metadata already stored is kept; only the category is added. + assert.equal(byUid.get("102")?.messageId, ""); + assert.equal(byUid.get("102")?.category, "newsletter"); + // A stored category is kept; only thread metadata is added. + assert.equal(byUid.get("112")?.category, "notification"); + assert.equal(byUid.get("112")?.messageId, ""); + + await syncWorker.syncAccount(mailAccount); + await syncWorker.backfillSettled(mailAccount.id); + assert.equal(requests.length, 3); +}); + function customAccount(supportsIdle?: boolean): MailAccount { return { ...account(),