This commit is contained in:
Your Name
2026-11-09 11:56:28 +08:00
parent 839166524f
commit 01a46ee06f
17 changed files with 1552 additions and 31 deletions
+98 -3
View File
@@ -1,5 +1,7 @@
import request from '@/utils/request'
export type MobileRecordingUploadState = 'not_uploaded' | 'uploading' | 'partial' | 'complete'
export interface MobileRecordingMetadata {
id: number
diagnosis_id: number
@@ -7,9 +9,12 @@ export interface MobileRecordingMetadata {
recorded_at: number
duration_ms: number
bound_by: string
playback_location: 'original_device'
playback_location: string
created_at: number
updated_at: number
audio_available?: boolean
transcript_available?: boolean
upload_state?: MobileRecordingUploadState
}
export interface MobileRecordingPage {
@@ -19,10 +24,100 @@ export interface MobileRecordingPage {
page_size: number
}
export interface MobileRecordingTranscript {
text: string
sha256: string
size_bytes: number
}
interface Envelope<T> { code: number; msg?: string; data: T }
export class MobileRecordingMediaError extends Error {
constructor(message: string, public readonly code = 0) {
super(message)
this.name = 'MobileRecordingMediaError'
}
}
const requestOptions = { withToken: true, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 }
const mediaOptions = { ...requestOptions, isTransformResponse: false }
const audioExtensions: Record<string, string> = {
'audio/wav': 'wav', 'audio/x-wav': 'wav', 'audio/wave': 'wav',
'audio/flac': 'flac', 'audio/x-flac': 'flac', 'audio/ogg': 'ogg',
'audio/mpeg': 'mp3', 'audio/mp4': 'm4a', 'audio/amr': 'amr'
}
function checkSignal(signal?: AbortSignal) {
if (signal?.aborted) throw new DOMException('请求已取消', 'AbortError')
}
function unwrap<T>(response: Envelope<T>): T {
if (!response || response.code !== 1) {
const code = Number(response?.code) || 0
const message = code === -1 ? '登录已失效,请重新登录后查看。'
: code === 10 ? '请先完成企业微信绑定后查看。'
: (typeof response?.msg === 'string' ? response.msg.slice(0, 160) : '') || '无法读取内容,请确认患者权限后重试。'
throw new MobileRecordingMediaError(message, code)
}
return response.data
}
function mediaParams(bindingId: number, diagnosisId: number) {
if (!Number.isSafeInteger(bindingId) || bindingId <= 0 || !Number.isSafeInteger(diagnosisId) || diagnosisId <= 0) {
throw new MobileRecordingMediaError('录音关联标识无效,请刷新列表。')
}
return { binding_id: bindingId, diagnosis_id: diagnosisId }
}
export function mobileRecordingPatientLists(params: {
diagnosis_id: number
page_no: number
page_size: number
}): Promise<MobileRecordingPage> {
return request.get({ url: '/tcm.mobileRecording/patientLists', params })
}, signal?: AbortSignal): Promise<MobileRecordingPage> {
return request.get({ url: '/tcm.mobileRecording/patientLists', params, signal }, requestOptions)
}
/** Existing request hooks attach the current token header; neither the media URL nor Blob URL contains it. */
export async function mobileRecordingAudio(bindingId: number, diagnosisId: number, signal?: AbortSignal,
onProgress?: (loaded: number, total?: number) => void): Promise<Blob> {
checkSignal(signal)
const blob = await request.get<Blob>({
url: '/tcm.mobileRecordingMedia/audio', params: mediaParams(bindingId, diagnosisId),
responseType: 'blob', signal, timeout: 300000,
onDownloadProgress: event => onProgress?.(event.loaded, event.total)
}, mediaOptions)
checkSignal(signal)
if (!(blob instanceof Blob)) throw new MobileRecordingMediaError('音频响应格式不正确,请重试。')
const mime = blob.type.toLowerCase().split(';')[0].trim()
if (mime.includes('json')) {
let response: Envelope<unknown>
try { response = JSON.parse(await blob.text()) }
catch { throw new MobileRecordingMediaError('音频响应格式不正确,请重试。') }
checkSignal(signal)
unwrap(response)
throw new MobileRecordingMediaError('服务器未返回可播放的音频,请刷新列表。')
}
if (!audioExtensions[mime] || blob.size <= 0 || blob.size > 512 * 1024 * 1024) {
throw new MobileRecordingMediaError('音频格式或大小不符合要求,请重新上传后查看。')
}
return blob
}
export async function mobileRecordingTranscript(bindingId: number, diagnosisId: number, signal?: AbortSignal): Promise<MobileRecordingTranscript> {
checkSignal(signal)
const response = await request.get<Envelope<MobileRecordingTranscript>>({
url: '/tcm.mobileRecordingMedia/transcript', params: mediaParams(bindingId, diagnosisId), signal, timeout: 120000
}, mediaOptions)
checkSignal(signal)
const result = unwrap(response)
if (!result || typeof result.text !== 'string' || !Number.isSafeInteger(result.size_bytes)
|| result.size_bytes < 0 || result.size_bytes > 8 * 1024 * 1024) {
throw new MobileRecordingMediaError('文字响应格式不正确,请重试。')
}
return result
}
export function mobileRecordingDownloadName(bindingId: number, kind: 'audio' | 'transcript', mime = ''): string {
const id = Number.isSafeInteger(bindingId) && bindingId > 0 ? bindingId : 0
const extension = kind === 'transcript' ? 'txt' : audioExtensions[mime.toLowerCase().split(';')[0].trim()] || 'audio'
return `${kind === 'audio' ? 'recording' : 'transcript'}-${id}.${extension}`
}
@@ -1,23 +1,36 @@
<template>
<div class="mobile-recording-panel">
<div class="panel-toolbar">
<span>仅同步关联信息;音频和转写保存在原手机,请在原手机播放。</span>
<span>已上传的录音和文字可在此查看;未上传的内容仍保存在原手机。</span>
<el-button :loading="loading" @click="load">刷新</el-button>
</div>
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
<el-table v-loading="loading" :data="rows" border stripe empty-text="暂无手机录音关联">
<el-table-column label="来源" width="140">
<el-table-column label="来源" width="130">
<template #default>安卓手机录音</template>
</el-table-column>
<el-table-column label="录音时间(北京时间)" min-width="190">
<template #default="{ row }">{{ recordedTime(row.recorded_at) }}</template>
</el-table-column>
<el-table-column label="时长" width="120">
<el-table-column label="时长" width="100">
<template #default="{ row }">{{ durationText(row.duration_ms) }}</template>
</el-table-column>
<el-table-column label="绑定账号" prop="bound_by" min-width="130" />
<el-table-column label="播放位置" min-width="170">
<template #default>仅原手机可播放</template>
<el-table-column label="绑定账号" prop="bound_by" min-width="120" />
<el-table-column label="上传状态" min-width="130">
<template #default="{ row }">
<el-tag :type="uploadStatus(row).type" effect="light">{{ uploadStatus(row).label }}</el-tag>
</template>
</el-table-column>
<el-table-column label="录音与文字" min-width="220">
<template #default="{ row }">
<div class="media-actions">
<el-button v-if="row.audio_available === true" link type="primary" @click="openMedia(row, 'audio')">播放录音</el-button>
<el-button v-if="row.transcript_available === true" link type="primary" @click="openMedia(row, 'transcript')">查看文字</el-button>
<span v-if="!row.audio_available && !row.transcript_available" class="muted">{{ row.upload_state === 'uploading' ? '上传后刷新查看' : '请在原手机上传' }}</span>
<span v-else-if="!row.audio_available" class="muted">录音待上传</span>
<span v-else-if="!row.transcript_available" class="muted">文字待上传</span>
</div>
</template>
</el-table-column>
</el-table>
<el-pagination
@@ -28,12 +41,48 @@
layout="total, prev, pager, next"
@current-change="load"
/>
<el-drawer :model-value="mediaVisible" :title="mediaKind === 'audio' ? '手机录音' : '转写文字'"
size="min(680px, 100vw)" append-to-body destroy-on-close
@update:model-value="onMediaVisibility" @close="closeMedia">
<div class="media-detail">
<div v-if="mediaRow" class="media-meta">
<span>{{ recordedTime(mediaRow.recorded_at) }}(北京时间)</span>
<span>{{ durationText(mediaRow.duration_ms) }} · {{ mediaRow.bound_by }}</span>
</div>
<div v-if="mediaLoading" class="media-loading" role="status" aria-live="polite">
<p>{{ mediaKind === 'audio' ? '正在下载音频,完成后即可播放。大文件可能需要一些时间。' : '正在读取转写文字…' }}</p>
<el-progress :percentage="downloadPercent" :indeterminate="!downloadTotal" :show-text="!!downloadTotal" />
<span v-if="mediaKind === 'audio'" class="muted">{{ downloadProgressText }}</span>
<el-button @click="closeMedia">取消并关闭</el-button>
</div>
<template v-else-if="mediaError">
<el-alert :title="mediaError" type="error" :closable="false" show-icon />
<el-button @click="loadMedia">重新读取</el-button>
</template>
<template v-else-if="mediaReady">
<template v-if="mediaKind === 'audio'">
<audio ref="audioElement" class="audio-player" :src="mediaUrl" controls preload="metadata"
@error="playbackError = '浏览器无法播放此格式,可下载后使用播放器打开。'" />
<el-alert v-if="playbackError" :title="playbackError" type="info" :closable="false" show-icon />
</template>
<template v-else>
<pre v-if="transcriptText.length" class="transcript-text">{{ transcriptText }}</pre>
<el-empty v-else description="已上传的转写文字为空" />
</template>
<a v-if="mediaUrl" class="media-download" :href="mediaUrl" :download="mediaFilename">{{ mediaKind === 'audio' ? '下载录音' : '下载文字' }}</a>
</template>
</div>
</el-drawer>
</div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { mobileRecordingPatientLists, type MobileRecordingMetadata } from '@/api/mobileRecording'
import { computed, onActivated, onBeforeUnmount, onDeactivated, ref, watch } from 'vue'
import {
mobileRecordingAudio, mobileRecordingDownloadName, mobileRecordingPatientLists, mobileRecordingTranscript,
MobileRecordingMediaError, type MobileRecordingMetadata
} from '@/api/mobileRecording'
const props = defineProps<{ diagnosisId: number }>()
const rows = ref<MobileRecordingMetadata[]>([])
@@ -43,10 +92,29 @@ const page = ref(1)
const pageSize = 20
const total = ref(0)
let generation = 0
let listController: AbortController | null = null
let suspended = false
const mediaVisible = ref(false)
const mediaKind = ref<'audio' | 'transcript'>('audio')
const mediaRow = ref<MobileRecordingMetadata | null>(null)
const mediaLoading = ref(false)
const mediaReady = ref(false)
const mediaError = ref('')
const mediaUrl = ref('')
const mediaFilename = ref('')
const transcriptText = ref('')
const playbackError = ref('')
const audioElement = ref<HTMLAudioElement | null>(null)
const downloadLoaded = ref(0)
const downloadTotal = ref(0)
let mediaGeneration = 0
let mediaController: AbortController | null = null
const downloadPercent = computed(() => downloadTotal.value > 0 ? Math.min(100, Math.floor(downloadLoaded.value / downloadTotal.value * 100)) : 0)
const downloadProgressText = computed(() => `已下载 ${sizeText(downloadLoaded.value)}${downloadTotal.value > 0 ? ` / ${sizeText(downloadTotal.value)}` : ''}`)
const timeFormatter = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric', month: '2-digit', day: '2-digit',
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
})
function recordedTime(value: number): string {
@@ -60,14 +128,106 @@ function durationText(value: number): string {
const remaining = String(seconds % 60).padStart(2, '0')
return hours ? hours + ':' + String(minutes).padStart(2, '0') + ':' + remaining : minutes + ':' + remaining
}
function sizeText(bytes: number): string {
return bytes >= 1024 * 1024 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB` : `${Math.ceil(bytes / 1024)} KB`
}
function uploadStatus(row: MobileRecordingMetadata): { label: string; type: 'info' | 'primary' | 'warning' | 'success' } {
switch (row.upload_state) {
case 'uploading': return { label: '上传中', type: 'primary' }
case 'partial': return { label: '部分已上传', type: 'warning' }
case 'complete': return { label: '上传完成', type: 'success' }
default: return { label: '未上传', type: 'info' }
}
}
function clearMediaContent() {
try {
audioElement.value?.pause()
audioElement.value?.removeAttribute('src')
audioElement.value?.load()
} catch { /* Revoke and clear content even if the player is already detached. */ }
if (mediaUrl.value) URL.revokeObjectURL(mediaUrl.value)
mediaUrl.value = ''
mediaFilename.value = ''
transcriptText.value = ''
playbackError.value = ''
mediaReady.value = false
downloadLoaded.value = 0
downloadTotal.value = 0
}
function closeMedia() {
mediaGeneration++
mediaController?.abort()
mediaController = null
clearMediaContent()
mediaVisible.value = false
mediaRow.value = null
mediaLoading.value = false
mediaError.value = ''
}
function onMediaVisibility(visible: boolean) { if (!visible) closeMedia() }
function openMedia(row: MobileRecordingMetadata, kind: 'audio' | 'transcript') {
closeMedia()
if (suspended || row.diagnosis_id !== props.diagnosisId || !rows.value.some(item => item.id === row.id)
|| (kind === 'audio' ? row.audio_available !== true : row.transcript_available !== true)) return
mediaRow.value = { ...row }
mediaKind.value = kind
mediaVisible.value = true
void loadMedia()
}
async function loadMedia() {
const row = mediaRow.value
if (!row || !mediaVisible.value || suspended || row.diagnosis_id !== props.diagnosisId) return
const ticket = ++mediaGeneration
mediaController?.abort()
const controller = new AbortController()
mediaController = controller
const diagnosisId = props.diagnosisId
const kind = mediaKind.value
const current = () => ticket === mediaGeneration && !controller.signal.aborted && !suspended
&& mediaVisible.value && diagnosisId === props.diagnosisId && mediaRow.value?.id === row.id
clearMediaContent()
mediaError.value = ''
mediaLoading.value = true
try {
if (kind === 'audio') {
const blob = await mobileRecordingAudio(row.id, diagnosisId, controller.signal, (loaded, size) => {
if (!current()) return
downloadLoaded.value = Math.max(0, loaded)
downloadTotal.value = size && size > 0 ? size : 0
})
if (!current()) return
mediaUrl.value = URL.createObjectURL(blob)
mediaFilename.value = mobileRecordingDownloadName(row.id, 'audio', blob.type)
} else {
const result = await mobileRecordingTranscript(row.id, diagnosisId, controller.signal)
if (!current()) return
transcriptText.value = result.text
mediaUrl.value = URL.createObjectURL(new Blob([result.text], { type: 'text/plain;charset=utf-8' }))
mediaFilename.value = mobileRecordingDownloadName(row.id, 'transcript')
}
mediaReady.value = true
} catch (failure) {
if (!current()) return
clearMediaContent()
mediaError.value = failure instanceof MobileRecordingMediaError ? failure.message : '读取失败,请确认网络和患者权限后重试。'
} finally {
if (current()) mediaLoading.value = false
}
}
async function load() {
const requestId = ++generation
listController?.abort()
closeMedia()
const controller = new AbortController()
listController = controller
const diagnosisId = props.diagnosisId
const requestedPage = page.value
error.value = ''
rows.value = []
total.value = 0
if (!Number.isInteger(diagnosisId) || diagnosisId <= 0) {
if (suspended || !Number.isInteger(diagnosisId) || diagnosisId <= 0) {
loading.value = false
return
}
@@ -75,8 +235,8 @@ async function load() {
try {
const result = await mobileRecordingPatientLists({
diagnosis_id: diagnosisId, page_no: requestedPage, page_size: pageSize
})
if (requestId !== generation || diagnosisId !== props.diagnosisId) return
}, controller.signal)
if (requestId !== generation || controller.signal.aborted || diagnosisId !== props.diagnosisId) return
const lastPage = Math.max(1, Math.ceil(result.count / pageSize))
if (requestedPage > lastPage) {
page.value = lastPage
@@ -86,17 +246,39 @@ async function load() {
rows.value = result.lists
total.value = result.count
} catch {
if (requestId === generation) error.value = '无法读取手机录音关联,请确认患者权限后重试。'
if (requestId === generation && !controller.signal.aborted) error.value = '无法读取手机录音关联,请确认患者权限后重试。'
} finally {
if (requestId === generation) loading.value = false
}
}
watch(() => props.diagnosisId, () => { page.value = 1; void load() }, { immediate: true })
onBeforeUnmount(() => { generation++ })
function stop() {
generation++
listController?.abort()
listController = null
closeMedia()
rows.value = []
total.value = 0
loading.value = false
}
watch(() => props.diagnosisId, () => { page.value = 1; void load() }, { immediate: true, flush: 'sync' })
onDeactivated(() => { suspended = true; stop() })
onActivated(() => { if (suspended) { suspended = false; void load() } })
onBeforeUnmount(() => { suspended = true; stop() })
</script>
<style scoped>
.mobile-recording-panel { display: flex; flex-direction: column; gap: 12px; }
.panel-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: #606266; }
.mobile-recording-panel, .media-detail { display: flex; flex-direction: column; gap: 16px; }
.panel-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: #606266; line-height: 1.7; }
.panel-toolbar .el-button { flex-shrink: 0; }
.media-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.media-actions .el-button { margin-left: 0; }
.muted { color: #909399; font-size: 12px; }
.media-meta { display: flex; flex-direction: column; gap: 6px; padding: 14px 16px; background: #f7f9fc; border-radius: 10px; color: #606266; font-size: 13px; }
.media-loading { display: flex; flex-direction: column; gap: 14px; padding: 20px 0; color: #606266; }
.media-loading .el-button, .media-detail > .el-button { align-self: flex-start; }
.audio-player { width: 100%; }
.transcript-text { margin: 0; padding: 16px; max-height: 65vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; line-height: 1.9; color: #303133; background: #fafbfc; border: 1px solid #ebeef5; border-radius: 10px; }
.media-download { align-self: flex-start; color: var(--el-color-primary); text-decoration: none; padding: 6px 0; }
.media-download:hover { text-decoration: underline; }
.el-pagination { justify-content: flex-end; }
</style>