Progress gives a Day/Week/Month view of routines held against a weekly target, compared with the same point of the previous period, with active time and the daily streak. Targets & reminders sets routines and minutes per week and schedules a heads-up before each routine. The runner's summary now shows today's held count and streak. Finished runs are mirrored to a device run log that feeds both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KhQh614DMeYoQEH9SoMRUw
290 lines
9.6 KiB
Dart
290 lines
9.6 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
import 'package:timezone/data/latest.dart' as timezones;
|
|
import 'package:timezone/timezone.dart' as tz;
|
|
|
|
import '../about/external/data/Commitment.dart';
|
|
import '../about/external/data/LiveSession.dart';
|
|
import '../about/external/data/RoutineChain.dart';
|
|
import '../about/internal/application/CommitmentClass.dart';
|
|
import '../about/internal/application/EscalationTier.dart';
|
|
import '../about/internal/application/ToneLevel.dart';
|
|
import '../utils/CommonUtils.dart';
|
|
import '../utils/ToneEngine.dart';
|
|
|
|
/// Notification channels, the ongoing "task running" notification, and the
|
|
/// full-screen alarm used for non-negotiables.
|
|
class LocalNotificationEngine {
|
|
static final FlutterLocalNotificationsPlugin plugin =
|
|
FlutterLocalNotificationsPlugin();
|
|
|
|
/// Ordinary reminders — respects quiet hours.
|
|
static const String reminderChannel = "grounded_reminders";
|
|
|
|
/// The ongoing notification attached to a running task. Not dismissable, so
|
|
/// a task in progress is always one tap away from the lock screen.
|
|
static const String sessionChannel = "grounded_session";
|
|
|
|
/// Alarm-class, full-screen. Reserved for non-negotiables, and the only
|
|
/// channel that overrides quiet hours.
|
|
static const String alarmChannel = "grounded_alarm";
|
|
|
|
static const int sessionNotificationId = 9000;
|
|
|
|
static bool _ready = false;
|
|
|
|
static Future<void> init() async {
|
|
if (_ready || kIsWeb) {
|
|
return;
|
|
}
|
|
|
|
const AndroidInitializationSettings android =
|
|
AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
|
|
const DarwinInitializationSettings apple = DarwinInitializationSettings(
|
|
requestAlertPermission: true,
|
|
requestBadgePermission: true,
|
|
requestSoundPermission: true,
|
|
// Critical alerts need Apple entitlement approval; requesting without it
|
|
// is simply ignored rather than failing.
|
|
requestCriticalPermission: true,
|
|
);
|
|
|
|
await plugin.initialize(
|
|
settings: const InitializationSettings(
|
|
android: android, iOS: apple, macOS: apple),
|
|
);
|
|
|
|
if (Platform.isAndroid) {
|
|
await _createAndroidChannels();
|
|
}
|
|
|
|
_ready = true;
|
|
}
|
|
|
|
static Future<void> _createAndroidChannels() async {
|
|
final AndroidFlutterLocalNotificationsPlugin? android =
|
|
plugin.resolvePlatformSpecificImplementation<
|
|
AndroidFlutterLocalNotificationsPlugin>();
|
|
|
|
if (android == null) {
|
|
return;
|
|
}
|
|
|
|
await android.createNotificationChannel(const AndroidNotificationChannel(
|
|
reminderChannel,
|
|
'Reminders',
|
|
description: 'Nudges about commitments that are due.',
|
|
importance: Importance.defaultImportance,
|
|
));
|
|
|
|
await android.createNotificationChannel(const AndroidNotificationChannel(
|
|
sessionChannel,
|
|
'Task in progress',
|
|
description: 'The ongoing notification for a task you are running.',
|
|
importance: Importance.low,
|
|
playSound: false,
|
|
enableVibration: false,
|
|
));
|
|
|
|
await android.createNotificationChannel(const AndroidNotificationChannel(
|
|
alarmChannel,
|
|
'Non-negotiables',
|
|
description:
|
|
'Full-screen alarms for non-negotiable commitments. These ignore quiet hours.',
|
|
importance: Importance.max,
|
|
playSound: true,
|
|
enableVibration: true,
|
|
));
|
|
|
|
await android.requestNotificationsPermission();
|
|
|
|
// Exact alarms are what let a window actually close on time rather than
|
|
// whenever the OS feels like it.
|
|
await android.requestExactAlarmsPermission();
|
|
}
|
|
|
|
/// The ongoing notification for a running task. Shows the live remaining
|
|
/// time so it is useful from the lock screen without unlocking.
|
|
static Future<void> showSessionNotification(LiveSession session) async {
|
|
// The browser has no notification channels; the runner works without.
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
|
|
final String remaining = session.requiredSeconds > 0
|
|
? "${formatClock(session.remainingSeconds())} remaining"
|
|
: "${formatClock(session.elapsedSeconds())} elapsed";
|
|
|
|
final AndroidNotificationDetails android = AndroidNotificationDetails(
|
|
sessionChannel,
|
|
'Task in progress',
|
|
channelDescription: 'The ongoing notification for a running task.',
|
|
importance: Importance.low,
|
|
priority: Priority.low,
|
|
ongoing: true,
|
|
autoCancel: false,
|
|
onlyAlertOnce: true,
|
|
showWhen: true,
|
|
usesChronometer: session.requiredSeconds <= 0,
|
|
category: AndroidNotificationCategory.workout,
|
|
actions: const <AndroidNotificationAction>[
|
|
AndroidNotificationAction('pause', 'Pause'),
|
|
AndroidNotificationAction('finish', 'Finish'),
|
|
],
|
|
);
|
|
|
|
await plugin.show(
|
|
id: sessionNotificationId,
|
|
title: session.title,
|
|
body: session.goalTitle.isEmpty
|
|
? remaining
|
|
: "${session.goalTitle} · $remaining",
|
|
notificationDetails: NotificationDetails(
|
|
android: android,
|
|
iOS: const DarwinNotificationDetails(presentBanner: false),
|
|
),
|
|
payload: session.commitmentId,
|
|
);
|
|
}
|
|
|
|
static Future<void> cancelSessionNotification() async {
|
|
// The browser has no notification channels; the runner works without.
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
await plugin.cancel(id: sessionNotificationId);
|
|
}
|
|
|
|
/// A due-window nudge. Non-negotiables go out full-screen and alarm-class so
|
|
/// they surface over the lock screen; everything else is an ordinary
|
|
/// notification.
|
|
static Future<void> showCommitmentNudge(
|
|
Commitment commitment,
|
|
EscalationTier tier,
|
|
ToneLevel tone,
|
|
) async {
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
|
|
final bool nonNegotiable =
|
|
commitment.commitmentClass == CommitmentClass.NonNegotiable;
|
|
|
|
final AndroidNotificationDetails android = AndroidNotificationDetails(
|
|
nonNegotiable ? alarmChannel : reminderChannel,
|
|
nonNegotiable ? 'Non-negotiables' : 'Reminders',
|
|
importance: nonNegotiable ? Importance.max : Importance.defaultImportance,
|
|
priority: nonNegotiable ? Priority.max : Priority.defaultPriority,
|
|
// The full-screen intent is what turns this into a lock-screen takeover
|
|
// rather than a banner that can be swiped past.
|
|
fullScreenIntent: nonNegotiable,
|
|
category: nonNegotiable
|
|
? AndroidNotificationCategory.alarm
|
|
: AndroidNotificationCategory.reminder,
|
|
actions: <AndroidNotificationAction>[
|
|
const AndroidNotificationAction('start', 'Start now'),
|
|
if (!nonNegotiable)
|
|
const AndroidNotificationAction('snooze', 'Snooze'),
|
|
],
|
|
);
|
|
|
|
await plugin.show(
|
|
id: commitment.id.hashCode,
|
|
title: commitment.title,
|
|
body: ToneEngine.nudge(tier, tone, commitment.title),
|
|
notificationDetails: NotificationDetails(
|
|
android: android,
|
|
iOS: DarwinNotificationDetails(
|
|
// Critical alerts bypass Do Not Disturb, and are the iOS equivalent
|
|
// of the Android full-screen intent. Requires Apple approval.
|
|
interruptionLevel: nonNegotiable
|
|
? InterruptionLevel.critical
|
|
: InterruptionLevel.active,
|
|
),
|
|
),
|
|
payload: commitment.id,
|
|
);
|
|
}
|
|
|
|
/// Routine reminders occupy ids [reminderBase, reminderBase + reminderSlots).
|
|
static const int reminderBase = 7000;
|
|
|
|
static const int reminderSlots = 200;
|
|
|
|
/// One-shot reminders for every scheduled routine over the next seven days,
|
|
/// [leadMinutes] before its start. One-shots rather than repeating rules so
|
|
/// no device time-zone lookup is needed: each fire time is an absolute
|
|
/// instant. Home re-places them on every open, so the week rolls forward.
|
|
static Future<void> scheduleRoutineReminders(
|
|
List<RoutineChain> routines, int leadMinutes) async {
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
await cancelRoutineReminders();
|
|
timezones.initializeTimeZones();
|
|
|
|
final DateTime now = DateTime.now();
|
|
final DateTime today = DateTime(now.year, now.month, now.day);
|
|
int slot = 0;
|
|
|
|
for (int offset = 0; offset < 7; offset++) {
|
|
final DateTime day = today.add(Duration(days: offset));
|
|
|
|
for (RoutineChain routine in routines) {
|
|
if (!routine.days.contains(day.weekday) || routine.startMinute < 0) {
|
|
continue;
|
|
}
|
|
|
|
final DateTime fireAt = day.add(
|
|
Duration(minutes: routine.startMinute - leadMinutes));
|
|
if (!fireAt.isAfter(now) || slot >= reminderSlots) {
|
|
continue;
|
|
}
|
|
|
|
await plugin.zonedSchedule(
|
|
id: reminderBase + slot,
|
|
title: routine.title,
|
|
body: leadMinutes == 0
|
|
? "Starting now."
|
|
: "Starts in $leadMinutes minutes.",
|
|
scheduledDate: tz.TZDateTime.from(fireAt, tz.UTC),
|
|
notificationDetails: const NotificationDetails(
|
|
android: AndroidNotificationDetails(reminderChannel, 'Reminders',
|
|
category: AndroidNotificationCategory.reminder),
|
|
iOS: DarwinNotificationDetails(),
|
|
),
|
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
|
payload: routine.id,
|
|
);
|
|
slot = slot + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
static Future<void> cancelRoutineReminders() async {
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
for (int index = 0; index < reminderSlots; index++) {
|
|
await plugin.cancel(id: reminderBase + index);
|
|
}
|
|
}
|
|
|
|
static Future<void> cancelAll() async {
|
|
// The browser has no notification channels; the runner works without.
|
|
if (kIsWeb) {
|
|
return;
|
|
}
|
|
await init();
|
|
await plugin.cancelAll();
|
|
}
|
|
}
|