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
// 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.

//! # Twitch API
//!
//! Rust library for interacting with the Twitch API:
//! https://dev.twitch.tv/docs/
//!
//! # Examples
//!
//! ```
//! extern crate twitch_api;
//!
//! use twitch_api::games;
//!
//! let c = twitch_api::new("<clientid>".to_owned());
//! // Print the name of the top 20 games
//! if let Ok(games) = games::TopGames::get(&c) {
//!     for entry in games.take(20) {
//!         println!("{}: {}", entry.game.name, entry.viewers);
//!     }
//! }
//! ```

#[macro_use]
extern crate serde_derive;

extern crate hyper;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;

#[macro_use]
pub mod response;
pub mod channel_feed;
pub mod channels;
pub mod chat;
pub mod communities;
pub mod games;
pub mod ingests;
pub mod search;
pub mod streams;
pub mod teams;
pub mod users;
pub mod videos;

use response::{ApiError, ErrorResponse, TwitchResult};

use hyper::client::RequestBuilder;
use hyper::header::{qitem, Accept, Authorization, ContentType, Headers};
use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value};
use hyper::net::HttpsConnector;
use hyper::Client;

use serde::de::Deserialize;
use serde::Serialize;
use std::io::Write;
use std::io::{stderr, Read};

#[derive(Debug)]
pub struct TwitchClient {
    client: Client,
    cid: String,
    token: Option<String>,
}

pub fn new(clientid: String) -> TwitchClient {
    TwitchClient {
        client: Client::with_connector(HttpsConnector::new(hyper_rustls::TlsClient::new())),
        cid: clientid.clone(),
        token: None,
    }
}

impl TwitchClient {
    fn build_request<'a, F>(&self, path: &str, build: F) -> RequestBuilder<'a>
    where
        F: Fn(&str) -> RequestBuilder<'a>,
    {
        let url = String::from("https://api.twitch.tv/kraken") + path;
        let mut headers = Headers::new();

        headers.set_raw("Client-ID", vec![self.cid.clone().into_bytes()]);
        headers.set(Accept(vec![qitem(Mime(
            TopLevel::Application,
            SubLevel::Ext("vnd.twitchtv.v5+json".to_owned()),
            vec![],
        ))]));
        headers.set(ContentType(Mime(
            TopLevel::Application,
            SubLevel::Json,
            vec![(Attr::Charset, Value::Utf8)],
        )));
        if let Some(ref token) = self.token {
            headers.set(Authorization(format!("OAuth {}", token)));
        }

        build(&url).headers(headers)
    }

    pub fn set_oauth_token(&mut self, token: &str) {
        self.token = Some(String::from(token));
    }

    pub fn get<T: Deserialize>(&self, path: &str) -> TwitchResult<T> {
        let mut r = r#try!(self.build_request(path, |url| self.client.get(url)).send());
        let mut s = String::new();
        let _ = r#try!(r.read_to_string(&mut s));
        if s.len() == 0 {
            return Err(ApiError::empty_response());
        } else {
            match serde_json::from_str(&s) {
                Ok(x) => Ok(x),
                Err(err) => {
                    if let Ok(mut e) = serde_json::from_str::<ErrorResponse>(&s) {
                        e.cause = Some(Box::new(err));
                        return Err(ApiError::from(e));
                    }
                    writeln!(&mut stderr(), "Serde Parse Fail:\n\"{}\"", &s).unwrap();
                    Err(ApiError::from(err))
                }
            }
        }
    }

    pub fn post<T, R>(&self, path: &str, data: &T) -> TwitchResult<R>
    where
        T: Serialize,
        R: Deserialize,
    {
        let mut r = r#try!(self
            .build_request(path, |url| self.client.post(url))
            .body(&r#try!(serde_json::to_string(data)))
            .send());
        let mut s = String::new();
        let _ = r#try!(r.read_to_string(&mut s));
        if s.len() == 0 {
            return Err(ApiError::empty_response());
        } else {
            match serde_json::from_str(&s) {
                Ok(x) => Ok(x),
                Err(err) => {
                    if let Ok(mut e) = serde_json::from_str::<ErrorResponse>(&s) {
                        e.cause = Some(Box::new(err));
                        return Err(ApiError::from(e));
                    }
                    writeln!(&mut stderr(), "Serde Parse Fail:\n\"{}\"", &s).unwrap();
                    Err(ApiError::from(err))
                }
            }
        }
    }

