irelia_cli/
rest.rs

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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Module containing all the data for the rest LCU bindings

pub mod types;

use http_body_util::BodyExt;
use hyper::Uri;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::{utils::process_info::get_running_client, Error, RequestClient};

/// Struct representing a connection to the LCU
pub struct LcuClient {
    url: String,
    auth_header: String,
}

#[cfg(feature = "batched")]
pub mod batch {
    use crate::rest::LcuClient;
    use crate::{Error, RequestClient};
    use futures_util::StreamExt;
    use serde::de::DeserializeOwned;
    use std::borrow::Cow;

    /// Enum representing the different requests that can be sent to the LCU
    pub enum RequestType<'a> {
        Delete,
        Get,
        Patch(Option<&'a dyn erased_serde::Serialize>),
        Post(Option<&'a dyn erased_serde::Serialize>),
        Put(Option<&'a dyn erased_serde::Serialize>),
    }

    /// Struct representing a batched request, taking the
    /// request type and endpoint
    pub struct Request<'a> {
        pub request_type: RequestType<'a>,
        pub endpoint: Cow<'static, str>,
    }

    impl<'a> Request<'a> {
        /// Creates a new batched request, which can be wrapped in a slice and send to the LCU
        pub fn new(request_type: RequestType<'a>, endpoint: impl Into<Cow<'static, str>>) -> Self {
            Request {
                request_type,
                endpoint: endpoint.into(),
            }
        }

        pub fn delete(endpoint: impl Into<Cow<'static, str>>) -> Self {
            Self::new(RequestType::Delete, endpoint)
        }

        pub fn get(endpoint: impl Into<Cow<'static, str>>) -> Self {
            Self::new(RequestType::Get, endpoint)
        }

        pub fn patch(
            endpoint: impl Into<Cow<'static, str>>,
            body: Option<&'a dyn erased_serde::Serialize>,
        ) -> Self {
            Self::new(RequestType::Patch(body), endpoint)
        }

        pub fn put(
            endpoint: impl Into<Cow<'static, str>>,
            body: Option<&'a dyn erased_serde::Serialize>,
        ) -> Self {
            Self::new(RequestType::Put(body), endpoint)
        }

        pub fn post(
            endpoint: impl Into<Cow<'static, str>>,
            body: Option<&'a dyn erased_serde::Serialize>,
        ) -> Self {
            Self::new(RequestType::Post(body), endpoint)
        }
    }

    impl LcuClient {
        /// System for batching requests to the LCU by sending a slice
        /// The buffer size is how many requests can be operated on at
        /// the same time, returns a vector with all the replies
        ///
        /// # Errors
        /// The value will be an error if the provided type is invalid, or the LCU API is not running
        pub async fn batched<'a, R>(
            &self,
            requests: &[Request<'a>],
            buffer_size: usize,
            request_client: &RequestClient,
        ) -> Vec<Result<Option<R>, Error>>
        where
            R: DeserializeOwned,
        {
            futures_util::stream::iter(requests.iter().map(|request| async {
                let endpoint = &*request.endpoint;
                match &request.request_type {
                    RequestType::Delete => self.delete(endpoint, request_client).await,
                    RequestType::Get => self.get(endpoint, request_client).await,
                    RequestType::Patch(body) => self.patch(endpoint, *body, request_client).await,
                    RequestType::Post(body) => self.post(endpoint, *body, request_client).await,
                    RequestType::Put(body) => self.put(endpoint, *body, request_client).await,
                }
            }))
            .buffered(buffer_size)
            .collect()
            .await
        }
    }

    pub struct Builder;

    mod hidden {
        use crate::rest::batch::Request;
        use crate::rest::LcuClient;
        use crate::RequestClient;

        pub struct WithClient<'a> {
            pub(super) request_client: &'a RequestClient,
            pub(super) requests: Vec<Request<'a>>,
        }

        pub struct WithBufferSize<'a> {
            pub(super) request_client: &'a RequestClient,
            pub(super) requests: Vec<Request<'a>>,
            pub(super) buffer_size: usize,
        }

