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

use percent_encoding::{percent_decode_str, utf8_percent_encode, NON_ALPHANUMERIC};
use url::Url;

use serde::{Deserialize, Serialize};

#[cfg(feature = "ts_rs")]
use ts_rs::TS;

use crate::prelude::*;

#[derive(Deserialize, Serialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct OEmbedResponse {
    pub author_name: String,
    pub author_url: String,
    pub html: String,
    pub provider_name: String,
    pub provider_url: String,
    pub title: String,
    pub version: String,
}

#[derive(Deserialize, Debug)]
pub struct OEmbedRequest {
    pub url: String,
}

// https://github.com/WordPress/wordpress-develop/blob/master/src/wp-includes/class-wp-oembed.php
pub fn url_to_oembed_endpoint(url: String, base_url: Option<String>) -> UtilResult<Url> {
    let parsed_url = Url::parse(url.as_str())?;
    if let Some(host) = parsed_url.host_str() {
        if host.ends_with("youtu.be") || host.ends_with("youtube.com") {
            return oembed_url_builder(
                "https://www.youtube.com/oembed",
                &format!("url={}&format=json&maxwidth=780&maxheight=440", url),
            );
        }
        if host.ends_with("twitter.com") {
            return oembed_url_builder(
                "https://publish.twitter.com/oembed",
                &format!("url={}&maxwidth=780&maxheight=440", url),
            );
        }
        if host.ends_with("soundcloud.com") {
            return oembed_url_builder(
                "https://soundcloud.com/oembed",
                &format!("url={}&format=json&maxwidth=780&maxheight=440", url),
            );
        }
        if host.ends_with("open.spotify.com") || host.ends_with("play.spotify.com") {
            return oembed_url_builder(
                "https://embed.spotify.com/oembed",
                &format!("url={}&format=json&height=335&width=780", url),
            );
        }
        if host.ends_with("flickr.com") || host.ends_with("flic.kr") {
            return oembed_url_builder(
                "https://www.flickr.com/services/oembed",
                &format!("url={}&format=json&maxwidth=780&maxheight=780", url),
            );
        }
        if host.ends_with("vimeo.com") {
            return oembed_url_builder(
                "https://vimeo.com/api/oembed.json",
                &format!("url={}&maxwidth=780&maxheight=440", url),
            );
        }
        if host.ends_with("menti.com") || host.ends_with("mentimeter.com") {
            return oembed_url_builder(
                &format!(
                    "{}/api/v0/cms/gutenberg/oembed/mentimeter",
                    base_url.unwrap()
                ),
                &format!(
                    "url={}",
                    utf8_percent_encode(url.as_str(), NON_ALPHANUMERIC)
                ),
            );
        }
        if host.ends_with("thinglink.com") {
            return oembed_url_builder(
                &format!(
                    "{}/api/v0/cms/gutenberg/oembed/thinglink",
                    base_url.unwrap()
                ),
                &format!(
                    "url={}",
                    utf8_percent_encode(url.as_str(), NON_ALPHANUMERIC)
                ),
            );
        }
        if host.ends_with("imgur.com") {
            return oembed_url_builder(
                "https://api.imgur.com/oembed",
                &format!("url={}&maxwidth=780", url),
            );
        }
        if host.ends_with("reddit.com") {
            return oembed_url_builder(
                "https://www.reddit.com/oembed",
                &format!("url={}&format=json", url),
            );
        }
        if host.ends_with("slideshare.net") {
            return oembed_url_builder(
                "https://www.slideshare.net/api/oembed/2",
                &format!("url={}&format=json", url),
            );
        }
        if host.ends_with("ted.com") {
            return oembed_url_builder(
                "https://www.ted.com/services/v1/oembed.json",
                &format!("url={}", url),
            );
        }
        if host.ends_with("tumblr.com") {
            // Old tumblr api, v2 is latest, but WP uses 1.0
            return oembed_url_builder(
                "https://www.tumblr.com/oembed/1.0",
                &format!("url={}&format=json", url),
            );
        }
        Err(UtilError::new(
            UtilErrorType::Other,
            "Link not supported for embedding.".to_string(),
            None,
        ))
    } else {
        Err(UtilError::new(
            UtilErrorType::Other,
            "Failed to parse host from URL.".to_string(),
            None,
        ))
    }
}

