72 lines
2.5 KiB
Dart
72 lines
2.5 KiB
Dart
import 'dart:developer';
|
|
|
|
import 'package:firebase_messaging/firebase_messaging.dart';
|
|
|
|
import '../api/marianumconnect/queries/push_device_register/push_device_register.dart';
|
|
import '../api/marianumconnect/queries/push_device_unregister/push_device_unregister.dart';
|
|
import '../utils/random_id.dart';
|
|
import 'push_device_info.dart';
|
|
import 'push_secure_storage.dart';
|
|
|
|
/// Push registration for accounts without Nextcloud (guardians): the device
|
|
/// registers straight with MarianumConnect and only receives its direct
|
|
/// pushes (newsletter, widget refresh, later guardian messages). Nextcloud
|
|
/// normally supplies the device identifier; here a random one is kept per
|
|
/// install.
|
|
class DirectPushRegistration {
|
|
static const String registrationType = 'direct';
|
|
static const _deviceIdentifierKey = 'push_direct_device_identifier';
|
|
|
|
final FlutterSecureStorageLike _storage;
|
|
|
|
const DirectPushRegistration({
|
|
FlutterSecureStorageLike storage = const PushSecureStorage(),
|
|
}) : _storage = storage;
|
|
|
|
Future<bool> register() async {
|
|
try {
|
|
final (fcmToken, appVersion, identifier) = await (
|
|
FirebaseMessaging.instance.getToken(),
|
|
pushAppVersion(),
|
|
deviceIdentifier(),
|
|
).wait;
|
|
if (fcmToken == null || fcmToken.isEmpty) {
|
|
log('Push (direct): no FCM token, skipping registration');
|
|
return false;
|
|
}
|
|
await PushDeviceRegister().run(
|
|
deviceIdentifier: identifier,
|
|
pushToken: fcmToken,
|
|
platform: pushPlatform,
|
|
registrationType: registrationType,
|
|
appVersion: appVersion,
|
|
);
|
|
return true;
|
|
} on Object catch (e) {
|
|
log('Push (direct): registration failed: $e');
|
|
return false;
|
|
}
|
|
}
|
|
|
|
Future<void> unregister() async {
|
|
final identifier = await _storage.read(key: _deviceIdentifierKey);
|
|
if (identifier == null) return;
|
|
try {
|
|
await PushDeviceUnregister().run(deviceIdentifier: identifier);
|
|
} on Object catch (e) {
|
|
log('Push (direct): unregister failed: $e');
|
|
}
|
|
await _storage.delete(key: _deviceIdentifierKey);
|
|
}
|
|
|
|
/// Stable per install until [unregister], so re-registrations upsert the
|
|
/// same server row instead of piling up devices.
|
|
Future<String> deviceIdentifier() async {
|
|
final stored = await _storage.read(key: _deviceIdentifierKey);
|
|
if (stored != null && stored.isNotEmpty) return stored;
|
|
final fresh = randomHexId();
|
|
await _storage.write(key: _deviceIdentifierKey, value: fresh);
|
|
return fresh;
|
|
}
|
|
}
|