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
// This file was ((taken|adapted)|contains (data|code)) from twitch_api,
// Copyright 2017 Matt Shanker
// It's licensed under the Apache License, Version 2.0.
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// (Modifications|Other (data|code)|Everything else) Copyright 2019 the libtwitch-rs authors.
//  See copying.md for further legal info.

extern crate hyper;
extern crate serde_json;

use std::error::Error;
use std::fmt;
use std::io;

pub type TwitchResult<T> = Result<T, ApiError>;

#[derive(Debug)]
pub enum ApiError {
    HyperErr(hyper::error::Error),
    IoError(io::Error),
    ParseError(serde_json::error::Error),
    TwitchError(ErrorResponse),
    EmptyResponse(EmptyResponse),
}

impl From<hyper::error::Error> for ApiError {
    fn from(err: hyper::error::Error) -> ApiError {
        ApiError::HyperErr(err)
    }
}

impl From<io::Error> for ApiError {
    fn from(err: io::Error) -> ApiError {
        ApiError::IoError(err)
    }
}

impl From<serde_json::error::Error> for ApiError {
    fn from(err: serde_json::error::Error) -> ApiError {
        ApiError::ParseError(err)
    }
}

impl From<ErrorResponse> for ApiError {
    fn from(err: ErrorResponse) -> ApiError {
        ApiError::TwitchError(err)
    }
}

impl ApiError {
    pub fn empty_response() -> ApiError {
        ApiError::EmptyResponse(EmptyResponse {})
    }
}

impl Error for ApiError {
    fn description(&self) -> &str {
        match *self {
            ApiError::HyperErr(ref err) => err.description(),
            ApiError::IoError(ref err) => err.description(),
            ApiError::ParseError(ref err) => err.description(),
            ApiError::TwitchError(ref err) => &err.error,
            ApiError::EmptyResponse(_) => "EmptyResponse",
        }
    }

    fn cause(&self) -> Option<&dyn Error> {
        Some(match *self {
            ApiError::HyperErr(ref err) => err as &dyn Error,
            ApiError::IoError(ref err) => err as &dyn Error,
            ApiError::ParseError(ref err) => err as &dyn Error,
            ApiError::TwitchError(ref err) => err as &dyn Error,
            ApiError::EmptyResponse(ref err) => err as &dyn Error,
        })
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ApiError::HyperErr(ref err) => fmt::Display::fmt(err, f),
            ApiError::IoError(ref err) => fmt::Display::fmt(err, f),
            ApiError::ParseError(ref err) => fmt::Display::fmt(err, f),
            ApiError::TwitchError(ref err) => fmt::Display::fmt(err, f),
            ApiError::EmptyResponse(ref err) => fmt::Display::fmt(err, f),
        }
    }
}

///////////////////////////////////////
// ErrorResponse
///////////////////////////////////////
#[derive(Deserialize, Debug)]
pub struct ErrorResponse {
    pub error: String,
    pub status: i32,
    pub message: String,
    #[serde(skip_deserializing)]
    pub cause: Option<Box<Error>>,
}

impl fmt::Display for ErrorResponse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "TwitchError: (Status: {}, Error: {}, Message: {})",
            &self.status, self.error, &self.message
        )
    }
}

impl Error for ErrorResponse {
    fn description(&self) -> &str {
        &self.error
    }

    fn cause(&self) -> Option<&dyn Error> {
        if let Some(ref cause) = self.cause {
            Some(cause.as_ref())
        } else {
            None
        }
    }
}

///////////////////////////////////////
// EmptyResponse
///////////////////////////////////////
#[derive(Debug)]
pub struct EmptyResponse {}

impl fmt::Display for EmptyResponse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "EmptyResponse")
    }
}

impl Error for EmptyResponse {
    fn description(&self) -> &str {
        "EmptyResponse"
    }

    fn cause(&self) -> Option<&dyn Error> {
        None
    }
}

macro_rules! next_result {
    ($obj:ident, $url:expr, $serde:ty, $lst:ident) => {{
        let mut values_exist = false;
        if $obj.cur.is_none() {
            match $obj.client.get::<$serde>($url) {
                Ok(r) => {
                    $obj.offset += r.$lst.len() as i32;
                    $obj.cur = Some(r);
                    values_exist = true;
                }
                Err(r) => writeln!(
                    &mut std::io::stderr(),
                    "{} Error: {}",
                    stringify!($serde),
                    r
                )
                .unwrap(),
            };
        } else {
            values_exist = true;
        }

        match values_exist {
            true => {
                let mut x = None;
                let mut cnt = 0;
                if let Some(ref mut cur) = $obj.cur {
                    cnt = cur.$lst.len();
                    if cnt > 0 {
                        x = Some(cur.$lst.remove(0));
                        cnt -= 1;
                    }
                }
                if cnt == 0 {
                    $obj.cur = None;
                }
                x
            }
            false => None,
        }
    }};
}

macro_rules! next_result_cursor {
    ($obj:ident, $url:expr, $serde:ty, $lst:ident) => {{
        let mut values_exist = false;
        if $obj.cur.is_none() {
            let mut new_url = $url.clone();
            {
                if let Some(ref cursor) = $obj.cursor {
                    if cursor.len() == 0 {
                        return None;
                    } else {
                        new_url.push_str("&cursor=");
                        new_url.push_str(cursor.clone().as_str());
                    }
                }
            }
            match $obj.client.get::<$serde>(&new_url) {
                Ok(r) => {
                    if r.$lst.len() > 0 {
                        values_exist = true;
                    } else {
                        values_exist = false;
                    }
                    $obj.cursor = r._cursor.clone();
                    $obj.cur = Some(r);
                }
                Err(r) => writeln!(
                    &mut std::io::stderr(),
                    "{} Error: {}",
                    stringify!($serde),
                    r
                )
                .unwrap(),
            };
        } else {
            values_exist = true;
        }

        match values_exist {
            true => {
                let mut x = None;
                let mut cnt = 0;
                if let Some(ref mut cur) = $obj.cur {
                    cnt = cur.$lst.len();
                    if cnt > 0 {
                        x = Some(cur.$lst.remove(0));
                        cnt -= 1;
                    }
                }
                if cnt == 0 {
                    $obj.cur = None;
                }
                x
            }
            false => None,
        }
    }};
}