diff --git a/Cargo.lock b/Cargo.lock
index 103dc8b0..aa4ab70f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -824,6 +824,7 @@ dependencies = [
"fire-store",
"fire-uniffi-types",
"serde_json",
+ "thiserror 2.0.18",
"tokio",
"uniffi",
]
diff --git a/apps/android-app/src/main/AndroidManifest.xml b/apps/android-app/src/main/AndroidManifest.xml
index 3784cab8..46ead15c 100644
--- a/apps/android-app/src/main/AndroidManifest.xml
+++ b/apps/android-app/src/main/AndroidManifest.xml
@@ -57,7 +57,8 @@
+ android:launchMode="singleTop"
+ android:theme="@style/Theme.Fire.ChallengeSheet" />
diff --git a/apps/android-app/src/main/java/com/fire/app/FireApplication.kt b/apps/android-app/src/main/java/com/fire/app/FireApplication.kt
index 1d29ac61..1f81e452 100644
--- a/apps/android-app/src/main/java/com/fire/app/FireApplication.kt
+++ b/apps/android-app/src/main/java/com/fire/app/FireApplication.kt
@@ -5,6 +5,7 @@ import android.content.Context
import com.fire.app.core.image.FireImageLoader
import com.fire.app.core.theme.FireColors
import com.fire.app.push.FirePushNotificationDispatcher
+import com.fire.app.session.FireForegroundActivity
import com.fire.app.ui.topicdetail.BookmarkReminderScheduler
import com.google.android.material.color.DynamicColors
import kotlinx.coroutines.CoroutineScope
@@ -30,6 +31,7 @@ class FireApplication : Application() {
FireImageLoader.initialize(this)
BookmarkReminderScheduler.createNotificationChannel(this)
FirePushNotificationDispatcher.createNotificationChannel(this)
+ registerActivityLifecycleCallbacks(FireForegroundActivity.callbacks)
}
override fun onTerminate() {
diff --git a/apps/android-app/src/main/java/com/fire/app/MainActivity.kt b/apps/android-app/src/main/java/com/fire/app/MainActivity.kt
index 603fea59..b773c9fd 100644
--- a/apps/android-app/src/main/java/com/fire/app/MainActivity.kt
+++ b/apps/android-app/src/main/java/com/fire/app/MainActivity.kt
@@ -10,11 +10,14 @@ import androidx.core.view.updatePadding
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
+import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import com.fire.app.databinding.ActivityMainBinding
+import com.fire.app.session.FireBrowserTransportPrompt
+import com.fire.app.session.FireSessionRecoveryPolicy
import com.fire.app.session.FireCfClearanceRefreshService
import com.fire.app.session.FireSessionStoreRepository
import com.fire.app.session.FireStateObserverRepository
@@ -22,10 +25,14 @@ import com.fire.app.session.FireWebViewCookieActionSupport
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
+import uniffi.fire_uniffi_session.SessionState
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
+ private var hasLatchedAskEnableBrowserTransport = false
+ private var isAskEnableDialogVisible = false
+ private var latestSessionSnapshot: SessionState? = null
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
@@ -50,10 +57,21 @@ class MainActivity : AppCompatActivity() {
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
FireCfClearanceRefreshService.get(this@MainActivity).setSceneActive(true)
+ lifecycleScope.launch {
+ runCatching {
+ FireSessionStoreRepository.get(this@MainActivity).noteAppForegrounded()
+ }
+ presentAskEnableBrowserTransportIfNeeded(latestSessionSnapshot)
+ }
}
override fun onStop(owner: LifecycleOwner) {
FireCfClearanceRefreshService.get(this@MainActivity).setSceneActive(false)
+ lifecycleScope.launch {
+ runCatching {
+ FireSessionStoreRepository.get(this@MainActivity).noteAppBackgrounded()
+ }
+ }
}
})
lifecycleScope.launch {
@@ -176,8 +194,15 @@ class MainActivity : AppCompatActivity() {
}.getOrDefault(false)
}
FireStateObserverRepository.sessionSnapshots.collect { snapshot ->
+ latestSessionSnapshot = snapshot
+ val suppressLoginRecovery = FireSessionRecoveryPolicy.suppressesHostLoginRecovery(
+ snapshot.recovery,
+ )
+ if (!suppressLoginRecovery) {
+ presentAskEnableBrowserTransportIfNeeded(snapshot)
+ }
val isAuthenticated = snapshot.readiness.canReadAuthenticatedApi
- if (wasAuthenticated && !isAuthenticated) {
+ if (!suppressLoginRecovery && wasAuthenticated && !isAuthenticated) {
FireWebViewCookieActionSupport.clearIdentityCookies()
if (navController.currentDestination?.id != R.id.onboardingFragment) {
val options = NavOptions.Builder()
@@ -197,6 +222,44 @@ class MainActivity : AppCompatActivity() {
}
}
+ private fun presentAskEnableBrowserTransportIfNeeded(snapshot: SessionState?) {
+ val kind = snapshot?.let(FireBrowserTransportPrompt::signalKind)
+ if (!FireBrowserTransportPrompt.shouldPresent(kind, hasLatchedAskEnableBrowserTransport)) {
+ hasLatchedAskEnableBrowserTransport = FireBrowserTransportPrompt.nextLatch(kind)
+ return
+ }
+ if (isFinishing || isDestroyed || !lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) {
+ return
+ }
+ if (isAskEnableDialogVisible) {
+ return
+ }
+ hasLatchedAskEnableBrowserTransport = true
+ isAskEnableDialogVisible = true
+ AlertDialog.Builder(this)
+ .setTitle(R.string.browser_transport_prompt_title)
+ .setMessage(R.string.browser_transport_prompt_message)
+ .setPositiveButton(R.string.browser_transport_prompt_enable) { _, _ ->
+ lifecycleScope.launch {
+ runCatching {
+ FireSessionStoreRepository.get(this@MainActivity)
+ .enableBrowserTransportForSession()
+ }
+ }
+ }
+ .setNegativeButton(R.string.browser_transport_prompt_decline) { _, _ ->
+ lifecycleScope.launch {
+ runCatching {
+ FireSessionStoreRepository.get(this@MainActivity).declineBrowserTransport()
+ }
+ }
+ }
+ .setOnDismissListener {
+ isAskEnableDialogVisible = false
+ }
+ .show()
+ }
+
private fun handleSignedOutLaunch(navController: NavController) {
val entry = intent?.getStringExtra(EXTRA_ONBOARDING_ENTRY) ?: return
if (entry.isBlank()) return
diff --git a/apps/android-app/src/main/java/com/fire/app/richtext/FireRenderPresentation.kt b/apps/android-app/src/main/java/com/fire/app/richtext/FireRenderPresentation.kt
index abdfb45c..bc35aea7 100644
--- a/apps/android-app/src/main/java/com/fire/app/richtext/FireRenderPresentation.kt
+++ b/apps/android-app/src/main/java/com/fire/app/richtext/FireRenderPresentation.kt
@@ -43,6 +43,10 @@ object FireRenderPresentation {
is RenderUiSegmentState.Onebox -> {
FireRichTextBlock.Text(listOf(mapOnebox(segment.card)))
}
+ is RenderUiSegmentState.Quote -> {
+ val nodes = segment.nodes.map(::mapNode)
+ if (nodes.isEmpty()) null else FireRichTextBlock.Text(nodes)
+ }
null -> null
}
}
@@ -63,6 +67,7 @@ object FireRenderPresentation {
return (0u until handle.segmentCount()).flatMap { index ->
when (val segment = handle.segment(index)) {
is RenderUiSegmentState.Rich -> segment.nodes.map(::mapNode)
+ is RenderUiSegmentState.Quote -> segment.nodes.map(::mapNode)
else -> emptyList()
}
}
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireBrowserHttpHandler.kt b/apps/android-app/src/main/java/com/fire/app/session/FireBrowserHttpHandler.kt
new file mode 100644
index 00000000..2c414f8a
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireBrowserHttpHandler.kt
@@ -0,0 +1,106 @@
+package com.fire.app.session
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import android.webkit.CookieManager
+import android.webkit.WebView
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+import org.json.JSONObject
+import uniffi.fire_uniffi_session.BrowserHttpException
+import uniffi.fire_uniffi_session.BrowserHttpHandler
+import uniffi.fire_uniffi_session.BrowserHttpHeaderState
+import uniffi.fire_uniffi_session.BrowserHttpRequestState
+import uniffi.fire_uniffi_session.BrowserHttpResponseState
+
+class FireBrowserHttpHandler(
+ context: Context,
+) : BrowserHttpHandler {
+ private val appContext = context.applicationContext
+
+ override fun executeBrowserHttp(request: BrowserHttpRequestState): BrowserHttpResponseState {
+ val latch = CountDownLatch(1)
+ var result: BrowserHttpResponseState? = null
+ var error: String? = null
+ Handler(Looper.getMainLooper()).post {
+ val webView = WebView(appContext)
+ CookieManager.getInstance().setAcceptCookie(true)
+ val headerObject = request.headers.joinToString(",") { header ->
+ "\"${header.name.jsonEscape()}\":\"${header.value.jsonEscape()}\""
+ }
+ val script = """
+ (async () => {
+ try {
+ const res = await fetch("${request.url.jsonEscape()}", {
+ method: "${request.method.jsonEscape()}",
+ headers: {$headerObject},
+ body: ${requestBodyLiteral(request)},
+ credentials: "include"
+ });
+ const buffer = await res.arrayBuffer();
+ const body = Array.from(new Uint8Array(buffer));
+ const headers = [];
+ res.headers.forEach((value, name) => headers.push({name, value}));
+ return JSON.stringify({status: res.status, headers, body});
+ } catch (error) {
+ return JSON.stringify({error: String(error)});
+ }
+ })()
+ """.trimIndent()
+ webView.evaluateJavascript(script) { raw ->
+ try {
+ val json = JSONObject(raw.trim('"').replace("\\\"", "\""))
+ if (json.has("error")) {
+ error = json.optString("error")
+ } else {
+ val headers = mutableListOf()
+ val headerArray = json.optJSONArray("headers")
+ if (headerArray != null) {
+ for (index in 0 until headerArray.length()) {
+ val item = headerArray.optJSONObject(index) ?: continue
+ headers += BrowserHttpHeaderState(
+ name = item.optString("name"),
+ value = item.optString("value"),
+ )
+ }
+ }
+ val bodyArray = json.optJSONArray("body")
+ val body = if (bodyArray == null) {
+ byteArrayOf()
+ } else {
+ ByteArray(bodyArray.length()) { bodyArray.optInt(it).toByte() }
+ }
+ result = BrowserHttpResponseState(
+ status = json.optInt("status", 502).toUShort(),
+ headers = headers,
+ body = body,
+ )
+ }
+ } catch (thrown: Exception) {
+ error = thrown.message
+ } finally {
+ latch.countDown()
+ }
+ }
+ }
+ latch.await((request.timeoutMs + 2_000u).toLong(), TimeUnit.MILLISECONDS)
+ return result ?: throw BrowserHttpException.Failed(
+ details = error ?: "browser fetch failed",
+ )
+ }
+}
+
+private fun requestBodyLiteral(request: BrowserHttpRequestState): String {
+ val body = request.body ?: return "undefined"
+ if (body.isEmpty()) return "undefined"
+ val encoded = android.util.Base64.encodeToString(
+ body.map { it.toByte() }.toByteArray(),
+ android.util.Base64.NO_WRAP,
+ )
+ return "Uint8Array.from(atob(\"${encoded.jsonEscape()}\"), c => c.charCodeAt(0))"
+}
+
+private fun String.jsonEscape(): String {
+ return replace("\\", "\\\\").replace("\"", "\\\"")
+}
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireBrowserTransportPrompt.kt b/apps/android-app/src/main/java/com/fire/app/session/FireBrowserTransportPrompt.kt
new file mode 100644
index 00000000..dee298ca
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireBrowserTransportPrompt.kt
@@ -0,0 +1,18 @@
+package com.fire.app.session
+
+import uniffi.fire_uniffi_session.AuthRuntimeSignalKindState
+import uniffi.fire_uniffi_session.SessionState
+
+object FireBrowserTransportPrompt {
+ fun shouldPresent(kind: AuthRuntimeSignalKindState?, alreadyLatched: Boolean): Boolean {
+ return kind == AuthRuntimeSignalKindState.ASK_ENABLE_BROWSER_TRANSPORT && !alreadyLatched
+ }
+
+ fun nextLatch(kind: AuthRuntimeSignalKindState?): Boolean {
+ return kind == AuthRuntimeSignalKindState.ASK_ENABLE_BROWSER_TRANSPORT
+ }
+
+ fun signalKind(snapshot: SessionState): AuthRuntimeSignalKindState? {
+ return snapshot.lastAuthRuntimeSignal?.kind
+ }
+}
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt b/apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt
index a97d1c9a..ca7cc7a2 100644
--- a/apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireCloudflareChallengeCoordinator.kt
@@ -1,8 +1,12 @@
package com.fire.app.session
+import android.app.Activity
+import android.app.Application
import android.content.Context
import android.content.Intent
import android.net.Uri
+import android.os.Bundle
+import java.lang.ref.WeakReference
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
@@ -11,18 +15,170 @@ import uniffi.fire_uniffi_session.CloudflareChallengeHandler
import uniffi.fire_uniffi_session.CloudflareChallengeRequestState
import uniffi.fire_uniffi_session.CloudflareChallengeResultState
+object FireCloudflareChallengePresentationGate {
+ @Volatile
+ var isPresentationInFlight: Boolean = false
+ private set
+
+ @Volatile
+ internal var waitingJoiners: Int = 0
+ private set
+
+ private val lock = Any()
+ private var inFlight: Session? = null
+
+ private class Session {
+ private val latch = CountDownLatch(1)
+ @Volatile
+ private var result: CloudflareChallengeResultState? = null
+
+ fun complete(value: CloudflareChallengeResultState) {
+ result = value
+ latch.countDown()
+ }
+
+ fun await(): CloudflareChallengeResultState {
+ latch.await(5, TimeUnit.MINUTES)
+ return result ?: cancelledResult()
+ }
+ }
+
+ fun runExclusive(block: () -> CloudflareChallengeResultState): CloudflareChallengeResultState {
+ val join: Session?
+ val owned: Session?
+ synchronized(lock) {
+ val current = inFlight
+ if (current != null) {
+ waitingJoiners += 1
+ join = current
+ owned = null
+ } else {
+ val session = Session()
+ inFlight = session
+ isPresentationInFlight = true
+ join = null
+ owned = session
+ }
+ }
+ if (join != null) {
+ return try {
+ join.await()
+ } finally {
+ synchronized(lock) {
+ waitingJoiners -= 1
+ }
+ }
+ }
+ val session = checkNotNull(owned)
+ return try {
+ val result = block()
+ session.complete(result)
+ result
+ } catch (error: Throwable) {
+ session.complete(cancelledResult())
+ throw error
+ } finally {
+ synchronized(lock) {
+ if (inFlight === session) {
+ inFlight = null
+ isPresentationInFlight = false
+ }
+ }
+ }
+ }
+
+ fun resetForTesting() {
+ synchronized(lock) {
+ inFlight?.complete(cancelledResult())
+ inFlight = null
+ isPresentationInFlight = false
+ waitingJoiners = 0
+ }
+ }
+
+ private fun cancelledResult(): CloudflareChallengeResultState {
+ return CloudflareChallengeResultState(
+ completed = false,
+ userCancelled = false,
+ freshCfClearance = null,
+ cookies = emptyList(),
+ browserUserAgent = null,
+ )
+ }
+}
+
+/**
+ * UI seam for a Cloudflare challenge. The logic handler calls this only when a
+ * new presentation is required. Joiners wait on the gate and never reach it.
+ */
+fun interface FireCloudflareChallengeUi {
+ fun present(request: CloudflareChallengeRequestState): CloudflareChallengeResultState
+}
+
+/** Tracks the resumed activity so a challenge can overlay it instead of starting a new task. */
+object FireForegroundActivity {
+ private var resumed = WeakReference(null)
+
+ fun current(): Activity? = resumed.get()
+
+ val callbacks = object : Application.ActivityLifecycleCallbacks {
+ override fun onActivityResumed(activity: Activity) {
+ if (activity !is FireCloudflareChallengeActivity) {
+ resumed = WeakReference(activity)
+ }
+ }
+
+ override fun onActivityPaused(activity: Activity) {
+ if (resumed.get() === activity) {
+ resumed = WeakReference(null)
+ }
+ }
+
+ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
+ override fun onActivityStarted(activity: Activity) = Unit
+ override fun onActivityStopped(activity: Activity) = Unit
+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
+ override fun onActivityDestroyed(activity: Activity) = Unit
+ }
+}
+
class FireCloudflareChallengeRuntimeHandler(
context: Context,
+ private val ui: FireCloudflareChallengeUi = FireCloudflareChallengeDialogUi(context.applicationContext),
) : CloudflareChallengeHandler {
- private val coordinator = FireCloudflareChallengeCoordinator(context.applicationContext)
-
override fun completeCloudflareChallenge(
request: CloudflareChallengeRequestState,
): CloudflareChallengeResultState {
+ if (!request.isForeground) {
+ return softChallengeResult(userCancelled = false)
+ }
+ // Only the owner of the gate presents UI. Concurrent requests wait here.
+ return FireCloudflareChallengePresentationGate.runExclusive {
+ ui.present(request)
+ }
+ }
+}
+
+class FireCloudflareChallengeDialogUi(
+ private val context: Context,
+) : FireCloudflareChallengeUi {
+ private val coordinator = FireCloudflareChallengeCoordinator(context.applicationContext)
+
+ override fun present(request: CloudflareChallengeRequestState): CloudflareChallengeResultState {
return coordinator.completeSynchronously(request)
}
}
+private fun softChallengeResult(userCancelled: Boolean): CloudflareChallengeResultState {
+ return CloudflareChallengeResultState(
+ completed = false,
+ userCancelled = userCancelled,
+ freshCfClearance = null,
+ cookies = emptyList(),
+ browserUserAgent = null,
+ )
+}
+
class FireCloudflareChallengeCoordinator(
private val context: Context,
) {
@@ -49,15 +205,18 @@ class FireCloudflareChallengeCoordinator(
val token = UUID.randomUUID().toString()
val pending = PendingChallenge()
PendingChallenges.register(token, pending)
- val intent = Intent(context, FireCloudflareChallengeActivity::class.java).apply {
- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ val host = FireForegroundActivity.current()
+ val intent = Intent(host ?: context, FireCloudflareChallengeActivity::class.java).apply {
+ if (host == null) {
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
putExtra(FireCloudflareChallengeActivity.EXTRA_PENDING_TOKEN, token)
putExtra(
FireCloudflareChallengeActivity.EXTRA_TARGET_URL,
challengeUrl(request.originUrl),
)
}
- context.startActivity(intent)
+ (host ?: context).startActivity(intent)
val completed = pending.latch.await(5, TimeUnit.MINUTES)
PendingChallenges.remove(token)
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireSessionRecoveryPolicy.kt b/apps/android-app/src/main/java/com/fire/app/session/FireSessionRecoveryPolicy.kt
new file mode 100644
index 00000000..925417cf
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireSessionRecoveryPolicy.kt
@@ -0,0 +1,9 @@
+package com.fire.app.session
+
+import uniffi.fire_uniffi_session.SessionRecoveryState
+
+object FireSessionRecoveryPolicy {
+ fun suppressesHostLoginRecovery(recovery: SessionRecoveryState): Boolean {
+ return recovery == SessionRecoveryState.CLOUDFLARE
+ }
+}
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt b/apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt
index 3e483a04..7dc085d9 100644
--- a/apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt
@@ -23,6 +23,7 @@ import uniffi.fire_uniffi_messagebus.MessageBusSubscriptionState
import uniffi.fire_uniffi_messagebus.TopicPresenceState
import uniffi.fire_uniffi_chat.BrowseChatChannelsQueryState
import uniffi.fire_uniffi_chat.ChatChannelMemberState
+import uniffi.fire_uniffi_chat.ChatChannelRuntimeState
import uniffi.fire_uniffi_chat.ChatChannelState
import uniffi.fire_uniffi_chat.ChatMessagesQueryState
import uniffi.fire_uniffi_chat.ChatMessagesState
@@ -41,7 +42,9 @@ import uniffi.fire_uniffi_search.TagSearchResultState
import uniffi.fire_uniffi_search.UserMentionQueryState
import uniffi.fire_uniffi_search.UserMentionResultState
import uniffi.fire_uniffi_session.AppStateRefreshHandler
+import uniffi.fire_uniffi_session.BrowserHttpHandler
import uniffi.fire_uniffi_session.CloudflareChallengeHandler
+import uniffi.fire_uniffi_session.CloudflarePolicyState
import uniffi.fire_uniffi_session.CloudflareClearanceResolvedHandler
import uniffi.fire_uniffi_session.CookieSelfHealingHandler
import uniffi.fire_uniffi_session.CookieReplayEntryState
@@ -128,6 +131,31 @@ class FireSessionStore(
core.session().sessionEpoch()
}
+ fun getCloudflarePolicy(): CloudflarePolicyState = core.session().getCloudflarePolicy()
+
+ fun setCloudflarePolicy(policy: CloudflarePolicyState): CloudflarePolicyState =
+ core.session().setCloudflarePolicy(policy)
+
+ fun enableBrowserTransportForSession() {
+ core.session().enableBrowserTransportForSession()
+ }
+
+ fun declineBrowserTransport() {
+ core.session().declineBrowserTransport()
+ }
+
+ fun noteAppBackgrounded() {
+ core.session().noteAppBackgrounded()
+ }
+
+ fun noteAppForegrounded() {
+ core.session().noteAppForegrounded()
+ }
+
+ fun registerBrowserHttpHandler(handler: BrowserHttpHandler) {
+ core.session().registerBrowserHttpHandler(handler)
+ }
+
fun registerCloudflareChallengeHandler(handler: CloudflareChallengeHandler) {
core.session().registerCloudflareChallengeHandler(handler)
}
@@ -491,6 +519,51 @@ class FireSessionStore(
core.chat().cachedMyChatChannels()
}
+ fun chatListSnapshot(): MyChatChannelsState? = core.chat().chatListSnapshot()
+
+ fun applyChatListTracking(
+ channelId: ULong,
+ unread: UInt,
+ mention: UInt,
+ explicitMarkRead: Boolean,
+ ): MyChatChannelsState = core.chat().applyChatListTracking(
+ channelId,
+ unread,
+ mention,
+ explicitMarkRead,
+ )
+
+ fun applyChatListBusEvent(
+ payloadJson: String,
+ eventType: String?,
+ fallbackChannelId: ULong?,
+ ): MyChatChannelsState = core.chat().applyChatListBusEvent(
+ payloadJson,
+ eventType,
+ fallbackChannelId,
+ )
+
+ fun chatChannelRuntimeSnapshot(
+ channelId: ULong,
+ threadId: ULong?,
+ ): ChatChannelRuntimeState? = core.chat().chatChannelRuntimeSnapshot(channelId, threadId)
+
+ fun applyChatChannelBusEvent(
+ channelId: ULong,
+ threadId: ULong?,
+ payloadJson: String,
+ eventType: String?,
+ ): ChatChannelRuntimeState = core.chat().applyChatChannelBusEvent(
+ channelId,
+ threadId,
+ payloadJson,
+ eventType,
+ )
+
+ fun closeChatChannelRuntime(channelId: ULong, threadId: ULong?) {
+ core.chat().closeChatChannelRuntime(channelId, threadId)
+ }
+
suspend fun cachedChatMessages(channelId: ULong, threadId: ULong?): ChatMessagesState? =
withContext(Dispatchers.IO) {
core.chat().cachedChatMessages(channelId, threadId)
@@ -852,6 +925,11 @@ class FireSessionStore(
post
}
+ suspend fun createBoost(postId: ULong, raw: String) = withContext(Dispatchers.IO) {
+ core.topics().createBoost(postId, raw)
+ persistCurrentSession()
+ }
+
suspend fun updateTopic(input: TopicUpdateRequestState) = withContext(Dispatchers.IO) {
core.topics().updateTopic(input)
persistCurrentSession()
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireSessionStoreRepository.kt b/apps/android-app/src/main/java/com/fire/app/session/FireSessionStoreRepository.kt
index d797a98c..49db1f36 100644
--- a/apps/android-app/src/main/java/com/fire/app/session/FireSessionStoreRepository.kt
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireSessionStoreRepository.kt
@@ -38,6 +38,7 @@ object FireSessionStoreRepository {
)
}
challengeHandler?.let(store::registerCloudflareChallengeHandler)
+ store.registerBrowserHttpHandler(FireBrowserHttpHandler(context.applicationContext))
store.registerCloudflareClearanceResolvedHandler(FireClearanceResolvedRepository)
if (cookieSelfHealingHandler == null) {
cookieSelfHealingHandler = FireCookieSelfHealingRuntimeHandler(store)
diff --git a/apps/android-app/src/main/java/com/fire/app/session/FireStateObserverRepository.kt b/apps/android-app/src/main/java/com/fire/app/session/FireStateObserverRepository.kt
index 5da17d21..89d8d727 100644
--- a/apps/android-app/src/main/java/com/fire/app/session/FireStateObserverRepository.kt
+++ b/apps/android-app/src/main/java/com/fire/app/session/FireStateObserverRepository.kt
@@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.asSharedFlow
import uniffi.fire_uniffi.StateObserver
import uniffi.fire_uniffi_notifications.NotificationCenterState
import uniffi.fire_uniffi_session.SessionState
+import uniffi.fire_uniffi_topics.TopicListRowPatchBatchState
import uniffi.fire_uniffi_types.TopicListState
object FireStateObserverRepository : StateObserver {
@@ -25,6 +26,12 @@ object FireStateObserverRepository : StateObserver {
)
val topicListSnapshots: SharedFlow = _topicListSnapshots.asSharedFlow()
+ private val _topicListPatches = MutableSharedFlow(
+ extraBufferCapacity = 8,
+ onBufferOverflow = BufferOverflow.DROP_OLDEST,
+ )
+ val topicListPatches: SharedFlow = _topicListPatches.asSharedFlow()
+
private val _notificationCenterSnapshots = MutableSharedFlow(
replay = 1,
extraBufferCapacity = 4,
@@ -44,6 +51,10 @@ object FireStateObserverRepository : StateObserver {
_topicListSnapshots.tryEmit(snapshot)
}
+ override fun onTopicListPatches(batch: TopicListRowPatchBatchState) {
+ _topicListPatches.tryEmit(batch)
+ }
+
override fun onNotificationCenterSnapshot(snapshot: NotificationCenterState) {
_notificationCenterSnapshots.tryEmit(snapshot)
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt
index 37767240..b20d0c50 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelSession.kt
@@ -1,11 +1,9 @@
package com.fire.app.ui.chat
import com.fire.app.session.FireSessionStore
-import uniffi.fire_uniffi_chat.ChatBusEventState
-import uniffi.fire_uniffi_chat.ChatMessageReactionState
+import uniffi.fire_uniffi_chat.ChatChannelRuntimeState
import uniffi.fire_uniffi_chat.ChatMessageState
import uniffi.fire_uniffi_chat.ChatMessagesQueryState
-import uniffi.fire_uniffi_chat.ChatReactionActionState
import uniffi.fire_uniffi_chat.SendChatMessageRequestState
import uniffi.fire_uniffi_messagebus.MessageBusEventState
import java.util.UUID
@@ -77,7 +75,6 @@ class ChatChannelSession(
private var isLoading = false
private var isSending = false
private var isOpen = false
- private var currentUserId: ULong? = null
private var chatBaseUrl: String = "https://linux.do"
fun snapshot(): Snapshot {
@@ -98,11 +95,9 @@ class ChatChannelSession(
isLoading = true
try {
val bootstrap = store.snapshot().bootstrap
- currentUserId = bootstrap.currentUserId
chatBaseUrl = bootstrap.baseUrl.ifBlank { "https://linux.do" }
- store.cachedChatMessages(channelId, threadId)?.messages?.takeIf { it.isNotEmpty() }?.let { cached ->
- messages = cached
- emit(Change.Cached)
+ store.cachedChatMessages(channelId, threadId)?.messages?.takeIf { it.isNotEmpty() }?.let {
+ adoptRuntime(Change.Cached)
} ?: emit(Change.Loading)
if (threadId == null) {
val channel = store.fetchChatChannel(channelId)
@@ -114,14 +109,12 @@ class ChatChannelSession(
runCatching { store.markChatChannelPinsRead(channelId) }
}
}
- val page = fetchMessages(fetchFromLastRead = true)
- messages = page.messages
- canLoadMorePast = page.canLoadMorePast
- val currentThreadId = threadId
- if (currentThreadId != null) {
- runCatching { store.markChatThreadRead(channelId, currentThreadId) }
+ fetchMessages(fetchFromLastRead = true)
+ adoptRuntime(Change.Initial)
+ if (threadId != null) {
+ runCatching { store.markChatThreadRead(channelId, threadId!!) }
} else {
- page.messages.lastOrNull()?.id?.let { latest ->
+ messages.lastOrNull()?.id?.let { latest ->
runCatching { store.markChatChannelRead(channelId, latest) }
}
}
@@ -130,7 +123,6 @@ class ChatChannelSession(
ownerToken = ownerToken,
lastMessageId = null,
)
- emit(Change.Initial)
} catch (error: Exception) {
if (isOpen) onError?.invoke(error)
} finally {
@@ -142,6 +134,7 @@ class ChatChannelSession(
suspend fun close() {
isOpen = false
store.unsubscribeMessageBusChannel(busChannelName, ownerToken)
+ store.closeChatChannelRuntime(channelId, threadId)
}
suspend fun command(command: Command): CommandResult {
@@ -179,36 +172,25 @@ class ChatChannelSession(
fun handleBusEvent(event: MessageBusEventState) {
if (!isOpen || event.channel != busChannelName) return
+ val payload = event.payloadJson ?: return
val type = event.detailEventType ?: event.messageType
- when (type) {
- "sent" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let {
- upsertMessage(it, preferAppend = true)
- }
- "edit", "processed", "refresh", "restore",
- "thread_created", "update_thread_original_message",
- -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let {
- upsertMessage(it, preferAppend = false)
- }
- "delete" -> {
- val deleted = FireChatBusPayload.event(event, channelId, chatBaseUrl)
- as? ChatBusEventState.MessageDeleted
- ?: return
- val next = messages.filterNot { it.id == deleted.id }
- if (next.size != messages.size) {
- messages = next
- emit(Change.MessageDeleted)
- }
- }
- "reaction" -> applyReaction(event)
- "pin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message ->
- pins = listOf(message) + pins.filterNot { it.id == message.id }
- emit(Change.Pins)
- }
- "unpin" -> FireChatBusPayload.chatMessage(event, channelId, chatBaseUrl)?.let { message ->
- pins = pins.filterNot { it.id == message.id }
- emit(Change.Pins)
- }
- }
+ val previousCount = messages.size
+ applyRuntime(
+ store.applyChatChannelBusEvent(
+ channelId = channelId,
+ threadId = threadId,
+ payloadJson = payload,
+ eventType = type,
+ ),
+ )
+ emit(
+ when (type) {
+ "pin", "unpin" -> Change.Pins
+ "delete" -> Change.MessageDeleted
+ "sent" -> if (messages.size > previousCount) Change.MessageInserted else Change.MessageUpdated
+ else -> Change.MessageUpdated
+ },
+ )
}
private suspend fun loadMorePast() {
@@ -223,10 +205,8 @@ class ChatChannelSession(
fetchFromLastRead = false,
pageSize = 50u,
)
- val page = fetchMessages(query)
- messages = page.messages + messages
- canLoadMorePast = page.canLoadMorePast
- emit(Change.Older)
+ fetchMessages(query)
+ adoptRuntime(Change.Older)
} finally {
isLoading = false
}
@@ -247,7 +227,9 @@ class ChatChannelSession(
uploadIds = uploadIds,
),
)
+ } catch (error: Exception) {
refreshLatest()
+ throw error
} finally {
isSending = false
}
@@ -265,15 +247,13 @@ class ChatChannelSession(
}
private suspend fun refreshLatest() {
- val page = fetchMessages(fetchFromLastRead = false)
- messages = page.messages
- canLoadMorePast = page.canLoadMorePast
+ fetchMessages(fetchFromLastRead = false)
+ adoptRuntime(Change.Latest)
if (threadId == null) {
- page.messages.lastOrNull()?.id?.let { latest ->
+ messages.lastOrNull()?.id?.let { latest ->
runCatching { store.markChatChannelRead(channelId, latest) }
}
}
- emit(Change.Latest)
}
private suspend fun fetchMessages(fetchFromLastRead: Boolean) = fetchMessages(
@@ -293,61 +273,21 @@ class ChatChannelSession(
store.fetchChatMessages(query)
}
- private fun upsertMessage(message: ChatMessageState, preferAppend: Boolean) {
- val index = messages.indexOfFirst { it.id == message.id }
- messages = if (index >= 0) {
- messages.toMutableList().also { it[index] = message }
- } else if (preferAppend) {
- messages + message
- } else {
- return
- }
- emit(if (index >= 0) Change.MessageUpdated else Change.MessageInserted)
+ private fun adoptRuntime(change: Change) {
+ val runtime = store.chatChannelRuntimeSnapshot(channelId, threadId) ?: return
+ applyRuntime(runtime)
+ emit(change)
}
- private fun applyReaction(event: MessageBusEventState) {
- val parsed = FireChatBusPayload.event(event, channelId, chatBaseUrl)
- as? ChatBusEventState.Reaction
- ?: return
- val index = messages.indexOfFirst { it.id == parsed.messageId }
- if (index < 0) return
- val message = messages[index]
- val isAdd = parsed.action == ChatReactionActionState.ADD
- val reactions = message.reactions.toMutableList()
- val existing = reactions.indexOfFirst { it.emoji == parsed.emoji }
- if (existing >= 0) {
- val current = reactions[existing]
- val nextCount = if (isAdd) current.count + 1u else current.count.saturatingDec()
- val reacted = if (isAdd) {
- current.reacted || parsed.actorId == currentUserId
- } else {
- false
- }
- if (nextCount == 0u) {
- reactions.removeAt(existing)
- } else {
- reactions[existing] = ChatMessageReactionState(
- emoji = parsed.emoji,
- count = nextCount,
- reacted = reacted,
- users = current.users,
- )
- }
- } else if (isAdd) {
- reactions += ChatMessageReactionState(
- emoji = parsed.emoji,
- count = 1u,
- reacted = true,
- users = emptyList(),
- )
+ private fun applyRuntime(runtime: ChatChannelRuntimeState) {
+ messages = runtime.messages
+ if (threadId == null) {
+ pins = runtime.pins
}
- messages = messages.toMutableList().also { it[index] = message.copy(reactions = reactions) }
- emit(Change.MessageUpdated)
+ canLoadMorePast = runtime.canLoadMorePast
}
private fun emit(change: Change) {
onChange?.invoke(snapshot(), change)
}
-
- private fun UInt.saturatingDec(): UInt = if (this == 0u) 0u else this - 1u
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelsViewModel.kt b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelsViewModel.kt
index e11f497f..3001fe6f 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelsViewModel.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/chat/ChatChannelsViewModel.kt
@@ -10,9 +10,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
-import uniffi.fire_uniffi_chat.ChatBusEventState
import uniffi.fire_uniffi_chat.ChatChannelState
-import uniffi.fire_uniffi_chat.ChatMessageState
import uniffi.fire_uniffi_chat.CreateDirectMessageChannelRequestState
import uniffi.fire_uniffi_chat.MyChatChannelsState
import uniffi.fire_uniffi_messagebus.MessageBusEventState
@@ -20,28 +18,14 @@ import uniffi.fire_uniffi_messagebus.MessageBusEventState
data class ChatChannelsUiState(
val publicChannels: List = emptyList(),
val directMessageChannels: List = emptyList(),
+ val displayedChannels: List = emptyList(),
val tracking: Map> = emptyMap(),
val totalUnreadBadge: UInt = 0u,
val isLoading: Boolean = false,
val hasLoadedOnce: Boolean = false,
val errorMessage: String? = null,
) {
- val displayedChannels: List
- get() = sortChannels(directMessageChannels + publicChannels)
-
- fun badgeFor(channel: ChatChannelState): UInt {
- if (channel.currentUserMembership?.muted == true) return 0u
- val (unread, mention) = tracking[channel.id] ?: (0u to 0u)
- return if (channel.isDirectMessage) unread + mention else mention
- }
-}
-
-private fun sortChannels(channels: List): List {
- return channels.sortedWith(
- compareByDescending { it.currentUserMembership?.starred == true }
- .thenByDescending { it.lastMessage?.createdAt.orEmpty() }
- .thenByDescending { it.id },
- )
+ fun badgeFor(channel: ChatChannelState): UInt = channel.unreadBadge
}
class ChatChannelsViewModel(
@@ -54,7 +38,6 @@ class ChatChannelsViewModel(
private val subscribedNewMessageChannels = mutableSetOf()
private var busJob: Job? = null
private var currentUserId: ULong? = null
- private var baseUrl: String = "https://linux.do"
private var didRefreshFromNetwork = false
init {
@@ -84,7 +67,6 @@ class ChatChannelsViewModel(
runCatching {
val bootstrap = sessionStore.snapshot().bootstrap
currentUserId = bootstrap.currentUserId
- baseUrl = bootstrap.baseUrl.ifBlank { "https://linux.do" }
sessionStore.fetchMyChatChannels()
}
.onSuccess { response ->
@@ -102,31 +84,18 @@ class ChatChannelsViewModel(
}
fun clearTracking(channelId: ULong) {
- val next = _state.value.tracking.toMutableMap()
- next[channelId] = 0u to 0u
- _state.value = _state.value.copy(
- tracking = next,
- totalUnreadBadge = recomputeBadge(
- publicChannels = _state.value.publicChannels,
- directMessageChannels = _state.value.directMessageChannels,
- tracking = next,
+ apply(
+ sessionStore.applyChatListTracking(
+ channelId = channelId,
+ unread = 0u,
+ mention = 0u,
+ explicitMarkRead = true,
),
)
}
fun upsert(channel: ChatChannelState) {
- val current = _state.value
- _state.value = if (channel.isDirectMessage) {
- current.copy(
- directMessageChannels = listOf(channel) +
- current.directMessageChannels.filterNot { it.id == channel.id },
- )
- } else {
- current.copy(
- publicChannels = listOf(channel) +
- current.publicChannels.filterNot { it.id == channel.id },
- )
- }
+ sessionStore.chatListSnapshot()?.let { apply(it) }
subscribeNewMessages(channel)
}
@@ -159,6 +128,7 @@ class ChatChannelsViewModel(
_state.value = _state.value.copy(
publicChannels = response.publicChannels,
directMessageChannels = response.directMessageChannels,
+ displayedChannels = response.inboxChannels,
tracking = tracking,
totalUnreadBadge = response.totalUnreadBadge,
isLoading = false,
@@ -212,92 +182,28 @@ class ChatChannelsViewModel(
}
private fun handleBusEvent(event: MessageBusEventState) {
- when {
- event.channel == "/chat/new-channel" -> handleNewChannel(event)
- event.channel.startsWith("/chat/user-tracking-state/") -> handleTracking(event)
- event.channel.endsWith("/new-messages") -> handleNewMessages(event)
+ val channel = event.channel
+ if (channel != "/chat/new-channel" &&
+ channel != "/chat/channel-edits" &&
+ !channel.startsWith("/chat/user-tracking-state/") &&
+ !channel.endsWith("/new-messages")
+ ) {
+ return
}
- }
-
- private fun handleNewChannel(event: MessageBusEventState) {
- val channel = FireChatBusPayload.channel(event, baseUrl) ?: return
- if (channel.isDirectMessage) {
- upsert(channel)
- }
- }
-
- private fun handleTracking(event: MessageBusEventState) {
- val parsed = FireChatBusPayload.event(event, event.topicId, baseUrl)
- val tracking = parsed as? ChatBusEventState.Tracking ?: return
- if (tracking.threadId != null || tracking.channelId == 0uL) return
- val next = _state.value.tracking.toMutableMap()
- next[tracking.channelId] = tracking.unread to tracking.mention
- _state.value = _state.value.copy(
- tracking = next,
- totalUnreadBadge = recomputeBadge(
- _state.value.publicChannels,
- _state.value.directMessageChannels,
- next,
+ val payload = event.payloadJson ?: return
+ val knownIds = (_state.value.directMessageChannels + _state.value.publicChannels)
+ .map { it.id }
+ .toSet()
+ apply(
+ sessionStore.applyChatListBusEvent(
+ payloadJson = payload,
+ eventType = event.detailEventType ?: event.messageType,
+ fallbackChannelId = event.topicId,
),
)
- }
-
- private fun handleNewMessages(event: MessageBusEventState) {
- when (val parsed = FireChatBusPayload.event(event, event.topicId, baseUrl)) {
- is ChatBusEventState.NewMessages -> {
- if (!parsed.isChannelLevel || parsed.channelId == 0uL) return
- val message = parsed.message ?: return
- applyIncomingLastMessage(message, isSelf = message.user?.id == currentUserId)
- }
- is ChatBusEventState.MessageUpsert -> {
- applyIncomingLastMessage(
- parsed.message,
- isSelf = parsed.message.user?.id == currentUserId,
- )
- }
- else -> Unit
- }
- }
-
- private fun applyIncomingLastMessage(message: ChatMessageState, isSelf: Boolean) {
- val channelId = message.channelId
- val current = _state.value
- val nextTracking = current.tracking.toMutableMap()
- if (!isSelf) {
- val old = nextTracking[channelId] ?: (0u to 0u)
- nextTracking[channelId] = (old.first + 1u) to old.second
- }
- fun withLastMessage(channel: ChatChannelState): ChatChannelState {
- return if (channel.id == channelId) channel.copy(lastMessage = message) else channel
- }
- _state.value = current.copy(
- publicChannels = sortChannels(current.publicChannels.map(::withLastMessage)),
- directMessageChannels = sortChannels(current.directMessageChannels.map(::withLastMessage)),
- tracking = nextTracking,
- totalUnreadBadge = recomputeBadge(
- current.publicChannels,
- current.directMessageChannels,
- nextTracking,
- ),
- )
- }
-
- private fun recomputeBadge(
- publicChannels: List,
- directMessageChannels: List,
- tracking: Map>,
- ): UInt {
- var sum = 0u
- for (channel in directMessageChannels) {
- if (channel.currentUserMembership?.muted == true) continue
- val (unread, mention) = tracking[channel.id] ?: (0u to 0u)
- sum += unread + mention
- }
- for (channel in publicChannels) {
- if (channel.currentUserMembership?.muted == true) continue
- sum += tracking[channel.id]?.second ?: 0u
- }
- return sum
+ (_state.value.directMessageChannels + _state.value.publicChannels)
+ .filter { it.id !in knownIds }
+ .forEach { subscribeNewMessages(it) }
}
override fun onCleared() {
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerViewModel.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerViewModel.kt
index 6e08c144..4fa1201d 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerViewModel.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ComposerViewModel.kt
@@ -32,11 +32,15 @@ class ComposerViewModel(
private val _error = MutableStateFlow(null)
val error = _error.asStateFlow()
+ private val _pendingReview = MutableStateFlow(false)
+ val pendingReview = _pendingReview.asStateFlow()
+
fun submitReply(topicId: ULong, rawBody: String, replyToPostNumber: UInt?) {
if (_isSubmitting.value) return
viewModelScope.launch {
_isSubmitting.value = true
_error.value = null
+ _pendingReview.value = false
_result.value = null
try {
val input = TopicReplyRequestState(
@@ -61,6 +65,7 @@ class ComposerViewModel(
viewModelScope.launch {
_isSubmitting.value = true
_error.value = null
+ _pendingReview.value = false
_topicCreated.value = null
_privateMessageCreated.value = null
try {
@@ -87,6 +92,7 @@ class ComposerViewModel(
viewModelScope.launch {
_isSubmitting.value = true
_error.value = null
+ _pendingReview.value = false
_topicCreated.value = null
_privateMessageCreated.value = null
try {
@@ -108,6 +114,10 @@ class ComposerViewModel(
}
private fun handleError(error: Exception) {
+ if (isPendingReview(error)) {
+ _pendingReview.value = true
+ return
+ }
val reported = FireErrorReporter.report(
operation = "composer.submit",
error = error,
@@ -117,6 +127,12 @@ class ComposerViewModel(
}
companion object {
+ fun isPendingReview(error: Throwable): Boolean {
+ val message = listOfNotNull(error.message, error.localizedMessage)
+ .joinToString("\n")
+ return message.contains("pending review", ignoreCase = true)
+ }
+
fun create(sessionStore: FireSessionStore): ComposerViewModel {
return ComposerViewModel(sessionStore)
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt
index f36184e6..e51c1811 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/PrivateMessageComposerSheet.kt
@@ -220,6 +220,17 @@ class PrivateMessageComposerSheet : BottomSheetDialogFragment() {
)
}
}
+ }
+ launch {
+ vm.pendingReview.collectLatest { pending ->
+ if (pending) {
+ didSubmit = true
+ draftAutosave?.cancel()
+ deleteDraftIfNeeded()
+ showToast(getString(R.string.composer_pending_review_message), FireToast.Style.SUCCESS)
+ dismiss()
+ }
+ }
}
}
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt
index b7e902c1..77b21558 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/ReplyComposerSheet.kt
@@ -27,7 +27,9 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
private var topicId: ULong = 0u
private var replyToPostNumber: UInt? = null
private var initialBody: String = ""
+ private var isBoost = false
private var onReplySubmitted: (() -> Unit)? = null
+ private var onBoostSubmitted: ((String) -> Unit)? = null
private lateinit var bodyInput: EditText
private lateinit var markdownToolbar: MarkdownToolbarView
@@ -72,12 +74,13 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
topicId = args.getLong(ARG_TOPIC_ID).toULong()
replyToPostNumber = args.getInt(ARG_REPLY_TO_POST_NUMBER).takeIf { it > 0 }?.toUInt()
initialBody = args.getString(ARG_INITIAL_BODY).orEmpty()
+ isBoost = args.getBoolean(ARG_IS_BOOST, false)
}
- val title = if (replyToPostNumber != null) {
- getString(R.string.topic_detail_reply_post_title, replyToPostNumber)
- } else {
- getString(R.string.topic_detail_reply_topic_title)
+ val title = when {
+ isBoost -> getString(R.string.topic_detail_boost_title)
+ replyToPostNumber != null -> getString(R.string.topic_detail_reply_post_title, replyToPostNumber)
+ else -> getString(R.string.topic_detail_reply_topic_title)
}
view.findViewById(R.id.reply_title).text = title
@@ -135,6 +138,13 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
bodyInput.error = getString(R.string.topic_detail_reply_min_length, "5")
return@setOnClickListener
}
+ if (isBoost) {
+ didSubmit = true
+ draftAutosave?.cancel()
+ onBoostSubmitted?.invoke(body)
+ dismiss()
+ return@setOnClickListener
+ }
viewModel?.submitReply(topicId, body, replyToPostNumber)
}
@@ -165,6 +175,13 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
)
}
}
+ }
+ launch {
+ vm.pendingReview.collectLatest { pending ->
+ if (pending) {
+ finishPendingReview(getString(R.string.composer_pending_review_reply))
+ }
+ }
}
}
}
@@ -221,6 +238,15 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
showToast(getString(R.string.composer_draft_restored), FireToast.Style.INFO)
}
+ private fun finishPendingReview(message: String) {
+ didSubmit = true
+ draftAutosave?.cancel()
+ viewLifecycleOwner.lifecycleScope.launch { deleteDraftIfNeeded() }
+ showToast(message, FireToast.Style.SUCCESS)
+ onReplySubmitted?.invoke()
+ dismiss()
+ }
+
private fun showToast(message: String, style: FireToast.Style) {
FireToast.show(view ?: return, message, style)
}
@@ -288,20 +314,27 @@ class ReplyComposerSheet : BottomSheetDialogFragment() {
private const val ARG_TOPIC_ID = "topic_id"
private const val ARG_REPLY_TO_POST_NUMBER = "reply_to_post_number"
private const val ARG_INITIAL_BODY = "initial_body"
+ private const val ARG_IS_BOOST = "is_boost"
fun newInstance(
topicId: Long,
replyToPostNumber: Int? = null,
initialBody: String? = null,
+ isBoost: Boolean = false,
+ postId: Long? = null,
onReplySubmitted: (() -> Unit)? = null,
+ onBoostSubmitted: ((String) -> Unit)? = null,
): ReplyComposerSheet {
return ReplyComposerSheet().apply {
arguments = Bundle().apply {
putLong(ARG_TOPIC_ID, topicId)
replyToPostNumber?.let { putInt(ARG_REPLY_TO_POST_NUMBER, it) }
initialBody?.let { putString(ARG_INITIAL_BODY, it) }
+ putBoolean(ARG_IS_BOOST, isBoost)
+ postId?.let { putLong("post_id", it) }
}
this.onReplySubmitted = onReplySubmitted
+ this.onBoostSubmitted = onBoostSubmitted
}
}
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt b/apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt
index 6d12f5a7..914dc5e8 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/composer/TopicComposerSheet.kt
@@ -5,6 +5,7 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
+import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.LinearLayout
@@ -50,6 +51,7 @@ class TopicComposerSheet : BottomSheetDialogFragment() {
private lateinit var previewRenderer: ComposerPreviewRenderer
private var previewMode = false
private var baseUrl = "https://linux.do"
+ private var lastAppliedTemplate: String? = null
private var onTopicCreated: ((ULong) -> Unit)? = null
@@ -140,6 +142,19 @@ class TopicComposerSheet : BottomSheetDialogFragment() {
if (defaultIndex >= 0) {
categorySpinner.setSelection(defaultIndex)
}
+ categorySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(
+ parent: AdapterView<*>?,
+ view: View?,
+ position: Int,
+ id: Long,
+ ) {
+ applyCategoryTemplateIfNeeded()
+ }
+
+ override fun onNothingSelected(parent: AdapterView<*>?) = Unit
+ }
+ applyCategoryTemplateIfNeeded()
canCreateTopic = session.readiness.canWriteAuthenticatedApi && categories.isNotEmpty()
categorySpinner.isEnabled = canCreateTopic
submitButton.isEnabled = canCreateTopic
@@ -233,6 +248,17 @@ class TopicComposerSheet : BottomSheetDialogFragment() {
)
}
}
+ }
+ launch {
+ vm.pendingReview.collectLatest { pending ->
+ if (pending) {
+ didSubmit = true
+ draftAutosave?.cancel()
+ deleteDraftIfNeeded()
+ showToast(getString(R.string.composer_pending_review_topic), FireToast.Style.SUCCESS)
+ dismiss()
+ }
+ }
}
}
}
@@ -294,6 +320,22 @@ class TopicComposerSheet : BottomSheetDialogFragment() {
}
}
+ private fun applyCategoryTemplateIfNeeded() {
+ val template = categories.getOrNull(categorySpinner.selectedItemPosition)
+ ?.topicTemplate
+ ?.trim()
+ .orEmpty()
+ if (template.isEmpty()) {
+ lastAppliedTemplate = null
+ return
+ }
+ val current = bodyInput.text?.toString().orEmpty()
+ if (current.isBlank() || current == lastAppliedTemplate) {
+ bodyInput.setText(template)
+ lastAppliedTemplate = template
+ }
+ }
+
private fun tagValues(): List =
tagsInput.text.toString()
.split("[,\\s]+".toRegex())
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt
index 75455220..821861a4 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeFragment.kt
@@ -18,6 +18,7 @@ import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
+import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
@@ -39,6 +40,8 @@ class HomeFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: TopicListAdapter
+ private lateinit var realtimeAdapter: HomeRealtimeRowsAdapter
+ private lateinit var newTopicsPill: TextView
private lateinit var emptyView: TextView
private lateinit var loadingSkeletonView: View
private lateinit var swipeRefresh: SwipeRefreshLayout
@@ -66,6 +69,7 @@ class HomeFragment : Fragment() {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.topic_list)
+ newTopicsPill = view.findViewById(R.id.new_topics_pill)
emptyView = view.findViewById(R.id.empty_view)
loadingSkeletonView = view.findViewById(R.id.loading_skeleton_view)
swipeRefresh = view.findViewById(R.id.swipe_refresh)
@@ -81,25 +85,35 @@ class HomeFragment : Fragment() {
val sessionStore = FireSessionStoreRepository.get(requireContext())
viewModel = ViewModelProvider(this@HomeFragment, HomeViewModelFactory(sessionStore))[HomeViewModel::class.java]
- adapter = TopicListAdapter(
- onTopicClick = { row ->
- if (!topicNavigationGate.tryBeginOpeningTopicDetail()) {
- return@TopicListAdapter
- }
+ val openTopic: (uniffi.fire_uniffi_types.TopicRowState) -> Unit = { row ->
+ if (topicNavigationGate.tryBeginOpeningTopicDetail()) {
TopicDetailActivity.start(
context = requireContext(),
topicId = row.topic.id.toLong(),
topicTitle = row.topic.title,
)
- },
- onTagClick = { tag ->
- viewModel?.selectTag(tag)
- recyclerView.scrollToPosition(0)
- },
+ }
+ }
+ val onTagClick: (String) -> Unit = { tag ->
+ viewModel?.selectTag(tag)
+ recyclerView.scrollToPosition(0)
+ }
+ adapter = TopicListAdapter(
+ onTopicClick = openTopic,
+ onTagClick = onTagClick,
+ )
+ realtimeAdapter = HomeRealtimeRowsAdapter(
+ onTopicClick = openTopic,
+ onTagClick = onTagClick,
)
+ newTopicsPill.setOnClickListener {
+ realtimeAdapter.flushPendingRows()
+ renderNewTopicsPill()
+ recyclerView.scrollToPosition(0)
+ }
recyclerView.layoutManager = LinearLayoutManager(requireContext())
- recyclerView.adapter = adapter
+ recyclerView.adapter = ConcatAdapter(realtimeAdapter, adapter)
recyclerView.optimizeForPaging()
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
@@ -166,10 +180,18 @@ class HomeFragment : Fragment() {
}
launch {
vm.session.collectLatest { session ->
- adapter.updateCategories(session?.bootstrap?.categories.orEmpty())
+ val categories = session?.bootstrap?.categories.orEmpty()
+ adapter.updateCategories(categories)
+ realtimeAdapter.updateCategories(categories)
renderScopeChrome()
}
}
+ launch {
+ vm.incrementalRows.collect { rows ->
+ realtimeAdapter.upsertRealtimeRows(rows, isTopicListAtTop())
+ renderNewTopicsPill()
+ }
+ }
launch {
vm.selectedKind.collectLatest { renderScopeChrome() }
}
@@ -185,13 +207,17 @@ class HomeFragment : Fragment() {
}
}
launch {
- vm.topicListRefreshEvents.collect {
- if (isTopicListAtTop()) {
- pendingAutoRefresh = false
- vm.prepareTopicRefresh()
- adapter.refresh()
- } else {
- pendingAutoRefresh = true
+ vm.topicListRefreshEvents.collect { mode ->
+ if (mode is HomeTopicListRefreshMode.Full) {
+ if (isTopicListAtTop()) {
+ pendingAutoRefresh = false
+ vm.prepareTopicRefresh()
+ realtimeAdapter.clear()
+ renderNewTopicsPill()
+ adapter.refresh()
+ } else {
+ pendingAutoRefresh = true
+ }
}
}
}
@@ -238,6 +264,10 @@ class HomeFragment : Fragment() {
swipeRefresh.setOnRefreshListener {
pendingAutoRefresh = false
viewModel?.prepareTopicRefresh()
+ if (::realtimeAdapter.isInitialized) {
+ realtimeAdapter.clear()
+ renderNewTopicsPill()
+ }
adapter.refresh()
}
}
@@ -410,6 +440,17 @@ class HomeFragment : Fragment() {
return firstVisibleView == null || firstVisibleView.top >= recyclerView.paddingTop
}
+ private fun renderNewTopicsPill() {
+ if (!::newTopicsPill.isInitialized || !::realtimeAdapter.isInitialized) {
+ return
+ }
+ newTopicsPill.visibility = if (realtimeAdapter.pendingCount > 0) {
+ View.VISIBLE
+ } else {
+ View.GONE
+ }
+ }
+
private fun flushPendingAutoRefreshIfAtTop() {
if (!pendingAutoRefresh || swipeRefresh.isRefreshing) {
return
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsAdapter.kt b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsAdapter.kt
new file mode 100644
index 00000000..a70a008a
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsAdapter.kt
@@ -0,0 +1,63 @@
+package com.fire.app.ui.home
+
+import android.view.ViewGroup
+import androidx.recyclerview.widget.RecyclerView
+import uniffi.fire_uniffi_session.TopicCategoryState
+import uniffi.fire_uniffi_types.TopicRowState
+
+class HomeRealtimeRowsAdapter(
+ private val onTagClick: (String) -> Unit = {},
+ private val onLongClick: ((TopicRowState) -> Boolean)? = null,
+ private val onTopicClick: (TopicRowState) -> Unit,
+) : RecyclerView.Adapter() {
+ private val store = HomeRealtimeRowsStore()
+ private var categoriesById: Map = emptyMap()
+
+ val pendingCount: Int
+ get() = store.pendingCount
+
+ fun snapshotIds(): Set = store.snapshotIds()
+
+ fun updateCategories(categories: List) {
+ val next = categories.associateBy { it.id }
+ if (categoriesById == next) return
+ categoriesById = next
+ notifyItemRangeChanged(0, itemCount)
+ }
+
+ fun upsertRealtimeRows(incoming: List, prependNow: Boolean): Int {
+ val mutation = store.upsertRealtimeRows(incoming, prependNow)
+ mutation.changedIndexes.forEach(::notifyItemChanged)
+ if (mutation.insertedCount > 0) {
+ notifyItemRangeInserted(0, mutation.insertedCount)
+ }
+ return pendingCount
+ }
+
+ fun flushPendingRows(): Int {
+ val inserted = store.flushPendingRows()
+ if (inserted > 0) {
+ notifyItemRangeInserted(0, inserted)
+ }
+ return pendingCount
+ }
+
+ fun clear() {
+ val count = store.clear()
+ if (count > 0) {
+ notifyItemRangeRemoved(0, count)
+ }
+ }
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TopicRowViewHolder {
+ return TopicRowViewHolder.create(parent)
+ }
+
+ override fun onBindViewHolder(holder: TopicRowViewHolder, position: Int) {
+ val row = store.rowAt(position)
+ val category = row.topic.categoryId?.let { categoriesById[it] }
+ holder.bind(row, category, onTopicClick, onTagClick, onLongClick)
+ }
+
+ override fun getItemCount(): Int = store.itemCount
+}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsStore.kt b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsStore.kt
new file mode 100644
index 00000000..4c0630ad
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeRealtimeRowsStore.kt
@@ -0,0 +1,74 @@
+package com.fire.app.ui.home
+
+import uniffi.fire_uniffi_types.TopicRowState
+
+class HomeRealtimeRowsStore {
+ private val rows = mutableListOf()
+ private val pendingRows = mutableListOf()
+
+ val snapshot: List
+ get() = rows.toList()
+
+ val pendingCount: Int
+ get() = pendingRows.size
+
+ fun snapshotIds(): Set = rows.map { it.topic.id }.toSet()
+
+ fun upsertRealtimeRows(incoming: List, prependNow: Boolean): HomeRealtimeRowsMutation {
+ if (incoming.isEmpty()) {
+ return HomeRealtimeRowsMutation()
+ }
+ val existingIds = rows.map { it.topic.id }.toSet()
+ val replacements = incoming.filter { existingIds.contains(it.topic.id) }
+ val inserts = incoming.filterNot { existingIds.contains(it.topic.id) }
+ val changedIndexes = mutableListOf()
+ replacements.forEach { replacement ->
+ val index = rows.indexOfFirst { it.topic.id == replacement.topic.id }
+ if (index >= 0) {
+ rows[index] = replacement
+ changedIndexes += index
+ }
+ }
+ var insertedCount = 0
+ if (inserts.isNotEmpty()) {
+ if (prependNow) {
+ rows.addAll(0, inserts)
+ insertedCount = inserts.size
+ } else {
+ pendingRows.removeAll { pending -> inserts.any { it.topic.id == pending.topic.id } }
+ pendingRows.addAll(0, inserts)
+ }
+ }
+ return HomeRealtimeRowsMutation(
+ changedIndexes = changedIndexes,
+ insertedCount = insertedCount,
+ )
+ }
+
+ fun flushPendingRows(): Int {
+ if (pendingRows.isEmpty()) {
+ return 0
+ }
+ val inserted = pendingRows.toList()
+ pendingRows.clear()
+ rows.addAll(0, inserted)
+ return inserted.size
+ }
+
+ fun clear(): Int {
+ val count = rows.size
+ rows.clear()
+ pendingRows.clear()
+ return count
+ }
+
+ fun rowAt(index: Int): TopicRowState = rows[index]
+
+ val itemCount: Int
+ get() = rows.size
+}
+
+data class HomeRealtimeRowsMutation(
+ val changedIndexes: List = emptyList(),
+ val insertedCount: Int = 0,
+)
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt
index 6acdc4bf..29c6771b 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt
@@ -14,6 +14,8 @@ data class HomeTopicDetailPatch(
val lastReadPostNumber: UInt?,
val highestPostNumber: UInt,
val unread: TopicHomeUnreadDecisionState = TopicHomeUnreadDecisionState.STILL_UNREAD,
+ val unreadPosts: UInt? = null,
+ val newPosts: UInt? = null,
) {
companion object {
fun from(patch: TopicHomeRowCountPatchState): HomeTopicDetailPatch {
@@ -25,6 +27,8 @@ data class HomeTopicDetailPatch(
lastReadPostNumber = patch.lastReadPostNumber,
highestPostNumber = patch.highestPostNumber,
unread = patch.unread,
+ unreadPosts = patch.unreadPosts,
+ newPosts = patch.newPosts,
)
}
}
@@ -69,8 +73,8 @@ object HomeTopicDetailPatcher {
nextHasUnreadPosts = false
}
TopicHomeUnreadDecisionState.STILL_UNREAD -> {
- nextUnreadPosts = topic.unreadPosts
- nextNewPosts = topic.newPosts
+ nextUnreadPosts = patch.unreadPosts ?: topic.unreadPosts
+ nextNewPosts = patch.newPosts ?: topic.newPosts
nextHasUnreadPosts = true
}
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt
index c4c0dded..4f2056c9 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/home/HomeViewModel.kt
@@ -57,14 +57,18 @@ internal data class HomeTopicListRefreshScope(
get() = kind == TopicListKindState.LATEST && categoryId == null && tags.isEmpty()
}
+internal sealed class HomeTopicListRefreshMode {
+ data object Full : HomeTopicListRefreshMode()
+ data class Incremental(val topicIds: List) : HomeTopicListRefreshMode()
+}
+
internal class HomeTopicListMessageBusRefreshController(
private val debounceDelayMs: Long = 1_500L,
- private val minimumIntervalMs: Long = 30_000L,
+ private val minimumIntervalMs: Long = 45_000L,
) {
private var scope: HomeTopicListRefreshScope? = null
private var lastRefreshAtMs: Long? = null
private val pendingTopicIds = mutableSetOf()
- private var requiresFullRefresh = false
fun register(
event: MessageBusEventState,
@@ -76,32 +80,25 @@ internal class HomeTopicListMessageBusRefreshController(
if (event.kind != MessageBusEventKindState.TOPIC_LIST || event.topicListKind != scope.kind) {
return null
}
-
- if (allowTopicScopedRefresh &&
- scope.supportsTopicScopedMessageBusRefresh &&
- event.topicId != null &&
- event.messageType?.equals("latest", ignoreCase = true) == true
+ if (!allowTopicScopedRefresh ||
+ !scope.supportsTopicScopedMessageBusRefresh ||
+ event.messageType?.equals("latest", ignoreCase = true) != true
) {
- event.topicId?.let { pendingTopicIds += it }
- } else {
- requiresFullRefresh = true
+ return null
}
-
+ val topicId = event.topicId ?: return null
+ pendingTopicIds += topicId
return scheduledDelay(nowMs)
}
- fun takePendingRefresh(scope: HomeTopicListRefreshScope): Boolean {
+ fun takePendingRefresh(scope: HomeTopicListRefreshScope): HomeTopicListRefreshMode? {
prepare(scope)
- if (requiresFullRefresh) {
- requiresFullRefresh = false
- pendingTopicIds.clear()
- return true
- }
if (pendingTopicIds.isEmpty()) {
- return false
+ return null
}
+ val topicIds = pendingTopicIds.sorted()
pendingTopicIds.clear()
- return true
+ return HomeTopicListRefreshMode.Incremental(topicIds)
}
fun markRefreshCompleted(scope: HomeTopicListRefreshScope, nowMs: Long) {
@@ -112,7 +109,6 @@ internal class HomeTopicListMessageBusRefreshController(
fun clearPending(scope: HomeTopicListRefreshScope) {
prepare(scope)
pendingTopicIds.clear()
- requiresFullRefresh = false
}
private fun prepare(nextScope: HomeTopicListRefreshScope) {
@@ -120,7 +116,6 @@ internal class HomeTopicListMessageBusRefreshController(
scope = nextScope
lastRefreshAtMs = null
pendingTopicIds.clear()
- requiresFullRefresh = false
}
private fun scheduledDelay(nowMs: Long): Long {
@@ -148,8 +143,13 @@ class HomeViewModel(
private val _selectedTags = MutableStateFlow>(emptyList())
val selectedTags = _selectedTags.asStateFlow()
- private val _topicListRefreshEvents = MutableSharedFlow(extraBufferCapacity = 1)
- val topicListRefreshEvents = _topicListRefreshEvents.asSharedFlow()
+ private val _topicListRefreshEvents = MutableSharedFlow(extraBufferCapacity = 1)
+ internal val topicListRefreshEvents = _topicListRefreshEvents.asSharedFlow()
+
+ private val _incrementalRows = MutableSharedFlow>(extraBufferCapacity = 4)
+ val incrementalRows = _incrementalRows.asSharedFlow()
+
+ private val visibleSnapshotIds = mutableSetOf()
private val _error = MutableSharedFlow(extraBufferCapacity = 1)
val error = _error.asSharedFlow()
@@ -214,6 +214,19 @@ class HomeViewModel(
}
}
+ viewModelScope.launch {
+ FireStateObserverRepository.topicListPatches.collectLatest { batch ->
+ val scope = currentRefreshScope()
+ if (batch.kind != scope.kind ||
+ batch.categoryId != scope.categoryId ||
+ batch.tags != scope.tags
+ ) {
+ return@collectLatest
+ }
+ batch.patches.forEach(HomeTopicDetailPatchRepository::publish)
+ }
+ }
+
viewModelScope.launch {
FireAppStateRefreshRepository.events.collectLatest { event ->
try {
@@ -346,9 +359,15 @@ class HomeViewModel(
}
}
+ fun updateVisibleSnapshot(rows: List) {
+ visibleSnapshotIds.clear()
+ rows.forEach { visibleSnapshotIds += it.topic.id }
+ }
+
private fun handleTopicPageLoaded(page: UInt, isCached: Boolean, rows: List) {
updateOfflineState(page, isCached)
if (page == 0u) {
+ updateVisibleSnapshot(rows)
FireWidgetData.updateTopicRows(
context = FireApplication.getInstance(),
rows = rows,
@@ -477,13 +496,20 @@ class HomeViewModel(
pendingMessageBusRefreshJob = viewModelScope.launch {
delay(delayMs)
val currentScope = currentRefreshScope()
- if (topicListMessageBusRefreshController.takePendingRefresh(currentScope)) {
- _topicListRefreshEvents.tryEmit(Unit)
- topicListMessageBusRefreshController.markRefreshCompleted(
- currentScope,
- System.currentTimeMillis(),
- )
+ val refresh = topicListMessageBusRefreshController.takePendingRefresh(currentScope)
+ ?: return@launch
+ when (refresh) {
+ HomeTopicListRefreshMode.Full -> {
+ _topicListRefreshEvents.tryEmit(refresh)
+ }
+ is HomeTopicListRefreshMode.Incremental -> {
+ applyIncrementalTopicIds(refresh.topicIds)
+ }
}
+ topicListMessageBusRefreshController.markRefreshCompleted(
+ currentScope,
+ System.currentTimeMillis(),
+ )
}
}
@@ -495,6 +521,48 @@ class HomeViewModel(
)
}
+ private suspend fun applyIncrementalTopicIds(topicIds: List) {
+ if (topicIds.isEmpty()) {
+ return
+ }
+ val list = topicRepository.fetchTopicList(
+ kind = TopicListKindState.LATEST,
+ topicIds = topicIds,
+ )
+ val existing = mutableListOf()
+ val inserted = mutableListOf()
+ for (row in list.rows) {
+ if (visibleSnapshotIds.contains(row.topic.id)) {
+ existing += row
+ } else {
+ inserted += row
+ visibleSnapshotIds += row.topic.id
+ }
+ }
+ existing.forEach { row ->
+ HomeTopicDetailPatchRepository.publishPatch(
+ HomeTopicDetailPatch(
+ topicId = row.topic.id,
+ postsCount = row.topic.postsCount,
+ replyCount = row.topic.replyCount,
+ views = row.topic.views,
+ lastReadPostNumber = row.topic.lastReadPostNumber,
+ highestPostNumber = row.topic.highestPostNumber,
+ unread = if (row.hasUnreadPosts) {
+ uniffi.fire_uniffi_topics.TopicHomeUnreadDecisionState.STILL_UNREAD
+ } else {
+ uniffi.fire_uniffi_topics.TopicHomeUnreadDecisionState.CAUGHT_UP
+ },
+ unreadPosts = row.topic.unreadPosts,
+ newPosts = row.topic.newPosts,
+ ),
+ )
+ }
+ if (inserted.isNotEmpty()) {
+ _incrementalRows.tryEmit(inserted)
+ }
+ }
+
private fun clearPendingMessageBusRefresh() {
pendingMessageBusRefreshJob?.cancel()
pendingMessageBusRefreshJob = null
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/settings/SettingsActivity.kt b/apps/android-app/src/main/java/com/fire/app/ui/settings/SettingsActivity.kt
index 5cdc72b9..c6ce1777 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/settings/SettingsActivity.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/settings/SettingsActivity.kt
@@ -24,6 +24,8 @@ import java.io.File
import kotlinx.coroutines.launch
import uniffi.fire_uniffi_diagnostics.LogFileSummaryState
import uniffi.fire_uniffi_diagnostics.NetworkTraceSummaryState
+import uniffi.fire_uniffi_session.BrowserTransportPrefState
+import uniffi.fire_uniffi_session.CloudflarePolicyState
import uniffi.fire_uniffi_session.DohPresetState
import uniffi.fire_uniffi_session.DohSettingsState
@@ -31,6 +33,9 @@ class SettingsActivity : AppCompatActivity() {
private val appearanceState = mutableStateOf(FireAppearancePreference.System)
private val dohSettingsState = mutableStateOf(DohSettingsState(enabled = false, endpointUrl = ""))
+ private val cloudflarePolicyState = mutableStateOf(
+ CloudflarePolicyState(autoVerify = true, browserTransport = BrowserTransportPrefState.OFF),
+ )
private val dohPresetsState = mutableStateOf>(emptyList())
private val customUrlState = mutableStateOf("")
private val dohStatusState = mutableStateOf("仅对 API 请求生效。关闭后使用系统 DNS。")
@@ -57,10 +62,15 @@ class SettingsActivity : AppCompatActivity() {
val logs by remember { logsState }
val traces by remember { tracesState }
val toolsStatus by remember { toolsStatusState }
+ val cloudflarePolicy by remember { cloudflarePolicyState }
SettingsHost(
appearance = appearance,
dohSubtitle = dohSubtitle(dohSettings, presets),
+ autoVerify = cloudflarePolicy.autoVerify,
+ browserTransportSubtitle = browserTransportSubtitle(cloudflarePolicy),
+ onToggleAutoVerify = { toggleAutoVerify() },
+ onToggleBrowserTransport = { toggleBrowserTransport() },
versionText = versionText(),
canLogout = true,
isLoggingOut = loggingOut,
@@ -130,6 +140,7 @@ class SettingsActivity : AppCompatActivity() {
val store = FireSessionStoreRepository.get(this)
dohPresetsState.value = store.listDohPresets()
dohSettingsState.value = store.getDohSettings()
+ cloudflarePolicyState.value = store.getCloudflarePolicy()
val settings = dohSettingsState.value
val match = dohPresetsState.value.any { it.endpointUrl == settings.endpointUrl }
if (!match) customUrlState.value = settings.endpointUrl
@@ -138,6 +149,38 @@ class SettingsActivity : AppCompatActivity() {
}
}
+ private fun toggleAutoVerify() {
+ val current = cloudflarePolicyState.value
+ persistCloudflarePolicy(current.copy(autoVerify = !current.autoVerify))
+ }
+
+ private fun toggleBrowserTransport() {
+ val current = cloudflarePolicyState.value
+ val next = when (current.browserTransport) {
+ BrowserTransportPrefState.OFF -> BrowserTransportPrefState.SESSION
+ BrowserTransportPrefState.SESSION -> BrowserTransportPrefState.PERSISTENT
+ BrowserTransportPrefState.PERSISTENT -> BrowserTransportPrefState.OFF
+ }
+ persistCloudflarePolicy(current.copy(browserTransport = next))
+ }
+
+ private fun persistCloudflarePolicy(next: CloudflarePolicyState) {
+ lifecycleScope.launch {
+ runCatching {
+ val store = FireSessionStoreRepository.get(this@SettingsActivity)
+ cloudflarePolicyState.value = store.setCloudflarePolicy(next)
+ }
+ }
+ }
+
+ private fun browserTransportSubtitle(policy: CloudflarePolicyState): String {
+ return when (policy.browserTransport) {
+ BrowserTransportPrefState.OFF -> "关闭"
+ BrowserTransportPrefState.SESSION -> "本会话"
+ BrowserTransportPrefState.PERSISTENT -> "排查用,确认 native 恢复后请关掉"
+ }
+ }
+
private fun persistDoh(next: DohSettingsState) {
lifecycleScope.launch {
runCatching {
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/settings/compose/SettingsScreen.kt b/apps/android-app/src/main/java/com/fire/app/ui/settings/compose/SettingsScreen.kt
index f0804489..2b710342 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/settings/compose/SettingsScreen.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/settings/compose/SettingsScreen.kt
@@ -44,6 +44,10 @@ enum class SettingsDestination {
fun SettingsHost(
appearance: FireAppearancePreference,
dohSubtitle: String,
+ autoVerify: Boolean,
+ browserTransportSubtitle: String,
+ onToggleAutoVerify: () -> Unit,
+ onToggleBrowserTransport: () -> Unit,
versionText: String,
canLogout: Boolean,
isLoggingOut: Boolean,
@@ -61,6 +65,10 @@ fun SettingsHost(
SettingsScreen(
appearance = appearance,
dohSubtitle = dohSubtitle,
+ autoVerify = autoVerify,
+ browserTransportSubtitle = browserTransportSubtitle,
+ onToggleAutoVerify = onToggleAutoVerify,
+ onToggleBrowserTransport = onToggleBrowserTransport,
versionText = versionText,
canLogout = canLogout,
isLoggingOut = isLoggingOut,
@@ -111,6 +119,10 @@ fun SettingsHost(
fun SettingsScreen(
appearance: FireAppearancePreference,
dohSubtitle: String,
+ autoVerify: Boolean,
+ browserTransportSubtitle: String,
+ onToggleAutoVerify: () -> Unit,
+ onToggleBrowserTransport: () -> Unit,
versionText: String,
canLogout: Boolean,
isLoggingOut: Boolean,
@@ -147,6 +159,20 @@ fun SettingsScreen(
subtitle = dohSubtitle,
iconWellColor = colors.info,
) to onOpenDoh,
+ FireListRowContent(
+ icon = Icons.Filled.Security,
+ title = "自动过盾",
+ subtitle = if (autoVerify) "开启" else "关闭,撞盾后需手动验证",
+ showsChevron = false,
+ iconWellColor = colors.info,
+ ) to onToggleAutoVerify,
+ FireListRowContent(
+ icon = Icons.Filled.Security,
+ title = "浏览器兼容运输",
+ subtitle = browserTransportSubtitle,
+ showsChevron = false,
+ iconWellColor = colors.warning,
+ ) to onToggleBrowserTransport,
),
)
Spacer(Modifier.height(16.dp))
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt
index a16864f2..9e8ee390 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostListModels.kt
@@ -29,6 +29,8 @@ data class PostRowCallbacks(
val onDeletePostClick: (TopicPostState) -> Unit = {},
val onRecoverPostClick: (TopicPostState) -> Unit = {},
val onFlagPostClick: (TopicPostState) -> Unit = {},
+ val onAcceptSolutionClick: (TopicPostState) -> Unit = {},
+ val onBoostClick: (TopicPostState) -> Unit = {},
val onEditPostClick: (TopicPostState) -> Unit = {},
val onImageClick: (FireCookedImage) -> Unit = {},
val onAuthorClick: (String) -> Unit = {},
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt
index 19d13910..5a18a99e 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/PostViewHolder.kt
@@ -40,6 +40,8 @@ class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val reactionsAction: TextView = itemView.findViewById(R.id.action_reactions)
private val editAction: TextView = itemView.findViewById(R.id.action_edit)
private val deleteRecoverAction: TextView = itemView.findViewById(R.id.action_delete_recover)
+ private val acceptAction: TextView = itemView.findViewById(R.id.action_accept)
+ private val boostAction: TextView = itemView.findViewById(R.id.action_boost)
private val flagAction: TextView = itemView.findViewById(R.id.action_flag)
internal var boostBarrageStartRunnable: Runnable? = null
internal val boostBarrageAnimators = mutableListOf()
@@ -114,7 +116,7 @@ class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
replyContextText.setOnClickListener(null)
}
- val contentId = "${post.id}:${post.presentation.hashCode()}"
+ val contentId = "${post.id}:${post.presentation?.checksum() ?: 0uL}"
if (bodyContainer.getTag(R.id.tag_post_content_id) != contentId) {
val presentation = post.presentation
bindPostBody(contentId, presentation, callbacks)
@@ -254,6 +256,35 @@ class PostViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
}
+ if (post.canAcceptAnswer || post.canUnacceptAnswer) {
+ configureIconAction(
+ view = acceptAction,
+ iconRes = R.drawable.ic_restore,
+ active = post.acceptedAnswer,
+ contentDescription = context.getString(
+ if (post.acceptedAnswer) {
+ R.string.topic_detail_unaccept_solution
+ } else {
+ R.string.topic_detail_accept_solution
+ },
+ ),
+ onClick = { callbacks.onAcceptSolutionClick(post) },
+ )
+ } else {
+ configureHiddenAction(acceptAction)
+ }
+
+ if (post.canBoost) {
+ configureIconAction(
+ view = boostAction,
+ iconRes = R.drawable.ic_add,
+ contentDescription = context.getString(R.string.topic_detail_boost_post),
+ onClick = { callbacks.onBoostClick(post) },
+ )
+ } else {
+ configureHiddenAction(boostAction)
+ }
+
if (!post.hidden) {
configureIconAction(
view = flagAction,
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt
index 2a866857..461fb821 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Composer.kt
@@ -19,6 +19,20 @@ import uniffi.fire_uniffi_session.TopicCategoryState
import uniffi.fire_uniffi_topics.TopicDetailState
import uniffi.fire_uniffi_topics.TopicPostState
+internal fun TopicDetailActivity.showBoostComposerForPost(post: TopicPostState) {
+ val currentRoute = route ?: return
+ val sheet = ReplyComposerSheet.newInstance(
+ topicId = currentRoute.topicId,
+ replyToPostNumber = post.postNumber.toInt(),
+ isBoost = true,
+ postId = post.id.toLong(),
+ onBoostSubmitted = { raw ->
+ viewModel?.createBoost(post, raw)
+ },
+ )
+ sheet.show(supportFragmentManager, "boost_composer")
+}
+
internal fun TopicDetailActivity.showReplyComposerForPost(post: TopicPostState) {
showReplyComposer(replyToPostNumber = post.postNumber.toInt())
}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt
index ace007bc..1b2981d2 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity+Observe.kt
@@ -124,6 +124,24 @@ internal fun TopicDetailActivity.observeViewModel() {
loadingFooterAdapter.isLoading = loadingMore
}
}
+
+ lifecycleScope.launch {
+ vm.typingUsers.collectLatest { usernames ->
+ val label = binding.topicDetailTyping
+ if (usernames.isEmpty()) {
+ label.visibility = View.GONE
+ label.text = null
+ } else {
+ val leading = usernames.take(3).joinToString("、")
+ label.text = if (usernames.size > 3) {
+ getString(R.string.topic_detail_typing_many, leading, usernames.size.toString())
+ } else {
+ getString(R.string.topic_detail_typing, leading)
+ }
+ label.visibility = View.VISIBLE
+ }
+ }
+ }
}
internal fun TopicDetailActivity.loadRoute(route: TopicDetailActivity.TopicDetailRoute) {
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt
index 9de434b9..dc0775db 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt
@@ -144,6 +144,8 @@ class TopicDetailActivity : AppCompatActivity() {
onDeletePostClick = { confirmDeletePost(it) },
onRecoverPostClick = { confirmRecoverPost(it) },
onFlagPostClick = { showFlagPostOptions(it) },
+ onAcceptSolutionClick = { viewModel?.acceptSolution(it) },
+ onBoostClick = { showBoostComposerForPost(it) },
onEditPostClick = { showPostEditor(it) },
onImageClick = { showImageViewer(it) },
onAuthorClick = { showUserInfoSheet(it) },
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailSnapshotMirror.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailSnapshotMirror.kt
new file mode 100644
index 00000000..c977a8c8
--- /dev/null
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailSnapshotMirror.kt
@@ -0,0 +1,95 @@
+package com.fire.app.ui.topicdetail
+
+import uniffi.fire_uniffi_topics.TopicDetailReplyContextChangeState
+import uniffi.fire_uniffi_topics.TopicDetailSnapshotChangeState
+import uniffi.fire_uniffi_topics.TopicDetailUiRowState
+import uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState
+
+fun interface TopicDetailFullSnapshotSource {
+ fun full(): TopicDetailUiSnapshotState
+}
+
+class TopicDetailSnapshotMirror {
+ private var snapshot: TopicDetailUiSnapshotState? = null
+ private val rowsById = LinkedHashMap()
+ private var order: List = emptyList()
+
+ @Synchronized
+ fun apply(
+ change: TopicDetailSnapshotChangeState,
+ source: TopicDetailFullSnapshotSource,
+ ): TopicDetailUiSnapshotState? {
+ val current = snapshot
+ if (current != null && change.generation <= current.generation) {
+ return null
+ }
+ if (current == null || change.baseGeneration != current.generation) {
+ return replace(source.full(), change)
+ }
+ var next = requireNotNull(current)
+ change.status?.let { status ->
+ next = next.copy(
+ phase = status.phase,
+ loadError = status.loadError,
+ notice = status.notice,
+ hasMore = status.hasMore,
+ isLoadingMore = status.isLoadingMore,
+ loadMoreError = status.loadMoreError,
+ scrollTargetPostNumber = status.scrollTargetPostNumber,
+ )
+ }
+ change.chrome?.let { next = next.copy(chrome = it) }
+ change.composer?.let { next = next.copy(composer = it) }
+ change.sidecar?.let { next = next.copy(sidecar = it) }
+ next = when (val reply = change.replyContext) {
+ is TopicDetailReplyContextChangeState.Unchanged -> next
+ is TopicDetailReplyContextChangeState.Cleared -> next.copy(focusedReplyContext = null)
+ is TopicDetailReplyContextChangeState.Set -> next.copy(focusedReplyContext = reply.context)
+ }
+ change.flagTypes?.let { next = next.copy(flagTypes = it) }
+ next = next.copy(homeRowPatch = change.homeRowPatch)
+ for (row in change.upsertedRows) {
+ rowsById[row.postId] = row
+ }
+ change.rowOrder?.let { rowOrder ->
+ order = rowOrder
+ val keep = rowOrder.toSet()
+ rowsById.keys.retainAll(keep)
+ }
+ if (order.any { it !in rowsById }) {
+ return replace(source.full(), change)
+ }
+ val rows = order.mapNotNull { rowsById[it] }
+ snapshot = next.copy(
+ generation = change.generation,
+ collectionRevision = change.revisions.collection,
+ chromeRevision = change.revisions.chrome,
+ sidecarRevision = change.revisions.sidecar,
+ interactionRevision = change.revisions.interaction,
+ composerRevision = change.revisions.composer,
+ rows = rows,
+ )
+ return snapshot
+ }
+
+ private fun replace(
+ full: TopicDetailUiSnapshotState,
+ change: TopicDetailSnapshotChangeState,
+ ): TopicDetailUiSnapshotState {
+ val next = full.copy(
+ generation = change.generation,
+ collectionRevision = change.revisions.collection,
+ chromeRevision = change.revisions.chrome,
+ sidecarRevision = change.revisions.sidecar,
+ interactionRevision = change.revisions.interaction,
+ composerRevision = change.revisions.composer,
+ )
+ rowsById.clear()
+ for (row in next.rows) {
+ rowsById[row.postId] = row
+ }
+ order = next.rows.map { it.postId }
+ snapshot = next
+ return next
+ }
+}
diff --git a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt
index da85dfab..d6f5d18b 100644
--- a/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt
+++ b/apps/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt
@@ -1,12 +1,9 @@
package com.fire.app.ui.topicdetail
-import android.util.LruCache
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.fire.app.core.error.FireErrorReporter
-import com.fire.app.richtext.FireRichTextContent
-import com.fire.app.richtext.FireRenderPresentation
import com.fire.app.session.FireSessionStore
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
@@ -62,14 +59,27 @@ class TopicDetailViewModel(
private val _bookmarkEvents = MutableSharedFlow(extraBufferCapacity = 1)
val bookmarkEvents = _bookmarkEvents.asSharedFlow()
+ private val _typingUsers = MutableStateFlow>(emptyList())
+ val typingUsers = _typingUsers.asStateFlow()
+
private var openedTopicId: ULong? = null
private var snapshotReplyRows: List = emptyList()
private val expandedReplyRootPostIds = mutableSetOf()
private var sessionHandle: uniffi.fire_uniffi_topics.TopicDetailSessionHandle? = null
+ private val snapshotMirror = TopicDetailSnapshotMirror()
+ private val postsById = LinkedHashMap()
+ private val rowFingerprints = HashMap()
+ private var lastRowOrder: List = emptyList()
private val sessionObserver = object : uniffi.fire_uniffi_topics.TopicDetailObserver {
- override fun onSnapshot(snapshot: uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState) {
+ override fun onChange(
+ change: uniffi.fire_uniffi_topics.TopicDetailSnapshotChangeState,
+ snapshot: uniffi.fire_uniffi_topics.TopicDetailSnapshotHandle,
+ ) {
+ val materialized = snapshotMirror.apply(change, snapshot::full)
+ snapshot.close()
+ if (materialized == null) return
viewModelScope.launch(Dispatchers.Main) {
- applyUiSnapshot(snapshot)
+ applyUiSnapshot(materialized)
}
}
}
@@ -77,8 +87,6 @@ class TopicDetailViewModel(
private var snapshotHasMore = false
val hasMorePosts: Boolean get() = snapshotHasMore
- private val renderCache = LruCache, FireRichTextContent>(64)
-
fun loadTopicDetail(topicId: ULong, targetPostNumber: UInt? = null) {
if (_isLoading.value) return
viewModelScope.launch {
@@ -132,7 +140,9 @@ class TopicDetailViewModel(
openedTopicId = null
snapshotReplyRows = emptyList()
expandedReplyRootPostIds.clear()
- renderCache.evictAll()
+ postsById.clear()
+ rowFingerprints.clear()
+ lastRowOrder = emptyList()
_detail.value = null
_postRows.value = emptyList()
_topicAiSummary.value = null
@@ -232,18 +242,6 @@ class TopicDetailViewModel(
}
}
- fun getRenderContent(post: TopicPostState): FireRichTextContent? {
- val cacheKey = renderCacheKey(post)
- val cached = renderCache.get(cacheKey)
- if (cached != null) return cached
-
- val content = parsePostContent(post)
- if (content != null) {
- renderCache.put(cacheKey, content)
- }
- return content
- }
-
fun toggleHeart(post: TopicPostState) {
viewModelScope.launch {
try {
@@ -368,6 +366,28 @@ class TopicDetailViewModel(
}
}
+ fun acceptSolution(post: TopicPostState) {
+ viewModelScope.launch {
+ try {
+ sessionHandle?.acceptSolution(post.id, !post.acceptedAnswer)
+ } catch (e: Exception) {
+ handleActionError(e, "解决方案更新失败")
+ }
+ }
+ }
+
+ fun createBoost(post: TopicPostState, raw: String) {
+ val trimmed = raw.trim()
+ if (trimmed.isEmpty()) return
+ viewModelScope.launch {
+ try {
+ sessionHandle?.createBoost(post.id, trimmed)
+ } catch (e: Exception) {
+ handleActionError(e, "Boost 发送失败")
+ }
+ }
+ }
+
fun deletePost(post: TopicPostState) {
viewModelScope.launch {
try {
@@ -398,39 +418,12 @@ class TopicDetailViewModel(
raw = trimmedRaw,
editReason = editReason?.trim()?.takeIf { it.isNotEmpty() },
)
- renderCache.remove(renderCacheKey(post))
} catch (e: Exception) {
handleActionError(e, "帖子编辑失败")
}
}
}
- private fun preloadRenderContent(posts: List) {
- viewModelScope.launch(Dispatchers.Default) {
- for (post in posts) {
- if (renderCache.get(renderCacheKey(post)) == null) {
- val content = parsePostContent(post)
- if (content != null) {
- renderCache.put(renderCacheKey(post), content)
- }
- }
- }
- }
- }
-
- private fun renderCacheKey(post: TopicPostState): Pair {
- return post.id to (post.presentation?.checksum() ?: 0uL)
- }
-
- private fun parsePostContent(post: TopicPostState): FireRichTextContent? {
- val presentation = post.presentation ?: return null
- return try {
- FireRenderPresentation.content(presentation)
- } catch (_: Exception) {
- null
- }
- }
-
private fun handleActionError(error: Exception, fallbackMessage: String) {
val reported = FireErrorReporter.report(
operation = "topic_detail.action",
@@ -441,6 +434,55 @@ class TopicDetailViewModel(
_actionError.tryEmit(reported.displayMessage)
}
+ private data class RowFingerprint(
+ val shape: Long,
+ val layoutChecksum: ULong,
+ val interactionChecksum: ULong,
+ val postNumber: UInt,
+ val rootPostNumber: UInt,
+ val parentPostNumber: UInt?,
+ val depth: UShort,
+ val hasChildren: Boolean,
+ val isLastSibling: Boolean,
+ val descendantCount: UInt,
+ val replyCount: UInt,
+ val isOriginalPost: Boolean,
+ )
+
+ private fun fingerprint(row: uniffi.fire_uniffi_topics.TopicDetailUiRowState): RowFingerprint {
+ return RowFingerprint(
+ shape = row.postId.toLong(),
+ layoutChecksum = row.layoutChecksum,
+ interactionChecksum = row.interactionChecksum,
+ postNumber = row.postNumber,
+ rootPostNumber = row.rootPostNumber,
+ parentPostNumber = row.parentPostNumber,
+ depth = row.depth,
+ hasChildren = row.hasChildren,
+ isLastSibling = row.isLastSibling,
+ descendantCount = row.descendantCount,
+ replyCount = row.replyCount,
+ isOriginalPost = row.isOriginalPost,
+ )
+ }
+
+ private fun upsertPosts(
+ rows: List,
+ ): List {
+ val keep = rows.map { it.postId }.toSet()
+ postsById.keys.retainAll(keep)
+ rowFingerprints.keys.retainAll(keep)
+ for (row in rows) {
+ val next = fingerprint(row)
+ if (rowFingerprints[row.postId] == next && postsById[row.postId] != null) {
+ continue
+ }
+ postsById[row.postId] = rowToPost(row)
+ rowFingerprints[row.postId] = next
+ }
+ return rows.mapNotNull { postsById[it.postId] }
+ }
+
private fun rowToPost(row: uniffi.fire_uniffi_topics.TopicDetailUiRowState): TopicPostState {
val author = row.author
return TopicPostState(
@@ -593,16 +635,26 @@ class TopicDetailViewModel(
snapshotHasMore = snapshot.hasMore
snapshot.scrollTargetPostNumber?.let { _scrollTargetPostNumber.tryEmit(it) }
snapshot.homeRowPatch?.let { com.fire.app.ui.home.HomeTopicDetailPatchRepository.publish(it) }
- val posts = snapshot.rows.map { rowToPost(it) }
+ val posts = upsertPosts(snapshot.rows)
val detail = detailFromSnapshot(snapshot, posts)
_detail.value = detail
- snapshotReplyRows = snapshot.rows.filter { !it.isOriginalPost }.map { rowToTreeRow(it) }
- _postRows.value = TopicDetailPostRows.projectRows(
- rows = snapshotReplyRows,
- postsById = posts.associateBy { it.id },
- expandedReplyRootPostIds = expandedReplyRootPostIds,
- focusedPostNumber = snapshot.scrollTargetPostNumber,
- )
+ val nextOrder = snapshot.rows.map { it.postId }
+ val orderChanged = nextOrder != lastRowOrder
+ lastRowOrder = nextOrder
+ if (orderChanged) {
+ snapshotReplyRows = snapshot.rows.filter { !it.isOriginalPost }.map { rowToTreeRow(it) }
+ _postRows.value = TopicDetailPostRows.projectRows(
+ rows = snapshotReplyRows,
+ postsById = postsById,
+ expandedReplyRootPostIds = expandedReplyRootPostIds,
+ focusedPostNumber = snapshot.scrollTargetPostNumber,
+ )
+ } else {
+ _postRows.value = _postRows.value.map { row ->
+ val updated = postsById[row.post.id] ?: return@map row
+ if (updated === row.post) row else row.copy(post = updated)
+ }
+ }
_topicAiSummary.value = snapshot.sidecar.summarizedText?.let { text ->
TopicAiSummaryState(
summarizedText = text,
@@ -615,7 +667,7 @@ class TopicDetailViewModel(
}
_isLoadingTopicAiSummary.value = snapshot.sidecar.isLoading
_topicAiSummaryError.value = snapshot.sidecar.error
- preloadRenderContent(posts)
+ _typingUsers.value = snapshot.composer.typingUsers.map { it.username }
}
override fun onCleared() {
diff --git a/apps/android-app/src/main/res/drawable/bg_home_new_topics_pill.xml b/apps/android-app/src/main/res/drawable/bg_home_new_topics_pill.xml
new file mode 100644
index 00000000..b4afcc36
--- /dev/null
+++ b/apps/android-app/src/main/res/drawable/bg_home_new_topics_pill.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
diff --git a/apps/android-app/src/main/res/layout/activity_topic_detail.xml b/apps/android-app/src/main/res/layout/activity_topic_detail.xml
index 82e81339..a5d1dc0a 100644
--- a/apps/android-app/src/main/res/layout/activity_topic_detail.xml
+++ b/apps/android-app/src/main/res/layout/activity_topic_detail.xml
@@ -88,6 +88,16 @@
android:layout_height="1dp"
android:background="@color/fire_divider" />
+
+
+
+
+
+
+
+
Native host shell for LinuxDo login, session restore, and inline topic browsing.
首页
当前范围暂无话题。下拉刷新,或点顶部范围胶囊切换分类 / 排序后再试。
+ 有新话题
打开分类抽屉
分类
搜索分类
选择子分类
回复话题…
+ %1$s 正在输入
+ %1$s 等 %2$s 人正在输入
+ 采纳为解决方案
+ 取消采纳
+ Boost
+ Boost 这条帖子
+ 改用浏览器网络
+ 当前网络反复触发验证,是否改用浏览器网络(本会话)?
+ 使用
+ 暂不
+ 帖子已提交,等待审核。
+ 回复已提交,等待审核。
+ 私信已提交,等待审核。
搜索 LinuxDo
输入关键词搜索话题、帖子或用户。
通知
diff --git a/apps/android-app/src/main/res/values/themes.xml b/apps/android-app/src/main/res/values/themes.xml
index d278e145..f0e015a0 100644
--- a/apps/android-app/src/main/res/values/themes.xml
+++ b/apps/android-app/src/main/res/values/themes.xml
@@ -1,5 +1,14 @@
+
+