hrt/lib/notification.dart
Lea 1932e215d1
jesus fucking christ
i am never going to touch android dev again
2023-10-06 20:21:43 +02:00

116 lines
3 KiB
Dart

// ignore_for_file: avoid_print
import 'dart:io';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:timezone/data/latest.dart';
import 'package:timezone/standalone.dart';
import 'package:timezone/timezone.dart';
const details = NotificationDetails(
android: AndroidNotificationDetails(
'hrt',
'HRT',
autoCancel: false,
styleInformation: BigPictureStyleInformation(
DrawableResourceAndroidBitmap('take_your_hrt'),
),
importance: Importance.max,
ongoing: true,
actions: [AndroidNotificationAction("confirmation", "Done!")],
),
);
void _initializePlugin() async {
var initialized = await FlutterLocalNotificationsPlugin().initialize(
const InitializationSettings(
android: AndroidInitializationSettings('estrogen'),
),
);
if (initialized != true) {
throw "Not initialized";
}
}
void sendNotification() async {
_initializePlugin();
await FlutterLocalNotificationsPlugin().show(
1,
null,
null,
details,
);
}
void scheduleNotification() async {
_initializePlugin();
initializeTimeZones();
var timezone = await FlutterNativeTimezone.getLocalTimezone();
setLocalLocation(getLocation(timezone));
// [Hours, Minutes]
var times = [
[12, 00],
[18, 00],
[19, 50],
[19, 51],
[20, 52],
[20, 53],
];
if (times.isEmpty) return;
final SharedPreferences prefs = await SharedPreferences.getInstance();
var currentTime = TZDateTime.now(local);
print(local.name);
// Map the time entries to TZDateTime objects
var notificationTimes = times
.map((item) => TZDateTime(
local,
currentTime.year,
currentTime.month,
currentTime.day,
item[0],
item[1],
))
.toList();
// For all entries in the past, add 1 day
for (var time
in notificationTimes.where((time) => time.compareTo(currentTime) <= 0)) {
notificationTimes.remove(time);
notificationTimes.add(time.add(const Duration(days: 1)));
print("trolling ${time.toString()}");
}
// Sort the array so we can find the closest time
notificationTimes.sort((a, b) => a.compareTo(b));
print(notificationTimes.map((e) => e.toString()).join(" - "));
var notificationTime = notificationTimes[0];
if (prefs.getString('scheduled_notification') ==
notificationTime.toIso8601String()) {
print("Notification already scheduled for "
"${notificationTime.toIso8601String()}, not re-scheduling");
return;
}
print("Scheduling notification for ${notificationTime.toIso8601String()}");
await FlutterLocalNotificationsPlugin().zonedSchedule(
1,
null,
null,
notificationTime,
details,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
await prefs.setString(
'scheduled_notification', notificationTime.toIso8601String());
}