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
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
pub mod chapter;
pub mod directory;
pub mod directory_list;
pub mod recent_chapter;
pub(crate) mod tag;
pub(crate) mod utils;
use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use reqwest::Url;
use serde::de::DeserializeOwned;
use chapter::Chapter;
use directory::Directory;
use directory_list::DirectoryList;
use recent_chapter::RecentChapter;
pub use chapter::ChapterConfig;
pub use directory::DirectoryConfig;
pub use directory_list::DirectoryListConfig;
pub use recent_chapter::RecentChapterConfig;
pub use tag::TagItem;
static USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
pub static DYNASTY_READER_BASE: Lazy<Url> = Lazy::new(|| {
let s = std::env::var("DYNASTY_READER_BASE")
.unwrap_or_else(|_| "https://dynasty-scans.com".to_string());
let url = Url::parse(&s)
.expect("failed to parse `DYNASTY_READER_BASE` environment variable as `reqwest::Url`");
if url.cannot_be_a_base() {
panic!("`DYNASTY_READER_BASE` environment variable has invalid `reqwest::Url`")
}
url
});
#[derive(Debug, Clone)]
pub struct DynastyApi {
client: reqwest::Client,
}
impl Default for DynastyApi {
fn default() -> Self {
Self::new()
}
}
impl DynastyApi {
pub fn new() -> DynastyApi {
let client = reqwest::ClientBuilder::new()
.user_agent(USER_AGENT)
.build()
.unwrap();
DynastyApi::with_client(client)
}
pub fn with_client(client: reqwest::Client) -> DynastyApi {
DynastyApi { client }
}
pub async fn chapter(&self, config: ChapterConfig) -> Result<Chapter> {
self.execute_request_into_json(config).await
}
pub fn clone_reqwest_client(&self) -> reqwest::Client {
self.client.clone()
}
pub async fn directory(&self, config: DirectoryConfig) -> Result<Directory> {
use directory::UntaggedDirectory;
let directory_kind = config.kind;
self.execute_request_into_json(config)
.await
.map(|untagged: UntaggedDirectory| untagged.into_tagged(directory_kind))
}
pub async fn directory_list(&self, config: DirectoryListConfig) -> Result<DirectoryList> {
self.execute_request_into_json(config).await
}
pub async fn recent(&self, config: RecentChapterConfig) -> Result<RecentChapter> {
self.execute_request_into_json(config).await
}
async fn execute_request_into_json<R, T>(&self, route: R) -> Result<T>
where
R: DynastyReaderRoute,
T: DeserializeOwned,
{
let request_url = route.request_url();
self.execute_request(route)
.await?
.json::<T>()
.await
.with_context(|| format!("unable to parse {} response", request_url,))
}
async fn execute_request<R: DynastyReaderRoute>(&self, route: R) -> Result<reqwest::Response> {
let request_url = route.request_url();
route
.request_builder(&self.client, request_url.clone())
.send()
.await
.with_context(|| format!("failed to send request to {}", request_url))?
.error_for_status()
.map_err(|reqwest_error| {
anyhow::anyhow!(
"request to {} returns an unexpected status code `{}`",
request_url,
reqwest_error
.status()
.map(|status| status.as_u16())
.unwrap_or(500)
)
})
}
}
trait DynastyReaderRoute {
fn request_builder(&self, client: &reqwest::Client, url: Url) -> reqwest::RequestBuilder;
fn request_url(&self) -> reqwest::Url;
}
#[cfg(test)]
mod test_utils {
use std::{future::Future, time::Duration};
use anyhow::Result;
use once_cell::sync::Lazy;
use tryhard::{backoff_strategies::ExponentialBackoff, NoOnRetry, RetryFutureConfig};
use super::DynastyApi;
static DEFAULT_CLIENT: Lazy<DynastyApi> = Lazy::new(DynastyApi::default);
static TRYHARD_CONFIG: Lazy<RetryFutureConfig<ExponentialBackoff, NoOnRetry>> =
Lazy::new(|| RetryFutureConfig::new(7).exponential_backoff(Duration::from_millis(100)));
pub async fn tryhard_configs<T, F, R, X>(
configs: impl IntoIterator<Item = T>,
future: F,
) -> Result<()>
where
T: Clone + Send + Sync + 'static,
F: Fn(&'static DynastyApi, T) -> R + Send + Sync + Copy + 'static,
R: Future<Output = Result<X>> + Send + 'static,
X: Send + 'static,
{
let mut handles = Vec::new();
for config in configs.into_iter() {
handles.push(tokio::spawn(
tryhard::retry_fn(move || future(&DEFAULT_CLIENT, config.clone()))
.with_config(*TRYHARD_CONFIG),
))
}
for handle in handles {
handle.await??;
}
Ok(())
}
}