Implementation
Future<void> connect(
String url,
String token, {
ConnectOptions? connectOptions,
@Deprecated('deprecated, please use roomOptions in Room constructor') RoomOptions? roomOptions,
FastConnectOptions? fastConnectOptions,
}) async {
var roomOptions = this.roomOptions;
connectOptions ??= ConnectOptions();
_pendingTrackQueue.updateTtl(connectOptions.timeouts.subscribe);
// ignore: deprecated_member_use_from_same_package
if ((roomOptions.encryption != null || roomOptions.e2eeOptions != null) && engine.e2eeManager == null) {
if (!lkPlatformSupportsE2EE()) {
throw LiveKitE2EEException('E2EE is not supported on this platform');
}
// ignore: deprecated_member_use_from_same_package
final e2eeOptions = roomOptions.encryption ?? roomOptions.e2eeOptions;
_e2eeManager = E2EEManager(e2eeOptions!.keyProvider, dcEncryptionEnabled: roomOptions.encryption != null);
await _e2eeManager!.setup(this);
engine.setE2eeManager(_e2eeManager);
} else {
_e2eeManager = engine.e2eeManager;
}
if (_e2eeManager != null) {
// Disable backup codec when e2ee is enabled
roomOptions = roomOptions.copyWith(
defaultVideoPublishOptions: roomOptions.defaultVideoPublishOptions.copyWith(
backupVideoCodec: const BackupVideoCodec(enabled: false),
),
);
}
if (_regionUrlProvider?.getServerUrl().toString() != url) {
_regionUrl = null;
_regionUrlProvider = null;
}
if (isCloudUrl(Uri.parse(url))) {
if (_regionUrlProvider == null) {
_regionUrlProvider = RegionUrlProvider(url: url, token: token);
} else {
_regionUrlProvider?.updateToken(token);
}
// trigger the first fetch without waiting for a response
// if initial connection fails, this will speed up picking regional url
// on subsequent runs
unawaited(_regionUrlProvider?.fetchRegionSettings().then((settings) {
_regionUrlProvider?.setServerReportedRegions(settings);
}).catchError((e) {
logger.warning('could not fetch region settings $e');
}));
}
// configure audio for native platform
await NativeAudioManagement.start();
try {
await engine.connect(
_regionUrl ?? url,
token,
connectOptions: connectOptions,
roomOptions: roomOptions,
fastConnectOptions: fastConnectOptions,
regionUrlProvider: _regionUrlProvider,
);
} catch (e) {
logger.warning('could not connect to $url $e');
if (_regionUrlProvider != null && e is WebSocketException ||
(e is ConnectException && e.reason != ConnectionErrorReason.NotAllowed)) {
String? nextUrl;
try {
nextUrl = await _regionUrlProvider!.getNextBestRegionUrl();
} catch (error) {
if (error is ConnectException && (error.statusCode == 401)) {
rethrow;
}
}
if (nextUrl != null) {
logger.fine('Initial connection failed with ConnectionError: $e. Retrying with another region: ${nextUrl}');
await engine.connect(
nextUrl,
token,
connectOptions: connectOptions,
roomOptions: roomOptions,
fastConnectOptions: fastConnectOptions,
regionUrlProvider: _regionUrlProvider,
);
} else {
rethrow;
}
} else {
rethrow;
}
}
}