doRelayBroadcast method

Future<void> doRelayBroadcast(
  1. String relayUrl,
  2. Nip01Event nostrEvent, {
  3. RelayAuth? auth,
})

===================================================================================== The flow:

  1. register broadcast in relay manager's global state, so that even failed to connect relays will be taken into account for broadcast done logic
  2. make sure the relay is connected by calling reconnect
  3. if connected was successfull send the event
  4. otherwise call failBroadcast in order to publish a RelayBroadcastResponse for that specific relay with an error message

Implementation

Future<void> doRelayBroadcast(
  String relayUrl,
  Nip01Event nostrEvent, {
  RelayAuth? auth,
}) async {
  _relayManager.registerRelayBroadcast(
    eventToPublish: nostrEvent,
    relayUrl: relayUrl,
  );

  RelayConnectivity? relayConnectivity;
  Object? error;
  try {
    relayConnectivity = await _relayManager.connectionForBroadcast(
      relayUrl,
      auth,
      connectTimeout: 1,
    );
  } catch (e) {
    Logger.log.w(
      () => "Error during quick connect for $relayUrl in doRelayBroadcast",
      error: e,
    );
    error = e;
  }

  if (relayConnectivity != null) {
    // checked once the connection is there: a newer version may have been
    // persisted while it was opening, and that one supersedes this send
    if (await _shouldSkipObsoleteReplaceableBroadcast(nostrEvent)) {
      Logger.log.d(
        () =>
            'skip obsolete specific-relay broadcast ${nostrEvent.id} for $relayUrl',
      );
      _relayManager.failBroadcast(
        nostrEvent.id,
        relayUrl,
        'obsolete replaceable event skipped',
      );
      return;
    }

    await _relayManager.sendOrThrow(
      relayConnectivity,
      ClientMsg(ClientMsgType.kEvent, event: nostrEvent),
    );
    return;
  }
  if (auth is RelayAuthRequire) {
    _relayManager.failBroadcast(
      nostrEvent.id,
      relayUrl,
      "no connection bound to ${auth.account.pubkey} could be opened",
    );
    return;
  }
  _relayManager.failBroadcast(
    nostrEvent.id,
    relayUrl,
    "Could not connect to relay $relayUrl $error",
  );
}