ytm

package module
v1.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 18 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ytm-go

Read this in other languages: Bahasa Indonesia.

ytm-go is a Go port of ytm-kt. It provides search functions and metadata extraction from YouTube Music.

Key Features

  • Search & Autocomplete: Query songs, albums, playlists, artists, and fetch real-time autocomplete search suggestions.
  • Full Metadata Extraction: Retrieve tracks' detailed info (title, artists, duration, thumbnail provider, explicit tags).
  • Artist Profiles: Load artist details, channel statistics, and categorized visual shelves (singles, popular tracks, albums).
  • Playlists & Albums: Read the complete tracklists and metadata for public playlists or official albums.
  • Lyrics Sheet Loading: Fetch plaintext lyrics, and timed lyrics with per-line cue ranges, using a song's lyrics browse ID.
  • Radio Recommendations: Build recommended radio mix tracklists dynamically.
  • Mix Playlists: Read the queue behind a shared "RD…" mix id, seeded where the link would start and paged by continuation.
  • Signed-in Library: Read the account's playlists, liked songs, albums and artists, with paging.
  • Account & Channels: List the channels a Google account owns, read its display name and email, and switch the active channel.
  • Video Renditions: Opt in to the video tracks behind a song, with a resolution cap and a codec preference for hardware decoding.

Getting Started

Unlike the original ytm-kt library which leverages NewPipeExtractor to resolve/download media formats, ytm-go delegates downloading entirely to yt-dlp via the local Go bindings go-ytdlp.

This decouples the library's catalog parsing from the decryption/download routing (which frequently breaks due to YouTube's player signature revisions).

Simple Usage Example

Here is a quick example of searching for a track and downloading it directly to Ogg/Opus format:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/dlcuy22/ytm-go"
	"github.com/lrstanley/go-ytdlp"
)

func main() {
	ctx := context.Background()

	// 1. Initialize the client
	client := ytm.NewClient()

	// 2. Search for the song
	fmt.Println("Searching for 'MURI MURI EVOLUTION'...")
	results, err := client.Search(ctx, "MURI MURI EVOLUTION - NANAOAKARI", "", false)
	if err != nil {
		log.Fatalf("Search failed: %v", err)
	}

	var targetSong *ytm.Song
	for _, cat := range results.Categories {
		for _, item := range cat.Layout.Items {
			if s, ok := item.(*ytm.Song); ok {
				targetSong = s
				break
			}
		}
		if targetSong != nil {
			break
		}
	}

	if targetSong == nil {
		log.Fatalf("Song not found in search results.")
	}
	fmt.Printf("Found Song: %s (ID: %s)\n", targetSong.Name, targetSong.ID)

	// 3. Ensure runtime dependencies and download via go-ytdlp
	fmt.Println("Ensuring go-ytdlp dependencies are installed...")
	ytdlp.MustInstallAll(ctx)

	fmt.Println("Downloading audio and converting to Opus...")
	dl := ytdlp.New().
		Format("bestaudio").
		ExtractAudio().
		AudioFormat("opus").
		AudioQuality("0").
		Output("./temp_song.opus").
		NoPlaylist()

	_, err = dl.Run(ctx, "https://www.youtube.com/watch?v="+targetSong.ID)
	if err != nil {
		log.Fatalf("Download failed: %v", err)
	}

	fmt.Println("Song successfully downloaded to: ./temp_song.opus")
}

Core API Reference

NewClient()

Creates a new Client instance configured with default connection settings.

client.Search(ctx, query, params, authRequired)

Queries the YouTube Music catalog for tracks, albums, playlists, or artists matching the string query.

  • Returns: *SearchResults, error
client.GetSearchSuggestions(ctx, query)

Fetches live autocomplete suggestions for search terms.

  • Returns: []string, error
client.LoadArtist(ctx, artistID)

Retrieves full details for an artist channel including layouts, popular tracks, and subscriber metrics.

  • Returns: *Artist, error
client.LoadPlaylist(ctx, playlistID, continuation, browseParams, playlistURL, useNonMusicAPI)

Retrieves detailed metadata and tracklistings for playlists or albums.

  • Returns: *Playlist, error
client.GetSongLyrics(ctx, lyricsBrowseID)

Retrieves the plaintext lyrics for a song.

  • Returns: string, error
client.GetSongLyricsTimed(ctx, lyricsBrowseID)

Retrieves the lyric sheet for a song, with cue ranges when the endpoint has them. Song.LyricsBrowseID is the ID to pass, and LoadSong is what fills it.

  • Returns: *Lyrics, error
sheet, err := client.GetSongLyricsTimed(ctx, song.LyricsBrowseID)
if errors.Is(err, ytm.ErrLyricsNotAvailable) {
    // the track has no lyrics
}
for _, line := range sheet.Lines {
    fmt.Println(line.StartMs, line.Text) // StartMs is 0 for an untimed sheet
}
fmt.Println(sheet.Synced)

The request uses the iOS Music client, which is the profile the endpoint answers with timed lines. When that profile is refused or returns nothing, the desktop web client is used instead and the sheet comes back unsynced. The client version is therefore load-bearing: YouTube retires old ones with FAILED_PRECONDITION, which is what the fallback is for.

client.GetStreamWithOptions(ctx, songID, opts)

Resolves playable media URLs for a track. GetStream is the same call with the default options.

  • Returns: *Streams, error

Only audio is returned by default. opts.Video adds the video renditions:

streams, err := client.GetStreamWithOptions(ctx, id, ytm.StreamOptions{
    Video:      true,
    MaxHeight:  720,
    VideoCodec: ytm.VideoCodecH264,
})
audio, _ := streams.Best()
video, ok := streams.BestVideo()

An adaptive video rendition carries no audio, so streams.AudioFor(video) returns the audio track that has to be played alongside it. A muxed rendition reports false and plays on its own.

VideoCodec ranks rather than filters, so a family the endpoint did not offer falls back instead of failing. Preferring H264 is how you get hardware decoding where VP9 and AV1 are unsupported; YouTube serves avc1 only up to 1080p.

The URLs answer byte ranges, so a player can stream and seek them directly. Do not save one in a single long request: fetch a few MiB at a time, or the transfer is throttled to a crawl partway through.

Authentication

ytm-go does not implement a login flow. It takes a Cookie: header captured from a signed-in browser and replays it:

auth, err := ytm.NewAuthFromCookieString(cookieHeader)
if err != nil {
    return err // the header carries no SAPISID
}
client.SetAuth(auth)
client.SetVisitorID(visitorData) // optional, saves a request on every start

The header must be the whole thing, not one field. A SAPISID on its own only seeds the Authorization hash; the session identity lives in SID or __Secure-3PSID. A header with SAPISID but neither of those returns a signed-out page for every request.

auth.SetChannel(pageID, dataSyncID, authUser) points the session at one channel of an account that owns several. The cookies stay the same; only the account headers change. DataSyncID is bookkeeping and is never sent in a request.

client.GetAccounts(ctx)

Lists the channels the signed-in Google account owns.

  • Returns: []Account, error
client.GetAccountInfo(ctx)

Reads the display name, email, channel handle and avatar of the signed-in account.

  • Returns: *AccountInfo, error
client.GetLikedSongs(ctx) / client.GetLikedSongsContinuation(ctx, token)

Pages the account's liked songs.

  • Returns: []Song, *BuiltInContinuation, error
client.GetLibraryPlaylists(ctx) / client.GetLibraryPlaylistsContinuation(ctx, token)

Pages the account's playlists.

  • Returns: []Playlist, *BuiltInContinuation, error
client.GetLikedAlbumsContinuation(ctx, token)

Pages the account's liked albums. GetLikedAlbums loads the first page.

  • Returns: []Playlist, *BuiltInContinuation, error
client.GetLikedArtistsContinuation(ctx, token)

Pages the account's artists. GetLikedArtists loads the first page.

  • Returns: []Artist, *BuiltInContinuation, error
client.SignedIn()

Reports whether the most recent response was produced for a signed-in viewer.

  • Returns: bool

A dead session is not an HTTP error: the server answers 200 with a signed-out page. The authed readers therefore return ErrSessionExpired rather than an empty slice, so a broken session is visible instead of looking like an empty library.

Playlist Mutations & Ownership
  • client.SetPlaylistSaved(ctx, playlistID, saved): saves or removes a foreign playlist (including album OLAK… IDs) in the signed-in account's library.
  • client.CreatePlaylist(ctx, opts): creates a playlist with CreatePlaylistOptions (Title, Description, Privacy: PlaylistPrivate default / PlaylistUnlisted / PlaylistPublic, and optional initial VideoIDs). Angle brackets (<, >) are stripped from titles.
  • client.AddSongsToPlaylistOpts(ctx, playlistID, videoIDs, mode): adds tracks with DedupeAsk (returns ErrDuplicates if already present), DedupeDrop (skips duplicates), or DedupeAdd (appends unconditionally, same as AddSongsToPlaylist).
  • client.GetAddToPlaylistTargets(ctx, videoID): fetches []AddToPlaylistTarget (PlaylistID, Title, Subtitle, Thumbnail) from /playlist/get_add_to_playlist.
  • Playlist.Owned(channelID) & IsEditablePlaylistID(id): checks ownership and filters out built-in/non-editable IDs (LM, OLAK…, RD…, MPRE…, SE, MPSP…).
  • Write protection & status errors: signed-in writes are paced (500 ms minimum gap), repeated HTTP 403 refusals back off and return ErrRateLimited, and non-SUCCEEDED write responses return ErrEditRejected.

Documentation

Overview

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement account playlist CRUD operations and editing.

Key Components:

  • GetAccountPlaylists: retrieves the playlists owned by the authenticated user
  • CreateAccountPlaylist: creates a new empty playlist
  • DeleteAccountPlaylist: deletes a user-owned playlist
  • EditPlaylist: applies a list of raw playlist edit actions
  • AddSongsToPlaylist: adds a list of video IDs to a playlist
  • PlaylistEditor: stateful wrapper tracking playlist contents during updates

Dependencies:

  • context
  • fmt
  • strings

Error Types:

  • ErrLoginRequired: returned if the action is attempted without credentials

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Read the signed-in account: its display identity and the channels it owns.

Key Components:

  • GetAccounts: the channel list behind the account switcher
  • GetAccountInfo: the display name and email of the active Google account
  • accountsListResponse: the response nesting both readers walk

Dependencies:

  • context
  • strconv
  • strings

Error Types:

  • ErrLoginRequired: returned without credentials
  • ErrSessionExpired: returned when the server answers signed out

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Fetch account playlists available as targets when adding a song.

Key Components:

  • AddToPlaylistTarget: playlist metadata shown in YouTube Music's "Save to playlist" sheet
  • GetAddToPlaylistTargets: calls /playlist/get_add_to_playlist for a track

Dependencies:

  • context
  • fmt
  • strings

Error Types:

  • ErrLoginRequired: returned when called without credentials

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement artist details loading and parsing.

Key Components:

  • LoadArtist: loads detail metadata for an artist using /browse endpoint and MOBILE context
  • parseArtistResponse: maps InnerTube browse structures into the Artist model
  • parseSubscribers: parses subscriber string counts (like 10M or 250K) into integer metrics

Dependencies:

  • context
  • strconv
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define AuthState and SAPISIDHASH authentication generation logic.

Key Components:

  • AuthState: Credentials container
  • GenerateSAPISIDHash: SAPISID hashing algorithm
  • NewAuthFromCookies / NewAuthFromCookieString: Constructors for AuthState

Dependencies:

  • crypto/sha1
  • encoding/hex
  • net/http

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement song feed browse views and view more pagination.

Key Components:

  • GetSongFeed: requests and pages the home music feed using browse endpoint
  • GetGenericFeedViewMore: loads a specific view-more section (like listen again)
  • processRows: maps unmarshaled browse shelf rows into display layouts

Dependencies:

  • context
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define connection orchestration and JSON request dispatching.

Key Components:

  • InnerTubeError / APIError: Structured InnerTube execution exception types
  • doInnerTube: Encapsulates authentication injection, visitor IDs, context merging, and POST dispatching
  • setHeaders: injects browser headers to bypass simple bot checks

Dependencies:

  • bytes
  • context
  • encoding/json
  • fmt
  • io
  • net/http
  • strings
  • time

Error Types:

  • InnerTubeError: returned on HTTP status failure or backend response failure

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define preset ClientContext models to impersonate different device profiles.

Key Components:

  • ClientContext: Profile payload containing client version, name, and user-agent details
  • Preset context generators: GetContextWebRemix, GetContextAndroid, etc.

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Placeholder and base utilities for endpoints.

Key Components:

  • Endpoint: Description of endpoint structure

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define authentication requirements for mutating endpoints.

Key Components:

  • requireAuth: Asserts that AuthState is initialized

Dependencies:

  • None

Error Types:

  • ErrLoginRequired: returned when AuthState is nil

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement in-memory cache layer to avoid duplicate InnerTube details fetching.

Key Components:

  • ItemCache: thread-safe container storing tracks, artists, and playlists
  • GetOrLoadSong / GetOrLoadArtist / GetOrLoadPlaylist: helper loaders with cache fallbacks

Dependencies:

  • context
  • sync

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement the account library surface: the liked-songs list, and adding or
removing a song from the library.

Key Components:

  • GetLikedSongs / GetLikedSongsContinuation: FEmusic_liked_videos paging
  • SetSongInLibrary: toggles library membership via /feedback tokens
  • SendFeedback: the low-level token submission
  • libraryToggleTokens: pulls the add/remove tokens out of a /next menu

Dependencies:

  • context
  • fmt

Error Types:

  • ErrLoginRequired: returned when the action is attempted without credentials
  • ErrFeedbackTokenMissing: the /next response carried no library toggle

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement song liking modification and check.

Key Components:

  • SongLikedStatus: enum for track preference (neutral, liked, disliked)
  • SetSongLiked: updates liking state on a track
  • GetSongLiked: checks preference status from /next player overlays

Dependencies:

  • context
  • fmt

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement queries for liked library items (albums, artists, and playlists).

Key Components:

  • GetLikedAlbums: retrieves the list of albums liked by the user
  • GetLikedArtists: retrieves the list of artists followed/liked by the user
  • GetLikedPlaylists: retrieves the list of playlists liked by the user (delegates to GetAccountPlaylists)

Dependencies:

  • context
  • strings

Error Types:

  • ErrLoginRequired: returned if the action is attempted without credentials

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement lyrics loading, timed and plaintext.

Key Components:

  • GetSongLyricsTimed: requests and decodes the lyric sheet for a lyrics browse ID
  • GetSongLyrics: the plaintext view of the same sheet
  • LyricLine / Lyrics: the decoded sheet, with cue ranges when the endpoint has them

Dependencies:

  • context
  • errors
  • fmt
  • strings

