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
#![doc = include_str!("../README.md")]

use dmzj_proto::comic::{ComicChapterResponse, ComicDetailResponse};
use http_cache_reqwest::{
    Cache, CacheMode, HttpCache, HttpCacheOptions, MokaManager,
};
use protobuf::Message;
use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
use snafu::ResultExt;
use std::time::Duration;
use tracing::{event, Level};

use crate::crypto::decrypt_bytes;
use crate::error::{DmzjResult, ParseSnafu, ProtoBufSnafu, RequestSnafu};
use crate::model::{
    AuthorDetailsResponse, CategoryResponse, LatestUpdatesMangaItem,
    MangaSearchResponse, PopularMangaItem,
};

mod crypto;
/// Dmzj errors
pub mod error;
pub mod model;

/// `User-Agent` used by http client
pub const USER_AGENT: &str = "PostmanRuntime/7.28.4";

/// Dmzj API
#[derive(Debug, Clone)]
pub struct Api {
    http_client: ClientWithMiddleware,
}

impl Api {
    const V3_URL: &'static str = "https://v3api.idmzj.com";
    const V3_API_URL: &'static str = "https://nnv3api.idmzj.com";
    const V4_API_URL: &'static str = "https://nnv4api.dmzj.com";
    // const API_URL: &'static str = "https://api.dmzj.com";

    pub fn new() -> Self {
        let http_client = ClientBuilder::new(
            reqwest::ClientBuilder::new()
                .timeout(Duration::from_secs(30))
                .user_agent(USER_AGENT)
                .build()
                .expect("failed to build http client"),
        )
        .with(Cache(HttpCache {
            mode: CacheMode::Default,
            manager: MokaManager::default(),
            options: HttpCacheOptions::default(),
        }))
        .build();

        Self { http_client }
    }

    /// Construct a Client instance from a provided `reqwest_middleware` HTTP client
    pub fn from_http_client(http_client: ClientWithMiddleware) -> Self {
        Self { http_client }
    }

    fn popular_manga_url(page: u16) -> String {
        format!("{}/classify/0/0/{}.json", Self::V3_URL, page)
    }

    fn latest_updates_url(page: u16) -> String {
        format!("{}/classify/0/1/{}.json", Self::V3_URL, page)
    }

    // fn manga_info_url_v1(id: u32) -> String {
    //     format!("{}/dynamic/comicinfo/{}.json", Self::API_URL, id)
    // }

    fn manga_info_url(id: u32) -> String {
        format!("{}/comic/detail/{}?uid=2665531", Self::V4_API_URL, id)
    }

    // fn chapter_images_url_v1(path: String) -> String {
    //     format!("https://m.idmzj.com/chapinfo/{}.html", path)
    // }

    fn chapter_images_url(manga_id: u32, chapter_id: i32) -> String {
        format!(
            "{}/comic/chapter/{}/{}",
            Self::V4_API_URL,
            manga_id,
            chapter_id
        )
    }

    fn category_url() -> String {
        format!("{}/0/category.json", Self::V3_API_URL)
    }

    fn author_details_url(author_tag_id: i64) -> String {
        format!("{}/UCenter/author/{}.json", Self::V3_API_URL, author_tag_id)
    }

    fn search_url<T: AsRef<str>>(keyword: T, page: u16) -> String {
        format!(
            "{}/search/show/0/{}/{}.json",
            Self::V3_API_URL,
            keyword.as_ref(),
            page
        )
    }

    #[tracing::instrument(skip(self))]
    pub async fn fetch_popular_manga(
        &self,
        page: u16,
    ) -> DmzjResult<Vec<PopularMangaItem>> {
        let url = Self::popular_manga_url(page);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;
        response.json().await.context(ParseSnafu)
    }

    #[tracing::instrument(skip(self))]
    pub async fn fetch_latest_updates_manga(
        &self,
        page: u16,
    ) -> DmzjResult<Vec<LatestUpdatesMangaItem>> {
        let url = Self::latest_updates_url(page);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;
        response.json().await.context(ParseSnafu)
    }

    /// ```rust
    #[doc = include_str!("../examples/parse.rs")]
    /// ```
    #[tracing::instrument(skip(self))]
    pub async fn fetch_manga_details(
        &self,
        id: u32,
    ) -> DmzjResult<ComicDetailResponse> {
        let url = Self::manga_info_url(id);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;

        let bytes_from_res = response.bytes().await.context(ParseSnafu)?;

        let b = decrypt_bytes(bytes_from_res)?;

        ComicDetailResponse::parse_from_bytes(&b).context(ProtoBufSnafu)
    }

    /// ```rust
    #[doc = include_str!("../examples/chapter_images.rs")]
    /// ```
    #[tracing::instrument(skip(self))]
    pub async fn fetch_chapter_images(
        &self,
        manga_id: u32,
        chapter_id: i32,
    ) -> DmzjResult<ComicChapterResponse> {
        let url = Self::chapter_images_url(manga_id, chapter_id);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;

        let bytes_from_res = response.bytes().await.context(ParseSnafu)?;

        let b = decrypt_bytes(bytes_from_res)?;

        ComicChapterResponse::parse_from_bytes(&b).context(ProtoBufSnafu)
    }

    /// ```rust
    #[doc = include_str!("../examples/category.rs")]
    /// ```
    #[tracing::instrument(skip(self))]
    pub async fn fetch_category(&self) -> DmzjResult<CategoryResponse> {
        let url = Self::category_url();

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;

        response.json().await.context(ParseSnafu)
    }

    /// ```rust
    #[doc = include_str!("../examples/author_details.rs")]
    /// ```
    #[tracing::instrument(skip(self))]
    pub async fn fetch_author_details(
        &self,
        author_tag_id: i64,
    ) -> DmzjResult<AuthorDetailsResponse> {
        let url = Self::author_details_url(author_tag_id);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;

        response.json().await.context(ParseSnafu)
    }

    /// ```rust
    #[doc = include_str!("../examples/search.rs")]
    /// ```
    #[tracing::instrument(skip(self))]
    pub async fn search_manga<T: AsRef<str> + std::fmt::Debug>(
        &self,
        keyword: T,
        page: u16,
    ) -> DmzjResult<MangaSearchResponse> {
        let url = Self::search_url(keyword, page);

        event!(Level::DEBUG, url = url.as_str());

        let response = self
            .http_client
            .get(url)
            .send()
            .await
            .context(RequestSnafu)?;

        response.json().await.context(ParseSnafu)
    }
}

impl Default for Api {
    fn default() -> Self {
        Self::new()
    }
}