gpipipi 0.2.0

a rust crate for the google play api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! a rust crate for the google play api
//!
//! to get started, get an oauth token, you one by logging in into the
//! [embedded setup page](https://accounts.google.com/EmbeddedSetup), opening the dev tools and
//! then checking the network tab / application tab for the returned cookie. the token can only be
//! used once, and the resulting aas token doesn't seem to expire
//!
//! after getting the oauth token, you can convert it with the crate by running it as a binary like so:
//! ```bash
//! OAUTH_TOKEN="..." EMAIL="..." cargo run --features binary
//! ```
//!
//! or alternatively, convert it manually using [`OAuthRequest`]
//!
//! after you get an aas token, parse your device props using [`PropsMap::parse_aurora_config`]
//! then construct a [`LongLivedClient`] using [`LongLivedClient::login`] to start sending requests
//!
//! if instead you already have an auth token that was generated from an aas token somewhere else,
//! use [`ShortLivedClient::login`], keeping in mind that auth tokens expire much faster than aas
//! tokens and that this client can't renew them on its own
//!
//! both of them implement the [`Client`] trait, which holds every method, so it needs to be
//! in scope to send requests

#![warn(clippy::all, clippy::pedantic, clippy::perf, clippy::nursery)]
#![allow(clippy::struct_field_names)]
use crate::{
    api::{
        endpoint::Requester,
        login::{AuthToken, checkin, fetch_auth, toc, upload_device},
    },
    error::{
        CategoryError, DetailsError, DownloadsError, IntoGoogleError, LoginError, PropsError,
        ReviewsError, SearchError, SearchSuggestionError,
    },
    proto::{Item, Review, SearchSuggestEntry},
};
pub use api::{
    oauth::OAuthRequest,
    properties::{DeviceProperties, PropsMap},
};
use async_stream::try_stream;
use futures_core::stream::Stream;
use std::future::Future;

mod api;
mod consts;
pub mod error;
pub mod proto;

