import "dart:io"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:intl/intl.dart"; import "package:nexus/main.dart"; import "package:nexus/controllers/client.dart"; import "package:nexus/controllers/client_state.dart"; import "package:nexus/models/requests/register_pusher.dart"; import "package:unifiedpush/unifiedpush.dart"; import "package:unifiedpush_storage_shared_preferences/storage.dart"; class UnifiedPushController extends AsyncNotifier { @override Future build() async { final registered = await UnifiedPush.initialize( linuxOptions: .new( dbusName: "nexus.federated.nexus", storage: UnifiedPushStorageSharedPreferences(), background: isInBackground, ), onNewEndpoint: (endpoint, instance) async { final client = ref.watch(ClientController.provider.notifier); await client.registerPusher( .new( appDisplayName: "Nexus", appId: "nexus.federated.nexus", data: PusherData.webPush( url: Uri.parse(endpoint.url), auth: endpoint.pubKeySet!.auth, ), deviceDisplayName: "Nexus on ${toBeginningOfSentenceCase(Platform.operatingSystem)}", kind: .webPush, lang: "en", pushKey: endpoint.pubKeySet!.pubKey, ), ); }, onMessage: (message, instance) async { print(message); // TODO: Handle incoming message }, onRegistrationFailed: (e, r) { throw "e"; }, onUnregistered: (_) { throw "r"; }, onTempUnavailable: (_) { throw "t"; }, ); if (registered) { // Needs to be registered every startup await register(true); } return registered; } Future register([bool alreadyRegistered = false]) async { final clientState = ref.watch(ClientStateController.provider); if (clientState?.deviceId == null) ref.invalidateSelf(); final capabilities = await ref .watch(ClientController.provider.notifier) .getCapabilities(); if (capabilities.webpush?.vapid == null) { throw UnsupportedError( "Your homeserver does not support MSC4174 (Web Push), and therefore cannot send notifications to Nexus.", ); } if (!alreadyRegistered && !await UnifiedPush.tryUseCurrentOrDefaultDistributor()) { throw Exception("No UnifiedPush distributors found"); } await UnifiedPush.register( instance: clientState!.deviceId!, vapid: capabilities.webpush?.vapid, ); if (!alreadyRegistered) ref.invalidateSelf(); } static final provider = AsyncNotifierProvider( UnifiedPushController.new, ); }