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
use std::collections::HashMap;

use lazy_static::lazy_static;
use reqwest::{header, IntoUrl};

use crate::{error::Error, spec::EmbedResponse};

lazy_static! {
    static ref DEFAULT_CLIENT: reqwest::Client = reqwest::Client::new();
}

/// Request for fetching oEmbed data
///
/// See the [oembed specification](https://oembed.com/#section2.2) for more information
#[derive(Default)]
pub struct ConsumerRequest<'a> {
    pub url: &'a str,
    pub max_width: Option<i32>,
    pub max_height: Option<i32>,
    pub params: Option<HashMap<&'a str, &'a str>>,
}

/// oEmbed client
#[derive(Clone)]
pub struct Client(reqwest::Client);

impl Client {
    pub fn new(client: reqwest::Client) -> Self {
        Self(client)
    }

    /// Fetch oEmbed data from the endpoint of a provider
    pub async fn fetch(
        &self,
        endpoint: impl IntoUrl,
        request: ConsumerRequest<'_>,
    ) -> Result<EmbedResponse, Error> {
        let mut url = endpoint.into_url()?;

        {
            let mut query = url.query_pairs_mut();

            query.append_pair("url", request.url);

            if let Some(max_width) = request.max_width {
                query.append_pair("maxwidth", &max_width.to_string());
            }

            if let Some(max_height) = request.max_height {
                query.append_pair("maxheight", &max_height.to_string());
            }

            if let Some(params) = request.params {
                for (key, value) in params {
                    query.append_pair(key, value);
                }
            }

            query.finish();
        }

        Ok(self
            .0
            .get(url)
            .header(header::USER_AGENT, "crates/oembed-rs")
            .send()
            .await?
            .error_for_status()?
            .json()
            .await
            .map(|mut response: EmbedResponse| {
                // Remove the `type` field from the extra fields as we use #[serde(flatten)] twice
                response.extra.remove("type");
                response
            })?)
    }
}

/// Fetch oEmbed data from the endpoint of a provider
pub async fn fetch(
    endpoint: impl IntoUrl,
    request: ConsumerRequest<'_>,
) -> Result<EmbedResponse, Error> {
    Client::new(DEFAULT_CLIENT.clone())
        .fetch(endpoint, request)
        .await
}

#[cfg(test)]
mod tests {
    use mockito::Server;

    use super::*;

    #[tokio::test]
    async fn test_fetch_success() {
        let mut server = Server::new_async().await;

        let mock = server
            .mock("GET", "/?url=https%3A%2F%2Fexample.com")
            .with_status(200)
            .with_body(r#"{"version": "1.0", "type": "link"}"#)
            .with_header("content-type", "application/json")
            .create_async()
            .await;

        let result = fetch(
            server.url(),
            ConsumerRequest {
                url: "https://example.com",
                ..ConsumerRequest::default()
            },
        )
        .await;
        assert_eq!(
            result.ok(),
            Some(EmbedResponse {
                oembed_type: crate::EmbedType::Link,
                version: "1.0".to_string(),
                title: None,
                author_name: None,
                author_url: None,
                provider_name: None,
                provider_url: None,
                cache_age: None,
                thumbnail_url: None,
                thumbnail_width: None,
                thumbnail_height: None,
                extra: HashMap::default(),
            })
        );

        mock.assert_async().await;
    }

    #[tokio::test]
    async fn test_fetch_error() {
        let mut server = Server::new_async().await;

        let mock = server
            .mock("GET", "/?url=https%3A%2F%2Fexample.com")
            .with_status(404)
            .create_async()
            .await;

        let result = fetch(
            server.url(),
            ConsumerRequest {
                url: "https://example.com",
                ..ConsumerRequest::default()
            },
        )
        .await;

        if let Err(Error::Reqwest(err)) = result {
            assert_eq!(err.status(), Some(reqwest::StatusCode::NOT_FOUND))
        } else {
            panic!("unexpected result: {:?}", result);
        }

        mock.assert_async().await;
    }
}