/*
* Copyright (c) 2024-2026 Fabian Freund.
*
* This file is part of WebLibre
* (see https://weblibre.eu).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
import 'dart:async';
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'providers.g.dart';
@Riverpod(keepAlive: true)
GeckoPushService pushService(Ref ref) {
final service = GeckoPushService();
service.setUp();
ref.onDispose(() {
unawaited(service.dispose());
});
return service;
}
/// Current distributor selection and availability.
///
/// Re-reads native state whenever the distributor acknowledges registration or
/// is uninstalled, so a distributor removed while this screen is open does not
/// leave a stale "configured" reading on screen.
///
/// The native event stream is subscribed to *before* the initial snapshot is
/// requested: `statusChanges` does not replay, so a PENDING → READY transition
/// landing between the two would otherwise be lost and leave the screen stale.
/// If an event wins that race the snapshot is discarded rather than emitted
/// after it, since the snapshot is by then the older value.
@riverpod
Stream pushStatus(Ref ref) {
final service = ref.watch(pushServiceProvider);
final controller = StreamController();
var sawEvent = false;
final subscription = service.statusChanges.listen(
(status) {
sawEvent = true;
if (!controller.isClosed) {
controller.add(status);
}
},
onError: (Object error, StackTrace stackTrace) {
if (!controller.isClosed) {
controller.addError(error, stackTrace);
}
},
);
unawaited(
service
.getPushStatus()
.then((status) {
if (!sawEvent && !controller.isClosed) {
controller.add(status);
}
})
.onError