Error Types:

  • ErrLyricsNotFound: the response carried no lyric sheet at all
  • ErrLyricsNotAvailable: the endpoint answered that lyrics are unavailable

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement mix queue loading from the watch-next endpoint.

Key Components:

  • GetMix: loads an "RD…" mix playlist and its continuation pages
  • mixVideoID: recovers the seed video a share id carries
  • playlistPanelSongs: flattens a queue panel into songs

Dependencies:

  • context
  • fmt
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define core shared types, interfaces, and utilities including media items,
thumbnails, and authentication models.

Key Components:

  • MediaItem: Interface for all YouTube Music items (songs, artists, playlists)
  • Thumbnail: Representation of an image asset
  • ThumbnailProvider: Structured selector for various resolution thumbnails

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define visual feed layout and chip structures for home feed and browse pages.

Key Components:

  • FeedLoadResult: Scraped home feed outcome
  • MediaItemLayout: Generic visual group of MediaItems (grid, row, list, etc.)
  • FilterChip: InnerTube category pill

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define search outcome and category filtering options.

Key Components:

  • SearchResults: Scraped search outcomes
  • SearchCategory: Result groups (Songs, Albums, Artists, etc.)
  • SearchFilter: Parameter parameters used for pagination or category switching

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define song, artist, playlist, and layout structures used to interact
with InnerTube API endpoints.

Key Components:

  • Song: Model representing a YouTube Music track
  • Artist: Model representing a music creator or channel
  • Playlist: Model representing a compilation of tracks (including albums and radios)
  • ArtistLayout: Visual sections returned in artist browse details

Dependencies:

  • None

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement playlist details loading and parsing.

Key Components:

  • LoadPlaylist: retrieves metadata and tracks for a playlist, album, or radio
  • parsePlaylistResponse: unmarshals the browse response into a Playlist struct
  • formatBrowseID: formats a playlist ID prefix ensuring VL is prepended when necessary

Dependencies:

  • context
  • strconv
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement playlist continuation paging.

Key Components:

  • GetPlaylistContinuation: loads the next page of playlist items
  • toContinuationToken: helper to extract pagination tokens

Dependencies:

  • context

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement SongRadio endpoints and modifier generation.

Key Components:

  • GetSongRadio: fetches a song-radio stream and alternative modifiers
  • RadioBuilderModifier: enum matching InnerTube radio filters (discover, upbeat, chill, etc.)
  • videoIdToRadio / radioToFilters: encodes/decodes InnerTube RDAT radio keys

Dependencies:

  • context
  • fmt
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement ArtistRadio loading.

Key Components:

  • GetArtistRadio: returns the artist radio playlist by loading playlist ID prefixed with RART

Dependencies:

  • context

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement RadioBuilder endpoints and token generation.

Key Components:

  • RadioBuilderArtist: artist seed structure used to build a custom radio
  • GetRadioBuilderArtists: retrieves seed list of artists
  • BuildRadioToken: encodes builder artists and modifiers into custom VLRDAT radio token
  • GetBuiltRadio: retrieves custom playlist from token

Dependencies:

  • context
  • fmt
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement radio and queue continuation loading.

Key Components:

  • LoadContinuation: resolves the next list of media items based on the continuation parameters

Dependencies:

  • context
  • fmt

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement ArtistShuffle details loading and parsing.

Key Components:

  • GetArtistShuffle: loads artist shuffle queue list prefixed with RAS
  • GetArtistShuffleContinuation: pages the artist shuffle queue

Dependencies:

  • context

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement related content resolving for tracks.

Key Components:

  • RelatedGroup: collection of items related to a track
  • GetSongRelated: requests and parses recommended playlists, albums, and tracks using relatedBrowseId

Dependencies:

  • context
  • fmt

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define the raw InnerTube response JSON structures and parsers.

Key Components:

  • YoutubeiBrowseResponse: represents InnerTube browse outcome JSON
  • YoutubeiNextResponse: represents watch-next queue details
  • Various visual renderers like MusicResponsiveListItemRenderer, MusicTwoRowItemRenderer, etc.

Dependencies:

  • strings
  • strconv

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement Search endpoint logic.

Key Components:

  • Search: queries search terms and returns categorized results (Songs, Artists, Albums, etc.)

Dependencies:

  • context
  • strings

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement search suggestions endpoint query.

Key Components:

  • GetSearchSuggestions: returns query autocomplete suggestions from InnerTube
  • SearchSuggestion: suggestion metadata containing result query and history flag

Dependencies:

  • context

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Decide whether a response was produced for a signed-in viewer.

Key Components:

  • authState: the verdict a response body carries
  • classifyAuthState: reads the two markers a body can hold
  • Client.SignedIn: the verdict of the most recent response
  • discardHandler: the no-op logger used when none was installed

Dependencies:

  • bytes
  • context
  • log/slog
  • regexp

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement song information fetching.

Key Components:

  • LoadSong: retrieves details for a track by sending requests to /next and /player endpoints
  • parseSongResponse: parses /next queue items to extract lyrics and related browse IDs

Dependencies:

  • context
  • fmt

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Resolve playable audio streams for a track without shelling out to yt-dlp.

Key Components:

  • StreamFormat: one selectable audio representation from /player
  • StreamOptions / AudioCodec: how a caller asks for a codec
  • GetStream / GetStreamWithOptions: /player against the VISIONOS profile
  • selectAudioFormat: the ranking that implements the codec preference

Dependencies:

  • context
  • fmt
  • net/url
  • sort
  • strconv
  • strings
  • time

Error Types:

  • ErrStreamNotFound: no audio format survived selection
  • ErrContentNotAvailable: the track is not playable for this client

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement artist subscription status modification and checker.

Key Components:

  • SetSubscribedToArtist: Subscribes or unsubscribes to an artist channel
  • GetSubscribedToArtist: Checks if the user is subscribed to an artist

Dependencies:

  • context
  • errors

Error Types:

  • ErrLoginRequired: returned if the action is attempted without credentials

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Handle YouTube Music visitor ID acquisition and lifecycle.

Key Components:

  • GetVisitorID: Fetches a fresh visitor ID from InnerTube
  • ensureVisitorID: Lazy loader ensuring visitor ID is present before dispatching requests

Dependencies:

  • context

Error Types:

  • None

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Implement recording playback progress (marking songs as watched).

Key Components:

  • MarkSongAsWatched: reports song playback start to YouTube tracking servers
  • generateCpn: generates a random tracking correlation identifier

Dependencies:

  • context
  • fmt
  • math/rand
  • net/http
  • strings
  • time

Error Types:

  • ErrLoginRequired: returned if the action is attempted without credentials

Package ytm provides models and definitions for YouTube Music InnerTube requests and responses.

Purpose:

Define the main Client struct, defaults, and configuration setters.

Key Components:

  • Client: Central orchestrator containing the HTTP client, API routes, authentication context, and item caches
  • NewClient / NewClientWithHTTP: Client factory constructors
  • SetAuth / SetVisitorID: configuration modifiers

Dependencies:

  • net/http
  • time

Error Types:

  • ErrLoginRequired: returned when an authenticated action is attempted without credentials
  • ErrContentNotAvailable: returned when paid or premium streaming tracks are encountered
  • ErrStreamNotFound: returned when no stream urls are found

Index

Constants

View Source
const (
	YtmUserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:145.0) Gecko/20100101 Firefox/145.0"
	DefaultHL    = "en-GB"
)
View Source
const (
	DefaultAPIURL         = "https://music.youtube.com/youtubei/v1/"
	DefaultNonMusicAPIURL = "https://www.youtube.com/youtubei/v1/"
)
View Source
const Version = "1.6.0"

Version is the current version of the ytm-go library.

Variables

View Source
var (
	ErrLoginRequired       = errors.New("login required")
	ErrContentNotAvailable = errors.New("content not available")
	ErrStreamNotFound      = errors.New("stream not found")
	ErrLyricsNotFound      = errors.New("lyrics not found")
	ErrLyricsNotAvailable  = errors.New("lyrics not available")

	// ErrSessionExpired means credentials were supplied but the server treated
	// the request as signed out. It is a different failure from ErrLoginRequired:
	// the caller did configure a session, the session is just no longer valid.
	//
	// The distinction matters because a dead session is not an HTTP error. The
	// server answers 200 with a signed-out page, so this error is raised by
	// inspecting the response body, not the status code.
	ErrSessionExpired = errors.New("session expired")

	// ErrDuplicates means an add-to-playlist request with DedupeAsk was refused
	// because one or more tracks are already in the playlist.
	ErrDuplicates = errors.New("ytm: playlist already has some of these songs")

	// ErrEditRejected means InnerTube answered HTTP 200 for a write operation,
	// but the JSON status field did not report SUCCEEDED.
	ErrEditRejected = errors.New("ytm: YouTube Music rejected the change")

	// ErrRateLimited means repeated HTTP 403 refusals on signed-in requests
	// triggered exponential backoff.
	ErrRateLimited = errors.New("ytm: rate limited")
)
View Source
var ErrFeedbackTokenMissing = errors.New("ytm: library feedback token not found")

ErrFeedbackTokenMissing means the /next response did not contain the library toggle the caller asked to act on. It is distinct from a network failure: the track may be unplayable, or the account may not be allowed to save it.

Functions

func BuildRadioToken

func BuildRadioToken(artists []RadioBuilderArtist, modifiers []RadioBuilderModifier) string

BuildRadioToken encodes selected artists and modifiers into custom VLRDAT radio token.

params:
      artists: seed choices
      modifiers: selected variety or style filters
returns:
      string: constructed token

func CleanPlaylistID

func CleanPlaylistID(id string) string

CleanPlaylistID removes common playlist prefixes like MPSP.

func CleanSongID

func CleanSongID(id string) string

CleanSongID removes common song prefixes like MPED.

func GenerateSAPISIDHash

func GenerateSAPISIDHash(sapisid string) string

GenerateSAPISIDHash calculates a valid SAPISIDHASH header value.

params:
      sapisid: the SAPISID cookie value
returns:
      string: formatted SAPISIDHASH authorization header

func IsEditablePlaylistID added in v1.8.0

func IsEditablePlaylistID(id string) bool

IsEditablePlaylistID reports whether id refers to a user-editable playlist rather than Liked Music, albums, mixes, or podcasts.

func IsMixID added in v1.7.0

func IsMixID(playlistID string) bool

IsMixID reports whether a playlist id names a mix, the "RD…" form the browse endpoint refuses and only the watch-next queue resolves.

func SetLogger added in v1.4.0

func SetLogger(l *slog.Logger)

SetLogger installs a package-level logger for helpers that cannot reach a Client. Callers that do have a client should prefer Client.SetLogger.

Types

type APIError

type APIError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Status  string `json:"status"`
}

APIError represents the structured error response from InnerTube API.

type Account added in v1.4.0

type Account struct {
	Name          string
	Byline        string
	ChannelHandle string
	ThumbnailURL  string
	IsSelected    bool

	// SigninURL is the per-channel sign-in URL the listing reports. It is kept
	// because it carries the channel's X-Goog-AuthUser index, which AuthUser
	// exposes separately.
	SigninURL string

	// PageID is the channel browse ID, the "UC…" form. It is what ChannelID
	// needs on AuthState, so a switch does not have to re-derive it.
	PageID string

	// DataSyncID is the channel's datasync token. It is bookkeeping only: sending
	// it as user.onBehalfOfUser makes the server answer HTTP 500.
	DataSyncID string

	// AuthUser is the X-Goog-AuthUser index for this channel, parsed out of
	// SigninURL. It is the value the request header must carry.
	AuthUser string
}

Account is one channel of the signed-in Google account.

type AccountInfo added in v1.4.0

type AccountInfo struct {
	Name          string
	Email         string
	ChannelHandle string
	ThumbnailURL  string
}

AccountInfo is the display identity of the active Google account.

type AddToPlaylistTarget added in v1.8.0

type AddToPlaylistTarget struct {
	PlaylistID string
	Title      string
	Subtitle   string // e.g. "9 tracks" from shortBylineText
	Thumbnail  string // highest-resolution URL from thumbnailRenderer
}

AddToPlaylistTarget represents an account playlist that can receive a song.

type Artist

type Artist struct {
	ID                 string             `json:"id"`
	Type               string             `json:"type,omitempty"`
	Name               string             `json:"name,omitempty"`
	Description        string             `json:"description,omitempty"`
	Thumbnail          *ThumbnailProvider `json:"thumbnail,omitempty"`
	ShufflePlaylistID  string             `json:"shuffle_playlist_id,omitempty"`
	Layouts            []ArtistLayout     `json:"layouts,omitempty"`
	SubscribeChannelID string             `json:"subscribe_channel_id,omitempty"`
	SubscriberCount    int                `json:"subscriber_count,omitempty"`
	Subscribed         bool               `json:"subscribed"`
}

Artist represents a music artist or channel.

func (Artist) GetID

func (a Artist) GetID() string

func (Artist) GetName

func (a Artist) GetName() string

func (Artist) GetThumbnailProvider

func (a Artist) GetThumbnailProvider() *ThumbnailProvider

type ArtistLayout

type ArtistLayout struct {
	Items      []MediaItem `json:"items,omitempty"`
	Title      string      `json:"title,omitempty"`
	Subtitle   string      `json:"subtitle,omitempty"`
	Type       string      `json:"type,omitempty"`
	ViewMore   *PageRef    `json:"view_more,omitempty"`
	PlaylistID string      `json:"playlist_id,omitempty"`
}

ArtistLayout represents components in an artist browse overview.

type AudioCodec added in v1.2.0

type AudioCodec string

AudioCodec names a container/codec family a caller can ask for. The values are deliberately coarse: a caller picks a family, and selectAudioFormat picks the best bitrate inside it.

const (
	// CodecAuto prefers Opus in WebM and falls back to AAC in MP4. It is the
	// zero value, so an unset StreamOptions means "best available".
	CodecAuto AudioCodec = ""
	// CodecOpus is audio/webm; codecs="opus". The default in practice: 48 kHz
	// stereo at the highest bitrate YouTube offers for music.
	CodecOpus AudioCodec = "opus"
	// CodecAAC is audio/mp4; codecs="mp4a.*", the AAC family.
	CodecAAC AudioCodec = "aac"
)

type AuthState

type AuthState struct {
	Cookie        string    `json:"cookie"`
	Authorization string    `json:"authorization"` // Current SAPISIDHASH
	ChannelID     string    `json:"channel_id,omitempty"`
	SAPISID       string    `json:"sapisid,omitempty"`
	LastUpdated   time.Time `json:"last_updated"`

	// AuthUser is the X-Goog-AuthUser index of the active channel. One Google
	// account can own several channels, and the server picks the channel from
	// this header, so "0" is only correct for the first one.
	AuthUser string `json:"auth_user,omitempty"`

	// DataSyncID identifies the active channel. It is bookkeeping only: sending
	// it as user.onBehalfOfUser makes the server answer HTTP 500 INTERNAL for a
	// plain channel-scoped session.
	DataSyncID string `json:"data_sync_id,omitempty"`
}

