diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index 6fbe011f..9d14f189 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -124,9 +124,18 @@ export const D1_MIGRATIONS = [ file: "worker/migrations/2026-08-30-pinned-messages.sql", artifacts: ["table:channel_pins", "trigger:clear_pin_after_message_soft_delete"], }, + { + id: "2026-09-01-message-mentions", + file: "worker/migrations/2026-09-01-message-mentions.sql", + artifacts: ["column:messages.mention_user_ids"], + }, { - id: "2026-09-01-message-mentions", - file: "worker/migrations/2026-09-01-message-mentions.sql", - artifacts: ["column:messages.mention_user_ids"], + id: "2026-09-02-voice-messages", + file: "worker/migrations/2026-09-02-voice-messages.sql", + artifacts: [ + "column:messages.attachment_kind", + "column:messages.attachment_duration_ms", + "column:messages.attachment_waveform", + ], }, ]; diff --git a/README.en.md b/README.en.md index b65628a0..ed0fa19e 100644 --- a/README.en.md +++ b/README.en.md @@ -2,7 +2,7 @@ EdgeChat

A modern team chat system built on the Cloudflare ecosystem

-

Accounts · Public/Private Groups · Direct Messages · Real-time Messaging · File Uploads · Admin Dashboard

+

Accounts · Public/Private Groups · Direct Messages · Real-time Messaging · Voice Messages · File Uploads · Admin Dashboard

license @@ -24,7 +24,7 @@ 中文 · English · 日本語 · - Online Demo · + Online Demo · Project Documentation · Telegram Community

@@ -34,7 +34,7 @@
-EdgeChat is a team chat system deployed on Cloudflare: accounts, public groups, private groups, direct messages, real-time messaging, file uploads, and an admin dashboard — everything you need. The goal is straightforward: run a production-ready, in-site IM in the Cloudflare ecosystem with as little operational overhead as possible. +EdgeChat is a team chat system deployed on Cloudflare: accounts, public groups, private groups, direct messages, real-time messaging, voice messages, file uploads, and an admin dashboard — everything you need. The goal is straightforward: run a production-ready, in-site IM in the Cloudflare ecosystem with as little operational overhead as possible. ## Latest Update @@ -81,7 +81,7 @@ The login tool reuses the existing authentication flow and browser safety confir ## Online Demo -**[edgechat-demo.wcjxxgaq.workers.dev](https://edgechat-demo.wcjxxgaq.workers.dev)** +**[edgechat-demo.gdz66601.workers.dev](https://edgechat-demo.gdz66601.workers.dev)** The demo site reuses the production project's Vue pages, routing, state management, and real-time messaging logic, but all APIs, WebSocket, file uploads, and Telegram round trips are simulated in browser memory. Reload the page or click **“Reset demo data”** in the top-right corner to restore the initial state. It never contacts the production Worker, nor does it write to D1, KV, or R2. @@ -115,7 +115,8 @@ Admins can bind any group in EdgeChat to a Telegram group. Once bound, messages **💬 Messaging & Conversations** - Public groups, private groups, and direct message conversations - [Two-way Telegram group bridge](#featured-feature-telegram-two-way-message-bridge) — one Bot connects members on both sides -- Real-time messaging, paginated history, and file messages +- Real-time messaging, paginated history, Telegram-style voice messages, and file messages +- Web and Android recording, waveform seeking, playback speed controls, and two-way Telegram voice/audio sync - File uploads and avatar management - Scheduled hard deletion of expired messages diff --git a/README.ja.md b/README.ja.md index 9c7cdd28..458a79dd 100644 --- a/README.ja.md +++ b/README.ja.md @@ -2,7 +2,7 @@ EdgeChat

Cloudflare フルスタックで作られたモダンなチーム向けチャットシステム

-

アカウント体系 · 公開/プライベートグループ · ダイレクトメッセージ · リアルタイムメッセージ · ファイルアップロード · 管理ダッシュボード

+

アカウント体系 · 公開/プライベートグループ · ダイレクトメッセージ · リアルタイムメッセージ · ボイスメッセージ · ファイルアップロード · 管理ダッシュボード

license @@ -24,7 +24,7 @@ 中文 · English · 日本語 · - オンラインデモ · + オンラインデモ · プロジェクトドキュメント · Telegram コミュニティ

@@ -34,7 +34,7 @@
-EdgeChat は Cloudflare 上にデプロイするチーム向けチャットシステムです。アカウント体系、公開グループ、プライベートグループ、ダイレクトメッセージ、リアルタイムメッセージ、ファイルアップロード、管理ダッシュボードをひととおり揃えています。目標は明確です。Cloudflare エコシステムの中で、できるだけ低い運用コストで、そのまま本番投入できるサイト内 IM を動かすことです。 +EdgeChat は Cloudflare 上にデプロイするチーム向けチャットシステムです。アカウント体系、公開グループ、プライベートグループ、ダイレクトメッセージ、リアルタイムメッセージ、ボイスメッセージ、ファイルアップロード、管理ダッシュボードをひととおり揃えています。目標は明確です。Cloudflare エコシステムの中で、できるだけ低い運用コストで、そのまま本番投入できるサイト内 IM を動かすことです。 ## 最新アップデート @@ -81,7 +81,7 @@ EdgeChat は Cloudflare 上にデプロイするチーム向けチャットシ ## オンラインデモ -**[edgechat-demo.wcjxxgaq.workers.dev](https://edgechat-demo.wcjxxgaq.workers.dev)** +**[edgechat-demo.gdz66601.workers.dev](https://edgechat-demo.gdz66601.workers.dev)** デモサイトは本番プロジェクトの Vue ページ、ルーティング、状態管理、リアルタイムメッセージのロジックをそのまま再利用していますが、すべての API・WebSocket・ファイルアップロード・Telegram のやり取りはブラウザのメモリ内でシミュレーションされます。ページをリロードするか、右上の「**デモデータをリセット**」をクリックすると初期状態に戻ります。本番 Worker には一切アクセスせず、D1・KV・R2 への書き込みも発生しません。 @@ -115,7 +115,8 @@ EdgeChat は Cloudflare 上にデプロイするチーム向けチャットシ **💬 メッセージと会話** - 公開グループ、プライベートグループ、ダイレクトメッセージの会話に対応 - [Telegram グループ双方向メッセージブリッジ](#注目機能telegram-双方向メッセージブリッジ):1 つの Bot で両側のメンバーをつなぐ -- リアルタイムメッセージ、履歴のページング、ファイルメッセージ +- リアルタイムメッセージ、履歴のページング、Telegram 風ボイスメッセージ、ファイルメッセージ +- Web / Android の録音、波形シーク、倍速再生、Telegram voice/audio の双方向同期 - ファイルアップロードとアバター管理 - 期限切れメッセージの定期ハード削除に対応 diff --git a/README.md b/README.md index f0ae2a8c..593da634 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ EdgeChat

基于 Cloudflare 全家桶打造的现代团队聊天系统

-

账号体系 · 公开/私有群组 · 私信 · 实时消息 · 文件上传 · 管理后台

+

账号体系 · 公开/私有群组 · 私信 · 实时消息 · 语音消息 · 文件上传 · 管理后台

license @@ -24,7 +24,7 @@ 中文 · English · 日本語 · - 在线 Demo · + 在线 Demo · 项目文档 · Telegram 社区

