]> Untitled Git - lemmy.git/blob - crates/utils/src/request.rs
f1655710e202533245382a37c45cb35a6c5d5bdc
[lemmy.git] / crates / utils / src / request.rs
1 use crate::{settings::structs::Settings, LemmyError};
2 use anyhow::anyhow;
3 use log::error;
4 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
5 use reqwest::Client;
6 use serde::{Deserialize, Serialize};
7 use std::future::Future;
8 use thiserror::Error;
9 use url::Url;
10 use webpage::HTML;
11
12 #[derive(Clone, Debug, Error)]
13 #[error("Error sending request, {0}")]
14 struct SendError(pub String);
15
16 #[derive(Clone, Debug, Error)]
17 #[error("Error receiving response, {0}")]
18 pub struct RecvError(pub String);
19
20 pub async fn retry<F, Fut, T>(f: F) -> Result<T, reqwest::Error>
21 where
22   F: Fn() -> Fut,
23   Fut: Future<Output = Result<T, reqwest::Error>>,
24 {
25   retry_custom(|| async { Ok((f)().await) }).await
26 }
27
28 async fn retry_custom<F, Fut, T>(f: F) -> Result<T, reqwest::Error>
29 where
30   F: Fn() -> Fut,
31   Fut: Future<Output = Result<Result<T, reqwest::Error>, reqwest::Error>>,
32 {
33   let mut response: Option<Result<T, reqwest::Error>> = None;
34
35   for _ in 0u8..3 {
36     match (f)().await? {
37       Ok(t) => return Ok(t),
38       Err(e) => {
39         if e.is_timeout() {
40           response = Some(Err(e));
41           continue;
42         }
43         return Err(e);
44       }
45     }
46   }
47
48   response.expect("retry http request")
49 }
50
51 #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
52 pub struct SiteMetadata {
53   pub title: Option<String>,
54   pub description: Option<String>,
55   image: Option<Url>,
56   pub html: Option<String>,
57 }
58
59 /// Fetches the post link html tags (like title, description, image, etc)
60 pub async fn fetch_site_metadata(client: &Client, url: &Url) -> Result<SiteMetadata, LemmyError> {
61   let response = retry(|| client.get(url.as_str()).send()).await?;
62
63   let html = response
64     .text()
65     .await
66     .map_err(|e| RecvError(e.to_string()))?;
67
68   let tags = html_to_site_metadata(&html)?;
69
70   Ok(tags)
71 }
72
73 fn html_to_site_metadata(html: &str) -> Result<SiteMetadata, LemmyError> {
74   let page = HTML::from_string(html.to_string(), None)?;
75
76   let page_title = page.title;
77   let page_description = page.description;
78
79   let og_description = page
80     .opengraph
81     .properties
82     .get("description")
83     .map(|t| t.to_string());
84   let og_title = page
85     .opengraph
86     .properties
87     .get("title")
88     .map(|t| t.to_string());
89   let og_image = page
90     .opengraph
91     .images
92     .get(0)
93     .map(|ogo| Url::parse(&ogo.url).ok())
94     .flatten();
95
96   let title = og_title.or(page_title);
97   let description = og_description.or(page_description);
98   let image = og_image;
99
100   Ok(SiteMetadata {
101     title,
102     description,
103     image,
104     html: None,
105   })
106 }
107
108 #[derive(Deserialize, Debug, Clone)]
109 pub(crate) struct PictrsResponse {
110   files: Vec<PictrsFile>,
111   msg: String,
112 }
113
114 #[derive(Deserialize, Debug, Clone)]
115 pub(crate) struct PictrsFile {
116   file: String,
117   #[allow(dead_code)]
118   delete_token: String,
119 }
120
121 pub(crate) async fn fetch_pictrs(
122   client: &Client,
123   image_url: &Url,
124 ) -> Result<PictrsResponse, LemmyError> {
125   if let Some(pictrs_url) = Settings::get().pictrs_url {
126     is_image_content_type(client, image_url).await?;
127
128     let fetch_url = format!(
129       "{}/image/download?url={}",
130       pictrs_url,
131       utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
132     );
133
134     let response = retry(|| client.get(&fetch_url).send()).await?;
135
136     let response: PictrsResponse = response
137       .json()
138       .await
139       .map_err(|e| RecvError(e.to_string()))?;
140
141     if response.msg == "ok" {
142       Ok(response)
143     } else {
144       Err(anyhow!("{}", &response.msg).into())
145     }
146   } else {
147     Err(anyhow!("pictrs_url not set up in config").into())
148   }
149 }
150
151 /// Both are options, since the URL might be either an html page, or an image
152 /// Returns the SiteMetadata, and a Pictrs URL, if there is a picture associated
153 pub async fn fetch_site_data(
154   client: &Client,
155   url: Option<&Url>,
156 ) -> (Option<SiteMetadata>, Option<Url>) {
157   match &url {
158     Some(url) => {
159       // Fetch metadata
160       // Ignore errors, since it may be an image, or not have the data.
161       // Warning, this may ignore SSL errors
162       let metadata_option = fetch_site_metadata(client, url).await.ok();
163
164       // Fetch pictrs thumbnail
165       let pictrs_hash = match &metadata_option {
166         Some(metadata_res) => match &metadata_res.image {
167           // Metadata, with image
168           // Try to generate a small thumbnail if there's a full sized one from post-links
169           Some(metadata_image) => fetch_pictrs(client, metadata_image)
170             .await
171             .map(|r| r.files[0].file.to_owned()),
172           // Metadata, but no image
173           None => fetch_pictrs(client, url)
174             .await
175             .map(|r| r.files[0].file.to_owned()),
176         },
177         // No metadata, try to fetch the URL as an image
178         None => fetch_pictrs(client, url)
179           .await
180           .map(|r| r.files[0].file.to_owned()),
181       };
182
183       // The full urls are necessary for federation
184       let pictrs_thumbnail = pictrs_hash
185         .map(|p| {
186           Url::parse(&format!(
187             "{}/pictrs/image/{}",
188             Settings::get().get_protocol_and_hostname(),
189             p
190           ))
191           .ok()
192         })
193         .ok()
194         .flatten();
195
196       (metadata_option, pictrs_thumbnail)
197     }
198     None => (None, None),
199   }
200 }
201
202 async fn is_image_content_type(client: &Client, test: &Url) -> Result<(), LemmyError> {
203   let response = retry(|| client.get(test.to_owned()).send()).await?;
204   if response
205     .headers()
206     .get("Content-Type")
207     .ok_or_else(|| anyhow!("No Content-Type header"))?
208     .to_str()?
209     .starts_with("image/")
210   {
211     Ok(())
212   } else {
213     Err(anyhow!("Not an image type.").into())
214   }
215 }
216
217 #[cfg(test)]
218 mod tests {
219   use crate::request::fetch_site_metadata;
220   use url::Url;
221
222   use super::SiteMetadata;
223
224   // These helped with testing
225   #[actix_rt::test]
226   async fn test_site_metadata() {
227     let client = reqwest::Client::default();
228     let sample_url = Url::parse("https://www.redspark.nu/en/peoples-war/district-leader-of-chand-led-cpn-arrested-in-bhojpur/").unwrap();
229     let sample_res = fetch_site_metadata(&client, &sample_url).await.unwrap();
230     assert_eq!(
231       SiteMetadata {
232         title: Some("District Leader Of Chand Led CPN Arrested In Bhojpur - Redspark".to_string()),
233         description: Some("BHOJPUR: A district leader of the outlawed Netra Bikram Chand alias Biplav-led outfit has been arrested. According to District Police".to_string()),
234         image: Some(Url::parse("https://www.redspark.nu/wp-content/uploads/2020/03/netra-bikram-chand-attends-program-1272019033653-1000x0-845x653-1.jpg").unwrap()),
235         html: None,
236       }, sample_res);
237
238     let youtube_url = Url::parse("https://www.youtube.com/watch?v=IquO_TcMZIQ").unwrap();
239     let youtube_res = fetch_site_metadata(&client, &youtube_url).await.unwrap();
240     assert_eq!(
241       SiteMetadata {
242         title: Some("A Hard Look at Rent and Rent Seeking with Michael Hudson & Pepe Escobar".to_string()),
243         description: Some("An interactive discussion on wealth inequality and the “Great Game” on the control of natural resources.In this webinar organized jointly by the Henry George...".to_string()),
244         image: Some(Url::parse("https://i.ytimg.com/vi/IquO_TcMZIQ/maxresdefault.jpg").unwrap()),
245         html: None,
246       }, youtube_res);
247   }
248
249   // #[test]
250   // fn test_pictshare() {
251   //   let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
252   //   assert!(res.is_ok());
253   //   let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
254   //   assert!(res_other.is_err());
255   // }
256 }