rs621 0.5.0-alpha1

Rust crate for the E621 API (a large online archive of furry art).
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use super::{
    client::Client,
    error::{Error, Result as Rs621Result},
    post::Post,
    utils::{get_json_api_time, get_json_value_as},
};
use chrono::{offset::Utc, DateTime};
use serde_json::Value as JsonValue;
use std::convert::TryFrom;

/// An iterator over [`PoolListEntry`]s.
///
/// [`PoolListEntry`]: struct.PoolListEntry.html
#[derive(Debug)]
pub struct PoolIter<'a, C: reqwest_mock::Client> {
    client: &'a Client<C>,
    query: Option<String>,

    page: u64,
    chunk: Vec<Rs621Result<PoolListEntry>>,
    ended: bool,
}

impl<C: reqwest_mock::Client> PoolIter<'_, C> {
    fn new<'a>(client: &'a Client<C>, query: Option<&str>) -> PoolIter<'a, C> {
        PoolIter {
            client,
            query: query.map(urlencoding::encode),

            page: 1,
            chunk: Vec::new(),
            ended: false,
        }
    }
}

impl<C: reqwest_mock::Client> Iterator for PoolIter<'_, C> {
    type Item = Rs621Result<PoolListEntry>;

    fn next(&mut self) -> Option<Rs621Result<PoolListEntry>> {
        // check if we need to load a new chunk of results
        if self.chunk.is_empty() {
            // get the JSON
            match self.client.get_json(&format!(
                "https://e621.net/pool/index.json?page={}{}",
                {
                    let page = self.page;
                    self.page += 1;
                    page
                },
                match &self.query {
                    None => String::new(),
                    Some(title) => format!("&query={}", title),
                }
            )) {
                Ok(body) => {
                    // put everything in the chunk
                    self.chunk = body
                        .as_array()
                        .unwrap()
                        .iter()
                        .rev()
                        .map(|v| PoolListEntry::try_from(v))
                        .collect()
                }

                // if something goes wrong, make the chunk be a single Err, and end the iterator
                Err(e) => {
                    self.ended = true;
                    self.chunk = vec![Err(e)]
                }
            }
        }

        // it's over if the chunk is still empty
        self.ended |= self.chunk.is_empty();

        if !self.ended {
            // get a pool
            let pool = self.chunk.pop().unwrap();

            // return the pool
            Some(pool)
        } else {
            // pop any eventual error
            // Vec::pop returns None if the Vec is empty anyway
            self.chunk.pop()
        }
    }
}

/// Represents the pool information returned by pool listing functions.
///
/// The main difference between [`PoolListEntry`] and [`Pool`] is the absence of the description
/// field in the former.
/// You can convert a [`PoolListEntry`] to a regular [`Pool`] using a `&Client` because [`Pool`] is
/// `From<(PoolListEntry, &Client)>`:
///
/// ```no_run
/// # use rs621::client::Client;
/// # use rs621::pool::{Pool, PoolListEntry};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::convert::TryFrom;
///
/// let client = Client::new("MyProject/1.0 (by username on e621)")?;
///
/// let entry: PoolListEntry = client.pool_list().next().unwrap()?;
/// let pool = Pool::try_from((entry, &client))?;
///
/// println!("Description of pool #{}: {}", pool.id, pool.description);
/// # Ok(()) }
/// ```
/// _Note: This function performs a request; it will be subject to a short sleep time to ensure that
/// the API rate limit isn't exceeded._
///
/// [`Pool`]: struct.Pool.html
/// [`PoolListEntry`]: struct.PoolListEntry.html
#[derive(Debug)]
pub struct PoolListEntry {
    /// The raw JSON description of the pool list result (from the API).
    pub raw: String,

    /// The ID of the pool.
    pub id: u64,
    /// The name of the pool.
    pub name: String,
    /// When the pool was created.
    pub created_at: DateTime<Utc>,
    /// Last time the pool was updated.
    pub updated_at: DateTime<Utc>,
    /// The uploader's user ID.
    pub user_id: u64,
    /// Whether the pool is locked.
    pub is_locked: bool,
    /// How many posts the pool contains.
    pub post_count: u64,
}

impl TryFrom<&JsonValue> for PoolListEntry {
    type Error = super::error::Error;

    fn try_from(v: &JsonValue) -> Rs621Result<Self> {
        Ok(PoolListEntry {
            raw: v.to_string(),

            id: get_json_value_as(&v, "id", JsonValue::as_u64)?,
            name: get_json_value_as(&v, "name", JsonValue::as_str)?.to_string(),
            user_id: v["user_id"].as_u64().unwrap(),
            created_at: get_json_api_time(&v, "created_at")?,
            updated_at: get_json_api_time(&v, "updated_at")?,
            is_locked: get_json_value_as(&v, "is_locked", JsonValue::as_bool)?,
            post_count: v["post_count"].as_u64().unwrap(),
        })
    }
}