pub fn mentimeter_oembed_response_builder(
    url: String,
    base_url: String,
) -> UtilResult<OEmbedResponse> {
    let mut parsed_url = Url::parse(url.as_str()).unwrap();
    // Get the height and title params
    let params: HashMap<_, _> = parsed_url.query_pairs().into_owned().collect();
    // We want to remove the query params so that the iframe src url doesn't have them
    parsed_url.set_query(None);
    let decoded_title = percent_decode_str(
        params
            .get("title")
            .unwrap_or(&"Mentimeter%20embed".to_string()),
    )
    .decode_utf8()
    .expect("Decoding title or default value for menti embed failed")
    .to_string();

    let response = OEmbedResponse {
        author_name: "Mooc.fi".to_string(),
        author_url: base_url,
        html: format!(
            "<iframe src={} style='width: 99%;' height={:?} title={:?}></iframe>",
            parsed_url,
            params.get("height").unwrap_or(&"500".to_string()),
            decoded_title
        ),
        provider_name: "mentimeter".to_string(),
        provider_url: parsed_url
            .host_str()
            .unwrap_or("https://www.mentimeter.com")
            .to_string(),
        title: decoded_title,
        version: "1.0".to_string(),
    };
    Ok(response)
}

pub fn thinglink_oembed_response_builder(
    url: String,
    base_url: String,
) -> UtilResult<OEmbedResponse> {
    let mut parsed_url = Url::parse(url.as_str()).unwrap();
    // Get the height and title params
    let params: HashMap<_, _> = parsed_url.query_pairs().into_owned().collect();
    // We want to remove the query params so that the iframe src url doesn't have them
    parsed_url.set_query(None);
    let decoded_title = percent_decode_str(
        params
            .get("title")
            .unwrap_or(&"Thinlink%20embed".to_string()),
    )
    .decode_utf8()
    .expect("Decoding title or default value for thinglink embed failed")
    .to_string();

    let response = OEmbedResponse {
        author_name: "Mooc.fi".to_string(),
        author_url: base_url,
        html: format!(
            "<iframe sandbox=\"allow-scripts allow-same-origin\" src={} style='width: 99%;' height={:?} title={:?}></iframe>",
            parsed_url,
            params.get("height").unwrap_or(&"500".to_string()),
            decoded_title
        ),
        provider_name: "thinglink".to_string(),
        provider_url: parsed_url
            .host_str()
            .unwrap_or("https://www.thinglink.com/")
            .to_string(),
        title: decoded_title,
        version: "1.0".to_string(),
    };
    Ok(response)
}

fn oembed_url_builder(url: &str, query_params: &str) -> UtilResult<Url> {
    let mut endpoint_url = Url::parse(url)?;
    endpoint_url.set_query(Some(query_params));
    Ok(endpoint_url)
}

#[cfg(test)]
mod tests {
    use url::Url;

    use super::*;
    #[test]
    fn works_with_youtu_be() {
        assert_eq!(
            url_to_oembed_endpoint("https://youtu.be/dQw4w9WgXcQ".to_string(), None).unwrap(),
            Url::parse(
                "https://www.youtube.com/oembed?url=https://youtu.be/dQw4w9WgXcQ&format=json&maxwidth=780&maxheight=440"
            )
            .unwrap()
        )
    }
    #[test]
    fn works_with_youtube_com() {
        assert_eq!(
            url_to_oembed_endpoint("https://www.youtube.com/watch?v=dQw4w9WgXcQ".to_string(), None)
                .unwrap(),
            Url::parse("https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ&format=json&maxwidth=780&maxheight=440").unwrap()
        )
    }
    #[test]
    fn works_with_youtube_com_playlist() {
        assert_eq!(
            url_to_oembed_endpoint(
                "https://www.youtube.com/playlist?list=gYLqDMMh1GEbHf-Q1".to_string(), None
            )
            .unwrap(),
            Url::parse("https://www.youtube.com/oembed?url=https://www.youtube.com/playlist?list=gYLqDMMh1GEbHf-Q1&format=json&maxwidth=780&maxheight=440").unwrap()
        )
    }
    #[test]
    fn works_with_open_spotify_com() {
        assert_eq!(url_to_oembed_endpoint(
            "http://open.spotify.com/track/298gs9ATwKlQR".to_string(), None
        )
        .unwrap(),
        Url::parse("https://embed.spotify.com/oembed?url=http://open.spotify.com/track/298gs9ATwKlQR&format=json&height=335&width=780").unwrap())
    }
    #[test]
    fn works_with_flic_kr_com() {
        assert_eq!(
            url_to_oembed_endpoint("https://flic.kr/p/2jJ".to_string(), None).unwrap(),
            Url::parse(
                "https://www.flickr.com/services/oembed?url=https://flic.kr/p/2jJ&format=json&maxwidth=780&maxheight=780"
            ).unwrap()
        )
    }

    #[test]
    fn works_with_thinglink() {
        assert_eq!(
            url_to_oembed_endpoint(
                "https://www.thinglink.com/card/1205257932048957445".to_string(),
                Some("http://project-331.local".to_string())
            )
            .unwrap().to_string(),
            "http://project-331.local/api/v0/cms/gutenberg/oembed/thinglink?url=https%3A%2F%2Fwww%2Ethinglink%2Ecom%2Fcard%2F1205257932048957445"
        )
    }
}