connectRelay method

Future<bool> connectRelay(
  1. String dirtyUrl, {
  2. int connectTimeout = DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT,
})

Connect a new relay

Implementation

Future<bool> connectRelay(String dirtyUrl,
    {int connectTimeout = DEFAULT_WEB_SOCKET_CONNECT_TIMEOUT}) async {
  String? url = Relay.clean(dirtyUrl);
  if (url == null) {
    return false;
  }
  if (blockedRelays.contains(url)) {
    return false;
  }
  try {
    if (relays[url] == null) {
      relays[url] = Relay(url);
    }
    relays[url]!.tryingToConnect();
    if (url.startsWith("wss://brb.io")) {
      relays[url]!.failedToConnect();
      relays[url]!.stats.connectionErrors++;
      return false;
    }
    // var connectionOptions = SocketConnectionOptions(
    //   timeoutConnectionMs: connectTimeout*1000,
    //   skipPingMessages: true,
    //   pingRestrictionForce: true,
    //   reconnectionDelay: const Duration(seconds:5),
    // );
    // webSockets[url] = IWebSocketHandler<String, String>.createClient(
    //   url,
    //   SocketSimpleTextProcessor(),
    //   connectionOptions: connectionOptions
    // );
    final wsUrl = Uri.parse(url);
    webSockets[url] = WebSocketChannel.connect(wsUrl);
    await webSockets[url]!.ready;

    // webSockets[url] = await WebSocket.connect(url, customClient: httpClient)
    //     .timeout(Duration(seconds: connectTimeout))
    //     .catchError((error) {
    //   return Future<WebSocket>.error(error);
    // });
    // webSockets[url]!.logEventStream.listen((event) {
    //   if (event.socketLogEventType != SocketLogEventType.fromServerMessage) {
    //     print("${event.socketLogEventType.value} -> ${event.data}");
    //   }
    // });

    startListeningToSocket(url);
    // webSockets[url]!.socketHandlerStateStream.listen((stateEvent) {
    //   print('> $url ${stateEvent.status}');
    // });

    // bool connected = await webSockets[url]!.connect();

    // await for (final state in webSockets[url]!.socketHandlerStateStream) {
    //   print('> $url ${state.status}');
    //   if (state.status == SocketStatus.connected) {
    //     break;
    //   }
    // };

    // if (connected) {
    developer.log("connected to relay: $url");
    relays[url]!.succeededToConnect();
    relays[url]!.stats.connections++;
    getRelayInfo(url);
    return true;
    // }
  } catch (e) {
    print("!! could not connect to $url -> $e");
    webSockets.remove(url);
  }
  relays[url]!.failedToConnect();
  relays[url]!.stats.connectionErrors++;
  return false;
}