mirror of
https://github.com/koloideal/Casha.git
synced 2026-08-08 17:51:14 +03:00
step
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
class BackupData {
|
||||
final String ownerPurchaseToken;
|
||||
final DateTime createdAt;
|
||||
final Map<String, dynamic> payload;
|
||||
|
||||
const BackupData({
|
||||
required this.ownerPurchaseToken,
|
||||
required this.createdAt,
|
||||
required this.payload,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'owner_purchase_token': ownerPurchaseToken,
|
||||
'created_at': createdAt.toIso8601String(),
|
||||
'payload': payload,
|
||||
};
|
||||
|
||||
factory BackupData.fromJson(Map<String, dynamic> json) {
|
||||
return BackupData(
|
||||
ownerPurchaseToken: json['owner_purchase_token'] as String? ?? '',
|
||||
createdAt: DateTime.tryParse(json['created_at'] as String? ?? '') ??
|
||||
DateTime.now(),
|
||||
payload: json['payload'] as Map<String, dynamic>? ?? {},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum BackupVerifyResult { ok, tokenMismatch, noToken, invalidFormat }
|
||||
|
||||
class BackupService {
|
||||
String _currentPurchaseToken;
|
||||
|
||||
BackupService(this._currentPurchaseToken);
|
||||
|
||||
void updatePurchaseToken(String token) {
|
||||
_currentPurchaseToken = token;
|
||||
}
|
||||
|
||||
String get currentPurchaseToken => _currentPurchaseToken;
|
||||
|
||||
Uint8List createBackup(Map<String, dynamic> payload) {
|
||||
final data = BackupData(
|
||||
ownerPurchaseToken: _currentPurchaseToken,
|
||||
createdAt: DateTime.now(),
|
||||
payload: payload,
|
||||
);
|
||||
final json = jsonEncode(data.toJson());
|
||||
return Uint8List.fromList(utf8.encode(json));
|
||||
}
|
||||
|
||||
(BackupVerifyResult, BackupData?) verifyAndParse(Uint8List raw) {
|
||||
try {
|
||||
final json = jsonDecode(utf8.decode(raw)) as Map<String, dynamic>;
|
||||
final data = BackupData.fromJson(json);
|
||||
|
||||
if (data.ownerPurchaseToken.isEmpty) {
|
||||
return (BackupVerifyResult.noToken, null);
|
||||
}
|
||||
|
||||
if (data.ownerPurchaseToken != _currentPurchaseToken) {
|
||||
return (BackupVerifyResult.tokenMismatch, null);
|
||||
}
|
||||
|
||||
return (BackupVerifyResult.ok, data);
|
||||
} catch (e) {
|
||||
return (BackupVerifyResult.invalidFormat, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,192 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../models/user_model.dart';
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:in_app_purchase/in_app_purchase.dart';
|
||||
|
||||
class PurchaseResult {
|
||||
final bool success;
|
||||
final String? purchaseToken;
|
||||
final String? error;
|
||||
|
||||
const PurchaseResult({this.success = false, this.purchaseToken, this.error});
|
||||
|
||||
factory PurchaseResult.ok(String token) =>
|
||||
PurchaseResult(success: true, purchaseToken: token);
|
||||
|
||||
factory PurchaseResult.failed([String? error]) =>
|
||||
PurchaseResult(success: false, error: error);
|
||||
}
|
||||
|
||||
abstract class BillingService {
|
||||
Future<bool> purchasePro();
|
||||
Future<bool> restorePurchases();
|
||||
Future<UserPlan> getCurrentPlan();
|
||||
static const proProductId = 'casha_pro_lifetime';
|
||||
|
||||
Future<PurchaseResult> purchasePro();
|
||||
Future<PurchaseResult> restorePurchases();
|
||||
Future<PurchaseResult> queryPastPurchase();
|
||||
Future<void> completePurchase(String purchaseToken);
|
||||
Stream<List<PurchaseDetails>> get purchaseStream;
|
||||
Future<void> dispose();
|
||||
}
|
||||
|
||||
class MockBillingService implements BillingService {
|
||||
static const _key = 'user_plan';
|
||||
final SharedPreferences _prefs;
|
||||
class PlayBillingService implements BillingService {
|
||||
final InAppPurchase _inAppPurchase = InAppPurchase.instance;
|
||||
late final StreamSubscription<List<PurchaseDetails>> _sub;
|
||||
final _controller = StreamController<List<PurchaseDetails>>.broadcast();
|
||||
|
||||
MockBillingService(this._prefs);
|
||||
|
||||
@override
|
||||
Future<bool> purchasePro() async {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
await _prefs.setString(_key, 'vip');
|
||||
return true;
|
||||
PlayBillingService() {
|
||||
_sub = _inAppPurchase.purchaseStream.listen((purchases) {
|
||||
_controller.add(purchases);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> restorePurchases() async {
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
return false;
|
||||
Stream<List<PurchaseDetails>> get purchaseStream => _controller.stream;
|
||||
|
||||
@override
|
||||
Future<PurchaseResult> purchasePro() async {
|
||||
final available = await _inAppPurchase.isAvailable();
|
||||
if (!available) {
|
||||
return PurchaseResult.failed('Billing not available');
|
||||
}
|
||||
|
||||
final response = await _inAppPurchase.queryProductDetails(
|
||||
{BillingService.proProductId},
|
||||
);
|
||||
if (response.productDetails.isEmpty) {
|
||||
return PurchaseResult.failed('Product not found');
|
||||
}
|
||||
|
||||
final product = response.productDetails.first;
|
||||
final purchaseParam = PurchaseParam(productDetails: product);
|
||||
|
||||
final started = await _inAppPurchase.buyNonConsumable(
|
||||
purchaseParam: purchaseParam,
|
||||
);
|
||||
if (!started) {
|
||||
return PurchaseResult.failed('Could not start purchase');
|
||||
}
|
||||
|
||||
final completer = Completer<PurchaseResult>();
|
||||
late StreamSubscription sub;
|
||||
sub = purchaseStream.timeout(
|
||||
const Duration(seconds: 60),
|
||||
onTimeout: (sink) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.failed('Purchase timed out'));
|
||||
}
|
||||
sub.cancel();
|
||||
},
|
||||
).listen((purchases) {
|
||||
for (final p in purchases) {
|
||||
if (p.productID == BillingService.proProductId &&
|
||||
p.status == PurchaseStatus.purchased) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
|
||||
}
|
||||
sub.cancel();
|
||||
return;
|
||||
}
|
||||
if (p.status == PurchaseStatus.error) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.failed(p.error?.message));
|
||||
}
|
||||
sub.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserPlan> getCurrentPlan() async {
|
||||
final value = _prefs.getString(_key);
|
||||
return value == 'vip' ? UserPlan.vip : UserPlan.free;
|
||||
Future<PurchaseResult> restorePurchases() async {
|
||||
final available = await _inAppPurchase.isAvailable();
|
||||
if (!available) {
|
||||
return PurchaseResult.failed('Billing not available');
|
||||
}
|
||||
|
||||
await _inAppPurchase.restorePurchases();
|
||||
|
||||
final completer = Completer<PurchaseResult>();
|
||||
late StreamSubscription sub;
|
||||
sub = purchaseStream.timeout(
|
||||
const Duration(seconds: 15),
|
||||
onTimeout: (sink) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.failed('Restore timed out'));
|
||||
}
|
||||
sub.cancel();
|
||||
},
|
||||
).listen((purchases) {
|
||||
for (final p in purchases) {
|
||||
if (p.productID == BillingService.proProductId &&
|
||||
(p.status == PurchaseStatus.restored ||
|
||||
p.status == PurchaseStatus.purchased)) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
|
||||
}
|
||||
sub.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<PurchaseResult> queryPastPurchase() async {
|
||||
final available = await _inAppPurchase.isAvailable();
|
||||
if (!available) {
|
||||
return const PurchaseResult();
|
||||
}
|
||||
|
||||
final response = await _inAppPurchase.queryProductDetails(
|
||||
{BillingService.proProductId},
|
||||
);
|
||||
if (response.productDetails.isEmpty) {
|
||||
return const PurchaseResult();
|
||||
}
|
||||
|
||||
final completer = Completer<PurchaseResult>();
|
||||
late StreamSubscription sub;
|
||||
sub = purchaseStream.timeout(
|
||||
const Duration(seconds: 10),
|
||||
onTimeout: (sink) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(const PurchaseResult());
|
||||
}
|
||||
sub.cancel();
|
||||
},
|
||||
).listen((purchases) {
|
||||
for (final p in purchases) {
|
||||
if (p.productID == BillingService.proProductId &&
|
||||
(p.status == PurchaseStatus.restored ||
|
||||
p.status == PurchaseStatus.purchased)) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(PurchaseResult.ok(p.verificationData.serverVerificationData));
|
||||
}
|
||||
sub.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await _inAppPurchase.restorePurchases();
|
||||
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> completePurchase(String purchaseToken) async {
|
||||
if (kDebugMode) {
|
||||
print('completePurchase: $purchaseToken');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
await _sub.cancel();
|
||||
await _controller.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,10 @@ import 'package:google_sign_in/google_sign_in.dart';
|
||||
class GoogleAuthService {
|
||||
final GoogleSignIn _googleSignIn;
|
||||
|
||||
GoogleAuthService() : _googleSignIn = GoogleSignIn(scopes: ['email']);
|
||||
GoogleAuthService() : _googleSignIn = GoogleSignIn(scopes: [
|
||||
'email',
|
||||
'https://www.googleapis.com/auth/drive.appdata',
|
||||
]);
|
||||
|
||||
GoogleSignInAccount? get currentUser => _googleSignIn.currentUser;
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:googleapis/drive/v3.dart' as drive;
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
|
||||
|
||||
class DriveBackupResult {
|
||||
final bool success;
|
||||
final String? error;
|
||||
final String? fileId;
|
||||
final DateTime? modifiedTime;
|
||||
|
||||
const DriveBackupResult({this.success = false, this.error, this.fileId, this.modifiedTime});
|
||||
|
||||
factory DriveBackupResult.ok(String fileId, DateTime modifiedTime) =>
|
||||
DriveBackupResult(success: true, fileId: fileId, modifiedTime: modifiedTime);
|
||||
|
||||
factory DriveBackupResult.failed(String error) =>
|
||||
DriveBackupResult(success: false, error: error);
|
||||
}
|
||||
|
||||
class GoogleDriveService {
|
||||
static const _fileName = 'casha_backup.json';
|
||||
static const _appDataFolder = 'appDataFolder';
|
||||
|
||||
final GoogleSignIn _googleSignIn;
|
||||
|
||||
GoogleDriveService(this._googleSignIn);
|
||||
|
||||
GoogleSignInAccount? get currentUser => _googleSignIn.currentUser;
|
||||
Stream<GoogleSignInAccount?> get onUserChanged => _googleSignIn.onCurrentUserChanged;
|
||||
|
||||
Future<void> signIn() async {
|
||||
await _googleSignIn.signIn();
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
await _googleSignIn.signOut();
|
||||
}
|
||||
|
||||
Future<drive.DriveApi?> _getDriveApi() async {
|
||||
if (_googleSignIn.currentUser == null) return null;
|
||||
final httpClient = await _googleSignIn.authenticatedClient();
|
||||
if (httpClient == null) return null;
|
||||
return drive.DriveApi(httpClient);
|
||||
}
|
||||
|
||||
Future<String?> _findExistingFile(drive.DriveApi api) async {
|
||||
final list = await api.files.list(
|
||||
spaces: _appDataFolder,
|
||||
q: "name = '$_fileName' and trashed = false",
|
||||
$fields: 'files(id, name, modifiedTime)',
|
||||
);
|
||||
return list.files?.isNotEmpty == true ? list.files!.first.id : null;
|
||||
}
|
||||
|
||||
Future<DriveBackupResult> uploadBackup(Uint8List data) async {
|
||||
final api = await _getDriveApi();
|
||||
if (api == null) {
|
||||
return DriveBackupResult.failed('Not authenticated');
|
||||
}
|
||||
|
||||
try {
|
||||
final existingId = await _findExistingFile(api);
|
||||
|
||||
final media = drive.Media(
|
||||
Stream<List<int>>.fromIterable([data.toList()]),
|
||||
data.length,
|
||||
);
|
||||
|
||||
if (existingId != null) {
|
||||
final file = drive.File(
|
||||
name: _fileName,
|
||||
modifiedTime: DateTime.now(),
|
||||
);
|
||||
final updated = await api.files.update(
|
||||
file,
|
||||
existingId,
|
||||
uploadMedia: media,
|
||||
$fields: 'id, modifiedTime',
|
||||
);
|
||||
return DriveBackupResult.ok(
|
||||
updated.id!,
|
||||
updated.modifiedTime!,
|
||||
);
|
||||
} else {
|
||||
final file = drive.File(
|
||||
name: _fileName,
|
||||
parents: [_appDataFolder],
|
||||
modifiedTime: DateTime.now(),
|
||||
);
|
||||
final created = await api.files.create(
|
||||
file,
|
||||
uploadMedia: media,
|
||||
$fields: 'id, modifiedTime',
|
||||
);
|
||||
return DriveBackupResult.ok(
|
||||
created.id!,
|
||||
created.modifiedTime!,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
return DriveBackupResult.failed(e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<Uint8List?> downloadBackup() async {
|
||||
final api = await _getDriveApi();
|
||||
if (api == null) return null;
|
||||
|
||||
try {
|
||||
final fileId = await _findExistingFile(api);
|
||||
if (fileId == null) return null;
|
||||
|
||||
final media = await api.files.get(
|
||||
fileId,
|
||||
downloadOptions: drive.DownloadOptions.fullMedia,
|
||||
) as drive.Media;
|
||||
|
||||
final bytes = <int>[];
|
||||
await for (final chunk in media.stream) {
|
||||
bytes.addAll(chunk);
|
||||
}
|
||||
return Uint8List.fromList(bytes);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<DateTime?> getLastBackupTime() async {
|
||||
final api = await _getDriveApi();
|
||||
if (api == null) return null;
|
||||
|
||||
try {
|
||||
final list = await api.files.list(
|
||||
spaces: _appDataFolder,
|
||||
q: "name = '$_fileName' and trashed = false",
|
||||
$fields: 'files(id, name, modifiedTime)',
|
||||
);
|
||||
if (list.files?.isNotEmpty == true) {
|
||||
return list.files!.first.modifiedTime;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../models/user_model.dart';
|
||||
import 'billing_service.dart';
|
||||
|
||||
class PremiumManager {
|
||||
static const _keyIsPremium = 'is_premium';
|
||||
static const _keyPurchaseToken = 'purchase_token';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
final BillingService _billing;
|
||||
|
||||
PremiumManager(this._prefs, this._billing);
|
||||
|
||||
bool get isPremium => _prefs.getBool(_keyIsPremium) ?? false;
|
||||
String? get purchaseToken => _prefs.getString(_keyPurchaseToken);
|
||||
|
||||
Future<void> _setPremium(bool value, String? token) async {
|
||||
await _prefs.setBool(_keyIsPremium, value);
|
||||
if (token != null) {
|
||||
await _prefs.setString(_keyPurchaseToken, token);
|
||||
} else if (!value) {
|
||||
await _prefs.remove(_keyPurchaseToken);
|
||||
}
|
||||
}
|
||||
|
||||
Future<PurchaseResult> purchase() async {
|
||||
final result = await _billing.purchasePro();
|
||||
if (result.success && result.purchaseToken != null) {
|
||||
await _setPremium(true, result.purchaseToken);
|
||||
await _billing.completePurchase(result.purchaseToken!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<PurchaseResult> restore() async {
|
||||
final result = await _billing.restorePurchases();
|
||||
if (result.success && result.purchaseToken != null) {
|
||||
await _setPremium(true, result.purchaseToken);
|
||||
await _billing.completePurchase(result.purchaseToken!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> autoRestore() async {
|
||||
if (isPremium) return;
|
||||
final result = await _billing.queryPastPurchase();
|
||||
if (result.success && result.purchaseToken != null) {
|
||||
await _setPremium(true, result.purchaseToken);
|
||||
await _billing.completePurchase(result.purchaseToken!);
|
||||
}
|
||||
}
|
||||
|
||||
UserPlan get currentPlan => isPremium ? UserPlan.vip : UserPlan.free;
|
||||
|
||||
Future<void> clear() async {
|
||||
await _setPremium(false, null);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user