    pub fn put<T, R>(&self, path: &str, data: &T) -> TwitchResult<R>
    where
        T: Serialize,
        R: Deserialize,
    {
        let mut r = r#try!(self
            .build_request(path, |url| self.client.put(url))
            .body(&r#try!(serde_json::to_string(data)))
            .send());
        let mut s = String::new();
        let _ = r#try!(r.read_to_string(&mut s));
        if s.len() == 0 {
            return Err(ApiError::empty_response());
        } else {
            match serde_json::from_str(&s) {
                Ok(x) => Ok(x),
                Err(err) => {
                    if let Ok(mut e) = serde_json::from_str::<ErrorResponse>(&s) {
                        e.cause = Some(Box::new(err));
                        return Err(ApiError::from(e));
                    }
                    writeln!(&mut stderr(), "Serde Parse Fail:\n\"{}\"", &s).unwrap();
                    Err(ApiError::from(err))
                }
            }
        }
    }

    pub fn delete<T: Deserialize>(&self, path: &str) -> TwitchResult<T> {
        let mut r = r#try!(self
            .build_request(path, |url| self.client.delete(url))
            .send());
        let mut s = String::new();
        let _ = r#try!(r.read_to_string(&mut s));
        if s.len() == 0 {
            return Err(ApiError::empty_response());
        } else {
            match serde_json::from_str(&s) {
                Ok(x) => Ok(x),
                Err(err) => {
                    if let Ok(mut e) = serde_json::from_str::<ErrorResponse>(&s) {
                        e.cause = Some(Box::new(err));
                        return Err(ApiError::from(e));
                    }
                    writeln!(&mut stderr(), "Serde Parse Fail:\n\"{}\"", &s).unwrap();
                    Err(ApiError::from(err))
                }
            }
        }
    }
}

pub mod auth {
    use std::fmt;

    use super::TwitchClient;

    #[derive(Debug)]
    #[allow(non_camel_case_types)]
    pub enum Scope {
        channel_check_subscription,
        channel_commercial,
        channel_editor,
        channel_feed_edit,
        channel_feed_read,
        channel_read,
        channel_stream,
        channel_subscriptions,
        chat_login,
        user_blocks_edit,
        user_blocks_read,
        user_follows_edit,
        user_read,
        user_subscriptions,
        viewing_activity_ready,
    }

    impl fmt::Display for Scope {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            fmt::Debug::fmt(self, f)
        }
    }

    // TODO: replace with:
    // https://doc.rust-lang.org/std/slice/trait.SliceConcatExt.html
    fn format_scope(scopes: &[Scope]) -> String {
        let mut res = String::with_capacity(27 * scopes.len());
        for scope in scopes.iter() {
            res.push_str(&scope.to_string());
            res.push('+');
        }
        res.trim_end_matches('+').to_owned()
    }

    fn gen_auth_url(
        c: &TwitchClient,
        rtype: &str,
        redirect_url: &str,
        scope: &[Scope],
        state: &str,
    ) -> String {
        String::from("https://api.twitch.tv/kraken/oauth2/authorize")
            + "?response_type="
            + rtype
            + "&client_id="
            + &c.cid
            + "&redirect_uri="
            + redirect_url
            + "&scope="
            + &format_scope(scope)
            + "&state="
            + state
    }

    pub fn auth_code_flow(
        c: &TwitchClient,
        redirect_url: &str,
        scope: &[Scope],
        state: &str,
    ) -> String {
        gen_auth_url(c, "code", redirect_url, scope, state)
    }

    pub fn imp_grant_flow(
        c: &TwitchClient,
        redirect_url: &str,
        scope: &[Scope],
        state: &str,
    ) -> String {
        gen_auth_url(c, "token", redirect_url, scope, state)
    }
}

#[cfg(test)]
mod tests {
    pub const CLIENTID: &'static str = "";
    pub const TOKEN: &'static str = "";
    pub const CHANID: &'static str = "";
    pub const TESTCH: i64 = 12826;
}