expungeMessages method

Future<ExpungeAck?> expungeMessages({
  1. PeerId? serverPeerId,
  2. String? folderPath,
})

Expunge messages marked with \Deleted flag (IMAP EXPUNGE)

folderPath Optional: expunge specific folder only (null = all folders)

Implementation

Future<ExpungeAck?> expungeMessages({
  PeerId? serverPeerId,
  String? folderPath,
}) async {
  _logger.info('Expunging deleted messages from ${folderPath ?? 'all folders'}');

  // Select server
  final serverId = serverPeerId ??
      await _serverSelector.selectServer(config.preferredServers);

  if (serverId == null) {
    _logger.warning('No S&F server available');
    return null;
  }

  P2PStream? stream;
  try {
    // Use MAA (Mail Access Agent) protocol for IMAP-style operations
    final context = Context();
    stream = await host.newStream(
      serverId,
      [AccessHandler.protocolId],
      context,
    ).timeout(config.connectionTimeout);

    final ack = await AccessHandler.expunge(
      stream,
      host.id,
      folderPath: folderPath,
    ).timeout(config.messageTimeout);

    _logger.info('Expunged ${ack.deletedCount} messages');
    return ack;

  } on TimeoutException {
    _logger.warning('Expunge timed out');
    return null;
  } catch (e) {
    _logger.warning('Failed to expunge: $e');
    return null;
  } finally {
    // The stream is closed on every path: a stream left open holds a slot
    // on the connection for as long as the session lives.
    if (stream != null && !stream.isClosed) {
      try {
        await stream.close();
      } catch (e) {
        _logger.fine('Error closing stream: $e');
      }
    }
  }
}