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
use crate::error::HoundifyError;
use crate::query::{Query, QueryOptions, TextQuery};
use uuid::Uuid;
use base64;
use hmac::{Hmac, Mac};
use reqwest::blocking::Client as HttpClient;
use reqwest::header::HeaderMap;
use sha2::Sha256;
use std::time::SystemTime;

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

fn get_current_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

#[derive(Debug)]
pub struct Client {
    api_url: String,
    client_id: String,
    client_key: String,
    http_client: HttpClient,
    request_id_generator: fn()->String,
}

impl Client {
    pub fn new(api_url: &str, client_id: &str, client_key: &str, request_id_generator_option: Option<fn()->String>) -> Self {
        let http_client = reqwest::blocking::Client::builder()
            .http1_title_case_headers() // because houndify API headers are case-sensitive :(
            .build()
            .unwrap();

        let request_id_generator = match request_id_generator_option {
            Some(f) => f,
            None => || Uuid::new_v4().to_string(),
        };

        Client {
            api_url: api_url.to_string(),
            client_id: client_id.to_string(),
            client_key: client_key.to_string(),
            http_client,
            request_id_generator,
        }
    }

    fn build_auth_headers(
        &self,
        user_id: &str,
        request_id: &str,
        timestamp: u64,
    ) -> std::result::Result<HeaderMap, Box<dyn std::error::Error>> {
        let decoded_client_key = base64::decode_config(&self.client_key, base64::URL_SAFE)?;
        let mut mac: Hmac<Sha256> = Hmac::new_varkey(&decoded_client_key).unwrap();
        let data = format!("{};{}{}", user_id, request_id, timestamp.to_string());
        mac.input(data.as_bytes());
        let hmac_result = mac.result();
        let signature = base64::encode_config(&hmac_result.code(), base64::URL_SAFE);
        let mut header_map = HeaderMap::new();
        header_map.insert(
            "Hound-Client-Authentication",
            format!("{};{};{}", &self.client_id, &timestamp, &signature).parse()?,
        );
        header_map.insert(
            "Hound-Request-Authentication",
            format!("{};{}", &user_id, &request_id).parse()?,
        );
        Ok(header_map)
    }

    pub fn text_query(&self, q: &str, options: &QueryOptions) -> Result<String> {
        let query = TextQuery::new(q);
        let timestamp = get_current_timestamp();
        println!("Timestamp={}", timestamp);

        let request_id = (&self.request_id_generator)();
        let mut headers = match self.build_auth_headers(&options.user_id, &request_id, timestamp) {
            Ok(h) => h,
            Err(e) => return Err(HoundifyError::new(e.into())),
        };

        let url = query.get_url(&self.api_url);
        let extra_headers = match query.get_headers(&self.client_id, &options.user_id, timestamp) {
            Ok(h) => h,
            Err(e) => return Err(HoundifyError::new(e.into())),
        };

        for (k, v) in extra_headers.iter() {
            headers.insert(k.clone(), v.clone());
        }

        let req = self.http_client.get(&url).headers(headers);
        println!("Request={:#?}", req);

        let res = match req.send() {
            Ok(r) => {
                println!("Response={:#?}", r);
                r
            }
            Err(e) => return Err(HoundifyError::new(e.into())),
        };

        match res.text() {
            Ok(res) => Ok(res),
            Err(e) => Err(HoundifyError::new(e.into())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_auth_values() {
        let client_id = String::from("EqQpJDGt0YozIb8Az6xvvA==");
        let client_key = String::from("jLTVjUOFBSetQtA3l-lGlb75rPVqKmH_JFgOVZjl4BdJqOq7PwUpub8ROcNnXUTssqd6M_7rC8Jn3_FjITouxQ==");
        let api_base = String::from("https://api.houndify.com/");
        let client = Client::new(&api_base, &client_id, &client_key, None);
        let auth_headers = client
            .build_auth_headers("test_user", "deadbeef", 1580278266)
            .unwrap();
        assert_eq!(
            auth_headers.get("Hound-Client-Authentication").unwrap(),
            "EqQpJDGt0YozIb8Az6xvvA==;1580278266;Ix3_MpLnyz1jGEV5g-mXxmbfgfZ85rD8-6S6yRTJEag="
        );
        assert_eq!(
            auth_headers.get("Hound-Request-Authentication").unwrap(),
            "test_user;deadbeef"
        );
    }
}