70 lines
2.1 KiB
Dart
70 lines
2.1 KiB
Dart
import 'dart:convert';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:accessible_terminal/models/saved_connection.dart';
|
|
|
|
// Key for SharedPreferences
|
|
const String _kSavedConnectionsKey = 'saved_connections';
|
|
|
|
class SavedConnectionsNotifier extends StateNotifier<List<SavedConnection>> {
|
|
SavedConnectionsNotifier() : super([]) {
|
|
_loadConnections();
|
|
}
|
|
|
|
Future<void> _loadConnections() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final String? jsonString = prefs.getString(_kSavedConnectionsKey);
|
|
if (jsonString != null) {
|
|
try {
|
|
final List<dynamic> jsonList = jsonDecode(jsonString);
|
|
state = jsonList.map((e) => SavedConnection.fromJson(e)).toList();
|
|
} catch (e) {
|
|
// Handle corruption or format change gracefully
|
|
state = [];
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<void> addConnection({
|
|
required String host,
|
|
required int port,
|
|
required String username,
|
|
String? privateKey,
|
|
}) async {
|
|
// Check for duplicates (simple check based on host/user/port)
|
|
final exists = state.any((c) =>
|
|
c.host == host && c.port == port && c.username == username
|
|
);
|
|
|
|
if (exists) return; // Don't save if already exists
|
|
|
|
// Use timestamp for simple ID generation
|
|
final simpleId = DateTime.now().millisecondsSinceEpoch.toString();
|
|
final connection = SavedConnection(
|
|
id: simpleId,
|
|
host: host,
|
|
port: port,
|
|
username: username,
|
|
privateKey: privateKey,
|
|
);
|
|
|
|
state = [...state, connection];
|
|
await _saveToDisk();
|
|
}
|
|
|
|
Future<void> removeConnection(String id) async {
|
|
state = state.where((c) => c.id != id).toList();
|
|
await _saveToDisk();
|
|
}
|
|
|
|
Future<void> _saveToDisk() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final jsonList = state.map((c) => c.toJson()).toList();
|
|
await prefs.setString(_kSavedConnectionsKey, jsonEncode(jsonList));
|
|
}
|
|
}
|
|
|
|
final savedConnectionsProvider = StateNotifierProvider<SavedConnectionsNotifier, List<SavedConnection>>((ref) {
|
|
return SavedConnectionsNotifier();
|
|
});
|