2024-11-21 14:10:12 +00:00
|
|
|
import 'dart:developer';
|
|
|
|
import 'dart:io';
|
|
|
|
|
|
|
|
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:flutter_udid/flutter_udid.dart';
|
|
|
|
import 'package:provider/provider.dart';
|
|
|
|
import 'package:surface/providers/sn_network.dart';
|
|
|
|
import 'package:surface/providers/userinfo.dart';
|
|
|
|
|
|
|
|
class NotificationProvider extends ChangeNotifier {
|
|
|
|
late final SnNetworkProvider _sn;
|
|
|
|
late final UserProvider _ua;
|
|
|
|
|
|
|
|
NotificationProvider(BuildContext context) {
|
|
|
|
_sn = context.read<SnNetworkProvider>();
|
|
|
|
_ua = context.read<UserProvider>();
|
2024-11-21 14:55:00 +00:00
|
|
|
|
|
|
|
// Delay to wait user provider ready to use
|
|
|
|
Future.delayed(const Duration(milliseconds: 3000), () async {
|
|
|
|
if (!_ua.isAuthorized) return;
|
|
|
|
log("Registering push notifications...");
|
|
|
|
await registerPushNotifications();
|
2024-11-23 04:52:13 +00:00
|
|
|
log("Registered push notification subscriber successfully!");
|
2024-11-21 14:55:00 +00:00
|
|
|
});
|
2024-11-21 14:10:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> registerPushNotifications() async {
|
2024-12-08 13:24:06 +00:00
|
|
|
if (kIsWeb || Platform.isWindows || Platform.isLinux) return;
|
2024-11-21 14:10:12 +00:00
|
|
|
if (!_ua.isAuthorized) return;
|
|
|
|
|
2024-12-08 13:24:06 +00:00
|
|
|
await FirebaseMessaging.instance.requestPermission(
|
|
|
|
alert: true,
|
|
|
|
announcement: true,
|
|
|
|
badge: true,
|
|
|
|
carPlay: false,
|
|
|
|
criticalAlert: false,
|
|
|
|
provisional: false,
|
|
|
|
sound: true,
|
|
|
|
);
|
|
|
|
|
2024-11-21 14:10:12 +00:00
|
|
|
late final String? token;
|
|
|
|
late final String provider;
|
|
|
|
var deviceUuid = await FlutterUdid.consistentUdid;
|
|
|
|
|
|
|
|
if (deviceUuid.isEmpty) {
|
|
|
|
log("Unable to active push notifications, couldn't get device uuid");
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
log('Device UUID is $deviceUuid');
|
|
|
|
log('Registering device push notifications...');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Platform.isIOS || Platform.isMacOS) {
|
2024-11-26 13:48:04 +00:00
|
|
|
provider = 'apns';
|
2024-11-21 14:10:12 +00:00
|
|
|
token = await FirebaseMessaging.instance.getAPNSToken();
|
|
|
|
} else {
|
2024-11-26 13:48:04 +00:00
|
|
|
provider = 'fcm';
|
2024-11-21 14:10:12 +00:00
|
|
|
token = await FirebaseMessaging.instance.getToken();
|
|
|
|
}
|
|
|
|
log('Device Push Token is $token');
|
|
|
|
|
|
|
|
await _sn.client.post(
|
2024-11-23 04:52:13 +00:00
|
|
|
'/cgi/id/notifications/subscription',
|
2024-11-21 14:10:12 +00:00
|
|
|
data: {
|
|
|
|
'provider': provider,
|
|
|
|
'device_token': token,
|
|
|
|
'device_id': deviceUuid,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|