AuthState manages authenticated session credentials.

func NewAuthFromCookieString

func NewAuthFromCookieString(cookieStr string) (*AuthState, error)

NewAuthFromCookieString parses raw cookie header string to build an AuthState.

params:
      cookieStr: raw cookie header content
returns:
      *AuthState: authenticated session state, or error if SAPISID is missing

func NewAuthFromCookies

func NewAuthFromCookies(cookies []*http.Cookie) (*AuthState, error)

NewAuthFromCookies parses cookie slice to build an AuthState.

params:
      cookies: list of http.Cookies
returns:
      *AuthState: authenticated session state, or error if SAPISID is missing

func (*AuthState) GetAuthorizationHeader

func (a *AuthState) GetAuthorizationHeader() string

GetAuthorizationHeader returns a fresh authorization token if SAPISID is present, or the cached fallback.

returns:
      string: authorization header token

func (*AuthState) SetChannel added in v1.4.0

func (a *AuthState) SetChannel(pageID, dataSyncID, authUser string)

SetChannel points the session at one channel of a signed-in account.

The cookies stay the same for every channel; only the account headers move. Pass the empty string to leave a value untouched, which is what a caller does when the account listing did not carry that particular token.

pageID is the channel browse ID (the "UC…" form), dataSyncID is the channel's datasync token, and authUser is the X-Goog-AuthUser index the account listing reports for this channel.

type Badge

type Badge struct {
	MusicInlineBadgeRenderer *struct {
		Icon *struct {
			IconType string `json:"iconType"`
		} `json:"icon"`
	} `json:"musicInlineBadgeRenderer"`
}

func (Badge) IsExplicit

func (b Badge) IsExplicit() bool

type BrowseEndpoint

type BrowseEndpoint struct {
	BrowseID                              string                                 `json:"browseId"`
	BrowseEndpointContextSupportedConfigs *BrowseEndpointContextSupportedConfigs `json:"browseEndpointContextSupportedConfigs,omitempty"`
	Params                                string                                 `json:"params,omitempty"`
}

BrowseEndpoint represents a browse navigation target.

func (BrowseEndpoint) GetMediaItem

func (be BrowseEndpoint) GetMediaItem() MediaItem

func (BrowseEndpoint) GetMediaItemType

func (be BrowseEndpoint) GetMediaItemType() string

func (BrowseEndpoint) PageType

func (be BrowseEndpoint) PageType() string

type BrowseEndpointContextMusicConfig

type BrowseEndpointContextMusicConfig struct {
	PageType string `json:"pageType"`
}

BrowseEndpointContextMusicConfig defines browse item pages.

type BrowseEndpointContextSupportedConfigs

type BrowseEndpointContextSupportedConfigs struct {
	BrowseEndpointContextMusicConfig BrowseEndpointContextMusicConfig `json:"browseEndpointContextMusicConfig"`
}

BrowseEndpointContextSupportedConfigs wraps page layout configurations.

type BuiltInContinuation

type BuiltInContinuation struct {
	Token           string           `json:"token"`
	Type            ContinuationType `json:"type"`
	ItemID          string           `json:"item_id,omitempty"`
	PlaylistSkipAmt int              `json:"playlist_skip_amount"`
}

BuiltInContinuation contains parameters needed to continue loading lists or radios.

func (*BuiltInContinuation) LoadContinuation

func (bc *BuiltInContinuation) LoadContinuation(ctx context.Context, client *Client, filters []RadioBuilderModifier) ([]MediaItem, *BuiltInContinuation, error)

LoadContinuation dispatches request to resolve items for any continuation token.

params:
      ctx: execution context
      client: client orchestrator
      filters: optional list of tuner filters
returns:
      []MediaItem: resolved continuation items
      *BuiltInContinuation: next page continuation token
      error: network or parsing error

type ChannelCreationFormEndpoint

type ChannelCreationFormEndpoint struct {
	ChannelCreationToken string `json:"channelCreationToken"`
}

ChannelCreationFormEndpoint represents channel updates.

type Chip added in v1.1.0

type Chip struct {
	Name   string     `json:"name"`
	Params string     `json:"params,omitempty"`
	Type   SearchType `json:"type,omitempty"`
}

Chip represents a search filter chip from the chip cloud.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client manages connection parameters to YouTube Music.

func NewClient

func NewClient() *Client

NewClient creates a Client instance with sensible default timeouts.

returns:
      *Client: configured client

func NewClientWithHTTP

func NewClientWithHTTP(httpClient *http.Client) *Client

NewClientWithHTTP initializes a Client with a custom http.Client.

params:
      httpClient: custom http client
returns:
      *Client: configured client

func (*Client) AddSongsToPlaylist

func (c *Client) AddSongsToPlaylist(ctx context.Context, playlistID string, videoIDs []string) error

AddSongsToPlaylist adds the specified track IDs to a playlist without duplicate checking (DedupeAdd), so tracks already in the playlist can be added again. Prefer AddSongsToPlaylistOpts when duplicate handling matters.

params:
      ctx: execution context
      playlistID: target playlist identifier
      videoIDs: tracks to add
returns:
      error: network or rejection error

func (*Client) AddSongsToPlaylistOpts added in v1.8.0

func (c *Client) AddSongsToPlaylistOpts(ctx context.Context, playlistID string, videoIDs []string, mode DedupeMode) error

AddSongsToPlaylistOpts adds the specified track IDs to a playlist with the chosen duplicate-handling mode.

func (*Client) Auth added in v1.4.0

func (c *Client) Auth() *AuthState

Auth returns the session the client was configured with, or nil when it is running anonymously. It is the live pointer, so a caller can adjust the channel on it; prefer AuthState.SetChannel over writing fields directly.

func (*Client) AuthKnown added in v1.4.0

func (c *Client) AuthKnown() bool

AuthKnown reports whether any response so far carried a viewer marker. It separates "signed out" from "no opinion yet", which SignedIn alone cannot.

func (*Client) CreateAccountPlaylist

func (c *Client) CreateAccountPlaylist(ctx context.Context, title, description string) (string, error)

CreateAccountPlaylist creates a new empty private playlist.

params:
      ctx: execution context
      title: playlist title
      description: playlist description
returns:
      string: the created playlist ID
      error: network or rejection error

func (*Client) CreatePlaylist added in v1.8.0

func (c *Client) CreatePlaylist(ctx context.Context, opts CreatePlaylistOptions) (string, error)

CreatePlaylist creates a new playlist on the signed-in account. Empty Privacy defaults to PlaylistPrivate, and angle brackets are stripped from Title.

func (*Client) DeleteAccountPlaylist

func (c *Client) DeleteAccountPlaylist(ctx context.Context, playlistID string) error

DeleteAccountPlaylist deletes the user-owned playlist with the given ID.

params:
      ctx: execution context
      playlistID: playlist identifier
returns:
      error: network or rejection error

func (*Client) EditPlaylist

func (c *Client) EditPlaylist(ctx context.Context, playlistID string, actions []PlaylistEditAction) error

EditPlaylist applies raw commands to mutate playlist settings or elements.

params:
      ctx: execution context
      playlistID: playlist identifier
      actions: list of edit action commands
returns:
      error: network or rejection error

func (*Client) GetAccountInfo added in v1.4.0

func (c *Client) GetAccountInfo(ctx context.Context) (*AccountInfo, error)

GetAccountInfo returns the display identity of the active Google account.

The email is not in the channel items; it only appears in the account menu header, which is why this reads a different part of the same response.

params:
      ctx: execution context
returns:
      *AccountInfo: name, email, channel handle and avatar
      error: network, parsing, or ErrSessionExpired

func (*Client) GetAccountPlaylists

func (c *Client) GetAccountPlaylists(ctx context.Context) ([]Playlist, error)

GetAccountPlaylists retrieves the playlists owned by the authenticated user.

params:
      ctx: execution context
returns:
      []Playlist: list of user playlists
      error: network or parsing error

func (*Client) GetAccounts added in v1.4.0

func (c *Client) GetAccounts(ctx context.Context) ([]Account, error)

GetAccounts returns the channels the signed-in Google account owns.

A plain account owns exactly one channel, and the listing then holds a single item with IsSelected set. Brand accounts return several, and the one the session currently uses is the one flagged IsSelected.

params:
      ctx: execution context
returns:
      []Account: the channels, in the order the account switcher shows them
      error: network, parsing, or ErrSessionExpired

func (*Client) GetAddToPlaylistTargets added in v1.8.0

func (c *Client) GetAddToPlaylistTargets(ctx context.Context, videoID string) ([]AddToPlaylistTarget, error)

GetAddToPlaylistTargets returns the playlists (including "LM" for Liked Music) that YouTube Music offers in its "Save to playlist" sheet for videoID.

func (*Client) GetArtistRadio

func (c *Client) GetArtistRadio(ctx context.Context, artistID string, continuation *BuiltInContinuation) (*Playlist, error)

GetArtistRadio retrieves the artist automix radio playlist.

params:
      ctx: execution context
      artistID: channel browse ID
      continuation: optional continuation token
returns:
      *Playlist: artist radio playlist
      error: network or parsing error

func (*Client) GetArtistShuffle

func (c *Client) GetArtistShuffle(ctx context.Context, artistID string, continuation *string) (*Playlist, error)

GetArtistShuffle retrieves artist tracks in random order.

params:
      ctx: execution context
      artistID: channel browse ID
      continuation: optional continuation token
returns:
      *Playlist: artist shuffle playlist
      error: network or parsing error

func (*Client) GetArtistShuffleContinuation

func (c *Client) GetArtistShuffleContinuation(ctx context.Context, artistID string, token string) ([]MediaItem, *BuiltInContinuation, error)

GetArtistShuffleContinuation retrieves next page of artist shuffle queue.

params:
      ctx: execution context
      artistID: channel browse ID
      token: continuation token
returns:
      []MediaItem: list of continuation items
      *BuiltInContinuation: next page continuation token
      error: network or parsing error

func (*Client) GetBuiltRadio

func (c *Client) GetBuiltRadio(ctx context.Context, radioToken string) (*Playlist, error)

GetBuiltRadio retrieves custom playlist contents from VLRDAT token.

params:
      ctx: execution context
      radioToken: custom VLRDAT token
returns:
      *Playlist: custom generated radio playlist
      error: network or parsing error

func (*Client) GetGenericFeedViewMore

func (c *Client) GetGenericFeedViewMore(ctx context.Context, browseID string) ([]MediaItem, error)

GetGenericFeedViewMore loads items for a dedicated section browse ID.

params:
      ctx: execution context
      browseID: browse target ID
returns:
      []MediaItem: list of loaded media items
      error: network or parsing error

func (*Client) GetLibraryPlaylists added in v1.4.0

func (c *Client) GetLibraryPlaylists(ctx context.Context) ([]Playlist, *BuiltInContinuation, error)

GetLibraryPlaylists retrieves the first page of the account's playlists.

This is the paging form of GetAccountPlaylists. The two read the same page; this one also returns the token for the next one.

params:
      ctx: execution context
returns:
      []Playlist: playlists, in library order
      *BuiltInContinuation: next page token, or nil on the last page
      error: network, parsing, or ErrSessionExpired

func (*Client) GetLibraryPlaylistsContinuation added in v1.4.0

func (c *Client) GetLibraryPlaylistsContinuation(ctx context.Context, token string) ([]Playlist, *BuiltInContinuation, error)

GetLibraryPlaylistsContinuation loads the next page of the account's playlists.

params:
      ctx: execution context
      token: continuation token from a previous page
returns:
      []Playlist: the next page
      *BuiltInContinuation: following page token, or nil on the last page
      error: network, parsing, or ErrSessionExpired

func (*Client) GetLikedAlbums

func (c *Client) GetLikedAlbums(ctx context.Context) ([]Playlist, error)

GetLikedAlbums retrieves the list of liked albums in the user's library.

params:
      ctx: execution context
returns:
      []Playlist: list of liked albums
      error: network or parsing error

func (*Client) GetLikedAlbumsContinuation added in v1.4.0

func (c *Client) GetLikedAlbumsContinuation(ctx context.Context, token string) ([]Playlist, *BuiltInContinuation, error)

GetLikedAlbumsContinuation loads the next page of the account's liked albums.

params:
      ctx: execution context
      token: continuation token from a previous page
returns:
      []Playlist: the next page
      *BuiltInContinuation: following page token, or nil on the last page
      error: network, parsing, or ErrSessionExpired

func (*Client) GetLikedArtists

func (c *Client) GetLikedArtists(ctx context.Context) ([]Artist, error)

GetLikedArtists retrieves the list of artists from the user's library.

params:
      ctx: execution context
returns:
      []Artist: list of followed or liked artists
      error: network or parsing error

func (*Client) GetLikedArtistsContinuation added in v1.4.0

func (c *Client) GetLikedArtistsContinuation(ctx context.Context, token string) ([]Artist, *BuiltInContinuation, error)

GetLikedArtistsContinuation loads the next page of the account's artists.

params:
      ctx: execution context
      token: continuation token from a previous page
returns:
      []Artist: the next page
      *BuiltInContinuation: following page token, or nil on the last page
      error: network, parsing, or ErrSessionExpired

func (*Client) GetLikedPlaylists

func (c *Client) GetLikedPlaylists(ctx context.Context) ([]Playlist, error)

GetLikedPlaylists retrieves the list of user-owned and liked playlists.

params:
      ctx: execution context
returns:
      []Playlist: list of liked playlists
      error: network or parsing error

func (*Client) GetLikedSongs added in v1.2.0

func (c *Client) GetLikedSongs(ctx context.Context) ([]Song, *BuiltInContinuation, error)

GetLikedSongs retrieves the first page of songs in the user's library.

params:
      ctx: execution context
returns:
      []Song: liked songs, in library order
      *BuiltInContinuation: next page token, or nil on the last page
      error: network or parsing error

func (*Client) GetLikedSongsContinuation added in v1.2.0

func (c *Client) GetLikedSongsContinuation(ctx context.Context, token string) ([]Song, *BuiltInContinuation, error)

GetLikedSongsContinuation loads the next page of liked songs.

params:
      ctx: execution context
      token: continuation token from a previous page
returns:
      []Song: the next page of liked songs
      *BuiltInContinuation: following page token, or nil on the last page
      error: network or parsing error

func (*Client) GetMix added in v1.7.0

func (c *Client) GetMix(ctx context.Context, playlistID string, continuation *BuiltInContinuation) (*Playlist, error)

GetMix loads the tracks behind a YouTube mix playlist, the "RD…" id a mix share URL carries (for example RDLoK17z6xDwI). The browse endpoint rejects these with "This playlist type is unviewable.", so the queue comes from the watch-next endpoint instead.

