rnatui 2.0.15

NetActuate API client library and cli program
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! Example rust app using the NetActuate API rust library
//!
//! This app is mainly for testing and is just an example
//!
//! # Usage
//! ### Set ENVs
//!
//! ```bash
//! export API_KEY='<your api key>'
//! export API_ADDRESS='https://vapi2.netactuate.com/api/cloud'
//! ```
//!
//! ### Install example client
//! ```rust
//! cargo install rnaapi
//! ```
//!
//! ### There are two forms of output, all server info or a single server's info
//!
//! #### All servers info
//! `rnaapi`
//!
//! ## A single servers info
//! `rnaapi -m <mbpkgid>`
//!
//! That's it.
//!
// Copyright (C) 2025 Dennis Durling
// This file is part of RNAAPI Rust API Client Library, licensed
// under the GNU General Public License v3.0
use anyhow::Result;
use chrono::NaiveDate;
use clap::CommandFactory;
use clap::{Parser, Subcommand};
use clap_complete::{Shell, generate};
use rnaapi::NaClient;
use rnaapi::config::Settings;
use rnaapi::endpoints;
use rnaapi::{EndpointGetAll, EndpointGetArgs, EndpointGetOne};

#[tokio::main]
async fn main() -> Result<()> {
    //! Test/Example "main" function, right now it just takes
    //! one argument, `-m <mbpkgid>` if not given, returns all the servers you own

    // Get settings from config
    let settings = Settings::new()?;

    // Defaults
    let mut ssh_keyid: u32 = 0;
    let mut display_count: usize = 0;
    let mut loc_mbpkgid: u32 = 0;
    let mut loc_jobid: u32 = 0;
    let mut loc_zoneid: u32 = 0;
    let mut loc_sizes: u32 = 0;
    let mut command: &str = "default";

    // parse our args into args
    let cli = Cli::parse();

    // check cli sub commands
    match &cli.cmd {
        Some(Commands::GenerateCompletions { shell }) => {
            let mut app = Cli::command();
            let appclone = app.clone();
            generate(
                *shell,
                &mut app,
                appclone.get_name().to_string(),
                &mut std::io::stdout(),
            );
        }
        Some(Commands::Get { cmd }) => match cmd {
            GetCommands::Server { mbpkgid } => {
                if *mbpkgid >= 1 {
                    loc_mbpkgid = *mbpkgid;
                    command = "server";
                } else {
                    command = "server";
                }
            }
            GetCommands::Dns { id } => {
                if *id >= 1 {
                    loc_zoneid = *id;
                    command = "dns";
                } else {
                    command = "dns";
                }
            }
            GetCommands::Ssh { id } => {
                if *id >= 1 {
                    ssh_keyid = *id;
                    command = "ssh";
                } else {
                    command = "ssh";
                }
            }
            GetCommands::Job { mbpkgid, jobid } => {
                if *mbpkgid >= 1 {
                    loc_mbpkgid = *mbpkgid;
                    command = "job";
                    if *jobid >= 1 {
                        loc_jobid = *jobid;
                    }
                }
            }
            GetCommands::Ip { mbpkgid } => {
                if *mbpkgid >= 1 {
                    loc_mbpkgid = *mbpkgid;
                    command = "ip";
                }
            }
            GetCommands::Bandwidth { mbpkgid } => {
                if *mbpkgid >= 1 {
                    loc_mbpkgid = *mbpkgid;
                    command = "bandwidth";
                }
            }
            GetCommands::Invoice { count } => {
                display_count = *count;
                command = "invoice";
            }
            GetCommands::Sizes { id } => {
                loc_sizes = *id;
                command = "sizes";
            }
            GetCommands::Location {} => {
                command = "location";
            }
            GetCommands::Image {} => {
                command = "image";
            }
            GetCommands::Account {} => {
                command = "account";
            }
        },
        _ => {}
    }
    // playing with new constructor for client
    // let na_client = NaClient::new(API_KEY.to_owned(), API_ADDRESS.to_owned()).await;
    let na_client = NaClient::new(settings.api_key, settings.api_url).await;

    if command == "server" {
        if loc_mbpkgid > 0 {
            // submit jobs to the tokio async runtime
            // this automatically awaits so no need for .await
            let (server, srvjobs, ipv4s, ipv6s, status, bw_usage) = tokio::join!(
                endpoints::Server::get_one(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::SrvJob::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::IPv4::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::IPv6::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::SrvStatus::get_one(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::MonthlyBw::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid),
                ),
            );

            // print basic server info
            if let Ok(srv) = server {
                println!(
                    "Package: {}, fqdn: {}, mbpkgid: {}",
                    srv.domu_package, srv.fqdn, srv.mbpkgid
                );
            }

            println!();
            // print the job data
            if let Ok(jobs) = srvjobs {
                for job in jobs {
                    println!(
                        "Inserted: {}, Status: {}, command: {}",
                        job.ts_insert, job.status, job.command
                    );
                }
            }

            println!();
            // print IPv4 Addresses
            if let Ok(ip4s) = ipv4s {
                for ipv4 in ip4s {
                    println!(
                        "Reverse: {}, IP: {}, Gateway: {}",
                        ipv4.reverse, ipv4.ip, ipv4.gateway
                    );
                }
            }

            println!();
            // print IPv6 Addresses
            if let Ok(ip6s) = ipv6s {
                for ipv6 in ip6s {
                    println!(
                        "Reverse: {}, IP: {}, Gateway: {}",
                        ipv6.reverse, ipv6.ip, ipv6.gateway
                    );
                }
            }

            println!();
            // print server status, very unverbose
            if let Ok(stat) = status {
                println!("Status: {}", stat.status);
            }

            // print out bandwidth usage
            println!();
            if let Ok(mut bwusage) = bw_usage {
                bwusage.sort_by_key(|b| {
                    let date_with_day = format!("{}-01", b.date);
                    NaiveDate::parse_from_str(&date_with_day, "%Y-%m-%d")
                        .expect("Failed to parse date")
                });
                for usage in bwusage {
                    println!(
                        "Date: {}, Rx: {}, Tx: {}",
                        usage.date, usage.rx, usage.tx
                    );
                }
            }
        } else {
            let srvrs =
                endpoints::Server::get_all(&na_client, EndpointGetArgs::NoArgs)
                    .await?;

            for srvr in srvrs {
                println!("ID: {}, fqdn: {}", srvr.mbpkgid, srvr.fqdn);
            }
        }
    } else if command == "dns" {
        if loc_zoneid > 0 {
            println!();
            // // print out the zone name
            let zone = endpoints::Zone::get_one(
                &na_client,
                EndpointGetArgs::OneInt(loc_zoneid),
            )
            .await?;
            println!("Zone: {}", zone.name);

            // print out the SOA for the zone
            if let Some(soa) = zone.soa {
                println!("SOA: {}", soa.primary);
            }

            // print out the first record
            if let Some(recs) = zone.records {
                println!("1st Record: {}", recs[0].name);
            }

            // print out the first NS record
            if let Some(nsrecs) = zone.ns {
                println!("1st NS: {}", nsrecs[0].name)
            }
        } else {
            println!();
            // list dns zones
            let zones =
                endpoints::Zone::get_all(&na_client, EndpointGetArgs::NoArgs)
                    .await?;
            for zone in zones {
                println!(
                    "ID: {}, Size: {}, Name: {}",
                    zone.id, zone.name, zone.zone_type
                );
            }
        }
    } else if command == "ssh" {
        if ssh_keyid > 0 {
            let sshkey = endpoints::SSHKeys::get_one(
                &na_client,
                EndpointGetArgs::OneInt(ssh_keyid),
            )
            .await?;
            println!();
            // print some ssh keys
            println!(
                "ID: {}, Key: {}, Fingerprint: {}",
                sshkey.id, sshkey.name, sshkey.fingerprint
            );
        } else {
            let keys = endpoints::SSHKeys::get_all(
                &na_client,
                EndpointGetArgs::NoArgs,
            )
            .await?;
            println!();
            // print some ssh keys
            for sshkey in keys {
                println!(
                    "ID: {}, Key: {}, Fingerprint: {}",
                    sshkey.id, sshkey.name, sshkey.fingerprint
                );
            }
        }
    } else if command == "job" {
        if loc_mbpkgid > 0 && loc_jobid > 0 {
            let job = endpoints::SrvJob::get_one(
                &na_client,
                EndpointGetArgs::TwoInt(loc_mbpkgid, loc_jobid),
            )
            .await?;
            println!();
            // print some ssh keys
            println!(
                "ID: {}, Status: {}, Command: {}",
                job.id, job.status, job.command
            );
        } else if loc_mbpkgid > 0 {
            let jobs = endpoints::SrvJob::get_all(
                &na_client,
                EndpointGetArgs::OneInt(loc_mbpkgid),
            )
            .await?;
            println!();
            // print some ssh keys
            for job in jobs {
                println!(
                    "ID: {}, Status: {}, Command: {}",
                    job.id, job.status, job.command
                );
            }
        }
    } else if command == "ip" {
        if loc_mbpkgid > 0 {
            let (ipv4s, ipv6s) = tokio::join!(
                endpoints::IPv4::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
                endpoints::IPv6::get_all(
                    &na_client,
                    EndpointGetArgs::OneInt(loc_mbpkgid)
                ),
            );

            // print IPv4 Addresses
            if let Ok(ip4s) = ipv4s {
                for ipv4 in ip4s {
                    println!(
                        "Reverse: {}, IP: {}, Gateway: {}",
                        ipv4.reverse, ipv4.ip, ipv4.gateway
                    );
                }
            }

            // print IPv6 Addresses
            if let Ok(ip6s) = ipv6s {
                for ipv6 in ip6s {
                    println!(
                        "Reverse: {}, IP: {}, Gateway: {}",
                        ipv6.reverse, ipv6.ip, ipv6.gateway
                    );
                }
            }
        } else {
            println!("you need to provide an mbpkgid");
        }
    } else if command == "bandwidth" {
        let mut bw_usage = endpoints::MonthlyBw::get_all(
            &na_client,
            EndpointGetArgs::OneInt(loc_mbpkgid),
        )
        .await?;
        println!();
        bw_usage.sort_by_key(|b| {
            let date_with_day = format!("{}-01", b.date);
            NaiveDate::parse_from_str(&date_with_day, "%Y-%m-%d")
                .expect("Failed to parse date")
        });
        for usage in bw_usage {
            println!(
                "Date: {}, Rx: {}, Tx: {}",
                usage.date, usage.rx, usage.tx
            );
        }
    } else if command == "location" {
        let locs =
            endpoints::Location::get_all(&na_client, EndpointGetArgs::NoArgs)
                .await?;
        println!();
        // list locations
        for loc in locs {
            println!(
                "ID: {}, Name: {}, Continent: {}",
                loc.id, loc.name, loc.continent
            );
        }
    } else if command == "account" {
        let deets =
            endpoints::Details::get_one(&na_client, EndpointGetArgs::NoArgs)
                .await?;
        println!();
        // print acct details
        println!(
            "FullName: {:?}, Address: {:?}, {:?} {:?} {:?}",
            deets.fullname,
            deets.address1,
            deets.city,
            deets.state,
            deets.postcode
        );
    } else if command == "image" {
        let imgs =
            endpoints::Image::get_all(&na_client, EndpointGetArgs::NoArgs)
                .await?;
        println!();
        // list images
        for img in imgs {
            println!(
                "ID: {}, Size: {}, Name: {}",
                img.id,
                img.size.unwrap_or("null".to_owned()),
                img.os.unwrap_or("null".to_owned())
            );
        }
        println!();
    } else if command == "invoice" {
        let invoices =
            endpoints::Invoices::get_all(&na_client, EndpointGetArgs::NoArgs)
                .await?;
        // print some of the invoices, say 3?
        for invoice in invoices.iter().take(display_count) {
            println!("ID: {}, Status: {}", invoice.id, invoice.status);
        }
    } else if command == "sizes" {
        let sizes = endpoints::Sizes::get_all(
            &na_client,
            EndpointGetArgs::OneInt(loc_sizes),
        )
        .await?;
        // print some of the invoices, say 3?
        for size in sizes.iter().take(40) {
            println!("ID: {}, Name: {}", size.plan_id, size.plan);
        }
    }
    Ok(())
}

