Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / youpipe / src / main / rust / tests / coverage_stream_search.rs

coverage_stream_search.rs442 lines · 19.6 KiBRaw
1//! Coverage for stream.rs / stream_part1.rs / search.rs via public API.
2use serde_json::json;
3use std::sync::{Mutex, MutexGuard};
4use youpipe_extractor::decoder::clear_caches;
5use youpipe_extractor::http::{HttpClient, Request, Response, Result};
6use youpipe_extractor::innertube::reset_client_version;
7use youpipe_extractor::model::{SearchItem, StreamInfo, StreamKind};
8use youpipe_extractor::{search, stream};
9
10static LOCK: Mutex<()> = Mutex::new(());
11fn lock() -> MutexGuard<'static, ()> {
12 let g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
13 reset_client_version();
14 clear_caches();
15 g
16}
17fn resp(url: &str, body: String) -> Response {
18 Response {
19 code: 200,
20 body: body.into_bytes(),
21 latest_url: url.to_string(),
22 headers: [("Content-Type".into(), vec!["application/json".into()])].into_iter().collect(),
23 }
24}
25
26#[derive(Default, Clone)]
27struct Client {
28 player: String,
29 next: String,
30 search: String,
31 search_cont: String,
32}
33impl HttpClient for Client {
34 fn execute(&self, req: Request<'_>) -> Result<Response> {
35 if req.url.contains("sw.js") {
36 return Ok(resp(
37 &req.url,
38 r#"{"INNERTUBE_CONTEXT_CLIENT_VERSION":"2.20260120.01.00"}"#.into(),
39 ));
40 }
41 if req.url.contains("latest-player") {
42 return Ok(resp(
43 &req.url,
44 r#"{"player":"testplayer","signatureTimestamp":12345}"#.into(),
45 ));
46 }
47 if req.url.contains("decoder/decode") {
48 // extract sig= or n= value
49 let val =
50 req.url.split(&['=', '&'][..]).rfind(|s| !s.is_empty()).unwrap_or("x").to_string();
51 // find param value: after sig= or n=
52 let v = if let Some(i) = req.url.find("sig=") {
53 req.url[i + 4..].split('&').next().unwrap_or("").to_string()
54 } else if let Some(i) = req.url.find("&n=") {
55 req.url[i + 3..].split('&').next().unwrap_or("").to_string()
56 } else if let Some(i) = req.url.find("?n=") {
57 req.url[i + 3..].split('&').next().unwrap_or("").to_string()
58 } else {
59 val
60 };
61 let body = json!({"type":"result","responses":[{"type":"result","data":{ v.clone(): format!("decoded-{v}") }}]}).to_string();
62 return Ok(resp(&req.url, body));
63 }
64 let body = req.body.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
65 let is_cont = body.contains("\"continuation\"");
66 if req.url.contains("youtubei/v1/player") {
67 return Ok(resp(&req.url, self.player.clone()));
68 }
69 if req.url.contains("youtubei/v1/next") {
70 return Ok(resp(&req.url, self.next.clone()));
71 }
72 if req.url.contains("youtubei/v1/search") {
73 return Ok(resp(
74 &req.url,
75 if is_cont { self.search_cont.clone() } else { self.search.clone() },
76 ));
77 }
78 Ok(resp(&req.url, "{}".into()))
79 }
80}
81
82fn player_fixture() -> String {
83 json!({
84 "playabilityStatus":{"status":"OK"},
85 "videoDetails":{"title":"Test Vid","lengthSeconds":"214","viewCount":"1234567","author":"Uploader","channelId":"UC12345678901234567890","shortDescription":"desc","thumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/t.jpg","width":120,"height":90}]},"keywords":["a","b"]},
86 "microformat":{"playerMicroformatRenderer":{"uploadDate":"2024-01-02","category":"Music","isFamilySafe":true,"likeCount":"999"}},
87 "streamingData":{"dashManifestUrl":"https://example.com/dash","hlsManifestUrl":"https://example.com/hls",
88 "formats":[{"itag":18,"mimeType":"video/mp4; codecs=\"avc1.64001F\"","url":"https://example.com/v18?itag=18","width":640,"height":360,"bitrate":500000,"qualityLabel":"360p","contentLength":"12345","fps":30}],
89 "adaptiveFormats":[
90 {"itag":140,"mimeType":"audio/mp4; codecs=\"mp4a.40.2\"","url":"https://example.com/a140?itag=140","bitrate":130000,"averageBitrate":128000,"audioSampleRate":"44100","audioChannels":2,"audioTrack":{"id":"en.4","displayName":"English"},"contentLength":"999","initRange":{"start":0,"end":10},"indexRange":{"start":11,"end":20}},
91 {"itag":137,"mimeType":"video/mp4; codecs=\"avc1.640028\"","url":"https://example.com/v137?itag=137&n=XYZABC","width":1920,"height":1080,"qualityLabel":"1080p","bitrate":4000000},
92 {"itag":999,"mimeType":"text/plain","url":"https://example.com/x"},
93 {"itag":313,"mimeType":"video/webm"}
94 ]}
95 }).to_string()
96}
97
98#[test]
99fn stream_info_full() {
100 let _g = lock();
101 let info = stream::stream_info(
102 &Client { player: player_fixture(), ..Default::default() },
103 "aaaaaaaaaaa",
104 "en",
105 "US",
106 )
107 .unwrap();
108 assert_eq!(info.name, "Test Vid");
109 assert_eq!(info.duration_seconds, 214);
110 assert_eq!(info.view_count, 1234567);
111 assert_eq!(info.like_count, 999);
112 assert_eq!(info.kind, StreamKind::Video);
113 assert_eq!(info.age_limit, 0);
114 assert_eq!(info.tags, vec!["a".to_string(), "b".to_string()]);
115 assert_eq!(info.video_streams.len(), 1);
116 assert_eq!(info.video_streams[0].codec.as_deref(), Some("avc1.64001F"));
117 assert_eq!(info.audio_streams.len(), 1);
118 assert_eq!(info.audio_streams[0].sample_rate, 44100);
119 assert_eq!(info.audio_streams[0].track_id.as_deref(), Some("en.4"));
120 assert_eq!(info.video_only_streams.len(), 1);
121 // n param decoded
122 assert!(
123 info.video_only_streams[0].url.contains("decoded-XYZABC"),
124 "url {}",
125 info.video_only_streams[0].url
126 );
127 assert!(!info.sabr_only);
128 assert_eq!(info.dash_manifest_url.as_deref(), Some("https://example.com/dash"));
129}
130
131#[test]
132fn stream_info_live_postlive_and_sabr() {
133 let _g = lock();
134 let live = json!({"playabilityStatus":{"status":"OK","liveStreamability":{}},"videoDetails":{"title":"Live","isLiveContent":true},"microformat":{"playerMicroformatRenderer":{"isFamilySafe":false,"publishDate":"2024-01-01"}},"streamingData":{"serverAbrStreamingUrl":"https://example.com/sabr","adaptiveFormats":[{"itag":313,"mimeType":"video/webm"}]}}).to_string();
135 let info = stream::stream_info(
136 &Client { player: live, ..Default::default() },
137 "bbbbbbbbbbb",
138 "en",
139 "US",
140 )
141 .unwrap();
142 assert_eq!(info.kind, StreamKind::Live);
143 assert_eq!(info.age_limit, 18);
144 assert!(info.sabr_only);
145 assert_eq!(info.server_abr_streaming_url.as_deref(), Some("https://example.com/sabr"));
146 assert_eq!(info.view_count, -1);
147 assert_eq!(info.like_count, -1);
148 // post-live DVR via isPostLiveDvr, also live via playability liveStreamability already covered; use DVR flag
149 let dvr = json!({"videoDetails":{"title":"DVR","isPostLiveDvr":true},"microformat":{"playerMicroformatRenderer":{}},"streamingData":{}}).to_string();
150 let info2 = stream::stream_info(
151 &Client { player: dvr, ..Default::default() },
152 "ccccccccccc",
153 "en",
154 "US",
155 )
156 .unwrap();
157 assert_eq!(info2.kind, StreamKind::PostLive);
158 let dvr2 = json!({"videoDetails":{"title":"DVR2","isLiveDvrEnabled":true},"microformat":{"playerMicroformatRenderer":{}},"streamingData":{}}).to_string();
159 assert_eq!(
160 stream::stream_info(
161 &Client { player: dvr2, ..Default::default() },
162 "ccccccccccc",
163 "en",
164 "US"
165 )
166 .unwrap()
167 .kind,
168 StreamKind::PostLive
169 );
170}
171
172#[test]
173fn stream_info_signature_cipher_and_errors() {
174 let _g = lock();
175 let fixture = json!({
176 "videoDetails":{"title":"Cipher"},
177 "microformat":{"playerMicroformatRenderer":{}},
178 "streamingData":{"formats":[
179 {"itag":22,"mimeType":"video/mp4","signatureCipher":"s=SIGVAL&sp=sig&url=https%3A%2F%2Fexample.com%2Fvideoplayback%3Fitag%3D22"},
180 {"itag":23,"mimeType":"video/mp4","cipher":"s=SIG2&url=https%3A%2F%2Fexample.com%2Fv%3Fx%3D1"},
181 {"itag":24,"mimeType":"video/mp4","signatureCipher":"s=NONE"}
182 ],"adaptiveFormats":[
183 {"itag":140,"mimeType":"audio/webm; codecs=\"opus\"","url":"https://example.com/a?x=1"}
184 ]}
185 }).to_string();
186 let info = stream::stream_info(
187 &Client { player: fixture, ..Default::default() },
188 "ddddddddddd",
189 "en",
190 "US",
191 )
192 .unwrap();
193 assert_eq!(info.video_streams.len(), 2);
194 assert!(info.video_streams[0].url.contains("decoded-SIGVAL"));
195 assert!(info.video_streams[0].url.contains("sig=decoded-SIGVAL"));
196 // second uses default sp=signature
197 assert!(info.video_streams[1].url.contains("signature=decoded-SIG2"));
198 assert_eq!(info.errors.len(), 1, "missing url in cipher is an error entry: {:?}", info.errors);
199}
200
201#[test]
202fn stream_playability_via_public_api() {
203 let _g = lock();
204 for (status, reason, expect) in [
205 ("LOGIN_REQUIRED", "inappropriate for some users", "age-restricted"),
206 ("LOGIN_REQUIRED", "This video is private", "private"),
207 ("LOGIN_REQUIRED", "Sign in to confirm you're not a bot", "blocking anonymous"),
208 ("LOGIN_REQUIRED", "something else", "login required"),
209 ("UNPLAYABLE", "requires Music Premium", "Music Premium"),
210 ("UNPLAYABLE", "payment required", "paid"),
211 ("UNPLAYABLE", "members only", "members-only"),
212 ("UNPLAYABLE", "not available in your country", "country"),
213 ("ERROR", "This account has been terminated", "terminated"),
214 ("ERROR", "account closed", "terminated"),
215 ("ERROR", "weird failure", "weird"),
216 ] {
217 let fixture = json!({"playabilityStatus":{"status":status,"reason":reason}}).to_string();
218 let err = stream::stream_info(
219 &Client { player: fixture, ..Default::default() },
220 "eeeeeeeeeee",
221 "en",
222 "US",
223 )
224 .unwrap_err()
225 .to_string();
226 assert!(err.contains(expect), "{status}/{reason} -> {err} expected {expect}");
227 }
228 // reason via messages array
229 let fixture = json!({"playabilityStatus":{"status":"UNPLAYABLE","messages":[{"simpleText":"not available in your country"}]}}).to_string();
230 let err = stream::stream_info(
231 &Client { player: fixture, ..Default::default() },
232 "eeeeeeeeeee",
233 "en",
234 "US",
235 )
236 .unwrap_err()
237 .to_string();
238 assert!(err.contains("country"), "{err}");
239 // case-insensitive OK
240 let ok = json!({"playabilityStatus":{"status":"ok"},"videoDetails":{"title":"x"},"microformat":{"playerMicroformatRenderer":{}},"streamingData":{}}).to_string();
241 assert!(stream::stream_info(
242 &Client { player: ok, ..Default::default() },
243 "eeeeeeeeeee",
244 "en",
245 "US"
246 )
247 .is_ok());
248}
249
250#[test]
251fn augment_from_next_full() {
252 let _g = lock();
253 let next = json!({"contents":{"twoColumnWatchNextResults":{"results":{"results":{"contents":[
254 {"videoPrimaryInfoRenderer":{"viewCount":{"videoViewCountRenderer":{"viewCount":{"simpleText":"5,678 views"}}},"videoActions":{"menuRenderer":{"topLevelButtons":[{"segmentedLikeDislikeButtonViewModel":{"likeButtonViewModel":{"likeButtonViewModel":{"toggleButtonViewModel":{"toggleButtonViewModel":{"defaultButtonViewModel":{"buttonViewModel":{"accessibilityText":"like this video along with 1,234,567 other people"}}}}}}}}]}}}},
255 {"videoSecondaryInfoRenderer":{"owner":{"videoOwnerRenderer":{"badges":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_VERIFIED"}}],"subscriberCountText":{"simpleText":"2.5M subscribers"},"navigationEndpoint":{"commandMetadata":{"webCommandMetadata":{"url":"/@chan"}}},"thumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/av.jpg","width":40,"height":40}]}}}}}
256 ]}}}}}).to_string();
257 let mut info = StreamInfo { view_count: -1, like_count: -1, ..Default::default() };
258 stream::augment_from_next(
259 &Client { next: next.clone(), ..Default::default() },
260 "aaaaaaaaaaa",
261 "en",
262 "US",
263 &mut info,
264 )
265 .unwrap();
266 assert_eq!(info.view_count, 5678);
267 assert_eq!(info.like_count, 1234567);
268 assert!(info.uploader_verified);
269 assert_eq!(info.uploader_subscriber_count, 2_500_000);
270 assert_eq!(info.uploader_url.as_deref(), Some("https://www.youtube.com/@chan"));
271 assert_eq!(info.uploader_avatars.len(), 1);
272 // already-set counts not overwritten, likes extractor returns -1 when no buttons
273 let next2 = json!({"contents":{"twoColumnWatchNextResults":{"results":{"results":{"contents":[{"videoPrimaryInfoRenderer":{"viewCount":{"videoViewCountRenderer":{"viewCount":{"simpleText":"9 views"}}}}}]}}}}}).to_string();
274 let mut info2 = StreamInfo {
275 view_count: 111,
276 like_count: 222,
277 uploader_url: Some("https://www.youtube.com/channel/UC123".into()),
278 ..Default::default()
279 };
280 stream::augment_from_next(
281 &Client { next: next2, ..Default::default() },
282 "aaaaaaaaaaa",
283 "en",
284 "US",
285 &mut info2,
286 )
287 .unwrap();
288 assert_eq!(info2.view_count, 111);
289 assert_eq!(info2.like_count, 222);
290}
291
292#[test]
293fn search_all_item_types_and_filters() {
294 let _g = lock();
295 assert_eq!(search::filter_params(Some("videos")), Some(search::FILTER_VIDEOS));
296 assert_eq!(search::filter_params(Some("channels")), Some(search::FILTER_CHANNELS));
297 assert_eq!(search::filter_params(Some("playlists")), Some(search::FILTER_PLAYLISTS));
298 assert_eq!(search::filter_params(Some("bogus")), None);
299 assert_eq!(search::filter_params(None), None);
300 let fixture = json!({"contents":{"twoColumnSearchResultsRenderer":{"primaryContents":{"sectionListRenderer":{"contents":[
301 {"itemSectionRenderer":{"contents":[
302 {"backgroundPromoRenderer":{}},
303 {"channelRenderer":{"channelId":"UC12345678901234567890","title":{"simpleText":"Chan"},"subscriberCountText":{"simpleText":"1.2M subscribers"},"videoCountText":{"simpleText":"42 videos"},"descriptionSnippet":{"simpleText":"chan desc"},"thumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/c.jpg","width":10,"height":10}]},"ownerBadges":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_VERIFIED"}}]}},
304 {"playlistRenderer":{"playlistId":"PLabc","title":{"simpleText":"My Playlist"},"videoCount":"17","longBylineText":{"simpleText":"Uploader"},"thumbnail":{"thumbnails":[{"url":"https://i.ytimg.com/p.jpg","width":10,"height":10}]}}},
305 {"lockupViewModel":{"contentType":"LOCKUP_CONTENT_TYPE_VIDEO","contentId":"aaaaaaaaaaa","metadata":{"lockupMetadataViewModel":{"title":{"content":"Lock Vid"}}}}},
306 {"lockupViewModel":{"contentType":"LOCKUP_CONTENT_TYPE_PLAYLIST","contentId":"PLxyz","metadata":{"lockupMetadataViewModel":{"title":{"content":"Lock PL"}}}}},
307 {"lockupViewModel":{"contentType":"LOCKUP_CONTENT_TYPE_PODCAST","contentId":"PLpod","metadata":{"lockupMetadataViewModel":{"title":{"content":"Pod"}}}}},
308 {"lockupViewModel":{"contentType":"LOCKUP_CONTENT_TYPE_CHANNEL","contentId":"UCx","metadata":{"lockupMetadataViewModel":{"title":{"content":"?"}}}}},
309 {"lockupViewModel":{"contentType":"LOCKUP_CONTENT_TYPE_VIDEO","metadata":{}}},
310 {"videoRenderer":{"videoId":"bbbbbbbbbbb","title":{"simpleText":"Live Vid"},"badges":[{"metadataBadgeRenderer":{"style":"BADGE_STYLE_TYPE_LIVE_NOW"}}]}},
311 {"videoRenderer":{"title":{"simpleText":"no id"}}},
312 {"channelRenderer":{"title":{"simpleText":"no id"}}},
313 {"playlistRenderer":{"title":{"simpleText":"no id"}}},
314 {"someAdRenderer":{}}
315 ]}},
316 {"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"SEARCHTOK"}}}}
317 ]}}}}}).to_string();
318 for filter in [None, Some("videos"), Some("channels"), Some("playlists"), Some("bogus")] {
319 let r = search::search(
320 &Client { search: fixture.clone(), ..Default::default() },
321 "q",
322 filter,
323 "en",
324 "US",
325 )
326 .unwrap();
327 assert_eq!(r.next_page_token.as_deref(), Some("SEARCHTOK"));
328 // 1 channel + 1 playlist + 3 lockups + 1 live video = 6 good, errors: unknown lockup, missing-id lockup, video, channel, playlist =5
329 assert_eq!(r.items.len(), 6, "filter {filter:?} items {:?}", r.items);
330 assert_eq!(r.errors.len(), 5, "{:?}", r.errors);
331 match &r.items[0] {
332 SearchItem::Channel(ch) => {
333 assert_eq!(
334 ch.subscriber_count, 1_200_000,
335 "subscriber count from subscriberCountText"
336 );
337 assert_eq!(ch.stream_count, 42);
338 assert!(ch.verified);
339 }
340 _ => panic!("channel first"),
341 }
342 match &r.items[1] {
343 SearchItem::Playlist(p) => assert_eq!(p.stream_count, 17),
344 _ => panic!("playlist"),
345 }
346 match &r.items[5] {
347 SearchItem::Stream(s) => assert!(s.is_live),
348 _ => panic!("live stream"),
349 }
350 }
351}
352
353#[test]
354fn search_suggestion_didyoumean_and_page() {
355 let _g = lock();
356 let fixture = json!({"contents":{"twoColumnSearchResultsRenderer":{"primaryContents":{"sectionListRenderer":{"contents":[
357 {"itemSectionRenderer":{"contents":[{"didYouMeanRenderer":{"correctedQuery":{"runs":[{"text":"did you mean cats"}]}}}]}}
358 ]}}}}}).to_string();
359 let r =
360 search::search(&Client { search: fixture, ..Default::default() }, "q", None, "en", "US")
361 .unwrap();
362 assert_eq!(r.search_suggestion.as_deref(), Some("did you mean cats"));
363 // search_page via continuation
364 let cont = json!({"onResponseReceivedCommands":[{"appendContinuationItemsAction":{"continuationItems":[
365 {"itemSectionRenderer":{"contents":[{"videoRenderer":{"videoId":"aaaaaaaaaaa","title":{"simpleText":"Paged"}}}]}},
366 {"continuationItemRenderer":{"continuationEndpoint":{"continuationCommand":{"token":"PAGE2"}}}}
367 ]}}]}).to_string();
368 let r2 =
369 search::search_page(&Client { search_cont: cont, ..Default::default() }, "tok", "en", "US")
370 .unwrap();
371 assert_eq!(r2.items.len(), 1);
372 assert_eq!(r2.next_page_token.as_deref(), Some("PAGE2"));
373 // empty continuation response
374 let r3 = search::search_page(
375 &Client {
376 search_cont:
377 json!({"onResponseReceivedCommands":[],"padding":"xxxxxxxxxxxxxxxxxxxxxxxx"})
378 .to_string(),
379 ..Default::default()
380 },
381 "tok",
382 "en",
383 "US",
384 )
385 .unwrap();
386 assert!(r3.items.is_empty());
387}
388
389#[test]
390fn search_response_validation() {
391 let _g = lock();
392 struct Custom(u16, String, String);
393 impl HttpClient for Custom {
394 fn execute(&self, req: Request<'_>) -> Result<Response> {
395 if req.url.contains("sw.js") {
396 return Ok(resp(
397 &req.url,
398 r#"{"INNERTUBE_CONTEXT_CLIENT_VERSION":"2.20260120.01.00"}"#.into(),
399 ));
400 }
401 Ok(Response {
402 code: self.0,
403 body: self.1.as_bytes().to_vec(),
404 latest_url: req.url.clone(),
405 headers: [("Content-Type".into(), vec![self.2.clone()])].into_iter().collect(),
406 })
407 }
408 }
409 assert!(search::search(
410 &Custom(404, "x".repeat(100), "application/json".into()),
411 "q",
412 None,
413 "en",
414 "US"
415 )
416 .is_err());
417 assert!(search::search(
418 &Custom(200, "{}".into(), "application/json".into()),
419 "q",
420 None,
421 "en",
422 "US"
423 )
424 .is_err());
425 assert!(search::search(
426 &Custom(200, "x".repeat(100), "text/html".into()),
427 "q",
428 None,
429 "en",
430 "US"
431 )
432 .is_err());
433 let bad_json = "not json at all padding padding padding padding padding padding";
434 assert!(search::search(
435 &Custom(200, bad_json.into(), "application/json".into()),
436 "q",
437 None,
438 "en",
439 "US"
440 )
441 .is_err());
442}