major migration part 5
- Commit
27fbae8d247b667016d9345f0de842b5c3685ac8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-31 21:30 UTC (4 months ago)
- Parents
e68e70f
Diff
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.ktindex eba1ad83cb..48faea3b37 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/GameBoard.kt@@ -64,6 +64,27 @@ fun GameBoard( }?.key } + val boardBounds = if (cellRects.isEmpty()) Rect.Zero else Rect(+ left = cellRects.values.minOf { it.left },+ top = cellRects.values.minOf { it.top },+ right = cellRects.values.maxOf { it.right },+ bottom = cellRects.values.maxOf { it.bottom }+ )++ // While dragging, a finger that leaves the board keeps driving the border+ // cell nearest to it, so the user doesn't have to come back inside to+ // continue the pipe.+ fun hitTestDrag(offset: Offset): CellPos? {+ hitTest(offset)?.let { return it }+ if (cellRects.isEmpty() || boardBounds.contains(offset)) return null+ return cellRects.entries.minWithOrNull(+ compareBy(+ { squaredDistanceToRect(it.value, offset) },+ { (it.value.center - offset).getDistanceSquared() }+ )+ )?.key+ }+ Canvas( modifier = Modifier .size(boardSize)@@ -80,7 +101,7 @@ fun GameBoard( if (cell != null) onStartDraw(cell) } event.changes.any { it.pressed } -> {- val cell = hitTest(pos)+ val cell = hitTestDrag(pos) if (cell != null) onExtendPath(cell) } event.changes.any { !it.pressed && it.previousPressed } -> {@@ -126,6 +147,12 @@ fun GameBoard( } } +private fun squaredDistanceToRect(rect: Rect, point: Offset): Float {+ val dx = maxOf(rect.left - point.x, 0f, point.x - rect.right)+ val dy = maxOf(rect.top - point.y, 0f, point.y - rect.bottom)+ return dx * dx + dy * dy+}+ private fun directionBetween(from: CellPos, to: CellPos): Direction? { return when { to.row < from.row -> Direction.UP
games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.ktindex de54c028b5..f5e2d9131f 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/util/PipesViewModel.kt@@ -100,20 +100,18 @@ class PipesViewModel(application: Application) : AndroidViewModel(application) { val endpointColor = levelData.endpoints.find { ep -> cell in ep.cells }?.colorIndex if (endpointColor != null) {- val currentPath = s.gameState.paths[endpointColor] ?: emptyList()- val activePath = when {- currentPath.isEmpty() -> listOf(cell)- currentPath.last() == cell -> currentPath- currentPath.first() == cell -> {- val ep = levelData.endpoints.find { it.colorIndex == endpointColor }- val isComplete = ep != null && currentPath.size >= 2 &&- setOf(currentPath.first(), currentPath.last()) == ep.cells.toSet()- if (!isComplete) return- currentPath.reversed()- }- else -> listOf(cell)+ // Grabbing an endpoint always restarts that color: its current line breaks+ // right away (like grabbing a line partway does) so the drag is free to take+ // a different route. Releasing without drawing leaves the line cleared.+ val brokenState = clearColor(s.gameState, endpointColor)+ _uiState.update {+ it.copy(+ activeColor = endpointColor,+ activePath = listOf(cell),+ gameState = brokenState,+ preDrawState = it.gameState+ ) }- _uiState.update { it.copy(activeColor = endpointColor, activePath = activePath, preDrawState = it.gameState) } return } @@ -125,6 +123,14 @@ class PipesViewModel(application: Application) : AndroidViewModel(application) { } } + /** Removes [color]'s line from the board, leaving every other color untouched. */+ private fun clearColor(state: PipesGameState, color: Int): PipesGameState {+ val path = state.paths[color] ?: return state+ val newCellOwner = state.cellOwner.toMutableMap()+ path.forEach { c -> if (newCellOwner[c] == color) newCellOwner.remove(c) }+ return PipesGameState(state.paths - color, newCellOwner)+ }+ fun extendPath(cell: CellPos) { val s = _uiState.value val activeColor = s.activeColor ?: return@@ -161,45 +167,13 @@ class PipesViewModel(application: Application) : AndroidViewModel(application) { if (cell in otherEndpoints) return val existingOwner = s.gameState.cellOwner[cell]- if (existingOwner != null && existingOwner != activeColor) {- if (cell in levelData.bridges) {- _uiState.update { it.copy(activePath = currentPath + cell) }- } else {- val newGameState = breakPipe(s.gameState, existingOwner, cell, levelData)- _uiState.update { it.copy(activePath = currentPath + cell, gameState = newGameState) }- }- } else {- _uiState.update { it.copy(activePath = currentPath + cell) }- }- }-- private fun breakPipe(state: PipesGameState, color: Int, collisionCell: CellPos, levelData: LevelData): PipesGameState {- val path = state.paths[color] ?: return state- val idx = path.indexOf(collisionCell)- if (idx < 0) return state-- val ep = levelData.endpoints.find { it.colorIndex == color }- val isComplete = ep != null && path.size >= 2 &&- setOf(path.first(), path.last()) == ep.cells.toSet()-- val kept = if (isComplete) {- val seg1 = path.take(idx)- val seg2 = path.drop(idx + 1)- if (seg1.size >= seg2.size) seg1 else seg2.reversed()- } else {- path.take(idx)+ if (existingOwner != null && existingOwner != activeColor && cell !in levelData.bridges) {+ // Occupied by another pipe: ignore the movement instead of breaking it.+ // The path stays put until the finger reaches an actually free neighbor.+ return } - val newPaths = state.paths.toMutableMap()- val newCellOwner = state.cellOwner.toMutableMap()- path.forEach { c -> if (newCellOwner[c] == color) newCellOwner.remove(c) }- if (kept.isNotEmpty()) {- newPaths[color] = kept- kept.forEach { newCellOwner[it] = color }- } else {- newPaths.remove(color)- }- return PipesGameState(newPaths, newCellOwner)+ _uiState.update { it.copy(activePath = currentPath + cell) } } fun commitDraw() {@@ -211,7 +185,19 @@ class PipesViewModel(application: Application) : AndroidViewModel(application) { val preDrawState = s.preDrawState ?: s.gameState if (newPath.size < 2) {- _uiState.update { it.copy(activeColor = null, activePath = emptyList(), gameState = preDrawState, preDrawState = null) }+ if (s.gameState != preDrawState) {+ // Tapped an endpoint without drawing: keep the line broken, but make it undoable.+ _uiState.update {+ it.copy(+ history = it.history + preDrawState,+ activeColor = null,+ activePath = emptyList(),+ preDrawState = null+ )+ }+ } else {+ _uiState.update { it.copy(activeColor = null, activePath = emptyList(), gameState = preDrawState, preDrawState = null) }+ } return }
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.ktindex 067e383a09..d1a21582f4 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/DragAndDrop.kt@@ -24,10 +24,14 @@ import androidx.compose.ui.zIndex import com.vayunmathur.games.solitaire.data.Card import com.vayunmathur.games.solitaire.util.SolitaireViewModel +/**+ * A card the player can pick up. [sourceId] identifies the pile position it comes from;+ * the cards the drag actually carries are derived from live game state by the view model,+ * so nothing here can go stale between recompositions.+ */ @Composable fun DraggableCard( card: Card,- cards: List<Card>, sourceId: String, viewModel: SolitaireViewModel, modifier: Modifier = Modifier,@@ -49,9 +53,8 @@ fun DraggableCard( .pointerInput(card, sourceId) { detectDragGestures( onDragStart = {- isDragging = true dragOffset = Offset.Zero- viewModel.startDrag(cards, sourceId, startPos)+ isDragging = viewModel.startDrag(sourceId, startPos) }, onDrag = { change, dragAmount -> change.consume()
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.ktindex acc9b4d9a4..9599c091e5 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/FoundationView.kt@@ -39,7 +39,6 @@ fun FreeCellSlot( if (card != null) { DraggableCard( card = card,- cards = listOf(card), sourceId = "freecell_$index", viewModel = viewModel, cardWidth = cardWidth,
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.ktindex f00ccd2e30..4214b116ea 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/KlondikeBoard.kt@@ -57,7 +57,6 @@ fun KlondikeBoard(state: KlondikeState, viewModel: SolitaireViewModel, modifier: if (isTop) { DraggableCard( card = card,- cards = listOf(card), sourceId = "waste", viewModel = viewModel, modifier = Modifier.offset(x = fanOffset * index),
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.ktindex 4aacbdecf4..709cc416fe 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/ui/TableauColumn.kt@@ -45,10 +45,8 @@ fun TableauColumn( } val faceDownOffset = FACE_DOWN_OVERLAP * pile.faceDown.size pile.faceUp.forEachIndexed { index, card ->- val cardsFromHere = pile.faceUp.subList(index, pile.faceUp.size) DraggableCard( card = card,- cards = cardsFromHere, sourceId = "tableau_${columnIndex}_$index", viewModel = viewModel, modifier = Modifier.offset(y = faceDownOffset + FACE_UP_OVERLAP * index),@@ -87,10 +85,8 @@ fun FreeCellTableauColumn( EmptySlot(cardWidth = cardWidth, cardHeight = cardHeight) } pile.forEachIndexed { index, card ->- val cardsFromHere = pile.subList(index, pile.size) DraggableCard( card = card,- cards = cardsFromHere, sourceId = "tableau_${columnIndex}_$index", viewModel = viewModel, modifier = Modifier.offset(y = FACE_UP_OVERLAP * index),
games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt
diff --git a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.ktindex 2d72891057..33ea51d24a 100644--- a/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt+++ b/games/solitaire/src/main/java/com/vayunmathur/games/solitaire/util/SolitaireViewModel.kt@@ -762,25 +762,56 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio // --- Shared --- - fun tryMoveByDrag(cards: List<Card>, sourceId: String, dropOffset: Offset) {+ /**+ * The cards a drag from [sourceId] carries, read from the live state rather than+ * from whatever the UI captured when the gesture was set up. Empty when the source+ * no longer holds a card (a stale slot), which is the signal not to start a drag.+ */+ private fun draggedCards(sourceId: String): List<Card> = with(_uiState.value) {+ when {+ sourceId == "waste" -> klondike?.waste?.lastOrNull()?.let { listOf(it) } ?: emptyList()+ sourceId.startsWith("freecell_") -> {+ val ci = sourceId.removePrefix("freecell_").toIntOrNull() ?: return emptyList()+ freeCell?.freeCells?.getOrNull(ci)?.let { listOf(it) } ?: emptyList()+ }+ sourceId.startsWith("tableau_") -> {+ val parts = sourceId.removePrefix("tableau_").split("_")+ val col = parts.getOrNull(0)?.toIntOrNull() ?: return emptyList()+ val idx = parts.getOrNull(1)?.toIntOrNull() ?: return emptyList()+ val faceUp = when (gameMode) {+ GameMode.KLONDIKE -> klondike?.tableauPiles?.getOrNull(col)?.faceUp+ GameMode.SPIDER -> spider?.tableauPiles?.getOrNull(col)?.faceUp+ GameMode.FREECELL -> freeCell?.tableauPiles?.getOrNull(col)+ else -> null+ } ?: return emptyList()+ if (idx in faceUp.indices) faceUp.subList(idx, faceUp.size) else emptyList()+ }+ else -> emptyList()+ }+ }++ /** A foundation only ever accepts a drag that carries the single top card. */+ private fun isSingleCardDrag(sourceId: String): Boolean = draggedCards(sourceId).size == 1++ fun tryMoveByDrag(sourceId: String, dropOffset: Offset) { val targetId = dropTargets.entries.find { (_, rect) -> rect.contains(dropOffset) }?.key ?: return when (_uiState.value.gameMode) {- GameMode.KLONDIKE -> handleKlondikeDrop(cards, sourceId, targetId)- GameMode.SPIDER -> handleSpiderDrop(cards, sourceId, targetId)- GameMode.FREECELL -> handleFreeCellDrop(cards, sourceId, targetId)+ GameMode.KLONDIKE -> handleKlondikeDrop(sourceId, targetId)+ GameMode.SPIDER -> handleSpiderDrop(sourceId, targetId)+ GameMode.FREECELL -> handleFreeCellDrop(sourceId, targetId) GameMode.PYRAMID -> {} // Pyramid is tap-based, not drag-based. null -> {} } } - private fun handleKlondikeDrop(cards: List<Card>, sourceId: String, targetId: String) {+ private fun handleKlondikeDrop(sourceId: String, targetId: String) { when { targetId.startsWith("foundation_") -> { val fi = targetId.removePrefix("foundation_").toInt()- if (cards.size == 1) {+ if (isSingleCardDrag(sourceId)) { when { sourceId == "waste" -> klondikeMoveWasteToFoundation(fi) sourceId.startsWith("tableau_") -> {@@ -805,7 +836,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio } } - private fun handleSpiderDrop(cards: List<Card>, sourceId: String, targetId: String) {+ private fun handleSpiderDrop(sourceId: String, targetId: String) { if (!targetId.startsWith("tableau_") || !sourceId.startsWith("tableau_")) return val toCol = targetId.removePrefix("tableau_").toInt() val parts = sourceId.removePrefix("tableau_").split("_")@@ -814,7 +845,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio spiderMoveCards(fromCol, cardIdx, toCol) } - private fun handleFreeCellDrop(cards: List<Card>, sourceId: String, targetId: String) {+ private fun handleFreeCellDrop(sourceId: String, targetId: String) { when { targetId.startsWith("freecell_") -> { val ci = targetId.removePrefix("freecell_").toInt()@@ -825,7 +856,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio } targetId.startsWith("foundation_") -> { val fi = targetId.removePrefix("foundation_").toInt()- if (cards.size == 1) {+ if (isSingleCardDrag(sourceId)) { when { sourceId.startsWith("freecell_") -> { val ci = sourceId.removePrefix("freecell_").toInt()@@ -856,8 +887,18 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio } } - fun startDrag(cards: List<Card>, sourceId: String, startPos: Offset = Offset.Zero) {+ /**+ * Starts a drag from [sourceId], deriving the carried cards from current state.+ * Returns false (and starts nothing) when that source holds no card.+ */+ fun startDrag(sourceId: String, startPos: Offset = Offset.Zero): Boolean {+ val cards = draggedCards(sourceId)+ if (cards.isEmpty()) {+ _dragInfo.value = null+ return false+ } _dragInfo.value = DragInfo(cards, sourceId, startPos, startPos)+ return true } fun updateDrag(offset: Offset) {@@ -866,7 +907,7 @@ class SolitaireViewModel(application: Application) : AndroidViewModel(applicatio fun endDrag(dropOffset: Offset) { val info = _dragInfo.value ?: return- tryMoveByDrag(info.cards, info.sourceId, dropOffset)+ tryMoveByDrag(info.sourceId, dropOffset) _dragInfo.value = null }
messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.java
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.java b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.javadeleted file mode 100644index 345d36f13a..0000000000--- a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.java+++ /dev/null@@ -1,22 +0,0 @@-package com.vayunmathur.messages.signal.receiving;--import org.signal.libsignal.internal.Native;-import org.signal.libsignal.protocol.state.IdentityKeyStore;--/**- * Bridges to libsignal's {@code SealedSessionCipher_DecryptToUsmc} native binding.- *- * <p>libsignal 0.86.5 has no public {@code SealedSessionCipher.decryptToUsmc()} method; the only- * way to recover the {@code UnidentifiedSenderMessageContent} (and therefore the inner ciphertext- * type and content hint) is the {@code org.signal.libsignal.internal.Native} binding, which is- * marked Kotlin-{@code internal} and so cannot be referenced from Kotlin. Java interop does not- * enforce Kotlin's {@code internal} visibility, so this thin Java shim exposes it to- * {@code EnvelopeDecryptor}. // UNVERIFIED: relies on an internal libsignal binding.- */-final class SealedSenderUnwrap {- private SealedSenderUnwrap() {}-- static long decryptToUsmc(byte[] ciphertext, IdentityKeyStore identityStore) throws Exception {- return Native.SealedSessionCipher_DecryptToUsmc(ciphertext, identityStore);- }-}
messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.kt
diff --git a/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.kt b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.ktnew file mode 100644index 0000000000..35776b9003--- /dev/null+++ b/messages/src/main/java/com/vayunmathur/messages/signal/receiving/SealedSenderUnwrap.kt@@ -0,0 +1,30 @@+@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")++package com.vayunmathur.messages.signal.receiving++import org.signal.libsignal.internal.Native+import org.signal.libsignal.protocol.state.IdentityKeyStore++/**+ * Bridges to libsignal's `SealedSessionCipher_DecryptToUsmc` native binding.+ *+ * libsignal 0.86.5 has no public `SealedSessionCipher.decryptToUsmc()` method; the only way to+ * recover the `UnidentifiedSenderMessageContent` (and therefore the inner ciphertext type and+ * content hint) is the `org.signal.libsignal.internal.Native` binding.+ *+ * `Native` is declared `internal` in libsignal's own Kotlin sources, so it is not normally visible+ * from another module. The file-level `@Suppress` above is the standard escape hatch: the JVM+ * class and method are both public (verified with javap — an `internal` *class* does not get its+ * public members name-mangled), so the emitted call site is an ordinary `invokestatic`.+ *+ * Note the compiler warns that suppressing `INVISIBLE_REFERENCE` is unspecified behaviour and may+ * stop working in a future Kotlin release. If it ever does, reverting this file to a small Java+ * shim restores it, since Java interop does not enforce Kotlin's `internal`.+ * // UNVERIFIED: relies on an internal libsignal binding.+ */+internal object SealedSenderUnwrap {++ @Throws(Exception::class)+ fun decryptToUsmc(ciphertext: ByteArray, identityStore: IdentityKeyStore): Long =+ Native.SealedSessionCipher_DecryptToUsmc(ciphertext, identityStore)+}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeDescriptionHelper.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeDescriptionHelper.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeDescriptionHelper.javadeleted file mode 100644index 0b3bf13bc8..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeDescriptionHelper.java+++ /dev/null@@ -1,328 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getUrlFromNavigationEndpoint;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isYoutubeServiceURL;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isYoutubeURL;-import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;--import com.grack.nanojson.JsonObject;--import org.jsoup.nodes.Entities;--import java.net.MalformedURLException;-import java.net.URL;-import java.util.ArrayList;-import java.util.Collections;-import java.util.Comparator;-import java.util.List;-import java.util.Stack;-import java.util.function.Function;-import java.util.regex.Matcher;-import java.util.regex.Pattern;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;--public final class YoutubeDescriptionHelper {-- private YoutubeDescriptionHelper() {- }-- private static final String LINK_CLOSE = "</a>";- private static final String STRIKETHROUGH_OPEN = "<s>";- private static final String STRIKETHROUGH_CLOSE = "</s>";- private static final String BOLD_OPEN = "<b>";- private static final String BOLD_CLOSE = "</b>";- private static final String ITALIC_OPEN = "<i>";- private static final String ITALIC_CLOSE = "</i>";-- // special link chips (e.g. for YT videos, YT channels or social media accounts):- // (u00a0) u00a0 u00a0 [/•] u00a0 <link content> u00a0 u00a0- private static final Pattern LINK_CONTENT_CLEANER_REGEX- = Pattern.compile("(?s)^ +[/•] +(.*?) +$");-- /**- * Can be a command run, or a style run.- */- static final class Run {- @Nonnull final String open;- @Nonnull final String close;- final int pos;- @Nullable final Function<String, String> transformContent;- int openPosInOutput = -1;-- Run(- @Nonnull final String open,- @Nonnull final String close,- final int pos- ) {- this(open, close, pos, null);- }-- Run(- @Nonnull final String open,- @Nonnull final String close,- final int pos,- @Nullable final Function<String, String> transformContent- ) {- this.open = open;- this.close = close;- this.pos = pos;- this.transformContent = transformContent;- }-- public boolean sameOpen(@Nonnull final Run other) {- return open.equals(other.open);- }- }-- /**- * Parse a video description in the new "attributed" format, which contains the entire visible- * plaintext ({@code content}) and an array of {@code commandRuns} and {@code styleRuns}.- * Returns the formatted content in HTML format, and escapes the text to make sure there are no- * XSS attacks.- *- * <p>- * {@code commandRuns} include the links and their range in the text, while {@code styleRuns}- * include the styling to apply to various ranges in the text.- * </p>- *- * @param attributedDescription the JSON object of the attributed description- * @return the parsed description, in HTML format, as a string- */- @Nullable- public static String attributedDescriptionToHtml(- @Nullable final JsonObject attributedDescription- ) {- if (isNullOrEmpty(attributedDescription)) {- return null;- }-- final String content = attributedDescription.getString("content");- if (content == null) {- return null;- }-- // all run pairs must always of length at least 1, or they should be discarded,- // otherwise various assumptions made in runsToHtml may fail- final List<Run> openers = new ArrayList<>();- final List<Run> closers = new ArrayList<>();- addAllCommandRuns(attributedDescription, openers, closers);- addAllStyleRuns(attributedDescription, openers, closers);-- // Note that sorting this way might put closers with the same close position in the wrong- // order with respect to their openers, causing unnecessary closes and reopens. E.g.- // <b>b<i>b&i</i></b> is instead generated as <b>b<i>b&i</b></i><b></b> if the </b> is- // encountered before the </i>. Solving this wouldn't be difficult, thanks to stable sort,- // but would require additional sorting steps which would just make this slower for the- // general case where it's unlikely there are coincident closes.- Collections.sort(openers, Comparator.comparingInt(run -> run.pos));- Collections.sort(closers, Comparator.comparingInt(run -> run.pos));-- return runsToHtml(openers, closers, content);- }-- /**- * Applies the formatting specified by the intervals stored in {@code openers} and {@code- * closers} to {@code content} in order to obtain valid HTML even when intervals overlap. For- * example <b>b<i>b&i</b>i</i> would not be valid HTML, so this function- * instead generates <b>b<i>b&i</i></b><i>i</i>. Any HTML- * special characters in {@code rawContent} are escaped to make sure there are no XSS attacks.- *- * <p>- * Every opener in {@code openers} must have a corresponding closer in {@code closers}. Every- * corresponding (opener, closer) pair must have a length of at least one (i.e. empty intervals- * are not allowed).- * </p>- *- * @param openers contains all of the places where a run begins, must have the same size of- * closers, must be ordered by {@link Run#pos}- * @param closers contains all of the places where a run ends, must have the same size of- * openers, must be ordered by {@link Run#pos}- * @param rawContent the content to apply formatting to, and to escape to avoid XSS- * @return the formatted content in HTML- */- static String runsToHtml(- @Nonnull final List<Run> openers,- @Nonnull final List<Run> closers,- @Nonnull final String rawContent- ) {- final String content = rawContent.replace('\u00a0', ' ');- final Stack<Run> openRuns = new Stack<>();- final Stack<Run> tempStack = new Stack<>();- final StringBuilder textBuilder = new StringBuilder();- int currentTextPos = 0;- int openersIndex = 0;- int closersIndex = 0;-- // openers and closers have the same length, but we will surely finish openers earlier than- // closers, since every opened interval needs to be closed at some point and there can't be- // empty intervals, hence check only closersIndex < closers.size()- while (closersIndex < closers.size()) {- final int minPos = openersIndex < openers.size()- ? Math.min(closers.get(closersIndex).pos, openers.get(openersIndex).pos)- : closers.get(closersIndex).pos;-- // append piece of text until current index- textBuilder.append(Entities.escape(content.substring(currentTextPos, minPos)));- currentTextPos = minPos;-- if (closers.get(closersIndex).pos == minPos) {- // even in case of position tie, first process closers- final Run closer = closers.get(closersIndex);- ++closersIndex;-- // because of the assumptions, this while wouldn't need the !openRuns.empty()- // condition, because no run will close before being opened, but let's be sure- while (!openRuns.empty()) {- final Run popped = openRuns.pop();- if (popped.sameOpen(closer)) {- // before closing the current run, if the run has a transformContent- // function, use it to transform the content of the current run, based on- // the openPosInOutput set when the current run was opened- if (popped.transformContent != null && popped.openPosInOutput >= 0) {- textBuilder.replace(popped.openPosInOutput, textBuilder.length(),- popped.transformContent.apply(- textBuilder.substring(popped.openPosInOutput)));- }- // close the run that we really need to close- textBuilder.append(popped.close);- break;- }- // we keep popping from openRuns, closing all of the runs we find,- // until we find the run that we really need to close ...- textBuilder.append(popped.close);- tempStack.push(popped);- }- while (!tempStack.empty()) {- // ... and then we reopen all of the runs that we didn't need to close- // e.g. in <b>b<i>b&i</b>i</i>, when </b> is encountered, </i></b><i> is printed- // instead, to make sure the HTML is valid, obtaining <b>b<i>b&i</i></b><i>i</i>- final Run popped = tempStack.pop();- textBuilder.append(popped.open);- openRuns.push(popped);- }-- } else {- // this will never be reached if openersIndex >= openers.size() because of the- // way minPos is calculated- final Run opener = openers.get(openersIndex);- textBuilder.append(opener.open);- opener.openPosInOutput = textBuilder.length(); // save for transforming later- openRuns.push(opener);- ++openersIndex;- }- }-- // append last piece of text- textBuilder.append(Entities.escape(content.substring(currentTextPos)));-- return textBuilder.toString()- .replace("\n", "<br>")- .replace(" ", " ");- }-- private static void addAllCommandRuns(- @Nonnull final JsonObject attributedDescription,- @Nonnull final List<Run> openers,- @Nonnull final List<Run> closers- ) {- attributedDescription.getArray("commandRuns")- .streamAsJsonObjects()- .forEach(run -> {- final JsonObject navigationEndpoint = run.getObject("onTap")- .getObject("innertubeCommand");-- final int startIndex = run.getInt("startIndex", -1);- final int length = run.getInt("length", 0);- if (startIndex < 0 || length < 1 || navigationEndpoint == null) {- return;- }-- final String url = getUrlFromNavigationEndpoint(navigationEndpoint);- if (url == null) {- return;- }-- boolean isYoutubeUrl;- try {- final URL parsedUrl = new URL(url);- isYoutubeUrl = isYoutubeURL(parsedUrl) || isYoutubeServiceURL(parsedUrl);- } catch (final MalformedURLException ignored) {- // this should never happen, but just in case, assume this is a generic URL- isYoutubeUrl = false;- }-- final String open = "<a href=\"" + Entities.escape(url) + "\">";- final Function<String, String> transformContent = getTransformContentFun(- run, isYoutubeUrl);-- openers.add(new Run(open, LINK_CLOSE, startIndex, transformContent));- closers.add(new Run(open, LINK_CLOSE, startIndex + length, transformContent));- });- }-- private static Function<String, String> getTransformContentFun(final JsonObject run,- final boolean isYoutube) {- final String accessibilityLabel = run.getObject("onTapOptions")- .getObject("accessibilityInfo")- .getString("accessibilityLabel", "")- // accessibility labels are e.g. "Instagram Channel Link: instagram_profile_name"- .replaceFirst(" Channel Link", "");-- final Function<String, String> transformContent;- if (isYoutube- || accessibilityLabel.isEmpty() || accessibilityLabel.startsWith("YouTube: ")) {- // if there is no accessibility label, or the link points to YouTube, cleanup the link- // text, see LINK_CONTENT_CLEANER_REGEX's documentation for more details- transformContent = (content) -> {- final Matcher m = LINK_CONTENT_CLEANER_REGEX.matcher(content);- if (m.find()) {- return m.group(1);- }- return content;- };- } else {- // if there is an accessibility label, replace the link text with it, because on the- // YouTube website an ambiguous link text is next to an icon explaining which service it- // belongs to, but since we can't add icons, we instead use the accessibility label- // which contains information about the service- transformContent = (content) -> accessibilityLabel;- }-- return transformContent;- }-- private static void addAllStyleRuns(- @Nonnull final JsonObject attributedDescription,- @Nonnull final List<Run> openers,- @Nonnull final List<Run> closers- ) {- attributedDescription.getArray("styleRuns")- .streamAsJsonObjects()- .forEach(run -> {- final int start = run.getInt("startIndex", -1);- final int length = run.getInt("length", 0);- if (start < 0 || length < 1) {- return;- }- final int end = start + length;-- if (run.has("strikethrough")) {- openers.add(new Run(STRIKETHROUGH_OPEN, STRIKETHROUGH_CLOSE, start));- closers.add(new Run(STRIKETHROUGH_OPEN, STRIKETHROUGH_CLOSE, end));- }-- if (run.getBoolean("italic", false)) {- openers.add(new Run(ITALIC_OPEN, ITALIC_CLOSE, start));- closers.add(new Run(ITALIC_OPEN, ITALIC_CLOSE, end));- }-- if (run.has("weightLabel")- && !"FONT_WEIGHT_NORMAL".equals(run.getString("weightLabel"))) {- openers.add(new Run(BOLD_OPEN, BOLD_CLOSE, start));- closers.add(new Run(BOLD_OPEN, BOLD_CLOSE, end));- }- });- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.javadeleted file mode 100644index 61c3932b71..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeJavaScriptPlayerManager.java+++ /dev/null@@ -1,303 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import com.grack.nanojson.JsonObject;-import com.grack.nanojson.JsonParser;-import com.grack.nanojson.JsonParserException;-import org.schabi.newpipe.extractor.NewPipe;-import org.schabi.newpipe.extractor.downloader.Response;-import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.exceptions.ReCaptchaException;-import org.schabi.newpipe.extractor.localization.Localization;-import org.schabi.newpipe.extractor.utils.Parser;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;-import java.io.IOException;-import java.util.Collections;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.regex.Pattern;--/**- * Manage the extraction and the usage of YouTube's player JavaScript needed data in the YouTube- * service.- *- * <p>- * YouTube restrict streaming their media in multiple ways by requiring their HTML5 clients to use- * a signature timestamp, and on streaming URLs a signature deobfuscation function for some- * contents and a throttling parameter deobfuscation one for all contents.- * </p>- *- * <p>- * This class provides access to methods which allows to get base JavaScript player's signature- * timestamp and to deobfuscate streaming URLs' signature and/or throttling parameter of HTML5- * clients using the PipePipe API.- * </p>- */-public final class YoutubeJavaScriptPlayerManager {-- private static final Pattern THROTTLING_PARAM_PATTERN = Pattern.compile("[&?]n=([^&]+)");-- private static final String LATEST_PLAYER_URL =- "https://api.pipepipe.dev/decoder/latest-player";- private static final String USER_AGENT = "PipePipe/4.9.0";- private static final long PLAYER_METADATA_TTL_MILLIS = 24L * 60L * 60L * 1000L;-- @Nullable- private static PlayerMetadata playerMetadata;-- private YoutubeJavaScriptPlayerManager() {- }-- /**- * Get the signature timestamp of the base JavaScript player file.- *- * <p>- * A valid signature timestamp sent in the payload of player InnerTube requests is required to- * get valid stream URLs on HTML5 clients for videos which have obfuscated signatures.- * </p>- *- * <p>- * The signature timestamp is loaded together with the player ID from the decoder API.- * </p>- *- * <p>- * The metadata is reused for up to 24 hours before being refreshed from the API.- * </p>- *- * @param videoId the video ID used to get the JavaScript base player file (an empty one can be- * passed, even it is not recommend in order to spoof better official YouTube- * clients)- * @return the signature timestamp of the base JavaScript player file- * @throws ParsingException if the extraction of the signature timestamp failed- */- @Nonnull- public static Integer getSignatureTimestamp(@Nonnull final String videoId)- throws ParsingException {- final long startedAtNanos = System.nanoTime();- final int signatureTimestamp = getPlayerMetadata(videoId).signatureTimestamp;- logPerformance(videoId, "ejs.signatureTimestamp", startedAtNanos);- return signatureTimestamp;- }-- /**- * Deobfuscate a signature of a streaming URL using the PipePipe API.- *- * <p>- * Obfuscated signatures are only present on streaming URLs of some videos with HTML5 clients.- * </p>- *- * @param videoId the video ID used to get the JavaScript base player ID (an- * empty one can be passed, even it is not recommend in order to- * spoof better official YouTube clients)- * @param obfuscatedSignature the obfuscated signature of a streaming URL- * @return the deobfuscated signature- * @throws ParsingException if the extraction of the player ID or the API call failed- */- @Nonnull- public static String deobfuscateSignature(@Nonnull final String videoId,- @Nonnull final String obfuscatedSignature)- throws ParsingException {- return YoutubeApiDecoder.decodeSignature(- getPlayerMetadata(videoId).playerId, obfuscatedSignature);- }-- /**- * Return a streaming URL with the throttling parameter of a given one deobfuscated, if it is- * present, using the PipePipe API.- *- * <p>- * The throttling parameter is present on all streaming URLs of HTML5 clients.- * </p>- *- * <p>- * If it is not given or deobfuscated, speeds will be throttled to a very slow speed (around 50- * KB/s) and some streaming URLs could even lead to invalid HTTP responses such a 403 one.- * </p>- *- * @param videoId the video ID used to get the JavaScript base player ID (an empty one- * can be passed, even it is not recommend in order to spoof better- * official YouTube clients)- * @param streamingUrl a streaming URL- * @return the original streaming URL if it has no throttling parameter or a URL with a- * deobfuscated throttling parameter- * @throws ParsingException if the extraction of the player ID or the API call failed- */- @Nonnull- public static String getUrlWithThrottlingParameterDeobfuscated(- @Nonnull final String videoId,- @Nonnull final String streamingUrl) throws ParsingException {- final String obfuscatedThrottlingParameter =- getThrottlingParameterFromStreamingUrl(streamingUrl);- // If the throttling parameter is not present, return the original streaming URL- if (obfuscatedThrottlingParameter == null) {- return streamingUrl;- }-- final PlayerMetadata metadata = getPlayerMetadata(videoId);-- final String deobfuscatedThrottlingParameter = YoutubeApiDecoder.decodeThrottlingParameter(- metadata.playerId, obfuscatedThrottlingParameter);-- return streamingUrl.replace(- obfuscatedThrottlingParameter, deobfuscatedThrottlingParameter);- }-- /**- * Clear the cached player metadata.- *- * <p>- * The next access will fetch a fresh player ID and signature timestamp from the API.- * </p>- */- public static void clearAllCaches() {- playerMetadata = null;- YoutubeApiDecoder.clearCache();- }-- public static void clearThrottlingParametersCache() {- YoutubeApiDecoder.clearCache();- }-- public static int getThrottlingParametersCacheSize() {- return YoutubeApiDecoder.getCacheSize();- }-- @Nullable- public static String getThrottlingParameterFromStreamingUrl(- @Nonnull final String streamingUrl) {- try {- return Parser.matchGroup1(THROTTLING_PARAM_PATTERN, streamingUrl);- } catch (final Parser.RegexException e) {- return null;- }- }-- /**- * Batch deobfuscate multiple signatures and throttling parameters in a single API call.- *- * <p>- * This method is more efficient than calling {@link #deobfuscateSignature(String, String)}- * and {@link #getUrlWithThrottlingParameterDeobfuscated(String, String)} individually for- * each stream, as it combines all parameters into a single API request.- * </p>- *- * @param videoId the video ID used to get the JavaScript base player ID- * @param signatures list of obfuscated signatures to decode (can be null or empty)- * @param throttlingParams list of obfuscated throttling parameters to decode (can be null or empty)- * @return a BatchDecodeResult containing decoded signatures and throttling parameters- * @throws ParsingException if the extraction of the player ID or the API call failed- */- @Nonnull- public static YoutubeApiDecoder.BatchDecodeResult deobfuscateBatch(- @Nonnull final String videoId,- @Nullable final List<String> signatures,- @Nullable final List<String> throttlingParams) throws ParsingException {- final String playerId = getPlayerMetadata(videoId).playerId;- final long startedAtNanos = System.nanoTime();- final YoutubeApiDecoder.BatchDecodeResult result = YoutubeApiDecoder.decodeBatch(- playerId, signatures, throttlingParams);- logPerformanceIfSlow(videoId, "ejs.batch.decode", startedAtNanos);- return result;- }-- /**- * Load player metadata from memory or refresh it from the decoder API.- *- * @param videoId unused, kept to avoid changing public call sites- * @throws ParsingException if loading the player metadata failed- */- @Nonnull- private static PlayerMetadata getPlayerMetadata(@Nonnull final String videoId)- throws ParsingException {- final PlayerMetadata currentMetadata = playerMetadata;- if (currentMetadata != null && !currentMetadata.isExpired()) {- return currentMetadata;- }-- final long startedAtNanos = System.nanoTime();- final YoutubeJavaScriptDecoder decoder = YoutubeApiDecoder.getLocalDecoder();- if (decoder != null) {- final YoutubeJavaScriptDecoder.PlayerData data = decoder.getPlayerData(videoId);- playerMetadata = new PlayerMetadata(data.getPlayerId(), data.getSignatureTimestamp(),- System.currentTimeMillis() + PLAYER_METADATA_TTL_MILLIS);- logPerformance(videoId, "ejs.playerMetadata.local", startedAtNanos);- return playerMetadata;- }-- playerMetadata = fetchLatestPlayerMetadata();- logPerformance(videoId, "ejs.playerMetadata.remoteFallback", startedAtNanos);- return playerMetadata;- }-- private static void logPerformance(@Nonnull final String videoId,- @Nonnull final String stage,- final long startedAtNanos) {- System.out.println("YT_PERF videoId=" + videoId + " stage=" + stage- + " durationMs="- + java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(- System.nanoTime() - startedAtNanos));- }-- private static void logPerformanceIfSlow(@Nonnull final String videoId,- @Nonnull final String stage,- final long startedAtNanos) {- final long durationMs = java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(- System.nanoTime() - startedAtNanos);- if (durationMs >= 5) {- System.out.println("YT_PERF videoId=" + videoId + " stage=" + stage- + " durationMs=" + durationMs);- }- }-- @Nonnull- private static PlayerMetadata fetchLatestPlayerMetadata() throws ParsingException {- final Map<String, List<String>> headers = new HashMap<>();- headers.put("User-Agent", Collections.singletonList(USER_AGENT));-- try {- final Response response = NewPipe.getDownloader().get(- LATEST_PLAYER_URL, headers, Localization.DEFAULT);- final JsonObject responseJson = JsonParser.object().from(response.responseBody());-- final String playerId = responseJson.getString("player", "");- if (playerId.isEmpty()) {- throw new ParsingException("latest-player response missing player");- }-- if (!responseJson.has("signatureTimestamp")) {- throw new ParsingException("latest-player response missing signatureTimestamp");- }-- final int signatureTimestamp = responseJson.getInt("signatureTimestamp");- return new PlayerMetadata(playerId, signatureTimestamp,- System.currentTimeMillis() + PLAYER_METADATA_TTL_MILLIS);- } catch (final IOException e) {- throw new ParsingException("Failed to fetch latest player metadata", e);- } catch (final ReCaptchaException e) {- throw new ParsingException("Failed to fetch latest player metadata", e);- } catch (final JsonParserException e) {- throw new ParsingException("Failed to parse latest player metadata", e);- }- }-- private static final class PlayerMetadata {- @Nonnull- private final String playerId;- private final int signatureTimestamp;- private final long expiresAt;-- private PlayerMetadata(@Nonnull final String playerId,- final int signatureTimestamp,- final long expiresAt) {- this.playerId = playerId;- this.signatureTimestamp = signatureTimestamp;- this.expiresAt = expiresAt;- }-- private boolean isExpired() {- return System.currentTimeMillis() >= expiresAt;- }- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeMetaInfoHelper.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeMetaInfoHelper.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeMetaInfoHelper.javadeleted file mode 100644index bc8d9f85d0..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeMetaInfoHelper.java+++ /dev/null@@ -1,224 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.extractCachedUrlIfNeeded;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getTextFromObject;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getTextFromObjectOrThrow;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getUrlFromNavigationEndpoint;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.isGoogleURL;-import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;-import static org.schabi.newpipe.extractor.utils.Utils.replaceHttpWithHttps;--import com.grack.nanojson.JsonArray;-import com.grack.nanojson.JsonObject;--import org.schabi.newpipe.extractor.MetaInfo;-import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.stream.Description;--import java.net.MalformedURLException;-import java.net.URL;-import java.util.ArrayList;-import java.util.List;-import java.util.Objects;-import java.util.function.Consumer;-import java.util.stream.Collectors;--import javax.annotation.Nonnull;--public final class YoutubeMetaInfoHelper {-- private YoutubeMetaInfoHelper() {- }--- @Nonnull- public static List<MetaInfo> getMetaInfo(@Nonnull final JsonArray contents)- throws ParsingException {- final List<MetaInfo> metaInfo = new ArrayList<>();- for (final Object content : contents) {- final JsonObject resultObject = (JsonObject) content;- if (resultObject.has("itemSectionRenderer")) {- for (final Object sectionContentObject- : resultObject.getObject("itemSectionRenderer").getArray("contents")) {-- final JsonObject sectionContent = (JsonObject) sectionContentObject;- if (sectionContent.has("infoPanelContentRenderer")) {- metaInfo.add(getInfoPanelContent(sectionContent- .getObject("infoPanelContentRenderer")));- }- if (sectionContent.has("clarificationRenderer")) {- metaInfo.add(getClarificationRenderer(sectionContent- .getObject("clarificationRenderer")- ));- }- if (sectionContent.has("emergencyOneboxRenderer")) {- getEmergencyOneboxRenderer(- sectionContent.getObject("emergencyOneboxRenderer"),- metaInfo::add- );- }- }- }- }- return metaInfo;- }-- @Nonnull- private static MetaInfo getInfoPanelContent(@Nonnull final JsonObject infoPanelContentRenderer)- throws ParsingException {- final MetaInfo metaInfo = new MetaInfo();- final StringBuilder sb = new StringBuilder();- for (final Object paragraph : infoPanelContentRenderer.getArray("paragraphs")) {- if (sb.length() != 0) {- sb.append("<br>");- }- sb.append(getTextFromObject((JsonObject) paragraph));- }- metaInfo.setContent(new Description(sb.toString(), Description.HTML));- if (infoPanelContentRenderer.has("sourceEndpoint")) {- final String metaInfoLinkUrl = getUrlFromNavigationEndpoint(- infoPanelContentRenderer.getObject("sourceEndpoint"));- try {- metaInfo.addUrl(new URL(Objects.requireNonNull(extractCachedUrlIfNeeded(- metaInfoLinkUrl))));- } catch (final NullPointerException | MalformedURLException e) {- throw new ParsingException("Could not get metadata info URL", e);- }-- final String metaInfoLinkText;- if (infoPanelContentRenderer.has("inlineSource")) {- metaInfoLinkText = getTextFromObject(- infoPanelContentRenderer.getObject("inlineSource"));- } else {- metaInfoLinkText = getTextFromObject(- infoPanelContentRenderer.getObject("disclaimer"));- }- if (isNullOrEmpty(metaInfoLinkText)) {- throw new ParsingException("Could not get metadata info link text.");- }- metaInfo.addUrlText(metaInfoLinkText);- }-- return metaInfo;- }-- @Nonnull- private static MetaInfo getClarificationRenderer(- @Nonnull final JsonObject clarificationRenderer) throws ParsingException {- final MetaInfo metaInfo = new MetaInfo();-- final String title = getTextFromObject(clarificationRenderer- .getObject("contentTitle"));- final String text = getTextFromObject(clarificationRenderer- .getObject("text"));- if (title == null || text == null) {- throw new ParsingException("Could not extract clarification renderer content");- }- metaInfo.setTitle(title);- metaInfo.setContent(new Description(text, Description.PLAIN_TEXT));-- if (clarificationRenderer.has("actionButton")) {- final JsonObject actionButton = clarificationRenderer.getObject("actionButton")- .getObject("buttonRenderer");- try {- final String url = getUrlFromNavigationEndpoint(actionButton- .getObject("command"));- metaInfo.addUrl(new URL(Objects.requireNonNull(extractCachedUrlIfNeeded(url))));- } catch (final NullPointerException | MalformedURLException e) {- throw new ParsingException("Could not get metadata info URL", e);- }-- final String metaInfoLinkText = getTextFromObject(- actionButton.getObject("text"));- if (isNullOrEmpty(metaInfoLinkText)) {- throw new ParsingException("Could not get metadata info link text.");- }- metaInfo.addUrlText(metaInfoLinkText);- }-- if (clarificationRenderer.has("secondaryEndpoint") && clarificationRenderer- .has("secondarySource")) {- final String url = getUrlFromNavigationEndpoint(clarificationRenderer- .getObject("secondaryEndpoint"));- // Ignore Google URLs, because those point to a Google search about "Covid-19"- if (url != null && !isGoogleURL(url)) {- try {- metaInfo.addUrl(new URL(url));- final String description = getTextFromObject(clarificationRenderer- .getObject("secondarySource"));- metaInfo.addUrlText(description == null ? url : description);- } catch (final MalformedURLException e) {- throw new ParsingException("Could not get metadata info secondary URL", e);- }- }- }-- return metaInfo;- }-- private static void getEmergencyOneboxRenderer(- @Nonnull final JsonObject emergencyOneboxRenderer,- final Consumer<MetaInfo> addMetaInfo- ) throws ParsingException {- final List<JsonObject> supportRenderers = emergencyOneboxRenderer.values()- .stream()- .filter(o -> o instanceof JsonObject- && ((JsonObject) o).has("singleActionEmergencySupportRenderer"))- .map(o -> ((JsonObject) o).getObject("singleActionEmergencySupportRenderer"))- .collect(Collectors.toList());-- if (supportRenderers.isEmpty()) {- throw new ParsingException("Could not extract any meta info from emergency renderer");- }-- for (final JsonObject r : supportRenderers) {- final MetaInfo metaInfo = new MetaInfo();-- // usually an encouragement like "We are with you"- final String title = getTextFromObjectOrThrow(r.getObject("title"), "title");-- // usually a phone number- final String action; // this variable is expected to start with "\n"- if (r.has("actionText")) {- action = "\n" + getTextFromObjectOrThrow(r.getObject("actionText"), "action");- } else if (r.has("contacts")) {- final JsonArray contacts = r.getArray("contacts");- final StringBuilder stringBuilder = new StringBuilder();- // Loop over contacts item from the first contact to the last one- for (int i = 0; i < contacts.size(); i++) {- stringBuilder.append("\n");- stringBuilder.append(getTextFromObjectOrThrow(contacts.getObject(i)- .getObject("actionText"), "contacts.actionText"));- }- action = stringBuilder.toString();- } else {- action = "";- }-- // usually details about the phone number- final String details = getTextFromObjectOrThrow(r.getObject("detailsText"), "details");-- // usually the name of an association- final String urlText = getTextFromObjectOrThrow(r.getObject("navigationText"),- "urlText");-- metaInfo.setTitle(title);- metaInfo.setContent(new Description(details + action, Description.PLAIN_TEXT));- metaInfo.addUrlText(urlText);-- // usually the webpage of the association- final String url = getUrlFromNavigationEndpoint(r.getObject("navigationEndpoint"));- if (url == null) {- throw new ParsingException("Could not extract emergency renderer url");- }-- try {- metaInfo.addUrl(new URL(replaceHttpWithHttps(url)));- } catch (final MalformedURLException e) {- throw new ParsingException("Could not parse emergency renderer url", e);- }-- addMetaInfo.accept(metaInfo);- }- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeService.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeService.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeService.javadeleted file mode 100644index 7127453fda..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeService.java+++ /dev/null@@ -1,298 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.AUDIO;-import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.COMMENTS;-import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.LIVE;-import static org.schabi.newpipe.extractor.StreamingService.ServiceInfo.MediaCapability.VIDEO;--import org.schabi.newpipe.extractor.StreamingService;-import org.schabi.newpipe.extractor.channel.ChannelExtractor;-import org.schabi.newpipe.extractor.channel.tabs.ChannelTabExtractor;-import org.schabi.newpipe.extractor.comments.CommentsExtractor;-import org.schabi.newpipe.extractor.exceptions.ExtractionException;-import org.schabi.newpipe.extractor.feed.FeedExtractor;-import org.schabi.newpipe.extractor.kiosk.KioskList;-import org.schabi.newpipe.extractor.linkhandler.LinkHandler;-import org.schabi.newpipe.extractor.linkhandler.LinkHandlerFactory;-import org.schabi.newpipe.extractor.linkhandler.ListLinkHandler;-import org.schabi.newpipe.extractor.linkhandler.ListLinkHandlerFactory;-import org.schabi.newpipe.extractor.linkhandler.ReadyChannelTabListLinkHandler;-import org.schabi.newpipe.extractor.linkhandler.SearchQueryHandler;-import org.schabi.newpipe.extractor.linkhandler.SearchQueryHandlerFactory;-import org.schabi.newpipe.extractor.localization.ContentCountry;-import org.schabi.newpipe.extractor.localization.Localization;-import org.schabi.newpipe.extractor.playlist.PlaylistExtractor;-import org.schabi.newpipe.extractor.search.SearchExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeChannelExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeChannelTabExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeCommentsExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeFeedExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeMixPlaylistExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeMusicSearchExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubePlaylistExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeSearchExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeStreamExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeSubscriptionExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeSuggestionExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeTrendingExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeLiveExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeTrendingGamingVideosExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeTrendingMoviesAndShowsTrailersExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeTrendingMusicExtractor;-import org.schabi.newpipe.extractor.services.youtube.extractors.kiosk.YoutubeTrendingPodcastsEpisodesExtractor;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeChannelLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeChannelTabLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeCommentsLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeLiveLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubePlaylistLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeSearchQueryHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeStreamLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeTrendingGamingVideosLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeTrendingLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeTrendingMoviesAndShowsTrailersLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeTrendingMusicLinkHandlerFactory;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeTrendingPodcastsEpisodesLinkHandlerFactory;-import org.schabi.newpipe.extractor.stream.StreamExtractor;-import org.schabi.newpipe.extractor.subscription.SubscriptionExtractor;-import org.schabi.newpipe.extractor.suggestion.SuggestionExtractor;--import java.util.EnumSet;-import java.util.List;--import javax.annotation.Nonnull;--/*- * Created by Christian Schabesberger on 23.08.15.- *- * Copyright (C) 2018 Christian Schabesberger <[email protected]>- * YoutubeService.java is part of NewPipe Extractor.- *- * NewPipe Extractor 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 Extractor 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 Extractor. If not, see <http://www.gnu.org/licenses/>.- */--public class YoutubeService extends StreamingService {-- public YoutubeService(final int id) {- super(id, "YouTube", EnumSet.of(AUDIO, VIDEO, LIVE, COMMENTS));- }-- @Override- public String getBaseUrl() {- return "https://youtube.com";- }-- @Override- public LinkHandlerFactory getStreamLHFactory() {- return YoutubeStreamLinkHandlerFactory.getInstance();- }-- @Override- public ListLinkHandlerFactory getChannelLHFactory() {- return YoutubeChannelLinkHandlerFactory.getInstance();- }-- @Override- public ListLinkHandlerFactory getChannelTabLHFactory() {- return YoutubeChannelTabLinkHandlerFactory.getInstance();- }-- @Override- public ListLinkHandlerFactory getPlaylistLHFactory() {- return YoutubePlaylistLinkHandlerFactory.getInstance();- }-- @Override- public SearchQueryHandlerFactory getSearchQHFactory() {- return YoutubeSearchQueryHandlerFactory.getInstance();- }-- @Override- public StreamExtractor getStreamExtractor(final LinkHandler linkHandler) {- return new YoutubeStreamExtractor(this, linkHandler);- }-- @Override- public ChannelExtractor getChannelExtractor(final ListLinkHandler linkHandler) {- return new YoutubeChannelExtractor(this, linkHandler);- }-- @Override- public ChannelTabExtractor getChannelTabExtractor(final ListLinkHandler linkHandler) {- if (linkHandler instanceof ReadyChannelTabListLinkHandler) {- return ((ReadyChannelTabListLinkHandler) linkHandler).getChannelTabExtractor(this);- } else {- return new YoutubeChannelTabExtractor(this, linkHandler);- }- }-- @Override- public PlaylistExtractor getPlaylistExtractor(final ListLinkHandler linkHandler) {- if (YoutubeParsingHelper.isYoutubeMixId(linkHandler.getId())) {- return new YoutubeMixPlaylistExtractor(this, linkHandler);- } else {- return new YoutubePlaylistExtractor(this, linkHandler);- }- }-- @Override- public SearchExtractor getSearchExtractor(final SearchQueryHandler query) {- final List<String> contentFilters = query.getContentFilters();-- if (!contentFilters.isEmpty() && contentFilters.get(0).startsWith("music_")) {- return new YoutubeMusicSearchExtractor(this, query);- } else {- return new YoutubeSearchExtractor(this, query);- }- }-- @Override- public SuggestionExtractor getSuggestionExtractor() {- return new YoutubeSuggestionExtractor(this);- }-- @Override- public KioskList getKioskList() throws ExtractionException {- final KioskList list = new KioskList(this);- final ListLinkHandlerFactory trendingLHF = YoutubeTrendingLinkHandlerFactory.INSTANCE;- final ListLinkHandlerFactory runningLivesLHF =- YoutubeLiveLinkHandlerFactory.INSTANCE;- final ListLinkHandlerFactory trendingPodcastsEpisodesLHF =- YoutubeTrendingPodcastsEpisodesLinkHandlerFactory.INSTANCE;- final ListLinkHandlerFactory trendingGamingVideosLHF =- YoutubeTrendingGamingVideosLinkHandlerFactory.INSTANCE;- final ListLinkHandlerFactory trendingMoviesAndShowsLHF =- YoutubeTrendingMoviesAndShowsTrailersLinkHandlerFactory.INSTANCE;- final ListLinkHandlerFactory trendingMusicLHF =- YoutubeTrendingMusicLinkHandlerFactory.INSTANCE;-- try {- list.addKioskEntry(- (streamingService, url, id) -> new YoutubeLiveExtractor(- YoutubeService.this,- runningLivesLHF.fromUrl(url),- id),- runningLivesLHF,- YoutubeLiveLinkHandlerFactory.KIOSK_ID- );- list.addKioskEntry(- (streamingService, url, id) -> new YoutubeTrendingPodcastsEpisodesExtractor(- YoutubeService.this,- trendingPodcastsEpisodesLHF.fromUrl(url),- id),- trendingPodcastsEpisodesLHF,- YoutubeTrendingPodcastsEpisodesLinkHandlerFactory.KIOSK_ID- );- list.addKioskEntry(- (streamingService, url, id) -> new YoutubeTrendingGamingVideosExtractor(- YoutubeService.this,- trendingGamingVideosLHF.fromUrl(url),- id),- trendingGamingVideosLHF,- YoutubeTrendingGamingVideosLinkHandlerFactory.KIOSK_ID- );- list.addKioskEntry(- (streamingService, url, id) ->- new YoutubeTrendingMoviesAndShowsTrailersExtractor(- YoutubeService.this,- trendingMoviesAndShowsLHF.fromUrl(url),- id),- trendingMoviesAndShowsLHF,- YoutubeTrendingMoviesAndShowsTrailersLinkHandlerFactory.KIOSK_ID- );- list.addKioskEntry(- (streamingService, url, id) -> new YoutubeTrendingMusicExtractor(- YoutubeService.this,- trendingMusicLHF.fromUrl(url),- id),- trendingMusicLHF,- YoutubeTrendingMusicLinkHandlerFactory.KIOSK_ID- );- // Deprecated (i.e. removed from the interface of YouTube) since July 21, 2025- list.addKioskEntry(- (streamingService, url, id) -> new YoutubeTrendingExtractor(- YoutubeService.this,- trendingLHF.fromUrl(url),- id- ),- trendingLHF,- YoutubeTrendingExtractor.KIOSK_ID- );- list.setDefaultKiosk(YoutubeLiveLinkHandlerFactory.KIOSK_ID);- } catch (final Exception e) {- throw new ExtractionException(e);- }-- return list;- }-- @Override- public SubscriptionExtractor getSubscriptionExtractor() {- return new YoutubeSubscriptionExtractor(this);- }-- @Nonnull- @Override- public FeedExtractor getFeedExtractor(final String channelUrl) throws ExtractionException {- return new YoutubeFeedExtractor(this, getChannelLHFactory().fromUrl(channelUrl));- }-- @Override- public ListLinkHandlerFactory getCommentsLHFactory() {- return YoutubeCommentsLinkHandlerFactory.getInstance();- }-- @Override- public CommentsExtractor getCommentsExtractor(final ListLinkHandler urlIdHandler)- throws ExtractionException {- return new YoutubeCommentsExtractor(this, urlIdHandler);- }-- /*//////////////////////////////////////////////////////////////////////////- // Localization- //////////////////////////////////////////////////////////////////////////*/-- // https://www.youtube.com/picker_ajax?action_language_json=1- private static final List<Localization> SUPPORTED_LANGUAGES = Localization.listFrom(- "en-GB"- /*"af", "am", "ar", "az", "be", "bg", "bn", "bs", "ca", "cs", "da", "de",- "el", "en", "en-GB", "es", "es-419", "es-US", "et", "eu", "fa", "fi", "fil", "fr",- "fr-CA", "gl", "gu", "hi", "hr", "hu", "hy", "id", "is", "it", "iw", "ja",- "ka", "kk", "km", "kn", "ko", "ky", "lo", "lt", "lv", "mk", "ml", "mn",- "mr", "ms", "my", "ne", "nl", "no", "pa", "pl", "pt", "pt-PT", "ro", "ru",- "si", "sk", "sl", "sq", "sr", "sr-Latn", "sv", "sw", "ta", "te", "th", "tr",- "uk", "ur", "uz", "vi", "zh-CN", "zh-HK", "zh-TW", "zu"*/- );-- // https://www.youtube.com/picker_ajax?action_country_json=1- private static final List<ContentCountry> SUPPORTED_COUNTRIES = ContentCountry.listFrom(- "DZ", "AR", "AU", "AT", "AZ", "BH", "BD", "BY", "BE", "BO", "BA", "BR", "BG", "KH",- "CA", "CL", "CO", "CR", "HR", "CY", "CZ", "DK", "DO", "EC", "EG", "SV", "EE", "FI",- "FR", "GE", "DE", "GH", "GR", "GT", "HN", "HK", "HU", "IS", "IN", "ID", "IQ", "IE",- "IL", "IT", "JM", "JP", "JO", "KZ", "KE", "KW", "LA", "LV", "LB", "LY", "LI", "LT",- "LU", "MY", "MT", "MX", "ME", "MA", "NP", "NL", "NZ", "NI", "NG", "MK", "NO", "OM",- "PK", "PA", "PG", "PY", "PE", "PH", "PL", "PT", "PR", "QA", "RO", "RU", "SA", "SN",- "RS", "SG", "SK", "SI", "ZA", "KR", "ES", "LK", "SE", "CH", "TW", "TZ", "TH", "TN",- "TR", "UG", "UA", "AE", "GB", "US", "UY", "VE", "VN", "YE", "ZW"- );-- @Override- public List<Localization> getSupportedLocalizations() {- return SUPPORTED_LANGUAGES;- }-- @Override- public List<ContentCountry> getSupportedCountries() {- return SUPPORTED_COUNTRIES;- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.javadeleted file mode 100644index af0b747fe6..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/YoutubeStreamHelper.java+++ /dev/null@@ -1,301 +0,0 @@-package org.schabi.newpipe.extractor.services.youtube;--import com.grack.nanojson.JsonBuilder;-import com.grack.nanojson.JsonObject;-import com.grack.nanojson.JsonWriter;-import org.schabi.newpipe.extractor.exceptions.ExtractionException;-import org.schabi.newpipe.extractor.localization.ContentCountry;-import org.schabi.newpipe.extractor.localization.Localization;-import org.schabi.newpipe.extractor.utils.JsonUtils;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;-import java.io.IOException;-import java.nio.charset.StandardCharsets;-import java.util.HashMap;-import java.util.List;-import java.util.Map;--import static org.schabi.newpipe.extractor.NewPipe.getDownloader;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_EMBEDDED_CLIENT_ID;-import static org.schabi.newpipe.extractor.services.youtube.ClientsConstants.WEB_EMBEDDED_CLIENT_VERSION;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.CONTENT_CHECK_OK;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.CPN;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.DISABLE_PRETTY_PRINT_PARAMETER;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.RACY_CHECK_OK;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.VIDEO_ID;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.YOUTUBEI_V1_GAPIS_URL;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.YOUTUBEI_V1_URL;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.generateTParameter;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getAndroidUserAgent;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getClientHeaders;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getClientVersion;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getIosUserAgent;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getOriginReferrerHeaders;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getValidJsonResponseBody;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getVisionOsUserAgent;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getYouTubeHeaders;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.prepareJsonBuilder;--public final class YoutubeStreamHelper {-- private static final String PLAYER = "player";- private static final String SERVICE_INTEGRITY_DIMENSIONS = "serviceIntegrityDimensions";- private static final String PO_TOKEN = "poToken";- private static final String BASE_YT_DESKTOP_WATCH_URL = "https://www.youtube.com/watch?v=";-- private YoutubeStreamHelper() {- }-- @Nonnull- public static JsonObject getWebMetadataPlayerResponse(- @Nonnull final Localization localization,- @Nonnull final ContentCountry contentCountry,- @Nonnull final String videoId) throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofWebClient();- innertubeClientRequestInfo.clientInfo.clientVersion = getClientVersion();-- final Map<String, List<String>> headers = getYouTubeHeaders();-- // We must always pass a valid visitorData to get valid player responses, which needs to be- // got from YouTube- innertubeClientRequestInfo.clientInfo.visitorData =- YoutubeParsingHelper.getVisitorDataFromInnertube(innertubeClientRequestInfo,- localization, contentCountry, headers, YOUTUBEI_V1_URL, null, false);-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, null);-- addVideoIdCpnAndOkChecks(builder, videoId, null);-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);-- final String url = YOUTUBEI_V1_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER- + "&$fields=microformat,videoDetails.thumbnail.thumbnails,videoDetails.videoId";-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(- url, headers, body, localization)));- }-- @Nonnull- public static JsonObject getWebEmbeddedPlayerResponse(- @Nonnull final Localization localization,- @Nonnull final ContentCountry contentCountry,- @Nonnull final String videoId,- @Nonnull final String cpn,- @Nullable final PoTokenResult webEmbeddedPoTokenResult,- final int signatureTimestamp) throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofWebEmbeddedPlayerClient();-- final Map<String, List<String>> headers = new HashMap<>(- getClientHeaders(WEB_EMBEDDED_CLIENT_ID, WEB_EMBEDDED_CLIENT_VERSION));- headers.putAll(getOriginReferrerHeaders("https://www.youtube.com"));-- final String embedUrl = BASE_YT_DESKTOP_WATCH_URL + videoId;-- // We must always pass a valid visitorData to get valid player responses, which needs to be- // got from YouTube- innertubeClientRequestInfo.clientInfo.visitorData = webEmbeddedPoTokenResult == null- ? YoutubeParsingHelper.getVisitorDataFromInnertube(innertubeClientRequestInfo,- localization, contentCountry, headers, YOUTUBEI_V1_URL, embedUrl, false)- : webEmbeddedPoTokenResult.visitorData;-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, embedUrl);-- addVideoIdCpnAndOkChecks(builder, videoId, cpn);-- addPlaybackContext(builder, embedUrl, signatureTimestamp);-- if (webEmbeddedPoTokenResult != null) {- addPoToken(builder, webEmbeddedPoTokenResult.playerRequestPoToken);- }-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);- final String url = YOUTUBEI_V1_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER;-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(url, headers, body, localization)));- }-- public static JsonObject getAndroidPlayerResponse(- @Nonnull final ContentCountry contentCountry,- @Nonnull final Localization localization,- @Nonnull final String videoId,- @Nonnull final String cpn,- @Nonnull final PoTokenResult androidPoTokenResult)- throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofAndroidClient();- innertubeClientRequestInfo.clientInfo.visitorData = androidPoTokenResult.visitorData;-- final Map<String, List<String>> headers =- getMobileClientHeaders(getAndroidUserAgent(localization));-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, null);-- addVideoIdCpnAndOkChecks(builder, videoId, cpn);-- addPoToken(builder, androidPoTokenResult.playerRequestPoToken);-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);-- final String url = YOUTUBEI_V1_GAPIS_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER- + "&t=" + generateTParameter() + "&id=" + videoId;-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(url, headers, body, localization)));- }-- public static JsonObject getAndroidReelPlayerResponse(- @Nonnull final ContentCountry contentCountry,- @Nonnull final Localization localization,- @Nonnull final String videoId,- @Nonnull final String cpn) throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofAndroidClient();-- final Map<String, List<String>> headers =- getMobileClientHeaders(getAndroidUserAgent(localization));-- // We must always pass a valid visitorData to get valid player responses, which needs to be- // got from YouTube- innertubeClientRequestInfo.clientInfo.visitorData =- YoutubeParsingHelper.getVisitorDataFromInnertube(innertubeClientRequestInfo,- localization, contentCountry, headers, YOUTUBEI_V1_GAPIS_URL, null, false);-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, null);-- builder.object("playerRequest");- addVideoIdCpnAndOkChecks(builder, videoId, cpn);- builder.end()- .value("disablePlayerResponse", false);-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);-- final String url = YOUTUBEI_V1_GAPIS_URL + "reel/reel_item_watch" + "?"- + DISABLE_PRETTY_PRINT_PARAMETER + "&t=" + generateTParameter() + "&id=" + videoId- + "&$fields=playerResponse";-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(url, headers, body, localization)))- .getObject("playerResponse");- }-- public static JsonObject getIosPlayerResponse(@Nonnull final ContentCountry contentCountry,- @Nonnull final Localization localization,- @Nonnull final String videoId,- @Nonnull final String cpn,- @Nullable final PoTokenResult iosPoTokenResult)- throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofIosClient();-- final Map<String, List<String>> headers =- getMobileClientHeaders(getIosUserAgent(localization));-- // We must always pass a valid visitorData to get valid player responses, which needs to be- // got from YouTube- innertubeClientRequestInfo.clientInfo.visitorData = iosPoTokenResult == null- ? YoutubeParsingHelper.getVisitorDataFromInnertube(innertubeClientRequestInfo,- localization, contentCountry, headers, YOUTUBEI_V1_URL, null, false)- : iosPoTokenResult.visitorData;-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, null);-- addVideoIdCpnAndOkChecks(builder, videoId, cpn);-- if (iosPoTokenResult != null) {- addPoToken(builder, iosPoTokenResult.playerRequestPoToken);- }-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);-- final String url = YOUTUBEI_V1_GAPIS_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER- + "&t=" + generateTParameter() + "&id=" + videoId;-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(url, headers, body, localization)));- }-- public static JsonObject getVisionOsPlayerResponse(@Nonnull final ContentCountry contentCountry,- @Nonnull final Localization localization,- @Nonnull final String videoId,- @Nonnull final String cpn)- throws IOException, ExtractionException {- final InnertubeClientRequestInfo innertubeClientRequestInfo =- InnertubeClientRequestInfo.ofVisionOsClient();-- final Map<String, List<String>> headers =- getMobileClientHeaders(getVisionOsUserAgent(localization));-- // We must always pass a valid visitorData to get valid player responses, which needs to be- // got from YouTube- innertubeClientRequestInfo.clientInfo.visitorData =- YoutubeParsingHelper.getVisitorDataFromInnertube(innertubeClientRequestInfo,- localization, contentCountry, headers, YOUTUBEI_V1_URL, null, false);-- final JsonBuilder<JsonObject> builder = prepareJsonBuilder(localization, contentCountry,- innertubeClientRequestInfo, null);-- addVideoIdCpnAndOkChecks(builder, videoId, cpn);-- final byte[] body = JsonWriter.string(builder.done())- .getBytes(StandardCharsets.UTF_8);-- final String url = YOUTUBEI_V1_GAPIS_URL + PLAYER + "?" + DISABLE_PRETTY_PRINT_PARAMETER- + "&t=" + generateTParameter() + "&id=" + videoId;-- return JsonUtils.toJsonObject(getValidJsonResponseBody(- getDownloader().postWithContentTypeJson(url, headers, body, localization)));- }-- private static void addVideoIdCpnAndOkChecks(@Nonnull final JsonBuilder<JsonObject> builder,- @Nonnull final String videoId,- @Nullable final String cpn) {- builder.value(VIDEO_ID, videoId);-- if (cpn != null) {- builder.value(CPN, cpn);- }-- builder.value(CONTENT_CHECK_OK, true)- .value(RACY_CHECK_OK, true);- }-- private static void addPlaybackContext(@Nonnull final JsonBuilder<JsonObject> builder,- @Nonnull final String referer,- final int signatureTimestamp) {- builder.object("playbackContext")- .object("contentPlaybackContext")- .value("signatureTimestamp", signatureTimestamp)- .value("referer", referer)- .end()- .end();- }-- private static void addPoToken(@Nonnull final JsonBuilder<JsonObject> builder,- @Nonnull final String poToken) {- builder.object(SERVICE_INTEGRITY_DIMENSIONS)- .value(PO_TOKEN, poToken)- .end();- }-- @Nonnull- private static Map<String, List<String>> getMobileClientHeaders(- @Nonnull final String userAgent) {- return Map.of("User-Agent", List.of(userAgent),- "X-Goog-Api-Format-Version", List.of("2"));- }-}
youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java
diff --git a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java b/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.javadeleted file mode 100644index b78867c472..0000000000--- a/youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/services/youtube/extractors/YoutubeStreamExtractor.java+++ /dev/null@@ -1,1837 +0,0 @@-/*- * Created by Christian Schabesberger on 06.08.15.- *- * Copyright (C) 2019 Christian Schabesberger <[email protected]>- * YoutubeStreamExtractor.java is part of NewPipe Extractor.- *- * NewPipe Extractor 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 Extractor 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 Extractor. If not, see <https://www.gnu.org/licenses/>.- */--package org.schabi.newpipe.extractor.services.youtube.extractors;--import static org.schabi.newpipe.extractor.services.youtube.ItagItem.APPROX_DURATION_MS_UNKNOWN;-import static org.schabi.newpipe.extractor.services.youtube.ItagItem.CONTENT_LENGTH_UNKNOWN;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeDescriptionHelper.attributedDescriptionToHtml;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.CONTENT_CHECK_OK;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.CPN;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.RACY_CHECK_OK;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.VIDEO_ID;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.fixThumbnailUrl;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.generateContentPlaybackNonce;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getImagesFromThumbnailsArray;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getJsonPostResponse;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.getTextFromObject;-import static org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper.prepareDesktopJsonBuilder;-import static org.schabi.newpipe.extractor.utils.Utils.isNullOrEmpty;--import com.grack.nanojson.JsonArray;-import com.grack.nanojson.JsonObject;-import com.grack.nanojson.JsonWriter;--import org.schabi.newpipe.extractor.Image;-import org.schabi.newpipe.extractor.MediaFormat;-import org.schabi.newpipe.extractor.MetaInfo;-import org.schabi.newpipe.extractor.MultiInfoItemsCollector;-import org.schabi.newpipe.extractor.StreamingService;-import org.schabi.newpipe.extractor.downloader.Downloader;-import org.schabi.newpipe.extractor.exceptions.AccountTerminatedException;-import org.schabi.newpipe.extractor.exceptions.AgeRestrictedContentException;-import org.schabi.newpipe.extractor.exceptions.ContentNotAvailableException;-import org.schabi.newpipe.extractor.exceptions.ExtractionException;-import org.schabi.newpipe.extractor.exceptions.GeographicRestrictionException;-import org.schabi.newpipe.extractor.exceptions.PaidContentException;-import org.schabi.newpipe.extractor.exceptions.ParsingException;-import org.schabi.newpipe.extractor.exceptions.PrivateContentException;-import org.schabi.newpipe.extractor.exceptions.YoutubeMusicPremiumContentException;-import org.schabi.newpipe.extractor.exceptions.SignInConfirmNotBotException;-import org.schabi.newpipe.extractor.linkhandler.LinkHandler;-import org.schabi.newpipe.extractor.localization.ContentCountry;-import org.schabi.newpipe.extractor.localization.DateWrapper;-import org.schabi.newpipe.extractor.localization.Localization;-import org.schabi.newpipe.extractor.localization.TimeAgoParser;-import org.schabi.newpipe.extractor.localization.TimeAgoPatternsManager;-import org.schabi.newpipe.extractor.services.youtube.ItagItem;-import org.schabi.newpipe.extractor.services.youtube.PoTokenProvider;-import org.schabi.newpipe.extractor.services.youtube.PoTokenResult;-import org.schabi.newpipe.extractor.services.youtube.YoutubeJavaScriptPlayerManager;-import org.schabi.newpipe.extractor.services.youtube.YoutubeMetaInfoHelper;-import org.schabi.newpipe.extractor.services.youtube.YoutubeParsingHelper;-import org.schabi.newpipe.extractor.services.youtube.YoutubeStreamHelper;-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrClientProfile;-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrFormat;-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrInfo;-import org.schabi.newpipe.extractor.services.youtube.sabr.YoutubeSabrProbe;-import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeChannelLinkHandlerFactory;-import org.schabi.newpipe.extractor.stream.AudioStream;-import org.schabi.newpipe.extractor.stream.DeliveryMethod;-import org.schabi.newpipe.extractor.stream.Description;-import org.schabi.newpipe.extractor.stream.Frameset;-import org.schabi.newpipe.extractor.stream.Stream;-import org.schabi.newpipe.extractor.stream.StreamExtractor;-import org.schabi.newpipe.extractor.stream.StreamSegment;-import org.schabi.newpipe.extractor.stream.StreamType;-import org.schabi.newpipe.extractor.stream.SubtitlesStream;-import org.schabi.newpipe.extractor.stream.VideoStream;-import org.schabi.newpipe.extractor.utils.ExtractorLogger;-import org.schabi.newpipe.extractor.utils.JsonUtils;-import org.schabi.newpipe.extractor.utils.LocaleCompat;-import org.schabi.newpipe.extractor.utils.Pair;-import org.schabi.newpipe.extractor.utils.Parser;-import org.schabi.newpipe.extractor.utils.Utils;--import java.io.IOException;-import java.nio.charset.StandardCharsets;-import java.time.LocalDate;-import java.time.format.DateTimeFormatter;-import java.time.format.DateTimeParseException;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.Collections;-import java.util.Comparator;-import java.util.List;-import java.util.Locale;-import java.util.Objects;-import java.util.Optional;--import javax.annotation.Nonnull;-import javax.annotation.Nullable;--public class YoutubeStreamExtractor extends StreamExtractor {-- private static final String PREMIERED = "Premiered ";- private static final String PREMIERED_ON = "Premiered on ";- private static final String FORMATS = "formats";- private static final String ADAPTIVE_FORMATS = "adaptiveFormats";- private static final String STREAMING_DATA = "streamingData";- private static final String NEXT = "next";- private static final String SIGNATURE_CIPHER = "signatureCipher";- private static final String CIPHER = "cipher";- private static final String PLAYER_CAPTIONS_TRACKLIST_RENDERER- = "playerCaptionsTracklistRenderer";- private static final String CAPTIONS = "captions";- private static final String PLAYABILITY_STATUS = "playabilityStatus";- private static final String THUMBNAIL = "thumbnail";- private static final String THUMBNAILS = "thumbnails";- private static final String VIDEO_DETAILS = "videoDetails";- private static final String TITLE = "title";-- @Nullable- private static PoTokenProvider poTokenProvider;- private static boolean fetchIosClient;-- private JsonObject playerResponse;- private JsonObject nextResponse;-- @Nullable- private JsonObject visionOsStreamingData;- @Nullable- private JsonObject iosStreamingData;- @Nullable- private JsonObject androidStreamingData;-- private JsonObject videoPrimaryInfoRenderer;- private JsonObject videoSecondaryInfoRenderer;- private JsonObject playerMicroFormatRenderer;- private JsonObject playerCaptionsTracklistRenderer;- private JsonArray thumbnailsArray;- private int ageLimit = -1;- private StreamType streamType;-- // We need to store the contentPlaybackNonces because we need to append them to videoplayback- // URLs (with the cpn parameter).- // Also because a nonce should be unique, it should be different between clients used, so- // three different strings are used.- private String visionOsCpn;- private String iosCpn;- private String androidCpn;-- @Nullable- private String androidStreamingUrlsPoToken;- @Nullable- private String iosStreamingUrlsPoToken;-- // SABR (Server Adaptive BitRate) session-based streams, built lazily from the ANDROID player- // response when it carries a serverAbrStreamingUrl.- private boolean sabrStreamsBuilt;- @Nonnull- private final List<AudioStream> sabrAudioStreams = new ArrayList<>();- @Nonnull- private final List<VideoStream> sabrVideoOnlyStreams = new ArrayList<>();-- public YoutubeStreamExtractor(final StreamingService service, final LinkHandler linkHandler) {- super(service, linkHandler);- }-- /*//////////////////////////////////////////////////////////////////////////- // Impl- //////////////////////////////////////////////////////////////////////////*/-- @Nonnull- @Override- public String getName() throws ParsingException {- assertPageFetched();- String title;-- // Try to get the video's original title, which is untranslated- title = playerResponse.getObject(VIDEO_DETAILS)- .getString(TITLE);-- if (isNullOrEmpty(title)) {- title = getTextFromObject(getVideoPrimaryInfoRenderer().getObject(TITLE));-- if (isNullOrEmpty(title)) {- throw new ParsingException("Could not get name");- }- }-- return title;- }-- @Nullable- @Override- public String getTextualUploadDate() {- String timestamp = playerMicroFormatRenderer.getString("uploadDate", "");- if (timestamp.isEmpty()) {- timestamp = playerMicroFormatRenderer.getString("publishDate", "");- }- if (!timestamp.isEmpty()) {- return timestamp;- }-- final var liveDetails = playerMicroFormatRenderer.getObject("liveBroadcastDetails");- timestamp = liveDetails.getString("endTimestamp", ""); // an ended live stream- if (timestamp.isEmpty()) {- // a running live stream- timestamp = liveDetails.getString("startTimestamp", "");- }- if (!timestamp.isEmpty()) {- return timestamp;- } else if (getStreamType() == StreamType.LIVE_STREAM) {- // this should never be reached, but a live stream without upload date is valid- return null;- }-- final var textObject = getVideoPrimaryInfoRenderer().getObject("dateText");- final String rendererDateText = getTextFromObject(textObject);- if (rendererDateText == null) {- return null;- } else if (rendererDateText.startsWith(PREMIERED_ON)) { // Premiered on 21 Feb 2020- return rendererDateText.substring(PREMIERED_ON.length());- } else if (rendererDateText.startsWith(PREMIERED)) {- // Premiered 20 hours ago / Premiered Feb 21, 2020- return rendererDateText.substring(PREMIERED.length());- } else {- return rendererDateText;- }- }-- @Override- public DateWrapper getUploadDate() throws ParsingException {- final String dateText = getTextualUploadDate();- try {- return DateWrapper.fromOffsetDateTime(dateText);- } catch (final ParsingException e) {- // Try other patterns first- }-- try { // Premiered 20 hours ago- final var localization = new Localization("en");- return TimeAgoPatternsManager.getTimeAgoParserFor(localization).parse(dateText);- } catch (final ParsingException e) {- // Try other patterns first- }-- return parseOptionalDate(dateText, "MMM dd, yyyy")- .or(() -> parseOptionalDate(dateText, "dd MMM yyyy"))- .map(date -> new DateWrapper(date.atStartOfDay(), true))- .orElseThrow(() ->- new ParsingException("Could not parse upload date \"" + dateText + "\""));- }-- private Optional<LocalDate> parseOptionalDate(final String date, final String pattern) {- try {- // TODO: this parses English formatted dates only, we need a better approach to parse- // the textual date- final var formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);- return Optional.of(LocalDate.parse(date, formatter));- } catch (final DateTimeParseException e) {- return Optional.empty();- }- }-- @Nonnull- @Override- public List<Image> getThumbnails() throws ParsingException {- assertPageFetched();- try {- return getImagesFromThumbnailsArray(thumbnailsArray);- } catch (final Exception e) {- throw new ParsingException("Could not get thumbnails");- }- }-- @Nonnull- @Override- public Description getDescription() throws ParsingException {- assertPageFetched();- // Description with more info on links- final String videoSecondaryInfoRendererDescription = getTextFromObject(- getVideoSecondaryInfoRenderer().getObject("description"),- true);- if (!isNullOrEmpty(videoSecondaryInfoRendererDescription)) {- return new Description(videoSecondaryInfoRendererDescription, Description.HTML);- }-- final String attributedDescription = attributedDescriptionToHtml(- getVideoSecondaryInfoRenderer().getObject("attributedDescription"));- if (!isNullOrEmpty(attributedDescription)) {- return new Description(attributedDescription, Description.HTML);- }-- String description = playerResponse.getObject(VIDEO_DETAILS)- .getString("shortDescription");- if (description == null) {- final JsonObject descriptionObject = playerMicroFormatRenderer.getObject("description");- description = getTextFromObject(descriptionObject);- }-- // Raw non-html description- return new Description(description, Description.PLAIN_TEXT);- }-- @Override- public int getAgeLimit() throws ParsingException {- if (ageLimit != -1) {- return ageLimit;- }-- final boolean ageRestricted = getVideoSecondaryInfoRenderer()- .getObject("metadataRowContainer")- .getObject("metadataRowContainerRenderer")- .getArray("rows")- .streamAsJsonObjects()- .flatMap(metadataRow -> metadataRow- .getObject("metadataRowRenderer")- .getArray("contents")- .streamAsJsonObjects())- .flatMap(content -> content- .getArray("runs")- .streamAsJsonObjects())- .map(run -> run.getString("text", ""))- .anyMatch(rowText -> rowText.contains("Age-restricted"));-- ageLimit = ageRestricted ? 18 : NO_AGE_LIMIT;- return ageLimit;- }-- @Override- public long getLength() throws ParsingException {- assertPageFetched();-- try {- final String duration = playerResponse.getObject(VIDEO_DETAILS)- .getString("lengthSeconds");- return Long.parseLong(duration);- } catch (final Exception e) {- return getDurationFromFirstAdaptiveFormat(Arrays.asList(- androidStreamingData, iosStreamingData));- }- }-- private int getDurationFromFirstAdaptiveFormat(@Nonnull final List<JsonObject> streamingDatas)- throws ParsingException {- for (final JsonObject streamingData : streamingDatas) {- final JsonArray adaptiveFormats = streamingData.getArray(ADAPTIVE_FORMATS);- if (adaptiveFormats.isEmpty()) {- continue;- }-- final String durationMs = adaptiveFormats.getObject(0)- .getString("approxDurationMs");- try {- return Math.round(Long.parseLong(durationMs) / 1000f);- } catch (final NumberFormatException ignored) {- }- }-- throw new ParsingException("Could not get duration");- }-- /**- * 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 {- final long timestamp =- getTimestampSeconds("((#|&|\\?)t=\\d*h?\\d*m?\\d+s?)");-- if (timestamp == -2) {- // Regex for timestamp was not found- return 0;- }- return timestamp;- }-- @Override- public long getViewCount() throws ParsingException {- String views = getTextFromObject(getVideoPrimaryInfoRenderer().getObject("viewCount")- .getObject("videoViewCountRenderer").getObject("viewCount"));-- if (isNullOrEmpty(views)) {- views = playerResponse.getObject(VIDEO_DETAILS)- .getString("viewCount");-- if (isNullOrEmpty(views)) {- throw new ParsingException("Could not get view count");- }- }-- if (views.toLowerCase().contains("no views")) {- return 0;- }-- return Long.parseLong(Utils.removeNonDigitCharacters(views));- }-- @Override- public long getLikeCount() throws ParsingException {- assertPageFetched();-- // If ratings are not allowed, there is no like count available- if (!playerResponse.getObject(VIDEO_DETAILS)- .getBoolean("allowRatings")) {- return -1L;- }-- final JsonArray topLevelButtons = getVideoPrimaryInfoRenderer()- .getObject("videoActions")- .getObject("menuRenderer")- .getArray("topLevelButtons");-- try {- return parseLikeCountFromLikeButtonViewModel(topLevelButtons);- } catch (final ParsingException ignored) {- // A segmentedLikeDislikeButtonRenderer could be returned instead of a- // segmentedLikeDislikeButtonViewModel, so ignore extraction errors relative to- // segmentedLikeDislikeButtonViewModel object- }-- try {- return parseLikeCountFromLikeButtonRenderer(topLevelButtons);- } catch (final ParsingException e) {- throw new ParsingException("Could not get like count", e);- }- }-- private static long parseLikeCountFromLikeButtonRenderer(- @Nonnull final JsonArray topLevelButtons) throws ParsingException {- String likesString = null;- final JsonObject likeToggleButtonRenderer = topLevelButtons.streamAsJsonObjects()- .map(button -> button.getObject("segmentedLikeDislikeButtonRenderer")- .getObject("likeButton")- .getObject("toggleButtonRenderer"))- .filter(toggleButtonRenderer -> !isNullOrEmpty(toggleButtonRenderer))- .findFirst()- .orElse(null);-- if (likeToggleButtonRenderer != null) {- // Use one of the accessibility strings available (this one has the same path as the- // one used for comments' like count extraction)- likesString = likeToggleButtonRenderer.getObject("accessibilityData")- .getObject("accessibilityData")- .getString("label");-- // Use the other accessibility string available which contains the exact like count- if (likesString == null) {- likesString = likeToggleButtonRenderer.getObject("accessibility")- .getString("label");- }-- // Last method: use the defaultText's accessibility data, which contains the exact like- // count too, except when it is equal to 0, where a localized string is returned instead- if (likesString == null) {- likesString = likeToggleButtonRenderer.getObject("defaultText")- .getObject("accessibility")- .getObject("accessibilityData")- .getString("label");- }-- // This check only works with English localizations!- if (likesString != null && likesString.toLowerCase().contains("no likes")) {- return 0;- }- }-- // If ratings are allowed and the likes string is null, it means that we couldn't extract- // the full like count from accessibility data- if (likesString == null) {- throw new ParsingException("Could not get like count from accessibility data");- }-- try {- return Long.parseLong(Utils.removeNonDigitCharacters(likesString));- } catch (final NumberFormatException e) {- throw new ParsingException("Could not parse \"" + likesString + "\" as a long", e);- }- }-- private static long parseLikeCountFromLikeButtonViewModel(- @Nonnull final JsonArray topLevelButtons) throws ParsingException {- // Try first with the current video actions buttons data structure- final JsonObject likeToggleButtonViewModel = topLevelButtons.streamAsJsonObjects()- .map(button -> button.getObject("segmentedLikeDislikeButtonViewModel")- .getObject("likeButtonViewModel")- .getObject("likeButtonViewModel")- .getObject("toggleButtonViewModel")- .getObject("toggleButtonViewModel")- .getObject("defaultButtonViewModel")- .getObject("buttonViewModel"))- .filter(buttonViewModel -> !isNullOrEmpty(buttonViewModel))- .findFirst()- .orElse(null);-- if (likeToggleButtonViewModel == null) {- throw new ParsingException("Could not find buttonViewModel object");- }-- final String accessibilityText = likeToggleButtonViewModel.getString("accessibilityText");- if (accessibilityText == null) {- throw new ParsingException("Could not find buttonViewModel's accessibilityText string");- }-- // The like count is always returned as a number in this element, even for videos with no- // likes- try {- return Long.parseLong(Utils.removeNonDigitCharacters(accessibilityText));- } catch (final NumberFormatException e) {- throw new ParsingException(- "Could not parse \"" + accessibilityText + "\" as a long", e);- }- }-- @Nonnull- @Override- public String getUploaderUrl() throws ParsingException {- assertPageFetched();-- // Don't use the id in the videoSecondaryRenderer object to get real id of the uploader- // The difference between the real id of the channel and the displayed id is especially- // visible for music channels and autogenerated channels.- final String uploaderId = playerResponse.getObject(VIDEO_DETAILS)- .getString("channelId");- if (!isNullOrEmpty(uploaderId)) {- return YoutubeChannelLinkHandlerFactory.getInstance().getUrl("channel/" + uploaderId);- }-- throw new ParsingException("Could not get uploader url");- }-- @Nonnull- @Override- public String getUploaderName() throws ParsingException {- assertPageFetched();-- // Don't use the name in the videoSecondaryRenderer object to get real name of the uploader- // The difference between the real name of the channel and the displayed name is especially- // visible for music channels and autogenerated channels.- final String uploaderName = playerResponse.getObject(VIDEO_DETAILS)- .getString("author");- if (isNullOrEmpty(uploaderName)) {- throw new ParsingException("Could not get uploader name");- }-- return uploaderName;- }-- @Override- public boolean isUploaderVerified() throws ParsingException {- final JsonObject videoOwnerRenderer = getVideoSecondaryInfoRenderer()- .getObject("owner")- .getObject("videoOwnerRenderer");-- if (videoOwnerRenderer.has("badges")) {- return YoutubeParsingHelper.isVerified(videoOwnerRenderer- .getArray("badges"));- }--- final JsonObject channel = YoutubeParsingHelper.getFirstCollaborator(- videoOwnerRenderer.getObject("navigationEndpoint"));- if (channel == null) {- return false;- }-- return YoutubeParsingHelper.hasArtistOrVerifiedIconBadgeAttachment(- channel.getObject(TITLE)- .getArray("attachmentRuns"));- }-- @Nonnull- @Override- public List<Image> getUploaderAvatars() throws ParsingException {- assertPageFetched();- final JsonObject owner = getVideoSecondaryInfoRenderer().getObject("owner")- .getObject("videoOwnerRenderer");-- final List<Image> imageList;- if (owner.has("avatarStack")) {- imageList = getImagesFromThumbnailsArray(- owner.getObject("avatarStack").getObject("avatarStackViewModel")- .getArray("avatars")- // only consider the first collaborator, which is the video owner- .getObject(0)- .getObject("avatarViewModel")- .getObject("image")- .getArray("sources"));- } else {- imageList = getImagesFromThumbnailsArray(owner.getObject(THUMBNAIL)- .getArray(THUMBNAILS));- }-- if (imageList.isEmpty() && ageLimit == NO_AGE_LIMIT) {- throw new ParsingException("Could not get uploader avatars");- }-- return imageList;- }-- @Override- public long getUploaderSubscriberCount() throws ParsingException {- final JsonObject videoOwnerRenderer = JsonUtils.getObject(videoSecondaryInfoRenderer,- "owner.videoOwnerRenderer");-- String subscriberCountText = null;- if (videoOwnerRenderer.has("subscriberCountText")) {- subscriberCountText = getTextFromObject(videoOwnerRenderer- .getObject("subscriberCountText"));- } else {- final String content = YoutubeParsingHelper.getFirstCollaborator(- videoOwnerRenderer.getObject("navigationEndpoint")- ).getObject("subtitle").getString("content");- subscriberCountText = content.split("•")[1];- }-- if (isNullOrEmpty(subscriberCountText)) {- return UNKNOWN_SUBSCRIBER_COUNT;- }-- try {- return Utils.mixedNumberWordToLong(subscriberCountText);- } catch (final NumberFormatException e) {- throw new ParsingException("Could not get uploader subscriber count", e);- }- }-- @Nonnull- @Override- public String getDashMpdUrl() throws ParsingException {- assertPageFetched();-- // There is no DASH manifest available with the iOS and visionOS clients- return getManifestUrl(- "dash",- List.of(new Pair<>(androidStreamingData, androidStreamingUrlsPoToken)),- // Return version 7 of the DASH manifest, which is the latest one, reducing- // manifest size and allowing playback with some DASH players- "mpd_version=7");- }-- @Nonnull- @Override- public String getHlsUrl() throws ParsingException {- assertPageFetched();-- // Return HLS manifest of an Apple client first because on livestreams, the HLS manifest- // returned has separated audio and video streams- // Also, on videos, non-Apple clients don't have an HLS manifest URL in their player- // response- return getManifestUrl(- "hls",- List.of(new Pair<>(visionOsStreamingData, null),- new Pair<>(iosStreamingData, iosStreamingUrlsPoToken),- new Pair<>(androidStreamingData, androidStreamingUrlsPoToken)),- "");- }-- @Nonnull- private static String getManifestUrl(- @Nonnull final String manifestType,- @Nonnull final List<Pair<JsonObject, String>> streamingDataObjects,- @Nonnull final String partToAppendToManifestUrlEnd) {- final String manifestKey = manifestType + "ManifestUrl";-- for (final Pair<JsonObject, String> streamingDataObj : streamingDataObjects) {- if (streamingDataObj.getFirst() != null) {- final String manifestUrl = streamingDataObj.getFirst().getString(manifestKey);- if (isNullOrEmpty(manifestUrl)) {- continue;- }-- // If poToken is not null, add it to manifest URL- if (streamingDataObj.getSecond() == null) {- return manifestUrl + "?" + partToAppendToManifestUrlEnd;- } else {- return manifestUrl + "?pot=" + streamingDataObj.getSecond() + "&"- + partToAppendToManifestUrlEnd;- }- }- }-- return "";- }-- @Override- public List<AudioStream> getAudioStreams() throws ExtractionException {- assertPageFetched();- final List<AudioStream> streams = getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.AUDIO,- getAudioStreamBuilderHelper(), "audio");- buildSabrStreamsIfNeeded();- streams.addAll(sabrAudioStreams);- return streams;- }-- @Override- public List<VideoStream> getVideoStreams() throws ExtractionException {- assertPageFetched();- return getItags(FORMATS, ItagItem.ItagType.VIDEO,- getVideoStreamBuilderHelper(false), "video");- }-- @Override- public List<VideoStream> getVideoOnlyStreams() throws ExtractionException {- assertPageFetched();- final List<VideoStream> streams = getItags(ADAPTIVE_FORMATS, ItagItem.ItagType.VIDEO_ONLY,- getVideoStreamBuilderHelper(true), "video-only");- buildSabrStreamsIfNeeded();- streams.addAll(sabrVideoOnlyStreams);- return streams;- }-- @Override- @Nonnull- public List<SubtitlesStream> getSubtitlesDefault() throws ParsingException {- return getSubtitles(MediaFormat.TTML);- }-- @Override- @Nonnull- public List<SubtitlesStream> getSubtitles(final MediaFormat format) throws ParsingException {- assertPageFetched();-- // We cannot store the subtitles list because the media format may change- final List<SubtitlesStream> subtitlesToReturn = new ArrayList<>();- final JsonArray captionsArray = playerCaptionsTracklistRenderer.getArray("captionTracks");- // TODO: use this to apply auto translation to different language from a source language- // final JsonArray autoCaptionsArray = renderer.getArray("translationLanguages");-- for (int i = 0; i < captionsArray.size(); 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.");- final String cleanUrl = baseUrl- // Remove preexisting format if exists- .replaceAll("&fmt=[^&]*", "")- // Remove translation language- .replaceAll("&tlang=[^&]*", "");-- subtitlesToReturn.add(new SubtitlesStream.Builder()- .setContent(cleanUrl + "&fmt=" + format.getSuffix(), true)- .setMediaFormat(format)- .setLanguageCode(languageCode)- .setAutoGenerated(isAutoGenerated)- .build());- }- }-- return subtitlesToReturn;- }-- @Override- public StreamType getStreamType() {- assertPageFetched();-- return streamType;- }-- private void setStreamType() {- if (playerResponse.getObject(PLAYABILITY_STATUS).has("liveStreamability")) {- streamType = StreamType.LIVE_STREAM;- } else if (playerResponse.getObject(VIDEO_DETAILS)- .getBoolean("isPostLiveDvr", false)) {- streamType = StreamType.POST_LIVE_STREAM;- } else {- streamType = StreamType.VIDEO_STREAM;- }- }-- @Nullable- @Override- public MultiInfoItemsCollector getRelatedItems() throws ExtractionException {- assertPageFetched();-- if (getAgeLimit() != NO_AGE_LIMIT) {- return null;- }-- try {- final MultiInfoItemsCollector collector = new MultiInfoItemsCollector(getServiceId());-- final JsonArray results = nextResponse- .getObject("contents")- .getObject("twoColumnWatchNextResults")- .getObject("secondaryResults")- .getObject("secondaryResults")- .getArray("results");-- final TimeAgoParser timeAgoParser = getTimeAgoParser();- results.streamAsJsonObjects()- .map(result -> {- if (result.has("compactVideoRenderer")) {- return new YoutubeStreamInfoItemExtractor(- result.getObject("compactVideoRenderer"), timeAgoParser);- } else if (result.has("compactRadioRenderer")) {- return new YoutubeMixOrPlaylistInfoItemExtractor(- result.getObject("compactRadioRenderer"));- } else if (result.has("compactPlaylistRenderer")) {- return new YoutubeMixOrPlaylistInfoItemExtractor(- result.getObject("compactPlaylistRenderer"));- } else if (result.has("lockupViewModel")) {- final JsonObject lockupViewModel = result.getObject("lockupViewModel");- final String contentType = lockupViewModel.getString("contentType");- if ("LOCKUP_CONTENT_TYPE_PLAYLIST".equals(contentType)- || "LOCKUP_CONTENT_TYPE_PODCAST".equals(contentType)) {- return new YoutubeMixOrPlaylistLockupInfoItemExtractor(- lockupViewModel);- } else if ("LOCKUP_CONTENT_TYPE_VIDEO".equals(contentType)) {- return new YoutubeStreamInfoItemLockupExtractor(- lockupViewModel, timeAgoParser);- }- }- return null;- })- .filter(Objects::nonNull)- .forEach(collector::commit);-- return collector;- } catch
Diff truncated.