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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use std::borrow::Cow;

use de_lobby_model::{
    Game, GameListing, GamePlayerInfo, GameSetup, Token, UserWithPassword, UsernameAndPassword,
};
use reqwest::{header::HeaderValue, Method, Request};
use serde::Serialize;
use url::Url;

use crate::requestable::{LobbyRequest, LobbyRequestCreator};

pub struct SignUpRequest(UserWithPassword);

impl SignUpRequest {
    pub fn new(params: UserWithPassword) -> Self {
        Self(params)
    }
}

impl LobbyRequest for SignUpRequest {
    type Response = Token;
}

impl LobbyRequestCreator for SignUpRequest {
    fn path(&self) -> Cow<str> {
        "/p/auth/sign-up".into()
    }

    fn create(&self, url: Url) -> Request {
        let mut request = Request::new(Method::POST, url);
        json(&mut request, &self.0);
        request
    }
}

pub struct SignInRequest(UsernameAndPassword);

impl SignInRequest {
    pub fn new(params: UsernameAndPassword) -> Self {
        Self(params)
    }
}

impl LobbyRequest for SignInRequest {
    type Response = Token;
}

impl LobbyRequestCreator for SignInRequest {
    fn path(&self) -> Cow<str> {
        "/p/auth/sign-in".into()
    }

    fn create(&self, url: Url) -> Request {
        let mut request = Request::new(Method::POST, url);
        json(&mut request, &self.0);
        request
    }
}

pub struct CreateGameRequest(GameSetup);

impl CreateGameRequest {
    pub fn new(setup: GameSetup) -> Self {
        Self(setup)
    }
}

impl LobbyRequest for CreateGameRequest {
    type Response = ();
}

impl LobbyRequestCreator for CreateGameRequest {
    fn path(&self) -> Cow<str> {
        "/a/games".into()
    }

    fn create(&self, url: Url) -> Request {
        let mut request = Request::new(Method::POST, url);
        json(&mut request, &self.0);
        request
    }
}

pub struct ListGamesRequest;

impl LobbyRequest for ListGamesRequest {
    type Response = GameListing;
}

impl LobbyRequestCreator for ListGamesRequest {
    fn path(&self) -> Cow<str> {
        "/a/games".into()
    }

    fn create(&self, url: Url) -> Request {
        Request::new(Method::GET, url)
    }
}

pub struct GetGameRequest(String);

impl GetGameRequest {
    pub fn new(id: impl ToString) -> Self {
        Self(id.to_string())
    }
}

impl LobbyRequest for GetGameRequest {
    type Response = Game;
}

impl LobbyRequestCreator for GetGameRequest {
    fn path(&self) -> Cow<str> {
        encode(&["a", "games", self.0.as_str()])
    }

    fn create(&self, url: Url) -> Request {
        Request::new(Method::GET, url)
    }
}

pub struct JoinGameRequest {
    game: String,
    player: GamePlayerInfo,
}

impl JoinGameRequest {
    pub fn new(game: String, player: GamePlayerInfo) -> Self {
        Self { game, player }
    }
}

impl LobbyRequest for JoinGameRequest {
    type Response = ();
}

impl LobbyRequestCreator for JoinGameRequest {
    fn path(&self) -> Cow<str> {
        encode(&["a", "games", self.game.as_str(), "join"])
    }

    fn create(&self, url: Url) -> Request {
        let mut request = Request::new(Method::PUT, url);
        json(&mut request, &self.player);
        request
    }
}

pub struct LeaveGameRequest(String);

impl LeaveGameRequest {
    pub fn new(name: String) -> Self {
        Self(name)
    }
}

impl LobbyRequest for LeaveGameRequest {
    type Response = ();
}

impl LobbyRequestCreator for LeaveGameRequest {
    fn path(&self) -> Cow<str> {
        encode(&["a", "games", self.0.as_str(), "leave"])
    }

