Skip to main content

innertube_rs/
lib.rs

1//! # innertube-rs
2//!
3//! A fast, lightweight, and asynchronous pure Rust client for YouTube's internal API (InnerTube).
4//!
5//! `innertube-rs` provides direct access to YouTube metadata extraction, audio/video streaming URL
6//! resolution (with automated signature & n-token deciphering via embedded QuickJS), search queries,
7//! and channel/playlist scraping.
8//!
9//! ## Quick Start
10//!
11//! Add `innertube-rs` to your `Cargo.toml`:
12//!
13//! ```toml
14//! [dependencies]
15//! innertube-rs = { git = "https://github.com/caya8205-2/innertube-rs" }
16//! tokio = { version = "1", features = ["full"] }
17//! ```
18//!
19//! ### 1. Fetch Video Metadata & Streaming URLs
20//!
21//! ```no_run
22//! use innertube_rs::{Innertube, FormatFilter, FormatType, QualityPreference};
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
26//!     // Initialize client (bootstraps session & decipher engine)
27//!     let yt = Innertube::new().await?;
28//!
29//!     // Fetch metadata
30//!     let video_info = yt.get_video_info("dQw4w9WgXcQ").await?;
31//!     if let Some(details) = video_info.video_details {
32//!         println!("Title: {}", details.title);
33//!         println!("Duration: {}s", details.length_seconds);
34//!     }
35//!
36//!     // Resolve highest quality audio-only stream URL (e.g. for music players)
37//!     let audio_filter = FormatFilter {
38//!         format_type: FormatType::AudioOnly,
39//!         quality: QualityPreference::Highest,
40//!         container: None,
41//!     };
42//!
43//!     let audio_url = yt.get_stream_url("dQw4w9WgXcQ", &audio_filter).await?;
44//!     println!("Playable Audio Stream URL: {}", audio_url);
45//!
46//!     Ok(())
47//! }
48//! ```
49//!
50//! ### 2. Search Videos, Channels, and Playlists
51//!
52//! ```no_run
53//! use innertube_rs::{Innertube, SearchResultItem};
54//!
55//! #[tokio::main]
56//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
57//!     let yt = Innertube::new().await?;
58//!     let results = yt.search("rick astley", None).await?;
59//!
60//!     for item in results.items {
61//!         match item {
62//!             SearchResultItem::Video(v) => println!("Video: {} ({})", v.title, v.video_id),
63//!             SearchResultItem::Channel(c) => println!("Channel: {} ({})", c.title, c.channel_id),
64//!             SearchResultItem::Playlist(p) => println!("Playlist: {} ({})", p.title, p.playlist_id),
65//!         }
66//!     }
67//!
68//!     Ok(())
69//! }
70//! ```
71//!
72//! ### 3. Browse Channels & Playlists
73//!
74//! ```no_run
75//! use innertube_rs::Innertube;
76//!
77//! #[tokio::main]
78//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
79//!     let yt = Innertube::new().await?;
80//!
81//!     // Fetch channel details & top tracks
82//!     let channel = yt.get_channel("@RickAstleyYT").await?;
83//!     println!("Channel Name: {}", channel.name);
84//!     println!("Top tracks: {}", channel.top_tracks.len());
85//!
86//!     // Fetch playlist videos
87//!     let playlist = yt.get_playlist("PLlaN88a7y2_plecYoJxeQNnWiiN01LUcZ").await?;
88//!     println!("Playlist Title: {}", playlist.title);
89//!     println!("Videos: {}", playlist.videos.len());
90//!
91//!     Ok(())
92//! }
93//! ```
94
95pub mod proto {
96    pub mod misc {
97        include!(concat!(env!("OUT_DIR"), "/misc.rs"));
98    }
99    pub mod youtube {
100        pub mod api {
101            pub mod pfiinnertube {
102                include!(concat!(env!("OUT_DIR"), "/youtube.api.pfiinnertube.rs"));
103            }
104        }
105    }
106}
107
108pub mod constants;
109pub mod core;
110pub mod endpoints;
111pub mod error;
112pub mod log;
113pub mod models;
114pub mod parser;
115pub mod utils;
116
117use std::sync::Arc;
118
119// Re-exports for convenient top-level access
120pub use core::actions::Actions;
121pub use core::actions::ApiResponse;
122pub use core::managers::{
123    AccountManager, InteractionManager, KidsManager, MusicManager, PlaylistManager,
124};
125pub use core::oauth::OAuth2;
126pub use core::player::Player;
127pub use core::session::{Session, SessionOptions};
128pub use error::{InnertubeError, Result};
129pub use models::account::{
130    AccountNotification, AccountNotificationsResponse, HistoryFeed, LibraryFeed,
131};
132pub use models::actions::{
133    ActionResult, CreateCommentResult, CreatePlaylistResult, NotificationPreferenceType,
134};
135pub use models::channel::{
136    ChannelAbout, ChannelArtistView, ChannelPlaylist, ChannelShortItem, ChannelShortsResponse,
137    ChannelTrack, ChannelVideoItem, ChannelVideosResponse, YouTubePlaylistView,
138};
139pub use models::comments::{Comment, CommentThread, CommentsResult, PostCommentSort};
140pub use models::feed::{
141    BrowseFeed, Feed, FilterChip, HashtagFeed, HomeFeed, TrendingFeed, TrendingTab,
142};
143pub use models::format::{
144    DownloadOptions, DownloadRange, FormatFilter, FormatOptions, FormatType, QualityPreference,
145    StreamingFormat,
146};
147pub use models::guide::{GuideItem, GuideResponse, GuideSection};
148pub use models::live_chat::{
149    LiveChatMembership, LiveChatMessage, LiveChatResponse, LiveChatSuperChat, LiveChatTextMessage,
150};
151pub use models::manifest::{ManifestStream, ParsedManifest};
152pub use models::music::{
153    MusicAlbumItem, MusicAlbumRef, MusicAlbumView, MusicArtistItem, MusicArtistPage,
154    MusicArtistRef, MusicExplore, MusicHistory, MusicHistoryEntry, MusicHomeFeed, MusicHomeItem,
155    MusicLibraryKind, MusicLibraryPage, MusicLikeStatus, MusicLyrics, MusicPlaylistItem,
156    MusicPlaylistPage, MusicPlaylistView, MusicSearchFilter, MusicSearchResults, MusicShelf,
157    MusicTrackItem, MusicWatchPage,
158};
159pub use models::next::{
160    AutoplayVideo, PlaylistPanelItem, RelatedVideo, VideoChapter, WatchNextResults,
161};
162pub use models::oauth::{DeviceAndUserCode, OAuth2ClientID, OAuth2Tokens};
163pub use models::playlist::{PlaylistContinuation, PlaylistVideoItem, PlaylistView};
164pub use models::post::{
165    CommunityPoll, CommunityPost, CommunityPostsResponse, PollChoice, PostImage,
166};
167pub use models::search::{
168    DurationFilter, FeatureFilter, SearchChannelItem, SearchFilters, SearchPlaylistItem,
169    SearchPrioritize, SearchResultItem, SearchResults, SearchTypeFilter, SearchVideoItem,
170    UploadDateFilter,
171};
172pub use models::suggestions::{SearchSuggestion, SearchSuggestionsResult};
173pub use models::transcript::{Transcript, TranscriptSegment, TranscriptTrack};
174pub use models::video::{
175    GetVideoInfoOptions, PlayabilityStatus, PlayerResponse, ShortFormVideoInfo, StreamingData,
176    Thumbnail, VideoDetails, VideoInfo,
177};
178pub use parser::{
179    AboutChannelNode, AboutChannelViewNode, AccessibilityContextNode, AccessibilityDataNode,
180    AccountChannelNode, AccountItemNode, AccountItemSectionHeaderNode, AccountItemSectionNode,
181    AccountSectionListNode, ActiveAccountHeaderNode, AddBannerToLiveChatCommandNode,
182    AddChatItemActionNode, AddLiveChatTickerItemActionNode, AddToPlaylistCommandNode,
183    AddToPlaylistEndpointNode, AddToPlaylistNode, AddToPlaylistServiceEndpointNode, AlertNode,
184    AlertWithButtonNode, AnchoredSectionNode, AnimatedThumbnailOverlayViewNode,
185    AppendContinuationItemsActionNode, AttributionViewNode, AudioOnlyPlayabilityNode,
186    AuthorCommentBadgeNode, AutomixPreviewVideoNode, AvatarStackViewNode, AvatarViewNode,
187    BackgroundPromoNode, BackstageImageNode, BackstagePostNode, BackstagePostThreadNode,
188    BadgeViewNode, BrowseEndpointNode, BrowseFeedActionsNode, BrowserMediaSessionNode,
189    BumperUserEduContentViewNode, ButtonCardViewNode, ButtonNode, ButtonViewNode,
190    C4TabbedHeaderNode, CallToActionButtonNode, CardCollectionNode, CardNode, CarouselHeaderNode,
191    CarouselItemNode, CarouselItemViewNode, CarouselLockupNode, CarouselTitleViewNode,
192    ChangeEngagementPanelVisibilityActionNode, ChannelAboutFullMetadataNode, ChannelAgeGateNode,
193    ChannelCardNode, ChannelExternalLinkViewNode, ChannelFeaturedContentNode,
194    ChannelHeaderLinksNode, ChannelHeaderLinksViewNode, ChannelHeaderNode, ChannelMetadataNode,
195    ChannelMobileHeaderNode, ChannelNode, ChannelOptionsNode, ChannelOwnerEmptyStateNode,
196    ChannelSubMenuNode, ChannelSwitcherHeaderNode, ChannelSwitcherPageNode, ChannelTaglineNode,
197    ChannelThumbnailWithLinkNode, ChannelVideoPlayerNode, ChapterNode, ChildElementNode,
198    ChildVideoNode, ChipBarViewNode, ChipCloudChipNode, ChipCloudNode, ChipViewNode,
199    ClarificationNode, ClientSideToggleMenuItemNode, ClipAdStateNode, ClipCreationNode,
200    ClipCreationScrubberNode, ClipCreationTextInputNode, ClipSectionNode,
201    CollaboratorInfoCardContentNode, CollageHeroImageNode, CollectionThumbnailViewNode,
202    CommandContextNode, CommandExecutorCommandNode, CommentActionButtonsNode, CommentDialogNode,
203    CommentNode, CommentRepliesNode, CommentReplyDialogNode, CommentSimpleboxNode,
204    CommentThreadNode, CommentViewNode, CommentsContinuationNode, CommentsEntryPointHeaderNode,
205    CommentsEntryPointTeaserNode, CommentsHeaderNode, CommentsSimpleboxNode, CompactChannelNode,
206    CompactLinkNode, CompactMixNode, CompactMovieNode, CompactPlaylistNode, CompactStationNode,
207    CompactVideoNode, CompositeVideoPrimaryInfoNode, ConfirmDialogNode, ContainerKind,
208    ContentListItemViewNode, ContentMetadataViewNode, ContentPreviewImageViewNode,
209    ContinuationCommandNode, ContinuationEndpointNode, ContinuationItemNode,
210    ContinuationItemViewNode, ConversationBarNode, CopyLinkNode, CreateCommentEndpointNode,
211    CreatePlaylistDialogFormViewNode, CreatePlaylistDialogNode, CreatePlaylistServiceEndpointNode,
212    CreatorHeartNode, CreatorHeartViewNode, DecoratedAvatarViewNode, DecoratedPlayerBarNode,
213    DefaultPromoPanelNode, DeletePlaylistEndpointNode, DescriptionPreviewViewNode,
214    DialogHeaderViewNode, DialogNode, DialogViewNode, DidYouMeanNode, DimChatItemActionNode,
215    DislikeButtonViewNode, DismissableDialogContentSectionNode, DismissableDialogNode,
216    DownloadButtonNode, DownloadListItemViewNode, DropdownItemNode, DropdownNode, DropdownViewNode,
217    DynamicTextViewNode, ElementKind, ElementNode, EmergencyOneboxNode,
218    EmojiPickerCategoryButtonNode, EmojiPickerCategoryNode, EmojiPickerNode,
219    EmojiPickerUpsellCategoryNode, EmojiRunNode, EndScreenPlaylistNode, EndScreenVideoNode,
220    EndpointKind, EndscreenElementNode, EndscreenNode, EngagementPanelSectionListNode,
221    EngagementPanelTitleHeaderNode, EomSettingsDisclaimerNode, ExpandableMetadataNode,
222    ExpandableTabNode, ExpandableVideoDescriptionBodyNode, ExpandedShelfContentsNode, FactoidNode,
223    FancyDismissibleDialogNode, FeedFilterChipBarNode, FeedNudgeNode, FeedTabbedHeaderNode,
224    FeedbackEndpointNode, FlexibleActionsViewNode, FormFooterViewNode, FormNode, FormPopupNode,
225    FormatNode, GameCardNode, GameDetailsNode, GetAccountsListInnertubeEndpointNode,
226    GetKidsBlocklistPickerCommandNode, GetMultiPageMenuActionNode, GridChannelNode, GridHeaderNode,
227    GridMixNode, GridMovieNode, GridNode, GridPlaylistNode, GridShelfViewNode, GridShowNode,
228    GridVideoNode, GuideCollapsibleEntryNode, GuideCollapsibleSectionEntryNode,
229    GuideDownloadsEntryNode, GuideEntryNode, GuideSectionNode, GuideSubscriptionsSectionNode,
230    HashtagHeaderNode, HashtagTileNode, HeatMarkerNode, HeatmapNode, HeroPlaylistThumbnailNode,
231    HideEngagementPanelEndpointNode, HighlightsCarouselNode, HistorySuggestionNode,
232    HorizontalCardListNode, HorizontalListNode, HorizontalMovieListNode,
233    HowThisWasMadeSectionViewNode, HypeFanCreditsSectionViewNode, HypePointsFactoidNode,
234    IconLinkNode, ImageBannerViewNode, IncludingResultsForNode, InfoPanelContainerNode,
235    InfoPanelContentNode, InfoRowNode, InteractiveTabbedHeaderNode, ItemSectionHeaderNode,
236    ItemSectionNode, ItemSectionTabNode, ItemSectionTabbedHeaderNode, KidsBlocklistPickerItemNode,
237    KidsBlocklistPickerNode, KidsCategoriesHeaderNode, KidsCategoryTabNode, KidsHomeScreenNode,
238    KidsKind, LegacyClassMeta, LikeButtonNode, LikeButtonViewNode, LikeEndpointNode,
239    ListItemViewNode, ListViewNode, LiveChatActionPanelNode, LiveChatAuthorBadgeNode,
240    LiveChatAutoModMessageNode, LiveChatBannerChatSummaryNode, LiveChatBannerHeaderNode,
241    LiveChatBannerNode, LiveChatBannerPollNode, LiveChatBannerRedirectNode, LiveChatDialogNode,
242    LiveChatHeaderNode, LiveChatItemBumperViewNode, LiveChatItemContextMenuEndpointNode,
243    LiveChatItemListNode, LiveChatMembershipItemNode, LiveChatMessageInputNode,
244    LiveChatMessageNode, LiveChatModeChangeMessageNode, LiveChatPaidMessageNode,
245    LiveChatPaidStickerNode, LiveChatParticipantNode, LiveChatParticipantsListNode,
246    LiveChatPlaceholderItemNode, LiveChatProductItemNode, LiveChatRestrictedParticipationNode,
247    LiveChatSponsorshipsGiftPurchaseAnnouncementNode,
248    LiveChatSponsorshipsGiftRedemptionAnnouncementNode, LiveChatSponsorshipsHeaderNode,
249    LiveChatTextMessageNode, LiveChatTickerPaidMessageItemNode, LiveChatTickerPaidStickerItemNode,
250    LiveChatTickerSponsorItemNode, LiveChatViewerEngagementMessageNode, LockupMetadataViewNode,
251    LockupViewNode, MacroMarkersInfoItemNode, MacroMarkersListEntityNode, MacroMarkersListItemNode,
252    MacroMarkersListNode, MarkChatItemAsDeletedActionNode,
253    MarkChatItemsByAuthorAsDeletedActionNode, MenuFlexibleItemNode, MenuItemNode,
254    MenuNavigationItemNode, MenuNode, MenuPopupNode, MenuServiceItemDownloadNode,
255    MenuServiceItemNode, MenuTitleNode, MerchandiseItemNode, MerchandiseShelfNode, MessageNode,
256    MetadataBadgeNode, MetadataRowContainerNode, MetadataRowHeaderNode, MetadataRowNode,
257    MetadataScreenNode, MicroformatDataNode, MixNode, MobileTopbarNode,
258    ModalWithTitleAndButtonNode, ModifyChannelNotificationPreferenceEndpointNode, MovieNode,
259    MovingThumbnailNode, MultiMarkersPlayerBarNode, MultiPageMenuNode,
260    MultiPageMenuNotificationSectionNode, MultiPageMenuSectionNode, MusicAutoplayNode,
261    MusicCardShelfHeaderBasicNode, MusicCardShelfNode, MusicCarouselShelfBasicHeaderNode,
262    MusicCarouselShelfNode, MusicDescriptionShelfNode, MusicDetailHeaderNode,
263    MusicDownloadStateBadgeNode, MusicEditablePlaylistDetailHeaderNode, MusicElementHeaderNode,
264    MusicHeaderNode, MusicImmersiveHeaderNode, MusicInlineBadgeNode, MusicItemThumbnailOverlayNode,
265    MusicLargeCardItemCarouselNode, MusicMenuItemDividerNode, MusicMultiRowListItemNode,
266    MusicMultiSelectMenuItemNode, MusicMultiSelectMenuNode, MusicNavigationButtonNode,
267    MusicPlayButtonNode, MusicPlaylistEditHeaderNode, MusicPlaylistShelfNode, MusicQueueNode,
268    MusicResponsiveHeaderNode, MusicResponsiveListItemFixedColumnNode,
269    MusicResponsiveListItemFlexColumnNode, MusicResponsiveListItemNode, MusicShelfNode,
270    MusicSideAlignedItemNode, MusicSortFilterButtonNode, MusicTastebuilderShelfNode,
271    MusicTastebuilderShelfThumbnailNode, MusicThumbnailNode, MusicTwoRowItemNode,
272    MusicVisualHeaderNode, NavigateActionNode, NavigationEndpointNode, NodeListExt,
273    NotificationActionNode, NotificationNode, OpenOnePickAddVideoModalCommandNode,
274    OpenPopupActionNode, PageHeaderNode, PageHeaderViewNode, PageIndicatorViewNode,
275    PageIntroductionNode, PanelFooterViewNode, Parser, ParserCategory, ParserDispatchTarget,
276    ParserRegistry, PdgCommentChipNode, PdgReplyButtonViewNode, PerformCommentActionEndpointNode,
277    PivotBarItemNode, PivotBarNode, PivotButtonNode, PlayerAnnotationsExpandedNode,
278    PlayerCaptchaViewNode, PlayerCaptionsTracklistNode, PlayerControlsOverlayNode,
279    PlayerErrorMessageNode, PlayerLegacyDesktopYpcOfferNode, PlayerLegacyDesktopYpcTrailerNode,
280    PlayerLiveStoryboardSpecNode, PlayerMicroformatNode, PlayerOverflowNode,
281    PlayerOverlayAutoplayNode, PlayerOverlayNode, PlayerOverlayVideoDetailsNode,
282    PlayerStoryboardSpecNode, PlaylistAddToOptionNode, PlaylistCollaborationFormDataNode,
283    PlaylistCollaborationFormSchemaNode,
284    PlaylistCollaborationViewModelPlaylistCollaboratorDataNode, PlaylistCollaborationViewNode,
285    PlaylistCustomThumbnailNode, PlaylistEditEndpointNode, PlaylistHeaderNode,
286    PlaylistInfoCardContentNode, PlaylistMetadataNode, PlaylistNode, PlaylistPanelNode,
287    PlaylistPanelVideoNode, PlaylistPanelVideoWrapperNode, PlaylistSidebarNode,
288    PlaylistSidebarPrimaryInfoNode, PlaylistSidebarSecondaryInfoNode, PlaylistThumbnailOverlayNode,
289    PlaylistVideoListNode, PlaylistVideoNode, PlaylistVideoThumbnailNode, PollHeaderNode, PollNode,
290    PostMultiImageNode, PostNode, PrefetchWatchCommandNode, PremiereTrailerBadgeNode,
291    ProductListHeaderNode, ProductListItemNode, ProductListNode, ProfileColumnNode,
292    ProfileColumnStatsEntryNode, ProfileColumnStatsNode, ProfileColumnUserInfoNode, QuizNode,
293    RecognitionShelfNode, ReelItemNode, ReelPlayerHeaderNode, ReelPlayerOverlayNode, ReelShelfNode,
294    ReelWatchEndpointNode, RelatedChipCloudNode, RemoveBannerForLiveChatCommandNode,
295    RemoveChatItemActionNode, RemoveChatItemByAuthorActionNode, RendererContextNode,
296    ReplaceChatItemActionNode, ReplaceLiveChatActionNode, ReplayChatItemActionNode, RichGridNode,
297    RichItemNode, RichListHeaderNode, RichMetadataNode, RichMetadataRowNode, RichSectionNode,
298    RichShelfNode, RunAttestationCommandNode, SearchBoxNode, SearchFilterGroupNode,
299    SearchFilterNode, SearchFilterOptionsDialogNode, SearchHeaderNode, SearchRefinementCardNode,
300    SearchSubMenuNode, SearchSuggestionNode, SearchSuggestionsSectionNode,
301    SecondarySearchContainerNode, SectionHeaderViewNode, SectionListNode,
302    SegmentedLikeDislikeButtonNode, SegmentedLikeDislikeButtonViewNode, SendFeedbackActionNode,
303    SettingBooleanNode, SettingsCheckboxNode, SettingsOptionsNode, SettingsSidebarNode,
304    SettingsSwitchNode, ShareEndpointNode, ShareEntityEndpointNode, ShareEntityServiceEndpointNode,
305    SharePanelHeaderNode, SharePanelTitleV15Node, ShareTargetNode, SharedPostNode, SheetViewNode,
306    ShelfNode, ShortNode, ShortsLockupViewNode, ShowCustomThumbnailNode, ShowDialogCommandNode,
307    ShowEngagementPanelActionNode, ShowEngagementPanelEndpointNode, ShowLiveChatActionNode,
308    ShowLiveChatActionPanelActionNode, ShowLiveChatDialogActionNode,
309    ShowLiveChatTooltipCommandNode, ShowSheetCommandNode, ShowingResultsForNode, SignalActionNode,
310    SignalServiceEndpointNode, SimpleCardContentNode, SimpleCardTeaserNode, SimpleMenuHeaderNode,
311    SimpleTextSectionNode, SingleActionEmergencySupportNode, SingleColumnBrowseResultsNode,
312    SingleColumnMusicWatchNextResultsNode, SingleHeroImageNode, SlimOwnerNode,
313    SlimVideoMetadataNode, SortFilterHeaderNode, SortFilterSubMenuNode, SponsorCommentBadgeNode,
314    StartAtNode, StructuredDescriptionContentNode, StructuredDescriptionPlaylistLockupNode,
315    SubFeedOptionNode, SubFeedSelectorNode, SubscribeButtonNode, SubscribeButtonViewNode,
316    SubscribeEndpointNode, SubscriptionButtonNode, SubscriptionNotificationToggleButtonNode,
317    TabNode, TabbedNode, TabbedSearchResultsNode, TextCarouselItemViewNode, TextFieldViewNode,
318    TextHeaderNode, TextNode, TextRunNode, ThirdPartyShareTargetSectionNode,
319    ThumbnailBadgeViewNode, ThumbnailBottomOverlayViewNode,
320    ThumbnailHoverOverlayToggleActionsViewNode, ThumbnailHoverOverlayViewNode,
321    ThumbnailLandscapePortraitNode, ThumbnailListNode, ThumbnailNode,
322    ThumbnailOverlayAvatarStackViewNode, ThumbnailOverlayBadgeViewNode,
323    ThumbnailOverlayBottomPanelNode, ThumbnailOverlayEndorsementNode,
324    ThumbnailOverlayHoverTextNode, ThumbnailOverlayInlineUnplayableNode,
325    ThumbnailOverlayLoadingPreviewNode, ThumbnailOverlayNowPlayingNode,
326    ThumbnailOverlayPinkingNode, ThumbnailOverlayPlaybackStatusNode,
327    ThumbnailOverlayProgressBarNode, ThumbnailOverlayProgressBarViewNode,
328    ThumbnailOverlayResumePlaybackNode, ThumbnailOverlaySidePanelNode,
329    ThumbnailOverlayTimeStatusNode, ThumbnailOverlayTitleViewNode,
330    ThumbnailOverlayToggleButtonNode, ThumbnailViewNode, TicketEventNode, TicketShelfNode,
331    TimedMarkerDecorationNode, TitleAndButtonListHeaderNode, ToggleButtonNode,
332    ToggleButtonViewNode, ToggleFormFieldNode, ToggleMenuServiceItemNode, TooltipNode,
333    TopbarMenuButtonNode, TopicChannelDetailsNode, TranscriptFooterNode, TranscriptNode,
334    TranscriptSearchBoxNode, TranscriptSearchPanelNode, TranscriptSectionHeaderNode,
335    TranscriptSegmentListNode, TranscriptSegmentNode, TwoColumnBrowseResultsNode,
336    TwoColumnSearchResultsNode, TwoColumnWatchNextResultsNode, UnifiedSharePanelNode,
337    UniversalWatchCardNode, UnsubscribeEndpointNode, UpdateChannelSwitcherPageActionNode,
338    UpdateDateTextActionNode, UpdateDescriptionActionNode, UpdateEngagementPanelActionNode,
339    UpdateEngagementPanelContentCommandNode, UpdateLiveChatPollActionNode,
340    UpdateSubscribeButtonActionNode, UpdateTitleActionNode, UpdateToggleButtonTextActionNode,
341    UpdateViewershipActionNode, UploadTimeFactoidNode, UpsellDialogNode, VerticalListNode,
342    VerticalWatchCardListNode, VideoAttributeViewNode, VideoAttributesSectionViewNode,
343    VideoCardNode, VideoDescriptionCourseSectionNode, VideoDescriptionHeaderNode,
344    VideoDescriptionInfocardsSectionNode, VideoDescriptionMusicSectionNode,
345    VideoDescriptionTranscriptSectionNode, VideoDescriptionYouchatSectionViewNode,
346    VideoDetailsNode, VideoInfoCardContentNode, VideoMetadataCarouselViewNode, VideoNode,
347    VideoOwnerNode, VideoPrimaryInfoNode, VideoSecondaryInfoNode, VideoSummaryContentViewNode,
348    VideoSummaryParagraphViewNode, VideoViewCountNode, ViewCountFactoidNode, ViewCountNode,
349    VoiceReplyContainerViewNode, WatchCardCompactVideoNode, WatchCardHeroVideoNode,
350    WatchCardRichHeaderNode, WatchCardSectionSequenceNode, WatchEndpointNode,
351    WatchNextEndScreenNode, WatchNextEndpointNode, WatchNextTabbedResultsNode, YTNode,
352    YTNodeVariant, YpcTrailerNode,
353};
354
355use crate::endpoints::account::{
356    get_history, get_library, get_notifications, get_unseen_notifications_count,
357};
358use crate::endpoints::attestation::get_attestation_challenge;
359use crate::endpoints::browse::get_channel;
360use crate::endpoints::channel::{
361    get_channel_about, get_channel_community, get_channel_shorts, get_channel_videos,
362};
363use crate::endpoints::comments::{get_comment_replies, get_comments, get_comments_with_options};
364use crate::endpoints::feed::{
365    get_browse_feed, get_hashtag_feed, get_home_feed, get_home_feed_continuation, get_trending,
366};
367use crate::endpoints::guide::get_guide;
368use crate::endpoints::live_chat::{extract_live_chat_continuation_token, get_live_chat};
369use crate::endpoints::music::{
370    get_music_album, get_music_artist, get_music_explore, get_music_history, get_music_home,
371    get_music_library_page, get_music_lyrics, get_music_playlist_continuation,
372    get_music_playlist_page, get_music_radio_page, get_music_shuffled_playlist_page, search_music,
373    search_music_continuation,
374};
375use crate::endpoints::navigation::resolve_url;
376use crate::endpoints::next::get_watch_next;
377use crate::endpoints::player::{
378    fetch_player_response, fetch_player_response_with_options, fetch_shorts_video_info,
379    resolve_stream_url, select_format, select_format_with_options,
380};
381use crate::endpoints::playlist::{get_playlist, get_playlist_continuation};
382use crate::endpoints::post::{get_post, get_post_comments};
383use crate::endpoints::search::{search, search_with_filters};
384use crate::endpoints::suggestions::{get_search_suggestions, get_search_suggestions_with_options};
385use crate::endpoints::transcript::{get_transcript, get_transcript_tracks};
386
387/// Main high-level Innertube client.
388///
389/// Holds the HTTP session state, API keys, client context, and the player decipher engine.
390#[derive(Clone)]
391pub struct Innertube {
392    /// InnerTube session state and HTTP client.
393    pub session: Arc<Session>,
394    /// Player manager and signature/n-token decipher engine.
395    pub player: Arc<Player>,
396}
397
398impl Innertube {
399    /// Initialize a new `Innertube` client with default options.
400    ///
401    /// Bootstraps session data from YouTube (`sw.js_data`) and downloads the latest
402    /// player script to initialize the QuickJS decipher engine.
403    pub async fn new() -> Result<Self> {
404        Self::with_options(SessionOptions::default()).await
405    }
406
407    /// Initialize a new `Innertube` client with custom session options.
408    pub async fn with_options(options: SessionOptions) -> Result<Self> {
409        let session = Session::create(options).await?;
410        let player = Player::create(&session.http_client, None).await?;
411
412        Ok(Self {
413            session: Arc::new(session),
414            player: Arc::new(player),
415        })
416    }
417
418    /// Fetch metadata and available streaming formats for a YouTube video ID.
419    pub async fn get_video_info(&self, video_id: &str) -> Result<PlayerResponse> {
420        fetch_player_response(
421            &self.session,
422            video_id,
423            Some(self.player.decipherer.signature_timestamp),
424        )
425        .await
426    }
427
428    /// Fetch complete parsed video metadata, player response, and Watch Next results concurrently.
429    ///
430    /// Matches YouTube.js `Innertube.getInfo(video_id, options)` 1:1 by issuing parallel requests
431    /// to `/player` and `/next`.
432    pub async fn get_info(
433        &self,
434        video_id: &str,
435        options: Option<&GetVideoInfoOptions>,
436    ) -> Result<VideoInfo> {
437        let sig_ts = Some(self.player.decipherer.signature_timestamp);
438        let player_future =
439            fetch_player_response_with_options(&self.session, video_id, sig_ts, options);
440        let next_future = get_watch_next(&self.session, video_id, None, None, None);
441
442        let (player_response, watch_next_res) = tokio::join!(player_future, next_future);
443        let player_response = player_response?;
444        let watch_next = watch_next_res.ok();
445        let cpn = crate::utils::proto::generate_random_string(16);
446
447        Ok(VideoInfo {
448            player_response,
449            watch_next,
450            cpn,
451            po_token: self.session.po_token.clone(),
452        })
453    }
454
455    /// Fetch player-only metadata and streaming formats for a video ID with options.
456    pub async fn get_basic_info(
457        &self,
458        video_id: &str,
459        options: Option<&GetVideoInfoOptions>,
460    ) -> Result<VideoInfo> {
461        let player_response = fetch_player_response_with_options(
462            &self.session,
463            video_id,
464            Some(self.player.decipherer.signature_timestamp),
465            options,
466        )
467        .await?;
468        let cpn = crate::utils::proto::generate_random_string(16);
469        Ok(VideoInfo {
470            player_response,
471            watch_next: None,
472            cpn,
473            po_token: self.session.po_token.clone(),
474        })
475    }
476
477    /// Publish the initial playback event for a YouTube Music track.
478    pub async fn add_music_to_watch_history(&self, info: &VideoInfo) -> Result<reqwest::Response> {
479        info.add_to_music_watch_history(&self.session).await
480    }
481
482    /// Publish a YouTube Music watch-time update for an already-fetched track.
483    pub async fn update_music_watch_time(
484        &self,
485        info: &VideoInfo,
486        start_time: f64,
487    ) -> Result<reqwest::Response> {
488        info.update_music_watch_time(&self.session, start_time)
489            .await
490    }
491
492    /// Fetch Shorts video metadata and reel watch sequence navigation.
493    pub async fn get_shorts_video_info(
494        &self,
495        video_id: &str,
496        client: Option<&str>,
497    ) -> Result<ShortFormVideoInfo> {
498        fetch_shorts_video_info(&self.session, video_id, client).await
499    }
500
501    /// Retrieve a decrypted, playable streaming URL matching the specified filter.
502    ///
503    /// Automatically applies signature deciphering and n-token transformations to ensure
504    /// the returned URL is not throttled or forbidden (403).
505    pub async fn get_stream_url(&self, video_id: &str, filter: &FormatFilter) -> Result<String> {
506        let player_res = self.get_video_info(video_id).await?;
507        let format = select_format(&player_res, filter)?;
508        crate::endpoints::player::resolve_stream_url_full(
509            format,
510            &self.player.decipherer,
511            self.session.po_token.as_deref(),
512            None,
513        )
514    }
515
516    /// Resolve a YouTube Music stream through the `YTMUSIC` client alias used by
517    /// YouTube.js `Music.getInfo()` instead of the generic video-player fallback chain.
518    pub async fn get_music_stream_url(
519        &self,
520        video_id: &str,
521        filter: &FormatFilter,
522    ) -> Result<String> {
523        let options = GetVideoInfoOptions {
524            client: Some(crate::constants::clients::YTMUSIC_NAME.to_string()),
525            ..Default::default()
526        };
527        let info = self.get_basic_info(video_id, Some(&options)).await?;
528        let format = select_format(&info.player_response, filter)?;
529        resolve_stream_url(format, &self.player.decipherer)
530    }
531
532    /// Retrieve the selected YouTube Music stream format with its deciphered, playable URL.
533    pub async fn get_music_streaming_data(
534        &self,
535        video_id: &str,
536        filter: &FormatFilter,
537    ) -> Result<StreamingFormat> {
538        let options = GetVideoInfoOptions {
539            client: Some(crate::constants::clients::YTMUSIC_NAME.to_string()),
540            ..Default::default()
541        };
542        let info = self.get_basic_info(video_id, Some(&options)).await?;
543        let mut format = select_format(&info.player_response, filter)?.clone();
544        format.url = Some(resolve_stream_url(&format, &self.player.decipherer)?);
545        format.signature_cipher = None;
546        format.cipher = None;
547        Ok(format)
548    }
549
550    /// Retrieve the selected stream format with its deciphered, playable URL.
551    pub async fn get_streaming_data(
552        &self,
553        video_id: &str,
554        filter: &FormatFilter,
555    ) -> Result<StreamingFormat> {
556        let player_res = self.get_video_info(video_id).await?;
557        let mut format = select_format(&player_res, filter)?.clone();
558        format.url = Some(crate::endpoints::player::resolve_stream_url_full(
559            &format,
560            &self.player.decipherer,
561            self.session.po_token.as_deref(),
562            None,
563        )?);
564        format.signature_cipher = None;
565        format.cipher = None;
566        Ok(format)
567    }
568
569    /// Retrieve the selected stream format matching rich `FormatOptions` with deciphered URL.
570    pub async fn get_streaming_data_with_options(
571        &self,
572        video_id: &str,
573        options: &FormatOptions,
574    ) -> Result<StreamingFormat> {
575        let player_res = fetch_player_response_with_options(
576            &self.session,
577            video_id,
578            Some(self.player.decipherer.signature_timestamp),
579            None,
580        )
581        .await?;
582        let mut format = select_format_with_options(&player_res, options)?.clone();
583        format.url = Some(crate::endpoints::player::resolve_stream_url_full(
584            &format,
585            &self.player.decipherer,
586            self.session.po_token.as_deref(),
587            None,
588        )?);
589        format.signature_cipher = None;
590        format.cipher = None;
591        Ok(format)
592    }
593
594    /// Open the selected media stream for incremental consumption.
595    ///
596    /// The returned `reqwest::Response` is the Rust equivalent of the legacy
597    /// readable stream; callers can consume it with `bytes_stream()`.
598    pub async fn download(
599        &self,
600        video_id: &str,
601        filter: &FormatFilter,
602    ) -> Result<reqwest::Response> {
603        let format = self.get_streaming_data(video_id, filter).await?;
604        let url = format.url.ok_or_else(|| {
605            InnertubeError::Format("Resolved stream format did not contain a URL".to_string())
606        })?;
607        let response = self
608            .session
609            .http_client
610            .get(url)
611            .send()
612            .await
613            .map_err(InnertubeError::Network)?;
614        Session::ensure_success("stream download", response).await
615    }
616
617    /// Open the selected media stream with download options including byte ranges.
618    pub async fn download_with_options(
619        &self,
620        video_id: &str,
621        options: &DownloadOptions,
622    ) -> Result<reqwest::Response> {
623        let format = self
624            .get_streaming_data_with_options(video_id, &options.format_options)
625            .await?;
626        let url = format.url.ok_or_else(|| {
627            InnertubeError::Format("Resolved stream format did not contain a URL".to_string())
628        })?;
629        let mut req = self.session.http_client.get(url);
630        if let Some(range) = options.range {
631            req = req.header("Range", format!("bytes={}-{}", range.start, range.end));
632        }
633        let response = req.send().await.map_err(InnertubeError::Network)?;
634        Session::ensure_success("stream download", response).await
635    }
636
637    /// Call an InnerTube endpoint with a caller-supplied JSON payload.
638    ///
639    /// This is the raw compatibility escape hatch for legacy `call()` users;
640    /// typed endpoint wrappers should be preferred whenever available.
641    pub async fn call(
642        &self,
643        endpoint: &str,
644        payload: serde_json::Value,
645    ) -> Result<serde_json::Value> {
646        let response = self.session.post_innertube(endpoint, payload).await?;
647        response.json().await.map_err(InnertubeError::Network)
648    }
649
650    /// Call a parsed legacy `NavigationEndpoint`, optionally extending its payload.
651    pub async fn call_navigation_endpoint(
652        &self,
653        endpoint: &NavigationEndpointNode,
654        extra_payload: serde_json::Value,
655    ) -> Result<serde_json::Value> {
656        let path = endpoint.api_path.as_deref().ok_or_else(|| {
657            InnertubeError::NotFound(
658                "Navigation endpoint does not define an InnerTube API path".to_string(),
659            )
660        })?;
661        let mut payload = endpoint.payload.clone();
662        let payload_object = payload.as_object_mut().ok_or_else(|| {
663            InnertubeError::Format("Navigation endpoint payload is not a JSON object".to_string())
664        })?;
665        let extra_object = extra_payload.as_object().ok_or_else(|| {
666            InnertubeError::Format(
667                "Navigation endpoint extra payload is not a JSON object".to_string(),
668            )
669        })?;
670        payload_object.extend(extra_object.clone());
671        self.call(path, payload).await
672    }
673
674    /// Execute a search query for videos, channels, and playlists.
675    pub async fn search(
676        &self,
677        query: &str,
678        continuation_token: Option<&str>,
679    ) -> Result<SearchResults> {
680        search(&self.session, query, continuation_token).await
681    }
682
683    /// Execute a search query with optional filters and continuation token.
684    pub async fn search_with_filters(
685        &self,
686        query: &str,
687        filters: Option<&SearchFilters>,
688        continuation_token: Option<&str>,
689    ) -> Result<SearchResults> {
690        search_with_filters(&self.session, query, filters, continuation_token).await
691    }
692
693    /// Fetch channel profile, videos, and playlists by channel ID or handle (e.g. `@RickAstleyYT` or `UC...`).
694    pub async fn get_channel(&self, channel_id_or_handle: &str) -> Result<ChannelArtistView> {
695        get_channel(&self.session, channel_id_or_handle).await
696    }
697
698    /// Fetch search autocomplete suggestions for YouTube or YouTube Music.
699    pub async fn get_search_suggestions(
700        &self,
701        query: &str,
702        is_music: bool,
703    ) -> Result<SearchSuggestionsResult> {
704        get_search_suggestions(&self.session, query, is_music).await
705    }
706
707    /// Fetch search autocomplete suggestions with optional previous query support.
708    pub async fn get_search_suggestions_with_options(
709        &self,
710        query: &str,
711        previous_query: Option<&str>,
712        is_music: bool,
713    ) -> Result<SearchSuggestionsResult> {
714        get_search_suggestions_with_options(&self.session, query, previous_query, is_music).await
715    }
716
717    /// Fetch full YouTube playlist metadata and videos.
718    pub async fn get_playlist(&self, playlist_id: &str) -> Result<PlaylistView> {
719        get_playlist(&self.session, playlist_id).await
720    }
721
722    /// Fetch next page of playlist videos using a continuation token.
723    pub async fn get_playlist_continuation(
724        &self,
725        continuation_token: &str,
726    ) -> Result<PlaylistContinuation> {
727        get_playlist_continuation(&self.session, continuation_token).await
728    }
729
730    /// Fetch channel profile and about details.
731    pub async fn get_channel_about(&self, channel_id: &str) -> Result<ChannelAbout> {
732        get_channel_about(&self.session, channel_id).await
733    }
734
735    /// Fetch channel videos (Videos tab) with pagination support.
736    pub async fn get_channel_videos(
737        &self,
738        channel_id: &str,
739        continuation_token: Option<&str>,
740    ) -> Result<ChannelVideosResponse> {
741        get_channel_videos(&self.session, channel_id, continuation_token).await
742    }
743
744    /// Fetch channel shorts (Shorts tab) with pagination support.
745    pub async fn get_channel_shorts(
746        &self,
747        channel_id: &str,
748        continuation_token: Option<&str>,
749    ) -> Result<ChannelShortsResponse> {
750        get_channel_shorts(&self.session, channel_id, continuation_token).await
751    }
752
753    /// Fetch channel community posts (Community tab) with pagination support.
754    pub async fn get_channel_community(
755        &self,
756        channel_id: &str,
757        continuation_token: Option<&str>,
758    ) -> Result<CommunityPostsResponse> {
759        get_channel_community(&self.session, channel_id, continuation_token).await
760    }
761
762    /// Fetch watch next details including recommended/related videos, autoplay, and playlist queue.
763    pub async fn get_watch_next(&self, video_id: &str) -> Result<WatchNextResults> {
764        get_watch_next(&self.session, video_id, None, None, None).await
765    }
766
767    /// Fetch recommended related videos for a given video ID.
768    pub async fn get_related_videos(&self, video_id: &str) -> Result<Vec<RelatedVideo>> {
769        let next_res = self.get_watch_next(video_id).await?;
770        Ok(next_res.related_videos)
771    }
772
773    /// Fetch watch next details when playing within a playlist.
774    pub async fn get_playlist_watch_next(
775        &self,
776        video_id: &str,
777        playlist_id: &str,
778        playlist_index: Option<usize>,
779    ) -> Result<WatchNextResults> {
780        get_watch_next(
781            &self.session,
782            video_id,
783            Some(playlist_id),
784            playlist_index,
785            None,
786        )
787        .await
788    }
789
790    /// Fetch continuation results for watch next recommendations using a continuation token.
791    pub async fn get_watch_next_continuation(
792        &self,
793        continuation_token: &str,
794    ) -> Result<WatchNextResults> {
795        get_watch_next(&self.session, "", None, None, Some(continuation_token)).await
796    }
797
798    /// Fetch available caption tracks for a video.
799    pub async fn get_transcript_tracks(&self, video_id: &str) -> Result<Vec<TranscriptTrack>> {
800        get_transcript_tracks(&self.session, video_id).await
801    }
802
803    /// Fetch timed transcript/subtitles for a video in the specified language (or first available).
804    pub async fn get_transcript(&self, video_id: &str, lang: Option<&str>) -> Result<Transcript> {
805        get_transcript(&self.session, video_id, lang).await
806    }
807
808    /// Fetch top comment threads for a video ID or continuation token.
809    pub async fn get_comments(&self, video_id: &str) -> Result<CommentsResult> {
810        get_comments(&self.session, video_id, None).await
811    }
812
813    /// Fetch comments with sort option, specific comment ID, or continuation token.
814    pub async fn get_comments_with_options(
815        &self,
816        video_id: &str,
817        sort_by: Option<PostCommentSort>,
818        comment_id: Option<&str>,
819        continuation_token: Option<&str>,
820    ) -> Result<CommentsResult> {
821        get_comments_with_options(
822            &self.session,
823            video_id,
824            sort_by,
825            comment_id,
826            continuation_token,
827        )
828        .await
829    }
830
831    /// Fetch next page of comments using a continuation token.
832    pub async fn get_comments_continuation(
833        &self,
834        continuation_token: &str,
835    ) -> Result<CommentsResult> {
836        get_comments(&self.session, "", Some(continuation_token)).await
837    }
838
839    /// Fetch child replies for a specific comment thread.
840    pub async fn get_comment_replies(&self, continuation_token: &str) -> Result<Vec<Comment>> {
841        get_comment_replies(&self.session, continuation_token).await
842    }
843
844    /// Perform a filtered search on YouTube Music (`WEB_REMIX`).
845    pub async fn search_music(
846        &self,
847        query: &str,
848        filter: Option<MusicSearchFilter>,
849    ) -> Result<MusicSearchResults> {
850        search_music(&self.session, query, filter).await
851    }
852
853    /// Fetch a continuation page of filtered YouTube Music search results.
854    pub async fn search_music_continuation(
855        &self,
856        query: &str,
857        filter: Option<MusicSearchFilter>,
858        continuation_token: &str,
859    ) -> Result<MusicSearchResults> {
860        search_music_continuation(&self.session, query, filter, continuation_token).await
861    }
862
863    /// Fetch song lyrics from YouTube Music for a given video ID.
864    pub async fn get_music_lyrics(&self, video_id: &str) -> Result<MusicLyrics> {
865        get_music_lyrics(&self.session, video_id).await
866    }
867
868    /// Fetch one page from a persistent YouTube Music recommendation radio.
869    pub async fn get_music_radio_page(
870        &self,
871        video_id: &str,
872        continuation: Option<&str>,
873    ) -> Result<MusicWatchPage> {
874        get_music_radio_page(&self.session, video_id, continuation).await
875    }
876
877    /// Fetch one page from YouTube Music's shuffled playlist queue.
878    pub async fn get_music_shuffled_playlist_page(
879        &self,
880        playlist_id: &str,
881        continuation: Option<&str>,
882    ) -> Result<MusicWatchPage> {
883        get_music_shuffled_playlist_page(&self.session, playlist_id, continuation).await
884    }
885
886    /// Fetch YouTube Music album details and tracklist by browse ID (e.g. `MPREb_...`).
887    pub async fn get_music_album(&self, browse_id: &str) -> Result<MusicAlbumView> {
888        get_music_album(&self.session, browse_id).await
889    }
890
891    /// Fetch YouTube Music explore and trending page data.
892    pub async fn get_music_explore(&self) -> Result<MusicExplore> {
893        get_music_explore(&self.session).await
894    }
895
896    /// Fetch YouTube Music dedicated Artist Page by channel/artist ID (e.g. `UC...`).
897    pub async fn get_music_artist(&self, artist_id: &str) -> Result<MusicArtistPage> {
898        get_music_artist(&self.session, artist_id).await
899    }
900
901    /// Fetch one native page from a YouTube Music library destination.
902    pub async fn get_music_library_page(
903        &self,
904        kind: MusicLibraryKind,
905        continuation_token: Option<&str>,
906    ) -> Result<MusicLibraryPage> {
907        get_music_library_page(&self.session, kind, continuation_token).await
908    }
909
910    /// Fetch the complete authenticated YouTube Music playback history.
911    pub async fn get_music_history(&self) -> Result<MusicHistory> {
912        get_music_history(&self.session).await
913    }
914
915    /// Fetch YouTube Music Home Feed with dynamic shelves (`FEmusic_home`).
916    pub async fn get_music_home(&self) -> Result<MusicHomeFeed> {
917        get_music_home(&self.session).await
918    }
919
920    /// Fetch a continuation page of the YouTube Music Home Feed.
921    pub async fn get_music_home_continuation(
922        &self,
923        continuation_token: &str,
924    ) -> Result<MusicHomeFeed> {
925        crate::endpoints::music::get_music_home_continuation(&self.session, continuation_token)
926            .await
927    }
928
929    /// Fetch the first native typed page of a YouTube Music playlist.
930    pub async fn get_music_playlist_page(&self, playlist_id: &str) -> Result<MusicPlaylistPage> {
931        get_music_playlist_page(&self.session, playlist_id).await
932    }
933
934    /// Fetch a continuation page of a YouTube Music playlist.
935    pub async fn get_music_playlist_continuation(
936        &self,
937        continuation_token: &str,
938        is_collaborative: bool,
939    ) -> Result<MusicPlaylistPage> {
940        get_music_playlist_continuation(&self.session, continuation_token, is_collaborative).await
941    }
942
943    /// Fetch YouTube Music playlist details and the native initial track window.
944    pub async fn get_music_playlist_details(
945        &self,
946        playlist_id: &str,
947    ) -> Result<crate::models::music::MusicPlaylistView> {
948        crate::endpoints::music::get_music_playlist_details(&self.session, playlist_id).await
949    }
950
951    /// Fetch the main YouTube Home Feed (`FEwhat_to_watch`).
952    pub async fn get_home_feed(&self, params: Option<&str>) -> Result<HomeFeed> {
953        get_home_feed(&self.session, params).await
954    }
955
956    /// Fetch continuation page of the YouTube Home Feed.
957    pub async fn get_home_feed_continuation(&self, continuation_token: &str) -> Result<HomeFeed> {
958        get_home_feed_continuation(&self.session, continuation_token).await
959    }
960
961    /// Fetch YouTube Trending Feed (`FEtrending`).
962    pub async fn get_trending(&self, tab_params: Option<&str>) -> Result<TrendingFeed> {
963        get_trending(&self.session, tab_params).await
964    }
965
966    /// Fetch videos for a specific hashtag (`FEhashtag`).
967    pub async fn get_hashtag_feed(&self, tag: &str) -> Result<HashtagFeed> {
968        get_hashtag_feed(&self.session, tag).await
969    }
970
971    /// Fetch the Courses browse destination (`FEcourses_destination`).
972    pub async fn get_courses(&self) -> Result<BrowseFeed> {
973        get_browse_feed(&self.session, "FEcourses_destination").await
974    }
975
976    /// Fetch the subscriptions browse destination (`FEsubscriptions`).
977    pub async fn get_subscriptions_feed(&self) -> Result<BrowseFeed> {
978        get_browse_feed(&self.session, "FEsubscriptions").await
979    }
980
981    /// Fetch the subscribed channels browse destination (`FEchannels`).
982    pub async fn get_channels_feed(&self) -> Result<BrowseFeed> {
983        get_browse_feed(&self.session, "FEchannels").await
984    }
985
986    /// Fetch the authenticated playlist aggregation destination (`FEplaylist_aggregation`).
987    pub async fn get_playlists(&self) -> Result<BrowseFeed> {
988        get_browse_feed(&self.session, "FEplaylist_aggregation").await
989    }
990
991    /// Resolve a YouTube URL to its InnerTube navigation endpoint.
992    pub async fn resolve_url(&self, url: &str) -> Result<NavigationEndpointNode> {
993        resolve_url(&self.session, url).await
994    }
995
996    /// Fetch a Community Post detail page.
997    pub async fn get_post(
998        &self,
999        post_id: &str,
1000        channel_id: &str,
1001    ) -> Result<CommunityPostsResponse> {
1002        get_post(&self.session, post_id, channel_id).await
1003    }
1004
1005    /// Fetch comments attached to a Community Post.
1006    pub async fn get_post_comments(
1007        &self,
1008        post_id: &str,
1009        channel_id: &str,
1010        sort: PostCommentSort,
1011    ) -> Result<CommentsResult> {
1012        get_post_comments(&self.session, post_id, channel_id, sort).await
1013    }
1014
1015    /// Request an attestation challenge for a BotGuard-compatible engagement flow.
1016    pub async fn get_attestation_challenge(
1017        &self,
1018        engagement_type: &str,
1019        ids: Option<serde_json::Value>,
1020    ) -> Result<serde_json::Value> {
1021        get_attestation_challenge(&self.session, engagement_type, ids).await
1022    }
1023
1024    /// Fetch the YouTube Guide navigation menu (/guide endpoint).
1025    pub async fn get_guide(&self) -> Result<GuideResponse> {
1026        get_guide(&self.session).await
1027    }
1028
1029    /// Fetch a batch of live chat messages using a live chat continuation token.
1030    pub async fn get_live_chat(&self, continuation_token: &str) -> Result<LiveChatResponse> {
1031        get_live_chat(&self.session, continuation_token).await
1032    }
1033
1034    /// Extract live chat continuation token from a live stream video ID.
1035    pub async fn get_live_chat_token(&self, video_id: &str) -> Result<Option<String>> {
1036        let next_resp = self
1037            .session
1038            .post_innertube(
1039                "/next",
1040                serde_json::json!({
1041                    "videoId": video_id,
1042                }),
1043            )
1044            .await?;
1045        let raw: serde_json::Value = next_resp.json().await?;
1046        Ok(extract_live_chat_continuation_token(&raw))
1047    }
1048
1049    /// Request an OAuth2 device and user code for Google TV authentication.
1050    pub async fn request_oauth_code(&self) -> Result<(OAuth2ClientID, DeviceAndUserCode)> {
1051        let client = OAuth2::get_client_id(&self.session.http_client).await?;
1052        let code =
1053            OAuth2::get_device_and_user_code(&self.session.http_client, &client.client_id).await?;
1054        Ok((client, code))
1055    }
1056
1057    /// Poll for OAuth2 access tokens after user authorizes on `https://www.google.com/device`.
1058    pub async fn poll_oauth_token(
1059        &self,
1060        client: &OAuth2ClientID,
1061        code: &DeviceAndUserCode,
1062    ) -> Result<OAuth2Tokens> {
1063        OAuth2::poll_for_access_token(
1064            &self.session.http_client,
1065            client,
1066            &code.device_code,
1067            code.interval,
1068        )
1069        .await
1070    }
1071
1072    /// Like a YouTube video (`POST /like/like`).
1073    pub async fn like(&self, video_id: &str) -> Result<ActionResult> {
1074        Actions::like(&self.session, video_id).await
1075    }
1076
1077    /// Dislike a YouTube video (`POST /like/dislike`).
1078    pub async fn dislike(&self, video_id: &str) -> Result<ActionResult> {
1079        Actions::dislike(&self.session, video_id).await
1080    }
1081
1082    /// Remove like/dislike rating from a video (`POST /like/removelike`).
1083    pub async fn remove_rating(&self, video_id: &str) -> Result<ActionResult> {
1084        Actions::remove_rating(&self.session, video_id).await
1085    }
1086
1087    /// Subscribe to YouTube channels (`POST /subscription/subscribe`).
1088    pub async fn subscribe(&self, channel_ids: &[&str]) -> Result<ActionResult> {
1089        Actions::subscribe(&self.session, channel_ids).await
1090    }
1091
1092    /// Unsubscribe from YouTube channels (`POST /subscription/unsubscribe`).
1093    pub async fn unsubscribe(&self, channel_ids: &[&str]) -> Result<ActionResult> {
1094        Actions::unsubscribe(&self.session, channel_ids).await
1095    }
1096
1097    /// Create a new YouTube playlist (`POST /playlist/create`).
1098    pub async fn create_playlist(
1099        &self,
1100        title: &str,
1101        video_ids: Option<&[&str]>,
1102    ) -> Result<CreatePlaylistResult> {
1103        Actions::create_playlist(&self.session, title, video_ids).await
1104    }
1105
1106    /// Delete a YouTube playlist (`POST /playlist/delete`).
1107    pub async fn delete_playlist(&self, playlist_id: &str) -> Result<ActionResult> {
1108        Actions::delete_playlist(&self.session, playlist_id).await
1109    }
1110
1111    /// Add videos to an existing playlist (`POST /browse/edit_playlist`).
1112    pub async fn add_to_playlist(
1113        &self,
1114        playlist_id: &str,
1115        video_ids: &[&str],
1116    ) -> Result<ActionResult> {
1117        Actions::add_to_playlist(&self.session, playlist_id, video_ids).await
1118    }
1119
1120    /// Remove videos from an existing playlist (`POST /browse/edit_playlist`).
1121    pub async fn remove_from_playlist(
1122        &self,
1123        playlist_id: &str,
1124        set_video_ids: &[&str],
1125    ) -> Result<ActionResult> {
1126        Actions::remove_from_playlist(&self.session, playlist_id, set_video_ids).await
1127    }
1128
1129    /// Create a top-level comment on a video (`POST /comment/create_comment`).
1130    pub async fn create_comment(
1131        &self,
1132        video_id: &str,
1133        comment_text: &str,
1134    ) -> Result<CreateCommentResult> {
1135        Actions::create_comment(&self.session, video_id, comment_text).await
1136    }
1137
1138    /// Set the title / name of a playlist (`POST /browse/edit_playlist`).
1139    pub async fn set_playlist_name(&self, playlist_id: &str, name: &str) -> Result<ActionResult> {
1140        Actions::set_playlist_name(&self.session, playlist_id, name).await
1141    }
1142
1143    /// Set the description of a playlist (`POST /browse/edit_playlist`).
1144    pub async fn set_playlist_description(
1145        &self,
1146        playlist_id: &str,
1147        description: &str,
1148    ) -> Result<ActionResult> {
1149        Actions::set_playlist_description(&self.session, playlist_id, description).await
1150    }
1151
1152    /// Move a video to after another video in a playlist (`POST /browse/edit_playlist`).
1153    pub async fn move_playlist_video(
1154        &self,
1155        playlist_id: &str,
1156        set_video_id: &str,
1157        predecessor_set_video_id: &str,
1158    ) -> Result<ActionResult> {
1159        Actions::move_playlist_video(
1160            &self.session,
1161            playlist_id,
1162            set_video_id,
1163            predecessor_set_video_id,
1164        )
1165        .await
1166    }
1167
1168    /// Add a playlist to the user's library (`POST /like/like`).
1169    pub async fn add_playlist_to_library(&self, playlist_id: &str) -> Result<ActionResult> {
1170        Actions::add_playlist_to_library(&self.session, playlist_id).await
1171    }
1172
1173    /// Remove a playlist from the user's library (`POST /like/removelike`).
1174    pub async fn remove_playlist_from_library(&self, playlist_id: &str) -> Result<ActionResult> {
1175        Actions::remove_playlist_from_library(&self.session, playlist_id).await
1176    }
1177
1178    /// Modify notification preferences for a channel (`POST /notification/modify_channel_preference`).
1179    pub async fn set_notification_preferences(
1180        &self,
1181        channel_id: &str,
1182        pref_type: NotificationPreferenceType,
1183    ) -> Result<ActionResult> {
1184        Actions::set_notification_preferences(&self.session, channel_id, pref_type).await
1185    }
1186
1187    /// Fetch authenticated user watch history (`FEhistory`).
1188    pub async fn get_history(&self, continuation_token: Option<&str>) -> Result<HistoryFeed> {
1189        get_history(&self.session, continuation_token).await
1190    }
1191
1192    /// Fetch authenticated user library (`FElibrary`).
1193    pub async fn get_library(&self) -> Result<LibraryFeed> {
1194        get_library(&self.session).await
1195    }
1196
1197    /// Fetch account notifications.
1198    pub async fn get_notifications(&self) -> Result<AccountNotificationsResponse> {
1199        get_notifications(&self.session).await
1200    }
1201
1202    /// Return the number shown by YouTube's unread-notifications indicator.
1203    pub async fn get_unseen_notifications_count(&self) -> Result<u64> {
1204        get_unseen_notifications_count(&self.session).await
1205    }
1206
1207    /// Access YouTube Music manager (`client.music()`).
1208    pub fn music(&self) -> MusicManager<'_> {
1209        MusicManager::new(&self.session)
1210    }
1211
1212    /// Access playlist manager (`client.playlist()`).
1213    pub fn playlist(&self) -> PlaylistManager<'_> {
1214        PlaylistManager::new(&self.session)
1215    }
1216
1217    /// Access interaction and mutation manager (`client.interact()`).
1218    pub fn interact(&self) -> InteractionManager<'_> {
1219        InteractionManager::new(&self.session)
1220    }
1221
1222    /// Access actions manager (`client.actions()`). Alias for `interact()`.
1223    pub fn actions(&self) -> InteractionManager<'_> {
1224        InteractionManager::new(&self.session)
1225    }
1226
1227    /// Access account manager (`client.account()`).
1228    pub fn account(&self) -> AccountManager<'_> {
1229        AccountManager::new(&self.session)
1230    }
1231
1232    /// Access YouTube Kids manager (`client.kids()`).
1233    pub fn kids(&self) -> KidsManager<'_> {
1234        KidsManager::new(&self.session)
1235    }
1236
1237    /// Access YouTube Studio manager (`client.studio()`).
1238    pub fn studio(&self) -> crate::core::managers::StudioManager<'_> {
1239        crate::core::managers::StudioManager::new(&self.session)
1240    }
1241}