wyvern 1.0.0

A simple CLI tool for installing and maintaining linux GOG games
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
#[macro_use]
extern crate structopt;
extern crate confy;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use structopt::StructOpt;
extern crate zip;
#[macro_use]
extern crate human_panic;
extern crate dirs;
extern crate gog;
extern crate indicatif;
#[cfg(feature = "eidolonint")]
extern crate libeidolon;
extern crate regex;
use regex::Regex;
mod args;
mod config;
use crate::args::Connect::*;
use crate::args::Sync::*;
use crate::args::Wyvern;
use crate::args::Wyvern::Download;
use crate::args::Wyvern::*;
use crate::config::*;
use gog::extract::*;
use gog::gog::{connect::ConnectGameStatus::*, connect::*, FilterParam::*, *};
use gog::token::Token;
use gog::Error;
use gog::ErrorKind::*;
use gog::Gog;
use indicatif::{ProgressBar, ProgressStyle};
use std::fs;
use std::fs::*;
use std::io;
use std::io::Read;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::process::Command;
fn main() -> Result<(), ::std::io::Error> {
    #[cfg(not(debug_assertions))]
    setup_panic!();
    let mut config: Config = confy::load("wyvern")?;
    let args = Wyvern::from_args();
    if config.token.is_none() {
        let token = login();
        config.token = Some(token);
    }
    config.token = Some(config.token.unwrap().refresh().unwrap());
    print!("");
    let gog = Gog::new(config.token.clone().unwrap());
    let mut sync_saves = config.sync_saves.clone();
    if sync_saves.is_some() {
        sync_saves = Some(
            sync_saves
                .unwrap()
                .replace("~", dirs::home_dir().unwrap().to_str().unwrap()),
        );
    }
    confy::store("wyvern", config)?;
    match args {
        List { id } => {
            if let Some(id) = id {
                let details = gog.get_game_details(id).unwrap();
                println!("Title - GameID");
                println!("{} - {}", details.title, id);
            } else {
                list_owned(gog).unwrap();
            }
        }
        Download {
            id,
            search,
            install_after,
            windows_auto,
            windows_force,
            first,
        } => {
            if let Some(search) = search {
                let search_results =
                    gog.get_filtered_products(FilterParams::from_one(Search(search)));
                if search_results.is_ok() {
                    let e = search_results.unwrap();
                    if !first {
                        for (idx, pd) in e.iter().enumerate() {
                            println!("{}. {} - {}", idx, pd.title, pd.id);
                        }
                        let mut choice = String::new();
                        loop {
                            print!("Select a game to download:");
                            io::stdout().flush().unwrap();
                            io::stdin().read_line(&mut choice).unwrap();
                            let parsed = choice.trim().parse::<usize>();
                            if let Ok(i) = parsed {
                                if e.len() > i {
                                    let details = gog.get_game_details(e[i].id).unwrap();
                                    let pname = details.title.clone();
                                    let (name, downloaded_windows) =
                                        download_prep(gog, details, windows_auto, windows_force)
                                            .unwrap();
                                    if install_after.is_some() && !downloaded_windows {
                                        println!("Installing game");
                                        let mut installer = fs::File::open(name).unwrap();
                                        install(&mut installer, install_after.unwrap(), pname);
;
                                    }
                                    break;
                                } else {
                                    println!("Please enter a valid number corresponding to an available download");
                                }
                            } else {
                                println!(
                                    "Please enter a number corresponding to an available download"
                                );
                            }
                        }
                    } else {
                        let details = gog.get_game_details(e[0].id).unwrap();
                        let pname = details.title.clone();
                        let (name, downloaded_windows) =
                            download_prep(gog, details, windows_auto, windows_force).unwrap();
                        if install_after.is_some() && !downloaded_windows {
                            println!("Installing game");
                            let mut installer = fs::File::open(name).unwrap();
                            install(&mut installer, install_after.unwrap(), pname);
                        }
                    }
                } else {
                    println!("Could not find any games.");
                }
            } else if let Some(id) = id {
                let details = gog.get_game_details(id).unwrap();
                let pname = details.title.clone();
                let (name, downloaded_windows) =
                    download_prep(gog, details, windows_auto, windows_force).unwrap();

                if install_after.is_some() && !downloaded_windows {
                    println!("Installing game");
                    let mut installer = fs::File::open(name).unwrap();
                    install(&mut installer, install_after.unwrap(), pname);
                }
            } else {
                println!("Did not specify a game to download. Exiting.");
            }
        }
        Install {
            installer_name,
            path,
        } => {
            let mut installer = File::open(&installer_name);
            if installer.is_ok() {
                install(&mut installer.unwrap(), path, installer_name);
            } else {
                println!("File {} does not exist", installer_name)
            }
        }
        #[cfg(feature = "eidolonint")]
        UpdateEidolon { force } => {
            use libeidolon::games::*;
            let eidolon_games = get_games();
            for game in eidolon_games {
                if let Ok(read) = read_game(game.as_str()) {
                    if read.typeg == GameType::WyvernGOG {
                        println!("Attempting to update {}", read.pname);
                        let path = PathBuf::from(read.command);
                        let ginfo_path = path.clone().join("gameinfo");
                        update(&gog, path, ginfo_path, force);
                    }
                } else {
                    println!("Could not check {}", game);
                }
            }
        }
        Sync { .. } => match args {
            Sync(Push { game_dir, sync_to }) => {
                if sync_saves.is_some() {
                    let mut sync_saves = sync_saves.unwrap();
                    if sync_to.is_some() {
                        sync_saves = sync_to.unwrap().to_str().unwrap().to_string();
                    }
                    let gameinfo = File::open(game_dir.join("gameinfo"));
                    if gameinfo.is_ok() {
                        let mut ginfo_string = String::new();
                        gameinfo.unwrap().read_to_string(&mut ginfo_string).unwrap();
                        let gameinfo = parse_gameinfo(ginfo_string);
                        if let Ok(details) =
                            gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone())))
                        {
                            let id = details[0].id;
                            let savedb_path = PathBuf::from(sync_saves.clone()).join("savedb.json");
                            let mut save_db = SaveDB::load(&savedb_path).unwrap();
                            let mut path: PathBuf;
                            if save_db.saves.contains_key(&format!("{}", id)) {
                                path = PathBuf::from(
                                    save_db.saves.get(&format!("{}", id)).unwrap().path.clone(),
                                );
                            } else {
                                let mut input = String::new();
                                let mut yn = String::new();
                                println!("You haven't specified where this game's save files are yet. Please insert a path to where they are located.");
                                loop {
                                    io::stdout().flush().unwrap();
                                    io::stdin().read_line(&mut input).unwrap();
                                    print!(
                                        "Are you sure this where the save files are located?(Y/n)"
                                    );
                                    io::stdout().flush().unwrap();
                                    io::stdin().read_line(&mut yn).unwrap();
                                    if &yn == "n" || &yn == "N" {
                                        continue;
                                    }
                                    break;
                                }
                                let save_path = std::env::current_dir()
                                    .unwrap()
                                    .join(PathBuf::from(&input.trim()));
                                save_db.saves.insert(
                                    format!("{}", id),
                                    SaveInfo {
                                        path: save_path.to_str().unwrap().to_string(),
                                        identifier: SaveType::GOG(id),
                                    },
                                );
                                path = save_path;;
                                save_db.store(&savedb_path).unwrap();
                            }
                            let mut path_string = path.to_str().unwrap().to_string();
                            if path.exists() && path.is_dir() {
                                path_string += "/";
                            }
                            let save_dir = PathBuf::from(sync_saves);
                            let save_folder =
                                save_dir.clone().join("saves").join(format!("gog_{}", id));
                            if fs::metadata(&save_folder).is_err() {
                                fs::create_dir_all(&save_folder).unwrap();
                            }
                            Command::new("rsync")
                                .arg(
                                    path_string
                                        .replace("~", dirs::home_dir().unwrap().to_str().unwrap()),
                                )
                                .arg(save_folder.to_str().unwrap())
                                .arg("-a")
                                .output()
                                .unwrap();
                            println!("Synced save files to save folder!");
                        } else {
                            println!("Could not find a game named {}.", gameinfo.name);
                        }
                    } else {
                        println!("Game directory or gameinfo file missing.")
                    }
                } else {
                    println!("You have not configured a directory to sync your saves to. Edit ~/.config/wyvern/wyvern.toml to get started!");
                }
            }
            Sync(Pull {
                game_dir,
                sync_from,
                force,
                ignore_older,
            }) => {
                if sync_saves.is_some() {
                    let sync_saves = sync_saves
                        .unwrap()
                        .replace("~", dirs::home_dir().unwrap().to_str().unwrap());
                    let gameinfo = File::open(game_dir.join("gameinfo"));
                    if gameinfo.is_ok() {
                        let mut ginfo_string = String::new();
                        gameinfo
                            .unwrap()
                            .read_to_string(&mut ginfo_string)
                            .expect("Couldn't read from gameinfo file.");
                        let gameinfo = parse_gameinfo(ginfo_string);
                        if let Ok(details) =
                            gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone())))
                        {
                            let id = details[0].id;
                            let mut savedb_path =
                                PathBuf::from(sync_saves.clone()).join("savedb.json");
                            if sync_from.is_some() {
                                savedb_path = sync_from.unwrap().join("savedb.json");
                            }
                            let mut save_db = SaveDB::load(&savedb_path).unwrap();
                            if save_db.saves.contains_key(&format!("{}", id)) {
                                let save_path = PathBuf::from(sync_saves.clone())
                                    .join("saves")
                                    .join(format!("gog_{}", id));
                                let save_files = save_db.saves.get(&format!("{}", id)).unwrap();

                                let saved_path = PathBuf::from(
                                    save_files
                                        .path
                                        .replace("~", dirs::home_dir().unwrap().to_str().unwrap()),
                                );
                                sync(save_path, saved_path, force, ignore_older);
                            } else {
                                println!("This game's saves have not been configured to be synced yet. Push first!");
                            }
                        } else {
                            println!("Could not find a game named {}.", gameinfo.name)
                        }
                    } else {
                        println!("Game directory or gameinfo file missing.");
                    }
                } else {
                    println!("You have not config a directory to sync your saves from. Edit ~/.config/wyvern/wyvern.toml to get started!");
                }
            }
            Sync(DbPull {
                path,
                force,
                ignore_older,
            }) => {
                let dbpath: PathBuf;
                if path.is_some() {
                    dbpath = path.unwrap();
                } else if sync_saves.is_some() {
                    dbpath = PathBuf::from(sync_saves.unwrap());
                } else {
                    println!("You have not specified a sync directory in the config yet. Specify one or call db with a path to your db.");
                    std::process::exit(0);
                }
                let savedb = SaveDB::load(&dbpath.join("savedb.json")).unwrap();
                for (key, value) in savedb.saves.iter() {
                    println!("Syncing {} now", key);
                    let save_path = PathBuf::from(
                        value
                            .path
                            .replace("~", dirs::home_dir().unwrap().to_str().unwrap()),
                    );
                    let mut folder_name = key.clone();
                    if let SaveType::GOG(id) = value.identifier {
                        folder_name = format!("gog_{}", id);
                    }
                    let synced_path = dbpath.join("saves").join(folder_name);
                    sync(synced_path, save_path, force, ignore_older);
                    println!("Synced {}", key);
                }
            }
            Sync(DbPush {
                path,
                force,
                ignore_older,
            }) => {
                let dpath: PathBuf;
                if path.is_some() {
                    dpath = path.unwrap();
                } else if sync_saves.is_some() {
                    dpath = PathBuf::from(sync_saves.unwrap());
                } else {
                    println!("You have not specified a sync directory in the config yet. Specify one or call db with a path to your db.");
                    std::process::exit(0);
                }
                let savedb = SaveDB::load(dpath.clone().join("savedb.json")).unwrap();
                for (key, value) in savedb.saves {
                    println!("Syncing {} now", key);
                    let save_path = PathBuf::from(
                        value
                            .path
                            .replace("~", dirs::home_dir().unwrap().to_str().unwrap()),
                    );
                    let mut folder_name = key.clone();
                    if let SaveType::GOG(id) = value.identifier {
                        folder_name = format!("gog_{}", id);
                    }
                    let mut dest_path = dpath.join("saves").join(&folder_name);
                    sync(save_path, dest_path, force, ignore_older);
                    println!("Synced {}", key);
                }
            }
            Sync(Saves {
                game_dir,
                saves,
                db,
            }) => {
                let dpath: PathBuf;
                if db.is_some() {
                    println!("db");
                    dpath = db.unwrap();
                } else if sync_saves.is_some() {
                    dpath = PathBuf::from(sync_saves.unwrap());
                } else {
                    println!("You have not specified a sync directory in the config yet. Specify one or call saves with a path to your db.");
                    std::process::exit(0);
                }
                let dbpath = std::env::current_dir()
                    .unwrap()
                    .join(dpath.clone())
                    .join("savedb.json");
                println!("{:?}", dbpath);
                let mut savedb = SaveDB::load(dbpath.clone()).unwrap();
                let gameinfo_path = std::env::current_dir()
                    .unwrap()
                    .join(game_dir)
                    .join("gameinfo");
                if gameinfo_path.is_file() {
                    let mut ginfo_string = String::new();
                    File::open(&gameinfo_path)
                        .unwrap()
                        .read_to_string(&mut ginfo_string)
                        .unwrap();
                    let gameinfo = parse_gameinfo(ginfo_string);
                    if let Ok(details) =
                        gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone())))
                    {
                        let id = details[0].id;
                        savedb.saves.insert(
                            format!("{}", id),
                            SaveInfo {
                                path: std::env::current_dir()
                                    .unwrap()
                                    .join(saves)
                                    .to_str()
                                    .unwrap()
                                    .to_string(),
                                identifier: SaveType::GOG(id),
                            },
                        );
                        savedb.store(dbpath).unwrap();
                    } else {
                        println!("Could not find a game named {}.", gameinfo.name);
                    }
                } else {
                    println!("No gameinfo")
                }
            }
            _ => println!("Wow, you should not be seeing this message."),
        },

        Update { mut path, force } => {
            if path.is_none() {
                path = Some(PathBuf::from(".".to_string()));
            }
            let path = path.unwrap();

            let game_info_path = path.clone().join("gameinfo");
            update(&gog, path, game_info_path, force);
        }
        Connect { .. } => {
            let uid: i64 = gog.get_user_data().unwrap().user_id.parse().unwrap();
            let linked = gog.connect_account(uid);
            if linked.is_err() {
                println!("You don't have a steam account linked to GOG! Go to https://www.gog.com/connect to link one.");
                return Ok(());
            } else {
                gog.connect_scan(uid).unwrap();
            }
            match args {
                Connect(ListConnect { claim, quiet }) => {
                    let status = gog.connect_status(uid);
                    if status.is_ok() {
                        let mut items = status.unwrap().items;
                        let left_over: Vec<(String, ConnectGame)> = items
                            .into_iter()
                            .filter_map(|x| {
                                if !claim || x.1.status == READY_TO_LINK {
                                    let details = gog.product(vec![x.1.id], vec![]);
                                    if details.is_ok() {
                                        println!(
                                            "{} - {:?}",
                                            details.unwrap()[0].title,
                                            x.1.status
                                        );
                                        return None;
                                    }
                                }
                                return Some(x);
                            })
                            .collect();
                        if !quiet {
                            println!("{} items not shown due to options", left_over.len());
                        }
                    } else {
                        let err = status.err().unwrap();
                        match err.kind() {
                            NotAvailable => println!("No GOG Connect games are available."),
                            _ => panic!("{:?}", err),
                        };
                    }
                }
                Connect(ClaimAll {}) => {
                    gog.connect_claim(uid).unwrap();
                    println!("Claimed all available games");
                }
                _ => println!("Tell someone about this, because it should not be happening"),
            }
        }
    };
    Ok(())
}
fn update(gog: &Gog, path: PathBuf, game_info_path: PathBuf, force: bool) {
    if let Ok(mut gameinfo) = File::open(game_info_path) {
        let regex = Regex::new(r"(.*) \(gog").unwrap();
        let mut ginfo_string = String::new();
        gameinfo.read_to_string(&mut ginfo_string).unwrap();
        let ginfo = parse_gameinfo(ginfo_string);
        let name = ginfo.name.clone();
        let version = ginfo.version.clone();
        let product = gog.get_filtered_products(FilterParams::from_one(Search(name.clone())));
        if product.is_ok() {
            let details = gog.get_game_details(product.unwrap()[0].id).unwrap();
            let downloads = details.downloads.linux.unwrap();
            let current_version = regex
                .captures(&(downloads[0].version.clone().unwrap()))
                .unwrap()[1]
                .trim()
                .to_string();
            println!(
                "Installed version : {}. Version Online: {}",
                version, current_version
            );
            if version == current_version && !force {
                println!("No newer version to update to. Sorry!");
            } else {
                if force && version == current_version {
                    println!("Forcing reinstall due to --force option.");
                }
                println!("Updating {} to version {}", name, current_version);
                let name = download(&gog, downloads).unwrap();
                println!("Installing.");
                let mut installer = File::open(name.clone()).unwrap();
                install(&mut installer, path, name);
                println!("Game finished updating!");
            }
        } else {
            println!("Can't find game {} in your library.", name);
        }
    } else {
        println!("Game installation missing a gameinfo file to check for update with.");
    }
}
fn parse_gameinfo(ginfo: String) -> GameInfo {
    let mut lines = ginfo.trim().lines();
    let name = lines.next().unwrap().to_string();
    let version = lines.last().unwrap().trim().to_string();
    GameInfo {
        name: name,
        version: version,
    }
}
fn sync(sync_from: PathBuf, sync_to: PathBuf, ignore_older: bool, force: bool) {
    let from_meta = fs::metadata(&sync_from);
    let to_meta = fs::metadata(&sync_to);
    if from_meta.is_err() {
        println!("Can't sync nonexistent files! There should be save files at {:?}, but there are not. Aborting.", &sync_from);
        return;
    }
    if let Ok(to_meta) = to_meta {
        let to_modified = to_meta.modified().unwrap();
        let from_modified = from_meta.unwrap().modified().unwrap();
        if to_modified > from_modified && !force {
            if ignore_older {
                println!("Aborting due to --ignore-older flag and newer save files being present");
                return;
            }
            print!("Synced save files are more recent. Are you sure you want to proceed?(y/N)");
            let mut answer = String::new();
            io::stdout().flush().unwrap();
            io::stdin().read_line(&mut answer).unwrap();
            if answer.trim() == "y" || answer.trim() == "Y" {
                println!("Proceeding as normal.");
            } else {
                println!("Sync aborted.");
                return;
            }
        }
    }
    Command::new("rsync")
        .arg(sync_from.to_str().unwrap().to_string() + "/")
        .arg(
            sync_to
                .parent()
                .unwrap()
                .to_path_buf()
                .to_str()
                .unwrap()
                .to_string()
                + "/",
        )
        .arg("-a")
        .arg("--force")
        .output()
        .unwrap();
}
fn download_prep(
    gog: Gog,
    details: GameDetails,
    windows_auto: bool,
    windows_force: bool,
) -> Result<(String, bool), Error> {
    if details.downloads.linux.is_some() && !windows_force {
        let name = download(&gog, details.downloads.linux.unwrap()).unwrap();
        return Ok((name, false));
    } else {
        if !windows_auto && !windows_force {
            let mut choice = String::new();
            loop {
                println!("This game does not support linux! Would you like to download the windows version to run under wine?(y/n)");
                io::stdout().flush().unwrap();
                io::stdin().read_line(&mut choice).unwrap();
                match choice.to_lowercase().as_str() {
                    "y" => {
                        println!("Downloading windows files. Note: wyvern does not support automatic installation from windows games");
                        let name = download(&gog, details.downloads.windows.unwrap()).unwrap();
                        return Ok((name, true));
                    }
                    "n" => {
                        println!("No suitable downloads found. Exiting");
                        std::process::exit(0);
                    }
                    _ => println!("Please enter y or n to proceed."),
                }
            }
        } else {
            if !windows_force {
                println!("No linux version available. Downloading windows version.");
            }
            let name = download(&gog, details.downloads.windows.unwrap()).unwrap();
            return Ok((name, true));
        }
    }
}
fn install(installer: &mut File, path: PathBuf, name: String) {
    extract(
        installer,
        "/tmp",
        ToExtract {
            unpacker: false,
            mojosetup: false,
            data: true,
        },
    )
    .unwrap();
    let file = File::open("/tmp/data.zip").unwrap();
    // Extract code taken mostly from zip example
    let mut archive = zip::ZipArchive::new(file).unwrap();
    let len = archive.len();
    let pb = ProgressBar::new(len as u64);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len}")
            .progress_chars("#>-"),
    );
    for i in 0..len {
        let mut file = archive.by_index(i).unwrap();
        let filtered_path = file
            .sanitized_name()
            .to_str()
            .unwrap()
            .replace("/noarch", "")
            .replace("data/", "")
            .to_owned();
        //Extract only files for the game itself
        if !filtered_path.contains("meta") && !filtered_path.contains("scripts") {
            let outpath = path.clone().join(PathBuf::from(filtered_path));
            if (&*file.name()).ends_with('/') {
                fs::create_dir_all(&outpath).unwrap();
            } else {
                if let Some(p) = outpath.parent() {
                    if !p.exists() {
                        fs::create_dir_all(&p).unwrap();
                    }
                }
                let mut outfile = fs::File::create(&outpath).unwrap();
                io::copy(&mut file, &mut outfile).unwrap();
            }
            use std::os::unix::fs::PermissionsExt;
            if let Some(mode) = file.unix_mode() {
                fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap();
            }
        }
        pb.inc(1);
    }
    pb.finish_with_message("Game installed!");
    #[cfg(feature = "eidolonint")]
    {
        use libeidolon::games::*;
        use libeidolon::helper::*;
        use libeidolon::*;
        let proc_name = create_procname(name.clone());
        let game = Game {
            name: proc_name,
            pname: name,
            command: std::env::current_dir()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string(),
            typeg: GameType::WyvernGOG,
        };
        add_game(game);
    }
}
pub fn login() -> Token {
    println!("It appears that you have not logged into GOG. Please go to the following URL, log into GOG, and paste the code from the resulting url's ?code parameter into the input here.");
    println!("https://login.gog.com/auth?client_id=46899977096215655&layout=client2%22&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code");
    io::stdout().flush().unwrap();
    let mut code = String::new();
    let mut token: Token;
    loop {
        io::stdin().read_line(&mut code).unwrap();
        let attempt_token = Token::from_login_code(code.as_str());
        if attempt_token.is_ok() {
            token = attempt_token.unwrap();
            println!("Got token. Thanks!");
            break;
        } else {
            println!("Invalid code. Try again!");
        }
    }
    token
}
fn list_owned(gog: Gog) -> Result<(), Error> {
    let games = gog.get_filtered_products(FilterParams::from_one(MediaType(1)))?;
    println!("Title - GameID");
    for game in games {
        println!("{} - {}", game.title, game.id);
    }
    Ok(())
}
fn download(gog: &Gog, downloads: Vec<gog::gog::Download>) -> Result<String, Error> {
    let mut names = vec![];
    for download in downloads.iter() {
        names.push(download.name.clone());
    }
    let mut responses = gog.download_game(downloads);
    let count = responses.len();
    for (idx, mut response) in responses.iter_mut().enumerate() {
        let total_size = response
            .headers()
            .get("Content-Length")
            .unwrap()
            .to_str()
            .unwrap()
            .parse()
            .unwrap();
        let pb = ProgressBar::new(total_size);
        pb.set_style(ProgressStyle::default_bar()
            .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})")
            .progress_chars("#>-"));
        let name = names[idx].clone();
        println!("Downloading {}, {} of {}", name, idx + 1, count);
        let mut fd = fs::File::create(name.clone())?;
        let mut perms = fd.metadata()?.permissions();
        perms.set_mode(0o744);
        fd.set_permissions(perms)?;
        let mut pb_read = pb.wrap_read(response);
        io::copy(&mut pb_read, &mut fd)?;
        pb.finish();
    }
    println!("Done downloading!");
    return Ok(names[0].clone());
}