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
use std::borrow::Cow;

#[cfg(feature = "reqwest")]
use reqwest::{self, IntoUrl, Url, UrlError, Error as HttpError};

#[cfg(feature = "hyper")] use hyper::Url;
#[cfg(feature = "hyper")] use hyper::client::IntoUrl;
#[cfg(feature = "hyper")]
use hyper::error::{ParseError as UrlError, Error as HttpError};

use serde_json;

use super::*;

/// A Builder struct for making the query.
#[derive(Clone, Debug, Default)]
pub struct Query<'a> {
    name: Cow<'a, str>,
    no_html: bool,
    query: Cow<'a, str>,
    skip_disambig: bool,
}

impl<'a> Query<'a> {
    /// Constructs a new query object, requiring the **query**, and the **name**
    /// of your app. It is recommended to use a constant for the name of your
    /// app.
    ///
    /// ```no_run
    /// use ddg::Query;
    /// const APP_NAME: &'static str = "ddg_example_app";
    /// let query = Query::new("Rust", APP_NAME);
    ///
    /// let response = query.execute().unwrap();
    /// ```
    pub fn new<I: Into<Cow<'a, str>>>(query: I, name: I) -> Self {
        Query { query: query.into(), name: name.into(), ..Self::default() }
    }

    /// Will strip out any HTML content from the text in the Response
    /// eg.(_italics_, **bolds**, etc)
    ///
    /// ```no_run
    /// use ddg::Query;
    /// const APP_NAME: &'static str = "ddg_example_app";
    ///
    /// let query = Query::new("Rust", APP_NAME).no_html();
    ///
    /// let response = query.execute().unwrap();
    /// ```
    pub fn no_html(mut self) -> Self {
        self.no_html = true;
        self
    }

    /// Skip the D(Disambiguation) type of Instant Answer.
    pub fn skip_disambig(mut self) -> Self {
        self.skip_disambig = true;
        self
    }

    /// Execute the request and parses it into a `DdgResponse` struct.
    #[cfg(feature = "reqwest")]
    pub fn execute(self) -> Result<Response, Error> {
        Ok(serde_json::from_reader(reqwest::get(self)?)?)
    }
}

/// Error from parsing or convertingi into a URL.
#[derive(Debug)]
pub enum Error {
    /// An error in making the HTTP request, or parsing the query string into a
    /// url.
    Http(HttpError),
    /// An error in parsing the JSON.
    SerdeJson(serde_json::Error),
}

impl From<HttpError> for Error {
    fn from(error: HttpError) -> Self {
        Error::Http(error)
    }
}

impl From<serde_json::Error> for Error {
    fn from(error: serde_json::Error) -> Self {
        Error::SerdeJson(error)
    }
}

impl<'a> IntoUrl for Query<'a> {
    fn into_url(self) -> Result<Url, UrlError> {
        const URL: &'static str = "https://api.duckduckgo.com?format=json&no_redirect=1";
        let mut query = String::from(URL);

        if self.no_html {
            query.push_str("&no_html=1");
        }

        if self.skip_disambig {
            query.push_str("&skip_disambig=1");
        }

        Url::parse_with_params(&query, &[
            ("q", &*self.query),
            ("t", &*self.name)
        ])
    }
}

#[cfg(all(test, feature = "reqwest"))]
mod tests {
    use super::Query;

    const APP_NAME: &'static str = "ddg_rs_tests";

    #[test]
    fn it_works() {
        let rs = Query::new("Rust", APP_NAME).execute();

        println!("{:?}", rs);
        assert!(rs.is_ok());
    }

    #[test]
    fn never_directly_redirect() {
        let query = Query::new("!crates tokei", APP_NAME);

        let rs = query.execute();

        assert!(rs.is_ok());
    }
}