p2p_chat/ui/runner/actions/commands/
peers.rs

1//! This module contains the command handler for listing connected peers.
2use anyhow::Result;
3
4use crate::ui::UIEvent;
5
6use super::super::context::CommandContext;
7
8/// Lists all currently connected peers and their roles (friend, mailbox, or generic peer).
9///
10/// # Arguments
11///
12/// * `context` - The `CommandContext` providing access to the application's state and network.
13///
14/// # Errors
15///
16/// This function returns an error if retrieving the peer list from the network fails.
17pub async fn list_peers(context: &CommandContext) -> Result<()> {
18    match context.node().network.get_connected_peers().await {
19        Ok(peers) => {
20            let mailboxes = {
21                let sync_engine = context.node().sync_engine.lock().await;
22                sync_engine.get_mailbox_providers().clone()
23            };
24
25            context.emit(UIEvent::UpdatePeersCount(peers.len()));
26            let peer_strings: Vec<String> = peers.iter().map(|p| p.to_string()).collect();
27            context.emit(UIEvent::UpdateDiscoveredPeers(peer_strings));
28
29            if peers.is_empty() {
30                context.emit_chat("No peers currently connected.");
31            } else {
32                let mut output = format!("Connected peers ({}):", peers.len());
33                for peer in &peers {
34                    if let Ok(Some(friend)) = context.node().friends.get_friend(peer).await {
35                        let nickname = friend.nickname.as_deref().unwrap_or("(no nickname)");
36                        output.push_str(&format!("\n  {} - {} (👥 Friend)", peer, nickname));
37                    } else if mailboxes.contains(peer) {
38                        output.push_str(&format!("\n  {} - 📬 Mailbox", peer));
39                    } else {
40                        output.push_str(&format!("\n  {} - 🌐 Peer", peer));
41                    }
42                }
43                context.emit_chat(output);
44            }
45        }
46        Err(e) => {
47            context.emit_chat(format!("❌ Failed to get peer list: {}", e));
48        }
49    }
50
51    Ok(())
52}