ytmapi-rs 0.0.2

An asynchronous (tokio) pure Rust API for Youtube Music using Google's internal API
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use super::common::{ChannelID};
use super::query::*;
use super::*;
use crate::common::{LyricsID, PlaylistID, TextRun, YoutubeID};
use crate::Error;

use std::env;


const COOKIE_PATH: &str = "cookie.txt";
const EXPIRED_OAUTH_PATH: &str = "oauth.json";
// Cookie filled with nonsense values to test this case.
const INVALID_COOKIE: &str = "HSID=abc; SSID=abc; APISID=abc; SAPISID=abc; __Secure-1PAPISID=abc; __Secure-3PAPISID=abc; YSC=abc; LOGIN_INFO=abc; VISITOR_INFO1_LIVE=abc; _gcl_au=abc; PREF=tz=Australia.Perth&f6=40000000&f7=abc; VISITOR_PRIVACY_METADATA=abc; __Secure-1PSIDTS=abc; __Secure-3PSIDTS=abc; SID=abc; __Secure-1PSID=abc; __Secure-3PSID=abc; SIDCC=abc; __Secure-1PSIDCC=abc; __Secure-3PSIDCC=abc";
// Placeholder for future implementation.
// const INVALID_EXPIRED_OAUTH: &str = "
// {
//   \"token_type\": \"Bearer\",
//   \"access_token\": \"abc\",
//   \"refresh_token\": \"abc\",
//   \"expires_in\": 62609,
//   \"request_time\": {
//     \"secs_since_epoch\": 1702907669,
//     \"nanos_since_epoch\": 594642820
//   }
// }";

async fn new_standard_oauth_api() -> Result<YtMusic<OAuthToken>> {
    let oauth_token = if let Ok(tok) = env::var("youtui_test_oauth") {
        tok
    } else {
        tokio::fs::read_to_string(EXPIRED_OAUTH_PATH).await.unwrap()
    };
    Ok(YtMusic::from_oauth_token(
        serde_json::from_slice(oauth_token.as_bytes()).unwrap(),
    ))
}
async fn new_standard_api() -> Result<YtMusic<BrowserToken>> {
    if let Ok(cookie) = env::var("youtui_test_cookie") {
        YtMusic::from_cookie(cookie).await
    } else {
        YtMusic::from_cookie_file(Path::new(COOKIE_PATH)).await
    }
}
pub fn write_json(e: &Error) {
    if let Some((json, key)) = e.get_json_and_key() {
        std::fs::write("err.json", json)
            .unwrap_or_else(|_| eprintln!("Error writing json to err.json"));
        panic!("{key} not found, wrote to err.json");
    }
}

#[tokio::test]
async fn test_refresh_expired_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    api.refresh_token().await.unwrap();
}
#[tokio::test]
async fn test_expired_oauth() {
    // XXX: Assuming this error only occurs for expired headers.
    // This assumption may be incorrect.
    let api = new_standard_oauth_api().await.unwrap();
    // Library query needs authentication.
    let res = api.json_query(GetLibraryPlaylistsQuery).await;
    // TODO: Add matching functions to error type. Current method not very ergonomic.
    let Err(error) = res else {
        panic!("Expected an error")
    };
    assert!(error.is_oauth_expired());
}
// Placeholder for future implementation.
// #[tokio::test]
// async fn test_expired_header() {
// }
#[tokio::test]
async fn test_invalid_header() {
    let api = YtMusic::from_cookie(INVALID_COOKIE).await;
    // Library query needs authentication.
    let res = api.unwrap().json_query(GetLibraryPlaylistsQuery).await;
    // TODO: Add matching functions to error type. Current method not very ergonomic.
    let Err(error) = res else {
        eprintln!("{:#?}", res);
        panic!("Expected an error")
    };
    assert!(error.is_browser_authentication_failed());
}
// Placeholder for future implementation
// #[tokio::test]
// async fn test_invalid_expired_oauth() {
//     let oauth_token: OAuthToken = serde_json::from_str(INVALID_EXPIRED_OAUTH).unwrap();
//     let api = YtMusic::from_oauth_token(oauth_token);
//     // Library query needs authentication.
//     let res = api.json_query(GetLibraryPlaylistsQuery).await;
//     // TODO: Add matching functions to error type. Current method not very ergonomic.
//     let Err(error) = res else {
//         eprintln!("{:#?}", res);
//         panic!("Expected an error")
//     };
//     eprintln!("{:#?}", error);
//     assert!(error.is_browser_authentication_failed());
// }

