packtrack 2.8.0

A simple CLI for tracking mail packages
Documentation
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
use crate::cli::display::{display_job, heading, line};
use crate::cli::settings;
use crate::cli::settings::Settings;
use crate::cli::urls;
use byte_unit::{Byte, UnitType};
use clap::Args;
use clap::{Parser, Subcommand};
use enum_iterator::all;
use log::{self, LevelFilter};
use packtrack::Result;
use packtrack::api::Filters;
use packtrack::api::Job;
use packtrack::api::{Context, track_urls};
use packtrack::cache::{Cache, JsonCache};
use packtrack::tracker::PackageStatus;
use packtrack::url_store::AnnotatedUrl;
use packtrack::utils::check_path_exists;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::Instant;

pub async fn main() -> Result<()> {
    let args = Cli::parse();

    let verbosity = match args.globals.verbosity.as_str() {
        "0" | "off" => LevelFilter::Off,
        "1" | "error" => LevelFilter::Error,
        "2" | "warn" => LevelFilter::Warn,
        "3" | "info" => LevelFilter::Info,
        "4" | "debug" => LevelFilter::Debug,
        "5" | "trace" => LevelFilter::Trace,
        other => return Err(format!("Invalid verbosity: {other}").into()),
    };
    env_logger::Builder::new()
        .filter(None, verbosity)
        .init();
    log::debug!("Verbosity {verbosity}");

    let sets = settings::load()?;
    let ctx = Context {
        cache_seconds:      args
            .tracking
            .cache_seconds
            .unwrap_or(sets.cache_seconds.clone()),
        use_cache:          !args.tracking.no_cache,
        filters:            Filters {
            url:       args.tracking.url.clone(),
            sender:    args.tracking.sender.clone(),
            recipient: args.tracking.recipient.clone(),
            carrier:   args.tracking.carrier.clone(),
        },
        default_postcode:   args
            .tracking
            .postcode
            .clone()
            .or(sets.postcode.clone()),
        preferred_language: args
            .tracking
            .language
            .clone()
            .or(sets.language.clone())
            .unwrap_or(Context::default().preferred_language),
    };
    log::debug!("Cache seconds: {}", ctx.cache_seconds);

    // Handle subcommands
    match args.subcommand {
        None => track(&sets, &ctx, args.tracking).await?,
        Some(Command::Url { command }) => {
            handle_url_command(command, &sets).await?
        }
        Some(Command::Config { command }) => {
            handle_config_command(command, sets)?
        }
        Some(Command::Cache { command }) => {
            handle_cache_command(command, &sets).await?
        }
    }
    Ok(())
}
async fn handle_cache_command(
    command: CacheCommand,
    settings: &Settings,
) -> Result<()> {
    match command {
        CacheCommand::Clear => {
            let file = JsonCache::get_file()?;
            if !file.exists() {
                println!("No cache exists currently");
                return Ok(());
            } else {
                let cache = JsonCache::new()?;
                let size = cache.size_bytes()?;
                let human_readable =
                    Byte::from_u64(size).get_appropriate_unit(UnitType::Binary);
                fs::remove_file(file)?;
                println!("Cleared cache (was {human_readable:#.1})")
            }
        }
        CacheCommand::Location => {
            println!("{}", JsonCache::get_file()?.display())
        }
        CacheCommand::Size => {
            // TODO: Handle cache no exist
            let cache = JsonCache::new()?;
            let size = cache.size_bytes()?;
            let human_readable =
                Byte::from_u64(size).get_appropriate_unit(UnitType::Binary);
            println!("{human_readable:#.1}");
        }
        CacheCommand::Prune { dry_run, args } => {
            let file = JsonCache::get_file()?;
            if !file.exists() {
                println!("Cache is empty");
                return Ok(());
            }

            let urls_file = args
                .urls_file
                .as_ref()
                .unwrap_or(&settings.urls_file);
            log::info!("Using URLs file {urls_file:#?}");

            let mut cache = JsonCache::new()?;
            let cache_size_before = cache.size_bytes()?;

            let keep: Vec<String> = urls::filter(&urls_file, None)?
                .into_iter()
                .map(|au| au.url)
                .collect();
            log::info!("Aiming to keep {} urls", keep.len());
            for url in keep.iter() {
                log::debug!("Keep {url}");
            }

            let removed_urls = cache.prune(&keep);

            if dry_run {
                println!("Would remove {} urls (dry run)", removed_urls.len());
                for url in removed_urls {
                    log::debug!("Removed {url}");
                }
            } else {
                cache.save().await?;
                let cache_size_after = cache.size_bytes()?;
                println!("Removed {} urls", removed_urls.len());
                for url in &removed_urls {
                    log::debug!("Removed {url}");
                }
                if removed_urls.len() > 0 {
                    println!(
                        "Cache size reduced from {:#.1} to {:#.1}",
                        Byte::from_u64(cache_size_before)
                            .get_appropriate_unit(UnitType::Binary),
                        Byte::from_u64(cache_size_after)
                            .get_appropriate_unit(UnitType::Binary),
                    );
                } else {
                    println!(
                        "Cache size is still {:#.1}",
                        Byte::from_u64(cache_size_before)
                            .get_appropriate_unit(UnitType::Binary),
                    )
                }
            }
        }
    }
    Ok(())
}
/// URL file management
async fn handle_url_command(
    command: UrlCommand,
    settings: &Settings,
) -> Result<()> {
    let default_file = &settings.urls_file;
    match command {
        UrlCommand::Add {
            url,
            description,
            args,
        } => {
            let file = args
                .urls_file
                .as_ref()
                .unwrap_or(default_file);
            let msg = format!("Added {url}");
            let aurl = AnnotatedUrl::new(url, description);
            match urls::add(file, aurl) {
                Ok(()) => println!("{msg}"),
                Err(err) => return Err(err),
            }
        }
        UrlCommand::Remove { url, args } => {
            let file = args
                .urls_file
                .as_ref()
                .unwrap_or(default_file);
            match urls::remove(file, url) {
                Ok(removed) => {
                    println!("Removed urls:");
                    for url in removed {
                        println!("{url}");
                    }
                }
                Err(err) => return Err(err),
            }
        }
        UrlCommand::List { query, args } => {
            let file = args
                .urls_file
                .as_ref()
                .unwrap_or(default_file);
            let urls = urls::filter(file, query.as_deref())?;
            for url in urls {
                println!("{url}");
            }
        }
    }
    Ok(())
}