macro_rules! async_doc {
    ($code:literal) => {
        concat!(
            r#"```
# tokio_test::block_on(async {
# #[allow(unused_imports)] use gpipipi::Client;
# const PROPS: &str = include_str!("../example.properties");
# let mut props_map = gpipipi::PropsMap::parse_aurora_config(PROPS)?;
# let props = props_map.remove("arm").ok_or("No 'arm' device props!")?;
# let aas_token = std::env::var("AAS_TOKEN").map_err(|_| "Set 'AAS_TOKEN' to an aas token, running the binary turns an oauth token into one!")?;
# let email = std::env::var("EMAIL").map_err(|_| "Set 'EMAIL' to the email used for the token!")?;
"#,
            $code,
            "
# Ok::<(), Box<dyn std::error::Error>>(())
# })?;
# Ok::<(), Box<dyn std::error::Error>>(())
```"
        )
    }
}

macro_rules! short_doc {
    ($code:literal) => {
        concat!(
            r#"```
# tokio_test::block_on(async {
# #[allow(unused_imports)] use gpipipi::Client;
# const PROPS: &str = include_str!("../example.properties");
# let mut props_map = gpipipi::PropsMap::parse_aurora_config(PROPS)?;
# let props = props_map.remove("arm").ok_or("No 'arm' device props!")?;
# let auth_token = std::env::var("AUTH_TOKEN").map_err(|_| "Set 'AUTH_TOKEN' to an auth token generated from an aas token!")?;
"#,
            $code,
            "
# Ok::<(), Box<dyn std::error::Error>>(())
# })?;
# Ok::<(), Box<dyn std::error::Error>>(())
```"
        )
    }
}

mod sealed {
    use crate::{api::endpoint::Requester, error::PropsError};
    use std::future::Future;

    /// implemented by every client, builds a requester holding whatever state that client has
    ///
    /// this is private on purpose, so [`super::Client`] can't be implemented outside of the crate
    pub trait Sealed {
        fn requester(&self) -> impl Future<Output = Result<Requester<'_>, PropsError>> + Send;
    }
}

/// the shared state of a logged in client, everything google handed back while logging in
struct Session {
    props: DeviceProperties,
    auth_token: AuthToken,

    checkin_token: String,
    config_token: String,
    dfe_cookie: String,
    gsf: i64,
}

impl Session {
    /// checks in and uploads the device props, returning the gsf id, the checkin token and the
    /// config token, everything a client needs before it can authenticate
    async fn prepare(props: &DeviceProperties) -> Result<(i64, String, String), LoginError> {
        let checkin_response = checkin(props).await?;
        let gsf = checkin_response
            .android_id
            .ok_or(LoginError::NoAndroidId())?
            .cast_signed();

        let checkin_token = checkin_response
            .device_checkin_consistency_token
            .ok_or(LoginError::NoDeviceToken())?;

        let upload_response = upload_device(props, gsf, &checkin_token).await?;
        let config_token = upload_response
            .upload_device_config_token
            .ok_or(LoginError::NoConfigToken())?;

        Ok((gsf, checkin_token, config_token))
    }

    fn requester(&'_ self) -> Requester<'_> {
        Requester::new()
            .checkin_token(&self.checkin_token)
            .config_token(&self.config_token)
            .auth_token(&self.auth_token)
            .dfe_cookie(&self.dfe_cookie)
            .props(&self.props)
            .gsf(self.gsf)
    }
}

/// a logged in google play client that owns an aas token
///
/// aas tokens don't seem to expire, so this client renews its own auth token whenever the current
/// one runs out, which makes it the one to use for anything long running
///
/// to create one, see [`LongLivedClient::login`], the requests themselves live on [`Client`]
pub struct LongLivedClient {
    aas_token: String,
    email: String,

    session: Session,
}

impl LongLivedClient {
    /// creates a new client, logging in using the email and AAS token, acting as the given
    /// device props, **AND accepting Terms of Service if required!!**
    ///
    /// if you have an oauth token, you first need to convert it to aas using [`OAuthRequest`]
    ///
    /// # Examples
    #[doc = async_doc!(r#"let mut props_map = gpipipi::PropsMap::parse_aurora_config(PROPS)?;
let props = props_map.remove("arm").ok_or("No 'arm' device props!")?;
let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;"#)]
    ///
    /// # Errors
    /// - `Checkin` - failed to checkin into google
    /// - `Upload` - failed to upload device props to google
    /// - `Auth` - failed to fetch the auth token from google
    /// - `Toc` - failed to fetch the terms of service / accept them
    /// - `NoDeviceToken` - google returned no `device_checkin_consistency_token`
    /// - `NoAndroidId` - google returned no `android_id`
    /// - `NoConfigToken` - google returned no `upload_device_config_token`
    pub async fn login<A: Into<String>, B: Into<String>>(
        email: A,
        aas_token: B,
        props: DeviceProperties,
    ) -> Result<Self, LoginError> {
        // internal state is all handled here so there's no case where clients can exist
        // with incomplete data

        let email = email.into();
        let aas_token = aas_token.into();

        let (gsf, checkin_token, config_token) = Session::prepare(&props).await?;

        let auth_token = fetch_auth(&props, &aas_token, &email, gsf).await?;
        let dfe_cookie = toc(&auth_token, gsf, &checkin_token, &props).await?;

        Ok(Self {
            aas_token,
            email,
            session: Session {
                props,
                auth_token,
                checkin_token,
                config_token,
                dfe_cookie,
                gsf,
            },
        })
    }
}

impl sealed::Sealed for LongLivedClient {
    async fn requester(&self) -> Result<Requester<'_>, PropsError> {
        // the aas token and the email are what lets the requester fetch a new auth token
        // once the current one expires
        self.session
            .requester()
            .aas_token(&self.aas_token)
            .email(&self.email)
            .default_headers()
            .await
    }
}

impl Client for LongLivedClient {}

/// a logged in google play client that only owns an auth token, one that was generated from an
/// aas token outside of this crate
///
/// auth tokens expire way faster than aas tokens do, usually within the hour, and this client has
/// no aas token to generate a new one with, so requests start failing with google errors once it's
/// gone, either hand it a fresh token with [`ShortLivedClient::set_auth_token`] or use a
/// [`LongLivedClient`] instead
///
/// to create one, see [`ShortLivedClient::login`], the requests themselves live on [`Client`]
pub struct ShortLivedClient {
    session: Session,
}

impl ShortLivedClient {
    /// creates a new client from an existing auth token, acting as the given device props,
    /// **AND accepting Terms of Service if required!!**
    ///
    /// the token has to be an auth token, the one google hands back for
    /// `oauth2:https://www.googleapis.com/auth/googleplay`, not the aas token it was generated
    /// from, for that one use [`LongLivedClient::login`]
    ///
    /// # Examples
    #[doc = short_doc!(r#"let mut props_map = gpipipi::PropsMap::parse_aurora_config(PROPS)?;
let props = props_map.remove("arm").ok_or("No 'arm' device props!")?;
let client = gpipipi::ShortLivedClient::login(auth_token, props).await?;"#)]
    ///
    /// # Errors
    /// - `Checkin` - failed to checkin into google
    /// - `Upload` - failed to upload device props to google
    /// - `Toc` - failed to fetch the terms of service / accept them, usually a dead auth token
    /// - `NoDeviceToken` - google returned no `device_checkin_consistency_token`
    /// - `NoAndroidId` - google returned no `android_id`
    /// - `NoConfigToken` - google returned no `upload_device_config_token`
    pub async fn login<A: Into<String>>(
        auth_token: A,
        props: DeviceProperties,
    ) -> Result<Self, LoginError> {
        let (gsf, checkin_token, config_token) = Session::prepare(&props).await?;

        // google is the only one that knows how much is left of a token we didn't fetch,
        // so it's always sent and google decides when it stopped being valid
        let auth_token = AuthToken::without_expire(auth_token.into());
        let dfe_cookie = toc(&auth_token, gsf, &checkin_token, &props).await?;

        Ok(Self {
            session: Session {
                props,
                auth_token,
                checkin_token,
                config_token,
                dfe_cookie,
                gsf,
            },
        })
    }

    /// swaps in a new auth token, for when the current one expired
    ///
    /// the rest of the login state stays as it is, so this doesn't do any requests
    ///
    /// # Examples
    #[doc = short_doc!(r#"let client = gpipipi::ShortLivedClient::login(&auth_token, props).await?;
client.set_auth_token(auth_token);"#)]
    pub fn set_auth_token<A: Into<String>>(&self, auth_token: A) {
        self.session.auth_token.set(auth_token.into(), None);
    }
}

impl sealed::Sealed for ShortLivedClient {
    async fn requester(&self) -> Result<Requester<'_>, PropsError> {
        self.session.requester().default_headers().await
    }
}

impl Client for ShortLivedClient {}

/// every request a logged in google play client can send
///
/// it's implemented by [`LongLivedClient`] and [`ShortLivedClient`] and can't be implemented
/// outside of this crate, so bring it into scope and pick whichever of the two fits the token
/// you have
///
/// every future and stream it hands out is `Send`, so code generic over a client can still be
/// spawned onto a runtime
///
/// # Examples
#[doc = async_doc!(r#"async fn first_hit(client: &impl Client) -> Result<Option<String>, gpipipi::error::SearchError> {
    let results = client.search("robl", None).await?;
    Ok(results.items.into_iter().next().and_then(|a| a.title))
}

