verifyTurnServer method

Future<bool> verifyTurnServer()

Implementation

Future<bool> verifyTurnServer() async {
  final iceServers = await getIceServers();
  final configuration = <String, dynamic>{
    'iceServers': iceServers,
    'sdpSemantics': 'unified-plan',
    'iceCandidatePoolSize': 1,
    'iceTransportPolicy': 'relay'
  };
  pc1 = await delegate.createPeerConnection(configuration);
  pc2 = await delegate.createPeerConnection(configuration);

  pc1!.onIceCandidate = (candidate) {
    if (candidate.candidate!.contains('relay')) {
      pc2!.addCandidate(candidate);
    }
  };
  pc2!.onIceCandidate = (candidate) {
    if (candidate.candidate!.contains('relay')) {
      pc1!.addCandidate(candidate);
    }
  };

  await pc1!.createDataChannel('conn-tester', RTCDataChannelInit());

  final offer = await pc1!.createOffer();

  await pc2!.setRemoteDescription(offer);
  final answer = await pc2!.createAnswer();

  await pc1!.setLocalDescription(offer);
  await pc2!.setLocalDescription(answer);

  await pc1!.setRemoteDescription(answer);

  Future<void> dispose() async {
    await Future.wait([
      pc1!.close(),
      pc2!.close(),
    ]);
    await Future.wait([
      pc1!.dispose(),
      pc2!.dispose(),
    ]);
  }

  bool connected = false;
  try {
    await waitUntilAsync(() async {
      if (pc1!.connectionState ==
              RTCPeerConnectionState.RTCPeerConnectionStateConnected &&
          pc2!.connectionState ==
              RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
        connected = true;
        return true;
      }
      return false;
    });
  } catch (e, s) {
    Logs()
        .e('[VOIP] ConnectionTester Error while testing TURN server: ', e, s);
  }

  // ignore: unawaited_futures
  dispose();
  return connected;
}