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.

85 lines
2.7KB

  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.clone())
  41. .json(&payload)
  42. .send().await;
  43. if let Ok(response) = result {
  44. //println!("Resp: {}", response.text().await.unwrap());
  45. let res = response.json::<AuthenticationInfo>().await;
  46. if let Ok(auth) = &res {
  47. self.auth = Some(auth.clone());
  48. }
  49. return res;
  50. }
  51. /*let result = self.client.post(url)
  52. .json(&payload)
  53. .send().await;*/
  54. Err(result.err().unwrap())
  55. }
  56. // TODO username authentication
  57. /// Retrieve lobby information for all active Cardlife servers
  58. pub async fn lobbies(&self) -> Result<LobbyInfo, Error> {
  59. let url = Url::parse(LOBBY_DOMAIN)
  60. .unwrap()
  61. .join("/api/client/games")
  62. .unwrap();
  63. let public_id;
  64. if let Some(auth) = &self.auth {
  65. public_id = auth.public_id.clone();
  66. } else {
  67. public_id = "".to_string();
  68. }
  69. let payload = LobbyPayload{public_id};
  70. let result = self.client.post(url).json(&payload).send().await;
  71. if let Ok(response) = result {
  72. return response.json::<LobbyInfo>().await;
  73. }
  74. Err(result.err().unwrap())
  75. }
  76. }