twitch_api/helix/endpoints/search/search_channels.rs
1//! Returns a list of channels (users who have streamed within the past 6 months) that match the query via channel name or description either entirely or partially.
2//!
3//! [`search-channels`](https://dev.twitch.tv/docs/api/reference#search-channels)
4//!
5//! # Accessing the endpoint
6//!
7//! ## Request: [SearchChannelsRequest]
8//!
9//! To use this endpoint, construct a [`SearchChannelsRequest`] with the [`SearchChannelsRequest::query()`] method.
10//!
11//! ```rust
12//! use twitch_api::helix::search::search_channels;
13//! let request = search_channels::SearchChannelsRequest::query("hello");
14//! ```
15//!
16//! ## Response: [Channel]
17//!
18//! Send the request to receive the response with [`HelixClient::req_get()`](helix::HelixClient::req_get).
19//!
20//! ```rust, no_run
21//! use twitch_api::helix::{self, search::search_channels};
22//! # use twitch_api::client;
23//! # #[tokio::main]
24//! # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
25//! # let client: helix::HelixClient<'static, client::DummyHttpClient> = helix::HelixClient::default();
26//! # let token = twitch_oauth2::AccessToken::new("validtoken".to_string());
27//! # let token = twitch_oauth2::UserToken::from_existing(&client, token, None, None).await?;
28//! let request = search_channels::SearchChannelsRequest::query("hello");
29//! let response: Vec<search_channels::Channel> = client.req_get(request, &token).await?.data;
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! You can also get the [`http::Request`] with [`request.create_request(&token, &client_id)`](helix::RequestGet::create_request)
35//! and parse the [`http::Response`] with [`SearchChannelsRequest::parse_response(None, &request.get_uri(), response)`](SearchChannelsRequest::parse_response)
36
37use super::*;
38use helix::RequestGet;
39
40/// Query Parameters for [Search Channels](super::search_channels)
41///
42/// [`search-channels`](https://dev.twitch.tv/docs/api/reference#search-channels)
43#[derive(PartialEq, Eq, Deserialize, Serialize, Clone, Debug)]
44#[cfg_attr(feature = "typed-builder", derive(typed_builder::TypedBuilder))]
45#[must_use]
46#[non_exhaustive]
47pub struct SearchChannelsRequest<'a> {
48 /// URL encoded search query
49 #[cfg_attr(feature = "typed-builder", builder(setter(into)))]
50 #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
51 pub query: Cow<'a, str>,
52 /// 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.
53 #[cfg_attr(feature = "typed-builder", builder(default))]
54 #[cfg_attr(feature = "deser_borrow", serde(borrow = "'a"))]
55 pub after: Option<Cow<'a, helix::CursorRef>>,
56 /// Maximum number of objects to return. Maximum: 100 Default: 20
57 #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
58 // FIXME: No setter because int
59 pub first: Option<usize>,
60 /// Filter results for live streams only. Default: false
61 #[cfg_attr(feature = "typed-builder", builder(default, setter(into)))]
62 pub live_only: Option<bool>,
63}
64
65impl<'a> SearchChannelsRequest<'a> {
66 /// Search channels with the following query.
67 pub fn query(query: impl Into<Cow<'a, str>>) -> Self {
68 Self {
69 query: query.into(),
70 after: None,
71 first: None,
72 live_only: None,
73 }
74 }
75
76 /// Get live streams only
77 pub const fn live_only(mut self, live_only: bool) -> Self {
78 self.live_only = Some(live_only);
79 self
80 }
81
82 /// Set amount of results returned per page.
83 pub const fn first(mut self, first: usize) -> Self {
84 self.first = Some(first);
85 self
86 }
87}
88
89/// Return Values for [Search Channels](super::search_channels)
90///
91/// [`search-channels`](https://dev.twitch.tv/docs/api/reference#search-channels)
92#[derive(PartialEq, Eq, Deserialize, Serialize, Debug, Clone)]
93#[cfg_attr(feature = "deny_unknown_fields", serde(deny_unknown_fields))]
94#[non_exhaustive]
95pub struct Channel {
96 /// ID of the game being played on the stream
97 pub game_id: types::CategoryId,
98 /// Name of the game being played on the stream.
99 pub game_name: String,
100 /// Channel ID
101 pub id: types::UserId,
102 /// Display name corresponding to user_id
103 pub display_name: types::DisplayName,
104 /// Channel language (Broadcaster Language field from the [Channels service][crate::helix::channels])
105 pub broadcaster_language: String,
106 /// Login of the broadcaster.
107 pub broadcaster_login: types::UserName,
108 /// channel title
109 pub title: String,
110 /// 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.
111 pub thumbnail_url: String,
112 /// Live status
113 pub is_live: bool,
114 /// UTC timestamp. (live only)
115 #[serde(
116 default,
117 deserialize_with = "crate::deserialize_none_from_empty_string"
118 )]
119 pub started_at: Option<types::Timestamp>,
120 /// Shows tag IDs that apply to the stream (live only).See <https://www.twitch.tv/directory/all/tags> for tag types
121 #[deprecated(note = "use `tags` instead")]
122 pub tag_ids: Vec<types::TagId>,
123 /// The tags applied to the channel.
124 pub tags: Vec<String>,
125}
126
127impl Request for SearchChannelsRequest<'_> {
128 type Response = Vec<Channel>;
129
130 const PATH: &'static str = "search/channels";
131 #[cfg(feature = "twitch_oauth2")]
132 const SCOPE: twitch_oauth2::Validator = twitch_oauth2::validator![];
133}
134
135impl RequestGet for SearchChannelsRequest<'_> {}
136
137impl helix::Paginated for SearchChannelsRequest<'_> {
138 fn set_pagination(&mut self, cursor: Option<helix::Cursor>) {
139 self.after = cursor.map(|c| c.into_cow())
140 }
141}
142
143#[cfg(test)]
144#[test]
145fn test_request() {
146 use helix::*;
147 let req = SearchChannelsRequest::query("fort");
148
149 // From twitch docs
150 let data = br#"
151 {
152 "data": [
153 {
154 "broadcaster_language": "en",
155 "broadcaster_login": "loserfruit",
156 "display_name": "Loserfruit",
157 "game_id": "498000",
158 "game_name": "House Flipper",
159 "id": "41245072",
160 "is_live": false,
161 "tag_ids": [],
162 "tags": [],
163 "thumbnail_url": "https://static-cdn.jtvnw.net/jtv_user_pictures/fd17325a-7dc2-46c6-8617-e90ec259501c-profile_image-300x300.png",
164 "title": "loserfruit",
165 "started_at": ""
166 },
167 {
168 "broadcaster_language": "en",
169 "broadcaster_login": "a_seagull",
170 "display_name": "A_Seagull",
171 "game_id": "506442",
172 "game_name": "DOOM Eternal",
173 "id": "19070311",
174 "is_live": true,
175 "tag_ids": [],
176 "tags": ["English"],
177 "thumbnail_url": "https://static-cdn.jtvnw.net/jtv_user_pictures/a_seagull-profile_image-4d2d235688c7dc66-300x300.png",
178 "title": "a_seagull",
179 "started_at": "2020-03-18T17:56:00Z"
180 }
181 ],
182 "pagination": {}
183 }
184"#
185 .to_vec();
186
187 let http_response = http::Response::builder().body(data).unwrap();
188
189 let uri = req.get_uri().unwrap();
190 assert_eq!(
191 uri.to_string(),
192 "https://api.twitch.tv/helix/search/channels?query=fort"
193 );
194
195 dbg!(SearchChannelsRequest::parse_response(Some(req), &uri, http_response).unwrap());
196}