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
//! # dot4ch

//!
//! dot4ch is a convenient wrapper library around 4chan's API.
//!
//! This library can fetch and update:
//! - Posts
//! - Threads
//! - Catalog
//! - Boards
//!
//! While respecting 4chan's:  
//! - GET 1 second-per-request cooldown.
//! - `If-Modified-Since` headers with update requests.
//! - 10 second cooldown with [`thread::Thread`], [`catalog::Catalog`] and [`board::Board`] update requests.
//!
//! ## Example: Getting an image from the OP of a thread
//!
//! ```
//! #[tokio::main]
//! async fn main() {
//!     use dot4ch::{Client, thread::Thread};
//!     
//!     // Making a client.
//!     let mut client = Client::new();
//!     
//!     // Building a board.
//!     let board = "g";
//!
//!     // Getting a specific `Thread` from the board.
//!     let post_id = 76759434;
//!
//!     // Fetching a new thread.
//!     let thread = Thread::new(&client, board, post_id).await.unwrap();
//!     
//!     // Getting the OP of the thread.
//!     let post = thread.op();
//!     println!("{}", post.image_url(board).unwrap());
//! }
//! ```

// #![deny(anonymous_parameters, clippy::all, clippy::pedantic)]
#![allow(
    clippy::missing_const_for_fn,
    clippy::must_use_candidate,
    clippy::cast_precision_loss,
    clippy::struct_excessive_bools
)]

use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use crate::error::DotError;
use log::{info, trace};
use reqwest::Response;
use std::sync::Arc;
use tokio::{
    sync::Mutex,
    time::{sleep, Duration as TkDuration},
};

pub mod board;
mod cat_thread;
mod catalog;
pub mod error;
pub mod post;
pub mod thread;
pub use catalog::Catalog as Catalog;

/// Crate result type
pub(crate) type Result<T> = std::result::Result<T, DotError>;

/// The main client for accessing API.
/// Handles updates, board and `reqwest::Client`
#[derive(Debug)]
pub struct Client {
    /// The creation time of the client.
    creation_time: DateTime<Utc>,
    /// The reqwest client
    req_client: reqwest::Client,
    /// The last time a client was checked
    pub(crate) last_checked: DateTime<Utc>,
}

impl Client {
    /// Make a new chan api client.
    ///
    /// This client handles your cooldown and requests internally.
    /// Thread safe.
    pub fn new() -> Arc<Mutex<Self>> {
        let req_client = reqwest::Client::new();
        let last_checked = Utc::now();
        let creation_time = last_checked;
        info!("constructed client.");
        Arc::new(Mutex::new(Self {
            creation_time,
            req_client,
            last_checked,
        }))
    }

    /// Returns a reference to the reqwest client in the API client.
    pub fn req_client(&self) -> &reqwest::Client {
        &self.req_client
    }

    /// Constructs and sends a GET Request to the given 4chan URL.
    ///
    /// Respects the 4chan 1 request-per-second guideline.
    ///
    /// Returns a `Response` from the given 4chan url
    ///
    /// # Errors
    ///
    ///  This function will return an error if the `GET` request to the URL fails.
    pub async fn get(&mut self, url: &str) -> Result<Response> {
        let current_time = Utc::now().signed_duration_since(self.last_checked);

        if (current_time < Duration::seconds(1)) && (self.creation_time != self.last_checked) {
            trace!("Requesting responses too fast! Slowing down requests to 1 per second");
            sleep(TkDuration::from_secs(1)).await;
        }

        let resp = self.req_client.get(url).send().await?;
        self.last_checked = Utc::now();
        trace!(
            "Updated the client last checked time: {}",
            self.last_checked
        );
        Ok(resp)
    }
}

/// Type alias for an client in an Arc<Mutex<Client>>
type Dot4chClient = Arc<Mutex<Client>>;

/// Returns an If-Modified-Since header to be used in requests.
pub(crate) async fn header(client: &Dot4chClient) -> String {
    trace!("Sending request with If-Modified-Since header");
    format!(
        "{}",
        client
            .lock()
            .await
            .last_checked
            .format("%a, %d %b %Y %T GMT")
    )
}

/// Helper trait that sends a GET request from the reqwest client
/// with a If-Modified-Since header.
#[async_trait(?Send)]
pub trait IfModifiedSince {
    /// Fetches the given URL with an `If-Modifed-Since` header.
    async fn fetch(
        client: &Dot4chClient,
        url: &str,
        header: &str,
    ) -> Result<Response>;
}

/// Update trait specifies if something can be updated or not.
///
/// By default, only Threads, Catalogs, and Boards can be updated.
///
/// # Usecase Example
/// ```
/// use dot4ch::{Client, thread::Thread, Update};
///
/// # async fn update_usecase() {
/// let client = Client::new();
///
/// let thread = Thread::new(&client, "g", 76759434).await.unwrap();
///
/// /* --- do some work with the thread */
///
/// // time to update
/// let thread = thread.update().await.unwrap();
///
/// println!("{:?}", thread);
/// # }
/// ```
///
/// # Implementation Example
/// ```
/// # use async_trait::async_trait;
/// # use dot4ch::Update;
/// # use dot4ch::error::DotError;
/// # #[derive(Debug, Clone, Copy)]
/// struct Something(i32);
///
/// # #[async_trait(?Send)]
/// impl Update for Something {
///     // the output this trait should produce
///     type Output = ();
///     
///     async fn update(mut self) -> Result<Self::Output, DotError> {
///         self.0 += 32;
///         Ok(())
///     }
/// }
///
/// 
/// # fn update_test() {
/// let mut x = Something(21);
/// x.update();
/// assert_eq!(x.0, 53);
/// # }
/// ```
#[async_trait(?Send)]
pub trait Update {
    /// The type of the output.
    type Output;

    /// Returns the updated `self` type.
    async fn update(self) -> Result<Self::Output>;
}

/// Another helper trait for the [`Update`] trait.
#[async_trait(?Send)]
pub trait Procedures {
    /// The Output type.
    type Output;

    /// Refreshes the last time [`Self`]  was accessed.
    async fn refresh_time(&mut self) -> Result<()>;

    /// Matches the [`Self`]'s status code to see if it has been updated.
    async fn fetch_status(self, response: Response) -> Result<Self::Output>;

    /// Converts a [`Response`] into a concrete object.
    async fn from_response(self, response: Response) -> Result<Self::Output>;
}

#[doc(hidden)]
/// Returns the default of a type.
///
/// Used interally to generate missing fields for Post struct
fn default<T: Default>() -> T {
    Default::default()
}