ytmapi-rs 0.0.16

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
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
//! Type safe queries to pass to the API, and the traits to allow you to
//! implement new ones.
//! # Implementation example
//! Note, to implement Query, you must also meet the trait bounds for
//! QueryMethod. In practice, this means you must implement both Query and
//! PostQuery when using PostMethod, and Query and GetQuery when using
//! GetMethod.
//! In addition, note that your output type will need to implement ParseFrom -
//! see [`crate::parse`] for implementation notes.
//! ```no_run
//! # #[derive(Debug)]
//! # struct Date;
//! # impl ytmapi_rs::parse::ParseFrom<GetDateQuery> for Date {
//! #     fn parse_from(_: ytmapi_rs::parse::ProcessedResult<GetDateQuery>) -> ytmapi_rs::Result<Self> {todo!()}
//! # }
//! struct GetDateQuery;
//! impl ytmapi_rs::query::Query<ytmapi_rs::auth::BrowserToken> for GetDateQuery {
//!     type Output = Date;
//!     type Method = ytmapi_rs::query::PostMethod;
//! }
//! // Note that this is not a real Innertube endpoint - example for reference only!
//! impl ytmapi_rs::query::PostQuery for GetDateQuery {
//!     fn header(&self) -> serde_json::Map<String, serde_json::Value> {
//!         serde_json::Map::from_iter([("get_date".to_string(), serde_json::json!("YYYYMMDD"))])
//!     }
//!     fn params(&self) -> Vec<(&str, std::borrow::Cow<str>)> {
//!         vec![]
//!     }
//!     fn path(&self) -> &str {
//!         "date"
//!     }
//! }
//! ```
use crate::auth::AuthToken;
use crate::parse::ParseFrom;
use crate::{RawResult, Result};
use std::borrow::Cow;
use std::future::Future;

use private::Sealed;

pub use album::*;
pub use artist::*;
pub use continuations::*;
pub use history::*;
pub use library::*;
pub use playlist::*;
pub use podcasts::*;
pub use recommendations::*;
pub use search::*;
pub use upload::*;

mod artist;
mod continuations;
mod history;
mod library;
mod playlist;
mod podcasts;
mod recommendations;
mod search;
mod upload;

mod private {
    pub trait Sealed {}
}

/// Represents a query that can be passed to Innertube.
/// The Output associated type describes how to parse a result from the query,
/// and the Method associated type describes how to call the query.
pub trait Query<A: AuthToken>: Sized {
    type Output: ParseFrom<Self>;
    type Method: QueryMethod<Self, A, Self::Output>;
}

/// Represents a plain POST query that can be sent to Innertube.
pub trait PostQuery {
    fn header(&self) -> serde_json::Map<String, serde_json::Value>;
    fn params(&self) -> Vec<(&str, Cow<str>)>;
    fn path(&self) -> &str;
}
/// Represents a plain GET query that can be sent to Innertube.
pub trait GetQuery {
    fn url(&self) -> &str;
    fn params(&self) -> Vec<(&str, Cow<str>)>;
}

/// The GET query method
pub struct GetMethod;
/// The POST query method
pub struct PostMethod;

/// Represents a method of calling an query, using a query, client and auth
/// token. Not intended to be implemented by api users, the pre-implemented
/// GetMethod and PostMethod structs should be sufficient, and in addition,
/// async methods are required currently.
// Allow async_fn_in_trait required, as trait currently sealed.
#[allow(async_fn_in_trait)]
pub trait QueryMethod<Q, A, O>: Sealed
where
    Q: Query<A>,
    A: AuthToken,
{
    async fn call<'a>(
        query: &'a Q,
        client: &crate::client::Client,
        tok: &A,
    ) -> Result<RawResult<'a, Q, A>>;
}

