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
use serde::{Deserialize, Serialize};

use crate::{
    directory_list::DirectoryListChapterItem, recent_chapter::RecentChapterItem, tag::TagItem,
    DynastyReaderRoute, DYNASTY_READER_BASE,
};

use self::utils::chapter_name_to_permalink;

/// A configuration to get a [Chapter]
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChapterConfig {
    pub name: String,
}

impl From<String> for ChapterConfig {
    fn from(s: String) -> Self {
        ChapterConfig { name: s }
    }
}

impl From<DirectoryListChapterItem> for ChapterConfig {
    fn from(item: DirectoryListChapterItem) -> Self {
        ChapterConfig { name: item.title }
    }
}

impl From<RecentChapterItem> for ChapterConfig {
    fn from(item: RecentChapterItem) -> Self {
        ChapterConfig { name: item.title }
    }
}

impl DynastyReaderRoute for ChapterConfig {
    fn request_builder(
        &self,
        client: &reqwest::Client,
        url: reqwest::Url,
    ) -> reqwest::RequestBuilder {
        client.get(url)
    }

    fn request_url(&self) -> reqwest::Url {
        let permalink = chapter_name_to_permalink(&self.name);

        DYNASTY_READER_BASE
            .join(&format!("chapters/{}.json", permalink))
            .unwrap()
    }
}

/// A wrapper around Dynasty Reader's chapter
///
/// # Example urls
///
/// - <https://dynasty-scans.com/chapters/momoiro_trance_ch01>
/// - <https://dynasty-scans.com/chapters/liar_satsuki_can_see_death_ch54>
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Chapter {
    pub title: String,
    pub long_title: String,
    pub permalink: String,
    pub released_on: String,
    pub added_on: String,
    pub tags: Vec<TagItem>,
    pub pages: Vec<ChapterPage>,
}

/// A Dynasty Reader's chapter page
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct ChapterPage {
    pub name: String,
    #[serde(deserialize_with = "crate::utils::join_path_with_dynasty_reader_base")]
    pub url: String,
}

mod utils {
    use once_cell::sync::OnceCell;
    use regex::Regex;

    use crate::utils::name_to_permalink;

    pub(super) fn chapter_name_to_permalink(chapter_name: &str) -> String {
        let chapter_re = {
            static CHAPTER_RE: OnceCell<Regex> = OnceCell::new();
            CHAPTER_RE.get_or_init(|| Regex::new(r"(ch[\d.]+):").unwrap())
        };

        let name = chapter_re
            .find(chapter_name)
            .map(|matches| &chapter_name[..matches.end()])
            .unwrap_or(chapter_name);

        name_to_permalink(name)
    }

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

        #[test]
        fn should_convert_chapter_name_to_permalink() {
            let predicates = [
                ("\"Toda-san,\"", "toda_san"),
                ("B.G.M.R.S.P.", "b_g_m_r_s_p"),
                ("Assorted NicoMaki (03015)", "assorted_nicomaki_03015"),
                (
                    "Adachi and Shimamura (Moke ver.) ch27.1: Leaving Azure",
                    "adachi_and_shimamura_moke_ver_ch27_1",
                ),
                (
                    "Love Live! Comic Anthology μ’s Precious Days ch01",
                    "love_live_comic_anthology_μs_precious_days_ch01",
                ),
                (
                    "a_story_about_doing_xx_to_girls_from_different_species_ch51",
                    "a_story_about_doing_xx_to_girls_from_different_species_ch51",
                ),
            ];

            for (left, right) in predicates {
                assert_eq!(chapter_name_to_permalink(left), right)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use anyhow::Result;

    use crate::test_utils::tryhard_configs;

    use super::*;

    fn create_config(c: &str) -> ChapterConfig {
        c.to_string().into()
    }

    #[tokio::test]
    #[ignore = "requires internet"]
    async fn response_structure() -> Result<()> {
        let configs = [
            "4-Koma Starlight ch01",
            "4-Koma Starlight ch01: Act 1: Nice To Meet You!",
            "4_koma_starlight_ch01",
            "Just ChisaTaki Kissing",
            "just_chisataki_kissing",
        ]
        .map(create_config);

        tryhard_configs(configs, |client, config| client.chapter(config)).await?;

        Ok(())
    }
}