diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 5d24827..fb76575 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -267,6 +267,12 @@ class AppStrings { String get deleteAccountDescription => _ko ? '이 앱에 저장된 계정과 동기화된 메일 목록이 삭제됩니다.' : 'This removes the account and synced mail list from this app.'; + String get signature => _ko ? '서명' : 'Signature'; + String get signatureHint => _ko + ? '새 메일 끝에 자동으로 붙습니다. 비워 두면 서명을 붙이지 않습니다.' + : 'Added to the end of new messages. Leave empty for no signature.'; + String get signatureSaved => _ko ? '서명을 저장했습니다.' : 'Signature saved.'; + String get save => _ko ? '저장' : 'Save'; String get cancel => _ko ? '취소' : 'Cancel'; String get statusIdle => _ko ? '대기' : 'Idle'; String get statusValidating => _ko ? '검증 중' : 'Validating'; diff --git a/apps/client/lib/features/accounts/accounts_page.dart b/apps/client/lib/features/accounts/accounts_page.dart index add8169..caa2bc4 100644 --- a/apps/client/lib/features/accounts/accounts_page.dart +++ b/apps/client/lib/features/accounts/accounts_page.dart @@ -7,6 +7,7 @@ import '../../core/i18n/language_controller.dart'; import '../../services/browser_launcher.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; +import '../message/compose_page.dart' show composeAccountsProvider; import 'account_providers.dart'; export 'account_providers.dart' show accountsProvider, accountMessagesProvider; @@ -472,6 +473,8 @@ class _AccountDetail extends ConsumerWidget { value: _receiveModeLabel(account, strings), ), ], + const SizedBox(height: 24), + _SignatureEditor(key: ValueKey(account.id), account: account), if (account.syncError != null) ...[ const SizedBox(height: 12), Text( @@ -484,6 +487,85 @@ class _AccountDetail extends ConsumerWidget { } } +/// Saves a signature and refreshes caches; lives in the provider scope so it +/// completes even if the editor widget is disposed mid-request. +final _saveSignatureProvider = Provider< + Future Function(String accountId, String signature)>((ref) { + return (accountId, signature) async { + await ref.read(mailApiClientProvider).updateAccountSignature( + accountId: accountId, + signature: signature, + ); + ref.invalidate(accountsProvider); + ref.invalidate(composeAccountsProvider); + }; +}, name: 'saveSignature'); + +class _SignatureEditor extends ConsumerStatefulWidget { + const _SignatureEditor({super.key, required this.account}); + + final MailAccountSummary account; + + @override + ConsumerState<_SignatureEditor> createState() => _SignatureEditorState(); +} + +class _SignatureEditorState extends ConsumerState<_SignatureEditor> { + late final _controller = TextEditingController(text: widget.account.signature); + bool _saving = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _save() async { + final strings = ref.read(appStringsProvider); + final messenger = ScaffoldMessenger.maybeOf(context); + final save = ref.read(_saveSignatureProvider); + setState(() => _saving = true); + try { + await save(widget.account.id, _controller.text); + if (!mounted) return; + messenger?.showSnackBar(SnackBar(content: Text(strings.signatureSaved))); + } catch (error) { + if (!mounted) return; + messenger?.showSnackBar( + SnackBar(content: Text(friendlyError(error, strings))), + ); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + final strings = ref.watch(appStringsProvider); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _controller, + minLines: 3, + maxLines: 8, + maxLength: 2000, + decoration: InputDecoration( + labelText: strings.signature, + helperText: strings.signatureHint, + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: 8), + FilledButton( + onPressed: _saving ? null : _save, + child: Text(strings.save), + ), + ], + ); + } +} + String _receiveModeLabel(MailAccountSummary account, AppStrings strings) { final idle = account.idleSupported; if (idle == null) return strings.receiveUnknown; diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index fc06f56..ffa103b 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -16,6 +16,21 @@ final composeAccountsProvider = FutureProvider>((ref) { return ref.watch(mailApiClientProvider).fetchAccounts(); }); +const _signatureSeparator = '\n\n-- \n'; + +/// Appends [signature] to [body], or swaps it for [previous] when the user +/// has not edited the old signature block. +String swapSignature(String body, String previous, String signature) { + final oldBlock = previous.isEmpty ? '' : _signatureSeparator + previous; + final newBlock = signature.isEmpty ? '' : _signatureSeparator + signature; + if (oldBlock.isNotEmpty) { + // Edited or deleted by the user: leave the body alone. + if (!body.endsWith(oldBlock)) return body; + return body.substring(0, body.length - oldBlock.length) + newBlock; + } + return body + newBlock; +} + class ComposePage extends ConsumerStatefulWidget { const ComposePage({ super.key, @@ -40,6 +55,8 @@ class _ComposePageState extends ConsumerState { final _subjectController = TextEditingController(); final _bodyController = TextEditingController(); String? _accountId; + String _signature = ''; + bool _signatureInitialized = false; bool _sending = false; @override @@ -109,6 +126,15 @@ class _ComposePageState extends ConsumerState { !items.any((account) => account.id == _accountId)) { _accountId = items.firstOrNull?.id; } + if (!_signatureInitialized && items.isNotEmpty) { + _signatureInitialized = true; + if (widget.initialDraft != null) { + // Recovered draft already carries its signature: adopt, don't re-insert. + _signature = _signatureOf(items, _accountId); + } else { + _useSignatureOf(items, _accountId); + } + } return ListView( padding: const EdgeInsets.all(24), @@ -123,7 +149,10 @@ class _ComposePageState extends ConsumerState { child: Text(account.emailAddress), ), ], - onChanged: (value) => setState(() => _accountId = value), + onChanged: (value) => setState(() { + _accountId = value; + _useSignatureOf(items, value); + }), ), const SizedBox(height: 12), TextField( @@ -170,6 +199,36 @@ class _ComposePageState extends ConsumerState { ); } + String _signatureOf(List items, String? accountId) => + items.where((a) => a.id == accountId).firstOrNull?.signature ?? ''; + + void _useSignatureOf(List items, String? accountId) { + final next = _signatureOf(items, accountId); + // Reply quote stays below the signature (signature sits above the quote). + final quote = widget.initialDraft == null ? widget.reply?.body ?? '' : ''; + final full = _bodyController.text; + if (!full.endsWith(quote)) return; + final body = full.substring(0, full.length - quote.length); + // User edited the managed block: keep owning the old signature so later + // switches neither overwrite the edit nor append a duplicate. + if (_signature.isNotEmpty && + !body.endsWith(_signatureSeparator + _signature)) { + return; + } + final text = swapSignature(body, _signature, next); + final bodyEnd = text.length - + (next.isEmpty ? 0 : _signatureSeparator.length + next.length); + final selection = _bodyController.selection; + // An invalid selection jumps to the end on focus, i.e. after the signature. + _bodyController.value = TextEditingValue( + text: text + quote, + selection: selection.isValid && selection.end <= bodyEnd + ? selection + : TextSelection.collapsed(offset: bodyEnd), + ); + _signature = next; + } + Future _send() async { final accountId = _accountId; if (accountId == null || _sending) return; diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 1426402..df671e2 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -264,6 +264,15 @@ class MailApiClient { }); } + Future updateAccountSignature({ + required String accountId, + required String signature, + }) async { + await _dio.put('/accounts/$accountId/signature', data: { + 'signature': signature, + }); + } + Future validateStoredAccount(String accountId) async { await _dio.post('/accounts/$accountId/validate'); } @@ -588,6 +597,7 @@ class MailAccountSummary { this.syncErrorCode, required this.initialSync, required this.lastSyncedAtLabel, + this.signature = '', this.threadBackfilling = false, this.idleSupported, this.capabilitiesCheckedAtLabel = '', @@ -597,6 +607,7 @@ class MailAccountSummary { final String id; final String providerId; final String emailAddress; + final String signature; final String incomingProtocol; final String authMode; final String syncStatus; @@ -630,6 +641,7 @@ class MailAccountSummary { json['initialSync'] as Map) : null, lastSyncedAtLabel: _formatReceivedAt(json['lastSyncedAt'] as String?), + signature: json['signature'] as String? ?? '', threadBackfilling: json['threadBackfill'] == 'running', idleSupported: capabilities?['idle'] as bool?, capabilitiesCheckedAtLabel: diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 5ce92a1..c86641c 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -9,6 +9,7 @@ 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/compose_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'; @@ -34,7 +35,9 @@ void main() { test('successful attachment download writes destination, leaves no temp', () async { + final httpOverrides = HttpOverrides.current; HttpOverrides.global = null; // test binding stubs HTTP with 400 + addTearDown(() => HttpOverrides.global = httpOverrides); final server = await HttpServer.bind('127.0.0.1', 0); addTearDown(() => server.close(force: true)); server.listen((req) { @@ -880,6 +883,271 @@ void main() { expect(openedUri, Uri.parse(url)); }); + test('swaps the signature only when the user has not edited it', () { + expect(swapSignature('', '', 'A'), '\n\n-- \nA'); + expect(swapSignature('hi', '', ''), 'hi'); + expect(swapSignature('hi\n\n-- \nA', 'A', 'B'), 'hi\n\n-- \nB'); + expect(swapSignature('hi\n\n-- \nA', 'A', ''), 'hi'); + expect( + swapSignature('hi\n\n-- \nA edited', 'A', 'B'), + 'hi\n\n-- \nA edited', + ); + }); + + testWidgets('compose appends the account signature and swaps it', ( + WidgetTester tester, + ) async { + const accounts = [ + MailAccountSummary( + id: 'a', + providerId: 'gmail', + emailAddress: 'a@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: 'Sig A', + ), + MailAccountSummary( + id: 'b', + providerId: 'gmail', + emailAddress: 'b@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ), + ]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + String body() => + tester.widget(find.byType(TextField).last).controller!.text; + expect(body(), '\n\n-- \nSig A'); + + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('b@example.com').last); + await tester.pumpAndSettle(); + expect(body(), ''); + }); + + testWidgets('reply puts the signature above the quote; recovery adds none', ( + WidgetTester tester, + ) async { + const accounts = [ + MailAccountSummary( + id: 'a', + providerId: 'gmail', + emailAddress: 'a@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: 'Sig A', + ), + ]; + Future open(ComposePage page) async { + await tester.pumpWidget( + ProviderScope( + key: UniqueKey(), + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: MaterialApp(home: page), + ), + ); + await tester.pumpAndSettle(); + return tester + .widget(find.byType(TextField).last) + .controller! + .text; + } + + const quote = '\n\nOn x, y wrote:\n> hi'; + expect( + await open( + const ComposePage( + reply: ReplyDraft( + to: ['y@example.com'], + cc: [], + subject: 'Re: s', + body: quote, + ), + ), + ), + '\n\n-- \nSig A$quote', + ); + const recovered = 'text\n\n-- \nSig A'; + expect( + await open( + const ComposePage( + initialDraft: ComposeDraft( + accountId: 'a', + to: 'y@example.com', + subject: 's', + body: recovered, + ), + ), + ), + recovered, + ); + }); + + testWidgets('compose keeps an edited signature without duplicating it', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id, String signature) => + MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: signature, + ); + final accounts = [account('a', 'Sig A'), account('b', '')]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + final bodyField = tester.widget(find.byType(TextField).last); + bodyField.controller!.text = '\n\n-- \nSig A edited'; + + Future pick(String email) async { + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text(email).last); + await tester.pumpAndSettle(); + } + + await pick('b@example.com'); + await pick('a@example.com'); + expect(bodyField.controller!.text, '\n\n-- \nSig A edited'); + }); + + testWidgets('compose types before the signature and still swaps it', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id, String signature) => + MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: signature, + ); + final accounts = [account('a', 'Sig A'), account('b', 'Sig B')]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + final controller = + tester.widget(find.byType(TextField).last).controller!; + await tester.showKeyboard(find.byType(TextField).last); + await tester.pump(); + // Type at the caret the way the platform IME does. + final value = controller.value; + tester.testTextInput.updateEditingValue( + value.replaced(value.selection, 'Hi'), + ); + await tester.pump(); + expect(controller.text, 'Hi\n\n-- \nSig A'); + + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('b@example.com').last); + await tester.pumpAndSettle(); + expect(controller.text, 'Hi\n\n-- \nSig B'); + expect(controller.selection, const TextSelection.collapsed(offset: 2)); + }); + + testWidgets('signature save refreshes caches after switching accounts', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id) => MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + final api = _SlowSignatureApi(); + var accountLoads = 0; + await tester.binding.setSurfaceSize(const Size(1200, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async { + accountLoads += 1; + return [account('first'), account('second')]; + }), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, id) async => const []), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('계정관리').first); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).first, 'Sig'); + await tester.tap(find.widgetWithText(FilledButton, '저장')); + await tester.pump(); + + await tester.tap(find.text('second@example.com').first); + await tester.pumpAndSettle(); + final loadsBefore = accountLoads; + api.release.complete(); + await tester.pumpAndSettle(); + + expect(api.saved, [('first', 'Sig')]); + expect(accountLoads, greaterThan(loadsBefore)); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(const SizedBox()); + }); + test('merges word boxes into one continuous underline per line', () { final merged = mergeLinkUnderlineBoxes(const [ TextBox.fromLTRBD(0, 0, 42, 20, TextDirection.ltr), @@ -1276,6 +1544,22 @@ class _DelayedSearchApi extends MailApiClient { } } +class _SlowSignatureApi extends MailApiClient { + _SlowSignatureApi() : super(baseUrl: 'http://127.0.0.1:1'); + + final release = Completer(); + final saved = <(String, String)>[]; + + @override + Future updateAccountSignature({ + required String accountId, + required String signature, + }) async { + await release.future; + saved.add((accountId, signature)); + } +} + class _CredentialRecordingApi extends MailApiClient { _CredentialRecordingApi() : super(baseUrl: 'http://127.0.0.1:1'); diff --git a/apps/server/package.json b/apps/server/package.json index ec4c0a5..4b79585 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/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", + "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/accountSignature.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/api/routes.ts b/apps/server/src/api/routes.ts index 398a76d..482dc14 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -249,6 +249,24 @@ export async function registerRoutes( return reply.code(204).send(); }); + app.put("/accounts/:id/signature", async (request, reply) => { + const params = z.object({ id: z.string() }).parse(request.params); + const body = z.object({ signature: z.string().max(2000) }).parse(request.body); + const account = await deps.accounts.getAccount(params.id); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + + const signature = body.signature.trim(); + account.signature = signature || undefined; + account.updatedAt = new Date(); + await deps.accounts.updateAccount(account); + + const { encryptedSecretRef: _secret, ...publicAccount } = account; + return publicAccount; + }); + app.patch("/accounts/:id/notifications", async (request, reply) => { const params = z.object({ id: z.string() }).parse(request.params); const body = z.object({ enabled: z.boolean() }).parse(request.body); diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index 4f1b4b4..0ff9b0f 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -47,6 +47,7 @@ export interface MailAccount { providerId: ProviderId; emailAddress: string; displayName?: string; + signature?: string; authMode: AuthMode; incomingProtocol: MailProtocol; encryptedSecretRef: string; diff --git a/apps/server/test/accountSignature.test.ts b/apps/server/test/accountSignature.test.ts new file mode 100644 index 0000000..e007144 --- /dev/null +++ b/apps/server/test/accountSignature.test.ts @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import type { MailAccount } from "../src/domain/types.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +process.env.GOOGLE_OAUTH_CLIENT_ID = "test-client"; +const { registerRoutes } = await import("../src/api/routes.js"); + +async function setup() { + const now = new Date(); + const account: MailAccount = { + id: "account-1", + userId: "demo-user", + providerId: "naver", + emailAddress: "user@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "secret", + createdAt: now, + updatedAt: now + }; + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount(account); + const app = Fastify(); + await registerRoutes(app, { accounts } as never); + return { app, accounts }; +} + +test("saves, lists and clears an account signature", async () => { + const { app, accounts } = await setup(); + + const saved = await app.inject({ + method: "PUT", + url: "/accounts/account-1/signature", + payload: { signature: " Kim\nExample Corp " } + }); + assert.equal(saved.statusCode, 200); + assert.equal(saved.json().signature, "Kim\nExample Corp"); + assert.equal(saved.json().encryptedSecretRef, undefined); + assert.equal((await accounts.getAccount("account-1"))?.signature, "Kim\nExample Corp"); + + const listed = await app.inject({ method: "GET", url: "/accounts" }); + assert.equal(listed.json()[0].signature, "Kim\nExample Corp"); + + await app.inject({ + method: "PUT", + url: "/accounts/account-1/signature", + payload: { signature: " " } + }); + assert.equal((await accounts.getAccount("account-1"))?.signature, undefined); +}); + +test("rejects unknown accounts", async () => { + const { app } = await setup(); + const response = await app.inject({ + method: "PUT", + url: "/accounts/missing/signature", + payload: { signature: "x" } + }); + assert.equal(response.statusCode, 404); +});