Plume/plume-common/src/activity_pub/mod.rs

735 lines
22 KiB
Rust
Raw Normal View History

use activitystreams::{
actor::{ApActor, Group, Person},
2022-03-06 12:04:16 +01:00
base::{AnyBase, Base, Extends},
iri_string::types::IriString,
2022-03-06 12:04:16 +01:00
kind,
2022-05-02 18:10:44 +02:00
markers::{self, Activity},
object::{ApObject, Article, Object},
primitives::{AnyString, OneOrMany},
unparsed::UnparsedMutExt,
};
2022-02-23 17:58:05 +01:00
use activitystreams_ext::{Ext1, Ext2, UnparsedExtension};
2018-05-16 20:20:44 +02:00
use array_tool::vec::Uniq;
2022-05-05 06:03:41 +02:00
use futures::future::join_all;
use reqwest::{header::HeaderValue, ClientBuilder, RequestBuilder, Url};
2018-05-19 09:39:59 +02:00
use rocket::{
http::Status,
request::{FromRequest, Request},
response::{Responder, Response},
Outcome,
2018-05-19 09:39:59 +02:00
};
2022-05-06 21:50:58 +02:00
use tokio::{
runtime,
time::{sleep, Duration},
};
2021-01-11 00:38:41 +01:00
use tracing::{debug, warn};
2018-04-24 14:31:02 +02:00
2018-05-16 20:20:44 +02:00
use self::sign::Signable;
2018-05-01 16:00:29 +02:00
pub mod inbox;
2018-05-04 17:18:00 +02:00
pub mod request;
2018-04-29 19:49:56 +02:00
pub mod sign;
2018-04-24 14:31:02 +02:00
pub const CONTEXT_URL: &str = "https://www.w3.org/ns/activitystreams";
Big refactoring of the Inbox (#443) * Big refactoring of the Inbox We now have a type that routes an activity through the registered handlers until one of them matches. Each Actor/Activity/Object combination is represented by an implementation of AsObject These combinations are then registered on the Inbox type, which will try to deserialize the incoming activity in the requested types. Advantages: - nicer syntax: the final API is clearer and more idiomatic - more generic: only two traits (`AsActor` and `AsObject`) instead of one for each kind of activity - it is easier to see which activities we handle and which one we don't * Small fixes - Avoid panics - Don't search for AP ID infinitely - Code style issues * Fix tests * Introduce a new trait: FromId It should be implemented for any AP object. It allows to look for an object in database using its AP ID, or to dereference it if it was not present in database Also moves the inbox code to plume-models to test it (and write a basic test for each activity type we handle) * Use if let instead of match * Don't require PlumeRocket::intl for tests * Return early and remove a forgotten dbg! * Add more tests to try to understand where the issues come from * Also add a test for comment federation * Don't check creation_date is the same for blogs * Make user and blog federation more tolerant to errors/missing fields * Make clippy happy * Use the correct Accept header when dereferencing * Fix follow approval with Mastodon * Add spaces to characters that should not be in usernames And validate blog names too * Smarter dereferencing: only do it once for each actor/object * Forgot some files * Cargo fmt * Delete plume_test * Delete plume_tests * Update get_id docs + Remove useless : Sized * Appease cargo fmt * Remove dbg! + Use as_ref instead of clone when possible + Use and_then instead of map when possible * Remove .po~ * send unfollow to local instance * read cover from update activity * Make sure "cc" and "to" are never empty and fix a typo in a constant name * Cargo fmt
2019-04-17 19:31:47 +02:00
pub const PUBLIC_VISIBILITY: &str = "https://www.w3.org/ns/activitystreams#Public";
2018-07-18 16:58:28 +02:00
2019-03-20 17:56:17 +01:00
pub const AP_CONTENT_TYPE: &str =
r#"application/ld+json; profile="https://www.w3.org/ns/activitystreams""#;
2018-07-18 16:58:28 +02:00
pub fn ap_accept_header() -> Vec<&'static str> {
vec![
2022-05-03 18:56:49 +02:00
"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"",
"application/ld+json;profile=\"https://www.w3.org/ns/activitystreams\"",
2018-07-18 16:58:28 +02:00
"application/activity+json",
"application/ld+json",
2018-07-18 16:58:28 +02:00
]
}
2018-04-24 14:31:02 +02:00
pub fn context() -> serde_json::Value {
json!([
2018-04-29 19:49:56 +02:00
CONTEXT_URL,
2018-04-24 14:31:02 +02:00
"https://w3id.org/security/v1",
{
"manuallyApprovesFollowers": "as:manuallyApprovesFollowers",
"sensitive": "as:sensitive",
"movedTo": "as:movedTo",
"Hashtag": "as:Hashtag",
"ostatus":"http://ostatus.org#",
"atomUri":"ostatus:atomUri",
"inReplyToAtomUri":"ostatus:inReplyToAtomUri",
"conversation":"ostatus:conversation",
"toot":"http://joinmastodon.org/ns#",
"Emoji":"toot:Emoji",
"focalPoint": {
"@container":"@list",
"@id":"toot:focalPoint"
},
"featured":"toot:featured"
}
])
}
pub struct ActivityStream<T>(T);
2018-05-16 20:20:44 +02:00
impl<T> ActivityStream<T> {
pub fn new(t: T) -> ActivityStream<T> {
ActivityStream(t)
}
}
impl<'r, O: serde::Serialize> Responder<'r> for ActivityStream<O> {
2020-01-21 07:02:03 +01:00
fn respond_to(self, request: &Request<'_>) -> Result<Response<'r>, Status> {
let mut json = serde_json::to_value(&self.0).map_err(|_| Status::InternalServerError)?;
json["@context"] = context();
serde_json::to_string(&json).respond_to(request).map(|r| {
Response::build_from(r)
.raw_header("Content-Type", "application/activity+json")
.finalize()
})
2018-05-16 20:20:44 +02:00
}
}
#[derive(Clone)]
pub struct ApRequest;
impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
request
.headers()
.get_one("Accept")
.map(|header| {
header
.split(',')
2022-05-03 19:01:58 +02:00
.map(|ct| {
match ct.trim() {
// bool for Forward: true if found a valid Content-Type for Plume first (HTML), false otherwise
2022-05-03 19:01:58 +02:00
"application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""
| "application/ld+json;profile=\"https://www.w3.org/ns/activitystreams\""
| "application/activity+json"
| "application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false),
2022-05-03 19:01:58 +02:00
}
})
.fold(Outcome::Forward(false), |out, ct| {
if out.clone().forwarded().unwrap_or_else(|| out.is_success()) {
out
} else {
ct
}
})
.map_forward(|_| ())
})
.unwrap_or(Outcome::Forward(()))
}
}
2018-05-16 20:20:44 +02:00
pub fn broadcast<S, A, T, C>(sender: &S, act: A, to: Vec<T>, proxy: Option<reqwest::Proxy>)
where
S: sign::Signer,
2022-05-02 18:10:44 +02:00
A: Activity + serde::Serialize,
T: inbox::AsActor<C>,
{
let boxes = to
.into_iter()
2022-05-03 05:36:31 +02:00
.filter(|u| !u.is_local())
.map(|u| {
u.get_shared_inbox_url()
.unwrap_or_else(|| u.get_inbox_url())
})
.collect::<Vec<String>>()
.unique();
let mut act = serde_json::to_value(act).expect("activity_pub::broadcast: serialization error");
act["@context"] = context();
let signed = act
.sign(sender)
.expect("activity_pub::broadcast: signature error");
2022-05-03 21:40:16 +02:00
let client = if let Some(proxy) = proxy {
ClientBuilder::new().proxy(proxy)
} else {
ClientBuilder::new()
}
.connect_timeout(std::time::Duration::from_secs(5))
.build()
.expect("Can't build client");
2022-05-04 21:34:04 +02:00
let rt = runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("Error while initializing tokio runtime for federation");
2022-05-04 21:34:04 +02:00
rt.block_on(async {
2022-05-05 09:29:52 +02:00
// TODO: should be determined dependent on database connections because
// after broadcasting, target instance sends request to this instance,
// and Plume accesses database at that time.
2022-05-05 08:50:44 +02:00
let capacity = 6;
2022-05-05 06:03:41 +02:00
let (tx, rx) = flume::bounded::<RequestBuilder>(capacity);
let mut handles = Vec::with_capacity(capacity);
for _ in 0..capacity {
let rx = rx.clone();
let handle = rt.spawn(async move {
while let Ok(request_builder) = rx.recv_async().await {
2022-05-06 21:50:58 +02:00
// After broadcasting, target instance sends request to this instance.
// Sleep here in order to reduce requests at once
sleep(Duration::from_millis(500)).await;
2022-05-05 06:03:41 +02:00
let _ = request_builder
.send()
.await
.map(move |r| {
if r.status().is_success() {
debug!("Successfully sent activity to inbox ({})", &r.url());
} else {
warn!("Error while sending to inbox ({:?})", &r)
}
debug!("Response: \"{:?}\"\n", r);
})
.map_err(|e| warn!("Error while sending to inbox ({:?})", e));
}
});
handles.push(handle);
}
2022-05-04 21:34:04 +02:00
for inbox in boxes {
let body = signed.to_string();
let mut headers = request::headers();
let url = Url::parse(&inbox);
if url.is_err() {
warn!("Inbox is invalid URL: {:?}", &inbox);
continue;
}
let url = url.unwrap();
if !url.has_host() {
warn!("Inbox doesn't have host: {:?}", &inbox);
continue;
};
let host_header_value = HeaderValue::from_str(url.host_str().expect("Unreachable"));
if host_header_value.is_err() {
warn!("Header value is invalid: {:?}", url.host_str());
continue;
}
headers.insert("Host", host_header_value.unwrap());
headers.insert("Digest", request::Digest::digest(&body));
headers.insert(
2022-05-04 14:12:35 +02:00
"Signature",
request::signature(sender, &headers, ("post", url.path(), url.query()))
.expect("activity_pub::broadcast: request signature error"),
2022-05-04 21:34:04 +02:00
);
2022-05-05 06:12:04 +02:00
let request_builder = client.post(&inbox).headers(headers.clone()).body(body);
2022-05-05 09:35:03 +02:00
let _ = tx.send_async(request_builder).await;
2022-05-04 21:34:04 +02:00
}
2022-05-05 06:03:41 +02:00
drop(tx);
join_all(handles).await;
2022-05-04 21:34:04 +02:00
});
}
#[derive(Shrinkwrap, Clone, Serialize, Deserialize)]
2018-05-19 11:50:56 +02:00
pub struct Id(String);
2018-05-16 20:20:44 +02:00
impl Id {
pub fn new(id: impl ToString) -> Id {
Id(id.to_string())
}
}
impl AsRef<str> for Id {
fn as_ref(&self) -> &str {
&self.0
}
}
2018-05-18 10:04:40 +02:00
pub trait IntoId {
2018-05-19 00:04:30 +02:00
fn into_id(self) -> Id;
2018-05-18 10:04:40 +02:00
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
2022-05-02 17:29:44 +02:00
pub struct ApSignature {
pub public_key: PublicKey,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
2022-05-02 17:29:44 +02:00
pub struct PublicKey {
pub id: IriString,
pub owner: IriString,
pub public_key_pem: String,
}
2022-05-02 17:29:44 +02:00
impl<U> UnparsedExtension<U> for ApSignature
where
U: UnparsedMutExt,
{
type Error = serde_json::Error;
fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
2022-05-02 17:29:44 +02:00
Ok(ApSignature {
public_key: unparsed_mut.remove("publicKey")?,
})
}
fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
unparsed_mut.insert("publicKey", self.public_key)?;
Ok(())
}
}
2022-02-23 17:58:05 +01:00
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
2022-03-06 16:03:01 +01:00
pub struct SourceProperty {
2022-02-23 17:58:05 +01:00
pub source: Source,
}
2022-03-06 16:03:01 +01:00
impl<U> UnparsedExtension<U> for SourceProperty
2022-02-23 17:58:05 +01:00
where
U: UnparsedMutExt,
{
type Error = serde_json::Error;
fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
2022-03-06 16:03:01 +01:00
Ok(SourceProperty {
2022-02-23 17:58:05 +01:00
source: unparsed_mut.remove("source")?,
})
}
fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
unparsed_mut.insert("source", self.source)?;
Ok(())
}
}
2022-05-02 17:29:44 +02:00
pub type CustomPerson = Ext1<ApActor<Person>, ApSignature>;
pub type CustomGroup = Ext2<ApActor<Group>, ApSignature, SourceProperty>;
2022-05-02 17:10:51 +02:00
kind!(HashtagType, Hashtag);
2022-03-06 12:04:16 +01:00
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
2022-05-02 17:10:51 +02:00
pub struct Hashtag {
2022-03-06 12:04:16 +01:00
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<IriString>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<AnyString>,
#[serde(flatten)]
inner: Object<HashtagType>,
2022-03-06 12:04:16 +01:00
}
2022-05-02 17:10:51 +02:00
impl Hashtag {
2022-03-06 12:04:16 +01:00
pub fn new() -> Self {
2022-03-06 19:48:55 +01:00
Self {
2022-03-06 12:04:16 +01:00
href: None,
name: None,
inner: Object::new(),
2022-03-06 12:04:16 +01:00
}
}
pub fn extending(mut inner: Object<HashtagType>) -> Result<Self, serde_json::Error> {
2022-03-06 12:04:16 +01:00
let href = inner.remove("href")?;
let name = inner.remove("name")?;
2022-03-06 19:48:55 +01:00
Ok(Self { href, name, inner })
2022-03-06 12:04:16 +01:00
}
pub fn retracting(self) -> Result<Object<HashtagType>, serde_json::Error> {
2022-03-06 19:48:55 +01:00
let Self {
2022-03-06 12:04:16 +01:00
href,
name,
mut inner,
} = self;
inner.insert("href", href)?;
inner.insert("name", name)?;
Ok(inner)
}
}
pub trait AsHashtag: markers::Object {
2022-05-02 17:10:51 +02:00
fn hashtag_ref(&self) -> &Hashtag;
2022-03-06 12:04:16 +01:00
2022-05-02 17:10:51 +02:00
fn hashtag_mut(&mut self) -> &mut Hashtag;
2022-03-06 12:04:16 +01:00
}
pub trait HashtagExt: AsHashtag {
fn href(&self) -> Option<&IriString> {
self.hashtag_ref().href.as_ref()
}
fn set_href<T>(&mut self, href: T) -> &mut Self
where
T: Into<IriString>,
{
self.hashtag_mut().href = Some(href.into());
self
}
fn take_href(&mut self) -> Option<IriString> {
self.hashtag_mut().href.take()
}
fn delete_href(&mut self) -> &mut Self {
self.hashtag_mut().href = None;
self
}
fn name(&self) -> Option<&AnyString> {
self.hashtag_ref().name.as_ref()
}
fn set_name<T>(&mut self, name: T) -> &mut Self
where
T: Into<AnyString>,
{
self.hashtag_mut().name = Some(name.into());
self
}
fn take_name(&mut self) -> Option<AnyString> {
self.hashtag_mut().name.take()
}
fn delete_name(&mut self) -> &mut Self {
self.hashtag_mut().name = None;
self
}
}
2022-05-02 17:10:51 +02:00
impl Default for Hashtag {
2022-03-06 19:48:55 +01:00
fn default() -> Self {
Self::new()
}
}
2022-05-02 17:10:51 +02:00
impl AsHashtag for Hashtag {
2022-03-06 19:48:55 +01:00
fn hashtag_ref(&self) -> &Self {
2022-03-06 12:04:16 +01:00
self
}
2022-03-06 19:48:55 +01:00
fn hashtag_mut(&mut self) -> &mut Self {
2022-03-06 12:04:16 +01:00
self
}
}
2022-05-02 17:10:51 +02:00
impl Extends<HashtagType> for Hashtag {
2022-03-06 12:04:16 +01:00
type Error = serde_json::Error;
2022-05-02 17:10:51 +02:00
fn extends(base: Base<HashtagType>) -> Result<Self, Self::Error> {
let inner = Object::extends(base)?;
2022-03-06 12:04:16 +01:00
Self::extending(inner)
}
2022-05-02 17:10:51 +02:00
fn retracts(self) -> Result<Base<HashtagType>, Self::Error> {
2022-03-06 12:04:16 +01:00
let inner = self.retracting()?;
inner.retracts()
}
}
2022-05-02 17:10:51 +02:00
impl markers::Base for Hashtag {}
impl markers::Object for Hashtag {}
2022-03-06 12:04:16 +01:00
impl<T> HashtagExt for T where T: AsHashtag {}
2022-02-23 17:58:05 +01:00
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Source {
pub media_type: String,
pub content: String,
}
2022-02-23 17:58:05 +01:00
impl<U> UnparsedExtension<U> for Source
where
U: UnparsedMutExt,
{
type Error = serde_json::Error;
fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
Ok(Source {
content: unparsed_mut.remove("content")?,
media_type: unparsed_mut.remove("mediaType")?,
})
}
fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
unparsed_mut.insert("content", self.content)?;
unparsed_mut.insert("mediaType", self.media_type)?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
2022-05-02 18:15:13 +02:00
pub struct Licensed {
pub license: Option<String>,
}
2022-05-02 18:15:13 +02:00
impl<U> UnparsedExtension<U> for Licensed
where
U: UnparsedMutExt,
{
type Error = serde_json::Error;
fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
2022-05-02 18:15:13 +02:00
Ok(Licensed {
license: unparsed_mut.remove("license")?,
})
}
fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
unparsed_mut.insert("license", self.license)?;
Ok(())
}
}
2022-05-03 03:04:22 +02:00
pub type LicensedArticle = Ext1<ApObject<Article>, Licensed>;
pub trait ToAsString {
fn to_as_string(&self) -> Option<String>;
}
impl ToAsString for OneOrMany<&AnyString> {
fn to_as_string(&self) -> Option<String> {
2022-02-12 17:15:39 +01:00
self.as_as_str().map(|s| s.to_string())
}
}
2022-02-12 16:59:15 +01:00
trait AsAsStr {
fn as_as_str(&self) -> Option<&str>;
}
impl AsAsStr for OneOrMany<&AnyString> {
fn as_as_str(&self) -> Option<&str> {
2022-02-14 12:44:28 +01:00
self.iter().next().map(|prop| prop.as_str())
}
}
pub trait ToAsUri {
fn to_as_uri(&self) -> Option<String>;
}
impl ToAsUri for OneOrMany<AnyBase> {
fn to_as_uri(&self) -> Option<String> {
2022-02-14 12:44:28 +01:00
self.iter()
.next()
.and_then(|prop| prop.as_xsd_any_uri().map(|uri| uri.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
2022-05-03 03:04:22 +02:00
use activitystreams::{
activity::{ActorAndObjectRef, Create},
object::kind::ArticleType,
};
use assert_json_diff::assert_json_eq;
use serde_json::{from_str, json, to_value};
#[test]
fn se_ap_signature() {
2022-05-02 17:29:44 +02:00
let ap_signature = ApSignature {
public_key: PublicKey {
id: "https://example.com/pubkey".parse().unwrap(),
owner: "https://example.com/owner".parse().unwrap(),
public_key_pem: "pubKeyPem".into(),
},
};
let expected = json!({
"publicKey": {
"id": "https://example.com/pubkey",
"owner": "https://example.com/owner",
"publicKeyPem": "pubKeyPem"
}
});
assert_json_eq!(to_value(ap_signature).unwrap(), expected);
}
#[test]
fn de_ap_signature() {
2022-05-02 17:29:44 +02:00
let value: ApSignature = from_str(
r#"
{
"publicKey": {
"id": "https://example.com/",
"owner": "https://example.com/",
"publicKeyPem": ""
}
}
"#,
)
.unwrap();
2022-05-02 17:29:44 +02:00
let expected = ApSignature {
public_key: PublicKey {
id: "https://example.com/".parse().unwrap(),
owner: "https://example.com/".parse().unwrap(),
public_key_pem: "".into(),
},
};
assert_eq!(value, expected);
}
#[test]
fn se_custom_person() {
let actor = ApActor::new("https://example.com/inbox".parse().unwrap(), Person::new());
let person = CustomPerson::new(
actor,
2022-05-02 17:29:44 +02:00
ApSignature {
public_key: PublicKey {
id: "https://example.com/pubkey".parse().unwrap(),
owner: "https://example.com/owner".parse().unwrap(),
public_key_pem: "pubKeyPem".into(),
},
},
);
let expected = json!({
"inbox": "https://example.com/inbox",
"type": "Person",
"publicKey": {
"id": "https://example.com/pubkey",
"owner": "https://example.com/owner",
"publicKeyPem": "pubKeyPem"
}
});
assert_eq!(to_value(person).unwrap(), expected);
}
2022-05-03 03:16:57 +02:00
#[test]
2023-01-04 17:16:13 +01:00
fn se_custom_group() {
2022-05-03 03:16:57 +02:00
let group = CustomGroup::new(
ApActor::new("https://example.com/inbox".parse().unwrap(), Group::new()),
ApSignature {
public_key: PublicKey {
id: "https://example.com/pubkey".parse().unwrap(),
owner: "https://example.com/owner".parse().unwrap(),
public_key_pem: "pubKeyPem".into(),
},
},
SourceProperty {
source: Source {
content: String::from("This is a *custom* group."),
media_type: String::from("text/markdown"),
},
},
);
let expected = json!({
"inbox": "https://example.com/inbox",
"type": "Group",
"publicKey": {
"id": "https://example.com/pubkey",
"owner": "https://example.com/owner",
"publicKeyPem": "pubKeyPem"
},
"source": {
"content": "This is a *custom* group.",
"mediaType": "text/markdown"
}
});
assert_eq!(to_value(group).unwrap(), expected);
}
#[test]
fn se_licensed_article() {
let object = ApObject::new(Article::new());
let licensed_article = LicensedArticle::new(
object,
2022-05-02 18:15:13 +02:00
Licensed {
license: Some("CC-0".into()),
},
);
let expected = json!({
"type": "Article",
"license": "CC-0",
});
assert_json_eq!(to_value(licensed_article).unwrap(), expected);
}
#[test]
fn de_licensed_article() {
let value: LicensedArticle = from_str(
r#"
{
"type": "Article",
"id": "https://plu.me/~/Blog/my-article",
"attributedTo": ["https://plu.me/@/Admin", "https://plu.me/~/Blog"],
"content": "Hello.",
"name": "My Article",
"summary": "Bye.",
"source": {
"content": "Hello.",
"mediaType": "text/markdown"
},
"published": "2014-12-12T12:12:12Z",
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"license": "CC-0"
}
"#,
)
.unwrap();
let expected = json!({
"type": "Article",
"id": "https://plu.me/~/Blog/my-article",
"attributedTo": ["https://plu.me/@/Admin", "https://plu.me/~/Blog"],
"content": "Hello.",
"name": "My Article",
"summary": "Bye.",
"source": {
"content": "Hello.",
"mediaType": "text/markdown"
},
"published": "2014-12-12T12:12:12Z",
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"license": "CC-0"
});
assert_eq!(to_value(value).unwrap(), expected);
}
#[test]
fn de_create_with_licensed_article() {
2022-05-03 03:04:22 +02:00
let create: Create = from_str(
r#"
{
"id": "https://plu.me/~/Blog/my-article",
"type": "Create",
"actor": "https://plu.me/@/Admin",
"to": "https://www.w3.org/ns/activitystreams#Public",
"object": {
"type": "Article",
"id": "https://plu.me/~/Blog/my-article",
"attributedTo": ["https://plu.me/@/Admin", "https://plu.me/~/Blog"],
"content": "Hello.",
"name": "My Article",
"summary": "Bye.",
"source": {
"content": "Hello.",
"mediaType": "text/markdown"
},
"published": "2014-12-12T12:12:12Z",
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"license": "CC-0"
}
}
"#,
)
.unwrap();
2022-05-03 03:04:22 +02:00
let base = create.object_field_ref().as_single_base().unwrap();
let any_base = AnyBase::from_base(base.clone());
let value = any_base.extend::<LicensedArticle, ArticleType>().unwrap();
let expected = json!({
2022-05-03 03:04:22 +02:00
"type": "Article",
"id": "https://plu.me/~/Blog/my-article",
2022-05-03 03:04:22 +02:00
"attributedTo": ["https://plu.me/@/Admin", "https://plu.me/~/Blog"],
"content": "Hello.",
"name": "My Article",
"summary": "Bye.",
"source": {
"content": "Hello.",
2022-05-03 03:04:22 +02:00
"mediaType": "text/markdown"
},
"published": "2014-12-12T12:12:12Z",
"to": ["https://www.w3.org/ns/activitystreams#Public"],
"license": "CC-0"
});
assert_eq!(to_value(value).unwrap(), expected);
}
}