├── .github └── FUNDING.yml ├── .gitignore ├── .builds ├── arm.yml └── wyvern.yml ├── snap └── snapcraft.yaml ├── Cargo.toml ├── src ├── connect.rs ├── config.rs ├── interactive.rs ├── args.rs ├── sync.rs ├── main.rs └── games.rs ├── README.md └── LICENSE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [nicohman] 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | /target 13 | **/*.rs.bk 14 | -------------------------------------------------------------------------------- /.builds/arm.yml: -------------------------------------------------------------------------------- 1 | image: archlinux 2 | secrets: 3 | - dcfce43c-8472-4e5d-89f8-319e9ff7cb1c 4 | - 89991b16-705b-4276-9178-bfc81c7fdd28 5 | environment: 6 | deploy: nicohman@demenses.net 7 | sources: 8 | - https://git.sr.ht/~nicohman/wyvern 9 | tasks: 10 | - deploy: | 11 | sshopts="ssh -o StrictHostKeyChecking=no" 12 | $sshopts $deploy /home/nicohman/update_wyvern_arm.sh 13 | triggers: 14 | - {action: email, condition: failure, to: Nico Hickman } 15 | -------------------------------------------------------------------------------- /snap/snapcraft.yaml: -------------------------------------------------------------------------------- 1 | name: wyvern 2 | base: core18 3 | version: git 4 | summary: Commandline gog downloader client 5 | description: Command-line tool written in rust that is meant to make downloading GOG games and associated activities easier and faster on linux. 6 | 7 | grade: stable 8 | confinement: strict 9 | 10 | apps: 11 | wyvern: 12 | command: wyvern 13 | plugs: [ network, home ] 14 | 15 | parts: 16 | wyvern: 17 | plugin: rust 18 | source: . 19 | build-packages: 20 | - build-essential 21 | - libssl-dev 22 | - pkg-config 23 | stage-packages: 24 | - libssl1.0.0 25 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wyvern" 3 | version = "1.4.1" 4 | authors = ["nicohman "] 5 | license="GPL-3.0" 6 | repository="https://git.sr.ht/~nicohman/wyvern" 7 | description="A simple CLI tool for installing and maintaining linux GOG games" 8 | readme="README.md" 9 | keywords=["gog", "games", "gaming"] 10 | categories=["games","command-line-interface"] 11 | [features] 12 | eidolonint = ["eidolon"] 13 | [[bin]] 14 | name = "wyvern" 15 | path = "src/main.rs" 16 | [dependencies] 17 | structopt = "0.2.10" 18 | serde = "1.0.70" 19 | dialoguer = "0.4.0" 20 | serde_derive = "1.0" 21 | serde_json = "1.0" 22 | human-panic = "1.0.1" 23 | confy = "0.3.1" 24 | gog = "0.4.0" 25 | indicatif = "0.10.3" 26 | zip = "0.5" 27 | eidolon = { version = "1.4.6", optional = true } 28 | toml = "0.4.10" 29 | dirs = "1.0.4" 30 | rayon = "1.0.3" 31 | log = "0.4" 32 | clap-verbosity-flag = "0.2.0" 33 | crc = "1.8.1" 34 | inflate = "0.4.4" 35 | reqwest = "0.9.9" 36 | curl = "0.4" 37 | walkdir = "2" 38 | url = "1.7.2" 39 | console = "0.7.0" 40 | lazy_static = "1" 41 | tempfile = "2" 42 | -------------------------------------------------------------------------------- /.builds/wyvern.yml: -------------------------------------------------------------------------------- 1 | image: archlinux 2 | packages: 3 | - cargo 4 | - rsync 5 | secrets: 6 | - dcfce43c-8472-4e5d-89f8-319e9ff7cb1c 7 | - 89991b16-705b-4276-9178-bfc81c7fdd28 8 | environment: 9 | RUST_BACKTRACE: "1" 10 | deploy: nicohman@demenses.net 11 | sources: 12 | - https://git.sr.ht/~nicohman/wyvern 13 | tasks: 14 | - build_test: | 15 | cd wyvern 16 | cargo build 17 | - setup: | 18 | mkdir wyvern/target/debug/game_dir 19 | mkdir wyvern/target/debug/knights 20 | - test : | 21 | cd wyvern/target/debug 22 | ./wyvern down "Knights" --first 23 | ./wyvern install gog_knights_of_pen_and_paper_1_edition_2.0.0.1.sh knights/ 24 | echo "test" > knights/game/knightspp_Data/data.kopp 25 | ./wyvern sync saves knights knights/game/knightspp_Data/data.kopp --db ./game_dir 26 | ./wyvern sync push knights ./game_dir 27 | rm knights/game/knightspp_Data/data.kopp 28 | ./wyvern sync pull knights ./game_dir 29 | cat knights/game/knightspp_Data/data.kopp 30 | - build_release: | 31 | cd wyvern 32 | cargo build --release 33 | - deploy: | 34 | cd wyvern/target/release 35 | sshopts="ssh -o StrictHostKeyChecking=no" 36 | rsync --rsh="$sshopts" -rP wyvern $deploy:/home/nicohman/ravenserver-rs/static/wyvern-nightly 37 | triggers: 38 | - {action: email, condition: failure, to: Nico Hickman } 39 | -------------------------------------------------------------------------------- /src/connect.rs: -------------------------------------------------------------------------------- 1 | use args::Command::Connect; 2 | use args::Connect::*; 3 | use gog::gog::connect::ConnectGameStatus::*; 4 | use gog::gog::connect::*; 5 | use gog::ErrorKind::*; 6 | pub fn parse_args(gog: gog::Gog, args: ::args::Wyvern) -> gog::Gog { 7 | let uid: i64 = gog.get_user_data().unwrap().user_id.parse().unwrap(); 8 | info!("Getting GOG Connect steam account"); 9 | let linked = gog.connect_account(uid); 10 | if linked.is_err() { 11 | error!("You don't have a steam account linked to GOG! Go to https://www.gog.com/connect to link one."); 12 | return gog; 13 | } else { 14 | info!("Scanning for Connect games"); 15 | gog.connect_scan(uid).unwrap(); 16 | } 17 | match args.command { 18 | Connect(ListConnect { claim, quiet, json }) => { 19 | let status = gog.connect_status(uid); 20 | if status.is_ok() { 21 | let mut items = status.unwrap().items; 22 | let mut count_hidden = 0; 23 | let games: Vec<(String, ConnectGame)> = items 24 | .into_iter() 25 | .filter_map(|x| { 26 | if !claim || x.1.status == READY_TO_LINK { 27 | info!("Getting details for connect game"); 28 | let details = gog.product(vec![x.1.id], vec![]); 29 | if details.is_ok() { 30 | return Some((details.unwrap()[0].title.clone(), x.1)); 31 | } 32 | } 33 | count_hidden += 1; 34 | return None; 35 | }) 36 | .collect(); 37 | if json { 38 | let uct = ConnectList { games: games }; 39 | println!( 40 | "{}", 41 | serde_json::to_string(&uct) 42 | .expect("Couldn't convert connect games list to string") 43 | ); 44 | } else { 45 | for connect in games { 46 | println!("{} - {:?}", connect.0, connect.1.status); 47 | } 48 | } 49 | if !quiet { 50 | println!("{} items not shown due to options", count_hidden); 51 | } 52 | } else { 53 | let err = status.err().unwrap(); 54 | match err.kind() { 55 | NotAvailable => error!("No GOG Connect games are available."), 56 | _ => error!("{}", err), 57 | }; 58 | } 59 | } 60 | Connect(ClaimAll) => { 61 | gog.connect_claim(uid).unwrap(); 62 | println!("Claimed all available games"); 63 | } 64 | _ => error!("Tell someone about this, because it should not be happening"), 65 | }; 66 | gog 67 | } 68 | #[derive(Serialize, Debug)] 69 | struct ConnectList { 70 | games: Vec<(String, ConnectGame)>, 71 | } 72 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wyvern ![](https://img.shields.io/crates/v/wyvern.svg?style=flat-square) [![builds.sr.ht status](https://builds.sr.ht/~nicohman/wyvern.svg)](https://builds.sr.ht/~nicohman/wyvern?) 2 | 3 | Wyvern is a command-line tool written in rust that is meant to make downloading GOG games and associated activities easier and faster on linux. It features: 4 | 5 | - Downloading games 6 | 7 | - Installing games without need for the graphical installers 8 | 9 | - One-command updating of games to their latest versions, while only updating files that have changed between versions. 10 | 11 | - GOG Connect functionality so you can scan for and claim games without leaving the terminal 12 | 13 | - Syncing save files to a filesystem backup(with integration with cloud services being worked on). 14 | 15 | - Optional(compile with the 'eidolonint' feature) integration with [eidolon](https://git.sr.ht/~nicohman/eidolon), so that it automatically registers installed games to eidolon. 16 | 17 | The GitHub repo is a mirror of the main [sr.ht](https://git.sr.ht/~nicohman/wyvern) repository. 18 | 19 | ## See it working 20 | 21 | [![asciicast](https://asciinema.org/a/226434.svg)](https://asciinema.org/a/226434) 22 | 23 | ## Installation 24 | 25 | Wyvern is available on [crates.io](https://crates.io/crates/wyvern), installable via cargo: 26 | 27 | `cargo install wyvern` 28 | 29 | There's also a few other ways to get wyvern: 30 | 31 | - AUR: [wyvern](https://aur.archlinux.org/packages/wyvern), maintained by 32 | [@PinkCathodeCat@cathoderay.tube](https://cathoderay.tube/users/PinkCathodeCat) 33 | 34 | - snap: [wyvern](https://snapcraft.io) on snapcraft.io 35 | 36 | - Download a binary, built from the latest git commit from [my website](https://demenses.net/downloads) 37 | 38 | - OpenSuse package 39 | [here](https://software.opensuse.org//download.html?project=home:stryan&package=wyvern), 40 | maintained by Steve Ryan 41 | 42 | - Build from source: 43 | 44 | ``` 45 | 46 | git clone https://git.sr.ht/~nicohman/wyvern && cd wyvern 47 | 48 | cargo install --path . --force 49 | 50 | ``` 51 | 52 | ### Dependencies 53 | 54 | Wyvern has a few extra dependencies, but few are required: 55 | - rsync for save file syncing 56 | - innoextract for windows game installation 57 | - unzip for faster game installation 58 | 59 | ## Usage 60 | 61 | Run `wyvern help` for a list of commands: 62 | 63 | ``` 64 | wyvern 1.4.0 65 | nicohman 66 | A simple CLI tool for installing and maintaining linux GOG games 67 | 68 | USAGE: 69 | wyvern [FLAGS] 70 | 71 | FLAGS: 72 | -h, --help Prints help information 73 | -V, --version Prints version information 74 | -v, --verbosity Pass many times for more log output 75 | 76 | SUBCOMMANDS: 77 | connect Operations associated with GOG Connect 78 | down Download specific game 79 | extras Download a game's extras 80 | help Prints this message or the help of the given subcommand(s) 81 | install Install a GOG game from an installer 82 | int Enter interactive mode 83 | login Force a login to GOG 84 | ls List all games you own 85 | sync Sync a game's saves to a specific location for backup 86 | update Update a game if there is an update available 87 | ``` 88 | 89 | ## Contributing/Reporting bugs 90 | 91 | Please file isues at the [sr.ht issue tracker](https://todo.sr.ht/~nicohman/wyvern) and patches/pull requests should be sent to [the mailing list](https://lists.sr.ht/~nicohman/wyvern). However, I will still accept both on GitHub if need be. 92 | 93 | 94 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use curl::easy::{Handler, WriteError}; 2 | use fs::File; 3 | use fs::OpenOptions; 4 | use gog::token::Token; 5 | use indicatif::{ProgressBar, ProgressStyle}; 6 | use serde_json; 7 | use std::collections::HashMap; 8 | use std::default::Default; 9 | use std::fs; 10 | use std::io::{Read, Write}; 11 | use std::path::PathBuf; 12 | #[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Hash)] 13 | pub enum SaveType { 14 | GOG(i64), 15 | Other(String), 16 | } 17 | type SaveMap = HashMap; 18 | #[derive(Serialize, Deserialize)] 19 | pub struct Config { 20 | pub version: u8, 21 | pub sync_saves: Option, 22 | pub token: Option, 23 | } 24 | impl Default for Config { 25 | fn default() -> Config { 26 | Config { 27 | version: 1, 28 | sync_saves: None, 29 | token: None, 30 | } 31 | } 32 | } 33 | #[derive(Serialize, Deserialize)] 34 | pub struct SaveInfo { 35 | pub identifier: SaveType, 36 | pub path: String, 37 | } 38 | #[derive(Serialize, Deserialize)] 39 | pub struct SaveDB { 40 | pub saves: SaveMap, 41 | } 42 | impl Default for SaveDB { 43 | fn default() -> SaveDB { 44 | SaveDB { 45 | saves: HashMap::new(), 46 | } 47 | } 48 | } 49 | impl SaveDB { 50 | pub fn load(path: N) -> Result 51 | where 52 | N: Into, 53 | { 54 | let path = path.into(); 55 | let mut unparsed = String::new(); 56 | let file = fs::File::open(path.clone()); 57 | if file.is_ok() { 58 | file.unwrap().read_to_string(&mut unparsed)?; 59 | Ok(serde_json::from_str(&unparsed).unwrap()) 60 | } else { 61 | let default = SaveDB::default(); 62 | default.store(path)?; 63 | Ok(default) 64 | } 65 | } 66 | pub fn store(&self, path: N) -> Result<&SaveDB, std::io::Error> 67 | where 68 | N: Into, 69 | { 70 | let to_write = serde_json::to_string(&self).unwrap(); 71 | OpenOptions::new() 72 | .create(true) 73 | .write(true) 74 | .truncate(true) 75 | .open(path.into())? 76 | .write_all(to_write.as_bytes())?; 77 | Ok(self) 78 | } 79 | } 80 | pub struct GameInfo { 81 | pub version: String, 82 | pub name: String, 83 | } 84 | impl GameInfo { 85 | pub fn parse(ginfo: impl Into) -> Result { 86 | let ginfo = ginfo.into(); 87 | let mut lines = ginfo.trim().lines(); 88 | info!("Getting name from gameinfo"); 89 | if let Some(name) = lines.next() { 90 | let name = name.to_string(); 91 | info!("Getting version string from gameinfo"); 92 | if let Some(version) = lines.last() { 93 | let version = version.trim().to_string(); 94 | Ok(GameInfo { 95 | name: name, 96 | version: version, 97 | }) 98 | } else { 99 | error!("Could not get version from gameinfo"); 100 | Err(gog::ErrorKind::MissingField("name".to_string()).into()) 101 | } 102 | } else { 103 | error!("Could not fetch name from gameinfo file"); 104 | Err(gog::ErrorKind::MissingField("name".to_string()).into()) 105 | } 106 | } 107 | } 108 | pub struct WriteHandler { 109 | pub writer: File, 110 | pub pb: Option, 111 | } 112 | impl Handler for WriteHandler { 113 | fn write(&mut self, data: &[u8]) -> std::result::Result { 114 | self.writer.write_all(data).expect("Couldn't write to file"); 115 | if self.pb.is_some() { 116 | let pb = self.pb.take().unwrap(); 117 | pb.inc(data.len() as u64); 118 | self.pb.replace(pb); 119 | } 120 | Ok(data.len()) 121 | } 122 | } 123 | #[derive(Serialize, Debug)] 124 | pub struct GamesList { 125 | pub games: Vec, 126 | } 127 | #[derive(Serialize, Debug)] 128 | pub enum Game { 129 | ProductInfo(gog::gog::ProductDetails), 130 | GameInfo(gog::gog::GameDetails, i64), 131 | } 132 | impl Game { 133 | pub fn title(&self) -> String { 134 | match self { 135 | Game::ProductInfo(details) => details.title.clone(), 136 | Game::GameInfo(details, _id) => details.title.clone(), 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/interactive.rs: -------------------------------------------------------------------------------- 1 | /// This module provides wyvern's interactive mode, which lets the user use wyvern through a text-based GUI instead of by running single commands 2 | use args::*; 3 | use crate::parse_args; 4 | use dialoguer::*; 5 | use gog::gog::FilterParam::*; 6 | use gog::gog::*; 7 | use gog::*; 8 | use std::fs; 9 | use structopt::StructOpt; 10 | pub fn interactive(gog: Gog, sync_saves: Option) -> Gog { 11 | let options = ["List", "Download", "Extras", "Connect"]; 12 | let mut gog = gog; 13 | loop { 14 | let pick = Select::new() 15 | .default(0) 16 | .items(&options[..]) 17 | .interact() 18 | .unwrap(); 19 | match options[pick] { 20 | // Both download and extras use an alphabetically-sorted list of all games owned 21 | "Download" | "Extras" => { 22 | let mut games = gog 23 | .get_all_filtered_products(FilterParams::from_one(MediaType(1))) 24 | .expect("Couldn't fetch games"); 25 | games.sort_by(|a, b| a.title.partial_cmp(&b.title).unwrap()); 26 | if options[pick] == "Download" { 27 | let mut check = Checkboxes::new(); 28 | let mut picks = check.with_prompt("Select games to download").paged(true); 29 | for g in games.iter() { 30 | picks.item(g.title.as_str()); 31 | } 32 | let picked = picks.interact().unwrap(); 33 | let install = Confirmation::new() 34 | .with_text("Do you want to install these games after they are downloaded?") 35 | .interact() 36 | .unwrap(); 37 | for g in picked { 38 | let id = games[g].id.to_string(); 39 | let mut args = vec!["wyvern", "download", "--id", id.as_str()]; 40 | if install { 41 | args.push("--install"); 42 | args.push(games[g].title.as_str()); 43 | if fs::create_dir(&games[g].title).is_err() { 44 | error!( 45 | "Could not make install directory named {}. Skipping.", 46 | games[g].title 47 | ); 48 | continue; 49 | } 50 | } 51 | let parsed = Wyvern::from_iter_safe(&args).unwrap(); 52 | gog = parse_args(parsed, gog, sync_saves.clone()).unwrap(); 53 | } 54 | } else 55 | // Extras 56 | { 57 | let mut select = Select::new(); 58 | let mut pick = select.with_prompt("Select game to download extras from").paged(true); 59 | for g in games.iter() { 60 | pick.item(g.title.as_str()); 61 | } 62 | let picked = pick.interact().unwrap(); 63 | let parsed = Wyvern::from_iter_safe(&vec![ 64 | "wyvern", 65 | "extras", 66 | "--first", 67 | games[picked].title.as_str(), 68 | ]) 69 | .unwrap(); 70 | gog = parse_args(parsed, gog, sync_saves.clone()).unwrap(); 71 | } 72 | } 73 | "Connect" => { 74 | let actions = ["Claim", "List", "Quit"]; 75 | loop { 76 | let pick = Select::new().default(0).items(&actions).interact().unwrap(); 77 | match actions[pick] { 78 | "Quit" => { 79 | break; 80 | } 81 | _ => { 82 | let parsed = Wyvern::from_iter_safe(&vec![ 83 | "wyvern", 84 | "connect", 85 | actions[pick].to_lowercase().as_str(), 86 | ]) 87 | .unwrap(); 88 | gog = crate::connect::parse_args(gog, parsed); 89 | } 90 | } 91 | } 92 | } 93 | _ => { 94 | let parsed = 95 | Wyvern::from_iter_safe(&["wyvern", options[pick].to_lowercase().as_str()]) 96 | .unwrap(); 97 | gog = parse_args(parsed, gog, sync_saves.clone()).unwrap(); 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/args.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | #[derive(StructOpt, Debug)] 3 | #[structopt(name = "wyvern")] 4 | pub struct Wyvern { 5 | #[structopt(flatten)] 6 | pub verbose: clap_verbosity_flag::Verbosity, 7 | #[structopt(subcommand)] 8 | pub command: Command, 9 | } 10 | #[derive(StructOpt, Debug)] 11 | pub enum Command { 12 | #[structopt(name = "ls", alias = "list", about = "List all games you own")] 13 | List { 14 | #[structopt(short = "i", long = "id", help = "search with id")] 15 | id: Option, 16 | #[structopt(short = "j", long = "json", help = "Display games in JSON format")] 17 | json: bool, 18 | }, 19 | #[structopt(name = "down", alias = "download", about = "Download specific game")] 20 | Download { 21 | #[structopt(flatten)] 22 | options: DownloadOptions, 23 | #[structopt(flatten)] 24 | shortcuts: ShortcutOptions, 25 | }, 26 | #[structopt(name = "extras", about = "Download a game's extras")] 27 | Extras { 28 | #[structopt(short = "a", long = "all", help = "Download all available extras")] 29 | all: bool, 30 | #[structopt(short = "f", long = "first", help = "Download the first search result")] 31 | first: bool, 32 | #[structopt(short = "i", long = "id", help = "Download a game's extras by id")] 33 | id: Option, 34 | #[structopt(parse(from_os_str))] 35 | #[structopt(short = "o", long = "output-folder", help = "Name of folder to output extras to")] 36 | output: Option, 37 | game: Option, 38 | #[structopt(short = "s", long = "slug", help = "Download a single extra by slug name")] 39 | slug: Option 40 | }, 41 | #[derive(Default)] 42 | #[cfg(feature = "eidolonint")] 43 | #[structopt( 44 | name = "update-eidolon", 45 | about = "Update all eidolon-registered GOG games" 46 | )] 47 | UpdateEidolon { 48 | force: bool, 49 | #[structopt(flatten)] 50 | verbose: clap_verbosity_flag::Verbosity, 51 | #[structopt(short = "d", long = "delta", help = "Update only changed files")] 52 | delta: bool, 53 | }, 54 | #[structopt(name = "connect", about = "Operations associated with GOG Connect")] 55 | Connect(Connect), 56 | #[structopt(name = "install", about = "Install a GOG game from an installer")] 57 | Install { 58 | installer_name: String, 59 | #[structopt(parse(from_os_str))] 60 | path: PathBuf, 61 | #[structopt(flatten)] 62 | shortcuts: ShortcutOptions, 63 | #[structopt(short = "w", long = "windows", help = "Install a windows game")] 64 | windows: bool, 65 | #[structopt( 66 | short = "e", 67 | long = "external-zip", 68 | help = "Use the zip CLI tool to unzip the installer. Faster." 69 | )] 70 | external_zip: bool, 71 | }, 72 | #[structopt( 73 | name = "update", 74 | about = "Update a game if there is an update available" 75 | )] 76 | Update { 77 | #[structopt(parse(from_os_str))] 78 | path: Option, 79 | #[structopt(short = "d", long = "dlc", help = "Update with all DLCs")] 80 | dlc: bool, 81 | }, 82 | #[structopt( 83 | name = "sync", 84 | about = "Sync a game's saves to a specific location for backup" 85 | )] 86 | Sync(Sync), 87 | #[structopt(name = "int", alias = "interactive", about = "Enter interactive mode")] 88 | Interactive, 89 | #[structopt(name = "login", about = "Force a login to GOG")] 90 | Login { 91 | #[structopt(short = "u", long = "username", help = "Username to log in with")] 92 | username: Option, 93 | #[structopt(short = "p", long = "password", help = "Password to log in with")] 94 | password: Option, 95 | #[structopt(short = "c", long = "code", help = "Use a login code to log in")] 96 | code: Option 97 | } 98 | } 99 | #[derive(StructOpt, Debug)] 100 | pub enum Sync { 101 | #[structopt(name = "saves", about = "Configure where a game's saves are located")] 102 | Saves { 103 | #[structopt(parse(from_os_str))] 104 | game_dir: PathBuf, 105 | #[structopt(parse(from_os_str))] 106 | saves: PathBuf, 107 | #[structopt(short = "d", long = "db", help = "Db to save config to")] 108 | #[structopt(parse(from_os_str))] 109 | db: Option, 110 | }, 111 | #[structopt(name = "push", about = "Push save files to sync location")] 112 | Push { 113 | #[structopt(parse(from_os_str))] 114 | game_dir: PathBuf, 115 | #[structopt(parse(from_os_str))] 116 | sync_to: Option, 117 | }, 118 | #[structopt(name = "pull", about = "Pull synced save files")] 119 | Pull { 120 | #[structopt(parse(from_os_str))] 121 | game_dir: PathBuf, 122 | #[structopt(parse(from_os_str))] 123 | sync_from: Option, 124 | #[structopt(short = "f", long = "force", help = "Force syncing even if unneeded")] 125 | force: bool, 126 | #[structopt( 127 | short = "i", 128 | long = "ignore", 129 | help = "Automatically refuse syncing save files that are older than the current" 130 | )] 131 | ignore_older: bool, 132 | }, 133 | #[structopt(name = "db-pull", about = "Pull all save files from a database")] 134 | DbPull { 135 | #[structopt(parse(from_os_str))] 136 | path: Option, 137 | #[structopt(short = "f", long = "force", help = "Force syncing even if unneeded")] 138 | force: bool, 139 | #[structopt( 140 | short = "i", 141 | long = "ignore", 142 | help = "Automatically refuse syncing save files that are older than the current" 143 | )] 144 | ignore_older: bool, 145 | }, 146 | #[structopt(name = "db-push", about = "Push all save files in a database")] 147 | DbPush { 148 | #[structopt(parse(from_os_str))] 149 | path: Option, 150 | #[structopt(short = "f", long = "force", help = "Force syncing even if unneeded")] 151 | force: bool, 152 | #[structopt( 153 | short = "i", 154 | long = "ignore", 155 | help = "Automatically refuse pushing save files that are older than the current" 156 | )] 157 | ignore_older: bool, 158 | }, 159 | } 160 | #[derive(StructOpt, Debug)] 161 | pub enum Connect { 162 | #[structopt( 163 | name = "ls", 164 | alias = "list", 165 | about = "List available GOG Connect games" 166 | )] 167 | ListConnect { 168 | #[structopt( 169 | short = "c", 170 | long = "claimable", 171 | help = "only show games that are currently claimable" 172 | )] 173 | claim: bool, 174 | #[structopt(short = "q", long = "quiet", help = "Only print game names")] 175 | quiet: bool, 176 | #[structopt(short = "j", long = "json", help = "Print results in JSON format")] 177 | json: bool, 178 | }, 179 | #[structopt(name = "claim", about = "Claim all available GOG Connect games")] 180 | ClaimAll, 181 | } 182 | #[derive(StructOpt, Debug)] 183 | pub struct ShortcutOptions { 184 | #[structopt( 185 | short = "d", 186 | long = "desktop", 187 | help = "Add a desktop shortcut for the installed game" 188 | )] 189 | pub desktop: bool, 190 | #[structopt( 191 | short = "m", 192 | long = "menu", 193 | help = "Add an application menu shortcut for the installed game" 194 | )] 195 | pub menu: bool, 196 | #[structopt( 197 | short = "c", 198 | long = "shortcuts", 199 | help = "Add both kinds of shortcuts for the installed game" 200 | )] 201 | pub shortcuts: bool, 202 | } 203 | #[derive(StructOpt, Debug, Default)] 204 | pub struct DownloadOptions { 205 | #[structopt(short = "i", long = "id", help = "download id")] 206 | pub id: Option, 207 | #[structopt(help = "search manually")] 208 | pub search: Option, 209 | #[structopt(parse(from_os_str))] 210 | #[structopt( 211 | short = "n", 212 | long = "install", 213 | help = "install downloaded game to path" 214 | )] 215 | pub install_after: Option, 216 | #[structopt( 217 | short = "w", 218 | long = "windows-auto", 219 | help = "Download windows version if no linux is available" 220 | )] 221 | pub windows_auto: bool, 222 | #[structopt(long = "force-windows", help = "Force downloading windows version")] 223 | pub windows_force: bool, 224 | #[structopt( 225 | short = "f", 226 | long = "first", 227 | help = "When searching, use first result without waiting for selection" 228 | )] 229 | pub first: bool, 230 | #[structopt(short = "a", long = "all", help = "Download all games in your library")] 231 | pub all: bool, 232 | #[structopt(short = "D", long = "dlc", help = "Download DLCs as well")] 233 | pub dlc: bool, 234 | #[structopt(short = "r", long = "resume", help = "Resume downloading games")] 235 | pub resume: bool, 236 | #[structopt( 237 | short = "O", 238 | long = "no-original-name", 239 | help = "Don't preserve the original game name" 240 | )] 241 | pub original: bool, 242 | #[structopt(parse(from_os_str))] 243 | #[structopt( 244 | short = "o", 245 | long = "output", 246 | help = "Write downloaded file to target location. Note: if the file already exists/multiple files are downloaded, appends a count to the end" 247 | )] 248 | pub output: Option, 249 | #[structopt( 250 | long = "preserve-extension", 251 | help = "When used with -o, preserves the original file extension" 252 | )] 253 | pub preserve_extension: bool, 254 | #[structopt( 255 | short = "e", 256 | long = "external-zip", 257 | help = "Use the zip CLI tool to unzip the installer. Faster." 258 | )] 259 | pub external_zip: bool, 260 | } 261 | -------------------------------------------------------------------------------- /src/sync.rs: -------------------------------------------------------------------------------- 1 | use args::Command::*; 2 | use args::Sync::*; 3 | use config::*; 4 | use gog::gog::FilterParam::*; 5 | use gog::gog::*; 6 | use gog::*; 7 | use std::env::current_dir; 8 | use std::fs::{self, File}; 9 | use std::io::{self, *}; 10 | use std::path::*; 11 | use std::process::*; 12 | /// Parses args, assuming a sync subcommand 13 | pub fn parse_args(gog: Gog, sync_saves: Option, args: ::args::Wyvern) -> Gog { 14 | match args.command { 15 | Sync(Push { game_dir, sync_to }) => { 16 | if sync_saves.is_some() { 17 | let mut sync_saves = sync_saves.unwrap(); 18 | if sync_to.is_some() { 19 | info!("Using manual argument sync path"); 20 | sync_saves = sync_to.unwrap().to_str().unwrap().to_string(); 21 | } 22 | info!("Opening gameinfo file"); 23 | let gameinfo = File::open(game_dir.join("gameinfo")); 24 | if gameinfo.is_ok() { 25 | let mut ginfo_string = String::new(); 26 | info!("Reading from gameinfo file"); 27 | gameinfo.unwrap().read_to_string(&mut ginfo_string).unwrap(); 28 | info!("Parsing gameinfo"); 29 | let gameinfo = 30 | GameInfo::parse(ginfo_string).expect("Couldn't parse gameinfo file"); 31 | info!("Fetching details about game from GOG"); 32 | if let Ok(details) = 33 | gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone()))) 34 | { 35 | let id = details[0].id; 36 | let savedb_path = PathBuf::from(sync_saves.clone()).join("savedb.json"); 37 | let mut save_db = SaveDB::load(&savedb_path).unwrap(); 38 | let mut path: PathBuf; 39 | if save_db.saves.contains_key(&format!("{}", id)) { 40 | info!("Savedb has path to saves confgured already"); 41 | path = PathBuf::from( 42 | save_db.saves.get(&format!("{}", id)).unwrap().path.clone(), 43 | ); 44 | } else { 45 | let mut input = String::new(); 46 | let mut yn = String::new(); 47 | println!("You haven't specified where this game's save files are yet. Please insert a path to where they are located."); 48 | loop { 49 | io::stdout().flush().unwrap(); 50 | io::stdin().read_line(&mut input).unwrap(); 51 | print!("Are you sure this where the save files are located?(Y/n)"); 52 | io::stdout().flush().unwrap(); 53 | io::stdin().read_line(&mut yn).unwrap(); 54 | if &yn == "n" || &yn == "N" { 55 | continue; 56 | } 57 | break; 58 | } 59 | let save_path = 60 | current_dir().unwrap().join(PathBuf::from(&input.trim())); 61 | info!("Inserting saveinfo into savedb"); 62 | save_db.saves.insert( 63 | format!("{}", id), 64 | SaveInfo { 65 | path: save_path.to_str().unwrap().to_string(), 66 | identifier: SaveType::GOG(id), 67 | }, 68 | ); 69 | path = save_path; 70 | info!("Storing savedb"); 71 | save_db.store(&savedb_path).unwrap(); 72 | } 73 | let mut path_string = path.to_str().unwrap().to_string(); 74 | if path.exists() && path.is_dir() { 75 | path_string += "/"; 76 | } 77 | let save_dir = PathBuf::from(sync_saves); 78 | let save_folder = 79 | save_dir.clone().join("saves").join(format!("gog_{}", id)); 80 | if fs::metadata(&save_folder).is_err() { 81 | info!("Creating directories for files"); 82 | fs::create_dir_all(&save_folder).unwrap(); 83 | } 84 | info!("Start Rsyncing files"); 85 | Command::new("rsync") 86 | .arg( 87 | path_string 88 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()), 89 | ) 90 | .arg(save_folder.to_str().unwrap()) 91 | .arg("-a") 92 | .output() 93 | .unwrap(); 94 | println!("Synced save files to save folder!"); 95 | } else { 96 | error!("Could not find a game named {}.", gameinfo.name); 97 | } 98 | } else { 99 | error!("Game directory or gameinfo file missing") 100 | } 101 | } else { 102 | error!("You have not configured a directory to sync your saves to. Edit ~/.config/wyvern/wyvern.toml to get started!"); 103 | } 104 | } 105 | Sync(Pull { 106 | game_dir, 107 | sync_from, 108 | force, 109 | ignore_older, 110 | }) => { 111 | if sync_saves.is_some() { 112 | let sync_saves = sync_saves 113 | .unwrap() 114 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()); 115 | info!("Opening gameinfo file"); 116 | let gameinfo = File::open(game_dir.join("gameinfo")); 117 | if gameinfo.is_ok() { 118 | let mut ginfo_string = String::new(); 119 | info!("Reading in gameinfo file"); 120 | gameinfo 121 | .unwrap() 122 | .read_to_string(&mut ginfo_string) 123 | .expect("Couldn't read from gameinfo file."); 124 | info!("Parsing gameinfo file"); 125 | let gameinfo = 126 | GameInfo::parse(ginfo_string).expect("Couldn't parse gameinfo file"); 127 | if let Ok(details) = 128 | gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone()))) 129 | { 130 | let id = details[0].id; 131 | let mut savedb_path = PathBuf::from(sync_saves.clone()).join("savedb.json"); 132 | if sync_from.is_some() { 133 | savedb_path = sync_from.unwrap().join("savedb.json"); 134 | } 135 | info!("Loading savedb"); 136 | let mut save_db = SaveDB::load(&savedb_path).unwrap(); 137 | if save_db.saves.contains_key(&format!("{}", id)) { 138 | let save_path = PathBuf::from(sync_saves.clone()) 139 | .join("saves") 140 | .join(format!("gog_{}", id)); 141 | let save_files = save_db.saves.get(&format!("{}", id)).unwrap(); 142 | let saved_path = PathBuf::from( 143 | save_files 144 | .path 145 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()), 146 | ); 147 | info!("Syncing files now"); 148 | sync(save_path, saved_path, force, ignore_older); 149 | } else { 150 | error!("This game's saves have not been configured to be synced yet. Push first!"); 151 | } 152 | } else { 153 | error!("Could not find a game named {}", gameinfo.name) 154 | } 155 | } else { 156 | error!("Game directory or gameinfo file missing"); 157 | } 158 | } else { 159 | error!("You have not config a directory to sync your saves from. Edit ~/.config/wyvern/wyvern.toml to get started!"); 160 | } 161 | } 162 | Sync(DbPull { 163 | path, 164 | force, 165 | ignore_older, 166 | }) => { 167 | let dbpath: PathBuf; 168 | if path.is_some() { 169 | info!("Using db passed in arguments"); 170 | dbpath = path.unwrap(); 171 | } else if sync_saves.is_some() { 172 | info!("Using configured db path"); 173 | dbpath = PathBuf::from(sync_saves.unwrap()); 174 | } else { 175 | error!("You have not specified a sync directory in the config yet. Specify one or call db with a path to your db."); 176 | std::process::exit(0); 177 | } 178 | info!("Loading savedb"); 179 | let savedb = SaveDB::load(&dbpath.join("savedb.json")).unwrap(); 180 | for (key, value) in savedb.saves.iter() { 181 | println!("Syncing {} now", key); 182 | let save_path = PathBuf::from( 183 | value 184 | .path 185 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()), 186 | ); 187 | let mut folder_name = key.clone(); 188 | if let SaveType::GOG(id) = value.identifier { 189 | folder_name = format!("gog_{}", id); 190 | } 191 | let synced_path = dbpath.join("saves").join(folder_name); 192 | info!("Syncing files now."); 193 | sync(synced_path, save_path, force, ignore_older); 194 | println!("Synced {}", key); 195 | } 196 | } 197 | Sync(DbPush { 198 | path, 199 | force, 200 | ignore_older, 201 | }) => { 202 | let dpath: PathBuf; 203 | if path.is_some() { 204 | info!("Using db passed in arguments"); 205 | dpath = path.unwrap(); 206 | } else if sync_saves.is_some() { 207 | info!("Using configured db path"); 208 | dpath = PathBuf::from(sync_saves.unwrap()); 209 | } else { 210 | error!("You have not specified a sync directory in the config yet. Specify one or call db with a path to your db."); 211 | std::process::exit(0); 212 | } 213 | info!("Loading savedb"); 214 | let savedb = SaveDB::load(dpath.clone().join("savedb.json")).unwrap(); 215 | for (key, value) in savedb.saves { 216 | println!("Syncing {} now", key); 217 | let save_path = PathBuf::from( 218 | value 219 | .path 220 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()), 221 | ); 222 | let mut folder_name = key.clone(); 223 | if let SaveType::GOG(id) = value.identifier { 224 | folder_name = format!("gog_{}", id); 225 | } 226 | let mut dest_path = dpath.join("saves").join(&folder_name); 227 | info!("Syncing file snow"); 228 | sync(save_path, dest_path, force, ignore_older); 229 | println!("Synced {}", key); 230 | } 231 | } 232 | Sync(Saves { 233 | game_dir, 234 | saves, 235 | db, 236 | }) => { 237 | let dpath: PathBuf; 238 | if db.is_some() { 239 | info!("Using db passed in arguments"); 240 | dpath = db.unwrap(); 241 | } else if sync_saves.is_some() { 242 | info!("Using configured db path"); 243 | dpath = PathBuf::from(sync_saves.unwrap()); 244 | } else { 245 | error!("You have not specified a sync directory in the config yet. Specify one or call saves with a path to your db."); 246 | std::process::exit(0); 247 | } 248 | let dbpath = current_dir() 249 | .unwrap() 250 | .join(dpath.clone()) 251 | .join("savedb.json"); 252 | info!("Loading savedb"); 253 | let mut savedb = SaveDB::load(dbpath.clone()).unwrap(); 254 | let gameinfo_path = current_dir().unwrap().join(game_dir).join("gameinfo"); 255 | if gameinfo_path.is_file() { 256 | let mut ginfo_string = String::new(); 257 | info!("Opening and reading gameinfo file"); 258 | File::open(&gameinfo_path) 259 | .unwrap() 260 | .read_to_string(&mut ginfo_string) 261 | .unwrap(); 262 | let gameinfo = GameInfo::parse(ginfo_string).expect("Couldn't parse gameinfo"); 263 | if let Ok(details) = 264 | gog.get_products(FilterParams::from_one(Search(gameinfo.name.clone()))) 265 | { 266 | let id = details[0].id; 267 | info!("Inserting record into savedb"); 268 | savedb.saves.insert( 269 | format!("{}", id), 270 | SaveInfo { 271 | path: current_dir() 272 | .unwrap() 273 | .join(saves) 274 | .to_str() 275 | .unwrap() 276 | .to_string(), 277 | identifier: SaveType::GOG(id), 278 | }, 279 | ); 280 | info!("Storing savedb"); 281 | savedb.store(dbpath).unwrap(); 282 | } else { 283 | error!("Could not find a game named {}", gameinfo.name); 284 | } 285 | } else { 286 | error!("No gameinfo file at {}", gameinfo_path.to_str().unwrap()); 287 | } 288 | } 289 | _ => println!("Wow, you should not be seeing this message."), 290 | }; 291 | gog 292 | } 293 | /// Syncs save files from one location to another 294 | fn sync(sync_from: PathBuf, sync_to: PathBuf, ignore_older: bool, force: bool) { 295 | let from_meta = fs::metadata(&sync_from); 296 | let to_meta = fs::metadata(&sync_to); 297 | if from_meta.is_err() { 298 | error!("Can't sync nonexistent files! There should be save files at {}, but there are not. Aborting.", sync_from.to_str().unwrap()); 299 | return; 300 | } 301 | if let Ok(to_meta) = to_meta { 302 | info!("File already synced to locations. Getting modified times"); 303 | let to_modified = to_meta.modified().unwrap(); 304 | let from_modified = from_meta.unwrap().modified().unwrap(); 305 | if to_modified > from_modified && !force { 306 | if ignore_older { 307 | println!("Aborting due to --ignore-older flag and newer save files being present"); 308 | return; 309 | } 310 | print!("Synced save files are more recent. Are you sure you want to proceed?(y/N)"); 311 | let mut answer = String::new(); 312 | io::stdout().flush().unwrap(); 313 | io::stdin().read_line(&mut answer).unwrap(); 314 | if answer.trim() == "y" || answer.trim() == "Y" { 315 | println!("Proceeding as normal."); 316 | } else { 317 | println!("Sync aborted."); 318 | return; 319 | } 320 | } 321 | } else { 322 | info!("No files synced to location currently"); 323 | } 324 | info!("Rsyncing files to location"); 325 | Command::new("rsync") 326 | .arg(sync_from.to_str().unwrap().to_string() + "/") 327 | .arg( 328 | sync_to 329 | .parent() 330 | .unwrap() 331 | .to_path_buf() 332 | .to_str() 333 | .unwrap() 334 | .to_string() 335 | + "/", 336 | ) 337 | .arg("-a") 338 | .arg("--force") 339 | .output() 340 | .unwrap(); 341 | } 342 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "eidolonint")] 2 | extern crate libeidolon; 3 | #[macro_use] 4 | extern crate structopt; 5 | #[macro_use] 6 | extern crate human_panic; 7 | #[macro_use] 8 | extern crate serde_derive; 9 | #[macro_use] 10 | extern crate log; 11 | extern crate clap_verbosity_flag; 12 | extern crate confy; 13 | extern crate crc; 14 | extern crate curl; 15 | extern crate dialoguer; 16 | extern crate dirs; 17 | extern crate gog; 18 | extern crate indicatif; 19 | extern crate inflate; 20 | extern crate rayon; 21 | extern crate serde; 22 | extern crate serde_json; 23 | extern crate url; 24 | extern crate walkdir; 25 | extern crate zip; 26 | mod args; 27 | mod config; 28 | mod connect; 29 | mod games; 30 | mod interactive; 31 | mod sync; 32 | use args::Command::Download; 33 | use args::Command::*; 34 | use args::Wyvern; 35 | use args::{DownloadOptions, ShortcutOptions}; 36 | use config::*; 37 | use crc::crc32; 38 | use dialoguer::*; 39 | use games::*; 40 | use gog::extract::*; 41 | use gog::gog::{FilterParam::*, *}; 42 | use gog::token::Token; 43 | use gog::Error; 44 | use gog::ErrorKind::*; 45 | use gog::Gog; 46 | use indicatif::{ProgressBar, ProgressStyle}; 47 | use std::env::current_dir; 48 | use std::fs; 49 | use std::fs::*; 50 | use std::io; 51 | use std::io::SeekFrom::*; 52 | use std::io::Write; 53 | use std::os::unix::fs::PermissionsExt; 54 | use std::path::{Path, PathBuf}; 55 | use std::process::Command; 56 | use structopt::StructOpt; 57 | use walkdir::WalkDir; 58 | use {download::*, install::*, update::*}; 59 | fn main() -> Result<(), ::std::io::Error> { 60 | #[cfg(not(debug_assertions))] 61 | setup_panic!(); 62 | let mut config: Config = confy::load("wyvern")?; 63 | let args = Wyvern::from_args(); 64 | args.verbose 65 | .setup_env_logger("wyvern") 66 | .expect("Couldn't set up logger"); 67 | match args.command { 68 | Login { 69 | code, 70 | username, 71 | password, 72 | } => { 73 | let mut config: Config = confy::load("wyvern")?; 74 | if let Some(code) = code { 75 | if let Ok(token) = Token::from_login_code(code) { 76 | config.token = Some(token); 77 | } else { 78 | error!("Could not login with code"); 79 | } 80 | } else if let Some(username) = username { 81 | let password = password.unwrap_or_else(|| { 82 | let pword: String = PasswordInput::new() 83 | .with_prompt("Password") 84 | .interact() 85 | .unwrap(); 86 | return pword; 87 | }); 88 | let token = Token::login( 89 | username, 90 | password, 91 | Some(|| { 92 | println!("A two factor authentication code is required. Please check your email for one and enter it here."); 93 | let mut token: String; 94 | loop { 95 | token = Input::new().with_prompt("2FA Code:").interact().unwrap(); 96 | token = token.trim().to_string(); 97 | if token.len() == 4 && token.parse::().is_ok() { 98 | break; 99 | } 100 | } 101 | token 102 | }), 103 | ); 104 | if token.is_err() { 105 | error!("Could not login to GOG."); 106 | let err = token.err().unwrap(); 107 | match err.kind() { 108 | IncorrectCredentials => error!("Wrong email or password. Sometimes this fails because GOG's login form can be inconsistent, so you may just need to try again."), 109 | NotAvailable => error!("You've triggered the captcha. 5 tries every 24 hours is allowed before the captcha is triggered. You should probably use the alternate login method or wait 24 hours"), 110 | _ => error!("Error: {:?}", err), 111 | }; 112 | } else { 113 | config.token = Some(token.unwrap()); 114 | } 115 | } else { 116 | config.token = Some(login()); 117 | } 118 | confy::store("wyvern", config)?; 119 | ::std::process::exit(0); 120 | } 121 | _ => {} 122 | } 123 | if config.token.is_none() { 124 | let token = login(); 125 | config.token = Some(token); 126 | } 127 | let token_try = config.token.unwrap().refresh(); 128 | if token_try.is_err() { 129 | error!("Could not refresh token. You may need to log in again."); 130 | let token = login(); 131 | config.token = Some(token); 132 | } else { 133 | config.token = Some(token_try.unwrap()); 134 | } 135 | let gog = Gog::new(config.token.clone().unwrap()); 136 | let mut sync_saves = config.sync_saves.clone(); 137 | if sync_saves.is_some() { 138 | sync_saves = Some( 139 | sync_saves 140 | .unwrap() 141 | .replace("~", dirs::home_dir().unwrap().to_str().unwrap()), 142 | ); 143 | } 144 | confy::store("wyvern", config)?; 145 | parse_args(args, gog, sync_saves)?; 146 | Ok(()) 147 | } 148 | fn parse_args( 149 | args: Wyvern, 150 | mut gog: Gog, 151 | sync_saves: Option, 152 | ) -> Result { 153 | match args.command { 154 | List { id, json } => { 155 | let mut games = GamesList { games: vec![] }; 156 | if let Some(id) = id { 157 | let details = gog.get_game_details(id).unwrap(); 158 | games.games.push(Game::GameInfo(details, id)); 159 | } else { 160 | games.games = gog 161 | .get_all_filtered_products(FilterParams::from_one(MediaType(1))) 162 | .expect("Couldn't fetch games") 163 | .into_iter() 164 | .map(|x| Game::ProductInfo(x)) 165 | .collect(); 166 | } 167 | if json { 168 | println!( 169 | "{}", 170 | serde_json::to_string(&games).expect("Couldn't deserialize games list") 171 | ); 172 | } else { 173 | println!("Title - GameID"); 174 | games 175 | .games 176 | .sort_by(|a, b| a.title().partial_cmp(&b.title()).unwrap()); 177 | for game in games.games { 178 | print!("{} - ", game.title()); 179 | match game { 180 | Game::GameInfo(_details, id) => println!("{}", id), 181 | Game::ProductInfo(pinfo) => println!("{}", pinfo.id), 182 | } 183 | } 184 | } 185 | } 186 | Download { 187 | mut options, 188 | mut shortcuts, 189 | } => { 190 | if shortcuts.shortcuts { 191 | shortcuts.desktop = true; 192 | shortcuts.menu = true; 193 | } 194 | options.original = !options.original; 195 | if let Some(search) = options.search.clone() { 196 | info!("Searching for games"); 197 | let search_results = 198 | gog.get_filtered_products(FilterParams::from_one(Search(search))); 199 | if search_results.is_ok() { 200 | info!("Game search results OK"); 201 | let e = search_results.unwrap().products; 202 | if !options.first { 203 | if e.len() > 0 { 204 | let mut select = Select::new(); 205 | let mut selects = 206 | select.with_prompt("Select a game to download:").default(0); 207 | for pd in e.iter() { 208 | selects.item(format!("{} - {}", pd.title, pd.id).as_str()); 209 | } 210 | let i = selects.interact().expect("Couldn't pick game"); 211 | info!("Fetching game details"); 212 | let details = gog.get_game_details(e[i].id).unwrap(); 213 | let pname = details.title.clone(); 214 | info!("Beginning download process"); 215 | let (name, downloaded_windows) = 216 | download_prep(&gog, details, &options).unwrap(); 217 | if options.install_after.is_some() { 218 | println!("Installing game"); 219 | info!("Installing game"); 220 | install_all( 221 | name, 222 | options.install_after.unwrap(), 223 | pname, 224 | &shortcuts, 225 | downloaded_windows, 226 | options.external_zip, 227 | ); 228 | } 229 | } else { 230 | error!("Found no games when searching."); 231 | std::process::exit(64); 232 | } 233 | } else { 234 | info!("Downloading first game from results"); 235 | let details = gog.get_game_details(e[0].id).unwrap(); 236 | let pname = details.title.clone(); 237 | info!("Beginning download process"); 238 | let (name, downloaded_windows) = 239 | download_prep(&gog, details, &options).unwrap(); 240 | if options.install_after.is_some() { 241 | println!("Installing game"); 242 | info!("Installing game"); 243 | install_all( 244 | name, 245 | options.install_after.unwrap(), 246 | pname, 247 | &shortcuts, 248 | downloaded_windows, 249 | options.external_zip, 250 | ); 251 | } 252 | } 253 | } else { 254 | error!("Could not find any games."); 255 | } 256 | } else if let Some(id) = options.id { 257 | let details = gog.get_game_details(id).unwrap(); 258 | let pname = details.title.clone(); 259 | info!("Beginning download process"); 260 | let (name, downloaded_windows) = download_prep(&gog, details, &options).unwrap(); 261 | if options.install_after.is_some() { 262 | println!("Installing game"); 263 | info!("Installing game"); 264 | install_all( 265 | name, 266 | options.install_after.unwrap(), 267 | pname, 268 | &shortcuts, 269 | downloaded_windows, 270 | options.external_zip, 271 | ); 272 | } 273 | } else if options.all { 274 | println!("Downloading all games in library"); 275 | let games = gog.get_games().unwrap(); 276 | for game in games { 277 | let details = gog.get_game_details(game).unwrap(); 278 | info!("Beginning download process"); 279 | download_prep(&gog, details, &options).unwrap(); 280 | } 281 | if options.install_after.is_some() { 282 | println!("--install does not work with --all"); 283 | } 284 | } else { 285 | error!("Did not specify a game to download. Exiting."); 286 | } 287 | } 288 | Login {..} => {} 289 | Extras { 290 | game, 291 | all, 292 | first, 293 | slug, 294 | id, 295 | output, 296 | } => { 297 | let mut details: GameDetails; 298 | if let Some(search) = game { 299 | if let Ok(results) = 300 | gog.get_filtered_products(FilterParams::from_one(Search(search.clone()))) 301 | { 302 | let e = results.products; 303 | if e.len() < 1 { 304 | error!("Found no games named {} in your library.", search) 305 | } 306 | let mut i = 0; 307 | if !first { 308 | let mut selects = Select::new(); 309 | let mut select = 310 | selects.with_prompt("Select a game to download extras from:"); 311 | for pd in e.iter() { 312 | select.item(format!("{} - {}", pd.title, pd.id).as_str()); 313 | } 314 | i = select.interact().unwrap(); 315 | } 316 | info!("Fetching game details"); 317 | details = gog.get_game_details(e[i].id).unwrap(); 318 | } else { 319 | error!("Could not search for games."); 320 | 321 | return Ok(gog); 322 | } 323 | } else if let Some(id) = id { 324 | if let Ok(fetched) = gog.get_game_details(id) { 325 | details = fetched; 326 | } else { 327 | error!("Could not fetch game details. Are you sure that the id is right?"); 328 | 329 | return Ok(gog); 330 | } 331 | } else { 332 | error!("Did not specify a game."); 333 | 334 | return Ok(gog); 335 | } 336 | println!("Downloading extras for game {}", details.title); 337 | let mut folder_name = PathBuf::from(format!("{} Extras", details.title)); 338 | if let Some(output) = output { 339 | folder_name = output; 340 | } 341 | if fs::metadata(&folder_name).is_err() { 342 | fs::create_dir(&folder_name).expect("Couldn't create extras folder"); 343 | } 344 | let mut picked: Vec = vec![]; 345 | if !all && slug.is_none() { 346 | let mut check = Checkboxes::new(); 347 | let mut checks = check.with_prompt("Pick the extras you want to download"); 348 | for ex in details.extras.iter() { 349 | checks.item(&ex.name); 350 | } 351 | picked = checks.interact().unwrap(); 352 | } 353 | if let Some(slug) = slug { 354 | details.extras.iter().enumerate().for_each(|(i, x)| { 355 | if x.name.trim() == slug.trim() { 356 | picked.push(i); 357 | } 358 | }); 359 | if picked.len() == 0 { 360 | error!("Couldn't find an extra named {}", slug); 361 | return Ok(gog); 362 | } 363 | } 364 | 365 | let extra_responses: Vec> = details 366 | .extras 367 | .iter() 368 | .enumerate() 369 | .filter(|(i, _x)| { 370 | if !all { 371 | return picked.contains(i); 372 | } else { 373 | return true; 374 | } 375 | }) 376 | .map(|(_i, x)| { 377 | info!("Finding URL"); 378 | let mut url = "https://gog.com".to_string() + &x.manual_url; 379 | let mut response; 380 | loop { 381 | let temp_response = gog.client_noredirect.borrow().get(&url).send(); 382 | if temp_response.is_ok() { 383 | response = temp_response.unwrap(); 384 | let headers = response.headers(); 385 | // GOG appears to be inconsistent with returning either 301/302, so this just checks for a redirect location. 386 | if headers.contains_key("location") { 387 | url = headers 388 | .get("location") 389 | .unwrap() 390 | .to_str() 391 | .unwrap() 392 | .to_string(); 393 | } else { 394 | break; 395 | } 396 | } else { 397 | return Err(temp_response.err().unwrap().into()); 398 | } 399 | } 400 | Ok(response) 401 | }) 402 | .collect(); 403 | for extra in extra_responses.into_iter() { 404 | let mut extra = extra.expect("Couldn't fetch extra"); 405 | let mut real_response = gog 406 | .client_noredirect 407 | .borrow() 408 | .get(extra.url().clone()) 409 | .send() 410 | .expect("Couldn't fetch extra data"); 411 | let name = extra 412 | .url() 413 | .path_segments() 414 | .unwrap() 415 | .last() 416 | .unwrap() 417 | .to_string(); 418 | let n_path = folder_name.join(&name); 419 | if fs::metadata(&n_path).is_ok() { 420 | warn!("This extra has already been downloaded. Skipping."); 421 | continue; 422 | } 423 | println!("Starting download of {}", name); 424 | let pb = ProgressBar::new(extra.content_length().unwrap()); 425 | pb.set_style(ProgressStyle::default_bar() 426 | .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})") 427 | .progress_chars("#>-")); 428 | let mut pb_read = pb.wrap_read(real_response); 429 | let mut file = File::create(n_path).expect("Couldn't create file"); 430 | io::copy(&mut pb_read, &mut file).expect("Couldn't copy to target file"); 431 | pb.finish(); 432 | } 433 | } 434 | Interactive => { 435 | gog = interactive::interactive(gog, sync_saves); 436 | } 437 | Install { 438 | installer_name, 439 | path, 440 | mut shortcuts, 441 | windows, 442 | external_zip, 443 | } => { 444 | if shortcuts.shortcuts { 445 | shortcuts.desktop = true; 446 | shortcuts.menu = true; 447 | } 448 | info!("Starting installation"); 449 | install( 450 | installer_name.clone(), 451 | path, 452 | installer_name, 453 | &shortcuts, 454 | windows, 455 | external_zip, 456 | ); 457 | } 458 | #[cfg(feature = "eidolonint")] 459 | UpdateEidolon { force, delta } => { 460 | use libeidolon::games::*; 461 | let eidolon_games = get_games(); 462 | for game in eidolon_games { 463 | if let Ok(read) = read_game(game.as_str()) { 464 | if read.typeg == GameType::WyvernGOG { 465 | println!("Attempting to update {}", read.pname); 466 | let path = PathBuf::from(read.command); 467 | let ginfo_path = path.clone().join("gameinfo"); 468 | update(&gog, path, ginfo_path, force, delta); 469 | } 470 | } else { 471 | println!("Could not check {}", game); 472 | } 473 | } 474 | } 475 | Sync(..) => { 476 | gog = sync::parse_args(gog, sync_saves, args); 477 | } 478 | Connect { .. } => { 479 | gog = connect::parse_args(gog, args); 480 | } 481 | Update { mut path, dlc } => { 482 | if path.is_none() { 483 | info!("Path not specified. Using current dir"); 484 | path = Some(PathBuf::from(".".to_string())); 485 | } 486 | let path = path.unwrap(); 487 | let game_info_path = PathBuf::from(path.join("gameinfo")); 488 | info!("Updating game"); 489 | update(&gog, path, game_info_path, dlc); 490 | } 491 | }; 492 | Ok(gog) 493 | } 494 | pub fn login() -> Token { 495 | let choices = ["OAuth Token Login", "Username/Password Login"]; 496 | println!("It appears that you have not logged into GOG. Please pick a login method."); 497 | let pick = Select::new() 498 | .with_prompt("Login Method") 499 | .items(&choices) 500 | .interact() 501 | .expect("Couldn't pick a login method"); 502 | match pick { 503 | //OAuth Token 504 | 0 => { 505 | println!("Please go to the following URL, log into GOG, and paste the code from the resulting url's ?code parameter into the input here."); 506 | 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"); 507 | io::stdout().flush().unwrap(); 508 | let token: Token; 509 | loop { 510 | let code: String = Input::new().with_prompt("Code:").interact().unwrap(); 511 | info!("Creating token from input"); 512 | let attempt_token = Token::from_login_code(code.as_str()); 513 | if attempt_token.is_ok() { 514 | token = attempt_token.unwrap(); 515 | println!("Got token. Thanks!"); 516 | break; 517 | } else { 518 | println!("Invalid code. Try again!"); 519 | } 520 | } 521 | return token; 522 | } 523 | 1 => { 524 | println!("Please input your credentials."); 525 | let username: String = Input::new() 526 | .with_prompt("Email") 527 | .interact() 528 | .expect("Couldn't fetch username"); 529 | let password: String = PasswordInput::new() 530 | .with_prompt("Password") 531 | .interact() 532 | .expect("Couldn't fetch password"); 533 | let token = Token::login( 534 | username, 535 | password, 536 | Some(|| { 537 | println!("A two factor authentication code is required. Please check your email for one and enter it here."); 538 | let mut token: String; 539 | loop { 540 | token = Input::new().with_prompt("2FA Code:").interact().unwrap(); 541 | token = token.trim().to_string(); 542 | if token.len() == 4 && token.parse::().is_ok() { 543 | break; 544 | } 545 | } 546 | token 547 | }), 548 | ); 549 | if token.is_err() { 550 | error!("Could not login to GOG."); 551 | let err = token.err().unwrap(); 552 | match err.kind() { 553 | IncorrectCredentials => error!("Wrong email or password. Sometimes this fails because GOG's login form can be inconsistent, so you may just need to try again."), 554 | NotAvailable => error!("You've triggered the captcha. 5 tries every 24 hours is allowed before the captcha is triggered. You should probably use the alternate login method or wait 24 hours"), 555 | _ => error!("Error: {:?}", err), 556 | }; 557 | } else { 558 | return token.unwrap(); 559 | } 560 | } 561 | _ => { 562 | panic!("Please tell somebody about this."); 563 | } 564 | }; 565 | std::process::exit(64); 566 | } 567 | fn shortcuts(name: &String, path: &std::path::Path, shortcut_opts: &ShortcutOptions) { 568 | if shortcut_opts.menu || shortcut_opts.desktop { 569 | info!("Creating shortcuts"); 570 | let game_path = current_dir().unwrap().join(&path); 571 | info!("Creating text of shortcut"); 572 | let shortcut = desktop_shortcut(name.as_str(), &game_path); 573 | if shortcut_opts.menu { 574 | info!("Adding menu shortcut"); 575 | let desktop_path = dirs::home_dir().unwrap().join(format!( 576 | ".local/share/applications/gog_com-{}_1.desktop", 577 | name 578 | )); 579 | info!("Created menu file"); 580 | let fd = File::create(&desktop_path); 581 | if fd.is_ok() { 582 | info!("Writing to file"); 583 | fd.unwrap() 584 | .write(shortcut.as_str().as_bytes()) 585 | .expect("Couldn't write to menu shortcut"); 586 | } else { 587 | error!( 588 | "Could not create menu shortcut. Error: {}", 589 | fd.err().unwrap() 590 | ); 591 | } 592 | } 593 | if shortcut_opts.desktop { 594 | info!("Adding desktop shortcut"); 595 | let desktop_path = dirs::home_dir() 596 | .unwrap() 597 | .join(format!("Desktop/gog_com-{}_1.desktop", name)); 598 | let fd = File::create(&desktop_path); 599 | if fd.is_ok() { 600 | info!("Writing to file."); 601 | let mut fd = fd.unwrap(); 602 | fd.write(shortcut.as_str().as_bytes()) 603 | .expect("Couldn't write to desktop shortcut"); 604 | info!("Setting permissions"); 605 | fd.set_permissions(Permissions::from_mode(0o0774)) 606 | .expect("Couldn't make desktop shortcut executable"); 607 | } else { 608 | error!( 609 | "Could not create desktop shortcut. Error: {}", 610 | fd.err().unwrap() 611 | ); 612 | } 613 | } 614 | } 615 | } 616 | fn desktop_shortcut(name: impl Into, path: &std::path::Path) -> String { 617 | let name = name.into(); 618 | let path = current_dir().unwrap().join(path); 619 | format!("[Desktop Entry]\nEncoding=UTF-8\nValue=1.0\nType=Application\nName={}\nGenericName={}\nComment={}\nIcon={}\nExec=\"{}\" \"\"\nCategories=Game;\nPath={}",name,name,name,path.join("support/icon.png").to_str().unwrap(),path.join("start.sh").to_str().unwrap(), path.to_str().unwrap()) 620 | } 621 | -------------------------------------------------------------------------------- /src/games.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | pub mod update { 3 | use crate::*; 4 | use rayon::prelude::*; 5 | use std::io::Cursor; 6 | use std::io::Read; 7 | use std::io::Seek; 8 | pub fn update(gog: &Gog, _path: PathBuf, game_info_path: PathBuf, dlc: bool) { 9 | if let Ok(mut gameinfo) = File::open(&game_info_path) { 10 | let mut ginfo_string = String::new(); 11 | info!("Reading in gameinfo file"); 12 | gameinfo.read_to_string(&mut ginfo_string).unwrap(); 13 | info!("Parsing gameinfo"); 14 | let ginfo = GameInfo::parse(ginfo_string).expect("Couldn't parse GameInfo"); 15 | let name = ginfo.name.clone(); 16 | info!("Searching GOG products for {}", name); 17 | if let Ok(product) = 18 | gog.get_filtered_products(FilterParams::from_one(Search(name.clone()))) 19 | { 20 | info!("Fetching the GameDetails for first result of search"); 21 | if product.products.len() < 1 { 22 | error!("Could not find a game named {} in your library.", name); 23 | std::process::exit(64); 24 | } 25 | let details = gog.get_game_details(product.products[0].id).unwrap(); 26 | info!("Getting game's linux downloads"); 27 | let mut downloads; 28 | if dlc { 29 | info!("Using DLC to update"); 30 | downloads = details.all(true); 31 | } else { 32 | downloads = details 33 | .downloads 34 | .linux 35 | .expect("Game has no linux downloads"); 36 | } 37 | info!("Fetching installer data."); 38 | let data = gog.extract_data(downloads).unwrap(); 39 | println!("Fetched installer data. Checking files."); 40 | io::stdout().flush().expect("Couldn't flush stdout"); 41 | let access_token = gog.token.borrow().access_token.clone(); 42 | data.par_iter().for_each(|data| { 43 | let pb = ProgressBar::new(data.files.len() as u64); 44 | pb.set_style( 45 | ProgressStyle::default_bar() 46 | .template( 47 | "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len}", 48 | ) 49 | .progress_chars("#>-"), 50 | ); 51 | data.files.par_iter().for_each(|file| { 52 | if !file.filename.contains("meta") && !file.filename.contains("scripts") { 53 | let path = game_info_path 54 | .parent() 55 | .unwrap() 56 | .join(&file.filename.replace("/noarch", "").replace("data/", "")); 57 | let is_dir = path.extension().is_none() 58 | || file.filename.clone().pop().unwrap() == '/'; 59 | if path.is_file() { 60 | info!("Checking file {:?}", path); 61 | let mut buffer = vec![]; 62 | info!("Opening file"); 63 | let mut fd = File::open(&path) 64 | .expect(&format!("Couldn't open file {:?}", path)); 65 | fd.read_to_end(&mut buffer).unwrap(); 66 | let checksum = crc32::checksum_ieee(buffer.as_slice()); 67 | if checksum == file.crc32 { 68 | info!("File {:?} is the same", path); 69 | pb.inc(1); 70 | return; 71 | } 72 | pb.println(format!("File {:?} is different. Downloading.", path)); 73 | } else if !path.exists() && is_dir { 74 | pb.inc(1); 75 | return; 76 | } else if is_dir { 77 | fs::create_dir_all(path); 78 | pb.inc(1); 79 | return; 80 | } else { 81 | pb.println(format!("File {:?} does not exist. Downloading.", path)); 82 | } 83 | fs::create_dir_all(path.parent().unwrap()); 84 | info!("Fetching file from installer"); 85 | let easy = Gog::download_request_range_at( 86 | access_token.as_str(), 87 | data.url.as_str(), 88 | gog::Collector(Vec::new()), 89 | file.start_offset as i64, 90 | file.end_offset as i64, 91 | ) 92 | .unwrap(); 93 | let bytes = easy.get_ref().0.clone(); 94 | drop(easy); 95 | let bytes_len = bytes.len(); 96 | let mut bytes_cur = Cursor::new(bytes); 97 | let mut header_buffer = [0; 4]; 98 | bytes_cur.read_exact(&mut header_buffer).unwrap(); 99 | if u32::from_le_bytes(header_buffer) != 0x04034b50 { 100 | error!("Bad local file header"); 101 | } 102 | bytes_cur.seek(Start(28)).unwrap(); 103 | let mut buffer = [0; 2]; 104 | info!("Reading length of extra field"); 105 | bytes_cur.read_exact(&mut buffer).unwrap(); 106 | let extra_length = u16::from_le_bytes(buffer); 107 | info!("Seeking to beginning of file"); 108 | bytes_cur 109 | .seek(Current((file.filename_length + extra_length) as i64)) 110 | .unwrap(); 111 | let mut bytes = vec![0; bytes_len - bytes_cur.position() as usize]; 112 | bytes_cur.read_exact(&mut bytes).unwrap(); 113 | let mut fd = OpenOptions::new() 114 | .write(true) 115 | .create(true) 116 | .open(&path) 117 | .expect(&format!("Couldn't open file {:?}", path)); 118 | if file.external_file_attr != Some(0) { 119 | info!("Setting permissions"); 120 | fd.set_permissions(Permissions::from_mode( 121 | file.external_file_attr.unwrap() >> 16, 122 | )) 123 | .expect("Couldn't set permissions"); 124 | } 125 | if file.compression_method == 8 { 126 | info!("Decompressing file"); 127 | let def = inflate::inflate_bytes(bytes.as_slice()).unwrap(); 128 | info!("Writing decompressed file to disk"); 129 | fd.write_all(&def) 130 | .expect(&format!("Couldn't write to file {:?}", path)); 131 | } else { 132 | println!("Writing file to disk normally"); 133 | fd.write_all(&bytes) 134 | .expect(&format!("Couldn't write to file {:?}", path)); 135 | } 136 | 137 | pb.inc(1); 138 | } 139 | }); 140 | pb.finish_with_message("Updated game!"); 141 | }); 142 | } else { 143 | error!("Could not find game on GOG"); 144 | println!("Can't find game {} in your library.", name); 145 | } 146 | } else { 147 | error!( 148 | "Could not open gameinfo file that should be at {}.", 149 | game_info_path.to_str().unwrap() 150 | ); 151 | println!("Game installation missing a gameinfo file to check for update with."); 152 | } 153 | } 154 | } 155 | pub mod download { 156 | use crate::*; 157 | pub fn download_prep( 158 | gog: &Gog, 159 | details: GameDetails, 160 | options: &DownloadOptions, 161 | ) -> Result<(Vec, bool), Error> { 162 | if details.downloads.linux.is_some() && !options.windows_force { 163 | info!("Downloading linux downloads"); 164 | let name; 165 | if options.dlc { 166 | info!("Downloading DLC"); 167 | name = download(gog, details.all(true), options).unwrap(); 168 | } else { 169 | name = download(gog, details.downloads.linux.unwrap(), options).unwrap(); 170 | } 171 | return Ok((name, false)); 172 | } else { 173 | if !options.windows_auto && !options.windows_force { 174 | info!("Asking user about downloading windows version"); 175 | if Confirmation::new().with_text("This game does not support linux! Would you like to download the windows version to run under wine?").interact().unwrap() { 176 | println!("Downloading windows files. Note: wyvern does not support automatic installation from windows games"); 177 | info!("Downloading windows downloads"); 178 | let name; 179 | if options.dlc { 180 | info!("Downloading DLC as well"); 181 | name = download(&gog, details.all(false), options).unwrap(); 182 | } else { 183 | name = download(gog, details.downloads.windows.unwrap(), options).unwrap(); 184 | } 185 | return Ok((name, true)); 186 | 187 | } else { 188 | error!("No suitable downloads found. Exiting"); 189 | std::process::exit(0); 190 | } 191 | } else { 192 | if !options.windows_force { 193 | println!("No linux version available. Downloading windows version."); 194 | } 195 | info!("Downloading windows downloads"); 196 | let name; 197 | if options.dlc { 198 | info!("Downloading DLC as well"); 199 | name = download(&gog, details.all(false), options).unwrap(); 200 | } else { 201 | name = download(gog, details.downloads.windows.unwrap(), options).unwrap(); 202 | } 203 | return Ok((name, true)); 204 | } 205 | } 206 | } 207 | pub fn download( 208 | gog: &Gog, 209 | downloads: Vec, 210 | options: &DownloadOptions, 211 | ) -> Result, Error> { 212 | info!("Downloading files"); 213 | let mut names = vec![]; 214 | for download in downloads.iter() { 215 | names.push(download.name.clone()); 216 | } 217 | info!("Getting responses to requests"); 218 | let count = downloads.len(); 219 | for idx in 0..count { 220 | let ref tok = gog.token.borrow(); 221 | if tok.is_expired() { 222 | let gog = Gog::new(tok.refresh()?); 223 | } 224 | let mut responses = gog.download_game(vec![downloads[idx].clone()]); 225 | let mut response = responses.remove(0); 226 | if response.is_err() { 227 | println!( 228 | "Error downloading file. Error message:{}", 229 | response.err().unwrap() 230 | ); 231 | } else { 232 | let response = response.unwrap(); 233 | let total_size = response 234 | .headers() 235 | .get("Content-Length") 236 | .unwrap() 237 | .to_str() 238 | .unwrap() 239 | .parse() 240 | .unwrap(); 241 | let pb = ProgressBar::new(total_size); 242 | pb.set_style(ProgressStyle::default_bar() 243 | .template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})") 244 | .progress_chars("#>-")); 245 | let mut name = names[idx].clone(); 246 | let url = response.url().clone(); 247 | let final_name_encoded = url.path_segments().unwrap().last().unwrap().to_string(); 248 | let final_name = 249 | url::percent_encoding::percent_decode(&final_name_encoded.as_bytes()) 250 | .decode_utf8() 251 | .unwrap() 252 | .to_string(); 253 | let final_name_path = PathBuf::from(&final_name); 254 | if options.original { 255 | name = final_name; 256 | } 257 | if let Some(output) = options.output.clone() { 258 | if output.is_dir() { 259 | name = output 260 | .join(PathBuf::from(&name)) 261 | .to_str() 262 | .unwrap() 263 | .to_string(); 264 | } else { 265 | name = output.to_str().unwrap().to_string(); 266 | } 267 | } 268 | if options.preserve_extension { 269 | if let Some(extension) = final_name_path.extension() { 270 | name = name + "." + &extension.to_string_lossy().to_string(); 271 | } 272 | } 273 | let mut i = 1; 274 | let mut name_path = PathBuf::from(&name); 275 | let filename = name_path.file_name().unwrap().to_str().unwrap().to_string(); 276 | if name_path.exists() { 277 | error!("A file named {} already exists. Skipping this file.", filename); 278 | continue; 279 | } 280 | name = name_path.to_str().unwrap().to_string(); 281 | names[idx] = name.clone(); 282 | let temp_name = name.clone() + ".tmp"; 283 | if options.resume { 284 | if let Ok(mut meta) = fs::metadata(&temp_name) { 285 | if meta.len() >= total_size { 286 | println!("Resuming {}, {} of {}", name, idx + 1, count); 287 | pb.set_position(meta.len()); 288 | let mut fd = OpenOptions::new().append(true).open(&temp_name)?; 289 | let handler = WriteHandler { 290 | writer: fd, 291 | pb: Some(pb), 292 | }; 293 | let mut result = Gog::download_request_range_at( 294 | gog.token.borrow().access_token.as_str(), 295 | url.as_str(), 296 | handler, 297 | meta.len() as i64, 298 | total_size as i64, 299 | )?; 300 | let fd_ref = result.get_mut(); 301 | fd_ref.pb.take().unwrap().finish(); 302 | continue; 303 | } else { 304 | error!("This file is larger than or equal to the total size of the file. Not downloading anything."); 305 | continue; 306 | } 307 | } else { 308 | info!("No file to resume from. Continuing as normal."); 309 | } 310 | } else { 311 | if PathBuf::from(name.as_str()).exists() { 312 | error!("The file {} already exists.", name); 313 | std::process::exit(64); 314 | } 315 | } 316 | println!("Downloading {}, {} of {}", name, idx + 1, count); 317 | info!("Creating file"); 318 | let mut fd = fs::File::create(&temp_name)?; 319 | let mut perms = fd.metadata()?.permissions(); 320 | info!("Setting permissions to executable"); 321 | perms.set_mode(0o744); 322 | fd.set_permissions(perms)?; 323 | let mut pb_read = pb.wrap_read(response); 324 | io::copy(&mut pb_read, &mut fd)?; 325 | fs::rename(&temp_name, &name)?; 326 | pb.finish(); 327 | } 328 | } 329 | println!("Done downloading!"); 330 | return Ok(names); 331 | } 332 | } 333 | pub mod install { 334 | use crate::*; 335 | use rayon::prelude::*; 336 | use std::io::BufReader; 337 | pub fn install_all( 338 | names: Vec, 339 | path: PathBuf, 340 | name: String, 341 | shortcut_opts: &ShortcutOptions, 342 | windows: bool, 343 | external_zip: bool, 344 | ) { 345 | for name in names 346 | .iter() 347 | .filter(|x| if windows { x.contains("exe") } else { true }) 348 | { 349 | install( 350 | name.as_str(), 351 | path.clone(), 352 | name.clone(), 353 | &ShortcutOptions { 354 | menu: false, 355 | desktop: false, 356 | shortcuts: false, 357 | }, 358 | windows, 359 | external_zip, 360 | ); 361 | } 362 | shortcuts(&name, path.as_path(), shortcut_opts); 363 | } 364 | pub fn install( 365 | installer: impl Into, 366 | path: PathBuf, 367 | name: String, 368 | shortcut_opts: &ShortcutOptions, 369 | windows: bool, 370 | external_zip: bool, 371 | ) { 372 | info!("Starting installer extraction process"); 373 | if windows { 374 | info!("Extracting windows game using innoextract"); 375 | let output = Command::new("innoextract") 376 | .arg("--exclude-temp") 377 | .arg("--gog") 378 | .arg("--output-dir") 379 | .arg(path.to_str().expect("Couldn't convert path to string")) 380 | .arg(installer.into()) 381 | .output(); 382 | if let Ok(output) = output { 383 | if output.status.success() { 384 | info!("innoextract successfully run"); 385 | if path.join("app").is_dir() { 386 | info!("Game is nested within app directory. Attempting to rename."); 387 | fs::rename(path.join("app"), "tmp").expect("Couldn't rename app folder"); 388 | fs::remove_dir_all(&path).expect("Couldn't remove old folder"); 389 | fs::rename("tmp", &path).expect("Couldn't rename tmp folder"); 390 | } 391 | return; 392 | } else { 393 | error!("Could not run innoextract. Are you sure it's installed and in $PATH?"); 394 | error!("Stdout: {}", String::from_utf8_lossy(&output.stdout)); 395 | error!("Stderr: {}", String::from_utf8_lossy(&output.stderr)); 396 | std::process::exit(64); 397 | } 398 | } else { 399 | error!("Could not run innoextract. Are youu sure it's installed and in $PATH?"); 400 | error!("Error: {:?}", output.err().unwrap()); 401 | std::process::exit(64); 402 | } 403 | } else { 404 | if external_zip { 405 | info!("Unzipping using unzip command"); 406 | if let Err(err) = fs::create_dir("tmp") { 407 | warn!("Could not create temporary extract dir. Error: {:?}", err); 408 | } 409 | println!("Starting unzip of installer."); 410 | let output = Command::new("unzip") 411 | .arg("-d") 412 | .arg("tmp") 413 | .arg("/tmp/data.zip") 414 | .output(); 415 | if let Err(err) = output { 416 | error!("Unzip command failed. Error: {:?}", err); 417 | } else { 418 | let output = output.unwrap(); 419 | if output.status.success() { 420 | info!("Unzip command succeeded. Beginning path processing."); 421 | for entry in WalkDir::new("tmp").into_iter().filter_map(|e| e.ok()) { 422 | let new_path = path 423 | .join( 424 | entry 425 | .path() 426 | .strip_prefix(Path::new("tmp")) 427 | .expect("Couldn't strip path") 428 | .to_str() 429 | .unwrap() 430 | .replace("/noarch", "") 431 | .replace("data/", "") 432 | .to_owned(), 433 | ) 434 | .to_path_buf(); 435 | let str_new = format!("{}", new_path.clone().to_str().unwrap()); 436 | if !str_new.contains("meta") && !str_new.contains("scripts") { 437 | if str_new.ends_with("/") { 438 | info!("Creating dir"); 439 | fs::create_dir_all(new_path) 440 | .expect("Couldn't create directory"); 441 | } else { 442 | if let Some(p) = new_path.as_path().parent() { 443 | if !p.exists() { 444 | fs::create_dir_all(&p) 445 | .expect("Couldn't create parent directory!"); 446 | } 447 | } 448 | if entry.path().is_dir() { 449 | fs::create_dir_all(new_path); 450 | } else { 451 | info!("Moving file"); 452 | fs::rename(entry.path(), new_path.as_path()) 453 | .expect("Couldn't move file to proper directory"); 454 | } 455 | } 456 | } 457 | } 458 | fs::remove_dir_all("tmp").expect("Could not remove temp directory"); 459 | } else { 460 | error!( 461 | "Unzip command failed.\n Stdout: {:?}\n Stderr: {:?}", 462 | output.stdout, output.stderr 463 | ); 464 | } 465 | } 466 | } else { 467 | if let Ok(mut installer) = File::open(installer.into()) { 468 | extract( 469 | &mut installer, 470 | "/tmp", 471 | ToExtract { 472 | unpacker: false, 473 | mojosetup: false, 474 | data: true, 475 | }, 476 | ) 477 | .unwrap(); 478 | info!("Opening extracted zip"); 479 | let file = File::open("/tmp/data.zip").unwrap(); 480 | // Extract code taken mostly from zip example 481 | let archive = zip::ZipArchive::new(BufReader::new(file)).unwrap(); 482 | let len = archive.len(); 483 | let pb = ProgressBar::new(len as u64); 484 | pb.set_style( 485 | ProgressStyle::default_bar() 486 | .template( 487 | "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len}", 488 | ) 489 | .progress_chars("#>-"), 490 | ); 491 | info!("Starting zip extraction process"); 492 | (0..len).into_par_iter().for_each(|i| { 493 | info!("Starting extraction of file #{}. Opening archive", i); 494 | let mut archive = zip::ZipArchive::new(BufReader::new( 495 | File::open("/tmp/data.zip").unwrap(), 496 | )) 497 | .unwrap(); 498 | info!("Getting file from archive"); 499 | let mut file = archive.by_index(i).unwrap(); 500 | let filtered_path = file 501 | .sanitized_name() 502 | .to_str() 503 | .unwrap() 504 | .replace("/noarch", "") 505 | .replace("data/", "") 506 | .to_owned(); 507 | //Extract only files for the game itself 508 | if !filtered_path.contains("meta") && !filtered_path.contains("scripts") { 509 | let outpath = path.clone().join(PathBuf::from(filtered_path)); 510 | if (&*file.name()).ends_with('/') { 511 | info!("Creating dir"); 512 | fs::create_dir_all(&outpath).unwrap(); 513 | } else { 514 | if let Some(p) = outpath.parent() { 515 | if !p.exists() { 516 | fs::create_dir_all(&p).unwrap(); 517 | } 518 | } 519 | info!("Creating file"); 520 | let mut outfile = fs::File::create(&outpath).unwrap(); 521 | info!("Copying to file"); 522 | io::copy(&mut file, &mut outfile).unwrap(); 523 | } 524 | use std::os::unix::fs::PermissionsExt; 525 | if let Some(mode) = file.unix_mode() { 526 | info!("Setting permissions for file"); 527 | fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)) 528 | .unwrap(); 529 | } 530 | } else { 531 | info!("File {} not being extracted", filtered_path); 532 | } 533 | pb.inc(1); 534 | }); 535 | pb.finish_with_message("Game installed!"); 536 | shortcuts(&name, path.as_path(), shortcut_opts); 537 | } else { 538 | error!("Could not open installer file"); 539 | return; 540 | } 541 | } 542 | } 543 | #[cfg(feature = "eidolonint")] 544 | { 545 | if !windows { 546 | info!("Compiled with eidolon integration. Adding game to registry"); 547 | use libeidolon::games::*; 548 | use libeidolon::helper::*; 549 | use libeidolon::*; 550 | let proc_name = create_procname(name.clone()); 551 | info!("Creating game object"); 552 | let game = Game { 553 | name: proc_name, 554 | pname: name, 555 | command: current_dir().unwrap().to_str().unwrap().to_string(), 556 | typeg: GameType::WyvernGOG, 557 | }; 558 | info!("Adding game to eidolon"); 559 | add_game(game); 560 | println!("Added game to eidolon registry!"); 561 | } 562 | } 563 | } 564 | } 565 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------