The first call sends the playlist id and, when the id encodes one, the seed video, so the queue starts where the share URL would. A continuation call sends only the token.

params:
      ctx: execution context
      playlistID: mix playlist id, with or without a share URL prefix
      continuation: opt-in next page, as returned in Playlist.Continuation
returns:
      *Playlist: the mix tracks, typed as radio
      error: network, parsing, or empty-queue error

func (*Client) GetPlaylistContinuation

func (c *Client) GetPlaylistContinuation(ctx context.Context, initial bool, token string, skipInitial int) ([]MediaItem, *BuiltInContinuation, error)

GetPlaylistContinuation fetches paginated elements from the playlist.

params:
      ctx: execution context
      initial: is this the first continuation page
      token: continuation token
      skipInitial: number of items to skip
returns:
      []MediaItem: list of continuation items
      *BuiltInContinuation: next page continuation token
      error: network or parsing error

func (*Client) GetPlaylistEditor

func (c *Client) GetPlaylistEditor(playlistID string, itemIDs, itemSetIDs []string) *PlaylistEditor

GetPlaylistEditor returns an editor instance for a playlist.

params:
      playlistID: ID of the playlist
      itemIDs: ordered list of media item IDs in the playlist
      itemSetIDs: ordered list of item set IDs in the playlist
returns:
      *PlaylistEditor: the playlist editor instance

func (*Client) GetRadioBuilderArtists

func (c *Client) GetRadioBuilderArtists(ctx context.Context) ([]RadioBuilderArtist, error)

GetRadioBuilderArtists retrieves the list of seed artists configured for custom radio generation.

params:
      ctx: execution context
returns:
      []RadioBuilderArtist: list of seed options
      error: network or parsing error

func (*Client) GetSearchContinuation added in v1.1.0

func (c *Client) GetSearchContinuation(ctx context.Context, token string) ([]MediaItem, string, error)

func (*Client) GetSearchSuggestions

func (c *Client) GetSearchSuggestions(ctx context.Context, query string) ([]SearchSuggestion, error)

GetSearchSuggestions retrieves query autocomplete strings from YouTube Music.

params:
      ctx: execution context
      query: prefix query keywords
returns:
      []SearchSuggestion: list of suggestions
      error: network or parsing error

func (*Client) GetSongFeed

func (c *Client) GetSongFeed(ctx context.Context, minRows int, params *string, continuation *string) (*FeedLoadResult, error)

GetSongFeed retrieves the structured feed layouts for home browse view.

params:
      ctx: execution context
      minRows: minimum rows to load before stopping pagination
      params: optional InnerTube chip search params
      continuation: optional pagination ctoken
returns:
      *FeedLoadResult: list of loaded layouts and continuation metadata
      error: network or parsing error

func (*Client) GetSongFeedWithBrowse added in v1.2.0

func (c *Client) GetSongFeedWithBrowse(ctx context.Context, browseID string, minRows int, params *string, continuation *string, authed bool) (*FeedLoadResult, error)

GetSongFeedWithBrowse retrieves a named browse feed, optionally as the signed-in account.

The browse targets that matter for a music client are FEmusic_home (the home feed), FEmusic_explore, FEmusic_charts, FEmusic_new_releases_albums and FEmusic_moods_and_genres. Sending browseId is what makes the response a real home feed: without it the endpoint still answers, but with a generic anonymous selection rather than the account's own rows.

authed controls whether the account cookie is sent. For FEmusic_home the difference is measurable: a signed-in request returns more rows and carousels than an anonymous one. Callers without credentials should pass false.

params:
      ctx: execution context
      browseID: browse target, e.g. "FEmusic_home"
      minRows: minimum rows to load before stopping pagination
      params: optional InnerTube chip search params
      continuation: optional pagination ctoken
      authed: send the account cookie
returns:
      *FeedLoadResult: list of loaded layouts and continuation metadata
      error: network or parsing error

func (*Client) GetSongLiked

func (c *Client) GetSongLiked(ctx context.Context, songID string) (SongLikedStatus, error)

GetSongLiked checks the liked preference status of a track.

params:
      ctx: execution context
      songID: YouTube track ID
returns:
      SongLikedStatus: preference state
      error: network or parsing error

func (*Client) GetSongLyrics

func (c *Client) GetSongLyrics(ctx context.Context, lyricsID string) (string, error)

GetSongLyrics retrieves the plaintext lyrics content for the specified lyrics browse ID.

Timed lines are joined into the same plaintext a plain sheet would give, so a caller that only needs text does not have to know which shape the sheet had.

params:
      ctx: execution context
      lyricsID: lyrics browse ID
returns:
      string: plaintext lyrics
      error: network, parsing, or availability error

func (*Client) GetSongLyricsTimed added in v1.6.0

func (c *Client) GetSongLyricsTimed(ctx context.Context, lyricsID string) (*Lyrics, error)

GetSongLyricsTimed retrieves the lyric sheet for the specified lyrics browse ID.

The request is made with the iOS Music client, which is the profile the endpoint answers with timedLyricsModel: one entry per line, each with a cue range in milliseconds. The desktop web client is answered with a plaintext description shelf instead, and that is used as the fallback when the mobile profile returns nothing usable, so a stale client version degrades to unsynced lyrics rather than to an error.

params:
      ctx: execution context
      lyricsID: lyrics browse ID from Song.LyricsBrowseID
returns:
      *Lyrics: lines, with cue ranges when the endpoint had them
      error: network, parsing, or availability error

func (*Client) GetSongRadio

func (c *Client) GetSongRadio(ctx context.Context, songID string, continuation *string, filters []RadioBuilderModifier) (*RadioData, error)

GetSongRadio retrieves tracks on the automix song radio feed.

params:
      ctx: execution context
      songID: seed track ID
      continuation: optional continuation pagination token
      filters: list of active radio filters (upbeat, low variety, etc.)
returns:
      *RadioData: matching radio tracks and filter alternatives
      error: network or parsing error

func (*Client) GetSongRelated

func (c *Client) GetSongRelated(ctx context.Context, songID string) ([]RelatedGroup, error)

GetSongRelated queries and parses related tracks and albums for the specified track.

params:
      ctx: execution context
      songID: YouTube track ID
returns:
      []RelatedGroup: related groups of media items
      error: network or parsing error

func (*Client) GetStream added in v1.2.0

func (c *Client) GetStream(ctx context.Context, songID string) (*Streams, error)

GetStream resolves the playable audio stream for a song ID using the default preference: the highest-bitrate Opus format in WebM.

params:
      ctx: execution context
      songID: YouTube track ID (an "MPED" prefix is stripped)
returns:
      *Streams: resolved formats, best first
      error: network, parsing, or availability error

func (*Client) GetStreamWithOptions added in v1.2.0

func (c *Client) GetStreamWithOptions(ctx context.Context, songID string, opts StreamOptions) (*Streams, error)

GetStreamWithOptions resolves playable audio streams for a song ID.

The request is made with the VISIONOS client context, which is the profile that currently answers with plain media URLs. It is anonymous by design: the profile cannot log in, so this call never sends the account cookie and works the same whether or not SetAuth was called.

params:
      ctx: execution context
      songID: YouTube track ID (an "MPED" prefix is stripped)
      opts: codec preference and bitrate cap
returns:
      *Streams: resolved formats, best first
      error: network, parsing, or availability error

func (*Client) GetSubscribedToArtist

func (c *Client) GetSubscribedToArtist(ctx context.Context, artistID string) (bool, error)

GetSubscribedToArtist checks if currently subscribed to the artist.

params:
      ctx: execution context
      artistID: channel ID of the artist
returns:
      bool: true if subscribed, false otherwise
      error: network or parsing error

func (*Client) GetVisitorID

func (c *Client) GetVisitorID(ctx context.Context) (string, error)

GetVisitorID requests a new visitor ID from the visitor_id endpoint.

params:
      ctx: execution context
returns:
      string: visitor ID token
      error: network or parsing error

func (*Client) LoadArtist

func (c *Client) LoadArtist(ctx context.Context, artistID string) (*Artist, error)

LoadArtist retrieves detail layouts and channel metadata for the specified artist ID.

params:
      ctx: execution context
      artistID: artist browse or channel ID
returns:
      *Artist: populated artist details
      error: network or parsing error

func (*Client) LoadPlaylist

func (c *Client) LoadPlaylist(ctx context.Context, playlistID string, continuation *BuiltInContinuation, browseParams *string, playlistURL *string, useNonMusicAPI bool) (*Playlist, error)

LoadPlaylist retrieves metadata and track list contents for the specified playlist ID.

params:
      ctx: execution context
      playlistID: playlist browse ID
      continuation: opt-in pagination token
      browseParams: opt-in filter params
      playlistURL: opt-in canonical URL
      useNonMusicAPI: force standard YouTube API rather than Music
returns:
      *Playlist: populated playlist metadata
      error: network or parsing error

func (*Client) LoadSong

func (c *Client) LoadSong(ctx context.Context, songID string) (*Song, error)

LoadSong retrieves metadata details for the specified song ID.

params:
      ctx: execution context
      songID: YouTube track ID
returns:
      *Song: track metadata details
      error: network or parsing error

func (*Client) MarkSongAsWatched

func (c *Client) MarkSongAsWatched(ctx context.Context, songID string) error

MarkSongAsWatched reports song playback to YouTube stats tracking backend.

params:
      ctx: execution context
      songID: track identifier to mark as watched
returns:
      error: network or validation error

func (*Client) Search

func (c *Client) Search(ctx context.Context, query string, params string, nonMusic bool) (*SearchResults, error)

Search queries YouTube or YouTube Music for matching tracks, playlists, and channels.

params:
      ctx: execution context
      query: term keywords
      params: optional search filter params
      nonMusic: search standard YouTube instead of YouTube Music
returns:
      *SearchResults: correction options and layouts partitioned by type categories
      error: network or parsing error

func (*Client) SendFeedback added in v1.2.0

func (c *Client) SendFeedback(ctx context.Context, tokens ...string) error

SendFeedback submits one or more feedback tokens.

It is exported because tokens are minted for more than library membership: liking, pinning, and other menu actions all ride the same endpoint. Callers who want a specific action should prefer the named helper, which reads the token for that action from a fresh /next response.

params:
      ctx: execution context
      tokens: feedback tokens to submit together
returns:
      error: network or parsing error

func (*Client) SetAuth

func (c *Client) SetAuth(auth *AuthState)

SetAuth configures the authentication state on the client.

params:
      auth: auth credential container

func (*Client) SetHL

func (c *Client) SetHL(hl string)

SetHL overrides the client's locale language setting.

params:
      hl: language tag (e.g. id-ID)

func (*Client) SetLogger added in v1.4.0

func (c *Client) SetLogger(l *slog.Logger)

SetLogger installs a logger for this client. A nil logger is ignored, so a caller can pass a value that may be nil without checking.

func (*Client) SetPlaylistSaved added in v1.8.0

func (c *Client) SetPlaylistSaved(ctx context.Context, playlistID string, saved bool) error

SetPlaylistSaved saves or removes a playlist (including album OLAK IDs) in the signed-in account's library.

func (*Client) SetSongInLibrary added in v1.2.0

func (c *Client) SetSongInLibrary(ctx context.Context, songID string, inLibrary bool) error

SetSongInLibrary adds or removes a song from the account library.

The endpoint does not take a video ID for this operation: it takes a feedback token that a /next response mints for that track and that account. So the call is two round trips: read the queue entry's library toggle, then submit the token matching the requested direction.

If the track is already in the requested state the call is a no-op and returns nil, which makes it safe to call idempotently.

params:
      ctx: execution context
      songID: YouTube track ID
      inLibrary: true to save, false to remove
returns:
      error: network, parsing, or ErrFeedbackTokenMissing

func (*Client) SetSongLiked

func (c *Client) SetSongLiked(ctx context.Context, songID string, liked SongLikedStatus) error

SetSongLiked updates the liked preference status of a track.

params:
      ctx: execution context
      songID: YouTube track ID
      liked: preference target (NEUTRAL, LIKED, DISLIKED)
returns:
      error: error if request or unmarshal failed

func (*Client) SetSubscribedToArtist

func (c *Client) SetSubscribedToArtist(ctx context.Context, artistID string, subscribed bool, subscribeChannelID string) error

SetSubscribedToArtist updates the subscription status to an artist channel.

params:
      ctx: execution context
      artistID: channel ID of the artist
      subscribed: true to subscribe, false to unsubscribe
      subscribeChannelID: optional specific subscription channel ID
returns:
      error: error if request or unmarshal failed

func (*Client) SetVisitorID

func (c *Client) SetVisitorID(id string)

SetVisitorID overrides the client's visitor ID token.

params:
      id: visitor ID token string

func (*Client) SignedIn added in v1.4.0

func (c *Client) SignedIn() bool

SignedIn reports whether the most recent response was produced for a signed-in account.

It answers true when nothing is known yet. An endpoint that does not echo the viewer state must not be mistaken for a dead session, so only a body that positively reports logged_in=0, or that offers a sign-in endpoint, flips this to false.

type ClientContext

type ClientContext struct {
	HL                string `json:"hl"`
	Platform          string `json:"platform,omitempty"`
	ClientName        string `json:"clientName"`
	ClientVersion     string `json:"clientVersion"`
	UserAgent         string `json:"userAgent,omitempty"`
	OsName            string `json:"osName,omitempty"`
	OsVersion         string `json:"osVersion,omitempty"`
	DeviceMake        string `json:"deviceMake,omitempty"`
	DeviceModel       string `json:"deviceModel,omitempty"`
	AcceptHeader      string `json:"acceptHeader,omitempty"`
	VisitorData       string `json:"visitorData,omitempty"`
	AndroidSDKVersion int    `json:"androidSdkVersion,omitempty"`

	// ClientID is the numeric X-YouTube-Client-Name value that pairs with
	// ClientName. It is not part of the request body, so it carries no JSON
	// tag. An empty value leaves the historical WEB_REMIX header in place,
	// which is what every preset other than VISIONOS still relies on.
	ClientID string `json:"-"`
}

ClientContext impersonates an InnerTube client context.

func GetContextAndroid

func GetContextAndroid(hl string) ClientContext

GetContextAndroid generates the Android YouTube app client context.

params:
      hl: language tag
returns:
      ClientContext: ANDROID client context

func GetContextAndroidMusic

func GetContextAndroidMusic(hl string) ClientContext

GetContextAndroidMusic generates the Android YouTube Music app client context.

params:
      hl: language tag
returns:
      ClientContext: ANDROID_MUSIC client context

func GetContextIOS

func GetContextIOS(hl string) ClientContext

GetContextIOS generates the iOS YouTube app client context.

params:
      hl: language tag
returns:
      ClientContext: IOS client context