        pub struct WithLcuClient<'a> {
            pub(super) request_client: &'a RequestClient,
            pub(super) requests: Vec<Request<'a>>,
            pub(super) buffer_size: usize,
            pub(super) lcu_client: &'a LcuClient,
        }
    }

    use crate::rest::batch::hidden::WithLcuClient;
    use hidden::{WithBufferSize, WithClient};

    impl Builder {
        #[must_use]
        pub fn new() -> Self {
            Self
        }

        #[must_use]
        pub fn with_client(self, request_client: &RequestClient) -> WithClient {
            WithClient {
                request_client,
                requests: Vec::new(),
            }
        }

        #[must_use]
        pub fn with_client_and_capacity(
            self,
            request_client: &RequestClient,
            capacity: usize,
        ) -> WithClient {
            WithClient {
                request_client,
                requests: Vec::with_capacity(capacity),
            }
        }
    }

    impl Default for Builder {
        fn default() -> Self {
            Self
        }
    }

    impl<'a> WithClient<'a> {
        pub fn request(mut self, request: Request<'a>) -> Self {
            self.add_request(request);

            self
        }

        pub fn add_request(&mut self, request: Request<'a>) {
            self.requests.push(request);
        }

        pub fn with_buffer_size(self, buffer_size: usize) -> WithBufferSize<'a> {
            WithBufferSize {
                requests: self.requests,
                request_client: self.request_client,
                buffer_size,
            }
        }
    }

    impl<'a> WithBufferSize<'a> {
        pub fn with_lcu_client(self, lcu_client: &'a LcuClient) -> WithLcuClient<'a> {
            WithLcuClient {
                requests: self.requests,
                request_client: self.request_client,
                buffer_size: self.buffer_size,
                lcu_client,
            }
        }
    }

    impl<'a> WithLcuClient<'a> {
        pub async fn execute<R: DeserializeOwned>(self) -> Vec<Result<Option<R>, Error>> {
            self.lcu_client
                .batched(&self.requests, self.buffer_size, self.request_client)
                .await
        }
    }
}

impl LcuClient {
    /// Attempts to create a connection to the LCU, errors if it fails
    /// to spin up the child process, or fails to get data from the client.
    ///
    /// force_lock_file will read the lock file regardless of whether the client
    /// or the game is running at the time
    /// 
    /// # Errors
    /// This will return an error if the LCU API is not running, this can include
    /// the client being down, the lock file being unable to be opened, or the LCU
    /// not running at all
    pub fn new(force_lock_file: bool) -> Result<Self, Error> {
        let (port, pass) = get_running_client(force_lock_file)?;

        Ok(LcuClient {
            url: port,
            auth_header: pass,
        })
    }

    #[must_use]
    /// Creates a new LCU Client that implicitly trusts the port and auth string given,
    /// Encoding them in a URL and header respectively
    pub fn new_with_credentials(auth: &str, port: u16) -> LcuClient {
        LcuClient {
            url: format!("127.0.0.1:{port}"),
            auth_header: format!(
                "Basic {}",
                crate::utils::process_info::ENCODER.encode(format!("riot:{auth}"))
            ),
        }
    }

    /// Queries the client or lock file, getting a new url and auth header
    ///
    /// # Errors
    /// This will return an error if the lock file is inaccessible, or if
    /// the LCU is not running
    pub fn reconnect(&mut self, force_lock_file: bool) -> Result<(), Error> {
        let (port, pass) = get_running_client(force_lock_file)?;
        self.url = port;
        self.auth_header = pass;
        Ok(())
    }

    /// Sets the url and auth header according to the auth and port provided
    pub fn reconnect_with_credentials(&mut self, auth: &str, port: u16) {
        let port = format!("127.0.0.1:{port}");
        let pass = format!(
            "Basic {}",
            crate::utils::process_info::ENCODER.encode(format!("riot:{auth}"))
        );
        self.url = port;
        self.auth_header = pass;
    }

    #[must_use]
    /// Returns a reference to the URL in use
    pub fn url(&self) -> &str {
        &self.url
    }

    #[must_use]
    /// Returns a reference to the auth header in use
    pub fn auth_header(&self) -> &str {
        &self.auth_header
    }

