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
use crate::clients::account::AccountClient;
use crate::clients::author::AuthorClient;
use crate::clients::works::WorksClient;
use crate::models::account::Session;
use clients::books::BooksClient;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{ClientBuilder, Error, StatusCode};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use thiserror::Error;
use url::{ParseError, Url};

mod clients;
mod format;
pub mod models;
#[cfg(test)]
mod tests;

#[derive(Debug, Error)]
pub enum OpenLibraryError {
    #[error(
        "Received an {:?} response from the Open Library API: {:?}",
        status_code,
        error
    )]
    ApiError {
        status_code: StatusCode,
        error: Option<OpenLibraryErrorResponse>,
    },
    #[error("Unable to build HTTP client: {}", source)]
    ClientBuildingError { source: reqwest::Error },
    #[error("An internal error occurred: {}", reason)]
    InternalError { reason: String },
    #[error("An error occurred while parsing json: {}", source)]
    JsonParseError { source: reqwest::Error },
    #[error("The operation ({}) requires authentication to be provided!", reason)]
    NotAuthenticated { reason: String },
    #[error("An error occurred while trying to parse a value: {}", reason)]
    ParsingError { reason: String },
    #[error("An error occurred while sending HTTP request: {}", source)]
    RequestFailed { source: reqwest::Error },
}

impl From<reqwest::Error> for OpenLibraryError {
    fn from(error: Error) -> Self {
        OpenLibraryError::RequestFailed { source: error }
    }
}

impl From<ParseError> for OpenLibraryError {
    fn from(error: ParseError) -> Self {
        OpenLibraryError::ParsingError {
            reason: error.to_string(),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct OpenLibraryErrorResponse {
    pub error: String,
}

pub struct OpenLibraryAuthClient {
    account: AccountClient,
}

impl OpenLibraryAuthClient {
    pub fn new(host: Option<Url>) -> Result<OpenLibraryAuthClient, OpenLibraryError> {
        let client = ClientBuilder::new()
            .build()
            .map_err(|error| OpenLibraryError::ClientBuildingError { source: error })?;

        let host_url = match host {
            Some(value) => value,
            None => Url::parse("https://openlibrary.org/").unwrap(),
        };

        Ok(Self {
            account: AccountClient {
                client,
                host: host_url,
            },
        })
    }

    pub async fn login(
        &self,
        username: String,
        password: String,
    ) -> Result<Session, OpenLibraryError> {
        self.account.login(username, password).await
    }
}

#[derive(Clone)]
pub struct OpenLibraryClient {
    pub account: AccountClient,
    pub author: AuthorClient,
    pub books: BooksClient,
    pub works: WorksClient,
}

impl OpenLibraryClient {
    pub fn builder() -> OpenLibraryClientBuilder {
        OpenLibraryClientBuilder::new()
    }
}

pub struct OpenLibraryClientBuilder {
    host: Url,
    session: Option<Session>,
}

impl OpenLibraryClientBuilder {
    fn new() -> OpenLibraryClientBuilder {
        OpenLibraryClientBuilder {
            host: Url::parse("https://openlibrary.org/").unwrap(),
            session: None,
        }
    }

    pub fn with_host(self, host: Url) -> OpenLibraryClientBuilder {
        OpenLibraryClientBuilder {
            host,
            session: self.session,
        }
    }

    pub fn with_session(self, session: &Session) -> OpenLibraryClientBuilder {
        OpenLibraryClientBuilder {
            host: self.host,
            session: Some(session.clone()),
        }
    }

    pub fn build(self) -> Result<OpenLibraryClient, OpenLibraryError> {
        let default_headers = match self.session {
            Some(session) => {
                let mut headers = HeaderMap::new();
                headers.insert(
                    "Cookie",
                    HeaderValue::from_str(session.cookie().as_str()).map_err(|_error| {
                        OpenLibraryError::ParsingError {
                            reason: "Unable to parse session cookie into header value".to_string(),
                        }
                    })?,
                );
                headers
            }
            None => HeaderMap::new(),
        };

        let client = ClientBuilder::new()
            .default_headers(default_headers)
            .build()
            .map_err(|error| OpenLibraryError::ClientBuildingError { source: error })?;

        Ok(OpenLibraryClient {
            books: BooksClient::new(&client, &self.host),
            account: AccountClient::new(&client, &self.host),
            author: AuthorClient::new(&client, &self.host),
            works: WorksClient::new(&client, &self.host),
        })
    }
}