1 use crate::{settings::structs::Settings, version::VERSION, LemmyError, REQWEST_TIMEOUT};
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;
9 use tracing::{error, info};
13 #[derive(Clone, Debug, Error)]
14 #[error("Error sending request, {0}")]
15 struct SendError(pub String);
17 #[derive(Clone, Debug, Error)]
18 #[error("Error receiving response, {0}")]
19 pub struct RecvError(pub String);
21 #[tracing::instrument(skip_all)]
22 pub async fn retry<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
25 Fut: Future<Output = Result<T, reqwest_middleware::Error>>,
27 retry_custom(|| async { Ok((f)().await) }).await
30 #[tracing::instrument(skip_all)]
31 async fn retry_custom<F, Fut, T>(f: F) -> Result<T, reqwest_middleware::Error>
34 Fut: Future<Output = Result<Result<T, reqwest_middleware::Error>, reqwest_middleware::Error>>,
36 let mut response: Option<Result<T, reqwest_middleware::Error>> = None;
40 Ok(t) => return Ok(t),
41 Err(reqwest_middleware::Error::Reqwest(e)) => {
43 response = Some(Err(reqwest_middleware::Error::Reqwest(e)));
46 return Err(reqwest_middleware::Error::Reqwest(e));
49 return Err(otherwise);
54 response.expect("retry http request")
57 #[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
58 pub struct SiteMetadata {
59 pub title: Option<String>,
60 pub description: Option<String>,
62 pub html: Option<String>,
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,
70 ) -> Result<SiteMetadata, LemmyError> {
71 info!("Fetching site metadata for url: {}", url);
74 .timeout(REQWEST_TIMEOUT)
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
83 .map_err(|e| RecvError(e.to_string()))?
86 let tags = html_to_site_metadata(&html_bytes)?;
91 fn html_to_site_metadata(html_bytes: &[u8]) -> Result<SiteMetadata, LemmyError> {
92 let html = String::from_utf8_lossy(html_bytes);
94 // Make sure the first line is doctype html
100 .ok_or_else(|| LemmyError::from_message("No lines in html"))?
103 if !first_line.starts_with("<!doctype html>") {
104 return Err(LemmyError::from_message(
105 "Site metadata page fetch is not DOCTYPE html",
109 let mut page = HTML::from_string(html.to_string(), None)?;
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
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)?;
124 let page_title = page.title;
125 let page_description = page.description;
127 let og_description = page
131 .map(|t| t.to_string());
136 .map(|t| t.to_string());
141 .and_then(|ogo| Url::parse(&ogo.url).ok());
143 let title = og_title.or(page_title);
144 let description = og_description.or(page_description);
145 let image = og_image;
155 #[derive(Deserialize, Debug, Clone)]
156 pub(crate) struct PictrsResponse {
157 files: Vec<PictrsFile>,
161 #[derive(Deserialize, Debug, Clone)]
162 pub(crate) struct PictrsFile {
165 delete_token: String,
168 #[tracing::instrument(skip_all)]
169 pub(crate) async fn fetch_pictrs(
170 client: &ClientWithMiddleware,
173 ) -> Result<PictrsResponse, LemmyError> {
174 if let Some(pictrs_url) = settings.pictrs_url.to_owned() {
175 is_image_content_type(client, image_url).await?;
177 let fetch_url = format!(
178 "{}/image/download?url={}",
180 utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
183 let response = client
185 .timeout(REQWEST_TIMEOUT)
189 let response: PictrsResponse = response
192 .map_err(|e| RecvError(e.to_string()))?;
194 if response.msg == "ok" {
197 Err(anyhow!("{}", &response.msg).into())
200 Err(anyhow!("pictrs_url not set up in config").into())
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,
211 ) -> (Option<SiteMetadata>, Option<Url>) {
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();
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)
226 .map(|r| r.files[0].file.to_owned()),
227 // Metadata, but no image
228 None => fetch_pictrs(client, settings, url)
230 .map(|r| r.files[0].file.to_owned()),
232 // No metadata, try to fetch the URL as an image
233 None => fetch_pictrs(client, settings, url)
235 .map(|r| r.files[0].file.to_owned()),
238 // The full urls are necessary for federation
239 let pictrs_thumbnail = pictrs_hash
242 "{}/pictrs/image/{}",
243 settings.get_protocol_and_hostname(),
251 (metadata_option, pictrs_thumbnail)
253 None => (None, None),
257 #[tracing::instrument(skip_all)]
258 async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> Result<(), LemmyError> {
259 let response = client
261 .timeout(REQWEST_TIMEOUT)
267 .ok_or_else(|| anyhow!("No Content-Type header"))?
269 .starts_with("image/")
273 Err(anyhow!("Not an image type.").into())
277 pub fn build_user_agent(settings: &Settings) -> String {
281 settings.get_protocol_and_hostname()
287 use crate::request::{build_user_agent, fetch_site_metadata};
290 use super::SiteMetadata;
291 use crate::settings::structs::Settings;
293 // These helped with testing
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))
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();
306 title: Some("FAQ · Wiki · IzzyOnDroid / repo".to_string()),
308 "The F-Droid compatible repo at https://apt.izzysoft.de/fdroid/".to_string()
311 Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
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();
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()),
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());