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 .map(|ogo| Url::parse(&ogo.url).ok())
144 let title = og_title.or(page_title);
145 let description = og_description.or(page_description);
146 let image = og_image;
156 #[derive(Deserialize, Debug, Clone)]
157 pub(crate) struct PictrsResponse {
158 files: Vec<PictrsFile>,
162 #[derive(Deserialize, Debug, Clone)]
163 pub(crate) struct PictrsFile {
166 delete_token: String,
169 #[tracing::instrument(skip_all)]
170 pub(crate) async fn fetch_pictrs(
171 client: &ClientWithMiddleware,
174 ) -> Result<PictrsResponse, LemmyError> {
175 if let Some(pictrs_url) = settings.pictrs_url.to_owned() {
176 is_image_content_type(client, image_url).await?;
178 let fetch_url = format!(
179 "{}/image/download?url={}",
181 utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
184 let response = client
186 .timeout(REQWEST_TIMEOUT)
190 let response: PictrsResponse = response
193 .map_err(|e| RecvError(e.to_string()))?;
195 if response.msg == "ok" {
198 Err(anyhow!("{}", &response.msg).into())
201 Err(anyhow!("pictrs_url not set up in config").into())
205 /// Both are options, since the URL might be either an html page, or an image
206 /// Returns the SiteMetadata, and a Pictrs URL, if there is a picture associated
207 #[tracing::instrument(skip_all)]
208 pub async fn fetch_site_data(
209 client: &ClientWithMiddleware,
212 ) -> (Option<SiteMetadata>, Option<Url>) {
216 // Ignore errors, since it may be an image, or not have the data.
217 // Warning, this may ignore SSL errors
218 let metadata_option = fetch_site_metadata(client, url).await.ok();
220 // Fetch pictrs thumbnail
221 let pictrs_hash = match &metadata_option {
222 Some(metadata_res) => match &metadata_res.image {
223 // Metadata, with image
224 // Try to generate a small thumbnail if there's a full sized one from post-links
225 Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
227 .map(|r| r.files[0].file.to_owned()),
228 // Metadata, but no image
229 None => fetch_pictrs(client, settings, url)
231 .map(|r| r.files[0].file.to_owned()),
233 // No metadata, try to fetch the URL as an image
234 None => fetch_pictrs(client, settings, url)
236 .map(|r| r.files[0].file.to_owned()),
239 // The full urls are necessary for federation
240 let pictrs_thumbnail = pictrs_hash
243 "{}/pictrs/image/{}",
244 settings.get_protocol_and_hostname(),
252 (metadata_option, pictrs_thumbnail)
254 None => (None, None),
258 #[tracing::instrument(skip_all)]
259 async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> Result<(), LemmyError> {
260 let response = client
262 .timeout(REQWEST_TIMEOUT)
268 .ok_or_else(|| anyhow!("No Content-Type header"))?
270 .starts_with("image/")
274 Err(anyhow!("Not an image type.").into())
278 pub fn build_user_agent(settings: &Settings) -> String {
282 settings.get_protocol_and_hostname()
288 use crate::request::{build_user_agent, fetch_site_metadata};
291 use super::SiteMetadata;
292 use crate::settings::structs::Settings;
294 // These helped with testing
296 async fn test_site_metadata() {
297 let settings = Settings::init().unwrap();
298 let client = reqwest::Client::builder()
299 .user_agent(build_user_agent(&settings))
303 let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ").unwrap();
304 let sample_res = fetch_site_metadata(&client, &sample_url).await.unwrap();
307 title: Some("FAQ · Wiki · IzzyOnDroid / repo".to_string()),
309 "The F-Droid compatible repo at https://apt.izzysoft.de/fdroid/".to_string()
312 Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
320 let youtube_url = Url::parse("https://www.youtube.com/watch?v=IquO_TcMZIQ").unwrap();
321 let youtube_res = fetch_site_metadata(&client, &youtube_url).await.unwrap();
324 title: Some("A Hard Look at Rent and Rent Seeking with Michael Hudson & Pepe Escobar".to_string()),
325 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()),
326 image: Some(Url::parse("https://i.ytimg.com/vi/IquO_TcMZIQ/maxresdefault.jpg").unwrap()),
332 // fn test_pictshare() {
333 // let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
334 // assert!(res.is_ok());
335 // let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
336 // assert!(res_other.is_err());