speedtest-tui 0.1.1

A terminal-based network speed test tool with real-time gauges and graphs
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use anyhow::Result;
use clap::{Parser, Subcommand};

use crate::config::Config;
use crate::network::{self, providers::Provider, SpeedTestResult};
use crate::storage;

#[derive(Parser)]
#[command(name = "speedtest-tui")]
#[command(author, version, about = "A beautiful TUI network speed test tool", long_about = None)]
pub struct Cli {
    /// Run a quick test with text output only
    #[arg(short, long)]
    pub simple: bool,

    /// Output results as JSON
    #[arg(long)]
    pub json: bool,

    /// Output results as CSV
    #[arg(long)]
    pub csv: bool,

    /// Select provider (cloudflare, librespeed, custom)
    #[arg(short, long, default_value = "cloudflare")]
    pub provider: String,

    /// Run download test only
    #[arg(long)]
    pub download_only: bool,

    /// Run upload test only
    #[arg(long)]
    pub upload_only: bool,

    /// Skip upload test
    #[arg(long)]
    pub no_upload: bool,

    /// Select specific server by ID
    #[arg(long)]
    pub server: Option<String>,

    /// List available servers
    #[arg(long)]
    pub list_servers: bool,

    #[command(subcommand)]
    pub command: Option<Commands>,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Run full network diagnostics
    Diagnose,

    /// Ping a specific host
    Ping {
        /// Host to ping
        host: String,
    },

    /// Traceroute to a host
    Traceroute {
        /// Host to trace
        host: String,
    },

    /// DNS lookup timing
    Dns {
        /// Domain to lookup
        domain: String,
    },

    /// List network interfaces
    Interfaces,

    /// View or manage test history
    History {
        /// Export history to CSV
        #[arg(long)]
        export: bool,

        /// Clear all history
        #[arg(long)]
        clear: bool,
    },
}

