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
// 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 chrono;
extern crate serde_json;
extern crate urlparse;

use std;
use std::io::Write;

use self::urlparse::quote;

use super::channels::Channel;
use super::games::Game;
use super::response::TwitchResult;
use super::streams::Stream;
use super::TwitchClient;

/// Searches for channels based on a specified query parameter
///
/// A channel is returned if the query parameter is
/// matched entirely or partially, in the channel
/// description or game name.
///
/// #### Authentication: `None`
///
pub fn channels<'c>(c: &'c TwitchClient, query: &str) -> TwitchResult<SearchChannelIterator<'c>> {
    let iter = SearchChannelIterator {
        client: c,
        query: quote(query, b"").ok().unwrap(),
        cur: None,
        offset: 0,
    };
    Ok(iter)
}

/// Searches for games based on a specified query parameter
///
/// A game is returned if the query parameter is
/// matched entirely or partially, in the game name.
///
/// #### Authentication: `None`
///
pub fn games<'c>(
    c: &'c TwitchClient,
    query: &str,
    live_only: bool,
) -> TwitchResult<SearchGameIterator<'c>> {
    let iter: SearchGameIterator = SearchGameIterator {
        client: c,
        query: quote(query, b"").ok().unwrap(),
        live_only,
        cur: None,
        offset: 0,
    };
    Ok(iter)
}

/// Searches for streams based on a specified query parameter
///
/// A stream is returned if the query parameter is
/// matched entirely or partially, in the channel
/// description or game name.
///
/// #### Authentication: `None`
///
pub fn streams<'c>(
    c: &'c TwitchClient,
    query: &str,
    protocol: Option<Protocol>,
) -> TwitchResult<SearchStreamIterator<'c>> {
    let iter = SearchStreamIterator {
        client: c,
        query: quote(query, b"").ok().unwrap(),
        protocol,
        cur: None,
        offset: 0,
    };
    Ok(iter)
}

///////////////////////////////////////
// SearchChannels
///////////////////////////////////////
#[derive(Debug)]
pub struct SearchChannelIterator<'c> {
    client: &'c TwitchClient,
    query: String,
    cur: Option<SerdeSearchChannels>,
    offset: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeSearchChannels {
    channels: Vec<Channel>,
}

impl<'c> Iterator for SearchChannelIterator<'c> {
    type Item = Channel;

    fn next(&mut self) -> Option<Channel> {
        let url = &format!(
            "/search/channels?query={}&limit=100&offset={}",
            self.query, self.offset
        );
        next_result!(self, &url, SerdeSearchChannels, channels)
    }
}

///////////////////////////////////////
// SearchGames
///////////////////////////////////////
pub struct SearchGameIterator<'c> {
    client: &'c TwitchClient,
    query: String,
    live_only: bool,
    cur: Option<SerdeSearchGames>,
    offset: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeSearchGames {
    games: Vec<Game>,
}

impl<'c> Iterator for SearchGameIterator<'c> {
    type Item = Game;

    fn next(&mut self) -> Option<Game> {
        let url = &format!(
            "/search/games?query={}&live={}&limit=100&offset={}",
            self.query, self.live_only, self.offset
        );
        next_result!(self, &url, SerdeSearchGames, games)
    }
}

///////////////////////////////////////
// SearchStreams
///////////////////////////////////////
pub struct SearchStreamIterator<'c> {
    client: &'c TwitchClient,
    query: String,
    protocol: Option<Protocol>,
    cur: Option<SerdeSearchStreams>,
    offset: i32,
}

#[derive(Deserialize, Debug)]
struct SerdeSearchStreams {
    streams: Vec<Stream>,
}

pub enum Protocol {
    HLS,
    RTMP,
}

impl<'c> Iterator for SearchStreamIterator<'c> {
    type Item = Stream;

    fn next(&mut self) -> Option<Stream> {
        let mut path = format!(
            "/search/streams?query={}&limit=100&offset={}",
            self.query, self.offset
        );
        path = match self.protocol {
            Some(Protocol::HLS) => path + "&hls=true",
            Some(Protocol::RTMP) => path + "&hls=false",
            None => path,
        };
        next_result!(self, &path, SerdeSearchStreams, streams)
    }
}

///////////////////////////////////////
// TESTS
///////////////////////////////////////
#[cfg(test)]
mod tests {
    use super::super::new;
    use super::super::response;
    use super::super::tests::CLIENTID;

    #[test]
    fn channels() {
        let c = new(String::from(CLIENTID));

        match super::channels(&c, "twitch") {
            Ok(mut r) => assert_ne!(r.next().unwrap().id, 0),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        }
    }

    #[test]
    fn games() {
        let c = new(String::from(CLIENTID));

        match super::games(&c, "league", false) {
            Ok(mut r) => assert_ne!(r.next().unwrap().id, 0),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        }
    }

    #[test]
    fn streams() {
        let c = new(String::from(CLIENTID));

        match super::streams(&c, "twitch", None) {
            Ok(mut r) => assert_ne!(r.next().unwrap().id, 0),
            Err(r) => {
                println!("{:?}", r);
                assert!(false);
            }
        }
    }
}