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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use std::{collections::BTreeMap, fmt::Display, marker::PhantomData, str::FromStr};

use iso8601::DateTime;
use nom::{branch::alt, bytes::complete::tag, combinator::map, sequence::tuple, IResult};
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};

const ROOT: &str = "https://github.com/bangumi-data/bangumi-data/raw/master";

#[cfg(feature = "reqwest")]
pub async fn get_all() -> Result<BangumiData, reqwest::Error> {
    reqwest::get(format!("{ROOT}/dist/data.json"))
        .await?
        .json()
        .await
}

#[cfg(feature = "reqwest")]
pub async fn get_by_month(year: u32, month: u8) -> Result<Vec<Item>, reqwest::Error> {
    assert!(month <= 12);
    assert!(year >= 1960);

    reqwest::get(format!("{ROOT}/data/items/{year}/{month:02}.json"))
        .await?
        .json()
        .await
}

#[cfg(feature = "reqwest")]
pub async fn get_info_site() -> Result<BTreeMap<String, SiteMeta>, reqwest::Error> {
    reqwest::get(format!("{ROOT}/data/sites/info.json"))
        .await?
        .json()
        .await
}

#[cfg(feature = "reqwest")]
pub async fn get_on_air_site() -> Result<BTreeMap<String, SiteMeta>, reqwest::Error> {
    reqwest::get(format!("{ROOT}/data/sites/onair.json"))
        .await?
        .json()
        .await
}

#[cfg(feature = "reqwest")]
pub async fn get_resource_site() -> Result<BTreeMap<String, SiteMeta>, reqwest::Error> {
    reqwest::get(format!("{ROOT}/data/sites/resource.json"))
        .await?
        .json()
        .await
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct BangumiData {
    pub site_meta: BTreeMap<String, SiteMeta>,
    pub items: Vec<Item>,
}

impl FromStr for BangumiData {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

impl BangumiData {
    pub fn from_bytes(s: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(s)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct SiteMeta {
    pub title: String,
    pub url_template: String,
    #[serde(rename = "type", deserialize_with = "empty_str", default)]
    pub site_type: Option<String>,
    pub regions: Option<Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ItemType {
    TV,
    Web,
    Ova,
    Movie,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct Item {
    pub title: String,
    pub title_translate: BTreeMap<Language, Vec<String>>,
    #[serde(rename = "type")]
    pub item_type: ItemType,
    pub lang: Language,
    pub official_site: String,
    #[serde(deserialize_with = "empty_str", default)]
    #[cfg_attr(feature = "ts", ts(type = "Option<String>"))]
    pub begin: Option<DateTime>,
    #[serde(deserialize_with = "empty_str", default)]
    #[cfg_attr(feature = "ts", ts(type = "Option<String>"))]
    pub end: Option<DateTime>,
    pub sites: Vec<Site>,
    #[serde(deserialize_with = "empty_str", default)]
    pub broadcast: Option<Broadcast>,
    #[serde(deserialize_with = "empty_str", default)]
    pub comment: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct Site {
    pub site: String,
    #[serde(deserialize_with = "empty_str", default)]
    pub id: Option<String>,
    #[serde(deserialize_with = "empty_str", default)]
    pub begin: Option<String>,
    #[serde(deserialize_with = "empty_str", default)]
    pub broadcast: Option<String>,
    #[serde(deserialize_with = "empty_str", default)]
    pub comment: Option<String>,
    #[serde(deserialize_with = "empty_str", default)]
    pub url: Option<String>,
    pub regions: Option<Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct Broadcast {
    #[cfg_attr(feature = "ts", ts(type = "String"))]
    pub begin: DateTime,
    #[cfg_attr(feature = "ts", ts(type = "String"))]
    pub period: Period,
}

impl FromStr for Broadcast {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse(s.as_bytes())
            .map_err(|e| format!("Unable to parse broadcast: {e}"))
            .map(|(_, b)| b)
    }
}

impl<'de> Deserialize<'de> for Broadcast {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Broadcast::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl Display for Broadcast {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let period = match self.period {
            Period::Once => "0D",
            Period::Daily => "1D",
            Period::Weekly => "7D",
            Period::Monthly => "1M",
        };
        write!(f, "R/{}/P{}", self.begin, period)
    }
}

impl Serialize for Broadcast {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum Period {
    Once,
    Daily,
    Weekly,
    Monthly,
}

fn empty_str<'de, T, D>(de: D) -> Result<Option<T>, D::Error>
where
    T: FromStr + 'de,
    T::Err: Display,
    D: Deserializer<'de>,
{
    struct EmptyStringVisitor<'de, T>(PhantomData<&'de T>);

    impl<'de, T> Visitor<'de> for EmptyStringVisitor<'de, T>
    where
        T: FromStr,
        T::Err: Display,
    {
        type Value = Option<T>;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a string")
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(None)
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            if v.is_empty() {
                return Ok(None);
            }
            T::from_str(v).map_err(serde::de::Error::custom).map(Some)
        }
    }

    de.deserialize_any(EmptyStringVisitor(PhantomData))
}

fn parse_period(input: &[u8]) -> IResult<&[u8], Period> {
    alt((
        map(tag("0D"), |_| Period::Once),
        map(tag("1D"), |_| Period::Daily),
        map(tag("7D"), |_| Period::Weekly),
        map(tag("1M"), |_| Period::Monthly),
    ))(input)
}

fn parse(input: &[u8]) -> IResult<&[u8], Broadcast> {
    map(
        tuple((
            tag("R/"),
            iso8601::parsers::parse_datetime,
            tag("/P"),
            parse_period,
        )),
        |(_, begin, _, period)| Broadcast { begin, period },
    )(input)
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[non_exhaustive]
pub enum Language {
    #[serde(rename = "zh-Hans")]
    ZhHans,
    #[serde(rename = "zh-Hant")]
    ZhHant,
    #[serde(rename = "en")]
    En,
    #[serde(rename = "ja")]
    Ja,
}

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

    #[test]
    fn test_datetime() {
        let time = iso8601::datetime("2020-01-01T13:00:00Z").unwrap();
        let (_, b) = parse(b"R/2020-01-01T13:00:00Z/P0D").unwrap();
        assert_eq!(b.period, Period::Once);
        assert_eq!(b.begin, time);
        let (_, b) = parse(b"R/2020-01-01T13:00:00Z/P1D").unwrap();
        assert_eq!(b.period, Period::Daily);
        let (_, b) = parse(b"R/2020-01-01T13:00:00Z/P7D").unwrap();
        assert_eq!(b.period, Period::Weekly);
        let (_, b) = parse(b"R/2020-01-01T13:00:00Z/P1M").unwrap();
        assert_eq!(b.period, Period::Monthly);
    }

    #[test]
    fn local() {
        let s = std::fs::read_to_string("data/dist.json").unwrap();
        let b = BangumiData::from_str(&s).unwrap();
        println!("{b:#?}",)
    }

    #[tokio::test]
    async fn remote() {
        println!("{:#?}\n============", get_all().await.unwrap());
        println!("{:#?}\n============", get_by_month(2023, 10).await.unwrap());
        println!("{:#?}\n============", get_info_site().await.unwrap());
        println!("{:#?}\n============", get_on_air_site().await.unwrap());
        println!("{:#?}\n============", get_resource_site().await.unwrap());
    }
}