#[tokio::test]
async fn test_new() {
    new_standard_api().await.unwrap();
    new_standard_oauth_api().await.unwrap();
}
#[tokio::test]
async fn test_basic_search() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_basic_search_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_artists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_artists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_artists() {
    // TODO: Add siginficantly more queries.
    let api = new_standard_api().await.unwrap();
    let _res = api.search_artists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_songs_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_songs("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_songs() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_songs("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_albums_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_albums("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_albums() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_albums("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_videos_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_videos("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_videos() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_videos("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_episodes_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_episodes("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_episodes() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_episodes("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_podcasts_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_podcasts("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_podcasts() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_podcasts("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_profiles_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_profiles("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_profiles() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_profiles("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_featured_playlists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_featured_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_featured_playlists() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_featured_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_community_playlists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_community_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_community_playlists() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_community_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_playlists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let _res = api.search_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_search_playlists() {
    let api = new_standard_api().await.unwrap();
    let _res = api.search_playlists("Beatles").await.unwrap();
}
#[tokio::test]
async fn test_get_library_playlists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let res = api.get_library_playlists().await.unwrap();
    assert!(res.len() > 0);
}
#[tokio::test]
async fn test_get_library_playlists() {
    let api = new_standard_api().await.unwrap();
    let res = api.get_library_playlists().await.unwrap();
    assert!(res.len() > 0);
}
#[tokio::test]
async fn test_get_library_artists_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let query = GetLibraryArtistsQuery::default();
    let res = api.get_library_artists(query).await.unwrap();
    assert!(res.len() > 0);
}
#[tokio::test]
async fn test_get_library_artists() {
    let api = new_standard_api().await.unwrap();
    let query = GetLibraryArtistsQuery::default();
    let res = api.get_library_artists(query).await.unwrap();
    assert!(res.len() > 0);
}
#[tokio::test]
async fn test_watch_playlist() {
    // TODO: Make more generic
    let api = new_standard_api().await.unwrap();
    let res = api
        .get_watch_playlist(GetWatchPlaylistQuery::new_from_video_id(VideoID::from_raw(
            "9mWr4c_ig54",
        )))
        .await
        .unwrap();
    let example = WatchPlaylist {
        _tracks: Vec::new(),
        playlist_id: Some(PlaylistID::from_raw("RDAMVM9mWr4c_ig54")),
        lyrics_id: LyricsID("MPLYt_C8aRK1qmsDJ-1".into()),
    };
    assert_eq!(res, example)
}
#[tokio::test]
async fn test_get_lyrics() {
    // TODO: Make more generic
    let api = new_standard_api().await.unwrap();
    let res = api
        .get_watch_playlist(GetWatchPlaylistQuery::new_from_video_id(VideoID::from_raw(
            "9mWr4c_ig54",
        )))
        .await
        .unwrap();
    let res = api
        .get_lyrics(GetLyricsQuery::new(res.lyrics_id))
        .await
        .unwrap();
    let example = Lyrics {
            lyrics: "You're my lesson I had to learn\nAnother page I'll have to turn\nI got one more message, always tryna be heard\nBut you never listen to a word\n\nHeaven knows we came so close\nBut this ain't real, it's just a dream\nWake me up, I've been fast asleep\nLetting go of fantasies\nBeen caught up in who I needed you to be\nHow foolish of me\n\nFoolish of me\nFoolish of me\nFoolish of me\nFoolish of me\n\nJust give me one second and I'll be fine\nJust let me catch my breath and come back to life\nI finally get the message, you were never meant to be mine\nCouldn't see the truth, I was blind (meant to be mine)\n\nWhoa, heaven knows we came so close\nBut this ain't real, it's just a dream\nWake me up, I've been fast asleep\nLetting go of fantasies\nBeen caught up in who I needed you to be\nHow foolish of me\n\nFoolish of me\nFoolish of me\nFoolish of me\nFoolish of me\n\nLetting go, we came so close (how foolish of me)\nOh, I'm letting go of fantasies\nBeen caught up in who I needed you to be\nHow foolish of me".into(),
            source: "Source: Musixmatch".into(),
        };
    assert_eq!(res, example)
}
#[tokio::test]
async fn test_search_suggestions_oauth() {
    let mut api = new_standard_oauth_api().await.unwrap();
    // Don't stuff around trying the keep the local OAuth secret up to date, just refresh it each time.
    api.refresh_token().await;
    let res = api.get_search_suggestions("faded").await.unwrap();
    let example = SearchSuggestion::new(
        common::SuggestionType::Prediction,
        vec![
            TextRun::Bold("faded".into()),
            TextRun::Normal(" alan walker".into()),
        ],
    );
    assert!(res.contains(&example));
}
#[tokio::test]
async fn test_search_suggestions() {
    let api = new_standard_api().await.unwrap();
    let res = api.get_search_suggestions("faded").await.unwrap();
    let example = SearchSuggestion::new(
        common::SuggestionType::Prediction,
        vec![
            TextRun::Bold("faded".into()),
            TextRun::Normal(" alan walker".into()),
        ],
    );
    assert!(res.contains(&example));
}
#[tokio::test]
async fn test_get_artist() {
    let now = std::time::Instant::now();
    let api = new_standard_api().await.unwrap();
    println!("API took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = api
        .raw_query(GetArtistQuery::new(ChannelID::from_raw(
            "UC2XdaAVUannpujzv32jcouQ",
        )))
        .await
        .unwrap();
    println!("Get artist took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = res.process().unwrap();
    let _res = res.parse().unwrap();
    println!("Parse artist took {} ms", now.elapsed().as_millis());
}
#[tokio::test]
async fn test_get_artist_albums() {
    let now = std::time::Instant::now();
    let api = new_standard_api().await.unwrap();
    println!("API took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = api
        .raw_query(GetArtistQuery::new(ChannelID::from_raw(
            // Metallica
            "UCGexNm_Kw4rdQjLxmpb2EKw",
        )))
        .await
        .unwrap();
    println!("Get artist took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    // TODO: fix temporary value dropped while borrowed error.
    // This won't compile:
    // let res = res.process().unwrap().parse().unwrap();
    let res = res.process().unwrap();
    let res = res.parse().unwrap();
    println!("Parse artist took {} ms", now.elapsed().as_millis());
    let _now = std::time::Instant::now();
    let albums = res.top_releases.albums.unwrap();
    let params = albums.params.unwrap();
    // For some reason the params is wrong. needs investigation.
    let channel_id = &albums.browse_id.unwrap();
    let q = GetArtistAlbumsQuery::new(ChannelID::from_raw(channel_id.get_raw()), params);
    api.get_artist_albums(q).await.unwrap();
    let now = std::time::Instant::now();
    println!("Get albums took {} ms", now.elapsed().as_millis());
}

#[tokio::test]
async fn test_get_oauth_code() {
    let client = Client::new();
    let _code = OAuthTokenGenerator::new(&client).await.unwrap();
}

#[tokio::test]
async fn test_get_artist_album_songs() {
    let now = std::time::Instant::now();
    let api = new_standard_api().await.unwrap();
    println!("API took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = api
        .raw_query(GetArtistQuery::new(ChannelID::from_raw(
            "UCGexNm_Kw4rdQjLxmpb2EKw",
        )))
        .await
        .unwrap();
    println!("Get artist took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    // TODO: fix temporary value dropped while borrowed error.
    // This won't compile:
    // let res = res.process().unwrap().parse().unwrap();
    let res = res.process().unwrap();
    let res = res.parse().unwrap();
    println!("Parse artist took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let albums = res.top_releases.albums.unwrap();
    let params = albums.params.unwrap();
    let channel_id = &albums.browse_id.unwrap();
    let res = api
        .raw_query(GetArtistAlbumsQuery::new(
            ChannelID::from_raw(channel_id.get_raw()),
            params,
        ))
        .await
        .unwrap();
    println!("Get albums took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = res.process().unwrap();
    let res = res.parse().unwrap();
    println!("Process albums took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let browse_id = &res[0].browse_id;
    let res = api.raw_query(GetAlbumQuery::new(browse_id)).await.unwrap();
    println!("Get album took {} ms", now.elapsed().as_millis());
    let now = std::time::Instant::now();
    let res = res.process().map_err(|e| write_json(&e)).unwrap();
    let _res = res.parse().unwrap();
    println!("Process album took {} ms", now.elapsed().as_millis());
}