@@ -34,7 +34,7 @@
-EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系、公开群组、私有群组、私信、实时消息、文件上传、管理员后台一应俱全。目标很直接——在 Cloudflare 生态里,用尽量低的运维成本,跑起一套能直接落地使用的站内 IM。 +EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系、公开群组、私有群组、私信、实时消息、语音消息、文件上传、管理员后台一应俱全。目标很直接——在 Cloudflare 生态里,用尽量低的运维成本,跑起一套能直接落地使用的站内 IM。 ## 最近更新 @@ -82,7 +82,7 @@ EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系 ## 在线 Demo -**[edgechat-demo.wcjxxgaq.workers.dev](https://edgechat-demo.wcjxxgaq.workers.dev)** +**[edgechat-demo.gdz66601.workers.dev](https://edgechat-demo.gdz66601.workers.dev)** 演示站复用正式项目的 Vue 页面、路由、状态管理和实时消息逻辑,但所有 API、WebSocket、文件上传与 Telegram 回流都在浏览器内存中模拟。刷新页面或点击右上角「重置演示数据」即可恢复初始状态,不会访问正式 Worker,也不会写入 D1、KV 或 R2。 @@ -116,7 +116,8 @@ EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系 **💬 消息与会话** - 支持公开群组、私有群组与私信会话 - [Telegram 群组双向消息桥接](#特色功能telegram-消息双向桥接),一个 Bot 打通两侧成员 -- 实时消息、历史消息分页、文件消息 +- 实时消息、历史消息分页、Telegram 风格语音消息与文件消息 +- 网页和 Android 均支持录音、波形进度、倍速播放;Telegram voice/audio 可双向同步 - 文件上传与头像管理 - 支持定时硬删除过期消息 diff --git a/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/3.json b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/3.json new file mode 100644 index 00000000..84bae658 --- /dev/null +++ b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/3.json @@ -0,0 +1,474 @@ +{ + "formatVersion": 1, + "database": { + "version": 3, + "identityHash": "31ba91022b40290cab0a35e0529dfe3b", + "entities": [ + { + "tableName": "users", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `username` TEXT NOT NULL, `displayName` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "conversations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `id` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, `isGeneral` INTEGER NOT NULL, `isMember` INTEGER NOT NULL, `canManage` INTEGER NOT NULL, `myRole` TEXT NOT NULL, `memberCount` INTEGER NOT NULL, `otherUserId` INTEGER, `lastMessageAt` TEXT, `unreadCount` INTEGER NOT NULL, `mentionUnreadCount` INTEGER NOT NULL, PRIMARY KEY(`kind`, `id`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subtitle", + "columnName": "subtitle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isGeneral", + "columnName": "isGeneral", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isMember", + "columnName": "isMember", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManage", + "columnName": "canManage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "myRole", + "columnName": "myRole", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "memberCount", + "columnName": "memberCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "otherUserId", + "columnName": "otherUserId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "unreadCount", + "columnName": "unreadCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionUnreadCount", + "columnName": "mentionUnreadCount", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `clientMessageId` TEXT, `content` TEXT NOT NULL, `createdAt` TEXT NOT NULL, `source` TEXT NOT NULL, `senderKind` TEXT NOT NULL, `senderId` TEXT NOT NULL, `senderUsername` TEXT NOT NULL, `senderDisplayName` TEXT NOT NULL, `senderAvatarUrl` TEXT NOT NULL, `attachmentKey` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `attachmentUrl` TEXT, `attachmentKind` TEXT, `attachmentDurationMs` INTEGER, `attachmentWaveform` TEXT NOT NULL, `mentionUserIds` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderKind", + "columnName": "senderKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderId", + "columnName": "senderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderUsername", + "columnName": "senderUsername", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderDisplayName", + "columnName": "senderDisplayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderAvatarUrl", + "columnName": "senderAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attachmentKey", + "columnName": "attachmentKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentUrl", + "columnName": "attachmentUrl", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentKind", + "columnName": "attachmentKind", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentDurationMs", + "columnName": "attachmentDurationMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentWaveform", + "columnName": "attachmentWaveform", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mentionUserIds", + "columnName": "mentionUserIds", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_roomKind_roomId_id", + "unique": false, + "columnNames": [ + "roomKind", + "roomId", + "id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_roomKind_roomId_id` ON `${TABLE_NAME}` (`roomKind`, `roomId`, `id`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "room_sync", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `cursor` INTEGER NOT NULL, PRIMARY KEY(`kind`, `roomId`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursor", + "columnName": "cursor", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "roomId" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "outbox", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`clientMessageId` TEXT NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `content` TEXT NOT NULL, `localAttachmentPath` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `attachmentKind` TEXT, `attachmentDurationMs` INTEGER, `attachmentWaveform` TEXT NOT NULL, `clientUploadId` TEXT, `uploadedKey` TEXT, `uploadedUrl` TEXT, `mentionUserIds` TEXT NOT NULL, `state` TEXT NOT NULL, `failure` TEXT, `attempts` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`clientMessageId`))", + "fields": [ + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "localAttachmentPath", + "columnName": "localAttachmentPath", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentKind", + "columnName": "attachmentKind", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentDurationMs", + "columnName": "attachmentDurationMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentWaveform", + "columnName": "attachmentWaveform", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "clientUploadId", + "columnName": "clientUploadId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedKey", + "columnName": "uploadedKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedUrl", + "columnName": "uploadedUrl", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mentionUserIds", + "columnName": "mentionUserIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "failure", + "columnName": "failure", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "clientMessageId" + ] + }, + "indices": [ + { + "name": "index_outbox_createdAt", + "unique": false, + "columnNames": [ + "createdAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_outbox_createdAt` ON `${TABLE_NAME}` (`createdAt`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '31ba91022b40290cab0a35e0529dfe3b')" + ] + } +} \ No newline at end of file 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 1d492987..ff065ab4 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 @@ -66,7 +66,7 @@ class ChatMessagesLayoutTest { } @Test - fun imageAttachmentsUseInlinePreviewAndRemainOpenable() { + fun imageAttachmentsUseInlinePreviewAndRemainOpenable() { var opened: Triple? = null compose.setContent { EdgeChatTheme { @@ -101,7 +101,45 @@ class ChatMessagesLayoutTest { onDeleteMessage = {}, onOpenAttachment = { url, name, type -> opened = Triple(url, name, type) }, ) - } + } + + @Test + fun voiceAttachmentsUseInlineWaveformPlayer() { + compose.setContent { + EdgeChatTheme { + Box(Modifier.width(360.dp).height(640.dp)) { + ChatMessages( + messages = listOf( + message( + id = 5, + senderId = "2", + content = "", + attachmentName = "voice.m4a", + attachmentType = "audio/mp4", + attachmentUrl = "/files/voice.m4a", + attachmentKind = "voice", + attachmentDurationMs = 8_200, + attachmentWaveform = "12,44,90", + ), + ), + outbox = emptyList(), + currentUser = currentUser(), + serverBaseUrl = "https://example.com", + language = "en-US", + scrollState = rememberLazyListState(), + onLoadOlder = {}, + onRetry = {}, + onCancel = {}, + onDeleteMessage = {}, + onOpenAttachment = { _, _, _ -> }, + ) + } + } + } + + compose.onNodeWithTag("message_voice:5").fetchSemanticsNode() + compose.onNodeWithTag("voice_play:message:5").fetchSemanticsNode() + } } } @@ -172,7 +210,10 @@ class ChatMessagesLayoutTest { content: String, attachmentName: String? = null, attachmentType: String? = null, - attachmentUrl: String? = null, + attachmentUrl: String? = null, + attachmentKind: String? = null, + attachmentDurationMs: Long? = null, + attachmentWaveform: String = "", ) = MessageEntity( id = id, roomKind = "public", @@ -190,7 +231,10 @@ class ChatMessagesLayoutTest { attachmentName = attachmentName, attachmentType = attachmentType, attachmentSize = null, - attachmentUrl = attachmentUrl, + attachmentUrl = attachmentUrl, + attachmentKind = attachmentKind, + attachmentDurationMs = attachmentDurationMs, + attachmentWaveform = attachmentWaveform, ) private fun pendingMessage( diff --git a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt index 596a2db5..c4de109a 100644 --- a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt +++ b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt @@ -1,9 +1,10 @@ package com.aozorae.edgechat.feature.chat import androidx.compose.ui.test.assertIsEnabled -import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onAllNodesWithTag import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput import androidx.compose.ui.semantics.SemanticsProperties @@ -35,7 +36,8 @@ class MessageComposerTest { } } - compose.onNodeWithTag("send_message").assertIsNotEnabled() + compose.onAllNodesWithTag("send_message").assertCountEquals(0) + compose.onNodeWithTag("record_voice").fetchSemanticsNode() compose.onNodeWithTag("message_input").performTextInput("Hello") compose.onNodeWithTag("send_message").assertIsEnabled().performClick() val editableText = compose diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 70dd06c4..c343812c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,7 +1,8 @@ - + + ): String = samples + .take(64) + .joinToString(",") { it.coerceIn(0, 100).toString() } + +fun decodeVoiceWaveform(value: String): List = value + .split(',') + .mapNotNull(String::toIntOrNull) + .map { it.coerceIn(0, 100) } diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceMedia.kt b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceMedia.kt new file mode 100644 index 00000000..3f5eb69f --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceMedia.kt @@ -0,0 +1,44 @@ +package com.aozorae.edgechat.core.media + +import kotlin.math.roundToInt + +data class VoiceRecordingState( + val active: Boolean = false, + val elapsedMs: Long = 0, + val waveform: List = emptyList(), +) + +data class VoicePlaybackState( + val playbackId: String? = null, + val playing: Boolean = false, + val positionMs: Long = 0, + val durationMs: Long = 0, + val speed: Float = 1f, + val failed: Boolean = false, +) + +fun normalizeVoiceWaveform(samples: List, targetCount: Int = 48): List { + val values = samples.map { it.coerceIn(0, 100) } + if (values.size <= targetCount) return values + return List(targetCount) { index -> + val start = index * values.size / targetCount + val end = ((index + 1) * values.size / targetCount).coerceAtLeast(start + 1) + values.subList(start, end).max() + } +} + +fun fallbackVoiceWaveform(seed: String, count: Int = 42): List { + var state = seed.fold(2_166_136_261L) { hash, character -> + (hash * 31 + character.code).and(0xffffffffL) + } + return List(count) { index -> + state = (state * 1_664_525 + 1_013_904_223).and(0xffffffffL) + val envelope = 0.68 + 0.32 * kotlin.math.sin(index.toDouble() / (count - 1).coerceAtLeast(1) * Math.PI) + ((24 + state % 68) * envelope).roundToInt().coerceIn(8, 100) + } +} + +fun formatVoiceDuration(durationMs: Long): String { + val totalSeconds = (durationMs.coerceAtLeast(0) / 1000).toInt() + return "%d:%02d".format(totalSeconds / 60, totalSeconds % 60) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/media/VoicePlaybackController.kt b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoicePlaybackController.kt new file mode 100644 index 00000000..c0b1420e --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoicePlaybackController.kt @@ -0,0 +1,106 @@ +package com.aozorae.edgechat.core.media + +import android.content.Context +import android.os.Handler +import android.os.Looper +import androidx.media3.common.MediaItem +import androidx.media3.common.PlaybackException +import androidx.media3.common.PlaybackParameters +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.okhttp.OkHttpDataSource +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import dagger.hilt.android.qualifiers.ApplicationContext +import javax.inject.Inject +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import okhttp3.OkHttpClient + +@androidx.annotation.OptIn(markerClass = [UnstableApi::class]) +class VoicePlaybackController @Inject constructor( + @ApplicationContext context: Context, + client: OkHttpClient, +) { + private val player = ExoPlayer.Builder(context) + .setMediaSourceFactory(DefaultMediaSourceFactory(OkHttpDataSource.Factory(client))) + .build() + private val handler = Handler(Looper.getMainLooper()) + private val mutableState = MutableStateFlow(VoicePlaybackState()) + val state: StateFlow = mutableState.asStateFlow() + private var fallbackDurationMs = 0L + private val progress = object : Runnable { + override fun run() { + publish() + if (player.isPlaying) handler.postDelayed(this, 200) + } + } + + init { + player.addListener(object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) { + publish() + handler.removeCallbacks(progress) + if (isPlaying) handler.post(progress) + } + + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState == Player.STATE_ENDED) player.seekTo(0) + publish() + } + + override fun onPlayerError(error: PlaybackException) { + mutableState.value = mutableState.value.copy(playing = false, failed = true) + } + }) + } + + fun toggle(playbackId: String, url: String, durationMs: Long) { + if (mutableState.value.playbackId == playbackId) { + if (player.isPlaying) player.pause() else player.play() + return + } + fallbackDurationMs = durationMs + mutableState.value = VoicePlaybackState(playbackId = playbackId, durationMs = durationMs) + player.setMediaItem(MediaItem.fromUri(url)) + player.prepare() + player.play() + } + + fun seek(playbackId: String, fraction: Float) { + if (mutableState.value.playbackId != playbackId) return + val duration = durationMs() + if (duration > 0) player.seekTo((duration * fraction.coerceIn(0f, 1f)).toLong()) + publish() + } + + fun cycleSpeed(playbackId: String) { + if (mutableState.value.playbackId != playbackId) return + val next = when (mutableState.value.speed) { + 1f -> 1.5f + 1.5f -> 2f + else -> 1f + } + player.playbackParameters = PlaybackParameters(next) + publish() + } + + fun close() { + handler.removeCallbacksAndMessages(null) + player.release() + mutableState.value = VoicePlaybackState() + } + + private fun durationMs(): Long = player.duration.takeIf { it > 0 } ?: fallbackDurationMs + + private fun publish() { + val current = mutableState.value + mutableState.value = current.copy( + playing = player.isPlaying, + positionMs = player.currentPosition.coerceAtLeast(0), + durationMs = durationMs(), + speed = player.playbackParameters.speed, + ) + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceRecorder.kt b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceRecorder.kt new file mode 100644 index 00000000..da9a6978 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/media/VoiceRecorder.kt @@ -0,0 +1,121 @@ +package com.aozorae.edgechat.core.media + +import android.content.Context +import android.media.MediaRecorder +import android.os.Build +import dagger.hilt.android.qualifiers.ApplicationContext +import java.io.File +import javax.inject.Inject +import kotlin.math.sqrt +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch + +class VoiceRecorder @Inject constructor(@ApplicationContext private val context: Context) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val mutableState = MutableStateFlow(VoiceRecordingState()) + val state: StateFlow = mutableState.asStateFlow() + private var recorder: MediaRecorder? = null + private var output: File? = null + private var startedAt = 0L + private var samples = mutableListOf() + private var samplingJob: Job? = null + + fun start() { + if (recorder != null) return + val directory = File(context.filesDir, "pending").apply { mkdirs() } + val file = File(directory, "voice-${System.currentTimeMillis()}.m4a") + val activeRecorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + MediaRecorder(context) + } else { + @Suppress("DEPRECATION") + MediaRecorder() + } + try { + activeRecorder.apply { + setAudioSource(MediaRecorder.AudioSource.MIC) + setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) + setAudioEncoder(MediaRecorder.AudioEncoder.AAC) + setAudioChannels(1) + setAudioSamplingRate(24_000) + setAudioEncodingBitRate(64_000) + setOutputFile(file.absolutePath) + prepare() + start() + } + } catch (error: Exception) { + activeRecorder.release() + file.delete() + throw error + } + recorder = activeRecorder + output = file + samples = mutableListOf() + startedAt = System.currentTimeMillis() + mutableState.value = VoiceRecordingState(active = true) + samplingJob = scope.launch { + while (isActive && recorder === activeRecorder) { + delay(100) + val amplitude = activeRecorder.maxAmplitude.coerceAtLeast(0) + val level = (sqrt(amplitude / 32767.0) * 100).toInt().coerceIn(6, 100) + samples += level + mutableState.value = VoiceRecordingState( + active = true, + elapsedMs = System.currentTimeMillis() - startedAt, + waveform = normalizeVoiceWaveform(samples.takeLast(80), 32), + ) + } + } + } + + fun finish(): com.aozorae.edgechat.core.repository.PendingAttachment? { + val file = output ?: return null + val durationMs = System.currentTimeMillis() - startedAt + val stopped = stopRecorder() + if (!stopped || durationMs < 500 || !file.exists()) { + file.delete() + return null + } + return com.aozorae.edgechat.core.repository.PendingAttachment( + path = file.absolutePath, + name = file.name, + type = "audio/mp4", + size = file.length(), + kind = "voice", + durationMs = durationMs, + waveform = normalizeVoiceWaveform(samples), + ) + } + + fun cancel() { + val file = output + stopRecorder() + file?.delete() + } + + fun close() { + if (recorder != null) cancel() + scope.cancel() + } + + private fun stopRecorder(): Boolean { + val activeRecorder = recorder ?: return false + samplingJob?.cancel() + samplingJob = null + val stopped = runCatching { activeRecorder.stop() }.isSuccess + activeRecorder.reset() + activeRecorder.release() + recorder = null + output = null + mutableState.value = VoiceRecordingState() + return stopped + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt index 06918505..9564df96 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt @@ -123,11 +123,14 @@ data class SenderDto( @Serializable data class AttachmentDto( - val key: String, - val name: String, - val type: String, - val size: Long = 0, - val url: String, + val key: String, + val name: String, + val type: String, + val size: Long = 0, + val url: String, + val kind: String? = null, + val durationMs: Long? = null, + val waveform: List = emptyList(), ) @Serializable diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt index 59504909..f876acbd 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt @@ -16,7 +16,15 @@ import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request -data class PendingAttachment(val path: String, val name: String, val type: String, val size: Long) +data class PendingAttachment( + val path: String, + val name: String, + val type: String, + val size: Long, + val kind: String? = null, + val durationMs: Long? = null, + val waveform: List = emptyList(), +) @Singleton class AttachmentRepository @Inject constructor( diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt index 02528dc3..d289ae4e 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt @@ -10,7 +10,9 @@ import androidx.work.WorkManager import com.aozorae.edgechat.core.database.EdgeChatDatabase import com.aozorae.edgechat.core.database.OutboxEntity import com.aozorae.edgechat.core.database.decodeMentionUserIds +import com.aozorae.edgechat.core.database.decodeVoiceWaveform import com.aozorae.edgechat.core.database.encodeMentionUserIds +import com.aozorae.edgechat.core.database.encodeVoiceWaveform import com.aozorae.edgechat.core.database.toEntity import com.aozorae.edgechat.core.network.EdgeChatApi import com.aozorae.edgechat.core.network.bodyOrThrow @@ -65,8 +67,11 @@ class OutboxRepository @Inject constructor( content = content.trim(), localAttachmentPath = attachment?.path, attachmentName = attachment?.name, - attachmentType = attachment?.type, - attachmentSize = attachment?.size, + attachmentType = attachment?.type, + attachmentSize = attachment?.size, + attachmentKind = attachment?.kind, + attachmentDurationMs = attachment?.durationMs, + attachmentWaveform = encodeVoiceWaveform(attachment?.waveform.orEmpty()), clientUploadId = attachment?.let { UUID.randomUUID().toString() }, uploadedKey = null, uploadedUrl = null, @@ -140,14 +145,17 @@ class OutboxRepository @Inject constructor( private suspend fun uploadIfNeeded(item: OutboxEntity): AttachmentDto? { val path = item.localAttachmentPath ?: return null - if (item.uploadedKey != null && item.uploadedUrl != null) { - return AttachmentDto( - item.uploadedKey, - item.attachmentName.orEmpty(), - item.attachmentType.orEmpty(), - item.attachmentSize ?: 0, - item.uploadedUrl, - ) + if (item.uploadedKey != null && item.uploadedUrl != null) { + return AttachmentDto( + key = item.uploadedKey, + name = item.attachmentName.orEmpty(), + type = item.attachmentType.orEmpty(), + size = item.attachmentSize ?: 0, + url = item.uploadedUrl, + kind = item.attachmentKind, + durationMs = item.attachmentDurationMs, + waveform = decodeVoiceWaveform(item.attachmentWaveform), + ) } database.outbox().updateState(item.clientMessageId, "UPLOADING") val file = File(path) @@ -162,8 +170,12 @@ class OutboxRepository @Inject constructor( .bodyOrThrow(json) .file database.outbox().setUploaded(item.clientMessageId, uploaded.key, uploaded.url) - return uploaded - } + return uploaded.copy( + kind = item.attachmentKind, + durationMs = item.attachmentDurationMs, + waveform = decodeVoiceWaveform(item.attachmentWaveform), + ) + } private fun schedule() { val request = OneTimeWorkRequestBuilder() diff --git a/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt index 1b4674a1..b7ca2a38 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt @@ -8,6 +8,7 @@ import androidx.datastore.preferences.preferencesDataStoreFile import androidx.room.Room import com.aozorae.edgechat.core.database.EdgeChatDatabase import com.aozorae.edgechat.core.database.MIGRATION_1_2 +import com.aozorae.edgechat.core.database.MIGRATION_2_3 import com.aozorae.edgechat.core.network.AuthInterceptor import com.aozorae.edgechat.core.network.EdgeChatApi import com.aozorae.edgechat.core.network.ServerUrlInterceptor @@ -45,7 +46,7 @@ object AppModule { @Singleton fun database(@ApplicationContext context: Context): EdgeChatDatabase = Room.databaseBuilder(context, EdgeChatDatabase::class.java, "edgechat.db") - .addMigrations(MIGRATION_1_2) + .addMigrations(MIGRATION_1_2, MIGRATION_2_3) .build() @Provides 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 01b3f26f..3f5c1196 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 @@ -5,6 +5,7 @@ import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut +import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -31,6 +32,7 @@ import androidx.compose.material.icons.outlined.Forum import androidx.compose.material.icons.outlined.Image import androidx.compose.material.icons.outlined.KeyboardArrowDown import androidx.compose.material.icons.outlined.Movie +import androidx.compose.material.icons.outlined.Mic import androidx.compose.material.icons.outlined.Refresh import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -57,6 +59,8 @@ import androidx.compose.ui.unit.dp import com.aozorae.edgechat.core.database.MessageEntity import com.aozorae.edgechat.core.database.OutboxEntity import com.aozorae.edgechat.core.database.decodeMentionUserIds +import com.aozorae.edgechat.core.database.decodeVoiceWaveform +import com.aozorae.edgechat.core.media.VoicePlaybackState import com.aozorae.edgechat.core.network.dto.MemberDto import com.aozorae.edgechat.core.network.dto.SessionDto import com.aozorae.edgechat.ui.components.EdgeAvatar @@ -88,7 +92,11 @@ fun ChatMessages( onRetry: (String) -> Unit, onCancel: (String) -> Unit, onDeleteMessage: (Long) -> Unit, - onOpenAttachment: (String, String, String) -> Unit, + onOpenAttachment: (String, String, String) -> Unit, + voicePlayback: VoicePlaybackState = VoicePlaybackState(), + onToggleVoicePlayback: (String, String, Long) -> Unit = { _, _, _ -> }, + onSeekVoicePlayback: (String, Float) -> Unit = { _, _ -> }, + onCycleVoicePlaybackSpeed: (String) -> Unit = {}, modifier: Modifier = Modifier, ) { val scope = rememberCoroutineScope() @@ -148,7 +156,11 @@ fun ChatMessages( serverBaseUrl = serverBaseUrl, language = language, onDelete = onDeleteMessage, - onOpenAttachment = onOpenAttachment, + onOpenAttachment = onOpenAttachment, + voicePlayback = voicePlayback, + onToggleVoicePlayback = onToggleVoicePlayback, + onSeekVoicePlayback = onSeekVoicePlayback, + onCycleVoicePlaybackSpeed = onCycleVoicePlaybackSpeed, ) } if (older == null || messageDate(older.createdAt) != messageDate(message.createdAt)) { @@ -233,7 +245,11 @@ private fun MessageItem( serverBaseUrl: String, language: String, onDelete: (Long) -> Unit, - onOpenAttachment: (String, String, String) -> Unit, + onOpenAttachment: (String, String, String) -> Unit, + voicePlayback: VoicePlaybackState, + onToggleVoicePlayback: (String, String, Long) -> Unit, + onSeekVoicePlayback: (String, Float) -> Unit, + onCycleVoicePlaybackSpeed: (String) -> Unit, ) { val colors = LocalEdgeChatColors.current Row( @@ -304,7 +320,11 @@ private fun MessageItem( members = members, serverBaseUrl = serverBaseUrl, language = language, - onOpenAttachment = onOpenAttachment, + onOpenAttachment = onOpenAttachment, + voicePlayback = voicePlayback, + onToggleVoicePlayback = onToggleVoicePlayback, + onSeekVoicePlayback = onSeekVoicePlayback, + onCycleVoicePlaybackSpeed = onCycleVoicePlaybackSpeed, modifier = Modifier.testTag("message_bubble:${message.id}"), ) } @@ -321,7 +341,11 @@ private fun MessageBubble( members: List, serverBaseUrl: String, language: String, - onOpenAttachment: (String, String, String) -> Unit, + onOpenAttachment: (String, String, String) -> Unit, + voicePlayback: VoicePlaybackState, + onToggleVoicePlayback: (String, String, Long) -> Unit, + onSeekVoicePlayback: (String, Float) -> Unit, + onCycleVoicePlaybackSpeed: (String) -> Unit, modifier: Modifier = Modifier, ) { val colors = LocalEdgeChatColors.current @@ -367,7 +391,23 @@ private fun MessageBubble( val openAttachment = { onOpenAttachment(attachmentUrl, attachmentName, attachmentType) } - if (isImageAttachment(attachmentType)) { + if (attachmentType.startsWith("audio/")) { + VoiceMessageBubble( + playbackId = "message:${message.id}", + name = attachmentName, + url = resolveServerUrl(serverBaseUrl, attachmentUrl), + durationMs = message.attachmentDurationMs ?: 0, + waveform = decodeVoiceWaveform(message.attachmentWaveform), + voiceNote = message.attachmentKind == "voice", + playback = voicePlayback, + language = language, + onToggle = onToggleVoicePlayback, + onSeek = onSeekVoicePlayback, + onCycleSpeed = onCycleVoicePlaybackSpeed, + onFallback = openAttachment, + modifier = Modifier.testTag("message_voice:${message.id}"), + ) + } else if (isImageAttachment(attachmentType)) { MessageImageAttachment( model = resolveServerUrl(serverBaseUrl, attachmentUrl), name = attachmentName, @@ -494,7 +534,9 @@ private fun PendingMessageItem( item.attachmentName?.let { attachmentName -> if (item.content.isNotBlank()) Spacer(Modifier.height(6.dp)) val localPath = item.localAttachmentPath - if (localPath != null && isImageAttachment(item.attachmentType)) { + if (item.attachmentKind == "voice") { + PendingVoiceMessage(item) + } else if (localPath != null && isImageAttachment(item.attachmentType)) { MessageImageAttachment( model = File(localPath), name = attachmentName, @@ -524,6 +566,36 @@ private fun PendingMessageItem( } } +@Composable +private fun PendingVoiceMessage(item: OutboxEntity) { + val colors = LocalEdgeChatColors.current + val samples = decodeVoiceWaveform(item.attachmentWaveform).ifEmpty { List(32) { 24 } } + Row(Modifier.width(230.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(Icons.Outlined.Mic, contentDescription = null, tint = colors.accent) + Spacer(Modifier.width(8.dp)) + Column(Modifier.weight(1f)) { + Canvas(Modifier.fillMaxWidth().height(24.dp)) { + val gap = 2.dp.toPx() + val barWidth = ((size.width - gap * (samples.size - 1)) / samples.size).coerceAtLeast(1.dp.toPx()) + samples.forEachIndexed { index, sample -> + val height = size.height * sample.coerceAtLeast(8) / 100f + drawRoundRect( + color = colors.accent, + topLeft = androidx.compose.ui.geometry.Offset(index * (barWidth + gap), (size.height - height) / 2), + size = androidx.compose.ui.geometry.Size(barWidth, height), + cornerRadius = androidx.compose.ui.geometry.CornerRadius(barWidth / 2), + ) + } + } + Text( + com.aozorae.edgechat.core.media.formatVoiceDuration(item.attachmentDurationMs ?: 0), + style = MaterialTheme.typography.labelSmall, + color = colors.textSecondary, + ) + } + } +} + @Composable private fun DayHeader(label: String) { val colors = LocalEdgeChatColors.current diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt index cd4a23e1..2667a879 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt @@ -1,6 +1,8 @@ package com.aozorae.edgechat.feature.chat +import android.Manifest import android.content.Intent +import android.content.pm.PackageManager import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts @@ -41,11 +43,14 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat import com.aozorae.edgechat.core.database.ConversationEntity 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.core.network.dto.MemberDto +import com.aozorae.edgechat.core.media.VoicePlaybackState +import com.aozorae.edgechat.core.media.VoiceRecordingState import com.aozorae.edgechat.core.repository.PendingAttachment import com.aozorae.edgechat.core.repository.RoomIdentity import com.aozorae.edgechat.ui.components.EdgeAvatar @@ -61,9 +66,11 @@ fun ChatPane( room: RoomIdentity?, conversation: ConversationEntity?, messages: List, - outbox: List, - attachment: PendingAttachment?, - members: List, + outbox: List, + attachment: PendingAttachment?, + voiceRecording: VoiceRecordingState, + voicePlayback: VoicePlaybackState, + members: List, currentUser: SessionDto, serverBaseUrl: String, busy: Boolean, @@ -73,7 +80,13 @@ fun ChatPane( onLoadOlder: () -> Unit, onSend: (String, List) -> Unit, onChooseAttachment: (android.net.Uri) -> Unit, - onClearAttachment: () -> Unit, + onClearAttachment: () -> Unit, + onStartVoiceRecording: () -> Unit, + onCancelVoiceRecording: () -> Unit, + onSendVoiceRecording: () -> Unit, + onToggleVoicePlayback: (String, String, Long) -> Unit, + onSeekVoicePlayback: (String, Float) -> Unit, + onCycleVoicePlaybackSpeed: (String) -> Unit, onRetry: (String) -> Unit, onCancel: (String) -> Unit, onDeleteMessage: (Long) -> Unit, @@ -114,9 +127,21 @@ fun ChatPane( BackHandler(enabled = onBack != null) { onBack?.invoke() } val scrollState = rememberLazyListState() val scope = rememberCoroutineScope() - val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> - uri?.let(onChooseAttachment) - } + val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + uri?.let(onChooseAttachment) + } + val microphonePermission = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { granted -> + if (granted) onStartVoiceRecording() + } + val requestVoiceRecording = { + if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { + onStartVoiceRecording() + } else { + microphonePermission.launch(Manifest.permission.RECORD_AUDIO) + } + } LaunchedEffect(room) { scrollState.scrollToItem(0) } val bottomInsets = WindowInsets.navigationBars.union(WindowInsets.ime) @@ -199,7 +224,11 @@ fun ChatPane( onRetry = onRetry, onCancel = onCancel, onDeleteMessage = onDeleteMessage, - onOpenAttachment = onOpenAttachment, + onOpenAttachment = onOpenAttachment, + voicePlayback = voicePlayback, + onToggleVoicePlayback = onToggleVoicePlayback, + onSeekVoicePlayback = onSeekVoicePlayback, + onCycleVoicePlaybackSpeed = onCycleVoicePlaybackSpeed, modifier = Modifier.weight(1f), ) MessageComposer( @@ -208,9 +237,13 @@ fun ChatPane( attachment = attachment, language = language, members = members, - currentUserId = currentUser.userId, - onChooseAttachment = { picker.launch("*/*") }, - onClearAttachment = onClearAttachment, + currentUserId = currentUser.userId, + recording = voiceRecording, + onChooseAttachment = { picker.launch("*/*") }, + onClearAttachment = onClearAttachment, + onStartVoiceRecording = requestVoiceRecording, + onCancelVoiceRecording = onCancelVoiceRecording, + onSendVoiceRecording = onSendVoiceRecording, onSend = { content, mentionUserIds -> onSend(content, mentionUserIds) scope.launch { scrollState.animateScrollToItem(0) } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt index 39e8aebe..df2c23e5 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt @@ -8,6 +8,10 @@ import com.aozorae.edgechat.core.database.MessageEntity import com.aozorae.edgechat.core.database.OutboxEntity import com.aozorae.edgechat.core.database.UserEntity import com.aozorae.edgechat.core.network.dto.MemberDto +import com.aozorae.edgechat.core.media.VoicePlaybackController +import com.aozorae.edgechat.core.media.VoicePlaybackState +import com.aozorae.edgechat.core.media.VoiceRecorder +import com.aozorae.edgechat.core.media.VoiceRecordingState import com.aozorae.edgechat.core.realtime.RealtimeCoordinator import com.aozorae.edgechat.core.repository.AttachmentRepository import com.aozorae.edgechat.core.repository.ChatRepository @@ -35,7 +39,9 @@ data class ChatUiState( val messages: List = emptyList(), val outbox: List = emptyList(), val attachment: PendingAttachment? = null, - val members: List = emptyList(), + val members: List = emptyList(), + val voiceRecording: VoiceRecordingState = VoiceRecordingState(), + val voicePlayback: VoicePlaybackState = VoicePlaybackState(), val busy: Boolean = false, val error: String? = null, ) @@ -45,8 +51,10 @@ data class ChatUiState( class ChatViewModel @Inject constructor( private val chatRepository: ChatRepository, private val outboxRepository: OutboxRepository, - private val attachmentRepository: AttachmentRepository, - private val realtime: RealtimeCoordinator, + private val attachmentRepository: AttachmentRepository, + private val realtime: RealtimeCoordinator, + private val voiceRecorder: VoiceRecorder, + private val voicePlayback: VoicePlaybackController, ) : ViewModel() { private val mutableOpenAttachment = MutableSharedFlow>(extraBufferCapacity = 1) val openAttachment: SharedFlow> = mutableOpenAttachment @@ -70,8 +78,10 @@ class ChatViewModel @Inject constructor( roomMessages, roomOutbox, attachment, - members, - busy, + members, + voiceRecorder.state, + voicePlayback.state, + busy, error, ) { values -> @Suppress("UNCHECKED_CAST") @@ -83,14 +93,19 @@ class ChatViewModel @Inject constructor( outbox = values[4] as List, attachment = values[5] as PendingAttachment?, members = values[6] as List, - busy = values[7] as Boolean, - error = values[8] as String?, + voiceRecording = values[7] as VoiceRecordingState, + voicePlayback = values[8] as VoicePlaybackState, + busy = values[9] as Boolean, + error = values[10] as String?, ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ChatUiState()) fun refresh() = action { chatRepository.bootstrap() } - fun select(room: RoomIdentity?) { + fun select(room: RoomIdentity?) { + if (voiceRecorder.state.value.active) { + voiceRecorder.cancel() + } val generation = ++memberLoadGeneration selectedRoom.value = room members.value = emptyList() @@ -132,10 +147,42 @@ class ChatViewModel @Inject constructor( attachment.value = attachmentRepository.import(uri) } - fun clearAttachment() { + fun clearAttachment() { attachment.value?.path?.let { java.io.File(it).delete() } attachment.value = null - } + } + + fun startVoiceRecording() { + error.value = null + runCatching(voiceRecorder::start) + .onFailure { error.value = it.message ?: "无法开始录音" } + } + + fun cancelVoiceRecording() { + voiceRecorder.cancel() + } + + fun sendVoiceRecording() { + val room = selectedRoom.value ?: return + val pending = voiceRecorder.finish() + if (pending == null) { + error.value = "录音时间太短,请重新录制" + return + } + action { outboxRepository.enqueue(room, "", pending) } + } + + fun toggleVoicePlayback(playbackId: String, url: String, durationMs: Long) { + voicePlayback.toggle(playbackId, url, durationMs) + } + + fun seekVoicePlayback(playbackId: String, fraction: Float) { + voicePlayback.seek(playbackId, fraction) + } + + fun cycleVoicePlaybackSpeed(playbackId: String) { + voicePlayback.cycleSpeed(playbackId) + } fun retry(clientMessageId: String) = action { outboxRepository.retry(clientMessageId) } @@ -182,6 +229,12 @@ class ChatViewModel @Inject constructor( error.value = null } + override fun onCleared() { + voiceRecorder.close() + voicePlayback.close() + super.onCleared() + } + private fun updateMembers(channelId: Long, request: suspend () -> List) { val generation = memberLoadGeneration action { diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt index 83a633a1..be7be426 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt @@ -1,6 +1,8 @@ package com.aozorae.edgechat.feature.chat import androidx.compose.foundation.border +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -21,6 +23,8 @@ import androidx.compose.material.icons.automirrored.filled.Send import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.AttachFile import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.DeleteOutline +import androidx.compose.material.icons.outlined.Mic import androidx.compose.material3.FilledIconButton import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -45,6 +49,8 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.aozorae.edgechat.core.repository.PendingAttachment import com.aozorae.edgechat.core.network.dto.MemberDto +import com.aozorae.edgechat.core.media.VoiceRecordingState +import com.aozorae.edgechat.core.media.formatVoiceDuration import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors @Composable @@ -54,9 +60,13 @@ fun MessageComposer( attachment: PendingAttachment?, language: String, members: List, - currentUserId: Long, - onChooseAttachment: () -> Unit, - onClearAttachment: () -> Unit, + currentUserId: Long, + recording: VoiceRecordingState = VoiceRecordingState(), + onChooseAttachment: () -> Unit, + onClearAttachment: () -> Unit, + onStartVoiceRecording: () -> Unit = {}, + onCancelVoiceRecording: () -> Unit = {}, + onSendVoiceRecording: () -> Unit = {}, onSend: (String, List) -> Unit, modifier: Modifier = Modifier, ) { @@ -138,10 +148,17 @@ fun MessageComposer( } } } - Row( - modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(horizontal = 8.dp, vertical = 8.dp), - verticalAlignment = Alignment.Bottom, - ) { + if (recording.active) { + VoiceRecordingBar( + recording = recording, + language = language, + onCancel = onCancelVoiceRecording, + onSend = onSendVoiceRecording, + ) + } else Row( + modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(horizontal = 8.dp, vertical = 8.dp), + verticalAlignment = Alignment.Bottom, + ) { FilledIconButton( onClick = onChooseAttachment, modifier = Modifier.size(48.dp), @@ -191,21 +208,84 @@ fun MessageComposer( ) } Spacer(Modifier.width(4.dp)) - IconButton( - onClick = { - onSend(content.text, resolveMentionUserIds(content.text, members, currentUserId)) - content = TextFieldValue() - }, - enabled = canSend, - modifier = Modifier.size(48.dp).testTag("send_message"), - ) { - Icon( - Icons.AutoMirrored.Filled.Send, - contentDescription = if (language == "zh-CN") "发送消息" else "Send message", - tint = if (canSend) colors.accent else colors.iconSecondary, - ) - } + if (canSend) { + IconButton( + onClick = { + onSend(content.text, resolveMentionUserIds(content.text, members, currentUserId)) + content = TextFieldValue() + }, + modifier = Modifier.size(48.dp).testTag("send_message"), + ) { + Icon( + Icons.AutoMirrored.Filled.Send, + contentDescription = if (language == "zh-CN") "发送消息" else "Send message", + tint = colors.accent, + ) + } + } else { + IconButton( + onClick = onStartVoiceRecording, + modifier = Modifier.size(48.dp).testTag("record_voice"), + ) { + Icon( + Icons.Outlined.Mic, + contentDescription = if (language == "zh-CN") "录制语音消息" else "Record voice message", + tint = colors.accent, + ) + } + } + } + } + } +} + +@Composable +private fun VoiceRecordingBar( + recording: VoiceRecordingState, + language: String, + onCancel: () -> Unit, + onSend: () -> Unit, +) { + val colors = LocalEdgeChatColors.current + Row( + modifier = Modifier.fillMaxWidth().height(64.dp).padding(horizontal = 8.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onCancel, modifier = Modifier.size(48.dp).testTag("cancel_voice")) { + Icon( + Icons.Outlined.DeleteOutline, + contentDescription = if (language == "zh-CN") "取消录音" else "Cancel recording", + tint = colors.critical, + ) + } + Box(Modifier.size(8.dp).background(colors.critical, CircleShape)) + Spacer(Modifier.width(8.dp)) + Text( + formatVoiceDuration(recording.elapsedMs), + color = colors.textPrimary, + style = MaterialTheme.typography.bodyMedium, + ) + Spacer(Modifier.width(10.dp)) + val samples = recording.waveform.ifEmpty { List(24) { 8 } } + Canvas(Modifier.weight(1f).height(28.dp)) { + val gap = 2.dp.toPx() + val barWidth = ((size.width - gap * (samples.size - 1)) / samples.size).coerceAtLeast(1.dp.toPx()) + samples.forEachIndexed { index, sample -> + val barHeight = size.height * (sample.coerceAtLeast(8) / 100f) + drawRoundRect( + color = colors.accent, + topLeft = androidx.compose.ui.geometry.Offset(index * (barWidth + gap), (size.height - barHeight) / 2), + size = androidx.compose.ui.geometry.Size(barWidth, barHeight), + cornerRadius = androidx.compose.ui.geometry.CornerRadius(barWidth / 2), + ) } } + IconButton(onClick = onSend, modifier = Modifier.size(48.dp).testTag("send_voice")) { + Icon( + Icons.AutoMirrored.Filled.Send, + contentDescription = if (language == "zh-CN") "发送语音消息" else "Send voice message", + tint = colors.accent, + ) + } } } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/VoiceMessageBubble.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/VoiceMessageBubble.kt new file mode 100644 index 00000000..c80301b6 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/VoiceMessageBubble.kt @@ -0,0 +1,139 @@ +package com.aozorae.edgechat.feature.chat + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.aozorae.edgechat.core.media.VoicePlaybackState +import com.aozorae.edgechat.core.media.fallbackVoiceWaveform +import com.aozorae.edgechat.core.media.formatVoiceDuration +import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors + +@Composable +fun VoiceMessageBubble( + playbackId: String, + name: String, + url: String, + durationMs: Long, + waveform: List, + voiceNote: Boolean, + playback: VoicePlaybackState, + language: String, + onToggle: (String, String, Long) -> Unit, + onSeek: (String, Float) -> Unit, + onCycleSpeed: (String) -> Unit, + onFallback: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = LocalEdgeChatColors.current + val active = playback.playbackId == playbackId + val effectiveDuration = if (active && playback.durationMs > 0) playback.durationMs else durationMs + val progress = if (active && effectiveDuration > 0) { + playback.positionMs.toFloat() / effectiveDuration + } else { + 0f + }.coerceIn(0f, 1f) + val samples = waveform.ifEmpty { fallbackVoiceWaveform(playbackId) } + + Row(modifier.width(250.dp), verticalAlignment = Alignment.CenterVertically) { + if (active && playback.failed) { + IconButton(onClick = onFallback, modifier = Modifier.size(42.dp)) { + Icon( + Icons.Outlined.Download, + contentDescription = if (language == "zh-CN") "下载语音" else "Download voice message", + tint = colors.accent, + ) + } + } else { + IconButton( + onClick = { onToggle(playbackId, url, durationMs) }, + modifier = Modifier.size(42.dp).testTag("voice_play:$playbackId"), + ) { + Icon( + if (active && playback.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow, + contentDescription = if (active && playback.playing) { + if (language == "zh-CN") "暂停语音" else "Pause voice message" + } else { + if (language == "zh-CN") "播放语音" else "Play voice message" + }, + tint = colors.accent, + ) + } + } + Spacer(Modifier.width(8.dp)) + Column(Modifier.weight(1f)) { + if (!voiceNote) { + Text( + name, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.labelMedium, + color = colors.textPrimary, + ) + } + Canvas( + Modifier + .fillMaxWidth() + .height(28.dp) + .pointerInput(playbackId, effectiveDuration) { + detectTapGestures { offset -> onSeek(playbackId, offset.x / size.width) } + } + .testTag("voice_waveform:$playbackId"), + ) { + val gap = 2.dp.toPx() + val barWidth = ((size.width - gap * (samples.size - 1)) / samples.size).coerceAtLeast(1.dp.toPx()) + samples.forEachIndexed { index, sample -> + val barHeight = size.height * (sample.coerceAtLeast(8) / 100f) + drawRoundRect( + color = if (index.toFloat() / samples.size <= progress) colors.accent else colors.iconSecondary, + topLeft = Offset(index * (barWidth + gap), (size.height - barHeight) / 2), + size = Size(barWidth, barHeight), + cornerRadius = CornerRadius(barWidth / 2), + ) + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + formatVoiceDuration(if (active && playback.positionMs > 0) playback.positionMs else effectiveDuration), + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.labelSmall, + color = colors.textSecondary, + ) + TextButton( + onClick = { onCycleSpeed(playbackId) }, + modifier = Modifier.height(28.dp), + ) { + Text( + text = "${if (active) playback.speed else 1f}x".replace(".0", ""), + style = MaterialTheme.typography.labelSmall, + 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 039229e5..05d4d630 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 @@ -235,8 +235,10 @@ private fun ChatContent( room = chatState.selectedRoom, conversation = selectedConversation, messages = chatState.messages, - outbox = chatState.outbox, - attachment = chatState.attachment, + outbox = chatState.outbox, + attachment = chatState.attachment, + voiceRecording = chatState.voiceRecording, + voicePlayback = chatState.voicePlayback, members = chatState.members, currentUser = session, serverBaseUrl = server.baseUrl, @@ -246,8 +248,14 @@ private fun ChatContent( onBack = onBack, onLoadOlder = chatViewModel::loadOlder, onSend = chatViewModel::send, - onChooseAttachment = chatViewModel::chooseAttachment, - onClearAttachment = chatViewModel::clearAttachment, + onChooseAttachment = chatViewModel::chooseAttachment, + onClearAttachment = chatViewModel::clearAttachment, + onStartVoiceRecording = chatViewModel::startVoiceRecording, + onCancelVoiceRecording = chatViewModel::cancelVoiceRecording, + onSendVoiceRecording = chatViewModel::sendVoiceRecording, + onToggleVoicePlayback = chatViewModel::toggleVoicePlayback, + onSeekVoicePlayback = chatViewModel::seekVoicePlayback, + onCycleVoicePlaybackSpeed = chatViewModel::cycleVoicePlaybackSpeed, onRetry = chatViewModel::retry, onCancel = chatViewModel::cancel, onDeleteMessage = chatViewModel::deleteMessage, diff --git a/android/app/src/test/java/com/aozorae/edgechat/core/media/VoiceMediaTest.kt b/android/app/src/test/java/com/aozorae/edgechat/core/media/VoiceMediaTest.kt new file mode 100644 index 00000000..263a39b6 --- /dev/null +++ b/android/app/src/test/java/com/aozorae/edgechat/core/media/VoiceMediaTest.kt @@ -0,0 +1,13 @@ +package com.aozorae.edgechat.core.media + +import org.junit.Assert.assertEquals +import org.junit.Test + +class VoiceMediaTest { + @Test + fun durationAndWaveformStayCompact() { + assertEquals("1:05", formatVoiceDuration(65_400)) + assertEquals(listOf(30, 90), normalizeVoiceWaveform(listOf(5, 30, 10, 90), 2)) + assertEquals(fallbackVoiceWaveform("same", 8), fallbackVoiceWaveform("same", 8)) + } +} diff --git a/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt b/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt index d0eb78f3..8cba53f0 100644 --- a/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt +++ b/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt @@ -9,7 +9,7 @@ class ApiDtosTest { private val json = Json { ignoreUnknownKeys = true } @Test - fun senderIdAcceptsLocalNumberAndExternalString() { + fun senderIdAcceptsLocalNumberAndExternalString() { val local = json.decodeFromString( """{"id":1,"createdAt":"2026-08-30 12:00:00","sender":{"kind":"local","id":42,"displayName":"A"}}""", ) @@ -18,5 +18,15 @@ class ApiDtosTest { ) assertEquals("42", local.sender.id) assertEquals("telegram:7", external.sender.id) - } + } + + @Test + fun voiceAttachmentKeepsDurationAndWaveform() { + val message = json.decodeFromString( + """{"id":3,"createdAt":"2026-09-02 12:00:00","sender":{"kind":"local","id":42,"displayName":"A"},"attachment":{"key":"42/voice.m4a","name":"voice.m4a","type":"audio/mp4","size":2048,"url":"/files/voice","kind":"voice","durationMs":8200,"waveform":[12,44,90]}}""", + ) + assertEquals("voice", message.attachment?.kind) + assertEquals(8_200L, message.attachment?.durationMs) + assertEquals(listOf(12, 44, 90), message.attachment?.waveform) + } } diff --git a/docs/api/edgechat-v1.openapi.yaml b/docs/api/edgechat-v1.openapi.yaml index 10eae04d..def9042a 100644 --- a/docs/api/edgechat-v1.openapi.yaml +++ b/docs/api/edgechat-v1.openapi.yaml @@ -571,6 +571,12 @@ components: type: { type: string } size: { type: integer } url: { type: string } + kind: { type: string, enum: [voice, audio] } + durationMs: { type: integer, minimum: 0 } + waveform: + type: array + maxItems: 64 + items: { type: integer, minimum: 0, maximum: 100 } Sender: type: object required: [kind, id, username, displayName, avatarUrl, source] diff --git a/frontend/src/components/chat/MessageAttachment.vue b/frontend/src/components/chat/MessageAttachment.vue index c8a3ba10..c846812a 100644 --- a/frontend/src/components/chat/MessageAttachment.vue +++ b/frontend/src/components/chat/MessageAttachment.vue @@ -4,6 +4,8 @@ import api from '../../api.js'; import { useOverlayLifecycle } from '../../composables/useOverlayLifecycle.js'; import { t } from '../../i18n.js'; import { isPreviewableImageAttachment } from './attachment-utils.js'; +import { isAudioAttachment } from '../../voice-message.js'; +import VoiceMessage from './VoiceMessage.vue'; const props = defineProps({ attachment: { @@ -16,6 +18,7 @@ const previewOpen = ref(false); const previewEl = ref(null); const imageFailed = ref(false); const isImage = computed(() => isPreviewableImageAttachment(props.attachment)); +const isAudio = computed(() => isAudioAttachment(props.attachment)); const displayName = computed(() => props.attachment?.name || t('attachments.fallback')); const openOriginalLabel = computed(() => t('attachments.openOriginalNamed', { name: displayName.value })); const attachmentUrl = computed(() => api.getFileUrl(props.attachment?.key || props.attachment?.url)); @@ -47,8 +50,9 @@ watch(