setTokens method
Creates and registered the Twilio Device. Returns true if successful, false otherwise.
See twilio_js.Device.new
Note: deviceToken is ignored for web
Implementation
@override
Future<bool?> setTokens({required String accessToken, String? deviceToken}) async {
// TODO use updateOptions for Twilio device
assert(accessToken.isNotEmpty, "Access token cannot be empty");
// The Twilio JS SDK is bundled with this package and injected on demand - `twilio_js.Device`
// resolves the `window.Twilio` global, so the SDK must be present before we construct it.
try {
await ensureSdkLoaded();
} catch (e) {
printDebug("Failed to load Twilio Voice JS SDK: $e");
// Keep the default "LOG" prefix - a prefix-less string is not a valid event and would
// throw in [parseCallEvent].
logLocalEvent("Failed to load Twilio Voice JS SDK: $e");
return false;
}
// assert(deviceToken != null && deviceToken.isNotEmpty, "Device token cannot be null or empty");
// if (device != null) {
// // check active calls?
// printDebug("Twilio device already active, unregistering...");
// try {
// await device!.unregister();
//
// } catch (e) {
// printDebug("Failed to unregister device: $e");
// return false;
// }
// }
try {
final shouldUpdate = device != null && getDeviceState(device!) == DeviceState.registered;
if (shouldUpdate) {
if(device?.token == accessToken) {
printDebug("Device token is the same, no need to update");
return true;
}
device!.updateToken(accessToken);
} else {
final existing = device;
if (existing != null) {
try {
_detachDeviceListeners(existing);
existing.destroy();
} catch (e) {
printDebug("Failed to tear down previous Twilio Device: $e");
}
}
/// opus set as primary code
/// https://www.twilio.com/blog/client-javascript-sdk-1-7-ga
List<String> codecs = ["opus", "pcmu"];
twilio_js.DeviceOptions options = twilio_js.DeviceOptions(
logLevel: 1,
codecPreferences: codecs.map((e) => e.toJS).toList().toJS,
closeProtection: true,
enableImprovedSignalingErrorPrecision: true,
allowIncomingWhileBusy: _allowIncomingWhileBusy,
);
/// create new Twilio device
device = twilio_js.Device(accessToken, options);
_call.device = device;
_attachDeviceListeners(device!);
// Register device to accept notifications
final promise = device!.register();
await promise.toDart;
}
return true;
} catch (e) {
printDebug("Failed to set Twilio Device token: $e");
return false;
}
}