fix(compras): revocar el PRO tras un reembolso sin penalizar a quien pago
Verificacion silenciosa en segundo plano con queryPastPurchases, al abrir o volver a la app y al cargar Android Auto. Solo revoca tras dos respuestas validas de Play sin la compra separadas 12h; sin red o con error no toca nada. Reactiva el PRO automaticamente si Play confirma la compra.
This commit is contained in:
@@ -205,6 +205,10 @@ class _PaginaPrincipalState extends State<_PaginaPrincipal>
|
||||
// without a live native sink. Re-subscribe and re-seed the active device
|
||||
// (no-op when multi-device EQ is off).
|
||||
unawaited(context.read<EstadoEcualizador>().refrescarDispositivoActual());
|
||||
// Silent, throttled license re-verification (refund revocation) and a
|
||||
// re-sync with any change the Android Auto path persisted meanwhile.
|
||||
// Fire-and-forget: never delays the resume, never shows anything.
|
||||
unawaited(context.read<EstadoEntitlement>().refrescarLicencia());
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -5,12 +5,14 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../servicios/servicio_audio.dart' show invalidarArbolAuto;
|
||||
import '../servicios/servicio_compras.dart';
|
||||
import '../servicios/verificacion_licencia.dart';
|
||||
|
||||
/// Versioned persistence key (Design ADR-1) for the permanent, non-consumable
|
||||
/// premium unlock. Older builds that predate this key simply never read it —
|
||||
/// no migration needed (Rollout "Versioned key ... is ignored by older
|
||||
/// builds").
|
||||
const _keyPremium = 'compra_premium_v1';
|
||||
/// builds"). Shared with the silent license re-verification
|
||||
/// (`verificacion_licencia.dart`), which may revoke it after a refund.
|
||||
const _keyPremium = claveCompraPremium;
|
||||
|
||||
/// Headless-safe entitlement read (Design ADR-1, Spec "Headless-Safe
|
||||
/// Entitlement Read"): resolves the persisted premium flag directly from
|
||||
@@ -55,14 +57,21 @@ enum ResultadoEntitlementUsuario {
|
||||
/// this; headless callers (Android Auto) use [esPremiumPersistido] instead,
|
||||
/// since no `Provider` exists on that path.
|
||||
class EstadoEntitlement extends ChangeNotifier {
|
||||
EstadoEntitlement({SharedPreferences? prefs, PuertoCompras? compras})
|
||||
: _prefs = prefs,
|
||||
_compras = compras {
|
||||
EstadoEntitlement({
|
||||
SharedPreferences? prefs,
|
||||
PuertoCompras? compras,
|
||||
DateTime Function()? reloj,
|
||||
}) : _prefs = prefs,
|
||||
_compras = compras,
|
||||
_reloj = reloj {
|
||||
final flujo = _compras;
|
||||
if (flujo != null) {
|
||||
_comprasSub = flujo.eventos.listen(_alRecibirEvento);
|
||||
}
|
||||
_cargar();
|
||||
// The silent license check is chained AFTER the load and never awaited
|
||||
// by anyone: the persisted flag is served immediately, exactly as
|
||||
// before, and the check can only adjust it later, in the background.
|
||||
unawaited(_cargar().then((_) => _verificarLicencia()));
|
||||
}
|
||||
|
||||
/// The single non-consumable product id (Design "Interfaces / Contracts"),
|
||||
@@ -72,7 +81,11 @@ class EstadoEntitlement extends ChangeNotifier {
|
||||
|
||||
final SharedPreferences? _prefs;
|
||||
final PuertoCompras? _compras;
|
||||
|
||||
/// Injectable clock for the license check's throttle/spacing rules.
|
||||
final DateTime Function()? _reloj;
|
||||
StreamSubscription<EventoCompra>? _comprasSub;
|
||||
bool _desechado = false;
|
||||
|
||||
bool _esPremium = false;
|
||||
bool _compraEnCurso = false;
|
||||
@@ -106,6 +119,53 @@ class EstadoEntitlement extends ChangeNotifier {
|
||||
Future<SharedPreferences> _resolverPrefs() async =>
|
||||
_prefs ?? SharedPreferences.getInstance();
|
||||
|
||||
/// Fire-and-forget hook for app resume: re-syncs with the persisted flag
|
||||
/// (the Android Auto path may have changed it) and runs the throttled
|
||||
/// silent license check. Never throws, never touches [compraEnCurso] or
|
||||
/// [resultadoUsuario].
|
||||
Future<void> refrescarLicencia() async {
|
||||
try {
|
||||
_sincronizarConPrefs(await _resolverPrefs());
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][licencia] refresco fallido $e');
|
||||
}
|
||||
await _verificarLicencia();
|
||||
}
|
||||
|
||||
/// Runs [verificarLicencia] against the purchase port and mirrors any
|
||||
/// change of the persisted flag. Silent by construction: it only ever
|
||||
/// updates [esPremium] and notifies — no purchase-stream event, no
|
||||
/// [resultadoUsuario], no [compraEnCurso].
|
||||
Future<void> _verificarLicencia() async {
|
||||
final compras = _compras;
|
||||
if (compras == null || _desechado) return;
|
||||
try {
|
||||
final prefs = await _resolverPrefs();
|
||||
await verificarLicencia(
|
||||
consultar: compras.consultarPropiedad,
|
||||
prefs: prefs,
|
||||
reloj: _reloj,
|
||||
);
|
||||
_sincronizarConPrefs(prefs);
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][licencia] verificacion fallida $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Aligns [esPremium] with the persisted flag. Safe against a racing
|
||||
/// [_desbloquear]: that one writes the prefs cache in the same synchronous
|
||||
/// block where it flips [_esPremium], so both always agree here.
|
||||
void _sincronizarConPrefs(SharedPreferences prefs) {
|
||||
if (_desechado) return;
|
||||
final premium = prefs.getBool(_keyPremium) ?? false;
|
||||
if (premium == _esPremium) return;
|
||||
_esPremium = premium;
|
||||
notifyListeners();
|
||||
// Either direction changes what the car may show (local music is
|
||||
// premium-gated), so the cached Android Auto tree is stale both ways.
|
||||
invalidarArbolAuto();
|
||||
}
|
||||
|
||||
/// Starts the purchase flow (Spec "Successful purchase"). A no-op when
|
||||
/// already premium (Spec "Already-purchased attempt is idempotent") — no
|
||||
/// duplicate charge is even attempted.
|
||||
@@ -171,11 +231,19 @@ class EstadoEntitlement extends ChangeNotifier {
|
||||
}
|
||||
|
||||
Future<void> _desbloquear() async {
|
||||
// Prefs resolved FIRST so the in-memory flip and the prefs-cache write
|
||||
// below happen in one synchronous block (`setBool` updates the cache
|
||||
// before awaiting the platform) — [_sincronizarConPrefs] can never
|
||||
// observe one without the other.
|
||||
final prefs = await _resolverPrefs();
|
||||
final yaEraPremium = _esPremium;
|
||||
_esPremium = true;
|
||||
_compraEnCurso = false;
|
||||
final prefs = await _resolverPrefs();
|
||||
await prefs.setBool(_keyPremium, true);
|
||||
final escritura = prefs.setBool(_keyPremium, true);
|
||||
// A real purchase/restore is fresh proof of ownership: drop any stale
|
||||
// absence streak of the silent license check.
|
||||
await reiniciarAusenciasLicencia(prefs);
|
||||
await escritura;
|
||||
notifyListeners();
|
||||
if (!yaEraPremium) {
|
||||
// Orchestrator-resolved open question (design.md): actively
|
||||
@@ -187,6 +255,7 @@ class EstadoEntitlement extends ChangeNotifier {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_desechado = true;
|
||||
_comprasSub?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
+12
-2
@@ -20,6 +20,7 @@ import 'servicios/servicio_compras.dart';
|
||||
import 'servicios/servicio_consentimiento.dart';
|
||||
import 'servicios/servicio_ecualizador.dart';
|
||||
import 'servicios/servicio_presets_personalizados.dart';
|
||||
import 'servicios/verificacion_licencia.dart';
|
||||
import 'tema/pluriwave_tokens.dart';
|
||||
|
||||
const _anchoMinimoLandscape = 600.0;
|
||||
@@ -146,6 +147,16 @@ Future<void> main() async {
|
||||
// injected into every state/service below.
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
// Silent license re-verification (refund revocation) for the Android Auto
|
||||
// path: this engine may be the headless one, with no widget tree and so no
|
||||
// `EstadoEntitlement`. The browse root triggers it fire-and-forget; the
|
||||
// shared in-flight guard in `verificarLicencia` keeps it to one query at a
|
||||
// time even when the phone UI checks too.
|
||||
registrarVerificacionLicenciaAuto(
|
||||
() =>
|
||||
verificarLicencia(consultar: compras.consultarPropiedad, prefs: prefs),
|
||||
);
|
||||
|
||||
// User-saved EQ presets for the car's Ecualizador folder, same
|
||||
// injectable-prefs DI convention and same pre-init placement as the two
|
||||
// registrations above (neither depends on the AudioHandler). Passed as a
|
||||
@@ -354,8 +365,7 @@ bool debeInvalidarArbolAutoAlReanudar({
|
||||
required AppLifecycleState estado,
|
||||
required bool hayCocheSuscrito,
|
||||
required bool yaInvalidado,
|
||||
}) =>
|
||||
!yaInvalidado && hayCocheSuscrito && estado == AppLifecycleState.resumed;
|
||||
}) => !yaInvalidado && hayCocheSuscrito && estado == AppLifecycleState.resumed;
|
||||
|
||||
/// Root wrapper that keeps the orientation policy applied and owns the
|
||||
/// Android Auto browse-tree recovery hook.
|
||||
|
||||
@@ -20,6 +20,7 @@ import 'emisoras_destacadas.dart';
|
||||
import 'musica_local_auto.dart';
|
||||
import 'navegacion_auto.dart';
|
||||
import 'servicio_audio_session.dart';
|
||||
import 'verificacion_licencia.dart' show CambioLicencia;
|
||||
|
||||
/// Estado de reproducción expuesto al UI.
|
||||
enum EstadoReproduccion {
|
||||
@@ -383,6 +384,36 @@ void invalidarArbolAuto() {
|
||||
_invalidarArbolAutoGlobal?.call();
|
||||
}
|
||||
|
||||
/// Silent license re-verification for the headless Android Auto engine,
|
||||
/// registered from `main.dart` (it owns the purchase port and the prefs).
|
||||
/// `null` until registered — [dispararVerificacionLicenciaAuto] is then a
|
||||
/// no-op.
|
||||
Future<CambioLicencia> Function()? _verificarLicenciaAutoGlobal;
|
||||
|
||||
/// Registers (or, with `null`, clears) the verification
|
||||
/// [dispararVerificacionLicenciaAuto] runs. Module-level like every other
|
||||
/// `registrar*` seam here, so tests need no real handler.
|
||||
void registrarVerificacionLicenciaAuto(
|
||||
Future<CambioLicencia> Function()? verificar,
|
||||
) {
|
||||
_verificarLicenciaAutoGlobal = verificar;
|
||||
}
|
||||
|
||||
/// Runs the registered license check and, if it changed the persisted flag
|
||||
/// in either direction, invalidates the cached car tree (local music is
|
||||
/// premium-gated). Never throws. The browse path calls it UNAWAITED so a
|
||||
/// head unit's browse answer is never delayed by a Play query.
|
||||
Future<void> dispararVerificacionLicenciaAuto() async {
|
||||
final verificar = _verificarLicenciaAutoGlobal;
|
||||
if (verificar == null) return;
|
||||
try {
|
||||
final cambio = await verificar();
|
||||
if (cambio != CambioLicencia.sinCambios) invalidarArbolAuto();
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][licencia] verificacion Auto fallida $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a head unit has actually SUBSCRIBED to at least one browse id on
|
||||
/// the live handler (fix/android-auto-musica-local, item 4 — corrected).
|
||||
///
|
||||
@@ -3472,6 +3503,13 @@ class PluriWaveAudioHandler extends BaseAudioHandler
|
||||
// [resolverLocalizacionesRespaldo], so this works on the engine
|
||||
// Android Auto starts without an Activity -- which is the only engine
|
||||
// a Play reviewer ever gets.
|
||||
// Silent license re-verification (refund revocation), on the root
|
||||
// only — every car connection asks for it — and fire-and-forget: the
|
||||
// browse answer below is served from the persisted flag right away,
|
||||
// and the check is throttled to at most once a day.
|
||||
if (parentMediaId == AudioService.browsableRootId) {
|
||||
unawaited(dispararVerificacionLicenciaAuto());
|
||||
}
|
||||
final etiquetas = etiquetasArbolAutoDesde(_textos);
|
||||
final constructor = ConstructorArbolAuto(etiquetas: etiquetas);
|
||||
// The "recent" root, resolved BEFORE the entitlement gate.
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrint;
|
||||
import 'package:in_app_purchase/in_app_purchase.dart';
|
||||
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
|
||||
|
||||
/// Outcome kinds the purchase stream can report (Design ADR-2). Mirrors
|
||||
/// `in_app_purchase`'s [PurchaseStatus] but stays a PluriWave-owned type so
|
||||
@@ -38,6 +39,25 @@ class EventoCompra {
|
||||
final String? mensaje;
|
||||
}
|
||||
|
||||
/// Outcome of the SILENT ownership query ([PuertoCompras.consultarPropiedad])
|
||||
/// used to re-verify the persisted premium flag (refund revocation).
|
||||
///
|
||||
/// Only [poseida] and [noPoseida] are definitive answers from Play; anything
|
||||
/// that is not a clean answer (offline, billing unavailable, query error,
|
||||
/// exception, timeout, pending purchase) is [desconocido], which the
|
||||
/// verification policy treats as "change nothing" (fail-open, ADR-2).
|
||||
enum ResultadoVerificacionLicencia {
|
||||
/// Play reports the premium product as purchased on this account.
|
||||
poseida,
|
||||
|
||||
/// Play answered successfully and the premium product is NOT among the
|
||||
/// account's purchases (e.g. refunded or revoked).
|
||||
noPoseida,
|
||||
|
||||
/// No trustworthy answer — never used to revoke.
|
||||
desconocido,
|
||||
}
|
||||
|
||||
/// Purchase I/O abstraction (Design ADR-2): [EstadoEntitlement] depends on
|
||||
/// this port, never on `in_app_purchase` directly — matches
|
||||
/// `EstadoAlarmas(android: PuertoAlarmasAndroid)`'s injection shape, and
|
||||
@@ -55,13 +75,24 @@ abstract class PuertoCompras {
|
||||
|
||||
/// Re-queries Play Billing for a prior purchase on this account.
|
||||
Future<void> restaurar();
|
||||
|
||||
/// Silently asks the store whether this account currently owns the
|
||||
/// premium product. Unlike [restaurar], it NEVER emits on [eventos] (the
|
||||
/// premium sheet listens there) and never throws: every failure maps to
|
||||
/// [ResultadoVerificacionLicencia.desconocido].
|
||||
Future<ResultadoVerificacionLicencia> consultarPropiedad();
|
||||
}
|
||||
|
||||
/// The SOLE `in_app_purchase` call site (Design ADR-2) — every other file
|
||||
/// depends on [PuertoCompras] instead.
|
||||
class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
ServicioComprasPlayBilling({InAppPurchase? inAppPurchase})
|
||||
: _iap = inAppPurchase ?? InAppPurchase.instance {
|
||||
ServicioComprasPlayBilling({
|
||||
InAppPurchase? inAppPurchase,
|
||||
Future<QueryPurchaseDetailsResponse> Function()? consultarComprasPasadas,
|
||||
Duration limiteConsultaPropiedad = const Duration(seconds: 10),
|
||||
}) : _iap = inAppPurchase ?? InAppPurchase.instance,
|
||||
_consultarComprasPasadasInyectada = consultarComprasPasadas,
|
||||
_limiteConsultaPropiedad = limiteConsultaPropiedad {
|
||||
_sub = _iap.purchaseStream.listen(
|
||||
_alRecibirCompras,
|
||||
onError: (Object error) {
|
||||
@@ -77,6 +108,15 @@ class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
static const idProducto = 'pluriwave_premium';
|
||||
|
||||
final InAppPurchase _iap;
|
||||
|
||||
/// Test seam for [consultarPropiedad]; `null` in production, where the
|
||||
/// Android platform addition's `queryPastPurchases` is used.
|
||||
final Future<QueryPurchaseDetailsResponse> Function()?
|
||||
_consultarComprasPasadasInyectada;
|
||||
|
||||
/// Upper bound for [consultarPropiedad]: a hung BillingClient connection
|
||||
/// resolves to [ResultadoVerificacionLicencia.desconocido].
|
||||
final Duration _limiteConsultaPropiedad;
|
||||
final _eventos = StreamController<EventoCompra>.broadcast();
|
||||
StreamSubscription<List<PurchaseDetails>>? _sub;
|
||||
|
||||
@@ -125,6 +165,33 @@ class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ResultadoVerificacionLicencia> consultarPropiedad() async {
|
||||
try {
|
||||
final disponible = await _iap.isAvailable().timeout(
|
||||
_limiteConsultaPropiedad,
|
||||
);
|
||||
if (!disponible) return ResultadoVerificacionLicencia.desconocido;
|
||||
final consultar =
|
||||
_consultarComprasPasadasInyectada ??
|
||||
() =>
|
||||
_iap
|
||||
.getPlatformAddition<InAppPurchaseAndroidPlatformAddition>()
|
||||
.queryPastPurchases();
|
||||
// `queryPastPurchases` reads the account's purchases straight from
|
||||
// the BillingClient: unlike `restorePurchases` it does NOT push them
|
||||
// into `purchaseStream`, so the premium sheet never sees this check.
|
||||
final respuesta = await consultar().timeout(_limiteConsultaPropiedad);
|
||||
return resultadoDesdeComprasPasadas(
|
||||
respuesta.pastPurchases,
|
||||
conError: respuesta.error != null,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][compras] consultarPropiedad -> desconocido $e');
|
||||
return ResultadoVerificacionLicencia.desconocido;
|
||||
}
|
||||
}
|
||||
|
||||
void _alRecibirCompras(List<PurchaseDetails> compras) {
|
||||
if (compras.isEmpty) {
|
||||
// `restorePurchases()` with nothing to restore pushes an EMPTY batch
|
||||
@@ -176,6 +243,33 @@ EventoCompra eventoDesdeEstadoCompra(PurchaseStatus status, {String? mensaje}) {
|
||||
};
|
||||
}
|
||||
|
||||
/// Pure mapping from a `queryPastPurchases` answer to the typed ownership
|
||||
/// result (same port-boundary rationale as [eventoDesdeEstadoCompra]).
|
||||
///
|
||||
/// The premium product present as purchased/restored is proof of ownership
|
||||
/// even when the answer also carries an error (the query spans in-app AND
|
||||
/// subscriptions, and a failure of the latter is irrelevant here). A pending
|
||||
/// entry is not a clean answer. Absence only counts as [noPoseida] when the
|
||||
/// query succeeded without error.
|
||||
ResultadoVerificacionLicencia resultadoDesdeComprasPasadas(
|
||||
List<PurchaseDetails> compras, {
|
||||
required bool conError,
|
||||
}) {
|
||||
final delProducto = compras.where(
|
||||
(c) => c.productID == ServicioComprasPlayBilling.idProducto,
|
||||
);
|
||||
final comprada = delProducto.any(
|
||||
(c) =>
|
||||
c.status == PurchaseStatus.purchased ||
|
||||
c.status == PurchaseStatus.restored,
|
||||
);
|
||||
if (comprada) return ResultadoVerificacionLicencia.poseida;
|
||||
if (conError || delProducto.isNotEmpty) {
|
||||
return ResultadoVerificacionLicencia.desconocido;
|
||||
}
|
||||
return ResultadoVerificacionLicencia.noPoseida;
|
||||
}
|
||||
|
||||
extension<T> on List<T> {
|
||||
T? get firstOrNull => isEmpty ? null : first;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrint;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'servicio_compras.dart';
|
||||
|
||||
export 'servicio_compras.dart' show ResultadoVerificacionLicencia;
|
||||
|
||||
/// Versioned persistence key (Design ADR-1) of the permanent, non-consumable
|
||||
/// premium unlock. Owned here so the headless verification below and
|
||||
/// `EstadoEntitlement` read/write exactly ONE key.
|
||||
const claveCompraPremium = 'compra_premium_v1';
|
||||
|
||||
/// Epoch millis of the last verification that got a DEFINITIVE answer
|
||||
/// ([ResultadoVerificacionLicencia.poseida] / [noPoseida]).
|
||||
const claveUltimaVerificacionLicencia = 'licencia_ultima_verificacion_ms';
|
||||
|
||||
/// Epoch millis of the last ATTEMPT, whatever its outcome.
|
||||
const claveUltimoIntentoLicencia = 'licencia_ultimo_intento_ms';
|
||||
|
||||
/// Consecutive definitive "not owned" answers while the flag was premium.
|
||||
const claveAusenciasLicencia = 'licencia_ausencias_consecutivas';
|
||||
|
||||
/// Epoch millis of the FIRST absence of the current streak.
|
||||
const clavePrimeraAusenciaLicencia = 'licencia_primera_ausencia_ms';
|
||||
|
||||
/// After a definitive answer, Play is not asked again for this long.
|
||||
const intervaloVerificacionLicencia = Duration(hours: 24);
|
||||
|
||||
/// After an attempt without a definitive answer (offline, billing
|
||||
/// unavailable, error), the retry waits at least this long, so resuming the
|
||||
/// app or reconnecting the car while offline never hammers Play.
|
||||
const intervaloReintentoLicencia = Duration(hours: 1);
|
||||
|
||||
/// Minimum time between the first absence and the one that confirms it —
|
||||
/// a transient empty Play Store cache must never revoke a paying user.
|
||||
const separacionMinimaAusencias = Duration(hours: 12);
|
||||
|
||||
/// Definitive absences required (spaced by [separacionMinimaAusencias])
|
||||
/// before the premium flag is revoked.
|
||||
const ausenciasParaRevocar = 2;
|
||||
|
||||
/// What a [verificarLicencia] run changed in the persisted flag.
|
||||
enum CambioLicencia {
|
||||
/// Nothing changed (throttled, unknown answer, or state already right).
|
||||
sinCambios,
|
||||
|
||||
/// The flag went false -> true (e.g. a reinstall of a paying user).
|
||||
desbloqueada,
|
||||
|
||||
/// The flag went true -> false (refund confirmed twice, spaced apart).
|
||||
revocada,
|
||||
}
|
||||
|
||||
/// The run currently in flight, shared by every caller in this isolate
|
||||
/// (phone UI and Android Auto), so only ONE ownership query runs at a time.
|
||||
Future<CambioLicencia>? _verificacionEnCurso;
|
||||
|
||||
/// Silent, headless-safe license re-verification (refund revocation).
|
||||
///
|
||||
/// No `BuildContext`, no purchase-stream events, never throws, and every
|
||||
/// non-definitive outcome leaves the persisted state untouched (fail-open,
|
||||
/// ADR-2) — PRO is never removed for lack of connectivity. Callers fire and
|
||||
/// forget it; it must never sit on a startup or browse path.
|
||||
///
|
||||
/// Rules:
|
||||
/// * throttled by [intervaloVerificacionLicencia] after a definitive answer
|
||||
/// and by [intervaloReintentoLicencia] after any attempt; a clock that
|
||||
/// went backwards never blocks it;
|
||||
/// * [ResultadoVerificacionLicencia.poseida]: flag forced to `true` (silent
|
||||
/// unlock if it was `false`), absence streak cleared;
|
||||
/// * [ResultadoVerificacionLicencia.noPoseida] with the flag `true`: the
|
||||
/// streak grows, and the flag is revoked only once it reaches
|
||||
/// [ausenciasParaRevocar] AND at least [separacionMinimaAusencias] passed
|
||||
/// since its first absence; with the flag `false` there is nothing to do;
|
||||
/// * [ResultadoVerificacionLicencia.desconocido] (or an exception): nothing
|
||||
/// changes, not even the streak.
|
||||
Future<CambioLicencia> verificarLicencia({
|
||||
required Future<ResultadoVerificacionLicencia> Function() consultar,
|
||||
SharedPreferences? prefs,
|
||||
DateTime Function()? reloj,
|
||||
}) {
|
||||
final enCurso = _verificacionEnCurso;
|
||||
if (enCurso != null) return enCurso;
|
||||
final ejecucion = _verificar(
|
||||
consultar: consultar,
|
||||
prefs: prefs,
|
||||
reloj: reloj ?? DateTime.now,
|
||||
);
|
||||
_verificacionEnCurso = ejecucion;
|
||||
unawaited(
|
||||
ejecucion.whenComplete(() {
|
||||
if (identical(_verificacionEnCurso, ejecucion)) {
|
||||
_verificacionEnCurso = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return ejecucion;
|
||||
}
|
||||
|
||||
/// Clears the absence streak — a real purchase/restore is fresh proof of
|
||||
/// ownership, so a stale streak must not survive it.
|
||||
Future<void> reiniciarAusenciasLicencia(SharedPreferences prefs) async {
|
||||
await prefs.remove(claveAusenciasLicencia);
|
||||
await prefs.remove(clavePrimeraAusenciaLicencia);
|
||||
}
|
||||
|
||||
Future<CambioLicencia> _verificar({
|
||||
required Future<ResultadoVerificacionLicencia> Function() consultar,
|
||||
required SharedPreferences? prefs,
|
||||
required DateTime Function() reloj,
|
||||
}) async {
|
||||
try {
|
||||
final p = prefs ?? await SharedPreferences.getInstance();
|
||||
final ahora = reloj();
|
||||
if (_dentroDeVentana(
|
||||
p,
|
||||
claveUltimaVerificacionLicencia,
|
||||
ahora,
|
||||
intervaloVerificacionLicencia,
|
||||
) ||
|
||||
_dentroDeVentana(
|
||||
p,
|
||||
claveUltimoIntentoLicencia,
|
||||
ahora,
|
||||
intervaloReintentoLicencia,
|
||||
)) {
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
await p.setInt(claveUltimoIntentoLicencia, ahora.millisecondsSinceEpoch);
|
||||
|
||||
ResultadoVerificacionLicencia resultado;
|
||||
try {
|
||||
resultado = await consultar();
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][licencia] consulta fallida -> sin cambios $e');
|
||||
resultado = ResultadoVerificacionLicencia.desconocido;
|
||||
}
|
||||
|
||||
switch (resultado) {
|
||||
case ResultadoVerificacionLicencia.desconocido:
|
||||
return CambioLicencia.sinCambios;
|
||||
case ResultadoVerificacionLicencia.poseida:
|
||||
await p.setInt(
|
||||
claveUltimaVerificacionLicencia,
|
||||
ahora.millisecondsSinceEpoch,
|
||||
);
|
||||
await reiniciarAusenciasLicencia(p);
|
||||
if (p.getBool(claveCompraPremium) ?? false) {
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
await p.setBool(claveCompraPremium, true);
|
||||
return CambioLicencia.desbloqueada;
|
||||
case ResultadoVerificacionLicencia.noPoseida:
|
||||
await p.setInt(
|
||||
claveUltimaVerificacionLicencia,
|
||||
ahora.millisecondsSinceEpoch,
|
||||
);
|
||||
if (!(p.getBool(claveCompraPremium) ?? false)) {
|
||||
await reiniciarAusenciasLicencia(p);
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
return _registrarAusencia(p, ahora);
|
||||
}
|
||||
} catch (e) {
|
||||
// Fail-open (ADR-2): a prefs failure never touches the entitlement.
|
||||
debugPrint('[PluriWave][licencia] verificacion fallida -> sin cambios $e');
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
}
|
||||
|
||||
Future<CambioLicencia> _registrarAusencia(
|
||||
SharedPreferences p,
|
||||
DateTime ahora,
|
||||
) async {
|
||||
final ausencias = (p.getInt(claveAusenciasLicencia) ?? 0) + 1;
|
||||
final primeraMs = p.getInt(clavePrimeraAusenciaLicencia);
|
||||
if (primeraMs == null || ausencias == 1) {
|
||||
await p.setInt(claveAusenciasLicencia, 1);
|
||||
await p.setInt(clavePrimeraAusenciaLicencia, ahora.millisecondsSinceEpoch);
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
final separacion = ahora.difference(
|
||||
DateTime.fromMillisecondsSinceEpoch(primeraMs),
|
||||
);
|
||||
if (separacion.isNegative) {
|
||||
// The clock went backwards: restart the spacing from now (delays the
|
||||
// revocation, never hastens it).
|
||||
await p.setInt(clavePrimeraAusenciaLicencia, ahora.millisecondsSinceEpoch);
|
||||
await p.setInt(claveAusenciasLicencia, ausencias);
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
if (ausencias >= ausenciasParaRevocar &&
|
||||
separacion >= separacionMinimaAusencias) {
|
||||
await p.setBool(claveCompraPremium, false);
|
||||
await reiniciarAusenciasLicencia(p);
|
||||
return CambioLicencia.revocada;
|
||||
}
|
||||
await p.setInt(claveAusenciasLicencia, ausencias);
|
||||
return CambioLicencia.sinCambios;
|
||||
}
|
||||
|
||||
/// Whether [clave]'s timestamp is less than [ventana] before [ahora]. A
|
||||
/// timestamp in the future (clock moved backwards) does NOT throttle.
|
||||
bool _dentroDeVentana(
|
||||
SharedPreferences p,
|
||||
String clave,
|
||||
DateTime ahora,
|
||||
Duration ventana,
|
||||
) {
|
||||
final ms = p.getInt(clave);
|
||||
if (ms == null) return false;
|
||||
final transcurrido = ahora.difference(
|
||||
DateTime.fromMillisecondsSinceEpoch(ms),
|
||||
);
|
||||
return !transcurrido.isNegative && transcurrido < ventana;
|
||||
}
|
||||
Reference in New Issue
Block a user