p2p_chat/ui/runner/actions/
resolver.rs

1//! This module provides utility functions for resolving peer IDs.
2use std::str::FromStr;
3
4use anyhow::{anyhow, Result};
5use libp2p::PeerId;
6
7use super::context::CommandContext;
8
9/// Resolves a `PeerId` from a string, which can be either a direct `PeerId`
10/// or a friend's nickname.
11///
12/// # Arguments
13///
14/// * `destination` - The string to resolve (Peer ID or nickname).
15/// * `context` - The `CommandContext` for accessing friend information.
16///
17/// # Returns
18///
19/// A `Result` containing the resolved `PeerId` or an error if the peer
20/// cannot be found.
21pub(crate) async fn resolve_peer_id(destination: &str, context: &CommandContext) -> Result<PeerId> {
22    if let Ok(peer_id) = PeerId::from_str(destination) {
23        return Ok(peer_id);
24    }
25
26    let friends = context.node().friends.list_friends().await?;
27    friends
28        .into_iter()
29        .find(|f| f.nickname.as_deref() == Some(destination))
30        .map(|f| f.peer_id)
31        .ok_or_else(|| anyhow!("Peer not found by ID or nickname: '{}'", destination))
32}