youpipe: read SponsorBlock/DeArrow from static R2 shards first (#static-r2)
- Commit
07df9ad27c4ad480cf7bd5bb2b03e64cca223a57- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 22:37 UTC (22 days ago)
- Parents
d43cc1f
What changed: getSponsorSegments and getDeArrowBranding first fetch the
static shard for the video from https://static.maproj.org/sb/v1/
{segments,branding}/<first 4 hex of sha256(videoID)>.json, and only fall
back to api.maproj.org/api/skipSegments and /api/branding when the shard
is not there (404, unreachable, or undecodable).
Why: /api/branding is the second-busiest server endpoint (7.8k calls a
day) and /api/skipSegments adds 285; both answer the same thing for
every user and only change when the server's SponsorBlock mirror is
rebuilt. The server (location_share_server feat/static-r2,
src/static_r2/sb_shards.rs) now publishes the whole catalog as 65,536
hash-prefix shards in SponsorBlock's privacy-API shape, so the app's
lookups stop costing the server anything. Side benefit: the request
names only a 4-hex-digit hash prefix shared by ~70 videos, so neither
the server nor Cloudflare learns which video is being watched.
Details:
- A shard that loads is authoritative: a video missing from it has no
segments / no branding (the server writes every shard, empty ones as
[] / {}, so a 404 only ever means "not published yet").
- Segment shards carry every action type; the app keeps skip and mute,
which is exactly what the endpoint returns by default (it was called
without actionTypes), with the same dedup applied server-side.
- Missing branding becomes an empty DeArrowBranding, the same as the
endpoint's empty answer (no title or thumbnail override).
- SPONSORBLOCK_STATIC is an internal var like SPONSORBLOCK_MIRROR so
the unreachable-host tests stay hermetic.
User-visible effect: none, beyond working when the server is slow.
Verified: new SbShardTest (sha256 prefix "5f6b" for dQw4w9WgXcQ checked
with sha256sum; segment filtering to skip/mute for the right video;
absent video and empty shard; branding present / absent);
W5Slice2ExtractorHttpTest now also points the static base at the
closed port. Run via :youpipe:testDevUnitTest in the container build.Diff
youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.ktindex 19a6d62ebf..90b1df6096 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt@@ -2,15 +2,18 @@ package com.vayunmathur.youpipe.util import androidx.core.net.toUri import androidx.core.text.HtmlCompat import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.StaticMirror import com.vayunmathur.youpipe.ui.ChannelInfo import com.vayunmathur.youpipe.ui.VideoInfo import kotlinx.coroutines.coroutineScope import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json import org.schabi.newpipe.extractor.ServiceList import org.schabi.newpipe.extractor.stream.ContentAvailability import org.schabi.newpipe.extractor.stream.StreamInfoItem import java.nio.ByteBuffer+import java.security.MessageDigest import kotlin.io.encoding.Base64 import kotlin.time.toKotlinInstant @@ -177,7 +180,8 @@ data class DeArrowBranding( ) /**- * SponsorBlock + DeArrow data APIs are mirrored on the self-hosted proxy+ * SponsorBlock + DeArrow data APIs are mirrored on the self-hosted proxy (and+ * published as static shards, see [SPONSORBLOCK_STATIC]) * (see location_share_server `sb_build.sh` + handlers/sponsorblock.rs), served * from a local copy of the SponsorBlock database. DeArrow thumbnail *frames* * are now self-hosted via the same origin (yt-dlp + ffmpeg renderer implemented@@ -191,10 +195,66 @@ data class DeArrowBranding( internal var SPONSORBLOCK_MIRROR = "https://api.maproj.org" internal var DEARROW_THUMB_MIRROR = "https://api.maproj.org/api/dearrow/thumbnail" +/**+ * The same SponsorBlock/DeArrow data as static shards on R2+ * (location_share_server `src/static_r2/sb_shards.rs`): one file per first+ * [SB_SHARD_PREFIX_HEX] hex digits of sha256(videoID), holding every video in+ * that range. Read first; the endpoints above are the fallback. A shard that+ * loads is authoritative (a video missing from it has no data), and since only+ * the hash prefix is requested, nobody learns which video is being watched.+ */+internal var SPONSORBLOCK_STATIC = "${StaticMirror.BASE}/sb/v1"++/** Must match the server's `PREFIX_HEX`. */+private const val SB_SHARD_PREFIX_HEX = 4++private val sbShardJson = Json { ignoreUnknownKeys = true }++/** First [SB_SHARD_PREFIX_HEX] lowercase hex digits of sha256([videoId]). */+internal fun sbShardPrefix(videoId: String): String =+ MessageDigest.getInstance("SHA-256").digest(videoId.toByteArray(Charsets.UTF_8))+ .joinToString("") { "%02x".format(it) }+ .take(SB_SHARD_PREFIX_HEX)++@Serializable+internal data class SbShardVideo(+ val videoID: String,+ val segments: List<SbShardSegment> = emptyList(),+)++@Serializable+internal data class SbShardSegment(+ val category: String,+ val segment: List<Float>,+ @SerialName("UUID") val uuid: String,+ val actionType: String = "skip",+)++/**+ * [videoId]'s segments out of a segments shard, limited to the action types the+ * endpoint returns by default (skip, mute); the shard carries every type.+ */+internal fun segmentsFromShard(body: String, videoId: String): List<SponsorSegment> =+ sbShardJson.decodeFromString<List<SbShardVideo>>(body)+ .firstOrNull { it.videoID == videoId }+ ?.segments.orEmpty()+ .filter { it.actionType == "skip" || it.actionType == "mute" }+ .map { SponsorSegment(it.category, it.segment, it.uuid) }++/** [videoId]'s branding out of a branding shard; absent = no branding (empty, as the endpoint answers). */+internal fun brandingFromShard(body: String, videoId: String): DeArrowBranding =+ sbShardJson.decodeFromString<Map<String, DeArrowBranding>>(body)[videoId]+ ?: DeArrowBranding(titles = emptyList(), thumbnails = emptyList(), randomTime = 0.0)++/** The shard body for [videoId] under [kind] (`segments` / `branding`), or null when not published. */+private suspend fun sbShard(kind: String, videoId: String): String? =+ StaticMirror.getStatic("$SPONSORBLOCK_STATIC/$kind/${sbShardPrefix(videoId)}.json")?.text+ suspend fun getDeArrowBranding(videoId: Long): DeArrowBranding? { val idString = decodeVideoID(videoId) return try {- NetworkClient.getJson<DeArrowBranding>("$SPONSORBLOCK_MIRROR/api/branding?videoID=$idString")+ sbShard("branding", idString)?.let { runCatching { brandingFromShard(it, idString) }.getOrNull() }+ ?: NetworkClient.getJson<DeArrowBranding>("$SPONSORBLOCK_MIRROR/api/branding?videoID=$idString") } catch (_: Exception) { // Best-effort enrichment: branding is optional, feed plays fine without it. null@@ -220,7 +280,8 @@ fun DeArrowBranding.trustedThumbnailUrl(videoId: Long): String? { suspend fun getSponsorSegments(videoId: Long): List<SponsorSegment> { val idString = decodeVideoID(videoId) return try {- NetworkClient.getJson("$SPONSORBLOCK_MIRROR/api/skipSegments?videoID=$idString")+ sbShard("segments", idString)?.let { runCatching { segmentsFromShard(it, idString) }.getOrNull() }+ ?: NetworkClient.getJson("$SPONSORBLOCK_MIRROR/api/skipSegments?videoID=$idString") } catch (_: Exception) { // Best-effort enrichment: no segments simply means no auto-skip for this video. emptyList()
youpipe/src/test/java/com/vayunmathur/youpipe/util/SbShardTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/SbShardTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/SbShardTest.ktnew file mode 100644index 0000000000..8bc8e61b99--- /dev/null+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/SbShardTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.youpipe.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Static SponsorBlock/DeArrow shard parsing (same shapes as the server's sb_shards.rs). */+class SbShardTest {++ @Test+ fun prefix_is_the_first_four_hex_digits_of_sha256() {+ // sha256("dQw4w9WgXcQ") starts 5f6b (computed independently with sha256sum).+ assertEquals(SHA_PREFIX, sbShardPrefix("dQw4w9WgXcQ"))+ assertEquals(4, sbShardPrefix("x").length)+ }++ @Test+ fun segments_keep_the_endpoints_default_action_types_for_the_right_video() {+ val body = """[+ {"videoID":"other","hash":"h","segments":[{"UUID":"o","segment":[1,2],"category":"sponsor","actionType":"skip"}]},+ {"videoID":"dQw4w9WgXcQ","hash":"h","segments":[+ {"UUID":"a","segment":[10.5,20],"category":"sponsor","actionType":"skip","votes":3,"locked":0},+ {"UUID":"b","segment":[30,31],"category":"music_offtopic","actionType":"mute"},+ {"UUID":"c","segment":[40,40],"category":"poi_highlight","actionType":"poi"},+ {"UUID":"d","segment":[0,600],"category":"exclusive_access","actionType":"full"}+ ]}+ ]"""+ val segs = segmentsFromShard(body, "dQw4w9WgXcQ")+ assertEquals(listOf("a", "b"), segs.map { it.uuid })+ assertEquals(10_500L, segs[0].start)+ assertTrue(segmentsFromShard(body, "absent").isEmpty())+ assertTrue(segmentsFromShard("[]", "dQw4w9WgXcQ").isEmpty())+ }++ @Test+ fun branding_absent_from_its_shard_is_empty() {+ val body = """{"dQw4w9WgXcQ":{"titles":[{"title":"Better","original":false,"votes":2,"locked":false,"UUID":"t"}],+ "thumbnails":[],"randomTime":0.25,"videoDuration":212.0}}"""+ assertEquals("Better", brandingFromShard(body, "dQw4w9WgXcQ").trustedTitle())+ val none = brandingFromShard(body, "absent")+ assertTrue(none.titles.isEmpty() && none.thumbnails.isEmpty())+ assertEquals(null, brandingFromShard("{}", "x").trustedTitle())+ }++ private companion object {+ const val SHA_PREFIX = "5f6b"+ }+}
youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt
diff --git a/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.ktindex 5cbaa12f56..9e0338332b 100644--- a/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt+++ b/youpipe/src/test/java/com/vayunmathur/youpipe/util/W5Slice2ExtractorHttpTest.kt@@ -18,18 +18,21 @@ import kotlin.test.assertNull class W5Slice2ExtractorHttpTest { private val realSponsor = SPONSORBLOCK_MIRROR+ private val realStatic = SPONSORBLOCK_STATIC private val realThumb = DEARROW_THUMB_MIRROR @BeforeTest fun pointAtClosedPort() { // Port 1 is never bound: connect() fails fast with "refused". SPONSORBLOCK_MIRROR = "http://127.0.0.1:1"+ SPONSORBLOCK_STATIC = "http://127.0.0.1:1/sb/v1" DEARROW_THUMB_MIRROR = "http://127.0.0.1:1/api/dearrow/thumbnail" } @AfterTest fun restoreMirrors() { SPONSORBLOCK_MIRROR = realSponsor+ SPONSORBLOCK_STATIC = realStatic DEARROW_THUMB_MIRROR = realThumb }