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
//! Helix endpoints or the [New Twitch API](https://dev.twitch.tv/docs/api)
use serde::{Deserialize, Serialize};
use std::{convert::TryInto, io, sync::Arc};
use tokio::sync;
use twitch_oauth2::TwitchToken;

pub mod channel;
pub mod clips;
pub mod moderation;
pub mod streams;
pub mod users;

pub use twitch_oauth2::Scope;

/// Client for Helix or the [New Twitch API](https://dev.twitch.tv/docs/api)
#[derive(Clone)]
pub struct HelixClient {
    token: Arc<sync::RwLock<Box<dyn TwitchToken + Send + Sync>>>,
    client: reqwest::Client,
    // TODO: Implement rate limiter...
}

impl HelixClient {
    /// Create a new client with a default [reqwest::Client]
    pub fn new<T>(token: Box<T>) -> HelixClient
    where T: TwitchToken + Sized + Send + Sync + 'static {
        let client = reqwest::Client::new();
        HelixClient {
            token: Arc::new(sync::RwLock::new(token)),
            client,
        }
    }

    /// Retrieve a clone of the [reqwest::Client] inside this [HelixClient]
    pub fn clone_client(&self) -> reqwest::Client { self.client.clone() }

    /// Get a [tokio::time::Delay] that will return when the token attached to this client expires
    pub async fn monitor_expire(&self) -> Option<tokio::time::Delay> {
        self.token()
            .await
            .as_ref()
            .expires()
            .map(tokio::time::Instant::from_std)
            .map(tokio::time::delay_until)
    }

    /// Access the underlying [TwitchToken] from this client
    pub async fn token(&self) -> sync::RwLockReadGuard<'_, Box<dyn TwitchToken + Send + Sync>> {
        self.token.read().await
    }

    /// Access the underlying [TwitchToken] from this client
    pub async fn validate_token(
        &self,
    ) -> Result<twitch_oauth2::ValidatedToken, twitch_oauth2::ValidationError> {
        let t = self.token().await;
        t.validate_token().await
    }

    /// Refresh the underlying [TwitchToken]
    pub async fn refresh_token(&self) -> Result<(), twitch_oauth2::RefreshTokenError> {
        let mut token = self.token.write().await;
        token.as_mut().refresh_token().await?;
        Ok(())
    }

    /// Request on a valid [Request] endpoint
    ///
    /// ```rust,no_run
    /// # #[tokio::main]
    /// # async fn main() {
    /// #   use twitch_api2::helix::{HelixClient, channel};
    /// #   let token = Box::new(twitch_oauth2::UserToken::from_existing_unchecked(
    /// #       twitch_oauth2::AccessToken::new("totallyvalidtoken".to_string()), None,
    /// #       twitch_oauth2::ClientId::new("validclientid".to_string()), None, None));
    ///     let req = channel::GetChannelRequest::builder().broadcaster_id("").build();
    ///     let client = HelixClient::new(token);
    ///     let response = client.req_get(req).await;
    /// # }
    /// # // fn main() {run()}
    /// ```
    #[allow(clippy::needless_doctest_main)]
    pub async fn req_get<R, D>(&self, request: R) -> Result<Response<R, D>, RequestError>
    where
        R: Request<Response = D> + Request + RequestGet,
        D: serde::de::DeserializeOwned, {
        #[derive(PartialEq, Deserialize, Debug)]
        struct InnerResponse<D> {
            data: Vec<D>,
            /// A cursor value, to be used in a subsequent request to specify the starting point of the next set of results.
            #[serde(default)]
            pagination: Pagination,
        }
        #[derive(Deserialize, Clone, Debug)]
        pub struct HelixRequestError {
            error: String,
            status: u16,
            message: String,
        }

        let url = url::Url::parse(&format!(
            "{}{}?{}",
            crate::TWITCH_HELIX_URL,
            <R as Request>::PATH,
            request.query()?
        ))?;

        let token = self.token().await;
        let req = self
            .client
            .get(url.clone())
            .header("Client-ID", token.client_id().as_str())
            .bearer_auth(token.token().secret())
            .send()
            .await?;
        let text = req.text().await?;
        //eprintln!("\n\nmessage is ------------ {} ------------", text);
        if let Ok(HelixRequestError {
            error,
            status,
            message,
        }) = serde_json::from_str::<HelixRequestError>(&text)
        {
            return Err(RequestError::HelixRequestError {
                error,
                status: status
                    .try_into()
                    .unwrap_or_else(|_| reqwest::StatusCode::BAD_REQUEST),
                message,
                url,
            });
        }
        let response: InnerResponse<D> = serde_json::from_str(&text)?;
        Ok(Response {
            data: response.data,
            pagination: response.pagination,
            request,
        })
    }
}

