itchio-api 0.3.0

Easily interact with the itch.io server-side API
Documentation
use chrono::{DateTime, Utc};
use serde::Deserialize;

use crate::{Itchio, ItchioError, User, parsers::date_from_str};

/// The original response this crate gets from the server, useless to crate users.
#[derive(Clone, Debug, Deserialize)]
struct WrappedDownloadKey {
  download_key: DownloadKey
}

/// An Object containing all the information regarding a download key, including the key itself.
#[derive(Clone, Debug, Deserialize)]
pub struct DownloadKey {
  pub id: u64,
  #[serde(deserialize_with = "date_from_str")]
  pub created_at: DateTime<Utc>,
  pub downloads: u64,
  pub key: String,
  pub game_id: u32,
  /// Is `None` if the key has not been claimed
  pub owner: Option<User>,
}

impl Itchio {
  /// Get a download key: <https://itch.io/docs/api/serverside#reference/gameviewpurchases-httpsitchioapi1keygamegame-iddownload-keys>
  pub async fn get_download_key(&self, game_id: u32, lookup: &str, property_name: &str) -> Result<DownloadKey, ItchioError> {
    let url = format!("game/{}/download_keys?{}={}", game_id, property_name, lookup);
    let response = self.request::<WrappedDownloadKey>(url).await?;
    Ok(response.download_key)
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::env;
  use dotenv::dotenv;

  #[tokio::test]
  async fn good() {
    dotenv().ok();
    let client_secret = env::var("KEY").expect("KEY has to be set");
    let key_string = env::var("DOWNLOAD_KEY").expect("DOWNLOAD_KEY has to be set");
    let api = Itchio::new(client_secret).unwrap();
    let download_key = api.get_download_key(
      2295061,
      key_string.as_str(),
      "download_key"
    ).await.inspect_err(|err| eprintln!("Error spotted: {}", err));
    assert!(download_key.is_ok())
  }

  #[tokio::test]
  async fn bad_key() {
    dotenv().ok();
    let key_string = env::var("DOWNLOAD_KEY").expect("DOWNLOAD_KEY has to be set");
    let api = Itchio::new("bad_key".to_string()).unwrap();
    let download_key = api.get_download_key(
      2295061,
      key_string.as_str(),
      "download_key"
    ).await;
    assert!(download_key.is_err_and(|err| matches!(err, ItchioError::BadKey)))
  }
}