func GetContextIOSMusic added in v1.6.0

func GetContextIOSMusic(hl string) ClientContext

GetContextIOSMusic generates the iOS YouTube Music app client context.

It is the profile that returns timed lyrics. The lyric browse endpoint answers this client with timedLyricsModel, a per-line cue range list; the desktop web client is answered with a plaintext description shelf instead, with no timing at all.

ClientVersion is load-bearing. Older iOS Music builds are refused with FAILED_PRECONDITION, so a stale version turns synced lyrics into a request error rather than degrading on its own. GetSongLyricsTimed falls back to the web client for that reason.

params:
      hl: language tag (e.g. en-GB)
returns:
      ClientContext: IOS_MUSIC client context

func GetContextMobile

func GetContextMobile(hl string) ClientContext

GetContextMobile generates the mobile browser music client context.

params:
      hl: language tag
returns:
      ClientContext: WEB_REMIX mobile client context

func GetContextVisionOS added in v1.2.0

func GetContextVisionOS(hl string) ClientContext

GetContextVisionOS generates the visionOS playback client context.

This is the profile that makes direct streaming possible. It is an unreleased YouTube client identity that YouTube still answers with plain, already-authorised media URLs: no signatureCipher, no PO token, and no SABR-only response. Those URLs stream a whole track with an ordinary ranged GET.

Two properties are load-bearing and easy to lose in a refactor:

  • The context must carry visitorData. Without it the endpoint answers LOGIN_REQUIRED. That is why this client is only usable after ensureVisitorID has run, which doInnerTube already does for every path except visitor_id.
  • ClientName is what selects the profile. The X-YouTube-Client-Name header does not have to match, but ClientID keeps it consistent.

It is a playback-only profile. Unlike WEB_REMIX it cannot browse, search, or carry a login, so catalogue and library calls must stay on WEB_REMIX.

params:
      hl: language tag
returns:
      ClientContext: VISIONOS client context

func GetContextWeb

func GetContextWeb(hl string) ClientContext

GetContextWeb generates the standard YouTube web client context.

params:
      hl: language tag
returns:
      ClientContext: WEB client context

func GetContextWebRemix

func GetContextWebRemix(hl string) ClientContext

GetContextWebRemix generates the desktop music web client context.

params:
      hl: language tag (e.g. en-GB)
returns:
      ClientContext: WEB_REMIX desktop client context

type CommandMetadata

type CommandMetadata struct {
	WebCommandMetadata struct {
		WebPageType string `json:"webPageType"`
	} `json:"webCommandMetadata"`
}

CommandMetadata stores web-specific platform type.

type Content

type Content struct {
	SectionListRenderer *SectionListRenderer `json:"sectionListRenderer,omitempty"`
	MusicQueueRenderer  *MusicQueueRenderer  `json:"musicQueueRenderer,omitempty"`
}

type Contents

type Contents struct {
	SingleColumnBrowseResultsRenderer *SingleColumnBrowseResultsRenderer `json:"singleColumnBrowseResultsRenderer,omitempty"`
	TwoColumnBrowseResultsRenderer    *TwoColumnBrowseResultsRenderer    `json:"twoColumnBrowseResultsRenderer,omitempty"`
}

type Continuation

type Continuation struct {
	NextContinuationData      *ContinuationData `json:"nextContinuationData,omitempty"`
	NextRadioContinuationData *ContinuationData `json:"nextRadioContinuationData,omitempty"`
}

func (Continuation) GetToken

func (c Continuation) GetToken() string

type ContinuationContents

type ContinuationContents struct {
	SectionListContinuation        *SectionListRenderer `json:"sectionListContinuation,omitempty"`
	MusicPlaylistShelfContinuation *MusicShelfRenderer  `json:"musicPlaylistShelfContinuation,omitempty"`
	MusicShelfContinuation         *MusicShelfRenderer  `json:"musicShelfContinuation,omitempty"`
	GridContinuation               *GridRenderer        `json:"gridContinuation,omitempty"`
}

type ContinuationData

type ContinuationData struct {
	Continuation string `json:"continuation"`
}

type ContinuationItemRenderer

type ContinuationItemRenderer struct {
	ContinuationEndpoint struct {
		ContinuationCommand struct {
			Token string `json:"token"`
		} `json:"continuationCommand"`
	} `json:"continuationEndpoint"`
}

ContinuationItemRenderer handles paginating items.

type ContinuationType

type ContinuationType string

ContinuationType categorizes standard continuation actions.

const (
	ContinuationSong          ContinuationType = "SONG"
	ContinuationPlaylist      ContinuationType = "PLAYLIST"
	ContinuationPlaylistInit  ContinuationType = "PLAYLIST_INITIAL"
	ContinuationArtistShuffle ContinuationType = "ARTIST_SHUFFLE"
	ContinuationMix           ContinuationType = "MIX"
)

type CreatePlaylistOptions added in v1.8.0

type CreatePlaylistOptions struct {
	Title       string
	Description string
	Privacy     PlaylistPrivacy // empty defaults to PlaylistPrivate
	VideoIDs    []string
}

CreatePlaylistOptions configures a new account playlist.

type DedupeMode added in v1.8.0

type DedupeMode int

DedupeMode controls how InnerTube handles songs already present in a playlist.

const (
	// DedupeAsk refuses the add and returns ErrDuplicates if any track is already in the playlist.
	DedupeAsk DedupeMode = iota
	// DedupeDrop skips tracks already in the playlist and adds only new ones.
	DedupeDrop
	// DedupeAdd skips the duplicate check and appends every track, even if already present.
	DedupeAdd
)

type DidYouMeanRenderer

type DidYouMeanRenderer struct {
	CorrectedQuery TextRuns `json:"correctedQuery"`
}

type EditorAdd

type EditorAdd struct {
	SongID string
}

EditorAdd adds a song to the playlist.

type EditorMove

type EditorMove struct{ From, To int }

EditorMove moves a song within the playlist.

type EditorRemove

type EditorRemove struct{ Index int }

EditorRemove removes a song by index.

type EditorSetDescription

type EditorSetDescription struct{ Description string }

EditorSetDescription updates the playlist description.

type EditorSetTitle

type EditorSetTitle struct{ Title string }

EditorSetTitle updates the playlist title.

type FeedLoadResult

type FeedLoadResult struct {
	Layouts      []MediaItemLayout `json:"layouts"`
	Continuation string            `json:"continuation,omitempty"`
	FilterChips  []FilterChip      `json:"filter_chips,omitempty"`
}

FeedLoadResult contains the parsed feed rows and next pagination tokens.

type FeedbackEndpoint added in v1.2.0

type FeedbackEndpoint struct {
	FeedbackToken string `json:"feedbackToken"`
}

FeedbackEndpoint carries the opaque token a /feedback submission needs. The token encodes the action, the target, and the account, so it cannot be constructed locally and must come from a fresh response.

type FilterChip

type FilterChip struct {
	Text   string `json:"text"`
	Params string `json:"params"`
}

FilterChip represents a tag/pill for filtering feeds.

type FixedColumn

type FixedColumn struct {
	MusicResponsiveListItemFixedColumnRenderer struct {
		Text *TextRuns `json:"text,omitempty"`
	} `json:"musicResponsiveListItemFixedColumnRenderer"`
}

type FlexColumn

type FlexColumn struct {
	MusicResponsiveListItemFlexColumnRenderer struct {
		Text *TextRuns `json:"text,omitempty"`
	} `json:"musicResponsiveListItemFlexColumnRenderer"`
}

type FlexInt added in v1.7.1

type FlexInt int

FlexInt unmarshals a JSON integer encoded as either a number (4) or a string ("4").

func (*FlexInt) UnmarshalJSON added in v1.7.1

func (f *FlexInt) UnmarshalJSON(b []byte) error

type GridRenderer

type GridRenderer struct {
	Items []YoutubeiShelfContentsItem `json:"items"`
	// Continuations carries the paging token for grid-backed lists such as the
	// library playlists, which page the grid rather than a music shelf.
	Continuations []Continuation `json:"continuations,omitempty"`
	Header        *struct {
		GridHeaderRenderer HeaderRenderer `json:"gridHeaderRenderer"`
	} `json:"header,omitempty"`
}

GridRenderer represents visual grids.

type Header struct {
	MusicCarouselShelfBasicHeaderRenderer     *HeaderRenderer                            `json:"musicCarouselShelfBasicHeaderRenderer,omitempty"`
	MusicImmersiveHeaderRenderer              *HeaderRenderer                            `json:"musicImmersiveHeaderRenderer,omitempty"`
	MusicVisualHeaderRenderer                 *HeaderRenderer                            `json:"musicVisualHeaderRenderer,omitempty"`
	MusicDetailHeaderRenderer                 *MusicDetailHeaderRenderer                 `json:"musicDetailHeaderRenderer,omitempty"`
	MusicEditablePlaylistDetailHeaderRenderer *MusicEditablePlaylistDetailHeaderRenderer `json:"musicEditablePlaylistDetailHeaderRenderer,omitempty"`
	MusicCardShelfHeaderBasicRenderer         *HeaderRenderer                            `json:"musicCardShelfHeaderBasicRenderer,omitempty"`
}

func (Header) GetRenderer

func (h Header) GetRenderer() *HeaderRenderer

type HeaderChips

type HeaderChips struct {
	ChipCloudRenderer struct {
		Chips []SearchChip `json:"chips"`
	} `json:"chipCloudRenderer"`
}

type HeaderRenderer

type HeaderRenderer struct {
	Title               *TextRuns           `json:"title,omitempty"`
	Strapline           *TextRuns           `json:"strapline,omitempty"`
	SubscriptionButton  *SubscriptionButton `json:"subscriptionButton,omitempty"`
	PlayButton          *MoreContentButton  `json:"playButton,omitempty"`
	Description         *TextRuns           `json:"description,omitempty"`
	Thumbnail           *Thumbnails         `json:"thumbnail,omitempty"`
	ForegroundThumbnail *Thumbnails         `json:"foregroundThumbnail,omitempty"`
	Subtitle            *TextRuns           `json:"subtitle,omitempty"`
	SecondSubtitle      *TextRuns           `json:"secondSubtitle,omitempty"`
	MoreContentButton   *MoreContentButton  `json:"moreContentButton,omitempty"`
}

HeaderRenderer represents general page or section titles.

func (*HeaderRenderer) GetThumbnails

func (h *HeaderRenderer) GetThumbnails() []Thumbnail

type InnerTubeError

type InnerTubeError struct {
	ResponseCode int
	Body         string
	Parsed       *APIError
}

InnerTubeError wraps HTTP status errors and parses APIError when available.

func (*InnerTubeError) Error

func (e *InnerTubeError) Error() string

type ItemCache

type ItemCache struct {
	// contains filtered or unexported fields
}

ItemCache stores retrieved metadata items.

func NewItemCache

func NewItemCache() *ItemCache

NewItemCache initializes a blank ItemCache.

returns:
      *ItemCache: newly allocated cache instance

func (*ItemCache) GetArtist

func (c *ItemCache) GetArtist(id string) (*Artist, bool)

GetArtist retrieves an artist by ID from cache.

params:
      id: artist channel ID
returns:
      *Artist: artist model if found, nil otherwise
      bool: true if found, false otherwise

func (*ItemCache) GetOrLoadArtist

func (c *ItemCache) GetOrLoadArtist(ctx context.Context, client *Client, id string) (*Artist, error)

GetOrLoadArtist attempts retrieval from cache before fetching from remote.

params:
      ctx: execution context
      client: API connection client
      id: artist channel ID
returns:
      *Artist: retrieved artist details
      error: network or parsing error

func (*ItemCache) GetOrLoadPlaylist

func (c *ItemCache) GetOrLoadPlaylist(ctx context.Context, client *Client, id string) (*Playlist, error)

GetOrLoadPlaylist attempts retrieval from cache before fetching from remote.

params:
      ctx: execution context
      client: API connection client
      id: playlist browse ID
returns:
      *Playlist: retrieved playlist details
      error: network or parsing error

func (*ItemCache) GetOrLoadSong

func (c *ItemCache) GetOrLoadSong(ctx context.Context, client *Client, id string) (*Song, error)

GetOrLoadSong attempts retrieval from cache before fetching from remote.

params:
      ctx: execution context
      client: API connection client
      id: YouTube video ID
returns:
      *Song: retrieved song details
      error: network or parsing error

func (*ItemCache) GetPlaylist

func (c *ItemCache) GetPlaylist(id string) (*Playlist, bool)

GetPlaylist retrieves a playlist by ID from cache.

params:
      id: playlist browse ID
returns:
      *Playlist: playlist model if found, nil otherwise
      bool: true if found, false otherwise

func (*ItemCache) GetSong

func (c *ItemCache) GetSong(id string) (*Song, bool)

GetSong retrieves a song by ID from cache.

params:
      id: YouTube video ID
returns:
      *Song: song model if found, nil otherwise
      bool: true if found, false otherwise

func (*ItemCache) StoreArtist

func (c *ItemCache) StoreArtist(a *Artist)

StoreArtist saves the artist details in memory.

params:
      a: artist model pointer

func (*ItemCache) StorePlaylist

func (c *ItemCache) StorePlaylist(p *Playlist)

StorePlaylist saves the playlist details in memory.

params:
      p: playlist model pointer

func (*ItemCache) StoreSong

func (c *ItemCache) StoreSong(s *Song)

StoreSong saves the song details in memory.

params:
      s: song model pointer

type ItemSectionRenderer

type ItemSectionRenderer struct {
	Contents []ItemSectionRendererContent `json:"contents"`
}

ItemSectionRenderer represents a general section containing list rows.

func (ItemSectionRenderer) GetMediaItems

func (r ItemSectionRenderer) GetMediaItems(hl string) []MediaItem

type ItemSectionRendererContent

type ItemSectionRendererContent struct {
	DidYouMeanRenderer              *DidYouMeanRenderer              `json:"didYouMeanRenderer,omitempty"`
	MusicResponsiveListItemRenderer *MusicResponsiveListItemRenderer `json:"musicResponsiveListItemRenderer,omitempty"`
	PlaylistVideoListRenderer       *PlaylistVideoListRenderer       `json:"playlistVideoListRenderer,omitempty"`
	VideoRenderer                   *VideoRenderer                   `json:"videoRenderer,omitempty"`
}

type LayoutType

type LayoutType string

LayoutType defines visual layouts for item lists.

const (
	LayoutTypeGrid         LayoutType = "GRID"
	LayoutTypeGridAlt      LayoutType = "GRID_ALT"
	LayoutTypeRow          LayoutType = "ROW"
	LayoutTypeList         LayoutType = "LIST"
	LayoutTypeNumberedList LayoutType = "NUMBERED_LIST"
	LayoutTypeCard         LayoutType = "CARD"
)

type LyricLine added in v1.6.0

