Merge: Android in-app notification service

This commit is contained in:
2026-11-01 02:22:03 +00:00
33 changed files with 2589 additions and 3 deletions
@@ -0,0 +1,88 @@
import 'dart:async';
import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart';
/// A scripted background service: records calls and reports [current].
class FakeNotificationService implements NotificationServiceBridge {
FakeNotificationService({NotificationServiceStatus? status})
: current =
status ??
const NotificationServiceStatus(
enabled: true,
configured: true,
state: DeliveryState.connected,
notificationsAllowed: true,
batteryExempt: false,
);
NotificationServiceStatus current;
final calls = <(String, Map<String, Object?>)>[];
final _changes = StreamController<NotificationServiceStatus>.broadcast();
bool batteryGranted = true;
void push(NotificationServiceStatus status) {
current = status;
_changes.add(status);
}
NotificationServiceStatus copy({
bool? enabled,
DeliveryState? state,
bool? notificationsAllowed,
bool? batteryExempt,
}) => NotificationServiceStatus(
enabled: enabled ?? current.enabled,
configured: current.configured,
state: state ?? current.state,
notificationsAllowed: notificationsAllowed ?? current.notificationsAllowed,
batteryExempt: batteryExempt ?? current.batteryExempt,
);
@override
bool get supported => true;
@override
Stream<NotificationServiceStatus> get changes => _changes.stream;
@override
Future<NotificationServiceStatus> status() async {
calls.add(('status', const {}));
return current;
}
@override
Future<NotificationServiceStatus> start() async {
calls.add(('start', const {}));
return current;
}
@override
Future<NotificationServiceStatus> configure({
required String serverId,
required List<String> endpoints,
required String cookie,
}) async {
calls.add((
'configure',
{'serverId': serverId, 'endpoints': endpoints, 'cookie': cookie},
));
return current;
}
@override
Future<NotificationServiceStatus> setEnabled(bool enabled) async {
calls.add(('setEnabled', {'enabled': enabled}));
current = copy(
enabled: enabled,
state: enabled ? DeliveryState.connecting : DeliveryState.off,
);
return current;
}
@override
Future<bool> requestBatteryExemption() async {
calls.add(('requestBatteryExemption', const {}));
if (batteryGranted) current = copy(batteryExempt: true);
return true;
}
}
@@ -0,0 +1,96 @@
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('test/notification_service');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
late List<MethodCall> calls;
Map<String, Object?> reply({String status = 'connected'}) => {
'enabled': true,
'configured': true,
'status': status,
'notificationsAllowed': true,
'batteryExempt': false,
};
setUp(() {
calls = [];
messenger.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return call.method == 'requestBatteryExemption' ? true : reply();
});
});
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
test('the production channel name matches the Kotlin side', () {
expect(
MethodChannelNotificationServiceBridge.channelName,
'pipelines/notification_service',
);
});
test('configure hands over the server, addresses and cookie', () async {
final bridge = MethodChannelNotificationServiceBridge(channel);
final status = await bridge.configure(
serverId: 'home',
endpoints: ['wss://a:8443/connect', 'ws://b:8081/connect'],
cookie: 'pipelines_session=abc',
);
expect(calls.single.method, 'configure');
expect(calls.single.arguments, {
'serverId': 'home',
'endpoints': ['wss://a:8443/connect', 'ws://b:8081/connect'],
'cookie': 'pipelines_session=abc',
});
expect(status.state, DeliveryState.connected);
expect(status.enabled, isTrue);
expect(status.batteryExempt, isFalse);
});
test('setEnabled, start, status and the battery prompt', () async {
final bridge = MethodChannelNotificationServiceBridge(channel);
await bridge.setEnabled(false);
await bridge.start();
await bridge.status();
expect(await bridge.requestBatteryExemption(), isTrue);
expect(calls.map((call) => call.method), [
'setEnabled',
'start',
'status',
'requestBatteryExemption',
]);
expect(calls.first.arguments, {'enabled': false});
});
test('statusChanged from the service reaches listeners', () async {
final bridge = MethodChannelNotificationServiceBridge(channel);
final next = bridge.changes.first;
await messenger.handlePlatformMessage(
channel.name,
channel.codec.encodeMethodCall(
MethodCall('statusChanged', reply(status: 'waiting_for_network')),
),
(_) {},
);
expect((await next).state, DeliveryState.waitingForNetwork);
});
test('unknown or malformed status falls back to off', () {
expect(
NotificationServiceStatus.fromMap({'status': 'weird'}).state,
DeliveryState.off,
);
expect(NotificationServiceStatus.fromMap(null).enabled, isFalse);
});
test('the host test platform has no service', () async {
final bridge = createNotificationServiceBridge();
expect(bridge.supported, isFalse);
expect((await bridge.status()).state, DeliveryState.off);
});
}
@@ -0,0 +1,82 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart';
import 'package:pipelines_app/features/notification_service/notification_service_handoff.dart';
import '../settings/fake_channel.dart';
import 'fake_notification_service.dart';
void main() {
test('each connection hands the proven server to the service', () async {
final channels = <FakeChannel>[];
final client = PipelinesClient(
channelFactory: (uri) {
final channel = FakeChannel(uri)..markReady();
channels.add(channel);
return channel;
},
);
final service = FakeNotificationService();
final handoff = NotificationServiceHandoff(
bridge: service,
client: client,
serverId: 'home',
headersFor: (uri) => uri.host == 'b'
? {'Cookie': 'pipelines_session=abc'}
: const <String, String>{},
);
// The app starts the service at launch when it is enabled.
expect(service.calls.single.$1, 'start');
await client.connectAny([
Uri.parse('wss://b:8443/connect'),
Uri.parse('ws://a:8081/connect'),
]);
await pumpEventQueue();
final configure = service.calls.last;
expect(configure.$1, 'configure');
expect(configure.$2, {
'serverId': 'home',
'endpoints': ['wss://b:8443/connect', 'ws://a:8081/connect'],
'cookie': 'pipelines_session=abc',
});
handoff.dispose();
await client.dispose();
});
test('without a server id the connected address names the server', () async {
final client = PipelinesClient(
channelFactory: (uri) => FakeChannel(uri)..markReady(),
);
final service = FakeNotificationService();
final handoff = NotificationServiceHandoff(
bridge: service,
client: client,
serverId: null,
headersFor: (_) => const <String, String>{},
);
await client.connect(Uri.parse('ws://a:8081/connect'));
await pumpEventQueue();
expect(service.calls.last.$2['serverId'], 'ws://a:8081/connect');
expect(service.calls.last.$2['cookie'], '');
handoff.dispose();
await client.dispose();
});
test('an unsupported platform is never called', () async {
final client = PipelinesClient(
channelFactory: (uri) => FakeChannel(uri)..markReady(),
);
final handoff = NotificationServiceHandoff(
bridge: const UnsupportedNotificationServiceBridge(),
client: client,
serverId: 'home',
headersFor: (_) => throw StateError('must not read credentials'),
);
await client.connect(Uri.parse('ws://a:8081/connect'));
await pumpEventQueue();
handoff.dispose();
await client.dispose();
});
}
@@ -0,0 +1,154 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/notification_service/notification_service_bridge.dart';
import 'package:pipelines_app/features/settings/settings_device_delivery_section.dart';
import '../notification_service/fake_notification_service.dart';
Widget _host(
NotificationServiceBridge bridge, {
required bool cupertino,
Future<void> Function()? requestPermission,
}) => MaterialApp(
theme: ThemeData(
platform: cupertino ? TargetPlatform.iOS : TargetPlatform.android,
),
home: Scaffold(
body: SingleChildScrollView(
child: SettingsDeviceDeliverySection(
bridge: bridge,
requestNotificationPermission: requestPermission,
),
),
),
);
bool _switchValue(WidgetTester tester, {required bool cupertino}) {
final tile = find.byKey(DeviceDeliveryKeys.toggle);
if (cupertino) {
return tester
.widget<CupertinoSwitch>(
find.descendant(of: tile, matching: find.byType(CupertinoSwitch)),
)
.value;
}
return tester.widget<SwitchListTile>(tile).value;
}
void main() {
for (final cupertino in [false, true]) {
final style = cupertino ? 'Cupertino' : 'Material';
testWidgets('$style shows the switch, status and ntfy note', (
tester,
) async {
final service = FakeNotificationService();
await tester.pumpWidget(_host(service, cupertino: cupertino));
await tester.pumpAndSettle();
expect(find.text(deviceDeliverySwitchLabel), findsOneWidget);
expect(_switchValue(tester, cupertino: cupertino), isTrue);
expect(find.text('Connected'), findsOneWidget);
expect(find.text(deviceDeliveryNote), findsOneWidget);
expect(find.text(deviceDeliveryBatteryLabel), findsOneWidget);
expect(find.byKey(DeviceDeliveryKeys.permission), findsNothing);
});
testWidgets('$style switching off stops delivery', (tester) async {
final service = FakeNotificationService();
await tester.pumpWidget(_host(service, cupertino: cupertino));
await tester.pumpAndSettle();
await tester.tap(find.byKey(DeviceDeliveryKeys.toggle));
await tester.pumpAndSettle();
expect(service.calls.last.$1, 'setEnabled');
expect(service.calls.last.$2, {'enabled': false});
expect(_switchValue(tester, cupertino: cupertino), isFalse);
expect(find.text('Off'), findsOneWidget);
// The grants only matter while delivery is on.
expect(find.text(deviceDeliveryBatteryLabel), findsNothing);
});
}
testWidgets('live status pushed by the service is shown', (tester) async {
final service = FakeNotificationService();
await tester.pumpWidget(_host(service, cupertino: false));
await tester.pumpAndSettle();
service.push(service.copy(state: DeliveryState.reconnecting));
await tester.pumpAndSettle();
expect(find.text('Reconnecting…'), findsOneWidget);
});
testWidgets('allow background delivery asks for the exemption', (
tester,
) async {
final service = FakeNotificationService();
await tester.pumpWidget(_host(service, cupertino: false));
await tester.pumpAndSettle();
await tester.tap(find.text(deviceDeliveryBatteryLabel));
await tester.pumpAndSettle();
expect(
service.calls.map((call) => call.$1),
contains('requestBatteryExemption'),
);
expect(
find.text('Allowed: battery optimisation will not pause delivery'),
findsOneWidget,
);
});
testWidgets('blocked notifications offer the permission request', (
tester,
) async {
var asked = 0;
final service = FakeNotificationService();
service.current = service.copy(notificationsAllowed: false);
await tester.pumpWidget(
_host(
service,
cupertino: false,
requestPermission: () async {
asked++;
service.current = service.copy(notificationsAllowed: true);
},
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(DeviceDeliveryKeys.permission));
await tester.pumpAndSettle();
expect(asked, 1);
expect(find.byKey(DeviceDeliveryKeys.permission), findsNothing);
});
testWidgets('switching on asks for notifications when blocked', (
tester,
) async {
var asked = 0;
final service = FakeNotificationService();
service.current = service.copy(
enabled: false,
state: DeliveryState.off,
notificationsAllowed: false,
);
await tester.pumpWidget(
_host(service, cupertino: false, requestPermission: () async => asked++),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(DeviceDeliveryKeys.toggle));
await tester.pumpAndSettle();
expect(asked, 1);
expect(service.calls.last.$1, 'setEnabled');
expect(service.calls.last.$2, {'enabled': true});
});
testWidgets('a failing platform is reported, not hidden', (tester) async {
await tester.pumpWidget(_host(_FailingService(), cupertino: false));
await tester.pumpAndSettle();
expect(find.byKey(DeviceDeliveryKeys.error), findsOneWidget);
});
}
class _FailingService extends FakeNotificationService {
@override
Future<NotificationServiceStatus> status() async =>
throw StateError('no service');
}
@@ -200,4 +200,50 @@ void main() {
isFalse,
);
});
group('ntfy_enabled', () {
JsonMap withNtfy(bool ntfy) => {
'type': 'notification_settings',
'notification_settings': {
...(_reply(true, true, false)['notification_settings'] as Map),
'ntfy_enabled': ntfy,
},
};
testWidgets('hidden when the server does not send it', (tester) async {
final gateway = _Gateway((_, _) => _reply(true, true, false));
await tester.pumpWidget(_host(gateway, cupertino: false));
await tester.pumpAndSettle();
expect(find.byKey(ntfySettingKey('ntfy_enabled')), findsNothing);
expect(find.text(ntfySectionSubtitle), findsOneWidget);
});
for (final cupertino in [false, true]) {
testWidgets(
'${cupertino ? 'Cupertino' : 'Material'} shows and writes it',
(tester) async {
final gateway = _Gateway(
(type, _) => withNtfy(type == 'set_notification_settings'),
);
await tester.pumpWidget(_host(gateway, cupertino: cupertino));
await tester.pumpAndSettle();
expect(find.text('Also send to ntfy'), findsOneWidget);
expect(find.text(ntfySectionAppSubtitle), findsOneWidget);
expect(
_checked(tester, 'ntfy_enabled', cupertino: cupertino),
isFalse,
);
await tester.tap(find.byKey(ntfySettingKey('ntfy_enabled')));
await tester.pumpAndSettle();
expect(gateway.calls.last.$2, {
'notification_settings': {'ntfy_enabled': true},
});
expect(
_checked(tester, 'ntfy_enabled', cupertino: cupertino),
isTrue,
);
},
);
}
});
}