impl Sealed for GetMethod {}
impl<Q, A, O> QueryMethod<Q, A, O> for GetMethod
where
    Q: GetQuery + Query<A, Output = O>,
    A: AuthToken,
{
    fn call<'a>(
        query: &'a Q,
        client: &crate::client::Client,
        tok: &A,
    ) -> impl Future<Output = Result<RawResult<'a, Q, A>>>
    where
        Self: Sized,
    {
        tok.raw_query_get(client, query)
    }
}

impl Sealed for PostMethod {}
impl<Q, A, O> QueryMethod<Q, A, O> for PostMethod
where
    Q: PostQuery + Query<A, Output = O>,
    A: AuthToken,
{
    fn call<'a>(
        query: &'a Q,
        client: &crate::client::Client,
        tok: &A,
    ) -> impl Future<Output = Result<RawResult<'a, Q, A>>>
    where
        Self: Sized,
    {
        tok.raw_query_post(client, query)
    }
}

pub mod album {
    use super::{PostMethod, PostQuery, Query};
    use crate::{
        auth::AuthToken,
        common::{AlbumID, YoutubeID},
        parse::GetAlbum,
    };
    use serde_json::json;

    #[derive(Clone)]
    pub struct GetAlbumQuery<'a> {
        browse_id: AlbumID<'a>,
    }
    impl<'a, A: AuthToken> Query<A> for GetAlbumQuery<'a> {
        type Output = GetAlbum;
        type Method = PostMethod;
    }
    impl<'a> PostQuery for GetAlbumQuery<'a> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            let serde_json::Value::Object(map) = json!({
                 "browseId" : self.browse_id.get_raw(),
            }) else {
                unreachable!("Created a map");
            };
            map
        }
        fn path(&self) -> &str {
            "browse"
        }
        fn params(&self) -> std::vec::Vec<(&str, std::borrow::Cow<'_, str>)> {
            vec![]
        }
    }
    impl<'a> GetAlbumQuery<'_> {
        pub fn new<T: Into<AlbumID<'a>>>(browse_id: T) -> GetAlbumQuery<'a> {
            GetAlbumQuery {
                browse_id: browse_id.into(),
            }
        }
    }
}

pub mod lyrics {
    use super::{PostMethod, PostQuery, Query};
    use crate::{
        auth::AuthToken,
        common::{LyricsID, YoutubeID},
        parse::Lyrics,
    };
    use serde_json::json;

    pub struct GetLyricsQuery<'a> {
        id: LyricsID<'a>,
    }
    impl<'a, A: AuthToken> Query<A> for GetLyricsQuery<'a> {
        type Output = Lyrics;
        type Method = PostMethod;
    }
    impl<'a> PostQuery for GetLyricsQuery<'a> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            let serde_json::Value::Object(map) = json!({
                "browseId": self.id.get_raw(),
            }) else {
                unreachable!()
            };
            map
        }
        fn path(&self) -> &str {
            "browse"
        }
        fn params(&self) -> std::vec::Vec<(&str, std::borrow::Cow<'_, str>)> {
            vec![]
        }
    }
    impl<'a> GetLyricsQuery<'a> {
        pub fn new(id: LyricsID<'a>) -> GetLyricsQuery<'a> {
            GetLyricsQuery { id }
        }
    }
}

pub mod watch {
    use super::{PostMethod, PostQuery, Query};
    use crate::{
        auth::AuthToken,
        common::{PlaylistID, VideoID, YoutubeID},
    };
    use serde_json::json;
    use std::borrow::Cow;

    pub trait GetWatchPlaylistQueryID {
        fn get_video_id(&self) -> Option<Cow<str>>;
        fn get_playlist_id(&self) -> Cow<str>;
    }

