about summary refs log tree commit diff
path: root/templates/src/lib.rs
blob: 01c69ab50aa064e43c8d998f5bc87051e589984a (plain) (blame)
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
mod templates;
pub use templates::{ErrorPage, MainPage, Template, POSTS_PER_PAGE, Entry, VCard, Feed};
mod onboarding;
pub use onboarding::OnboardingPage;
mod login;
pub use login::LoginPage;

#[cfg(test)]
mod tests {
    use serde_json::json;
    use microformats::types::Document;

    enum PostType {
        Note,
        Article,
        ReplyTo(serde_json::Value),
        ReplyToLink(String),
        LikeOf(serde_json::Value),
        LikeOfLink(String)
    }

    fn gen_hcard(domain: &str) -> serde_json::Value {
        use faker_rand::en_us::names::FirstName;

        json!({
            "type": ["h-card"],
            "properties": {
                "name": [rand::random::<FirstName>().to_string()],
                "photo": [format!("https://{domain}/media/me.png")],
                "uid": [format!("https://{domain}/")],
                "url": [format!("https://{domain}/")]
            }
        })
    }
    
    fn gen_random_post(domain: &str, kind: PostType) -> serde_json::Value {
        use faker_rand::lorem::{Paragraph, Word, Sentence};

        fn html(content: Paragraph) -> serde_json::Value {
            json!({
                "html": format!("<p>{}</p>", content),
                "value": content.to_string()
            })
        }
            
        let uid = format!(
            "https://{domain}/posts/{}-{}-{}",
            rand::random::<Word>(), rand::random::<Word>(), rand::random::<Word>()
        );
        let dt = chrono::offset::Local::now()
            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);

        match kind {
            PostType::Note => {
                let content = rand::random::<Paragraph>();

                json!({
                    "type": ["h-entry"],
                    "properties": {
                        "content": [html(content)],
                        "published": [dt],
                        "uid": [&uid],
                        "url": [&uid],
                        "author": [gen_hcard(domain)]
                    }
                })
            }
            PostType::Article => {
                let content = rand::random::<Paragraph>();
                let name = rand::random::<Sentence>();

                json!({
                    "type": ["h-entry"],
                    "properties": {
                        "content": [html(content)],
                        "published": [dt],
                        "uid": [&uid],
                        "url": [&uid],
                        "author": [gen_hcard(domain)],
                        "name": [name.to_string()]
                    }
                })
            }
            _ => todo!()
        }
    }

    #[test]
    #[ignore = "see https://gitlab.com/maxburon/microformats-parser/-/issues/7"]
    fn test_note() {
        use microformats::types::PropertyValue;
        use faker_rand::en_us::internet::Domain;

        test_logger::ensure_env_logger_initialized();

        let mf2 = gen_random_post(
            &rand::random::<Domain>().to_string(),
            PostType::Note
        );

        let html = crate::templates::Entry {
            post: &mf2
        }.to_string();
        println!("\n```html\n{}\n```", &html);
        let url: microformats::types::Url = mf2["properties"]["uid"][0].as_str()
            .unwrap()
            .parse()
            .unwrap();
        let parsed: Document = microformats::from_html(&html, url.clone()).unwrap();

        let item = parsed.get_item_by_url(&url).unwrap();
        println!("\n```json\n{}\n```", serde_json::to_string_pretty(&item).unwrap());
        if let PropertyValue::Item(item) = item {
            let _item = item.borrow();
            let props = _item.properties.borrow();

            if let PropertyValue::Fragment(content) = props.get("content").and_then(|v| v.first()).unwrap() {
                assert_eq!(content.html, mf2["properties"]["content"][0]["html"].as_str().unwrap());
            } else {
                unreachable!()
            }

            assert!(props.contains_key("published"));
            use microformats::types::temporal::Value as TemporalValue;
            if let Some(PropertyValue::Temporal(
                TemporalValue::Timestamp(item)
            )) = props.get("published")
                .and_then(|v| v.first())
            {
                use chrono::{DateTime, FixedOffset, NaiveDateTime};

                let offset = item.as_offset().unwrap().data;
                let ndt: NaiveDateTime = item.as_date().unwrap().data
                    .and_time(item.as_time().unwrap().data)
                    - offset;
                let dt = DateTime::<FixedOffset>::from_utc(ndt, offset);

                let expected: DateTime<FixedOffset> = chrono::DateTime::parse_from_rfc3339(
                    mf2["properties"]["published"][0].as_str().unwrap()
                ).unwrap();

                assert_eq!(dt, expected);
            } else {
                panic!("Failed to find datetime in properties!");
            }
                
            assert!(props.contains_key("uid"));
            assert!(props.contains_key("url"));
            assert!(props.get("url")
                    .unwrap()
                    .iter()
                    .any(|i| i == props.get("uid").and_then(|v| v.first()).unwrap()));
            // XXX: fails because of https://gitlab.com/maxburon/microformats-parser/-/issues/7
            assert!(!props.contains_key("name"));

        } else {
            unreachable!()
        }
    }
}