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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use reqwest;
pub use reqwest::header::ContentType;
pub use reqwest::{Method, StatusCode};
use sign::SignatureV2;
use std::io::Read;
use tdff::FromTdff;
use xmlhelper::decode::{FromXMLStream, Stream};

error_chain! {
  foreign_links {
    Io(::std::io::Error);
    Request(reqwest::Error);
  }

  links {
    XmlDecode(::xmlhelper::decode::Error, ::xmlhelper::decode::ErrorKind);
    TdffDecode(::tdff::Error, ::tdff::ErrorKind);
    Sign(super::sign::Error, super::sign::ErrorKind);
  }

  errors {
    ErrorResponse(resp: ErrorResponse) {
      description("MWS request is unsuccessful")
      display("MWS request is unsuccessful: {:?}", resp)
    }
  }
}

#[derive(Debug)]
pub enum Response<T> {
  Success(T),
  Error(ErrorResponse),
}

#[derive(Debug)]
pub struct ErrorResponse {
  pub status: StatusCode,
  pub info: Option<ErrorResponseInfo>,
  pub raw: String,
}

#[derive(Debug, Default)]
pub struct ErrorResponseInfo {
  pub errors: Vec<ErrorResponseError>,
  pub request_id: String,
}

#[derive(Debug, Default, PartialEq)]
pub struct ErrorResponseError {
  pub error_type: String,
  pub code: String,
  pub message: String,
  pub detail: String,
}

impl ErrorResponseInfo {
  fn from_xml_stream<R: ::std::io::Read>(
    s: &mut Stream<R>,
  ) -> ::xmlhelper::decode::Result<ErrorResponseInfo> {
    use xmlhelper::decode::{characters, element, fold_elements, start_document};
    start_document(s)?;
    element(s, "ErrorResponse", |s| {
      fold_elements(s, ErrorResponseInfo::default(), |s, resp| {
        match s.local_name() {
          "Error" => {
            let err = fold_elements(s, ErrorResponseError::default(), |s, err| {
              match s.local_name() {
                "Type" => {
                  err.error_type = characters(s)?;
                }
                "Code" => {
                  err.code = characters(s)?;
                }
                "Message" => {
                  err.message = characters(s)?;
                }
                "Detail" => {
                  err.detail = characters(s)?;
                }
                _ => {}
              }
              Ok(())
            })?;
            resp.errors.push(err);
          }
          "RequestID" => {
            resp.request_id = characters(s)?;
          }
          _ => {}
        }
        Ok(())
      })
    }).into()
  }
}

impl FromXMLStream<Stream<reqwest::Response>> for ErrorResponseInfo {
  fn from_xml(s: &mut Stream<reqwest::Response>) -> ::xmlhelper::decode::Result<ErrorResponseInfo> {
    ErrorResponseInfo::from_xml_stream(s)
  }
}

impl FromXMLStream<Stream<::std::io::Cursor<String>>> for ErrorResponseInfo {
  fn from_xml(
    s: &mut Stream<::std::io::Cursor<String>>,
  ) -> ::xmlhelper::decode::Result<ErrorResponseInfo> {
    ErrorResponseInfo::from_xml_stream(s)
  }
}

/// [Reference](http://docs.developer.amazonservices.com/en_CA/dev_guide/DG_Endpoints.html)
pub struct ClientOptions {
  /// Your software can access Amazon Marketplace Web Service (Amazon MWS) using region-specific endpoints.
  pub endpoint: String,

  /// Your seller or merchant identifier.
  pub seller_id: String,

  /// Represents the authorization of a specific developer of a web application by a specific Amazon seller.
  pub mws_auth_token: Option<String>,

  /// Your Amazon MWS account is identified by your access key Id, which Amazon MWS uses to look up your Secret Access Key.
  pub aws_access_key_id: String,
  pub secret_key: String,
}

pub struct Client {
  options: ClientOptions,
  http_client: reqwest::Client,
}

impl Client {
  pub fn new(options: ClientOptions) -> Result<Client> {
    Ok(Client {
      options: options,
      http_client: reqwest::Client::new(),
    })
  }

  pub fn with_http_client(options: ClientOptions, http_client: reqwest::Client) -> Client {
    Client {
      options: options,
      http_client: http_client,
    }
  }

