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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! Define the net subcommands.
use std::{net::SocketAddr, time::Duration};

use anyhow::Result;
use clap::Subcommand;
use colored::Colorize;
use comfy_table::{presets::NOTHING, Cell, Table};
use futures_lite::{Stream, StreamExt};
use human_time::ToHumanTimeString;
use iroh::{
    endpoint::{DirectAddrInfo, RemoteInfo},
    NodeAddr, NodeId, RelayUrl,
};

/// Commands to manage the iroh network.
#[derive(Subcommand, Debug, Clone)]
#[allow(clippy::large_enum_variant, missing_docs)]
pub enum NetCommands {
    /// Get information about the different remote nodes.
    RemoteList,
    /// Get information about a particular remote node.
    Remote { node_id: NodeId },
    /// Get the node addr of this node.
    NodeAddr,
    /// Add this node addr to the known nodes.
    AddNodeAddr {
        node_id: NodeId,
        relay: Option<RelayUrl>,
        addresses: Vec<SocketAddr>,
    },
    /// Get the relay server we are connected to.
    HomeRelay,
}

impl NetCommands {
    /// Runs the net command given the iroh client.
    pub async fn run(self, client: &crate::rpc::client::net::Client) -> Result<()> {
        match self {
            Self::RemoteList => {
                let connections = client.remote_info_iter().await?;
                let timestamp = time::OffsetDateTime::now_utc()
                    .format(&time::format_description::well_known::Rfc2822)
                    .unwrap_or_else(|_| String::from("failed to get current time"));

                println!(
                    " {}: {}\n\n{}",
                    "current time".bold(),
                    timestamp,
                    fmt_remote_infos(connections).await
                );
            }
            Self::Remote { node_id } => {
                let info = client.remote_info(node_id).await?;
                match info {
                    Some(info) => println!("{}", fmt_info(info)),
                    None => println!("Not Found"),
                }
            }
            Self::NodeAddr => {
                let addr = client.node_addr().await?;
                println!("Node ID: {}", addr.node_id);
                let relay = addr
                    .info
                    .relay_url
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "Not Available".to_string());
                println!("Home Relay: {}", relay);
                println!("Direct Addresses ({}):", addr.info.direct_addresses.len());
                for da in &addr.info.direct_addresses {
                    println!(" {}", da);
                }
            }
            Self::AddNodeAddr {
                node_id,
                relay,
                addresses,
            } => {
                let mut addr = NodeAddr::new(node_id).with_direct_addresses(addresses);
                if let Some(relay) = relay {
                    addr = addr.with_relay_url(relay);
                }
                client.add_node_addr(addr).await?;
            }
            Self::HomeRelay => {
                let relay = client.home_relay().await?;
                let relay = relay
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| "Not Available".to_string());
                println!("Home Relay: {}", relay);
            }
        }
        Ok(())
    }
}

/// Formats the remote information into a `Table`.
async fn fmt_remote_infos(
    mut infos: impl Stream<Item = Result<RemoteInfo, anyhow::Error>> + Unpin,
) -> String {
    let mut table = Table::new();
    table.load_preset(NOTHING).set_header(
        ["node id", "relay", "conn type", "latency", "last used"]
            .into_iter()
            .map(bold_cell),
    );
    while let Some(Ok(info)) = infos.next().await {
        let node_id: Cell = info.node_id.to_string().into();
        let relay_url = info
            .relay_url
            .map_or(String::new(), |url_info| url_info.relay_url.to_string())
            .into();
        let conn_type = info.conn_type.to_string().into();
        let latency = match info.latency {
            Some(latency) => latency.to_human_time_string(),
            None => String::from("unknown"),
        }
        .into();
        let last_used = info
            .last_used
            .map(fmt_how_long_ago)
            .map(Cell::new)
            .unwrap_or_else(never);
        table.add_row([node_id, relay_url, conn_type, latency, last_used]);
    }
    table.to_string()
}

/// Formats the remote information into a `String`.
fn fmt_info(info: RemoteInfo) -> String {
    let RemoteInfo {
        node_id,
        relay_url,
        addrs,
        conn_type,
        latency,
        last_used,
    } = info;
    let timestamp = time::OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc2822)
        .unwrap_or_else(|_| String::from("failed to get current time"));
    let mut table = Table::new();
    table.load_preset(NOTHING);
    table.add_row([bold_cell("current time"), timestamp.into()]);
    table.add_row([bold_cell("node id"), node_id.to_string().into()]);
    let relay_url = relay_url
        .map(|r| r.relay_url.to_string())
        .unwrap_or_else(|| String::from("unknown"));
    table.add_row([bold_cell("relay url"), relay_url.into()]);
    table.add_row([bold_cell("connection type"), conn_type.to_string().into()]);
    table.add_row([bold_cell("latency"), fmt_latency(latency).into()]);
    table.add_row([
        bold_cell("last used"),
        last_used
            .map(fmt_how_long_ago)
            .map(Cell::new)
            .unwrap_or_else(never),
    ]);
    table.add_row([bold_cell("known addresses"), addrs.len().into()]);

    let general_info = table.to_string();

    let addrs_info = fmt_addrs(addrs);

    format!("{general_info}\n\n{addrs_info}")
}

/// Formats the [`DirectAddrInfo`] into a [`Table`].
fn direct_addr_row(info: DirectAddrInfo) -> comfy_table::Row {
    let DirectAddrInfo {
        addr,
        latency,
        last_control,
        last_payload,
        last_alive,
        ..
    } = info;

    let last_control = match last_control {
        None => never(),
        Some((how_long_ago, kind)) => {
            format!("{kind} ( {} )", fmt_how_long_ago(how_long_ago)).into()
        }
    };
    let last_payload = last_payload
        .map(fmt_how_long_ago)
        .map(Cell::new)
        .unwrap_or_else(never);

    let last_alive = last_alive
        .map(fmt_how_long_ago)
        .map(Cell::new)
        .unwrap_or_else(never);

    [
        addr.into(),
        fmt_latency(latency).into(),
        last_control,
        last_payload,
        last_alive,
    ]
    .into()
}

/// Formats a collection o [`DirectAddrInfo`] into a [`Table`].
fn fmt_addrs(addrs: Vec<DirectAddrInfo>) -> comfy_table::Table {
    let mut table = Table::new();
    table.load_preset(NOTHING).set_header(
        vec!["addr", "latency", "last control", "last data", "last alive"]
            .into_iter()
            .map(bold_cell),
    );
    table.add_rows(addrs.into_iter().map(direct_addr_row));
    table
}

/// Creates a cell with the dimmed text "never".
fn never() -> Cell {
    Cell::new("never").add_attribute(comfy_table::Attribute::Dim)
}

/// Formats a [`Duration`] into a human-readable `String`.
fn fmt_how_long_ago(duration: Duration) -> String {
    duration
        .to_human_time_string()
        .split_once(',')
        .map(|(first, _rest)| first)
        .unwrap_or("-")
        .to_string()
}

/// Formats the latency into a human-readable `String`.
fn fmt_latency(latency: Option<Duration>) -> String {
    match latency {
        Some(latency) => latency.to_human_time_string(),
        None => String::from("unknown"),
    }
}

/// Creates a bold cell with the given text.
fn bold_cell(s: &str) -> Cell {
    Cell::new(s).add_attribute(comfy_table::Attribute::Bold)
}