fix:客服上传图片及接受问题修复
This commit is contained in:
@@ -1,11 +1,19 @@
|
||||
import { request } from '@/api/request'
|
||||
import type { ProductOption } from './complete.types'
|
||||
|
||||
/** POST /app/device/productOptions — 获取产品型号下拉列表 */
|
||||
function normalizeProductOption(item: ProductOption): ProductOption {
|
||||
const model = item.model?.trim() || item.name?.trim() || ''
|
||||
return {
|
||||
...item,
|
||||
model,
|
||||
name: item.name?.trim() || model,
|
||||
}
|
||||
}
|
||||
|
||||
/** GET /app/device/productOptions — 获取产品型号下拉列表 */
|
||||
export function fetchProductOptions() {
|
||||
return request<ProductOption[]>({
|
||||
url: '/app/device/productOptions',
|
||||
method: 'POST',
|
||||
data: {},
|
||||
})
|
||||
method: 'GET',
|
||||
}).then((rows) => (Array.isArray(rows) ? rows.map(normalizeProductOption) : []))
|
||||
}
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.complete-page__select-text,
|
||||
.complete-page__room-text {
|
||||
flex: 1;
|
||||
font-size: 28rpx;
|
||||
|
||||
@@ -55,28 +55,23 @@
|
||||
</view>
|
||||
<view class="complete-page__field">
|
||||
<text class="complete-page__label">产品型号</text>
|
||||
<picker
|
||||
mode="selector"
|
||||
:range="productOptions"
|
||||
range-key="model"
|
||||
:value="productIndex"
|
||||
:disabled="productOptionsLoading || !productOptions.length"
|
||||
@change="onProductChange"
|
||||
<view
|
||||
class="complete-page__select-row"
|
||||
hover-class="complete-page__select-row--hover"
|
||||
@tap.stop="onPickProduct"
|
||||
>
|
||||
<view class="complete-page__select-row">
|
||||
<text
|
||||
class="complete-page__select-text"
|
||||
:class="{ 'complete-page__select-text--placeholder': !productSelected }"
|
||||
>
|
||||
{{ productDisplayText }}
|
||||
</text>
|
||||
<image
|
||||
class="complete-page__select-arrow"
|
||||
:src="staticAssets.iconHomeArrow"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</picker>
|
||||
<text
|
||||
class="complete-page__select-text"
|
||||
:class="{ 'complete-page__select-text--placeholder': !productSelected }"
|
||||
>
|
||||
{{ productDisplayText }}
|
||||
</text>
|
||||
<image
|
||||
class="complete-page__select-arrow"
|
||||
:src="staticAssets.iconHomeArrow"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</view>
|
||||
<view class="complete-page__field">
|
||||
<text class="complete-page__label">所在房间</text>
|
||||
@@ -139,8 +134,6 @@ const {
|
||||
currentStep,
|
||||
deviceName,
|
||||
serialMasked,
|
||||
productOptions,
|
||||
productIndex,
|
||||
productDisplayText,
|
||||
productSelected,
|
||||
productOptionsLoading,
|
||||
@@ -151,7 +144,7 @@ const {
|
||||
bluetoothConnected,
|
||||
bluetoothStatusText,
|
||||
initPage,
|
||||
onProductChange,
|
||||
onPickProduct,
|
||||
onPickRoom,
|
||||
onFinishAdd,
|
||||
} = useCompleteDevice()
|
||||
|
||||
@@ -157,11 +157,26 @@ export function useCompleteDevice() {
|
||||
initialized.value = true
|
||||
}
|
||||
|
||||
function onProductChange(event: { detail: { value: number } }) {
|
||||
const index = Number(event.detail.value)
|
||||
const option = productOptions.value[index]
|
||||
if (!option) return
|
||||
applyProduct(option)
|
||||
function onPickProduct() {
|
||||
if (productOptionsLoading.value) {
|
||||
uni.showToast({ title: '产品型号加载中', icon: 'none' })
|
||||
return
|
||||
}
|
||||
const options = productOptions.value
|
||||
if (!options.length) {
|
||||
uni.showToast({ title: '暂无产品型号,请稍后重试', icon: 'none' })
|
||||
void loadProductOptions()
|
||||
return
|
||||
}
|
||||
|
||||
const labels = options.map((item) => item.model || item.name || '未知型号')
|
||||
uni.showActionSheet({
|
||||
itemList: labels.slice(0, 6),
|
||||
success: (res) => {
|
||||
const option = options[res.tapIndex]
|
||||
if (option) applyProduct(option)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function onPickRoom() {
|
||||
@@ -268,7 +283,7 @@ export function useCompleteDevice() {
|
||||
bluetoothConnected,
|
||||
bluetoothStatusText,
|
||||
initPage,
|
||||
onProductChange,
|
||||
onPickProduct,
|
||||
onPickRoom,
|
||||
onFinishAdd,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { onShow } from '@dcloudio/uni-app'
|
||||
import { onHide, onShow } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
||||
import { fetchHomeList, resolveValidHomeId } from '@/api/home'
|
||||
@@ -17,6 +17,9 @@ import {
|
||||
mapDeviceItem,
|
||||
} from './device.utils'
|
||||
|
||||
/** 与设备详情页 BLE 同步间隔一致 */
|
||||
const PRESENCE_INTERVAL_MS = 15000
|
||||
|
||||
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
|
||||
{
|
||||
id: 'z2',
|
||||
@@ -42,6 +45,8 @@ export function useDevice() {
|
||||
const roomDialogVisible = ref(false)
|
||||
const successToastVisible = ref(false)
|
||||
|
||||
let presenceTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const hasDevices = computed(() => devices.value.length > 0)
|
||||
|
||||
const filteredDevices = computed(() =>
|
||||
@@ -108,11 +113,31 @@ export function useDevice() {
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshPresenceOnly() {
|
||||
if (!devices.value.length || loading.value) return
|
||||
devices.value = await refreshDevicePresence(devices.value)
|
||||
}
|
||||
|
||||
function startPresencePolling() {
|
||||
stopPresencePolling()
|
||||
presenceTimer = setInterval(() => {
|
||||
void refreshPresenceOnly()
|
||||
}, PRESENCE_INTERVAL_MS)
|
||||
}
|
||||
|
||||
function stopPresencePolling() {
|
||||
if (presenceTimer) clearInterval(presenceTimer)
|
||||
presenceTimer = undefined
|
||||
}
|
||||
|
||||
onShow(() => {
|
||||
void loadDevices()
|
||||
void refreshUnreadMessageCount()
|
||||
startPresencePolling()
|
||||
})
|
||||
|
||||
onHide(stopPresencePolling)
|
||||
|
||||
function showOperationSuccess() {
|
||||
successToastVisible.value = true
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getErrorMessage } from '@/utils/api-error'
|
||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { SMS_CODE_SCENE } from '@/types/api'
|
||||
import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth'
|
||||
import { loginByPassword, loginBySms } from './login.api'
|
||||
import type { LoginMode } from './login.types'
|
||||
|
||||
@@ -46,6 +47,7 @@ export function useLogin() {
|
||||
return
|
||||
}
|
||||
await loginBySms({ phone: phone.value, code: code.value })
|
||||
await syncCsAuthBySms(phone.value, code.value)
|
||||
} else {
|
||||
if (!account.value.trim()) {
|
||||
uni.showToast({ title: '请输入账号', icon: 'none' })
|
||||
@@ -59,6 +61,7 @@ export function useLogin() {
|
||||
account: account.value,
|
||||
password: password.value,
|
||||
})
|
||||
await syncCsAuthByPassword(account.value, password.value)
|
||||
}
|
||||
if (!getStoredToken()) {
|
||||
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
|
||||
|
||||
@@ -8,6 +8,14 @@ export function isUnreadMessage(message: AppMessageVo): boolean {
|
||||
return flag === 0 || flag === '0'
|
||||
}
|
||||
|
||||
function pad2(value: number): string {
|
||||
return String(value).padStart(2, '0')
|
||||
}
|
||||
|
||||
function formatNotifyDateTime(date: Date): string {
|
||||
return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${pad2(date.getHours())}:${pad2(date.getMinutes())}`
|
||||
}
|
||||
|
||||
export function formatNotifyTime(message: AppMessageVo): string {
|
||||
const raw = message.timestamp || message.createTime
|
||||
if (!raw) return ''
|
||||
@@ -16,6 +24,6 @@ export function formatNotifyTime(message: AppMessageVo): string {
|
||||
|
||||
const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
|
||||
if (Number.isNaN(date.getTime())) return text
|
||||
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
return formatNotifyDateTime(date)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { resolveCsAppToken } from '@/api/request'
|
||||
import type { CsChatWsPayload, CsMessageVo, CsSessionVo } from './support.types'
|
||||
|
||||
const RECONNECT_DELAY_MS = 2000
|
||||
/** 断线后首次重连等待(非轮询;连接成功后会保持长连接) */
|
||||
const RECONNECT_BASE_MS = 10000
|
||||
const RECONNECT_MAX_MS = 30000
|
||||
|
||||
let socketTask: UniApp.SocketTask | null = null
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
@@ -11,6 +13,7 @@ let activeSessionId = ''
|
||||
let socketOpened = false
|
||||
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
|
||||
let connectionSeq = 0
|
||||
let reconnectAttempt = 0
|
||||
|
||||
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
||||
|
||||
@@ -25,13 +28,21 @@ function resolveCsChatWsBase(): string {
|
||||
|
||||
if (isH5Dev() && !forceDirect) {
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
return `${proto}//${window.location.host}/app/cs/chat`
|
||||
const useCsHost = !!import.meta.env.VITE_CS_API_BASE_URL?.trim()
|
||||
const path = useCsHost ? '/cs-app/cs/chat' : '/app/cs/chat'
|
||||
return `${proto}//${window.location.host}${path}`
|
||||
}
|
||||
|
||||
if (configured) {
|
||||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
||||
}
|
||||
|
||||
const csBase = import.meta.env.VITE_CS_API_BASE_URL?.trim()
|
||||
if (csBase) {
|
||||
const wsBase = csBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws').replace(/\/$/, '')
|
||||
return `${wsBase}/app/cs/chat`
|
||||
}
|
||||
|
||||
const envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
||||
const fallback =
|
||||
import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.222:8082'
|
||||
@@ -68,11 +79,16 @@ function clearReconnectTimer() {
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (manualClosed || !getStoredToken() || !activeSessionId) return
|
||||
if (manualClosed || !resolveCsAppToken() || !activeSessionId) return
|
||||
clearReconnectTimer()
|
||||
const delay = Math.min(
|
||||
RECONNECT_BASE_MS * Math.pow(1.5, reconnectAttempt),
|
||||
RECONNECT_MAX_MS,
|
||||
)
|
||||
reconnectAttempt += 1
|
||||
reconnectTimer = setTimeout(() => {
|
||||
connectCsChatSocket(activeSessionId)
|
||||
}, RECONNECT_DELAY_MS)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function resetSocketState() {
|
||||
@@ -81,7 +97,7 @@ function resetSocketState() {
|
||||
connecting = false
|
||||
}
|
||||
|
||||
export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
||||
function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
||||
if (!raw || raw === 'ping' || raw === 'pong') return null
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
||||
@@ -163,6 +179,7 @@ function bindSocketTask(task: UniApp.SocketTask, seq: number) {
|
||||
if (seq !== connectionSeq) return
|
||||
socketOpened = true
|
||||
connecting = false
|
||||
reconnectAttempt = 0
|
||||
if (import.meta.env.DEV) console.log('[CS Chat WS] connected')
|
||||
})
|
||||
|
||||
@@ -192,7 +209,7 @@ function bindSocketTask(task: UniApp.SocketTask, seq: number) {
|
||||
}
|
||||
|
||||
export function connectCsChatSocket(sessionId: string) {
|
||||
const token = getStoredToken()
|
||||
const token = resolveCsAppToken()
|
||||
if (!token || !sessionId) return
|
||||
if (connecting) return
|
||||
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
||||
@@ -244,6 +261,7 @@ export function disconnectCsChatSocket() {
|
||||
manualClosed = true
|
||||
connectionSeq += 1
|
||||
activeSessionId = ''
|
||||
reconnectAttempt = 0
|
||||
clearReconnectTimer()
|
||||
const task = socketTask
|
||||
socketTask = null
|
||||
|
||||
@@ -88,7 +88,13 @@
|
||||
</view>
|
||||
|
||||
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
|
||||
我
|
||||
<image
|
||||
v-if="userAvatarUrl"
|
||||
class="support-page__msg-avatar-img"
|
||||
:src="userAvatarUrl"
|
||||
mode="aspectFill"
|
||||
/>
|
||||
<text v-else>我</text>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -224,14 +230,21 @@
|
||||
>
|
||||
<image
|
||||
class="support-page__image"
|
||||
:src="item.src"
|
||||
:src="chatImageDisplaySrc(item)"
|
||||
mode="aspectFill"
|
||||
@tap="onPreviewImage(item.src)"
|
||||
@error="onChatImageError(item)"
|
||||
@tap="onPreviewImage(chatImageDisplaySrc(item))"
|
||||
/>
|
||||
</view>
|
||||
</view>
|
||||
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
|
||||
我
|
||||
<image
|
||||
v-if="userAvatarUrl"
|
||||
class="support-page__msg-avatar-img"
|
||||
:src="userAvatarUrl"
|
||||
mode="aspectFill"
|
||||
/>
|
||||
<text v-else>我</text>
|
||||
</view>
|
||||
</view>
|
||||
</template>
|
||||
@@ -254,59 +267,32 @@
|
||||
</text>
|
||||
</view>
|
||||
<view class="support-page__input-row">
|
||||
<view class="support-page__mic" @tap="toggleInputMode">
|
||||
<image
|
||||
v-if="inputMode === 'text'"
|
||||
class="support-page__mic-icon"
|
||||
:src="staticAssets.iconSupportMic"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
<text v-else class="support-page__keyboard-icon">⌨</text>
|
||||
</view>
|
||||
|
||||
<view v-if="inputMode === 'text'" class="support-page__input-wrap">
|
||||
<view class="support-page__input-wrap">
|
||||
<input
|
||||
v-model="inputValue"
|
||||
class="support-page__input"
|
||||
type="text"
|
||||
placeholder="输入你的问题..."
|
||||
placeholder="输入你的问题.."
|
||||
placeholder-class="support-page__input-placeholder"
|
||||
confirm-type="send"
|
||||
@confirm="onSend"
|
||||
/>
|
||||
</view>
|
||||
<view
|
||||
v-else
|
||||
class="support-page__voice-btn"
|
||||
:class="{
|
||||
'support-page__voice-btn--holding': voiceHolding,
|
||||
'support-page__voice-btn--recognizing': voiceRecognizing,
|
||||
}"
|
||||
@touchstart.prevent="onVoiceTouchStart"
|
||||
@touchend.prevent="onVoiceTouchEnd"
|
||||
@touchcancel.prevent="onVoiceTouchCancel"
|
||||
>
|
||||
<text class="support-page__voice-btn-text">
|
||||
{{ voiceButtonText }}
|
||||
</text>
|
||||
</view>
|
||||
|
||||
<template v-if="inputMode === 'text'">
|
||||
<view class="support-page__tag" @tap="onPickImage">
|
||||
<image
|
||||
class="support-page__tag-icon"
|
||||
:src="staticAssets.iconSupportPhoto"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<view class="support-page__send" @tap="onSend">
|
||||
<image
|
||||
class="support-page__send-icon"
|
||||
:src="staticAssets.iconSupportSend"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</template>
|
||||
<view class="support-page__tag" @tap="onPickImage">
|
||||
<image
|
||||
class="support-page__tag-icon"
|
||||
:src="staticAssets.iconSupportPhoto"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
<view class="support-page__send" @tap="onSend">
|
||||
<image
|
||||
class="support-page__send-icon"
|
||||
:src="staticAssets.iconSupportSend"
|
||||
mode="aspectFit"
|
||||
/>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -315,14 +301,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { staticAssets } from '@/utils/static-assets'
|
||||
import { useCsChatImage } from './use-cs-chat-image'
|
||||
import { useSupport } from './use-support'
|
||||
import { useSupportVoice } from './use-support-voice'
|
||||
import type { DiagnosisItem } from './support.types'
|
||||
|
||||
const {
|
||||
messages,
|
||||
inputValue,
|
||||
headerInfo,
|
||||
userAvatarUrl,
|
||||
showTransfer,
|
||||
showEndSession,
|
||||
formattedQueueWait,
|
||||
@@ -338,28 +325,11 @@ const {
|
||||
onPickImage,
|
||||
} = useSupport()
|
||||
|
||||
const {
|
||||
inputMode,
|
||||
voiceHolding,
|
||||
voiceRecognizing,
|
||||
toggleInputMode,
|
||||
onVoiceTouchStart,
|
||||
onVoiceTouchEnd,
|
||||
onVoiceTouchCancel,
|
||||
} = useSupportVoice({
|
||||
onRecognized: (text) => {
|
||||
inputValue.value = text
|
||||
onSend()
|
||||
},
|
||||
})
|
||||
|
||||
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
|
||||
|
||||
const voiceButtonText = computed(() => {
|
||||
if (voiceRecognizing.value && !voiceHolding.value) return '识别中...'
|
||||
if (voiceHolding.value) return '松手 发送'
|
||||
return '按住 说话'
|
||||
})
|
||||
const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage(
|
||||
() => messages.value,
|
||||
)
|
||||
|
||||
const scrollIntoView = ref('chat-bottom')
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ let messagePollTimer: ReturnType<typeof setInterval> | null = null
|
||||
let queueTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const QUEUE_POLL_INTERVAL_MS = 5000
|
||||
const MESSAGE_POLL_INTERVAL_MS = 5000
|
||||
const MESSAGE_POLL_INTERVAL_MS = 10000
|
||||
|
||||
export function isSupportPageActive(): boolean {
|
||||
return pageActive
|
||||
@@ -30,13 +30,6 @@ export function stopSupportQueueTimer() {
|
||||
queueTimer = null
|
||||
}
|
||||
|
||||
export function teardownSupportRuntime() {
|
||||
markSupportPageActive(false)
|
||||
stopSupportPollTimer()
|
||||
stopSupportMessagePollTimer()
|
||||
stopSupportQueueTimer()
|
||||
}
|
||||
|
||||
/** 定时增量拉消息(WebSocket 漏推时的兜底) */
|
||||
export function startSupportMessagePolling(onTick: () => void) {
|
||||
stopSupportMessagePollTimer()
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { API_CLIENT_ID, request } from '@/api/request'
|
||||
import type { ApiResponse } from '@/types/api'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
||||
import { resolveCsAppBaseUrl, request, requestCsApp, uploadAppFile } from '@/api/request'
|
||||
import { assertCsUploadToken, ensureCsUploadReady } from '@/api/cs-auth'
|
||||
import { ApiError } from '@/utils/api-error'
|
||||
import {
|
||||
isSessionEnded,
|
||||
normalizeCsMediaUrl,
|
||||
normalizeSessionId,
|
||||
normalizeSessionResponse,
|
||||
registerCsImageUrl,
|
||||
unwrapCsActionResponse,
|
||||
} from './support.utils'
|
||||
import { CS_IMAGE_MESSAGE_PLACEHOLDER } from './support.types'
|
||||
import type {
|
||||
CsAppActionVo,
|
||||
CsClickButtonBody,
|
||||
CsChatImageUploadVo,
|
||||
CzCsUploadVo,
|
||||
CsCreateSessionBody,
|
||||
CsMessageVo,
|
||||
@@ -26,12 +27,15 @@ function buildSessionPath(sessionId: string, suffix = '') {
|
||||
return `/app/cs/session/${encodeURIComponent(sessionId)}${suffix}`
|
||||
}
|
||||
|
||||
function resolveUploadBaseUrl(): string {
|
||||
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return ''
|
||||
// #endif
|
||||
return envUrl
|
||||
/** 客服会话相关接口统一走 212(与 upload / 图片 message 同服,保证 ossId、url 一致) */
|
||||
function csRequest<T>(options: Parameters<typeof request>[0]): Promise<T> {
|
||||
return resolveCsAppBaseUrl() ? requestCsApp<T>(options) : request<T>(options)
|
||||
}
|
||||
|
||||
function resolveCsUploadUrl(): string {
|
||||
const csBase = resolveCsAppBaseUrl()
|
||||
if (csBase) return `${csBase}/cs/upload`
|
||||
return '/app/cs/upload'
|
||||
}
|
||||
|
||||
function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
||||
@@ -44,9 +48,12 @@ function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
||||
if (!url) {
|
||||
throw new ApiError('上传失败,未返回访问地址')
|
||||
}
|
||||
const normalizedUrl = normalizeCsMediaUrl(url)
|
||||
const ossIdStr = typeof ossId === 'number' ? String(ossId) : String(ossId)
|
||||
registerCsImageUrl(ossIdStr, normalizedUrl)
|
||||
return {
|
||||
ossId: typeof ossId === 'number' ? String(ossId) : String(ossId),
|
||||
url,
|
||||
ossId: ossIdStr,
|
||||
url: normalizedUrl,
|
||||
fileName: raw.fileName != null ? String(raw.fileName) : undefined,
|
||||
}
|
||||
}
|
||||
@@ -59,7 +66,7 @@ function unwrapRows<T>(data: T[] | CsTableData<T> | undefined): T[] {
|
||||
|
||||
/** POST /app/cs/session — 创建客服会话;已有未结束会话时返回原会话 */
|
||||
export function createCsSession(data: CsCreateSessionBody = {}) {
|
||||
return request<CsAppActionVo | CsSessionVo | string | null>({
|
||||
return csRequest<CsAppActionVo | CsSessionVo | string | null>({
|
||||
url: '/app/cs/session',
|
||||
method: 'POST',
|
||||
data,
|
||||
@@ -106,7 +113,7 @@ export async function resolveCsSession(): Promise<CsResolvedSession> {
|
||||
|
||||
/** GET /app/cs/session/list — 查询自己的会话 */
|
||||
export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
||||
return request<CsSessionVo[] | CsTableData<CsSessionVo>>({
|
||||
return csRequest<CsSessionVo[] | CsTableData<CsSessionVo>>({
|
||||
url: '/app/cs/session/list',
|
||||
method: 'GET',
|
||||
data: query,
|
||||
@@ -115,7 +122,7 @@ export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
||||
|
||||
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
||||
export function fetchCsSessionDetail(sessionId: string) {
|
||||
return request<CsAppActionVo | CsSessionVo | string | null>({
|
||||
return csRequest<CsAppActionVo | CsSessionVo | string | null>({
|
||||
url: buildSessionPath(sessionId),
|
||||
method: 'GET',
|
||||
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
|
||||
@@ -123,57 +130,39 @@ export function fetchCsSessionDetail(sessionId: string) {
|
||||
|
||||
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
||||
export function fetchCsMessages(sessionId: string, afterSeq = 0) {
|
||||
return request<CsMessageVo[] | CsTableData<CsMessageVo>>({
|
||||
return csRequest<CsMessageVo[] | CsTableData<CsMessageVo>>({
|
||||
url: buildSessionPath(sessionId, '/messages'),
|
||||
method: 'GET',
|
||||
data: { afterSeq },
|
||||
}).then(unwrapRows)
|
||||
}
|
||||
|
||||
/** POST /app/cs/upload — 上传聊天图片 */
|
||||
export function uploadCsChatImage(filePath: string): Promise<CsChatImageUploadVo> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = getStoredToken()
|
||||
uni.uploadFile({
|
||||
url: `${resolveUploadBaseUrl()}/app/cs/upload`,
|
||||
filePath,
|
||||
name: 'file',
|
||||
header: {
|
||||
clientId: API_CLIENT_ID,
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
success: (res) => {
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
reject(new ApiError(`上传失败(${res.statusCode})`, res.statusCode))
|
||||
return
|
||||
}
|
||||
let body: ApiResponse<CzCsUploadVo>
|
||||
try {
|
||||
body = JSON.parse(res.data) as ApiResponse<CzCsUploadVo>
|
||||
} catch {
|
||||
reject(new ApiError('上传响应解析失败'))
|
||||
return
|
||||
}
|
||||
if (!isApiSuccess(body)) {
|
||||
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
||||
return
|
||||
}
|
||||
try {
|
||||
resolve(normalizeCsUploadVo(unwrapApiData(body)))
|
||||
} catch (err) {
|
||||
reject(err instanceof ApiError ? err : new ApiError('上传响应无效'))
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
reject(new ApiError(err.errMsg || '上传失败'))
|
||||
},
|
||||
})
|
||||
})
|
||||
/** POST /app/cs/upload — 212 上传(clientId=app + cs_token) */
|
||||
export function uploadCsChatImage(filePath: string): Promise<CzCsUploadVo> {
|
||||
assertCsUploadToken()
|
||||
return uploadAppFile<CzCsUploadVo>(resolveCsUploadUrl(), filePath, 'file', 'cs').then((data) =>
|
||||
normalizeCsUploadVo(data),
|
||||
)
|
||||
}
|
||||
|
||||
/** 图片消息体:msgType + ossId + clientMsgId */
|
||||
export function buildCsImageMessageBody(
|
||||
ossId: string | number,
|
||||
clientMsgId: string,
|
||||
): CsSendMessageBody {
|
||||
const ossIdValue = String(ossId).trim()
|
||||
return {
|
||||
msgType: 'image',
|
||||
ossId: ossIdValue,
|
||||
clientMsgId,
|
||||
content: CS_IMAGE_MESSAGE_PLACEHOLDER,
|
||||
}
|
||||
}
|
||||
|
||||
/** POST /app/cs/session/{sessionId}/message — 发送消息 */
|
||||
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
||||
return request<CsAppActionVo>({
|
||||
if (resolveCsAppBaseUrl()) ensureCsUploadReady()
|
||||
return csRequest<CsAppActionVo>({
|
||||
url: buildSessionPath(sessionId, '/message'),
|
||||
method: 'POST',
|
||||
data,
|
||||
@@ -182,7 +171,7 @@ export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
||||
|
||||
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
||||
export function transferCsSession(sessionId: string) {
|
||||
return request<CsAppActionVo | CsSessionVo | null>({
|
||||
return csRequest<CsAppActionVo | CsSessionVo | null>({
|
||||
url: buildSessionPath(sessionId, '/transfer'),
|
||||
method: 'POST',
|
||||
})
|
||||
@@ -190,7 +179,7 @@ export function transferCsSession(sessionId: string) {
|
||||
|
||||
/** POST /app/cs/session/{sessionId}/end — 结束会话 */
|
||||
export function endCsSession(sessionId: string) {
|
||||
return request<void>({
|
||||
return csRequest<void>({
|
||||
url: buildSessionPath(sessionId, '/end'),
|
||||
method: 'POST',
|
||||
})
|
||||
@@ -198,7 +187,7 @@ export function endCsSession(sessionId: string) {
|
||||
|
||||
/** POST /app/cs/session/{sessionId}/button — 点击机器人按钮 */
|
||||
export function clickCsButton(sessionId: string, data: CsClickButtonBody) {
|
||||
return request<void>({
|
||||
return csRequest<void>({
|
||||
url: buildSessionPath(sessionId, '/button'),
|
||||
method: 'POST',
|
||||
data,
|
||||
|
||||
@@ -212,9 +212,15 @@ $support-danger: #f04438;
|
||||
border-radius: 50%;
|
||||
background: #d0d5dd;
|
||||
color: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.support-page__msg-avatar-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.support-page__msg-body {
|
||||
max-width: calc(100% - 96rpx);
|
||||
display: flex;
|
||||
@@ -642,49 +648,6 @@ $support-danger: #f04438;
|
||||
gap: 16rpx;
|
||||
}
|
||||
|
||||
.support-page__mic {
|
||||
width: 80rpx;
|
||||
height: 80rpx;
|
||||
border-radius: 16rpx;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.support-page__mic-icon {
|
||||
width: 56rpx;
|
||||
height: 56rpx;
|
||||
}
|
||||
|
||||
.support-page__keyboard-icon {
|
||||
font-size: 40rpx;
|
||||
line-height: 1;
|
||||
color: $support-text-muted;
|
||||
}
|
||||
|
||||
.support-page__voice-btn {
|
||||
flex: 1;
|
||||
height: 72rpx;
|
||||
border-radius: 36rpx;
|
||||
background: #f5f6f8;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
user-select: none;
|
||||
|
||||
&--holding,
|
||||
&--recognizing {
|
||||
background: rgba(30, 198, 113, 0.12);
|
||||
}
|
||||
}
|
||||
|
||||
.support-page__voice-btn-text {
|
||||
font-size: 28rpx;
|
||||
color: $support-text;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.support-page__input-wrap {
|
||||
flex: 1;
|
||||
height: 72rpx;
|
||||
|
||||
@@ -6,8 +6,6 @@ export const CS_SESSION_STATUS = {
|
||||
closed: '3',
|
||||
} as const
|
||||
|
||||
export type CsSessionStatus = (typeof CS_SESSION_STATUS)[keyof typeof CS_SESSION_STATUS]
|
||||
|
||||
/** POST /app/cs/session、GET /app/cs/session/{sessionId} */
|
||||
export interface CsSessionVo {
|
||||
sessionId?: number | string
|
||||
@@ -47,10 +45,15 @@ export interface CsMessageVo {
|
||||
sessionId?: number | string
|
||||
senderType?: string | number
|
||||
/** 接口字段为 msgType;部分响应仍带 messageType */
|
||||
msgType?: string
|
||||
messageType?: string
|
||||
content?: string
|
||||
msgType?: string | number
|
||||
messageType?: string | number
|
||||
content?: string | null
|
||||
ossId?: number | string
|
||||
/** 图片地址,服务端由 ossId 翻译生成,前端直接用于展示 */
|
||||
url?: string
|
||||
imageUrl?: string
|
||||
fileUrl?: string
|
||||
clientMsgId?: string
|
||||
createTime?: string
|
||||
extra?: Record<string, unknown>
|
||||
}
|
||||
@@ -95,14 +98,16 @@ export interface CzCsUploadVo {
|
||||
fileName?: string
|
||||
}
|
||||
|
||||
export type CsChatImageUploadVo = CzCsUploadVo
|
||||
/** 图片消息占位文案(发消息 content 字段、列表摘要) */
|
||||
export const CS_IMAGE_MESSAGE_PLACEHOLDER = '[图片]'
|
||||
|
||||
/** POST /app/cs/session/{sessionId}/message */
|
||||
export interface CsSendMessageBody {
|
||||
content: string
|
||||
msgType?: 'text' | 'image' | string
|
||||
messageType?: 'text' | 'image' | string
|
||||
/** 文本必填;图片可选占位 [图片] */
|
||||
content?: string
|
||||
msgType: 'text' | 'image' | string
|
||||
clientMsgId: string
|
||||
/** 图片消息必填(仅 212 CzCsMessageBo 接收) */
|
||||
ossId?: number | string
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,58 @@ import type {
|
||||
SupportMessage,
|
||||
SupportPhase,
|
||||
} from './support.types'
|
||||
import { CS_SESSION_STATUS } from './support.types'
|
||||
import { CS_IMAGE_MESSAGE_PLACEHOLDER, CS_SESSION_STATUS } from './support.types'
|
||||
|
||||
/** 上传成功后缓存 ossId → 可访问地址,用于消息列表尚未带 url 时展示 */
|
||||
const csImageUrlCache = new Map<string, string>()
|
||||
/** 发图时按 clientMsgId 关联预览地址(服务端未回 ossId/url 时兜底) */
|
||||
const csImageUrlByClientMsgId = new Map<string, string>()
|
||||
/** 按 messageId 缓存图片 url(轮询消息缺 url 时兜底) */
|
||||
const csImageUrlByMessageId = new Map<string, string>()
|
||||
|
||||
export function registerCsImageUrl(ossId: string | number, url: string) {
|
||||
const id = String(ossId).trim()
|
||||
const normalized = normalizeCsMediaUrl(url)
|
||||
if (id && normalized) csImageUrlCache.set(id, normalized)
|
||||
}
|
||||
|
||||
function registerCsImageByClientMsgId(clientMsgId: string, url: string) {
|
||||
const id = clientMsgId.trim()
|
||||
const normalized = normalizeCsMediaUrl(url)
|
||||
if (id && normalized) csImageUrlByClientMsgId.set(id, normalized)
|
||||
}
|
||||
|
||||
function registerCsImageByMessageId(messageId: string | number, url: string) {
|
||||
const id = String(messageId).trim()
|
||||
const normalized = normalizeCsMediaUrl(url)
|
||||
if (id && normalized) csImageUrlByMessageId.set(id, normalized)
|
||||
}
|
||||
|
||||
/** 缓存消息里已有的图片 url(文档:展示直接用 url 字段) */
|
||||
export function ingestCsMessageMedia(message: CsMessageVo) {
|
||||
const candidates = [message.url, message.imageUrl, message.fileUrl]
|
||||
const raw = candidates.find((v) => v != null && String(v).trim())?.toString().trim()
|
||||
if (!raw) return
|
||||
const normalized = resolveMediaFieldValue(raw, message)
|
||||
if (!normalized) return
|
||||
if (message.messageId != null && message.messageId !== '') {
|
||||
registerCsImageByMessageId(message.messageId, normalized)
|
||||
}
|
||||
if (message.ossId != null && String(message.ossId).trim()) {
|
||||
registerCsImageUrl(message.ossId, normalized)
|
||||
}
|
||||
if (message.clientMsgId?.trim()) {
|
||||
registerCsImageByClientMsgId(message.clientMsgId, normalized)
|
||||
}
|
||||
}
|
||||
|
||||
function resolveMediaBaseUrl(): string {
|
||||
const envUrl = import.meta.env.VITE_API_BASE_URL?.trim() ?? ''
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return ''
|
||||
// #endif
|
||||
return envUrl.replace(/\/$/, '')
|
||||
}
|
||||
|
||||
const QUICK_ACTIONS: QuickActionItem[] = [
|
||||
{ id: 'wifi', label: '设备连不上 Wi-Fi' },
|
||||
@@ -174,38 +225,191 @@ export function injectTimeDividers(messages: SupportMessage[]): SupportMessage[]
|
||||
function resolveSenderRole(senderType?: string | number): ChatRole | null {
|
||||
const value = String(senderType ?? '').toLowerCase()
|
||||
if (!value) return 'bot'
|
||||
if (value === '0' || value.includes('user') || value.includes('app')) return 'user'
|
||||
if (
|
||||
value === '0'
|
||||
|| value.includes('user')
|
||||
|| value.includes('app')
|
||||
|| value.includes('customer')
|
||||
) {
|
||||
return 'user'
|
||||
}
|
||||
if (value === '1' || value.includes('bot') || value.includes('robot')) return 'bot'
|
||||
if (value === '2' || value.includes('agent') || value.includes('human')) return 'agent'
|
||||
if (
|
||||
value === '2'
|
||||
|| value.includes('agent')
|
||||
|| value.includes('human')
|
||||
|| value.includes('staff')
|
||||
|| value.includes('seat')
|
||||
) {
|
||||
return 'agent'
|
||||
}
|
||||
if (value === '3' || value.includes('system')) return 'system'
|
||||
return 'bot'
|
||||
}
|
||||
|
||||
/** 阿里云 OSS 公网地址统一 https;相对路径补全为可访问 URL */
|
||||
export function normalizeCsMediaUrl(raw: string): string {
|
||||
const value = raw.trim()
|
||||
if (!value) return ''
|
||||
if (/^https?:\/\//i.test(value)) {
|
||||
if (/^http:\/\//i.test(value) && /\.aliyuncs\.com/i.test(value)) {
|
||||
return value.replace(/^http:\/\//i, 'https://')
|
||||
}
|
||||
return value
|
||||
}
|
||||
if (value.startsWith('//')) return `https:${value}`
|
||||
if (value.startsWith('/')) {
|
||||
const base = resolveMediaBaseUrl()
|
||||
return base ? `${base}${value}` : value
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export function resolveOssImageUrl(ossId: string | number): string {
|
||||
const id = String(ossId).trim()
|
||||
if (!id) return ''
|
||||
const cached = csImageUrlCache.get(id)
|
||||
if (cached) return cached
|
||||
return normalizeCsMediaUrl(`/resource/oss/download/${id}`)
|
||||
}
|
||||
|
||||
function isLikelyMessageId(value: string, message: CsMessageVo): boolean {
|
||||
if (message.messageId == null || message.messageId === '') return false
|
||||
return value === String(message.messageId).trim()
|
||||
}
|
||||
|
||||
function isNumericOssId(value: string): boolean {
|
||||
return /^\d{10,}$/.test(value)
|
||||
}
|
||||
|
||||
/** 将 url / ossId / 相对路径统一解析为可加载地址 */
|
||||
function resolveMediaFieldValue(raw: string, message?: CsMessageVo): string {
|
||||
const value = raw.trim()
|
||||
if (!value) return ''
|
||||
if (message && isLikelyMessageId(value, message)) return ''
|
||||
if (isNumericOssId(value)) return resolveOssImageUrl(value)
|
||||
return normalizeCsMediaUrl(value)
|
||||
}
|
||||
|
||||
function pickBetterImageSrc(current?: string, next?: string): string {
|
||||
const a = current?.trim() ?? ''
|
||||
const b = next?.trim() ?? ''
|
||||
if (!a) return b
|
||||
if (!b) return a
|
||||
const aDirect = /^https?:\/\//i.test(a) || a.startsWith('blob:')
|
||||
const bDirect = /^https?:\/\//i.test(b) || b.startsWith('blob:')
|
||||
const aAuth = a.includes('/resource/oss/download/')
|
||||
const bAuth = b.includes('/resource/oss/download/')
|
||||
if (aDirect && bAuth) return a
|
||||
if (bDirect && aAuth) return b
|
||||
return b
|
||||
}
|
||||
|
||||
function isDisplayableImageSrc(src?: string): boolean {
|
||||
const value = src?.trim() ?? ''
|
||||
if (!value) return false
|
||||
if (/^https?:\/\//i.test(value)) return true
|
||||
if (value.startsWith('blob:') || value.startsWith('data:')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function registerLocalImagePreview(
|
||||
ossId: string | number,
|
||||
clientMsgId: string,
|
||||
preview: string,
|
||||
) {
|
||||
registerCsImageUrl(ossId, preview)
|
||||
registerCsImageByClientMsgId(clientMsgId, preview)
|
||||
}
|
||||
|
||||
/** 发图成功后缓存服务端回包中的图片地址,返回是否已有可展示图片 */
|
||||
export function cacheSentImageRefs(
|
||||
messages: CsMessageVo[] | undefined,
|
||||
clientMsgId: string,
|
||||
preview: string,
|
||||
): boolean {
|
||||
if (!preview || !messages?.length) return false
|
||||
for (const msg of messages) {
|
||||
const url = msg.url?.trim() || preview
|
||||
if (msg.messageId != null && msg.messageId !== '') {
|
||||
registerCsImageByMessageId(msg.messageId, url)
|
||||
}
|
||||
registerCsImageByClientMsgId(msg.clientMsgId?.trim() || clientMsgId, url)
|
||||
if (msg.ossId != null && String(msg.ossId).trim()) {
|
||||
registerCsImageUrl(msg.ossId, url)
|
||||
}
|
||||
}
|
||||
return messages.some((msg) => {
|
||||
const mapped = mapCsMessage(msg)
|
||||
return mapped?.type === 'image' && isDisplayableImageSrc(mapped.src)
|
||||
})
|
||||
}
|
||||
|
||||
function resolveMessageType(message: CsMessageVo): string {
|
||||
return String(message.msgType ?? message.messageType ?? '').toLowerCase()
|
||||
}
|
||||
|
||||
function isImageMessage(message: CsMessageVo): boolean {
|
||||
const type = resolveMessageType(message)
|
||||
const content = message.content?.trim() ?? ''
|
||||
const hasOssId = message.ossId !== undefined
|
||||
&& message.ossId !== null
|
||||
&& String(message.ossId).trim()
|
||||
|
||||
if (type === 'image' || type === '2' || type === 'img') return true
|
||||
if (content === CS_IMAGE_MESSAGE_PLACEHOLDER && hasOssId) return true
|
||||
if (hasOssId) {
|
||||
return type !== 'text' && type !== '1'
|
||||
}
|
||||
const url = message.url?.trim()
|
||||
return !!url && /^https?:\/\//i.test(url)
|
||||
}
|
||||
|
||||
function resolveImageSrc(message: CsMessageVo): string {
|
||||
if (message.messageId != null && message.messageId !== '') {
|
||||
const cached = csImageUrlByMessageId.get(String(message.messageId))
|
||||
if (cached) return cached
|
||||
}
|
||||
|
||||
if (message.clientMsgId?.trim()) {
|
||||
const byClient = csImageUrlByClientMsgId.get(message.clientMsgId.trim())
|
||||
if (byClient) return byClient
|
||||
}
|
||||
|
||||
const directUrl = message.url ?? message.imageUrl ?? message.fileUrl
|
||||
if (directUrl?.trim()) {
|
||||
const resolved = resolveMediaFieldValue(String(directUrl), message)
|
||||
if (resolved) return resolved
|
||||
}
|
||||
|
||||
const extra = message.extra
|
||||
if (extra && typeof extra === 'object') {
|
||||
const fromExtra = extra.url ?? extra.src ?? extra.link
|
||||
if (fromExtra != null && String(fromExtra).trim()) {
|
||||
return String(fromExtra).trim()
|
||||
const resolved = resolveMediaFieldValue(String(fromExtra), message)
|
||||
if (resolved) return resolved
|
||||
}
|
||||
}
|
||||
|
||||
const content = message.content?.trim() ?? ''
|
||||
if (!content) return ''
|
||||
if (/^https?:\/\//i.test(content)) return content
|
||||
if (content.startsWith('{') && content.endsWith('}')) {
|
||||
try {
|
||||
const payload = JSON.parse(content) as Record<string, unknown>
|
||||
const url = payload.url ?? payload.src ?? payload.link ?? payload.fileUrl
|
||||
if (url != null && String(url).trim()) return String(url).trim()
|
||||
} catch {
|
||||
// ignore
|
||||
if (content && content !== CS_IMAGE_MESSAGE_PLACEHOLDER) {
|
||||
if (isNumericOssId(content)) return resolveOssImageUrl(content)
|
||||
if (/^https?:\/\//i.test(content)) return normalizeCsMediaUrl(content)
|
||||
if (content.startsWith('{') && content.endsWith('}')) {
|
||||
try {
|
||||
const payload = JSON.parse(content) as Record<string, unknown>
|
||||
const url = payload.url ?? payload.src ?? payload.link ?? payload.fileUrl
|
||||
if (url != null && String(url).trim()) return normalizeCsMediaUrl(String(url))
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
return content
|
||||
|
||||
if (message.ossId !== undefined && message.ossId !== null && String(message.ossId).trim()) {
|
||||
return resolveOssImageUrl(message.ossId)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function createMessageId(message: CsMessageVo): string {
|
||||
@@ -274,14 +478,15 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
const src = String(payload.src ?? payload.url ?? '')
|
||||
if (type === 'image' || type === '2' || type === 'img') {
|
||||
const src = resolveImageSrc(message)
|
||||
|| normalizeCsMediaUrl(String(payload.src ?? payload.url ?? ''))
|
||||
if (!src) return null
|
||||
return {
|
||||
id,
|
||||
seq,
|
||||
type: 'image',
|
||||
role: 'user',
|
||||
role: resolveSenderRole(message.senderType) || 'user',
|
||||
src,
|
||||
createTime: message.createTime,
|
||||
}
|
||||
@@ -291,10 +496,10 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
|
||||
}
|
||||
|
||||
export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
|
||||
ingestCsMessageMedia(message)
|
||||
const content = message.content?.trim() ?? ''
|
||||
const messageType = resolveMessageType(message)
|
||||
|
||||
if (messageType === 'image') {
|
||||
if (isImageMessage(message)) {
|
||||
const src = resolveImageSrc(message)
|
||||
if (!src) return null
|
||||
const role = resolveSenderRole(message.senderType) || 'user'
|
||||
@@ -338,7 +543,14 @@ export function mergeSupportMessages(
|
||||
if (!incoming.length) return current
|
||||
const map = new Map<string, SupportMessage>()
|
||||
for (const item of current) map.set(item.id, item)
|
||||
for (const item of incoming) map.set(item.id, item)
|
||||
for (const item of incoming) {
|
||||
const prev = map.get(item.id)
|
||||
if (prev?.type === 'image' && item.type === 'image') {
|
||||
map.set(item.id, { ...item, src: pickBetterImageSrc(prev.src, item.src) })
|
||||
continue
|
||||
}
|
||||
map.set(item.id, item)
|
||||
}
|
||||
return Array.from(map.values()).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))
|
||||
}
|
||||
|
||||
|
||||
73
src/pages/mine/support/use-cs-chat-image.ts
Normal file
73
src/pages/mine/support/use-cs-chat-image.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { ref, watch } from 'vue'
|
||||
import { buildDownloadAuthHeaders } from '@/api/request'
|
||||
import { normalizeCsMediaUrl, resolveOssImageUrl } from './support.utils'
|
||||
import type { SupportMessage } from './support.types'
|
||||
|
||||
function isNumericOssId(value: string): boolean {
|
||||
return /^\d{10,}$/.test(value)
|
||||
}
|
||||
|
||||
function coerceImageSrc(src: string): string {
|
||||
const value = src.trim()
|
||||
if (!value) return ''
|
||||
if (isNumericOssId(value)) return resolveOssImageUrl(value)
|
||||
return normalizeCsMediaUrl(value)
|
||||
}
|
||||
|
||||
function isAuthRequiredSrc(src: string): boolean {
|
||||
return src.includes('/resource/oss/download/')
|
||||
}
|
||||
|
||||
function resolveFetchUrl(src: string): string {
|
||||
const normalized = coerceImageSrc(src)
|
||||
if (/^https?:\/\//i.test(normalized)) return normalized
|
||||
if (typeof window !== 'undefined' && normalized.startsWith('/')) {
|
||||
return `${window.location.origin}${normalized}`
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function useCsChatImage(getMessages: () => SupportMessage[]) {
|
||||
const displaySrcMap = ref<Record<string, string>>({})
|
||||
|
||||
function displaySrc(item: { id: string; src: string }): string {
|
||||
return displaySrcMap.value[item.id] || coerceImageSrc(item.src)
|
||||
}
|
||||
|
||||
async function loadAuthImage(id: string, src: string) {
|
||||
if (displaySrcMap.value[id]) return
|
||||
const fetchUrl = resolveFetchUrl(src)
|
||||
if (!fetchUrl) return
|
||||
try {
|
||||
const response = await fetch(fetchUrl, { headers: buildDownloadAuthHeaders() })
|
||||
if (!response.ok) return
|
||||
const blob = await response.blob()
|
||||
displaySrcMap.value = { ...displaySrcMap.value, [id]: URL.createObjectURL(blob) }
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDisplayable(item: { id: string; src: string }) {
|
||||
const src = coerceImageSrc(item.src)
|
||||
if (!src || displaySrcMap.value[item.id]) return
|
||||
if (isAuthRequiredSrc(src)) void loadAuthImage(item.id, src)
|
||||
}
|
||||
|
||||
function onImageError(item: { id: string; src: string }) {
|
||||
const current = displaySrcMap.value[item.id] || coerceImageSrc(item.src)
|
||||
if (isAuthRequiredSrc(current)) void loadAuthImage(item.id, current)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => getMessages(),
|
||||
(list) => {
|
||||
for (const item of list) {
|
||||
if (item.type === 'image') ensureDisplayable(item)
|
||||
}
|
||||
},
|
||||
{ immediate: true, deep: true },
|
||||
)
|
||||
|
||||
return { displaySrc, onImageError }
|
||||
}
|
||||
@@ -1,336 +0,0 @@
|
||||
import { onBeforeUnmount, ref } from 'vue'
|
||||
|
||||
type InputMode = 'text' | 'voice'
|
||||
|
||||
interface UseSupportVoiceOptions {
|
||||
onRecognized: (text: string) => void
|
||||
}
|
||||
|
||||
interface SpeechRecognitionInstance {
|
||||
lang: string
|
||||
continuous: boolean
|
||||
interimResults: boolean
|
||||
start: () => void
|
||||
stop: () => void
|
||||
abort: () => void
|
||||
onresult: ((event: { results: Array<Array<{ transcript?: string }>> }) => void) | null
|
||||
onerror: ((event: { error?: string }) => void) | null
|
||||
onend: (() => void) | null
|
||||
}
|
||||
|
||||
const MAX_VOICE_DURATION_MS = 60000
|
||||
|
||||
export function useSupportVoice(options: UseSupportVoiceOptions) {
|
||||
const inputMode = ref<InputMode>('text')
|
||||
const voiceHolding = ref(false)
|
||||
const voiceRecognizing = ref(false)
|
||||
|
||||
let touchCanceled = false
|
||||
let recordStopTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let h5Recognition: SpeechRecognitionInstance | null = null
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
let mpRecoManager: {
|
||||
start: (opts: { duration: number; lang: string }) => void
|
||||
stop: () => void
|
||||
onStop?: (res: { result?: string }) => void
|
||||
onError?: () => void
|
||||
} | null = null
|
||||
|
||||
try {
|
||||
const plugin = requirePlugin('WechatSI') as {
|
||||
getRecordRecognitionManager: () => NonNullable<typeof mpRecoManager>
|
||||
}
|
||||
mpRecoManager = plugin.getRecordRecognitionManager()
|
||||
mpRecoManager.onStop = (res) => {
|
||||
voiceRecognizing.value = false
|
||||
const text = res.result?.trim()
|
||||
if (text) {
|
||||
options.onRecognized(text)
|
||||
return
|
||||
}
|
||||
uni.showToast({ title: '未识别到语音内容', icon: 'none' })
|
||||
}
|
||||
mpRecoManager.onError = () => {
|
||||
voiceRecognizing.value = false
|
||||
uni.showToast({ title: '语音识别失败', icon: 'none' })
|
||||
}
|
||||
} catch {
|
||||
mpRecoManager = null
|
||||
}
|
||||
// #endif
|
||||
|
||||
function clearRecordStopTimer() {
|
||||
if (recordStopTimer) clearTimeout(recordStopTimer)
|
||||
recordStopTimer = null
|
||||
}
|
||||
|
||||
function resetVoiceState() {
|
||||
voiceHolding.value = false
|
||||
voiceRecognizing.value = false
|
||||
touchCanceled = false
|
||||
clearRecordStopTimer()
|
||||
}
|
||||
|
||||
function isVoiceSupported(): boolean {
|
||||
// #ifdef H5
|
||||
const win = window as Window & {
|
||||
SpeechRecognition?: new () => SpeechRecognitionInstance
|
||||
webkitSpeechRecognition?: new () => SpeechRecognitionInstance
|
||||
}
|
||||
return !!(win.SpeechRecognition || win.webkitSpeechRecognition)
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
return typeof plus !== 'undefined' && !!plus.speech
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
return !!mpRecoManager
|
||||
// #endif
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function ensureRecordPermission(): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
uni.getSetting({
|
||||
success: (res) => {
|
||||
if (res.authSetting['scope.record']) {
|
||||
resolve(true)
|
||||
return
|
||||
}
|
||||
uni.authorize({
|
||||
scope: 'scope.record',
|
||||
success: () => resolve(true),
|
||||
fail: () => {
|
||||
uni.showModal({
|
||||
title: '需要麦克风权限',
|
||||
content: '请在设置中开启麦克风权限后使用语音输入',
|
||||
confirmText: '去设置',
|
||||
success: (modalRes) => {
|
||||
if (modalRes.confirm) {
|
||||
uni.openSetting({})
|
||||
}
|
||||
},
|
||||
})
|
||||
resolve(false)
|
||||
},
|
||||
})
|
||||
},
|
||||
fail: () => resolve(false),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function cleanupH5Recognition() {
|
||||
if (!h5Recognition) return
|
||||
try {
|
||||
h5Recognition.abort()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
h5Recognition.onresult = null
|
||||
h5Recognition.onerror = null
|
||||
h5Recognition.onend = null
|
||||
h5Recognition = null
|
||||
}
|
||||
|
||||
async function startH5Voice() {
|
||||
const win = window as Window & {
|
||||
SpeechRecognition?: new () => SpeechRecognitionInstance
|
||||
webkitSpeechRecognition?: new () => SpeechRecognitionInstance
|
||||
}
|
||||
const Ctor = win.SpeechRecognition || win.webkitSpeechRecognition
|
||||
if (!Ctor) {
|
||||
uni.showToast({ title: '当前浏览器不支持语音输入', icon: 'none' })
|
||||
resetVoiceState()
|
||||
return
|
||||
}
|
||||
|
||||
cleanupH5Recognition()
|
||||
const recognition = new Ctor()
|
||||
h5Recognition = recognition
|
||||
recognition.lang = 'zh-CN'
|
||||
recognition.continuous = false
|
||||
recognition.interimResults = false
|
||||
voiceRecognizing.value = true
|
||||
|
||||
recognition.onresult = (event) => {
|
||||
const text = event.results[0]?.[0]?.transcript?.trim()
|
||||
if (text) options.onRecognized(text)
|
||||
}
|
||||
recognition.onerror = (event) => {
|
||||
if (event.error !== 'aborted') {
|
||||
uni.showToast({ title: '语音识别失败', icon: 'none' })
|
||||
}
|
||||
}
|
||||
recognition.onend = () => {
|
||||
voiceRecognizing.value = false
|
||||
h5Recognition = null
|
||||
}
|
||||
|
||||
try {
|
||||
recognition.start()
|
||||
} catch {
|
||||
voiceRecognizing.value = false
|
||||
h5Recognition = null
|
||||
uni.showToast({ title: '无法启动语音识别', icon: 'none' })
|
||||
}
|
||||
}
|
||||
|
||||
function stopH5Voice() {
|
||||
if (!h5Recognition) return
|
||||
try {
|
||||
h5Recognition.stop()
|
||||
} catch {
|
||||
h5Recognition.abort()
|
||||
}
|
||||
}
|
||||
|
||||
function startAppVoice() {
|
||||
if (!plus.speech) {
|
||||
uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' })
|
||||
return
|
||||
}
|
||||
voiceRecognizing.value = true
|
||||
plus.speech.startRecognize(
|
||||
{
|
||||
engine: 'baidu',
|
||||
lang: 'zh-cn',
|
||||
punctuation: false,
|
||||
timeout: 10000,
|
||||
},
|
||||
(text) => {
|
||||
voiceRecognizing.value = false
|
||||
const result = String(text || '').trim()
|
||||
if (result) {
|
||||
options.onRecognized(result)
|
||||
return
|
||||
}
|
||||
uni.showToast({ title: '未识别到语音内容', icon: 'none' })
|
||||
},
|
||||
() => {
|
||||
voiceRecognizing.value = false
|
||||
uni.showToast({ title: '语音识别失败', icon: 'none' })
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
async function startMpVoice() {
|
||||
if (!mpRecoManager) {
|
||||
uni.showToast({ title: '未配置同声传译插件,暂无法使用语音输入', icon: 'none' })
|
||||
resetVoiceState()
|
||||
return
|
||||
}
|
||||
const granted = await ensureRecordPermission()
|
||||
if (!granted) {
|
||||
resetVoiceState()
|
||||
return
|
||||
}
|
||||
voiceRecognizing.value = true
|
||||
mpRecoManager.start({ duration: MAX_VOICE_DURATION_MS, lang: 'zh_CN' })
|
||||
}
|
||||
|
||||
function stopMpVoice() {
|
||||
mpRecoManager?.stop()
|
||||
}
|
||||
|
||||
function cancelVoiceCapture() {
|
||||
// #ifdef H5
|
||||
cleanupH5Recognition()
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
if (voiceRecognizing.value) {
|
||||
plus.speech.stopRecognize()
|
||||
}
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
mpRecoManager?.stop()
|
||||
// #endif
|
||||
|
||||
voiceRecognizing.value = false
|
||||
}
|
||||
|
||||
function toggleInputMode() {
|
||||
if (inputMode.value === 'text') {
|
||||
if (!isVoiceSupported()) {
|
||||
uni.showToast({ title: '当前环境不支持语音输入', icon: 'none' })
|
||||
return
|
||||
}
|
||||
inputMode.value = 'voice'
|
||||
return
|
||||
}
|
||||
cancelVoiceCapture()
|
||||
resetVoiceState()
|
||||
inputMode.value = 'text'
|
||||
}
|
||||
|
||||
async function onVoiceTouchStart() {
|
||||
if (voiceRecognizing.value) return
|
||||
touchCanceled = false
|
||||
voiceHolding.value = true
|
||||
|
||||
// #ifdef H5
|
||||
await startH5Voice()
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
await startMpVoice()
|
||||
// #endif
|
||||
|
||||
clearRecordStopTimer()
|
||||
recordStopTimer = setTimeout(() => {
|
||||
if (voiceHolding.value) {
|
||||
onVoiceTouchEnd()
|
||||
}
|
||||
}, MAX_VOICE_DURATION_MS)
|
||||
}
|
||||
|
||||
function onVoiceTouchEnd() {
|
||||
if (!voiceHolding.value) return
|
||||
voiceHolding.value = false
|
||||
clearRecordStopTimer()
|
||||
|
||||
if (touchCanceled) {
|
||||
cancelVoiceCapture()
|
||||
return
|
||||
}
|
||||
|
||||
// #ifdef H5
|
||||
stopH5Voice()
|
||||
// #endif
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
startAppVoice()
|
||||
// #endif
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
stopMpVoice()
|
||||
// #endif
|
||||
}
|
||||
|
||||
function onVoiceTouchCancel() {
|
||||
touchCanceled = true
|
||||
voiceHolding.value = false
|
||||
clearRecordStopTimer()
|
||||
cancelVoiceCapture()
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
cancelVoiceCapture()
|
||||
clearRecordStopTimer()
|
||||
})
|
||||
|
||||
return {
|
||||
inputMode,
|
||||
voiceHolding,
|
||||
voiceRecognizing,
|
||||
toggleInputMode,
|
||||
onVoiceTouchStart,
|
||||
onVoiceTouchEnd,
|
||||
onVoiceTouchCancel,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { onBeforeUnmount } from 'vue'
|
||||
import { onHide, onShow, onUnload } from '@dcloudio/uni-app'
|
||||
import { computed, ref } from 'vue'
|
||||
import { ensureCsUploadReady } from '@/api/cs-auth'
|
||||
import { fetchProfile } from '@/api/profile'
|
||||
import { getErrorMessage } from '@/utils/api-error'
|
||||
import { getStoredToken } from '@/utils/auth-token'
|
||||
import {
|
||||
@@ -9,12 +11,12 @@ import {
|
||||
fetchCsMessages,
|
||||
fetchCsSessionDetail,
|
||||
resolveCsSession,
|
||||
buildCsImageMessageBody,
|
||||
sendCsMessage,
|
||||
transferCsSession,
|
||||
uploadCsChatImage,
|
||||
} from './support.api'
|
||||
import {
|
||||
connectCsChatSocket,
|
||||
disconnectCsChatSocket,
|
||||
isCsChatSocketConnected,
|
||||
onCsChatPush,
|
||||
@@ -45,7 +47,10 @@ import {
|
||||
injectTimeDividers,
|
||||
mapCsMessage,
|
||||
mergeSupportMessages,
|
||||
cacheSentImageRefs,
|
||||
normalizeCsMediaUrl,
|
||||
normalizeSessionId,
|
||||
registerLocalImagePreview,
|
||||
resolvePhaseFromSession,
|
||||
unwrapCsActionResponse,
|
||||
} from './support.utils'
|
||||
@@ -99,6 +104,7 @@ export function useSupport() {
|
||||
const sessionInitializing = ref(false)
|
||||
const sending = ref(false)
|
||||
const lastSeq = ref(0)
|
||||
const userAvatarUrl = ref('')
|
||||
|
||||
let unsubscribeChatPush: (() => void) | null = null
|
||||
let ensureSessionPromise: Promise<void> | null = null
|
||||
@@ -335,9 +341,26 @@ export function useSupport() {
|
||||
}
|
||||
}
|
||||
|
||||
async function sendUserImageMessage(ossId: string | number, imageUrl: string) {
|
||||
const url = imageUrl.trim()
|
||||
if (!url || !ossId || sending.value) return
|
||||
function appendLocalImageMessage(src: string, clientMsgId: string) {
|
||||
const normalized = normalizeCsMediaUrl(src)
|
||||
if (!normalized) return
|
||||
apiMessages.value = mergeSupportMessages(apiMessages.value, [{
|
||||
id: `local-${clientMsgId}`,
|
||||
type: 'image',
|
||||
role: 'user',
|
||||
src: normalized,
|
||||
createTime: new Date().toISOString(),
|
||||
}])
|
||||
}
|
||||
|
||||
function clearPendingLocalImage(clientMsgId: string) {
|
||||
apiMessages.value = apiMessages.value.filter(
|
||||
(item) => !(item.type === 'image' && item.id === `local-${clientMsgId}`),
|
||||
)
|
||||
}
|
||||
|
||||
async function sendUserImageMessage(ossId: string | number, previewUrl?: string) {
|
||||
if (!ossId || sending.value) return
|
||||
|
||||
if (!sessionId.value) {
|
||||
await ensureSession()
|
||||
@@ -349,16 +372,23 @@ export function useSupport() {
|
||||
|
||||
sending.value = true
|
||||
try {
|
||||
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
||||
content: url,
|
||||
msgType: 'image',
|
||||
ossId: String(ossId),
|
||||
clientMsgId: createClientMsgId(),
|
||||
}))
|
||||
const clientMsgId = createClientMsgId()
|
||||
const preview = previewUrl?.trim() || ''
|
||||
if (preview) {
|
||||
registerLocalImagePreview(ossId, clientMsgId, preview)
|
||||
appendLocalImageMessage(preview, clientMsgId)
|
||||
}
|
||||
const action = unwrapCsActionResponse(await sendCsMessage(
|
||||
sessionId.value,
|
||||
buildCsImageMessageBody(ossId, clientMsgId),
|
||||
))
|
||||
if (action.session) {
|
||||
applySessionState(action.session)
|
||||
}
|
||||
if (action.messages?.length) {
|
||||
if (cacheSentImageRefs(action.messages, clientMsgId, preview)) {
|
||||
clearPendingLocalImage(clientMsgId)
|
||||
}
|
||||
applyActionMessages(action)
|
||||
} else if (!isCsChatSocketConnected()) {
|
||||
await syncMessages()
|
||||
@@ -385,12 +415,12 @@ export function useSupport() {
|
||||
try {
|
||||
const uploaded = await uploadCsChatImage(filePath)
|
||||
const ossId = uploaded.ossId
|
||||
const imageUrl = uploaded.url?.trim() || ''
|
||||
if (!ossId || !imageUrl) {
|
||||
const previewUrl = uploaded.url?.trim() || filePath
|
||||
if (!ossId) {
|
||||
uni.showToast({ title: '上传失败,未获取图片信息', icon: 'none' })
|
||||
return
|
||||
}
|
||||
await sendUserImageMessage(ossId, imageUrl)
|
||||
await sendUserImageMessage(ossId, previewUrl)
|
||||
} catch (err) {
|
||||
uni.showToast({ title: getErrorMessage(err, '图片上传失败'), icon: 'none' })
|
||||
} finally {
|
||||
@@ -418,7 +448,6 @@ export function useSupport() {
|
||||
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
||||
content: text,
|
||||
msgType: 'text',
|
||||
messageType: 'text',
|
||||
clientMsgId: createClientMsgId(),
|
||||
}))
|
||||
if (action.session) {
|
||||
@@ -450,8 +479,7 @@ export function useSupport() {
|
||||
const action = unwrapCsActionResponse(await transferCsSession(sessionId.value))
|
||||
if (action.session) applySessionState(action.session)
|
||||
if (action.messages?.length) applyActionMessages(action)
|
||||
ensureChatPushListener()
|
||||
connectCsChatSocket(sessionId.value)
|
||||
bindChatSocket(sessionId.value)
|
||||
await refreshSession()
|
||||
await syncMessages(false, true)
|
||||
} catch (err) {
|
||||
@@ -547,8 +575,19 @@ export function useSupport() {
|
||||
void sendUserMessage(text)
|
||||
}
|
||||
|
||||
async function loadUserProfile() {
|
||||
try {
|
||||
const profile = await fetchProfile()
|
||||
userAvatarUrl.value = profile?.avatarUrl?.trim() || ''
|
||||
} catch {
|
||||
// 头像加载失败时保留「我」占位
|
||||
}
|
||||
}
|
||||
|
||||
function activatePage() {
|
||||
markSupportPageActive(true)
|
||||
ensureCsUploadReady()
|
||||
void loadUserProfile()
|
||||
if (!sessionId.value) {
|
||||
void ensureSession()
|
||||
return
|
||||
@@ -570,6 +609,7 @@ export function useSupport() {
|
||||
inputValue,
|
||||
sessionId,
|
||||
headerInfo,
|
||||
userAvatarUrl,
|
||||
showTransfer,
|
||||
showEndSession,
|
||||
formattedQueueWait,
|
||||
|
||||
Reference in New Issue
Block a user