type LyricLine struct {
	Text    string `json:"text"`
	StartMs int64  `json:"start_ms,omitempty"`
	EndMs   int64  `json:"end_ms,omitempty"`
}

LyricLine is one line of a lyric sheet.

StartMs and EndMs are zero when the endpoint returned the line without a cue range, which happens for tracks whose lyrics it has not timed. A line that carries only text is still a usable lyric line: it just cannot be followed.

type Lyrics added in v1.6.0

type Lyrics struct {
	Lines  []LyricLine `json:"lines,omitempty"`
	Synced bool        `json:"synced"`
}

Lyrics is the lyric sheet resolved for one track.

Synced reports that every line carries a cue range. It is false for a sheet that was only available as plain text, and for a timed sheet where the endpoint left a line untimed.

func (*Lyrics) PlainText added in v1.6.0

func (l *Lyrics) PlainText() string

PlainText joins the lines the way a plain lyric sheet reads. Blank lines and the instrumental markers the endpoint emits are dropped.

type MediaItem

type MediaItem interface {
	GetID() string
	GetName() string
	GetThumbnailProvider() *ThumbnailProvider
}

MediaItem represents a generic media item scraped from YouTube Music.

type MediaItemLayout

type MediaItemLayout struct {
	Items    []MediaItem `json:"items"`
	Title    string      `json:"title,omitempty"`
	Subtitle string      `json:"subtitle,omitempty"`
	ViewMore *PageRef    `json:"view_more,omitempty"`
	Type     LayoutType  `json:"type,omitempty"`
}

MediaItemLayout displays a generic list of media items.

type Menu struct {
	MenuRenderer struct {
		Items           []MenuItem       `json:"items"`
		TopLevelButtons []TopLevelButton `json:"topLevelButtons,omitempty"`
	} `json:"menuRenderer"`
}
type MenuItem struct {
	MenuNavigationItemRenderer    *MenuNavigationItemRenderer    `json:"menuNavigationItemRenderer,omitempty"`
	ToggleMenuServiceItemRenderer *ToggleMenuServiceItemRenderer `json:"toggleMenuServiceItemRenderer,omitempty"`
}
type MenuNavigationItemRenderer struct {
	Icon struct {
		IconType string `json:"iconType"`
	} `json:"icon"`
	NavigationEndpoint NavigationEndpoint `json:"navigationEndpoint"`
}

type Microformat

type Microformat struct {
	MicroformatDataRenderer struct {
		URLCanonical string `json:"urlCanonical"`
	} `json:"microformatDataRenderer"`
}

type MoreContentButton

type MoreContentButton struct {
	ButtonRenderer struct {
		NavigationEndpoint NavigationEndpoint `json:"navigationEndpoint"`
	} `json:"buttonRenderer"`
}

type MusicCardShelfHeaderBasicRenderer

type MusicCardShelfHeaderBasicRenderer struct {
	Title *TextRuns `json:"title,omitempty"`
}

type MusicCardShelfRenderer

type MusicCardShelfRenderer struct {
	Thumbnail *ThumbnailRenderer `json:"thumbnail,omitempty"`
	Title     TextRuns           `json:"title"`
	Subtitle  TextRuns           `json:"subtitle"`
	Menu      Menu               `json:"menu"`
	Header    struct {
		MusicCardShelfHeaderBasicRenderer *MusicCardShelfHeaderBasicRenderer `json:"musicCardShelfHeaderBasicRenderer,omitempty"`
	} `json:"header"`
}

func (*MusicCardShelfRenderer) GetMediaItem

func (c *MusicCardShelfRenderer) GetMediaItem() MediaItem

type MusicCarouselShelfRenderer

type MusicCarouselShelfRenderer struct {
	Header            *Header                     `json:"header,omitempty"`
	Contents          []YoutubeiShelfContentsItem `json:"contents"`
	NumItemsPerColumn *FlexInt                    `json:"numItemsPerColumn,omitempty"`
}

type MusicDescriptionShelfRenderer

type MusicDescriptionShelfRenderer struct {
	Description TextRuns  `json:"description"`
	Header      *TextRuns `json:"header,omitempty"`
}

type MusicDetailHeaderRenderer

type MusicDetailHeaderRenderer struct {
	Title              *TextRuns           `json:"title,omitempty"`
	Strapline          *TextRuns           `json:"strapline,omitempty"`
	SubscriptionButton *SubscriptionButton `json:"subscriptionButton,omitempty"`
	PlayButton         *MoreContentButton  `json:"playButton,omitempty"`
	Description        *TextRuns           `json:"description,omitempty"`
	Thumbnail          *Thumbnails         `json:"thumbnail,omitempty"`
	Subtitle           *TextRuns           `json:"subtitle,omitempty"`
	SecondSubtitle     *TextRuns           `json:"secondSubtitle,omitempty"`
	MoreContentButton  *MoreContentButton  `json:"moreContentButton,omitempty"`
	Menu               *Menu               `json:"menu,omitempty"`
}

type MusicEditablePlaylistDetailHeaderRenderer

type MusicEditablePlaylistDetailHeaderRenderer struct {
	Header struct {
		MusicResponsiveHeaderRenderer *MusicResponsiveHeaderRenderer `json:"musicResponsiveHeaderRenderer,omitempty"`
	} `json:"header"`
}

type MusicMultiRowListItemRenderer

type MusicMultiRowListItemRenderer struct {
	Title       TextRuns          `json:"title"`
	Subtitle    TextRuns          `json:"subtitle"`
	Thumbnail   ThumbnailRenderer `json:"thumbnail"`
	Menu        Menu              `json:"menu"`
	OnTap       *OnTap            `json:"onTap,omitempty"`
	SecondTitle *TextRuns         `json:"secondTitle,omitempty"`
}

MusicMultiRowListItemRenderer represents podcast show list items.

type MusicQueueRenderer

type MusicQueueRenderer struct {
	Content            *MusicQueueRendererContent `json:"content,omitempty"`
	SubHeaderChipCloud *SubHeaderChipCloud        `json:"subHeaderChipCloud,omitempty"`
}

type MusicQueueRendererContent

type MusicQueueRendererContent struct {
	PlaylistPanelRenderer PlaylistPanelRenderer `json:"playlistPanelRenderer"`
}

type MusicResponsiveHeaderRenderer

type MusicResponsiveHeaderRenderer struct {
	Title            *TextRuns `json:"title,omitempty"`
	StraplineTextOne *TextRuns `json:"straplineTextOne,omitempty"`
	Description      *struct {
		MusicDescriptionShelfRenderer MusicDescriptionShelfRenderer `json:"musicDescriptionShelfRenderer"`
	} `json:"description,omitempty"`
	Thumbnail *struct {
		MusicThumbnailRenderer *MusicThumbnailRenderer `json:"musicThumbnailRenderer,omitempty"`
	} `json:"thumbnail,omitempty"`
}

type MusicResponsiveListItemRenderer

type MusicResponsiveListItemRenderer struct {
	PlaylistItemData   *RendererPlaylistItemData `json:"playlistItemData,omitempty"`
	FlexColumns        []FlexColumn              `json:"flexColumns,omitempty"`
	FixedColumns       []FixedColumn             `json:"fixedColumns,omitempty"`
	Thumbnail          *ThumbnailRenderer        `json:"thumbnail,omitempty"`
	NavigationEndpoint *NavigationEndpoint       `json:"navigationEndpoint,omitempty"`
	Menu               *Menu                     `json:"menu,omitempty"`
	Index              *TextRuns                 `json:"index,omitempty"`
	Badges             []Badge                   `json:"badges,omitempty"`
}

MusicResponsiveListItemRenderer represents responsive items in lists.

func (*MusicResponsiveListItemRenderer) ParseItem

type MusicShelfRenderer

type MusicShelfRenderer struct {
	Title          *TextRuns                   `json:"title,omitempty"`
	Contents       []YoutubeiShelfContentsItem `json:"contents,omitempty"`
	Continuations  []Continuation              `json:"continuations,omitempty"`
	BottomEndpoint *NavigationEndpoint         `json:"bottomEndpoint,omitempty"`
}

type MusicThumbnailRenderer

type MusicThumbnailRenderer struct {
	Thumbnail struct {
		Thumbnails []Thumbnail `json:"thumbnails"`
	} `json:"thumbnail"`

	// Thumbnails is the queue-row shape. A playlist panel lists its stills one
	// level higher than the other renderers, so both shapes are read.
	Thumbnails []Thumbnail `json:"thumbnails"`
}

MusicThumbnailRenderer is the standard thumbnail image container.

func (MusicThumbnailRenderer) List added in v1.7.0

func (m MusicThumbnailRenderer) List() []Thumbnail

List returns the stills from whichever shape the response carried.

type MusicTwoRowItemRenderer

type MusicTwoRowItemRenderer struct {
	NavigationEndpoint NavigationEndpoint `json:"navigationEndpoint"`
	Title              TextRuns           `json:"title"`
	Subtitle           *TextRuns          `json:"subtitle,omitempty"`
	ThumbnailRenderer  ThumbnailRenderer  `json:"thumbnailRenderer"`
	Menu               *Menu              `json:"menu,omitempty"`
	SubtitleBadges     []Badge            `json:"subtitleBadges,omitempty"`
}

MusicTwoRowItemRenderer represents visual grid/row items.

type NavigationEndpoint struct {
	WatchEndpoint               *WatchEndpoint               `json:"watchEndpoint,omitempty"`
	BrowseEndpoint              *BrowseEndpoint              `json:"browseEndpoint,omitempty"`
	SearchEndpoint              *SearchEndpoint              `json:"searchEndpoint,omitempty"`
	WatchPlaylistEndpoint       *WatchPlaylistEndpoint       `json:"watchPlaylistEndpoint,omitempty"`
	ChannelCreationFormEndpoint *ChannelCreationFormEndpoint `json:"channelCreationFormEndpoint,omitempty"`
	CommandMetadata             *CommandMetadata             `json:"commandMetadata,omitempty"`
	QueueUpdateCommand          *QueueUpdateCommand          `json:"queueUpdateCommand,omitempty"`
}

NavigationEndpoint represents an action navigation routing in InnerTube.

func (ne NavigationEndpoint) GetMediaItem() MediaItem

type OnResponseReceivedAction

type OnResponseReceivedAction struct {
	AppendContinuationItemsAction *struct {
		ContinuationItems []YoutubeiShelfContentsItem `json:"continuationItems"`
	} `json:"appendContinuationItemsAction,omitempty"`
}

type OnTap

type OnTap struct {
	WatchEndpoint struct {
		WatchEndpointMusicSupportedConfigs struct {
			WatchEndpointMusicConfig struct {
				MusicVideoType string `json:"musicVideoType"`
			} `json:"watchEndpointMusicConfig"`
		} `json:"watchEndpointMusicSupportedConfigs"`
	} `json:"watchEndpoint"`
}

type PageRef

type PageRef struct {
	BrowseID     string `json:"browse_id"`
	BrowseParams string `json:"browse_params,omitempty"`
}

PageRef holds instructions to browse deeper into a resource.

type PlaybackTrackingResponse

type PlaybackTrackingResponse struct {
	PlaybackTracking struct {
		VideostatsPlaybackURL struct {
			BaseURL string `json:"baseUrl"`
		} `json:"videostatsPlaybackUrl"`
	} `json:"playbackTracking"`
}

type Playlist

type Playlist struct {
	ID              string               `json:"id"`
	Name            string               `json:"name,omitempty"`
	Description     string               `json:"description,omitempty"`
	Thumbnail       *ThumbnailProvider   `json:"thumbnail,omitempty"`
	Type            PlaylistType         `json:"type,omitempty"`
	Artists         []Artist             `json:"artists,omitempty"`
	Year            int                  `json:"year,omitempty"`
	Items           []Song               `json:"items,omitempty"`
	OwnerID         string               `json:"owner_id,omitempty"`
	Continuation    *BuiltInContinuation `json:"continuation,omitempty"`
	ItemSetIDs      []string             `json:"item_set_ids,omitempty"`
	ItemCount       int                  `json:"item_count,omitempty"`
	TotalDurationMs int64                `json:"total_duration_ms,omitempty"`
	PlaylistURL     string               `json:"playlist_url,omitempty"`
}

Playlist represents a collection of music tracks.

func (Playlist) GetID

func (p Playlist) GetID() string

func (Playlist) GetName

func (p Playlist) GetName() string

func (Playlist) GetThumbnailProvider

func (p Playlist) GetThumbnailProvider() *ThumbnailProvider

func (Playlist) Owned added in v1.8.0

func (p Playlist) Owned(channelID string) bool

Owned reports whether the playlist belongs to channelID.

type PlaylistEditAction

type PlaylistEditAction struct {
	Action                   PlaylistEditActionType `json:"action"`
	PlaylistName             string                 `json:"playlistName,omitempty"`
	PlaylistDescription      string                 `json:"playlistDescription,omitempty"`
	AddedVideoID             string                 `json:"addedVideoId,omitempty"`
	DedupeOption             string                 `json:"dedupeOption,omitempty"`
	SetVideoID               string                 `json:"setVideoId,omitempty"`
	MovedSetVideoIDSuccessor string                 `json:"movedSetVideoIdSuccessor,omitempty"`
	RemovedVideoID           string                 `json:"removedVideoId,omitempty"`
}

PlaylistEditAction represents a raw payload command for /browse/edit_playlist.

type PlaylistEditActionType

type PlaylistEditActionType string

PlaylistEditActionType describes InnerTube edit actions.

const (
	PlaylistEditActionSetName        PlaylistEditActionType = "ACTION_SET_PLAYLIST_NAME"
	PlaylistEditActionSetDescription PlaylistEditActionType = "ACTION_SET_PLAYLIST_DESCRIPTION"
	PlaylistEditActionAddVideo       PlaylistEditActionType = "ACTION_ADD_VIDEO"
	PlaylistEditActionMoveVideo      PlaylistEditActionType = "ACTION_MOVE_VIDEO_BEFORE"
	PlaylistEditActionRemoveVideo    PlaylistEditActionType = "ACTION_REMOVE_VIDEO"
)

type PlaylistEditor

type PlaylistEditor struct {
	// contains filtered or unexported fields
}

PlaylistEditor tracks playlist elements and updates them.

func (*PlaylistEditor) PerformAndCommitActions

func (e *PlaylistEditor) PerformAndCommitActions(ctx context.Context, actions []PlaylistEditorAction) error

PerformAndCommitActions runs a sequence of changes against the playlist.

params:
      ctx: execution context
      actions: slice of actions to apply
returns:
      error: network error or invalid index error

type PlaylistEditorAction

type PlaylistEditorAction interface {
	// contains filtered or unexported methods
}

PlaylistEditorAction is the interface for stateful playlist edit commands.

type PlaylistPanelRenderer

