Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
14830c0
feat(stories): the feed, the story of a link and the events of storie…
Xyzcancer Nov 20, 2026
9f5483e
feat(stories): poll answers of stories over API v3 are kept on the de…
Xyzcancer Nov 20, 2026
38f8ef4
feat(stories): stories over API v3 behave as the web SDK does: a stor…
Xyzcancer Nov 20, 2026
353af8e
docs(readme): how an app opens the shared links of stories over API v…
Xyzcancer Nov 20, 2026
50e1da8
feat(stories): the viewer of stories over API v3 keeps the sound butt…
Xyzcancer Nov 20, 2026
2e5468b
fix(stories): the sound button's choice of stories over API v3 is kep…
Xyzcancer Nov 20, 2026
b9abd33
docs(readme): the shared links of stories over API v3 leave the READM…
Xyzcancer Nov 20, 2026
6046900
feat(stories): stories over API v3 skip a slide that is neither image…
Xyzcancer Nov 20, 2026
ee378c3
fix(stories): a story over API v3 with nothing to show from its start…
Xyzcancer Nov 23, 2026
91032f9
fix(stories): going back on the first slide of the first story over A…
Xyzcancer Nov 23, 2026
a9c74eb
fix(stories): the ring of a story over API v3 in the bar lights no se…
Xyzcancer Nov 23, 2026
b4ce8f1
fix(stories): the Android bridge reads a video's audio track on a thr…
Xyzcancer Nov 23, 2026
5277044
fix(stories): the viewer of stories over API v3 keeps a mute state of…
Xyzcancer Nov 23, 2026
0f69e3b
fix(stories): the header element, text_italic and the monospace and c…
Xyzcancer Nov 23, 2026
89b274f
fix(stories): a slide over API v3 without media takes the kit's light…
Xyzcancer Nov 23, 2026
a1f660b
fix(stories): text blocks over API v3 take bold from bold first and t…
Xyzcancer Nov 23, 2026
2b2e85b
fix(stories): a poll answer over API v3 the server accepted is shown …
Xyzcancer Nov 23, 2026
ce36247
fix(stories): a poll over API v3 counts as answered as the web's hasA…
Xyzcancer Nov 23, 2026
1ec9d21
fix(stories): every poll element of a slide over API v3 is drawn, eac…
Xyzcancer Nov 23, 2026
2823dee
fix(stories): a poll card over API v3 keeps 16 from the sides instead…
Xyzcancer Nov 23, 2026
02c046b
fix(stories): the header of a slide over API v3 has a 40 icon, 12 to …
Xyzcancer Nov 23, 2026
1aca8ae
fix(stories): stories over API v3 follow the last cross-platform rule…
Xyzcancer Nov 23, 2026
d440106
fix(stories): over API v3 a forward swipe on the last story marks it …
Xyzcancer Nov 23, 2026
dbc8cc3
fix(stories): the built-in poll texts of stories over API v3 are the …
Xyzcancer Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ class Rees46FlutterSdkPlugin :
/** Which tokens Dart's `onToken` hears. */
private val tokenReports = TokenReports()

/** Whether a stories video has sound: the viewer's sound button. */
internal var storiesVideoAudio = StoriesVideoAudio()

