-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathmain.dart
454 lines (404 loc) · 14.1 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import 'dart:async';
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:twilio_voice/twilio_voice.dart';
import 'package:twilio_voice_example/screens/ui_call_screen.dart';
import 'package:twilio_voice_example/screens/ui_registration_screen.dart';
import 'api.dart';
import 'utils.dart';
extension IterableExtension<E> on Iterable<E> {
/// Extension on [Iterable]'s [firstWhere] that returns null if no element is found instead of throwing an exception.
E? firstWhereOrNull(bool Function(E element) test, {E Function()? orElse}) {
for (E element in this) {
if (test(element)) return element;
}
return (orElse == null) ? null : orElse();
}
}
enum RegistrationMethod {
env,
local,
firebase;
static RegistrationMethod? fromString(String? value) {
if (value == null) return null;
return RegistrationMethod.values.firstWhereOrNull((element) => element.name == value);
}
static RegistrationMethod? loadFromEnvironment() {
const value = String.fromEnvironment("REGISTRATION_METHOD");
return fromString(value);
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (kIsWeb) {
if(firebaseEnabled) {
// Add firebase config here
const options = FirebaseOptions(
apiKey: '',
appId: '',
messagingSenderId: '',
projectId: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
measurementId: '',
);
// For web apps only
// ignore: body_might_complete_normally_catch_error
await Firebase.initializeApp(options: options).catchError((error) {
printDebug("Failed to initialise firebase $error");
});
}
} else {
// For Android, iOS - Firebase will search for google-services.json in android/app directory or GoogleService-Info.plist in ios/Runner directory respectively.
await Firebase.initializeApp();
}
if(firebaseEnabled) {
FirebaseAnalytics.instance.logEvent(name: "app_started");
}
final app = App(registrationMethod: RegistrationMethod.loadFromEnvironment() ?? RegistrationMethod.env);
return runApp(MaterialApp(home: app));
}
class App extends StatefulWidget {
final RegistrationMethod registrationMethod;
const App({super.key, this.registrationMethod = RegistrationMethod.local});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
String userId = "";
/// Flag showing if TwilioVoice plugin has been initialised
bool twilioInit = false;
/// Flag showing registration status (for registering or re-registering on token change)
var authRegistered = false;
/// Flag showing if incoming call dialog is showing
var showingIncomingCallDialog = false;
//#region #region Register with Twilio
void register() async {
printDebug("voip-service registration");
// Use for locally provided token generator e.g. Twilio's quickstarter project: https://github.com/twilio/voice-quickstart-server-node
if (!kIsWeb) {
bool success = false;
// if not web, we use the requested registration method
switch (widget.registrationMethod) {
case RegistrationMethod.env:
success = await _registerFromEnvironment();
break;
case RegistrationMethod.local:
success = await _registerLocal();
break;
case RegistrationMethod.firebase:
success = await _registerFirebase();
break;
}
if (success) {
setState(() {
twilioInit = true;
});
}
} else {
// for web, we always show the initialisation screen unless we specified an
if (widget.registrationMethod == RegistrationMethod.env) {
bool success = await _registerFromEnvironment();
if (success) {
setState(() {
twilioInit = true;
});
}
}
}
if(firebaseEnabled) {
FirebaseAnalytics.instance.logEvent(name: "registration", parameters: {
"method": widget.registrationMethod.name,
"platform": kIsWeb ? "web" : Platform.isAndroid ? "android" : Platform.isIOS ? "ios" : Platform.isMacOS ? "macos" : "unknown"
});
}
}
/// Registers [accessToken] with TwilioVoice plugin, acquires a device token from FirebaseMessaging and registers with TwilioVoice plugin.
Future<bool> _registerAccessToken(String accessToken) async {
printDebug("voip-registering access token");
String? androidToken;
if(!kIsWeb && Platform.isAndroid) {
// Get device token for Android only
androidToken = await FirebaseMessaging.instance.getToken();
printDebug("androidToken is ${androidToken!}");
}
final result = await TwilioVoice.instance.setTokens(accessToken: accessToken, deviceToken: androidToken);
return result ?? false;
}
//#region #region Register from Environment
/// Use this method to register with a environment variables: RECIPIENT, ID, TOKEN
/// RECIPIENT - the recipient of the call
/// ID - the identity of the caller
/// TOKEN - the access token
///
/// To access this, run with `--dart-define=RECIPIENT=alicesId --dart-define=ID=bobsId --dart-define=TOKEN=ey... --dart-define=REGISTRATION_METHOD=env`
Future<bool> _registerFromEnvironment() async {
// Load config via --dart-define if available
String? myId = const String.fromEnvironment("ID");
String? myToken = const String.fromEnvironment("TOKEN");
if (myId.isEmpty) myId = null;
if (myToken.isEmpty) myToken = null;
printDebug("voip-registering with environment variables");
if (myId == null || myToken == null) {
printDebug("Failed to register with environment variables, please provide ID and TOKEN");
return false;
}
userId = myId;
return _registerAccessToken(myToken);
}
//#endregion
//#region #region Register from Credentials
/// Use this method to register with provided credentials
Future<bool> _registerFromCredentials(String identity, String token) async {
userId = identity;
return _registerAccessToken(token);
}
//#endregion
//#region #region Register with local provider
/// Use this method to register with a local token generator
/// To access this, run with `--dart-define=REGISTRATION_METHOD=local`
Future<bool> _registerLocal() async {
printDebug("voip-registering with local token generator");
final result = await generateLocalAccessToken();
if (result == null) {
printDebug("Failed to register with local token generator");
return false;
}
userId = result.identity;
return _registerAccessToken(result.accessToken);
}
//#endregion
//#region #region Register with Firebase provider
void _listenForFirebaseLogin() {
final auth = FirebaseAuth.instance;
auth.authStateChanges().listen((user) async {
// printDebug("authStateChanges $user");
if (user == null) {
printDebug("user is anonomous");
await auth.signInAnonymously();
} else if (!authRegistered) {
authRegistered = true;
// Note, you can either use Firebase provided [user.uid] or one provided from e.g. localhost:3000/token endpoint returning:
// {token: "ey...", identity: "user123"}
if (userId.isEmpty) {
userId = user.uid;
}
printDebug("registering client $userId [firebase id ${user.uid}]");
_registerFirebase();
}
});
}
/// Use this method to register with a firebase token generator
/// To access this, run with `--dart-define=REGISTRATION_METHOD=firebase`
Future<bool> _registerFirebase() async {
if (!authRegistered) {
_listenForFirebaseLogin();
return false;
}
printDebug("voip-registering with firebase token generator");
final result = await generateFirebaseAccessToken();
if (result == null) {
printDebug("Failed to register with firebase token generator");
return false;
}
userId = result.identity;
return _registerAccessToken(result.accessToken);
}
//#endregion
//#endregion
@override
void initState() {
super.initState();
TwilioVoice.instance.setOnDeviceTokenChanged((token) {
printDebug("voip-device token changed");
if (!kIsWeb) {
register();
}
});
listenForEvents();
register();
const partnerId = "alicesId";
TwilioVoice.instance.registerClient(partnerId, "Alice");
// TwilioVoice.instance.requestReadPhoneStatePermission();
// TwilioVoice.instance.requestMicAccess();
// TwilioVoice.instance.requestCallPhonePermission();
}
/// Listen for call events
void listenForEvents() {
TwilioVoice.instance.callEventsListener.listen((event) {
printDebug("voip-onCallStateChanged $event");
switch (event) {
case CallEvent.incoming:
// applies to web only
if (kIsWeb || Platform.isAndroid) {
final activeCall = TwilioVoice.instance.call.activeCall;
if (activeCall != null && activeCall.callDirection == CallDirection.incoming) {
_showWebIncomingCallDialog();
}
}
break;
case CallEvent.ringing:
final activeCall = TwilioVoice.instance.call.activeCall;
if (activeCall != null) {
final customData = activeCall.customParams;
if (customData != null) {
printDebug("voip-customData $customData");
}
}
break;
case CallEvent.connected:
case CallEvent.callEnded:
case CallEvent.declined:
case CallEvent.answer:
if (kIsWeb || Platform.isAndroid) {
final nav = Navigator.of(context);
if (nav.canPop() && showingIncomingCallDialog) {
nav.pop();
showingIncomingCallDialog = false;
}
}
break;
default:
break;
}
});
}
/// Place a call to [clientIdentifier]
Future<void> _onPerformCall(String clientIdentifier) async {
if (!await (TwilioVoice.instance.hasMicAccess())) {
printDebug("request mic access");
TwilioVoice.instance.requestMicAccess();
return;
}
printDebug("starting call to $clientIdentifier");
TwilioVoice.instance.call.place(to: clientIdentifier, from: userId, extraOptions: {"_TWI_SUBJECT": "Company Name"});
}
Future<void> _onRegisterWithToken(String token, [String? identity]) async {
return _registerFromCredentials(identity ?? "Unknown", token).then((value) {
if (!value) {
showDialog(
context: context,
builder: (context) => const AlertDialog(
title: Text("Error"),
content: Text("Failed to register for calls"),
),
);
} else {
setState(() {
twilioInit = true;
});
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Plugin example app"),
actions: [
_LogoutAction(
onSuccess: () {
setState(() {
twilioInit = false;
});
},
onFailure: (error) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text("Error"),
content: Text("Failed to unregister from calls: $error"),
),
);
},
),
],
),
body: SafeArea(
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: twilioInit
? UICallScreen(
userId: userId,
onPerformCall: _onPerformCall,
)
: UIRegistrationScreen(
onRegister: _onRegisterWithToken,
),
),
),
),
);
}
/// Show incoming call dialog for web and Android
void _showWebIncomingCallDialog() async {
showingIncomingCallDialog = true;
final activeCall = TwilioVoice.instance.call.activeCall!;
final action = await showIncomingCallScreen(context, activeCall);
if (action == true) {
printDebug("accepting call");
TwilioVoice.instance.call.answer();
} else if (action == false) {
printDebug("rejecting call");
TwilioVoice.instance.call.hangUp();
} else {
printDebug("no action");
}
}
Future<bool?> showIncomingCallScreen(BuildContext context, ActiveCall activeCall) async {
if (!kIsWeb && !Platform.isAndroid) {
printDebug("showIncomingCallScreen only for web");
return false;
}
// show accept/reject incoming call screen dialog
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text("Incoming Call"),
content: Text("Incoming call from ${activeCall.from}"),
actions: [
TextButton(
child: const Text("Accept"),
onPressed: () {
Navigator.of(context).pop(true);
},
),
TextButton(
child: const Text("Reject"),
onPressed: () {
Navigator.of(context).pop(false);
},
),
],
);
},
);
}
}
class _LogoutAction extends StatelessWidget {
final void Function()? onSuccess;
final void Function(String error)? onFailure;
const _LogoutAction({Key? key, this.onSuccess, this.onFailure}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton.icon(
onPressed: () async {
final result = await TwilioVoice.instance.unregister();
if (result == true) {
onSuccess?.call();
} else {
onFailure?.call("Failed to unregister");
}
},
label: const Text("Logout", style: TextStyle(color: Colors.white)),
icon: const Icon(Icons.logout, color: Colors.white));
}
}