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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639


#[allow(unused_imports)]
use std::collections::HashMap;
use std::convert::From;
use std::error::Error;
use std::fmt;

use serde_json;

use requests::SlackWebRequestSender;

/// Gets the access logs for the current team.
///
/// Wraps https://api.slack.com/methods/team.accessLogs

pub fn access_logs<R>(client: &R,
                      token: &str,
                      request: &AccessLogsRequest)
                      -> Result<AccessLogsResponse, AccessLogsError<R::Error>>
    where R: SlackWebRequestSender
{
    let count = request.count.map(|count| count.to_string());
    let page = request.page.map(|page| page.to_string());
    let before = request.before.map(|before| before.to_string());
    let params = vec![Some(("token", token)),
                      count.as_ref().map(|count| ("count", &count[..])),
                      page.as_ref().map(|page| ("page", &page[..])),
                      before.as_ref().map(|before| ("before", &before[..]))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("team.accessLogs");
    client
        .send(&url, &params[..])
        .map_err(|err| AccessLogsError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<AccessLogsResponse>(&result)
                            .map_err(|e| AccessLogsError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct AccessLogsRequest {
    /// Number of items to return per page.
    pub count: Option<u32>,
    /// Page number of results to return.
    pub page: Option<u32>,
    /// End of time range of logs to include in results (inclusive).
    pub before: Option<u32>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct AccessLogsResponse {
    error: Option<String>,
    pub logins: Option<Vec<AccessLogsResponseLogin>>,
    #[serde(default)]
    ok: bool,
    pub paging: Option<::Paging>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct AccessLogsResponseLogin {
    pub count: Option<i32>,
    pub country: Option<String>,
    pub date_first: Option<f32>,
    pub date_last: Option<f32>,
    pub ip: Option<String>,
    pub isp: Option<String>,
    pub region: Option<String>,
    pub user_agent: Option<String>,
    pub user_id: Option<String>,
    pub username: Option<String>,
}


impl<E: Error> Into<Result<AccessLogsResponse, AccessLogsError<E>>> for AccessLogsResponse {
    fn into(self) -> Result<AccessLogsResponse, AccessLogsError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum AccessLogsError<E: Error> {
    /// This is only available to paid teams.
    PaidOnly,
    /// It is not possible to request more than 1000 items per page or more than 100 pages.
    OverPaginationLimit,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// This method cannot be called by a bot user.
    UserIsBot,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for AccessLogsError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "paid_only" => AccessLogsError::PaidOnly,
            "over_pagination_limit" => AccessLogsError::OverPaginationLimit,
            "not_authed" => AccessLogsError::NotAuthed,
            "invalid_auth" => AccessLogsError::InvalidAuth,
            "account_inactive" => AccessLogsError::AccountInactive,
            "user_is_bot" => AccessLogsError::UserIsBot,
            "invalid_arg_name" => AccessLogsError::InvalidArgName,
            "invalid_array_arg" => AccessLogsError::InvalidArrayArg,
            "invalid_charset" => AccessLogsError::InvalidCharset,
            "invalid_form_data" => AccessLogsError::InvalidFormData,
            "invalid_post_type" => AccessLogsError::InvalidPostType,
            "missing_post_type" => AccessLogsError::MissingPostType,
            "team_added_to_org" => AccessLogsError::TeamAddedToOrg,
            "request_timeout" => AccessLogsError::RequestTimeout,
            _ => AccessLogsError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for AccessLogsError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for AccessLogsError<E> {
    fn description(&self) -> &str {
        match self {
            &AccessLogsError::PaidOnly => "paid_only: This is only available to paid teams.",
            &AccessLogsError::OverPaginationLimit => "over_pagination_limit: It is not possible to request more than 1000 items per page or more than 100 pages.",
            &AccessLogsError::NotAuthed => "not_authed: No authentication token provided.",
            &AccessLogsError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &AccessLogsError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &AccessLogsError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.",
            &AccessLogsError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &AccessLogsError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &AccessLogsError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &AccessLogsError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &AccessLogsError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &AccessLogsError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &AccessLogsError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &AccessLogsError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &AccessLogsError::MalformedResponse(ref e) => e.description(),
            &AccessLogsError::Unknown(ref s) => s,
            &AccessLogsError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &AccessLogsError::MalformedResponse(ref e) => Some(e),
            &AccessLogsError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Gets billable users information for the current team.
///
/// Wraps https://api.slack.com/methods/team.billableInfo

pub fn billable_info<R>(client: &R,
                        token: &str,
                        request: &BillableInfoRequest)
                        -> Result<BillableInfoResponse, BillableInfoError<R::Error>>
    where R: SlackWebRequestSender
{

    let params = vec![Some(("token", token)),
                      request.user.map(|user| ("user", user))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("team.billableInfo");
    client
        .send(&url, &params[..])
        .map_err(|err| BillableInfoError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<BillableInfoResponse>(&result)
                            .map_err(|e| BillableInfoError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct BillableInfoRequest<'a> {
    /// A user to retrieve the billable information for. Defaults to all users.
    pub user: Option<&'a str>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct BillableInfoResponse {
    pub billable_info: Option<HashMap<String, bool>>,
    error: Option<String>,
    #[serde(default)]
    ok: bool,
}


impl<E: Error> Into<Result<BillableInfoResponse, BillableInfoError<E>>> for BillableInfoResponse {
    fn into(self) -> Result<BillableInfoResponse, BillableInfoError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum BillableInfoError<E: Error> {
    /// Unable to find the requested user.
    UserNotFound,
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// This method cannot be called by a bot user.
    UserIsBot,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for BillableInfoError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "user_not_found" => BillableInfoError::UserNotFound,
            "not_authed" => BillableInfoError::NotAuthed,
            "invalid_auth" => BillableInfoError::InvalidAuth,
            "account_inactive" => BillableInfoError::AccountInactive,
            "user_is_bot" => BillableInfoError::UserIsBot,
            "invalid_arg_name" => BillableInfoError::InvalidArgName,
            "invalid_array_arg" => BillableInfoError::InvalidArrayArg,
            "invalid_charset" => BillableInfoError::InvalidCharset,
            "invalid_form_data" => BillableInfoError::InvalidFormData,
            "invalid_post_type" => BillableInfoError::InvalidPostType,
            "missing_post_type" => BillableInfoError::MissingPostType,
            "team_added_to_org" => BillableInfoError::TeamAddedToOrg,
            "request_timeout" => BillableInfoError::RequestTimeout,
            _ => BillableInfoError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for BillableInfoError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for BillableInfoError<E> {
    fn description(&self) -> &str {
        match self {
            &BillableInfoError::UserNotFound => "user_not_found: Unable to find the requested user.",
            &BillableInfoError::NotAuthed => "not_authed: No authentication token provided.",
            &BillableInfoError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &BillableInfoError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &BillableInfoError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.",
            &BillableInfoError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &BillableInfoError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &BillableInfoError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &BillableInfoError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &BillableInfoError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &BillableInfoError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &BillableInfoError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &BillableInfoError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &BillableInfoError::MalformedResponse(ref e) => e.description(),
            &BillableInfoError::Unknown(ref s) => s,
            &BillableInfoError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &BillableInfoError::MalformedResponse(ref e) => Some(e),
            &BillableInfoError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Gets information about the current team.
///
/// Wraps https://api.slack.com/methods/team.info

pub fn info<R>(client: &R, token: &str) -> Result<InfoResponse, InfoError<R::Error>>
    where R: SlackWebRequestSender
{
    let params = &[("token", token)];
    let url = ::get_slack_url_for_method("team.info");
    client
        .send(&url, &params[..])
        .map_err(|err| InfoError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<InfoResponse>(&result)
                            .map_err(|e| InfoError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Debug, Deserialize)]
pub struct InfoResponse {
    error: Option<String>,
    #[serde(default)]
    ok: bool,
    pub team: Option<::Team>,
}


impl<E: Error> Into<Result<InfoResponse, InfoError<E>>> for InfoResponse {
    fn into(self) -> Result<InfoResponse, InfoError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum InfoError<E: Error> {
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for InfoError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "not_authed" => InfoError::NotAuthed,
            "invalid_auth" => InfoError::InvalidAuth,
            "account_inactive" => InfoError::AccountInactive,
            "invalid_arg_name" => InfoError::InvalidArgName,
            "invalid_array_arg" => InfoError::InvalidArrayArg,
            "invalid_charset" => InfoError::InvalidCharset,
            "invalid_form_data" => InfoError::InvalidFormData,
            "invalid_post_type" => InfoError::InvalidPostType,
            "missing_post_type" => InfoError::MissingPostType,
            "team_added_to_org" => InfoError::TeamAddedToOrg,
            "request_timeout" => InfoError::RequestTimeout,
            _ => InfoError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for InfoError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for InfoError<E> {
    fn description(&self) -> &str {
        match self {
            &InfoError::NotAuthed => "not_authed: No authentication token provided.",
            &InfoError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &InfoError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &InfoError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &InfoError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &InfoError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &InfoError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &InfoError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &InfoError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &InfoError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &InfoError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &InfoError::MalformedResponse(ref e) => e.description(),
            &InfoError::Unknown(ref s) => s,
            &InfoError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &InfoError::MalformedResponse(ref e) => Some(e),
            &InfoError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}

/// Gets the integration logs for the current team.
///
/// Wraps https://api.slack.com/methods/team.integrationLogs

pub fn integration_logs<R>(client: &R,
                           token: &str,
                           request: &IntegrationLogsRequest)
                           -> Result<IntegrationLogsResponse, IntegrationLogsError<R::Error>>
    where R: SlackWebRequestSender
{
    let count = request.count.map(|count| count.to_string());
    let page = request.page.map(|page| page.to_string());
    let params = vec![Some(("token", token)),
                      request
                          .service_id
                          .map(|service_id| ("service_id", service_id)),
                      request.app_id.map(|app_id| ("app_id", app_id)),
                      request.user.map(|user| ("user", user)),
                      request
                          .change_type
                          .map(|change_type| ("change_type", change_type)),
                      count.as_ref().map(|count| ("count", &count[..])),
                      page.as_ref().map(|page| ("page", &page[..]))];
    let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
    let url = ::get_slack_url_for_method("team.integrationLogs");
    client
        .send(&url, &params[..])
        .map_err(|err| IntegrationLogsError::Client(err))
        .and_then(|result| {
                      serde_json::from_str::<IntegrationLogsResponse>(&result)
                            .map_err(|e| IntegrationLogsError::MalformedResponse(e))
                  })
        .and_then(|o| o.into())
}

#[derive(Clone, Default, Debug)]
pub struct IntegrationLogsRequest<'a> {
    /// Filter logs to this service. Defaults to all logs.
    pub service_id: Option<&'a str>,
    /// Filter logs to this Slack app. Defaults to all logs.
    pub app_id: Option<&'a str>,
    /// Filter logs generated by this user’s actions. Defaults to all logs.
    pub user: Option<&'a str>,
    /// Filter logs with this change type. Defaults to all logs.
    pub change_type: Option<&'a str>,
    /// Number of items to return per page.
    pub count: Option<u32>,
    /// Page number of results to return.
    pub page: Option<u32>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct IntegrationLogsResponse {
    error: Option<String>,
    pub logs: Option<Vec<IntegrationLogsResponseLog>>,
    #[serde(default)]
    ok: bool,
    pub paging: Option<::Paging>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct IntegrationLogsResponseLog {
    pub app_id: Option<String>,
    pub app_type: Option<String>,
    pub change_type: Option<String>,
    pub channel: Option<String>,
    pub date: Option<String>,
    pub reason: Option<String>,
    pub scope: Option<String>,
    pub service_id: Option<String>,
    pub service_type: Option<String>,
    pub user_id: Option<String>,
    pub user_name: Option<String>,
}


impl<E: Error> Into<Result<IntegrationLogsResponse, IntegrationLogsError<E>>>
    for IntegrationLogsResponse {
    fn into(self) -> Result<IntegrationLogsResponse, IntegrationLogsError<E>> {
        if self.ok {
            Ok(self)
        } else {
            Err(self.error
                    .as_ref()
                    .map(String::as_ref)
                    .unwrap_or("")
                    .into())
        }
    }
}
#[derive(Debug)]
pub enum IntegrationLogsError<E: Error> {
    /// No authentication token provided.
    NotAuthed,
    /// Invalid authentication token.
    InvalidAuth,
    /// Authentication token is for a deleted user or team.
    AccountInactive,
    /// This method cannot be called by a bot user.
    UserIsBot,
    /// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
    InvalidArgName,
    /// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
    InvalidArrayArg,
    /// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
    InvalidCharset,
    /// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
    InvalidFormData,
    /// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
    InvalidPostType,
    /// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
    MissingPostType,
    /// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
    TeamAddedToOrg,
    /// The method was called via a POST request, but the POST data was either missing or truncated.
    RequestTimeout,
    /// The response was not parseable as the expected object
    MalformedResponse(serde_json::error::Error),
    /// The response returned an error that was unknown to the library
    Unknown(String),
    /// The client had an error sending the request to Slack
    Client(E),
}

impl<'a, E: Error> From<&'a str> for IntegrationLogsError<E> {
    fn from(s: &'a str) -> Self {
        match s {
            "not_authed" => IntegrationLogsError::NotAuthed,
            "invalid_auth" => IntegrationLogsError::InvalidAuth,
            "account_inactive" => IntegrationLogsError::AccountInactive,
            "user_is_bot" => IntegrationLogsError::UserIsBot,
            "invalid_arg_name" => IntegrationLogsError::InvalidArgName,
            "invalid_array_arg" => IntegrationLogsError::InvalidArrayArg,
            "invalid_charset" => IntegrationLogsError::InvalidCharset,
            "invalid_form_data" => IntegrationLogsError::InvalidFormData,
            "invalid_post_type" => IntegrationLogsError::InvalidPostType,
            "missing_post_type" => IntegrationLogsError::MissingPostType,
            "team_added_to_org" => IntegrationLogsError::TeamAddedToOrg,
            "request_timeout" => IntegrationLogsError::RequestTimeout,
            _ => IntegrationLogsError::Unknown(s.to_owned()),
        }
    }
}

impl<E: Error> fmt::Display for IntegrationLogsError<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl<E: Error> Error for IntegrationLogsError<E> {
    fn description(&self) -> &str {
        match self {
            &IntegrationLogsError::NotAuthed => "not_authed: No authentication token provided.",
            &IntegrationLogsError::InvalidAuth => "invalid_auth: Invalid authentication token.",
            &IntegrationLogsError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
            &IntegrationLogsError::UserIsBot => "user_is_bot: This method cannot be called by a bot user.",
            &IntegrationLogsError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
            &IntegrationLogsError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
            &IntegrationLogsError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
            &IntegrationLogsError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
            &IntegrationLogsError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
            &IntegrationLogsError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
            &IntegrationLogsError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
            &IntegrationLogsError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
            &IntegrationLogsError::MalformedResponse(ref e) => e.description(),
            &IntegrationLogsError::Unknown(ref s) => s,
            &IntegrationLogsError::Client(ref inner) => inner.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            &IntegrationLogsError::MalformedResponse(ref e) => Some(e),
            &IntegrationLogsError::Client(ref inner) => Some(inner),
            _ => None,
        }
    }
}