forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphone_call_provider.dart
More file actions
822 lines (715 loc) · 27.5 KB
/
Copy pathphone_call_provider.dart
File metadata and controls
822 lines (715 loc) · 27.5 KB
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:omi/utils/platform/platform_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
// hide PermissionStatus: flutter_contacts has its own PermissionStatus enum, and this
// file never spells out permission_handler's version by name (only inferred via `var`).
import 'package:permission_handler/permission_handler.dart' hide PermissionStatus;
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:omi/backend/http/api/phone_calls.dart' as api;
import 'package:omi/backend/http/shared.dart';
import 'package:omi/backend/preferences.dart';
import 'package:omi/backend/schema/phone_call.dart';
import 'package:omi/backend/schema/transcript_segment.dart';
import 'package:omi/models/audio_route.dart';
import 'package:omi/services/auth/auth_token_result.dart';
import 'package:omi/services/phone_call_service.dart';
import 'package:omi/utils/logger.dart';
enum TranscriptionStatus { idle, connecting, active, reconnecting, failed, noAudio }
class PhoneCallProvider extends ChangeNotifier {
final PhoneCallService _nativeService = PhoneCallService();
// Call state
PhoneCallState _callState = PhoneCallState.idle;
PhoneCallState get callState => _callState;
String? _currentCallId;
String? get currentCallId => _currentCallId;
String? _remoteNumber;
String? get remoteNumber => _remoteNumber;
String? _contactName;
String? get contactName => _contactName;
bool _isMuted = false;
bool get isMuted => _isMuted;
bool _isSpeakerOn = false;
bool get isSpeakerOn => _isSpeakerOn;
// Call duration
DateTime? _callStartTime;
Timer? _durationTimer;
Duration _callDuration = Duration.zero;
Duration get callDuration => _callDuration;
// Real-time transcript segments
final List<TranscriptSegment> _transcriptSegments = [];
List<TranscriptSegment> get transcriptSegments => List.unmodifiable(_transcriptSegments);
// Audio routes
List<AudioRoute> _availableRoutes = [];
List<AudioRoute> get availableRoutes => List.unmodifiable(_availableRoutes);
AudioRoute? _selectedRoute;
AudioRoute? get selectedRoute => _selectedRoute;
// Transcription status
TranscriptionStatus _transcriptionStatus = TranscriptionStatus.idle;
TranscriptionStatus get transcriptionStatus => _transcriptionStatus;
// Token refresh
Timer? _tokenRefreshTimer;
// WebSocket for transcription
WebSocketChannel? _transcriptionSocket;
int _wsReconnectAttempts = 0;
Timer? _wsReconnectTimer;
static const int _maxWsReconnectAttempts = 10;
// Audio buffer during WS reconnect (~2s at 20ms per frame)
final List<Uint8List> _audioBuffer = [];
static const int _maxAudioBufferSize = 100;
// Per-call audio session stats (counts only — no audio content) surfaced
// through the `Phone Call Transcript Session` analytics event.
bool _wsAccepted = false;
int _audioFramesSent = 0;
int _audioBytesSent = 0;
int _audioChannel1Frames = 0;
int _audioChannel2Frames = 0;
bool _transcriptStallReported = false;
bool _transcriptSessionReported = false;
DateTime? _wsAcceptedAt;
Timer? _noAudioWatchdog;
/// How long an active call with an accepted transcription socket may stay
/// silent before the UI says so instead of showing the transcript placeholder.
@visibleForTesting
Duration noAudioStallTimeout = const Duration(seconds: 3);
/// Test seams for the transcription socket: header construction and socket
/// creation, so widget tests can drive WS-active without a live backend.
@visibleForTesting
static Future<Map<String, String>> Function(String url)? headerBuilderForTesting;
@visibleForTesting
static WebSocketChannel Function(String url, Map<String, String> headers)? socketFactoryForTesting;
/// Simulates the call-id assignment [startCall] performs, so tests can drive
/// the transcription socket without the Twilio/API flow.
@visibleForTesting
void debugSetCallIdForTesting(String callId) => _currentCallId = callId;
// Verified phone numbers
List<VerifiedPhoneNumber> _verifiedNumbers = [];
List<VerifiedPhoneNumber> get verifiedNumbers => _verifiedNumbers;
// Loading states
bool _isLoading = false;
bool get isLoading => _isLoading;
bool _numbersLoaded = false;
bool get numbersLoaded => _numbersLoaded;
String? _error;
String? get error => _error;
PhoneCallError? _lastError;
PhoneCallError? get lastError => _lastError;
Future<void>? _initialLoad;
Future<void> get initialLoad => _initialLoad ?? Future.value();
int _sessionGeneration = 0;
bool _sessionEnabled = true;
bool _disposed = false;
PhoneCallProvider() {
_wireNativeCallbacks();
_nativeService.startListening();
_initialLoad = loadVerifiedNumbers();
}
/// Same wiring as the default constructor without the constructor-time
/// network fetch, so widget tests drive the socket path hermetically.
@visibleForTesting
PhoneCallProvider.forTesting() {
_wireNativeCallbacks();
_nativeService.startListening();
}
void _wireNativeCallbacks() {
_nativeService.onCallStateChanged = _onCallStateChanged;
_nativeService.onAudioData = _onAudioData;
_nativeService.onError = _onNativeError;
_nativeService.onMuteConfirmed = _onMuteConfirmed;
_nativeService.onSpeakerConfirmed = _onSpeakerConfirmed;
}
// ************************************************
// *********** PHONE NUMBER MANAGEMENT ************
// ************************************************
Future<void> loadVerifiedNumbers() async {
_sessionEnabled = true;
final generation = _sessionGeneration;
try {
final numbers = await api.getVerifiedPhoneNumbers();
if (generation != _sessionGeneration) return;
_verifiedNumbers = numbers;
} catch (e) {
if (generation != _sessionGeneration) return;
print('PhoneCallProvider: failed to load verified numbers: $e');
_verifiedNumbers = [];
} finally {
if (generation == _sessionGeneration) {
_numbersLoaded = true;
notifyListeners();
}
}
}
String? _validationCode;
String? get validationCode => _validationCode;
String? _verificationStatus;
String? get verificationStatus => _verificationStatus;
Future<bool> startVerification(String phoneNumber) async {
final generation = _sessionGeneration;
_isLoading = true;
_error = null;
_validationCode = null;
_verificationStatus = null;
notifyListeners();
PlatformManager.instance.analytics.phoneCallVerificationStarted();
var result = await api.verifyPhoneNumber(phoneNumber);
if (generation != _sessionGeneration) return false;
_isLoading = false;
if (result == null) {
_error = 'Failed to start verification';
notifyListeners();
return false;
}
if (result.containsKey('error')) {
_error = result['error'] as String?;
notifyListeners();
return false;
}
_validationCode = result['validation_code'] as String?;
_verificationStatus = result['status'] as String?;
notifyListeners();
return true;
}
Future<bool> checkVerification(String phoneNumber) async {
final generation = _sessionGeneration;
var result = await api.checkPhoneVerification(phoneNumber);
if (generation != _sessionGeneration) return false;
if (result == null) return false;
bool verified = result['verified'] == true;
if (verified) {
PlatformManager.instance.analytics.phoneCallVerificationCompleted();
await loadVerifiedNumbers();
}
return verified;
}
Future<bool> deleteNumber(String phoneNumberId) async {
final generation = _sessionGeneration;
var success = await api.deleteVerifiedPhoneNumber(phoneNumberId);
if (generation != _sessionGeneration) return false;
if (success) {
_verifiedNumbers.removeWhere((n) => n.id == phoneNumberId);
notifyListeners();
}
return success;
}
// ************************************************
// ************** CALL MANAGEMENT *****************
// ************************************************
Future<bool> startCall(String phoneNumber) async {
_sessionEnabled = true;
final generation = _sessionGeneration;
if (_callState != PhoneCallState.idle) {
_error = 'A call is already in progress';
notifyListeners();
return false;
}
_error = null;
_lastError = null;
_callState = PhoneCallState.connecting;
_remoteNumber = phoneNumber;
final callId = DateTime.now().millisecondsSinceEpoch.toString();
_currentCallId = callId;
_transcriptSegments.clear();
_resetTranscriptSessionStats();
_nativeService.resetEventStats();
_isMuted = false;
_isSpeakerOn = false;
notifyListeners();
// Request mic permission first, before any SDK initialization
var micStatus = await Permission.microphone.request();
if (generation != _sessionGeneration) return false;
if (!micStatus.isGranted) {
_callState = PhoneCallState.idle;
_error = 'Microphone permission is required to make calls';
notifyListeners();
return false;
}
// Resolve contact name from device contacts
_contactName = await _resolveContactName(phoneNumber);
if (generation != _sessionGeneration) return false;
// Get Twilio token
var tokenResult = await api.getPhoneCallToken();
if (generation != _sessionGeneration) return false;
var token = tokenResult.token;
if (token == null) {
_callState = PhoneCallState.idle;
// The backend refuses for several different reasons (no verified number, quota
// exhausted, plan without calling). Reporting its own reason beats guessing one.
_error = tokenResult.error ?? 'Failed to get call token. Please try again.';
notifyListeners();
return false;
}
// Initialize native Twilio SDK
var initialized = await _nativeService.initialize(token.accessToken);
if (generation != _sessionGeneration) return false;
if (!initialized) {
_callState = PhoneCallState.idle;
_error = 'Failed to initialize call service';
notifyListeners();
return false;
}
// Schedule token refresh before expiry (3-minute buffer)
_scheduleTokenRefresh(token.ttl);
// Make the call via native layer
var callStarted = await _nativeService.makeCall(
phoneNumber: phoneNumber,
callId: callId,
contactName: _contactName,
);
if (generation != _sessionGeneration) {
if (callStarted) unawaited(_nativeService.endCall());
return false;
}
if (!callStarted) {
_callState = PhoneCallState.idle;
_error = 'Failed to start call';
PlatformManager.instance.analytics.phoneCallFailed(error: 'Failed to start call');
_disconnectTranscriptionSocket();
notifyListeners();
return false;
}
PlatformManager.instance.analytics.phoneCallStarted(contactName: _contactName);
return true;
}
Future<void> endCall() async {
await _nativeService.endCall();
_onCallEnded();
}
void toggleMute() {
// Don't update state here — wait for native confirmation via _onMuteConfirmed
_nativeService.toggleMute(!_isMuted);
}
void toggleSpeaker() {
// Don't update state here — wait for native confirmation via _onSpeakerConfirmed
_nativeService.toggleSpeaker(!_isSpeakerOn);
}
Future<void> loadAudioRoutes() async {
final generation = _sessionGeneration;
final routes = await _nativeService.getAudioRoutes();
if (generation != _sessionGeneration) return;
_availableRoutes = routes;
notifyListeners();
}
Future<void> selectAudioRoute(AudioRoute route) async {
final generation = _sessionGeneration;
var success = await _nativeService.selectAudioRoute(route.id);
if (generation != _sessionGeneration) return;
if (success) {
_selectedRoute = route;
_isSpeakerOn = route.type == AudioRouteType.speaker;
notifyListeners();
}
}
void sendDtmf(String digit) {
if (_callState == PhoneCallState.active) {
_nativeService.sendDtmf(digit);
}
}
// ************************************************
// ************* SPEAKER LABELS *******************
// ************************************************
String getSpeakerLabel(TranscriptSegment segment) {
if (segment.isUser) return 'You';
return _contactName ?? _remoteNumber ?? 'Unknown';
}
// ************************************************
// *********** PRIVATE HELPERS ********************
// ************************************************
void _onCallStateChanged(PhoneCallState state) {
if (!_sessionEnabled) return;
_callState = state;
if (state == PhoneCallState.active && _callStartTime == null) {
_callStartTime = DateTime.now();
_startDurationTimer();
_connectTranscriptionSocket();
PlatformManager.instance.analytics.phoneCallConnected();
} else if (state == PhoneCallState.ended || state == PhoneCallState.failed) {
_onCallEnded();
}
notifyListeners();
}
void _onAudioData(Uint8List audioData, int channel) {
if (!_sessionEnabled) return;
// Start-of-call-only watchdog: it detects zero prefixed frames after the
// socket was accepted and is permanently disarmed by the first delivered
// frame. Mid-call interruptions are intentionally not flagged here —
// they surface through the socket reconnect path instead.
_noAudioWatchdog?.cancel();
_noAudioWatchdog = null;
var socket = _transcriptionSocket;
// Buffer audio during WebSocket reconnect
if (socket == null) {
if (_audioBuffer.length < _maxAudioBufferSize) {
var data = Uint8List(1 + audioData.length);
data[0] = channel;
data.setRange(1, data.length, audioData);
_audioBuffer.add(data);
}
return;
}
try {
// Flush buffered audio first; buffered frames count the same as live
// ones so session telemetry matches bytes actually on the socket.
if (_audioBuffer.isNotEmpty) {
for (var buffered in _audioBuffer) {
socket.sink.add(buffered);
_countFrameSent(buffered);
}
_audioBuffer.clear();
}
var data = Uint8List(1 + audioData.length);
data[0] = channel; // 0x01 = user, 0x02 = remote
data.setRange(1, data.length, audioData);
socket.sink.add(data);
_countFrameSent(data);
if (_transcriptionStatus == TranscriptionStatus.noAudio) {
// Frames are flowing again; leave the stall state instead of parking
// the chip on a condition that no longer holds.
_transcriptionStatus = TranscriptionStatus.active;
notifyListeners();
}
} catch (e) {
Logger.error('PhoneCallProvider: failed to send audio data: $e');
}
}
void _countFrameSent(Uint8List prefixedFrame) {
_audioFramesSent++;
_audioBytesSent += prefixedFrame.length;
if (prefixedFrame[0] == 1) {
_audioChannel1Frames++;
} else if (prefixedFrame[0] == 2) {
_audioChannel2Frames++;
}
}
/// Arm the no-audio watchdog only once the server has accepted the socket
/// (`_wsAccepted`): a still-connecting socket must not read as no-audio.
/// Start-of-call-only: the first delivered frame cancels this timer for the
/// rest of the call (see `_onAudioData`); it is not re-armed per frame.
void _armNoAudioWatchdog() {
_noAudioWatchdog?.cancel();
_noAudioWatchdog = Timer(noAudioStallTimeout, () {
if (_callState != PhoneCallState.active || !_sessionEnabled) return;
if (!_wsAccepted) return;
if (_transcriptionSocket == null) return; // reconnecting/failed own their status
if (_audioFramesSent > 0) return;
_transcriptionStatus = TranscriptionStatus.noAudio;
notifyListeners();
if (!_transcriptStallReported) {
_transcriptStallReported = true;
_reportTranscriptSession(reason: 'no_audio_stall');
}
});
}
/// One `Phone Call Transcript Session` per call: `_onCallEnded` can fire twice
/// (native ended event plus `endCall()`), and a stalled call already reported.
void _reportTranscriptSession({String? reason}) {
if (_transcriptSessionReported) return;
_transcriptSessionReported = true;
PlatformManager.instance.analytics.phoneCallTranscriptSession(
wsAccepted: _wsAccepted,
audioFramesSent: _audioFramesSent,
audioBytesSent: _audioBytesSent,
audioChannel1Frames: _audioChannel1Frames,
audioChannel2Frames: _audioChannel2Frames,
eventChannelErrors: _nativeService.eventChannelErrors,
eventChannelCoerced: _nativeService.eventChannelCoerced,
transcriptionStatusFinal: _transcriptionStatus.name,
durationSeconds: _callDuration.inSeconds,
reason: reason,
);
}
void _onCallEnded() {
_noAudioWatchdog?.cancel();
_noAudioWatchdog = null;
_reportTranscriptSession();
PlatformManager.instance.analytics.phoneCallEnded(durationSeconds: _callDuration.inSeconds);
_callState = PhoneCallState.ended;
_stopDurationTimer();
_disconnectTranscriptionSocket();
_tokenRefreshTimer?.cancel();
_tokenRefreshTimer = null;
_transcriptionStatus = TranscriptionStatus.idle;
_audioBuffer.clear();
notifyListeners();
// Reset state after a short delay so UI can show "Call Ended"
Future.delayed(const Duration(seconds: 2), () {
if (_disposed) return;
_callState = PhoneCallState.idle;
_currentCallId = null;
_remoteNumber = null;
_contactName = null;
_callStartTime = null;
_callDuration = Duration.zero;
_transcriptSegments.clear();
_availableRoutes = [];
_selectedRoute = null;
notifyListeners();
});
}
void _onNativeError(PhoneCallError error) {
_lastError = error;
_error = error.message;
Logger.error('PhoneCallProvider: native error: ${error.code} - ${error.message}');
notifyListeners();
}
void _onMuteConfirmed(bool muted) {
_isMuted = muted;
notifyListeners();
}
void _onSpeakerConfirmed(bool speakerOn) {
_isSpeakerOn = speakerOn;
notifyListeners();
}
void _scheduleTokenRefresh(int ttlSeconds) {
_tokenRefreshTimer?.cancel();
final generation = _sessionGeneration;
// Refresh 3 minutes before expiry (or half TTL if TTL < 6 min)
var refreshInSeconds = ttlSeconds > 360 ? ttlSeconds - 180 : ttlSeconds ~/ 2;
if (refreshInSeconds <= 0) return;
Logger.info('PhoneCallProvider: scheduling token refresh in ${refreshInSeconds}s');
_tokenRefreshTimer = Timer(Duration(seconds: refreshInSeconds), () async {
if (generation != _sessionGeneration || !_sessionEnabled) return;
if (_callState != PhoneCallState.active && _callState != PhoneCallState.ringing) return;
Logger.info('PhoneCallProvider: refreshing call token');
var token = (await api.getPhoneCallToken()).token;
if (generation != _sessionGeneration || !_sessionEnabled) return;
if (token != null) {
await _nativeService.initialize(token.accessToken);
if (generation != _sessionGeneration || !_sessionEnabled) return;
_scheduleTokenRefresh(token.ttl);
} else {
Logger.error('PhoneCallProvider: token refresh failed, retrying in 30s');
_scheduleTokenRefresh(60);
}
});
}
void _startDurationTimer() {
_durationTimer?.cancel();
_durationTimer = Timer.periodic(const Duration(seconds: 1), (_) {
if (_callStartTime != null) {
_callDuration = DateTime.now().difference(_callStartTime!);
notifyListeners();
}
});
}
void _stopDurationTimer() {
_durationTimer?.cancel();
_durationTimer = null;
}
// ************************************************
// *********** TRANSCRIPTION SOCKET ***************
// ************************************************
Future<void> _connectTranscriptionSocket() async {
if (_currentCallId == null || !_sessionEnabled) return;
final generation = _sessionGeneration;
_wsReconnectTimer?.cancel();
_wsReconnectTimer = null;
_transcriptionStatus = TranscriptionStatus.connecting;
notifyListeners();
var language =
SharedPreferencesUtil().hasSetPrimaryLanguage ? SharedPreferencesUtil().userPrimaryLanguage : 'multi';
var wsUrl = api.buildPhoneCallWebSocketUrl(
callId: _currentCallId!,
uid: SharedPreferencesUtil().uid,
language: language,
);
Logger.info('PhoneCallProvider: connecting to $wsUrl');
try {
var headerBuilder = headerBuilderForTesting ?? _productionHeaderBuilder;
var headers = await headerBuilder(wsUrl);
if (generation != _sessionGeneration || !_sessionEnabled) return;
var socketFactory = socketFactoryForTesting ?? _productionSocketFactory;
_transcriptionSocket = socketFactory(wsUrl, headers);
_transcriptionSocket!.stream.listen(
(message) {
if (generation != _sessionGeneration || !_sessionEnabled) return;
if (_transcriptionStatus != TranscriptionStatus.active) {
_transcriptionStatus = TranscriptionStatus.active;
_wsAccepted = true;
_wsAcceptedAt ??= DateTime.now();
notifyListeners();
_armNoAudioWatchdog();
}
if (message is String) {
_handleTranscriptionMessage(message);
}
},
onError: (error) {
if (generation != _sessionGeneration || !_sessionEnabled) return;
Logger.error('PhoneCallProvider: WebSocket error: $error');
_transcriptionSocket = null;
_scheduleReconnect();
},
onDone: () {
if (generation != _sessionGeneration || !_sessionEnabled) return;
Logger.info('PhoneCallProvider: WebSocket closed');
_transcriptionSocket = null;
_scheduleReconnect();
},
);
_wsReconnectAttempts = 0;
} on AuthTokenUnavailableException catch (e) {
Logger.debug('PhoneCallProvider: authenticated WebSocket blocked before connect: ${e.result.runtimeType}');
_transcriptionSocket = null;
if (e.result is AuthTokenTransientFailure) {
_scheduleReconnect();
} else {
_transcriptionStatus = TranscriptionStatus.failed;
notifyListeners();
}
} catch (e) {
Logger.error('PhoneCallProvider: failed to connect WebSocket: $e');
_transcriptionSocket = null;
_scheduleReconnect();
}
}
Future<Map<String, String>> _productionHeaderBuilder(String url) =>
buildHeaders(requireAuthCheck: true, url: url, forWebSocket: true);
WebSocketChannel _productionSocketFactory(String url, Map<String, String> headers) => IOWebSocketChannel.connect(
url,
headers: headers,
pingInterval: const Duration(seconds: 20),
);
void _resetTranscriptSessionStats() {
_wsAccepted = false;
_audioFramesSent = 0;
_audioBytesSent = 0;
_audioChannel1Frames = 0;
_audioChannel2Frames = 0;
_transcriptStallReported = false;
_transcriptSessionReported = false;
_wsAcceptedAt = null;
_noAudioWatchdog?.cancel();
_noAudioWatchdog = null;
}
void _scheduleReconnect() {
if (_callState != PhoneCallState.active || !_sessionEnabled) return;
if (_wsReconnectAttempts >= _maxWsReconnectAttempts) {
Logger.error('PhoneCallProvider: max reconnect attempts reached, giving up');
_transcriptionStatus = TranscriptionStatus.failed;
notifyListeners();
return;
}
_transcriptionStatus = TranscriptionStatus.reconnecting;
notifyListeners();
var delay = Duration(seconds: 1 << _wsReconnectAttempts); // 1s, 2s, 4s, 8s...
_wsReconnectAttempts++;
Logger.info('PhoneCallProvider: reconnecting WebSocket in ${delay.inSeconds}s (attempt $_wsReconnectAttempts)');
_wsReconnectTimer = Timer(delay, () {
if (_callState == PhoneCallState.active) {
_connectTranscriptionSocket();
}
});
}
void _disconnectTranscriptionSocket() {
_noAudioWatchdog?.cancel();
_noAudioWatchdog = null;
_wsReconnectTimer?.cancel();
_wsReconnectTimer = null;
_wsReconnectAttempts = 0;
_transcriptionSocket?.sink.close();
_transcriptionSocket = null;
}
void _handleTranscriptionMessage(String message) {
if (message == 'ping') return;
try {
var data = jsonDecode(message);
// Standard segment array format: [{id, text, is_user, speaker, start, end, ...}, ...]
if (data is List) {
for (var segmentJson in data) {
var segment = TranscriptSegment.fromJson(segmentJson as Map<String, dynamic>);
var existingIndex = _transcriptSegments.indexWhere((s) => s.id == segment.id);
if (existingIndex >= 0) {
_transcriptSegments[existingIndex] = segment;
} else {
_transcriptSegments.add(segment);
}
}
if (data.isNotEmpty) notifyListeners();
return;
}
// Handle translation events
if (data is Map && data['type'] == 'translating') {
var segments = data['segments'] as List<dynamic>? ?? [];
for (var segmentJson in segments) {
var translated = TranscriptSegment.fromJson(segmentJson as Map<String, dynamic>);
var existingIndex = _transcriptSegments.indexWhere((s) => s.id == translated.id);
if (existingIndex >= 0) {
_transcriptSegments[existingIndex].translations = translated.translations;
}
}
if (segments.isNotEmpty) notifyListeners();
return;
}
} catch (e) {
Logger.error('PhoneCallProvider: failed to parse transcript message: $e');
}
}
// ************************************************
// *********** CONTACT RESOLUTION *****************
// ************************************************
Future<String?> _resolveContactName(String phoneNumber) async {
try {
final status = await FlutterContacts.permissions.request(PermissionType.read);
if (status != PermissionStatus.granted && status != PermissionStatus.limited) return null;
var contacts = await FlutterContacts.getAll(properties: {ContactProperty.phone});
var cleaned = _cleanPhoneNumber(phoneNumber);
for (var contact in contacts) {
for (var phone in contact.phones) {
if (_cleanPhoneNumber(phone.number) == cleaned) {
return contact.displayName;
}
}
}
} catch (e) {
Logger.error('PhoneCallProvider: contact resolution failed: $e');
}
return null;
}
String _cleanPhoneNumber(String number) {
return number.replaceAll(RegExp(r'[\s\-\(\)]'), '');
}
@override
void dispose() {
_disposed = true;
_noAudioWatchdog?.cancel();
_noAudioWatchdog = null;
_stopDurationTimer();
_disconnectTranscriptionSocket();
_tokenRefreshTimer?.cancel();
_nativeService.dispose();
super.dispose();
}
void clearUserData() {
_sessionGeneration++;
_sessionEnabled = false;
if (_callState != PhoneCallState.idle) unawaited(_nativeService.endCall());
_stopDurationTimer();
_disconnectTranscriptionSocket();
_tokenRefreshTimer?.cancel();
_tokenRefreshTimer = null;
_callState = PhoneCallState.idle;
_currentCallId = null;
_audioBuffer.clear();
_resetTranscriptSessionStats();
_nativeService.resetEventStats();
_contactName = null;
_callStartTime = null;
_callDuration = Duration.zero;
_transcriptSegments.clear();
_availableRoutes = [];
_selectedRoute = null;
_audioBuffer.clear();
_verifiedNumbers = [];
_numbersLoaded = false;
_validationCode = null;
_verificationStatus = null;
_transcriptionStatus = TranscriptionStatus.idle;
_isLoading = false;
_error = null;
_lastError = null;
notifyListeners();
}
}