pub async fn run_simple_test(cli: &Cli) -> Result<()> {
    println!("Speedtest TUI - Network Speed Test\n");

    let config = Config::load()?;
    let provider = get_provider(&cli.provider)?;

    // Get connection info
    print!("Retrieving connection info... ");
    let conn_info = network::connection::get_connection_info().await?;
    println!("Done");
    println!("  IP: {}", conn_info.ip);
    if let Some(ref isp) = conn_info.isp {
        println!("  ISP: {}", isp);
    }
    if let Some(ref location) = conn_info.location {
        println!("  Location: {}", location);
    }
    println!();

    // Ping test
    if !cli.download_only && !cli.upload_only {
        print!("Testing ping... ");
        let ping_result = network::ping::measure_ping(&provider.get_ping_url()).await?;
        println!("Done");
        println!("  Latency: {:.2} ms", ping_result.latency_ms);
        println!("  Jitter: {:.2} ms", ping_result.jitter_ms);
        println!();
    }

    // Download test
    if !cli.upload_only {
        print!("Testing download speed... ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let download_result = network::download::measure_download(
            &provider.get_download_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await?;
        println!("Done");
        println!("  Download: {:.2} Mbps", download_result.speed_mbps);
        println!("  Peak: {:.2} Mbps", download_result.peak_speed_mbps);
        println!();
    }

    // Upload test
    if !cli.no_upload && !cli.download_only {
        print!("Testing upload speed... ");
        std::io::Write::flush(&mut std::io::stdout())?;
        let upload_result = network::upload::measure_upload(
            &provider.get_upload_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await?;
        println!("Done");
        println!("  Upload: {:.2} Mbps", upload_result.speed_mbps);
        println!("  Peak: {:.2} Mbps", upload_result.peak_speed_mbps);
    }

    Ok(())
}

pub async fn run_json_test(cli: &Cli) -> Result<()> {
    let config = Config::load()?;
    let provider = get_provider(&cli.provider)?;

    let mut result = SpeedTestResult {
        provider: cli.provider.clone(),
        timestamp: chrono::Utc::now(),
        ..Default::default()
    };

    // Connection info
    if let Ok(conn_info) = network::connection::get_connection_info().await {
        result.connection_info = Some(conn_info);
    }

    // Ping
    if !cli.download_only && !cli.upload_only {
        if let Ok(ping) = network::ping::measure_ping(&provider.get_ping_url()).await {
            result.ping = Some(ping);
        }
    }

    // Download
    if !cli.upload_only {
        if let Ok(download) = network::download::measure_download(
            &provider.get_download_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await
        {
            result.download = Some(download);
        }
    }

    // Upload
    if !cli.no_upload && !cli.download_only {
        if let Ok(upload) = network::upload::measure_upload(
            &provider.get_upload_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await
        {
            result.upload = Some(upload);
        }
    }

    println!("{}", serde_json::to_string_pretty(&result)?);
    Ok(())
}

pub async fn run_csv_test(cli: &Cli) -> Result<()> {
    let config = Config::load()?;
    let provider = get_provider(&cli.provider)?;

    let mut result = SpeedTestResult {
        provider: cli.provider.clone(),
        timestamp: chrono::Utc::now(),
        ..Default::default()
    };

    // Ping
    if !cli.download_only && !cli.upload_only {
        if let Ok(ping) = network::ping::measure_ping(&provider.get_ping_url()).await {
            result.ping = Some(ping);
        }
    }

    // Download
    if !cli.upload_only {
        if let Ok(download) = network::download::measure_download(
            &provider.get_download_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await
        {
            result.download = Some(download);
        }
    }

    // Upload
    if !cli.no_upload && !cli.download_only {
        if let Ok(upload) = network::upload::measure_upload(
            &provider.get_upload_url(),
            config.general.test_duration_seconds,
            |_| {},
        )
        .await
        {
            result.upload = Some(upload);
        }
    }

    // Print CSV header and data
    println!("timestamp,provider,ping_ms,jitter_ms,download_mbps,upload_mbps");
    println!(
        "{},{},{:.2},{:.2},{:.2},{:.2}",
        result.timestamp.format("%Y-%m-%d %H:%M:%S"),
        result.provider,
        result.ping.as_ref().map(|p| p.latency_ms).unwrap_or(0.0),
        result.ping.as_ref().map(|p| p.jitter_ms).unwrap_or(0.0),
        result
            .download
            .as_ref()
            .map(|d| d.speed_mbps)
            .unwrap_or(0.0),
        result.upload.as_ref().map(|u| u.speed_mbps).unwrap_or(0.0),
    );

    Ok(())
}

pub async fn run_diagnose() -> Result<()> {
    println!("Network Diagnostics\n");
    println!("==================\n");

    // Connection info
    println!("Connection Information:");
    match network::connection::get_connection_info().await {
        Ok(info) => {
            println!("  Public IP: {}", info.ip);
            if let Some(ref isp) = info.isp {
                println!("  ISP: {}", isp);
            }
            if let Some(ref location) = info.location {
                println!("  Location: {}", location);
            }
        }
        Err(e) => println!("  Error: {}", e),
    }
    println!();

    // DNS test
    println!("DNS Resolution (google.com):");
    match network::dns::measure_dns("google.com").await {
        Ok(result) => {
            println!("  Resolution time: {:.2} ms", result.resolution_time_ms);
            println!("  Resolved IPs: {:?}", result.resolved_ips);
        }
        Err(e) => println!("  Error: {}", e),
    }
    println!();

    // Network interfaces
    println!("Network Interfaces:");
    let interfaces = network::interfaces::list_interfaces()?;
    for iface in interfaces {
        println!(
            "  {} - {} ({})",
            iface.name,
            iface.ip,
            if iface.is_up { "up" } else { "down" }
        );
    }
    println!();

    // Ping to common servers
    println!("Latency Tests:");
    for (name, url) in &[
        ("Cloudflare", "https://speed.cloudflare.com"),
        ("Google", "https://www.google.com"),
    ] {
        match network::ping::measure_ping(url).await {
            Ok(result) => {
                println!(
                    "  {}: {:.2} ms (jitter: {:.2} ms)",
                    name, result.latency_ms, result.jitter_ms
                );
            }
            Err(e) => println!("  {}: Error - {}", name, e),
        }
    }

    Ok(())
}

pub async fn run_ping(host: &str) -> Result<()> {
    let url = if host.starts_with("http") {
        host.to_string()
    } else {
        format!("https://{}", host)
    };

    println!("Pinging {}...\n", host);

    for i in 1..=5 {
        match network::ping::single_ping(&url).await {
            Ok(ms) => println!("  [{}/5] {:.2} ms", i, ms),
            Err(e) => println!("  [{}/5] Error: {}", i, e),
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
    }

    let result = network::ping::measure_ping(&url).await?;
    println!("\nStatistics:");
    println!("  Average: {:.2} ms", result.latency_ms);
    println!("  Jitter: {:.2} ms", result.jitter_ms);
    println!("  Min: {:.2} ms", result.min_ms);
    println!("  Max: {:.2} ms", result.max_ms);

    Ok(())
}

pub async fn run_traceroute(host: &str) -> Result<()> {
    println!("Traceroute to {}\n", host);

    let hops = network::traceroute::trace_route(host).await?;

    for hop in hops {
        if let Some(ref addr) = hop.address {
            println!(
                "{:>2}. {:>15}  {:.2} ms",
                hop.hop_number, addr, hop.latency_ms
            );
        } else {
            println!("{:>2}. *  Request timed out", hop.hop_number);
        }
    }

    Ok(())
}

pub async fn run_dns(domain: &str) -> Result<()> {
    println!("DNS Lookup for {}\n", domain);

    let result = network::dns::measure_dns(domain).await?;

    println!("Resolution time: {:.2} ms", result.resolution_time_ms);
    println!("\nResolved addresses:");
    for ip in &result.resolved_ips {
        println!("  {}", ip);
    }

    Ok(())
}

pub fn run_interfaces() -> Result<()> {
    println!("Network Interfaces\n");

    let interfaces = network::interfaces::list_interfaces()?;

    for iface in interfaces {
        let status = if iface.is_up { "UP" } else { "DOWN" };
        println!("{}", iface.name);
        println!("  Status: {}", status);
        println!("  IP: {}", iface.ip);
        if let Some(ref mac) = iface.mac {
            println!("  MAC: {}", mac);
        }
        println!();
    }

    Ok(())
}

pub async fn run_history(export: bool, clear: bool) -> Result<()> {
    if clear {
        storage::history::clear_history()?;
        println!("History cleared.");
        return Ok(());
    }

    if export {
        let path = storage::export::export_to_csv()?;
        println!("History exported to: {}", path.display());
        return Ok(());
    }

    // Display history
    let history = storage::history::load_history()?;

    if history.is_empty() {
        println!("No test history found.");
        return Ok(());
    }

    println!("Test History\n");
    println!(
        "{:<20} {:<12} {:<12} {:<12} {:<8}",
        "Date", "Provider", "Download", "Upload", "Ping"
    );
    println!("{}", "-".repeat(70));

    for entry in history.iter().rev().take(20) {
        let download = entry
            .download
            .as_ref()
            .map(|d| format!("{:.1} Mbps", d.speed_mbps))
            .unwrap_or_else(|| "-".to_string());
        let upload = entry
            .upload
            .as_ref()
            .map(|u| format!("{:.1} Mbps", u.speed_mbps))
            .unwrap_or_else(|| "-".to_string());
        let ping = entry
            .ping
            .as_ref()
            .map(|p| format!("{:.0} ms", p.latency_ms))
            .unwrap_or_else(|| "-".to_string());

        println!(
            "{:<20} {:<12} {:<12} {:<12} {:<8}",
            entry.timestamp.format("%Y-%m-%d %H:%M"),
            entry.provider,
            download,
            upload,
            ping
        );
    }

    Ok(())
}

fn get_provider(name: &str) -> Result<Box<dyn Provider>> {
    use crate::config::Config;
    use crate::network::providers::{
        cloudflare::CloudflareProvider, custom::CustomProvider, librespeed::LibrespeedProvider,
    };

    match name.to_lowercase().as_str() {
        "cloudflare" => Ok(Box::new(CloudflareProvider::new())),
        "librespeed" => Ok(Box::new(LibrespeedProvider::new())),
        "custom" => {
            let config = Config::load()?;
            Ok(Box::new(CustomProvider::new(
                config.providers.custom.download_url,
                config.providers.custom.upload_url,
            )))
        }
        _ => anyhow::bail!(
            "Unknown provider: {}. Use 'cloudflare', 'librespeed', or 'custom'",
            name
        ),
    }
}