/// Structure representing a pool.
#[derive(Debug, PartialEq, Eq)]
pub struct Pool {
    /// The raw JSON description of the pool (from the API).
    pub raw: String,

    /// The ID of the pool.
    pub id: u64,
    /// The name of the pool.
    pub name: String,
    /// The pool's description.
    pub description: String,
    /// The uploader's user ID.
    pub user_id: u64,
    /// When the pool was created.
    pub created_at: DateTime<Utc>,
    /// Last time the pool was updated.
    pub updated_at: DateTime<Utc>,
    /// Whether the pool is locked.
    pub is_locked: bool,
    /// Whether the pool is locked.
    pub is_active: bool,
    /// The posts this pool contains.
    pub posts: Vec<Post>,
}

impl TryFrom<&JsonValue> for Pool {
    type Error = super::error::Error;

    fn try_from(v: &JsonValue) -> Rs621Result<Self> {
        Ok(Pool {
            raw: v.to_string(),

            id: get_json_value_as(&v, "id", JsonValue::as_u64)?,
            name: get_json_value_as(&v, "name", JsonValue::as_str)?.to_string(),
            description: get_json_value_as(&v, "description", JsonValue::as_str)?.to_string(),
            user_id: v["user_id"].as_u64().unwrap(),
            created_at: get_json_api_time(&v, "created_at")?,
            updated_at: get_json_api_time(&v, "updated_at")?,
            is_locked: get_json_value_as(&v, "is_locked", JsonValue::as_bool)?,
            is_active: get_json_value_as(&v, "is_active", JsonValue::as_bool)?,
            posts: v["posts"]
                .as_array()
                .unwrap()
                .iter()
                .map(Post::try_from)
                .collect::<Rs621Result<Vec<Post>>>()?,
        })
    }
}

impl<C: reqwest_mock::Client> TryFrom<(PoolListEntry, &Client<C>)> for Pool {
    type Error = Error;

    /// An easy way to convert a [`PoolListEntry`] into the corresponding [`Pool`]. Currently, it's
    /// just calling [`Client::get_pool`] with the `id` of the [`PoolListEntry`].
    ///
    /// [`Client`]: ../client/struct.Client.html
    /// [`Client::get_pool`]: ../client/struct.Client.html#method.get_pool
    /// [`Pool`]: struct.Pool.html
    /// [`PoolListEntry`]: struct.PoolListEntry.html
    fn try_from((r, c): (PoolListEntry, &Client<C>)) -> Rs621Result<Pool> {
        c.get_pool(r.id)
    }
}

impl<C: reqwest_mock::Client> Client<C> {
    /// Returns the pool with the given ID.
    ///
    /// ```no_run
    /// # use rs621::client::Client;
    /// # use rs621::pool::Pool;
    /// # fn main() -> rs621::error::Result<()> {
    /// let client = Client::new("MyProject/1.0 (by username on e621)")?;
    /// let pool = client.get_pool(18274)?;
    ///
    /// assert_eq!(pool.id, 18274);
    /// # Ok(()) }
    /// ```
    ///
    /// _Note: This function performs a request; it will be subject to a short sleep time to ensure
    /// that the API rate limit isn't exceeded._
    pub fn get_pool(&self, id: u64) -> Rs621Result<Pool> {
        let body = self.get_json(&format!("https://e621.net/pool/show.json?id={}", id))?;

        Pool::try_from(&body)
    }

