package org.schabi.newpipe.extractor.services.youtube.extractors; import com.grack.nanojson.JsonArray; import com.grack.nanojson.JsonObject; import com.grack.nanojson.JsonParser; import com.grack.nanojson.JsonParserException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.ScriptableObject; import org.schabi.newpipe.extractor.*; import org.schabi.newpipe.extractor.exceptions.ContentNotAvailableException; import org.schabi.newpipe.extractor.exceptions.ExtractionException; import org.schabi.newpipe.extractor.exceptions.ParsingException; import org.schabi.newpipe.extractor.exceptions.ReCaptchaException; import org.schabi.newpipe.extractor.linkhandler.LinkHandler; import org.schabi.newpipe.extractor.services.youtube.ItagItem; import org.schabi.newpipe.extractor.stream.*; import org.schabi.newpipe.extractor.utils.Localization; import org.schabi.newpipe.extractor.utils.Parser; import org.schabi.newpipe.extractor.utils.Utils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * Created by Christian Schabesberger on 06.08.15. * * Copyright (C) Christian Schabesberger 2019 * YoutubeStreamExtractor.java is part of NewPipe. * * NewPipe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * NewPipe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NewPipe. If not, see . */ public class YoutubeStreamExtractor extends StreamExtractor { private static final String TAG = YoutubeStreamExtractor.class.getSimpleName(); /*////////////////////////////////////////////////////////////////////////// // Exceptions //////////////////////////////////////////////////////////////////////////*/ public class DecryptException extends ParsingException { DecryptException(String message, Throwable cause) { super(message, cause); } } public class GemaException extends ContentNotAvailableException { GemaException(String message) { super(message); } } public class SubtitlesException extends ContentNotAvailableException { SubtitlesException(String message, Throwable cause) { super(message, cause); } } /*//////////////////////////////////////////////////////////////////////////*/ private Document doc; @Nullable private JsonObject playerArgs; @Nonnull private final Map videoInfoPage = new HashMap<>(); private JsonObject playerResponse; @Nonnull private List subtitlesInfos = new ArrayList<>(); private boolean isAgeRestricted; public YoutubeStreamExtractor(StreamingService service, LinkHandler linkHandler, Localization localization) { super(service, linkHandler, localization); } /*////////////////////////////////////////////////////////////////////////// // Impl //////////////////////////////////////////////////////////////////////////*/ @Nonnull @Override public String getName() throws ParsingException { assertPageFetched(); String name = getStringFromMetaData("title"); if(name == null) { // Fallback to HTML method try { name = doc.select("meta[name=title]").attr(CONTENT); } catch (Exception e) { throw new ParsingException("Could not get the title", e); } } if(name == null || name.isEmpty()) { throw new ParsingException("Could not get the title"); } return name; } @Nonnull @Override public String getUploadDate() throws ParsingException { assertPageFetched(); try { return doc.select("meta[itemprop=datePublished]").attr(CONTENT); } catch (Exception e) {//todo: add fallback method throw new ParsingException("Could not get upload date", e); } } @Nonnull @Override public String getThumbnailUrl() throws ParsingException { assertPageFetched(); // Try to get high resolution thumbnail first, if it fails, use low res from the player instead try { return doc.select("link[itemprop=\"thumbnailUrl\"]").first().attr("abs:href"); } catch (Exception ignored) { // Try other method... } try { if (playerArgs != null && playerArgs.isString("thumbnail_url")) return playerArgs.getString("thumbnail_url"); } catch (Exception ignored) { // Try other method... } try { return videoInfoPage.get("thumbnail_url"); } catch (Exception e) { throw new ParsingException("Could not get thumbnail url", e); } } @Nonnull @Override public String getDescription() throws ParsingException { assertPageFetched(); try { return parseHtmlAndGetFullLinks(doc.select("p[id=\"eow-description\"]").first().html()); } catch (Exception e) { throw new ParsingException("Could not get the description", e); } } // onclick="yt.www.watch.player.seekTo(0*3600+00*60+00);return false;" // :00 is NOT recognized as a timestamp in description or comments. // 0:00 is recognized in both description and comments. // https://www.youtube.com/watch?v=4cccfDXu1vA private final static Pattern DESCRIPTION_TIMESTAMP_ONCLICK_REGEX = Pattern.compile( "seekTo\\(" + "(?:(\\d+)\\*3600\\+)?" // hours? + "(\\d+)\\*60\\+" // minutes + "(\\d+)" // seconds + "\\)"); @SafeVarargs private static T coalesce(T... args) { for (T arg : args) { if (arg != null) return arg; } throw new IllegalArgumentException("all arguments to coalesce() were null"); } private String parseHtmlAndGetFullLinks(String descriptionHtml) throws MalformedURLException, UnsupportedEncodingException, ParsingException { final Document description = Jsoup.parse(descriptionHtml, getUrl()); for(Element a : description.select("a")) { final String rawUrl = a.attr("abs:href"); final URL redirectLink = new URL(rawUrl); final Matcher onClickTimestamp; final String queryString; if ((onClickTimestamp = DESCRIPTION_TIMESTAMP_ONCLICK_REGEX.matcher(a.attr("onclick"))) .find()) { a.removeAttr("onclick"); String hours = coalesce(onClickTimestamp.group(1), "0"); String minutes = onClickTimestamp.group(2); String seconds = onClickTimestamp.group(3); int timestamp = 0; timestamp += Integer.parseInt(hours) * 3600; timestamp += Integer.parseInt(minutes) * 60; timestamp += Integer.parseInt(seconds); String setTimestamp = "&t=" + timestamp; // Even after clicking https://youtu.be/...?t=6, // getUrl() is https://www.youtube.com/watch?v=..., never youtu.be, never &t=. a.attr("href", getUrl() + setTimestamp); } else if((queryString = redirectLink.getQuery()) != null) { // if the query string is null we are not dealing with a redirect link, // so we don't need to override it. final String link = Parser.compatParseMap(queryString).get("q"); if(link != null) { // if link is null the a tag is a hashtag. // They refer to the youtube search. We do not handle them. a.text(link); a.attr("href", link); } else if(redirectLink.toString().contains("https://www.youtube.com/")) { a.text(redirectLink.toString()); a.attr("href", redirectLink.toString()); } } else if(redirectLink.toString().contains("https://www.youtube.com/")) { descriptionHtml = descriptionHtml.replace(rawUrl, redirectLink.toString()); a.text(redirectLink.toString()); a.attr("href", redirectLink.toString()); } } return description.select("body").first().html(); } @Override public int getAgeLimit() throws ParsingException { assertPageFetched(); if (!isAgeRestricted) { return NO_AGE_LIMIT; } try { return Integer.valueOf(doc.select("meta[property=\"og:restrictions:age\"]") .attr(CONTENT).replace("+", "")); } catch (Exception e) { throw new ParsingException("Could not get age restriction"); } } @Override public long getLength() throws ParsingException { assertPageFetched(); // try getting duration from playerargs try { String durationMs = playerResponse .getObject("streamingData") .getArray("formats") .getObject(0) .getString("approxDurationMs"); return Long.parseLong(durationMs)/1000; } catch (Exception e) { } //try getting value from age gated video try { String duration = playerResponse .getObject("videoDetails") .getString("lengthSeconds"); return Long.parseLong(duration); } catch (Exception e) { throw new ParsingException("Every methode to get the duration has failed: ", e); } } /** * Attempts to parse (and return) the offset to start playing the video from. * * @return the offset (in seconds), or 0 if no timestamp is found. */ @Override public long getTimeStamp() throws ParsingException { return getTimestampSeconds("((#|&|\\?)t=\\d{0,3}h?\\d{0,3}m?\\d{1,3}s?)"); } @Override public long getViewCount() throws ParsingException { assertPageFetched(); try { return Long.parseLong(doc.select("meta[itemprop=interactionCount]").attr(CONTENT)); } catch (Exception e) {//todo: find fallback method throw new ParsingException("Could not get number of views", e); } } @Override public long getLikeCount() throws ParsingException { assertPageFetched(); String likesString = ""; try { Element button = doc.select("button.like-button-renderer-like-button").first(); try { likesString = button.select("span.yt-uix-button-content").first().text(); } catch (NullPointerException e) { //if this kicks in our button has no content and therefore likes/dislikes are disabled return -1; } return Integer.parseInt(Utils.removeNonDigitCharacters(likesString)); } catch (NumberFormatException nfe) { throw new ParsingException("Could not parse \"" + likesString + "\" as an Integer", nfe); } catch (Exception e) { throw new ParsingException("Could not get like count", e); } } @Override public long getDislikeCount() throws ParsingException { assertPageFetched(); String dislikesString = ""; try { Element button = doc.select("button.like-button-renderer-dislike-button").first(); try { dislikesString = button.select("span.yt-uix-button-content").first().text(); } catch (NullPointerException e) { //if this kicks in our button has no content and therefore likes/dislikes are disabled return -1; } return Integer.parseInt(Utils.removeNonDigitCharacters(dislikesString)); } catch (NumberFormatException nfe) { throw new ParsingException("Could not parse \"" + dislikesString + "\" as an Integer", nfe); } catch (Exception e) { throw new ParsingException("Could not get dislike count", e); } } @Nonnull @Override public String getUploaderUrl() throws ParsingException { assertPageFetched(); try { return doc.select("div[class=\"yt-user-info\"]").first().children() .select("a").first().attr("abs:href"); } catch (Exception e) { throw new ParsingException("Could not get channel link", e); } } @Nullable private String getStringFromMetaData(String field) { assertPageFetched(); String value = null; if(playerArgs != null) { // This can not fail value = playerArgs.getString(field); } if(value == null) { // This can not fail too value = videoInfoPage.get(field); } return value; } @Nonnull @Override public String getUploaderName() throws ParsingException { assertPageFetched(); String name = getStringFromMetaData("author"); if(name == null) { try { // Fallback to HTML method name = doc.select("div.yt-user-info").first().text(); } catch (Exception e) { throw new ParsingException("Could not get uploader name", e); } } if(name == null || name.isEmpty()) { throw new ParsingException("Could not get uploader name"); } return name; } @Nonnull @Override public String getUploaderAvatarUrl() throws ParsingException { assertPageFetched(); try { return doc.select("a[class*=\"yt-user-photo\"]").first() .select("img").first() .attr("abs:data-thumb"); } catch (Exception e) {//todo: add fallback method throw new ParsingException("Could not get uploader thumbnail URL.", e); } } @Nonnull @Override public String getDashMpdUrl() throws ParsingException { assertPageFetched(); try { String dashManifestUrl; if (videoInfoPage.containsKey("dashmpd")) { dashManifestUrl = videoInfoPage.get("dashmpd"); } else if (playerArgs != null && playerArgs.isString("dashmpd")) { dashManifestUrl = playerArgs.getString("dashmpd", ""); } else { return ""; } if (!dashManifestUrl.contains("/signature/")) { String encryptedSig = Parser.matchGroup1("/s/([a-fA-F0-9\\.]+)", dashManifestUrl); String decryptedSig; decryptedSig = decryptSignature(encryptedSig, decryptionCode); dashManifestUrl = dashManifestUrl.replace("/s/" + encryptedSig, "/signature/" + decryptedSig); } return dashManifestUrl; } catch (Exception e) { throw new ParsingException("Could not get dash manifest url", e); } } @Nonnull @Override public String getHlsUrl() throws ParsingException { assertPageFetched(); try { return playerResponse.getObject("streamingData").getString("hlsManifestUrl"); } catch (Exception e) { if (playerArgs != null && playerArgs.isString("hlsvp")) { return playerArgs.getString("hlsvp"); } else { throw new ParsingException("Could not get hls manifest url", e); } } } @Override public List getAudioStreams() throws ExtractionException { assertPageFetched(); List audioStreams = new ArrayList<>(); try { for (Map.Entry entry : getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.AUDIO).entrySet()) { ItagItem itag = entry.getValue(); AudioStream audioStream = new AudioStream(entry.getKey(), itag.getMediaFormat(), itag.avgBitrate); if (!Stream.containSimilarStream(audioStream, audioStreams)) { audioStreams.add(audioStream); } } } catch (Exception e) { throw new ParsingException("Could not get audio streams", e); } return audioStreams; } @Override public List getVideoStreams() throws ExtractionException { assertPageFetched(); List videoStreams = new ArrayList<>(); try { for (Map.Entry entry : getItags(FORMATS, ItagItem.ItagType.VIDEO).entrySet()) { ItagItem itag = entry.getValue(); VideoStream videoStream = new VideoStream(entry.getKey(), itag.getMediaFormat(), itag.resolutionString); if (!Stream.containSimilarStream(videoStream, videoStreams)) { videoStreams.add(videoStream); } } } catch (Exception e) { throw new ParsingException("Could not get video streams", e); } return videoStreams; } @Override public List getVideoOnlyStreams() throws ExtractionException { assertPageFetched(); List videoOnlyStreams = new ArrayList<>(); try { for (Map.Entry entry : getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.VIDEO_ONLY).entrySet()) { ItagItem itag = entry.getValue(); VideoStream videoStream = new VideoStream(entry.getKey(), itag.getMediaFormat(), itag.resolutionString, true); if (!Stream.containSimilarStream(videoStream, videoOnlyStreams)) { videoOnlyStreams.add(videoStream); } } } catch (Exception e) { throw new ParsingException("Could not get video only streams", e); } return videoOnlyStreams; } @Override @Nonnull public List getSubtitlesDefault() throws IOException, ExtractionException { return getSubtitles(MediaFormat.TTML); } @Override @Nonnull public List getSubtitles(final MediaFormat format) throws IOException, ExtractionException { assertPageFetched(); List subtitles = new ArrayList<>(); for (final SubtitlesInfo subtitlesInfo : subtitlesInfos) { subtitles.add(subtitlesInfo.getSubtitle(format)); } return subtitles; } @Override public StreamType getStreamType() throws ParsingException { assertPageFetched(); try { if (playerArgs != null && (playerArgs.has("ps") && playerArgs.get("ps").toString().equals("live") || (!playerResponse.getObject("streamingData").has(FORMATS)))) { return StreamType.LIVE_STREAM; } } catch (Exception e) { throw new ParsingException("Could not get hls manifest url", e); } return StreamType.VIDEO_STREAM; } @Override public StreamInfoItem getNextStream() throws IOException, ExtractionException { assertPageFetched(); try { StreamInfoItemsCollector collector = new StreamInfoItemsCollector(getServiceId()); Elements watch = doc.select("div[class=\"watch-sidebar-section\"]"); if (watch.size() < 1) { return null;// prevent the snackbar notification "report error" on age-restricted videos } collector.commit(extractVideoPreviewInfo(watch.first().select("li").first())); return collector.getItems().get(0); } catch (Exception e) { throw new ParsingException("Could not get next video", e); } } @Override public StreamInfoItemsCollector getRelatedStreams() throws IOException, ExtractionException { assertPageFetched(); try { StreamInfoItemsCollector collector = new StreamInfoItemsCollector(getServiceId()); Element ul = doc.select("ul[id=\"watch-related\"]").first(); if (ul != null) { for (Element li : ul.children()) { // first check if we have a playlist. If so leave them out if (li.select("a[class*=\"content-link\"]").first() != null) { collector.commit(extractVideoPreviewInfo(li)); } } } return collector; } catch (Exception e) { throw new ParsingException("Could not get related videos", e); } } /** * {@inheritDoc} */ @Override public String getErrorMessage() { StringBuilder errorReason; Element errorElement = doc.select("h1[id=\"unavailable-message\"]").first(); if (errorElement == null) { errorReason = null; } else { String errorMessage = errorElement.text(); if (errorMessage == null || errorMessage.isEmpty()) { errorReason = null; } else if (errorMessage.contains("GEMA")) { // Gema sometimes blocks youtube music content in germany: // https://www.gema.de/en/ // Detailed description: // https://en.wikipedia.org/wiki/GEMA_%28German_organization%29 errorReason = new StringBuilder("GEMA"); } else { errorReason = new StringBuilder(errorMessage); errorReason.append(" "); errorReason.append(doc.select("[id=\"unavailable-submessage\"]").first().text()); } } return errorReason != null ? errorReason.toString() : null; } /*////////////////////////////////////////////////////////////////////////// // Fetch page //////////////////////////////////////////////////////////////////////////*/ private static final String FORMATS = "formats"; private static final String ADAPTIVE_FORMATS = "adaptiveFormats"; private static final String HTTPS = "https:"; private static final String CONTENT = "content"; private static final String DECRYPTION_FUNC_NAME = "decrypt"; private static final String VERIFIED_URL_PARAMS = "&has_verified=1&bpctr=9999999999"; private final static String DECYRYPTION_SIGNATURE_FUNCTION_REGEX = "([\\w$]+)\\s*=\\s*function\\((\\w+)\\)\\{\\s*\\2=\\s*\\2\\.split\\(\"\"\\)\\s*;"; private final static String DECRYPTION_AKAMAIZED_STRING_REGEX = "yt\\.akamaized\\.net/\\)\\s*\\|\\|\\s*.*?\\s*c\\s*&&\\s*d\\.set\\([^,]+\\s*,\\s*(:encodeURIComponent\\s*\\()([a-zA-Z0-9$]+)\\("; private final static String DECRYPTION_AKAMAIZED_SHORT_STRING_REGEX = "\\bc\\s*&&\\s*d\\.set\\([^,]+\\s*,\\s*(:encodeURIComponent\\s*\\()([a-zA-Z0-9$]+)\\("; private volatile String decryptionCode = ""; private String pageHtml = null; private String getPageHtml(Downloader downloader) throws IOException, ExtractionException { final String verifiedUrl = getUrl() + VERIFIED_URL_PARAMS; if (pageHtml == null) { pageHtml = downloader.download(verifiedUrl); } return pageHtml; } @Override public void onFetchPage(@Nonnull Downloader downloader) throws IOException, ExtractionException { final String pageContent = getPageHtml(downloader); doc = Jsoup.parse(pageContent, getUrl()); final String playerUrl; // Check if the video is age restricted if (pageContent.contains(" getAvailableSubtitlesInfo() throws SubtitlesException { // If the video is age restricted getPlayerConfig will fail if(isAgeRestricted) return Collections.emptyList(); final JsonObject playerConfig; try { playerConfig = getPlayerConfig(getPageHtml(NewPipe.getDownloader())); } catch (IOException | ExtractionException e) { throw new SubtitlesException("Unable to download player configs", e); } final JsonObject captions; if (!playerResponse.has("captions")) { // Captions does not exist return Collections.emptyList(); } captions = playerResponse.getObject("captions"); final JsonObject renderer = captions.getObject("playerCaptionsTracklistRenderer", new JsonObject()); final JsonArray captionsArray = renderer.getArray("captionTracks", new JsonArray()); // todo: use this to apply auto translation to different language from a source language final JsonArray autoCaptionsArray = renderer.getArray("translationLanguages", new JsonArray()); // This check is necessary since there may be cases where subtitles metadata do not contain caption track info // e.g. https://www.youtube.com/watch?v=-Vpwatutnko final int captionsSize = captionsArray.size(); if(captionsSize == 0) return Collections.emptyList(); List result = new ArrayList<>(); for (int i = 0; i < captionsSize; i++) { final String languageCode = captionsArray.getObject(i).getString("languageCode"); final String baseUrl = captionsArray.getObject(i).getString("baseUrl"); final String vssId = captionsArray.getObject(i).getString("vssId"); if (languageCode != null && baseUrl != null && vssId != null) { final boolean isAutoGenerated = vssId.startsWith("a."); result.add(new SubtitlesInfo(baseUrl, languageCode, isAutoGenerated)); } } return result; } /*////////////////////////////////////////////////////////////////////////// // Data Class //////////////////////////////////////////////////////////////////////////*/ private class EmbeddedInfo { final String url; final String sts; EmbeddedInfo(final String url, final String sts) { this.url = url; this.sts = sts; } } private class SubtitlesInfo { final String cleanUrl; final String languageCode; final boolean isGenerated; public SubtitlesInfo(final String baseUrl, final String languageCode, final boolean isGenerated) { this.cleanUrl = baseUrl .replaceAll("&fmt=[^&]*", "") // Remove preexisting format if exists .replaceAll("&tlang=[^&]*", ""); // Remove translation language this.languageCode = languageCode; this.isGenerated = isGenerated; } public SubtitlesStream getSubtitle(final MediaFormat format) { return new SubtitlesStream(format, languageCode, cleanUrl + "&fmt=" + format.getSuffix(), isGenerated); } } /*////////////////////////////////////////////////////////////////////////// // Utils //////////////////////////////////////////////////////////////////////////*/ @Nonnull private static String getVideoInfoUrl(final String id, final String sts) { return "https://www.youtube.com/get_video_info?" + "video_id=" + id + "&eurl=https://youtube.googleapis.com/v/" + id + "&sts=" + sts + "&ps=default&gl=US&hl=en"; } private Map getItags(String streamingDataKey, ItagItem.ItagType itagTypeWanted) throws ParsingException { Map urlAndItags = new LinkedHashMap<>(); JsonObject streamingData = playerResponse.getObject("streamingData"); if (!streamingData.has(streamingDataKey)) { return urlAndItags; } JsonArray formats = streamingData.getArray(streamingDataKey); for (int i = 0; i != formats.size(); ++i) { JsonObject formatData = formats.getObject(i); int itag = formatData.getInt("itag"); if (ItagItem.isSupported(itag)) { try { ItagItem itagItem = ItagItem.getItag(itag); if (itagItem.itagType == itagTypeWanted) { String streamUrl; if (formatData.has("url")) { streamUrl = formatData.getString("url"); } else { // this url has an encrypted signature Map cipher = Parser.compatParseMap(formatData.getString("cipher")); streamUrl = cipher.get("url") + "&" + cipher.get("sp") + "=" + decryptSignature(cipher.get("s"), decryptionCode); } urlAndItags.put(streamUrl, itagItem); } } catch (UnsupportedEncodingException ignored) { } } } return urlAndItags; } /** * Provides information about links to other videos on the video page, such as related videos. * This is encapsulated in a StreamInfoItem object, which is a subset of the fields in a full StreamInfo. */ private StreamInfoItemExtractor extractVideoPreviewInfo(final Element li) { return new YoutubeStreamInfoItemExtractor(li) { @Override public String getUrl() throws ParsingException { return li.select("a.content-link").first().attr("abs:href"); } @Override public String getName() throws ParsingException { //todo: check NullPointerException causing return li.select("span.title").first().text(); //this page causes the NullPointerException, after finding it by searching for "tjvg": //https://www.youtube.com/watch?v=Uqg0aEhLFAg } @Override public String getUploaderName() throws ParsingException { return li.select("span[class*=\"attribution\"").first() .select("span").first().text(); } @Override public String getUploaderUrl() throws ParsingException { return ""; // The uploader is not linked } @Override public String getUploadDate() throws ParsingException { return ""; } @Override public long getViewCount() throws ParsingException { try { if (getStreamType() == StreamType.LIVE_STREAM) return -1; return Long.parseLong(Utils.removeNonDigitCharacters( li.select("span.view-count").first().text())); } catch (Exception e) { //related videos sometimes have no view count return 0; } } @Override public String getThumbnailUrl() throws ParsingException { Element img = li.select("img").first(); String thumbnailUrl = img.attr("abs:src"); // Sometimes youtube sends links to gif files which somehow seem to not exist // anymore. Items with such gif also offer a secondary image source. So we are going // to use that if we caught such an item. if (thumbnailUrl.contains(".gif")) { thumbnailUrl = img.attr("data-thumb"); } if (thumbnailUrl.startsWith("//")) { thumbnailUrl = HTTPS + thumbnailUrl; } return thumbnailUrl; } }; } @Nonnull @Override public List getFrames() throws ExtractionException { try { final String script = doc.select("#player-api").first().siblingElements().select("script").html(); int p = script.indexOf("ytplayer.config"); if (p == -1) { return Collections.emptyList(); } p = script.indexOf('{', p); int e = script.indexOf("ytplayer.load", p); if (e == -1) { return Collections.emptyList(); } JsonObject jo = JsonParser.object().from(script.substring(p, e - 1)); final String resp = jo.getObject("args").getString("player_response"); jo = JsonParser.object().from(resp); final String[] spec = jo.getObject("storyboards").getObject("playerStoryboardSpecRenderer").getString("spec").split("\\|"); final String url = spec[0]; final ArrayList result = new ArrayList<>(spec.length - 1); for (int i = 1; i < spec.length; ++i) { final String[] parts = spec[i].split("#"); if (parts.length != 8) { continue; } final int frameWidth = Integer.parseInt(parts[0]); final int frameHeight = Integer.parseInt(parts[1]); final int totalCount = Integer.parseInt(parts[2]); final int framesPerPageX = Integer.parseInt(parts[3]); final int framesPerPageY = Integer.parseInt(parts[4]); final String baseUrl = url.replace("$L", String.valueOf(i - 1)).replace("$N", parts[6]) + "&sigh=" + parts[7]; final List urls; if (baseUrl.contains("$M")) { final int totalPages = (int) Math.ceil(totalCount / (double) (framesPerPageX * framesPerPageY)); urls = new ArrayList<>(totalPages); for (int j = 0; j < totalPages; j++) { urls.add(baseUrl.replace("$M", String.valueOf(j))); } } else { urls = Collections.singletonList(baseUrl); } result.add(new Frameset( urls, frameWidth, frameHeight, totalCount, framesPerPageX, framesPerPageY )); } result.trimToSize(); return result; } catch (Exception e) { throw new ExtractionException(e); } } }