Files
twilio-wp-plugin/mobile/lib/services/voice_service.dart
Claude 4af4be94a4
All checks were successful
Create Release / build (push) Successful in 6s
Add FCM push notifications, queue alerts, caller ID fixes, and auto-revert agent status
Server-side:
- Add push credential auto-creation for FCM incoming call notifications
- Add queue alert FCM notifications (data-only for background delivery)
- Add queue alert cancellation on call accept/disconnect
- Fix caller ID to show caller's number instead of Twilio number
- Fix FCM token storage when refresh_token is null
- Add pre_call_status tracking to revert agent status 30s after call ends
- Add SSE fallback polling for mobile app connectivity

Mobile app:
- Add Android telecom permissions and phone account registration
- Add VoiceFirebaseMessagingService for incoming call push handling
- Add insistent queue alert notifications with custom sound
- Fix caller number display on active call screen
- Add caller ID selection dropdown on dashboard
- Add phone numbers endpoint and provider support
- Add unit tests for CallInfo, QueueState, and CallProvider
- Remove local.properties from tracking, add .gitignore

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 17:11:02 -08:00

147 lines
4.5 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:twilio_voice/twilio_voice.dart';
import 'api_client.dart';
class VoiceService {
final ApiClient _api;
Timer? _tokenRefreshTimer;
String? _identity;
String? _deviceToken;
StreamSubscription? _eventSubscription;
final StreamController<CallEvent> _callEventController =
StreamController<CallEvent>.broadcast();
Stream<CallEvent> get callEvents => _callEventController.stream;
VoiceService(this._api);
Future<void> initialize({String? deviceToken}) async {
_deviceToken = deviceToken;
debugPrint('VoiceService.initialize: deviceToken=${deviceToken != null ? "present (${deviceToken.length} chars)" : "NULL"}');
// Request permissions (Android telecom requires these)
await TwilioVoice.instance.requestMicAccess();
if (!kIsWeb && Platform.isAndroid) {
await TwilioVoice.instance.requestReadPhoneStatePermission();
await TwilioVoice.instance.requestReadPhoneNumbersPermission();
await TwilioVoice.instance.requestCallPhonePermission();
await TwilioVoice.instance.requestManageOwnCallsPermission();
// Register phone account with Android telecom
// (enabling is handled by dashboard UI with a user-friendly dialog)
await TwilioVoice.instance.registerPhoneAccount();
}
// Fetch token and register
await _fetchAndRegisterToken();
// Listen for call events (only once)
_eventSubscription ??= TwilioVoice.instance.callEventsListener.listen((event) {
if (!_callEventController.isClosed) {
_callEventController.add(event);
}
});
// Refresh token every 50 minutes
_tokenRefreshTimer?.cancel();
_tokenRefreshTimer = Timer.periodic(
const Duration(minutes: 50),
(_) => _fetchAndRegisterToken(),
);
}
Future<void> _fetchAndRegisterToken() async {
try {
final response = await _api.dio.get('/voice/token');
final data = response.data;
final token = data['token'] as String;
_identity = data['identity'] as String;
await TwilioVoice.instance.setTokens(
accessToken: token,
deviceToken: _deviceToken ?? 'no-fcm',
);
} catch (e) {
debugPrint('VoiceService._fetchAndRegisterToken error: $e');
if (e is DioException) debugPrint(' response: ${e.response?.data}');
}
}
String? get identity => _identity;
Future<void> answer() async {
await TwilioVoice.instance.call.answer();
}
Future<void> reject() async {
await TwilioVoice.instance.call.hangUp();
}
Future<void> hangUp() async {
await TwilioVoice.instance.call.hangUp();
}
Future<void> toggleMute(bool mute) async {
await TwilioVoice.instance.call.toggleMute(mute);
}
Future<void> toggleSpeaker(bool speaker) async {
await TwilioVoice.instance.call.toggleSpeaker(speaker);
}
Future<bool> makeCall(String to, {String? callerId}) async {
try {
final extraOptions = <String, dynamic>{};
if (callerId != null && callerId.isNotEmpty) {
extraOptions['CallerId'] = callerId;
}
debugPrint('VoiceService.makeCall: to=$to, from=$_identity, extras=$extraOptions');
final result = await TwilioVoice.instance.call.place(
to: to,
from: _identity ?? '',
extraOptions: extraOptions,
) ?? false;
debugPrint('VoiceService.makeCall: result=$result');
return result;
} catch (e) {
debugPrint('VoiceService.makeCall error: $e');
return false;
}
}
Future<void> sendDigits(String digits) async {
await TwilioVoice.instance.call.sendDigits(digits);
}
Future<List<Map<String, dynamic>>> getQueueCalls(int queueId) async {
final response = await _api.dio.get('/queues/$queueId/calls');
return List<Map<String, dynamic>>.from(response.data['calls'] ?? []);
}
Future<void> acceptQueueCall(String callSid) async {
await _api.dio.post('/calls/$callSid/accept', data: {
'client_identity': _identity,
});
}
Future<void> holdCall(String callSid) async {
await _api.dio.post('/calls/$callSid/hold');
}
Future<void> unholdCall(String callSid) async {
await _api.dio.post('/calls/$callSid/unhold');
}
Future<void> transferCall(String callSid, String target) async {
await _api.dio.post('/calls/$callSid/transfer', data: {'target': target});
}
void dispose() {
_tokenRefreshTimer?.cancel();
_eventSubscription?.cancel();
_eventSubscription = null;
_callEventController.close();
}
}