mirror of
https://github.com/jonasbark/swiftcontrol.git
synced 2026-12-02 18:19:21 +01:00
405 lines
15 KiB
Dart
405 lines
15 KiB
Dart
import 'dart:async';
|
||
import 'dart:io';
|
||
import 'dart:isolate';
|
||
import 'dart:ui';
|
||
|
||
import 'package:bike_control/gen/l10n.dart';
|
||
import 'package:bike_control/main.dart' show ConnectionType, recordError;
|
||
import 'package:bike_control/services/overlay/trainer_overlay_service.dart';
|
||
import 'package:bike_control/utils/core.dart';
|
||
import 'package:bike_control/utils/host_platform.dart';
|
||
import 'package:bike_control/utils/requirements/platform.dart';
|
||
import 'package:bike_control/widgets/accessibility_disclosure_dialog.dart';
|
||
import 'package:bike_control/widgets/ui/toast.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:bike_control/pages/rides/ride_details_page.dart' show openRideFromNotification;
|
||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||
import 'package:permission_handler/permission_handler.dart';
|
||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||
import 'package:universal_ble/universal_ble.dart';
|
||
import 'package:url_launcher/url_launcher_string.dart';
|
||
|
||
class AccessibilityRequirement extends PlatformRequirement {
|
||
AccessibilityRequirement()
|
||
: super(
|
||
AppLocalizations.current.allowAccessibilityService,
|
||
description: AppLocalizations.current.accessibilityDescription,
|
||
icon: LucideIcons.personStanding,
|
||
);
|
||
|
||
@override
|
||
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
|
||
// Android only, for any target: with the trainer app on another device the
|
||
// service still takes the keys of HID remotes, keyboards and gamepads.
|
||
if (!HostPlatform.isAndroid) return;
|
||
await _showDisclosureDialog(context, onUpdate);
|
||
await getStatus();
|
||
}
|
||
|
||
@override
|
||
Future<bool> getStatus() async {
|
||
// The service is the same for every target, so this never depends on the
|
||
// action handler (a RemoteActions with the trainer app on another device).
|
||
if (!HostPlatform.isAndroid) {
|
||
status = false;
|
||
return status;
|
||
}
|
||
try {
|
||
status = await core.androidHidKeys.accessibility.hasPermission();
|
||
} on PlatformException catch (e, s) {
|
||
// Unknown counts as not granted: the rider is offered it again.
|
||
recordError(e, s, context: 'AccessibilityRequirement.getStatus');
|
||
status = false;
|
||
}
|
||
return status;
|
||
}
|
||
|
||
Future<void> _showDisclosureDialog(BuildContext context, VoidCallback onUpdate) async {
|
||
return showDialog<void>(
|
||
context: context,
|
||
barrierDismissible: false, // Prevent dismissing by tapping outside
|
||
builder: (BuildContext context) {
|
||
return AccessibilityDisclosureDialog(
|
||
// Not "This device": no touch control, the service only takes keys.
|
||
keysOnly: core.settings.getLastTarget()?.connectionType != ConnectionType.local,
|
||
onAccept: () {
|
||
Navigator.of(context).pop();
|
||
// Open accessibility settings after user consents
|
||
unawaited(() async {
|
||
try {
|
||
await core.androidHidKeys.accessibility.openPermissions();
|
||
await getStatus();
|
||
await core.androidHidKeys.refreshAccessibilityEnabled();
|
||
} catch (e, s) {
|
||
recordError(e, s, context: 'AccessibilityRequirement.openPermissions');
|
||
}
|
||
onUpdate();
|
||
}());
|
||
},
|
||
onDeny: () async {
|
||
await getStatus();
|
||
Navigator.of(context).pop();
|
||
// User denied, no action taken
|
||
},
|
||
);
|
||
},
|
||
);
|
||
}
|
||
}
|
||
|
||
class BluetoothScanRequirement extends PlatformRequirement {
|
||
BluetoothScanRequirement() : super(AppLocalizations.current.allowBluetoothScan, icon: LucideIcons.bluetoothSearching);
|
||
|
||
@override
|
||
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
|
||
await Permission.bluetoothScan.request();
|
||
await getStatus();
|
||
}
|
||
|
||
@override
|
||
Future<bool> getStatus() async {
|
||
final state = await Permission.bluetoothScan.status;
|
||
status = state.isGranted || state.isLimited;
|
||
return status;
|
||
}
|
||
}
|
||
|
||
class LocationRequirement extends PlatformRequirement {
|
||
LocationRequirement() : super(AppLocalizations.current.allowLocationForBluetooth, icon: LucideIcons.mapPin);
|
||
|
||
@override
|
||
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
|
||
await Permission.locationWhenInUse.request();
|
||
await getStatus();
|
||
}
|
||
|
||
@override
|
||
Future<bool> getStatus() async {
|
||
final state = await Permission.locationWhenInUse.status;
|
||
status = state.isGranted || state.isLimited;
|
||
return status;
|
||
}
|
||
}
|
||
|
||
class BluetoothConnectRequirement extends PlatformRequirement {
|
||
BluetoothConnectRequirement()
|
||
: super(AppLocalizations.current.allowBluetoothConnections, icon: LucideIcons.bluetoothConnected);
|
||
|
||
@override
|
||
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
|
||
await Permission.bluetoothConnect.request();
|
||
await getStatus();
|
||
}
|
||
|
||
@override
|
||
Future<bool> getStatus() async {
|
||
final state = await Permission.bluetoothConnect.status;
|
||
status = state.isGranted || state.isLimited;
|
||
return status;
|
||
}
|
||
}
|
||
|
||
ReceivePort? _receivePort;
|
||
StreamSubscription? _sub;
|
||
|
||
class NotificationRequirement extends PlatformRequirement {
|
||
NotificationRequirement()
|
||
: super(
|
||
AppLocalizations.current.allowPersistentNotification,
|
||
description: AppLocalizations.current.notificationDescription,
|
||
icon: LucideIcons.bellRing,
|
||
);
|
||
@override
|
||
Future<void> call(BuildContext context, VoidCallback onUpdate) async {
|
||
if (Platform.isAndroid) {
|
||
final result = await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
|
||
?.requestNotificationsPermission();
|
||
if (result == false) {
|
||
buildToast(
|
||
title: AppLocalizations.current.enableNotificationsAndroid,
|
||
);
|
||
}
|
||
} else if (Platform.isIOS) {
|
||
final result = await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
|
||
?.requestPermissions(
|
||
alert: true,
|
||
badge: false,
|
||
sound: false,
|
||
);
|
||
core.settings.setHasAskedPermissions(true);
|
||
if (result == false) {
|
||
buildToast(
|
||
title: AppLocalizations.current.enableNotificationsApple,
|
||
);
|
||
launchUrlString('x-apple.systempreferences:com.apple.preference.notifications');
|
||
}
|
||
} else if (Platform.isMacOS) {
|
||
final result = await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
|
||
?.requestPermissions(
|
||
alert: true,
|
||
badge: false,
|
||
sound: false,
|
||
);
|
||
core.settings.setHasAskedPermissions(true);
|
||
if (result == false) {
|
||
buildToast(
|
||
title: AppLocalizations.current.enableNotificationsApple,
|
||
);
|
||
launchUrlString('x-apple.systempreferences:com.apple.preference.notifications');
|
||
}
|
||
}
|
||
await getStatus();
|
||
return;
|
||
}
|
||
|
||
@override
|
||
Future<bool> getStatus() async {
|
||
if (Platform.isAndroid) {
|
||
final bool granted =
|
||
await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
|
||
?.areNotificationsEnabled() ??
|
||
false;
|
||
status = granted;
|
||
} else if (Platform.isIOS) {
|
||
final permissions = await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
|
||
?.checkPermissions();
|
||
status = permissions?.isEnabled == true || core.settings.hasAskedPermissions();
|
||
} else if (Platform.isMacOS) {
|
||
final permissions = await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()
|
||
?.checkPermissions();
|
||
status = permissions?.isEnabled == true || core.settings.hasAskedPermissions();
|
||
} else {
|
||
status = true;
|
||
}
|
||
return status;
|
||
}
|
||
|
||
static Future<void> setup() async {
|
||
print('NOTIFICATION SETUP');
|
||
// macOS has no background-isolate support for notification responses, and
|
||
// registering that callback there is the prime suspect for the startup
|
||
// hang some macOS users hit — so only wire the background handler off
|
||
// macOS. Foreground responses still route through the same handler.
|
||
await core.flutterLocalNotificationsPlugin.initialize(
|
||
settings: InitializationSettings(
|
||
android: AndroidInitializationSettings(
|
||
'@drawable/ic_notification',
|
||
),
|
||
iOS: DarwinInitializationSettings(
|
||
requestAlertPermission: false,
|
||
requestBadgePermission: false,
|
||
requestSoundPermission: false,
|
||
),
|
||
macOS: DarwinInitializationSettings(
|
||
requestAlertPermission: false,
|
||
),
|
||
windows: WindowsInitializationSettings(
|
||
appName: 'BikeControl',
|
||
appUserModelId: 'OpenBikeControl.BikeControl',
|
||
guid: '00000012-0000-1000-8000-00805f9b34fb',
|
||
),
|
||
linux: LinuxInitializationSettings(
|
||
defaultActionName: 'Open BikeControl',
|
||
),
|
||
),
|
||
onDidReceiveBackgroundNotificationResponse: Platform.isMacOS ? null : notificationTapBackground,
|
||
onDidReceiveNotificationResponse: (n) {
|
||
notificationTapBackground(n);
|
||
// A ride's push opens that ride's Details.
|
||
if (n.actionId == null) unawaited(openRideFromNotification(n.payload));
|
||
},
|
||
);
|
||
// The app was started by tapping a ride's push: open it once the first
|
||
// screen stands.
|
||
// Not implemented on Linux, where a notification can't launch the app.
|
||
final launch = Platform.isLinux
|
||
? null
|
||
: await core.flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
|
||
final payload = launch?.didNotificationLaunchApp == true ? launch?.notificationResponse?.payload : null;
|
||
if (payload != null) {
|
||
WidgetsBinding.instance.addPostFrameCallback((_) => unawaited(openRideFromNotification(payload)));
|
||
}
|
||
}
|
||
|
||
/// Closes every connection, drops the keep-alive foreground service and its
|
||
/// notification, then leaves the app. Popping alone only finishes the
|
||
/// activity — the service would keep the process and notification alive.
|
||
static Future<void> closeAndQuit() async {
|
||
UniversalBle.onAvailabilityChange = null;
|
||
// A disconnect that hangs or throws must not keep the app and its
|
||
// notification alive: each step gets a deadline, and quitting goes on.
|
||
//
|
||
// The gear overlay first: it runs in a service of its own and outlived
|
||
// the notification's "Close", floating over other apps with nothing
|
||
// behind it. Only closed, not switched off — it comes back on the next
|
||
// ride, as after swiping the app away.
|
||
await _quitStep('hide overlay', () => TrainerOverlayService.forCurrentPlatform().hide());
|
||
await _quitStep('disconnect all', core.connection.disconnectAll);
|
||
await _quitStep('action cleanup', () async => core.actionHandler.cleanup());
|
||
await _quitStep('stop connection', core.connection.stop);
|
||
if (Platform.isAndroid) {
|
||
final android = AndroidFlutterLocalNotificationsPlugin();
|
||
await _quitStep('stop foreground service', android.stopForegroundService);
|
||
await _quitStep('cancel notifications', android.cancelAll);
|
||
}
|
||
await leaveApp();
|
||
}
|
||
|
||
/// Stands in for dart:io's [exit] so a test can see the iOS quit without
|
||
/// ending the test run.
|
||
@visibleForTesting
|
||
static void Function(int code) exitProcess = exit;
|
||
|
||
/// The last step of [closeAndQuit]. Flutter ignores SystemNavigator.pop()
|
||
/// on iOS, so the row there tore everything down and then left the app
|
||
/// open; the rider explicitly asked to quit, so end the process.
|
||
@visibleForTesting
|
||
static Future<void> leaveApp() async {
|
||
if (HostPlatform.isIOS) {
|
||
exitProcess(0);
|
||
return;
|
||
}
|
||
await SystemNavigator.pop();
|
||
}
|
||
|
||
static Future<void> _quitStep(String name, Future<void> Function() step) async {
|
||
try {
|
||
await step().timeout(_quitStepTimeout);
|
||
} catch (e, s) {
|
||
unawaited(recordError(e, s, context: 'close and quit: $name'));
|
||
}
|
||
}
|
||
|
||
static const _quitStepTimeout = Duration(seconds: 3);
|
||
|
||
static Future<void> addPersistentNotification() async {
|
||
const String channelGroupId = 'BikeControl';
|
||
// create the group first
|
||
await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
|
||
.createNotificationChannelGroup(
|
||
AndroidNotificationChannelGroup(channelGroupId, channelGroupId, description: 'Keep Alive'),
|
||
);
|
||
|
||
// create channels associated with the group
|
||
await core.flutterLocalNotificationsPlugin
|
||
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
|
||
.createNotificationChannel(
|
||
const AndroidNotificationChannel(
|
||
channelGroupId,
|
||
channelGroupId,
|
||
description: 'Keep Alive',
|
||
groupId: channelGroupId,
|
||
),
|
||
);
|
||
|
||
await AndroidFlutterLocalNotificationsPlugin().startForegroundService(
|
||
id: 1,
|
||
title: channelGroupId,
|
||
body: AppLocalizations.current.allowsRunningInBackground,
|
||
foregroundServiceTypes: {AndroidServiceForegroundType.foregroundServiceTypeConnectedDevice},
|
||
// Not sticky: when Android kills the process, a redelivered intent restarts
|
||
// the service in the background, where startForeground is refused
|
||
// (ForegroundServiceStartNotAllowedException) and the app crashes. A restarted
|
||
// service has no engine or BLE connections anyway.
|
||
startType: AndroidServiceStartType.startNotSticky,
|
||
notificationDetails: AndroidNotificationDetails(
|
||
channelGroupId,
|
||
'Keep Alive',
|
||
actions: [
|
||
AndroidNotificationAction(
|
||
'disconnect',
|
||
AppLocalizations.current.disconnectDevices,
|
||
cancelNotification: true,
|
||
showsUserInterface: false,
|
||
),
|
||
AndroidNotificationAction(
|
||
'close',
|
||
AppLocalizations.current.close,
|
||
cancelNotification: true,
|
||
showsUserInterface: false,
|
||
),
|
||
],
|
||
),
|
||
);
|
||
|
||
_receivePort = ReceivePort();
|
||
// If already registered, remove and re-register
|
||
IsolateNameServer.removePortNameMapping('_backgroundChannelKey');
|
||
final ok = IsolateNameServer.registerPortWithName(_receivePort!.sendPort, '_backgroundChannelKey');
|
||
if (!ok) {
|
||
// If this happens, something else re-registered immediately or you’re in a weird state.
|
||
throw StateError('Failed to register port name');
|
||
}
|
||
final backgroundMessagePort = _receivePort!.asBroadcastStream();
|
||
_sub = backgroundMessagePort.listen((message) {
|
||
print('Background isolate received message: $message');
|
||
if (message == 'disconnect') {
|
||
UniversalBle.onAvailabilityChange = null;
|
||
core.connection.disconnectAll();
|
||
} else if (message == 'close') {
|
||
unawaited(
|
||
closeAndQuit().catchError((Object e, StackTrace s) => recordError(e, s, context: 'notification close')),
|
||
);
|
||
}
|
||
|
||
//exit(0);
|
||
});
|
||
}
|
||
}
|
||
|
||
@pragma('vm:entry-point')
|
||
void notificationTapBackground(NotificationResponse notificationResponse) {
|
||
if (notificationResponse.actionId != null) {
|
||
final sendPort = IsolateNameServer.lookupPortByName('_backgroundChannelKey');
|
||
sendPort?.send(notificationResponse.actionId);
|
||
//exit(0);
|
||
}
|
||
}
|