twitch_api2/helix/endpoints/streams/
get_streams.rs

1//! Gets information about active streams.
2//! [`get-streams`](https://dev.twitch.tv/docs/api/reference#get-streams)
3//!
4//! # Accessing the endpoint
5//!
6//! ## Request: [GetStreamsRequest]
7//!
8//! To use this endpoint, construct a [`GetStreamsRequest`] with the [`GetStreamsRequest::builder()`] method.
9//!
10//! ```rust
11//! use twitch_api2::helix::streams::get_streams;
12//! let request = get_streams::GetStreamsRequest::builder()
13//!     .user_login(vec!["justintvfan".into()])
14//!     .build();
15//! ```
16//!
17//! ## Response: [Stream]
18//!
19//! Send the request to receive the response with [`HelixClient::req_get()`](helix::HelixClient::req_get).
20//!
21//! ```rust, no_run
22//! use twitch_api2::helix::{self, streams::get_streams};
23//! # use twitch_api2::client;
24//! # #[tokio::main]
25//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
26//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
27//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
28//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
29//! let request = get_streams::GetStreamsRequest::builder()
30//!     .user_login(vec!["justintvfan".into()])
31//!     .build();
32//! let response: Vec<get_streams::Stream> = client.req_get(request, &token).await?.data;
33//! # Ok(())
34//! # }
35//! ```
36//!
37//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestGet::create_request)
38//! and parse the [`http::Response`] with [`GetStreamsRequest::parse_response(None, &request.get_uri(), response)`](GetStreamsRequest::parse_response)
39
40use super::*;
41use helix::RequestGet;
42
43/// Query Parameters for [Get Streams](super::get_streams)
44///
45/// [`get-streams`](https://dev.twitch.tv/docs/api/reference#get-streams)
46#[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug)]
47#[non_exhaustive]
48pub struct GetStreamsRequest {
49    /// Cursor for forward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
50    #[builder(default)]
51    pub after: Option<helix::Cursor>,
52    /// Cursor for backward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
53    #[builder(default)]
54    pub before: Option<helix::Cursor>,
55    /// Maximum number of objects to return. Maximum: 100. Default: 20.
56    #[builder(default, setter(into))]
57    pub first: Option<usize>,
58    /// Returns streams broadcasting a specified game ID. You can specify up to 10 IDs.
59    #[builder(default)]
60    pub game_id: Vec<types::CategoryId>,
61    /// Stream language. You can specify up to 100 languages.
62    #[builder(default)]
63    pub language: Option<String>,
64    /// Returns streams broadcast by one or more specified user IDs. You can specify up to 100 IDs.
65    #[builder(default, setter(into))]
66    pub user_id: Vec<types::UserId>,
67    /// Returns streams broadcast by one or more specified user login names. You can specify up to 100 names.
68    #[builder(default)]
69    pub user_login: Vec<types::UserName>,
70}
71
72/// Return Values for [Get Streams](super::get_streams)
73///
74/// [`get-streams`](https://dev.twitch.tv/docs/api/reference#get-streams)
75#[derive(PartialEq, Deserialize, Serialize, Debug, Clone)]
76#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
77#[non_exhaustive]
78pub struct Stream {
79    /// ID of the game being played on the stream.
80    pub game_id: types::CategoryId,
81    /// Name of the game being played.
82    pub game_name: String,
83    /// Stream ID.
84    pub id: types::StreamId,
85    /// Stream language.
86    pub language: String,
87    /// Indicates if the broadcaster has specified their channel contains mature content that may be inappropriate for younger audiences.
88    pub is_mature: bool,
89    /// UTC timestamp.
90    pub started_at: types::Timestamp,
91    /// Shows tag IDs that apply to the stream.
92    #[serde(deserialize_with = "helix::deserialize_default_from_null")]
93    pub tag_ids: Vec<types::TagId>,
94    /// Thumbnail URL of the stream. All image URLs have variable width and height. You can replace {width} and {height} with any values to get that size image
95    pub thumbnail_url: String,
96    /// Stream title.
97    pub title: String,
98    /// Stream type: "live" or "" (in case of error).
99    #[serde(rename = "type")]
100    pub type_: StreamType,
101    /// ID of the user who is streaming.
102    pub user_id: types::UserId,
103    /// Display name corresponding to user_id.
104    pub user_name: types::DisplayName,
105    /// Login of the user who is streaming.
106    pub user_login: types::UserName,
107    /// Number of viewers watching the stream at the time of the query.
108    pub viewer_count: usize,
109}
110
111impl Request for GetStreamsRequest {
112    type Response = Vec<Stream>;
113
114    const PATH: &'static str = "streams";
115    #[cfg(feature = "twitch_oauth2")]
116    const SCOPE: &'static [twitch_oauth2::Scope] = &[];
117}
118
119impl RequestGet for GetStreamsRequest {}
120
121impl helix::Paginated for GetStreamsRequest {
122    fn set_pagination(&mut self, cursor: Option<helix::Cursor>) { self.after = cursor }
123}
124
125#[cfg(test)]
126#[test]
127fn test_request() {
128    use helix::*;
129    let req = GetStreamsRequest::builder().build();
130
131    // From twitch docs, kinda. example 1 in https://dev.twitch.tv/docs/api/reference#get-streams is malformed
132    let data = br#"
133{
134    "data": [
135        {
136            "id": "26007494656",
137            "user_id": "23161357",
138            "user_name": "LIRIK",
139            "user_login": "lirik",
140            "game_id": "417752",
141            "game_name": "Talk Shows & Podcasts",
142            "type": "live",
143            "title": "Hey Guys, It's Monday - Twitter: @Lirik",
144            "viewer_count": 32575,
145            "started_at": "2017-08-14T16:08:32Z",
146            "language": "en",
147            "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_lirik-{width}x{height}.jpg",
148            "tag_ids":  [
149                "6ea6bca4-4712-4ab9-a906-e3336a9d8039"
150            ],
151            "is_mature": false
152        },
153        {
154            "id": "26007494656",
155            "user_id": "23161357",
156            "user_name": "LIRIK",
157            "user_login": "lirik",
158            "game_id": "417752",
159            "game_name": "Talk Shows & Podcasts",
160            "type": "live",
161            "title": "Hey Guys, It's Monday - Twitter: @Lirik",
162            "viewer_count": 32575,
163            "started_at": "2017-08-14T16:08:32Z",
164            "language": "en",
165            "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_lirik-{width}x{height}.jpg",
166            "tag_ids":  [
167                "6ea6bca4-4712-4ab9-a906-e3336a9d8039"
168            ],
169            "is_mature": false
170        }
171    ],
172    "pagination": {
173        "cursor": "eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ=="
174    }
175}
176"#
177        .to_vec();
178
179    let http_response = http::Response::builder().body(data).unwrap();
180
181    let uri = req.get_uri().unwrap();
182    assert_eq!(uri.to_string(), "https://api.twitch.tv/helix/streams?");
183
184    dbg!(GetStreamsRequest::parse_response(Some(req), &uri, http_response).unwrap());
185}
186
187#[cfg(test)]
188#[test]
189fn test_request_null_tags_issue184() {
190    use helix::*;
191    let req = GetStreamsRequest::builder().build();
192
193    // From twitch docs, kinda. example 1 in https://dev.twitch.tv/docs/api/reference#get-streams is malformed
194    let data = br#"
195{
196    "data": [
197        {
198            "id": "26007494656",
199            "user_id": "23161357",
200            "user_name": "LIRIK",
201            "user_login": "lirik",
202            "game_id": "417752",
203            "game_name": "Talk Shows & Podcasts",
204            "type": "live",
205            "title": "Hey Guys, It's Monday - Twitter: @Lirik",
206            "viewer_count": 32575,
207            "started_at": "2017-08-14T16:08:32Z",
208            "language": "en",
209            "thumbnail_url": "https://static-cdn.jtvnw.net/previews-ttv/live_user_lirik-{width}x{height}.jpg",
210            "tag_ids":  null,
211            "is_mature": false
212        }
213    ],
214    "pagination": {
215        "cursor": "eyJiIjpudWxsLCJhIjp7Ik9mZnNldCI6MjB9fQ=="
216    }
217}
218"#
219        .to_vec();
220
221    let http_response = http::Response::builder().body(data).unwrap();
222
223    let uri = req.get_uri().unwrap();
224    assert_eq!(uri.to_string(), "https://api.twitch.tv/helix/streams?");
225
226    dbg!(GetStreamsRequest::parse_response(Some(req), &uri, http_response).unwrap());
227}