tirocinio-canali-steffo-acrate/acrate-hostmeta/src/jrd.rs

256 lines
6.9 KiB
Rust
Raw Normal View History

2024-11-14 01:46:52 +00:00
use std::collections::HashMap;
use serde::{Serialize, Deserialize};
use thiserror::Error;
use crate::xrd::{ResourceDescriptorLinkXRD, ResourceDescriptorPropertyXRD, ResourceDescriptorTitleXRD, ResourceDescriptorXRD};
/// A resource descriptor object in JRD format.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4>
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceDescriptorJRD {
/// The resource this document refers to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.1>
///
2024-11-16 01:55:08 +00:00
#[serde(skip_serializing_if = "Option::is_none")]
2024-11-14 01:46:52 +00:00
pub subject: Option<String>,
/// Other names the resource described by this document can be referred to.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.2>
///
#[serde(default)]
pub aliases: Vec<String>,
/// Additional information about the resource described by this document.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.3>
///
#[serde(default)]
pub properties: HashMap<String, Option<String>>,
/// Links established between the [`Self::subject`] and other resources.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4>
///
#[serde(default)]
pub links: Vec<ResourceDescriptorLinkJRD>,
}
/// A link element, which puts the subject resource in relation with another.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-3.1.1>
///
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceDescriptorLinkJRD {
/// The kind of relation established by the subject with the attached resource.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.1>
///
pub rel: String,
/// The media type of the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.2>
///
2024-11-16 01:55:08 +00:00
#[serde(skip_serializing_if = "Option::is_none")]
2024-11-14 01:46:52 +00:00
pub r#type: Option<String>,
/// URI to the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.3>
///
2024-11-16 01:55:08 +00:00
#[serde(skip_serializing_if = "Option::is_none")]
2024-11-14 01:46:52 +00:00
pub href: Option<String>,
/// Titles of the resource put in relation in various languages.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.4>
///
#[serde(default)]
pub titles: HashMap<String, String>,
/// Additional information about the resource put in relation.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc7033#section-4.4.4.5>
///
#[serde(default)]
pub properties: HashMap<String, Option<String>>,
/// Template to fill to get the URL to resource-specific information.
///
/// # Specification
///
/// - <https://datatracker.ietf.org/doc/html/rfc6415#section-4.2>
///
2024-11-16 01:55:08 +00:00
#[serde(skip_serializing_if = "Option::is_none")]
2024-11-14 01:46:52 +00:00
pub template: Option<String>,
}
impl ResourceDescriptorJRD {
/// Get a [`ResourceDescriptorJRD`] from an URL.
///
/// # Notes
///
/// This follows redirects until the redirect chain is 10 hops; see [`reqwest::redirect`] for more info.
///
/// # Examples
///
/// ```
/// # tokio_test::block_on(async {
/// use acrate_hostmeta::jrd::ResourceDescriptorJRD;
///
/// let client = reqwest::Client::new();
/// let url: reqwest::Url = "https://junimo.party/.well-known/nodeinfo".parse()
/// .expect("URL to be valid");
///
/// let rd = ResourceDescriptorJRD::get(&client, url)
/// .await
/// .expect("JRD to be processed correctly");
/// # })
/// ```
///
pub async fn get(client: &reqwest::Client, url: reqwest::Url) -> Result<Self, GetJRDError> {
use GetJRDError::*;
log::debug!("Getting JRD document at: {url}");
log::trace!("Building request...");
let request = {
log::trace!("Creating new request...");
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
log::trace!("Setting request headers...");
let headers = request.headers_mut();
log::trace!("Setting `Accept: application/jrd+json, application/json`...");
let _ = headers.insert(
reqwest::header::ACCEPT,
"application/jrd+json, application/json".parse().unwrap()
);
request
};
log::trace!("Sending request...");
let response = client.execute(request)
.await
.map_err(Request)?;
log::trace!("Checking `Content-Type` of the response...");
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.ok_or(ContentTypeMissing)?;
log::trace!("Extracting MIME type from the `Content-Type` header...");
let mime_type = crate::utils::extract_mime_from_content_type(content_type)
.ok_or(ContentTypeInvalid)?;
log::trace!("Ensuring MIME type is acceptable for JRD parsing...");
if !(mime_type == "application/json" || mime_type == "application/jrd+json") {
log::error!("MIME type `{mime_type}` is not acceptable for JRD parsing.");
return Err(ContentTypeInvalid);
}
log::trace!("Attempting to parse response as JSON...");
let data = response.json::<Self>()
.await
.map_err(Parse)?;
Ok(data)
}
}
impl From<ResourceDescriptorXRD> for ResourceDescriptorJRD {
fn from(value: ResourceDescriptorXRD) -> Self {
Self {
subject: value.subject,
aliases: value.aliases,
properties: value.properties.into_iter()
.map(From::from)
.collect(),
links: value.links.into_iter()
.map(From::from)
.collect(),
}
}
}
impl From<ResourceDescriptorLinkXRD> for ResourceDescriptorLinkJRD {
fn from(value: ResourceDescriptorLinkXRD) -> Self {
Self {
rel: value.rel,
r#type: value.r#type,
href: value.href,
titles: HashMap::from_iter(
value.titles.into_iter()
.map(From::from)
),
properties: HashMap::from_iter(
value.properties.into_iter()
.map(From::from)
),
template: value.template,
}
}
}
impl From<ResourceDescriptorPropertyXRD> for (String, Option<String>) {
fn from(value: ResourceDescriptorPropertyXRD) -> Self {
(value.rel, value.value)
2024-11-14 01:46:52 +00:00
}
}
impl From<ResourceDescriptorTitleXRD> for (String, String) {
fn from(value: ResourceDescriptorTitleXRD) -> Self {
(value.language, value.value)
}
}
/// Error occurred during [`ResourceDescriptor::get_jrd`].
#[derive(Debug, Error)]
pub enum GetJRDError {
/// The HTTP request failed.
#[error("the HTTP request failed")]
Request(reqwest::Error),
/// The `Content-Type` header of the response is missing.
#[error("the Content-Type header of the response is missing")]
ContentTypeMissing,
/// The `Content-Type` header of the response is invalid.
#[error("the Content-Type header of the response is invalid")]
ContentTypeInvalid,
/// The document failed to be parsed as JSON by [`reqwest`].
#[error("the document failed to be parsed as JSON")]
Parse(reqwest::Error),
}