prasule/lib/api/wallet_manager.dart

82 lines
2.4 KiB
Dart
Raw Normal View History

2023-09-08 11:50:21 +02:00
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:prasule/api/wallet.dart';
2023-12-31 11:42:27 +01:00
import 'package:prasule/main.dart';
2023-09-08 11:50:21 +02:00
/// Used for [Wallet]-managing operations
2023-09-08 11:50:21 +02:00
class WalletManager {
/// Returns a list of all [Wallet]s
static Future<List<Wallet>> listWallets() async {
final path =
2023-09-08 11:50:21 +02:00
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
if (!path.existsSync()) {
path.createSync();
}
final wallets = <Wallet>[];
for (final w
in path.listSync().map((e) => e.path.split("/").last).toList()) {
try {
wallets.add(await loadWallet(w));
} catch (e) {
2023-12-31 11:42:27 +01:00
logger.e(e);
// TODO: do something with unreadable wallets
}
}
2023-12-31 11:42:27 +01:00
logger.i(wallets.length);
return wallets;
2023-09-08 11:50:21 +02:00
}
2024-01-19 20:23:16 +01:00
/// Deletes all [Wallet]s
static Future<void> deleteAllData() async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
if (!path.existsSync()) {
return;
}
for (final entry in path.listSync()) {
if (!entry.path.endsWith(".json")) return; // only delete wallet files
logger.d("Deleting ${entry.path}");
entry.deleteSync();
}
}
/// Loads and returns a single [Wallet] by name
2023-09-08 11:50:21 +02:00
static Future<Wallet> loadWallet(String name) async {
final path =
2023-09-08 11:50:21 +02:00
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/$name");
2023-09-08 11:50:21 +02:00
if (!path.existsSync()) {
path.createSync();
}
if (!wallet.existsSync()) {
return Future.error("Wallet does not exist");
}
return Wallet.fromJson(
2023-12-31 11:42:27 +01:00
jsonDecode(wallet.readAsStringSync()) as Map<String, dynamic>,
);
2023-09-08 11:50:21 +02:00
}
/// Converts [Wallet] to JSON and saves it to AppData
static Future<bool> saveWallet(Wallet w) async {
final path =
2023-09-08 11:50:21 +02:00
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/${w.name}");
2023-09-08 11:50:21 +02:00
if (!path.existsSync()) {
path.createSync();
}
// if (!wallet.existsSync()) return false;
2023-09-08 11:50:21 +02:00
wallet.writeAsStringSync(jsonEncode(w.toJson()));
return true;
2023-09-08 11:50:21 +02:00
}
2023-09-14 17:11:40 +02:00
/// Deletes the corresponding [Wallet] file
2023-09-14 17:11:40 +02:00
static Future<void> deleteWallet(Wallet w) async {
final path =
2023-09-14 17:11:40 +02:00
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
File("${path.path}/${w.name}").deleteSync();
2023-09-14 17:11:40 +02:00
}
2023-09-08 11:50:21 +02:00
}