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
4 changes: 4 additions & 0 deletions apps/client/lib/core/i18n/language_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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:'
Expand Down
26 changes: 24 additions & 2 deletions apps/client/lib/features/accounts/account_mailbox_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> {
bool _refreshing = false;
final _searchController = TextEditingController();
Future<List<MailSummary>>? _search;
String? _category;

static bool _busy(MailAccountSummary account) =>
account.threadBackfilling ||
Expand Down Expand Up @@ -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<List<MailSummary>>(
Expand All @@ -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));
}
Expand All @@ -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(
Expand Down
10 changes: 10 additions & 0 deletions apps/client/lib/services/mail_api_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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),
Expand All @@ -438,6 +442,12 @@ class MailSummary {
}
}

/// Unclassified mail (null category) shows only under "All".
List<MailSummary> filterByCategory(List<MailSummary> 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<MailSummary> groupByThread(List<MailSummary> items) {
Expand Down
63 changes: 63 additions & 0 deletions apps/client/test/widget_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/domain/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand Down
19 changes: 13 additions & 6 deletions apps/server/src/mail/ImapReceiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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)
};
}

Expand Down
45 changes: 45 additions & 0 deletions apps/server/src/mail/classifyMessage.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> {
const headers: Record<string, string> = {};
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<string, string>,
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";
}
31 changes: 20 additions & 11 deletions apps/server/src/workers/MailSyncWorker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -404,12 +406,14 @@ export class MailSyncWorker {
entry: { saving?: Promise<unknown> }
): Promise<void> {
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<string, typeof pending>();
Expand All @@ -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;
Expand All @@ -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
Expand Down
Loading
Loading