type PlaylistPanelRenderer struct {
	Contents      []ResponseRadioItem `json:"contents"`
	Continuations []Continuation      `json:"continuations,omitempty"`
}

type PlaylistPanelVideoRenderer

type PlaylistPanelVideoRenderer struct {
	VideoID        string                 `json:"videoId"`
	Title          TextRuns               `json:"title"`
	LongBylineText TextRuns               `json:"longBylineText"`
	Menu           Menu                   `json:"menu"`
	Thumbnail      MusicThumbnailRenderer `json:"thumbnail"`
	Badges         []Badge                `json:"badges,omitempty"`
	LengthText     *TextRuns              `json:"lengthText,omitempty"`
}

func (PlaylistPanelVideoRenderer) GetAlbum

func (vr PlaylistPanelVideoRenderer) GetAlbum() *Playlist

func (PlaylistPanelVideoRenderer) GetArtists

func (vr PlaylistPanelVideoRenderer) GetArtists() []Artist

func (PlaylistPanelVideoRenderer) LibraryToggle added in v1.2.0

func (vr PlaylistPanelVideoRenderer) LibraryToggle() (add, remove string, isToggled bool)

LibraryToggle returns the add and remove feedback tokens for a queue entry, and whether the track is currently saved.

type PlaylistPanelVideoWrapperRenderer

type PlaylistPanelVideoWrapperRenderer struct {
	PrimaryRenderer struct {
		PlaylistPanelVideoRenderer *PlaylistPanelVideoRenderer `json:"playlistPanelVideoRenderer,omitempty"`
	} `json:"primaryRenderer"`
}

type PlaylistPrivacy added in v1.8.0

type PlaylistPrivacy string

PlaylistPrivacy controls the visibility of a YouTube Music playlist.

const (
	PlaylistPrivate  PlaylistPrivacy = "PRIVATE"
	PlaylistUnlisted PlaylistPrivacy = "UNLISTED"
	PlaylistPublic   PlaylistPrivacy = "PUBLIC"
)

type PlaylistType

type PlaylistType string

PlaylistType categorizes playlist structures.

const (
	PlaylistTypePlaylist  PlaylistType = "PLAYLIST"
	PlaylistTypeAlbum     PlaylistType = "ALBUM"
	PlaylistTypeAudiobook PlaylistType = "AUDIOBOOK"
	PlaylistTypePodcast   PlaylistType = "PODCAST"
	PlaylistTypeRadio     PlaylistType = "RADIO"
)

type PlaylistVideoItem

type PlaylistVideoItem struct {
	PlaylistVideoRenderer VideoRenderer `json:"playlistVideoRenderer"`
}

type PlaylistVideoListRenderer

type PlaylistVideoListRenderer struct {
	Contents []PlaylistVideoItem `json:"contents"`
}

type QueueUpdateCommand

type QueueUpdateCommand struct {
	FetchContentsCommand struct {
		WatchEndpoint WatchEndpoint `json:"watchEndpoint"`
	} `json:"fetchContentsCommand"`
}

QueueUpdateCommand holds player queue additions.

type RadioBuilderArtist

type RadioBuilderArtist struct {
	Name      string    `json:"name"`
	Token     string    `json:"token"`
	Thumbnail Thumbnail `json:"thumbnail"`
}

RadioBuilderArtist represents an artist entity in the custom radio builder.

type RadioBuilderModifier

type RadioBuilderModifier string
const (
	ModifierArtist      RadioBuilderModifier = "ARTIST"
	ModifierLowVariety  RadioBuilderModifier = "rX"
	ModifierHighVariety RadioBuilderModifier = "rZ"
	ModifierFamiliar    RadioBuilderModifier = "iY"
	ModifierDiscover    RadioBuilderModifier = "iX"
	ModifierPopular     RadioBuilderModifier = "pY"
	ModifierHidden      RadioBuilderModifier = "pX"
	ModifierNew         RadioBuilderModifier = "dX"
	ModifierPumpUp      RadioBuilderModifier = "mY"
	ModifierChill       RadioBuilderModifier = "mX"
	ModifierUpbeat      RadioBuilderModifier = "mb"
	ModifierDownbeat    RadioBuilderModifier = "mc"
	ModifierFocus       RadioBuilderModifier = "ma"
)

func ModifierFromString

func ModifierFromString(s string) RadioBuilderModifier

type RadioChip

type RadioChip struct {
	ChipCloudChipRenderer struct {
		NavigationEndpoint struct {
			QueueUpdateCommand struct {
				FetchContentsCommand struct {
					WatchEndpoint WatchEndpoint `json:"watchEndpoint"`
				} `json:"fetchContentsCommand"`
			} `json:"queueUpdateCommand"`
		} `json:"navigationEndpoint"`
	} `json:"chipCloudChipRenderer"`
}

type RadioData

type RadioData struct {
	Items        []Song                   `json:"items"`
	Continuation string                   `json:"continuation,omitempty"`
	Filters      [][]RadioBuilderModifier `json:"filters,omitempty"`
}

type RelatedGroup

type RelatedGroup struct {
	Title       string      `json:"title"`
	Items       []MediaItem `json:"items,omitempty"`
	Description string      `json:"description,omitempty"`
}

RelatedGroup represents a section of related media items.

type RendererPlaylistItemData

type RendererPlaylistItemData struct {
	VideoID            string `json:"videoId"`
	PlaylistSetVideoID string `json:"playlistSetVideoId,omitempty"`
}

type ResponseContext added in v1.4.0

type ResponseContext struct {
	ServiceTrackingParams []ServiceTrackingParam `json:"serviceTrackingParams,omitempty"`
}

ResponseContext is the metadata every InnerTube response carries. Only the service tracking parameters are modelled, since they are the part callers read.

type ResponseRadioItem

type ResponseRadioItem struct {
	PlaylistPanelVideoRenderer        *PlaylistPanelVideoRenderer        `json:"playlistPanelVideoRenderer,omitempty"`
	PlaylistPanelVideoWrapperRenderer *PlaylistPanelVideoWrapperRenderer `json:"playlistPanelVideoWrapperRenderer,omitempty"`
}

func (ResponseRadioItem) GetRenderer

type SearchCategory

type SearchCategory struct {
	Layout       MediaItemLayout `json:"layout"`
	Filter       *SearchFilter   `json:"filter,omitempty"`
	Continuation string          `json:"continuation,omitempty"`
}

SearchCategory clusters search result layouts by category.

type SearchChip

type SearchChip struct {
	ChipCloudChipRenderer struct {
		NavigationEndpoint NavigationEndpoint `json:"navigationEndpoint"`
		Text               *TextRuns          `json:"text,omitempty"`
	} `json:"chipCloudChipRenderer"`
}

type SearchEndpoint

type SearchEndpoint struct {
	Query  string `json:"query"`
	Params string `json:"params,omitempty"`
}

SearchEndpoint represents a search target.

type SearchFilter

type SearchFilter struct {
	Type   SearchType `json:"type"`
	Params string     `json:"params"`
}

SearchFilter defines a filter target to search specific items.

type SearchResults

type SearchResults struct {
	Categories          []SearchCategory `json:"categories"`
	SuggestedCorrection string           `json:"suggested_correction,omitempty"`
	Chips               []Chip           `json:"chips,omitempty"`
}

SearchResults contains the parsed search response contents.

type SearchSuggestion

type SearchSuggestion struct {
	Query     string `json:"query"`
	IsHistory bool   `json:"is_history"`
}

SearchSuggestion represents a single query autocomplete suggestion.

type SearchType

type SearchType string

SearchType categorizes search filters.

const (
	SearchSong     SearchType = "SONG"
	SearchVideo    SearchType = "VIDEO"
	SearchPlaylist SearchType = "PLAYLIST"
	SearchAlbum    SearchType = "ALBUM"
	SearchArtist   SearchType = "ARTIST"
)

type SecondaryContents

type SecondaryContents struct {
	SectionListRenderer SectionListRenderer `json:"sectionListRenderer"`
}

type SectionListRenderer

type SectionListRenderer struct {
	Contents      []YoutubeiShelf `json:"contents,omitempty"`
	Header        *HeaderChips    `json:"header,omitempty"`
	Continuations []Continuation  `json:"continuations,omitempty"`
}

type ServiceEndpoint added in v1.2.0

type ServiceEndpoint struct {
	FeedbackEndpoint *FeedbackEndpoint `json:"feedbackEndpoint,omitempty"`
}

ServiceEndpoint is the command behind a menu entry. Only the feedback token is modelled: the other commands (queue, share) need their own request shapes and are not used by this package yet.

func (ServiceEndpoint) FeedbackToken added in v1.2.0

func (s ServiceEndpoint) FeedbackToken() string

FeedbackToken returns the token, or an empty string when this endpoint is not a feedback command.

type ServiceTrackingParam added in v1.4.0

type ServiceTrackingParam struct {
	Service string            `json:"service"`
	Params  []TrackingParamKV `json:"params,omitempty"`
}

ServiceTrackingParam is one tracking service and its key/value pairs.

type SingleColumnBrowseResultsRenderer

type SingleColumnBrowseResultsRenderer struct {
	Tabs []Tab `json:"tabs"`
}

type Song

type Song struct {
	ID              string             `json:"id"`
	Name            string             `json:"name,omitempty"`
	Description     string             `json:"description,omitempty"`
	Thumbnail       *ThumbnailProvider `json:"thumbnail,omitempty"`
	Artists         []Artist           `json:"artists,omitempty"`
	Type            SongType           `json:"type,omitempty"`
	IsExplicit      bool               `json:"is_explicit"`
	Album           *Playlist          `json:"album,omitempty"`
	DurationMs      int64              `json:"duration_ms,omitempty"`
	RelatedBrowseID string             `json:"related_browse_id,omitempty"`
	LyricsBrowseID  string             `json:"lyrics_browse_id,omitempty"`
}

Song represents a YouTube Music track.

func (Song) GetID

func (s Song) GetID() string

func (Song) GetName

func (s Song) GetName() string

func (Song) GetThumbnailProvider

func (s Song) GetThumbnailProvider() *ThumbnailProvider

type SongLikedStatus

type SongLikedStatus string

SongLikedStatus represents liking preference state.

const (
	SongLikedStatusNeutral  SongLikedStatus = "NEUTRAL"
	SongLikedStatusLiked    SongLikedStatus = "LIKED"
	SongLikedStatusDisliked SongLikedStatus = "DISLIKED"
)

type SongType

type SongType string

SongType categorizes track media types.

const (
	SongTypeSong    SongType = "SONG"
	SongTypeVideo   SongType = "VIDEO"
	SongTypePodcast SongType = "PODCAST"
)

type StreamFormat added in v1.2.0

type StreamFormat struct {
	// Itag is YouTube's format identifier (251 is the usual Opus music rung).
	Itag int `json:"itag"`
	// MimeType is the full MIME type, codecs parameter included, exactly as the
	// endpoint reported it.
	MimeType string `json:"mime_type"`
	// Codec is the coarse family derived from MimeType: "opus" or "aac".
	Codec AudioCodec `json:"codec"`
	// Bitrate is the average bitrate in bits per second.
	Bitrate int `json:"bitrate"`
	// SampleRate and Channels describe the decoded audio.
	SampleRate int `json:"sample_rate,omitempty"`
	Channels   int `json:"channels,omitempty"`
	// ContentLength is the byte size of the representation, or 0 when unknown.
	ContentLength int64 `json:"content_length,omitempty"`
	// URL is the signed media URL. It is already authorised for this client:
	// no signature cipher and no PO token apply.
	//
	// One gotcha travels with this URL: googlevideo throttles a GET that has no
	// Range header to roughly 32 KiB/s. Always request it with a Range, even
	// for the whole file ("bytes=0-"), which measured ~80x faster on the same
	// track. See cmd/e2e for the measured numbers.
	URL string `json:"url"`
	// ExpiresAt is when URL stops working. Signed URLs are also bound to the
	// requesting IP, so a cached StreamFormat is only reusable from the same
	// host and before this instant.
	ExpiresAt time.Time `json:"expires_at,omitempty"`
}

StreamFormat is one audio representation from a /player response.

It is a flat value type on purpose: it is serialised into caches and handed to a downloader, so it must not point back into the response tree.

func (StreamFormat) Expired added in v1.2.0

func (f StreamFormat) Expired(now time.Time) bool

Expired reports whether the signed URL is past its expiry. An unknown expiry (zero time) is treated as not expired, because the endpoint did not say.

type StreamOptions added in v1.2.0

type StreamOptions struct {
	// Codec selects the container/codec family. Empty means CodecAuto.
	Codec AudioCodec

	// MaxBitrate caps the chosen format in bits per second. Zero means no cap.
	// It is applied after the codec filter, so a cap never silently switches
	// the codec family.
	MaxBitrate int

	// ClientName overrides the impersonated playback client. Empty uses
	// VISIONOS, which is the profile that returns direct media URLs. It exists
	// so a caller can benchmark an alternative without editing this package.
	ClientName string

	// Video also resolves the video renditions. They are kept out of Formats
	// because a music player wants audio, and because an adaptive video track
	// carries no audio: playing one alone gives silence.
	Video bool

	// MaxHeight caps the chosen video resolution in pixels. Zero means no cap.
	// It only filters: a cap that would leave nothing is ignored.
	MaxHeight int

	// VideoCodec prefers a video family when Video is set. It ranks rather than
	// filters, so a codec the endpoint did not offer falls back to the best
	// available rendition instead of failing the call.
	//
	// Preferring H264 is the way to get hardware decoding on older GPUs: many
	// decoders, and WebKitGTK, have no VP9 or AV1 support. YouTube serves avc1
	// only up to 1080p, so asking for it caps the resolution there.
	VideoCodec VideoCodec
}

StreamOptions tunes stream resolution.

type Streams added in v1.2.0

type Streams struct {
	// VideoID is the track the formats belong to.
	VideoID string `json:"video_id"`
	// Title, Author and DurationMs come from videoDetails and are convenient
	// for a UI that has only an ID to start from.
	Title      string `json:"title,omitempty"`
	Author     string `json:"author,omitempty"`
	DurationMs int64  `json:"duration_ms,omitempty"`
	// HLSManifestURL is set when the endpoint offered an HLS master playlist.
	// It is a fallback transport, not the default: the direct URL is cheaper.
	HLSManifestURL string `json:"hls_manifest_url,omitempty"`
	// Formats are every audio format the endpoint returned, best first under
	// the requested preference. The selected one is Formats[0] when non-empty.
	Formats []StreamFormat `json:"formats,omitempty"`
	// VideoFormats is every video rendition, best first, and is only populated
	// when StreamOptions.Video was set.
	VideoFormats []VideoFormat `json:"video_formats,omitempty"`
}

Streams is the resolved playback information for one track.

func (*Streams) AudioFor added in v1.5.0

func (s *Streams) AudioFor(v VideoFormat) (StreamFormat, bool)

