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
mod config;
mod download;
mod humble_api;
mod key_match;
mod models;
mod util;

pub mod prelude {
    pub use crate::auth;
    pub use crate::download_bundle;
    pub use crate::list_bundles;
    pub use crate::list_humble_choices;
    pub use crate::search;
    pub use crate::show_bundle_details;

    pub use crate::humble_api::{ApiError, HumbleApi};
    pub use crate::models::*;
    pub use crate::util::byte_string_to_number;
}

use anyhow::{anyhow, Context};
use config::{get_config, set_config, Config};
use humble_api::{ApiError, HumbleApi};
use key_match::KeyMatch;
use prelude::*;
use std::fs;
use std::path;
use tabled::settings::object::Columns;
use tabled::settings::Alignment;
use tabled::settings::Merge;
use tabled::settings::Modify;
use tabled::settings::Style;

pub fn auth(session_key: &str) -> Result<(), anyhow::Error> {
    set_config(Config {
        session_key: session_key.to_owned(),
    })
}

pub fn handle_http_errors<T>(input: Result<T, ApiError>) -> Result<T, anyhow::Error> {
    match input {
        Ok(val) => Ok(val),
        Err(ApiError::NetworkError(e)) if e.is_status() => match e.status().unwrap() {
            reqwest::StatusCode::UNAUTHORIZED => Err(anyhow!(
                "Unauthorized request (401). Is the session key correct?"
            )),
            reqwest::StatusCode::NOT_FOUND => Err(anyhow!(
                "Bundle not found (404). Is the bundle key correct?"
            )),
            s => Err(anyhow!("failed with status: {}", s)),
        },
        Err(e) => Err(anyhow!("failed: {}", e)),
    }
}

pub fn list_humble_choices(period: &ChoicePeriod) -> Result<(), anyhow::Error> {
    let config = get_config()?;
    let api = HumbleApi::new(&config.session_key);

    let choices = api.read_bundle_choices(&period.to_string())?;

    println!();
    println!("{}", choices.options.title);
    println!();

    let options = choices.options;

    let mut builder = tabled::builder::Builder::default();
    builder.set_header(["#", "Title", "Redeemed"]);

    let mut counter = 1;
    let mut all_redeemed = true;
    for (_, game_data) in options.data.game_data.iter() {
        for tpkd in game_data.tpkds.iter() {
            builder.push_record([
                counter.to_string().as_str(),
                tpkd.human_name.as_str(),
                tpkd.claim_status().to_string().as_str(),
            ]);

            counter += 1;

            if tpkd.claim_status() == ClaimStatus::No {
                all_redeemed = false;
            }
        }
    }

    let table = builder
        .build()
        .with(Style::psql())
        .with(Modify::new(Columns::single(0)).with(Alignment::right()))
        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
        .to_string();

    println!("{table}");

    if !all_redeemed {
        let url = "https://www.humblebundle.com/membership/home";
        println!("Visit {url} to redeem your keys.");
    }
    Ok(())
}

pub fn search(keywords: &str, match_mode: MatchMode) -> Result<(), anyhow::Error> {
    let config = get_config()?;
    let api = HumbleApi::new(&config.session_key);

    let keywords = keywords.to_lowercase();
    let keywords: Vec<&str> = keywords.split(" ").collect();

    let bundles = handle_http_errors(api.list_bundles())?;
    type BundleItem<'a> = (&'a Bundle, String);
    let mut search_result: Vec<BundleItem> = vec![];

    for b in &bundles {
        for p in &b.products {
            if p.name_matches(&keywords, &match_mode) {
                search_result.push((b, p.human_name.to_owned()));
            }
        }
    }

    if search_result.is_empty() {
        println!("Nothing found");
        return Ok(());
    }

    let mut builder = tabled::builder::Builder::default();
    builder.set_header(["Key", "Name", "Sub Item"]);
    for record in search_result {
        builder.push_record([
            record.0.gamekey.as_str(),
            record.0.details.human_name.as_str(),
            record.1.as_str(),
        ]);
    }

    let table = builder
        .build()
        .with(Style::psql())
        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
        .with(Modify::new(Columns::single(2)).with(Alignment::left()))
        .with(Merge::vertical())
        .to_string();

    println!("{table}");
    Ok(())
}

