1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
/**
* Code to represent an activitystreams verb.
*
* SPDX-FileCopyrightText: 2023 Eilertsens Kodeknekkeri
* SPDX-FileCopyrightText: 2023 Harald Eilertsen <haraldei@anduin.net>
*
* 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<D>(deserializer: D) -> Result<Verb, D::Error>
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<E>(self, s: &str) -> Result<Self::Value, E>
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);
}
}
}
|