fn handle_config_command(command: ConfigCommand, sets: Settings) -> Result<()> {
    match command {
        ConfigCommand::List => settings::print()?,
        ConfigCommand::Set { key, value } => {
            let sets = sets.update(&key, value)?;
            settings::save(&sets)?;
        }
        ConfigCommand::Reset => settings::reset()?,
    }
    Ok(())
}

#[derive(Parser)]
// `args_conflicts_with_subcommands` makes non-global args only accessible for
// the default subcommand. So all the options related to tracking (sender, etc)
// are not available for the config subcommand, for example.
#[clap(args_conflicts_with_subcommands = true)]
#[command(version, about)]
struct Cli {
    #[command(subcommand)]
    subcommand: Option<Command>,

    #[clap(flatten)]
    tracking: TrackArgs,

    #[clap(flatten)]
    globals: GlobalArgs,
}

#[derive(Args)]
struct GlobalArgs {
    /// Set verbosity
    #[arg(
        short,
        long,
        global = true,
        required = false,
        default_value = "error"
    )]
    verbosity: String,
}

#[derive(Args)]
struct TrackArgs {
    /// Either a new URL, or a fragment of an existing URL
    url: Option<String>,

    /// Path to the URLs file
    #[arg(short, long, value_parser = check_path_exists)]
    urls_file: Option<PathBuf>,

    /// Filter by sender
    #[arg(short, long)]
    sender: Option<String>,

    /// Filter by postal carrier
    #[arg(short, long)]
    carrier: Option<String>,

    /// Filter by recipient
    #[arg(short, long)]
    recipient: Option<String>,

    /// Max age for cache entries to be reused
    #[arg(short = 'C', long)]
    cache_seconds: Option<usize>,

    /// Don't use the cache (even for delivered packages)
    #[arg(short, long)]
    no_cache: bool,

    // FIXME: This is only relevant for CLI printout (not JSON)
    /// Display detailed info on delivered packages
    #[arg(short, long)]
    delivered: bool,

    /// Preferred language (passed to the carrier)
    #[arg(short, long)]
    language: Option<String>,

    /// Recipient postcode (sometimes required to get full info)
    #[arg(short, long)]
    postcode: Option<String>,
}

