local pro version without needing to log in

This commit is contained in:
Jonas Bark
2026-02-20 15:42:28 +01:00
parent 3ba20688d0
commit a60cf5f736
8 changed files with 90 additions and 523 deletions

View File

@@ -83,6 +83,12 @@ Future<void> recordError(
StackTrace? stack, {
required String context,
}) async {
if (kDebugMode) {
print('Error in $context: $error');
if (stack != null) {
debugPrintStack(stackTrace: stack);
}
}
await _persistCrash(
type: 'dart',
error: error.toString(),
@@ -115,16 +121,26 @@ Future<void> _persistCrash({
final fileLength = await file.length();
if (fileLength > 5 * 1024 * 1024) {
// If log file exceeds 5MB, truncate it
final lines = await file.readAsLines();
final half = lines.length ~/ 2;
final truncatedLines = lines.sublist(half);
await file.writeAsString(truncatedLines.join('\n'));
try {
final lines = file.readAsLinesSync();
final half = lines.length ~/ 2;
final truncatedLines = lines.sublist(half);
await file.writeAsString(truncatedLines.join('\n'));
} catch (e) {
if (kDebugMode) {
print('Failed to truncate log file: $e');
}
file.deleteSync();
}
}
}
await file.writeAsString(crashData.toString(), mode: FileMode.append);
core.connection.signalNotification(LogNotification('App crashed: $error'));
} catch (_) {
} catch (error) {
if (kDebugMode) {
print('Failed to write crash log: $error');
}
// Avoid throwing from the crash logger
}
}

View File

@@ -134,7 +134,7 @@ class _LoginPageState extends State<LoginPage> {
Widget _buildSignedIn(BuildContext context, Session session) {
final hasActiveSubscription = _iapManager.hasActiveSubscription;
final isPremiumEnabled = _iapManager.isPremiumEnabled;
final isPremiumEnabled = _iapManager.isProEnabled;
final isRegisteredDevice = _iapManager.entitlements.isRegisteredDevice;
return Column(
spacing: 16,
@@ -655,7 +655,7 @@ class _LoginPageState extends State<LoginPage> {
await _reloadDevicesAndEntitlements();
if (!mounted) return;
setState(() {
_statusMessage = _iapManager.isPremiumEnabled
_statusMessage = _iapManager.isProEnabled
? 'Subscription activated.'
: 'Purchase completed. Entitlement sync may take a moment.';
});

View File

@@ -7,7 +7,6 @@ import 'package:bike_control/services/device_management_service.dart';
import 'package:bike_control/services/entitlements_service.dart';
import 'package:bike_control/services/windows_subscription_service.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/iap/iap_service.dart';
import 'package:bike_control/utils/iap/revenuecat_service.dart';
import 'package:bike_control/utils/iap/windows_iap_service.dart';
import 'package:flutter/cupertino.dart';
@@ -27,7 +26,6 @@ class IAPManager {
static const String premiumMonthlyProductKey = 'premium_monthly';
static int dailyCommandLimit = 15;
IAPService? _iapService;
RevenueCatService? _revenueCatService;
WindowsIAPService? _windowsIapService;
StreamSubscription<AuthState>? _authSubscription;
@@ -44,12 +42,13 @@ class IAPManager {
);
ValueNotifier<bool> isPurchased = ValueNotifier<bool>(false);
ValueNotifier<bool> isLocalPro = ValueNotifier<bool>(false);
IAPManager._();
bool get hasActiveSubscription => entitlements.hasActive(premiumMonthlyProductKey);
bool get hasActiveSubscription => entitlements.hasActive(premiumMonthlyProductKey) || isLocalPro.value;
bool get isPremiumEnabled => hasActiveSubscription && entitlements.isRegisteredDevice;
bool get isProEnabled => hasActiveSubscription && (entitlements.isRegisteredDevice || isLocalPro.value);
DateTime? get premiumActiveUntil => entitlements.activeUntil(premiumMonthlyProductKey);
@@ -87,6 +86,7 @@ class IAPManager {
_revenueCatService = RevenueCatService(
prefs,
isPurchasedNotifier: isPurchased,
isProNotifier: isLocalPro,
getDailyCommandLimit: () => dailyCommandLimit,
setDailyCommandLimit: (limit) => dailyCommandLimit = limit,
entitlementsService: entitlements,
@@ -94,9 +94,7 @@ class IAPManager {
);
await _revenueCatService!.initialize();
} else {
debugPrint('Using legacy IAP service (no RevenueCat key)');
_iapService = IAPService(prefs);
await _iapService!.initialize();
throw UnsupportedError('Unsupported platform for IAP: ${Platform.operatingSystem}');
}
await entitlements.refresh();
@@ -124,8 +122,6 @@ class IAPManager {
bool get hasTrialStarted {
if (_revenueCatService != null) {
return _revenueCatService!.hasTrialStarted;
} else if (_iapService != null) {
return _iapService!.hasTrialStarted;
} else if (_windowsIapService != null) {
return _windowsIapService!.hasTrialStarted;
}
@@ -136,8 +132,6 @@ class IAPManager {
Future<void> startTrial() async {
if (_revenueCatService != null) {
await _revenueCatService!.startTrial();
} else if (_iapService != null) {
await _iapService!.startTrial();
}
}
@@ -145,8 +139,6 @@ class IAPManager {
int get trialDaysRemaining {
if (_revenueCatService != null) {
return _revenueCatService!.trialDaysRemaining;
} else if (_iapService != null) {
return _iapService!.trialDaysRemaining;
} else if (_windowsIapService != null) {
return _windowsIapService!.trialDaysRemaining;
}
@@ -155,13 +147,11 @@ class IAPManager {
/// Check if the trial has expired.
bool get isTrialExpired {
if (isPremiumEnabled) {
if (isProEnabled) {
return false;
}
if (_revenueCatService != null) {
return _revenueCatService!.isTrialExpired;
} else if (_iapService != null) {
return _iapService!.isTrialExpired;
} else if (_windowsIapService != null) {
return _windowsIapService!.isTrialExpired;
}
@@ -170,13 +160,11 @@ class IAPManager {
/// Check if the user can execute a command.
bool get canExecuteCommand {
if (isPremiumEnabled) return true;
if (_revenueCatService == null && _iapService == null && _windowsIapService == null) return true;
if (isProEnabled) return true;
if (_revenueCatService == null && _windowsIapService == null) return true;
if (_revenueCatService != null) {
return _revenueCatService!.canExecuteCommand;
} else if (_iapService != null) {
return _iapService!.canExecuteCommand;
} else if (_windowsIapService != null) {
return _windowsIapService!.canExecuteCommand;
}
@@ -185,13 +173,11 @@ class IAPManager {
/// Get the number of commands remaining today (for free tier after trial).
int get commandsRemainingToday {
if (isPremiumEnabled) {
if (isProEnabled) {
return -1;
}
if (_revenueCatService != null) {
return _revenueCatService!.commandsRemainingToday;
} else if (_iapService != null) {
return _iapService!.commandsRemainingToday;
} else if (_windowsIapService != null) {
return _windowsIapService!.commandsRemainingToday;
}
@@ -202,8 +188,6 @@ class IAPManager {
int get dailyCommandCount {
if (_revenueCatService != null) {
return _revenueCatService!.dailyCommandCount;
} else if (_iapService != null) {
return _iapService!.dailyCommandCount;
} else if (_windowsIapService != null) {
return _windowsIapService!.dailyCommandCount;
}
@@ -212,13 +196,11 @@ class IAPManager {
/// Increment the daily command count.
Future<void> incrementCommandCount() async {
if (isPremiumEnabled) {
if (isProEnabled) {
return;
}
if (_revenueCatService != null) {
await _revenueCatService!.incrementCommandCount();
} else if (_iapService != null) {
await _iapService!.incrementCommandCount();
} else if (_windowsIapService != null) {
await _windowsIapService!.incrementCommandCount();
}
@@ -228,10 +210,10 @@ class IAPManager {
String getStatusMessage() {
if (kIsWeb) {
return "Web";
} else if (isPremiumEnabled || IAPManager.instance.isPurchased.value) {
} else if (isProEnabled || IAPManager.instance.isPurchased.value) {
return AppLocalizations.current.fullVersion;
} else if (!hasTrialStarted) {
return '${_revenueCatService?.trialDaysRemaining ?? _iapService?.trialDaysRemaining ?? _windowsIapService?.trialDaysRemaining} day trial available';
return '${_revenueCatService?.trialDaysRemaining ?? _windowsIapService?.trialDaysRemaining} day trial available';
} else if (!isTrialExpired) {
return AppLocalizations.current.trialDaysRemaining(trialDaysRemaining);
} else {
@@ -243,8 +225,6 @@ class IAPManager {
Future<void> purchaseFullVersion(BuildContext context) async {
if (_revenueCatService != null) {
return _revenueCatService!.purchaseFullVersion(context);
} else if (_iapService != null) {
return _iapService!.purchase(productId: IAPService.fullVersionId);
} else if (_windowsIapService != null) {
return _windowsIapService!.purchaseFullVersion();
}
@@ -254,8 +234,6 @@ class IAPManager {
Future<void> purchaseSubscription(BuildContext context) async {
if (_revenueCatService != null) {
return _revenueCatService!.purchaseSubscription(context);
} else if (_iapService != null) {
return _iapService!.purchase(productId: IAPService.subscriptionId);
} else if (_windowsIapService != null) {
return _windowsIapService!.purchaseFullVersion();
}
@@ -265,8 +243,6 @@ class IAPManager {
Future<void> restorePurchases() async {
if (_revenueCatService != null) {
await _revenueCatService!.restorePurchases();
} else if (_iapService != null) {
await _iapService!.restorePurchases();
} else if (_windowsIapService != null) {
await _windowsIapService!.restoreOrSyncSubscription();
}
@@ -281,7 +257,6 @@ class IAPManager {
_authSubscription?.cancel();
entitlements.removeListener(_onEntitlementsChanged);
_revenueCatService?.dispose();
_iapService?.dispose();
_windowsIapService?.dispose();
}
@@ -290,7 +265,6 @@ class IAPManager {
await entitlements.clearCache();
_windowsIapService?.reset();
await _revenueCatService?.reset(fullReset);
await _iapService?.reset(fullReset);
}
Future<void> redeem(String purchaseId) async {
@@ -298,8 +272,6 @@ class IAPManager {
await _revenueCatService!.redeem(purchaseId);
await entitlements.refresh(force: true);
_syncPurchaseFlagFromEntitlements();
} else if (_iapService != null) {
await _iapService!.redeem();
}
}
@@ -345,7 +317,7 @@ class IAPManager {
}
void _syncPurchaseFlagFromEntitlements() {
if (isPremiumEnabled) {
if (isProEnabled) {
isPurchased.value = true;
}
}

View File

@@ -1,450 +0,0 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:bike_control/bluetooth/messages/notification.dart';
import 'package:bike_control/main.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/iap/iap_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:intl/intl.dart';
import 'package:ios_receipt/ios_receipt.dart';
import 'package:prop/prop.dart';
import 'package:version/version.dart';
/// Service to handle in-app purchase functionality and trial period management
class IAPService {
static const int trialDays = 5;
static const String _trialStartDateKey = 'iap_trial_start_date';
static const String _purchaseStatusKey = 'iap_purchase_status';
static const String _dailyCommandCountKey = 'iap_daily_command_count';
static const String _lastCommandDateKey = 'iap_last_command_date';
static const String _lastPurchaseCheckKey = 'iap_last_purchase_check';
static const String _hasPurchasedKey = 'iap_has_purchased';
static const String fullVersionId = 'full_access_unlock';
static const String subscriptionId = 'pro';
final InAppPurchase _inAppPurchase = InAppPurchase.instance;
final FlutterSecureStorage _prefs;
StreamSubscription<List<PurchaseDetails>>? _subscription;
bool _isInitialized = false;
String? _trialStartDate;
String? _lastCommandDate;
int? _dailyCommandCount;
IAPService(this._prefs);
/// Initialize the IAP service
Future<void> initialize() async {
if (_isInitialized) return;
try {
// Skip IAP initialization on web
if (kIsWeb) {
debugPrint('IAP not supported on web');
_isInitialized = true;
return;
}
// Check if IAP is available on this platform
final available = await _inAppPurchase.isAvailable();
if (!available) {
debugPrint('IAP not available on this platform -');
// Set as purchased to allow unlimited access when IAP is not available
IAPManager.instance.isPurchased.value = false;
_isInitialized = true;
return;
}
// Listen for purchase updates
_subscription = _inAppPurchase.purchaseStream.listen(
_onPurchaseUpdate,
onDone: () => _subscription?.cancel(),
onError: (error) {
debugPrint('IAP Error: $error');
core.connection.signalNotification(
LogNotification('There was an error with in-app purchases: ${error.toString()}'),
);
// On error, default to allowing access
IAPManager.instance.isPurchased.value = false;
},
);
_trialStartDate = await _prefs.read(key: _trialStartDateKey);
core.connection.signalNotification(LogNotification('Trial start date: $_trialStartDate => $trialDaysRemaining'));
_lastCommandDate = await _prefs.read(key: _lastCommandDateKey);
final commandCount = await _prefs.read(key: _dailyCommandCountKey) ?? '0';
_dailyCommandCount = int.tryParse(commandCount);
// Check if already purchased
await _checkExistingPurchase();
_isInitialized = true;
if (!isTrialExpired && Platform.isAndroid) {
IAPManager.dailyCommandLimit = 80;
}
} catch (e, s) {
recordError(e, s, context: 'Initializing IAP Service');
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_ERROR, 'There was an error checking purchase status: ${e.toString()}'),
);
debugPrint('Failed to initialize IAP: $e');
// On initialization failure, default to allowing access
IAPManager.instance.isPurchased.value = false;
_isInitialized = true;
}
}
/// Check if the user has already purchased the app
Future<void> _checkExistingPurchase() async {
// First check if we have a stored purchase status
final storedStatus = await _prefs.read(key: _purchaseStatusKey);
final lastPurchaseCheck = await _prefs.read(key: _lastPurchaseCheckKey);
final hasPurchased = await _prefs.read(key: _hasPurchasedKey);
String todayDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
if (storedStatus == "true") {
if (Platform.isAndroid) {
if (lastPurchaseCheck == todayDate || hasPurchased == null) {
// hasPurchased means it was redeemed manually, so we skip the daily check
IAPManager.instance.isPurchased.value = true;
}
} else {
IAPManager.instance.isPurchased.value = true;
}
return;
}
await _prefs.write(key: _lastPurchaseCheckKey, value: todayDate);
// Platform-specific checks for existing paid app purchases
if (Platform.isIOS || Platform.isMacOS) {
// On iOS/macOS, check if the app was previously purchased (has a receipt)
await _checkAppleReceipt();
} else if (Platform.isAndroid) {
// On Android, check if user had the paid version before
await _checkAndroidPreviousPurchase();
}
// Also check for IAP purchase
if (!IAPManager.instance.isPurchased.value) {
await restorePurchases();
}
}
/// Check for Apple receipt (iOS/macOS)
Future<void> _checkAppleReceipt() async {
try {
final receiptContent = await IosReceipt.getAppleReceipt();
if (receiptContent != null) {
debugPrint('Existing Apple user detected - validating receipt $receiptContent');
var sharedSecret =
Platform.environment['VERIFYING_SHARED_SECRET'] ?? const String.fromEnvironment("VERIFYING_SHARED_SECRET");
if (sharedSecret.isEmpty) {
core.connection.signalNotification(AlertNotification(LogLevel.LOGLEVEL_ERROR, 'Shared Secret is empty'));
}
core.connection.signalNotification(
LogNotification('Using shared secret: ${sharedSecret.characters.take(10).join()}'),
);
await validateReceipt(
base64Receipt: receiptContent,
sharedSecret: sharedSecret,
);
} else {
debugPrint('No Apple receipt found');
}
} catch (e) {
core.connection.signalNotification(LogNotification('There was an error checking Apple receipt: ${e.toString()}'));
debugPrint('Error checking Apple receipt: $e');
}
}
Future<void> validateReceipt({
required String base64Receipt,
required String sharedSecret,
bool isSandbox = false,
}) async {
final Uri url = Uri.parse(
isSandbox ? 'https://sandbox.itunes.apple.com/verifyReceipt' : 'https://buy.itunes.apple.com/verifyReceipt',
);
final Map<String, dynamic> requestData = {
'receipt-data': base64Receipt,
'password': sharedSecret,
'exclude-old-transactions': false,
};
final HttpClient client = HttpClient();
try {
final HttpClientRequest request = await client.postUrl(url);
request.headers.set(
HttpHeaders.contentTypeHeader,
'application/json',
);
request.add(utf8.encode(jsonEncode(requestData)));
final HttpClientResponse response = await request.close();
final String responseBody = await response.transform(utf8.decoder).join();
final Map<String, dynamic> json = jsonDecode(responseBody) as Map<String, dynamic>;
if (json['status'] == 21007) {
// Receipt is from sandbox, retry with sandbox URL
debugPrint('Receipt is from sandbox, retrying with sandbox URL');
return validateReceipt(
base64Receipt: base64Receipt,
sharedSecret: sharedSecret,
isSandbox: true,
);
} else if (json['status'] != 0) {
core.connection.signalNotification(
LogNotification('Apple receipt validation failed with status: ${json['status']}'),
);
return;
}
final purchasedVersion = json['receipt']["original_application_version"];
core.connection.signalNotification(
LogNotification('Apple receipt validated for version: $purchasedVersion'),
);
final purchasedVersionAsInt = int.tryParse(purchasedVersion.toString()) ?? 0;
IAPManager.instance.isPurchased.value = purchasedVersionAsInt < (Platform.isMacOS ? 61 : 58);
if (IAPManager.instance.isPurchased.value) {
debugPrint('Apple receipt validation successful - granting full access');
await _prefs.write(key: _purchaseStatusKey, value: "true");
} else {
debugPrint('Apple receipt validation failed - no full access');
}
} catch (e) {
rethrow;
} finally {
client.close();
}
}
/// Check if Android user had the paid app before
Future<void> _checkAndroidPreviousPurchase() async {
try {
// On Android, we use the last seen version to determine if they had the paid version
// IMPORTANT: This assumes the app is currently paid and this update will be released
// while the app is still paid. Only users who downloaded the paid version will have
// a last_seen_version. After changing the app to free, new users won't have this set.
final lastSeenVersion = core.settings.getLastSeenVersion();
core.connection.signalNotification(LogNotification('Android last seen version: $lastSeenVersion'));
if (lastSeenVersion != null && lastSeenVersion.isNotEmpty) {
Version lastVersion = Version.parse(lastSeenVersion);
// If they had a previous version, they're an existing paid user
IAPManager.instance.isPurchased.value = lastVersion < Version(4, 2, 0);
if (IAPManager.instance.isPurchased.value) {
await _prefs.write(key: _purchaseStatusKey, value: "true");
}
debugPrint('Existing Android user detected - granting full access');
}
} catch (e, s) {
debugPrint('Error checking Android previous purchase: $e');
recordError(e, s, context: 'Checking Android previous purchase');
}
}
/// Restore previous purchases
Future<void> restorePurchases() async {
try {
await _inAppPurchase.restorePurchases();
// The purchase stream will be called with restored purchases
} catch (e, s) {
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_ERROR, 'There was an error restoring purchases: ${e.toString()}'),
);
recordError(e, s, context: 'Restore Purchases');
debugPrint('Error restoring purchases: $e');
}
}
/// Handle purchase updates
Future<void> _onPurchaseUpdate(List<PurchaseDetails> purchaseDetailsList) async {
for (final purchase in purchaseDetailsList) {
core.connection.signalNotification(
LogNotification('Purchase found: ${purchase.purchaseID} ${purchase.productID} - ${purchase.status}'),
);
if (purchase.status == PurchaseStatus.purchased || purchase.status == PurchaseStatus.restored) {
IAPManager.instance.isPurchased.value = true;
await _prefs.write(key: _hasPurchasedKey, value: "true");
await _prefs.write(key: _purchaseStatusKey, value: IAPManager.instance.isPurchased.value.toString());
debugPrint('Purchase successful or restored');
}
// Complete the purchase
if (purchase.pendingCompletePurchase) {
_inAppPurchase.completePurchase(purchase);
}
}
}
/// Purchase the full version
Future<void> purchase({required String productId}) async {
try {
if (!_isInitialized) {
await initialize();
}
final available = await _inAppPurchase.isAvailable();
if (!available) {
debugPrint('IAP not available');
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_INFO, 'IAP is not available on this platform.'),
);
return;
}
// Query product details
final response = await _inAppPurchase.queryProductDetails({productId});
if (response.error != null) {
debugPrint('Error querying products: ${response.error}');
if (response.error!.code == 'storekit_no_response') {
_trialStartDate = DateTime.now().toIso8601String();
core.connection.signalNotification(
AlertNotification(
LogLevel.LOGLEVEL_WARNING,
'Unlock will be available, soon! Trial days have been extended.',
),
);
} else {
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_INFO, 'IAP issue: ${response.error!.toString()}'),
);
}
return;
}
if (response.productDetails.isEmpty) {
debugPrint('Product not found: $productId');
core.connection.signalNotification(AlertNotification(LogLevel.LOGLEVEL_INFO, 'IAP issue: Product not found.'));
return;
}
final product = response.productDetails.first;
final purchaseParam = PurchaseParam(productDetails: product);
await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
await restorePurchases();
} catch (e, s) {
debugPrint('Error purchasing: $e');
recordError(e, s, context: 'Error purchasing');
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_ERROR, 'There was an error during purchasing: ${e.toString()}'),
);
}
}
/// Check if the trial period has started
bool get hasTrialStarted {
return _trialStartDate != null;
}
/// Start the trial period
Future<void> startTrial() async {
if (!hasTrialStarted) {
await _prefs.write(key: _trialStartDateKey, value: DateTime.now().toIso8601String());
}
}
/// Get the number of days remaining in the trial
int get trialDaysRemaining {
if (IAPManager.instance.isPurchased.value) return 0;
final trialStart = _trialStartDate;
if (trialStart == null) return trialDays;
final startDate = DateTime.parse(trialStart);
final now = DateTime.now();
final daysPassed = now.difference(startDate).inDays;
final remaining = trialDays - daysPassed;
return remaining > 0 ? remaining : 0;
}
/// Check if the trial has expired
bool get isTrialExpired {
return (!IAPManager.instance.isPurchased.value && hasTrialStarted && trialDaysRemaining <= 0);
}
/// Get the number of commands executed today
int get dailyCommandCount {
final lastDate = _lastCommandDate;
final today = DateTime.now().toIso8601String().split('T')[0];
if (lastDate != today) {
// Reset counter for new day
_lastCommandDate = today;
_dailyCommandCount = 0;
}
return _dailyCommandCount ?? 0;
}
/// Increment the daily command count
Future<void> incrementCommandCount() async {
final today = DateTime.now().toIso8601String().split('T')[0];
final lastDate = await _prefs.read(key: _lastCommandDateKey);
if (lastDate != today) {
// Reset counter for new day
_lastCommandDate = today;
_dailyCommandCount = 1;
await _prefs.write(key: _lastCommandDateKey, value: today);
await _prefs.write(key: _dailyCommandCountKey, value: '1');
} else {
final count = _dailyCommandCount ?? 0;
_dailyCommandCount = count + 1;
await _prefs.write(key: _dailyCommandCountKey, value: _dailyCommandCount.toString());
}
}
/// Check if the user can execute a command
bool get canExecuteCommand {
if (IAPManager.instance.isPurchased.value) return true;
if (!isTrialExpired && !Platform.isAndroid) return true;
return dailyCommandCount < IAPManager.dailyCommandLimit;
}
/// Get the number of commands remaining today (for free tier after trial)
int get commandsRemainingToday {
if (IAPManager.instance.isPurchased.value || (!isTrialExpired && !Platform.isAndroid)) return -1; // Unlimited
final remaining = IAPManager.dailyCommandLimit - dailyCommandCount;
return remaining > 0 ? remaining : 0; // Never return negative
}
/// Dispose the service
void dispose() {
_subscription?.cancel();
}
Future<void> reset(bool fullReset) async {
if (fullReset) {
await _prefs.deleteAll();
} else {
await _prefs.delete(key: _purchaseStatusKey);
_isInitialized = false;
await initialize();
}
}
Future<void> redeem() async {
IAPManager.instance.isPurchased.value = true;
await _prefs.write(key: _purchaseStatusKey, value: IAPManager.instance.isPurchased.value.toString());
}
}

View File

@@ -29,9 +29,11 @@ class RevenueCatService {
// RevenueCat entitlement identifier
static const String fullVersionEntitlement = 'Full Version';
static const String proVersionEntitlement = 'pro';
final FlutterSecureStorage _prefs;
final ValueNotifier<bool> isPurchasedNotifier;
final ValueNotifier<bool> isProNotifier;
final int Function() getDailyCommandLimit;
final void Function(int limit) setDailyCommandLimit;
final EntitlementsService entitlementsService;
@@ -46,6 +48,7 @@ class RevenueCatService {
RevenueCatService(
this._prefs, {
required this.isPurchasedNotifier,
required this.isProNotifier,
required this.getDailyCommandLimit,
required this.setDailyCommandLimit,
required this.entitlementsService,
@@ -166,13 +169,15 @@ class RevenueCatService {
/// Handle customer info updates from RevenueCat
Future<bool> _handleCustomerInfoUpdate(CustomerInfo customerInfo) async {
final hasEntitlement = customerInfo.entitlements.active.containsKey(fullVersionEntitlement);
final hasFullVersionEntitlements = customerInfo.entitlements.active.containsKey(fullVersionEntitlement);
final userId = await Purchases.appUserID;
core.connection.signalNotification(LogNotification('User ID: $userId at ${customerInfo.requestDate}'));
core.connection.signalNotification(LogNotification('Full Version entitlement: $hasEntitlement'));
core.connection.signalNotification(LogNotification('Full Version entitlement: $hasFullVersionEntitlements'));
if (!hasEntitlement) {
isProNotifier.value = customerInfo.entitlements.active.containsKey(proVersionEntitlement);
if (!hasFullVersionEntitlements) {
// purchased before IAP migration
if (Platform.isAndroid) {
final storedStatus = await _prefs.read(key: _purchaseStatusKey);
@@ -194,7 +199,7 @@ class RevenueCatService {
}
}
} else {
isPurchasedNotifier.value = hasEntitlement;
isPurchasedNotifier.value = hasFullVersionEntitlements;
}
return isPurchasedNotifier.value;
}
@@ -309,7 +314,8 @@ class RevenueCatService {
await Purchases.logOut();
} on PlatformException catch (error) {
// RevenueCat throws when logging out anonymous users.
if (error.code != 'log_out_called_on_anonymous_user') {
if (error.code != '22') {
// LogOut was called but the current user is anonymous.
rethrow;
}
}

View File

@@ -70,6 +70,13 @@ class WindowsIAPService {
return;
}
final boughtProducts = await _windowsIapPlugin.getAddonLicenses();
if (boughtProducts.containsKey(IAPManager.premiumMonthlyProductKey) &&
boughtProducts[IAPManager.premiumMonthlyProductKey]!.isActive == true) {
IAPManager.instance.isLocalPro.value = true;
return;
}
final trial = await _windowsIapPlugin.getTrialStatusAndRemainingDays();
core.connection.signalNotification(LogNotification('Trial status: $trial'));
final trialEndDate = trial.remainingDays;
@@ -100,10 +107,10 @@ class WindowsIAPService {
final status = await _windowsIapPlugin.makePurchase(productId);
if (status == StorePurchaseStatus.succeeded || status == StorePurchaseStatus.alreadyPurchased) {
await restoreOrSyncSubscription();
IAPManager.instance.isPurchased.value = IAPManager.instance.isPremiumEnabled;
IAPManager.instance.isPurchased.value = IAPManager.instance.isProEnabled;
buildToast(
title: 'Purchase Successful',
subtitle: IAPManager.instance.isPremiumEnabled
subtitle: IAPManager.instance.isProEnabled
? 'Subscription activated successfully.'
: 'Purchase complete. Sync may take a moment.',
);
@@ -119,7 +126,7 @@ class WindowsIAPService {
await _subscriptionService.restoreOrSyncSubscription(
productStoreId: subscriptionStoreProductId,
);
IAPManager.instance.isPurchased.value = IAPManager.instance.isPremiumEnabled;
IAPManager.instance.isPurchased.value = IAPManager.instance.isProEnabled;
} catch (e, s) {
recordError(e, s, context: 'Syncing Windows subscription');
rethrow;
@@ -134,7 +141,7 @@ class WindowsIAPService {
/// Check if the trial has expired
bool get isTrialExpired {
if (IAPManager.instance.isPremiumEnabled) {
if (IAPManager.instance.isProEnabled) {
return false;
}
return !IAPManager.instance.isPurchased.value && hasTrialStarted && trialDaysRemaining <= 0;
@@ -171,14 +178,14 @@ class WindowsIAPService {
/// Check if the user can execute a command
bool get canExecuteCommand {
if (IAPManager.instance.isPremiumEnabled || IAPManager.instance.isPurchased.value) return true;
if (IAPManager.instance.isProEnabled || IAPManager.instance.isPurchased.value) return true;
if (!isTrialExpired) return true;
return dailyCommandCount < dailyCommandLimit;
}
/// Get the number of commands remaining today (for free tier after trial)
int get commandsRemainingToday {
if (IAPManager.instance.isPremiumEnabled || IAPManager.instance.isPurchased.value || !isTrialExpired) {
if (IAPManager.instance.isProEnabled || IAPManager.instance.isPurchased.value || !isTrialExpired) {
return -1;
}
final remaining = dailyCommandLimit - dailyCommandCount;

View File

@@ -94,7 +94,7 @@ class _IAPStatusWidgetState extends State<IAPStatusWidget> {
child: ValueListenableBuilder(
valueListenable: IAPManager.instance.isPurchased,
builder: (context, isPurchased, child) {
final hasPremiumAccess = iapManager.isPremiumEnabled || isPurchased;
final hasPremiumAccess = iapManager.isProEnabled || isPurchased;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,

View File

@@ -1,9 +1,9 @@
import 'dart:io';
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2.dart';
import 'package:bike_control/pages/login.dart';
import 'package:bike_control/pages/markdown.dart';
import 'package:bike_control/pages/navigation.dart';
import 'package:bike_control/pages/subscription.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/widgets/title.dart';
@@ -20,8 +20,34 @@ import 'package:url_launcher/url_launcher_string.dart';
import '../utils/iap/iap_manager.dart';
List<Widget> buildMenuButtons(BuildContext context, BCPage currentPage, VoidCallback? openLogs) {
final iap = IAPManager.instance;
return [
if (IAPManager.instance.isPurchased.value || IAPManager.instance.isPremiumEnabled)
// Pro/Subscription Button
Builder(
builder: (context) {
return Button(
style: ButtonStyle.primary().withBackgroundColor(color: iap.isProEnabled ? Colors.green : null),
onPressed: () {
openDrawer(
context: context,
builder: (c) => SubscriptionPage(),
position: OverlayPosition.end,
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.workspace_premium, size: 14),
const SizedBox(width: 4),
Text('Pro'),
],
),
);
},
),
Gap(8),
if (IAPManager.instance.isPurchased.value || IAPManager.instance.isProEnabled)
Builder(
builder: (context) {
return OutlineButton(
@@ -100,7 +126,7 @@ Target: ${core.settings.getLastTarget()?.name ?? '-'}
Trainer App: ${core.settings.getTrainerApp()?.name ?? '-'}
Connected Controllers: ${core.connection.devices.map((e) => e.toString()).join(', ')}
Connected Trainers: ${core.logic.connectedTrainerConnections.map((e) => e.title).join(', ')}
Status: ${(IAPManager.instance.isPremiumEnabled || IAPManager.instance.isPurchased.value) ? 'Full Version' : 'Test Version'}${userId != null ? ' (User ID: $userId)' : ''}
Status: ${(IAPManager.instance.isProEnabled || IAPManager.instance.isPurchased.value) ? 'Full Version' : 'Test Version'}${userId != null ? ' (User ID: $userId)' : ''}
Logs:
${core.connection.lastLogEntries.reversed.joinToString(separator: '\n', transform: (e) => '${e.date.toString().split('.').first} - ${e.entry}')}
''';
@@ -150,16 +176,6 @@ class BKMenuButton extends StatelessWidget {
core.connection.disconnectAll();
},
),
MenuButton(
child: Text('Login'),
onPressed: (c) async {
openDrawer(
context: context,
builder: (c) => LoginPage(),
position: OverlayPosition.bottom,
);
},
),
MenuDivider(),
],
if (currentPage == BCPage.logs) ...[