ytmusicapi 0.4.2

Rust client for YouTube Music 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! YouTube Music API client.

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde_json::{json, Value};

use crate::auth::BrowserAuth;
use crate::context::{create_context, default_headers, YTM_BASE_API, YTM_PARAMS, YTM_PARAMS_KEY};
use crate::error::{Error, Result};
use crate::nav::nav;
use crate::parsers::{
    get_continuation_token, parse_library_playlists, parse_playlist_response, parse_playlist_tracks,
};
use crate::path;
use crate::types::{
    CreatePlaylistResponse, LikeStatus, MovePlaylistItemsResult, Playlist, PlaylistSummary,
    PlaylistTrack, Privacy, Song,
};

fn validate_playlist_id(playlist_id: &str) -> &str {
    playlist_id.strip_prefix("VL").unwrap_or(playlist_id)
}

fn status_succeeded(response: &Value) -> bool {
    response
        .get("status")
        .and_then(|v| v.as_str())
        .map(|s| s.contains("SUCCEEDED"))
        .unwrap_or(false)
}

fn collect_movable_items(items: &[PlaylistTrack]) -> Result<(Vec<String>, Vec<PlaylistTrack>)> {
    let mut video_ids = Vec::new();
    let mut removable = Vec::new();

    for item in items {
        if let (Some(video_id), Some(_set_video_id)) = (&item.video_id, &item.set_video_id) {
            video_ids.push(video_id.clone());
            removable.push(item.clone());
        }
    }

    if video_ids.is_empty() {
        return Err(Error::InvalidInput(
            "No playlist items include both video_id and set_video_id".to_string(),
        ));
    }

    Ok((video_ids, removable))
}

/// The main YouTube Music API client.
///
/// Construct with [`YTMusicClient::builder()`]. Methods that require
/// authentication return [`Error::AuthRequired`](crate::Error::AuthRequired) if
/// no [`BrowserAuth`] is configured.
pub struct YTMusicClient {
    http: reqwest::Client,
    auth: Option<BrowserAuth>,
    language: String,
    location: Option<String>,
    user: Option<String>,
}

/// Builder for constructing a [`YTMusicClient`].
pub struct YTMusicClientBuilder {
    auth: Option<BrowserAuth>,
    language: String,
    location: Option<String>,
    user: Option<String>,
}

impl YTMusicClient {
    /// Create a new client builder.
    ///
    /// Defaults:
    /// - language: `"en"`
    /// - location: `None`
    /// - user: `None`
    pub fn builder() -> YTMusicClientBuilder {
        YTMusicClientBuilder {
            auth: None,
            language: "en".to_string(),
            location: None,
            user: None,
        }
    }

    /// Check whether browser authentication is configured.
    ///
    /// This does not validate the cookie or perform a network request.
    pub fn is_authenticated(&self) -> bool {
        self.auth.is_some()
    }

    /// Get playlists from the user's library.
    ///
    /// Requires authentication. This currently fetches only the first page of
    /// playlists returned by the web client and does not follow continuations.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of playlists to return. `None` returns the
    ///   entire first page.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ytmusicapi::YTMusicClient;
    /// # async fn example(client: &YTMusicClient) -> ytmusicapi::Result<()> {
    /// let playlists = client.get_library_playlists(Some(10)).await?;
    /// for playlist in playlists {
    ///     println!("{}", playlist.title);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_library_playlists(&self, limit: Option<u32>) -> Result<Vec<PlaylistSummary>> {
        self.check_auth()?;

        let body = json!({
            "browseId": "FEmusic_liked_playlists"
        });

        let response = self.send_request("browse", body).await?;
        let mut playlists = parse_library_playlists(&response);

        // Handle pagination if needed
        if let Some(lim) = limit {
            playlists.truncate(lim as usize);
        }

        // TODO: Handle continuations for large libraries