#[derive(Subcommand)]
enum Command {
    /// URL management
    Url {
        #[command(subcommand)]
        command: UrlCommand,
    },
    /// Configuration
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },
    /// Cache management
    Cache {
        #[command(subcommand)]
        command: CacheCommand,
    },
}
#[derive(Subcommand)]
enum UrlCommand {
    /// List the URLs currently in the file
    List {
        query: Option<String>,
        #[clap(flatten)]
        args:  UrlArgs,
    },
    /// Add a URL to the urls file
    Add {
        url:         String,
        #[arg(short, long)]
        description: Option<String>,
        #[clap(flatten)]
        args:        UrlArgs,
    },
    /// Remove a URL from the urls file
    Remove {
        url:  String,
        #[clap(flatten)]
        args: UrlArgs,
    },
}
#[derive(Args)]
struct UrlArgs {
    /// Path to the URLs file
    #[arg(short, long, value_parser = check_path_exists)]
    urls_file: Option<PathBuf>,
}

#[derive(Subcommand)]
enum CacheCommand {
    /// Get the cache size
    Size,
    /// Remove cache entries for URLs that are no longer in the URL store
    Prune {
        /// Perform a dry run without modifying the cache
        #[arg(long)]
        dry_run: bool,
        #[clap(flatten)]
        args:    UrlArgs,
    },
    /// Show where the cache is stored on disk
    Location,
    /// Empty the cache
    Clear,
}

#[derive(Subcommand)]
enum ConfigCommand {
    /// List the current settings
    List,
    /// Update the settings
    Set { key: String, value: String },
    /// Reset settings to the defaults
    Reset,
}

fn display_jobs(jobs: Vec<Job>, delivered_detail: bool) {
    // sort the results by status / error
    let mut errors: Vec<Job> = vec![];
    let mut jobs_by_status: HashMap<PackageStatus, Vec<Job>> = HashMap::new();
    for job in jobs {
        match &job.result {
            Ok(package) => {
                let status = package.status();
                jobs_by_status
                    .entry(status)
                    .or_default()
                    .push(job);
            }
            Err(_) => errors.push(job),
        }
    }
    // sort by time
    for (status, packages) in jobs_by_status.iter_mut() {
        if status == &PackageStatus::Delivered {
            packages.sort_by(|a, b| {
                let a_time = a.result.as_ref().unwrap().delivered;
                let b_time = b.result.as_ref().unwrap().delivered;
                a_time.cmp(&b_time)
            });
        }
        if status == &PackageStatus::InTransit {
            packages.sort_by(|a, b| {
                let a_package = a.result.as_ref().unwrap();
                let a_eta = a_package.eta.or(a_package
                    .eta_window
                    .as_ref()
                    .map(|w| w.start));
                let b_package = b.result.as_ref().unwrap();
                let b_eta = b_package.eta.or(b_package
                    .eta_window
                    .as_ref()
                    .map(|w| w.start));
                a_eta.cmp(&b_eta)
            });
        }
    }

    // display successful results
    let line = format!("\n{}\n", line());
    for status in all::<PackageStatus>() {
        let jobs = jobs_by_status
            .entry(status.clone())
            .or_insert(vec![]);
        if jobs.len() > 0 {
            let separator = match status {
                PackageStatus::Delivered => {
                    if delivered_detail {
                        line.clone()
                    } else {
                        "\n".to_owned()
                    }
                }
                PackageStatus::InTransit => line.clone(),
            };
            heading(&status);
            let s = jobs
                .iter()
                .map(|job| display_job(job, delivered_detail))
                .collect::<Vec<_>>()
                .join(&separator);
            println!("{s}");
        }
    }

    if errors.len() > 0 {
        // display errors
        heading(&"errors");
        let separator = line;
        let s = errors
            .iter()
            .map(|job| display_job(job, delivered_detail))
            .collect::<Vec<_>>()
            .join(&separator);
        println!("{s}");
    }
}

async fn track(
    settings: &Settings,
    ctx: &Context,
    track_args: TrackArgs,
) -> Result<()> {
    let start = Instant::now();
    // TODO: Move this somewhere else, and make it completely stateless, so that
    // you can
    // - Pass no -f arg (use URLs file defined in settings)
    //     - allow filtering by query
    // - Pass -f urls_file (use different URLs file)
    //     - allow filtering by query
    // - Pass one or more URLs as a "\n" separated string
    let urls_file: &PathBuf = track_args
        .urls_file
        .as_ref()
        .unwrap_or(&settings.urls_file);
    let mut urls = urls::filter(urls_file, ctx.filters.url.as_deref())?;

    // TODO: make this clearer
    if urls.len() == 0 && ctx.filters.url.is_some() {
        urls = vec![AnnotatedUrl::new(
            ctx.filters.url.clone().unwrap(),
            Some("dynamic".into()),
        )]
    }
    let jobs = track_urls(urls, ctx).await?;
    display_jobs(jobs, track_args.delivered);
    log::info!("track_all took {:?}", start.elapsed());
    Ok(())
}