/** * Code to represent an activitystreams verb. * * SPDX-FileCopyrightText: 2023 Eilertsens Kodeknekkeri * SPDX-FileCopyrightText: 2023 Harald Eilertsen * * SPDX-License-Identifier: AGPL-3.0-or-later */ use serde::Deserialize; #[derive(Debug, PartialEq)] pub enum Verb { Announce, Create, Like, Post, Update, } impl<'de> Deserialize<'de> for Verb { fn deserialize(deserializer: D) -> Result where D: serde::de::Deserializer<'de>, { deserializer.deserialize_str(VerbVisitor) } } /** * Visitor used to deserialize an ActivityStreams verb from an Activity. * * Accepts both ActivityStream 1.0 and ActivityStreams 2.0 representations * of activities. */ struct VerbVisitor; impl<'de> serde::de::Visitor<'de> for VerbVisitor { type Value = Verb; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { write!(formatter, "a valid activity streams verb URI") } fn visit_str(self, s: &str) -> Result where E: serde::de::Error, { match s.to_lowercase().as_ref() { "announce" | "http://activitystrea.ms/schema/1.0/announce" => Ok(Verb::Announce), "create" | "http://activitystrea.ms/schema/1.0/create" => Ok(Verb::Create), "like" | "http://activitystrea.ms/schema/1.0/like" => Ok(Verb::Like), "post" | "http://activitystrea.ms/schema/1.0/post" => Ok(Verb::Post), "update" | "http://activitystrea.ms/schema/1.0/update" => Ok(Verb::Update), _ => Err(E::custom(format!("unknown activity streams verb: {}", s))) } } } #[cfg(test)] mod test { use super::*; #[test] fn deserialize_activitustreams_1_0_verb_from_json() { #[derive(Debug, Deserialize, PartialEq)] struct VerbTest { verb: Verb } let verbs = vec![ (Verb::Announce, "announce"), (Verb::Create, "create"), (Verb::Like, "like"), (Verb::Post, "post"), (Verb::Update, "update") ]; for v in verbs { let verb: VerbTest = serde_json::from_str( &format!(r#"{{"verb": "http://activitystrea.ms/schema/1.0/{}"}}"#, v.1) ).unwrap(); assert_eq!(v.0, verb.verb); } } #[test] fn deserialize_activitustreams_2_0_verb_from_json() { #[derive(Debug, Deserialize, PartialEq)] struct VerbTest { verb: Verb } let verbs = vec![ (Verb::Announce, "Announce"), (Verb::Announce, "announce"), (Verb::Create, "Create"), (Verb::Create, "create"), (Verb::Like, "Like"), (Verb::Like, "like"), (Verb::Post, "Post"), (Verb::Post, "post"), (Verb::Update, "Update"), (Verb::Update, "update") ]; for v in verbs { let verb: VerbTest = serde_json::from_str( &format!(r#"{{"verb": "{}"}}"#, v.1) ).unwrap(); assert_eq!(v.0, verb.verb); } } }