        Ok(playlists)
    }

    /// Get a playlist with its tracks.
    ///
    /// Fetches metadata and tracks for a given playlist ID. The client does not
    /// enforce authentication, but private playlists may be rejected by the API.
    /// If `limit` is `None`, the client follows continuations and returns up to
    /// 5,000 tracks.
    ///
    /// # Arguments
    ///
    /// * `playlist_id` - The playlist ID (can be with or without `VL` prefix).
    /// * `limit` - Maximum number of tracks to return. `None` for all (capped at 5,000).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ytmusicapi::YTMusicClient;
    /// # async fn example(client: &YTMusicClient) -> ytmusicapi::Result<()> {
    /// let playlist = client.get_playlist("PL123456789", None).await?;
    /// println!("Title: {}", playlist.title);
    /// for track in playlist.tracks {
    ///     println!(" - {} by {:?}", track.title.unwrap_or_default(), track.artists);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_playlist(&self, playlist_id: &str, limit: Option<u32>) -> Result<Playlist> {
        // Ensure playlist ID has VL prefix for browse endpoint
        let browse_id = if playlist_id.starts_with("VL") {
            playlist_id.to_string()
        } else {
            format!("VL{}", playlist_id)
        };

        let body = json!({
            "browseId": browse_id
        });

        let response = self.send_request("browse", body.clone()).await?;
        let mut playlist = parse_playlist_response(&response, playlist_id);

        // Handle pagination for tracks
        let track_limit = limit.unwrap_or(5000) as usize;

        // Get continuation token if present and we need more tracks
        let secondary_contents = nav(
            &response,
            &path![
                "contents",
                "twoColumnBrowseResultsRenderer",
                "secondaryContents",
                "sectionListRenderer",
                "contents",
                0,
                "musicPlaylistShelfRenderer"
            ],
        );

        if let Some(shelf) = secondary_contents {
            if playlist.tracks.len() < track_limit {
                if let Some(token) = get_continuation_token(shelf) {
                    let more_tracks = self
                        .fetch_playlist_continuations(&token, track_limit - playlist.tracks.len())
                        .await?;
                    playlist.tracks.extend(more_tracks);
                }
            }
        }

        // Apply limit
        if let Some(lim) = limit {
            playlist.tracks.truncate(lim as usize);
        }

        // Recalculate duration
        playlist.duration_seconds = Some(
            playlist
                .tracks
                .iter()
                .filter_map(|t| t.duration_seconds)
                .sum(),
        );

        Ok(playlist)
    }

    /// Get the "Liked Songs" playlist.
    ///
    /// Requires authentication.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum number of tracks to return. `None` for all.
    pub async fn get_liked_songs(&self, limit: Option<u32>) -> Result<Playlist> {
        self.check_auth()?;
        self.get_playlist("LM", limit).await
    }

    /// Create a new playlist.
    ///
    /// Requires authentication. An empty `description` is omitted from the request.
    pub async fn create_playlist(
        &self,
        title: &str,
        description: Option<&str>,
        privacy: Privacy,
    ) -> Result<CreatePlaylistResponse> {
        self.check_auth()?;
        if title.trim().is_empty() {
            return Err(Error::InvalidInput(
                "title must include at least one character".to_string(),
            ));
        }

        let privacy_status = match privacy {
            Privacy::Public => "PUBLIC",
            Privacy::Private => "PRIVATE",
            Privacy::Unlisted => "UNLISTED",
        };

        let mut body = json!({
            "title": title,
            "privacyStatus": privacy_status
        });

        if let Some(desc) = description {
            if !desc.trim().is_empty() {
                body["description"] = json!(desc);
            }
        }

        let response = self.send_request("playlist/create", body).await?;
        let created: CreatePlaylistResponse = serde_json::from_value(response)?;
        Ok(created)
    }

    /// Delete a playlist.
    ///
    /// Requires authentication. The ID may be provided with or without the `VL` prefix.
    pub async fn delete_playlist(&self, playlist_id: &str) -> Result<()> {
        self.check_auth()?;
        if playlist_id.trim().is_empty() {
            return Err(Error::InvalidInput(
                "playlist_id must include at least one character".to_string(),
            ));
        }

        let body = json!({
            "playlistId": validate_playlist_id(playlist_id)
        });

        self.send_request("playlist/delete", body).await?;
        Ok(())
    }

    /// Get song metadata from the `player` endpoint.
    ///
    /// This does not require authentication and does not return stream URLs.
    pub async fn get_song(&self, video_id: &str) -> Result<Song> {
        let body = json!({
            "video_id": video_id,
            "playbackContext": {
                "contentPlaybackContext": {
                    "signatureTimestamp": 0 // We might need a real timestamp for streaming, but 0 often works for metadata
                }
            }
        });

        let response = self.send_request("player", body).await?;
        let song: Song = serde_json::from_value(response)?;
        Ok(song)
    }

    /// Rate a song (like/dislike/indifferent).
    ///
    /// Requires authentication. Returns the raw API response.
    pub async fn rate_song(&self, video_id: &str, rating: LikeStatus) -> Result<Value> {
        self.check_auth()?;

        let body = json!({
            "target": {
                "videoId": video_id
            }
        });

        self.send_request(rating.endpoint(), body).await
    }

    /// Like a song.
    pub async fn like_song(&self, video_id: &str) -> Result<Value> {
        self.rate_song(video_id, LikeStatus::Like).await
    }

    /// Remove like/dislike from a song.
    pub async fn unlike_song(&self, video_id: &str) -> Result<Value> {
        self.rate_song(video_id, LikeStatus::Indifferent).await
    }

    /// Add items to a playlist by video ID.
    ///
    /// Requires authentication. When `allow_duplicates` is `true`, the request
    /// includes `DEDUPE_OPTION_SKIP`, which instructs the API to skip videos that
    /// are already present in the playlist.
    pub async fn add_playlist_items(
        &self,
        playlist_id: &str,
        video_ids: &[String],
        allow_duplicates: bool,
    ) -> Result<Value> {
        self.check_auth()?;
        if video_ids.is_empty() {
            return Err(Error::InvalidInput(
                "video_ids must include at least one item".to_string(),
            ));
        }

        let mut actions = Vec::new();
        for video_id in video_ids {
            let mut action = json!({
                "action": "ACTION_ADD_VIDEO",
                "addedVideoId": video_id
            });
            if allow_duplicates {
                action["dedupeOption"] = json!("DEDUPE_OPTION_SKIP");
            }
            actions.push(action);
        }

        let body = json!({
            "playlistId": validate_playlist_id(playlist_id),
            "actions": actions
        });

        self.send_request("browse/edit_playlist", body).await
    }

    /// Remove items from a playlist using playlist track metadata.
    ///
    /// Requires authentication. Only items with both `video_id` and `set_video_id`
    /// are removed; if none qualify, this returns [`Error::InvalidInput`].
    pub async fn remove_playlist_items(
        &self,
        playlist_id: &str,
        items: &[PlaylistTrack],
    ) -> Result<Value> {
        self.check_auth()?;

        let mut actions = Vec::new();
        for item in items {
            if let (Some(set_video_id), Some(video_id)) = (&item.set_video_id, &item.video_id) {
                actions.push(json!({
                    "action": "ACTION_REMOVE_VIDEO",
                    "setVideoId": set_video_id,
                    "removedVideoId": video_id
                }));
            }
        }

        if actions.is_empty() {
            return Err(Error::InvalidInput(
                "No playlist items include both video_id and set_video_id".to_string(),
            ));
        }

        let body = json!({
            "playlistId": validate_playlist_id(playlist_id),
            "actions": actions
        });

        self.send_request("browse/edit_playlist", body).await
    }

    /// Move items from one playlist to another (add to destination, then remove from source).
    ///
    /// Requires authentication. If the add succeeds but the remove fails, the
    /// destination playlist is not rolled back.
    pub async fn move_playlist_items(
        &self,
        from_playlist_id: &str,
        to_playlist_id: &str,
        items: &[PlaylistTrack],
        allow_duplicates: bool,
    ) -> Result<MovePlaylistItemsResult> {
        self.check_auth()?;
        let (video_ids, removable_items) = collect_movable_items(items)?;

        let add_response = self
            .add_playlist_items(to_playlist_id, &video_ids, allow_duplicates)
            .await?;
        if !status_succeeded(&add_response) {
            let status = add_response
                .get("status")
                .and_then(|v| v.as_str())
                .unwrap_or("Unknown status");
            return Err(Error::Server {
                status: 500,
                message: format!(
                    "Failed to add items to destination playlist: {}",
                    status
                ),
            });
        }

        let remove_response = self
            .remove_playlist_items(from_playlist_id, &removable_items)
            .await?;

        Ok(MovePlaylistItemsResult {
            add_response,
            remove_response,
        })
    }

    /// Fetch additional tracks via continuation token.
    async fn fetch_playlist_continuations(
        &self,
        initial_token: &str,
        max_items: usize,
    ) -> Result<Vec<PlaylistTrack>> {
        let mut all_tracks = Vec::new();
        let mut token = Some(initial_token.to_string());

        while let Some(current_token) = token {
            if all_tracks.len() >= max_items {
                break;
            }

            let body = json!({
                "continuation": current_token
            });

            let response = self.send_request("browse", body).await?;

            // Parse continuation response
            let continuation_items = nav(
                &response,
                &path![
                    "continuationContents",
                    "musicPlaylistShelfContinuation",
                    "contents"
                ],
            )
            .or_else(|| {
                nav(
                    &response,
                    &path![
                        "onResponseReceivedActions",
                        0,
                        "appendContinuationItemsAction",
                        "continuationItems"
                    ],
                )
            });

            if let Some(Value::Array(items)) = continuation_items {
                let tracks = parse_playlist_tracks(items);
                if tracks.is_empty() {
                    break;
                }
                all_tracks.extend(tracks);

                // Check for next continuation
                let next_token = items.last().and_then(|last| {
                    nav(
                        last,
                        &path![
                            "continuationItemRenderer",
                            "continuationEndpoint",
                            "continuationCommand",
                            "token"
                        ],
                    )
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                });

                token = next_token;
            } else {
                break;
            }
        }

        all_tracks.truncate(max_items);
        Ok(all_tracks)
    }

    /// Send a request to the YouTube Music API.
    ///
    /// This is a low-level helper that merges a client context into `body`,
    /// performs a `POST`, and returns the raw JSON response.
    ///
    /// Error behavior:
    /// - Surfaces network failures as [`Error::Http`](crate::Error::Http).
    /// - Surfaces non-2xx responses or error payloads as [`Error::Server`](crate::Error::Server).
    /// - Surfaces JSON decode failures as [`Error::Json`](crate::Error::Json).
    ///
    /// This crate does not configure timeouts, retries, or polling; any timeout
    /// behavior comes from the underlying HTTP client defaults.
    pub async fn send_request(&self, endpoint: &str, mut body: Value) -> Result<Value> {
        // Merge context into body
        let context = create_context(
            &self.language,
            self.location.as_deref(),
            self.user.as_deref(),
        );
        if let Value::Object(ref mut map) = body {
            if let Value::Object(ctx) = context {
                for (k, v) in ctx {
                    map.insert(k, v);
                }
            }
        }

        // Build URL
        let params = if self.auth.is_some() {
            format!("{}{}", YTM_PARAMS, YTM_PARAMS_KEY)
        } else {
            YTM_PARAMS.to_string()
        };
        let url = format!("{}{}{}", YTM_BASE_API, endpoint, params);

        // Build request
        let mut request = self.http.post(&url).json(&body);

        // Add auth headers if authenticated
        if let Some(ref auth) = self.auth {
            // Combine user cookies with required SOCS cookie
            let combined_cookie = format!("{}; SOCS=CAI", auth.cookie);
            request = request
                .header("authorization", auth.get_authorization()?)
                .header("cookie", combined_cookie)
                .header("x-goog-authuser", &auth.x_goog_authuser);
        } else {
            // Add only SOCS cookie for unauthenticated requests
            request = request.header("cookie", "SOCS=CAI");
        }

        let response = request.send().await?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text().await.unwrap_or_default();
            return Err(Error::Server {
                status,
                message: text,
            });
        }

        let json: Value = response.json().await?;

        // Check for API error in response
        if let Some(error) = json.get("error") {
            let message = error
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or("Unknown error")
                .to_string();
            let code = error.get("code").and_then(|c| c.as_u64()).unwrap_or(500) as u16;
            return Err(Error::Server {
                status: code,
                message,
            });
        }

        Ok(json)
    }

    /// Check that the client is authenticated, returning an error if not.
    fn check_auth(&self) -> Result<()> {
        if self.auth.is_none() {
            Err(Error::AuthRequired)
        } else {
            Ok(())
        }
    }
}

