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(id_only: bool, claimed_filter: &str) -> Result<(), anyhow::Error> {
153    let config = get_config()?;
154    let api = HumbleApi::new(&config.session_key);
155
156    // If no filter is required, we can do a single call
157    // and finish quickly. Otherwise we will need to fetch
158    // all bundle data and filter them.
159    if id_only && claimed_filter == "all" {
160        let ids = handle_http_errors(api.list_bundle_keys())?;
161        for id in ids {
162            println!("{}", id);
163        }
164
165        return Ok(());
166    }
167
168    let mut bundles = handle_http_errors(api.list_bundles())?;
169
170    if claimed_filter != "all" {
171        let claimed = claimed_filter == "yes";
172        bundles.retain(|b| {
173            let status = b.claim_status();
174            status == ClaimStatus::Yes && claimed || status == ClaimStatus::No && !claimed
175        });
176    }
177
178    if id_only {
179        for b in bundles {
180            println!("{}", b.gamekey);
181        }
182
183        return Ok(());
184    }
185
186    println!("{} bundle(s) found.\n", bundles.len());
187
188    if bundles.is_empty() {
189        return Ok(());
190    }
191
192    let mut builder = tabled::builder::Builder::default();
193    builder.push_record(["Key", "Name", "Size", "Claimed"]);
194
195    for p in bundles {
196        builder.push_record([
197            p.gamekey.as_str(),
198            p.details.human_name.as_str(),
199            util::humanize_bytes(p.total_size()).as_str(),
200            p.claim_status().to_string().as_str(),
201        ]);
202    }
203
204    let table = builder
205        .build()
206        .with(Style::psql())
207        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
208        .with(Modify::new(Columns::single(2)).with(Alignment::right()))
209        .to_string();
210    println!("{table}");
211
212    Ok(())
213}
214
215fn find_key(all_keys: Vec<String>, key_to_find: &str) -> Option<String> {
216    let key_match = KeyMatch::new(all_keys, key_to_find);
217    let keys = key_match.get_matches();
218
219    match keys.len() {
220        1 => Some(keys[0].clone()),
221        0 => {
222            eprintln!("No bundle matches '{}'", key_to_find);
223            None
224        }
225        _ => {
226            eprintln!("More than one bundle matches '{}':", key_to_find);
227            for key in keys {
228                eprintln!("{}", key);
229            }
230            None
231        }
232    }
233}
234
235pub fn show_bundle_details(bundle_key: &str) -> Result<(), anyhow::Error> {
236    let config = get_config()?;
237    let api = crate::HumbleApi::new(&config.session_key);
238
239    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
240        Some(key) => key,
241        None => return Ok(()),
242    };
243
244    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;
245
246    println!();
247    println!("{}", bundle.details.human_name);
248    println!();
249    println!("Purchased    : {}", bundle.created.format("%Y-%m-%d"));
250    println!("Amount spent : {} {}", bundle.amount_spent, bundle.currency);
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_bundle(
325    bundle_key: &str,
326    formats: Vec<String>,
327    max_size: u64,
328    item_numbers: Option<&str>,
329    torrents_only: bool,
330) -> Result<(), anyhow::Error> {
331    let config = get_config()?;
332
333    let api = crate::HumbleApi::new(&config.session_key);
334
335    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
336        Some(key) => key,
337        None => return Ok(()),
338    };
339
340    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;
341
342    // To parse the item number ranges, we need to know the max value
343    // for unbounded ranges (e.g. 12-). That's why we parse this argument
344    // after we read the bundle from the API.
345    let item_numbers = if let Some(value) = item_numbers {
346        let ranges = value.split(',').collect::<Vec<_>>();
347        util::union_usize_ranges(&ranges, bundle.products.len())?
348    } else {
349        vec![]
350    };
351
352    // Filter products based on entered criteria
353    // Note that item numbers entered by user start at 1, while our index
354    // starts as 0.
355    let products = bundle
356        .products
357        .iter()
358        .enumerate()
359        .filter(|&(i, _)| item_numbers.is_empty() || item_numbers.contains(&(i + 1)))
360        .map(|(_, p)| p)
361        .filter(|p| max_size == 0 || p.total_size() < max_size)
362        .filter(|p| {
363            formats.is_empty() || util::str_vectors_intersect(&p.formats_as_vec(), &formats)
364        })
365        .collect::<Vec<_>>();
366
367    if products.is_empty() {
368        println!("Nothing to download");
369        return Ok(());
370    }
371
372    // Create the bundle directory
373    let dir_name = util::replace_invalid_chars_in_filename(&bundle.details.human_name);
374    let bundle_dir = create_dir(&dir_name)?;
375
376    let http_read_timeout = Duration::from_secs(30);
377    let client = reqwest::Client::builder()
378        .read_timeout(http_read_timeout)
379        .build()?;
380
381    for product in products {
382        if max_size > 0 && product.total_size() > max_size {
383            continue;
384        }
385
386        println!();
387        println!("{}", product.human_name);
388
389        let dir_name = util::replace_invalid_chars_in_filename(&product.human_name);
390        let entry_dir = bundle_dir.join(dir_name);
391        if !entry_dir.exists() {
392            fs::create_dir(&entry_dir)?;
393        }
394
395        for product_download in product.downloads.iter() {
396            for dl_info in product_download.items.iter() {
397                if !formats.is_empty() && !formats.contains(&dl_info.format.to_lowercase()) {
398                    println!("Skipping '{}'", dl_info.format);
399                    continue;
400                }
401
402                let download_url = if torrents_only {
403                    &dl_info.url.bittorrent
404                } else {
405                    &dl_info.url.web
406                };
407
408                let filename = util::extract_filename_from_url(&download_url)
409                    .context(format!("Cannot get file name from URL '{}'", &download_url))?;
410                let download_path = entry_dir.join(&filename);
411
412                let f = download::download_file(
413                    &client,
414                    &download_url,
415                    download_path.to_str().unwrap(),
416                    &filename,
417                );
418                util::run_future(f)?;
419            }
420        }
421    }
422
423    Ok(())
424}
425
426fn create_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
427    let dir = path::Path::new(dir).to_owned();
428    if !dir.exists() {
429        fs::create_dir(&dir)?;
430    }
431    Ok(dir)
432}