]> Untitled Git - lemmy.git/blob - crates/utils/src/request.rs
Clippy fixes.
[lemmy.git] / crates / utils / src / request.rs
1 use crate::{settings::structs::Settings, version::VERSION, LemmyError, REQWEST_TIMEOUT};
2 use anyhow::anyhow;
3 use encoding::{all::encodings, DecoderTrap};
4 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
5 use reqwest_middleware::ClientWithMiddleware;
6 use serde::{Deserialize, Serialize};
7 use std::future::Future;
8 use thiserror::Error;
9 use tracing::{error, info};
10 use url::Url;
11 use webpage::HTML;
12
13 #[derive(Clone, Debug, Error)]
14 #[error("Error sending request, {0}")]
15 struct SendError(pub String);
16
17 #[derive(Clone, Debug, Error)]
18 #[error("Error receiving response, {0}")]
19 pub struct RecvError(pub String);
20
21 #[tracing::instrument(skip_all)]
22 pub async fn retry<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
23 where
24   F: Fn() -> Fut,
25   Fut: Future<Output = Result<T, reqwest_middleware::Error>>,
26 {
27   retry_custom(|| async { Ok((f)().await) }).await
28 }
29
30 #[tracing::instrument(skip_all)]
31 async fn retry_custom<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
32 where
33   F: Fn() -> Fut,
34   Fut: Future<Output = Result<Result<T, reqwest_middleware::Error>, reqwest_middleware::Error>>,
35 {
36   let mut response: Option<Result<T, reqwest_middleware::Error>> = None;
37
38   for _ in 0u8..3 {
39     match (f)().await? {
40       Ok(t) => return Ok(t),
41       Err(reqwest_middleware::Error::Reqwest(e)) => {
42         if e.is_timeout() {
43           response = Some(Err(reqwest_middleware::Error::Reqwest(e)));
44           continue;
45         }
46         return Err(reqwest_middleware::Error::Reqwest(e));
47       }
48       Err(otherwise) => {
49         return Err(otherwise);
50       }
51     }
52   }
53
54   response.expect("retry http request")
55 }
56
57 #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
58 pub struct SiteMetadata {
59   pub title: Option<String>,
60   pub description: Option<String>,
61   image: Option<Url>,
62   pub html: Option<String>,
63 }
64
65 /// Fetches the post link html tags (like title, description, image, etc)
66 #[tracing::instrument(skip_all)]
67 pub async fn fetch_site_metadata(
68   client: &ClientWithMiddleware,
69   url: &Url,
70 ) -> Result<SiteMetadata, LemmyError> {
71   info!("Fetching site metadata for url: {}", url);
72   let response = client
73     .get(url.as_str())
74     .timeout(REQWEST_TIMEOUT)
75     .send()
76     .await?;
77
78   // Can't use .text() here, because it only checks the content header, not the actual bytes
79   // https://github.com/LemmyNet/lemmy/issues/1964
80   let html_bytes = response
81     .bytes()
82     .await
83     .map_err(|e| RecvError(e.to_string()))?
84     .to_vec();
85
86   let tags = html_to_site_metadata(&html_bytes)?;
87
88   Ok(tags)
89 }
90
91 fn html_to_site_metadata(html_bytes: &[u8]) -> Result<SiteMetadata, LemmyError> {
92   let html = String::from_utf8_lossy(html_bytes);
93
94   // Make sure the first line is doctype html
95   let first_line = html
96     .trim_start()
97     .lines()
98     .into_iter()
99     .next()
100     .ok_or_else(|| LemmyError::from_message("No lines in html"))?
101     .to_lowercase();
102
103   if !first_line.starts_with("<!doctype html>") {
104     return Err(LemmyError::from_message(
105       "Site metadata page fetch is not DOCTYPE html",
106     ));
107   }
108
109   let mut page = HTML::from_string(html.to_string(), None)?;
110
111   // If the web page specifies that it isn't actually UTF-8, re-decode the received bytes with the
112   // proper encoding. If the specified encoding cannot be found, fall back to the original UTF-8
113   // version.
114   if let Some(charset) = page.meta.get("charset") {
115     if charset.to_lowercase() != "utf-8" {
116       if let Some(encoding_ref) = encodings().iter().find(|e| e.name() == charset) {
117         if let Ok(html_with_encoding) = encoding_ref.decode(html_bytes, DecoderTrap::Replace) {
118           page = HTML::from_string(html_with_encoding, None)?;
119         }
120       }
121     }
122   }
123
124   let page_title = page.title;
125   let page_description = page.description;
126
127   let og_description = page
128     .opengraph
129     .properties
130     .get("description")
131     .map(|t| t.to_string());
132   let og_title = page
133     .opengraph
134     .properties
135     .get("title")
136     .map(|t| t.to_string());
137   let og_image = page
138     .opengraph
139     .images
140     .get(0)
141     .and_then(|ogo| Url::parse(&ogo.url).ok());
142
143   let title = og_title.or(page_title);
144   let description = og_description.or(page_description);
145   let image = og_image;
146
147   Ok(SiteMetadata {
148     title,
149     description,
150     image,
151     html: None,
152   })
153 }
154
155 #[derive(Deserialize, Debug, Clone)]
156 pub(crate) struct PictrsResponse {
157   files: Vec<PictrsFile>,
158   msg: String,
159 }
160
161 #[derive(Deserialize, Debug, Clone)]
162 pub(crate) struct PictrsFile {
163   file: String,
164   #[allow(dead_code)]
165   delete_token: String,
166 }
167
168 #[tracing::instrument(skip_all)]
169 pub(crate) async fn fetch_pictrs(
170   client: &ClientWithMiddleware,
171   settings: &Settings,
172   image_url: &Url,
173 ) -> Result<PictrsResponse, LemmyError> {
174   if let Some(pictrs_url) = settings.pictrs_url.to_owned() {
175     is_image_content_type(client, image_url).await?;
176
177     let fetch_url = format!(
178       "{}/image/download?url={}",
179       pictrs_url,
180       utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
181     );
182
183     let response = client
184       .get(&fetch_url)
185       .timeout(REQWEST_TIMEOUT)
186       .send()
187       .await?;
188
189     let response: PictrsResponse = response
190       .json()
191       .await
192       .map_err(|e| RecvError(e.to_string()))?;
193
194     if response.msg == "ok" {
195       Ok(response)
196     } else {
197       Err(anyhow!("{}", &response.msg).into())
198     }
199   } else {
200     Err(anyhow!("pictrs_url not set up in config").into())
201   }
202 }
203
204 /// Both are options, since the URL might be either an html page, or an image
205 /// Returns the SiteMetadata, and a Pictrs URL, if there is a picture associated
206 #[tracing::instrument(skip_all)]
207 pub async fn fetch_site_data(
208   client: &ClientWithMiddleware,
209   settings: &Settings,
210   url: Option<&Url>,
211 ) -> (Option<SiteMetadata>, Option<Url>) {
212   match &url {
213     Some(url) => {
214       // Fetch metadata
215       // Ignore errors, since it may be an image, or not have the data.
216       // Warning, this may ignore SSL errors
217       let metadata_option = fetch_site_metadata(client, url).await.ok();
218
219       // Fetch pictrs thumbnail
220       let pictrs_hash = match &metadata_option {
221         Some(metadata_res) => match &metadata_res.image {
222           // Metadata, with image
223           // Try to generate a small thumbnail if there's a full sized one from post-links
224           Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
225             .await
226             .map(|r| r.files[0].file.to_owned()),
227           // Metadata, but no image
228           None => fetch_pictrs(client, settings, url)
229             .await
230             .map(|r| r.files[0].file.to_owned()),
231         },
232         // No metadata, try to fetch the URL as an image
233         None => fetch_pictrs(client, settings, url)
234           .await
235           .map(|r| r.files[0].file.to_owned()),
236       };
237
238       // The full urls are necessary for federation
239       let pictrs_thumbnail = pictrs_hash
240         .map(|p| {
241           Url::parse(&format!(
242             "{}/pictrs/image/{}",
243             settings.get_protocol_and_hostname(),
244             p
245           ))
246           .ok()
247         })
248         .ok()
249         .flatten();
250
251       (metadata_option, pictrs_thumbnail)
252     }
253     None => (None, None),
254   }
255 }
256
257 #[tracing::instrument(skip_all)]
258 async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> Result<(), LemmyError> {
259   let response = client
260     .get(url.as_str())
261     .timeout(REQWEST_TIMEOUT)
262     .send()
263     .await?;
264   if response
265     .headers()
266     .get("Content-Type")
267     .ok_or_else(|| anyhow!("No Content-Type header"))?
268     .to_str()?
269     .starts_with("image/")
270   {
271     Ok(())
272   } else {
273     Err(anyhow!("Not an image type.").into())
274   }
275 }
276
277 pub fn build_user_agent(settings: &Settings) -> String {
278   format!(
279     "Lemmy/{}; +{}",
280     VERSION,
281     settings.get_protocol_and_hostname()
282   )
283 }
284
285 #[cfg(test)]
286 mod tests {
287   use crate::request::{build_user_agent, fetch_site_metadata};
288   use url::Url;
289
290   use super::SiteMetadata;
291   use crate::settings::structs::Settings;
292
293   // These helped with testing
294   #[actix_rt::test]
295   async fn test_site_metadata() {
296     let settings = Settings::init().unwrap();
297     let client = reqwest::Client::builder()
298       .user_agent(build_user_agent(&settings))
299       .build()
300       .unwrap()
301       .into();
302     let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ").unwrap();
303     let sample_res = fetch_site_metadata(&client, &sample_url).await.unwrap();
304     assert_eq!(
305       SiteMetadata {
306         title: Some("FAQ · Wiki · IzzyOnDroid / repo".to_string()),
307         description: Some(
308           "The F-Droid compatible repo at https://apt.izzysoft.de/fdroid/".to_string()
309         ),
310         image: Some(
311           Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
312             .unwrap()
313         ),
314         html: None,
315       },
316       sample_res
317     );
318
319     let youtube_url = Url::parse("https://www.youtube.com/watch?v=IquO_TcMZIQ").unwrap();
320     let youtube_res = fetch_site_metadata(&client, &youtube_url).await.unwrap();
321     assert_eq!(
322       SiteMetadata {
323         title: Some("A Hard Look at Rent and Rent Seeking with Michael Hudson & Pepe Escobar".to_string()),
324         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()),
325         image: Some(Url::parse("https://i.ytimg.com/vi/IquO_TcMZIQ/maxresdefault.jpg").unwrap()),
326         html: None,
327       }, youtube_res);
328   }
329
330   // #[test]
331   // fn test_pictshare() {
332   //   let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
333   //   assert!(res.is_ok());
334   //   let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
335   //   assert!(res_other.is_err());
336   // }
337 }