///
/// This is the CLI Args struct
///
#[derive(Parser, Debug)]
#[command(version, about)]
#[command(arg_required_else_help(true))]
struct Cli {
    #[command(subcommand)]
    cmd: Option<Commands>,
}

#[derive(Subcommand, Debug)]
enum Commands {
    Get {
        #[command(subcommand)]
        cmd: GetCommands,
    },
    /// generate completions
    #[command(visible_alias = "gen")]
    GenerateCompletions { shell: Shell },
}

#[derive(Subcommand, Debug)]
enum GetCommands {
    /// Server subcommands
    #[command(visible_alias = "srv")]
    Server {
        // -i argument for picking an mbpkgid
        #[arg(short, long, default_value_t = 0)]
        mbpkgid: u32,
    },

    /// DNS subcommands
    Dns {
        // -i argument for picking a dns zone
        #[arg(short, long, default_value_t = 0)]
        id: u32,
    },

    /// SSh subcommands
    Ssh {
        // -i argument for ssh keyid
        #[arg(short, long, default_value_t = 0)]
        id: u32,
    },

    /// Job subcommands
    Job {
        // -i argument for picking a Job
        #[arg(short, long)]
        mbpkgid: u32,
        #[arg(short, long, default_value_t = 0)]
        jobid: u32,
    },

    /// IPs subcommands
    Ip {
        // --proto argument (-p) for 4 or 6
        // default to 4
        #[arg(short, long)]
        mbpkgid: u32,
    },

    /// Monthly Bandwidth subcommands
    #[command(visible_alias = "bw")]
    Bandwidth {
        #[arg(short, long)]
        mbpkgid: u32,
    },

    /// Invoices subcommands
    #[command(visible_alias = "inv")]
    Invoice {
        // -i argument for number to display
        #[arg(short, long, default_value_t = 5)]
        count: usize,
    },

    /// Invoices subcommands
    #[command(visible_alias = "sz")]
    Sizes {
        // -i argument for number to display
        #[arg(short, long)]
        id: u32,
    },

    /// Location subcommands
    #[command(visible_alias = "loc")]
    Location {},

    /// Images subcommands
    #[command(visible_alias = "img")]
    Image {},

    /// Account subcommands
    Account {},
}