Class YoutubeParsingHelper
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstatic final StringA parameter sent by official clients namedcontentCheckOk.static final StringA parameter sent by official clients namedcontentPlaybackNonce.static final StringA parameter to disable pretty-printed response of InnerTube requests, to reduce response sizes.static final Stringstatic final Stringstatic final StringA parameter which may be sent by official clients namedracyCheckOk.static final Stringstatic final Stringstatic final Stringstatic final StringThe base URL of requests of non-web clients to the InnerTube internal API.static final StringThe base URL of requests of theWEBclients to the InnerTube internal API. -
Method Summary
Modifier and TypeMethodDescriptionstatic voiddefaultAlertsCheck(com.grack.nanojson.JsonObject initialData) Shared alert detection function, multiple endpoints return the error similarly structured.static AudioTrackTypeextractAudioTrackType(String xtags) Extract the audio track type from the formats XTags.static StringSometimes, YouTube provides URLs which use Google's cache.static StringextractCookieValue(String cookieName, Response response) static PlaylistInfo.PlaylistTypeextractPlaylistTypeFromPlaylistId(String playlistId) static PlaylistInfo.PlaylistTypeextractPlaylistTypeFromPlaylistUrl(String playlistUrl) static StringextractVideoIdFromMixId(String playlistId) static StringfixThumbnailUrl(String thumbnailUrl) static Stringstatic StringGenerate a content playback nonce (also calledcpn), sent by YouTube clients in playback requests (and also for some clients, in the player request body).static StringTry to generate atparameter, sent by mobile clients as a query of the player request.getClientHeaders(String name, String version) Returns an unmodifiableMapcontaining theX-YouTube-Client-NameandX-YouTube-Client-Versionheaders.Returns aMapcontaining theX-YouTube-Client-Name,X-YouTube-Client-Version,Origin, andRefererheaders.static StringGet the client version used by YouTube website on InnerTube requests.Create a map with the required cookie header.static StringgetFeedUrlFrom(String channelIdOrUser) static com.grack.nanojson.JsonObjectgetFirstCollaborator(com.grack.nanojson.JsonObject navigationEndpoint) Gets the first collaborator, which is the channel that owns the video, i.e.getImagesFromThumbnailsArray(com.grack.nanojson.JsonArray thumbnails) Get images from a YouTubethumbnailsJsonArray.static com.grack.nanojson.JsonObjectgetJsonPostResponse(String endpoint, byte[] body, Localization localization) static com.grack.nanojson.JsonObjectgetJsonPostResponse(String endpoint, List<String> queryParameters, byte[] body, Localization localization) static StringgetTextAtKey(com.grack.nanojson.JsonObject jsonObject, String theKey) static StringgetTextFromObject(com.grack.nanojson.JsonObject textObject) static StringgetTextFromObject(com.grack.nanojson.JsonObject textObject, boolean html) Get the text from a JSON object that has either asimpleTextor arunsarray.static StringgetTextFromObjectOrThrow(com.grack.nanojson.JsonObject textObject, String error) getThumbnailsFromInfoItem(com.grack.nanojson.JsonObject infoItem) Get thumbnails from aJsonObjectrepresenting a YouTubeInfoItem.static StringgetUrlFromNavigationEndpoint(com.grack.nanojson.JsonObject navigationEndpoint) static StringgetUrlFromObject(com.grack.nanojson.JsonObject textObject) static StringgetValidJsonResponseBody(Response response) static StringgetVisionOsUserAgent(Localization localization) Get the user-agent string used as the user-agent for InnerTube requests with the visionOS client.static StringgetVisitorDataFromInnertube(InnertubeClientRequestInfo innertubeClientRequestInfo, Localization localization, ContentCountry contentCountry, Map<String, List<String>> httpHeaders, String innertubeDomainAndVersionEndpoint, String embedUrl, boolean useGuideEndpoint) Returns aMapcontaining the required YouTube headers, including theCONSENTcookie to prevent redirects toconsent.youtube.comstatic StringReturns aMapcontaining the required YouTube Music headers.static booleanhasArtistOrVerifiedIconBadgeAttachment(com.grack.nanojson.JsonArray attachmentRuns) static booleanGet the value of the consent's acceptance.static booleanisGoogleURL(String url) static booleanstatic booleanstatic booleanisInvidiousURL(URL url) static booleanisVerified(com.grack.nanojson.JsonArray badges) static booleanCheck if the streaming URL is a URL from the YouTubeVISIONOSclient.static booleanisWebStreamingUrl(String url) Check if the streaming URL is from the YouTubeWEBclient.static booleanisY2ubeURL(URL url) static booleanisYoutubeGenreMixId(String playlistId) Checks if the given playlist id is a YouTube Genre Mix (auto-generated playlist) Ids from a YouTube Genre Mix start with "RDGMEM"static booleanisYoutubeMixId(String playlistId) Checks if the given playlist id is a YouTube Mix (auto-generated playlist) Ids from a YouTube Mix start with "RD"static booleanisYoutubeMusicMixId(String playlistId) Checks if the given playlist id is a YouTube Music Mix (auto-generated playlist) Ids from a YouTube Music Mix start with "RDAMVM" or "RDCLAK"static booleanisYoutubeMyMixId(String playlistId) Checks if the given playlist id is a YouTube My Mix (auto-generated playlist) Ids from a YouTube My Mix start with "RDMM"static booleanisYoutubeServiceURL(URL url) static booleanisYoutubeURL(URL url) static intparseDurationString(String input) Parses the duration string of the video expecting ":" or "." as separatorsstatic com.grack.nanojson.JsonBuilder<com.grack.nanojson.JsonObject>prepareDesktopJsonBuilder(Localization localization, ContentCountry contentCountry) static com.grack.nanojson.JsonBuilder<com.grack.nanojson.JsonObject>prepareJsonBuilder(Localization localization, ContentCountry contentCountry, InnertubeClientRequestInfo innertubeClientRequestInfo, String embedUrl) static voidOnly used in tests.static voidsetConsentAccepted(boolean accepted) Determines how the consent cookie that is required for YouTube,SOCS, will be generated.static voidsetNumberGenerator(Random random) Only used in tests.
-
Field Details
-
YOUTUBEI_V1_URL
The base URL of requests of theWEBclients to the InnerTube internal API.- See Also:
-
YOUTUBEI_V1_GAPIS_URL
The base URL of requests of non-web clients to the InnerTube internal API.- See Also:
-
DISABLE_PRETTY_PRINT_PARAMETER
A parameter to disable pretty-printed response of InnerTube requests, to reduce response sizes.Sent in query parameters of the requests.
- See Also:
-
CPN
A parameter sent by official clients namedcontentPlaybackNonce.It is sent by official clients on videoplayback requests and InnerTube player requests in most cases.
It is composed of 16 characters which are generated from
this alphabet, with the use of strong random values. -
VIDEO_ID
- See Also:
-
CONTENT_CHECK_OK
A parameter sent by official clients namedcontentCheckOk.Setting it to
trueallows us to get streaming data on videos with a warning about what the sensible content they contain.- See Also:
-
RACY_CHECK_OK
A parameter which may be sent by official clients namedracyCheckOk.What this parameter does is not really known, but it seems to be linked to sensitive contents such as age-restricted content.
- See Also:
-
STYLE
- See Also:
-
METADATA_BADGE_RENDERER
- See Also:
-
LABEL
- See Also:
-
THUMBNAIL_OVERLAYS
- See Also:
-
BADGES
- See Also:
-
-
Method Details
-
isGoogleURL
-
isYoutubeURL
-
isYoutubeServiceURL
-
isInvidiousURL
-
isY2ubeURL
-
parseDurationString
public static int parseDurationString(@Nonnull String input) throws ParsingException, NumberFormatException Parses the duration string of the video expecting ":" or "." as separators- Returns:
- the duration in seconds
- Throws:
ParsingException- when more than 3 separators are foundNumberFormatException
-
getFeedUrlFrom
-
isYoutubeMixId
Checks if the given playlist id is a YouTube Mix (auto-generated playlist) Ids from a YouTube Mix start with "RD"- Parameters:
playlistId- the playlist id- Returns:
- Whether given id belongs to a YouTube Mix
-
isYoutubeMyMixId
Checks if the given playlist id is a YouTube My Mix (auto-generated playlist) Ids from a YouTube My Mix start with "RDMM"- Parameters:
playlistId- the playlist id- Returns:
- Whether given id belongs to a YouTube My Mix
-
isYoutubeMusicMixId
Checks if the given playlist id is a YouTube Music Mix (auto-generated playlist) Ids from a YouTube Music Mix start with "RDAMVM" or "RDCLAK"- Parameters:
playlistId- the playlist id- Returns:
- Whether given id belongs to a YouTube Music Mix
-
isYoutubeGenreMixId
Checks if the given playlist id is a YouTube Genre Mix (auto-generated playlist) Ids from a YouTube Genre Mix start with "RDGMEM"- Returns:
- Whether given id belongs to a YouTube Genre Mix
-
extractVideoIdFromMixId
- Parameters:
playlistId- the playlist id to parse- Returns:
- the
PlaylistInfo.PlaylistTypeextracted from the playlistId (mix playlist types included) - Throws:
ParsingException- if the playlistId is null or empty, if the playlistId is not a mix, if it is a mix but it's not based on a specific stream (this is the case for channel or genre mixes)
-
extractPlaylistTypeFromPlaylistId
@Nonnull public static PlaylistInfo.PlaylistType extractPlaylistTypeFromPlaylistId(String playlistId) throws ParsingException - Parameters:
playlistId- the playlist id to parse- Returns:
- the
PlaylistInfo.PlaylistTypeextracted from the playlistId (mix playlist types included) - Throws:
ParsingException- if the playlistId is null or empty
-
extractPlaylistTypeFromPlaylistUrl
public static PlaylistInfo.PlaylistType extractPlaylistTypeFromPlaylistUrl(String playlistUrl) throws ParsingException - Parameters:
playlistUrl- the playlist url to parse- Returns:
- the
PlaylistInfo.PlaylistTypeextracted from the playlistUrl's list param (mix playlist types included) - Throws:
ParsingException- if the playlistUrl is malformed, if has no list param or if the list param is empty
-
isHardcodedClientVersionValid
- Throws:
IOExceptionExtractionException
-
getClientVersion
Get the client version used by YouTube website on InnerTube requests.- Throws:
IOExceptionExtractionException
-
resetClientVersion
public static void resetClientVersion()Only used in tests.
Quick-and-dirty solution to reset global state in between test classes.
This is needed for the mocks because in order to reach that state a network request has to be made. If the global state is not reset and the RecordingDownloader is used, then only the first test class has that request recorded. Meaning running the other tests with mocks will fail, because the mock is missing.
-
setNumberGenerator
Only used in tests.
-
isHardcodedYoutubeMusicClientVersionValid
public static boolean isHardcodedYoutubeMusicClientVersionValid() throws IOException, ReCaptchaException- Throws:
IOExceptionReCaptchaException
-
getYoutubeMusicClientVersion
public static String getYoutubeMusicClientVersion() throws IOException, ReCaptchaException, Parser.RegexException -
getTextFromObject
@Nullable public static String getTextFromObject(com.grack.nanojson.JsonObject textObject, boolean html) Get the text from a JSON object that has either asimpleTextor arunsarray.- Parameters:
textObject- JSON object to get the text fromhtml- whether to return HTML, by parsing thenavigationEndpoint- Returns:
- text in the JSON object or
null
-
getTextFromObjectOrThrow
@Nonnull public static String getTextFromObjectOrThrow(com.grack.nanojson.JsonObject textObject, String error) throws ParsingException - Throws:
ParsingException
-
getTextFromObject
-
getUrlFromObject
-
getTextAtKey
-
fixThumbnailUrl
-
getThumbnailsFromInfoItem
@Nonnull public static List<Image> getThumbnailsFromInfoItem(@Nonnull com.grack.nanojson.JsonObject infoItem) throws ParsingException Get thumbnails from aJsonObjectrepresenting a YouTubeInfoItem.Thumbnails are got from the
thumbnailsJsonArrayinside thethumbnailJsonObjectof the YouTubeInfoItem, usinggetImagesFromThumbnailsArray(JsonArray).- Parameters:
infoItem- a YouTubeInfoItem- Returns:
- an unmodifiable list of
Images found in thethumbnailsJsonArray - Throws:
ParsingException- if an exception occurs whengetImagesFromThumbnailsArray(JsonArray)is executed
-
getImagesFromThumbnailsArray
@Nonnull public static List<Image> getImagesFromThumbnailsArray(@Nonnull com.grack.nanojson.JsonArray thumbnails) Get images from a YouTubethumbnailsJsonArray.The properties of the
Images created will be set using the corresponding ones of thumbnail items.- Parameters:
thumbnails- a YouTubethumbnailsJsonArray- Returns:
- an unmodifiable list of
Images extracted from the givenJsonArray
-
getValidJsonResponseBody
@Nonnull public static String getValidJsonResponseBody(@Nonnull Response response) throws ParsingException, MalformedURLException -
getJsonPostResponse
public static com.grack.nanojson.JsonObject getJsonPostResponse(@Nonnull String endpoint, byte[] body, @Nonnull Localization localization) throws IOException, ExtractionException - Throws:
IOExceptionExtractionException
-
getJsonPostResponse
public static com.grack.nanojson.JsonObject getJsonPostResponse(@Nonnull String endpoint, @Nonnull List<String> queryParameters, byte[] body, @Nonnull Localization localization) throws IOException, ExtractionException - Throws:
IOExceptionExtractionException
-
prepareDesktopJsonBuilder
@Nonnull public static com.grack.nanojson.JsonBuilder<com.grack.nanojson.JsonObject> prepareDesktopJsonBuilder(@Nonnull Localization localization, @Nonnull ContentCountry contentCountry) throws IOException, ExtractionException - Throws:
IOExceptionExtractionException
-
getVisionOsUserAgent
Get the user-agent string used as the user-agent for InnerTube requests with the visionOS client.If the
Localizationprovided isnull, fallbacks tothe default one.- Parameters:
localization- theLocalizationto set in the user-agent- Returns:
- the visionOS user-agent used for InnerTube requests with the visionOS client,
depending on the
Localizationprovided
-
getYoutubeMusicHeaders
Returns aMapcontaining the required YouTube Music headers. -
getYouTubeHeaders
Returns aMapcontaining the required YouTube headers, including theCONSENTcookie to prevent redirects toconsent.youtube.com- Throws:
ExtractionExceptionIOException
-
getClientInfoHeaders
public static Map<String,List<String>> getClientInfoHeaders() throws ExtractionException, IOExceptionReturns aMapcontaining theX-YouTube-Client-Name,X-YouTube-Client-Version,Origin, andRefererheaders.- Throws:
ExtractionExceptionIOException
-
getOriginReferrerHeaders
- Parameters:
url- The URL to be set as the origin and referrer.
-
getClientHeaders
public static Map<String,List<String>> getClientHeaders(@Nonnull String name, @Nonnull String version) Returns an unmodifiableMapcontaining theX-YouTube-Client-NameandX-YouTube-Client-Versionheaders.- Parameters:
name- The X-YouTube-Client-Name value.version- X-YouTube-Client-Version value.
-
getCookieHeader
Create a map with the required cookie header.- Returns:
- A singleton map containing the header.
-
generateConsentCookie
-
extractCookieValue
-
defaultAlertsCheck
public static void defaultAlertsCheck(@Nonnull com.grack.nanojson.JsonObject initialData) throws ParsingException Shared alert detection function, multiple endpoints return the error similarly structured.Will check if the object has an alert of the type "ERROR".
- Parameters:
initialData- the object which will be checked if an alert is present- Throws:
ContentNotAvailableException- if an alert is detectedParsingException
-
extractCachedUrlIfNeeded
Sometimes, YouTube provides URLs which use Google's cache. They look likehttps://webcache.googleusercontent.com/search?q=cache:CACHED_URL- Parameters:
url- the URL which might refer to the Google's webcache- Returns:
- the URL which is referring to the original site
-
isVerified
public static boolean isVerified(com.grack.nanojson.JsonArray badges) -
hasArtistOrVerifiedIconBadgeAttachment
public static boolean hasArtistOrVerifiedIconBadgeAttachment(@Nonnull com.grack.nanojson.JsonArray attachmentRuns) -
generateContentPlaybackNonce
Generate a content playback nonce (also calledcpn), sent by YouTube clients in playback requests (and also for some clients, in the player request body).- Returns:
- a content playback nonce string
-
generateTParameter
Try to generate atparameter, sent by mobile clients as a query of the player request.Some researches needs to be done to know how this parameter, unique at each request, is generated.
- Returns:
- a 12 characters string to try to reproduce the parameter
-
isWebStreamingUrl
Check if the streaming URL is from the YouTubeWEBclient.- Parameters:
url- the streaming URL to be checked.- Returns:
- true if it's a
WEBstreaming URL, false otherwise
-
isVisionOsStreamingUrl
Check if the streaming URL is a URL from the YouTubeVISIONOSclient.- Parameters:
url- the streaming URL on which check if it's aVISIONOSstreaming URL.- Returns:
- true if it's a
VISIONOSstreaming URL, false otherwise
-
setConsentAccepted
public static void setConsentAccepted(boolean accepted) Determines how the consent cookie that is required for YouTube,SOCS, will be generated.false(the default value) will useCAE=;truewill useCAISAiAD.
Setting this value to
trueis needed to extract mixes and some YouTube Music playlists in some countries such as the EU ones. -
isConsentAccepted
public static boolean isConsentAccepted()Get the value of the consent's acceptance.- Returns:
- the consent's acceptance value
- See Also:
-
extractAudioTrackType
Extract the audio track type from the formats XTags.Example:
acont=original, lang=en.- Parameters:
xtags- XTags of the audio track- Returns:
AudioTrackTypeornullif no track type was found
-
getVisitorDataFromInnertube
@Nonnull public static String getVisitorDataFromInnertube(@Nonnull InnertubeClientRequestInfo innertubeClientRequestInfo, @Nonnull Localization localization, @Nonnull ContentCountry contentCountry, @Nonnull Map<String, List<String>> httpHeaders, @Nonnull String innertubeDomainAndVersionEndpoint, @Nullable String embedUrl, boolean useGuideEndpoint) throws IOException, ExtractionException- Throws:
IOExceptionExtractionException
-
prepareJsonBuilder
@Nonnull public static com.grack.nanojson.JsonBuilder<com.grack.nanojson.JsonObject> prepareJsonBuilder(@Nonnull Localization localization, @Nonnull ContentCountry contentCountry, @Nonnull InnertubeClientRequestInfo innertubeClientRequestInfo, @Nullable String embedUrl) -
getFirstCollaborator
@Nullable public static com.grack.nanojson.JsonObject getFirstCollaborator(com.grack.nanojson.JsonObject navigationEndpoint) throws ParsingException Gets the first collaborator, which is the channel that owns the video, i.e. the video is displayed on their channel page.- Parameters:
navigationEndpoint- JSON object for the navigationEndpoint- Returns:
- The first collaborator in the JSON object or
null - Throws:
ParsingException
-