let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
println!("{:?}", first_hit(&client).await?);"#)]
#[allow(private_bounds)]
pub trait Client: sealed::Sealed + Sync {
    /// fetches the details for a specific package name, optionally for a specific version code
    ///
    /// # Examples
    #[doc = async_doc!(r#"let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
let details = client.details("com.roblox.client", None).await?;"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn details<A: AsRef<str> + Send>(
        &self,
        package_name: A,
        maybe_version: Option<i64>,
    ) -> impl Future<Output = Result<proto::AppDetails, DetailsError>> + Send {
        async move {
            let maybe_version = maybe_version.map(|a| a.to_string());
            let params = maybe_version.as_ref().map_or_else(
                || [("doc", package_name.as_ref()), ("", "")],
                |version| [("doc", package_name.as_ref()), ("vc", version)],
            );

            let request = self.requester().await?.params(&params);
            let mut response = request.fdfe_request("details", None).await?;

            let response = response
                .payload
                .take()
                .and_then(|a| a.details_response)
                .and_then(|a| a.item)
                .and_then(|a| a.details)
                .and_then(|a| a.app_details)
                .into_google_error(&response)?;

            Ok(response)
        }
    }

    /// fetches the download urls for a specific package name, optionally for a specific version code
    ///
    /// # Examples
    #[doc = async_doc!(r#"let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
