humble_cli/
lib.rs

1mod config;
2mod download;
3mod humble_api;
4mod key_match;
5mod models;
6mod util;
7
8pub mod prelude {
9    pub use crate::auth;
10    pub use crate::download_bundle;
11    pub use crate::list_bundles;
12    pub use crate::list_humble_choices;
13    pub use crate::search;
14    pub use crate::show_bundle_details;
15
16    pub use crate::humble_api::{ApiError, HumbleApi};
17    pub use crate::models::*;
18    pub use crate::util::byte_string_to_number;
19}
20
21use anyhow::{anyhow, Context};
22use config::{get_config, set_config, Config};
23use humble_api::{ApiError, HumbleApi};
24use key_match::KeyMatch;
25use prelude::*;
26use std::fs;
27use std::path;
28use std::time::Duration;
29use tabled::settings::object::Columns;
30use tabled::settings::Alignment;
31use tabled::settings::Merge;
32use tabled::settings::Modify;
33use tabled::settings::Style;
34
35pub fn auth(session_key: &str) -> Result<(), anyhow::Error> {
36    set_config(Config {
37        session_key: session_key.to_owned(),
38    })
39}
40
41pub fn handle_http_errors<T>(input: Result<T, ApiError>) -> Result<T, anyhow::Error> {
42    match input {
43        Ok(val) => Ok(val),
44        Err(ApiError::NetworkError(e)) if e.is_status() => match e.status().unwrap() {
45            reqwest::StatusCode::UNAUTHORIZED => Err(anyhow!(
46                "Unauthorized request (401). Is the session key correct?"
47            )),
48            reqwest::StatusCode::NOT_FOUND => Err(anyhow!(
49                "Bundle not found (404). Is the bundle key correct?"
50            )),
51            s => Err(anyhow!("failed with status: {}", s)),
52        },
53        Err(e) => Err(anyhow!("failed: {}", e)),
54    }
55}
56
57pub fn list_humble_choices(period: &ChoicePeriod) -> Result<(), anyhow::Error> {
58    let config = get_config()?;
59    let api = HumbleApi::new(&config.session_key);
60
61    let choices = api.read_bundle_choices(&period.to_string())?;
62
63    println!();
64    println!("{}", choices.options.title);
65    println!();
66
67    let options = choices.options;
68
69    let mut builder = tabled::builder::Builder::default();
70    builder.push_record(["#", "Title", "Redeemed"]);
71
72    let mut counter = 1;
73    let mut all_redeemed = true;
74    for (_, game_data) in options.data.game_data.iter() {
75        for tpkd in game_data.tpkds.iter() {
76            builder.push_record([
77                counter.to_string().as_str(),
78                tpkd.human_name.as_str(),
79                tpkd.claim_status().to_string().as_str(),
80            ]);
81
82            counter += 1;
83
84            if tpkd.claim_status() == ClaimStatus::No {
85                all_redeemed = false;
86            }
87        }
88    }
89
90    let table = builder
91        .build()
92        .with(Style::psql())
93        .with(Modify::new(Columns::single(0)).with(Alignment::right()))
94        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
95        .to_string();
96
97    println!("{table}");
98
99    if !all_redeemed {
100        let url = "https://www.humblebundle.com/membership/home";
101        println!("Visit {url} to redeem your keys.");
102    }
103    Ok(())
104}
105
106pub fn search(keywords: &str, match_mode: MatchMode) -> Result<(), anyhow::Error> {
107    let config = get_config()?;
108    let api = HumbleApi::new(&config.session_key);
109
110    let keywords = keywords.to_lowercase();
111    let keywords: Vec<&str> = keywords.split(" ").collect();
112
113    let bundles = handle_http_errors(api.list_bundles())?;
114    type BundleItem<'a> = (&'a Bundle, String);
115    let mut search_result: Vec<BundleItem> = vec![];
116
117    for b in &bundles {
118        for p in &b.products {
119            if p.name_matches(&keywords, &match_mode) {
120                search_result.push((b, p.human_name.to_owned()));
121            }
122        }
123    }
124
125    if search_result.is_empty() {
126        println!("Nothing found");
127        return Ok(());
128    }
129
130    let mut builder = tabled::builder::Builder::default();
131    builder.push_record(["Key", "Name", "Sub Item"]);
132    for record in search_result {
133        builder.push_record([
134            record.0.gamekey.as_str(),
135            record.0.details.human_name.as_str(),
136            record.1.as_str(),
137        ]);
138    }
139
140    let table = builder
141        .build()
142        .with(Style::psql())
143        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
144        .with(Modify::new(Columns::single(2)).with(Alignment::left()))
145        .with(Merge::vertical())
146        .to_string();
147
148    println!("{table}");
149    Ok(())
150}
151
152pub fn list_bundles(fields: Vec<String>, claimed_filter: &str) -> Result<(), anyhow::Error> {
153    let config = get_config()?;
154    let api = HumbleApi::new(&config.session_key);
155    let key_only = fields.len() == 1 && fields[0] == "key";
156
157    // If no filter is required, we can do a single call
158    // and finish quickly. Otherwise we will need to fetch
159    // all bundle data and filter them.
160    if key_only && claimed_filter == "all" {
161        let ids = handle_http_errors(api.list_bundle_keys())?;
162        for id in ids {
163            println!("{}", id);
164        }
165
166        return Ok(());
167    }
168
169    let mut bundles = handle_http_errors(api.list_bundles())?;
170
171    if claimed_filter != "all" {
172        let claimed = claimed_filter == "yes";
173        bundles.retain(|b| {
174            let status = b.claim_status();
175            status == ClaimStatus::Yes && claimed || status == ClaimStatus::No && !claimed
176        });
177    }
178
179    if !fields.is_empty() {
180        return bulk_format(&fields, &bundles);
181    }
182
183    println!("{} bundle(s) found.\n", bundles.len());
184
185    if bundles.is_empty() {
186        return Ok(());
187    }
188
189    let mut builder = tabled::builder::Builder::default();
190    builder.push_record(["Key", "Name", "Size", "Claimed"]);
191
192    for p in bundles {
193        builder.push_record([
194            p.gamekey.as_str(),
195            p.details.human_name.as_str(),
196            util::humanize_bytes(p.total_size()).as_str(),
197            p.claim_status().to_string().as_str(),
198        ]);
199    }
200
201    let table = builder
202        .build()
203        .with(Style::psql())
204        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
205        .with(Modify::new(Columns::single(2)).with(Alignment::right()))
206        .to_string();
207    println!("{table}");
208
209    Ok(())
210}
211
212fn find_key(all_keys: Vec<String>, key_to_find: &str) -> Option<String> {
213    let key_match = KeyMatch::new(all_keys, key_to_find);
214    let keys = key_match.get_matches();
215
216    match keys.len() {
217        1 => Some(keys[0].clone()),
218        0 => {
219            eprintln!("No bundle matches '{}'", key_to_find);
220            None
221        }
222        _ => {
223            eprintln!("More than one bundle matches '{}':", key_to_find);
224            for key in keys {
225                eprintln!("{}", key);
226            }
227            None
228        }
229    }
230}
231
232pub fn show_bundle_details(bundle_key: &str) -> Result<(), anyhow::Error> {
233    let config = get_config()?;
234    let api = crate::HumbleApi::new(&config.session_key);
235
236    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
237        Some(key) => key,
238        None => return Ok(()),
239    };
240
241    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;
242
243    println!();
244    println!("{}", bundle.details.human_name);
245    println!();
246    println!("Purchased    : {}", bundle.created.format("%Y-%m-%d"));
247    if let (Some(amount), Some(currency)) = (bundle.amount_spent.as_ref(), bundle.currency.as_ref())
248    {
249        println!("Amount spent : {} {}", amount, currency);
250    }
251    println!(
252        "Total size   : {}",
253        util::humanize_bytes(bundle.total_size())
254    );
255    println!();
256
257    if !bundle.products.is_empty() {
258        let mut builder = tabled::builder::Builder::default();
259        builder.push_record(["#", "Sub-item", "Format", "Total Size"]);
260
261        for (idx, entry) in bundle.products.iter().enumerate() {
262            builder.push_record([
263                &(idx + 1).to_string(),
264                &entry.human_name,
265                &entry.formats(),
266                &util::humanize_bytes(entry.total_size()),
267            ]);
268        }
269        let table = builder
270            .build()
271            .with(Style::psql())
272            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
273            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
274            .with(Modify::new(Columns::single(2)).with(Alignment::left()))
275            .with(Modify::new(Columns::single(3)).with(Alignment::right()))
276            .to_string();
277
278        println!("{table}");
279    } else {
280        println!("No items to show.");
281    }
282
283    // Product keys
284    let product_keys = bundle.product_keys();
285    if !product_keys.is_empty() {
286        println!();
287        println!("Keys in this bundle:");
288        println!();
289        let mut builder = tabled::builder::Builder::default();
290        builder.push_record(["#", "Key Name", "Redeemed"]);
291
292        let mut all_redeemed = true;
293        for (idx, entry) in product_keys.iter().enumerate() {
294            builder.push_record([
295                (idx + 1).to_string().as_str(),
296                entry.human_name.as_str(),
297                if entry.redeemed { "Yes" } else { "No" },
298            ]);
299
300            if !entry.redeemed {
301                all_redeemed = false;
302            }
303        }
304
305        let table = builder
306            .build()
307            .with(Style::psql())
308            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
309            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
310            .with(Modify::new(Columns::single(2)).with(Alignment::center()))
311            .to_string();
312
313        println!("{table}");
314
315        if !all_redeemed {
316            let url = "https://www.humblebundle.com/home/keys";
317            println!("Visit {url} to redeem your keys.");
318        }
319    }
320
321    Ok(())
322}
323
324pub fn download_bundles(
325    bundle_list_file: &str,
326    formats: Vec<String>,
327    max_size: u64,
328    torrents_only: bool,
329    cur_dir: bool,
330) -> Result<(), anyhow::Error> {
331    // ---------------------------------------------------------------------------------------------
332    let buffer = fs::read_to_string(bundle_list_file)?;
333
334    let mut err_vec: Vec<(String, anyhow::Error)> = Vec::new();
335    let lines = buffer.lines();
336    for line in lines {
337        let parts: Vec<&str> = line.split(',').collect();
338        let bundle_key: &str = parts[0];
339        let bundle_name: &str = if !parts.is_empty() {
340            parts[1]
341        } else {
342            parts[0]
343        };
344
345        if let Err(download_err) =
346            download_bundle(bundle_key, &formats, max_size, None, torrents_only, cur_dir)
347        {
348            err_vec.push((String::from(bundle_name), download_err));
349        }
350    }
351
352    //  --------------------------------------------------------------------------------------------
353    for err_item in err_vec {
354        println!("Error handeling: {}", err_item.0);
355        println!("Error: {}", err_item.1);
356    }
357    Ok(())
358}
359
360pub fn download_bundle(
361    bundle_key: &str,
362    formats: &[String],
363    max_size: u64,
364    item_numbers: Option<&str>,
365    torrents_only: bool,
366    cur_dir: bool,
367) -> Result<(), anyhow::Error> {
368    let config = get_config()?;
369
370    let api = crate::HumbleApi::new(&config.session_key);
371
372    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
373        Some(key) => key,
374        None => return Ok(()),
375    };
376
377    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;
378
379    // To parse the item number ranges, we need to know the max value
380    // for unbounded ranges (e.g. 12-). That's why we parse this argument
381    // after we read the bundle from the API.
382    let item_numbers = if let Some(value) = item_numbers {
383        let ranges = value.split(',').collect::<Vec<_>>();
384        util::union_usize_ranges(&ranges, bundle.products.len())?
385    } else {
386        vec![]
387    };
388
389    // Filter products based on entered criteria
390    // Note that item numbers entered by user start at 1, while our index
391    // starts as 0.
392    let products = bundle
393        .products
394        .iter()
395        .enumerate()
396        .filter(|&(i, _)| item_numbers.is_empty() || item_numbers.contains(&(i + 1)))
397        .map(|(_, p)| p)
398        .filter(|p| max_size == 0 || p.total_size() < max_size)
399        .filter(|p| formats.is_empty() || util::str_vectors_intersect(&p.formats_as_vec(), formats))
400        .collect::<Vec<_>>();
401
402    if products.is_empty() {
403        println!("Nothing to download");
404        return Ok(());
405    }
406
407    // Create the bundle directory
408    let dir_name = util::replace_invalid_chars_in_filename(&bundle.details.human_name);
409    let bundle_dir = match cur_dir {
410        false => create_dir(&dir_name)?,
411        true => open_dir(".")?,
412    };
413
414    let http_read_timeout = Duration::from_secs(30);
415    let client = reqwest::Client::builder()
416        .read_timeout(http_read_timeout)
417        .build()?;
418
419    for product in products {
420        if max_size > 0 && product.total_size() > max_size {
421            continue;
422        }
423
424        println!();
425        println!("{}", product.human_name);
426
427        let dir_name = util::replace_invalid_chars_in_filename(&product.human_name);
428        let entry_dir = bundle_dir.join(dir_name);
429        if !entry_dir.exists() {
430            fs::create_dir(&entry_dir)?;
431        }
432
433        for product_download in product.downloads.iter() {
434            for dl_info in product_download.items.iter() {
435                if !formats.is_empty() && !formats.contains(&dl_info.format.to_lowercase()) {
436                    println!("Skipping '{}'", dl_info.format);
437                    continue;
438                }
439
440                let download_url = if torrents_only {
441                    &dl_info.url.bittorrent
442                } else {
443                    &dl_info.url.web
444                };
445
446                let filename = util::extract_filename_from_url(download_url)
447                    .context(format!("Cannot get file name from URL '{}'", download_url))?;
448                let download_path = entry_dir.join(&filename);
449
450                let f = download::download_file(
451                    &client,
452                    download_url,
453                    download_path.to_str().unwrap(),
454                    &filename,
455                );
456                util::run_future(f)?;
457            }
458        }
459    }
460
461    Ok(())
462}
463
464fn create_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
465    let dir = path::Path::new(dir).to_owned();
466    if !dir.exists() {
467        fs::create_dir(&dir)?;
468    }
469    Ok(dir)
470}
471
472fn open_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
473    let dir = path::Path::new(dir).to_owned();
474    Ok(dir)
475}
476const VALID_FIELDS: [&str; 4] = ["key", "name", "size", "claimed"];
477
478fn validate_fields(fields: &[String]) -> bool {
479    for field in fields {
480        if !VALID_FIELDS.contains(&field.to_lowercase().as_str()) {
481            return false;
482        }
483    }
484    true
485}
486
487fn bulk_format(fields: &[String], bundles: &[Bundle]) -> Result<(), anyhow::Error> {
488    if !validate_fields(fields) {
489        return Err(anyhow!("invalid field in fields: {}", fields.join(",")));
490    }
491    let print_key = fields.contains(&VALID_FIELDS[0].to_lowercase());
492    let print_name = fields.contains(&VALID_FIELDS[1].to_lowercase());
493    let print_size = fields.contains(&VALID_FIELDS[2].to_lowercase());
494    let print_claimed = fields.contains(&VALID_FIELDS[3].to_lowercase());
495    for b in bundles {
496        let mut print_vec: Vec<String> = Vec::new();
497        if print_key {
498            print_vec.push(b.gamekey.clone());
499        };
500        if print_name {
501            print_vec.push(b.details.human_name.clone());
502        };
503        if print_size {
504            print_vec.push(util::humanize_bytes(b.total_size()))
505        };
506        if print_claimed {
507            print_vec.push(b.claim_status().to_string())
508        };
509        println!("{}", print_vec.join(","));
510    }
511    Ok(())
512}