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
272
273
274
275
276
277
278
279
use super::Md5Digest;
use std::num::NonZeroU64;
use time::OffsetDateTime;
use url::Url;

/// A list of posts
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct PostList {
    /// The # of posts.
    ///
    /// This is the total # of posts, not the # in this list.
    #[serde(rename = "@count")]
    pub count: u64,

    /// The current offset
    #[serde(rename = "@offset")]
    pub offset: u64,

    /// The posts
    #[serde(rename = "post", default)]
    pub posts: Box<[Post]>,
}

/// A Post
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct Post {
    /// The height of the original file.
    #[serde(rename = "@height")]
    pub height: NonZeroU64,

    /// The number of up-votes minus the number of down-votes.
    #[serde(rename = "@score")]
    pub score: i64,

    /// The main file url
    #[serde(rename = "@file_url")]
    pub file_url: Url,

    /// The parent post id
    #[serde(rename = "@parent_id", with = "serde_optional_str_non_zero_u64")]
    pub parent_id: Option<NonZeroU64>,

    /// The sample url
    #[serde(rename = "@sample_url")]
    pub sample_url: Url,

    /// The sample width
    #[serde(rename = "@sample_width")]
    pub sample_width: NonZeroU64,

    /// The sample height
    #[serde(rename = "@sample_height")]
    pub sample_height: NonZeroU64,

    /// The preview url
    #[serde(rename = "@preview_url")]
    pub preview_url: Url,

    /// The image rating
    #[serde(rename = "@rating")]
    pub rating: Rating,

    /// A list of tag names.
    ///
    /// Tag names are separated by one or more spaces.
    /// There may or may not be a leading or trailing space.
    /// Tag names are always lowercase.
    #[serde(rename = "@tags")]
    pub tags: Box<str>,

    /// The id the post
    #[serde(rename = "@id")]
    pub id: NonZeroU64,

    /// image width
    #[serde(rename = "@width")]
    pub width: NonZeroU64,

    /// The time of the last change.
    ///
    /// This tracks at least the date of posting and tag edits.
    /// This is a unix timestamp.
    #[serde(rename = "@change", with = "time::serde::timestamp")]
    pub change: OffsetDateTime,

    /// The md5 hash of the file.
    #[serde(rename = "@md5")]
    pub md5: Md5Digest,

    /// The creator id.
    #[serde(rename = "@creator_id")]
    pub creator_id: NonZeroU64,

    /// Whether this has children.
    #[serde(rename = "@has_children")]
    pub has_children: bool,

    /// The creation date of the post.
    #[serde(rename = "@created_at", with = "crate::util::asctime_with_offset")]
    pub created_at: OffsetDateTime,

    /// The status of the post.
    #[serde(rename = "@status")]
    pub status: PostStatus,

    /// The original source.
    ///
    /// May or may not be a url, it is filled manually by users.
    #[serde(rename = "@source", with = "serde_empty_str_is_none")]
    pub source: Option<Box<str>>,

    /// Whether the post has notes.
    #[serde(rename = "@has_notes")]
    pub has_notes: bool,

    /// Whether this post has comments.
    #[serde(rename = "@has_comments")]
    pub has_comments: bool,

    /// The preview image width.
    #[serde(rename = "@preview_width")]
    pub preview_width: NonZeroU64,

    /// The preview image height.
    #[serde(rename = "@preview_height")]
    pub preview_height: NonZeroU64,
}

impl Post {
    /// Iter over the tags in this object.
    ///
    /// There may be duplicate tags included.
    pub fn iter_tags(&self) -> impl Iterator<Item = &str> {
        self.tags
            .split(' ')
            .map(|tag| tag.trim())
            .filter(|tag| !tag.is_empty())
    }

    /// Get the html post url for this post.
    ///
    /// This allocates, so cache the result.
    pub fn get_html_post_url(&self) -> Url {
        crate::post_id_to_html_post_url(self.id)
    }
}

/// A post rating
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Rating {
    /// Questionable
    #[serde(rename = "q")]
    Questionable,

    /// Explicit
    #[serde(rename = "e")]
    Explicit,

    /// Safe
    #[serde(rename = "s")]
    Safe,
}

impl Rating {
    /// Get this as a char
    pub fn as_char(self) -> char {
        match self {
            Self::Questionable => 'q',
            Self::Explicit => 'e',
            Self::Safe => 's',
        }
    }

    /// Get this as a &str
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Questionable => "q",
            Self::Explicit => "e",
            Self::Safe => "s",
        }
    }
}

/// A Post Status
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PostStatus {
    /// Active, the default state.
    #[serde(rename = "active")]
    Active,

    /// Pending, probably waiting for moderator approval.
    #[serde(rename = "pending")]
    Pending,

    /// Deleted, the post has been deleted and metadata will soon be purged.
    #[serde(rename = "deleted")]
    Deleted,

    /// Flagged, the post is has been flagged for review by a moderator.
    #[serde(rename = "flagged")]
    Flagged,
}

mod serde_empty_str_is_none {
    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
        T: AsRef<str>,
    {
        match value.as_ref().map(|value| value.as_ref()) {
            Some(value) if value.is_empty() => serializer.serialize_none(),
            Some(value) => serializer.serialize_str(value.as_ref()),
            None => serializer.serialize_none(),
        }
    }

    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: serde::Deserializer<'de>,
        T: serde::Deserialize<'de> + AsRef<str>,
    {
        let string = T::deserialize(deserializer)?;
        if string.as_ref().is_empty() {
            Ok(None)
        } else {
            Ok(Some(string))
        }
    }
}

mod serde_optional_str_non_zero_u64 {
    use serde::de::Error;
    use std::{
        borrow::Cow,
        num::NonZeroU64,
        str::FromStr,
    };

    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: serde::Deserializer<'de>,
        T: FromStr,
        <T as FromStr>::Err: std::fmt::Display,
    {
        let data: Cow<'_, str> = serde::Deserialize::deserialize(deserializer)?;
        if data.is_empty() {
            return Ok(None);
        }

        Ok(Some(data.parse().map_err(D::Error::custom)?))
    }

    pub(super) fn serialize<S>(value: &Option<NonZeroU64>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match value {
            Some(value) => {
                let mut buffer = itoa::Buffer::new();
                serializer.serialize_str(buffer.format(value.get()))
            }
            None => serializer.serialize_str(""),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    const AOKURO_XML: &str = include_str!("../../test_data/aokuro.xml");

    #[test]
    fn aokuro() {
        let mut deserializer = quick_xml::de::Deserializer::from_str(AOKURO_XML);
        let _post_list: PostList =
            serde_path_to_error::deserialize(&mut deserializer).expect("failed to parse");
    }
}