  pub fn request<P>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
  ) -> Result<reqwest::Response>
  where
    P: Into<Vec<(String, String)>>,
  {
    let mut sign = SignatureV2::new(
      self.options.endpoint.clone(),
      self.options.aws_access_key_id.clone(),
      self.options.secret_key.clone(),
    );
    for (k, v) in parameters.into() {
      sign.add(&k, v);
    }
    sign.add("SellerId", self.options.seller_id.as_ref());
    //sign.add("Merchant", self.options.seller_id.as_ref());
    let url = sign
      .generate_url(method.clone(), path, version, action)?
      .to_string();
    //println!("request: {}", url);
    self
      .http_client
      .request(method, &url)
      .send()
      .map_err(Into::into)
  }

  pub fn request_with_body<P, R>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
    body: R,
    content_md5: String,
    content_type: ContentType,
  ) -> Result<reqwest::Response>
  where
    P: Into<Vec<(String, String)>>,
    R: Read + Send + 'static,
  {
    let mut sign = SignatureV2::new(
      self.options.endpoint.clone(),
      self.options.aws_access_key_id.clone(),
      self.options.secret_key.clone(),
    );
    for (k, v) in parameters.into() {
      sign.add(&k, v);
    }
    sign.add("SellerId", self.options.seller_id.as_ref());
    sign.add("ContentMD5Value", content_md5);
    //sign.add("Merchant", self.options.seller_id.as_ref());
    let url = sign
      .generate_url(method.clone(), path, version, action)?
      .to_string();
    //println!("request: {}", url);

    self
      .http_client
      .request(method, &url)
      .header(content_type)
      .body(reqwest::Body::new(body))
      .send()
      .map_err(Into::into)
  }

  pub fn request_xml<P, T>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
  ) -> Result<Response<T>>
  where
    P: Into<Vec<(String, String)>>,
    T: FromXMLStream<Stream<reqwest::Response>>,
  {
    let mut resp = self.request(method, path, version, action, parameters)?;
    if resp.status().is_success() {
      let mut stream = Stream::new(resp);
      let v = T::from_xml(&mut stream)?;
      Ok(Response::Success(v))
    } else {
      use std::io::{Cursor, Read};

      let mut body = String::new();
      resp.read_to_string(&mut body)?;
      let mut s = Stream::new(Cursor::new(body.clone()));
      match ErrorResponseInfo::from_xml(&mut s) {
        Ok(info) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: Some(info),
        })),
        Err(_) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: None,
        })),
      }
    }
  }

  pub fn request_xml_with_body<P, R, T>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
    body: R,
    content_md5: String,
    content_type: ContentType,
  ) -> Result<Response<T>>
  where
    P: Into<Vec<(String, String)>>,
    T: FromXMLStream<Stream<reqwest::Response>>,
    R: Read + Send + 'static,
  {
    let mut resp = self.request_with_body(
      method,
      path,
      version,
      action,
      parameters,
      body,
      content_md5,
      content_type,
    )?;
    if resp.status().is_success() {
      let mut stream = Stream::new(resp);
      let v = T::from_xml(&mut stream)?;
      Ok(Response::Success(v))
    } else {
      use std::io::{Cursor, Read};

      let mut body = String::new();
      resp.read_to_string(&mut body)?;
      let mut s = Stream::new(Cursor::new(body.clone()));
      match ErrorResponseInfo::from_xml(&mut s) {
        Ok(info) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: Some(info),
        })),
        Err(_) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: None,
        })),
      }
    }
  }

  pub fn request_tdff<P, T>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
  ) -> Result<Response<T>>
  where
    P: Into<Vec<(String, String)>>,
    T: FromTdff<reqwest::Response>,
  {
    let mut resp = self.request(method, path, version, action, parameters)?;
    if resp.status().is_success() {
      let v = T::from_tdff(resp)?;
      Ok(Response::Success(v))
    } else {
      use std::io::{Cursor, Read};

      let mut body = String::new();
      resp.read_to_string(&mut body)?;
      let mut s = Stream::new(Cursor::new(body.clone()));
      match ErrorResponseInfo::from_xml(&mut s) {
        Ok(info) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: Some(info),
        })),
        Err(_) => Ok(Response::Error(ErrorResponse {
          status: resp.status().clone(),
          raw: body,
          info: None,
        })),
      }
    }
  }

  #[cfg(test)]
  pub fn request_raw<P>(
    &self,
    method: Method,
    path: &str,
    version: &str,
    action: &str,
    parameters: P,
  ) -> Result<(StatusCode, String)>
  where
    P: Into<Vec<(String, String)>>,
  {
    use std::io::Read;

    let mut sign = SignatureV2::new(
      self.options.endpoint.clone(),
      self.options.aws_access_key_id.clone(),
      self.options.secret_key.clone(),
    );
    for (k, v) in parameters.into() {
      sign.add(&k, v);
    }
    let url = sign
      .generate_url(method.clone(), path, version, action)?
      .to_string();
    let mut resp = self.http_client.request(method, &url).send()?;
    let mut s = String::new();
    resp.read_to_string(&mut s)?;
    Ok((resp.status().clone(), s))
  }
}

#[cfg(test)]
pub fn get_test_client() -> Client {
  use std::env;
  Client::new(ClientOptions {
    endpoint: env::var("Endpoint").expect("get Endpoint"),
    seller_id: env::var("SellerId").expect("get SellerId"),
    mws_auth_token: None,
    aws_access_key_id: env::var("AWSAccessKeyId").expect("get AWSAccessKeyId"),
    secret_key: env::var("SecretKey").expect("get SecretKey"),
  }).expect("create client")
}

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

  #[test]
  fn it_works() {
    dotenv().ok();
    let client = get_test_client();
    let (status, body) = client
      .request_raw(
        Method::Post,
        "/Orders/2013-09-01",
        "2013-09-01",
        "GetServiceStatus",
        vec![],
      )
      .expect("send request");
    assert!(status.is_success());
    assert!(body.starts_with("<?xml"));

    use std::io::Cursor;
    let (status, body) = client
      .request_raw(
        Method::Post,
        "/Fake/2013-09-01",
        "2013-09-01",
        "GetServiceStatus",
        vec![],
      )
      .expect("send request");
    assert!(!status.is_success());
    let source = Cursor::new(body);
    let mut s = Stream::new(source);
    let err_info = ErrorResponseInfo::from_xml(&mut s).expect("decode error response");
    assert_eq!(err_info.errors.len(), 1);
    assert_eq!(
      err_info.errors[0],
      ErrorResponseError {
        error_type: "Sender".to_string(),
        code: "InvalidAddress".to_string(),
        message: "Section Fake/2013-09-01 is invalid".to_string(),
        detail: "".to_string(),
      }
    );
  }
}