/** This engine's Dart side of the native log, while Dart has a log handler. */
private val logSink: (SdkLogMessage) -> Unit = { message ->
onMain { runCatching { stateApi?.onLog(message.toWire()) { } } }
Expand Down Expand Up @@ -1016,6 +1019,9 @@ class Rees46FlutterSdkPlugin :

override fun endStoriesAudio() = Unit

override fun storiesVideoHasAudio(source: String, callback: (Result<Boolean?>) -> Unit) =
storiesVideoAudio.hasAudio(source, callback)

// endregion

// endregion
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.rees46.rees46_flutter_sdk

import android.media.MediaMetadataRetriever
import android.os.Handler
import android.os.Looper
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean

/**
* Whether a stories video has an audio track: the viewer hides its sound button only when the
* track list says there is none. The container is read off the main thread (a network video
* reads its header over the network), each read on a thread of its own, so a read that hangs
* does not hold the next ones. A read that is not done in [timeoutMs] answers null
* (inconclusive: the button stays). The answer goes back on the main thread, where Pigeon
* replies, exactly once.
*/
internal class StoriesVideoAudio(
private val probe: (String) -> Boolean? = ::readHasAudio,
private val worker: Executor = defaultWorker,
private val main: (Runnable) -> Unit = { mainHandler.post(it) },
private val schedule: (Long, Runnable) -> Unit = { delay, task ->
mainHandler.postDelayed(task, delay)
},
private val timeoutMs: Long = TIMEOUT_MS,
) {

/** Answers [callback] with the audio of [source]: null when it cannot be read in time. */
fun hasAudio(source: String, callback: (Result<Boolean?>) -> Unit) {
val answered = AtomicBoolean(false)
fun reply(answer: Boolean?) {
if (answered.compareAndSet(false, true)) {
main(Runnable { callback(Result.success(answer)) })
}
}
schedule(timeoutMs, Runnable { reply(null) })
try {
worker.execute {
val answer = try {
probe(source)
} catch (e: Exception) {
null
}
reply(answer)
}
} catch (e: Exception) {
// No thread for the read: inconclusive.
reply(null)
}
}

companion object {
/** How long a read may take before the answer is inconclusive. */
const val TIMEOUT_MS = 5_000L

/** A thread per read, kept a minute for the next one; daemon threads. */
private val defaultWorker: Executor by lazy {
Executors.newCachedThreadPool { task ->
Thread(task, "rees46-stories-audio").apply { isDaemon = true }
}
}
private val mainHandler: Handler by lazy { Handler(Looper.getMainLooper()) }

/** `http(s)` addresses are read over the network, anything else is a file path. */
fun isRemote(source: String): Boolean =
source.startsWith("http://", ignoreCase = true) ||
source.startsWith("https://", ignoreCase = true)

/**
* `METADATA_KEY_HAS_AUDIO` is there only when the container has an audio track; null
* when the source cannot be opened.
*/
fun readHasAudio(source: String): Boolean? {
val retriever = MediaMetadataRetriever()
return try {
if (isRemote(source)) {
retriever.setDataSource(source, emptyMap())
} else {
retriever.setDataSource(source)
}
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO) != null
} catch (e: Exception) {
null
} finally {
try {
retriever.release()
} catch (e: Exception) {
// Nothing was opened.
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4913,6 +4913,14 @@ interface PersonalizationHostApi {
* watching the volume. iOS only; a no-op on Android.
*/
fun endStoriesAudio()
/**
* Whether the video at [source] — an `http(s)` URL or a file path of the stories'
* video cache — has an audio track: the stories viewer shows its sound button only
* then, as the web SDK does. Read off the main thread from the container's track
* list (Android `MediaMetadataRetriever`, iOS `AVURLAsset`); null when it cannot be
* read.
*/
fun storiesVideoHasAudio(source: String, callback: (Result<Boolean?>) -> Unit)
/**
* Opens the system settings where the user turns notifications on for the app: the
* app's notification settings on Android, the app's page in Settings on iOS. What the
Expand Down Expand Up @@ -7063,6 +7071,26 @@ interface PersonalizationHostApi {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.storiesVideoHasAudio$separatedMessageChannelSuffix", codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val sourceArg = args[0] as String
api.storiesVideoHasAudio(sourceArg) { result: Result<Boolean?> ->
val error = result.exceptionOrNull()
if (error != null) {
reply.reply(PersonalizationApiPigeonUtils.wrapError(error))
} else {
val data = result.getOrNull()
reply.reply(PersonalizationApiPigeonUtils.wrapResult(data))
}
}
}
} else {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings$separatedMessageChannelSuffix", codec)
if (api != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package com.rees46.rees46_flutter_sdk

import java.util.concurrent.Executor
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

internal class StoriesVideoAudioTest {
/** Runs the work when asked, so the order of the threads is visible. */
private class Queue : Executor {
val tasks = mutableListOf<Runnable>()
override fun execute(command: Runnable) {
tasks += command
}

fun run() {
val pending = tasks.toList()
tasks.clear()
pending.forEach { it.run() }
}
}

@Test
fun theProbeRunsOffTheCallerAndTheAnswerComesOnTheMainThread() {
val worker = Queue()
val main = Queue()
val probed = mutableListOf<String>()
val audio = StoriesVideoAudio(
probe = { probed += it; true },
worker = worker,
main = { main.execute(it) },
schedule = { _, _ -> },
)
val answers = mutableListOf<Result<Boolean?>>()
audio.hasAudio("https://cdn.example/v.mp4") { answers += it }
assertTrue(probed.isEmpty(), "not on the caller's thread")
worker.run()
assertEquals(listOf("https://cdn.example/v.mp4"), probed)
assertTrue(answers.isEmpty(), "the reply waits for the main thread")
main.run()
assertEquals(true, answers.single().getOrNull())
}

@Test
fun noAudioIsFalseAndAFailedReadIsNull() {
val direct = Executor { it.run() }
val answers = mutableListOf<Boolean?>()
val never: (Long, Runnable) -> Unit = { _, _ -> }
StoriesVideoAudio(probe = { false }, worker = direct, main = { it.run() }, schedule = never)
.hasAudio("/cache/v.mp4") { answers += it.getOrThrow() }
StoriesVideoAudio(
probe = { throw IllegalStateException("broken") },
worker = direct,
main = { it.run() },
schedule = never,
).hasAudio("/cache/v.mp4") { answers += it.getOrThrow() }
StoriesVideoAudio(probe = { null }, worker = direct, main = { it.run() }, schedule = never)
.hasAudio("x") { answers += it.getOrThrow() }
assertEquals(listOf<Boolean?>(false, null, null), answers)
}

@Test
fun aReadNotDoneInTimeIsInconclusiveAndAnsweredOnce() {
val worker = Queue()
val timers = mutableListOf<Pair<Long, Runnable>>()
val answers = mutableListOf<Boolean?>()
StoriesVideoAudio(
probe = { false },
worker = worker,
main = { it.run() },
schedule = { delay, task -> timers += delay to task },
).hasAudio("https://cdn.example/slow.mp4") { answers += it.getOrThrow() }
assertEquals(listOf(StoriesVideoAudio.TIMEOUT_MS), timers.map { it.first })
timers.single().second.run()
assertEquals(listOf<Boolean?>(null), answers, "the time is up: the button stays")
worker.run()
assertEquals(listOf<Boolean?>(null), answers, "the late read is dropped")
}

@Test
fun aHangingReadDoesNotHoldTheNextOne() {
val release = java.util.concurrent.CountDownLatch(1)
val done = java.util.concurrent.CountDownLatch(1)
val answers = java.util.Collections.synchronizedList(mutableListOf<Boolean?>())
val audio = StoriesVideoAudio(
probe = { source ->
if (source == "hang") release.await()
true
},
main = { it.run() },
schedule = { _, _ -> },
)
audio.hasAudio("hang") { }
audio.hasAudio("next") { answers += it.getOrThrow(); done.countDown() }
assertTrue(done.await(5, java.util.concurrent.TimeUnit.SECONDS))
assertEquals(listOf<Boolean?>(true), answers)
release.countDown()
}

@Test
fun httpAddressesAreRemoteTheRestAreFiles() {
assertTrue(StoriesVideoAudio.isRemote("https://cdn.example/v.mp4"))
assertTrue(StoriesVideoAudio.isRemote("HTTP://cdn.example/v.mp4"))
assertFalse(StoriesVideoAudio.isRemote("/data/user/0/app/cache/stories/v.mp4"))
assertFalse(StoriesVideoAudio.isRemote("file:///cache/v.mp4"))
}

@Test
fun thePluginAnswersThroughIt() {
val plugin = Rees46FlutterSdkPlugin()
plugin.storiesVideoAudio = StoriesVideoAudio(
probe = { it.endsWith("sound.mp4") },
worker = { it.run() },
main = { it.run() },
schedule = { _, _ -> },
)
val answers = mutableListOf<Boolean?>()
plugin.storiesVideoHasAudio("https://cdn.example/sound.mp4") { answers += it.getOrThrow() }
plugin.storiesVideoHasAudio("https://cdn.example/mute.mp4") { answers += it.getOrThrow() }
assertEquals(listOf<Boolean?>(true, false), answers)
}
}
93 changes: 93 additions & 0 deletions example/ios/RunnerTests/RootBridgeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,96 @@ final class PendingPushesTests: XCTestCase {
XCTAssertEqual(pending.count("shop-a"), PendingPushes.limit)
}
}

/// Whether a stories video has sound: read off the main thread, answered on it; a source that
/// cannot be read is `nil`.
final class StoriesVideoAudioTests: XCTestCase {

private var original: ((URL) async throws -> Bool)!

override func setUp() {
super.setUp()
original = StoriesVideoAudio.loader
}

override func tearDown() {
StoriesVideoAudio.loader = original
super.tearDown()
}

private func answer(_ source: String, through plugin: Bool = false) -> Bool?? {
let done = expectation(description: "answer")
var result: Bool??
let reply: (Bool?) -> Void = { value in
XCTAssertTrue(Thread.isMainThread)
result = .some(value)
done.fulfill()
}
if plugin {
let impl = PersonalizationHostApiImpl(
popupApi: PersonalizationPopupFlutterApi(binaryMessenger: SilentMessenger()),
stateApi: PersonalizationStateFlutterApi(binaryMessenger: SilentMessenger())
)
impl.storiesVideoHasAudio(source: source) { reply(try? $0.get()) }
wait(for: [done], timeout: 5)
impl.stop()
} else {
StoriesVideoAudio.hasAudio(source: source, completion: reply)
wait(for: [done], timeout: 5)
}
return result
}

func test_urls_http_andFile_asTheyAre_aPath_asAFile() {
XCTAssertEqual(StoriesVideoAudio.url(for: "https://cdn.example/v.mp4")?.absoluteString,
"https://cdn.example/v.mp4")
XCTAssertEqual(StoriesVideoAudio.url(for: "file:///tmp/v.mp4")?.path, "/tmp/v.mp4")
let path = StoriesVideoAudio.url(for: "/var/cache/stories/v.mp4")
XCTAssertTrue(path?.isFileURL ?? false)
XCTAssertEqual(path?.path, "/var/cache/stories/v.mp4")
XCTAssertNil(StoriesVideoAudio.url(for: ""))
}

func test_theLoaderDecides_aFailureIsNil() {
var loaded: [String] = []
StoriesVideoAudio.loader = { url in
loaded.append(url.absoluteString)
if url.absoluteString.hasSuffix("broken.mp4") { throw URLError(.badServerResponse) }
return url.absoluteString.hasSuffix("sound.mp4")
}
XCTAssertEqual(answer("https://cdn.example/sound.mp4"), .some(true))
XCTAssertEqual(answer("https://cdn.example/mute.mp4", through: true), .some(false))
XCTAssertEqual(answer("https://cdn.example/broken.mp4"), .some(nil))
XCTAssertEqual(answer(""), .some(nil))
XCTAssertEqual(loaded.count, 3)
}

func test_aRealFile_audioIsSeen_aNonMediaFileHasNone() throws {
// A one-second silent WAV: an audio track AVFoundation reads.
let rate = 8000
var wav = Data()
func append<T: FixedWidthInteger>(_ value: T) {
var little = value.littleEndian
wav.append(Data(bytes: &little, count: MemoryLayout<T>.size))
}
wav.append("RIFF".data(using: .ascii)!)
append(UInt32(36 + rate * 2))
wav.append("WAVEfmt ".data(using: .ascii)!)
append(UInt32(16)); append(UInt16(1)); append(UInt16(1))
append(UInt32(rate)); append(UInt32(rate * 2)); append(UInt16(2)); append(UInt16(16))
wav.append("data".data(using: .ascii)!)
append(UInt32(rate * 2))
wav.append(Data(count: rate * 2))
let directory = FileManager.default.temporaryDirectory
let sound = directory.appendingPathComponent("stories-audio-test.wav")
let text = directory.appendingPathComponent("stories-audio-test.txt")
try wav.write(to: sound)
try Data("not a video".utf8).write(to: text)
defer {
try? FileManager.default.removeItem(at: sound)
try? FileManager.default.removeItem(at: text)
}
XCTAssertEqual(answer(sound.path), .some(true))
XCTAssertNotEqual(answer(text.path), .some(true))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1148,6 +1148,10 @@ final class PersonalizationHostApiImpl: PersonalizationHostApi {
StoriesAudio.shared.update(muted: muted)
}

func storiesVideoHasAudio(source: String, completion: @escaping (Result<Bool?, Error>) -> Void) {
StoriesVideoAudio.hasAudio(source: source) { completion(.success($0)) }
}

func endStoriesAudio() throws {
StoriesAudio.shared.end()
}
Expand Down
Loading
Loading