    /// Sends a delete request to the LCU
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type is invalid
    pub async fn delete<R: DeserializeOwned>(
        &self,
        endpoint: impl AsRef<str>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error> {
        self.lcu_request::<(), R>(endpoint.as_ref(), "DELETE", None, request_client)
            .await
    }

    /// Sends a get request to the LCU
    /// ```
    /// let request_client = irelia::RequestClient::new();
    /// let lcu_client = irelia::rest::LcuClient::new(false)?;
    ///
    ///  let response: Option<serde_json::Value> = lcu_client.get("/example/endpoint/", &request_client)?;
    /// ```
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type is invalid
    pub async fn get<R: DeserializeOwned>(
        &self,
        endpoint: impl AsRef<str>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error> {
        self.lcu_request::<(), R>(endpoint.as_ref(), "GET", None, request_client)
            .await
    }
    
    /// Sends a head request to the LCU
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running
    pub async fn head<S>(
        &self,
        endpoint: impl AsRef<str>,
        request_client: &RequestClient,
    ) -> Result<hyper::Response<hyper::body::Incoming>, Error>
    {
        request_client.raw_request_template::<()>(&self.url, endpoint.as_ref(), "HEAD", None, Some(&self.auth_header))
            .await
    }

    /// Sends a patch request to the LCU
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type or body is invalid
    pub async fn patch<T, R>(
        &self,
        endpoint: impl AsRef<str>,
        body: Option<T>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error>
    where
        T: Serialize,
        R: DeserializeOwned,
    {
        self.lcu_request(endpoint.as_ref(), "PATCH", body, request_client)
            .await
    }

    /// Sends a post request to the LCU
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type or body is invalid
    pub async fn post<T, R>(
        &self,
        endpoint: impl AsRef<str>,
        body: Option<T>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error>
    where
        T: Serialize,
        R: DeserializeOwned,
    {
        self.lcu_request(endpoint.as_ref(), "POST", body, request_client)
            .await
    }

    /// Sends a put request to the LCU
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type or body is invalid
    pub async fn put<T, R>(
        &self,
        endpoint: impl AsRef<str>,
        body: Option<T>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error>
    where
        T: Serialize,
        R: DeserializeOwned,
    {
        self.lcu_request(endpoint.as_ref(), "PUT", body, request_client)
            .await
    }

    /// Fetches the schema from a remote endpoint, for example:
    /// <`https://raw.githubusercontent.com/dysolix/hasagi-types/main/swagger.json/`>
    ///
    /// # Errors
    ///
    /// This function will error if it fails to connect to the given remote,
    /// or if the given remote cannot be deserialized to match the `Schema` type
    pub async fn schema(remote: &'static str) -> Result<types::Schema, Error> {
        let uri = Uri::from_static(remote);
        // This creates a custom client, as the default hyper client used by Irelia needs a cert, and it has no use outside here
        let https = hyper_rustls::HttpsConnectorBuilder::new()
            .with_native_roots()
            .map_err(Error::StdIo)?
            .https_only()
            .enable_http1()
            .build();
        let client =
            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
                .build::<_, http_body_util::Full<hyper::body::Bytes>>(https);
        let mut request = client.get(uri).await.map_err(Error::HyperClientError)?;
        let tmp = request.body_mut();
        let body = tmp.collect().await.map_err(Error::HyperError)?.to_bytes();
        serde_json::from_slice(&body).map_err(Error::SerdeJsonError)
    }

    /// Makes a request to the LCU with an unspecified method, valid options being
    /// "PUT", "GET", "POST", "HEAD", "DELETE"
    ///
    /// # Errors
    /// This will return an error if the LCU API is not running, or the provided type or body is invalid
    pub async fn lcu_request<T: Serialize, R: DeserializeOwned>(
        &self,
        endpoint: &str,
        method: &str,
        body: Option<T>,
        request_client: &RequestClient,
    ) -> Result<Option<R>, Error> {
        request_client
            .request_template(
                &self.url,
                endpoint,
                method,
                body,
                Some(&self.auth_header),
                |bytes| {
                    let body = if bytes.is_empty() {
                        None
                    } else {
                        Some(serde_json::from_slice(&bytes)?)
                    };

                    Ok(body)
                },
            )
            .await
    }
}

#[cfg(feature = "batched")]
#[cfg(test)]
mod tests {
    use crate::{rest::LcuClient, RequestClient};

    #[tokio::test]
    async fn batch_test() {
        use crate::rest::{
            batch::{Request, RequestType},
            LcuClient,
        };

        let page = serde_json::json!(
            {
              "blocks": [
                {
                  "items": [
                    {
                      "count": 1,
                      "id": "3153"
                    },
                  ],
                  "type": "Final Build"
                }
              ],
              "title": "Test Build",
            }
        );
        let client = RequestClient::new();

        let lcu_client = LcuClient::new(false).unwrap();

        let request: serde_json::Value = lcu_client
            .get("/lol-summoner/v1/current-summoner", &client)
            .await
            .unwrap()
            .unwrap();

        let id = &request["summonerId"];

        let endpoint = format!("/lol-item-sets/v1/item-sets/{id}/sets");

        let mut json: serde_json::Value = lcu_client
            .get(endpoint.as_str(), &client)
            .await
            .unwrap()
            .unwrap();

        json["itemSets"].as_array_mut().unwrap().push(page);

        let req = Request {
            request_type: RequestType::Put(Some(&json)),
            endpoint: format!("/lol-item-sets/v1/item-sets/{id}/sets").into(),
        };

        let result = lcu_client
            .batched::<serde_json::Value>(&[req], 1, &client)
            .await;

        println!("{result:?}");

        let a = lcu_client
            .put::<_, serde_json::Value>(
                format!("/lol-item-sets/v1/item-sets/{id}/sets"),
                Some(json),
                &client,
            )
            .await;
        println!("{a:?}");
    }

    #[tokio::test]
    async fn test_schema_des() {
        let _schema = LcuClient::schema(
            "https://raw.githubusercontent.com/dysolix/hasagi-types/main/swagger.json",
        )
        .await
        .unwrap();
    }
}