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 @@
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
@@ -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 @@
Cloudflare フルスタックで作られたモダンなチーム向けチャットシステム
- アカウント体系 · 公開/プライベートグループ · ダイレクトメッセージ · リアルタイムメッセージ · ファイルアップロード · 管理ダッシュボード
+ アカウント体系 · 公開/プライベートグループ · ダイレクトメッセージ · リアルタイムメッセージ · ボイスメッセージ · ファイルアップロード · 管理ダッシュボード
@@ -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 @@
基于 Cloudflare 全家桶打造的现代团队聊天系统
- 账号体系 · 公开/私有群组 · 私信 · 实时消息 · 文件上传 · 管理后台
+ 账号体系 · 公开/私有群组 · 私信 · 实时消息 · 语音消息 · 文件上传 · 管理后台
@@ -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(
-
-
+
+
+
-import { ArrowRight, Paperclip } from "@lucide/vue";
+import { ArrowRight, Mic, Paperclip, Send, Trash2 } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
import { t } from "../../i18n.js";
+import { useVoiceRecorder } from "../../composables/useVoiceRecorder.ts";
+import { formatVoiceDuration } from "../../voice-message.js";
import UiTextarea from "../ui/Textarea.vue";
import UiAvatar from "../ui/Avatar.vue";
import PendingAttachmentPreview from "./PendingAttachmentPreview.vue";
@@ -38,12 +40,15 @@ const emit = defineEmits([
"send",
"upload",
"clear-attachment",
+ "voice-recorded",
]);
const fileInput = ref(null);
const textarea = ref(null);
const mentionStart = ref(-1);
const mentionQuery = ref("");
const activeMentionIndex = ref(0);
+const recordingError = ref("");
+const { recording, elapsedMs, liveWaveform, start, finish, cancel } = useVoiceRecorder();
const filteredMentions = computed(() => {
const query = mentionQuery.value.toLocaleLowerCase();
return props.mentionCandidates
@@ -64,6 +69,9 @@ const sendDisabled = computed(
props.sending ||
(!props.modelValue.trim() && !props.pendingAttachment),
);
+const showVoiceButton = computed(
+ () => !props.modelValue.trim() && !props.pendingAttachment && !props.sending,
+);
function handleKeydown(event) {
if (mentionMenuOpen.value) {
@@ -135,6 +143,33 @@ function selectMention(member) {
function openPicker() {
fileInput.value?.click();
}
+
+async function startVoiceRecording() {
+ recordingError.value = "";
+ closeMentionMenu();
+ try {
+ await start();
+ } catch (error) {
+ recordingError.value =
+ error?.message === "voice_recording_unsupported"
+ ? t("voice.unsupported")
+ : t("voice.permissionDenied");
+ }
+}
+
+async function cancelVoiceRecording() {
+ await cancel();
+}
+
+async function sendVoiceRecording() {
+ const result = await finish();
+ if (!result) return;
+ if (result.durationMs < 500) {
+ recordingError.value = t("voice.tooShort");
+ return;
+ }
+ emit("voice-recorded", result);
+}
@@ -145,7 +180,7 @@ function openPicker() {
@clear="emit('clear-attachment')"
/>
- {{ error }}
+ {{ error || recordingError }}
-
+
+
+
+
+
+
{{ formatVoiceDuration(elapsedMs) }}
+
+
+
+
+
+
+
+
-
-
+
+
+
+
diff --git a/frontend/src/components/chat/PendingAttachmentPreview.vue b/frontend/src/components/chat/PendingAttachmentPreview.vue
index b43a049a..88be9a09 100644
--- a/frontend/src/components/chat/PendingAttachmentPreview.vue
+++ b/frontend/src/components/chat/PendingAttachmentPreview.vue
@@ -1,10 +1,12 @@
-
+ />
+
+
+ {{ formatVoiceDuration(attachment.durationMs) }}
+
{{ displayName }}
{{ t('common.remove') }}
diff --git a/frontend/src/components/chat/VoiceMessage.vue b/frontend/src/components/chat/VoiceMessage.vue
new file mode 100644
index 00000000..81777fdd
--- /dev/null
+++ b/frontend/src/components/chat/VoiceMessage.vue
@@ -0,0 +1,140 @@
+
+
+
+
+
diff --git a/frontend/src/composables/useChatRoom.js b/frontend/src/composables/useChatRoom.js
index 844c9b2f..abea05b8 100644
--- a/frontend/src/composables/useChatRoom.js
+++ b/frontend/src/composables/useChatRoom.js
@@ -247,38 +247,67 @@ export function useChatRoom({
roomSession.disconnect();
}
- async function sendMessage(mentionUserIds = []) {
- const key = activeRoom.value
- ? `${activeRoom.value.kind}:${activeRoom.value.id}`
- : "";
- if (!roomSession.isOpenFor(key)) {
- error.value = t('chat.realtimeNotReady');
- return;
- }
- if (!composerText.value.trim() && !pendingAttachment.value) {
- return;
+ async function sendMessage(mentionUserIds = []) {
+ const key = activeRoom.value
+ ? `${activeRoom.value.kind}:${activeRoom.value.id}`
+ : "";
+ if (!roomSession.isOpenFor(key)) {
+ error.value = t('chat.realtimeNotReady');
+ return;
+ }
+ if (!composerText.value.trim() && !pendingAttachment.value) {
+ return;
+ }
+
+ sending.value = true;
+ error.value = "";
+ try {
+ roomSession.send(
+ JSON.stringify({
+ type: "send",
+ content: composerText.value,
+ attachment: pendingAttachment.value,
+ mentionUserIds,
+ }),
+ key,
+ );
+ composerText.value = "";
+ pendingAttachment.value = null;
+ } catch (currentError) {
+ error.value = currentError.message;
+ } finally {
+ sending.value = false;
+ }
}
- sending.value = true;
- error.value = "";
- try {
- roomSession.send(
- JSON.stringify({
- type: "send",
- content: composerText.value,
- attachment: pendingAttachment.value,
- mentionUserIds,
- }),
- key,
- );
- composerText.value = "";
- pendingAttachment.value = null;
- } catch (currentError) {
- error.value = currentError.message;
- } finally {
- sending.value = false;
+ async function sendVoiceMessage(recording) {
+ const key = roomKey();
+ if (!roomSession.isOpenFor(key)) {
+ error.value = t('chat.realtimeNotReady');
+ return;
+ }
+ sending.value = true;
+ error.value = "";
+ let attachment = null;
+ try {
+ const payload = await roomApi.uploadFile(recording.file);
+ attachment = {
+ ...payload.file,
+ kind: "voice",
+ durationMs: recording.durationMs,
+ waveform: recording.waveform,
+ };
+ roomSession.send(
+ JSON.stringify({ type: "send", content: "", attachment, mentionUserIds: [] }),
+ key,
+ );
+ } catch (currentError) {
+ pendingAttachment.value = attachment;
+ error.value = currentError.message;
+ } finally {
+ sending.value = false;
+ }
}
- }
function deleteMessage(messageId) {
const key = activeRoom.value
@@ -411,7 +440,8 @@ export function useChatRoom({
deactivateRoom,
connectSocket,
disconnectSocket,
- sendMessage,
+ sendMessage,
+ sendVoiceMessage,
deleteMessage,
pinMessage,
unpinMessage,
diff --git a/frontend/src/composables/useVoiceRecorder.ts b/frontend/src/composables/useVoiceRecorder.ts
new file mode 100644
index 00000000..b2594b3a
--- /dev/null
+++ b/frontend/src/composables/useVoiceRecorder.ts
@@ -0,0 +1,138 @@
+import { onBeforeUnmount, ref } from "vue";
+import { normalizeVoiceWaveform } from "../voice-message.js";
+
+export interface VoiceRecording {
+ file: File;
+ durationMs: number;
+ waveform: number[];
+}
+
+function recorderFormat() {
+ const formats = [
+ { mimeType: "audio/webm;codecs=opus", extension: "webm" },
+ { mimeType: "audio/ogg;codecs=opus", extension: "ogg" },
+ { mimeType: "audio/mp4", extension: "m4a" },
+ ];
+ return formats.find(({ mimeType }) => MediaRecorder.isTypeSupported(mimeType)) || null;
+}
+
+export function useVoiceRecorder() {
+ const recording = ref(false);
+ const elapsedMs = ref(0);
+ const liveWaveform = ref([]);
+ let recorder: MediaRecorder | null = null;
+ let stream: MediaStream | null = null;
+ let audioContext: AudioContext | null = null;
+ let analyser: AnalyserNode | null = null;
+ let timer: number | null = null;
+ let chunks: Blob[] = [];
+ let samples: number[] = [];
+ let startedAt = 0;
+ let extension = "webm";
+
+ function sampleAmplitude() {
+ if (!analyser) return;
+ const values = new Uint8Array(analyser.fftSize);
+ analyser.getByteTimeDomainData(values);
+ const energy = values.reduce((sum, value) => {
+ const centered = (value - 128) / 128;
+ return sum + centered * centered;
+ }, 0);
+ const level = Math.min(100, Math.max(6, Math.round(Math.sqrt(energy / values.length) * 260)));
+ samples.push(level);
+ liveWaveform.value = normalizeVoiceWaveform(samples.slice(-80), 32);
+ }
+
+ async function start() {
+ if (recording.value) return;
+ if (!globalThis.navigator?.mediaDevices?.getUserMedia || !globalThis.MediaRecorder) {
+ throw new Error("voice_recording_unsupported");
+ }
+ const format = recorderFormat();
+ if (!format) throw new Error("voice_recording_unsupported");
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
+ });
+ try {
+ audioContext = new AudioContext();
+ analyser = audioContext.createAnalyser();
+ analyser.fftSize = 256;
+ audioContext.createMediaStreamSource(stream).connect(analyser);
+ extension = format.extension;
+ chunks = [];
+ samples = [];
+ elapsedMs.value = 0;
+ liveWaveform.value = [];
+ recorder = new MediaRecorder(stream, {
+ mimeType: format.mimeType,
+ audioBitsPerSecond: 64_000,
+ });
+ recorder.addEventListener("dataavailable", (event) => {
+ if (event.data.size) chunks.push(event.data);
+ });
+ recorder.start(250);
+ } catch (error) {
+ recorder = null;
+ closeDevices();
+ throw error;
+ }
+ startedAt = performance.now();
+ recording.value = true;
+ timer = window.setInterval(() => {
+ elapsedMs.value = Math.round(performance.now() - startedAt);
+ sampleAmplitude();
+ }, 100);
+ }
+
+ function closeDevices() {
+ if (timer !== null) window.clearInterval(timer);
+ timer = null;
+ stream?.getTracks().forEach((track) => {
+ track.stop();
+ });
+ stream = null;
+ void audioContext?.close();
+ audioContext = null;
+ analyser = null;
+ recording.value = false;
+ }
+
+ async function stopRecorder() {
+ const activeRecorder = recorder;
+ if (!activeRecorder || activeRecorder.state === "inactive") return;
+ await new Promise((resolve) => {
+ activeRecorder.addEventListener("stop", () => resolve(), { once: true });
+ activeRecorder.stop();
+ });
+ recorder = null;
+ }
+
+ async function finish(): Promise {
+ if (!recording.value || !recorder) return null;
+ const durationMs = Math.max(elapsedMs.value, Math.round(performance.now() - startedAt));
+ await stopRecorder();
+ const blob = new Blob(chunks, { type: chunks[0]?.type || `audio/${extension}` });
+ const waveform = normalizeVoiceWaveform(samples, 48);
+ closeDevices();
+ return {
+ file: new File([blob], `voice-${Date.now()}.${extension}`, { type: blob.type }),
+ durationMs,
+ waveform,
+ };
+ }
+
+ async function cancel() {
+ if (recorder?.state !== "inactive") await stopRecorder();
+ chunks = [];
+ samples = [];
+ elapsedMs.value = 0;
+ liveWaveform.value = [];
+ closeDevices();
+ }
+
+ onBeforeUnmount(() => {
+ void cancel();
+ });
+
+ return { recording, elapsedMs, liveWaveform, start, finish, cancel };
+}
diff --git a/frontend/src/demo/fixtures.js b/frontend/src/demo/fixtures.js
index 9d4d8713..e89e4621 100644
--- a/frontend/src/demo/fixtures.js
+++ b/frontend/src/demo/fixtures.js
@@ -1,5 +1,49 @@
const FIXTURE_TIME = '2026-08-14T10:00:00.000Z';
+function createDemoVoiceDataUrl() {
+ const sampleRate = 8000;
+ const durationSeconds = 3.2;
+ const sampleCount = Math.round(sampleRate * durationSeconds);
+ const bytes = new Uint8Array(44 + sampleCount);
+ const view = new DataView(bytes.buffer);
+ const writeText = (offset, value) => {
+ for (let index = 0; index < value.length; index += 1) {
+ bytes[offset + index] = value.charCodeAt(index);
+ }
+ };
+
+ writeText(0, 'RIFF');
+ view.setUint32(4, 36 + sampleCount, true);
+ writeText(8, 'WAVE');
+ writeText(12, 'fmt ');
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 1, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, sampleRate, true);
+ view.setUint16(32, 1, true);
+ view.setUint16(34, 8, true);
+ writeText(36, 'data');
+ view.setUint32(40, sampleCount, true);
+
+ // 生成轻柔且有起伏的短音频,便于在 demo 中真实验证播放、暂停与进度交互。
+ for (let index = 0; index < sampleCount; index += 1) {
+ const time = index / sampleRate;
+ const envelope = Math.sin(Math.PI * Math.min(time / 0.12, 1, (durationSeconds - time) / 0.18));
+ const modulation = Math.sin(2 * Math.PI * 2.4 * time) * 18;
+ const sample = Math.sin(2 * Math.PI * (176 + modulation) * time);
+ bytes[44 + index] = 128 + Math.round(sample * envelope * 24);
+ }
+
+ let binary = '';
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
+ }
+ return `data:audio/wav;base64,${btoa(binary)}`;
+}
+
+const DEMO_VOICE_URL = createDemoVoiceDataUrl();
+
function internalSender(user) {
return {
id: user.id,
@@ -191,14 +235,30 @@ export function createDemoFixtures() {
size: 8420
}
},
- {
- id: 104,
- content: '所有演示操作都只保存在当前浏览器页面中。',
- createdAt: '2026-08-14T09:58:00.000Z',
- sender: internalSender(users[3]),
- attachment: null
- }
- ],
+ {
+ id: 104,
+ content: '所有演示操作都只保存在当前浏览器页面中。',
+ createdAt: '2026-08-14T09:58:00.000Z',
+ sender: internalSender(users[3]),
+ attachment: null
+ },
+ {
+ id: 105,
+ content: '',
+ createdAt: '2026-08-14T10:01:00.000Z',
+ sender: internalSender(users[1]),
+ attachment: {
+ key: DEMO_VOICE_URL,
+ url: DEMO_VOICE_URL,
+ name: 'voice-demo.wav',
+ type: 'audio/wav',
+ size: 25644,
+ kind: 'voice',
+ durationMs: 3200,
+ waveform: [18, 30, 46, 72, 88, 64, 42, 28, 36, 58, 82, 94, 76, 54, 34, 22, 40, 68, 90, 74, 50, 32, 48, 78]
+ }
+ }
+ ],
'private:2': [
{
id: 111,
diff --git a/frontend/src/locales/en-US.js b/frontend/src/locales/en-US.js
index 4398a61e..b5df339f 100644
--- a/frontend/src/locales/en-US.js
+++ b/frontend/src/locales/en-US.js
@@ -168,7 +168,19 @@ export default {
'attachments.previewNamed': 'Preview image: {name}',
'attachments.imagePreviewNamed': 'Image preview: {name}',
'attachments.openOriginal': 'Open original image',
- 'attachments.closePreview': 'Close image preview',
+ 'attachments.closePreview': 'Close image preview',
+ 'voice.record': 'Record voice message',
+ 'voice.recording': 'Recording voice message',
+ 'voice.cancel': 'Cancel recording',
+ 'voice.send': 'Send voice message',
+ 'voice.play': 'Play voice message',
+ 'voice.pause': 'Pause voice message',
+ 'voice.seek': 'Seek voice message',
+ 'voice.speed': 'Change playback speed',
+ 'voice.fallback': 'Voice message',
+ 'voice.unsupported': 'Voice recording is not supported in this browser.',
+ 'voice.permissionDenied': 'The microphone is unavailable. Check your browser permission.',
+ 'voice.tooShort': 'That recording was too short. Please try again.',
'messages.empty': 'There are no messages yet.',
'messages.loadEarlier': 'Load earlier messages',
'messages.loading': 'Loading messages...',
diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js
index 0a6ab7e3..ba6303ad 100644
--- a/frontend/src/locales/zh-CN.js
+++ b/frontend/src/locales/zh-CN.js
@@ -168,7 +168,19 @@ export default {
'attachments.previewNamed': '预览图片:{name}',
'attachments.imagePreviewNamed': '图片预览:{name}',
'attachments.openOriginal': '打开原图',
- 'attachments.closePreview': '关闭图片预览',
+ 'attachments.closePreview': '关闭图片预览',
+ 'voice.record': '录制语音消息',
+ 'voice.recording': '正在录音',
+ 'voice.cancel': '取消录音',
+ 'voice.send': '发送语音消息',
+ 'voice.play': '播放语音消息',
+ 'voice.pause': '暂停语音消息',
+ 'voice.seek': '调整语音播放进度',
+ 'voice.speed': '切换播放速度',
+ 'voice.fallback': '语音消息',
+ 'voice.unsupported': '当前浏览器不支持语音录制。',
+ 'voice.permissionDenied': '无法使用麦克风,请检查浏览器权限。',
+ 'voice.tooShort': '录音时间太短,请重新录制。',
'messages.empty': '这里还没有消息。',
'messages.loadEarlier': '加载更早消息',
'messages.loading': '正在加载消息...',
diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue
index 553e7f5d..9b2e3fa4 100644
--- a/frontend/src/pages/ChatPage.vue
+++ b/frontend/src/pages/ChatPage.vue
@@ -111,7 +111,7 @@ function handleRoomAccessRevoked(room) {
const {
messages, pinnedMessage, highlightedMessageId, loading, wsStatus, composerText, pendingAttachment, sending,
messagesEl, isOwnMessage,
- loadMessages, activateRoom, deactivateRoom, disconnectSocket, sendMessage, deleteMessage,
+ loadMessages, activateRoom, deactivateRoom, disconnectSocket, sendMessage, sendVoiceMessage, deleteMessage,
pinMessage, unpinMessage, revealPinnedMessage,
uploadAttachment, clearAttachment, loadOlder
} = useChatRoom({
@@ -610,6 +610,7 @@ onBeforeUnmount(() => {
:error="error"
:mention-candidates="mentionCandidates"
@send="sendComposerMessage"
+ @voice-recorded="sendVoiceMessage"
@upload="uploadAttachment"
@clear-attachment="clearAttachment"
/>
diff --git a/frontend/src/styles/chat-attachments.css b/frontend/src/styles/chat-attachments.css
index fa3153a8..6eb65aa3 100644
--- a/frontend/src/styles/chat-attachments.css
+++ b/frontend/src/styles/chat-attachments.css
@@ -31,6 +31,104 @@
word-break: break-word;
}
+.message-attachment--audio {
+ width: min(310px, 68vw);
+}
+
+.voice-message {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 240px;
+}
+
+.voice-message__play {
+ display: inline-flex;
+ flex: 0 0 42px;
+ align-items: center;
+ justify-content: center;
+ width: 42px;
+ height: 42px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: #008069;
+ color: #fff;
+ cursor: pointer;
+}
+
+.voice-message__body {
+ display: grid;
+ flex: 1;
+ gap: 4px;
+ min-width: 0;
+}
+
+.voice-message__name {
+ overflow: hidden;
+ color: #111b21;
+ font-size: 12px;
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.voice-waveform {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ height: 28px;
+}
+
+.voice-waveform__bar {
+ flex: 1 1 2px;
+ min-width: 2px;
+ border-radius: 2px;
+ background: #aebac1;
+}
+
+.voice-waveform__bar--played {
+ background: #008069;
+}
+
+.voice-waveform__seek {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ opacity: 0;
+ cursor: pointer;
+}
+
+.voice-message__meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ color: #667781;
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+}
+
+.voice-message__speed {
+ min-width: 30px;
+ padding: 1px 3px;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: inherit;
+ cursor: pointer;
+ font: inherit;
+ font-weight: 700;
+}
+
+.voice-message__speed:hover,
+.voice-message__speed:focus-visible {
+ background: rgba(0, 128, 105, 0.1);
+ color: #008069;
+}
+
.pending-attachment {
display: flex;
align-items: center;
@@ -53,6 +151,16 @@
background: rgba(31, 37, 33, 0.08);
}
+.pending-attachment__voice {
+ display: inline-flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 5px;
+ color: #008069;
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+}
+
.pending-attachment__name {
flex: 1;
width: auto;
@@ -128,9 +236,17 @@
}
@media (max-width: 720px) {
- .message-attachment--image {
+ .message-attachment--image {
max-width: min(320px, 82vw);
- }
+ }
+
+ .message-attachment--audio {
+ width: min(300px, 78vw);
+ }
+
+ .voice-message {
+ min-width: 220px;
+ }
.message-attachment__image {
max-height: 260px;
diff --git a/frontend/src/voice-message.js b/frontend/src/voice-message.js
new file mode 100644
index 00000000..f21671bd
--- /dev/null
+++ b/frontend/src/voice-message.js
@@ -0,0 +1,35 @@
+export function isAudioAttachment(attachment) {
+ return String(attachment?.type || "").toLowerCase().startsWith("audio/");
+}
+
+export function formatVoiceDuration(durationMs) {
+ const totalSeconds = Math.max(0, Math.round(Number(durationMs) / 1000) || 0);
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = String(totalSeconds % 60).padStart(2, "0");
+ return `${minutes}:${seconds}`;
+}
+
+export function normalizeVoiceWaveform(samples, targetCount = 42) {
+ const values = Array.from(samples || [], (sample) =>
+ Math.min(Math.max(Math.round(Number(sample) || 0), 0), 100),
+ );
+ if (!values.length) return [];
+ if (values.length <= targetCount) return values;
+ return Array.from({ length: targetCount }, (_, index) => {
+ const start = Math.floor((index * values.length) / targetCount);
+ const end = Math.max(start + 1, Math.floor(((index + 1) * values.length) / targetCount));
+ return Math.max(...values.slice(start, end));
+ });
+}
+
+export function fallbackVoiceWaveform(seed, count = 42) {
+ let state = Array.from(String(seed || "voice")).reduce(
+ (hash, character) => (hash * 31 + character.codePointAt(0)) >>> 0,
+ 2166136261,
+ );
+ return Array.from({ length: count }, (_, index) => {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ const envelope = 0.68 + 0.32 * Math.sin((index / Math.max(count - 1, 1)) * Math.PI);
+ return Math.round((24 + (state % 68)) * envelope);
+ });
+}
diff --git a/test/api-v1-contract.test.js b/test/api-v1-contract.test.js
index 3703159c..9fcd6771 100644
--- a/test/api-v1-contract.test.js
+++ b/test/api-v1-contract.test.js
@@ -44,7 +44,9 @@ test("OpenAPI v1 keeps stable auth, idempotency, sync and error fields", () => {
"hasMore",
"mentionUserIds",
"mentionUnreadCount",
- "required: [code, message]",
+ "durationMs",
+ "waveform",
+ "required: [code, message]",
]) {
const escaped = field.replaceAll("[", "\\[").replaceAll("]", "\\]");
assert.match(openapi, new RegExp(escaped));
diff --git a/test/data-projections.test.js b/test/data-projections.test.js
index 1341190b..ff5d9a4e 100644
--- a/test/data-projections.test.js
+++ b/test/data-projections.test.js
@@ -237,8 +237,11 @@ test("消息 projection 保持附件和发送者字段", () => {
sender_avatar_key: "avatar.png",
attachment_key: "files/a b.txt",
attachment_name: "a b.txt",
- attachment_type: "text/plain",
- attachment_size: "10",
+ attachment_type: "text/plain",
+ attachment_size: "10",
+ attachment_kind: null,
+ attachment_duration_ms: null,
+ attachment_waveform: null,
source_attachment_id: null,
source_attachment_unique_id: null,
}),
@@ -267,3 +270,33 @@ test("消息 projection 保持附件和发送者字段", () => {
},
);
});
+
+test("语音消息 projection 保留时长与压缩波形", () => {
+ const message = mapMessage({
+ id: 6,
+ content: "",
+ mentions_json: "[]",
+ mention_user_ids: "[]",
+ created_at: "2026-09-02",
+ sender_id: 2,
+ sender_username: "alice",
+ sender_display_name: "Alice",
+ attachment_key: "files/voice.ogg",
+ attachment_name: "voice.ogg",
+ attachment_type: "audio/ogg",
+ attachment_size: 2048,
+ attachment_kind: "voice",
+ attachment_duration_ms: 8400,
+ attachment_waveform: "[12,45,90]",
+ });
+ assert.deepEqual(message.attachment, {
+ key: "files/voice.ogg",
+ name: "voice.ogg",
+ type: "audio/ogg",
+ size: 2048,
+ url: "/files/files%2Fvoice.ogg",
+ kind: "voice",
+ durationMs: 8400,
+ waveform: [12, 45, 90],
+ });
+});
diff --git a/test/mobile-api-v1.test.js b/test/mobile-api-v1.test.js
index 5803092b..42927517 100644
--- a/test/mobile-api-v1.test.js
+++ b/test/mobile-api-v1.test.js
@@ -43,7 +43,7 @@ function createEnvironment() {
keys: { 'test-v1': encodedKey() }
}),
MAX_FILE_SIZE: '20971520',
- ALLOWED_FILE_TYPES: 'image/,video/,text/,application/pdf,application/octet-stream',
+ ALLOWED_FILE_TYPES: 'image/,video/,audio/,text/,application/pdf,application/octet-stream',
FILES: {
files,
async put(key, value, metadata) {
@@ -180,8 +180,14 @@ test('客户端消息和附件重试复用同一服务端记录', async () => {
});
assert.equal(firstUpload.created, true);
assert.equal(retryUpload.created, false);
- assert.equal(retryUpload.file.key, firstUpload.file.key);
- assert.equal(env.FILES.files.size, 1);
+ assert.equal(retryUpload.file.key, firstUpload.file.key);
+ assert.equal(env.FILES.files.size, 1);
+ const voiceUpload = await saveUploadedFile(
+ env,
+ { userId: user.id },
+ new File([Uint8Array.from([1, 2, 3])], 'voice.ogg', { type: 'audio/ogg' }),
+ );
+ assert.equal(voiceUpload.file.type, 'audio/ogg');
database.run('UPDATE messages SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?', [
firstMessage.message.id
diff --git a/test/telegram-bridge.test.js b/test/telegram-bridge.test.js
index c6bbe52d..ac75ed6a 100644
--- a/test/telegram-bridge.test.js
+++ b/test/telegram-bridge.test.js
@@ -55,7 +55,7 @@ test("Telegram 文字消息转换为稳定的外部发送者模型", () => {
assert.equal(parseTelegramMessageUpdate({ message: { text: "bot", from: { is_bot: true } } }), null);
});
-test("Telegram 图片、视频与普通文件保留原始元数据", () => {
+test("Telegram 图片、视频、语音、音频与普通文件保留原始元数据", () => {
const base = {
message_id: 10,
caption: "说明",
@@ -93,6 +93,42 @@ test("Telegram 图片、视频与普通文件保留原始元数据", () => {
});
assert.equal(video.attachment.kind, "video");
assert.equal(video.attachment.fileName, "clip.mp4");
+ const voice = parseTelegramMessageUpdate({
+ message: {
+ ...base,
+ voice: {
+ file_id: "voice",
+ file_unique_id: "voice-u",
+ mime_type: "audio/ogg",
+ file_size: 250,
+ duration: 8,
+ },
+ },
+ });
+ assert.deepEqual(voice.attachment, {
+ kind: "voice",
+ fileId: "voice",
+ fileUniqueId: "voice-u",
+ fileName: "voice-10.ogg",
+ mimeType: "audio/ogg",
+ fileSize: 250,
+ durationMs: 8000,
+ });
+ const audio = parseTelegramMessageUpdate({
+ message: {
+ ...base,
+ audio: {
+ file_id: "audio",
+ file_unique_id: "audio-u",
+ file_name: "song.mp3",
+ mime_type: "audio/mpeg",
+ file_size: 350,
+ duration: 12,
+ },
+ },
+ });
+ assert.equal(audio.attachment.kind, "audio");
+ assert.equal(audio.attachment.durationMs, 12000);
const document = parseTelegramMessageUpdate({
message: {
...base,
@@ -147,6 +183,26 @@ test("Telegram 媒体上传按类型构造 multipart 请求", async () => {
assert.equal(captured.init.body.get("parse_mode"), "HTML");
assert.equal(captured.init.body.get("caption"), "Alice: \nhello");
assert.equal(captured.init.body.get("video").name, "clip.mp4");
+
+ globalThis.fetch = async (url, init) => {
+ captured = { url, init };
+ return Response.json({ ok: true, result: { message_id: 2 } });
+ };
+ try {
+ await sendTelegramMedia("123:token", {
+ chatId: "-1001",
+ kind: "voice",
+ bytes: Uint8Array.from([4, 5, 6]),
+ filename: "voice.ogg",
+ contentType: "audio/ogg",
+ durationMs: 8400,
+ });
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ assert.match(captured.url, /\/sendVoice$/);
+ assert.equal(captured.init.body.get("duration"), "8");
+ assert.equal(captured.init.body.get("voice").name, "voice.ogg");
});
test("Telegram 入站附件下载后加密写入 R2,超限时不下载", async () => {
@@ -171,6 +227,7 @@ test("Telegram 入站附件下载后加密写入 R2,超限时不下载", async
},
};
let imported;
+ let importedAudio;
try {
imported = await importTelegramAttachment(env, {
botToken: "123:token",
@@ -178,17 +235,36 @@ test("Telegram 入站附件下载后加密写入 R2,超限时不下载", async
telegramMessageId: 9,
attachment: {
fileId: "file-id",
- fileName: "a.bin",
- mimeType: "application/octet-stream",
+ fileName: "voice.ogg",
+ mimeType: "audio/ogg",
+ fileSize: 4,
+ kind: "voice",
+ durationMs: 4200,
+ },
+ });
+ importedAudio = await importTelegramAttachment(env, {
+ botToken: "123:token",
+ telegramChatId: "-1001",
+ telegramMessageId: 10,
+ attachment: {
+ fileId: "audio-id",
+ fileName: "song.mp3",
+ mimeType: "audio/mpeg",
fileSize: 4,
+ kind: "audio",
+ durationMs: 12_000,
},
});
} finally {
globalThis.fetch = originalFetch;
}
- assert.equal(fetchCount, 2);
- assert.match(imported.attachment.key, /^telegram\/-1001\/9-[0-9a-f-]+\.bin$/);
- assert.equal(writes.length, 1);
+ assert.equal(fetchCount, 4);
+ assert.match(imported.attachment.key, /^telegram\/-1001\/9-[0-9a-f-]+\.ogg$/);
+ assert.equal(imported.attachment.kind, "voice");
+ assert.equal(imported.attachment.durationMs, 4200);
+ assert.equal(importedAudio.attachment.kind, "audio");
+ assert.equal(importedAudio.attachment.durationMs, 12_000);
+ assert.equal(writes.length, 2);
assert.deepEqual(
(await decryptAttachment(env, writes[0].value, writes[0].key)).bytes,
Uint8Array.from([1, 2, 3, 4]),
@@ -282,8 +358,8 @@ test("可信 Telegram 外部消息可以直接引用 Bridge 创建的 R2 附件"
assert.equal(result.created, true);
assert.equal(result.message.attachment.key, "telegram/-1001/9-a.bin");
- assert.equal(insertBinds[13], "file-id");
- assert.equal(insertBinds[14], "unique-id");
+ assert.equal(insertBinds[16], "file-id");
+ assert.equal(insertBinds[17], "unique-id");
});
test("Bot Token 与 Webhook Secret 使用用途绑定的服务端密文", async () => {
diff --git a/test/voice-messages.test.js b/test/voice-messages.test.js
new file mode 100644
index 00000000..a5344feb
--- /dev/null
+++ b/test/voice-messages.test.js
@@ -0,0 +1,70 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { pickAttachment } from "../worker/src/utils.js";
+import {
+ fallbackVoiceWaveform,
+ formatVoiceDuration,
+ normalizeVoiceWaveform,
+} from "../frontend/src/voice-message.js";
+
+test("语音附件只保留受控时长和短波形", () => {
+ assert.deepEqual(
+ pickAttachment({
+ key: "7/voice.ogg",
+ name: "voice.ogg",
+ type: "audio/ogg; codecs=opus",
+ size: 1024,
+ kind: "voice",
+ durationMs: 8123.6,
+ waveform: [-4, 12.4, 110],
+ }, { ownerUserId: 7 }),
+ {
+ key: "7/voice.ogg",
+ name: "voice.ogg",
+ type: "audio/ogg; codecs=opus",
+ size: 1024,
+ url: "/files/7%2Fvoice.ogg",
+ kind: "voice",
+ durationMs: 8124,
+ waveform: [0, 12, 100],
+ },
+ );
+});
+
+test("普通音频附件不会被伪造成语音便笺", () => {
+ const attachment = pickAttachment({
+ key: "7/song.mp3",
+ name: "song.mp3",
+ type: "audio/mpeg",
+ size: 2048,
+ kind: "document",
+ durationMs: 9000,
+ waveform: [50],
+ }, { ownerUserId: 7 });
+ assert.equal(attachment.kind, undefined);
+ assert.equal(attachment.durationMs, undefined);
+ assert.equal(attachment.waveform, undefined);
+});
+
+test("普通音频可保留时长但不会获得语音波形", () => {
+ const attachment = pickAttachment({
+ key: "7/song.mp3",
+ name: "song.mp3",
+ type: "audio/mpeg",
+ size: 2048,
+ kind: "audio",
+ durationMs: 12_000,
+ waveform: [50],
+ }, { ownerUserId: 7 });
+ assert.equal(attachment.kind, "audio");
+ assert.equal(attachment.durationMs, 12_000);
+ assert.equal(attachment.waveform, undefined);
+});
+
+test("网页语音时长和波形 helper 保持紧凑稳定", () => {
+ assert.equal(formatVoiceDuration(65_400), "1:05");
+ assert.deepEqual(normalizeVoiceWaveform([5, 30, 10, 90], 2), [30, 90]);
+ assert.deepEqual(fallbackVoiceWaveform("same", 8), fallbackVoiceWaveform("same", 8));
+ assert.equal(fallbackVoiceWaveform("same", 8).length, 8);
+});
diff --git a/worker/migrations/2026-09-02-voice-messages.sql b/worker/migrations/2026-09-02-voice-messages.sql
new file mode 100644
index 00000000..1104a3ea
--- /dev/null
+++ b/worker/migrations/2026-09-02-voice-messages.sql
@@ -0,0 +1,5 @@
+ALTER TABLE messages ADD COLUMN attachment_kind TEXT CHECK (
+ attachment_kind IS NULL OR attachment_kind IN ('voice', 'audio')
+);
+ALTER TABLE messages ADD COLUMN attachment_duration_ms INTEGER;
+ALTER TABLE messages ADD COLUMN attachment_waveform TEXT;
diff --git a/worker/schema.sql b/worker/schema.sql
index 9bd94e99..73e62884 100644
--- a/worker/schema.sql
+++ b/worker/schema.sql
@@ -103,6 +103,9 @@ CREATE TABLE IF NOT EXISTS messages (
attachment_name TEXT,
attachment_type TEXT,
attachment_size INTEGER,
+ attachment_kind TEXT CHECK (attachment_kind IS NULL OR attachment_kind IN ('voice', 'audio')),
+ attachment_duration_ms INTEGER,
+ attachment_waveform TEXT,
sender_kind TEXT NOT NULL DEFAULT 'local' CHECK (sender_kind IN ('local', 'external')),
external_sender_id TEXT,
external_sender_name TEXT,
diff --git a/worker/src/api/upload.js b/worker/src/api/upload.js
index aec9b127..8a816005 100644
--- a/worker/src/api/upload.js
+++ b/worker/src/api/upload.js
@@ -31,10 +31,13 @@ function isInlineContentType(contentType) {
if (contentType.startsWith('image/')) {
return contentType !== 'image/svg+xml';
}
- if (contentType.startsWith('video/')) {
- return true;
- }
- return false;
+ if (contentType.startsWith('video/')) {
+ return true;
+ }
+ if (contentType.startsWith('audio/')) {
+ return true;
+ }
+ return false;
}
function contentDispositionValue(kind, filename) {
diff --git a/worker/src/attachment-metadata.js b/worker/src/attachment-metadata.js
index 078aa922..7ae4a1a4 100644
--- a/worker/src/attachment-metadata.js
+++ b/worker/src/attachment-metadata.js
@@ -27,3 +27,24 @@ export function safeFilenameExtension(filename) {
const extension = cleanName.slice(dotIndex + 1).toLowerCase();
return /^[a-z0-9]{1,10}$/.test(extension) ? `.${extension}` : "";
}
+
+const MAX_VOICE_DURATION_MS = 4 * 60 * 60 * 1000;
+const MAX_VOICE_WAVEFORM_SAMPLES = 64;
+
+export function normalizeAudioAttachmentMetadata(payload, contentType) {
+ const kind = payload?.kind === "voice" || payload?.kind === "audio" ? payload.kind : null;
+ if (!kind || !normalizeContentType(contentType).startsWith("audio/")) {
+ return {};
+ }
+
+ const durationMs = Math.min(
+ Math.max(Math.round(Number(payload.durationMs) || 0), 0),
+ MAX_VOICE_DURATION_MS,
+ );
+ const waveform = kind === "voice" && Array.isArray(payload.waveform)
+ ? payload.waveform
+ .slice(0, MAX_VOICE_WAVEFORM_SAMPLES)
+ .map((sample) => Math.min(Math.max(Math.round(Number(sample) || 0), 0), 100))
+ : [];
+ return { kind, durationMs, ...(kind === "voice" ? { waveform } : {}) };
+}
diff --git a/worker/src/data/messages.js b/worker/src/data/messages.js
index 96b17366..c3825f60 100644
--- a/worker/src/data/messages.js
+++ b/worker/src/data/messages.js
@@ -8,6 +8,25 @@ function toNullableNumber(value) {
return Number.isFinite(number) ? number : null;
}
+function mapAttachment(row) {
+ if (!row.attachment_key) return null;
+ const attachment = {
+ key: row.attachment_key,
+ name: row.attachment_name,
+ type: row.attachment_type,
+ size: toNullableNumber(row.attachment_size) || 0,
+ url: publicFileUrl(row.attachment_key),
+ };
+ if (row.attachment_kind === "voice" || row.attachment_kind === "audio") {
+ attachment.kind = row.attachment_kind;
+ attachment.durationMs = toNullableNumber(row.attachment_duration_ms) || 0;
+ if (row.attachment_kind === "voice") {
+ attachment.waveform = JSON.parse(row.attachment_waveform || "[]");
+ }
+ }
+ return attachment;
+}
+
export function mapMessage(row, content = row.content) {
const isExternal = row.sender_kind === "external";
const isTelegramExternal = isExternal && row.source === "telegram";
@@ -37,15 +56,7 @@ export function mapMessage(row, content = row.content) {
: "",
source: isExternal ? row.source : "edgechat",
},
- attachment: row.attachment_key
- ? {
- key: row.attachment_key,
- name: row.attachment_name,
- type: row.attachment_type,
- size: toNullableNumber(row.attachment_size) || 0,
- url: publicFileUrl(row.attachment_key),
- }
- : null,
+ attachment: mapAttachment(row),
};
if (row.client_message_id) {
message.clientMessageId = row.client_message_id;
@@ -80,8 +91,9 @@ async function mapDecryptedMessage(env, row) {
}
const MESSAGE_SELECT = `SELECT
- m.id, m.channel_id, m.content, m.attachment_key, m.attachment_name, m.attachment_type,
- m.attachment_size, m.sender_kind, m.external_sender_id, m.external_sender_name,
+ m.id, m.channel_id, m.content, m.attachment_key, m.attachment_name, m.attachment_type,
+ m.attachment_size, m.attachment_kind, m.attachment_duration_ms, m.attachment_waveform,
+ m.sender_kind, m.external_sender_id, m.external_sender_name,
m.external_sender_avatar_url, m.source, m.source_message_id,
m.source_attachment_id, m.source_attachment_unique_id, m.client_message_id,
m.mention_user_ids, m.created_at,
@@ -312,24 +324,32 @@ async function persistMessage(env, {
);
try {
const result = await env.DB
- .prepare(
- `INSERT INTO messages (
- channel_id, sender_id, content, attachment_key, attachment_name,
- attachment_type, attachment_size, sender_kind, external_sender_id,
- external_sender_name, external_sender_avatar_url, source, source_message_id,
- source_attachment_id, source_attachment_unique_id, client_message_id,
- mention_user_ids
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
+ .prepare(
+ `INSERT INTO messages (
+ channel_id, sender_id, content, attachment_key, attachment_name,
+ attachment_type, attachment_size, attachment_kind, attachment_duration_ms,
+ attachment_waveform, sender_kind, external_sender_id,
+ external_sender_name, external_sender_avatar_url, source, source_message_id,
+ source_attachment_id, source_attachment_unique_id, client_message_id,
+ mention_user_ids
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
.bind(
Number(channelId),
normalizedSenderId,
storedContent,
cleanAttachment?.key || null,
cleanAttachment?.name || null,
- cleanAttachment?.type || null,
- cleanAttachment?.size || null,
- isExternal ? "external" : "local",
+ cleanAttachment?.type || null,
+ cleanAttachment?.size || null,
+ cleanAttachment?.kind || null,
+ cleanAttachment?.kind === "voice" || cleanAttachment?.kind === "audio"
+ ? cleanAttachment.durationMs
+ : null,
+ cleanAttachment?.kind === "voice"
+ ? JSON.stringify(cleanAttachment.waveform)
+ : null,
+ isExternal ? "external" : "local",
isExternal ? externalId : null,
isExternal ? externalName : null,
isExternal ? String(externalSender.avatarUrl || "") : null,
diff --git a/worker/src/integrations/telegram/bridge.js b/worker/src/integrations/telegram/bridge.js
index d457b94e..c2633e97 100644
--- a/worker/src/integrations/telegram/bridge.js
+++ b/worker/src/integrations/telegram/bridge.js
@@ -50,9 +50,11 @@ export function splitTelegramFormattedMessage(displayName, content, limit) {
return chunks;
}
-function telegramMediaKind(contentType) {
+function telegramMediaKind(contentType, attachmentKind) {
+ if (attachmentKind === "voice") return "voice";
if (contentType.startsWith("image/")) return "photo";
if (contentType.startsWith("video/")) return "video";
+ if (contentType.startsWith("audio/")) return "audio";
return "document";
}
@@ -88,11 +90,12 @@ async function sendMessageToTelegram(env, botToken, mapping, message) {
const captions = splitTelegramFormattedMessage(displayName, message.content, 1024);
await sendTelegramMedia(botToken, {
chatId: mapping.telegramChatId,
- kind: telegramMediaKind(file.type),
+ kind: telegramMediaKind(file.type, file.kind),
bytes: file.bytes,
filename: file.name,
contentType: file.type,
caption: captions[0],
+ durationMs: file.durationMs,
});
for (const chunk of captions.slice(1)) {
await sendTelegramText(botToken, { chatId: mapping.telegramChatId, text: chunk });
diff --git a/worker/src/integrations/telegram/client.js b/worker/src/integrations/telegram/client.js
index 6125a18b..5b74e4bb 100644
--- a/worker/src/integrations/telegram/client.js
+++ b/worker/src/integrations/telegram/client.js
@@ -111,10 +111,13 @@ export function sendTelegramMedia(botToken, {
filename,
contentType,
caption,
+ durationMs = 0,
}) {
const methods = {
photo: ["sendPhoto", "photo"],
video: ["sendVideo", "video"],
+ voice: ["sendVoice", "voice"],
+ audio: ["sendAudio", "audio"],
document: ["sendDocument", "document"],
};
const [method, field] = methods[kind] || methods.document;
@@ -122,6 +125,9 @@ export function sendTelegramMedia(botToken, {
formData.set("chat_id", String(chatId));
formData.set("parse_mode", "HTML");
if (caption) formData.set("caption", String(caption));
+ if (durationMs > 0 && (kind === "voice" || kind === "audio")) {
+ formData.set("duration", String(Math.round(durationMs / 1000)));
+ }
formData.set(field, new Blob([bytes], { type: contentType }), filename);
return callTelegramMultipartApi(botToken, method, formData);
}
diff --git a/worker/src/integrations/telegram/files.js b/worker/src/integrations/telegram/files.js
index ab87280f..c0186efe 100644
--- a/worker/src/integrations/telegram/files.js
+++ b/worker/src/integrations/telegram/files.js
@@ -56,7 +56,19 @@ export async function importTelegramAttachment(env, {
customMetadata: { filename: name, edgechatEncryption: "v1", source: "telegram" },
});
return {
- attachment: { key, name, type, size: bytes.byteLength },
+ attachment: {
+ key,
+ name,
+ type,
+ size: bytes.byteLength,
+ ...(attachment.kind === "voice" || attachment.kind === "audio"
+ ? {
+ kind: attachment.kind,
+ durationMs: attachment.durationMs || 0,
+ ...(attachment.kind === "voice" ? { waveform: [] } : {}),
+ }
+ : {}),
+ },
skipReason: null,
};
}
@@ -86,9 +98,11 @@ export async function loadEdgeChatAttachment(env, attachment) {
file: {
bytes: decrypted.bytes,
name: sanitizeFilename(attachment.name),
- type: normalizeContentType(attachment.type) || "application/octet-stream",
- size: decrypted.bytes.byteLength,
- },
+ type: normalizeContentType(attachment.type) || "application/octet-stream",
+ size: decrypted.bytes.byteLength,
+ kind: attachment.kind,
+ durationMs: Number(attachment.durationMs || 0),
+ },
skipReason: null,
};
}
diff --git a/worker/src/integrations/telegram/parser.js b/worker/src/integrations/telegram/parser.js
index fe8e9a31..b30c55f3 100644
--- a/worker/src/integrations/telegram/parser.js
+++ b/worker/src/integrations/telegram/parser.js
@@ -25,6 +25,28 @@ function parseAttachment(message) {
fileSize: Number(message.video.file_size || 0),
};
}
+ if (message.voice?.file_id) {
+ return {
+ kind: "voice",
+ fileId: String(message.voice.file_id),
+ fileUniqueId: String(message.voice.file_unique_id || ""),
+ fileName: `voice-${message.message_id}.ogg`,
+ mimeType: message.voice.mime_type || "audio/ogg",
+ fileSize: Number(message.voice.file_size || 0),
+ durationMs: Number(message.voice.duration || 0) * 1000,
+ };
+ }
+ if (message.audio?.file_id) {
+ return {
+ kind: "audio",
+ fileId: String(message.audio.file_id),
+ fileUniqueId: String(message.audio.file_unique_id || ""),
+ fileName: message.audio.file_name || `audio-${message.message_id}.mp3`,
+ mimeType: message.audio.mime_type || "audio/mpeg",
+ fileSize: Number(message.audio.file_size || 0),
+ durationMs: Number(message.audio.duration || 0) * 1000,
+ };
+ }
if (message.document?.file_id) {
return {
kind: "document",
diff --git a/worker/src/utils.js b/worker/src/utils.js
index d1dbe545..4e5cf0f8 100644
--- a/worker/src/utils.js
+++ b/worker/src/utils.js
@@ -1,3 +1,5 @@
+import { normalizeAudioAttachmentMetadata } from "./attachment-metadata.js";
+
export function jsonResponse(data, init = {}) {
return new Response(JSON.stringify(data), {
...init,
@@ -68,13 +70,15 @@ export function pickAttachment(payload, options = {}) {
return null;
}
- return {
- key,
- name: String(payload.name),
- type: String(payload.type),
- size: Number(payload.size) || 0,
- url: `/files/${encodeURIComponent(key)}`
- };
+ const type = String(payload.type);
+ return {
+ key,
+ name: String(payload.name),
+ type,
+ size: Number(payload.size) || 0,
+ url: `/files/${encodeURIComponent(key)}`,
+ ...normalizeAudioAttachmentMetadata(payload, type),
+ };
}
export function publicFileUrl(key) {
diff --git a/wrangler.example.toml b/wrangler.example.toml
index b5aa9c2f..e8dc1a1b 100644
--- a/wrangler.example.toml
+++ b/wrangler.example.toml
@@ -11,7 +11,7 @@ SOFT_DELETE_RETENTION_DAYS = "60"
GC_BATCH_SIZE = "500"
GC_MAX_BATCHES_PER_RUN = "20"
R2_DELETE_MAX_RETRY = "8"
-ALLOWED_FILE_TYPES = "image/,video/,application/pdf,text/"
+ALLOWED_FILE_TYPES = "image/,video/,audio/,application/pdf,text/"
MAX_FILE_SIZE = "20971520"
[[d1_databases]]