magnetar/ext_activity_pub/src/recipe/block.rs

88 lines
2.5 KiB
Rust

use crate::object::activity::ActivityBlock;
use crate::object::Object;
use crate::recipe::RecipeError;
use crate::{extract_field, Id, ObjectRaw};
use serde::Deserialize;
#[derive(Clone, Debug)]
pub struct Block {
pub id: Id,
pub actor: Id,
pub object: Id,
pub to: Id,
}
impl Block {
fn parse(object: &ObjectRaw<impl AsRef<Object>>) -> Result<Block, RecipeError> {
let json = object.as_json();
let data: &Object = (*object.data).as_ref();
let ap_type = extract_field!(data, as_type, unwrap);
if ap_type.iter().all(|t| t != "Block") {
return Err(RecipeError::UnexpectedType(format!("{:?}", ap_type)));
}
let block = ActivityBlock::deserialize(json)?;
Ok(Block {
id: Id(extract_field!(block, as_id, unwrap | owned)),
actor: Id(extract_field!(
block,
actor,
unwrap | single | as_id | owned
)),
object: Id(extract_field!(
block,
object,
unwrap | single | as_id | owned
)),
to: Id(extract_field!(block, to, unwrap | single | as_id | owned)),
})
}
}
#[cfg(test)]
mod tests {
use crate::object::activity::{Activity, ActivityBlock, ActivityIgnore};
use crate::object::Object;
use crate::ObjectRaw;
use serde::Deserialize;
use serde_json::json;
#[test]
fn parse_json() {
let json = json!({
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://a.example.com/blocks/1",
"type": "Block",
"actor": "https://a.example.com/users/1",
"object": "https://b.example.com/users/2",
"to": "https://b.example.com/users/2",
});
let object = ObjectRaw::<Activity>::deserialize(json).unwrap();
let block = super::Block::parse(&object).unwrap();
println!("{:#?}", block);
}
#[test]
fn parse_json_with_multiple_types() {
let json = json!({
"@context": "https://www.w3.org/ns/activitystreams",
"id": "https://a.example.com/blocks/1",
"type": ["Block", "https://example.com/SomeOtherType"],
"actor": "https://a.example.com/users/1",
"object": "https://b.example.com/users/2",
"to": "https://b.example.com/users/2",
});
let object = ObjectRaw::<Activity>::deserialize(json).unwrap();
let block = super::Block::parse(&object).unwrap();
println!("{:#?}", block);
}
}