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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
//! This crate provides implementations of the [standards][standards] and [algorithms][algorithms] used with the IndieWeb.
//!
//! More information about what's available is in either the [algorithms][algorithms] or
//! [standards][standards] module. A required trait to use is the [HTTP Client][http::Client]
//! if you'd like to use your own networking stack that's compatible with [http][::http]. This
//! library also provides some [traits][traits] to extend common values with IndieWeb-adjacent
//! capabilities.
#[warn(missing_docs, invalid_doc_attributes, unused, deprecated, clippy::perf)]
#[deny(rustdoc::broken_intra_doc_links, dead_code, unsafe_code)]

/// A collection of algorithms commonly used in the IndieWeb.
/// This module provides a collection of implementation of known
/// algorithms when working with the IndieWeb or adjacent tooling.
pub mod algorithms;

/// A representation of errors from the IndieWeb error.
pub mod error;

/// A facade for HTTP interactions when working with this library.
pub mod http;

/// A collection of standards that the IndieWeb can support.
///
/// View <https://spec.indieweb.org> for more information.
pub mod standards;

/// Traits to extend everyday functionality with IndieWeb-adjacent tooling.
pub mod traits;

mod test;

#[doc(inline)]
pub use error::Error;

use microformats_types::Fragment;
use url::Url;

/// Converts into a concrete representation of text.
///
/// # Examples
/// ```
/// # use url::Url;
/// # use std::str::FromStr;
/// use microformats_types::Fragment;
/// use indieweb::parse_content_value;
///
/// assert_eq!(
///     vec![Fragment { value: "wow".to_string(), html: "<b>wow</b>".to_string(), lang: None }],
///     parse_content_value(serde_json::Value::String("<b>wow</b>".to_string()), &Url::from_str("https://indieweb.org").unwrap()),
///     "Converts text into a fragment represented with HTML santization."
/// );
pub fn parse_content_value<V>(v_opt: V, url: &Url) -> Vec<Fragment>
where
    V: TryInto<serde_json::Value>,
{
    use serde_json::Value;
    if let Ok(value) = v_opt.try_into() {
        match value {
            Value::String(text) => vec![Fragment {
                value: text.clone(),
                html: text,
                ..Default::default()
            }],
            Value::Object(obj) => {
                vec![serde_json::from_value::<Fragment>(Value::Object(obj)).unwrap_or_default()]
            }
            Value::Array(values) => values
                .into_iter()
                .flat_map(|v| parse_content_value(v, url))
                .collect::<Vec<_>>(),
            _ => vec![],
        }
    } else {
        Vec::default()
    }
}

#[test]
fn parse_content_value_from_string() {
    let u: Url = "http://foo.com".parse().unwrap();
    assert_eq!(
        parse_content_value(Some(serde_json::json!("plain text")), &u),
        vec![Fragment {
            html: "plain text".to_string(),
            value: "plain text".to_string(),
            lang: None
        }],
        "pulls out plain text"
    );

    assert_eq!(
        parse_content_value(Some(serde_json::json!("<strong>rich text</strong>")), &u),
        vec![Fragment {
            html: "<strong>rich text</strong>".to_string(),
            value: "rich text".to_string(),
            lang: None
        }],
        "pulls out rich text"
    );
}

#[test]
fn parse_content_value_from_object() {
    let u: Url = "http://foo.com".parse().unwrap();

    assert_eq!(
        parse_content_value(
            Some(serde_json::json!({"html":"<strong>plain text</strong>", "value": "plain text"})),
            &u
        ),
        vec![Fragment {
            html: "<strong>plain text</strong>".to_string(),
            value: "plain text".to_string(),
            lang: None
        }],
        "pulls out object highlighting HTML"
    );
}

#[test]
fn parse_content_value_from_array() {
    let u: Url = "http://foo.com".parse().unwrap();
    assert_eq!(
        parse_content_value(
            Some(
                serde_json::json!([{"html":"<strong>plain text</strong>", "value": "plain text"}])
            ),
            &u
        ),
        vec![Fragment {
            html: "<strong>plain text</strong>".to_string(),
            value: "plain text".to_string(),
            lang: None
        }],
        "pulls out plain text"
    );
}

#[test]
fn parse_content_value_from_unsupported_type() {
    let u: Url = "http://foo.com".parse().unwrap();
    assert_eq!(
        parse_content_value(Some(serde_json::json!(3)), &u),
        Vec::default(),
        "does not attempt to unfurl incompatible type"
    );
}

mod timestamp {
    use serde::de::Deserializer;

    struct FromIntegerVisitor;

    impl<'de> serde::de::Visitor<'de> for FromIntegerVisitor {
        type Value = chrono::DateTime<chrono::Utc>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a 64-bit integer representing a timestamp")
        }
        fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            i64::try_from(v)
                .map_err(serde::de::Error::custom)
                .and_then(|i| self.visit_i64(i))
        }

        fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if let Some(ndt) = chrono::NaiveDateTime::from_timestamp_opt(value, 0) {
                Ok(chrono::TimeZone::from_utc_datetime(&chrono::Utc, &ndt))
            } else {
                Err(serde::de::Error::custom(
                    chrono::RoundingError::TimestampExceedsLimit,
                ))
            }
        }
    }

    pub fn serialize<S>(
        dt: &chrono::DateTime<chrono::Utc>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_i64(dt.timestamp())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_i64(FromIntegerVisitor)
    }
}