1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! This crate provides an easy interface to communicate with the not-so-easy (unofficial) GOG API.
//! Many thanks to [Yepoleb](https://github.com/Yepoleb), who made
//! [this](https://gogapidocs.readthedocs.io/en/latest/index.html) very helpful set of docs.
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate error_chain;
extern crate regex;
extern crate reqwest;
extern crate serde;
mod containers;
/// Provides error-handling logic
mod error;
/// Module for extracting GOG installers into their component parts
pub mod extract;
/// Module for GOG structs and responses
pub mod gog;
/// Module for OAuth token management
pub mod token;
use connect::*;
use containers::*;
use domains::*;
/// Main error for GOG calls
pub use error::Error;
pub use error::ErrorKind;
pub use error::Result;
use gog::*;
use product::*;
use reqwest::RedirectPolicy;
use reqwest::{Client, Method, Response};
use serde::de::DeserializeOwned;
use serde_json::value::{Map, Value};
use std::cell::RefCell;
use token::Token;
use ErrorKind::*;
const GET: Method = Method::GET;
const POST: Method = Method::POST;
/// This is returned from functions that GOG doesn't return anything for. Should only be used for error-checking to see if requests failed, etc.
pub type EmptyResponse = ::std::result::Result<Response, Error>;
macro_rules! map_p {
    ($($js: tt)+) => {
        Some(json!($($js)+).as_object().unwrap().clone())
    }
}
/// The main GOG Struct that you'll use to make API calls.
pub struct Gog {
    pub token: RefCell<Token>,
    client: RefCell<Client>,
    client_noredirect: RefCell<Client>,
    pub auto_update: bool,
}
impl Gog {
    /// Initializes out of a token from a login code
    pub fn from_login_code(code: &str) -> Gog {
        Gog::from_token(Token::from_login_code(code).unwrap())
    }
    /// Creates using a pre-made token
    pub fn new(token: Token) -> Gog {
        Gog::from_token(token)
    }
    fn from_token(token: Token) -> Gog {
        let headers = Gog::headers_token(&token.access_token);
        let mut client = Client::builder();
        let mut client_re = Client::builder().redirect(RedirectPolicy::none());
        client = client.default_headers(headers.clone());
        client_re = client_re.default_headers(headers);
        return Gog {
            token: RefCell::new(token),
            client: RefCell::new(client.build().unwrap()),
            client_noredirect: RefCell::new(client_re.build().unwrap()),
            auto_update: true,
        };
    }
    fn update_token(&self, token: Token) {
        let headers = Gog::headers_token(&token.access_token);
        let client = Client::builder();
        let client_re = Client::builder().redirect(RedirectPolicy::none());
        self.client
            .replace(client.default_headers(headers.clone()).build().unwrap());
        self.client_noredirect
            .replace(client_re.default_headers(headers).build().unwrap());
        self.token.replace(token);
    }
    pub fn uid_string(&self) -> String {
        self.token.borrow().user_id.clone()
    }
    pub fn uid(&self) -> i64 {
        self.token.borrow().user_id.parse().unwrap()
    }
    fn headers_token(at: &str) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            "Authorization",
            ("Bearer ".to_string() + at).parse().unwrap(),
        );
        // GOG now requires this magic cookie to be included in all requests.
        headers.insert("CSRF", "csrf=true".parse().unwrap());
        return headers;
    }
    fn rget(
        &self,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
    ) -> Result<Response> {
        self.rreq(GET, domain, path, params)
    }
    fn rpost(
        &self,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
    ) -> Result<Response> {
        self.rreq(POST, domain, path, params)
    }
    fn rreq(
        &self,
        method: Method,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
    ) -> Result<Response> {
        if self.token.borrow().is_expired() {
            if self.auto_update {
                self.update_token(self.token.borrow().refresh()?);
                return self.rreq(method, domain, path, params);
            } else {
                return Err(ExpiredToken.into());
            }
        } else {
            let mut url = domain.to_string() + path;
            if params.is_some() {
                let params = params.unwrap();
                if params.len() > 0 {
                    url = url + "?";
                    for (k, v) in params.iter() {
                        url = url + k + "=" + &v.to_string() + "&";
                    }
                    url.pop();
                }
            }
            Ok(self.client.borrow().request(method, &url).send()?)
        }
    }
    fn fget<T>(&self, domain: &str, path: &str, params: Option<Map<String, Value>>) -> Result<T>
    where
        T: DeserializeOwned,
    {
        self.freq(GET, domain, path, params)
    }
    fn fpost<T>(&self, domain: &str, path: &str, params: Option<Map<String, Value>>) -> Result<T>
    where
        T: DeserializeOwned,
    {
        self.freq(POST, domain, path, params)
    }

    fn freq<T>(
        &self,
        method: Method,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let mut res = self.rreq(method, domain, path, params)?;
        let st = res.text()?;
        Ok(serde_json::from_str(&st)?)
    }
    fn nfreq<T>(
        &self,
        method: Method,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
        nested: &str,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let r: Map<String, Value> = self.freq(method, domain, path, params)?;
        if r.contains_key(nested) {
            return Ok(serde_json::from_str(&r.get(nested).unwrap().to_string())?);
        } else {
            return Err(MissingField(nested.to_string()).into());
        }
    }
    fn nfget<T>(
        &self,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
        nested: &str,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        self.nfreq(GET, domain, path, params, nested)
    }
    fn nfpost<T>(
        &self,
        domain: &str,
        path: &str,
        params: Option<Map<String, Value>>,
        nested: &str,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        self.nfreq(POST, domain, path, params, nested)
    }

    /// Gets the data of the user that is currently logged in
    pub fn get_user_data(&self) -> Result<UserData> {
        self.fget(EMBD, "/userData.json", None)
    }
    /// Gets any publically available data about a user
    pub fn get_pub_info(&self, uid: i64, expand: Vec<String>) -> Result<PubInfo> {
        self.fget(
            EMBD,
            &("/users/info/".to_string() + &uid.to_string()),
            map_p!({
            "expand":expand.iter().try_fold("".to_string(), fold_mult).unwrap()
            }),
        )
    }
    /// Gets a user's owned games. Only gameids.
    pub fn get_games(&self) -> Result<Vec<i64>> {
        let r: OwnedGames = self.fget(EMBD, "/user/data/games", None)?;
        Ok(r.owned)
    }
    /// Gets more info about a game by gameid
    pub fn get_game_details(&self, game_id: i64) -> Result<GameDetails> {
        let mut res: GameDetailsP = self.fget(
            EMBD,
            &("/account/gameDetails/".to_string() + &game_id.to_string() + ".json"),
            None,
        )?;
        res.downloads[0].remove(0);
        let downloads: Downloads =
            serde_json::from_str(&serde_json::to_string(&res.downloads[0][0])?)?;
        Ok(res.to_details(downloads))
    }
    /// Returns a vec of game parts
    pub fn download_game(&self, downloads: Vec<Download>) -> Vec<Response> {
        downloads
            .iter()
            .filter_map(|x| {
                let mut url = BASE.to_string() + &x.manual_url;
                let mut response;
                loop {
                    let temp_response = self.client_noredirect.borrow().get(&url).send();
                    if temp_response.is_ok() {
                        response = temp_response.unwrap();
                        let headers = response.headers();
                        // GOG appears to be inconsistent with returning either 301/302, so this just checks for a redirect location.
                        if headers.contains_key("location") {
                            url = headers
                                .get("location")
                                .unwrap()
                                .to_str()
                                .unwrap()
                                .to_string();
                        } else {
                            break;
                        }
                    } else {
                        return None;
                    }
                }
                Some(response)
            })
            .collect()
    }
    /// Hides a product from your library
    pub fn hide_product(&self, game_id: i64) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/account/hideProduct".to_string() + &game_id.to_string()),
            None,
        )
    }
    /// Reveals a product in your library
    pub fn reveal_product(&self, game_id: i64) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/account/revealProduct".to_string() + &game_id.to_string()),
            None,
        )
    }
    /// Gets the wishlist of the current user
    pub fn wishlist(&self) -> Result<Wishlist> {
        self.fget(EMBD, "/user/wishlist.json", None)
    }
    /// Adds an item to the wishlist. Returns wishlist
    pub fn add_wishlist(&self, game_id: i64) -> Result<Wishlist> {
        self.fget(
            EMBD,
            &("/user/wishlist/add/".to_string() + &game_id.to_string()),
            None,
        )
    }
    /// Removes an item from wishlist. Returns wishlist
    pub fn rm_wishlist(&self, game_id: i64) -> Result<Wishlist> {
        self.fget(
            EMBD,
            &("/user/wishlist/remove/".to_string() + &game_id.to_string()),
            None,
        )
    }
    /// Sets birthday of account. Date should be in ISO 8601 format
    pub fn save_birthday(&self, bday: &str) -> EmptyResponse {
        self.rget(EMBD, &("/account/save_birthday".to_string() + bday), None)
    }
    /// Sets country of account. Country should be in ISO 3166 format
    pub fn save_country(&self, country: &str) -> EmptyResponse {
        self.rget(EMBD, &("/account/save_country".to_string() + country), None)
    }
    /// Changes default currency. Currency is in ISO 4217 format. Only currencies supported are
    /// ones in the currency enum.
    pub fn save_currency(&self, currency: Currency) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/user/changeCurrency".to_string() + &currency.to_string()),
            None,
        )
    }
    /// Changes default language. Possible languages are available as constants in the langauge
    /// enum.
    pub fn save_language(&self, language: Language) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/user/changeLanguage".to_string() + &language.to_string()),
            None,
        )
    }
    /// Gets info about the steam account linked to GOG Connect for the user id
    pub fn connect_account(&self, user_id: i64) -> Result<LinkedSteam> {
        self.fget(
            EMBD,
            &("/api/v1/users/".to_string() + &user_id.to_string() + "/gogLink/steam/linkedAccount"),
            None,
        )
    }
    /// Gets claimable status of currently available games on GOG Connect
    pub fn connect_status(&self, user_id: i64) -> Result<ConnectStatus> {
        let st = self
            .rget(
                EMBD,
                &("/api/v1/users/".to_string()
                    + &user_id.to_string()
                    + "/gogLink/steam/exchangeableProducts"),
                None,
            )?
            .text()?;
        if let Ok(cs) = serde_json::from_str(&st) {
            return Ok(cs);
        } else {
            let map: Map<String, Value> = serde_json::from_str(&st)?;
            if let Some(items) = map.get("items") {
                let array = items.as_array();
                if array.is_some() && array.unwrap().len() == 0 {
                    return Err(NotAvailable.into());
                }
            }
        }
        Err(MissingField("items".to_string()).into())
    }
    /// Scans Connect for claimable games
    pub fn connect_scan(&self, user_id: i64) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/api/v1/users/".to_string()
                + &user_id.to_string()
                + "/gogLink/steam/synchronizeUserProfile"),
            None,
        )
    }
    /// Claims all available Connect games
    pub fn connect_claim(&self, user_id: i64) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/api/v1/users/".to_string() + &user_id.to_string() + "/gogLink/steam/claimProducts"),
            None,
        )
    }
    /// Returns detailed info about a product/products.
    pub fn product(&self, ids: Vec<i64>, expand: Vec<String>) -> Result<Vec<Product>> {
        self.fget(
            API,
            "/products",
            map_p!({
            "expand":expand.iter().try_fold("".to_string(), fold_mult).unwrap(),
            "ids": ids.iter().try_fold("".to_string(), |acc, x|{
                let done : Result<String> = Ok(acc +"," +&x.to_string());
                done
            }).unwrap()
        }),
        )
    }
    /// Get a list of achievements for a game and user id
    pub fn achievements(&self, product_id: i64, user_id: i64) -> Result<AchievementList> {
        self.fget(
            GPLAY,
            &("/clients/".to_string()
                + &product_id.to_string()
                + "/users/"
                + &user_id.to_string()
                + "/achievements"),
            None,
        )
    }
    /// Adds tag with tagid to product
    pub fn add_tag(&self, product_id: i64, tag_id: i64) -> Result<bool> {
        let res: Result<Success> = self.fget(
            EMBD,
            "/account/tags/attach",
            map_p!({
            "product_id":product_id,
            "tag_id":tag_id
        }),
        );
        res.map(|x| x.success)
    }
    /// Removes tag with tagid from product
    pub fn rm_tag(&self, product_id: i64, tag_id: i64) -> Result<bool> {
        self.nfget(
            EMBD,
            "/account/tags/detach",
            map_p!({
            "product_id":product_id,
            "tag_id":tag_id
        }),
            "success",
        )
    }
    /// Fetches info about a set of products owned by the user based on search criteria
    pub fn get_filtered_products(&self, params: FilterParams) -> Result<Vec<ProductDetails>> {
        //GOG.com url is just to avoid "cannot be a base" url parse error, as we only need the path anyways
        let url = reqwest::Url::parse(
            &("https://gog.com/account/getFilteredProducts".to_string()
                + &params.to_query_string()),
        )
        .unwrap();
        let path = url.path().to_string() + "?" + url.query().unwrap();
        self.nfget(EMBD, &path, None, "products")
    }
    /// Fetches info about a set of products based on search criteria
    pub fn get_products(&self, params: FilterParams) -> Result<Vec<UnownedProductDetails>> {
        //GOG.com url is just to avoid "cannot be a base" url parse error, as we only need the path anyways
        let url = reqwest::Url::parse(
            &("https://gog.com/games/ajax/filtered".to_string() + &params.to_query_string()),
        )
        .unwrap();
        let path = url.path().to_string() + "?" + url.query().unwrap();
        self.nfget(EMBD, &path, None, "products")
    }
    /// Creates a new tag. Returns the tag's id
    pub fn create_tag(&self, name: &str) -> Result<i64> {
        return self
            .nfget(EMBD, "/account/tags/add", map_p!({ "name": name }), "id")
            .map(|x: String| x.parse::<i64>().unwrap());
    }
    /// Deletes a tag. Returns bool indicating success
    pub fn delete_tag(&self, tag_id: i64) -> Result<bool> {
        let res: Result<StatusDel> =
            self.fget(EMBD, "/account/tags/delete", map_p!({ "tag_id": tag_id }));
        res.map(|x| {
            if x.status.as_str() == "deleted" {
                return true;
            } else {
                return false;
            }
        })
    }
    /// Changes newsletter subscription status
    pub fn newsletter_subscription(&self, enabled: bool) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/account/save_newsletter_subscription/".to_string()
                + &bool_to_int(enabled).to_string()),
            None,
        )
    }
    /// Changes promo subscription status
    pub fn promo_subscription(&self, enabled: bool) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/account/save_promo_subscription/".to_string() + &bool_to_int(enabled).to_string()),
            None,
        )
    }
    /// Changes wishlist subscription status
    pub fn wishlist_subscription(&self, enabled: bool) -> EmptyResponse {
        self.rget(
            EMBD,
            &("/account/save_wishlist_notification/".to_string()
                + &bool_to_int(enabled).to_string()),
            None,
        )
    }
    /// Shortcut function to enable or disable all subscriptions
    pub fn all_subscription(&self, enabled: bool) -> Vec<EmptyResponse> {
        vec![
            self.newsletter_subscription(enabled),
            self.promo_subscription(enabled),
            self.wishlist_subscription(enabled),
        ]
    }
    /// Gets games this user has rated
    pub fn game_ratings(&self) -> Result<Vec<(String, i64)>> {
        let g: Map<String, Value> =
            self.nfget(EMBD, "/user/games_rating.json", None, "games_rating")?;
        Ok(g.iter()
            .map(|x| return (x.0.to_owned(), x.1.as_i64().unwrap()))
            .collect::<Vec<(String, i64)>>())
    }
    /// Gets reviews the user has voted on
    pub fn voted_reviews(&self) -> Result<Vec<i64>> {
        return self.nfget(EMBD, "/user/review_votes.json", None, "reviews");
    }
    /// Reports a review
    pub fn report_review(&self, review_id: i32) -> Result<bool> {
        self.nfpost(
            EMBD,
            &("/reviews/report/review/".to_string() + &review_id.to_string() + ".json"),
            None,
            "reported",
        )
    }
    /// Sets library background style
    pub fn library_background(&self, bg: ShelfBackground) -> EmptyResponse {
        self.rpost(
            EMBD,
            &("/account/save_shelf_background/".to_string() + bg.as_str()),
            None,
        )
    }
    /// Returns list of friends
    pub fn friends(&self) -> Result<Vec<Friend>> {
        self.nfget(
            CHAT,
            &("/users/".to_string() + &self.uid_string() + "/friends"),
            None,
            "items",
        )
    }
}
fn fold_mult(acc: String, now: &String) -> Result<String> {
    return Ok(acc + "," + now);
}
fn bool_to_int(b: bool) -> i32 {
    let mut par = 0;
    if b {
        par = 1;
    }
    return par;
}