An unofficial collection of APIs used in FreeJam games and mods
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5KB

  1. use reqwest::{Client, Error};
  2. use url::{Url};
  3. use crate::cardlife::{AuthenticationInfo, AuthenticationPayload, LobbyInfo, LobbyPayload};
  4. const AUTHENTICATION_DOMAIN: &str = "https://live-auth.cardlifegame.com/";
  5. const LOBBY_DOMAIN: &str = "https://live-lobby.cardlifegame.com/";
  6. /// Cardlife live information API
  7. pub struct LiveAPI {
  8. client: Client,
  9. auth: Option<AuthenticationInfo>,
  10. }
  11. impl LiveAPI {
  12. /// Create a new instance
  13. pub fn new() -> LiveAPI {
  14. LiveAPI {
  15. client: Client::new(),
  16. auth: None,
  17. }
  18. }
  19. /// Create a new instance and login using email
  20. pub async fn login_email(email: &str, password: &str) -> Result<LiveAPI, Error> {
  21. let mut instance = LiveAPI::new();
  22. let result = instance.authenticate_email(email, password).await;
  23. if let Ok(response) = result {
  24. instance.auth = Some(response);
  25. return Ok(instance);
  26. } else {
  27. return Err(result.err().unwrap());
  28. }
  29. }
  30. /// Login using email and password
  31. pub async fn authenticate_email(&mut self, email: &str, password: &str) -> Result<AuthenticationInfo, Error> {
  32. let url = Url::parse(AUTHENTICATION_DOMAIN)
  33. .unwrap()
  34. .join("/api/auth/authenticate")
  35. .unwrap();
  36. let payload = AuthenticationPayload {
  37. email_address: email.to_string(),
  38. password: password.to_string()
  39. };
  40. let result = self.client.post(url)
  41. .json(&payload)
  42. .send().await;
  43. if let Ok(response) = result {
  44. let res = response.json::<AuthenticationInfo>().await;
  45. if let Ok(auth) = &res {
  46. self.auth = Some(auth.clone());
  47. }
  48. return res;
  49. }
  50. Err(result.err().unwrap())
  51. }
  52. // TODO username authentication
  53. /// Retrieve lobby information for all active Cardlife servers
  54. pub async fn lobbies(&self) -> Result<LobbyInfo, Error> {
  55. let url = Url::parse(LOBBY_DOMAIN)
  56. .unwrap()
  57. .join("/api/client/games")
  58. .unwrap();
  59. let public_id;
  60. if let Some(auth) = &self.auth {
  61. public_id = auth.public_id.clone();
  62. } else {
  63. public_id = "".to_string();
  64. }
  65. let payload = LobbyPayload{public_id};
  66. let result = self.client.post(url).json(&payload).send().await;
  67. if let Ok(response) = result {
  68. return response.json::<LobbyInfo>().await;
  69. }
  70. Err(result.err().unwrap())
  71. }
  72. }