185 lines
6.3 KiB
Dart
185 lines
6.3 KiB
Dart
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
import 'package:timezone/timezone.dart' as tz;
|
|
import 'package:timezone/data/latest.dart' as tz;
|
|
import 'package:flutter_timezone/flutter_timezone.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../services/app_settings.dart';
|
|
import '../services/google_calendar_service.dart';
|
|
|
|
class NotificationService {
|
|
static final NotificationService _instance = NotificationService._internal();
|
|
factory NotificationService() => _instance;
|
|
NotificationService._internal();
|
|
|
|
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
|
|
bool _initialized = false;
|
|
|
|
static const _channel = AndroidNotificationChannel(
|
|
'shooting_app_events',
|
|
'Event Reminders',
|
|
description: 'Notifications for upcoming shooting events',
|
|
importance: Importance.max,
|
|
playSound: true,
|
|
enableVibration: true,
|
|
);
|
|
|
|
NotificationDetails get _notifDetails => const NotificationDetails(
|
|
android: AndroidNotificationDetails(
|
|
'shooting_app_events',
|
|
'Event Reminders',
|
|
channelDescription: 'Notifications for upcoming shooting events',
|
|
importance: Importance.max,
|
|
priority: Priority.high,
|
|
icon: '@drawable/ic_stat_icon_white',
|
|
),
|
|
iOS: DarwinNotificationDetails(
|
|
presentAlert: true,
|
|
presentBadge: true,
|
|
presentSound: true,
|
|
),
|
|
);
|
|
|
|
Future<void> initialize() async {
|
|
if (_initialized) return;
|
|
_initialized = true; // set early to prevent re-entry
|
|
|
|
try {
|
|
tz.initializeTimeZones();
|
|
final String timezoneName = await FlutterTimezone.getLocalTimezone();
|
|
tz.setLocalLocation(tz.getLocation(timezoneName));
|
|
} catch (_) {}
|
|
|
|
try {
|
|
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
const iosSettings = DarwinInitializationSettings(
|
|
requestAlertPermission: true,
|
|
requestBadgePermission: true,
|
|
requestSoundPermission: true,
|
|
);
|
|
const initSettings = InitializationSettings(android: androidSettings, iOS: iosSettings);
|
|
await _plugin.initialize(initSettings);
|
|
|
|
final androidPlugin = _plugin.resolvePlatformSpecificImplementation<
|
|
AndroidFlutterLocalNotificationsPlugin>();
|
|
await androidPlugin?.createNotificationChannel(_channel);
|
|
await requestPermissions();
|
|
} catch (_) {}
|
|
}
|
|
|
|
/// Fetches the calendar and reschedules all reminders. Call on app start
|
|
/// and whenever notification settings change.
|
|
Future<void> rescheduleFromCalendar() async {
|
|
if (!AppSettings.instance.clubUnlocked) {
|
|
await cancelAll(); // reminders are a club-member feature
|
|
return;
|
|
}
|
|
final service = GoogleCalendarService();
|
|
try {
|
|
final now = DateTime.now();
|
|
final events = await service.getEvents(
|
|
startDate: now,
|
|
endDate: now.add(const Duration(days: 365)),
|
|
);
|
|
await scheduleEventNotifications(events);
|
|
} catch (_) {
|
|
} finally {
|
|
service.dispose();
|
|
}
|
|
}
|
|
|
|
Future<bool> requestPermissions() async {
|
|
final android = _plugin.resolvePlatformSpecificImplementation<
|
|
AndroidFlutterLocalNotificationsPlugin>();
|
|
final ios = _plugin.resolvePlatformSpecificImplementation<
|
|
IOSFlutterLocalNotificationsPlugin>();
|
|
|
|
bool granted = false;
|
|
if (android != null) {
|
|
granted = await android.requestNotificationsPermission() ?? false;
|
|
}
|
|
if (ios != null) {
|
|
granted = await ios.requestPermissions(alert: true, badge: true, sound: true) ?? false;
|
|
}
|
|
return granted;
|
|
}
|
|
|
|
Future<void> cancelAll() async {
|
|
await _plugin.cancelAll();
|
|
}
|
|
|
|
Future<void> scheduleEventNotifications(List<CalendarEvent> events) async {
|
|
try {
|
|
await initialize();
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final hours = prefs.getInt('notificationHours_single') ?? 1;
|
|
final notifyDezuranje = prefs.getBool('notifyDezuranje') ?? true;
|
|
final notifySestanek = prefs.getBool('notifySestanek') ?? true;
|
|
final notifyTekma = prefs.getBool('notifyTekma') ?? true;
|
|
final language = prefs.getString('language') ?? 'Slovenian';
|
|
final now = DateTime.now();
|
|
|
|
await _plugin.cancelAll();
|
|
|
|
int notifId = 0;
|
|
for (final event in events) {
|
|
if (event.startTime == null) continue;
|
|
|
|
final summary = (event.summary ?? '').toLowerCase();
|
|
// Same classification as the calendar screen; skip anything else
|
|
final isCompetition = summary.contains('liga') || summary.contains('tekmovanje') || summary.contains('tekma');
|
|
final isSestanek = !isCompetition && summary.contains('sestanek');
|
|
final isDezuranje = !isCompetition && !isSestanek && summary.contains('dežurstvo');
|
|
if (!isCompetition && !isSestanek && !isDezuranje) continue;
|
|
|
|
if (isCompetition && !notifyTekma) continue;
|
|
if (isSestanek && !notifySestanek) continue;
|
|
if (isDezuranje && !notifyDezuranje) continue;
|
|
|
|
final notifyAt = event.startTime!.subtract(Duration(hours: hours));
|
|
if (notifyAt.isAfter(now)) {
|
|
await _scheduleNotification(
|
|
id: notifId++,
|
|
title: event.summary ?? 'Event',
|
|
body: _startsIn(hours, language),
|
|
scheduledDate: notifyAt,
|
|
);
|
|
}
|
|
}
|
|
} catch (_) {}
|
|
}
|
|
|
|
static String _startsIn(int hours, String language) {
|
|
switch (language) {
|
|
case 'Slovenian':
|
|
final mod = hours % 100;
|
|
final unit = mod == 1 ? 'uro' : mod == 2 ? 'uri' : (mod == 3 || mod == 4) ? 'ure' : 'ur';
|
|
return 'Začne se čez $hours $unit';
|
|
case 'German':
|
|
return hours == 1 ? 'Beginnt in 1 Stunde' : 'Beginnt in $hours Stunden';
|
|
default:
|
|
return hours == 1 ? 'Starts in 1 hour' : 'Starts in $hours hours';
|
|
}
|
|
}
|
|
|
|
Future<void> _scheduleNotification({
|
|
required int id,
|
|
required String title,
|
|
required String body,
|
|
required DateTime scheduledDate,
|
|
}) async {
|
|
final tzDate = tz.TZDateTime.from(scheduledDate, tz.local);
|
|
await _plugin.zonedSchedule(
|
|
id,
|
|
title,
|
|
body,
|
|
tzDate,
|
|
_notifDetails,
|
|
// Inexact: avoids the SCHEDULE_EXACT_ALARM permission (Play policy).
|
|
androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
|
|
uiLocalNotificationDateInterpretation:
|
|
UILocalNotificationDateInterpretation.absoluteTime,
|
|
);
|
|
}
|
|
}
|