reconnectRelay method

Future<bool> reconnectRelay(
  1. String url, {
  2. required ConnectionSource connectionSource,
  3. bool force = false,
})

Reconnects to a relay, if the relay is not connected or the connection is closed.

Implementation

Future<bool> reconnectRelay(String url,
    {required ConnectionSource connectionSource, bool force = false}) async {
  RelayConnectivity? relayConnectivity = globalState.relays[url];
  if (relayConnectivity != null && relayConnectivity.relayTransport != null) {
    await relayConnectivity.relayTransport!.ready
        .timeout(Duration(seconds: DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT))
        .onError((error, stackTrace) {
      print("error connecting to relay ${url}: $error");
      return []; // Return an empty list in case of error
    });
  }
  if (relayConnectivity == null ||
      !relayConnectivity.relayTransport!.isOpen()) {
    if (!force &&
        (relayConnectivity == null ||
            !relayConnectivity.relay.wasLastConnectTryLongerThanSeconds(
                FAIL_RELAY_CONNECT_TRY_AFTER_SECONDS))) {
      // don't try too often
      return false;
    }

    if (!(await connectRelay(
      dirtyUrl: url,
      connectionSource: connectionSource,
    ))
        .first) {
      // could not connect
      return false;
    }
    relayConnectivity = globalState.relays[url];
    if (relayConnectivity == null ||
        !relayConnectivity.relayTransport!.isOpen()) {
      // web socket is not open
      return false;
    }
  }
  return true;
}