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