prasule/lib/api/walletmanager.dart
2023-12-29 21:39:54 +01:00

62 lines
1.9 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:prasule/api/wallet.dart';
/// Used for [Wallet]-managing operations
class WalletManager {
/// Returns a list of all [Wallet]s
static Future<List<Wallet>> listWallets() async {
final path =
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) {
// TODO: do something with unreadable wallets
}
}
return wallets;
}
/// Loads and returns a single [Wallet] by name
static Future<Wallet> loadWallet(String name) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/$name");
if (!path.existsSync()) {
path.createSync();
}
if (!wallet.existsSync()) {
return Future.error("Wallet does not exist");
}
return Wallet.fromJson(
jsonDecode(wallet.readAsStringSync()) as Map<String, String>,);
}
/// Converts [Wallet] to JSON and saves it to AppData
static Future<bool> saveWallet(Wallet w) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
final wallet = File("${path.path}/${w.name}");
if (!path.existsSync()) {
path.createSync();
}
// if (!wallet.existsSync()) return false;
wallet.writeAsStringSync(jsonEncode(w.toJson()));
return true;
}
/// Deletes the corresponding [Wallet] file
static Future<void> deleteWallet(Wallet w) async {
final path =
Directory("${(await getApplicationDocumentsDirectory()).path}/wallets");
File("${path.path}/${w.name}").deleteSync();
}
}