diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 013abaa..be9688f 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -75,6 +75,13 @@ class AppStrings { String get send => _ko ? '보내기' : 'Send'; String get message => _ko ? '메일' : 'Message'; String get reply => _ko ? '답장' : 'Reply'; + String get markUnread => _ko ? '읽지 않음으로 표시' : 'Mark as unread'; + String get markRead => _ko ? '읽음으로 표시' : 'Mark as read'; + String get addStar => _ko ? '별표 표시' : 'Add star'; + String get removeStar => _ko ? '별표 해제' : 'Remove star'; + String get flagUpdateFailed => _ko + ? '메일 상태를 서버에 반영하지 못했습니다.' + : 'Could not update the message on the server.'; String get replyAll => _ko ? '전체 답장' : 'Reply all'; String get cc => _ko ? '참조' : 'Cc'; diff --git a/apps/client/lib/features/accounts/account_mailbox_page.dart b/apps/client/lib/features/accounts/account_mailbox_page.dart index 797b25f..268460b 100644 --- a/apps/client/lib/features/accounts/account_mailbox_page.dart +++ b/apps/client/lib/features/accounts/account_mailbox_page.dart @@ -182,7 +182,16 @@ class _MailboxContentState extends ConsumerState<_MailboxContent> { maxLines: 2, overflow: TextOverflow.ellipsis, ), - trailing: Text(message.receivedAtLabel), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (message.flagged) ...[ + const Icon(Icons.star, size: 18, color: Colors.amber), + const SizedBox(width: 6), + ], + Text(message.receivedAtLabel), + ], + ), onTap: () => context.go( '/accounts/${account.id}/messages/${Uri.encodeComponent(message.id)}', extra: const {'disableTransition': true}, diff --git a/apps/client/lib/features/message/message_page.dart b/apps/client/lib/features/message/message_page.dart index f734462..4b35a03 100644 --- a/apps/client/lib/features/message/message_page.dart +++ b/apps/client/lib/features/message/message_page.dart @@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart'; import '../../core/i18n/language_controller.dart'; import '../../services/mail_api_client.dart'; +import '../accounts/account_providers.dart'; import '../../widgets/app_shell.dart'; import 'attachment_list.dart'; import 'linked_message_body.dart'; @@ -20,7 +21,7 @@ final messageProvider = ); }); -class MessagePage extends ConsumerWidget { +class MessagePage extends ConsumerStatefulWidget { const MessagePage({ super.key, required this.messageId, @@ -31,10 +32,91 @@ class MessagePage extends ConsumerWidget { final String accountId; @override - Widget build(BuildContext context, WidgetRef ref) { - final message = ref.watch( - messageProvider((messageId: messageId, accountId: accountId)), - ); + ConsumerState createState() => _MessagePageState(); +} + +class _MessagePageState extends ConsumerState { + // Local overrides until the server confirms; null means "as loaded". + bool? _seen; + bool? _flagged; + bool _autoMarked = false; + + String get messageId => widget.messageId; + String get accountId => widget.accountId; + + // Last server-confirmed values (null = as loaded); failures roll back to these. + bool? _confirmedSeen; + bool? _confirmedFlagged; + + // Bumped per request so a failure only rolls back when no newer request for the field is pending. + int _seenVersion = 0; + int _flaggedVersion = 0; + + // Requests run one at a time so the server applies them in tap order. + Future _queue = Future.value(); + + Future _setFlags({bool? seen, bool? flagged}) async { + final id = accountId; + // The container outlives this widget, so invalidation still works after dispose. + final container = ProviderScope.containerOf(context, listen: false); + final seenVersion = seen != null ? ++_seenVersion : _seenVersion; + final flaggedVersion = + flagged != null ? ++_flaggedVersion : _flaggedVersion; + setState(() { + if (seen != null) _seen = seen; + if (flagged != null) _flagged = flagged; + }); + try { + final run = _queue.then( + (_) => container.read(mailApiClientProvider).setMessageFlags( + accountId: id, + messageId: messageId, + seen: seen, + flagged: flagged, + ), + ); + _queue = run.catchError((_) {}); + await run; + if (seen != null) _confirmedSeen = seen; + if (flagged != null) _confirmedFlagged = flagged; + container.invalidate(accountMessagesProvider(id)); + container.invalidate( + messageProvider((messageId: messageId, accountId: id)), + ); + } catch (_) { + if (!mounted) return; + setState(() { + if (seen != null && seenVersion == _seenVersion) _seen = _confirmedSeen; + if (flagged != null && flaggedVersion == _flaggedVersion) { + _flagged = _confirmedFlagged; + } + }); + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar(content: Text(ref.read(appStringsProvider).flagUpdateFailed)), + ); + } + } + + // Opening a message marks it read, matching other mail apps. + void _markReadOnOpen(AsyncValue value) { + final item = value.valueOrNull; + if (item == null || _autoMarked) return; + _autoMarked = true; + if (!item.seen) _setFlags(seen: true); + } + + @override + Widget build(BuildContext context) { + final request = (messageId: messageId, accountId: accountId); + final message = ref.watch(messageProvider(request)); + final detail = message.valueOrNull; + if (!_autoMarked && detail != null) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _markReadOnOpen(message); + }); + } + final seen = _seen ?? detail?.seen ?? false; + final flagged = _flagged ?? detail?.flagged ?? false; final strings = ref.watch(appStringsProvider); final mailboxPath = '/accounts/$accountId/mail'; @@ -52,6 +134,25 @@ class MessagePage extends ConsumerWidget { ), title: Text(strings.message), actions: [ + if (detail != null) ...[ + IconButton( + tooltip: flagged ? strings.removeStar : strings.addStar, + onPressed: () => _setFlags(flagged: !flagged), + icon: Icon( + flagged ? Icons.star : Icons.star_border, + color: flagged ? Colors.amber : null, + ), + ), + IconButton( + tooltip: seen ? strings.markUnread : strings.markRead, + onPressed: () => _setFlags(seen: !seen), + icon: Icon( + seen + ? Icons.mark_email_unread_outlined + : Icons.drafts_outlined, + ), + ), + ], if (message.value case final item?) ...[ IconButton( tooltip: strings.reply, @@ -89,9 +190,8 @@ class MessagePage extends ConsumerWidget { ], ), loading: () => const Center(child: CircularProgressIndicator()), - error: (error, stackTrace) => Center( - child: Text(strings.messageLoadFailedTitle), - ), + error: (error, stackTrace) => + Center(child: Text(strings.messageLoadFailedTitle)), ), ), ], diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 38cc545..be17786 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -96,6 +96,21 @@ class MailApiClient { return MessageDetail.fromJson(response.data ?? {}); } + Future setMessageFlags({ + required String accountId, + required String messageId, + bool? seen, + bool? flagged, + }) async { + await _dio.post( + '/accounts/$accountId/messages/${Uri.encodeComponent(messageId)}/flags', + data: { + if (seen != null) 'seen': seen, + if (flagged != null) 'flagged': flagged, + }, + ); + } + Future downloadAttachment({ required String accountId, required String messageId, @@ -302,6 +317,7 @@ class MailSummary { required this.snippet, required this.receivedAtLabel, required this.unread, + this.flagged = false, }); final String id; @@ -310,6 +326,7 @@ class MailSummary { final String snippet; final String receivedAtLabel; final bool unread; + final bool flagged; factory MailSummary.fromJson(Map json) { return MailSummary( @@ -318,7 +335,8 @@ class MailSummary { subject: json['subject'] as String? ?? '', snippet: json['snippet'] as String? ?? '', receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), - unread: true, + unread: !(json['seen'] as bool? ?? false), + flagged: json['flagged'] as bool? ?? false, ); } } @@ -331,6 +349,8 @@ class MessageDetail { required this.body, required this.links, required this.receivedAtLabel, + this.seen = false, + this.flagged = false, this.attachments = const [], this.receivedAt, this.accountId, @@ -341,6 +361,8 @@ class MessageDetail { this.replyAllCc = const [], }); + final bool seen; + final bool flagged; final String? accountId; final String? messageId; final List references; @@ -367,6 +389,8 @@ class MessageDetail { .map(MessageLink.fromJson) .toList(growable: false), receivedAtLabel: _formatReceivedAt(json['receivedAt'] as String?), + seen: json['seen'] as bool? ?? false, + flagged: json['flagged'] as bool? ?? false, attachments: (json['attachments'] as List? ?? const []) .whereType>() .map(MessageAttachment.fromJson) diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index a58e312..469d2ff 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -5,10 +5,12 @@ import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:daily_postbox/features/accounts/accounts_page.dart'; import 'package:daily_postbox/features/message/linked_message_body.dart'; +import 'package:daily_postbox/features/message/message_page.dart'; import 'package:daily_postbox/core/i18n/language_controller.dart'; import 'package:daily_postbox/features/message/reply_draft.dart'; import 'package:daily_postbox/main.dart'; @@ -115,8 +117,9 @@ void main() { expect(find.text('계정관리'), findsWidgets); }); - testWidgets('shows a friendly server connection error', - (WidgetTester tester) async { + testWidgets('shows a friendly server connection error', ( + WidgetTester tester, + ) async { final error = DioException.connectionError( requestOptions: RequestOptions(path: '/accounts'), reason: 'Failed host lookup', @@ -139,8 +142,9 @@ void main() { expect(find.textContaining('DioException'), findsNothing); }); - testWidgets('opens a connected account mailbox from the sidebar', - (WidgetTester tester) async { + testWidgets('opens a connected account mailbox from the sidebar', ( + WidgetTester tester, + ) async { const account = MailAccountSummary( id: 'account-1', providerId: 'gmail', @@ -320,8 +324,9 @@ void main() { overrides: [ accountsProvider.overrideWith((ref) async => const [account]), providersProvider.overrideWith((ref) async => const []), - accountMessagesProvider - .overrideWith((ref, accountId) async => const []), + accountMessagesProvider.overrideWith( + (ref, accountId) async => const [], + ), ], child: const DailyPostBoxApp(), ), @@ -339,8 +344,9 @@ void main() { await tester.pumpWidget(const SizedBox()); }); - testWidgets('keeps the syncing mailbox when an account refresh fails', - (WidgetTester tester) async { + testWidgets('keeps the syncing mailbox when an account refresh fails', ( + WidgetTester tester, + ) async { const account = MailAccountSummary( id: 'syncing-account', providerId: 'naver', @@ -365,8 +371,9 @@ void main() { return const [account]; }), providersProvider.overrideWith((ref) async => const []), - accountMessagesProvider - .overrideWith((ref, accountId) async => const []), + accountMessagesProvider.overrideWith( + (ref, accountId) async => const [], + ), ], child: const DailyPostBoxApp(), ), @@ -385,8 +392,9 @@ void main() { await tester.pumpWidget(const SizedBox()); }); - testWidgets('reloads mail once more when account sync finishes', - (WidgetTester tester) async { + testWidgets('reloads mail once more when account sync finishes', ( + WidgetTester tester, + ) async { const syncing = MailAccountSummary( id: 'syncing-account', providerId: 'naver', @@ -450,8 +458,9 @@ void main() { await tester.pumpWidget(const SizedBox()); }); - testWidgets('explains an authentication failure in the mailbox', - (WidgetTester tester) async { + testWidgets('explains an authentication failure in the mailbox', ( + WidgetTester tester, + ) async { const account = MailAccountSummary( id: 'auth-failed-account', providerId: 'naver', @@ -472,8 +481,9 @@ void main() { overrides: [ accountsProvider.overrideWith((ref) async => const [account]), providersProvider.overrideWith((ref) async => const []), - accountMessagesProvider - .overrideWith((ref, accountId) async => const []), + accountMessagesProvider.overrideWith( + (ref, accountId) async => const [], + ), ], child: const DailyPostBoxApp(), ), @@ -483,16 +493,14 @@ void main() { await tester.tap(find.text(account.emailAddress).first); await tester.pumpAndSettle(); - expect( - find.textContaining('로그인 정보가 만료됐거나 올바르지 않아'), - findsOneWidget, - ); + expect(find.textContaining('로그인 정보가 만료됐거나 올바르지 않아'), findsOneWidget); expect(find.text('Command failed'), findsNothing); expect(tester.takeException(), isNull); }); - testWidgets('reconnects an app password account from the mailbox banner', - (WidgetTester tester) async { + testWidgets('reconnects an app password account from the mailbox banner', ( + WidgetTester tester, + ) async { const account = MailAccountSummary( id: 'auth-failed-account', providerId: 'naver', @@ -545,8 +553,9 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('keeps account management readable at the default window size', - (WidgetTester tester) async { + testWidgets('keeps account management readable at the default window size', ( + WidgetTester tester, + ) async { const accounts = [ MailAccountSummary( id: 'account-1', @@ -599,8 +608,9 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('guides Naver setup through an application password', - (WidgetTester tester) async { + testWidgets('guides Naver setup through an application password', ( + WidgetTester tester, + ) async { const providers = [ MailProviderSummary( id: 'naver', @@ -675,7 +685,9 @@ void main() { expect(segments.map((item) => item.text).join(), '설정을 완료하려면 시작하기'); expect(segments.where((item) => item.uri != null).single.text, '시작하기'); expect( - segments.where((item) => item.uri != null).single.uri.toString(), url); + segments.where((item) => item.uri != null).single.uri.toString(), + url, + ); }); test('uses a domain label for a bare URL and preserves punctuation', () { @@ -685,12 +697,15 @@ void main() { ); expect(segments.map((item) => item.text).join(), '문서: docs.example.com.'); - expect(segments.where((item) => item.uri != null).single.text, - 'docs.example.com'); + expect( + segments.where((item) => item.uri != null).single.text, + 'docs.example.com', + ); }); - testWidgets('opens a rendered mail link with the external launcher', - (WidgetTester tester) async { + testWidgets('opens a rendered mail link with the external launcher', ( + WidgetTester tester, + ) async { const url = 'https://example.com/account/setup'; Uri? openedUri; @@ -813,6 +828,7 @@ void main() { 'outgoing': {'host': 'smtp.example.com', 'port': 587, 'secure': false}, }); }); + testWidgets('shows mail that arrives after sync without a manual refresh', (WidgetTester tester) async { const idle = MailAccountSummary( @@ -863,6 +879,169 @@ void main() { expect(find.text('Arrived by IDLE'), findsOneWidget); await tester.pumpWidget(const SizedBox()); }); + + group('message flag updates', () { + Future<_FlagApi> pumpMessage(WidgetTester tester, _FlagApi api) async { + final router = GoRouter( + initialLocation: '/m', + routes: [ + GoRoute( + path: '/m', + builder: (context, state) => + const MessagePage(messageId: 'm1', accountId: 'a1'), + ), + GoRoute( + path: '/other', builder: (context, state) => const SizedBox()), + ], + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async => const []), + providersProvider.overrideWith((ref) async => const []), + ], + child: MaterialApp.router(routerConfig: router), + ), + ); + await tester.pump(); + await tester.pump(); + return api; + } + + testWidgets('failed older request does not undo newer star', ( + tester, + ) async { + final api = await pumpMessage(tester, _FlagApi()); + expect(api.calls, hasLength(1)); // auto mark-read, pending + await tester.tap(find.byIcon(Icons.star_border)); + await tester.pump(); + expect(find.byIcon(Icons.star), findsOneWidget); + expect(api.calls, hasLength(1)); // second request waits for the first + api.calls[0].completeError(Exception('x')); + await tester.pump(); + await tester.pump(); + expect(api.calls, hasLength(2)); + api.calls[1].complete(); + await tester.pump(); + await tester.pump(); + expect(find.byIcon(Icons.star), findsOneWidget); + }); + + testWidgets('consecutive failures restore the confirmed state', ( + tester, + ) async { + final api = await pumpMessage(tester, _FlagApi()); + api.calls[0].complete(); + await tester.pump(); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star_border)); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star)); + await tester.pump(); + api.calls[1].completeError(Exception('x')); + await tester.pump(); + await tester.pump(); + api.calls[2].completeError(Exception('x')); + await tester.pump(); + await tester.pump(); + expect(find.byIcon(Icons.star_border), findsOneWidget); + expect(find.byIcon(Icons.star), findsNothing); + }); + + testWidgets('failure after confirmed star restores starred', ( + tester, + ) async { + final api = await pumpMessage(tester, _FlagApi()); + api.calls[0].complete(); + await tester.pump(); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star_border)); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star)); + await tester.pump(); + api.calls[1].complete(); + await tester.pump(); + await tester.pump(); + api.calls[2].completeError(Exception('x')); + await tester.pump(); + await tester.pump(); + expect(find.byIcon(Icons.star), findsOneWidget); + }); + + testWidgets('same-flag requests are sent in order', (tester) async { + final api = await pumpMessage(tester, _FlagApi()); + api.calls[0].complete(); + await tester.pump(); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star_border)); + await tester.pump(); + await tester.tap(find.byIcon(Icons.star)); + await tester.pump(); + expect(api.sent, [true]); // unstar not sent until star finishes + api.calls[1].complete(); + await tester.pump(); + await tester.pump(); + expect(api.sent, [true, false]); + }); + + testWidgets('success after leaving page refreshes cached detail', ( + tester, + ) async { + final api = await pumpMessage(tester, _FlagApi()); + final fetchesBefore = api.fetches; + final router = GoRouter.of(tester.element(find.byType(MessagePage))); + router.go('/other'); + await tester.pump(); + await tester.pump(); + api.calls[0].complete(); + await tester.pump(); + await tester.pump(); + // Cache is only dropped; it refetches when the detail page reopens. + router.go('/m'); + await tester.pump(); + await tester.pump(); + expect(api.fetches, greaterThan(fetchesBefore)); + expect(tester.takeException(), isNull); + }); + }); +} + +class _FlagApi extends MailApiClient { + _FlagApi() : super(baseUrl: 'http://127.0.0.1:1'); + + final calls = >[]; + var fetches = 0; + final sent = []; // flagged values in send order + + @override + Future fetchAccountMessage({ + required String accountId, + required String messageId, + }) async { + fetches++; + return const MessageDetail( + id: 'm1', + sender: 's', + subject: 'sub', + body: 'b', + links: [], + receivedAtLabel: 'now', + ); + } + + @override + Future setMessageFlags({ + required String accountId, + required String messageId, + bool? seen, + bool? flagged, + }) { + final c = Completer(); + calls.add(c); + if (flagged != null) sent.add(flagged); + return c.future; + } } class _SearchApi extends MailApiClient { diff --git a/apps/server/package.json b/apps/server/package.json index bbeab43..fd5513d 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/accountValidate.test.ts test/accountReconnect.test.ts test/searchQuery.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.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/attachments.test.ts test/attachmentAccess.test.ts test/mailSearchAccess.test.ts test/replyRecipients.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/api/routes.ts b/apps/server/src/api/routes.ts index eade75c..589fa42 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -9,6 +9,7 @@ import type { IncomingMessageContent, IncomingMessageSummary, MailAccount, + MessageFlagChange, MailProtocol, OutgoingMessageDraft, ProviderId @@ -125,6 +126,11 @@ export async function registerRoutes( account: MailAccount, message: IncomingMessageSummary ) => Promise; + setMessageFlags: ( + account: MailAccount, + message: IncomingMessageSummary, + change: MessageFlagChange + ) => Promise; downloadAttachment: ( account: MailAccount, message: IncomingMessageSummary, @@ -346,7 +352,8 @@ export async function registerRoutes( .map((message) => ({ ...message, id: message.providerMessageId, - receivedAt: message.receivedAt.toISOString() + receivedAt: message.receivedAt.toISOString(), + ...flagState(message) })); }); @@ -412,6 +419,7 @@ export async function registerRoutes( ...message, id: message.providerMessageId, receivedAt: message.receivedAt.toISOString(), + ...flagState(message), body: content.text, bodyTruncated: content.truncated, bodyLinks: content.links, @@ -420,6 +428,41 @@ export async function registerRoutes( }; }); + app.post("/accounts/:accountId/messages/:messageId/flags", async (request, reply) => { + const params = z.object({ + accountId: z.string(), + messageId: z.string() + }).parse(request.params); + const change = z.object({ + seen: z.boolean().optional(), + flagged: z.boolean().optional() + }).refine((value) => value.seen !== undefined || value.flagged !== undefined, { + message: "seen or flagged is required." + }).parse(request.body); + const account = await deps.accounts.getAccount(params.accountId); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + const messages = await deps.accounts.listInbox(demoUserId); + const message = messages.find( + (item) => item.accountId === params.accountId && + item.providerMessageId === params.messageId + ); + if (!message) { + return reply.code(404).send({ error: "Message not found" }); + } + + // Server first: the local copy only changes once the mail server accepted it. + await deps.setMessageFlags(account, message, change); + await deps.accounts.updateMessageFlags( + params.accountId, + params.messageId, + change + ); + return flagState({ ...message, ...change }); + }); + app.get( "/accounts/:accountId/messages/:messageId/attachments/:part", async (request, reply) => { @@ -478,7 +521,8 @@ export async function registerRoutes( return messages.map((message) => ({ ...message, id: message.providerMessageId, - receivedAt: message.receivedAt.toISOString() + receivedAt: message.receivedAt.toISOString(), + ...flagState(message) })); }); @@ -525,3 +569,7 @@ function credentialFailureMessage(account: MailAccount, error: unknown): string if (serverReply) parts.push(`(${serverReply})`); return parts.join(" "); } + +function flagState(message: IncomingMessageSummary) { + return { seen: message.seen ?? false, flagged: message.flagged ?? false }; +} diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index 48b8afd..3ecc8e0 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -86,6 +86,13 @@ export interface IncomingMessageSummary { // receivedAt, which is the sender-set Date header. arrivedAt?: Date; hasAttachments: boolean; + seen?: boolean; + flagged?: boolean; +} + +export interface MessageFlagChange { + seen?: boolean; + flagged?: boolean; } export interface IncomingMessageContent { diff --git a/apps/server/src/mail/ImapReceiver.ts b/apps/server/src/mail/ImapReceiver.ts index 352af46..7474264 100644 --- a/apps/server/src/mail/ImapReceiver.ts +++ b/apps/server/src/mail/ImapReceiver.ts @@ -13,6 +13,7 @@ import type { IncomingMessageLink, IncomingMessageSummary, MailAccount, + MessageFlagChange, MessageThreadHeaders } from "../domain/types.js"; import { getProvider } from "../providers/providerRegistry.js"; @@ -265,6 +266,26 @@ export class ImapReceiver implements MailReceiver { } } + async setFlags( + account: MailAccount, + mailbox: string, + providerMessageId: string, + change: MessageFlagChange + ): Promise { + await this.withConnectedClient(account, async (client) => { + await client.mailboxOpen(mailbox); + const options = { uid: true }; + for (const [flag, value] of [ + ["\\Seen", change.seen], + ["\\Flagged", change.flagged] + ] as const) { + if (value === undefined) continue; + const apply = value ? client.messageFlagsAdd : client.messageFlagsRemove; + await apply.call(client, providerMessageId, [flag], options); + } + }); + } + async downloadAttachment( account: MailAccount, mailbox: string, @@ -500,7 +521,9 @@ function toIncomingMessage( subject: envelope.subject ?? "", receivedAt: envelope.date instanceof Date ? envelope.date : new Date(), arrivedAt: message.internalDate instanceof Date ? message.internalDate : undefined, - hasAttachments: false + hasAttachments: false, + seen: message.flags?.has("\\Seen") ?? false, + flagged: message.flags?.has("\\Flagged") ?? false }; } diff --git a/apps/server/src/mail/MailReceiver.ts b/apps/server/src/mail/MailReceiver.ts index c487c92..13473d7 100644 --- a/apps/server/src/mail/MailReceiver.ts +++ b/apps/server/src/mail/MailReceiver.ts @@ -2,7 +2,8 @@ import type { AttachmentDownload, IncomingMessageContent, IncomingMessageSummary, - MailAccount + MailAccount, + MessageFlagChange } from "../domain/types.js"; export interface MailReceiver { @@ -17,6 +18,12 @@ export interface MailReceiver { mailbox: string, providerMessageId: string ): Promise; + setFlags?( + account: MailAccount, + mailbox: string, + providerMessageId: string, + change: MessageFlagChange + ): Promise; downloadAttachment( account: MailAccount, mailbox: string, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 00596c0..5d52276 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -66,6 +66,15 @@ await registerRoutes(app, { message.providerMessageId ); }, + setMessageFlags: async (account, message, change) => { + if (account.incomingProtocol !== "imap") { + throw Object.assign( + new Error("Flag sync is only supported for IMAP accounts."), + { statusCode: 501 } + ); + } + await imap.setFlags(account, message.mailbox, message.providerMessageId, change); + }, downloadAttachment: async (account, message, part) => { const receiver = account.incomingProtocol === "imap" ? imap : pop3; return receiver.downloadAttachment( diff --git a/apps/server/src/workers/AccountRepository.ts b/apps/server/src/workers/AccountRepository.ts index d0429d0..b4ba0ee 100644 --- a/apps/server/src/workers/AccountRepository.ts +++ b/apps/server/src/workers/AccountRepository.ts @@ -1,6 +1,6 @@ import type { MailAccount } from "../domain/types.js"; import type { PushTarget } from "../notifications/PushNotifier.js"; -import type { IncomingMessageSummary } from "../domain/types.js"; +import type { IncomingMessageSummary, MessageFlagChange } from "../domain/types.js"; export interface AccountRepository { listActiveAccounts(): Promise; @@ -13,6 +13,11 @@ export interface AccountRepository { deletePushTarget(target: PushTarget): Promise; listInbox(userId: string): Promise; saveIncomingMessage(message: IncomingMessageSummary): Promise; + updateMessageFlags( + accountId: string, + providerMessageId: string, + change: MessageFlagChange + ): Promise; deleteMessages(accountId: string): Promise; } @@ -104,4 +109,14 @@ export class InMemoryAccountRepository implements AccountRepository { this.messages.set(key, message); return isNew; } + + async updateMessageFlags( + accountId: string, + providerMessageId: string, + change: MessageFlagChange + ): Promise { + const key = `${accountId}:${providerMessageId}`; + const message = this.messages.get(key); + if (message) this.messages.set(key, { ...message, ...change }); + } } diff --git a/apps/server/src/workers/LocalFileAccountRepository.ts b/apps/server/src/workers/LocalFileAccountRepository.ts index 742a559..bce4a8c 100644 --- a/apps/server/src/workers/LocalFileAccountRepository.ts +++ b/apps/server/src/workers/LocalFileAccountRepository.ts @@ -1,6 +1,6 @@ import { dirname } from "node:path"; import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; -import type { IncomingMessageSummary, MailAccount } from "../domain/types.js"; +import type { IncomingMessageSummary, MailAccount, MessageFlagChange } from "../domain/types.js"; import type { PushTarget } from "../notifications/PushNotifier.js"; import type { AccountRepository } from "./AccountRepository.js"; @@ -129,6 +129,19 @@ export class LocalFileAccountRepository implements AccountRepository { return isNew; } + async updateMessageFlags( + accountId: string, + providerMessageId: string, + change: MessageFlagChange + ): Promise { + await this.ensureLoaded(); + const key = `${accountId}:${providerMessageId}`; + const message = this.messages.get(key); + if (!message) return; + this.messages.set(key, { ...message, ...change }); + await this.persist(); + } + private async ensureLoaded(): Promise { this.loadPromise ??= this.load(); await this.loadPromise; diff --git a/apps/server/test/accountReconnect.test.ts b/apps/server/test/accountReconnect.test.ts index 6d020ca..07ebc05 100644 --- a/apps/server/test/accountReconnect.test.ts +++ b/apps/server/test/accountReconnect.test.ts @@ -42,6 +42,7 @@ async function setup(account: MailAccount) { throw authenticationFailure("Authentication failed."); } }, + setMessageFlags: async () => undefined, startAccountSync: async () => { calls.push("start"); }, diff --git a/apps/server/test/accountValidate.test.ts b/apps/server/test/accountValidate.test.ts index e1ae571..45928cd 100644 --- a/apps/server/test/accountValidate.test.ts +++ b/apps/server/test/accountValidate.test.ts @@ -30,6 +30,7 @@ async function validate(syncErrorCode: MailAccount["syncErrorCode"]) { fetchMessageContent: async () => { throw new Error("unused"); }, + setMessageFlags: async () => undefined, downloadAttachment: async () => null, startAccountSync: async () => undefined, resumeAccountSync: async () => { diff --git a/apps/server/test/messageFlags.test.ts b/apps/server/test/messageFlags.test.ts new file mode 100644 index 0000000..77b6000 --- /dev/null +++ b/apps/server/test/messageFlags.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import type { MessageFlagChange } from "../src/domain/types.js"; +import { registerRoutes } from "../src/api/routes.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +async function setup(failServer = false) { + const now = new Date(); + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount({ + id: "account-1", + userId: "demo-user", + providerId: "naver", + emailAddress: "user@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "app-password", + createdAt: now, + updatedAt: now + }); + await accounts.saveIncomingMessage({ + accountId: "account-1", + providerMessageId: "7", + mailbox: "INBOX", + from: "a@example.com", + subject: "hi", + receivedAt: now, + hasAttachments: false, + seen: false, + flagged: false + }); + const calls: Array<[string, MessageFlagChange]> = []; + const app = Fastify(); + await registerRoutes(app, { + accounts, + sender: {} as never, + validateAccount: async () => undefined, + fetchMessageContent: async () => { + throw new Error("unused"); + }, + setMessageFlags: async (_account, message, change) => { + if (failServer) throw new Error("server down"); + calls.push([message.providerMessageId, change]); + }, + startAccountSync: async () => undefined, + resumeAccountSync: async () => undefined, + stopAccountSync: async () => undefined + }); + return { app, calls }; +} + +const url = "/accounts/account-1/messages/7/flags"; + +test("flag change goes to the server and the stored copy", async () => { + const { app, calls } = await setup(); + const response = await app.inject({ + method: "POST", + url, + payload: { seen: true } + }); + assert.equal(response.statusCode, 200); + assert.deepEqual(response.json(), { seen: true, flagged: false }); + assert.deepEqual(calls, [["7", { seen: true }]]); + + const list = await app.inject({ method: "GET", url: "/accounts/account-1/messages" }); + assert.equal(list.json()[0].seen, true); +}); + +test("rejects an empty change and unknown messages", async () => { + const { app, calls } = await setup(); + // Zod errors become 400 in server.ts's error handler; bare Fastify gives 500. + const empty = await app.inject({ method: "POST", url, payload: {} }); + assert.notEqual(empty.statusCode, 200); + assert.equal(calls.length, 0); + const missing = await app.inject({ + method: "POST", + url: "/accounts/account-1/messages/99/flags", + payload: { seen: true } + }); + assert.equal(missing.statusCode, 404); +}); + +test("keeps the stored copy when the server rejects the change", async () => { + const { app } = await setup(true); + const response = await app.inject({ + method: "POST", + url, + payload: { flagged: true } + }); + assert.equal(response.statusCode, 500); + const list = await app.inject({ method: "GET", url: "/accounts/account-1/messages" }); + assert.equal(list.json()[0].flagged, false); +});