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    println!("Amount spent : {} {}", bundle.amount_spent, bundle.currency);
248    println!(
249        "Total size   : {}",
250        util::humanize_bytes(bundle.total_size())
251    );
252    println!();
253
254    if !bundle.products.is_empty() {
255        let mut builder = tabled::builder::Builder::default();
256        builder.push_record(["#", "Sub-item", "Format", "Total Size"]);
257
258        for (idx, entry) in bundle.products.iter().enumerate() {
259            builder.push_record([
260                &(idx + 1).to_string(),
261                &entry.human_name,
262                &entry.formats(),
263                &util::humanize_bytes(entry.total_size()),
264            ]);
265        }
266        let table = builder
267            .build()
268            .with(Style::psql())
269            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
270            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
271            .with(Modify::new(Columns::single(2)).with(Alignment::left()))
272            .with(Modify::new(Columns::single(3)).with(Alignment::right()))
273            .to_string();
274
275        println!("{table}");
276    } else {
277        println!("No items to show.");
278    }
279
280    // Product keys
281    let product_keys = bundle.product_keys();
282    if !product_keys.is_empty() {
283        println!();
284        println!("Keys in this bundle:");
285        println!();
286        let mut builder = tabled::builder::Builder::default();
287        builder.push_record(["#", "Key Name", "Redeemed"]);
288
289        let mut all_redeemed = true;
290        for (idx, entry) in product_keys.iter().enumerate() {
291            builder.push_record([
292                (idx + 1).to_string().as_str(),
293                entry.human_name.as_str(),
294                if entry.redeemed { "Yes" } else { "No" },
295            ]);
296
297            if !entry.redeemed {
298                all_redeemed = false;
299            }
300        }
301
302        let table = builder
303            .build()
304            .with(Style::psql())
305            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
306            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
307            .with(Modify::new(Columns::single(2)).with(Alignment::center()))
308            .to_string();
309
310        println!("{table}");
311
312        if !all_redeemed {
313            let url = "https://www.humblebundle.com/home/keys";
314            println!("Visit {url} to redeem your keys.");
315        }
316    }
317
318    Ok(())
319}
320
321pub fn download_bundles(
322    bundle_list_file: &str,
323    formats: Vec<String>,
324    max_size: u64,
325    torrents_only: bool,
326    cur_dir: bool,
327) -> Result<(), anyhow::Error> {
328    // ---------------------------------------------------------------------------------------------
329    let buffer = fs::read_to_string(bundle_list_file)?;
330
331    let mut err_vec: Vec<(String, anyhow::Error)> = Vec::new();
332    let lines = buffer.lines();
333    for line in lines {
334        let parts: Vec<&str> = line.split(',').collect();
335        let bundle_key: &str = parts[0];
336        let bundle_name: &str = if !parts.is_empty() {
337            parts[1]
338        } else {
339            parts[0]
340        };
341
342        if let Err(download_err) =
343            download_bundle(bundle_key, &formats, max_size, None, torrents_only, cur_dir)
344        {
345            err_vec.push((String::from(bundle_name), download_err));
346        }
347    }
348
349    //  --------------------------------------------------------------------------------------------
350    for err_item in err_vec {
351        println!("Error handeling: {}", err_item.0);
352        println!("Error: {}", err_item.1);
353    }
354    Ok(())
355}
356
357pub fn download_bundle(
358    bundle_key: &str,
359    formats: &[String],
360    max_size: u64,
361    item_numbers: Option<&str>,
362    torrents_only: bool,
363    cur_dir: bool,
364) -> Result<(), anyhow::Error> {
365    let config = get_config()?;
366
367    let api = crate::HumbleApi::new(&config.session_key);
368
369    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
370        Some(key) => key,
371        None => return Ok(()),
372    };
373
374    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;
375
376    // To parse the item number ranges, we need to know the max value
377    // for unbounded ranges (e.g. 12-). That's why we parse this argument
378    // after we read the bundle from the API.
379    let item_numbers = if let Some(value) = item_numbers {
380        let ranges = value.split(',').collect::<Vec<_>>();
381        util::union_usize_ranges(&ranges, bundle.products.len())?
382    } else {
383        vec![]
384    };
385
386    // Filter products based on entered criteria
387    // Note that item numbers entered by user start at 1, while our index
388    // starts as 0.
389    let products = bundle
390        .products
391        .iter()
392        .enumerate()
393        .filter(|&(i, _)| item_numbers.is_empty() || item_numbers.contains(&(i + 1)))
394        .map(|(_, p)| p)
395        .filter(|p| max_size == 0 || p.total_size() < max_size)
396        .filter(|p| formats.is_empty() || util::str_vectors_intersect(&p.formats_as_vec(), formats))
397        .collect::<Vec<_>>();
398
399    if products.is_empty() {
400        println!("Nothing to download");
401        return Ok(());
402    }
403
404    // Create the bundle directory
405    let dir_name = util::replace_invalid_chars_in_filename(&bundle.details.human_name);
406    let bundle_dir = match cur_dir {
407        false => create_dir(&dir_name)?,
408        true => open_dir(".")?,
409    };
410
411    let http_read_timeout = Duration::from_secs(30);
412    let client = reqwest::Client::builder()
413        .read_timeout(http_read_timeout)
414        .build()?;
415
416    for product in products {
417        if max_size > 0 && product.total_size() > max_size {
418            continue;
419        }
420
421        println!();
422        println!("{}", product.human_name);
423
424        let dir_name = util::replace_invalid_chars_in_filename(&product.human_name);
425        let entry_dir = bundle_dir.join(dir_name);
426        if !entry_dir.exists() {
427            fs::create_dir(&entry_dir)?;
428        }
429
430        for product_download in product.downloads.iter() {
431            for dl_info in product_download.items.iter() {
432                if !formats.is_empty() && !formats.contains(&dl_info.format.to_lowercase()) {
433                    println!("Skipping '{}'", dl_info.format);
434                    continue;
435                }
436
437                let download_url = if torrents_only {
438                    &dl_info.url.bittorrent
439                } else {
440                    &dl_info.url.web
441                };
442
443                let filename = util::extract_filename_from_url(download_url)
444                    .context(format!("Cannot get file name from URL '{}'", download_url))?;
445                let download_path = entry_dir.join(&filename);
446
447                let f = download::download_file(
448                    &client,
449                    download_url,
450                    download_path.to_str().unwrap(),
451                    &filename,
452                );
453                util::run_future(f)?;
454            }
455        }
456    }
457
458    Ok(())
459}
460
461fn create_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
462    let dir = path::Path::new(dir).to_owned();
463    if !dir.exists() {
464        fs::create_dir(&dir)?;
465    }
466    Ok(dir)
467}
468
469fn open_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
470    let dir = path::Path::new(dir).to_owned();
471    Ok(dir)
472}
473const VALID_FIELDS: [&str; 4] = ["key", "name", "size", "claimed"];
474
475fn validate_fields(fields: &[String]) -> bool {
476    for field in fields {
477        if !VALID_FIELDS.contains(&field.to_lowercase().as_str()) {
478            return false;
479        }
480    }
481    true
482}
483
484fn bulk_format(fields: &[String], bundles: &[Bundle]) -> Result<(), anyhow::Error> {
485    if !validate_fields(fields) {
486        return Err(anyhow!("invalid field in fields: {}", fields.join(",")));
487    }
488    let print_key = fields.contains(&VALID_FIELDS[0].to_lowercase());
489    let print_name = fields.contains(&VALID_FIELDS[1].to_lowercase());
490    let print_size = fields.contains(&VALID_FIELDS[2].to_lowercase());
491    let print_claimed = fields.contains(&VALID_FIELDS[3].to_lowercase());
492    for b in bundles {
493        let mut print_vec: Vec<String> = Vec::new();
494        if print_key {
495            print_vec.push(b.gamekey.clone());
496        };
497        if print_name {
498            print_vec.push(b.details.human_name.clone());
499        };
500        if print_size {
501            print_vec.push(util::humanize_bytes(b.total_size()))
502        };
503        if print_claimed {
504            print_vec.push(b.claim_status().to_string())
505        };
506        println!("{}", print_vec.join(","));
507    }
508    Ok(())
509}