let download_urls = client.downloads("com.roblox.client", Some(2036)).await?;"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `VersionFetchError` - no version was provided and fetching the latest got this
    /// - `Google` - error from google
    fn downloads<A: AsRef<str> + Send>(
        &self,
        package_name: A,
        version: Option<i64>,
    ) -> impl Future<Output = Result<DownloadResponse, DownloadsError>> + Send {
        async move {
            let version = if let Some(version) = version {
                version
            } else {
                latest_version(self, package_name.as_ref()).await?
            }
            .to_string();

            let headers = [("content-length", "0")];
            let params = [
                ("ot", "1"),
                ("doc", package_name.as_ref()),
                ("vc", &version),
            ];

            let mut request = self.requester().await?.headers(&headers).params(&params);
            let mut response = request.fdfe_request("purchase", Some(Vec::new())).await?;

            let delivery_token = response
                .payload
                .take()
                .and_then(|a| a.buy_response)
                .and_then(|a| a.encoded_delivery_token)
                .into_google_error(&response)?;

            let delivery_params = [
                ("doc", package_name.as_ref()),
                ("dtok", &delivery_token),
                ("vc", &version),
                ("ot", "1"),
            ];

            request = request.headers(&[]).params(&delivery_params);

            let mut delivery_response = request.fdfe_request("delivery", None).await?;
            let app_delivery_data = delivery_response
                .payload
                .take()
                .and_then(|a| a.delivery_response)
                .and_then(|a| a.app_delivery_data)
                .into_google_error(&response)?;

            let base = app_delivery_data
                .download_url
                .zip(app_delivery_data.sha1)
                .map(|(url, sha1)| CdnUrl {
                    filename: "base".to_string(),
                    url,
                    sha1,
                })
                .into_google_error(&response)?;

            let splits: Vec<_> = app_delivery_data
                .split_delivery_data
                .into_iter()
                .filter_map(|a| {
                    a.name
                        .zip(a.download_url)
                        .zip(a.sha1)
                        .map(|((filename, url), sha1)| CdnUrl {
                            filename,
                            sha1,
                            url,
                        })
                })
                .collect();

            let obbs: Vec<_> = app_delivery_data
                .additional_file
                .into_iter()
                .filter_map(|a| {
                    a.file_type
                        .zip(a.sha1)
                        .zip(a.version_code)
                        .zip(a.download_url)
                        .map(|(((ftype, sha1), version), url)| {
                            let prefix = if ftype == 0 { "main" } else { "patch" };
                            CdnUrl {
                                filename: format!(
                                    "{prefix}.{version}.{}.obb",
                                    package_name.as_ref()
                                ),
                                url,
                                sha1,
                            }
                        })
                })
                .collect();

            Ok(DownloadResponse { splits, obbs, base })
        }
    }

    /// fetches all categories of a certain type
    ///
    /// # Examples
    #[doc = async_doc!("let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
let categories = client.categories(gpipipi::CategoryType::Game).await?;")]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn categories(
        &self,
        cat_type: CategoryType,
    ) -> impl Future<Output = Result<Vec<Category>, CategoryError>> + Send {
        async move {
            let type_name = format!("{cat_type:?}").to_uppercase();

            let headers = [("User-Agent", consts::LEGACY_USERAGENT)];
            let params = [("c", "3"), ("cat", &type_name)];

            let request = self.requester().await?.headers(&headers).params(&params);
            let mut response = request.fdfe_request("categoriesList", None).await?;

            let items = response
                .payload
                .take()
                .and_then(|a| a.list_response)
                .and_then(|a| a.item)
                .and_then(|mut a| a.sub_item.pop())
                .into_google_error(&response)?;

            Ok(items
                .sub_item
                .into_iter()
                .filter_map(|a| {
                    a.title
                        .zip(a.annotations.and_then(|a| {
                            a.annotation_link
                                .and_then(|a| a.resolved_link)
                                .and_then(|a| a.browse_url)
                        }))
                        .map(|(title, browse_url)| Category {
                            images: a.image.into_iter().filter_map(|a| a.image_url).collect(),
                            cat_type,
                            browse_url,
                            title,
                        })
                })
                .collect())
        }
    }

    /// fetch search suggestions for a string query
    ///
    /// # Examples
    #[doc = async_doc!(r#"let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
