oxen-mobile-wallet/lib/src/stores/node_list/node_list_store.dart

94 lines
2.3 KiB
Dart
Raw Normal View History

2020-01-04 20:31:52 +01:00
import 'dart:async';
import 'package:mobx/mobx.dart';
import 'package:hive/hive.dart';
2021-01-30 14:27:10 +01:00
import 'package:oxen_wallet/src/node/node.dart';
import 'package:oxen_wallet/src/node/node_list.dart';
import 'package:oxen_wallet/l10n.dart';
2020-01-04 20:31:52 +01:00
part 'node_list_store.g.dart';
class NodeListStore = NodeListBase with _$NodeListStore;
abstract class NodeListBase with Store {
NodeListBase({required this.nodesSource}) :
nodes = ObservableList<Node>() {
2020-01-08 13:26:34 +01:00
_onNodesChangeSubscription = nodesSource.watch().listen((e) => update());
update();
}
2020-01-04 20:31:52 +01:00
@observable
ObservableList<Node> nodes;
@observable
bool isValid = false;
2020-01-04 20:31:52 +01:00
@observable
String? errorMessage;
2020-01-04 20:31:52 +01:00
Box<Node> nodesSource;
late StreamSubscription<BoxEvent> _onNodesChangeSubscription;
2020-01-04 20:31:52 +01:00
2020-07-13 18:23:13 +02:00
// @override
// void dispose() {
// super.dispose();
//
// if (_onNodesChangeSubscription != null) {
// _onNodesChangeSubscription.cancel();
// }
// }
2020-01-04 20:31:52 +01:00
@action
2020-01-08 13:26:34 +01:00
void update() =>
2020-01-04 20:31:52 +01:00
nodes.replaceRange(0, nodes.length, nodesSource.values.toList());
@action
Future addNode(
{required String address, String? port, required String login, required String password}) async {
2020-01-04 20:31:52 +01:00
var uri = address;
if (port != null && port.isNotEmpty)
2020-01-04 20:31:52 +01:00
uri += ':' + port;
final node = Node(uri: uri, login: login, password: password);
await nodesSource.add(node);
}
@action
Future remove({required Node node}) async => await node.delete();
2020-01-04 20:31:52 +01:00
@action
Future reset() async => await resetToDefault(nodesSource);
Future<bool> isNodeOnline(Node node) async {
try {
2021-01-30 14:27:10 +01:00
return await node.isOnline();
2020-01-04 20:31:52 +01:00
} catch (e) {
return false;
}
}
static final nodeAddrRE = RegExp('^[0-9a-zA-Z.-]{1,253}\$');
static final nodePortRE = RegExp('^[0-9]{1,5}\$');
2020-01-04 20:31:52 +01:00
void validateNodeAddress(String value, AppLocalizations l10n) {
isValid = nodeAddrRE.hasMatch(value);
errorMessage = isValid ? null : l10n.error_text_node_address;
}
2020-01-08 13:26:34 +01:00
void validateNodePort(String value, AppLocalizations l10n) {
if (nodePortRE.hasMatch(value)) {
2020-01-04 20:31:52 +01:00
try {
2020-01-08 13:26:34 +01:00
final intValue = int.parse(value);
isValid = (intValue > 0 && intValue <= 65535);
2020-01-04 20:31:52 +01:00
} catch (e) {
isValid = false;
}
2020-01-08 13:26:34 +01:00
} else {
2020-01-04 20:31:52 +01:00
isValid = false;
2020-01-08 13:26:34 +01:00
}
errorMessage = isValid ? null : l10n.error_text_node_port;
2020-01-04 20:31:52 +01:00
}
}