use crate::post::SiteMetadata;
use encoding::{all::encodings, DecoderTrap};
-use lemmy_utils::{error::LemmyError, settings::structs::Settings, version::VERSION};
+use lemmy_db_schema::newtypes::DbUrl;
+use lemmy_utils::{
+ error::LemmyError,
+ settings::structs::Settings,
+ version::VERSION,
+ REQWEST_TIMEOUT,
+};
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use reqwest_middleware::ClientWithMiddleware;
use serde::Deserialize;
let first_line = html
.trim_start()
.lines()
- .into_iter()
.next()
.ok_or_else(|| LemmyError::from_message("No lines in html"))?
.to_lowercase();
.opengraph
.properties
.get("description")
- .map(|t| t.to_string());
+ .map(std::string::ToString::to_string);
let og_title = page
.opengraph
.properties
.get("title")
- .map(|t| t.to_string());
+ .map(std::string::ToString::to_string);
let og_image = page
.opengraph
.images
- .get(0)
+ .first()
.and_then(|ogo| Url::parse(&ogo.url).ok());
-
- let title = og_title.or(page_title);
- let description = og_description.or(page_description);
- let image = og_image;
+ let og_embed_url = page
+ .opengraph
+ .videos
+ .first()
+ .and_then(|v| Url::parse(&v.url).ok());
Ok(SiteMetadata {
- title,
- description,
- image,
- html: None,
+ title: og_title.or(page_title),
+ description: og_description.or(page_description),
+ image: og_image.map(Into::into),
+ embed_video_url: og_embed_url.map(Into::into),
})
}
delete_token: String,
}
+#[derive(Deserialize, Debug, Clone)]
+pub(crate) struct PictrsPurgeResponse {
+ msg: String,
+}
+
#[tracing::instrument(skip_all)]
pub(crate) async fn fetch_pictrs(
client: &ClientWithMiddleware,
settings: &Settings,
image_url: &Url,
) -> Result<PictrsResponse, LemmyError> {
- if let Some(pictrs_url) = settings.pictrs_url.to_owned() {
- is_image_content_type(client, image_url).await?;
+ let pictrs_config = settings.pictrs_config()?;
+ is_image_content_type(client, image_url).await?;
- let fetch_url = format!(
- "{}/image/download?url={}",
- pictrs_url,
- utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
- );
+ let fetch_url = format!(
+ "{}image/download?url={}",
+ pictrs_config.url,
+ utf8_percent_encode(image_url.as_str(), NON_ALPHANUMERIC) // TODO this might not be needed
+ );
- let response = client.get(&fetch_url).send().await?;
+ let response = client
+ .get(&fetch_url)
+ .timeout(REQWEST_TIMEOUT)
+ .send()
+ .await?;
- let response: PictrsResponse = response.json().await.map_err(LemmyError::from)?;
+ let response: PictrsResponse = response.json().await.map_err(LemmyError::from)?;
- if response.msg == "ok" {
- Ok(response)
- } else {
- Err(LemmyError::from_message(&response.msg))
- }
+ if response.msg == "ok" {
+ Ok(response)
+ } else {
+ Err(LemmyError::from_message(&response.msg))
+ }
+}
+
+/// Purges an image from pictrs
+/// Note: This should often be coerced from a Result to .ok() in order to fail softly, because:
+/// - It might fail due to image being not local
+/// - It might not be an image
+/// - Pictrs might not be set up
+pub async fn purge_image_from_pictrs(
+ client: &ClientWithMiddleware,
+ settings: &Settings,
+ image_url: &Url,
+) -> Result<(), LemmyError> {
+ let pictrs_config = settings.pictrs_config()?;
+ is_image_content_type(client, image_url).await?;
+
+ let alias = image_url
+ .path_segments()
+ .ok_or_else(|| LemmyError::from_message("Image URL missing path segments"))?
+ .next_back()
+ .ok_or_else(|| LemmyError::from_message("Image URL missing last path segment"))?;
+
+ let purge_url = format!("{}/internal/purge?alias={}", pictrs_config.url, alias);
+
+ let pictrs_api_key = pictrs_config
+ .api_key
+ .ok_or_else(|| LemmyError::from_message("pictrs_api_key_not_provided"))?;
+ let response = client
+ .post(&purge_url)
+ .timeout(REQWEST_TIMEOUT)
+ .header("x-api-token", pictrs_api_key)
+ .send()
+ .await?;
+
+ let response: PictrsPurgeResponse = response.json().await.map_err(LemmyError::from)?;
+
+ if response.msg == "ok" {
+ Ok(())
} else {
- Err(LemmyError::from_message("pictrs_url not set up in config"))
+ Err(LemmyError::from_message(&response.msg))
}
}
client: &ClientWithMiddleware,
settings: &Settings,
url: Option<&Url>,
-) -> (Option<SiteMetadata>, Option<Url>) {
+) -> (Option<SiteMetadata>, Option<DbUrl>) {
match &url {
Some(url) => {
// Fetch metadata
// Warning, this may ignore SSL errors
let metadata_option = fetch_site_metadata(client, url).await.ok();
+ let missing_pictrs_file =
+ |r: PictrsResponse| r.files.first().expect("missing pictrs file").file.clone();
+
// Fetch pictrs thumbnail
let pictrs_hash = match &metadata_option {
Some(metadata_res) => match &metadata_res.image {
// Try to generate a small thumbnail if there's a full sized one from post-links
Some(metadata_image) => fetch_pictrs(client, settings, metadata_image)
.await
- .map(|r| r.files[0].file.to_owned()),
+ .map(missing_pictrs_file),
// Metadata, but no image
None => fetch_pictrs(client, settings, url)
.await
- .map(|r| r.files[0].file.to_owned()),
+ .map(missing_pictrs_file),
},
// No metadata, try to fetch the URL as an image
None => fetch_pictrs(client, settings, url)
.await
- .map(|r| r.files[0].file.to_owned()),
+ .map(missing_pictrs_file),
};
// The full urls are necessary for federation
.ok()
.flatten();
- (metadata_option, pictrs_thumbnail)
+ (metadata_option, pictrs_thumbnail.map(Into::into))
}
None => (None, None),
}
#[cfg(test)]
mod tests {
use crate::request::{build_user_agent, fetch_site_metadata, SiteMetadata};
- use lemmy_utils::settings::structs::Settings;
+ use lemmy_utils::settings::SETTINGS;
use url::Url;
// These helped with testing
- #[actix_rt::test]
+ #[tokio::test]
async fn test_site_metadata() {
- let settings = Settings::init().unwrap();
+ let settings = &SETTINGS.clone();
let client = reqwest::Client::builder()
- .user_agent(build_user_agent(&settings))
+ .user_agent(build_user_agent(settings))
.build()
.unwrap()
.into();
image: Some(
Url::parse("https://gitlab.com/uploads/-/system/project/avatar/4877469/iod_logo.png")
.unwrap()
+ .into()
),
- html: None,
+ embed_video_url: None,
},
sample_res
);