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
pub use self::error::{Error, Result};
use log::info;
use reqwest::Client;
use serde::Deserialize;

mod error; //TODO: Rename

/// A single logged in instance of a logged in Star Realms user
#[derive(Debug, Clone)]
pub struct StarRealms {
    pub token: Token,
    core_version: usize,
    client: Client,
}


impl StarRealms {
    /// Create a new instance of StarRealms using a user's Username and Password to login.
    /// Password is not retained internally and is sent via HTTPS connection to official Star Realms servers
    pub async fn new(username: &str, password: &str) -> Result<StarRealms> {
        let mut sr = StarRealms {
            token: Token::default(),
            core_version: 45,
            client: reqwest::Client::new(),
        };
        sr.new_token(username, password).await?;
        sr.find_core_version().await?;
        Ok(sr)
    }

    /// Create a new instance of StarRealms using a user's token. The required token is Token2 from the token response from the server.
    /// As we don't get a token, we also don't have other data available that is usually provided when retrieving a token, such as purchases.
    pub async fn new_with_token2_str(token: &str) -> Result<StarRealms> {
        let mut sr = StarRealms {
            token: Token::default(),
            core_version: 45,
            client: reqwest::Client::new(),
        };
        sr.token.token2 = token.to_string();
        sr.find_core_version().await?;
        Ok(sr)
    }

    /// Create a new instance of StarRealms using a previously made Token.
    pub async fn new_with_token(token: Token) -> Result<StarRealms> {
        let mut sr = StarRealms {
            token: token,
            core_version: 45,
            client: reqwest::Client::new(),
        };
        sr.find_core_version().await?;
        Ok(sr)
    }

    /// Gets a login token using the username and password.
    /// This token doesn't seem to expire
    async fn new_token(&mut self, username: &str, password: &str) -> Result<()> {
        let params = [("username", username), ("password", password)];
        let res = self
            .client
            .post("https://srprodv2.whitewizardgames.com/Account/Login")
            .form(&params)
            .send()
            .await?;
        if res.status() != 200 {
            return Err(Error::InvalidAPIResponse(res.status().to_string()));
        }
        self.token = res.json().await?;
        Ok(())
    }

    /// Get the latest core version via trial and error
    /// Incorrect core version causes empty or invalid responses for other calls
    async fn find_core_version(&mut self) -> Result<()> {
        //TODO: Improve, as maybe multiple core versions are needed
        for core_version in 45..100 {
            let res = self
                .client
                .get("https://srprodv2.whitewizardgames.com/NewGame/ListActivitySortable")
                .header("Auth", &self.token.token2)
                .header("coreversion", core_version)
                .send()
                .await?;
            if res.status() == 200 {
                self.core_version = core_version;
                info!("Found core version: {}", self.core_version);
                return Ok(());
            }
        }
        Err(Error::UnknownCoreVersion())
    }

    /// Get the latest user activity, including current player data
    pub async fn activity(&self) -> Result<Activity> {
        let res = self
            .client
            .get("https://srprodv2.whitewizardgames.com/NewGame/ListActivitySortable")
            .header("Auth", &self.token.token2)
            .header("coreversion", self.core_version)
            .send()
            .await?;
        if res.status() != 200 {
            return Err(Error::InvalidAPIResponse(res.status().to_string()));
        }
        Ok(res.json().await?)
    }

}

//TODO: More rust friendly names?
#[derive(Default, Deserialize, Debug, Clone)]
pub struct Token {
    #[serde(rename = "name")]
    pub username: String,
    pub id: usize,
    pub token1: String,
    pub token2: String,
    pub purchases: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct Activity {
    pub acceptedterms: bool,
    pub avatar: String,
    pub rankstars: i64,
    pub ranktotalstars: i64,
    pub level: i64,
    pub arenatrophystars: i64,
    pub hasfreearena: bool,
    pub pendingrewards: ::serde_json::Value, //TODO: Find what this is
    pub queues: Vec<::serde_json::Value>,    //TODO: Find what this is
    pub challenges: Vec<Challenge>,
    pub activegames: Vec<Game>,
    pub finishedgames: Vec<Game>,
    pub result: String,
}

//TODO: Merge ActiveGame and FinishedGame under "Game"
#[derive(Debug, Deserialize)]
pub struct Game {
    #[serde(rename = "gameid")]
    pub id: i64,
    pub timing: String,
    pub mmdata: String,     //TODO: Change this into a struct
    pub clientdata: String, //TODO: Change this into a struct
    pub opponentname: String,
    #[serde(default)]
    pub actionneeded: bool,
    #[serde(default)]
    pub endreason: i64, //TODO: Figure out what these are. 2 == concede
    #[serde(default)]
    pub won: bool,
    pub lastupdatedtime: String, //TODO: Change to chrono time?
    pub isleaguegame: bool,
    pub istournamentgame: bool,
}

impl Game {
    //TODO: Replace with a better method
    pub fn is_finished(&self) -> bool {
        self.endreason == 0 && !self.won && !self.actionneeded
    }
}

#[derive(Debug, Deserialize)]
pub struct Challenge {
    #[serde(rename = "challengeid")]
    pub id: i64,
    pub challengername: String,
    pub challengercommander: String,
    pub opponentname: String,
    pub mmdata: String,
    pub status: String, //TODO: Change to enum?
    pub statusdescription: String,
    pub lastupdatedtime: String,
    pub timing: String, //TODO: Change to enum?
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    fn init() {
        let _ = env_logger::builder().is_test(true).try_init();
        dotenv::dotenv().ok();
    }

    #[tokio::test]
    async fn new_star_realms_test() -> Result<()> {
        init();
        StarRealms::new(
            env::var("SR_USERNAME").unwrap().as_str(),
            env::var("SR_PASSWORD").unwrap().as_str(),
        )
        .await?;
        Ok(())
    }

    #[tokio::test]
    async fn username_test() -> Result<()> {
        init();
        let sr = StarRealms::new(
            env::var("SR_USERNAME").unwrap().as_str(),
            env::var("SR_PASSWORD").unwrap().as_str(),
        )
        .await?;
        assert_eq!(env::var("SR_USERNAME").unwrap().to_ascii_lowercase(), sr.token.username.to_ascii_lowercase());
        Ok(())
    }

    #[tokio::test]
    #[should_panic]
    async fn incorrect_login_test() {
        init();
        StarRealms::new("fakeuser123", "fakepass123").await.unwrap();
    }

    #[tokio::test]
    async fn list_activity_test() -> Result<()> {
        init();
        let sr = StarRealms::new(
            env::var("SR_USERNAME").unwrap().as_str(),
            env::var("SR_PASSWORD").unwrap().as_str(),
        )
        .await?;
        sr.activity().await?;
        Ok(())
    }

    // #[tokio::test]
    // async fn list_active_games_test() -> Result<()> {
    //     init();
    //     let sr = StarRealms::new(
    //         env::var("SR_USERNAME").unwrap().as_str(),
    //         env::var("SR_PASSWORD").unwrap().as_str(),
    //     )
    //     .await?;
    //     let activity = sr.activity().await?;
    //     assert!(activity.activegames.len()>=1);
    //     Ok(())
    // }
}