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
/*
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use serde::{de, Deserialize};
use std::fmt;
use std::ops::Deref;
use time::format_description::FormatItem;
use time::macros::format_description;
use time::{OffsetDateTime, PrimitiveDateTime};

/// See [datatypes](https://en.wikipedia.org/w/api.php#main/datatypes) documentation
const MW_TIMESTAMP: &[FormatItem] =
    format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]Z");

/// A MediaWiki timestamp in UTC. Dereferences to [`time::OffsetDateTime`]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Deserialize)]
#[repr(transparent)]
#[serde(try_from = "String")]
pub struct Timestamp(OffsetDateTime);

impl Deref for Timestamp {
    type Target = OffsetDateTime;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl TryFrom<String> for Timestamp {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match PrimitiveDateTime::parse(&value, &MW_TIMESTAMP) {
            Ok(dt) => Ok(Self(dt.assume_utc())),
            Err(err) => Err(format!("Unable to parse timestamp: {}", err)),
        }
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // TODO: verify unwrap safety
        write!(f, "{}", self.0.format(&MW_TIMESTAMP).unwrap())
    }
}

/// A MediaWiki expiry, which can either be infinity (aka indefinite) or
/// a specific datetime in UTC
#[derive(Debug, Copy, Clone, Eq, PartialEq, Deserialize)]
#[serde(try_from = "String")]
pub enum Expiry {
    Infinity,
    Finite(Timestamp),
}

impl Expiry {
    /// Whether the expiry is for an infinte (aka indefinite) amount of time
    pub fn is_infinity(&self) -> bool {
        matches!(self, Self::Infinity)
    }

    /// If the expiry is finite, get a timestamp for it
    pub fn as_timestamp(&self) -> Option<&Timestamp> {
        match self {
            Expiry::Infinity => None,
            Expiry::Finite(datetime) => Some(datetime),
        }
    }
}

impl TryFrom<String> for Expiry {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value == "infinity" {
            return Ok(Self::Infinity);
        }

        Timestamp::try_from(value).map(Self::Finite)
    }
}

impl fmt::Display for Expiry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Expiry::Infinity => {
                write!(f, "infinity")
            }
            Expiry::Finite(ts) => {
                write!(f, "{}", ts)
            }
        }
    }
}

/// Not public, for internal use only.
///
/// Wrapper for notificationtimestamp which is Option<Timestamp>
/// except uses empty string for the none case
#[doc(hidden)]
pub fn deserialize_notificationtimestamp<'de, D>(
    deserializer: D,
) -> Result<Option<Timestamp>, D::Error>
where
    D: de::Deserializer<'de>,
{
    let val = String::deserialize(deserializer)?;
    if val.is_empty() {
        return Ok(None);
    }
    match Timestamp::try_from(val) {
        Ok(ts) => Ok(Some(ts)),
        Err(err) => Err(de::Error::custom(err)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use time::macros::{date, time};
    #[test]
    fn test_expiry_timestamp() {
        let infinity = Expiry::try_from("infinity".to_string()).unwrap();
        assert!(infinity.is_infinity());
        assert_eq!(&infinity.to_string(), "infinity");
        let expiry =
            Expiry::try_from("2001-01-15T14:56:00Z".to_string()).unwrap();
        let timestamp = expiry.as_timestamp().unwrap();
        assert_eq!(timestamp.date(), date!(2001 - 01 - 15));
        assert_eq!(timestamp.time(), time!(14:56:00));
        assert_eq!(&timestamp.to_string(), "2001-01-15T14:56:00Z");
    }
}