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
use crate::{
cat_thread::Page, error::DotError, header, Dot4chClient, IfModifiedSince, Procedures, Update, Result
};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use log::debug;
use reqwest::{header::IF_MODIFIED_SINCE, Response, StatusCode};
use tokio::time;
#[derive(Debug)]
pub struct Catalog {
board: String,
threads: Vec<Page>,
last_accessed: DateTime<Utc>,
client: Dot4chClient,
}
impl Catalog {
pub async fn new(client: &Dot4chClient, board: &str) -> Result<Self> {
let url = format!("https://a.4cdn.org/{}/threads.json", board);
let threads = client.lock().await.get(&url).await?;
threads.error_for_status_ref().map_err(DotError::Reqwest)?;
let threads = threads.json::<Vec<Page>>().await?;
Ok(Self {
threads,
last_accessed: Utc::now(),
board: board.to_string(),
client: client.clone(),
})
}
pub fn update_time(mut self) {
self.last_accessed = Utc::now();
}
pub fn page(&self, index: usize) -> Option<&Page> {
self.threads.get(index)
}
pub fn all_pages(self) -> Vec<Page> {
self.threads
}
}
#[async_trait(?Send)]
impl Procedures for Catalog {
type Output = Self;
async fn refresh_time(&mut self) -> crate::Result<()> {
let since = Utc::now().signed_duration_since(self.last_accessed);
if since < Duration::seconds(10) {
let remaining = 10 - since.num_seconds();
debug!(
"Updating Catalog too quickly! Waiting for {} seconds",
remaining
);
if let Some(time) = Duration::seconds(10).checked_sub(&since) {
time::sleep(
time.to_std()
.expect("could not convert chrono time to stdtime"),
)
.await;
}
}
Ok(())
}
async fn fetch_status(self, response: Response) -> Result<Self::Output> {
match response.status() {
StatusCode::OK => Ok(self.from_response(response).await?),
StatusCode::NOT_MODIFIED => {
let mut catalog = self;
catalog.last_accessed = Utc::now();
Ok(catalog)
}
other => Err(DotError::Update(format!("recieved invalid status code: {}", other))),
}
}
async fn from_response(self, response: Response) -> crate::Result<Self::Output> {
let threads = response.json::<Vec<Page>>().await?;
let last_accessed = Utc::now();
Ok(Self {
threads,
last_accessed,
board: self.board.to_string(),
client: self.client.clone(),
})
}
}
#[async_trait(?Send)]
impl IfModifiedSince for Catalog {
async fn fetch(
client: &Dot4chClient,
url: &str,
header: &str,
) -> Result<Response> {
client
.lock()
.await
.req_client()
.get(url)
.header(IF_MODIFIED_SINCE, header)
.send()
.await
.map_err(DotError::Reqwest)
}
}
#[async_trait(?Send)]
impl Update for Catalog {
type Output = Self;
async fn update(mut self) -> crate::Result<Self> {
self.refresh_time().await?;
let updated_catalog = {
let header = header(&self.client).await;
let get_url = format!("https://a.4cdn.org/{}/threads.json", &self.board);
let response = Self::fetch(&self.client, &get_url, &header).await?;
self.client.lock().await.last_checked = Utc::now();
self.fetch_status(response).await?
};
Ok(updated_catalog)
}
}
impl<Idx> std::ops::Index<Idx> for Catalog
where Idx: std::slice::SliceIndex<[Page]> {
type Output = Idx::Output;
fn index(&self, index: Idx) -> &Self::Output {
&self.threads[index]
}
}
#[cfg(feature = "display")]
impl Display for Catalog {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let fmt = format!(
"Board: /{}/\nLast accessed: {}\nPages: {}",
self.board,
self.last_accessed.format("%a, %d %b %Y %T").to_string(),
self.threads.iter().map(Page::to_string).collect::<String>()
);
write!(f, "{}", fmt)
}
}