The RECORD_AUDIO permission was declared in the manifest but never requested at runtime, causing WebRTC to fail on Android 6+. Now requests microphone permission on app startup before initializing the WebView. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
333 lines
10 KiB
Dart
333 lines
10 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:permission_handler/permission_handler.dart';
|
|
import 'package:webview_flutter/webview_flutter.dart';
|
|
import 'package:webview_flutter_android/webview_flutter_android.dart';
|
|
import '../services/push_notification_service.dart';
|
|
|
|
/// Full-screen WebView that loads the TWP phone page.
|
|
///
|
|
/// Handles:
|
|
/// - Microphone permission grants for WebRTC
|
|
/// - JavaScript bridge (TwpMobile channel) for native communication
|
|
/// - Session expiry detection (redirect to wp-login.php)
|
|
/// - Back button confirmation to prevent accidental exit
|
|
/// - Network error retry UI
|
|
class PhoneScreen extends StatefulWidget {
|
|
final String serverUrl;
|
|
final VoidCallback onLogout;
|
|
final VoidCallback onSessionExpired;
|
|
|
|
const PhoneScreen({
|
|
super.key,
|
|
required this.serverUrl,
|
|
required this.onLogout,
|
|
required this.onSessionExpired,
|
|
});
|
|
|
|
@override
|
|
State<PhoneScreen> createState() => _PhoneScreenState();
|
|
}
|
|
|
|
class _PhoneScreenState extends State<PhoneScreen> with WidgetsBindingObserver {
|
|
late final WebViewController _controller;
|
|
late final PushNotificationService _pushService;
|
|
bool _loading = true;
|
|
bool _hasError = false;
|
|
String? _errorMessage;
|
|
bool _sessionExpired = false;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
WidgetsBinding.instance.addObserver(this);
|
|
_pushService = PushNotificationService();
|
|
_requestPermissionsAndInit();
|
|
}
|
|
|
|
Future<void> _requestPermissionsAndInit() async {
|
|
// Request microphone permission before initializing WebView
|
|
final micStatus = await Permission.microphone.request();
|
|
if (micStatus.isDenied || micStatus.isPermanentlyDenied) {
|
|
debugPrint('TWP: Microphone permission denied: $micStatus');
|
|
}
|
|
_initWebView();
|
|
_initPush();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
WidgetsBinding.instance.removeObserver(this);
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> _initPush() async {
|
|
await _pushService.initialize();
|
|
}
|
|
|
|
void _initWebView() {
|
|
_controller = WebViewController()
|
|
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
|
..setUserAgent('TWPMobile/2.0 (Android; WebView)')
|
|
..setNavigationDelegate(
|
|
NavigationDelegate(
|
|
onPageStarted: (url) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_loading = true;
|
|
_hasError = false;
|
|
});
|
|
}
|
|
// Detect session expiry: if we get redirected to wp-login.php
|
|
if (url.contains('/wp-login.php')) {
|
|
_sessionExpired = true;
|
|
}
|
|
},
|
|
onPageFinished: (url) {
|
|
if (mounted) {
|
|
setState(() => _loading = false);
|
|
}
|
|
if (_sessionExpired && url.contains('/wp-login.php')) {
|
|
widget.onSessionExpired();
|
|
return;
|
|
}
|
|
_sessionExpired = false;
|
|
|
|
// Inject the FCM token into the page if available
|
|
_injectFcmToken();
|
|
},
|
|
onWebResourceError: (error) {
|
|
// Only handle main frame errors
|
|
if (error.isForMainFrame ?? true) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_loading = false;
|
|
_hasError = true;
|
|
_errorMessage = error.description;
|
|
});
|
|
}
|
|
}
|
|
},
|
|
onNavigationRequest: (request) {
|
|
// Allow all navigation within our server
|
|
if (request.url.startsWith(widget.serverUrl)) {
|
|
return NavigationDecision.navigate;
|
|
}
|
|
// Allow blob: and data: URLs (for downloads, etc.)
|
|
if (request.url.startsWith('blob:') ||
|
|
request.url.startsWith('data:')) {
|
|
return NavigationDecision.navigate;
|
|
}
|
|
// Block external navigation
|
|
return NavigationDecision.prevent;
|
|
},
|
|
),
|
|
)
|
|
..addJavaScriptChannel(
|
|
'TwpMobile',
|
|
onMessageReceived: _handleJsMessage,
|
|
);
|
|
|
|
// Configure Android-specific settings
|
|
final androidController =
|
|
_controller.platform as AndroidWebViewController;
|
|
// Auto-grant microphone permission for WebRTC calls
|
|
androidController.setOnPlatformPermissionRequest(
|
|
(PlatformWebViewPermissionRequest request) {
|
|
request.grant();
|
|
},
|
|
);
|
|
// Allow media playback without user gesture (for ringtones)
|
|
androidController.setMediaPlaybackRequiresUserGesture(false);
|
|
|
|
// Load the phone page
|
|
final phoneUrl = '${widget.serverUrl}/twp-phone/';
|
|
_controller.loadRequest(Uri.parse(phoneUrl));
|
|
}
|
|
|
|
void _handleJsMessage(JavaScriptMessage message) {
|
|
final msg = message.message;
|
|
|
|
if (msg == 'onSessionExpired') {
|
|
widget.onSessionExpired();
|
|
} else if (msg == 'requestFcmToken') {
|
|
_injectFcmToken();
|
|
} else if (msg == 'onPageReady') {
|
|
// Phone page loaded successfully
|
|
_injectFcmToken();
|
|
}
|
|
}
|
|
|
|
Future<void> _injectFcmToken() async {
|
|
final token = _pushService.fcmToken;
|
|
if (token != null) {
|
|
// Send the FCM token to the web page via the TwpMobile bridge
|
|
await _controller.runJavaScript(
|
|
'if (window.TwpMobile && window.TwpMobile.setFcmToken) { window.TwpMobile.setFcmToken("$token"); }',
|
|
);
|
|
}
|
|
}
|
|
|
|
Future<void> _retry() async {
|
|
setState(() {
|
|
_hasError = false;
|
|
_loading = true;
|
|
});
|
|
final phoneUrl = '${widget.serverUrl}/twp-phone/';
|
|
await _controller.loadRequest(Uri.parse(phoneUrl));
|
|
}
|
|
|
|
Future<bool> _onWillPop() async {
|
|
// Check if WebView can go back
|
|
if (await _controller.canGoBack()) {
|
|
await _controller.goBack();
|
|
return false;
|
|
}
|
|
// Show confirmation dialog
|
|
if (!mounted) return true;
|
|
final result = await showDialog<bool>(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: const Text('Exit'),
|
|
content: const Text('Are you sure you want to exit the phone?'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(false),
|
|
child: const Text('Cancel'),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(true),
|
|
child: const Text('Exit'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
return result ?? false;
|
|
}
|
|
|
|
void _confirmLogout() async {
|
|
final result = await showDialog<bool>(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: const Text('Logout'),
|
|
content: const Text(
|
|
'This will clear your session. You will need to sign in again.'),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(false),
|
|
child: const Text('Cancel'),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(true),
|
|
child: const Text('Logout'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
|
|
if (result == true) {
|
|
// Clear WebView cookies
|
|
await WebViewCookieManager().clearCookies();
|
|
widget.onLogout();
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
// ignore: deprecated_member_use
|
|
return WillPopScope(
|
|
onWillPop: _onWillPop,
|
|
child: Scaffold(
|
|
appBar: _hasError
|
|
? null
|
|
: AppBar(
|
|
toolbarHeight: 40,
|
|
titleSpacing: 12,
|
|
title: Text(
|
|
'TWP Softphone',
|
|
style: Theme.of(context).textTheme.titleSmall,
|
|
),
|
|
actions: [
|
|
IconButton(
|
|
icon: const Icon(Icons.refresh, size: 20),
|
|
tooltip: 'Reload',
|
|
visualDensity: VisualDensity.compact,
|
|
onPressed: () => _controller.reload(),
|
|
),
|
|
PopupMenuButton<String>(
|
|
icon: const Icon(Icons.more_vert, size: 20),
|
|
tooltip: 'Menu',
|
|
padding: EdgeInsets.zero,
|
|
onSelected: (value) {
|
|
if (value == 'logout') _confirmLogout();
|
|
},
|
|
itemBuilder: (context) => [
|
|
const PopupMenuItem(
|
|
value: 'logout',
|
|
child: ListTile(
|
|
leading: Icon(Icons.logout),
|
|
title: Text('Logout'),
|
|
dense: true,
|
|
contentPadding: EdgeInsets.zero,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
body: SafeArea(
|
|
top: _hasError, // AppBar already handles top safe area when visible
|
|
child: Stack(
|
|
children: [
|
|
if (!_hasError) WebViewWidget(controller: _controller),
|
|
if (_hasError) _buildErrorView(),
|
|
if (_loading && !_hasError)
|
|
const Center(child: CircularProgressIndicator()),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildErrorView() {
|
|
final colorScheme = Theme.of(context).colorScheme;
|
|
return Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Icon(Icons.wifi_off, size: 64, color: colorScheme.onSurfaceVariant),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
'Connection Error',
|
|
style: TextStyle(
|
|
fontSize: 20,
|
|
fontWeight: FontWeight.bold,
|
|
color: colorScheme.onSurface,
|
|
),
|
|
),
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
_errorMessage ?? 'Could not load the phone page.',
|
|
textAlign: TextAlign.center,
|
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
|
),
|
|
const SizedBox(height: 24),
|
|
FilledButton.icon(
|
|
onPressed: _retry,
|
|
icon: const Icon(Icons.refresh),
|
|
label: const Text('Retry'),
|
|
),
|
|
const SizedBox(height: 12),
|
|
TextButton(
|
|
onPressed: widget.onLogout,
|
|
child: const Text('Change Server'),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|