From 5a4806e9b2bf34ec1dfb6b8d40679f1cc5690a3b Mon Sep 17 00:00:00 2001 From: csf Date: Wed, 21 Sep 2022 21:20:19 +0800 Subject: [PATCH] refactor peer alias --- flutter/lib/common/widgets/peer_widget.dart | 2 +- .../lib/common/widgets/peercard_widget.dart | 78 +++++++++---------- flutter/lib/models/model.dart | 18 ----- flutter/lib/models/peer_model.dart | 17 ++-- src/flutter_ffi.rs | 47 +++++++++-- src/ui.rs | 17 ++-- src/ui_interface.rs | 16 ++-- 7 files changed, 106 insertions(+), 89 deletions(-) diff --git a/flutter/lib/common/widgets/peer_widget.dart b/flutter/lib/common/widgets/peer_widget.dart index bdfbe53e5..e6236ff4e 100644 --- a/flutter/lib/common/widgets/peer_widget.dart +++ b/flutter/lib/common/widgets/peer_widget.dart @@ -303,7 +303,7 @@ class AddressBookPeerWidget extends BasePeerWidget { static List _loadPeers() { debugPrint("_loadPeers : ${gFFI.abModel.peers.toString()}"); return gFFI.abModel.peers.map((e) { - return Peer.fromJson(e['id'], e); + return Peer.fromJson(e); }).toList(); } diff --git a/flutter/lib/common/widgets/peercard_widget.dart b/flutter/lib/common/widgets/peercard_widget.dart index e3bc81af2..ecf89283a 100644 --- a/flutter/lib/common/widgets/peercard_widget.dart +++ b/flutter/lib/common/widgets/peercard_widget.dart @@ -27,13 +27,11 @@ final peerCardUiType = PeerUiType.grid.obs; class _PeerCard extends StatefulWidget { final Peer peer; - final RxString alias; final Function(BuildContext, String) connect; final PopupMenuEntryBuilder popupMenuEntryBuilder; const _PeerCard( {required this.peer, - required this.alias, required this.connect, required this.popupMenuEntryBuilder, Key? key}) @@ -77,7 +75,7 @@ class _PeerCardState extends State<_PeerCard> child: ListTile( contentPadding: const EdgeInsets.only(left: 12), subtitle: Text('${peer.username}@${peer.hostname}'), - title: Text(formatID(peer.id)), + title: Text(peer.alias.isEmpty ? formatID(peer.id) : peer.alias), leading: Container( padding: const EdgeInsets.all(6), color: str2color('${peer.id}${peer.platform}', 0x7f), @@ -216,6 +214,7 @@ class _PeerCardState extends State<_PeerCard> Widget _buildPeerCard( BuildContext context, Peer peer, Rx deco) { + final name = '${peer.username}@${peer.hostname}'; return Card( color: Colors.transparent, elevation: 0, @@ -246,24 +245,18 @@ class _PeerCardState extends State<_PeerCard> Row( children: [ Expanded( - child: Obx(() { - final name = widget.alias.value.isEmpty - ? '${peer.username}@${peer.hostname}' - : widget.alias.value; - return Tooltip( - message: name, - waitDuration: - const Duration(seconds: 1), - child: Text( - name, - style: const TextStyle( - color: Colors.white70, - fontSize: 12), - textAlign: TextAlign.center, - overflow: TextOverflow.ellipsis, - ), - ); - }), + child: Tooltip( + message: name, + waitDuration: const Duration(seconds: 1), + child: Text( + name, + style: const TextStyle( + color: Colors.white70, + fontSize: 12), + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + ), + ), ), ], ), @@ -287,7 +280,8 @@ class _PeerCardState extends State<_PeerCard> backgroundColor: peer.online ? Colors.green : Colors.yellow)), - Text(formatID(peer.id)) + Text( + peer.alias.isEmpty ? formatID(peer.id) : peer.alias) ]).paddingSymmetric(vertical: 8), _actionMore(peer), ], @@ -338,20 +332,14 @@ class _PeerCardState extends State<_PeerCard> } abstract class BasePeerCard extends StatelessWidget { - final RxString alias = ''.obs; final Peer peer; - BasePeerCard({required this.peer, Key? key}) : super(key: key) { - bind - .mainGetPeerOption(id: peer.id, key: 'alias') - .then((value) => alias.value = value); - } + BasePeerCard({required this.peer, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return _PeerCard( peer: peer, - alias: alias, connect: (BuildContext context, String id) => connect(context, id), popupMenuEntryBuilder: _buildPopupMenuEntry, ); @@ -379,7 +367,7 @@ abstract class BasePeerCard extends StatelessWidget { bool isRDP = false}) { return MenuEntryButton( childBuilder: (TextStyle? style) => Text( - translate(title), + title, style: style, ), proc: () { @@ -396,8 +384,13 @@ abstract class BasePeerCard extends StatelessWidget { } @protected - MenuEntryBase _connectAction(BuildContext context, String id) { - return _connectCommonAction(context, id, 'Connect'); + MenuEntryBase _connectAction(BuildContext context, Peer peer) { + return _connectCommonAction( + context, + peer.id, + peer.alias.isEmpty + ? translate('Connect') + : "${translate('Connect')} ${peer.id}"); } @protected @@ -405,7 +398,7 @@ abstract class BasePeerCard extends StatelessWidget { return _connectCommonAction( context, id, - 'Transfer File', + translate('Transfer File'), isFileTransfer: true, ); } @@ -415,7 +408,7 @@ abstract class BasePeerCard extends StatelessWidget { return _connectCommonAction( context, id, - 'TCP Tunneling', + translate('TCP Tunneling'), isTcpTunneling: true, ); } @@ -578,7 +571,7 @@ abstract class BasePeerCard extends StatelessWidget { void _rename(String id, bool isAddressBook) async { RxBool isInProgress = false.obs; - var name = await bind.mainGetPeerOption(id: id, key: 'alias'); + var name = peer.alias; var controller = TextEditingController(text: name); if (isAddressBook) { final peer = gFFI.abModel.peers.firstWhere((p) => id == p['id']); @@ -597,7 +590,12 @@ abstract class BasePeerCard extends StatelessWidget { gFFI.abModel.setPeerOption(id, 'alias', name); await gFFI.abModel.updateAb(); } - alias.value = await bind.mainGetPeerOption(id: peer.id, key: 'alias'); + if (isAddressBook) { + gFFI.abModel.getAb(); + } else { + bind.mainLoadRecentPeers(); + bind.mainLoadFavPeers(); + } close(); isInProgress.value = false; } @@ -642,7 +640,7 @@ class RecentPeerCard extends BasePeerCard { Future>> _buildMenuItems( BuildContext context) async { final List> menuItems = [ - _connectAction(context, peer.id), + _connectAction(context, peer), _transferFileAction(context, peer.id), _tcpTunnelingAction(context, peer.id), ]; @@ -674,7 +672,7 @@ class FavoritePeerCard extends BasePeerCard { Future>> _buildMenuItems( BuildContext context) async { final List> menuItems = [ - _connectAction(context, peer.id), + _connectAction(context, peer), _transferFileAction(context, peer.id), _tcpTunnelingAction(context, peer.id), ]; @@ -708,7 +706,7 @@ class DiscoveredPeerCard extends BasePeerCard { Future>> _buildMenuItems( BuildContext context) async { final List> menuItems = [ - _connectAction(context, peer.id), + _connectAction(context, peer), _transferFileAction(context, peer.id), _tcpTunnelingAction(context, peer.id), ]; @@ -739,7 +737,7 @@ class AddressBookPeerCard extends BasePeerCard { Future>> _buildMenuItems( BuildContext context) async { final List> menuItems = [ - _connectAction(context, peer.id), + _connectAction(context, peer), _transferFileAction(context, peer.id), _tcpTunnelingAction(context, peer.id), ]; diff --git a/flutter/lib/models/model.dart b/flutter/lib/models/model.dart index b9225414d..237378166 100644 --- a/flutter/lib/models/model.dart +++ b/flutter/lib/models/model.dart @@ -22,7 +22,6 @@ import '../common.dart'; import '../common/shared_state.dart'; import '../utils/image.dart' as img; import '../mobile/widgets/dialog.dart'; -import 'peer_model.dart'; import 'platform_model.dart'; typedef HandleMsgBox = Function(Map evt, String id); @@ -1107,23 +1106,6 @@ class FFI { id: id, msg: json.encode(modify({'x': '$x2', 'y': '$y2'}))); } - /// List the saved peers. - Future> peers() async { - try { - var str = await bind.mainGetRecentPeers(); - if (str == '') return []; - List peers = json.decode(str); - return peers - .map((s) => s as List) - .map((s) => - Peer.fromJson(s[0] as String, s[1] as Map)) - .toList(); - } catch (e) { - debugPrint('peers(): $e'); - } - return []; - } - /// Connect with the given [id]. Only transfer file if [isFileTransfer], only port forward if [isPortForward]. connect(String id, {bool isFileTransfer = false, diff --git a/flutter/lib/models/peer_model.dart b/flutter/lib/models/peer_model.dart index 0857bfcf8..c68ca26df 100644 --- a/flutter/lib/models/peer_model.dart +++ b/flutter/lib/models/peer_model.dart @@ -7,13 +7,16 @@ class Peer { final String username; final String hostname; final String platform; + final String alias; final List tags; bool online = false; - Peer.fromJson(this.id, Map json) - : username = json['username'] ?? '', + Peer.fromJson(Map json) + : id = json['id'] ?? '', + username = json['username'] ?? '', hostname = json['hostname'] ?? '', platform = json['platform'] ?? '', + alias = json['alias'] ?? '', tags = json['tags'] ?? []; Peer({ @@ -21,6 +24,7 @@ class Peer { required this.username, required this.hostname, required this.platform, + required this.alias, required this.tags, }); @@ -30,6 +34,7 @@ class Peer { username: '...', hostname: '...', platform: '...', + alias: '', tags: []); } @@ -109,11 +114,9 @@ class Peers extends ChangeNotifier { try { if (peersStr == "") return []; List peers = json.decode(peersStr); - return peers - .map((s) => s as List) - .map((s) => - Peer.fromJson(s[0] as String, s[1] as Map)) - .toList(); + return peers.map((peer) { + return Peer.fromJson(peer as Map); + }).toList(); } catch (e) { debugPrint('peers(): $e'); } diff --git a/src/flutter_ffi.rs b/src/flutter_ffi.rs index 253855e3f..0579ac272 100644 --- a/src/flutter_ffi.rs +++ b/src/flutter_ffi.rs @@ -7,11 +7,11 @@ use std::{ use flutter_rust_bridge::{StreamSink, SyncReturn, ZeroCopyBuffer}; use serde_json::json; -use hbb_common::ResultType; use hbb_common::{ config::{self, LocalConfig, PeerConfig, ONLINE}, fs, log, }; +use hbb_common::{message_proto::Hash, ResultType}; use crate::flutter::{self, SESSIONS}; use crate::start_server; @@ -567,9 +567,20 @@ pub fn main_forget_password(id: String) { pub fn main_get_recent_peers() -> String { if !config::APP_DIR.read().unwrap().is_empty() { - let peers: Vec<(String, config::PeerInfoSerde)> = PeerConfig::peers() + let peers: Vec> = PeerConfig::peers() .drain(..) - .map(|(id, _, p)| (id, p.info)) + .map(|(id, _, p)| { + HashMap::<&str, String>::from_iter([ + ("id", id), + ("username", p.info.username.clone()), + ("hostname", p.info.hostname.clone()), + ("platform", p.info.platform.clone()), + ( + "alias", + p.options.get("alias").unwrap_or(&"".to_owned()).to_owned(), + ), + ]) + }) .collect(); serde_json::ser::to_string(&peers).unwrap_or("".to_owned()) } else { @@ -579,9 +590,20 @@ pub fn main_get_recent_peers() -> String { pub fn main_load_recent_peers() { if !config::APP_DIR.read().unwrap().is_empty() { - let peers: Vec<(String, config::PeerInfoSerde)> = PeerConfig::peers() + let peers: Vec> = PeerConfig::peers() .drain(..) - .map(|(id, _, p)| (id, p.info)) + .map(|(id, _, p)| { + HashMap::<&str, String>::from_iter([ + ("id", id), + ("username", p.info.username.clone()), + ("hostname", p.info.hostname.clone()), + ("platform", p.info.platform.clone()), + ( + "alias", + p.options.get("alias").unwrap_or(&"".to_owned()).to_owned(), + ), + ]) + }) .collect(); if let Some(s) = flutter::GLOBAL_EVENT_STREAM .read() @@ -603,11 +625,20 @@ pub fn main_load_recent_peers() { pub fn main_load_fav_peers() { if !config::APP_DIR.read().unwrap().is_empty() { let favs = get_fav(); - let peers: Vec<(String, config::PeerInfoSerde)> = PeerConfig::peers() + let peers: Vec> = PeerConfig::peers() .into_iter() - .filter_map(|(id, _, peer)| { + .filter_map(|(id, _, p)| { if favs.contains(&id) { - Some((id, peer.info)) + Some(HashMap::<&str, String>::from_iter([ + ("id", id), + ("username", p.info.username.clone()), + ("hostname", p.info.hostname.clone()), + ("platform", p.info.platform.clone()), + ( + "alias", + p.options.get("alias").unwrap_or(&"".to_owned()).to_owned(), + ), + ])) } else { None } diff --git a/src/ui.rs b/src/ui.rs index 77d983e56..d1c669848 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -18,7 +18,7 @@ use hbb_common::{ tokio::{self, sync::mpsc, time}, }; -use crate::common::{get_app_name}; +use crate::common::get_app_name; use crate::ipc; use crate::ui_interface::{ check_mouse_time, closing, create_shortcut, current_is_wayland, fix_login_wayland, @@ -73,9 +73,7 @@ fn check_connect_status( let (tx, rx) = mpsc::unbounded_channel::(); let password = Arc::new(Mutex::new(String::default())); let cloned_password = password.clone(); - std::thread::spawn(move || { - crate::ui_interface::check_connect_status_(reconnect, rx) - }); + std::thread::spawn(move || crate::ui_interface::check_connect_status_(reconnect, rx)); (status, options, tx, password) } @@ -525,9 +523,16 @@ impl UI { fn get_lan_peers(&self) -> String { let peers = get_lan_peers() .into_iter() - .map(|(id, peer)| (id, peer.username, peer.hostname, peer.platform)) + .map(|mut peer| { + ( + peer.remove("id").unwrap_or_default(), + peer.remove("username").unwrap_or_default(), + peer.remove("hostname").unwrap_or_default(), + peer.remove("platform").unwrap_or_default(), + ) + }) .collect::>(); - serde_json::to_string(&peers).unwrap_or_default() + serde_json::to_string(&get_lan_peers()).unwrap_or_default() } fn get_uuid(&self) -> String { diff --git a/src/ui_interface.rs b/src/ui_interface.rs index 7242a35dc..dc3a02c7a 100644 --- a/src/ui_interface.rs +++ b/src/ui_interface.rs @@ -648,19 +648,17 @@ pub fn discover() { } #[inline] -pub fn get_lan_peers() -> Vec<(String, config::PeerInfoSerde)> { +pub fn get_lan_peers() -> Vec> { config::LanPeers::load() .peers .iter() .map(|peer| { - ( - peer.id.clone(), - config::PeerInfoSerde { - username: peer.username.clone(), - hostname: peer.hostname.clone(), - platform: peer.platform.clone(), - }, - ) + HashMap::<&str, String>::from_iter([ + ("id", peer.id.clone()), + ("username", peer.username.clone()), + ("hostname", peer.hostname.clone()), + ("platform", peer.platform.clone()), + ]) }) .collect() }