1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use super::{
super::ctrl::{self, ForwardNetMsg, UiClientPeer, UiUpdateMsg},
sm::*,
subs::peer_representation,
};
use crossbeam::channel::Sender;
use libp2p::core::{Multiaddr, PeerId};
use std::collections::HashSet;
pub struct UiData {
sender: Option<Sender<UiUpdateMsg>>,
ui_shown_peers: HashSet<PeerId>,
}
impl UiData {
pub fn new(sender: Option<Sender<UiUpdateMsg>>) -> Self {
Self {
sender,
ui_shown_peers: HashSet::new(),
}
}
pub fn has_peer(&mut self, peer_id: &PeerId) -> bool {
let ref collection = self.ui_shown_peers;
collection.get(peer_id).is_some()
}
pub fn register_address(&mut self, peer_id: &PeerId, multi_addresses: &Multiaddr) {
let ref mut collection = self.ui_shown_peers;
if collection.get(peer_id).is_none() {
collection.insert(peer_id.clone());
trace!(
"found new peer {}",
peer_representation::peer_to_hash_string(peer_id)
);
if let Some(ctrl_sender) = &self.sender {
let addr_as_string = multi_addresses.iter().map(|x| x.to_string()).collect();
ctrl_sender
.send(ctrl::UiUpdateMsg::NetUpdate(ForwardNetMsg::Add(
UiClientPeer {
id: peer_id.clone(),
addresses: addr_as_string,
},
)))
.unwrap_or_else(|e| error!("use one: {}", e));
}
} else {
error!("Hey, the StateMachine should have made this impossible!!!");
}
}
pub fn unregister_address(&mut self, peer_id: &PeerId) {
let ref mut collection = self.ui_shown_peers;
if collection.remove(peer_id) {
trace!(
"removed peer {}",
peer_representation::peer_to_hash_string(peer_id)
);
if let Some(ctrl_sender) = &self.sender {
ctrl_sender
.send(ctrl::UiUpdateMsg::NetUpdate(ForwardNetMsg::Delete(
peer_id.clone(),
)))
.unwrap_or_else(|e| error!("use one: {}", e));
}
} else {
warn!("Trying to remove something which wasn't there ...");
}
}
pub fn update_peer_data(&mut self, update_data: &UpdateData) {
if self.has_peer(&update_data.id) {
if let Some(ctrl_sender) = &self.sender {
ctrl_sender
.send(ctrl::UiUpdateMsg::PeerSearchFinished(
update_data.id.clone(),
update_data.data.clone(),
))
.unwrap_or_else(|e| error!("use one: {}", e));
}
} else {
warn!(
"Peer {} is not known!",
peer_representation::peer_to_hash_string(&update_data.id)
);
}
}
}