1 use crate::post::SiteMetadata;
2 use encoding::{all::encodings, DecoderTrap};
3 use lemmy_db_schema::newtypes::DbUrl;
4 use lemmy_utils::{error::LemmyError, settings::structs::Settings, version::VERSION};
5 use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
6 use reqwest_middleware::ClientWithMiddleware;
7 use serde::Deserialize;
12 /// Fetches the post link html tags (like title, description, image, etc)
13 #[tracing::instrument(skip_all)]
14 pub async fn fetch_site_metadata(
15 client: &ClientWithMiddleware,
17 ) -> Result<SiteMetadata, LemmyError> {
18 info!("Fetching site metadata for url: {}", url);
19 let response = client.get(url.as_str()).send().await?;
21 // Can't use .text() here, because it only checks the content header, not the actual bytes
22 // https://github.com/LemmyNet/lemmy/issues/1964
23 let html_bytes = response.bytes().await.map_err(LemmyError::from)?.to_vec();
25 let tags = html_to_site_metadata(&html_bytes)?;
30 fn html_to_site_metadata(html_bytes: &[u8]) -> Result<SiteMetadata, LemmyError> {
31 let html = String::from_utf8_lossy(html_bytes);
33 // Make sure the first line is doctype html
39 .ok_or_else(|| LemmyError::from_message("No lines in html"))?
42 if !first_line.starts_with("<!doctype html>") {
43 return Err(LemmyError::from_message(
44 "Site metadata page fetch is not DOCTYPE html",
48 let mut page = HTML::from_string(html.to_string(), None)?;
50 // If the web page specifies that it isn't actually UTF-8, re-decode the received bytes with the
51 // proper encoding. If the specified encoding cannot be found, fall back to the original UTF-8
53 if let Some(charset) = page.meta.get("charset") {
54 if charset.to_lowercase() != "utf-8" {
55 if let Some(encoding_ref) = encodings().iter().find(|e| e.name() == charset) {
56 if let Ok(html_with_encoding) = encoding_ref.decode(html_bytes, DecoderTrap::Replace) {
57 page = HTML::from_string(html_with_encoding, None)?;
63 let page_title = page.title;
64 let page_description = page.description;
66 let og_description = page
70 .map(|t| t.to_string());
75 .map(|t| t.to_string());
80 .and_then(|ogo| Url::parse(&ogo.url).ok());
81 let og_embed_url = page
85 .and_then(|v| Url::parse(&v.url).ok());
88 title: og_title.or(page_title),
89 description: og_description.or(page_description),
90 image: og_image.map(Into::into),
91 embed_video_url: og_embed_url.map(Into::into),
95 #[derive(Deserialize, Debug, Clone)]
96 pub(crate) struct PictrsResponse {
97 files: Vec<PictrsFile>,
101 #[derive(Deserialize, Debug, Clone)]
102 pub(crate) struct PictrsFile {
105 delete_token: String,
108 #[tracing::instrument(skip_all)]
109 pub(crate) async fn fetch_pictrs(
110 client: &ClientWithMiddleware,
113 ) -> Result<PictrsResponse, LemmyError> {
114 if let Some(pictrs_url) = settings.pictrs_url.to_owned() {
115 is_image_content_type(client, image_url).await?;
117 let fetch_url = format!(
118 "{}/image/download?url={}",
120 utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
123 let response = client.get(&fetch_url).send().await?;
125 let response: PictrsResponse = response.json().await.map_err(LemmyError::from)?;
127 if response.msg == "ok" {
130 Err(LemmyError::from_message(&response.msg))
133 Err(LemmyError::from_message("pictrs_url not set up in config"))
137 /// Both are options, since the URL might be either an html page, or an image
138 /// Returns the SiteMetadata, and a Pictrs URL, if there is a picture associated
139 #[tracing::instrument(skip_all)]
140 pub async fn fetch_site_data(
141 client: &ClientWithMiddleware,
144 ) -> (Option<SiteMetadata>, Option<DbUrl>) {
148 // Ignore errors, since it may be an image, or not have the data.
149 // Warning, this may ignore SSL errors
150 let metadata_option = fetch_site_metadata(client, url).await.ok();
152 // Fetch pictrs thumbnail
153 let pictrs_hash = match &metadata_option {
154 Some(metadata_res) => match &metadata_res.image {
155 // Metadata, with image
156 // Try to generate a small thumbnail if there's a full sized one from post-links
157 Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
159 .map(|r| r.files[0].file.to_owned()),
160 // Metadata, but no image
161 None => fetch_pictrs(client, settings, url)
163 .map(|r| r.files[0].file.to_owned()),
165 // No metadata, try to fetch the URL as an image
166 None => fetch_pictrs(client, settings, url)
168 .map(|r| r.files[0].file.to_owned()),
171 // The full urls are necessary for federation
172 let pictrs_thumbnail = pictrs_hash
175 "{}/pictrs/image/{}",
176 settings.get_protocol_and_hostname(),
184 (metadata_option, pictrs_thumbnail.map(Into::into))
186 None => (None, None),
190 #[tracing::instrument(skip_all)]
191 async fn is_image_content_type(client: &ClientWithMiddleware, url: &Url) -> Result<(), LemmyError> {
192 let response = client.get(url.as_str()).send().await?;
196 .ok_or_else(|| LemmyError::from_message("No Content-Type header"))?
198 .starts_with("image/")
202 Err(LemmyError::from_message("Not an image type."))
206 pub fn build_user_agent(settings: &Settings) -> String {
210 settings.get_protocol_and_hostname()
216 use crate::request::{build_user_agent, fetch_site_metadata, SiteMetadata};
217 use lemmy_utils::settings::structs::Settings;
220 // These helped with testing
222 async fn test_site_metadata() {
223 let settings = Settings::init().unwrap();
224 let client = reqwest::Client::builder()
225 .user_agent(build_user_agent(&settings))
229 let sample_url = Url::parse("https://gitlab.com/IzzyOnDroid/repo/-/wikis/FAQ").unwrap();
230 let sample_res = fetch_site_metadata(&client, &sample_url).await.unwrap();
233 title: Some("FAQ · Wiki · IzzyOnDroid / repo · GitLab".to_string()),
235 "The F-Droid compatible repo at https://apt.izzysoft.de/fdroid/".to_string()
238 Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
242 embed_video_url: None,
249 // fn test_pictshare() {
250 // let res = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpg");
251 // assert!(res.is_ok());
252 // let res_other = fetch_pictshare("https://upload.wikimedia.org/wikipedia/en/2/27/The_Mandalorian_logo.jpgaoeu");
253 // assert!(res_other.is_err());