connectSocket function

Future<Socket> connectSocket(
  1. String apiUserName,
  2. String apiKey,
  3. String apiToken,
  4. String link,
)

Connects to the socket using the provided API credentials and link. Returns a future that completes with the connected socket. Throws an exception if any of the required inputs are empty or if the API key or token is invalid.

Implementation

Future<io.Socket> connectSocket(
    String apiUserName, String apiKey, String apiToken, String link) async {
  // Validate inputs
  if (apiUserName.isEmpty) {
    throw Exception('API username required.');
  }
  if (apiKey.isEmpty && apiToken.isEmpty) {
    throw Exception('API key or token required.');
  }
  if (link.isEmpty) {
    throw Exception('Socket link required.');
  }

  // Validate the API key or token
  bool useKey = false;
  try {
    if (apiKey.isNotEmpty && apiKey.length == 64) {
      await validateApiKeyToken(apiKey);
      useKey = true;
    } else {
      await validateApiKeyToken(apiToken);
      useKey = false;
    }
  } catch (error) {
    throw Exception('Invalid API key or token.');
  }

  socket = io.io('$link/media', <String, dynamic>{
    'transports': ['websocket'],
    'query': useKey
        ? {'apiUserName': apiUserName, 'apiKey': apiKey}
        : {'apiUserName': apiUserName, 'apiToken': apiToken},
  });

  // Create a completer to await the connection
  Completer<io.Socket> completer = Completer<io.Socket>();

  // Handle socket connection events
  socket!.onConnect((_) {
    if (kDebugMode) {
      print('Connected to media socket with ID: ${socket!.id}');
    }
    completer.complete(socket); // Complete the future when connected
  });

  socket!.onError((error) {
    throw Exception('Error connecting to media socket.');
  });

  // Return the future from the completer
  return completer.future;
}