let suggestions = client.search_suggest("robl").await?;"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn search_suggest<A: AsRef<str> + Send>(
        &self,
        query: A,
    ) -> impl Future<Output = Result<Vec<SearchSuggestEntry>, SearchSuggestionError>> + Send {
        async move {
            let headers = [("User-Agent", consts::LEGACY_USERAGENT)];
            let params = [
                ("q", query.as_ref()),
                ("ssis", "120"),
                ("sb", "5"),
                ("sst", "2"),
                ("c", "3"),
            ];

            let request = self.requester().await?.headers(&headers).params(&params);
            let mut response = request.fdfe_request("searchSuggest", None).await?;

            let response = response
                .payload
                .take()
                .and_then(|a| a.search_suggest_response)
                .map(|a| a.entry)
                .into_google_error(&response)?;

            Ok(response)
        }
    }

    /// fetch search results for a string query, optionally continuing a past page
    ///
    /// # Examples
    #[doc = async_doc!(r#"let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;
let single_search = client.search("robl", None).await?;
let single_search2 = client.search("robl", single_search.next_page).await?;"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn search<A: AsRef<str> + Send>(
        &self,
        query: A,
        next_page_url: Option<NextSearchPage>,
    ) -> impl Future<Output = Result<SearchResults, SearchError>> + Send {
        async move {
            let (payload, next_page, response) = if let Some(next_page_url) = next_page_url {
                let request = self.requester().await?;
                let mut response = request.fdfe_request(&next_page_url.0, None).await?;

                (response.payload.take(), None, response)
            } else {
                let params = [("q", query.as_ref()), ("ksm", "1"), ("c", "3")];

                let request = self.requester().await?.params(&params);
                let mut response = request.fdfe_request("search", None).await?;

                (
                    response
                        .pre_fetch
                        .take()
                        .and_then(|a| a.response)
                        .and_then(|a| a.payload),
                    Some(
                        response
                            .payload
                            .take()
                            .and_then(|a| a.search_response)
                            .and_then(|a| a.next_page_url)
                            .map(NextSearchPage),
                    ),
                    response,
                )
            };

            let next_page = next_page.unwrap_or_else(|| {
                payload
                    .as_ref()
                    .and_then(|a| a.list_response.as_ref())
                    .and_then(|a| a.item.as_ref())
                    .and_then(|a| a.container_metadata.as_ref())
                    .and_then(|a| a.next_page_url.clone())
                    .map(NextSearchPage)
            });

            let items = payload
                .and_then(|a| a.list_response)
                .and_then(|a| a.item)
                .map(|a| {
                    a.sub_item
                        .into_iter()
                        .filter_map(|mut a| a.sub_item.pop())
                        .collect::<Vec<_>>()
                })
                .into_google_error(&response)?;

            Ok(SearchResults { next_page, items })
        }
    }

    /// returns a stream that yields pages of search results, automatically handling pagination
    ///
    /// # Examples
    #[doc = async_doc!(r#"use futures_util::TryStreamExt;
let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;

let mut search_stream = client.search_stream("robl");
# let mut count = 0;
while let Some(page) = search_stream.try_next().await? {
    # count += 1;
    # if count >= 3 {
    #   break
    # }

    for item in page {
        println!("Found app: {:?}", item.title);
    }
}"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn search_stream<'a, A: AsRef<str> + Send + 'a>(
        &'a self,
        query: A,
    ) -> impl Stream<Item = Result<Vec<Item>, SearchError>> + Send + 'a {
        Box::pin(try_stream! {
            let mut next_page: Option<NextSearchPage> = None;
            loop {
                let result = self.search(query.as_ref(), next_page).await?;
                yield result.items;

                next_page = result.next_page;
                if next_page.is_none() {
                    break;
                }
            }
        })
    }

    /// fetch reviews for a specific package name, optionally continuing a past page
    ///
    /// note that not setting a filter will cause google to return an error for next pages
    ///
    /// # Examples
    #[doc = async_doc!(r#"let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;

let reviews = client
    .reviews("com.roblox.client", Some(&gpipipi::ReviewsFilter::Newest), None)
    .await?;

