Files
sharedinbox/lib/core/sync/account_sync_manager.dart
T
Thomas GüttlerandClaude Sonnet 4.6 03d35387f7 Linting, tests, README, CI, and code quality improvements
Linting:
- analysis_options.yaml: flutter_lints base + 20 additional rules
  (prefer_single_quotes, avoid_print, cancel_subscriptions,
  unawaited_futures, empty_catches, always_declare_return_types, …)
- unused_import / dead_code treated as errors

pubspec.yaml:
- Remove 6 unused packages: freezed, freezed_annotation, json_annotation,
  json_serializable, riverpod_generator, collection
- Add test: ^1.25.0 for pure-Dart unit tests

Testable utilities (extracted from screen code):
- lib/core/utils/html_utils.dart — htmlToPlain()
- lib/core/utils/format_utils.dart — fmtSize()
- lib/core/utils/logger.dart — thin debugPrint wrapper

Unit tests (test/unit/, no device required):
- html_utils_test.dart — 13 cases covering tags, entities, edge cases
- format_utils_test.dart — B / KB / MB / GB formatting
- email_model_test.dart — EmailAddress JSON roundtrip, toString, EmailDraft
- account_sync_backoff_test.dart — exponential backoff + clamping

Taskfile:
- task test → dart test test/unit/ (fast, no device)
- task test-flutter → flutter test (widget tests)
- task check → analyze + unit tests in parallel

README rewrite:
- Covers user flow (download, add account)
- Developer flow: nix develop, direnv allow, task codegen, task check
- Platform status table (Linux done, others pending)
- Project layout diagram
- Schema-change workflow

CI (.github/workflows/ci.yml):
- analyze-and-test job: flutter analyze + dart test on every push/PR
- integration job: Nix + Stalwart on push to main
- build-linux job: flutter build linux --release

Logging:
- Replace all bare catch (_) {} with log() calls
- Sync backoff errors now print account email + retry delay
- STATUS failures on \Noselect mailboxes logged at debug level
- STARTTLS failures logged before continuing without TLS

.gitignore:
- Add .direnv/, .flutter-plugins-dependencies
- Add all platform generated-plugin wiring files
- Add .env / .env.local
- Add linux/build/

.env.example: documents optional STALWART_PORT overrides

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-16 08:11:29 +02:00

139 lines
3.6 KiB
Dart

import 'dart:async';
import 'package:enough_mail/enough_mail.dart' as imap;
import '../models/account.dart';
import '../repositories/account_repository.dart';
import '../repositories/email_repository.dart';
import '../repositories/mailbox_repository.dart';
import '../utils/logger.dart';
import '../../data/imap/imap_client_factory.dart';
/// Manages one IMAP IDLE connection per account.
/// On a new-message notification it triggers a re-sync then goes back to IDLE.
class AccountSyncManager {
AccountSyncManager(this._accounts, this._mailboxes, this._emails);
final AccountRepository _accounts;
final MailboxRepository _mailboxes;
final EmailRepository _emails;
final Map<String, _AccountSync> _active = {};
StreamSubscription<List<Account>>? _accountsSub;
void start() {
_accountsSub = _accounts.observeAccounts().listen((accounts) {
final currentIds = accounts.map((a) => a.id).toSet();
// Start sync for newly added accounts.
for (final account in accounts) {
if (!_active.containsKey(account.id)) {
final sync = _AccountSync(account, _accounts, _mailboxes, _emails);
_active[account.id] = sync;
sync.start();
}
}
// Stop sync for removed accounts.
for (final id in _active.keys.toList()) {
if (!currentIds.contains(id)) {
_active.remove(id)?.stop();
}
}
});
}
void dispose() {
_accountsSub?.cancel();
for (final s in _active.values) {
s.stop();
}
_active.clear();
}
}
class _AccountSync {
_AccountSync(this.account, this._accounts, this._mailboxes, this._emails);
final Account account;
final AccountRepository _accounts;
final MailboxRepository _mailboxes;
final EmailRepository _emails;
imap.ImapClient? _idleClient;
bool _running = false;
int _backoffSeconds = 5;
void start() {
_running = true;
_loop();
}
void stop() {
_running = false;
_idleClient?.logout().ignore();
_idleClient = null;
}
Future<void> _loop() async {
while (_running) {
try {
await _sync();
await _idle();
_backoffSeconds = 5;
} catch (e, st) {
log(
'Sync failed for ${account.email}, retrying in ${_backoffSeconds}s',
error: e,
stackTrace: st,
);
await Future.delayed(Duration(seconds: _backoffSeconds));
_backoffSeconds = (_backoffSeconds * 2).clamp(5, 300);
}
}
}
Future<void> _sync() async {
await _mailboxes.syncMailboxes(account.id);
await _emails.syncEmails(account.id, 'INBOX');
}
Future<void> _idle() async {
if (!_running) return;
final password = await _accounts.getPassword(account.id);
final client = await connectImap(account, password);
_idleClient = client;
try {
await client.selectMailboxByPath('INBOX');
final newMessageCompleter = Completer<void>();
// Wake up when new messages arrive or messages are expunged.
final sub = client.eventBus
.on<imap.ImapEvent>()
.where(
(e) =>
e is imap.ImapMessagesExistEvent ||
e is imap.ImapExpungeEvent,
)
.listen((_) {
if (!newMessageCompleter.isCompleted) newMessageCompleter.complete();
});
await client.idleStart();
// Cap IDLE at 25 minutes to stay within the RFC 2177 recommendation.
await Future.any([
newMessageCompleter.future,
Future.delayed(const Duration(minutes: 25)),
]);
await client.idleDone();
await sub.cancel();
} finally {
await client.logout();
_idleClient = null;
}
}
}