libedgegrid 0.1.0

This library implements an Authentication handler for the Akamai OPEN EdgeGrid Authentication scheme in Rust
//! Alerts API
use curl;
use auth::EdgeGridAuth;
use request::HttpRequestVerb::*;
use url::percent_encoding as pe;
use rustc_serialize::json;
use std::borrow::Borrow;

#[derive(Debug, RustcDecodable)]
#[allow(non_snake_case)]
pub struct AlertData {
    id: Option<String>,
    name: Option<String>,
    startDate: Option<String>,
    errorString: Option<String>,
}

#[derive(Debug, RustcDecodable)]
#[allow(non_snake_case)]
pub struct AlertList {
    alerts: Option<Vec<AlertData>>,
    errorString: Option<String>
}

#[derive(Debug, RustcEncodable)]
#[allow(non_snake_case)]
pub struct AlertPostData {
    status: String,
    cpCodes: Option<String>,
}

#[derive(Debug, RustcDecodable)]
#[allow(non_snake_case)]
pub struct Attributes {
    alert_delay_keyword: Option<String>,
    // Customer IP
    email_to_keyword: Option<String>,
    Domain: Option<String>,
    Property: Option<String>,
    // Data Center
    service_keywork: Option<String>,
    Reason: Option<String>,
}
#[derive(Debug, RustcDecodable)]
#[allow(non_snake_case)]
pub struct AlertDetails {
    id: Option<String>,
    name: Option<String>,
    startDate: Option<String>,
    threshold: Option<String>,
    attributes: Option<Attributes>,
}

#[derive(Debug, RustcDecodable)]
#[allow(non_snake_case)]
pub struct AlertDetailsResponse {
    alertDetails: Option<AlertDetails>,
    network: Option<String>,
    errorString: Option<String>,
}

pub fn get(
    egr: &EdgeGridAuth,
    cp_codes: Option<Vec<String>>
) -> ::EdgeGridResponse {
    let mut url = String::from(egr.baseurl());
    let mut relurl = format!("/alerts/v1/portal-user?status=active");

    let url_slice = match cp_codes {
        Some(cc) => {
            relurl.push_str("&cpCodes=");

            for cp_code in cc.iter() {
                relurl.push_str(cp_code);
                relurl.push_str(",");
            }

            relurl.trim_right_matches(",")
        },
        None     => { &relurl[..] },
    };

    url.push_str(url_slice);
    url = pe::utf8_percent_encode(&url[..], pe::QUERY_ENCODE_SET);
    let header = try!(egr.auth_header(GET, url_slice, None));
    debug!("URL: {}", url);
    let resp = try!(curl::http::handle()
        .timeout(egr.timeout())
        .get(&url[..])
        .header("Authorization", &header[..])
        .exec()
    );
    let body = String::from_utf8_lossy(resp.get_body());
    debug!("Status: {}", resp.get_code());
    debug!("Body: {}", body);

    match resp.get_code() {
        200 => {
            let jsonresp: AlertList = try!(json::decode(&body));
            Ok(jsonresp)
        },
        _   => {
            let json_err: ::JSONError = try!(json::decode(&body));
            Err(::ApiError{
                json_err: json_err,
                body: String::from(body.borrow())
            })
        }
    }
}

pub fn post(
    egr: &EdgeGridAuth,
    cp_codes: Option<Vec<String>>
) -> Result<AlertList, ::ApiError> {
    let mut url = String::from(egr.baseurl());
    let relurl = format!("/alerts/v1/portal-user");

    let codes = match cp_codes {
        Some(cc) => {
            let mut codes = String::new();

            for cp_code in cc.iter() {
                codes.push_str(cp_code);
                codes.push(',');
            }

            Some(String::from(codes.trim_right_matches(',')))
        },
        None     => None
    };

    let post_obj = AlertPostData {
        status: String::from("active"),
        cpCodes: codes,
    };

    let post_json = try!(json::encode(&post_obj));
    debug!("POST JSON: {}", post_json);

    url.push_str(&relurl[..]);
    url = pe::utf8_percent_encode(&url[..], pe::QUERY_ENCODE_SET);
    let header = try!(egr.auth_header(POST, &relurl[..], Some(&post_json[..])));
    debug!("URL: {}", url);
    let resp = try!(curl::http::handle()
        .timeout(egr.timeout())
        .post(&url[..], post_json.as_bytes())
        .header("Content-Type", "application/json")
        .header("Authorization", &header[..])
        .exec()
    );
    let body = String::from_utf8_lossy(resp.get_body());
    debug!("Status: {}", resp.get_code());
    debug!("Body: {}", body);

    match resp.get_code() {
        200 => {
            let jsonresp: AlertList = try!(json::decode(&body));
            Ok(jsonresp)
        },
        _   => {
            let json_err: ::JSONError = try!(json::decode(&body));
            Err(::ApiError{
                json_err: json_err,
                body: String::from(body.borrow())
            })
        }
    }
}

pub fn get_by_id(
    egr: &EdgeGridAuth,
    alert_id: usize
) -> Result<AlertDetailsResponse, ::ApiError> {
    let mut url = String::from(egr.baseurl());
    let relurl = format!("/alerts/v1/portal-user/alert/{}", alert_id);

    url.push_str(&relurl[..]);
    url = pe::utf8_percent_encode(&url[..], pe::QUERY_ENCODE_SET);
    let header = try!(egr.auth_header(GET, &relurl[..], None));
    debug!("URL: {}", url);
    let resp = try!(curl::http::handle()
        .timeout(egr.timeout())
        .get(&url[..])
        .header("Content-Type", "application/json")
        .header("Authorization", &header[..])
        .exec()
    );
    let body = String::from_utf8_lossy(resp.get_body());
    debug!("Status: {}", resp.get_code());
    debug!("Body: {}", body);

    match resp.get_code() {
        200 => {
            let jsonresp: AlertDetailsResponse = try!(json::decode(&body));
            Ok(jsonresp)
        },
        _   => {
            let json_err: ::JSONError = try!(json::decode(&body));
            Err(::ApiError{
                json_err: json_err,
                body: String::from(body.borrow())
            })
        }
    }
}