    pub struct GetWatchPlaylistQuery<T: GetWatchPlaylistQueryID> {
        id: T,
    }
    pub struct VideoAndPlaylistID<'a> {
        video_id: VideoID<'a>,
        playlist_id: PlaylistID<'a>,
    }

    impl<'a> GetWatchPlaylistQueryID for VideoAndPlaylistID<'a> {
        fn get_video_id(&self) -> Option<Cow<str>> {
            Some(self.video_id.get_raw().into())
        }

        fn get_playlist_id(&self) -> Cow<str> {
            self.playlist_id.get_raw().into()
        }
    }
    impl<'a> GetWatchPlaylistQueryID for VideoID<'a> {
        fn get_video_id(&self) -> Option<Cow<str>> {
            Some(self.get_raw().into())
        }

        fn get_playlist_id(&self) -> Cow<str> {
            format!("RDAMVM{}", self.get_raw()).into()
        }
    }
    impl<'a> GetWatchPlaylistQueryID for PlaylistID<'a> {
        fn get_video_id(&self) -> Option<Cow<str>> {
            None
        }
        fn get_playlist_id(&self) -> Cow<str> {
            self.get_raw().into()
        }
    }

    impl<T: GetWatchPlaylistQueryID, A: AuthToken> Query<A> for GetWatchPlaylistQuery<T> {
        type Output = crate::parse::WatchPlaylist;
        type Method = PostMethod;
    }
    impl<T: GetWatchPlaylistQueryID> PostQuery for GetWatchPlaylistQuery<T> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            let serde_json::Value::Object(mut map) = json!({
                "enablePersistentPlaylistPanel": true,
                "isAudioOnly": true,
                "tunerSettingValue": "AUTOMIX_SETTING_NORMAL",
                "playlistId" : self.id.get_playlist_id(),
            }) else {
                unreachable!()
            };
            if let Some(video_id) = self.id.get_video_id() {
                map.insert("videoId".to_string(), json!(video_id));
            };
            map
        }
        fn path(&self) -> &str {
            "next"
        }
        fn params(&self) -> Vec<(&str, Cow<str>)> {
            vec![]
        }
    }
    impl<'a> GetWatchPlaylistQuery<VideoID<'a>> {
        pub fn new_from_video_id<T: Into<VideoID<'a>>>(
            id: T,
        ) -> GetWatchPlaylistQuery<VideoID<'a>> {
            GetWatchPlaylistQuery { id: id.into() }
        }
        pub fn with_playlist_id(
            self,
            playlist_id: PlaylistID<'a>,
        ) -> GetWatchPlaylistQuery<VideoAndPlaylistID> {
            GetWatchPlaylistQuery {
                id: VideoAndPlaylistID {
                    video_id: self.id,
                    playlist_id,
                },
            }
        }
    }
    impl<'a> GetWatchPlaylistQuery<PlaylistID<'a>> {
        pub fn new_from_playlist_id(id: PlaylistID<'a>) -> GetWatchPlaylistQuery<PlaylistID<'a>> {
            GetWatchPlaylistQuery { id }
        }
        pub fn with_video_id(
            self,
            video_id: VideoID<'a>,
        ) -> GetWatchPlaylistQuery<VideoAndPlaylistID> {
            GetWatchPlaylistQuery {
                id: VideoAndPlaylistID {
                    video_id,
                    playlist_id: self.id,
                },
            }
        }
    }
}

pub mod rate {
    use std::borrow::Cow;

    use super::{PostMethod, PostQuery, Query};
    use crate::{
        auth::AuthToken,
        common::{LikeStatus, PlaylistID, VideoID, YoutubeID},
    };
    use serde_json::json;

