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
//! Connection over http using reqwest.
//!
//! You will usually use pretty much immediately turn the connection into a Client.
//! E.g.
//! ```rust
//! use glimesh::http::Connection
//! let client = Connection::new(Auth::ClientId("<GLIMESH_CLIENT_ID>")).into_client();
//! ```

use super::{MutationConn, QueryConn};
use crate::{Auth, Client, Error};
use reqwest::{header, RequestBuilder};
use std::{sync::Arc, time::Duration};

#[derive(Debug)]
struct Config {
    user_agent: String,
    timeout: Duration,
    api_url: String,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            user_agent: format!("Glimesh Rust / {}", env!("CARGO_PKG_VERSION")),
            timeout: Duration::from_secs(30),
            api_url: String::from("https://glimesh.tv/api"),
        }
    }
}

/// Configure and build an http [`Connection`].
///
/// ## Usage:
/// ```rust
/// let connection = Connection::builder()
///     .user_agent("My App / 0.1.0")
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct ConnectionBuilder {
    config: Config,
}

impl ConnectionBuilder {
    /// Build the http connection from the set options.
    ///
    /// # Panics
    /// This function panics if the TLS backend cannot be initialized, or the resolver cannot load the system configuration.
    pub fn build(self, auth: Auth) -> Connection {
        Connection {
            http: reqwest::Client::builder()
                .user_agent(self.config.user_agent)
                .timeout(self.config.timeout)
                .build()
                .expect("failed to create http client"),
            auth: Arc::new(auth),
            api_url: Arc::new(self.config.api_url),
        }
    }

    /// Set the user agent the http client will identify itself as.
    ///
    /// This defaults to `Glimesh Rust / x.x.x` where `x.x.x` is the version of this package.
    pub fn user_agent(mut self, value: impl Into<String>) -> Self {
        self.config.user_agent = value.into();
        self
    }

    /// Set the timeout for requests made to glimesh.
    ///
    /// The default is 30 seconds
    pub fn timeout(mut self, value: Duration) -> Self {
        self.config.timeout = value;
        self
    }

    /// Set the base api url used for request.
    /// Useful if running Glimesh locally for example.
    ///
    /// Defaults to `https://glimesh.tv/api`
    pub fn api_url(mut self, value: impl Into<String>) -> Self {
        self.config.api_url = value.into();
        self
    }
}

/// Connect to glimesh over http(s).
#[derive(Debug, Clone)]
pub struct Connection {
    http: reqwest::Client,
    auth: Arc<Auth>,
    api_url: Arc<String>,
}

impl Connection {
    /// Create a [`ConnectionBuilder`] to configure various options.
    pub fn builder() -> ConnectionBuilder {
        ConnectionBuilder::default()
    }

    /// Create a connection with the default options.
    pub fn new(auth: Auth) -> Self {
        ConnectionBuilder::default().build(auth)
    }

    /// Create a client with reference to this connection
    pub fn as_client(&self) -> Client<&Self> {
        Client::new(self)
    }

    /// Create a client with a clone of this connection
    pub fn to_client(&self) -> Client<Self> {
        Client::new(self.clone())
    }

    /// Convert this connection into a client
    pub fn into_client(self) -> Client<Self> {
        Client::new(self)
    }

    async fn request<Q>(&self, variables: Q::Variables) -> Result<Q::ResponseData, Error>
    where
        Q: graphql_client::GraphQLQuery,
    {
        let req = self
            .http
            .post(self.api_url.as_ref())
            .json(&Q::build_query(variables));

        let res = self
            .apply_auth(req)
            .await
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        if !res.status().is_success() {
            return Err(Error::BadStatus(res.status().as_u16()));
        }

        let res: graphql_client::Response<Q::ResponseData> =
            res.json().await.map_err(anyhow::Error::from)?;

        if let Some(errs) = res.errors {
            if errs.len() > 0 {
                return Err(Error::GraphqlErrors(errs));
            }
        }

        let data = res.data.ok_or_else(|| Error::NoData)?;
        Ok(data)
    }

    async fn apply_auth(&self, req: RequestBuilder) -> RequestBuilder {
        match self.auth.as_ref() {
            Auth::ClientId(client_id) => {
                req.header(header::AUTHORIZATION, format!("Client-ID {}", client_id))
            }
            Auth::AccessToken(access_token) => req.bearer_auth(access_token),
            Auth::AccessTokenWithRefresh { access_token, .. } => {
                // TODO: refresh token if required
                req.bearer_auth(access_token)
            }
        }
    }
}

#[async_trait]
impl QueryConn for Connection {
    async fn query<Q>(&self, variables: Q::Variables) -> Result<Q::ResponseData, Error>
    where
        Q: graphql_client::GraphQLQuery,
        Q::Variables: Send + Sync,
    {
        self.request::<Q>(variables).await
    }
}

#[async_trait]
impl MutationConn for Connection {
    async fn mutate<Q>(&self, variables: Q::Variables) -> Result<Q::ResponseData, Error>
    where
        Q: graphql_client::GraphQLQuery,
        Q::Variables: Send + Sync,
    {
        self.request::<Q>(variables).await
    }
}