refactor: cleanup dead code from reminder system

- Remove permission fallback logic from LocalNotificationService
- Remove unused methods: _scheduleInApp*, _trackFallback, bindInAppReminderHandler
- Remove unused fields: _permissionFallbackTracker, _inAppReminderHandler, _inAppFallbackTimersByEventId, _canDeliverSystemNotification
- Remove unused _showSnoozeOptions from ReminderOverlay
- Remove unused reminderActionExecutor from AuthSessionBootstrapper
- Remove obsolete test files: reminder_permission_fallback_test, reminder_notification_bridge_test, auth_session_bootstrapper_test
- Add native notification grouping (threadIdentifier/groupKey)
This commit is contained in:
qzl
2026-03-20 18:53:32 +08:00
parent 42c2fbc8f3
commit d17f5d78aa
7 changed files with 23 additions and 938 deletions
@@ -1,8 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz_data;
import 'package:timezone/timezone.dart' as tz;
@@ -18,45 +16,22 @@ typedef ReminderNotificationActionHandler =
required ReminderPayload payload,
});
typedef ReminderPermissionFallbackTracker =
void Function({
required String actionExecutionId,
required String permissionState,
required String appLifecycleState,
required String platform,
});
typedef ReminderInAppReminderHandler =
Future<void> Function(ReminderPayload payload);
class LocalNotificationService {
static const String _iosCategoryId = 'calendar_reminder_v2';
static const String _actionCancel = 'cancel';
static const String _actionSnooze = 'snooze10m';
final FlutterLocalNotificationsPlugin _plugin;
final ReminderPermissionFallbackTracker? _permissionFallbackTracker;
bool _initialized = false;
bool _canDeliverSystemNotification = true;
ReminderNotificationActionHandler? _actionHandler;
ReminderInAppReminderHandler? _inAppReminderHandler;
final Map<String, List<Timer>> _inAppFallbackTimersByEventId =
<String, List<Timer>>{};
LocalNotificationService({
FlutterLocalNotificationsPlugin? plugin,
ReminderPermissionFallbackTracker? permissionFallbackTracker,
}) : _plugin = plugin ?? FlutterLocalNotificationsPlugin(),
_permissionFallbackTracker = permissionFallbackTracker;
LocalNotificationService({FlutterLocalNotificationsPlugin? plugin})
: _plugin = plugin ?? FlutterLocalNotificationsPlugin();
void bindActionHandler(ReminderNotificationActionHandler handler) {
_actionHandler = handler;
}
void bindInAppReminderHandler(ReminderInAppReminderHandler handler) {
_inAppReminderHandler = handler;
}
Future<void> initialize() async {
if (_initialized) {
return;
@@ -98,18 +73,7 @@ class LocalNotificationService {
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
final androidPermissionGranted = await androidImpl
?.requestNotificationsPermission();
if (defaultTargetPlatform == TargetPlatform.android &&
androidPermissionGranted == false) {
_canDeliverSystemNotification = false;
_permissionFallbackTracker?.call(
actionExecutionId: 'permission_check',
permissionState: 'denied',
appLifecycleState: 'unknown',
platform: 'android',
);
}
await androidImpl?.requestNotificationsPermission();
await androidImpl?.requestExactAlarmsPermission();
await androidImpl?.requestFullScreenIntentPermission();
@@ -122,24 +86,8 @@ class LocalNotificationService {
_initialized = true;
}
Future<void> _refreshAndroidNotificationAvailability() async {
if (defaultTargetPlatform != TargetPlatform.android) {
return;
}
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
final enabled = await androidImpl?.areNotificationsEnabled();
if (enabled == null) {
return;
}
_canDeliverSystemNotification = enabled;
}
Future<void> upsertEventReminder(ScheduleItemModel event) async {
await initialize();
await _refreshAndroidNotificationAvailability();
if (event.status != ScheduleStatus.active ||
event.metadata?.reminderMinutes == null) {
await cancelEventReminder(event.id);
@@ -154,14 +102,6 @@ class LocalNotificationService {
return;
}
if (!_canDeliverSystemNotification) {
await _scheduleInAppFallbackRemindersFrom(
event: event,
firstFireAt: fireAt,
);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
@@ -171,21 +111,12 @@ class LocalNotificationService {
DateTime fireAt,
) async {
await initialize();
await _refreshAndroidNotificationAvailability();
if (!_canDeliverSystemNotification) {
await _scheduleInAppFallbackRemindersFrom(
event: event,
firstFireAt: fireAt,
);
return;
}
await cancelEventReminder(event.id);
await _scheduleRemindersFrom(event: event, firstFireAt: fireAt);
}
Future<void> cancelEventReminder(String eventId) async {
await initialize();
_cancelInAppFallbackTimers(eventId);
final pending = await _plugin.pendingNotificationRequests();
for (final request in pending) {
@@ -206,21 +137,7 @@ class LocalNotificationService {
Iterable<ScheduleItemModel> events,
) async {
await initialize();
await _refreshAndroidNotificationAvailability();
for (final event in events) {
if (!_canDeliverSystemNotification) {
final reminderMinutes = event.metadata?.reminderMinutes ?? 0;
final fireAt = event.startAt.subtract(
Duration(minutes: reminderMinutes),
);
if (fireAt.isAfter(DateTime.now())) {
await _scheduleInAppFallbackRemindersFrom(
event: event,
firstFireAt: fireAt,
);
}
continue;
}
await upsertEventReminder(event);
}
}
@@ -241,10 +158,6 @@ class LocalNotificationService {
}
Future<AndroidScheduleMode> _resolveAndroidScheduleMode() async {
if (defaultTargetPlatform != TargetPlatform.android) {
return AndroidScheduleMode.exactAllowWhileIdle;
}
final androidImpl = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
@@ -260,7 +173,7 @@ class LocalNotificationService {
: AndroidScheduleMode.inexactAllowWhileIdle;
}
NotificationDetails _buildNotificationDetails() {
NotificationDetails _buildNotificationDetails(DateTime fireAt) {
return NotificationDetails(
android: AndroidNotificationDetails(
'calendar_alarm_channel_v2',
@@ -276,6 +189,7 @@ class LocalNotificationService {
vibrationPattern: Int64List.fromList([0, 1000, 500, 1200]),
timeoutAfter: 30000,
autoCancel: true,
groupKey: _getGroupKey(fireAt),
actions: <AndroidNotificationAction>[
AndroidNotificationAction(_actionCancel, '取消'),
AndroidNotificationAction(
@@ -285,15 +199,30 @@ class LocalNotificationService {
),
],
),
iOS: const DarwinNotificationDetails(
iOS: DarwinNotificationDetails(
presentAlert: true,
presentSound: true,
presentBadge: true,
categoryIdentifier: _iosCategoryId,
threadIdentifier: _getThreadIdentifier(fireAt),
),
);
}
String _getThreadIdentifier(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'calendar_reminder_$bucket';
}
String _getGroupKey(DateTime fireAt) {
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
return 'com.socialapp.calendar.$bucket';
}
Future<void> _scheduleSingleReminder({
required ScheduleItemModel event,
required DateTime fireAt,
@@ -319,7 +248,7 @@ class LocalNotificationService {
version: 1,
);
final details = _buildNotificationDetails();
final details = _buildNotificationDetails(fireAt);
final scheduledAt = tz.TZDateTime.from(fireAt, tz.local);
final mode = await _resolveAndroidScheduleMode();
@@ -350,185 +279,6 @@ class LocalNotificationService {
}
}
Future<void> _scheduleInAppAggregateFallback(
List<ScheduleItemModel> events,
DateTime fireAt,
) async {
if (events.isEmpty) {
return;
}
final aggregateIds = events.map((event) => event.id).toList();
for (final eventId in aggregateIds) {
_cancelInAppFallbackTimers(eventId);
}
final first = events.first;
final payload = ReminderPayload(
eventId: first.id,
title: '你有${events.length}个日程提醒',
startAt: first.startAt,
endAt: first.endAt,
timezone: first.timezone,
mode: ReminderPayloadMode.aggregate,
aggregateIds: aggregateIds,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
await _scheduleInAppFallbackPayload(
eventId: first.id,
fireAt: fireAt,
payload: payload,
relatedEventIds: aggregateIds,
);
}
Future<void> _scheduleInAppFallbackRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
}) async {
_cancelInAppFallbackTimers(event.id);
final endAt = event.endAt;
var cursor = firstFireAt;
Future<void> scheduleAt(DateTime fireAt) async {
final payload = ReminderPayload(
eventId: event.id,
title: event.title,
startAt: event.startAt,
endAt: event.endAt,
timezone: event.timezone,
location: event.metadata?.location,
notes: event.metadata?.notes,
color: event.metadata?.color,
mode: ReminderPayloadMode.single,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
await _scheduleInAppFallbackPayload(
eventId: event.id,
fireAt: fireAt,
payload: payload,
relatedEventIds: <String>[event.id],
);
}
if (endAt == null) {
await scheduleAt(cursor);
return;
}
while (cursor.isBefore(endAt)) {
await scheduleAt(cursor);
cursor = cursor.add(const Duration(minutes: 10));
}
}
Future<Timer?> _scheduleInAppFallbackPayload({
required String eventId,
required DateTime fireAt,
required ReminderPayload payload,
required List<String> relatedEventIds,
}) async {
final handler = _inAppReminderHandler;
final bucket =
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds;
final actionExecutionId = '$eventId|fallback|$bucket';
_trackFallback(
actionExecutionId: actionExecutionId,
permissionState: 'denied',
);
if (handler == null) {
return null;
}
final now = DateTime.now();
final delay = fireAt.isAfter(now) ? fireAt.difference(now) : Duration.zero;
late final Timer timer;
timer = Timer(delay, () {
final activeHandler = _inAppReminderHandler;
if (activeHandler == null) {
_unregisterInAppFallbackTimer(relatedEventIds, timer);
return;
}
activeHandler(payload);
_unregisterInAppFallbackTimer(relatedEventIds, timer);
});
_registerInAppFallbackTimer(relatedEventIds, timer);
return timer;
}
void _registerInAppFallbackTimer(List<String> eventIds, Timer timer) {
for (final eventId in eventIds) {
final timers = _inAppFallbackTimersByEventId.putIfAbsent(
eventId,
() => <Timer>[],
);
timers.add(timer);
}
}
void _unregisterInAppFallbackTimer(List<String> eventIds, Timer timer) {
for (final eventId in eventIds) {
final timers = _inAppFallbackTimersByEventId[eventId];
if (timers == null) {
continue;
}
timers.remove(timer);
if (timers.isEmpty) {
_inAppFallbackTimersByEventId.remove(eventId);
}
}
}
void _cancelInAppFallbackTimers(String eventId) {
final timers = _inAppFallbackTimersByEventId.remove(eventId);
if (timers == null) {
return;
}
for (final timer in timers.toSet()) {
for (final entry in _inAppFallbackTimersByEventId.entries) {
entry.value.remove(timer);
}
timer.cancel();
}
_inAppFallbackTimersByEventId.removeWhere((_, value) => value.isEmpty);
}
void _clearAllInAppFallbackTimers() {
final allTimers = <Timer>{};
for (final timers in _inAppFallbackTimersByEventId.values) {
allTimers.addAll(timers);
}
_inAppFallbackTimersByEventId.clear();
for (final timer in allTimers) {
timer.cancel();
}
}
void _trackFallback({
required String actionExecutionId,
required String permissionState,
}) {
final lifecycleState =
WidgetsBinding.instance.lifecycleState?.name ?? 'unknown';
_permissionFallbackTracker?.call(
actionExecutionId: actionExecutionId,
permissionState: permissionState,
appLifecycleState: lifecycleState,
platform: 'android',
);
}
Future<void> _scheduleRemindersFrom({
required ScheduleItemModel event,
required DateTime firstFireAt,
@@ -546,56 +296,6 @@ class LocalNotificationService {
}
}
Future<void> _scheduleAggregateReminder(
List<ScheduleItemModel> events,
DateTime fireAt,
) async {
if (events.isEmpty) {
return;
}
final first = events.first;
final aggregateIds = events.map((event) => event.id).toList();
for (final id in aggregateIds) {
await cancelEventReminder(id);
}
final payload = ReminderPayload(
eventId: first.id,
title: '你有${events.length}个日程提醒',
startAt: first.startAt,
endAt: first.endAt,
timezone: first.timezone,
mode: ReminderPayloadMode.aggregate,
aggregateIds: aggregateIds,
fireTimeBucket:
fireAt.millisecondsSinceEpoch ~/
const Duration(minutes: 1).inMilliseconds,
version: 1,
);
final details = _buildNotificationDetails();
final scheduledAt = tz.TZDateTime.from(fireAt, tz.local);
final mode = await _resolveAndroidScheduleMode();
final preview = events.take(3).map((item) => item.title).join('');
await _plugin.zonedSchedule(
_notificationIdForEventCycle(
first.id,
fireAt,
ReminderPayloadMode.aggregate,
),
'你有${events.length}个日程提醒',
preview,
scheduledAt,
details,
payload: jsonEncode(payload.toJson()),
androidScheduleMode: mode,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
ReminderPayload? _decodePayload(String? raw) {
if (raw == null || raw.isEmpty) {
return null;
@@ -650,13 +350,6 @@ class LocalNotificationService {
}
if (action == null) {
if (response.notificationResponseType ==
NotificationResponseType.selectedNotification) {
final presenter = _inAppReminderHandler;
if (presenter != null) {
await presenter(payload);
}
}
return;
}
@@ -1,20 +1,16 @@
import '../../features/auth/presentation/bloc/auth_state.dart';
import '../../features/calendar/data/services/calendar_service.dart';
import '../../features/calendar/reminders/reminder_action_executor.dart';
import '../notifications/local_notification_service.dart';
class AuthSessionBootstrapper {
AuthSessionBootstrapper({
required CalendarService calendarService,
required LocalNotificationService notificationService,
required ReminderActionExecutor reminderActionExecutor,
}) : _calendarService = calendarService,
_notificationService = notificationService,
_reminderActionExecutor = reminderActionExecutor;
_notificationService = notificationService;
final CalendarService _calendarService;
final LocalNotificationService _notificationService;
final ReminderActionExecutor _reminderActionExecutor;
String? _syncedUserId;