diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index 17e47078..e47dd1e4 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -119,4 +119,9 @@ export const D1_MIGRATIONS = [ "table:message_event_compaction", ], }, + { + id: "2026-08-30-pinned-messages", + file: "worker/migrations/2026-08-30-pinned-messages.sql", + artifacts: ["table:channel_pins", "trigger:clear_pin_after_message_soft_delete"], + }, ]; diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml index 42d14175..fe2923ee 100644 --- a/.github/workflows/android-release.yml +++ b/.github/workflows/android-release.yml @@ -89,7 +89,8 @@ jobs: apksigner_path="$(find "$ANDROID_HOME/build-tools" -type f -name apksigner | sort -V | tail -n 1)" test -n "$apksigner_path" "$apksigner_path" verify --verbose --print-certs android/release-artifacts/*.apk - jarsigner -verify -strict android/release-artifacts/*.aab + # AAB 是 JAR 签名格式;JDK 17 的 strict 模式会把 App Bundle 合法的 ZIP 结构警告误判为失败。 + jarsigner -verify -verbose -certs android/release-artifacts/*.aab - name: Publish GitHub Release shell: bash env: diff --git a/README.en.md b/README.en.md index 7be370b3..59530152 100644 --- a/README.en.md +++ b/README.en.md @@ -148,7 +148,7 @@ GitHub Actions deployment is recommended first — it suits long-term maintenanc ### Native Android Client -The repository's `android/` directory is an independent Kotlin + Jetpack Compose client for Android 8 / API 26 and newer. It depends only on the stable `/api/v1` contract and never packages Vue components or CSS. On first launch, paste a valid HTTPS server origin or open `edgechat://connect?server=https%3A%2F%2Fchat.example.com`; the app validates server capabilities before sign-in. +The repository's `android/` directory is an independent Kotlin + Jetpack Compose client for Android 8 / API 26 and newer. It depends only on the stable `/api/v1` contract and never packages Vue components or CSS. When signed out, enter the HTTPS server origin, username, and password on one screen, or use `edgechat://connect?server=https%3A%2F%2Fchat.example.com` to prefill the server. The app validates server capabilities before completing sign-in. - Installation: download `edgechat-*.apk` from GitHub Releases and verify `SHA256SUMS.txt` - CI: `.github/workflows/android-ci.yml` runs unit tests, Lint, and a Debug APK build diff --git a/README.ja.md b/README.ja.md index dc69ca12..82c6f4e9 100644 --- a/README.ja.md +++ b/README.ja.md @@ -148,7 +148,7 @@ GitHub Actions でのデプロイを優先的に推奨します。長期的な ### ネイティブ Android クライアント -リポジトリの `android/` は Android 8 / API 26 以降向けの独立した Kotlin + Jetpack Compose クライアントです。安定した `/api/v1` 契約だけを共有し、Vue コンポーネントや CSS は APK に含めません。初回起動時に有効な HTTPS サーバー URL を入力するか、`edgechat://connect?server=https%3A%2F%2Fchat.example.com` を開くと、ログイン前にサーバー機能を確認します。 +リポジトリの `android/` は Android 8 / API 26 以降向けの独立した Kotlin + Jetpack Compose クライアントです。安定した `/api/v1` 契約だけを共有し、Vue コンポーネントや CSS は APK に含めません。未ログイン時は 1 つの画面で HTTPS サーバー URL、ユーザー名、パスワードを入力できます。`edgechat://connect?server=https%3A%2F%2Fchat.example.com` でサーバーを事前入力することもでき、送信後にサーバー機能を確認してからログインします。 - インストール:GitHub Releases から `edgechat-*.apk` を取得し、`SHA256SUMS.txt` を確認 - CI:`.github/workflows/android-ci.yml` が単体テスト、Lint、Debug APK ビルドを実行 diff --git a/README.md b/README.md index 6d99199d..60eaf388 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系 ### 原生 Android 客户端 -仓库内的 `android/` 是独立的 Kotlin + Jetpack Compose 客户端(Android 8 / API 26 起),只依赖稳定的 `/api/v1` 协议,不复用网页组件或 CSS。首次启动粘贴有效 HTTPS 服务器地址,或打开 `edgechat://connect?server=https%3A%2F%2Fchat.example.com`,客户端会先校验服务器能力再登录。 +仓库内的 `android/` 是独立的 Kotlin + Jetpack Compose 客户端(Android 8 / API 26 起),只依赖稳定的 `/api/v1` 协议,不复用网页组件或 CSS。未登录时可在同一页输入 HTTPS 服务器地址、用户名和密码;也可以通过 `edgechat://connect?server=https%3A%2F%2Fchat.example.com` 预填服务器。提交后客户端会先校验服务器能力,再完成登录。 - 安装包:从 GitHub Releases 下载 `edgechat-*.apk` 并核对 `SHA256SUMS.txt` - CI:`.github/workflows/android-ci.yml` 运行单元测试、Lint 和 Debug APK 构建 diff --git a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/WelcomeScreenTest.kt b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/WelcomeScreenTest.kt index 194c093f..26218e1b 100644 --- a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/WelcomeScreenTest.kt +++ b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/WelcomeScreenTest.kt @@ -1,10 +1,15 @@ package com.aozorae.edgechat.feature.auth import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextContains import androidx.compose.ui.test.junit4.createComposeRule -import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.junit4.StateRestorationTester +import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.performClick -import org.junit.Assert.assertTrue +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performTextReplacement +import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test @@ -12,14 +17,46 @@ class WelcomeScreenTest { @get:Rule val compose = createComposeRule() @Test - fun connectServerOpensSetupFlow() { - var continued = false + fun loginStartsDisabledUntilAllFieldsAreFilled() { compose.setContent { - WelcomeScreen(language = "en-US", onContinue = { continued = true }) + WelcomeScreen(null, false, "en-US") { _, _, _ -> } } - compose.onNodeWithText("EdgeChat").assertIsDisplayed() - compose.onNodeWithText("Connect server").assertIsDisplayed().performClick() - assertTrue(continued) + compose.onNodeWithTag("serverField").assertIsDisplayed() + compose.onNodeWithTag("usernameField").assertIsDisplayed() + compose.onNodeWithTag("passwordField").assertIsDisplayed() + compose.onNodeWithTag("loginButton").assertIsNotEnabled() + } + + @Test + fun loginSubmitsServerAndCredentials() { + var submitted: Triple? = null + compose.setContent { + WelcomeScreen(null, false, "en-US") { server, username, password -> + submitted = Triple(server, username, password) + } + } + + compose.onNodeWithTag("serverField").performTextInput("https://chat.example.com") + compose.onNodeWithTag("usernameField").performTextInput("alice") + compose.onNodeWithTag("passwordField").performTextInput("secret") + compose.onNodeWithTag("loginButton").performClick() + + assertEquals(Triple("https://chat.example.com", "alice", "secret"), submitted) + } + + @Test + fun serverAndUsernameSurviveStateRestoration() { + val restoration = StateRestorationTester(compose) + restoration.setContent { + WelcomeScreen("https://old.example.com", false, "en-US") { _, _, _ -> } + } + + compose.onNodeWithTag("serverField").performTextReplacement("https://chat.example.com") + compose.onNodeWithTag("usernameField").performTextInput("alice") + restoration.emulateSavedInstanceStateRestore() + + compose.onNodeWithTag("serverField").assertTextContains("https://chat.example.com") + compose.onNodeWithTag("usernameField").assertTextContains("alice") } } diff --git a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/ChatMessagesLayoutTest.kt b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/ChatMessagesLayoutTest.kt index 0d898589..1d492987 100644 --- a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/ChatMessagesLayoutTest.kt +++ b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/ChatMessagesLayoutTest.kt @@ -1,5 +1,7 @@ package com.aozorae.edgechat.feature.chat +import android.graphics.Bitmap +import android.graphics.Color import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width @@ -7,14 +9,18 @@ import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.ui.Modifier import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry import com.aozorae.edgechat.core.database.MessageEntity import com.aozorae.edgechat.core.database.OutboxEntity import com.aozorae.edgechat.core.network.dto.SessionDto import com.aozorae.edgechat.ui.theme.EdgeChatTheme +import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test +import java.io.File class ChatMessagesLayoutTest { @get:Rule val compose = createComposeRule() @@ -59,13 +65,115 @@ class ChatMessagesLayoutTest { assertTrue(pendingCenter > listCenter) } + @Test + fun imageAttachmentsUseInlinePreviewAndRemainOpenable() { + var opened: Triple? = null + compose.setContent { + EdgeChatTheme { + Box(Modifier.width(360.dp).height(640.dp)) { + ChatMessages( + messages = listOf( + message( + id = 3, + senderId = "2", + content = "", + attachmentName = "photo.jpg", + attachmentType = "image/jpeg", + attachmentUrl = "https://images.invalid/photo.jpg", + ), + message( + id = 4, + senderId = "2", + content = "", + attachmentName = "report.pdf", + attachmentType = "application/pdf", + attachmentUrl = "/files/report.pdf", + ), + ), + outbox = emptyList(), + currentUser = currentUser(), + serverBaseUrl = "https://example.com", + language = "en-US", + scrollState = rememberLazyListState(), + onLoadOlder = {}, + onRetry = {}, + onCancel = {}, + onDeleteMessage = {}, + onOpenAttachment = { url, name, type -> opened = Triple(url, name, type) }, + ) + } + } + } + + compose.onNodeWithTag("message_image:3").performClick() + compose.onNodeWithTag("message_attachment:4").assertExists() + assertEquals( + Triple("https://images.invalid/photo.jpg", "photo.jpg", "image/jpeg"), + opened, + ) + } + + @Test + fun portraitPendingImageUsesItsOwnAspectRatioAndStaysCompact() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val portrait = File(context.cacheDir, "portrait-preview.png") + Bitmap.createBitmap(90, 180, Bitmap.Config.ARGB_8888).run { + eraseColor(Color.RED) + portrait.outputStream().use { compress(Bitmap.CompressFormat.PNG, 100, it) } + recycle() + } + compose.setContent { + EdgeChatTheme { + Box(Modifier.width(360.dp).height(640.dp)) { + ChatMessages( + messages = emptyList(), + outbox = listOf( + pendingMessage( + localAttachmentPath = portrait.absolutePath, + attachmentName = "portrait-preview.png", + attachmentType = "image/png", + ), + ), + currentUser = currentUser(), + serverBaseUrl = "https://example.com", + language = "en-US", + scrollState = rememberLazyListState(), + onLoadOlder = {}, + onRetry = {}, + onCancel = {}, + onDeleteMessage = {}, + onOpenAttachment = { _, _, _ -> }, + ) + } + } + } + + compose.waitUntil(5_000) { + val bounds = compose.onNodeWithTag("pending_message_image:pending-1") + .fetchSemanticsNode().boundsInRoot + bounds.height > bounds.width + } + val bounds = compose.onNodeWithTag("pending_message_image:pending-1") + .fetchSemanticsNode().boundsInRoot + assertTrue(bounds.height > bounds.width * 1.9f) + assertTrue(bounds.height <= 240f * context.resources.displayMetrics.density + 1f) + portrait.delete() + } + private fun currentUser() = SessionDto( userId = 1, username = "me", displayName = "Me", ) - private fun message(id: Long, senderId: String, content: String) = MessageEntity( + private fun message( + id: Long, + senderId: String, + content: String, + attachmentName: String? = null, + attachmentType: String? = null, + attachmentUrl: String? = null, + ) = MessageEntity( id = id, roomKind = "public", roomId = 1, @@ -79,20 +187,24 @@ class ChatMessagesLayoutTest { senderDisplayName = "User $senderId", senderAvatarUrl = "", attachmentKey = null, - attachmentName = null, - attachmentType = null, + attachmentName = attachmentName, + attachmentType = attachmentType, attachmentSize = null, - attachmentUrl = null, + attachmentUrl = attachmentUrl, ) - private fun pendingMessage() = OutboxEntity( + private fun pendingMessage( + localAttachmentPath: String? = null, + attachmentName: String? = null, + attachmentType: String? = null, + ) = OutboxEntity( clientMessageId = "pending-1", roomKind = "public", roomId = 1, content = "Pending", - localAttachmentPath = null, - attachmentName = null, - attachmentType = null, + localAttachmentPath = localAttachmentPath, + attachmentName = attachmentName, + attachmentType = attachmentType, attachmentSize = null, clientUploadId = null, uploadedKey = null, diff --git a/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt b/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt index 7fe85d2c..01d94c9f 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt @@ -7,13 +7,19 @@ import coil.ImageLoader import coil.ImageLoaderFactory import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject +import okhttp3.OkHttpClient @HiltAndroidApp class EdgeChatApplication : Application(), Configuration.Provider, ImageLoaderFactory { @Inject lateinit var workerFactory: HiltWorkerFactory + @Inject lateinit var okHttpClient: OkHttpClient override val workManagerConfiguration: Configuration get() = Configuration.Builder().setWorkerFactory(workerFactory).build() - override fun newImageLoader(): ImageLoader = ImageLoader.Builder(this).crossfade(true).build() + override fun newImageLoader(): ImageLoader = ImageLoader.Builder(this) + // 消息图片受移动端会话保护,复用网络层客户端才能统一附加令牌并完成过期刷新。 + .okHttpClient(okHttpClient) + .crossfade(true) + .build() } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt index 93358d05..67302500 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt @@ -25,15 +25,23 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock data class AppUiState( val server: ServerProfile? = null, val session: SessionDto? = null, val language: String = "zh-CN", - val loading: Boolean = true, + val initializing: Boolean = true, + val loading: Boolean = false, val error: String? = null, ) +private data class AppProgress( + val initializing: Boolean, + val loading: Boolean, +) + @HiltViewModel class AppViewModel @Inject constructor( @ApplicationContext private val context: Context, @@ -46,17 +54,20 @@ class AppViewModel @Inject constructor( private val diagnostics: DiagnosticLog, private val realtime: RealtimeCoordinator, ) : ViewModel() { - private val loading = MutableStateFlow(true) + private val initializing = MutableStateFlow(true) + private val loading = MutableStateFlow(false) private val error = MutableStateFlow(null) + private val progress = combine(initializing, loading, ::AppProgress) + private val actionMutex = Mutex() val state: StateFlow = combine( serverStore.server, sessionRepository.session, serverStore.language, - loading, + progress, error, - ) { server, session, language, busy, failure -> - AppUiState(server, session, language, busy, failure) + ) { server, session, language, progress, failure -> + AppUiState(server, session, language, progress.initializing, progress.loading, failure) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppUiState()) init { @@ -74,11 +85,24 @@ class AppViewModel @Inject constructor( runCatching { chatRepository.bootstrap() }.onFailure { error.value = it.message } realtime.start() } - loading.value = false + initializing.value = false } } fun connect(server: String) = launchAction { + connectToServer(server) + } + + fun connectAndLogin(server: String, username: String, password: String) = launchAction { + connectToServer(server) + authenticate(username, password) + } + + fun login(username: String, password: String) = launchAction { + authenticate(username, password) + } + + private suspend fun connectToServer(server: String) { val hadSession = sessionRepository.session.value != null realtime.stop() outboxRepository.pauseForServerChange() @@ -99,9 +123,10 @@ class AppViewModel @Inject constructor( } } - fun login(username: String, password: String) = launchAction { + private suspend fun authenticate(username: String, password: String) { sessionRepository.login(username, password) chatRepository.bootstrap() + outboxRepository.resume() realtime.start() } @@ -155,13 +180,15 @@ class AppViewModel @Inject constructor( private fun launchAction(block: suspend () -> Unit) { viewModelScope.launch { - loading.value = true - error.value = null - runCatching { block() }.onFailure { - diagnostics.record("ui_action_failed reason=${it.javaClass.simpleName}") - error.value = it.message ?: "操作失败" + actionMutex.withLock { + loading.value = true + error.value = null + runCatching { block() }.onFailure { + diagnostics.record("ui_action_failed reason=${it.javaClass.simpleName}") + error.value = it.message ?: "操作失败" + } + loading.value = false } - loading.value = false } } } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/auth/WelcomeScreen.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/WelcomeScreen.kt index b3be32e3..eafa5018 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/auth/WelcomeScreen.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/WelcomeScreen.kt @@ -1,23 +1,46 @@ package com.aozorae.edgechat.feature.auth +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowForward +import androidx.compose.material.icons.outlined.AccountCircle +import androidx.compose.material.icons.outlined.Link +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material.icons.outlined.Visibility +import androidx.compose.material.icons.outlined.VisibilityOff import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.aozorae.edgechat.ui.components.EdgeChatBrandMark @@ -25,53 +48,115 @@ import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors @Composable fun WelcomeScreen( + initialServer: String?, + loading: Boolean, language: String, - onContinue: () -> Unit, + onLogin: (String, String, String) -> Unit, ) { + var server by rememberSaveable(initialServer) { mutableStateOf(initialServer.orEmpty()) } + var username by rememberSaveable { mutableStateOf("") } + var password by remember { mutableStateOf("") } + var passwordVisible by remember { mutableStateOf(false) } val colors = LocalEdgeChatColors.current - Column( - modifier = Modifier - .fillMaxSize() - .safeDrawingPadding() - .padding(horizontal = 24.dp, vertical = 20.dp), - horizontalAlignment = Alignment.CenterHorizontally, - ) { - Spacer(Modifier.weight(1f)) - EdgeChatBrandMark(size = 112.dp) - Spacer(Modifier.height(32.dp)) - Text( - text = "EdgeChat", - style = MaterialTheme.typography.displaySmall, - color = colors.textPrimary, - ) - Spacer(Modifier.height(12.dp)) - Text( - text = if (language == "zh-CN") { - "连接你的服务器,继续属于你的对话" - } else { - "Connect your server and continue the conversations that are yours." - }, - modifier = Modifier.widthIn(max = 460.dp), - style = MaterialTheme.typography.bodyLarge, - color = colors.textSecondary, - textAlign = TextAlign.Center, - ) - Spacer(Modifier.weight(1f)) - Button( - onClick = onContinue, + val canLogin = server.isNotBlank() && username.isNotBlank() && password.isNotBlank() && !loading + val submit = { if (canLogin) onLogin(server, username, password) } + + Scaffold(containerColor = colors.canvas) { contentPadding -> + Column( modifier = Modifier - .widthIn(max = 520.dp) - .fillMaxWidth() - .height(56.dp), - shape = MaterialTheme.shapes.extraLarge, + .fillMaxSize() + .padding(contentPadding) + .imePadding() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 24.dp, vertical = 28.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(if (language == "zh-CN") "连接服务器" else "Connect server") - Spacer(Modifier.weight(1f)) - Icon(Icons.AutoMirrored.Rounded.ArrowForward, contentDescription = null) + EdgeChatBrandMark(size = 72.dp) + Spacer(Modifier.height(20.dp)) + Text( + text = if (language == "zh-CN") "登录 EdgeChat" else "Sign in to EdgeChat", + style = MaterialTheme.typography.headlineSmall, + color = colors.textPrimary, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(8.dp)) + Text( + text = if (language == "zh-CN") { + "输入服务器地址和账号,继续你的对话" + } else { + "Enter your server and account to continue your conversations." + }, + modifier = Modifier.widthIn(max = 460.dp), + style = MaterialTheme.typography.bodyLarge, + color = colors.textSecondary, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(28.dp)) + Column(modifier = Modifier.fillMaxWidth().widthIn(max = 520.dp)) { + OutlinedTextField( + value = server, + onValueChange = { server = it }, + modifier = Modifier.fillMaxWidth().testTag("serverField"), + enabled = !loading, + singleLine = true, + label = { Text(if (language == "zh-CN") "服务器地址" else "Server address") }, + placeholder = { Text("https://chat.example.com") }, + leadingIcon = { Icon(Icons.Outlined.Link, contentDescription = null) }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next), + shape = MaterialTheme.shapes.large, + ) + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = username, + onValueChange = { username = it }, + modifier = Modifier.fillMaxWidth().testTag("usernameField"), + enabled = !loading, + singleLine = true, + label = { Text(if (language == "zh-CN") "用户名" else "Username") }, + leadingIcon = { Icon(Icons.Outlined.AccountCircle, contentDescription = null) }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), + shape = MaterialTheme.shapes.large, + ) + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + modifier = Modifier.fillMaxWidth().testTag("passwordField"), + enabled = !loading, + singleLine = true, + visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), + label = { Text(if (language == "zh-CN") "密码" else "Password") }, + leadingIcon = { Icon(Icons.Outlined.Lock, contentDescription = null) }, + trailingIcon = { + IconButton(onClick = { passwordVisible = !passwordVisible }) { + Icon( + if (passwordVisible) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility, + contentDescription = if (language == "zh-CN") "切换密码可见性" else "Toggle password visibility", + ) + } + }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { submit() }), + shape = MaterialTheme.shapes.large, + ) + Spacer(Modifier.height(20.dp)) + Button( + onClick = submit, + enabled = canLogin, + modifier = Modifier.fillMaxWidth().height(56.dp).testTag("loginButton"), + shape = MaterialTheme.shapes.extraLarge, + ) { + if (loading) { + CircularProgressIndicator( + modifier = Modifier.size(20.dp), + color = MaterialTheme.colorScheme.onPrimary, + strokeWidth = 2.dp, + ) + } else { + Text(if (language == "zh-CN") "登录" else "Sign in") + } + } } } } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt index fd826100..bbd26df2 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt @@ -61,6 +61,7 @@ import com.aozorae.edgechat.ui.formatDayLabel import com.aozorae.edgechat.ui.formatMessageTime import com.aozorae.edgechat.ui.messageDate import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors +import java.io.File import kotlinx.coroutines.launch private enum class MessageGroupPosition { @@ -290,6 +291,7 @@ private fun MessageItem( message = message, own = own, groupPosition = groupPosition, + serverBaseUrl = serverBaseUrl, language = language, onOpenAttachment = onOpenAttachment, modifier = Modifier.testTag("message_bubble:${message.id}"), @@ -304,6 +306,7 @@ private fun MessageBubble( message: MessageEntity, own: Boolean, groupPosition: MessageGroupPosition, + serverBaseUrl: String, language: String, onOpenAttachment: (String, String, String) -> Unit, modifier: Modifier = Modifier, @@ -323,18 +326,28 @@ private fun MessageBubble( val attachmentUrl = message.attachmentUrl if (attachmentUrl != null) { if (message.content.isNotBlank()) Spacer(Modifier.height(8.dp)) - AttachmentTile( - name = message.attachmentName ?: "attachment", - type = message.attachmentType ?: "application/octet-stream", - language = language, - onClick = { - onOpenAttachment( - attachmentUrl, - message.attachmentName ?: "attachment", - message.attachmentType ?: "application/octet-stream", - ) - }, - ) + val attachmentName = message.attachmentName ?: "attachment" + val attachmentType = message.attachmentType ?: "application/octet-stream" + val openAttachment = { + onOpenAttachment(attachmentUrl, attachmentName, attachmentType) + } + if (isImageAttachment(attachmentType)) { + MessageImageAttachment( + model = resolveServerUrl(serverBaseUrl, attachmentUrl), + name = attachmentName, + language = language, + tag = "message_image:${message.id}", + onClick = openAttachment, + ) + } else { + AttachmentTile( + name = attachmentName, + type = attachmentType, + language = language, + onClick = openAttachment, + modifier = Modifier.testTag("message_attachment:${message.id}"), + ) + } } Spacer(Modifier.height(4.dp)) Text( @@ -371,12 +384,18 @@ private fun messageBubbleShape(position: MessageGroupPosition, own: Boolean): Ro } @Composable -private fun AttachmentTile(name: String, type: String, language: String, onClick: () -> Unit) { +private fun AttachmentTile( + name: String, + type: String, + language: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { val colors = LocalEdgeChatColors.current Surface( color = colors.canvas.copy(alpha = 0.72f), shape = MaterialTheme.shapes.small, - modifier = Modifier.clickable( + modifier = modifier.clickable( role = Role.Button, onClickLabel = if (language == "zh-CN") "打开附件" else "Open attachment", onClick = onClick, @@ -436,9 +455,20 @@ private fun PendingMessageItem( ) { Column(Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { if (item.content.isNotBlank()) Text(item.content, style = MaterialTheme.typography.bodyLarge) - item.attachmentName?.let { + item.attachmentName?.let { attachmentName -> if (item.content.isNotBlank()) Spacer(Modifier.height(6.dp)) - Text(it, style = MaterialTheme.typography.bodySmall) + val localPath = item.localAttachmentPath + if (localPath != null && isImageAttachment(item.attachmentType)) { + MessageImageAttachment( + model = File(localPath), + name = attachmentName, + language = language, + tag = "pending_message_image:${item.clientMessageId}", + onClick = null, + ) + } else { + Text(attachmentName, style = MaterialTheme.typography.bodySmall) + } } Spacer(Modifier.height(5.dp)) Text( diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageImageAttachment.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageImageAttachment.kt new file mode 100644 index 00000000..3bcdcb49 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageImageAttachment.kt @@ -0,0 +1,118 @@ +package com.aozorae.edgechat.feature.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Image +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import coil.compose.SubcomposeAsyncImage +import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors + +internal fun isImageAttachment(contentType: String?): Boolean = contentType?.startsWith("image/") == true + +internal data class ImagePreviewSize(val width: Float, val height: Float) + +internal fun fitImagePreview(aspectRatio: Float, maxWidth: Float, maxHeight: Float): ImagePreviewSize = + if (aspectRatio >= maxWidth / maxHeight) { + ImagePreviewSize(width = maxWidth, height = maxWidth / aspectRatio) + } else { + ImagePreviewSize(width = maxHeight * aspectRatio, height = maxHeight) + } + +@Composable +internal fun MessageImageAttachment( + model: Any, + name: String, + language: String, + tag: String, + onClick: (() -> Unit)?, + modifier: Modifier = Modifier, +) { + val colors = LocalEdgeChatColors.current + var aspectRatio by remember(model) { mutableStateOf(null) } + val clickModifier = if (onClick == null) { + Modifier + } else { + Modifier.clickable( + role = Role.Button, + onClickLabel = if (language == "zh-CN") "打开图片" else "Open image", + onClick = onClick, + ) + } + BoxWithConstraints(modifier) { + val previewSize = aspectRatio?.let { + fitImagePreview( + aspectRatio = it, + maxWidth = minOf(maxWidth, 280.dp).value, + maxHeight = 240f, + ) + } + val sizeModifier = previewSize?.let { Modifier.size(it.width.dp, it.height.dp) } + ?: Modifier.size(width = 140.dp, height = 96.dp) + SubcomposeAsyncImage( + model = model, + contentDescription = name, + modifier = sizeModifier + .clip(RoundedCornerShape(8.dp)) + .then(clickModifier) + .testTag(tag), + contentScale = ContentScale.Fit, + onSuccess = { state -> + val size = state.painter.intrinsicSize + if (size.width > 0f && size.height > 0f) aspectRatio = size.width / size.height + }, + loading = { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) + } + }, + error = { + Column( + modifier = Modifier.fillMaxSize().padding(12.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Icon( + Icons.Outlined.Image, + contentDescription = null, + modifier = Modifier.size(28.dp), + tint = colors.iconSecondary, + ) + Text( + text = name, + modifier = Modifier.padding(top = 6.dp), + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + style = MaterialTheme.typography.bodySmall, + color = colors.textSecondary, + ) + } + }, + ) + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt index 11df2da3..ebab70f7 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt @@ -1,6 +1,5 @@ package com.aozorae.edgechat.ui -import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Row @@ -28,8 +27,6 @@ import com.aozorae.edgechat.core.database.ConversationEntity import com.aozorae.edgechat.core.network.dto.SessionDto import com.aozorae.edgechat.core.session.ServerProfile import com.aozorae.edgechat.feature.app.AppViewModel -import com.aozorae.edgechat.feature.auth.LoginScreen -import com.aozorae.edgechat.feature.auth.ServerSetupScreen import com.aozorae.edgechat.feature.auth.WelcomeScreen import com.aozorae.edgechat.feature.chat.ChatPane import com.aozorae.edgechat.feature.chat.ChatUiState @@ -52,48 +49,27 @@ fun EdgeChatApp( val preset by deepLinkServer.collectAsStateWithLifecycle() var showSettings by remember { mutableStateOf(false) } var showGroup by remember { mutableStateOf(false) } - var showServerSetup by rememberSaveable { mutableStateOf(false) } + var handledPreset by rememberSaveable { mutableStateOf(null) } - LaunchedEffect(preset) { - if (!preset.isNullOrBlank() && preset != appState.server?.baseUrl) { - showServerSetup = true - appViewModel.connect(requireNotNull(preset)) + LaunchedEffect(preset, appState.initializing) { + if (!appState.initializing && !preset.isNullOrBlank() && preset != handledPreset) { + handledPreset = preset + if (appState.session != null && preset != appState.server?.baseUrl) { + appViewModel.connect(requireNotNull(preset)) + } } } - BackHandler(enabled = appState.server == null && showServerSetup) { - showServerSetup = false - } when { - appState.loading && appState.server == null -> { + appState.initializing -> { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } - appState.server == null -> { - if (showServerSetup) { - ServerSetupScreen( - loading = appState.loading, - preset = preset, - language = appState.language, - onConnect = appViewModel::connect, - onBack = { showServerSetup = false }, - ) - } else { - WelcomeScreen( - language = appState.language, - onContinue = { showServerSetup = true }, - ) - } - } appState.session == null -> { - LoginScreen( - server = requireNotNull(appState.server), + WelcomeScreen( + initialServer = preset ?: appState.server?.baseUrl, loading = appState.loading, language = appState.language, - onLogin = appViewModel::login, - onChangeServer = { - showServerSetup = true - appViewModel.disconnect() - }, + onLogin = appViewModel::connectAndLogin, ) } else -> { diff --git a/android/app/src/main/java/com/aozorae/edgechat/ui/components/EdgeChatBrandMark.kt b/android/app/src/main/java/com/aozorae/edgechat/ui/components/EdgeChatBrandMark.kt index d6c35a9b..5249c921 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/ui/components/EdgeChatBrandMark.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/ui/components/EdgeChatBrandMark.kt @@ -5,6 +5,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @@ -26,6 +27,7 @@ fun EdgeChatBrandMark( val colors = LocalEdgeChatColors.current Box( modifier = modifier + .size(size) .background(colors.subtleSecondary, RoundedCornerShape(size * 0.28f)) .padding(size * 0.18f), ) { diff --git a/android/app/src/test/java/com/aozorae/edgechat/feature/chat/ChatMessagesTest.kt b/android/app/src/test/java/com/aozorae/edgechat/feature/chat/ChatMessagesTest.kt index 5ebf1e06..85c0621f 100644 --- a/android/app/src/test/java/com/aozorae/edgechat/feature/chat/ChatMessagesTest.kt +++ b/android/app/src/test/java/com/aozorae/edgechat/feature/chat/ChatMessagesTest.kt @@ -1,11 +1,31 @@ package com.aozorae.edgechat.feature.chat import com.aozorae.edgechat.core.database.MessageEntity +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class ChatMessagesTest { + @Test + fun onlyImageMimeTypesUseInlinePreview() { + assertTrue(isImageAttachment("image/jpeg")) + assertFalse(isImageAttachment("video/mp4")) + assertFalse(isImageAttachment("application/pdf")) + assertFalse(isImageAttachment(null)) + } + + @Test + fun imagePreviewKeepsPortraitAndLandscapeAspectRatiosWithinBounds() { + val portrait = fitImagePreview(aspectRatio = 9f / 19.5f, maxWidth = 280f, maxHeight = 240f) + assertEquals(240f, portrait.height, 0.01f) + assertEquals(110.77f, portrait.width, 0.01f) + + val landscape = fitImagePreview(aspectRatio = 19.5f / 9f, maxWidth = 280f, maxHeight = 240f) + assertEquals(280f, landscape.width, 0.01f) + assertEquals(129.23f, landscape.height, 0.01f) + } + @Test fun authorGroupRestartsForAnotherSender() { assertTrue(startsMessageGroup(message(2, "2026-08-30T10:01:00Z", "2"), message(1, "2026-08-30T10:00:00Z", "1"))) diff --git a/docs/api/websocket-v1.md b/docs/api/websocket-v1.md index fd62d325..10f41fbb 100644 --- a/docs/api/websocket-v1.md +++ b/docs/api/websocket-v1.md @@ -17,6 +17,8 @@ Every server frame is JSON and contains `protocolVersion: 1` plus `type`. - `ready`: the connection is authorized; room sockets include `room`. - `message`: includes the canonical `message`. Room clients merge by `message.id` and `message.clientMessageId`. - `message_deleted`: includes `messageId`. +- `message_pinned`: includes the canonical pinned `message` for the room. +- `message_unpinned`: includes `messageId`; clients clear the pin only when it still matches that ID. - `room_message`: inbox signal with `room`, `messageId`, `createdAt` and `unreadCount`; the client then runs room sync. - `error`: includes a client-safe `error` message and never contains a stack trace. diff --git a/frontend/src/components/chat/MessageContextMenu.vue b/frontend/src/components/chat/MessageContextMenu.vue index 6eccfc14..863a7471 100644 --- a/frontend/src/components/chat/MessageContextMenu.vue +++ b/frontend/src/components/chat/MessageContextMenu.vue @@ -1,20 +1,21 @@ + + + + diff --git a/frontend/src/components/demo/DemoNavigator.vue b/frontend/src/components/demo/DemoNavigator.vue index b7a8e1da..682af315 100644 --- a/frontend/src/components/demo/DemoNavigator.vue +++ b/frontend/src/components/demo/DemoNavigator.vue @@ -129,3 +129,13 @@ function resetDemo() { } } + + diff --git a/frontend/src/composables/useChatRoom.js b/frontend/src/composables/useChatRoom.js index 62f81d57..9b77df9d 100644 --- a/frontend/src/composables/useChatRoom.js +++ b/frontend/src/composables/useChatRoom.js @@ -21,6 +21,8 @@ export function useChatRoom({ openRoomConnection = connectRoomSocket, }) { const messages = ref([]); + const pinnedMessage = ref(null); + const highlightedMessageId = ref(null); const loading = ref(false); const wsStatus = ref("closed"); const composerText = ref(""); @@ -28,17 +30,18 @@ export function useChatRoom({ const sending = ref(false); const messagesEl = ref(null); let messageLoadGeneration = 0; + let highlightTimer = null; function roomKey(room = activeRoom.value) { return room?.kind && room?.id ? `${room.kind}:${room.id}` : ""; } - function isOwnMessage(message) { - return ( - message.sender.kind !== "external" && - Number(message.sender.id) === Number(session.value?.userId) - ); - } + function isOwnMessage(message) { + return ( + message.sender.kind !== "external" && + Number(message.sender.id) === Number(session.value?.userId) + ); + } function scrollToBottom() { const element = messagesEl.value; @@ -49,6 +52,44 @@ export function useChatRoom({ } } + function mergeMessages(...collections) { + const byId = new Map(); + for (const collection of collections) { + for (const message of collection || []) { + byId.set(Number(message.id), message); + } + } + return [...byId.values()].sort((left, right) => Number(left.id) - Number(right.id)); + } + + function highlightMessage(messageId) { + const numericMessageId = Number(messageId); + const element = messagesEl.value?.querySelector( + `[data-message-id="${numericMessageId}"]`, + ); + if (!element) { + return false; + } + element.scrollIntoView({ behavior: "smooth", block: "center" }); + highlightedMessageId.value = numericMessageId; + if (highlightTimer !== null) { + globalThis.clearTimeout(highlightTimer); + } + highlightTimer = globalThis.setTimeout(() => { + highlightedMessageId.value = null; + highlightTimer = null; + }, 1400); + return true; + } + + function clearMessageHighlight() { + highlightedMessageId.value = null; + if (highlightTimer !== null) { + globalThis.clearTimeout(highlightTimer); + highlightTimer = null; + } + } + function applyActiveRoomActivity(message) { if (!activeRoom.value || !message) { return; @@ -57,7 +98,7 @@ export function useChatRoom({ onRoomActivity({ room: activeRoom.value, message }); if (!isOwnMessage(message)) { - void roomApi + void roomApi .markRoomRead(activeRoom.value.kind, activeRoom.value.id, message.id) .catch(() => {}); } @@ -71,6 +112,8 @@ export function useChatRoom({ disconnectSocket(); messages.value = []; + pinnedMessage.value = null; + clearMessageHighlight(); onRoomAccessRevoked(room); } @@ -78,7 +121,7 @@ export function useChatRoom({ const code = Number(event?.code || 0); const reason = String(event?.reason || ""); if (code === WS_CLOSE_UNAUTHORIZED || reason === WS_REASON_UNAUTHORIZED) { - dispatchAuthInvalid(t('chat.sessionInvalid')); + dispatchAuthInvalid(t('chat.sessionInvalid')); return; } if (code === WS_CLOSE_FORBIDDEN || reason === WS_REASON_FORBIDDEN) { @@ -115,9 +158,21 @@ export function useChatRoom({ messages.value = messages.value.filter( (message) => Number(message.id) !== messageId, ); + if (Number(pinnedMessage.value?.id) === messageId) { + pinnedMessage.value = null; + } + } + if (payload.type === "message_pinned" && payload.message) { + pinnedMessage.value = payload.message; + } + if ( + payload.type === "message_unpinned" && + Number(pinnedMessage.value?.id) === Number(payload.messageId) + ) { + pinnedMessage.value = null; } if (payload.type === "error") { - error.value = localizeErrorMessage(payload.error); + error.value = localizeErrorMessage(payload.error); } }, }); @@ -138,8 +193,9 @@ export function useChatRoom({ return false; } messages.value = append - ? [...payload.messages, ...messages.value] + ? mergeMessages(payload.messages, messages.value) : payload.messages; + pinnedMessage.value = payload.pinnedMessage || null; await nextTick(); if (!append) { scrollToBottom(); @@ -160,6 +216,8 @@ export function useChatRoom({ async function activateRoom() { messageLoadGeneration += 1; messages.value = []; + pinnedMessage.value = null; + clearMessageHighlight(); loading.value = false; connectSocket(); return loadMessages(); @@ -168,6 +226,8 @@ export function useChatRoom({ function deactivateRoom() { messageLoadGeneration += 1; messages.value = []; + pinnedMessage.value = null; + clearMessageHighlight(); loading.value = false; disconnectSocket(); } @@ -192,7 +252,7 @@ export function useChatRoom({ ? `${activeRoom.value.kind}:${activeRoom.value.id}` : ""; if (!roomSession.isOpenFor(key)) { - error.value = t('chat.realtimeNotReady'); + error.value = t('chat.realtimeNotReady'); return; } if (!composerText.value.trim() && !pendingAttachment.value) { @@ -224,7 +284,7 @@ export function useChatRoom({ ? `${activeRoom.value.kind}:${activeRoom.value.id}` : ""; if (!roomSession.isOpenFor(key)) { - error.value = t('chat.realtimeNotReady'); + error.value = t('chat.realtimeNotReady'); return false; } @@ -235,6 +295,62 @@ export function useChatRoom({ ); } + function pinMessage(messageId) { + const key = roomKey(); + if (!roomSession.isOpenFor(key)) { + error.value = t('chat.realtimeNotReady'); + return false; + } + error.value = ""; + return roomSession.send( + JSON.stringify({ type: "pin_message", messageId: Number(messageId) }), + key, + ); + } + + function unpinMessage(messageId) { + const key = roomKey(); + if (!roomSession.isOpenFor(key)) { + error.value = t('chat.realtimeNotReady'); + return false; + } + error.value = ""; + return roomSession.send( + JSON.stringify({ type: "unpin_message", messageId: Number(messageId) }), + key, + ); + } + + async function revealPinnedMessage() { + const targetId = Number(pinnedMessage.value?.id); + const key = roomKey(); + if (!targetId || !key) { + return false; + } + await nextTick(); + if (highlightMessage(targetId)) { + return true; + } + + try { + const room = activeRoom.value; + const payload = await roomApi.getMessages(room.kind, room.id, targetId + 1); + if (roomKey() !== key || Number(pinnedMessage.value?.id) !== targetId) { + return false; + } + pinnedMessage.value = payload.pinnedMessage || null; + if (Number(pinnedMessage.value?.id) !== targetId) { + return false; + } + messages.value = mergeMessages(payload.messages, messages.value); + await nextTick(); + return highlightMessage(targetId); + } catch (currentError) { + error.value = currentError.message; + return false; + } + } + async function uploadAttachment(event) { const file = event.target.files?.[0]; if (!file) { @@ -280,6 +396,8 @@ export function useChatRoom({ return { messages, + pinnedMessage, + highlightedMessageId, loading, wsStatus, composerText, @@ -294,6 +412,9 @@ export function useChatRoom({ disconnectSocket, sendMessage, deleteMessage, + pinMessage, + unpinMessage, + revealPinnedMessage, uploadAttachment, clearAttachment, loadOlder, diff --git a/frontend/src/demo/api.js b/frontend/src/demo/api.js index cd589df1..99405411 100644 --- a/frontend/src/demo/api.js +++ b/frontend/src/demo/api.js @@ -323,7 +323,9 @@ export async function requestDemo(path, options = {}) { const index = demoState.channels.findIndex((channel) => Number(channel.id) === channelId); if (index >= 0) { const [channel] = demoState.channels.splice(index, 1); - delete demoState.messages[roomKey(channel.kind, channel.id)]; + const key = roomKey(channel.kind, channel.id); + delete demoState.messages[key]; + delete demoState.pinnedMessages[key]; } return { ok: true }; } @@ -332,9 +334,13 @@ export async function requestDemo(path, options = {}) { const kind = url.searchParams.get('kind'); const roomId = url.searchParams.get('roomId'); const before = Number(url.searchParams.get('before') || 0); - const allMessages = demoState.messages[roomKey(kind, roomId)] || []; + const key = roomKey(kind, roomId); + const allMessages = demoState.messages[key] || []; const filtered = before ? allMessages.filter((message) => Number(message.id) < before) : allMessages; - return { messages: cloneDemo(filtered.slice(-30)) }; + return { + messages: cloneDemo(filtered.slice(-30)), + pinnedMessage: cloneDemo(demoState.pinnedMessages[key] || null) + }; } if (method === 'POST' && pathname === '/messages/read') { const room = body.kind === 'dm' diff --git a/frontend/src/demo/fixtures.js b/frontend/src/demo/fixtures.js index 113c9b7d..54634846 100644 --- a/frontend/src/demo/fixtures.js +++ b/frontend/src/demo/fixtures.js @@ -279,6 +279,9 @@ export function createDemoFixtures() { channels, dms, messages, + pinnedMessages: { + 'public:1': messages['public:1'][1] + }, files: new Map(), invites: [ { diff --git a/frontend/src/demo/realtime.js b/frontend/src/demo/realtime.js index 01d3f7df..8081e6da 100644 --- a/frontend/src/demo/realtime.js +++ b/frontend/src/demo/realtime.js @@ -98,6 +98,34 @@ function handleRoomFrame(socket, frame) { type: 'message_deleted', messageId: Number(payload.messageId) }); + if (Number(demoState.pinnedMessages[key]?.id) === Number(payload.messageId)) { + delete demoState.pinnedMessages[key]; + } + return; + } + + if (payload.type === 'pin_message' && socket.kind !== 'dm') { + const key = roomKey(socket.kind, socket.roomId); + const message = (demoState.messages[key] || []).find( + (item) => Number(item.id) === Number(payload.messageId) + ); + if (!message) return; + demoState.pinnedMessages[key] = message; + publishRoom(socket.kind, socket.roomId, { + type: 'message_pinned', + message: cloneDemo(message) + }); + return; + } + + if (payload.type === 'unpin_message' && socket.kind !== 'dm') { + const key = roomKey(socket.kind, socket.roomId); + if (Number(demoState.pinnedMessages[key]?.id) !== Number(payload.messageId)) return; + delete demoState.pinnedMessages[key]; + publishRoom(socket.kind, socket.roomId, { + type: 'message_unpinned', + messageId: Number(payload.messageId) + }); } } diff --git a/frontend/src/locales/en-US.js b/frontend/src/locales/en-US.js index 7af761f8..e739bb98 100644 --- a/frontend/src/locales/en-US.js +++ b/frontend/src/locales/en-US.js @@ -171,6 +171,10 @@ export default { 'messages.loading': 'Loading messages...', 'messages.you': 'You', 'messages.actions': 'Message actions', + 'messages.pin': 'Pin message', + 'messages.unpin': 'Unpin message', + 'messages.pinned': 'Pinned message', + 'messages.revealPinned': 'Jump to pinned message', 'messages.delete': 'Delete message', 'composer.attach': 'Attach', 'composer.placeholder': 'Type a message, press Enter to send, or Shift+Enter for a new line', diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js index b9ee7077..1c338dc3 100644 --- a/frontend/src/locales/zh-CN.js +++ b/frontend/src/locales/zh-CN.js @@ -171,6 +171,10 @@ export default { 'messages.loading': '正在加载消息...', 'messages.you': '我', 'messages.actions': '消息操作', + 'messages.pin': '置顶消息', + 'messages.unpin': '取消置顶', + 'messages.pinned': '置顶消息', + 'messages.revealPinned': '定位到置顶消息', 'messages.delete': '删除消息', 'composer.attach': '附', 'composer.placeholder': '输入消息,Enter 发送,Shift+Enter 换行', diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue index fcf6c0c8..2c215e43 100644 --- a/frontend/src/pages/ChatPage.vue +++ b/frontend/src/pages/ChatPage.vue @@ -11,6 +11,7 @@ import MemberPanel from '../components/chat/MemberPanel.vue'; import MessageAttachment from '../components/chat/MessageAttachment.vue'; import MessageComposer from '../components/chat/MessageComposer.vue'; import MessageContextMenu from '../components/chat/MessageContextMenu.vue'; +import PinnedMessageBar from '../components/chat/PinnedMessageBar.vue'; import MobileNavigationDrawer from '../components/chat/MobileNavigationDrawer.vue'; import SenderSourceBadge from '../components/chat/SenderSourceBadge.vue'; import PublicGroupDiscovery from '../components/chat/PublicGroupDiscovery.vue'; @@ -105,9 +106,10 @@ function handleRoomAccessRevoked(room) { } const { - messages, loading, wsStatus, composerText, pendingAttachment, sending, + messages, pinnedMessage, highlightedMessageId, loading, wsStatus, composerText, pendingAttachment, sending, messagesEl, isOwnMessage, loadMessages, activateRoom, deactivateRoom, disconnectSocket, sendMessage, deleteMessage, + pinMessage, unpinMessage, revealPinnedMessage, uploadAttachment, clearAttachment, loadOlder } = useChatRoom({ activeRoom, @@ -129,6 +131,9 @@ const activeRoomSubtitle = computed(() => roomSubtitle(activeRoom.value, wsConne const canModerateMessages = computed( () => Boolean(session.value?.isAdmin || canManageActiveRoom.value) ); +const canPinMessages = computed( + () => Boolean(activeRoom.value?.kind !== 'dm' && (session.value?.isAdmin || canManageActiveRoom.value)) +); const { messageMenu, closeMessageMenu, @@ -137,6 +142,9 @@ const { startMessageLongPress, trackMessageLongPress } = useMessageContextMenu({ canModerateMessages }); +const selectedMessageIsPinned = computed( + () => Number(messageMenu.value.message?.id) === Number(pinnedMessage.value?.id) +); const roomManagement = useRoomManagement({ activeRoom, channels, users, error, refreshSidebar, refreshAndOpen, canManageActiveRoom, @@ -144,6 +152,7 @@ const roomManagement = useRoomManagement({ onRoomDeleted: () => { disconnectSocket(); messages.value = []; + pinnedMessage.value = null; } }); const { creation, members: memberManagement, settings: groupSettings, deleteGroup } = roomManagement; @@ -293,6 +302,18 @@ function confirmDeleteMessage() { deleteMessage(message.id); } +function pinSelectedMessage() { + const message = messageMenu.value.message; + closeMessageMenu(); + if (message) pinMessage(message.id); +} + +function unpinSelectedMessage() { + const message = messageMenu.value.message; + closeMessageMenu(); + if (message) unpinMessage(message.id); +} + onMounted(() => { startViewportSync(); window.addEventListener('focus', syncNotificationPermission); @@ -496,6 +517,14 @@ onBeforeUnmount(() => { + +
{{ t('chat.loadingMessages') }}
@@ -503,6 +532,7 @@ onBeforeUnmount(() => {
{ :open="Boolean(messageMenu.message)" :x="messageMenu.x" :y="messageMenu.y" + :can-pin="canPinMessages" + :pinned="selectedMessageIsPinned" @close="closeMessageMenu" + @pin="pinSelectedMessage" + @unpin="unpinSelectedMessage" @delete="confirmDeleteMessage" /> @@ -1037,6 +1074,12 @@ onBeforeUnmount(() => { justify-content: flex-end; } +.message-bubble--highlighted { + outline: 3px solid rgba(0, 128, 105, 0.3); + outline-offset: 3px; + transition: outline-color 180ms ease; +} + .message-avatar { width: 34px; height: 34px; @@ -1345,7 +1388,8 @@ onBeforeUnmount(() => { @media (prefers-reduced-motion: reduce) { .header-action, - .chat-header__button { + .chat-header__button, + .message-bubble--highlighted { transition: none; } } diff --git a/test/android-workflows.test.js b/test/android-workflows.test.js index 28135f6f..f7bbf642 100644 --- a/test/android-workflows.test.js +++ b/test/android-workflows.test.js @@ -28,6 +28,8 @@ test("Android release requires secret signing and publishes APK, AAB and SHA-256 assert.match(release, /assembleDebugAndroidTest/); assert.match(release, /assembleRelease bundleRelease/); assert.match(release, /sha256sum \*\.apk \*\.aab > SHA256SUMS\.txt/); + assert.match(release, /jarsigner -verify -verbose -certs/); + assert.doesNotMatch(release, /jarsigner -verify -strict/); assert.match(release, /gh release create/); }); diff --git a/test/api-v1-contract.test.js b/test/api-v1-contract.test.js index 8c7b687f..5cd54eb8 100644 --- a/test/api-v1-contract.test.js +++ b/test/api-v1-contract.test.js @@ -51,7 +51,15 @@ test("OpenAPI v1 keeps stable auth, idempotency, sync and error fields", () => { test("WebSocket v1 documents all supported frames and recovery rules", () => { assert.match(websocket, /protocolVersion: 1/); - for (const type of ["ready", "message", "message_deleted", "room_message", "error"]) { + for (const type of [ + "ready", + "message", + "message_deleted", + "message_pinned", + "message_unpinned", + "room_message", + "error", + ]) { assert.match(websocket, new RegExp(`\\b${type}\\b`)); } assert.match(websocket, /1 second, 2 seconds and then 5 seconds/); diff --git a/test/chat-room-transition.test.js b/test/chat-room-transition.test.js index 95f8b32f..0a0c3dfb 100644 --- a/test/chat-room-transition.test.js +++ b/test/chat-room-transition.test.js @@ -16,11 +16,14 @@ function createSocket(params, handlers) { return { params, handlers, + sentFrames: [], readyState: 1, close() { this.readyState = 3; }, - send() {}, + send(frame) { + this.sentFrames.push(JSON.parse(frame)); + }, emitMessage(message) { handlers.onMessage(JSON.stringify(message), this); }, @@ -67,3 +70,51 @@ test("快速切换房间时丢弃旧历史响应和旧连接消息", async () => assert.equal(await secondActivation, true); assert.deepEqual(room.messages.value, [{ id: 2, content: "current history" }]); }); + +test("房间置顶状态从历史与实时事件同步,并发送管理动作", async () => { + const activeRoom = ref({ id: 2, kind: "private" }); + const sockets = []; + const room = useChatRoom({ + activeRoom, + session: ref({ userId: 7 }), + error: ref(""), + roomApi: { + async getMessages() { + return { + messages: [{ id: 10, sender: { id: 7, kind: "local" } }], + pinnedMessage: { id: 10, sender: { id: 7, kind: "local" } }, + }; + }, + async markRoomRead() {}, + }, + openRoomConnection(params) { + const handlers = { onStatus: params.onStatus, onMessage: params.onMessage }; + const socket = createSocket(params, handlers); + sockets.push(socket); + handlers.onStatus({ status: "open", socket }); + return socket; + }, + }); + + assert.equal(await room.activateRoom(), true); + assert.equal(room.pinnedMessage.value.id, 10); + assert.equal(room.pinMessage(10), true); + assert.deepEqual(sockets[0].sentFrames.at(-1), { type: "pin_message", messageId: 10 }); + + sockets[0].emitMessage({ + type: "message_pinned", + message: { id: 11, sender: { id: 7, kind: "local" } }, + }); + assert.equal(room.pinnedMessage.value.id, 11); + assert.equal(room.unpinMessage(11), true); + assert.deepEqual(sockets[0].sentFrames.at(-1), { type: "unpin_message", messageId: 11 }); + + sockets[0].emitMessage({ type: "message_unpinned", messageId: 11 }); + assert.equal(room.pinnedMessage.value, null); + sockets[0].emitMessage({ + type: "message_pinned", + message: { id: 10, sender: { id: 7, kind: "local" } }, + }); + sockets[0].emitMessage({ type: "message_deleted", messageId: 10 }); + assert.equal(room.pinnedMessage.value, null); +}); diff --git a/test/demo-runtime.test.js b/test/demo-runtime.test.js index 10429d14..2102b4ce 100644 --- a/test/demo-runtime.test.js +++ b/test/demo-runtime.test.js @@ -153,6 +153,36 @@ test('demo room socket echoes sent messages through the real-time contract', asy inboxSocket.close(); }); +test('demo room socket persists pin, unpin and pinned-message deletion', async () => { + const frames = []; + let socket; + await new Promise((resolve) => { + socket = connectDemoRoomSocket({ + kind: 'public', + roomId: 1, + onMessage(frame) { + frames.push(JSON.parse(frame)); + }, + onStatus(event) { + if (event.status === 'open') resolve(); + } + }); + }); + + socket.send(JSON.stringify({ type: 'pin_message', messageId: 104 })); + assert.equal(frames.at(-1).type, 'message_pinned'); + assert.equal((await requestDemo('/messages?kind=public&roomId=1')).pinnedMessage.id, 104); + + socket.send(JSON.stringify({ type: 'unpin_message', messageId: 104 })); + assert.equal(frames.at(-1).type, 'message_unpinned'); + assert.equal((await requestDemo('/messages?kind=public&roomId=1')).pinnedMessage, null); + + socket.send(JSON.stringify({ type: 'pin_message', messageId: 103 })); + socket.send(JSON.stringify({ type: 'delete_message', messageId: 103 })); + assert.equal((await requestDemo('/messages?kind=public&roomId=1')).pinnedMessage, null); + socket.close(); +}); + test('Telegram replies increment the inbox unread projection', async () => { const inboxFrames = []; await requestDemo('/messages/read', { diff --git a/test/message-bubble-layout.test.js b/test/message-bubble-layout.test.js index 8440f823..d72be101 100644 --- a/test/message-bubble-layout.test.js +++ b/test/message-bubble-layout.test.js @@ -23,7 +23,11 @@ function getStyleRule(selector) { test("短文本消息为右下角时间戳预留末行空间", () => { assert.match( chatPage, - /:class="\{ 'message-bubble--with-attachment': msg\.attachment \}"/, + /'message-bubble--with-attachment': msg\.attachment/, + ); + assert.match( + chatPage, + /'message-bubble--highlighted': Number\(highlightedMessageId\) === Number\(msg\.id\)/, ); const bubble = getStyleRule(".message-bubble"); diff --git a/test/message-pinning.test.js b/test/message-pinning.test.js new file mode 100644 index 00000000..d4f453ec --- /dev/null +++ b/test/message-pinning.test.js @@ -0,0 +1,126 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import initSqlJs from "sql.js"; + +import { getPinnedMessage, pinMessage } from "../worker/src/data/pins.js"; +import { softDeleteMessage } from "../worker/src/data/messages.js"; +import { + MessagePinningError, + pinRoomMessage, + unpinRoomMessage, +} from "../worker/src/message-pinning.js"; +import { createD1Adapter } from "./support/d1.js"; + +const SQL = await initSqlJs(); +const schema = readFileSync(new URL("../worker/schema.sql", import.meta.url), "utf8"); + +function createEnvironment() { + const database = new SQL.Database(); + database.exec(schema); + database.run( + `INSERT INTO users (id, username, display_name, password_hash, password_salt, is_admin) + VALUES + (1, 'admin', 'Admin', 'hash', 'salt', 1), + (2, 'owner', 'Owner', 'hash', 'salt', 0), + (3, 'member', 'Member', 'hash', 'salt', 0)`, + ); + database.run( + `INSERT INTO channels (id, name, kind, dm_key, created_by) + VALUES + (2, 'team', 'private', NULL, 2), + (3, 'dm-room', 'dm', '2:3', 2)`, + ); + database.run( + `INSERT INTO channel_members (channel_id, user_id, role) + VALUES (2, 2, 'owner'), (2, 3, 'member'), (3, 2, 'member'), (3, 3, 'member')`, + ); + database.run( + `INSERT INTO messages (id, channel_id, sender_id, content) + VALUES (10, 2, 2, 'first'), (11, 2, 3, 'second'), (12, 3, 2, 'dm')`, + ); + return { database, env: { DB: createD1Adapter(database) } }; +} + +function countPins(database) { + return Number(database.exec("SELECT COUNT(*) FROM channel_pins")[0].values[0][0]); +} + +test("置顶引用随消息软删除和硬删除清理,但不改变消息保留策略", async () => { + const { database, env } = createEnvironment(); + + assert.equal( + await pinMessage(env.DB, { channelId: 2, messageId: 10, pinnedBy: 2 }), + true, + ); + assert.equal((await getPinnedMessage(env, 2)).content, "first"); + assert.equal(await softDeleteMessage(env.DB, { channelId: 2, messageId: 10 }), true); + assert.equal(countPins(database), 0); + + assert.equal( + await pinMessage(env.DB, { channelId: 2, messageId: 11, pinnedBy: 2 }), + true, + ); + database.run("DELETE FROM messages WHERE id = 11"); + assert.equal(countPins(database), 0); + assert.equal(await getPinnedMessage(env, 2), null); +}); + +test("群主和站点管理员可置顶群消息,普通成员与私信均被拒绝", async () => { + const { env } = createEnvironment(); + const ownerMeta = { + room: { id: 2, kind: "private" }, + principal: { userId: 2, isAdmin: false }, + }; + const pinned = await pinRoomMessage(env, ownerMeta, { messageId: 10 }); + assert.deepEqual(JSON.parse(pinned.packet), { + protocolVersion: 1, + type: "message_pinned", + message: pinned.message, + }); + + const adminPinned = await pinRoomMessage( + env, + { room: { id: 2, kind: "private" }, principal: { userId: 1, isAdmin: true } }, + { messageId: 11 }, + ); + assert.equal(adminPinned.message.id, 11); + + await assert.rejects( + pinRoomMessage( + env, + { room: { id: 2, kind: "private" }, principal: { userId: 3, isAdmin: false } }, + { messageId: 10 }, + ), + (error) => error instanceof MessagePinningError && error.message === "无权管理置顶消息", + ); + await assert.rejects( + pinRoomMessage( + env, + { room: { id: 3, kind: "dm" }, principal: { userId: 1, isAdmin: true } }, + { messageId: 12 }, + ), + (error) => error instanceof MessagePinningError && error.message === "无权管理置顶消息", + ); +}); + +test("取消置顶只作用于客户端看到的当前置顶消息", async () => { + const { env } = createEnvironment(); + const meta = { + room: { id: 2, kind: "private" }, + principal: { userId: 2, isAdmin: false }, + }; + await pinRoomMessage(env, meta, { messageId: 10 }); + await pinRoomMessage(env, meta, { messageId: 11 }); + + await assert.rejects( + unpinRoomMessage(env, meta, { messageId: 10 }), + (error) => error instanceof MessagePinningError && error.message === "该消息已不再置顶", + ); + const unpinned = await unpinRoomMessage(env, meta, { messageId: 11 }); + assert.deepEqual(JSON.parse(unpinned.packet), { + protocolVersion: 1, + type: "message_unpinned", + messageId: 11, + }); +}); diff --git a/worker/migrations/2026-08-30-pinned-messages.sql b/worker/migrations/2026-08-30-pinned-messages.sql new file mode 100644 index 00000000..1bafc76c --- /dev/null +++ b/worker/migrations/2026-08-30-pinned-messages.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS channel_pins ( + channel_id INTEGER PRIMARY KEY, + message_id INTEGER NOT NULL UNIQUE, + pinned_by INTEGER, + pinned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE, + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + FOREIGN KEY (pinned_by) REFERENCES users(id) ON DELETE SET NULL +); + +-- 软删除后立即移除置顶引用;消息保留期仍由 GC 独立决定,不因置顶而延长。 +CREATE TRIGGER IF NOT EXISTS clear_pin_after_message_soft_delete +AFTER UPDATE OF deleted_at ON messages +WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL +BEGIN + DELETE FROM channel_pins WHERE message_id = NEW.id; +END; diff --git a/worker/schema.sql b/worker/schema.sql index 5a2a17aa..de622633 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -122,6 +122,16 @@ CREATE TABLE IF NOT EXISTS messages ( FOREIGN KEY (sender_id) REFERENCES users(id) ); +CREATE TABLE IF NOT EXISTS channel_pins ( + channel_id INTEGER PRIMARY KEY, + message_id INTEGER NOT NULL UNIQUE, + pinned_by INTEGER, + pinned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE, + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + FOREIGN KEY (pinned_by) REFERENCES users(id) ON DELETE SET NULL +); + CREATE TABLE IF NOT EXISTS message_reads ( channel_id INTEGER NOT NULL, user_id INTEGER NOT NULL, @@ -264,6 +274,14 @@ BEGIN VALUES (NEW.channel_id, NEW.id, 'deleted'); END; +-- 软删除后立即移除置顶引用;消息保留期仍由 GC 独立决定,不因置顶而延长。 +CREATE TRIGGER IF NOT EXISTS clear_pin_after_message_soft_delete +AFTER UPDATE OF deleted_at ON messages +WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL +BEGIN + DELETE FROM channel_pins WHERE message_id = NEW.id; +END; + CREATE TABLE IF NOT EXISTS pending_r2_delete ( object_key TEXT PRIMARY KEY, retry_count INTEGER NOT NULL DEFAULT 0, diff --git a/worker/src/api/messages.js b/worker/src/api/messages.js index b2706d04..060866da 100644 --- a/worker/src/api/messages.js +++ b/worker/src/api/messages.js @@ -1,4 +1,5 @@ import { listMessages } from '../data/messages.js'; +import { getPinnedMessage } from '../data/pins.js'; import { markRoomRead } from '../data/unread.js'; import { authorizeRoom, isRoomKind } from '../room-access.js'; import { errorResponse, parseJsonRequest, sanitizeLimit } from '../utils.js'; @@ -21,7 +22,10 @@ export function registerMessageRoutes(app) { return errorResponse('无权访问该会话', 403); } - const messages = await listMessages(c.env, roomId, before, limit); + const [messages, pinnedMessage] = await Promise.all([ + listMessages(c.env, roomId, before, limit), + getPinnedMessage(c.env, roomId) + ]); await markRoomRead(c.env.DB, { channelId: roomId, userId: session.userId @@ -34,7 +38,8 @@ export function registerMessageRoutes(app) { name: access.room.name, description: access.room.description }, - messages + messages, + pinnedMessage }); }); diff --git a/worker/src/data/pins.js b/worker/src/data/pins.js new file mode 100644 index 00000000..b26e56e3 --- /dev/null +++ b/worker/src/data/pins.js @@ -0,0 +1,45 @@ +import { getMessageById } from "./messages.js"; + +export async function getPinnedMessage(env, channelId) { + const { results } = await env.DB.prepare( + `SELECT message_id + FROM channel_pins + WHERE channel_id = ? + LIMIT 1`, + ) + .bind(Number(channelId)) + .all(); + return results[0] ? getMessageById(env, results[0].message_id) : null; +} + +export async function pinMessage(db, { channelId, messageId, pinnedBy }) { + // 用单条 INSERT SELECT 同时确认消息仍然存活,避免删除与置顶并发时留下失效引用。 + const result = await db + .prepare( + `INSERT INTO channel_pins (channel_id, message_id, pinned_by, pinned_at) + SELECT ?, m.id, ?, CURRENT_TIMESTAMP + FROM messages m + WHERE m.id = ? + AND m.channel_id = ? + AND m.deleted_at IS NULL + ON CONFLICT(channel_id) DO UPDATE SET + message_id = excluded.message_id, + pinned_by = excluded.pinned_by, + pinned_at = CURRENT_TIMESTAMP`, + ) + .bind(Number(channelId), Number(pinnedBy), Number(messageId), Number(channelId)) + .run(); + return Number(result.meta?.changes || 0) > 0; +} + +export async function unpinMessage(db, { channelId, messageId }) { + const result = await db + .prepare( + `DELETE FROM channel_pins + WHERE channel_id = ? + AND message_id = ?`, + ) + .bind(Number(channelId), Number(messageId)) + .run(); + return Number(result.meta?.changes || 0) > 0; +} diff --git a/worker/src/do/ChannelRoom.js b/worker/src/do/ChannelRoom.js index f2b9742b..02d31795 100644 --- a/worker/src/do/ChannelRoom.js +++ b/worker/src/do/ChannelRoom.js @@ -4,6 +4,11 @@ import { submitRoomMessageIdempotent } from '../message-submission.js'; import { deleteRoomMessage, MessageDeletionError } from '../message-deletion.js'; +import { + MessagePinningError, + pinRoomMessage, + unpinRoomMessage +} from '../message-pinning.js'; import { submitExternalMessage } from '../external-message-submission.js'; import { forwardEdgeChatMessageToTelegram } from '../integrations/telegram/bridge.js'; import { authorizeRoom } from '../room-access.js'; @@ -214,12 +219,26 @@ export class ChannelRoom { await this.broadcast(result.packet); return Response.json({ ok: true, messageId: result.messageId }); } + if (action?.type === 'pin_message') { + const result = await pinRoomMessage(this.env, meta, action); + await this.broadcast(result.packet); + return Response.json({ ok: true, message: result.message }); + } + if (action?.type === 'unpin_message') { + const result = await unpinRoomMessage(this.env, meta, action); + await this.broadcast(result.packet); + return Response.json({ ok: true, messageId: result.messageId }); + } return Response.json( { error: { code: 'invalid_request', message: '不支持的消息操作' } }, { status: 400 } ); } catch (error) { - if (error instanceof MessageSubmissionError || error instanceof MessageDeletionError) { + if ( + error instanceof MessageSubmissionError || + error instanceof MessageDeletionError || + error instanceof MessagePinningError + ) { return Response.json( { error: { code: error.code || 'invalid_request', message: error.message } }, { status: error.status || 400 } @@ -313,7 +332,7 @@ export class ChannelRoom { return; } - if (!['send', 'delete_message'].includes(payload.type)) { + if (!['send', 'delete_message', 'pin_message', 'unpin_message'].includes(payload.type)) { sendSocketError(ws, 'Unsupported message type'); return; } @@ -329,6 +348,16 @@ export class ChannelRoom { await this.broadcast(packet); return; } + if (payload.type === 'pin_message') { + const { packet } = await pinRoomMessage(this.env, currentMeta, payload); + await this.broadcast(packet); + return; + } + if (payload.type === 'unpin_message') { + const { packet } = await unpinRoomMessage(this.env, currentMeta, payload); + await this.broadcast(packet); + return; + } const { message: saved, packet } = await submitRoomMessage( this.env, @@ -339,7 +368,11 @@ export class ChannelRoom { // 未读与外部桥接都属于提交后投影,异步执行以缩短 WebSocket 发送链路。 this.runMessageProjections(currentMeta.room, saved); } catch (error) { - if (error instanceof MessageSubmissionError || error instanceof MessageDeletionError) { + if ( + error instanceof MessageSubmissionError || + error instanceof MessageDeletionError || + error instanceof MessagePinningError + ) { sendSocketError(ws, error.message); return; } diff --git a/worker/src/message-pinning.js b/worker/src/message-pinning.js new file mode 100644 index 00000000..7680ffd5 --- /dev/null +++ b/worker/src/message-pinning.js @@ -0,0 +1,77 @@ +import { getPinnedMessage, pinMessage, unpinMessage } from "./data/pins.js"; +import { authorizeChannelManagement } from "./room-access.js"; + +export class MessagePinningError extends Error { + constructor(message) { + super(message); + this.name = "MessagePinningError"; + } +} + +function normalizeMessageId(payload) { + const messageId = Number(payload.messageId); + if (!Number.isInteger(messageId) || messageId <= 0) { + throw new MessagePinningError("消息不存在"); + } + return messageId; +} + +async function requirePinPermission(authorize, env, meta) { + const access = await authorize(env.DB, meta.principal, meta.room.id); + if (!access.ok) { + throw new MessagePinningError("无权管理置顶消息"); + } + return access; +} + +export function createMessagePinning({ + authorize = authorizeChannelManagement, + persistPin = pinMessage, + loadPinnedMessage = getPinnedMessage, +} = {}) { + return async function pinRoomMessage(env, meta, payload) { + const messageId = normalizeMessageId(payload); + const access = await requirePinPermission(authorize, env, meta); + const pinned = await persistPin(env.DB, { + channelId: meta.room.id, + messageId, + pinnedBy: access.identity.userId, + }); + if (!pinned) { + throw new MessagePinningError("消息不存在或已被删除"); + } + + const message = await loadPinnedMessage(env, meta.room.id); + if (!message) { + throw new MessagePinningError("消息不存在或已被删除"); + } + return { + message, + packet: JSON.stringify({ protocolVersion: 1, type: "message_pinned", message }), + }; + }; +} + +export function createMessageUnpinning({ + authorize = authorizeChannelManagement, + persistUnpin = unpinMessage, +} = {}) { + return async function unpinRoomMessage(env, meta, payload) { + const messageId = normalizeMessageId(payload); + await requirePinPermission(authorize, env, meta); + const unpinned = await persistUnpin(env.DB, { + channelId: meta.room.id, + messageId, + }); + if (!unpinned) { + throw new MessagePinningError("该消息已不再置顶"); + } + return { + messageId, + packet: JSON.stringify({ protocolVersion: 1, type: "message_unpinned", messageId }), + }; + }; +} + +export const pinRoomMessage = createMessagePinning(); +export const unpinRoomMessage = createMessageUnpinning();