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
//! Simplistic API accessor for wolframalpha. Currently only supports questions and image answer
mod prelude {
    pub use std::error::Error;
    pub use std::fmt::{self, Write};
}
use bytes::Bytes;
use std::error::Error;
use std::fmt;

#[cfg(feature = "image")]
mod get_image;

#[cfg(feature = "image")]
pub use get_image::api_retrieve_image;

mod encoding {
    use super::prelude::*;
    fn encode_char(c: char) -> bool {
        if c.is_ascii() {
            if c.is_alphanumeric() {
                false
            } else if "-_.~".contains(c) {
                false
            } else {
                true
            }
        } else {
            true
        }
    }

    pub fn encode_question(s: &str) -> Result<String, Box<dyn Error + Send + Sync>> {
        let mut res = String::with_capacity(s.len());

        for c in s.chars() {
            if !encode_char(c) {
                res.push(c);
            } else if c == ' ' {
                res.push('+');
            } else {
                let mut buf = [0; 4];
                let n = c.encode_utf8(&mut buf).len();

                let mut tmp = String::with_capacity(3 * n);

                for i in 0..n {
                    write!(tmp, "%{:02x}", buf[i])?;
                }

                res.push_str(&tmp);
            }
        }

        Ok(res)
    }
}



/// Does the same thing as `api_retrieve_image` but instead of retrieving
/// the image it just gives you the raw bytes of the image instead
pub async fn api_retrieve_bytes(
    app_id: &str,
    question: &str,
) -> Result<Result<Bytes, WolframalphaError>, Box<dyn Error + Send + Sync>> {
    if question.trim() == "" {
        return Ok(Err(WolframalphaError::InvalidQuestion))
    }

    let encoded_query = encoding::encode_question(question)?;

    let response = reqwest::get(format!(
        "http://api.wolframalpha.com/v1/simple?appid={}&i={}",
        app_id, encoded_query
    ))
    .await?;

    if response.status() == reqwest::StatusCode::NOT_IMPLEMENTED {
        return Ok(Err(WolframalphaError::InvalidQuestion))
    }

    Ok(Ok(response.bytes()
    .await?))
}

#[derive(Debug, Clone, Copy)]
pub enum WolframalphaError {
    InvalidQuestion
}

impl fmt::Display for WolframalphaError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", match self {
            Self::InvalidQuestion => "invalid question"
        })
    }
}

/// Errors specific to wolframalpha
impl Error for WolframalphaError {

}