connectSocket function

Future<Socket> connectSocket(
  1. ConnectSocketOptions options
)

Connects to a media socket with the specified options. Validates the API key or token and initiates a socket connection.

Throws an exception if inputs are invalid or if connection fails.

Example usage:

final options = ConnectSocketOptions(
  apiUserName: "user123",
  apiKey: "yourApiKeyHere",
  link: "https://socketlink.com",
);

try {
  final socket = await connectSocket(options);
  print("Connected to socket with ID: ${socket.id}");
} catch (error) {
  print("Failed to connect to socket: $error");
}

Implementation

Future<io.Socket> connectSocket(ConnectSocketOptions options) async {
  // Input validation
  if (options.apiUserName.isEmpty) throw Exception('API username required.');
  if ((options.apiKey?.isEmpty ?? true) &&
      (options.apiToken?.isEmpty ?? true)) {
    throw Exception('API key or token required.');
  }
  if (options.link.isEmpty) throw Exception('Socket link required.');

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

  // Configure socket options based on whether apiKey or apiToken is used
  final query = useKey
      ? {'apiUserName': options.apiUserName, 'apiKey': options.apiKey}
      : {'apiUserName': options.apiUserName, 'apiToken': options.apiToken};

  final socket = io.io('${options.link}/media', {
    'transports': ['websocket'],
    'query': query,
  });

  // Determine the socket connection path
  String conn = 'media';
  try {
    if (options.link.contains('mediasfu.com') &&
        (RegExp('c').allMatches(options.link).length > 1)) {
      conn = 'consume';
    }
  } catch (e) {
    // Do nothing
  }

  final completer = Completer<io.Socket>();

  // Handle connection success
  socket.onConnect((_) {
    if (kDebugMode) print('Connected to $conn socket with ID: ${socket.id}');
    completer.complete(socket);
  });

  // Handle connection error
  socket.onConnectError((error) {
    completer
        .completeError(Exception('Error connecting to media socket: $error'));
  });

  return completer.future;
}