pub fn list_bundles(id_only: bool, claimed_filter: &str) -> Result<(), anyhow::Error> {
    let config = get_config()?;
    let api = HumbleApi::new(&config.session_key);

    // If no filter is required, we can do a single call
    // and finish quickly. Otherwise we will need to fetch
    // all bundle data and filter them.
    if id_only && claimed_filter == "all" {
        let ids = handle_http_errors(api.list_bundle_keys())?;
        for id in ids {
            println!("{}", id);
        }

        return Ok(());
    }

    let mut bundles = handle_http_errors(api.list_bundles())?;

    if claimed_filter != "all" {
        let claimed = claimed_filter == "yes";
        bundles.retain(|b| {
            let status = b.claim_status();
            status == ClaimStatus::Yes && claimed || status == ClaimStatus::No && !claimed
        });
    }

    if id_only {
        for b in bundles {
            println!("{}", b.gamekey);
        }

        return Ok(());
    }

    println!("{} bundle(s) found.\n", bundles.len());

    if bundles.is_empty() {
        return Ok(());
    }

    let mut builder = tabled::builder::Builder::default();
    builder.set_header(["Key", "Name", "Size", "Claimed"]);

    for p in bundles {
        builder.push_record([
            p.gamekey.as_str(),
            p.details.human_name.as_str(),
            util::humanize_bytes(p.total_size()).as_str(),
            p.claim_status().to_string().as_str(),
        ]);
    }

    let table = builder
        .build()
        .with(Style::psql())
        .with(Modify::new(Columns::single(1)).with(Alignment::left()))
        .with(Modify::new(Columns::single(2)).with(Alignment::right()))
        .to_string();
    println!("{table}");

    Ok(())
}

fn find_key(all_keys: Vec<String>, key_to_find: &str) -> Option<String> {
    let key_match = KeyMatch::new(all_keys, key_to_find);
    let keys = key_match.get_matches();

    match keys.len() {
        1 => Some(keys[0].clone()),
        0 => {
            eprintln!("No bundle matches '{}'", key_to_find);
            None
        }
        _ => {
            eprintln!("More than one bundle matches '{}':", key_to_find);
            for key in keys {
                eprintln!("{}", key);
            }
            None
        }
    }
}

pub fn show_bundle_details(bundle_key: &str) -> Result<(), anyhow::Error> {
    let config = get_config()?;
    let api = crate::HumbleApi::new(&config.session_key);

    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
        Some(key) => key,
        None => return Ok(()),
    };

    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;

    println!();
    println!("{}", bundle.details.human_name);
    println!();
    println!("Purchased  : {}", bundle.created.format("%v %I:%M %p"));
    println!("Total size : {}", util::humanize_bytes(bundle.total_size()));
    println!();

    if !bundle.products.is_empty() {
        let mut builder = tabled::builder::Builder::default();
        builder.set_header(["#", "Sub-item", "Format", "Total Size"]);

        for (idx, entry) in bundle.products.iter().enumerate() {
            builder.push_record([
                &(idx + 1).to_string(),
                &entry.human_name,
                &entry.formats(),
                &util::humanize_bytes(entry.total_size()),
            ]);
        }
        let table = builder
            .build()
            .with(Style::psql())
            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
            .with(Modify::new(Columns::single(2)).with(Alignment::left()))
            .with(Modify::new(Columns::single(3)).with(Alignment::right()))
            .to_string();

        println!("{table}");
    } else {
        println!("No items to show.");
    }

    // Product keys
    let product_keys = bundle.product_keys();
    if !product_keys.is_empty() {
        println!();
        println!("Keys in this bundle:");
        println!();
        let mut builder = tabled::builder::Builder::default();
        builder.set_header(["#", "Key Name", "Redeemed"]);

        let mut all_redeemed = true;
        for (idx, entry) in product_keys.iter().enumerate() {
            builder.push_record([
                (idx + 1).to_string().as_str(),
                entry.human_name.as_str(),
                if entry.redeemed { "Yes" } else { "No" },
            ]);

            if !entry.redeemed {
                all_redeemed = false;
            }
        }

        let table = builder
            .build()
            .with(Style::psql())
            .with(Modify::new(Columns::single(0)).with(Alignment::right()))
            .with(Modify::new(Columns::single(1)).with(Alignment::left()))
            .with(Modify::new(Columns::single(2)).with(Alignment::center()))
            .to_string();

        println!("{table}");

        if !all_redeemed {
            let url = "https://www.humblebundle.com/home/keys";
            println!("Visit {url} to redeem your keys.");
        }
    }

    Ok(())
}