impl YTMusicClientBuilder {
    /// Set browser authentication.
    pub fn with_browser_auth(mut self, auth: BrowserAuth) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Set the language for responses.
    ///
    /// This maps to the `hl` client parameter (default: `"en"`).
    pub fn with_language(mut self, language: impl Into<String>) -> Self {
        self.language = language.into();
        self
    }

    /// Set the location for results.
    ///
    /// This maps to the `gl` client parameter and expects ISO 3166-1 alpha-2
    /// country codes (e.g., `"US"`, `"GB"`, `"DE"`).
    pub fn with_location(mut self, location: impl Into<String>) -> Self {
        self.location = Some(location.into());
        self
    }

    /// Set a user ID for brand account requests.
    ///
    /// This maps to `onBehalfOfUser` in the request context.
    pub fn with_user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Build the client.
    ///
    /// This does not validate authentication credentials.
    pub fn build(self) -> Result<YTMusicClient> {
        let mut headers = HeaderMap::new();

        for (key, value) in default_headers() {
            if let Ok(header_value) = HeaderValue::from_str(&value) {
                if let Ok(header_name) = key.parse::<HeaderName>() {
                    headers.insert(header_name, header_value);
                }
            }
        }

        let http = reqwest::Client::builder()
            .default_headers(headers)
            .gzip(true)
            .build()?;

        Ok(YTMusicClient {
            http,
            auth: self.auth,
            language: self.language,
            location: self.location,
            user: self.user,
        })
    }
}