    /// Returns an iterator over all the pools on the website.
    ///
    /// ```no_run
    /// # use rs621::client::Client;
    /// # use rs621::pool::Pool;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new("MyProject/1.0 (by username on e621)")?;
    ///
    /// for pool in client.pool_list().take(3) {
    ///     assert!(pool?.id != 0);
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// The iterator returns [`PoolListEntry`]s, which you can convert to regular [`Pool`]s because
    /// [`Pool`] is `From<(PoolListEntry, &Client)>`. See [`PoolListEntry`].
    ///
    /// _Note: This function performs a request; it will be subject to a short sleep time to ensure
    /// that the API rate limit isn't exceeded._
    ///
    /// [`Pool`]: ../pool/struct.Pool.html
    /// [`PoolListEntry`]: ../pool/struct.PoolListEntry.html
    pub fn pool_list<'a>(&'a self) -> PoolIter<'a, C> {
        PoolIter::new(self, None)
    }

    /// Search all the pools in the website and returns an iterator over the results.
    ///
    /// ```no_run
    /// # use rs621::client::Client;
    /// # use rs621::pool::Pool;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new("MyProject/1.0 (by username on e621)")?;
    ///
    /// for pool in client.pool_search("foo").take(3) {
    ///     assert!(pool?.name.contains("foo"));
    /// }
    /// # Ok(()) }
    /// ```
    ///
    /// The iterator returns [`PoolListEntry`]s, which you can convert to regular [`Pool`]s because
    /// [`Pool`] is `From<(PoolListEntry, &Client)>`. See [`PoolListEntry`].
    ///
    /// _Note: This function performs a request; it will be subject to a short sleep time to ensure
    /// that the API rate limit isn't exceeded._
    ///
    /// [`Pool`]: ../pool/struct.Pool.html
    /// [`PoolListEntry`]: ../pool/struct.PoolListEntry.html
    pub fn pool_search<'a>(&'a self, query: &str) -> PoolIter<'a, C> {
        PoolIter::new(self, Some(query))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::offset::TimeZone;
    use reqwest_mock::{Method, Url};

    #[test]
    fn pool_list_result_from_json() {
        let example_json = include_str!("mocked/pool_list_result-12668.json");

        let parsed = serde_json::from_str::<JsonValue>(example_json).unwrap();
        let result = PoolListEntry::try_from(&parsed).unwrap();

        assert_eq!(result.id, 12668);
        assert_eq!(result.is_locked, false);
        assert_eq!(result.name, "Random SFW name");
        assert_eq!(result.post_count, 33);
        assert_eq!(result.user_id, 171621);
        assert_eq!(result.created_at, Utc.timestamp(1506450220, 569794000));
        assert_eq!(result.updated_at, Utc.timestamp(1568077422, 207421000));
    }

    #[test]
    fn pool_from_json() {
        let example_json = include_str!("mocked/pool_18274.json");

        let parsed = serde_json::from_str::<JsonValue>(example_json).unwrap();
        let pool = Pool::try_from(&parsed).unwrap();

        assert_eq!(pool.id, 18274);
        assert_eq!(pool.is_active, true);
        assert_eq!(pool.is_locked, false);
        assert_eq!(pool.name, "oBEARwatch_by_Murasaki_Yuri");
        assert_eq!(pool.description, "");
        assert_eq!(pool.posts.len(), 8);
        assert_eq!(pool.user_id, 357072);
        assert_eq!(pool.created_at, Utc.timestamp(1567963035, 63943000));
        assert_eq!(pool.updated_at, Utc.timestamp(1567964144, 960193000));
    }

    #[test]
    fn get_pool() {
        let mut client = Client::new_mocked(b"rs621/unit_test").unwrap();

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/show.json?id=18274").unwrap())
            .method(Method::GET)
            .response()
            .body(include_str!("mocked/pool_18274.json"))
            .mock()
            .is_ok());

        let pool = client.get_pool(18274).unwrap();
        assert_eq!(pool.id, 18274);
    }

    #[test]
    fn pool_list() {
        let mut client = Client::new_mocked(b"rs621/unit_test").unwrap();

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/index.json?page=1").unwrap())
            .method(Method::GET)
            .response()
            .body(include_str!("mocked/pool_list-page_1.json"))
            .mock()
            .is_ok());

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/index.json?page=2").unwrap())
            .method(Method::GET)
            .response()
            .body(include_str!("mocked/pool_list-page_2.json"))
            .mock()
            .is_ok());

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/index.json?page=3").unwrap())
            .method(Method::GET)
            .response()
            .body("[]")
            .mock()
            .is_ok());

        let pools: Vec<_> = client.pool_list().collect();

        // We know how many pools we have because we've mocked the requests. Hah!
        assert_eq!(pools.len(), 6);
    }

    #[test]
    fn pool_search() {
        let mut client = Client::new_mocked(b"rs621/unit_test").unwrap();

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/index.json?page=1&query=foo").unwrap())
            .method(Method::GET)
            .response()
            .body(include_str!("mocked/pool_search-foo.json"))
            .mock()
            .is_ok());

        assert!(client
            .client
            .stub(Url::parse("https://e621.net/pool/index.json?page=2&query=foo").unwrap())
            .method(Method::GET)
            .response()
            .body("[]")
            .mock()
            .is_ok());

        // Should all contain foo in the name
        for pool in client.pool_search("foo") {
            assert!(pool.unwrap().name.contains("foo"));
        }
    }
}