    pub struct RateSongQuery<'a> {
        video_id: VideoID<'a>,
        rating: LikeStatus,
    }
    impl<'a> RateSongQuery<'a> {
        pub fn new(video_id: VideoID<'a>, rating: LikeStatus) -> Self {
            Self { video_id, rating }
        }
    }
    pub struct RatePlaylistQuery<'a> {
        playlist_id: PlaylistID<'a>,
        rating: LikeStatus,
    }
    impl<'a> RatePlaylistQuery<'a> {
        pub fn new(playlist_id: PlaylistID<'a>, rating: LikeStatus) -> Self {
            Self {
                playlist_id,
                rating,
            }
        }
    }

    // AUTH REQUIRED
    impl<'a, A: AuthToken> Query<A> for RateSongQuery<'a> {
        type Output = ();
        type Method = PostMethod;
    }
    impl<'a> PostQuery for RateSongQuery<'a> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            serde_json::Map::from_iter([(
                "target".to_string(),
                json!({"videoId" : self.video_id.get_raw()} ),
            )])
        }
        fn params(&self) -> Vec<(&str, Cow<str>)> {
            vec![]
        }
        fn path(&self) -> &str {
            like_endpoint(&self.rating)
        }
    }

    // AUTH REQUIRED
    impl<'a, A: AuthToken> Query<A> for RatePlaylistQuery<'a> {
        type Output = ();
        type Method = PostMethod;
    }

    impl<'a> PostQuery for RatePlaylistQuery<'a> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            serde_json::Map::from_iter([(
                "target".to_string(),
                json!({"playlistId" : self.playlist_id.get_raw()} ),
            )])
        }
        fn params(&self) -> Vec<(&str, Cow<str>)> {
            vec![]
        }
        fn path(&self) -> &str {
            like_endpoint(&self.rating)
        }
    }

    fn like_endpoint(rating: &LikeStatus) -> &'static str {
        match *rating {
            LikeStatus::Liked => "like/like",
            LikeStatus::Disliked => "like/dislike",
            LikeStatus::Indifferent => "like/removelike",
        }
    }
}

// Potentially better belongs within another module.
pub mod song {
    use super::{PostMethod, PostQuery, Query};
    use crate::common::VideoID;
    use crate::{auth::AuthToken, common::SongTrackingUrl, Result};
    use serde_json::json;
    use std::borrow::Cow;
    use std::time::SystemTime;

    pub struct GetSongTrackingUrlQuery<'a> {
        video_id: VideoID<'a>,
        signature_timestamp: u64,
    }

    impl<'a> GetSongTrackingUrlQuery<'a> {
        /// # NOTE
        /// A GetSongTrackingUrlQuery stores a timestamp, it's not recommended
        /// to store these for a long period of time. The constructor can fail
        /// due to a System Time error.
        pub fn new(video_id: VideoID) -> Result<GetSongTrackingUrlQuery<'_>> {
            let signature_timestamp = get_signature_timestamp()?;
            Ok(GetSongTrackingUrlQuery {
                video_id,
                signature_timestamp,
            })
        }
    }

    impl<'a, A: AuthToken> Query<A> for GetSongTrackingUrlQuery<'a> {
        type Output = SongTrackingUrl<'static>;
        type Method = PostMethod;
    }
    impl<'a> PostQuery for GetSongTrackingUrlQuery<'a> {
        fn header(&self) -> serde_json::Map<String, serde_json::Value> {
            serde_json::Map::from_iter([
                (
                    "playbackContext".to_string(),
                    json!(
                        {
                            "contentPlaybackContext": {
                                "signatureTimestamp": self.signature_timestamp
                            }
                        }
                    ),
                ),
                ("video_id".to_string(), json!(self.video_id)),
            ])
        }
        fn params(&self) -> Vec<(&str, Cow<str>)> {
            vec![]
        }
        fn path(&self) -> &str {
            "player"
        }
    }

    // Original: https://github.com/sigma67/ytmusicapi/blob/a15d90c4f356a530c6b2596277a9d70c0b117a0c/ytmusicapi/mixins/_utils.py#L42
    /// Approximation for google's signatureTimestamp which would normally be
    /// extracted from base.js.
    fn get_signature_timestamp() -> Result<u64> {
        const SECONDS_IN_DAY: u64 = 60 * 60 * 24;
        Ok(SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_secs()
            // SAFETY: SECONDS_IN_DAY is nonzero.
            .saturating_div(SECONDS_IN_DAY))
    }
}