    fn create(&self, url: Url) -> Request {
        Request::new(Method::PUT, url)
    }
}

fn json<T: Serialize>(request: &mut Request, content: &T) {
    request.headers_mut().insert(
        "Content-Type",
        HeaderValue::try_from("application/json").unwrap(),
    );
    *request.body_mut() = Some(serde_json::to_string(&content).unwrap().into());
}

fn encode(parts: &[&str]) -> Cow<'static, str> {
    let mut result = String::new();
    for part in parts {
        result.push('/');
        result.push_str(urlencoding::encode(part).as_ref());
    }
    result.into()
}

#[cfg(test)]
mod tests {
    use de_lobby_model::{GameConfig, GameMap, User};

    use super::*;

    #[test]
    fn test_encode() {
        assert_eq!(encode(&["ahoj", "svete"]), "/ahoj/svete");
        assert_eq!(encode(&["ahoj", "velky svete"]), "/ahoj/velky%20svete");
    }

    #[test]
    fn test_sign_up() {
        let request = SignUpRequest::new(UserWithPassword::new(
            "Obviously 123456".to_owned(),
            User::new("Indy".to_owned()),
        ));
        assert_eq!(request.path().as_ref(), "/p/auth/sign-up");

        let request = request.create(Url::parse("https://example.com/p/auth/sign-up").unwrap());
        assert_eq!(request.method().as_str(), "POST");
        assert_eq!(request.url().as_str(), "https://example.com/p/auth/sign-up");

        let body = String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap();
        let expected_body = r#"{"password":"Obviously 123456","user":{"username":"Indy"}}"#;
        assert_eq!(body, expected_body);
    }

    #[test]
    fn test_sign_in() {
        let request = SignInRequest::new(UsernameAndPassword::new(
            "Martin Indra".to_owned(),
            "Obviously 123456".to_owned(),
        ));
        assert_eq!(request.path().as_ref(), "/p/auth/sign-in");

        let request = request.create(Url::parse("https://example.com/p/auth/sign-in").unwrap());
        assert_eq!(request.method().as_str(), "POST");
        assert_eq!(request.url().as_str(), "https://example.com/p/auth/sign-in");

        let body = String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap();
        let expected_body = r#"{"username":"Martin Indra","password":"Obviously 123456"}"#;
        assert_eq!(body, expected_body);
    }

    #[test]
    fn test_create() {
        let config = GameConfig::new(
            "Druhá Hra".to_owned(),
            2,
            GameMap::new(
                "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_owned(),
                "custom".to_owned(),
            ),
        );
        let request =
            CreateGameRequest::new(GameSetup::new("127.0.0.1:8082".parse().unwrap(), config));
        assert_eq!(request.path().as_ref(), "/a/games");

        let request = request.create(Url::parse("http://example.com/a/games").unwrap());
        assert_eq!(request.method().as_str(), "POST");
        assert_eq!(request.url().as_str(), "http://example.com/a/games");

        let body = String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap();
        let expected_body = concat!(
            r#"{"server":"127.0.0.1:8082","config":{"name":"Druhá Hra","maxPlayers":2,"#,
            r#""map":{"hash":"#,
            r#""0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","#,
            r#""name":"custom"}}}"#
        );

        assert_eq!(body, expected_body);
    }

    #[test]
    fn test_join() {
        let request = JoinGameRequest::new("Cool Game".to_owned(), GamePlayerInfo::new(2));
        assert_eq!(request.path().as_ref(), "/a/games/Cool%20Game/join");

        let request = request.create(Url::parse("http://example.com/a/games/123/join").unwrap());
        let body = String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap();
        assert_eq!(body, r#"{"ordinal":2}"#);
    }

    #[test]
    fn test_leave() {
        let request = LeaveGameRequest::new("První Hra".to_owned());
        assert_eq!(request.path().as_ref(), "/a/games/Prvn%C3%AD%20Hra/leave");
    }
}