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
use crate::api_result::{ApiPayload, ApiResponse, ApiResponseExt, ApiResult};
use crate::authorization::Authorization;
use crate::error::Result;
use crate::utils::JsonStream;
use futures::prelude::*;
use reqwest::header::AUTHORIZATION;
use reqwest::{Client, IntoUrl, Method, Url};
use serde::de::DeserializeOwned;
use std::sync::Arc;

#[derive(Debug)]
pub struct TwitterApi<A> {
    client: Client,
    base_url: Url,
    auth: Arc<A>,
}

impl<A> TwitterApi<A>
where
    A: Authorization,
{
    pub fn new(auth: A) -> Self {
        Self {
            client: Client::new(),
            base_url: Url::parse("https://api.twitter.com/2/").unwrap(),
            auth: Arc::new(auth),
        }
    }

    pub fn auth(&self) -> &A {
        &self.auth
    }

    pub(crate) fn url(&self, url: impl AsRef<str>) -> Result<Url> {
        Ok(self.base_url.join(url.as_ref())?)
    }

    pub(crate) fn request(&self, method: Method, url: impl IntoUrl) -> reqwest::RequestBuilder {
        self.client.request(method, url)
    }

    pub(crate) async fn send<T: DeserializeOwned, M: DeserializeOwned>(
        &self,
        req: reqwest::RequestBuilder,
    ) -> ApiResult<A, T, M> {
        let mut req = req.build()?;
        let authorization = self.auth.header(&req).await?;
        let _ = req.headers_mut().insert(AUTHORIZATION, authorization);
        let url = req.url().clone();
        let response = self
            .client
            .execute(req)
            .await?
            .api_error_for_status()
            .await?
            .json()
            .await?;
        Ok(ApiResponse::new(self, url, response))
    }

    pub(crate) async fn stream<T: DeserializeOwned, M: DeserializeOwned>(
        &self,
        req: reqwest::RequestBuilder,
    ) -> Result<impl Stream<Item = Result<ApiPayload<T, M>>>> {
        let mut req = req.build()?;
        let authorization = self.auth.header(&req).await?;
        let _ = req.headers_mut().insert(AUTHORIZATION, authorization);
        Ok(JsonStream::new(
            self.client
                .execute(req)
                .await?
                .api_error_for_status()
                .await?
                .bytes_stream(),
        ))
    }
}

impl<A> Clone for TwitterApi<A> {
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
            base_url: self.base_url.clone(),
            auth: self.auth.clone(),
        }
    }
}