pub fn download_bundle(
    bundle_key: &str,
    formats: Vec<String>,
    max_size: u64,
    item_numbers: Option<&str>,
) -> Result<(), anyhow::Error> {
    let config = get_config()?;

    let api = crate::HumbleApi::new(&config.session_key);

    let bundle_key = match find_key(handle_http_errors(api.list_bundle_keys())?, bundle_key) {
        Some(key) => key,
        None => return Ok(()),
    };

    let bundle = handle_http_errors(api.read_bundle(&bundle_key))?;

    // To parse the item number ranges, we need to know the max value
    // for unbounded ranges (e.g. 12-). That's why we parse this argument
    // after we read the bundle from the API.
    let item_numbers = if let Some(value) = item_numbers {
        let ranges = value.split(',').collect::<Vec<_>>();
        util::union_usize_ranges(&ranges, bundle.products.len())?
    } else {
        vec![]
    };

    // Filter products based on entered criteria
    // Note that item numbers entered by user start at 1, while our index
    // starts as 0.
    let products = bundle
        .products
        .iter()
        .enumerate()
        .filter(|&(i, _)| item_numbers.is_empty() || item_numbers.contains(&(i + 1)))
        .map(|(_, p)| p)
        .filter(|p| max_size == 0 || p.total_size() < max_size)
        .filter(|p| {
            formats.is_empty() || util::str_vectors_intersect(&p.formats_as_vec(), &formats)
        })
        .collect::<Vec<_>>();

    if products.is_empty() {
        println!("Nothing to download");
        return Ok(());
    }

    // Create the bundle directory
    let dir_name = util::replace_invalid_chars_in_filename(&bundle.details.human_name);
    let bundle_dir = create_dir(&dir_name)?;

    let client = reqwest::Client::new();

    for product in products {
        if max_size > 0 && product.total_size() > max_size {
            continue;
        }

        println!();
        println!("{}", product.human_name);

        let dir_name = util::replace_invalid_chars_in_filename(&product.human_name);
        let entry_dir = bundle_dir.join(dir_name);
        if !entry_dir.exists() {
            fs::create_dir(&entry_dir)?;
        }

        for product_download in product.downloads.iter() {
            for dl_info in product_download.items.iter() {
                if !formats.is_empty() && !formats.contains(&dl_info.format.to_lowercase()) {
                    println!("Skipping '{}'", dl_info.format);
                    continue;
                }

                let filename = util::extract_filename_from_url(&dl_info.url.web).context(
                    format!("Cannot get file name from URL '{}'", &dl_info.url.web),
                )?;
                let download_path = entry_dir.join(&filename);

                let f = download::download_file(
                    &client,
                    &dl_info.url.web,
                    download_path.to_str().unwrap(),
                    &filename,
                );
                util::run_future(f)?;
            }
        }
    }

    Ok(())
}

fn create_dir(dir: &str) -> Result<path::PathBuf, std::io::Error> {
    let dir = path::Path::new(dir).to_owned();
    if !dir.exists() {
        fs::create_dir(&dir)?;
    }
    Ok(dir)
}