Skip to main content

itchio_api/
purchases.rs

1use chrono::{DateTime, Utc};
2use serde::Deserialize;
3
4use crate::{Itchio, ItchioError, parsers::date_from_str};
5
6/// The original response this crate gets from the server, useless to crate users.
7#[derive(Clone, Debug, Deserialize)]
8struct WrappedPurchases {
9  purchases: Vec<Purchase>
10}
11
12/// A representation of a purchase made on itch.io.
13#[derive(Clone, Debug, Deserialize)]
14pub struct Purchase {
15  pub id: u64,
16  #[serde(deserialize_with = "date_from_str")]
17  pub created_at: DateTime<Utc>,
18  pub game_id: u32,
19  pub sale_rate: u64,
20  /// Is true for any purchase that doesn’t have a download key associated with it, currently this only applies to web games
21  pub donation: bool,
22  pub price: String,
23  pub source: String,
24  pub email: String,
25}
26
27impl Itchio {
28  /// Gets the successful purchases from someone on a given game: <https://itch.io/docs/api/serverside#reference/gameviewpurchases-httpsitchioapi1keygamegame-idpurchases>
29  pub async fn get_purchases(&self, game_id: u32, lookup: &str, property_name: &str) -> Result<Vec<Purchase>, ItchioError> {
30    let url = format!("game/{}/purchases?{}={}", game_id, property_name, lookup);
31    let response = self.request::<WrappedPurchases>(url).await?;
32    Ok(response.purchases)
33  }
34}
35
36#[cfg(test)]
37mod tests {
38  use super::*;
39  // use std::env;
40  // use dotenv::dotenv;
41
42  // No one's ever purchased one of my games so I'm unable to test this, lol
43
44  // #[tokio::test]
45  // async fn good() {
46  //   dotenv().ok();
47  //   let client_secret = env::var("KEY").expect("KEY has to be set");
48  //   let api = Itchio::new(client_secret).unwrap();
49  //   let purchases = api.get_purchases(
50  //     2295061,
51  //     "someone@somewhere.thatdoesnotexist",
52  //     "email"
53  //   ).await.inspect_err(|err| eprintln!("Error spotted: {}", err));
54  //   assert!(purchases.is_ok())
55  // }
56
57  #[tokio::test]
58  async fn bad_key() {
59    let api = Itchio::new("bad_key".to_string()).unwrap();
60    let purchases = api.get_purchases(
61      2295061,
62      "someone@somewhere.thatdoesnotexist",
63      "email"
64    ).await;
65    assert!(purchases.is_err_and(|err| matches!(err, ItchioError::BadKey)))
66  }
67}