libpixiv 0.2.0

pixiv.net API client library
Documentation
use reqwest_middleware::reqwest::StatusCode;
use std::{error::Error, fmt::Display};

/// Core client functionality
pub mod client;
/// Illustration endpoints for the client
pub mod illusts;
/// API data models
pub mod models;
/// Search endpoints for the client
pub mod search;
/// Token store for the client
pub mod tokens;
/// Ugora (GIF) endpoints for the client
pub mod ugoira;
/// User endpoints for the client
pub mod users;

#[cfg(feature = "sqlx")]
pub use sqlx;
#[cfg(feature = "clap")]
pub use clap;
pub use reqwest_middleware::reqwest;

/// Pixiv application errors
#[derive(Debug, Clone)]
pub enum PixivAppError {
    /// (404) the requested content does not exist
    TargetNotFound,
    /// (400) the request failed, probably because it is malformed
    RequestFailed,
    /// (403) the request is not authorized and we need to log in
    MissingLogin,
    /// (429) we've hit the rate limit and need to wait a bit (no, we do not get headers that tell
    /// us how long we should wait)
    RateLimitReached,
    /// (everything else) the request was sent and the server responded, but we dont know what
    /// exactly the issue is
    UnhandledStatus(StatusCode),
    /// no one knows what went wrong
    Unknown,
}

impl Error for PixivAppError {}
impl Display for PixivAppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                PixivAppError::TargetNotFound => "Requested endpoint not found",
                PixivAppError::RequestFailed => "Request failed, check request parameters!",
                PixivAppError::MissingLogin => "Request failed because of missing authorization!",
                PixivAppError::RateLimitReached => "Too many requests, try again later",
                PixivAppError::UnhandledStatus(s) => s.as_str(),
                PixivAppError::Unknown => "An unknown error happened and no data was returned.",
            }
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{assert, assert_eq, env};

    //#[tokio::test]
    //async fn login() {
    //    let token = env!("PIXIV_REFRESH_TOKEN");
    //    let mut client = client::PixivAppClient::new(token.to_string());
    //    client.refresh_token().await;
    //    assert!(client.access_token.is_some(), "Expected to receive token!");
    //}

    #[tokio::test]
    async fn illust_details() {
        let illust_id = 122388293;
        let token = env::var("PIXIV_REFRESH_TOKEN");
        let client = client::PixivAppClient::new(
            token.expect("expecting PIXIV_REFRESH_TOKEN variable for testing!"),
        );
        //client.refresh_token().await;
        let illust = client.illust_details(illust_id).await;
        assert!(illust.is_ok(), "Expected illustration data: {:#?}", illust);
        assert_eq!(illust.unwrap().id, illust_id);
    }
}