AudioFor returns the audio track that has to be played alongside a video rendition. A muxed rendition already carries its own audio, so it reports false and the caller plays it alone.

func (*Streams) Best added in v1.2.0

func (s *Streams) Best() (StreamFormat, bool)

Best returns the format selection settled on, which is the first entry.

func (*Streams) BestVideo added in v1.5.0

func (s *Streams) BestVideo() (VideoFormat, bool)

BestVideo returns the video rendition selection settled on, which is the first entry. It reports false when VideoFormats is empty.

type SubHeaderChipCloud

type SubHeaderChipCloud struct {
	ChipCloudRenderer struct {
		Chips []RadioChip `json:"chips"`
	} `json:"chipCloudRenderer"`
}

type SubscriptionButton

type SubscriptionButton struct {
	SubscribeButtonRenderer struct {
		Subscribed          bool     `json:"subscribed"`
		SubscriberCountText TextRuns `json:"subscriberCountText"`
		ChannelID           string   `json:"channelId"`
	} `json:"subscribeButtonRenderer"`
}

type Tab

type Tab struct {
	TabRenderer struct {
		Content  *Content             `json:"content,omitempty"`
		Endpoint *TabRendererEndpoint `json:"endpoint,omitempty"`
	} `json:"tabRenderer"`
}

type TabRendererEndpoint

type TabRendererEndpoint struct {
	BrowseEndpoint BrowseEndpoint `json:"browseEndpoint"`
}

type TextRun

type TextRun struct {
	Text               string              `json:"text"`
	NavigationEndpoint *NavigationEndpoint `json:"navigationEndpoint,omitempty"`
}

TextRun holds a single segment of text.

func (TextRun) PageType

func (tr TextRun) PageType() string

type TextRuns

type TextRuns struct {
	Runs []TextRun `json:"runs"`
}

TextRuns holds runs of formatted text.

func (TextRuns) FirstText

func (tr TextRuns) FirstText() string

func (TextRuns) FirstTextOrNull

func (tr TextRuns) FirstTextOrNull() *string

type Thumbnail

type Thumbnail struct {
	URL    string `json:"url"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
}

Thumbnail represents a single thumbnail image.

type ThumbnailProvider

type ThumbnailProvider struct {
	UrlA string  `json:"url_a"`
	UrlB *string `json:"url_b,omitempty"`
}

ThumbnailProvider resolves thumbnail URLs dynamically based on target size.

func NewThumbnailProvider

func NewThumbnailProvider(thumbnails []Thumbnail) *ThumbnailProvider

NewThumbnailProvider creates a ThumbnailProvider from a slice of Thumbnails.

params:
      thumbnails: a list of thumbnails with different sizes
returns:
      *ThumbnailProvider: resolved thumbnail provider, or nil if slice is empty

func NewThumbnailProviderFromURL

func NewThumbnailProviderFromURL(url string) *ThumbnailProvider

NewThumbnailProviderFromURL creates a simple static ThumbnailProvider from a URL.

params:
      url: image source URL
returns:
      *ThumbnailProvider: static thumbnail provider

func (*ThumbnailProvider) GetThumbnailURL

func (p *ThumbnailProvider) GetThumbnailURL(quality ThumbnailQuality) string

GetThumbnailURL resolves the URL for the requested quality.

params:
      quality: desired quality constraint (LOW, HIGH)
returns:
      string: resolved image URL

type ThumbnailQuality

type ThumbnailQuality string

ThumbnailQuality specifies the quality constraint for the thumbnail URL.

const (
	ThumbnailQualityLow  ThumbnailQuality = "LOW"
	ThumbnailQualityHigh ThumbnailQuality = "HIGH"
)

type ThumbnailRenderer

type ThumbnailRenderer struct {
	MusicThumbnailRenderer *MusicThumbnailRenderer `json:"musicThumbnailRenderer,omitempty"`
}

ThumbnailRenderer wraps MusicThumbnailRenderer.

func (ThumbnailRenderer) ToThumbnailProvider

func (tr ThumbnailRenderer) ToThumbnailProvider() *ThumbnailProvider

type Thumbnails

type Thumbnails struct {
	MusicThumbnailRenderer         *MusicThumbnailRenderer `json:"musicThumbnailRenderer,omitempty"`
	CroppedSquareThumbnailRenderer *MusicThumbnailRenderer `json:"croppedSquareThumbnailRenderer,omitempty"`
}

func (Thumbnails) GetThumbnails

func (t Thumbnails) GetThumbnails() []Thumbnail

type ToggleMenuServiceItemRenderer added in v1.2.0

type ToggleMenuServiceItemRenderer struct {
	DefaultText            TextRuns        `json:"defaultText"`
	ToggledText            TextRuns        `json:"toggledText"`
	DefaultServiceEndpoint ServiceEndpoint `json:"defaultServiceEndpoint"`
	ToggledServiceEndpoint ServiceEndpoint `json:"toggledServiceEndpoint"`
	IsToggled              bool            `json:"isToggled,omitempty"`
}

ToggleMenuServiceItemRenderer is a menu entry that flips between two states, such as library membership. The two texts name the actions, and the two service endpoints carry the tokens that perform them.

type TopLevelButton

type TopLevelButton struct {
	ButtonRenderer *struct {
		Icon *struct {
			IconType string `json:"iconType"`
		} `json:"icon,omitempty"`
		NavigationEndpoint *NavigationEndpoint `json:"navigationEndpoint,omitempty"`
	} `json:"buttonRenderer,omitempty"`
}

type TrackingParamKV added in v1.4.0

type TrackingParamKV struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

TrackingParamKV is a single key/value tracking parameter.

type TwoColumnBrowseResultsRenderer

type TwoColumnBrowseResultsRenderer struct {
	Tabs              []Tab              `json:"tabs"`
	SecondaryContents *SecondaryContents `json:"secondaryContents,omitempty"`
}

type VideoCodec added in v1.5.0

type VideoCodec string

VideoCodec names a video family a caller can ask for.

const (
	// VideoCodecAuto takes the highest resolution available, whatever family
	// that is. It is the zero value.
	VideoCodecAuto VideoCodec = ""
	// VideoCodecH264 is avc1, the family with the widest hardware and webview
	// support.
	VideoCodecH264 VideoCodec = "avc1"
	// VideoCodecVP9 is the WebM family YouTube serves at every resolution.
	VideoCodecVP9 VideoCodec = "vp9"
	// VideoCodecAV1 is the most efficient family, and the least widely
	// decodable in hardware.
	VideoCodecAV1 VideoCodec = "av01"
)

type VideoFormat added in v1.5.0

type VideoFormat struct {
	// Itag is YouTube's format identifier (137 is the usual 1080p H.264 rung).
	Itag int `json:"itag"`
	// MimeType is the full MIME type, codecs parameter included.
	MimeType string `json:"mime_type"`
	// Codec is the coarse family derived from MimeType: "vp9", "av01" or "avc1".
	Codec string `json:"codec"`
	// Width, Height and Fps describe the rendition.
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	Fps    int `json:"fps,omitempty"`
	// QualityLabel is the label the endpoint printed, such as "720p".
	QualityLabel string `json:"quality_label,omitempty"`
	// Bitrate is the average bitrate in bits per second.
	Bitrate int `json:"bitrate"`
	// ContentLength is the byte size of the representation, or 0 when unknown.
	ContentLength int64 `json:"content_length,omitempty"`
	// URL is the signed media URL, already authorised for this client.
	URL string `json:"url"`
	// ExpiresAt is when URL stops working.
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	// Muxed reports that this rendition also carries audio, so it plays on its
	// own. Every adaptive video track is video-only and needs a separate audio
	// stream alongside it.
	Muxed bool `json:"muxed,omitempty"`
}

VideoFormat is one video representation from a /player response.

func (VideoFormat) Expired added in v1.5.0

func (f VideoFormat) Expired(now time.Time) bool

Expired reports whether the signed URL is past its expiry.

type VideoRenderer

type VideoRenderer struct {
	VideoID         string             `json:"videoId"`
	Title           TextRuns           `json:"title"`
	ShortBylineText *TextRuns          `json:"shortBylineText,omitempty"`
	LongBylineText  *TextRuns          `json:"longBylineText,omitempty"`
	LengthSeconds   *string            `json:"lengthSeconds,omitempty"`
	IsPlayable      *bool              `json:"isPlayable,omitempty"`
	Thumbnail       *ThumbnailRenderer `json:"thumbnail,omitempty"`
}

func (VideoRenderer) GetSong

func (vr VideoRenderer) GetSong() *Song

type WatchEndpoint

type WatchEndpoint struct {
	VideoID    string `json:"videoId"`
	PlaylistID string `json:"playlistId,omitempty"`
}

WatchEndpoint represents a video playback target.

type WatchPlaylistEndpoint

type WatchPlaylistEndpoint struct {
	PlaylistID string `json:"playlistId"`
	Params     string `json:"params,omitempty"`
}

WatchPlaylistEndpoint represents playing a playlist.

type YoutubeiBrowseResponse

type YoutubeiBrowseResponse struct {
	ResponseContext           *ResponseContext           `json:"responseContext,omitempty"`
	Contents                  *Contents                  `json:"contents,omitempty"`
	ContinuationContents      *ContinuationContents      `json:"continuationContents,omitempty"`
	Header                    *Header                    `json:"header,omitempty"`
	Microformat               *Microformat               `json:"microformat,omitempty"`
	OnResponseReceivedActions []OnResponseReceivedAction `json:"onResponseReceivedActions,omitempty"`
	// contains filtered or unexported fields
}

YoutubeiBrowseResponse represents the complete page structure from browse endpoint.

func (*YoutubeiBrowseResponse) CToken

func (br *YoutubeiBrowseResponse) CToken() string

func (*YoutubeiBrowseResponse) GetHeaderChips

func (br *YoutubeiBrowseResponse) GetHeaderChips() []FilterChip

func (*YoutubeiBrowseResponse) GetShelves

func (br *YoutubeiBrowseResponse) GetShelves(hasContinuation bool) []YoutubeiShelf

func (*YoutubeiBrowseResponse) SignedIn added in v1.4.0

func (br *YoutubeiBrowseResponse) SignedIn() bool

SignedIn reports whether this response was produced for a signed-in viewer.

InnerTube answers a dead session with HTTP 200 and a page that offers a sign-in button, so the status code carries nothing here. The verdict comes from the body: the GFEEDBACK logged_in tracking parameter, or, when that is absent, the presence of a sign-in endpoint.

type YoutubeiNextContinuationResponse

type YoutubeiNextContinuationResponse struct {
	ContinuationContents struct {
		PlaylistPanelContinuation PlaylistPanelRenderer `json:"playlistPanelContinuation"`
	} `json:"continuationContents"`
}

type YoutubeiNextResponse

type YoutubeiNextResponse struct {
	Contents struct {
		SingleColumnMusicWatchNextResultsRenderer struct {
			TabbedRenderer struct {
				WatchNextTabbedResultsRenderer struct {
					Tabs []Tab `json:"tabs"`
				} `json:"watchNextTabbedResultsRenderer"`
			} `json:"tabbedRenderer"`
		} `json:"singleColumnMusicWatchNextResultsRenderer"`
	} `json:"contents"`
}

YoutubeiNextResponse represents the complete page structure from /next endpoint.

type YoutubeiShelf

type YoutubeiShelf struct {
	MusicShelfRenderer                        *MusicShelfRenderer                        `json:"musicShelfRenderer,omitempty"`
	MusicCarouselShelfRenderer                *MusicCarouselShelfRenderer                `json:"musicCarouselShelfRenderer,omitempty"`
	MusicDescriptionShelfRenderer             *MusicDescriptionShelfRenderer             `json:"musicDescriptionShelfRenderer,omitempty"`
	MusicPlaylistShelfRenderer                *MusicShelfRenderer                        `json:"musicPlaylistShelfRenderer,omitempty"`
	MusicCardShelfRenderer                    *MusicCardShelfRenderer                    `json:"musicCardShelfRenderer,omitempty"`
	MusicResponsiveHeaderRenderer             *MusicResponsiveHeaderRenderer             `json:"musicResponsiveHeaderRenderer,omitempty"`
	MusicEditablePlaylistDetailHeaderRenderer *MusicEditablePlaylistDetailHeaderRenderer `json:"musicEditablePlaylistDetailHeaderRenderer,omitempty"`
	GridRenderer                              *GridRenderer                              `json:"gridRenderer,omitempty"`
	ItemSectionRenderer                       *ItemSectionRenderer                       `json:"itemSectionRenderer,omitempty"`
	ContinuationItemRenderer                  *ContinuationItemRenderer                  `json:"continuationItemRenderer,omitempty"`
}

YoutubeiShelf represents visual groups of items.

func (YoutubeiShelf) Artist

func (s YoutubeiShelf) Artist() *Artist

func (YoutubeiShelf) Description

func (s YoutubeiShelf) Description() string

func (YoutubeiShelf) GetHeader

func (s YoutubeiShelf) GetHeader() *Header

func (YoutubeiShelf) GetMediaItems

func (s YoutubeiShelf) GetMediaItems(hl string) []MediaItem

func (YoutubeiShelf) GetMediaItemsAndSetIDs

func (s YoutubeiShelf) GetMediaItemsAndSetIDs(hl string) []struct {
	Item  MediaItem
	SetID string
}

func (YoutubeiShelf) GetNavigationEndpoint

func (s YoutubeiShelf) GetNavigationEndpoint() *NavigationEndpoint

func (YoutubeiShelf) GetRenderer

func (s YoutubeiShelf) GetRenderer() any

func (YoutubeiShelf) Thumbnails

func (s YoutubeiShelf) Thumbnails() []Thumbnail

func (YoutubeiShelf) Title

func (s YoutubeiShelf) Title() string

type YoutubeiShelfContentsItem

type YoutubeiShelfContentsItem struct {
	MusicTwoRowItemRenderer         *MusicTwoRowItemRenderer         `json:"musicTwoRowItemRenderer,omitempty"`
	MusicResponsiveListItemRenderer *MusicResponsiveListItemRenderer `json:"musicResponsiveListItemRenderer,omitempty"`
	MusicMultiRowListItemRenderer   *MusicMultiRowListItemRenderer   `json:"musicMultiRowListItemRenderer,omitempty"`
	ContinuationItemRenderer        *ContinuationItemRenderer        `json:"continuationItemRenderer,omitempty"`
}

YoutubeiShelfContentsItem holds the decoded row details inside shelves.

func (*YoutubeiShelfContentsItem) ParseItem

func (i *YoutubeiShelfContentsItem) ParseItem(hl string) (MediaItem, string)

Directories

Path Synopsis
cmd
e2e command
Command e2e prints the resolved stream for one track, then downloads it.
Command e2e prints the resolved stream for one track, then downloads it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址