/// A request is a Twitch endpoint, see [New Twitch API](https://dev.twitch.tv/docs/api/reference) reference
#[async_trait::async_trait]
pub trait Request: serde::Serialize {
    /// The path to the endpoint relative to the helix root. eg. `channels` for [Get Channel Information](https://dev.twitch.tv/docs/api/reference#get-channel-information)
    const PATH: &'static str;
    /// Scopes needed by this endpoint
    const SCOPE: &'static [twitch_oauth2::Scope];
    /// Optional scopes needed by this endpoint
    const OPT_SCOPE: &'static [twitch_oauth2::Scope] = &[];
    /// Response type. twitch's response will  deserialize to this.
    type Response;
    /// Defines layout of the url parameters. By default uses [serde_urlencoded]
    fn query(&self) -> Result<String, serde_urlencoded::ser::Error> {
        serde_urlencoded::to_string(&self)
    }
}

/// Helix endpoint PUTs information
pub trait RequestPut: Request {}

/// Helix endpoint GETs information
pub trait RequestGet: Request {}

/// Response retrieved from endpoint. Data is the type in [Request::Response]
#[derive(PartialEq, Debug)]
pub struct Response<R, D>
where R: Request<Response = D> {
    ///  Twitch's response field for `data`.
    pub data: Vec<D>,
    /// A cursor value, to be used in a subsequent request to specify the starting point of the next set of results.
    pub pagination: Pagination,
    /// The request that was sent, used for [Paginated]
    pub request: R,
}

impl<R, D> Response<R, D>
where
    R: Request<Response = D> + Clone + Paginated + RequestGet,
    D: serde::de::DeserializeOwned,
{
    /// Get the next page in the responses.
    pub async fn get_next(
        self,
        client: &HelixClient,
    ) -> Result<Option<Response<R, D>>, RequestError>
    {
        let mut req = self.request.clone();
        if let Some(ref cursor) = self.pagination.cursor {
            req.set_pagination(cursor.clone());
            client.req_get(req).await.map(Some)
        } else {
            Ok(None)
        }
    }
}

/// Request can be paginated with a cursor
pub trait Paginated {
    /// Should returns the current pagination cursor.
    ///
    /// # Notes
    ///
    /// Use [Cursor.cursor] as [Option::None] if no cursor is found.
    fn set_pagination(&mut self, cursor: Cursor);
}
/// A cursor for pagination. This is needed because of how pagination is represented in the [New Twitch API](https://dev.twitch.tv/docs/api)
#[derive(PartialEq, Deserialize, Serialize, Debug, Clone, Default)]
pub struct Pagination {
    #[serde(default)]
    cursor: Option<Cursor>,
}

/// A cursor is a pointer to the current "page" in the twitch api pagination
pub type Cursor = String;

/// Errors for [HelixClient::req_get] and similar functions.
#[allow(missing_docs)]
#[derive(thiserror::Error, Debug)]
pub enum RequestError {
    #[error("url could not be parsed")]
    UrlParseError(#[from] url::ParseError),
    #[error("io error")]
    IOError(#[from] io::Error),
    #[error("deserialization failed")]
    DeserializeError(#[from] serde_json::Error),
    #[error("Could not serialize request to query")]
    QuerySerializeError(#[from] serde_urlencoded::ser::Error),
    #[error("request failed from reqwests side")]
    RequestError(#[from] reqwest::Error),
    #[error("no pagination found")]
    NoPage,
    #[error("something happened")]
    Other,
    #[error(
        "helix returned error {status:?} - {error} when calling `{url}` with message: {message}"
    )]
    HelixRequestError {
        error: String,
        status: reqwest::StatusCode,
        message: String,
        url: url::Url,
    },
}

/// Repeat url query items with name
///
/// ```rust
/// let users = &["emilgardis", "jtv", "tmi"].iter().map(<_>::to_string).collect::<Vec<_>>();
///  assert_eq!(&twitch_api2::helix::repeat_query("user", users), "user=emilgardis&user=jtv&user=tmi")
/// ```
pub fn repeat_query(name: &str, items: &[String]) -> String {
    let mut s = String::new();
    for (idx, item) in items.iter().enumerate() {
        s.push_str(&format!("{}={}", name, item));
        if idx + 1 != items.len() {
            s.push_str("&")
        }
    }
    s
}