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
#![deny(rust_2018_idioms)]
use reqwest;
use serde::{self, Deserialize};
use serde_json;
use crate::error::Error;

pub mod error;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Quote {
    pub quote_text: String,
    pub quote_author: String,
    pub sender_name: String,
    pub sender_link: String,
    pub quote_link: String,
}

/// Language specification.
#[derive(Clone, Copy)]
pub enum Lang {
    EN,
    RU,
}

impl std::fmt::Display for Lang {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Lang::EN => write!(f, "en"),
            Lang::RU => write!(f, "ru"),
        }
    }
}

pub type Result<T> = std::result::Result<T, Error>;

/// Get quote via forismatic API.
///
/// `key` must not be longer than 6 characters in string form.
/// # Examples
/// To get quote in English without key :
///
/// ```
/// get_quote(Lang::EN, None);
/// ```
///
/// To get quote in Russian with key `1000` :
///
/// ```
/// get_quote(Lang::RU, 1000);
/// ```
pub fn get_quote<T>(lang: Lang, key: T) -> Result<Quote>
where
    Option<u32>: From<T>,
{
    let url = match Option::from(key) {
        Some(k) => {
            if k.to_string().len() > 6 {
                return Err(Error::TooLongKey);
            }
            format!(
                "https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang={}&key={}",
                lang, k
            )
        }
        None => format!(
            "https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang={}",
            lang
        ),
    };
    let content = reqwest::get(&url)?.text()?.replace("\\'", "'");
    serde_json::from_str::<Quote>(content.as_str()).map_err(|e| -> Error {
        eprintln!("Parse Failed.");
        eprintln!("Please report to https://github.com/equal-l2/forismatic-rs with JSON!");
        eprintln!("JSON:\n{}", content);
        e.into()
    })
}