let reviews_page2 = client
    .reviews("com.roblox.client", Some(&gpipipi::ReviewsFilter::Newest), reviews.next_page)
    .await?;"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn reviews<A: AsRef<str> + Send>(
        &self,
        package_name: A,
        filter: Option<&ReviewsFilter>,
        next_page_url: Option<NextReviewsPage>,
    ) -> impl Future<Output = Result<ReviewsResults, ReviewsError>> + Send {
        async move {
            let (reviews_response, next_page, response) = if let Some(next_page_url) = next_page_url
            {
                let request = self.requester().await?;
                let mut response = request.fdfe_request(&next_page_url.0, None).await?;

                let review_response = response.payload.take().and_then(|a| a.review_response);
                let next_page = review_response
                    .as_ref()
                    .and_then(|a| a.next_page_url.clone())
                    .map(NextReviewsPage);

                (review_response, next_page, response)
            } else {
                let params = [
                    ("doc", package_name.as_ref()),
                    filter.map_or(("", ""), |filter| match filter {
                        ReviewsFilter::All => ("sfilter", "ALL"),
                        ReviewsFilter::Newest => ("sort", "0"),
                        ReviewsFilter::Positive => ("sent", "1"),
                        ReviewsFilter::Critical => ("sent", "2"),
                    }),
                ];

                let request = self.requester().await?.params(&params);
                let mut response = request.fdfe_request("rev", None).await?;

                let review_response = response.payload.take().and_then(|a| a.review_response);

                let next_page = review_response
                    .as_ref()
                    .and_then(|a| a.next_page_url.clone())
                    .map(NextReviewsPage);

                (review_response, next_page, response)
            };

            let reviews = reviews_response
                .and_then(|a| a.user_reviews_response)
                .map(|a| a.review)
                .into_google_error(&response)?;

            Ok(ReviewsResults { next_page, reviews })
        }
    }

    /// returns a stream that yields pages of reviews, automatically handling pagination
    ///
    /// # Examples
    #[doc = async_doc!(r#"use futures_util::TryStreamExt;
let client = gpipipi::LongLivedClient::login(email, aas_token, props).await?;

let mut reviews_stream = client
    .reviews_stream("com.roblox.client", Some(gpipipi::ReviewsFilter::Newest));

# let mut count = 0;
while let Some(page) = reviews_stream.try_next().await? {
    # count += 1;
    # if count >= 3 {
    #   break
    # }

    for review in page {
        println!("{:?} stars: {:?}", review.star_rating, review.comment);
    }
}"#)]
    ///
    /// # Errors
    /// - `Props` - internal error for missing required device props
    /// - `Request` - error from the http client
    /// - `Google` - error from google
    fn reviews_stream<'a, A: AsRef<str> + Send + 'a>(
        &'a self,
        package_name: A,
        filter: Option<ReviewsFilter>,
    ) -> impl Stream<Item = Result<Vec<Review>, ReviewsError>> + Send + 'a {
        Box::pin(try_stream! {
            let mut next_page: Option<NextReviewsPage> = None;
            loop {
                let result = self.reviews(package_name.as_ref(), filter.as_ref(), next_page).await?;
                yield result.reviews;

                next_page = result.next_page;
                if next_page.is_none() {
                    break;
                }
            }
        })
    }
}

async fn latest_version<A: Client + ?Sized>(
    client: &A,
    package_name: &str,
) -> Result<i64, DetailsError> {
    let response = client
        .details(package_name, None)
        .await?
        .version_code
        .into_google_error_map(|| "no version was returned by google".to_string())?;

    Ok(response)
}

/// a url for a specific file, with a filename and a sha1 hash
#[derive(Debug)]
pub struct CdnUrl {
    pub filename: String,
    pub sha1: String,
    pub url: String,
}

/// response for an app, contains the base apk and any additional splits and obbs
#[derive(Debug)]
pub struct DownloadResponse {
    pub splits: Vec<CdnUrl>,
    pub obbs: Vec<CdnUrl>,
    pub base: CdnUrl,
}

/// a category type for apps
#[derive(Debug, Clone, Copy)]
pub enum CategoryType {
    Application,
    Game,
    Family,
}

/// a category
#[derive(Debug)]
pub struct Category {
    pub cat_type: CategoryType,
    pub images: Vec<String>,
    pub browse_url: String,
    pub title: String,
}

/// search results for a query, optionally containing an identifier for the next page
#[derive(Debug)]
pub struct SearchResults {
    pub next_page: Option<NextSearchPage>,
    pub items: Vec<Item>,
}

/// unique identifier for a next search page
#[derive(Debug)]
pub struct NextSearchPage(String);

/// filter for reviews
#[derive(Debug)]
pub enum ReviewsFilter {
    All,
    Newest,
    Positive,
    Critical,
}

/// review results for an app, optionally containing an identifier for the next page
#[derive(Debug)]
pub struct ReviewsResults {
    pub next_page: Option<NextReviewsPage>,
    pub reviews: Vec<Review>,
}

/// unique identifier for a next reviews page
#[derive(Debug)]
pub struct NextReviewsPage(String);