更新
This commit is contained in:
@@ -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>
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
'use strict'
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const { createRequire } = require('node:module')
|
||||
const root = path.resolve(process.env.MOBILE_RECORDING_ADMIN_ROOT || path.join(__dirname, '..'))
|
||||
const sourceRoot = path.resolve(process.env.MOBILE_RECORDING_SOURCE_ROOT || root)
|
||||
const requireAdmin = createRequire(path.join(root, 'package.json'))
|
||||
const vue = requireAdmin('vue')
|
||||
const ts = requireAdmin('typescript')
|
||||
const sfc = requireAdmin('@vue/compiler-sfc')
|
||||
const apiSource = fs.readFileSync(path.join(sourceRoot, 'src/api/mobileRecording.ts'), 'utf8')
|
||||
const filename = path.join(sourceRoot, 'src/views/tcm/diagnosis/components/MobileRecordingPanel.vue')
|
||||
const parsed = sfc.parse(fs.readFileSync(filename, 'utf8'), { filename })
|
||||
assert.deepEqual(parsed.errors, [])
|
||||
const script = sfc.compileScript(parsed.descriptor, { id: 'mobile-media-test' })
|
||||
const template = sfc.compileTemplate({ source: parsed.descriptor.template.content, filename, id: 'mobile-media-test', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
for (const style of parsed.descriptor.styles) assert.deepEqual(sfc.compileStyle({ source: style.content, filename, id: 'mobile-media-test', scoped: true }).errors, [])
|
||||
|
||||
function execute(source, dependencies, globals = {}) {
|
||||
const output = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const module = { exports: {} }
|
||||
new Function('require', 'module', 'exports', ...Object.keys(globals), output)(dependencies, module, module.exports, ...Object.values(globals))
|
||||
return module.exports
|
||||
}
|
||||
function apiWith(get) { return execute(apiSource, name => { assert.equal(name, '@/utils/request'); return { default: { get } } }) }
|
||||
const apiTypes = apiWith(() => { throw new Error('Unexpected live API call') })
|
||||
const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
const flush = async () => { for (let i = 0; i < 12; i++) { await Promise.resolve(); await vue.nextTick() } }
|
||||
const row = (id = 1, diagnosisId = 101, extra = {}) => ({ id, diagnosis_id: diagnosisId, source_platform: 'android_bcr', recorded_at: 1700000000000, duration_ms: 12000, bound_by: '合成账号', playback_location: 'original_device', created_at: 1, updated_at: 1, ...extra })
|
||||
const page = (lists, total = lists.length) => ({ lists, count: total, page_no: 1, page_size: 20 })
|
||||
function fixture(overrides = {}, options = {}) {
|
||||
const calls = [], created = [], revoked = [], roots = [], hooks = {}
|
||||
const deps = {
|
||||
...apiTypes,
|
||||
mobileRecordingPatientLists: async (params, signal) => { calls.push(['list', params, signal]); return page([row(1, params.diagnosis_id, { audio_available: true, transcript_available: true, upload_state: 'complete' })]) },
|
||||
mobileRecordingAudio: async (id, diagnosisId, signal, progress) => { calls.push(['audio', id, diagnosisId, signal]); progress(8, 8); return new Blob(['synthetic'], { type: 'audio/wav' }) },
|
||||
mobileRecordingTranscript: async (id, diagnosisId, signal) => { calls.push(['text', id, diagnosisId, signal]); return { text: '合成转写', sha256: 'a'.repeat(64), size_bytes: 12 } },
|
||||
...overrides
|
||||
}
|
||||
const component = execute(script.content, name => {
|
||||
if (name === 'vue') return { ...vue, onDeactivated: callback => { hooks.deactivate = callback }, onActivated: callback => { hooks.activate = callback } }
|
||||
if (name === '@/api/mobileRecording') return deps
|
||||
throw new Error('Unexpected dependency: ' + name)
|
||||
}, { URL: { createObjectURL: blob => { const url = `blob:synthetic-${created.length}`; created.push({ url, blob }); return url }, revokeObjectURL: url => revoked.push(url) } }).default
|
||||
component.render = options.render ? execute(template.code, name => { assert.equal(name, 'vue'); return vue }).render : () => null
|
||||
const renderer = vue.createRenderer({
|
||||
createElement: tag => ({ tag, children: [], props: {}, pause() { this.paused = true }, removeAttribute(name) { delete this.props[name] }, load() { this.reloaded = true } }),
|
||||
createText: text => ({ text }), createComment: text => ({ comment: text }),
|
||||
setText: (node, text) => { node.text = text }, setElementText: (node, text) => { node.text = text; node.children = [] },
|
||||
patchProp: (node, name, prev, next) => { node.props[name] = next },
|
||||
parentNode: node => node.parent || null, nextSibling: () => null,
|
||||
insert(node, parent) { node.parent = parent; (parent.children ||= []).push(node) },
|
||||
remove(node) { if (node.parent) node.parent.children = node.parent.children.filter(child => child !== node) }
|
||||
})
|
||||
const props = vue.reactive({ diagnosisId: 101 })
|
||||
const app = renderer.createApp({ setup: () => () => vue.h(component, props) })
|
||||
const slotComponent = vue.defineComponent({ setup: (_, { slots }) => () => vue.h('div', slots.default?.()) })
|
||||
for (const name of ['ElButton', 'ElAlert', 'ElProgress', 'ElEmpty', 'ElTag', 'ElPagination', 'ElTableColumn']) app.component(name, slotComponent)
|
||||
app.component('ElTable', { render: () => null })
|
||||
app.component('ElDrawer', { props: ['modelValue'], setup: (p, { slots }) => () => p.modelValue ? vue.h('section', slots.default?.()) : null })
|
||||
app.directive('loading', {})
|
||||
const rootNode = { tag: 'root', children: [] }; roots.push(rootNode); app.mount(rootNode)
|
||||
return { state: app._instance.subTree.component.setupState, props, calls, created, revoked, roots, hooks, dispose: () => app.unmount() }
|
||||
}
|
||||
function findNodes(node, tag, found = []) { if (node.tag === tag) found.push(node); for (const child of node.children || []) findNodes(child, tag, found); return found }
|
||||
|
||||
test('audio uses existing authenticated request, fixed endpoint, diagnosis anchor, cancellable blob and long timeout', async () => {
|
||||
const calls = []; const controller = new AbortController(); const progress = []
|
||||
const api = apiWith(async (config, options) => { calls.push([config, options]); config.onDownloadProgress({ loaded: 6, total: 12 }); return new Blob(['audio'], { type: 'audio/wav' }) })
|
||||
const blob = await api.mobileRecordingAudio(7, 101, controller.signal, (...values) => progress.push(values))
|
||||
assert.equal(blob.type, 'audio/wav'); assert.deepEqual(progress, [[6, 12]])
|
||||
const [config, options] = calls[0]
|
||||
assert.equal(config.url, '/tcm.mobileRecordingMedia/audio'); assert.deepEqual(config.params, { binding_id: 7, diagnosis_id: 101 })
|
||||
assert.equal(config.responseType, 'blob'); assert.equal(config.signal, controller.signal); assert.equal(config.timeout, 300000)
|
||||
assert.equal(options.withToken, true); assert.equal(options.isOpenRetry, false); assert.equal(options.isTransformResponse, false)
|
||||
assert.equal(config.url.includes('token'), false); assert.equal('token' in config.params, false)
|
||||
})
|
||||
|
||||
test('HTTP 200 JSON denial or non-audio payload never becomes a playable blob', async () => {
|
||||
for (const code of [0, -1, 10]) {
|
||||
const api = apiWith(async () => new Blob([JSON.stringify({ code, msg: '合成权限拒绝', data: [] })], { type: 'application/json' }))
|
||||
await assert.rejects(api.mobileRecordingAudio(1, 101), error => error instanceof api.MobileRecordingMediaError && error.code === code)
|
||||
}
|
||||
for (const blob of [new Blob(['<html>login</html>'], { type: 'text/html' }), new Blob([], { type: 'audio/wav' }), new Blob(['{}'], { type: 'application/json' })]) {
|
||||
const api = apiWith(async () => blob); await assert.rejects(api.mobileRecordingAudio(1, 101), api.MobileRecordingMediaError)
|
||||
}
|
||||
})
|
||||
|
||||
test('aborted audio is rejected even when the request resolves late; no request starts with an aborted signal', async () => {
|
||||
let calls = 0; const wait = deferred(); const controller = new AbortController()
|
||||
const api = apiWith(async () => { calls++; return wait.promise })
|
||||
const pending = api.mobileRecordingAudio(1, 101, controller.signal); controller.abort(); wait.resolve(new Blob(['audio'], { type: 'audio/wav' }))
|
||||
await assert.rejects(pending, error => error.name === 'AbortError')
|
||||
await assert.rejects(api.mobileRecordingAudio(1, 101, controller.signal), error => error.name === 'AbortError')
|
||||
assert.equal(calls, 1)
|
||||
})
|
||||
|
||||
test('transcript reads envelope, keeps plain text including empty, rejects permission and malformed success', async () => {
|
||||
const text = '<img src=x onerror=alert(1)>\n纯文本'
|
||||
for (const value of [text, '']) {
|
||||
const api = apiWith(async (config, options) => { assert.deepEqual(config.params, { binding_id: 1, diagnosis_id: 101 }); assert.equal(options.withToken, true); return { code: 1, data: { text: value, sha256: 'a'.repeat(64), size_bytes: value.length } } })
|
||||
assert.equal((await api.mobileRecordingTranscript(1, 101)).text, value)
|
||||
}
|
||||
for (const response of [{ code: 0, msg: '无权读取', data: [] }, { code: 1, data: {} }, { code: 1, data: { text: 'x', size_bytes: 9 * 1024 * 1024 } }]) {
|
||||
const api = apiWith(async () => response); await assert.rejects(api.mobileRecordingTranscript(1, 101), api.MobileRecordingMediaError)
|
||||
}
|
||||
})
|
||||
|
||||
test('download names only use validated identifiers and allowed extensions', () => {
|
||||
assert.equal(apiTypes.mobileRecordingDownloadName(7, 'audio', 'audio/mpeg'), 'recording-7.mp3')
|
||||
assert.equal(apiTypes.mobileRecordingDownloadName(7, 'transcript'), 'transcript-7.txt')
|
||||
assert.equal(apiTypes.mobileRecordingDownloadName('../private', 'audio', '../../secret'), 'recording-0.audio')
|
||||
})
|
||||
|
||||
test('legacy metadata remains not uploaded; four upload states and media availability stay explicit', async () => {
|
||||
const f = fixture({ mobileRecordingPatientLists: async () => page([row()]) }); await flush()
|
||||
assert.equal(f.state.uploadStatus(row()).label, '未上传')
|
||||
for (const [state, label] of [['not_uploaded', '未上传'], ['uploading', '上传中'], ['partial', '部分已上传'], ['complete', '上传完成']]) assert.equal(f.state.uploadStatus(row(1, 101, { upload_state: state })).label, label)
|
||||
f.state.openMedia(f.state.rows[0], 'audio'); await flush(); assert.equal(f.state.mediaVisible, false); assert.equal(f.created.length, 0)
|
||||
f.dispose()
|
||||
})
|
||||
|
||||
test('successful audio loads progress, uses only a blob URL, and closes with revoke and player stop', async () => {
|
||||
const f = fixture({}, { render: true }); await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
|
||||
assert.equal(f.state.mediaReady, true); assert.equal(f.state.mediaLoading, false); assert.equal(f.state.downloadPercent, 100)
|
||||
assert.equal(f.state.mediaUrl, 'blob:synthetic-0'); assert.equal(f.state.mediaFilename, 'recording-1.wav')
|
||||
const player = f.state.audioElement; assert.ok(player)
|
||||
f.state.closeMedia(); await flush()
|
||||
assert.equal(player.paused, true); assert.equal(player.reloaded, true); assert.deepEqual(f.revoked, ['blob:synthetic-0'])
|
||||
assert.equal(f.state.mediaUrl, ''); assert.equal(f.state.mediaRow, null); f.dispose()
|
||||
})
|
||||
|
||||
test('permission errors clear media content and explicit retry can recover', async () => {
|
||||
let attempt = 0
|
||||
const f = fixture({ mobileRecordingAudio: async () => { if (++attempt === 1) throw new apiTypes.MobileRecordingMediaError('患者不存在或无权操作', 0); return new Blob(['synthetic'], { type: 'audio/wav' }) } })
|
||||
await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
|
||||
assert.match(f.state.mediaError, /无权/); assert.equal(f.created.length, 0); assert.equal(f.state.mediaReady, false)
|
||||
await f.state.loadMedia(); assert.equal(attempt, 2); assert.equal(f.state.mediaError, ''); assert.equal(f.state.mediaReady, true)
|
||||
f.dispose(); assert.equal(f.revoked.length, 1)
|
||||
})
|
||||
|
||||
test('diagnosis switch aborts media and late audio or progress never becomes new-patient content', async () => {
|
||||
const wait = deferred(); let signal, progress
|
||||
const f = fixture({ mobileRecordingAudio: async (_id, diagnosis, s, p) => { assert.equal(diagnosis, 101); signal = s; progress = p; return wait.promise } })
|
||||
await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush(); assert.equal(f.state.mediaLoading, true)
|
||||
f.props.diagnosisId = 202; await flush(); assert.equal(signal.aborted, true); assert.equal(f.state.mediaVisible, false)
|
||||
progress(99, 100); wait.resolve(new Blob(['old'], { type: 'audio/wav' })); await flush()
|
||||
assert.equal(f.created.length, 0); assert.equal(f.state.downloadLoaded, 0); assert.equal(f.state.rows[0].diagnosis_id, 202); f.dispose()
|
||||
})
|
||||
|
||||
test('old transcript cannot overwrite a new selection and text renders as text nodes, never markup', async () => {
|
||||
const wait = deferred(); let firstSignal
|
||||
const raw = '<img src=x onerror=alert(1)>\n<script>unsafe()</script>'
|
||||
const f = fixture({
|
||||
mobileRecordingPatientLists: async () => page([row(1, 101, { transcript_available: true }), row(2, 101, { transcript_available: true })]),
|
||||
mobileRecordingTranscript: async (id, _diagnosis, signal) => { if (id === 1) { firstSignal = signal; return wait.promise }; return { text: raw, size_bytes: raw.length, sha256: 'a'.repeat(64) } }
|
||||
}, { render: true })
|
||||
await flush(); f.state.openMedia(f.state.rows[0], 'transcript'); await flush(); f.state.openMedia(f.state.rows[1], 'transcript'); await flush()
|
||||
assert.equal(firstSignal.aborted, true); assert.equal(f.state.transcriptText, raw)
|
||||
const pre = findNodes(f.roots[0], 'pre'); assert.equal(pre.length, 1); assert.equal(pre[0].text, raw)
|
||||
assert.equal(findNodes(f.roots[0], 'img').length, 0); assert.equal(findNodes(f.roots[0], 'script').length, 0)
|
||||
wait.resolve({ text: '旧患者文字', size_bytes: 12, sha256: 'a'.repeat(64) }); await flush()
|
||||
assert.equal(f.state.transcriptText, raw); assert.equal(f.created.length, 1); assert.equal(f.state.mediaFilename, 'transcript-2.txt')
|
||||
f.dispose(); assert.deepEqual(f.revoked, ['blob:synthetic-0']); assert.equal(f.state.transcriptText, '')
|
||||
})
|
||||
|
||||
test('closing during download and unmount abort requests without retaining stale blobs or text', async () => {
|
||||
for (const finish of ['close', 'unmount']) {
|
||||
const wait = deferred(); let signal
|
||||
const f = fixture({ mobileRecordingTranscript: async (_id, _diagnosis, s) => { signal = s; return wait.promise } })
|
||||
await flush(); f.state.openMedia(f.state.rows[0], 'transcript'); await flush()
|
||||
if (finish === 'close') f.state.closeMedia(); else f.dispose()
|
||||
assert.equal(signal.aborted, true); wait.resolve({ text: 'late', size_bytes: 4, sha256: 'a'.repeat(64) }); await flush()
|
||||
assert.equal(f.created.length, 0); assert.equal(f.state.transcriptText, ''); if (finish === 'close') f.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test('deactivation revokes loaded media and activation reloads only the current diagnosis', async () => {
|
||||
const f = fixture(); await flush(); f.state.openMedia(f.state.rows[0], 'audio'); await flush()
|
||||
f.hooks.deactivate(); assert.deepEqual(f.revoked, ['blob:synthetic-0']); assert.equal(f.state.rows.length, 0)
|
||||
f.props.diagnosisId = 303; await flush(); assert.equal(f.state.rows.length, 0)
|
||||
f.hooks.activate(); await flush(); assert.equal(f.state.rows[0].diagnosis_id, 303); f.dispose()
|
||||
})
|
||||
|
||||
test('list generation cancels old requests and preserves the repaired out-of-range pagination', async () => {
|
||||
let count = 21; const pages = [], signals = []
|
||||
const f = fixture({ mobileRecordingPatientLists: async (params, signal) => {
|
||||
pages.push(params.page_no); signals.push(signal)
|
||||
const start = (params.page_no - 1) * 20
|
||||
return page(Array.from({ length: Math.max(0, Math.min(20, count - start)) }, (_, i) => row(start + i + 1, params.diagnosis_id)), count)
|
||||
} })
|
||||
await flush(); f.state.page = 2; await f.state.load(); assert.equal(f.state.rows.length, 1)
|
||||
count = 20; await f.state.load(); assert.equal(f.state.page, 1); assert.equal(f.state.rows.length, 20); assert.equal(f.state.total, 20)
|
||||
assert.deepEqual(pages, [1, 2, 2, 1]); assert.ok(signals.slice(0, -1).every(signal => signal.aborted))
|
||||
f.dispose(); assert.equal(signals.at(-1).aborted, true)
|
||||
})
|
||||
|
||||
test('late list response after patient switch cannot restore old rows or trigger a correction fetch', async () => {
|
||||
const requests = []
|
||||
const f = fixture({ mobileRecordingPatientLists: (params, signal) => { const wait = deferred(); requests.push({ params, signal, ...wait }); return wait.promise } })
|
||||
assert.equal(requests.length, 1); f.props.diagnosisId = 202; await flush(); assert.equal(requests[0].signal.aborted, true)
|
||||
requests[1].resolve(page([row(2, 202)])); await flush(); requests[0].resolve(page([row(1, 101)])); await flush()
|
||||
assert.equal(f.state.rows[0].diagnosis_id, 202); assert.equal(requests.length, 2); f.dispose()
|
||||
})
|
||||
Reference in New Issue
Block a user