66 lines
2 KiB
Dart
66 lines
2 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:prasule/api/wallet.dart';
|
|
import 'package:prasule/main.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) {
|
|
logger.e(e);
|
|
// TODO: do something with unreadable wallets
|
|
}
|
|
}
|
|
logger.i(wallets.length);
|
|
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, dynamic>,
|
|
);
|
|
}
|
|
|
|
/// 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();
|
|
}
|
|
}
|