fix:客服上传图片及接受问题修复
This commit is contained in:
@@ -1,5 +1,7 @@
|
|||||||
VITE_API_BASE_URL=http://192.168.0.222:8082
|
VITE_API_BASE_URL=http://192.168.0.222:8082
|
||||||
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
||||||
|
# 客服图片上传在 212(/app/cs/upload 仅 212 有该接口)
|
||||||
|
VITE_CS_API_BASE_URL=http://192.168.0.212:8082
|
||||||
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
||||||
# H5 开发:客服 WS 走本地 Vite 代理 → VITE_API_PROXY_TARGET(勿配 212 直连)
|
# H5 开发:客服 WS 走本地 Vite 代理 → VITE_API_PROXY_TARGET(勿配 212 直连)
|
||||||
# 若必须直连 212,取消下行并设 VITE_CS_CHAT_WS_DIRECT=true
|
# 若必须直连 212,取消下行并设 VITE_CS_CHAT_WS_DIRECT=true
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ VITE_API_PROXY_TARGET=http://192.168.0.222:8082
|
|||||||
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
|
# 消息推送 WebSocket(不含 token,连接时自动拼接 ?token=)
|
||||||
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
VITE_MESSAGE_WS_URL=ws://192.168.0.222:8082/app/ws/message
|
||||||
|
|
||||||
|
# 客服图片上传等 CS 服务地址(若与主 API 不同,如上传在 212、主接口在 222)
|
||||||
|
# VITE_CS_API_BASE_URL=http://192.168.0.212:8082
|
||||||
|
|
||||||
|
# 文件上传 clientId(与 Postman /app/cs/upload 一致,默认 app)
|
||||||
|
# VITE_UPLOAD_CLIENT_ID=app
|
||||||
|
|
||||||
# 在线客服 WebSocket(App/小程序直连;H5 开发默认走 Vite 代理,可不配此项)
|
# 在线客服 WebSocket(App/小程序直连;H5 开发默认走 Vite 代理,可不配此项)
|
||||||
# VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat
|
# VITE_CS_CHAT_WS_URL=ws://192.168.0.222:8082/app/cs/chat
|
||||||
# H5 仍要直连内网 IP 时设为 true(如客服 WS 只在 212 上)
|
# H5 仍要直连内网 IP 时设为 true(如客服 WS 只在 212 上)
|
||||||
|
|||||||
98
src/api/cs-auth.ts
Normal file
98
src/api/cs-auth.ts
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import { resolveCsAppBaseUrl, UPLOAD_CLIENT_ID } from './request'
|
||||||
|
import {
|
||||||
|
extractAuthToken,
|
||||||
|
getStoredCsToken,
|
||||||
|
getStoredToken,
|
||||||
|
saveStoredCsToken,
|
||||||
|
} from '@/utils/auth-token'
|
||||||
|
import { ApiError, isApiSuccess } from '@/utils/api-error'
|
||||||
|
import type { ApiResponse } from '@/types/api'
|
||||||
|
|
||||||
|
/** 与客服 API 同服同前缀(真机须为 .../app/auth/...,不能漏 /app) */
|
||||||
|
function resolveCsAuthUrl(path: string): string {
|
||||||
|
const normalized = path.startsWith('/') ? path : `/${path}`
|
||||||
|
const csBase = resolveCsAppBaseUrl()
|
||||||
|
if (csBase) return `${csBase}${normalized}`
|
||||||
|
const main = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
||||||
|
return `${main.replace(/\/$/, '')}/app${normalized}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBody(data: unknown): unknown {
|
||||||
|
if (typeof data === 'string') {
|
||||||
|
if (!data) return {}
|
||||||
|
try {
|
||||||
|
return JSON.parse(data)
|
||||||
|
} catch {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data ?? {}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestCsLogin(path: string, data: Record<string, unknown>): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
uni.request({
|
||||||
|
url: resolveCsAuthUrl(path),
|
||||||
|
method: 'POST',
|
||||||
|
header: {
|
||||||
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
|
clientId: UPLOAD_CLIENT_ID,
|
||||||
|
},
|
||||||
|
data,
|
||||||
|
dataType: 'text',
|
||||||
|
success: (res) => {
|
||||||
|
const body = parseBody(res.data) as ApiResponse
|
||||||
|
if (res.statusCode < 200 || res.statusCode >= 300 || !isApiSuccess(body)) {
|
||||||
|
reject(new ApiError(body?.msg || body?.message || 'CS 登录失败', body?.code ?? res.statusCode))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const token = extractAuthToken(body)
|
||||||
|
if (!token) {
|
||||||
|
reject(new ApiError('CS 登录失败,未获取到令牌'))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
saveStoredCsToken(token)
|
||||||
|
resolve()
|
||||||
|
},
|
||||||
|
fail: (err) => reject(new ApiError(err.errMsg || 'CS 登录失败')),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 主站登录后,向 212 用 clientId=app 同步登录,获取上传专用 token */
|
||||||
|
export async function syncCsAuthByPassword(account: string, password: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
await requestCsLogin('/auth/login/password', {
|
||||||
|
account: account.trim(),
|
||||||
|
password,
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
// 212 不可达时不阻断主登录
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncCsAuthBySms(phone: string, code: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
await requestCsLogin('/auth/login/sms', {
|
||||||
|
phonenumber: phone.trim(),
|
||||||
|
smsCode: code.trim(),
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
// 同上
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 212 无 cs_token 时,用主站 token 兜底(与 upload 请求头逻辑一致) */
|
||||||
|
export function ensureCsUploadReady(): void {
|
||||||
|
if (!getStoredCsToken()) {
|
||||||
|
const main = getStoredToken()
|
||||||
|
if (main) saveStoredCsToken(main)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertCsUploadToken(): void {
|
||||||
|
ensureCsUploadReady()
|
||||||
|
if (!getStoredCsToken() && !getStoredToken()) {
|
||||||
|
throw new ApiError('请先登录后再发送图片', 401)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +1,5 @@
|
|||||||
import { API_CLIENT_ID, request } from '@/api/request'
|
import { request, uploadAppFile } from '@/api/request'
|
||||||
import type { ApiResponse } from '@/types/api'
|
|
||||||
import type { AppUserProfileVo, AvatarUploadVo, UpdateProfileBo } from '@/types/profile'
|
import type { AppUserProfileVo, AvatarUploadVo, UpdateProfileBo } from '@/types/profile'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
|
||||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
|
||||||
|
|
||||||
const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? ''
|
|
||||||
|
|
||||||
/** GET /app/profile — 获取当前用户资料 */
|
/** GET /app/profile — 获取当前用户资料 */
|
||||||
export function fetchProfile() {
|
export function fetchProfile() {
|
||||||
@@ -25,37 +20,5 @@ export function updateProfile(data: UpdateProfileBo) {
|
|||||||
|
|
||||||
/** POST /app/profile/avatar — 上传用户头像 */
|
/** POST /app/profile/avatar — 上传用户头像 */
|
||||||
export function uploadProfileAvatar(filePath: string): Promise<AvatarUploadVo> {
|
export function uploadProfileAvatar(filePath: string): Promise<AvatarUploadVo> {
|
||||||
return new Promise((resolve, reject) => {
|
return uploadAppFile<AvatarUploadVo>('/app/profile/avatar', filePath, 'file')
|
||||||
const token = getStoredToken()
|
|
||||||
uni.uploadFile({
|
|
||||||
url: `${BASE_URL}/app/profile/avatar`,
|
|
||||||
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<AvatarUploadVo>
|
|
||||||
try {
|
|
||||||
body = JSON.parse(res.data) as ApiResponse<AvatarUploadVo>
|
|
||||||
} catch {
|
|
||||||
reject(new ApiError('上传响应解析失败'))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!isApiSuccess(body)) {
|
|
||||||
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
resolve(unwrapApiData(body))
|
|
||||||
},
|
|
||||||
fail: (err) => {
|
|
||||||
reject(new ApiError(err.errMsg || '上传失败'))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import type { ApiResponse } from '@/types/api'
|
import type { ApiResponse } from '@/types/api'
|
||||||
import { extractAuthToken, getStoredToken, saveStoredToken } from '@/utils/auth-token'
|
import {
|
||||||
|
extractAuthToken,
|
||||||
|
formatBearerAuthorization,
|
||||||
|
getStoredCsToken,
|
||||||
|
getStoredToken,
|
||||||
|
saveStoredToken,
|
||||||
|
} from '@/utils/auth-token'
|
||||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
||||||
|
|
||||||
/** H5 开发走 Vite 代理;App/小程序使用完整后端地址 */
|
/** H5 开发走 Vite 代理;App/小程序使用完整后端地址 */
|
||||||
@@ -12,19 +18,40 @@ function resolveBaseUrl(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const BASE_URL = resolveBaseUrl()
|
const BASE_URL = resolveBaseUrl()
|
||||||
/** RuoYi-Vue-Plus App 端 clientId(请求头 clientid,与 Postman 一致) */
|
/** RuoYi-Vue-Plus App 端 clientId(登录等 JSON 接口) */
|
||||||
export const API_CLIENT_ID =
|
export const API_CLIENT_ID =
|
||||||
import.meta.env.VITE_API_CLIENT_ID || '428a8310cd442757ae699df5d894f051'
|
import.meta.env.VITE_API_CLIENT_ID || '428a8310cd442757ae699df5d894f051'
|
||||||
|
|
||||||
|
/** 文件上传 clientId(与 Postman /app/cs/upload 一致) */
|
||||||
|
export const UPLOAD_CLIENT_ID = import.meta.env.VITE_UPLOAD_CLIENT_ID || 'app'
|
||||||
|
|
||||||
/** 将响应 JSON 中的 int64 主键字段转为字符串,避免 JS 精度丢失 */
|
/** 将响应 JSON 中的 int64 主键字段转为字符串,避免 JS 精度丢失 */
|
||||||
function parseJsonPreserveIdFields(text: string): unknown {
|
function parseJsonPreserveIdFields(text: string): unknown {
|
||||||
const safe = text.replace(
|
const safe = text.replace(
|
||||||
/"(deviceId|homeId|locationId|productId|sessionId|messageId|alertId|seq|id)"\s*:\s*(\d+)/g,
|
/"(deviceId|homeId|locationId|productId|sessionId|messageId|alertId|ossId|seq|id)"\s*:\s*(\d+)/g,
|
||||||
'"$1":"$2"',
|
'"$1":"$2"',
|
||||||
)
|
)
|
||||||
return JSON.parse(safe)
|
return JSON.parse(safe)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 212 客服服务根路径(含 /app);未配置时返回空字符串 */
|
||||||
|
export function resolveCsAppBaseUrl(): string {
|
||||||
|
const csBase = import.meta.env.VITE_CS_API_BASE_URL?.trim()
|
||||||
|
// #ifdef H5
|
||||||
|
if (import.meta.env.DEV) return '/cs-app'
|
||||||
|
// #endif
|
||||||
|
if (csBase) return `${csBase.replace(/\/$/, '')}/app`
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCsAppRequestUrl(path: string): string {
|
||||||
|
const csBase = resolveCsAppBaseUrl()
|
||||||
|
if (!csBase) return `${BASE_URL}${path}`
|
||||||
|
if (path.startsWith('/app/')) return `${csBase}${path.slice(4)}`
|
||||||
|
if (path.startsWith('/app')) return `${csBase}${path.slice(4)}`
|
||||||
|
return `${csBase}${path.startsWith('/') ? path : `/${path}`}`
|
||||||
|
}
|
||||||
|
|
||||||
function parseResponseBody(data: unknown): unknown {
|
function parseResponseBody(data: unknown): unknown {
|
||||||
if (typeof data === 'string') {
|
if (typeof data === 'string') {
|
||||||
if (!data) return {}
|
if (!data) return {}
|
||||||
@@ -41,17 +68,166 @@ export interface RequestOptions extends Omit<UniApp.RequestOptions, 'url'> {
|
|||||||
url: string
|
url: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 构建鉴权请求头:clientid + Authorization */
|
/** 构建鉴权请求头:clientId + Authorization */
|
||||||
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
export function buildAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||||
const token = getStoredToken()
|
const authorization = formatBearerAuthorization(getStoredToken())
|
||||||
return {
|
return {
|
||||||
'Content-Type': 'application/json;charset=UTF-8',
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
clientId: API_CLIENT_ID,
|
clientId: API_CLIENT_ID,
|
||||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
...(authorization ? { Authorization: authorization } : {}),
|
||||||
...(extra as Record<string, string> | undefined),
|
...(extra as Record<string, string> | undefined),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 头像等主服务上传鉴权头 */
|
||||||
|
export function buildUploadAuthHeaders(): Record<string, string> {
|
||||||
|
const authorization = formatBearerAuthorization(getStoredToken())
|
||||||
|
return {
|
||||||
|
clientId: API_CLIENT_ID,
|
||||||
|
...(authorization ? { Authorization: authorization } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 下载 OSS 等资源(GET),勿带 Content-Type */
|
||||||
|
export function buildDownloadAuthHeaders(): Record<string, string> {
|
||||||
|
const authorization = formatBearerAuthorization(getStoredToken())
|
||||||
|
return {
|
||||||
|
clientId: API_CLIENT_ID,
|
||||||
|
...(authorization ? { Authorization: authorization } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveCsAppToken(): string {
|
||||||
|
return getStoredCsToken() || getStoredToken()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 客服图片上传鉴权头(212,clientId=app,使用 cs_token) */
|
||||||
|
export function buildCsUploadAuthHeaders(): Record<string, string> {
|
||||||
|
const authorization = formatBearerAuthorization(resolveCsAppToken())
|
||||||
|
return {
|
||||||
|
clientId: UPLOAD_CLIENT_ID,
|
||||||
|
...(authorization ? { Authorization: authorization } : {}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 212 客服 JSON 接口鉴权(与 upload 一致:clientId=app + cs_token) */
|
||||||
|
export function buildCsAppAuthHeaders(extra?: Record<string, unknown>): Record<string, string> {
|
||||||
|
const authorization = formatBearerAuthorization(resolveCsAppToken())
|
||||||
|
return {
|
||||||
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
|
clientId: UPLOAD_CLIENT_ID,
|
||||||
|
...(authorization ? { Authorization: authorization } : {}),
|
||||||
|
...(extra as Record<string, string> | undefined),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type UploadAuthMode = 'default' | 'cs'
|
||||||
|
|
||||||
|
function resolveUploadAuthHeaders(mode: UploadAuthMode): Record<string, string> {
|
||||||
|
return mode === 'cs' ? buildCsUploadAuthHeaders() : buildUploadAuthHeaders()
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveUploadUrl(url: string): string {
|
||||||
|
if (/^https?:\/\//i.test(url)) return url
|
||||||
|
const path = url.startsWith('/') ? url : `/${url}`
|
||||||
|
return `${BASE_URL}${path}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUploadSuccess<T>(
|
||||||
|
statusCode: number,
|
||||||
|
rawData: string,
|
||||||
|
resolve: (value: T) => void,
|
||||||
|
reject: (reason: ApiError) => void,
|
||||||
|
) {
|
||||||
|
if (statusCode < 200 || statusCode >= 300) {
|
||||||
|
let message = `上传失败(${statusCode})`
|
||||||
|
try {
|
||||||
|
const body = JSON.parse(rawData) as ApiResponse
|
||||||
|
message = body.msg || body.message || message
|
||||||
|
reject(new ApiError(message, body.code ?? statusCode))
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
reject(new ApiError(message, statusCode))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: ApiResponse<T>
|
||||||
|
try {
|
||||||
|
body = parseResponseBody(rawData) as ApiResponse<T>
|
||||||
|
} catch {
|
||||||
|
reject(new ApiError('上传响应解析失败'))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!isApiSuccess(body)) {
|
||||||
|
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resolve(unwrapApiData<T>(body as ApiResponse<T> & Record<string, unknown>))
|
||||||
|
}
|
||||||
|
|
||||||
|
function uploadViaUniMultipart<T>(
|
||||||
|
targetUrl: string,
|
||||||
|
filePath: string,
|
||||||
|
fieldName: string,
|
||||||
|
authMode: UploadAuthMode,
|
||||||
|
): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
uni.uploadFile({
|
||||||
|
url: targetUrl,
|
||||||
|
filePath,
|
||||||
|
name: fieldName,
|
||||||
|
header: resolveUploadAuthHeaders(authMode),
|
||||||
|
success: (res) => {
|
||||||
|
handleUploadSuccess<T>(res.statusCode, String(res.data ?? ''), resolve, reject)
|
||||||
|
},
|
||||||
|
fail: (err) => {
|
||||||
|
reject(new ApiError(err.errMsg || '上传失败'))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** H5 用 fetch 发送 multipart,确保 Authorization: Bearer xxx 能带上 */
|
||||||
|
async function uploadViaFetchH5<T>(
|
||||||
|
targetUrl: string,
|
||||||
|
filePath: string,
|
||||||
|
fieldName: string,
|
||||||
|
authMode: UploadAuthMode,
|
||||||
|
): Promise<T> {
|
||||||
|
const blobRes = await fetch(filePath)
|
||||||
|
const blob = await blobRes.blob()
|
||||||
|
const ext = blob.type.split('/')[1] || 'jpg'
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append(fieldName, blob, `upload.${ext}`)
|
||||||
|
|
||||||
|
const response = await fetch(targetUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: resolveUploadAuthHeaders(authMode),
|
||||||
|
body: formData,
|
||||||
|
})
|
||||||
|
const rawData = await response.text()
|
||||||
|
return new Promise<T>((resolve, reject) => {
|
||||||
|
handleUploadSuccess<T>(response.status, rawData, resolve, reject)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** multipart/form-data 上传;H5 走 fetch 确保 Bearer token 发出 */
|
||||||
|
export function uploadAppFile<T>(
|
||||||
|
url: string,
|
||||||
|
filePath: string,
|
||||||
|
fieldName = 'file',
|
||||||
|
authMode: UploadAuthMode = 'default',
|
||||||
|
): Promise<T> {
|
||||||
|
const targetUrl = resolveUploadUrl(url)
|
||||||
|
|
||||||
|
// #ifdef H5
|
||||||
|
return uploadViaFetchH5<T>(targetUrl, filePath, fieldName, authMode)
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
return uploadViaUniMultipart<T>(targetUrl, filePath, fieldName, authMode)
|
||||||
|
}
|
||||||
|
|
||||||
function handleSuccess<T>(
|
function handleSuccess<T>(
|
||||||
res: UniApp.RequestSuccessCallbackResult,
|
res: UniApp.RequestSuccessCallbackResult,
|
||||||
resolve: (value: T) => void,
|
resolve: (value: T) => void,
|
||||||
@@ -83,14 +259,19 @@ function handleSuccess<T>(
|
|||||||
resolve(unwrapApiData<T>(body))
|
resolve(unwrapApiData<T>(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
export function request<T = unknown>(options: RequestOptions): Promise<T> {
|
function runRequest<T>(
|
||||||
|
options: RequestOptions,
|
||||||
|
url: string,
|
||||||
|
buildHeaders: (extra?: Record<string, unknown>) => Record<string, string>,
|
||||||
|
saveTokenFromBody = false,
|
||||||
|
): Promise<T> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
uni.request({
|
uni.request({
|
||||||
...options,
|
...options,
|
||||||
url: `${BASE_URL}${options.url}`,
|
url,
|
||||||
header: buildAuthHeaders(options.header),
|
header: buildHeaders(options.header),
|
||||||
dataType: 'text',
|
dataType: 'text',
|
||||||
success: (res) => handleSuccess<T>(res, resolve, reject),
|
success: (res) => handleSuccess<T>(res, resolve, reject, saveTokenFromBody),
|
||||||
fail: (err) => {
|
fail: (err) => {
|
||||||
reject(new ApiError(err.errMsg || '网络异常'))
|
reject(new ApiError(err.errMsg || '网络异常'))
|
||||||
},
|
},
|
||||||
@@ -98,6 +279,20 @@ export function request<T = unknown>(options: RequestOptions): Promise<T> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function request<T = unknown>(options: RequestOptions): Promise<T> {
|
||||||
|
return runRequest<T>(options, `${BASE_URL}${options.url}`, buildAuthHeaders)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 212 客服服务(与主站 222 的 CzCsMessageBo 不同:212 支持 ossId 字段)。
|
||||||
|
* 图片发消息须走此通道,且鉴权与 upload 一致(clientId=app + cs_token)。
|
||||||
|
*/
|
||||||
|
export function requestCsApp<T = unknown>(options: RequestOptions): Promise<T> {
|
||||||
|
const csBase = resolveCsAppBaseUrl()
|
||||||
|
if (!csBase) return request<T>(options)
|
||||||
|
return runRequest<T>(options, buildCsAppRequestUrl(options.url), buildCsAppAuthHeaders)
|
||||||
|
}
|
||||||
|
|
||||||
/** 登录类接口:从完整响应体提取并保存 token */
|
/** 登录类接口:从完整响应体提取并保存 token */
|
||||||
export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
|
export function requestLogin<T = unknown>(options: RequestOptions): Promise<T> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
import { request } from '@/api/request'
|
import { request } from '@/api/request'
|
||||||
import type { ProductOption } from './complete.types'
|
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() {
|
export function fetchProductOptions() {
|
||||||
return request<ProductOption[]>({
|
return request<ProductOption[]>({
|
||||||
url: '/app/device/productOptions',
|
url: '/app/device/productOptions',
|
||||||
method: 'POST',
|
method: 'GET',
|
||||||
data: {},
|
}).then((rows) => (Array.isArray(rows) ? rows.map(normalizeProductOption) : []))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -168,6 +168,7 @@
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.complete-page__select-text,
|
||||||
.complete-page__room-text {
|
.complete-page__room-text {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
font-size: 28rpx;
|
font-size: 28rpx;
|
||||||
|
|||||||
@@ -55,15 +55,11 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="complete-page__field">
|
<view class="complete-page__field">
|
||||||
<text class="complete-page__label">产品型号</text>
|
<text class="complete-page__label">产品型号</text>
|
||||||
<picker
|
<view
|
||||||
mode="selector"
|
class="complete-page__select-row"
|
||||||
:range="productOptions"
|
hover-class="complete-page__select-row--hover"
|
||||||
range-key="model"
|
@tap.stop="onPickProduct"
|
||||||
:value="productIndex"
|
|
||||||
:disabled="productOptionsLoading || !productOptions.length"
|
|
||||||
@change="onProductChange"
|
|
||||||
>
|
>
|
||||||
<view class="complete-page__select-row">
|
|
||||||
<text
|
<text
|
||||||
class="complete-page__select-text"
|
class="complete-page__select-text"
|
||||||
:class="{ 'complete-page__select-text--placeholder': !productSelected }"
|
:class="{ 'complete-page__select-text--placeholder': !productSelected }"
|
||||||
@@ -76,7 +72,6 @@
|
|||||||
mode="aspectFit"
|
mode="aspectFit"
|
||||||
/>
|
/>
|
||||||
</view>
|
</view>
|
||||||
</picker>
|
|
||||||
</view>
|
</view>
|
||||||
<view class="complete-page__field">
|
<view class="complete-page__field">
|
||||||
<text class="complete-page__label">所在房间</text>
|
<text class="complete-page__label">所在房间</text>
|
||||||
@@ -139,8 +134,6 @@ const {
|
|||||||
currentStep,
|
currentStep,
|
||||||
deviceName,
|
deviceName,
|
||||||
serialMasked,
|
serialMasked,
|
||||||
productOptions,
|
|
||||||
productIndex,
|
|
||||||
productDisplayText,
|
productDisplayText,
|
||||||
productSelected,
|
productSelected,
|
||||||
productOptionsLoading,
|
productOptionsLoading,
|
||||||
@@ -151,7 +144,7 @@ const {
|
|||||||
bluetoothConnected,
|
bluetoothConnected,
|
||||||
bluetoothStatusText,
|
bluetoothStatusText,
|
||||||
initPage,
|
initPage,
|
||||||
onProductChange,
|
onPickProduct,
|
||||||
onPickRoom,
|
onPickRoom,
|
||||||
onFinishAdd,
|
onFinishAdd,
|
||||||
} = useCompleteDevice()
|
} = useCompleteDevice()
|
||||||
|
|||||||
@@ -157,11 +157,26 @@ export function useCompleteDevice() {
|
|||||||
initialized.value = true
|
initialized.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
function onProductChange(event: { detail: { value: number } }) {
|
function onPickProduct() {
|
||||||
const index = Number(event.detail.value)
|
if (productOptionsLoading.value) {
|
||||||
const option = productOptions.value[index]
|
uni.showToast({ title: '产品型号加载中', icon: 'none' })
|
||||||
if (!option) return
|
return
|
||||||
applyProduct(option)
|
}
|
||||||
|
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() {
|
function onPickRoom() {
|
||||||
@@ -268,7 +283,7 @@ export function useCompleteDevice() {
|
|||||||
bluetoothConnected,
|
bluetoothConnected,
|
||||||
bluetoothStatusText,
|
bluetoothStatusText,
|
||||||
initPage,
|
initPage,
|
||||||
onProductChange,
|
onPickProduct,
|
||||||
onPickRoom,
|
onPickRoom,
|
||||||
onFinishAdd,
|
onFinishAdd,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { onShow } from '@dcloudio/uni-app'
|
import { onHide, onShow } from '@dcloudio/uni-app'
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
import { refreshUnreadMessageCount } from '@/hooks/use-message-inbox'
|
||||||
import { fetchHomeList, resolveValidHomeId } from '@/api/home'
|
import { fetchHomeList, resolveValidHomeId } from '@/api/home'
|
||||||
@@ -17,6 +17,9 @@ import {
|
|||||||
mapDeviceItem,
|
mapDeviceItem,
|
||||||
} from './device.utils'
|
} from './device.utils'
|
||||||
|
|
||||||
|
/** 与设备详情页 BLE 同步间隔一致 */
|
||||||
|
const PRESENCE_INTERVAL_MS = 15000
|
||||||
|
|
||||||
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
|
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
|
||||||
{
|
{
|
||||||
id: 'z2',
|
id: 'z2',
|
||||||
@@ -42,6 +45,8 @@ export function useDevice() {
|
|||||||
const roomDialogVisible = ref(false)
|
const roomDialogVisible = ref(false)
|
||||||
const successToastVisible = ref(false)
|
const successToastVisible = ref(false)
|
||||||
|
|
||||||
|
let presenceTimer: ReturnType<typeof setInterval> | undefined
|
||||||
|
|
||||||
const hasDevices = computed(() => devices.value.length > 0)
|
const hasDevices = computed(() => devices.value.length > 0)
|
||||||
|
|
||||||
const filteredDevices = computed(() =>
|
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(() => {
|
onShow(() => {
|
||||||
void loadDevices()
|
void loadDevices()
|
||||||
void refreshUnreadMessageCount()
|
void refreshUnreadMessageCount()
|
||||||
|
startPresencePolling()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
onHide(stopPresencePolling)
|
||||||
|
|
||||||
function showOperationSuccess() {
|
function showOperationSuccess() {
|
||||||
successToastVisible.value = true
|
successToastVisible.value = true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { getErrorMessage } from '@/utils/api-error'
|
|||||||
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
import { setupMessageInbox } from '@/hooks/use-message-inbox'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { getStoredToken } from '@/utils/auth-token'
|
||||||
import { SMS_CODE_SCENE } from '@/types/api'
|
import { SMS_CODE_SCENE } from '@/types/api'
|
||||||
|
import { syncCsAuthByPassword, syncCsAuthBySms } from '@/api/cs-auth'
|
||||||
import { loginByPassword, loginBySms } from './login.api'
|
import { loginByPassword, loginBySms } from './login.api'
|
||||||
import type { LoginMode } from './login.types'
|
import type { LoginMode } from './login.types'
|
||||||
|
|
||||||
@@ -46,6 +47,7 @@ export function useLogin() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
await loginBySms({ phone: phone.value, code: code.value })
|
await loginBySms({ phone: phone.value, code: code.value })
|
||||||
|
await syncCsAuthBySms(phone.value, code.value)
|
||||||
} else {
|
} else {
|
||||||
if (!account.value.trim()) {
|
if (!account.value.trim()) {
|
||||||
uni.showToast({ title: '请输入账号', icon: 'none' })
|
uni.showToast({ title: '请输入账号', icon: 'none' })
|
||||||
@@ -59,6 +61,7 @@ export function useLogin() {
|
|||||||
account: account.value,
|
account: account.value,
|
||||||
password: password.value,
|
password: password.value,
|
||||||
})
|
})
|
||||||
|
await syncCsAuthByPassword(account.value, password.value)
|
||||||
}
|
}
|
||||||
if (!getStoredToken()) {
|
if (!getStoredToken()) {
|
||||||
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
|
uni.showToast({ title: '登录失败,未获取到令牌', icon: 'none' })
|
||||||
|
|||||||
@@ -8,6 +8,14 @@ export function isUnreadMessage(message: AppMessageVo): boolean {
|
|||||||
return flag === 0 || flag === '0'
|
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 {
|
export function formatNotifyTime(message: AppMessageVo): string {
|
||||||
const raw = message.timestamp || message.createTime
|
const raw = message.timestamp || message.createTime
|
||||||
if (!raw) return ''
|
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)
|
const date = /^\d{13,}$/.test(text) ? new Date(Number(text)) : new Date(text)
|
||||||
if (Number.isNaN(date.getTime())) return 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'
|
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 socketTask: UniApp.SocketTask | null = null
|
||||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
@@ -11,6 +13,7 @@ let activeSessionId = ''
|
|||||||
let socketOpened = false
|
let socketOpened = false
|
||||||
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
|
/** 每次 connect / disconnect 递增,忽略已废弃连接的 onClose */
|
||||||
let connectionSeq = 0
|
let connectionSeq = 0
|
||||||
|
let reconnectAttempt = 0
|
||||||
|
|
||||||
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
const listeners = new Set<(payload: CsChatWsPayload) => void>()
|
||||||
|
|
||||||
@@ -25,13 +28,21 @@ function resolveCsChatWsBase(): string {
|
|||||||
|
|
||||||
if (isH5Dev() && !forceDirect) {
|
if (isH5Dev() && !forceDirect) {
|
||||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
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) {
|
if (configured) {
|
||||||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
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 envBase = import.meta.env.VITE_API_BASE_URL?.trim() || ''
|
||||||
const fallback =
|
const fallback =
|
||||||
import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.222:8082'
|
import.meta.env.VITE_API_PROXY_TARGET?.trim() || 'http://192.168.0.222:8082'
|
||||||
@@ -68,11 +79,16 @@ function clearReconnectTimer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function scheduleReconnect() {
|
function scheduleReconnect() {
|
||||||
if (manualClosed || !getStoredToken() || !activeSessionId) return
|
if (manualClosed || !resolveCsAppToken() || !activeSessionId) return
|
||||||
clearReconnectTimer()
|
clearReconnectTimer()
|
||||||
|
const delay = Math.min(
|
||||||
|
RECONNECT_BASE_MS * Math.pow(1.5, reconnectAttempt),
|
||||||
|
RECONNECT_MAX_MS,
|
||||||
|
)
|
||||||
|
reconnectAttempt += 1
|
||||||
reconnectTimer = setTimeout(() => {
|
reconnectTimer = setTimeout(() => {
|
||||||
connectCsChatSocket(activeSessionId)
|
connectCsChatSocket(activeSessionId)
|
||||||
}, RECONNECT_DELAY_MS)
|
}, delay)
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetSocketState() {
|
function resetSocketState() {
|
||||||
@@ -81,7 +97,7 @@ function resetSocketState() {
|
|||||||
connecting = false
|
connecting = false
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
function parseCsChatPayload(raw: string): CsChatWsPayload | null {
|
||||||
if (!raw || raw === 'ping' || raw === 'pong') return null
|
if (!raw || raw === 'ping' || raw === 'pong') return null
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(raw) as Record<string, unknown>
|
const parsed = JSON.parse(raw) as Record<string, unknown>
|
||||||
@@ -163,6 +179,7 @@ function bindSocketTask(task: UniApp.SocketTask, seq: number) {
|
|||||||
if (seq !== connectionSeq) return
|
if (seq !== connectionSeq) return
|
||||||
socketOpened = true
|
socketOpened = true
|
||||||
connecting = false
|
connecting = false
|
||||||
|
reconnectAttempt = 0
|
||||||
if (import.meta.env.DEV) console.log('[CS Chat WS] connected')
|
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) {
|
export function connectCsChatSocket(sessionId: string) {
|
||||||
const token = getStoredToken()
|
const token = resolveCsAppToken()
|
||||||
if (!token || !sessionId) return
|
if (!token || !sessionId) return
|
||||||
if (connecting) return
|
if (connecting) return
|
||||||
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
if (socketOpened && socketTask && activeSessionId === sessionId) return
|
||||||
@@ -244,6 +261,7 @@ export function disconnectCsChatSocket() {
|
|||||||
manualClosed = true
|
manualClosed = true
|
||||||
connectionSeq += 1
|
connectionSeq += 1
|
||||||
activeSessionId = ''
|
activeSessionId = ''
|
||||||
|
reconnectAttempt = 0
|
||||||
clearReconnectTimer()
|
clearReconnectTimer()
|
||||||
const task = socketTask
|
const task = socketTask
|
||||||
socketTask = null
|
socketTask = null
|
||||||
|
|||||||
@@ -88,7 +88,13 @@
|
|||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
|
<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>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
@@ -224,14 +230,21 @@
|
|||||||
>
|
>
|
||||||
<image
|
<image
|
||||||
class="support-page__image"
|
class="support-page__image"
|
||||||
:src="item.src"
|
:src="chatImageDisplaySrc(item)"
|
||||||
mode="aspectFill"
|
mode="aspectFill"
|
||||||
@tap="onPreviewImage(item.src)"
|
@error="onChatImageError(item)"
|
||||||
|
@tap="onPreviewImage(chatImageDisplaySrc(item))"
|
||||||
/>
|
/>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view v-if="item.role === 'user'" class="support-page__msg-avatar support-page__msg-avatar--user">
|
<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>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
@@ -254,44 +267,18 @@
|
|||||||
</text>
|
</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="support-page__input-row">
|
<view class="support-page__input-row">
|
||||||
<view class="support-page__mic" @tap="toggleInputMode">
|
<view class="support-page__input-wrap">
|
||||||
<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">
|
|
||||||
<input
|
<input
|
||||||
v-model="inputValue"
|
v-model="inputValue"
|
||||||
class="support-page__input"
|
class="support-page__input"
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="输入你的问题..."
|
placeholder="输入你的问题.."
|
||||||
placeholder-class="support-page__input-placeholder"
|
placeholder-class="support-page__input-placeholder"
|
||||||
confirm-type="send"
|
confirm-type="send"
|
||||||
@confirm="onSend"
|
@confirm="onSend"
|
||||||
/>
|
/>
|
||||||
</view>
|
</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">
|
<view class="support-page__tag" @tap="onPickImage">
|
||||||
<image
|
<image
|
||||||
class="support-page__tag-icon"
|
class="support-page__tag-icon"
|
||||||
@@ -306,7 +293,6 @@
|
|||||||
mode="aspectFit"
|
mode="aspectFit"
|
||||||
/>
|
/>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -315,14 +301,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, ref, watch } from 'vue'
|
import { computed, nextTick, ref, watch } from 'vue'
|
||||||
import { staticAssets } from '@/utils/static-assets'
|
import { staticAssets } from '@/utils/static-assets'
|
||||||
|
import { useCsChatImage } from './use-cs-chat-image'
|
||||||
import { useSupport } from './use-support'
|
import { useSupport } from './use-support'
|
||||||
import { useSupportVoice } from './use-support-voice'
|
|
||||||
import type { DiagnosisItem } from './support.types'
|
import type { DiagnosisItem } from './support.types'
|
||||||
|
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
inputValue,
|
inputValue,
|
||||||
headerInfo,
|
headerInfo,
|
||||||
|
userAvatarUrl,
|
||||||
showTransfer,
|
showTransfer,
|
||||||
showEndSession,
|
showEndSession,
|
||||||
formattedQueueWait,
|
formattedQueueWait,
|
||||||
@@ -338,28 +325,11 @@ const {
|
|||||||
onPickImage,
|
onPickImage,
|
||||||
} = useSupport()
|
} = useSupport()
|
||||||
|
|
||||||
const {
|
|
||||||
inputMode,
|
|
||||||
voiceHolding,
|
|
||||||
voiceRecognizing,
|
|
||||||
toggleInputMode,
|
|
||||||
onVoiceTouchStart,
|
|
||||||
onVoiceTouchEnd,
|
|
||||||
onVoiceTouchCancel,
|
|
||||||
} = useSupportVoice({
|
|
||||||
onRecognized: (text) => {
|
|
||||||
inputValue.value = text
|
|
||||||
onSend()
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
|
const humanAvatarText = computed(() => headerInfo.value.avatarText || '服')
|
||||||
|
|
||||||
const voiceButtonText = computed(() => {
|
const { displaySrc: chatImageDisplaySrc, onImageError: onChatImageError } = useCsChatImage(
|
||||||
if (voiceRecognizing.value && !voiceHolding.value) return '识别中...'
|
() => messages.value,
|
||||||
if (voiceHolding.value) return '松手 发送'
|
)
|
||||||
return '按住 说话'
|
|
||||||
})
|
|
||||||
|
|
||||||
const scrollIntoView = ref('chat-bottom')
|
const scrollIntoView = ref('chat-bottom')
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ let messagePollTimer: ReturnType<typeof setInterval> | null = null
|
|||||||
let queueTimer: ReturnType<typeof setInterval> | null = null
|
let queueTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
|
||||||
const QUEUE_POLL_INTERVAL_MS = 5000
|
const QUEUE_POLL_INTERVAL_MS = 5000
|
||||||
const MESSAGE_POLL_INTERVAL_MS = 5000
|
const MESSAGE_POLL_INTERVAL_MS = 10000
|
||||||
|
|
||||||
export function isSupportPageActive(): boolean {
|
export function isSupportPageActive(): boolean {
|
||||||
return pageActive
|
return pageActive
|
||||||
@@ -30,13 +30,6 @@ export function stopSupportQueueTimer() {
|
|||||||
queueTimer = null
|
queueTimer = null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function teardownSupportRuntime() {
|
|
||||||
markSupportPageActive(false)
|
|
||||||
stopSupportPollTimer()
|
|
||||||
stopSupportMessagePollTimer()
|
|
||||||
stopSupportQueueTimer()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 定时增量拉消息(WebSocket 漏推时的兜底) */
|
/** 定时增量拉消息(WebSocket 漏推时的兜底) */
|
||||||
export function startSupportMessagePolling(onTick: () => void) {
|
export function startSupportMessagePolling(onTick: () => void) {
|
||||||
stopSupportMessagePollTimer()
|
stopSupportMessagePollTimer()
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
import { API_CLIENT_ID, request } from '@/api/request'
|
import { resolveCsAppBaseUrl, request, requestCsApp, uploadAppFile } from '@/api/request'
|
||||||
import type { ApiResponse } from '@/types/api'
|
import { assertCsUploadToken, ensureCsUploadReady } from '@/api/cs-auth'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { ApiError } from '@/utils/api-error'
|
||||||
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
|
||||||
import {
|
import {
|
||||||
isSessionEnded,
|
isSessionEnded,
|
||||||
|
normalizeCsMediaUrl,
|
||||||
normalizeSessionId,
|
normalizeSessionId,
|
||||||
normalizeSessionResponse,
|
normalizeSessionResponse,
|
||||||
|
registerCsImageUrl,
|
||||||
unwrapCsActionResponse,
|
unwrapCsActionResponse,
|
||||||
} from './support.utils'
|
} from './support.utils'
|
||||||
|
import { CS_IMAGE_MESSAGE_PLACEHOLDER } from './support.types'
|
||||||
import type {
|
import type {
|
||||||
CsAppActionVo,
|
CsAppActionVo,
|
||||||
CsClickButtonBody,
|
CsClickButtonBody,
|
||||||
CsChatImageUploadVo,
|
|
||||||
CzCsUploadVo,
|
CzCsUploadVo,
|
||||||
CsCreateSessionBody,
|
CsCreateSessionBody,
|
||||||
CsMessageVo,
|
CsMessageVo,
|
||||||
@@ -26,12 +27,15 @@ function buildSessionPath(sessionId: string, suffix = '') {
|
|||||||
return `/app/cs/session/${encodeURIComponent(sessionId)}${suffix}`
|
return `/app/cs/session/${encodeURIComponent(sessionId)}${suffix}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveUploadBaseUrl(): string {
|
/** 客服会话相关接口统一走 212(与 upload / 图片 message 同服,保证 ossId、url 一致) */
|
||||||
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
|
function csRequest<T>(options: Parameters<typeof request>[0]): Promise<T> {
|
||||||
// #ifdef H5
|
return resolveCsAppBaseUrl() ? requestCsApp<T>(options) : request<T>(options)
|
||||||
if (import.meta.env.DEV) return ''
|
}
|
||||||
// #endif
|
|
||||||
return envUrl
|
function resolveCsUploadUrl(): string {
|
||||||
|
const csBase = resolveCsAppBaseUrl()
|
||||||
|
if (csBase) return `${csBase}/cs/upload`
|
||||||
|
return '/app/cs/upload'
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
||||||
@@ -44,9 +48,12 @@ function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
|||||||
if (!url) {
|
if (!url) {
|
||||||
throw new ApiError('上传失败,未返回访问地址')
|
throw new ApiError('上传失败,未返回访问地址')
|
||||||
}
|
}
|
||||||
|
const normalizedUrl = normalizeCsMediaUrl(url)
|
||||||
|
const ossIdStr = typeof ossId === 'number' ? String(ossId) : String(ossId)
|
||||||
|
registerCsImageUrl(ossIdStr, normalizedUrl)
|
||||||
return {
|
return {
|
||||||
ossId: typeof ossId === 'number' ? String(ossId) : String(ossId),
|
ossId: ossIdStr,
|
||||||
url,
|
url: normalizedUrl,
|
||||||
fileName: raw.fileName != null ? String(raw.fileName) : undefined,
|
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 — 创建客服会话;已有未结束会话时返回原会话 */
|
/** POST /app/cs/session — 创建客服会话;已有未结束会话时返回原会话 */
|
||||||
export function createCsSession(data: CsCreateSessionBody = {}) {
|
export function createCsSession(data: CsCreateSessionBody = {}) {
|
||||||
return request<CsAppActionVo | CsSessionVo | string | null>({
|
return csRequest<CsAppActionVo | CsSessionVo | string | null>({
|
||||||
url: '/app/cs/session',
|
url: '/app/cs/session',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data,
|
data,
|
||||||
@@ -106,7 +113,7 @@ export async function resolveCsSession(): Promise<CsResolvedSession> {
|
|||||||
|
|
||||||
/** GET /app/cs/session/list — 查询自己的会话 */
|
/** GET /app/cs/session/list — 查询自己的会话 */
|
||||||
export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
||||||
return request<CsSessionVo[] | CsTableData<CsSessionVo>>({
|
return csRequest<CsSessionVo[] | CsTableData<CsSessionVo>>({
|
||||||
url: '/app/cs/session/list',
|
url: '/app/cs/session/list',
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
data: query,
|
data: query,
|
||||||
@@ -115,7 +122,7 @@ export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
|||||||
|
|
||||||
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
||||||
export function fetchCsSessionDetail(sessionId: string) {
|
export function fetchCsSessionDetail(sessionId: string) {
|
||||||
return request<CsAppActionVo | CsSessionVo | string | null>({
|
return csRequest<CsAppActionVo | CsSessionVo | string | null>({
|
||||||
url: buildSessionPath(sessionId),
|
url: buildSessionPath(sessionId),
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
|
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
|
||||||
@@ -123,57 +130,39 @@ export function fetchCsSessionDetail(sessionId: string) {
|
|||||||
|
|
||||||
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
||||||
export function fetchCsMessages(sessionId: string, afterSeq = 0) {
|
export function fetchCsMessages(sessionId: string, afterSeq = 0) {
|
||||||
return request<CsMessageVo[] | CsTableData<CsMessageVo>>({
|
return csRequest<CsMessageVo[] | CsTableData<CsMessageVo>>({
|
||||||
url: buildSessionPath(sessionId, '/messages'),
|
url: buildSessionPath(sessionId, '/messages'),
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
data: { afterSeq },
|
data: { afterSeq },
|
||||||
}).then(unwrapRows)
|
}).then(unwrapRows)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** POST /app/cs/upload — 上传聊天图片 */
|
/** POST /app/cs/upload — 212 上传(clientId=app + cs_token) */
|
||||||
export function uploadCsChatImage(filePath: string): Promise<CsChatImageUploadVo> {
|
export function uploadCsChatImage(filePath: string): Promise<CzCsUploadVo> {
|
||||||
return new Promise((resolve, reject) => {
|
assertCsUploadToken()
|
||||||
const token = getStoredToken()
|
return uploadAppFile<CzCsUploadVo>(resolveCsUploadUrl(), filePath, 'file', 'cs').then((data) =>
|
||||||
uni.uploadFile({
|
normalizeCsUploadVo(data),
|
||||||
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 {
|
/** 图片消息体:msgType + ossId + clientMsgId */
|
||||||
body = JSON.parse(res.data) as ApiResponse<CzCsUploadVo>
|
export function buildCsImageMessageBody(
|
||||||
} catch {
|
ossId: string | number,
|
||||||
reject(new ApiError('上传响应解析失败'))
|
clientMsgId: string,
|
||||||
return
|
): CsSendMessageBody {
|
||||||
|
const ossIdValue = String(ossId).trim()
|
||||||
|
return {
|
||||||
|
msgType: 'image',
|
||||||
|
ossId: ossIdValue,
|
||||||
|
clientMsgId,
|
||||||
|
content: CS_IMAGE_MESSAGE_PLACEHOLDER,
|
||||||
}
|
}
|
||||||
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/session/{sessionId}/message — 发送消息 */
|
/** POST /app/cs/session/{sessionId}/message — 发送消息 */
|
||||||
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
||||||
return request<CsAppActionVo>({
|
if (resolveCsAppBaseUrl()) ensureCsUploadReady()
|
||||||
|
return csRequest<CsAppActionVo>({
|
||||||
url: buildSessionPath(sessionId, '/message'),
|
url: buildSessionPath(sessionId, '/message'),
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data,
|
data,
|
||||||
@@ -182,7 +171,7 @@ export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
|||||||
|
|
||||||
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
||||||
export function transferCsSession(sessionId: string) {
|
export function transferCsSession(sessionId: string) {
|
||||||
return request<CsAppActionVo | CsSessionVo | null>({
|
return csRequest<CsAppActionVo | CsSessionVo | null>({
|
||||||
url: buildSessionPath(sessionId, '/transfer'),
|
url: buildSessionPath(sessionId, '/transfer'),
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
})
|
})
|
||||||
@@ -190,7 +179,7 @@ export function transferCsSession(sessionId: string) {
|
|||||||
|
|
||||||
/** POST /app/cs/session/{sessionId}/end — 结束会话 */
|
/** POST /app/cs/session/{sessionId}/end — 结束会话 */
|
||||||
export function endCsSession(sessionId: string) {
|
export function endCsSession(sessionId: string) {
|
||||||
return request<void>({
|
return csRequest<void>({
|
||||||
url: buildSessionPath(sessionId, '/end'),
|
url: buildSessionPath(sessionId, '/end'),
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
})
|
})
|
||||||
@@ -198,7 +187,7 @@ export function endCsSession(sessionId: string) {
|
|||||||
|
|
||||||
/** POST /app/cs/session/{sessionId}/button — 点击机器人按钮 */
|
/** POST /app/cs/session/{sessionId}/button — 点击机器人按钮 */
|
||||||
export function clickCsButton(sessionId: string, data: CsClickButtonBody) {
|
export function clickCsButton(sessionId: string, data: CsClickButtonBody) {
|
||||||
return request<void>({
|
return csRequest<void>({
|
||||||
url: buildSessionPath(sessionId, '/button'),
|
url: buildSessionPath(sessionId, '/button'),
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
data,
|
data,
|
||||||
|
|||||||
@@ -212,9 +212,15 @@ $support-danger: #f04438;
|
|||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
background: #d0d5dd;
|
background: #d0d5dd;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.support-page__msg-avatar-img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
.support-page__msg-body {
|
.support-page__msg-body {
|
||||||
max-width: calc(100% - 96rpx);
|
max-width: calc(100% - 96rpx);
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -642,49 +648,6 @@ $support-danger: #f04438;
|
|||||||
gap: 16rpx;
|
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 {
|
.support-page__input-wrap {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
height: 72rpx;
|
height: 72rpx;
|
||||||
|
|||||||
@@ -6,8 +6,6 @@ export const CS_SESSION_STATUS = {
|
|||||||
closed: '3',
|
closed: '3',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export type CsSessionStatus = (typeof CS_SESSION_STATUS)[keyof typeof CS_SESSION_STATUS]
|
|
||||||
|
|
||||||
/** POST /app/cs/session、GET /app/cs/session/{sessionId} */
|
/** POST /app/cs/session、GET /app/cs/session/{sessionId} */
|
||||||
export interface CsSessionVo {
|
export interface CsSessionVo {
|
||||||
sessionId?: number | string
|
sessionId?: number | string
|
||||||
@@ -47,10 +45,15 @@ export interface CsMessageVo {
|
|||||||
sessionId?: number | string
|
sessionId?: number | string
|
||||||
senderType?: string | number
|
senderType?: string | number
|
||||||
/** 接口字段为 msgType;部分响应仍带 messageType */
|
/** 接口字段为 msgType;部分响应仍带 messageType */
|
||||||
msgType?: string
|
msgType?: string | number
|
||||||
messageType?: string
|
messageType?: string | number
|
||||||
content?: string
|
content?: string | null
|
||||||
ossId?: number | string
|
ossId?: number | string
|
||||||
|
/** 图片地址,服务端由 ossId 翻译生成,前端直接用于展示 */
|
||||||
|
url?: string
|
||||||
|
imageUrl?: string
|
||||||
|
fileUrl?: string
|
||||||
|
clientMsgId?: string
|
||||||
createTime?: string
|
createTime?: string
|
||||||
extra?: Record<string, unknown>
|
extra?: Record<string, unknown>
|
||||||
}
|
}
|
||||||
@@ -95,14 +98,16 @@ export interface CzCsUploadVo {
|
|||||||
fileName?: string
|
fileName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CsChatImageUploadVo = CzCsUploadVo
|
/** 图片消息占位文案(发消息 content 字段、列表摘要) */
|
||||||
|
export const CS_IMAGE_MESSAGE_PLACEHOLDER = '[图片]'
|
||||||
|
|
||||||
/** POST /app/cs/session/{sessionId}/message */
|
/** POST /app/cs/session/{sessionId}/message */
|
||||||
export interface CsSendMessageBody {
|
export interface CsSendMessageBody {
|
||||||
content: string
|
/** 文本必填;图片可选占位 [图片] */
|
||||||
msgType?: 'text' | 'image' | string
|
content?: string
|
||||||
messageType?: 'text' | 'image' | string
|
msgType: 'text' | 'image' | string
|
||||||
clientMsgId: string
|
clientMsgId: string
|
||||||
|
/** 图片消息必填(仅 212 CzCsMessageBo 接收) */
|
||||||
ossId?: number | string
|
ossId?: number | string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,58 @@ import type {
|
|||||||
SupportMessage,
|
SupportMessage,
|
||||||
SupportPhase,
|
SupportPhase,
|
||||||
} from './support.types'
|
} 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[] = [
|
const QUICK_ACTIONS: QuickActionItem[] = [
|
||||||
{ id: 'wifi', label: '设备连不上 Wi-Fi' },
|
{ id: 'wifi', label: '设备连不上 Wi-Fi' },
|
||||||
@@ -174,38 +225,191 @@ export function injectTimeDividers(messages: SupportMessage[]): SupportMessage[]
|
|||||||
function resolveSenderRole(senderType?: string | number): ChatRole | null {
|
function resolveSenderRole(senderType?: string | number): ChatRole | null {
|
||||||
const value = String(senderType ?? '').toLowerCase()
|
const value = String(senderType ?? '').toLowerCase()
|
||||||
if (!value) return 'bot'
|
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 === '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'
|
if (value === '3' || value.includes('system')) return 'system'
|
||||||
return 'bot'
|
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 {
|
function resolveMessageType(message: CsMessageVo): string {
|
||||||
return String(message.msgType ?? message.messageType ?? '').toLowerCase()
|
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 {
|
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
|
const extra = message.extra
|
||||||
if (extra && typeof extra === 'object') {
|
if (extra && typeof extra === 'object') {
|
||||||
const fromExtra = extra.url ?? extra.src ?? extra.link
|
const fromExtra = extra.url ?? extra.src ?? extra.link
|
||||||
if (fromExtra != null && String(fromExtra).trim()) {
|
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() ?? ''
|
const content = message.content?.trim() ?? ''
|
||||||
if (!content) return ''
|
if (content && content !== CS_IMAGE_MESSAGE_PLACEHOLDER) {
|
||||||
if (/^https?:\/\//i.test(content)) return content
|
if (isNumericOssId(content)) return resolveOssImageUrl(content)
|
||||||
|
if (/^https?:\/\//i.test(content)) return normalizeCsMediaUrl(content)
|
||||||
if (content.startsWith('{') && content.endsWith('}')) {
|
if (content.startsWith('{') && content.endsWith('}')) {
|
||||||
try {
|
try {
|
||||||
const payload = JSON.parse(content) as Record<string, unknown>
|
const payload = JSON.parse(content) as Record<string, unknown>
|
||||||
const url = payload.url ?? payload.src ?? payload.link ?? payload.fileUrl
|
const url = payload.url ?? payload.src ?? payload.link ?? payload.fileUrl
|
||||||
if (url != null && String(url).trim()) return String(url).trim()
|
if (url != null && String(url).trim()) return normalizeCsMediaUrl(String(url))
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return content
|
}
|
||||||
|
|
||||||
|
if (message.ossId !== undefined && message.ossId !== null && String(message.ossId).trim()) {
|
||||||
|
return resolveOssImageUrl(message.ossId)
|
||||||
|
}
|
||||||
|
return ''
|
||||||
}
|
}
|
||||||
|
|
||||||
function createMessageId(message: CsMessageVo): string {
|
function createMessageId(message: CsMessageVo): string {
|
||||||
@@ -274,14 +478,15 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === 'image') {
|
if (type === 'image' || type === '2' || type === 'img') {
|
||||||
const src = String(payload.src ?? payload.url ?? '')
|
const src = resolveImageSrc(message)
|
||||||
|
|| normalizeCsMediaUrl(String(payload.src ?? payload.url ?? ''))
|
||||||
if (!src) return null
|
if (!src) return null
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
seq,
|
seq,
|
||||||
type: 'image',
|
type: 'image',
|
||||||
role: 'user',
|
role: resolveSenderRole(message.senderType) || 'user',
|
||||||
src,
|
src,
|
||||||
createTime: message.createTime,
|
createTime: message.createTime,
|
||||||
}
|
}
|
||||||
@@ -291,10 +496,10 @@ function mapStructuredMessage(message: CsMessageVo, payload: Record<string, unkn
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
|
export function mapCsMessage(message: CsMessageVo): SupportMessage | null {
|
||||||
|
ingestCsMessageMedia(message)
|
||||||
const content = message.content?.trim() ?? ''
|
const content = message.content?.trim() ?? ''
|
||||||
const messageType = resolveMessageType(message)
|
|
||||||
|
|
||||||
if (messageType === 'image') {
|
if (isImageMessage(message)) {
|
||||||
const src = resolveImageSrc(message)
|
const src = resolveImageSrc(message)
|
||||||
if (!src) return null
|
if (!src) return null
|
||||||
const role = resolveSenderRole(message.senderType) || 'user'
|
const role = resolveSenderRole(message.senderType) || 'user'
|
||||||
@@ -338,7 +543,14 @@ export function mergeSupportMessages(
|
|||||||
if (!incoming.length) return current
|
if (!incoming.length) return current
|
||||||
const map = new Map<string, SupportMessage>()
|
const map = new Map<string, SupportMessage>()
|
||||||
for (const item of current) map.set(item.id, item)
|
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))
|
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 { onBeforeUnmount } from 'vue'
|
||||||
import { onHide, onShow, onUnload } from '@dcloudio/uni-app'
|
import { onHide, onShow, onUnload } from '@dcloudio/uni-app'
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
|
import { ensureCsUploadReady } from '@/api/cs-auth'
|
||||||
|
import { fetchProfile } from '@/api/profile'
|
||||||
import { getErrorMessage } from '@/utils/api-error'
|
import { getErrorMessage } from '@/utils/api-error'
|
||||||
import { getStoredToken } from '@/utils/auth-token'
|
import { getStoredToken } from '@/utils/auth-token'
|
||||||
import {
|
import {
|
||||||
@@ -9,12 +11,12 @@ import {
|
|||||||
fetchCsMessages,
|
fetchCsMessages,
|
||||||
fetchCsSessionDetail,
|
fetchCsSessionDetail,
|
||||||
resolveCsSession,
|
resolveCsSession,
|
||||||
|
buildCsImageMessageBody,
|
||||||
sendCsMessage,
|
sendCsMessage,
|
||||||
transferCsSession,
|
transferCsSession,
|
||||||
uploadCsChatImage,
|
uploadCsChatImage,
|
||||||
} from './support.api'
|
} from './support.api'
|
||||||
import {
|
import {
|
||||||
connectCsChatSocket,
|
|
||||||
disconnectCsChatSocket,
|
disconnectCsChatSocket,
|
||||||
isCsChatSocketConnected,
|
isCsChatSocketConnected,
|
||||||
onCsChatPush,
|
onCsChatPush,
|
||||||
@@ -45,7 +47,10 @@ import {
|
|||||||
injectTimeDividers,
|
injectTimeDividers,
|
||||||
mapCsMessage,
|
mapCsMessage,
|
||||||
mergeSupportMessages,
|
mergeSupportMessages,
|
||||||
|
cacheSentImageRefs,
|
||||||
|
normalizeCsMediaUrl,
|
||||||
normalizeSessionId,
|
normalizeSessionId,
|
||||||
|
registerLocalImagePreview,
|
||||||
resolvePhaseFromSession,
|
resolvePhaseFromSession,
|
||||||
unwrapCsActionResponse,
|
unwrapCsActionResponse,
|
||||||
} from './support.utils'
|
} from './support.utils'
|
||||||
@@ -99,6 +104,7 @@ export function useSupport() {
|
|||||||
const sessionInitializing = ref(false)
|
const sessionInitializing = ref(false)
|
||||||
const sending = ref(false)
|
const sending = ref(false)
|
||||||
const lastSeq = ref(0)
|
const lastSeq = ref(0)
|
||||||
|
const userAvatarUrl = ref('')
|
||||||
|
|
||||||
let unsubscribeChatPush: (() => void) | null = null
|
let unsubscribeChatPush: (() => void) | null = null
|
||||||
let ensureSessionPromise: Promise<void> | null = null
|
let ensureSessionPromise: Promise<void> | null = null
|
||||||
@@ -335,9 +341,26 @@ export function useSupport() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendUserImageMessage(ossId: string | number, imageUrl: string) {
|
function appendLocalImageMessage(src: string, clientMsgId: string) {
|
||||||
const url = imageUrl.trim()
|
const normalized = normalizeCsMediaUrl(src)
|
||||||
if (!url || !ossId || sending.value) return
|
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) {
|
if (!sessionId.value) {
|
||||||
await ensureSession()
|
await ensureSession()
|
||||||
@@ -349,16 +372,23 @@ export function useSupport() {
|
|||||||
|
|
||||||
sending.value = true
|
sending.value = true
|
||||||
try {
|
try {
|
||||||
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
const clientMsgId = createClientMsgId()
|
||||||
content: url,
|
const preview = previewUrl?.trim() || ''
|
||||||
msgType: 'image',
|
if (preview) {
|
||||||
ossId: String(ossId),
|
registerLocalImagePreview(ossId, clientMsgId, preview)
|
||||||
clientMsgId: createClientMsgId(),
|
appendLocalImageMessage(preview, clientMsgId)
|
||||||
}))
|
}
|
||||||
|
const action = unwrapCsActionResponse(await sendCsMessage(
|
||||||
|
sessionId.value,
|
||||||
|
buildCsImageMessageBody(ossId, clientMsgId),
|
||||||
|
))
|
||||||
if (action.session) {
|
if (action.session) {
|
||||||
applySessionState(action.session)
|
applySessionState(action.session)
|
||||||
}
|
}
|
||||||
if (action.messages?.length) {
|
if (action.messages?.length) {
|
||||||
|
if (cacheSentImageRefs(action.messages, clientMsgId, preview)) {
|
||||||
|
clearPendingLocalImage(clientMsgId)
|
||||||
|
}
|
||||||
applyActionMessages(action)
|
applyActionMessages(action)
|
||||||
} else if (!isCsChatSocketConnected()) {
|
} else if (!isCsChatSocketConnected()) {
|
||||||
await syncMessages()
|
await syncMessages()
|
||||||
@@ -385,12 +415,12 @@ export function useSupport() {
|
|||||||
try {
|
try {
|
||||||
const uploaded = await uploadCsChatImage(filePath)
|
const uploaded = await uploadCsChatImage(filePath)
|
||||||
const ossId = uploaded.ossId
|
const ossId = uploaded.ossId
|
||||||
const imageUrl = uploaded.url?.trim() || ''
|
const previewUrl = uploaded.url?.trim() || filePath
|
||||||
if (!ossId || !imageUrl) {
|
if (!ossId) {
|
||||||
uni.showToast({ title: '上传失败,未获取图片信息', icon: 'none' })
|
uni.showToast({ title: '上传失败,未获取图片信息', icon: 'none' })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await sendUserImageMessage(ossId, imageUrl)
|
await sendUserImageMessage(ossId, previewUrl)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
uni.showToast({ title: getErrorMessage(err, '图片上传失败'), icon: 'none' })
|
uni.showToast({ title: getErrorMessage(err, '图片上传失败'), icon: 'none' })
|
||||||
} finally {
|
} finally {
|
||||||
@@ -418,7 +448,6 @@ export function useSupport() {
|
|||||||
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
const action = unwrapCsActionResponse(await sendCsMessage(sessionId.value, {
|
||||||
content: text,
|
content: text,
|
||||||
msgType: 'text',
|
msgType: 'text',
|
||||||
messageType: 'text',
|
|
||||||
clientMsgId: createClientMsgId(),
|
clientMsgId: createClientMsgId(),
|
||||||
}))
|
}))
|
||||||
if (action.session) {
|
if (action.session) {
|
||||||
@@ -450,8 +479,7 @@ export function useSupport() {
|
|||||||
const action = unwrapCsActionResponse(await transferCsSession(sessionId.value))
|
const action = unwrapCsActionResponse(await transferCsSession(sessionId.value))
|
||||||
if (action.session) applySessionState(action.session)
|
if (action.session) applySessionState(action.session)
|
||||||
if (action.messages?.length) applyActionMessages(action)
|
if (action.messages?.length) applyActionMessages(action)
|
||||||
ensureChatPushListener()
|
bindChatSocket(sessionId.value)
|
||||||
connectCsChatSocket(sessionId.value)
|
|
||||||
await refreshSession()
|
await refreshSession()
|
||||||
await syncMessages(false, true)
|
await syncMessages(false, true)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -547,8 +575,19 @@ export function useSupport() {
|
|||||||
void sendUserMessage(text)
|
void sendUserMessage(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadUserProfile() {
|
||||||
|
try {
|
||||||
|
const profile = await fetchProfile()
|
||||||
|
userAvatarUrl.value = profile?.avatarUrl?.trim() || ''
|
||||||
|
} catch {
|
||||||
|
// 头像加载失败时保留「我」占位
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function activatePage() {
|
function activatePage() {
|
||||||
markSupportPageActive(true)
|
markSupportPageActive(true)
|
||||||
|
ensureCsUploadReady()
|
||||||
|
void loadUserProfile()
|
||||||
if (!sessionId.value) {
|
if (!sessionId.value) {
|
||||||
void ensureSession()
|
void ensureSession()
|
||||||
return
|
return
|
||||||
@@ -570,6 +609,7 @@ export function useSupport() {
|
|||||||
inputValue,
|
inputValue,
|
||||||
sessionId,
|
sessionId,
|
||||||
headerInfo,
|
headerInfo,
|
||||||
|
userAvatarUrl,
|
||||||
showTransfer,
|
showTransfer,
|
||||||
showEndSession,
|
showEndSession,
|
||||||
formattedQueueWait,
|
formattedQueueWait,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
const TOKEN_KEY = 'token'
|
const TOKEN_KEY = 'token'
|
||||||
|
const CS_TOKEN_KEY = 'cs_token'
|
||||||
|
|
||||||
/** 从登录响应中提取 access_token(兼容 RuoYi-Vue-Plus) */
|
/** 从登录响应中提取 access_token(兼容 RuoYi-Vue-Plus) */
|
||||||
export function extractAuthToken(payload: unknown): string {
|
export function extractAuthToken(payload: unknown): string {
|
||||||
@@ -30,6 +31,13 @@ export function getStoredToken(): string {
|
|||||||
return raw.replace(/^Bearer\s+/i, '').trim()
|
return raw.replace(/^Bearer\s+/i, '').trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 生成 Authorization 请求头值:Bearer <token> */
|
||||||
|
export function formatBearerAuthorization(token: string): string {
|
||||||
|
const normalized = token.replace(/^Bearer\s+/i, '').trim()
|
||||||
|
if (!normalized) return ''
|
||||||
|
return `Bearer ${normalized}`
|
||||||
|
}
|
||||||
|
|
||||||
export function saveStoredToken(token: string): string {
|
export function saveStoredToken(token: string): string {
|
||||||
const normalized = token.replace(/^Bearer\s+/i, '').trim()
|
const normalized = token.replace(/^Bearer\s+/i, '').trim()
|
||||||
if (!normalized) {
|
if (!normalized) {
|
||||||
@@ -41,4 +49,21 @@ export function saveStoredToken(token: string): string {
|
|||||||
|
|
||||||
export function clearStoredToken(): void {
|
export function clearStoredToken(): void {
|
||||||
uni.removeStorageSync(TOKEN_KEY)
|
uni.removeStorageSync(TOKEN_KEY)
|
||||||
|
clearStoredCsToken()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getStoredCsToken(): string {
|
||||||
|
const raw = (uni.getStorageSync(CS_TOKEN_KEY) as string) || ''
|
||||||
|
return raw.replace(/^Bearer\s+/i, '').trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveStoredCsToken(token: string): string {
|
||||||
|
const normalized = token.replace(/^Bearer\s+/i, '').trim()
|
||||||
|
if (!normalized) throw new Error('empty cs token')
|
||||||
|
uni.setStorageSync(CS_TOKEN_KEY, normalized)
|
||||||
|
return normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearStoredCsToken(): void {
|
||||||
|
uni.removeStorageSync(CS_TOKEN_KEY)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ export default defineConfig(({ mode }) => {
|
|||||||
const env = loadEnv(mode, process.cwd(), "");
|
const env = loadEnv(mode, process.cwd(), "");
|
||||||
const proxyTarget =
|
const proxyTarget =
|
||||||
env.VITE_API_PROXY_TARGET || "http://192.168.0.222:8082";
|
env.VITE_API_PROXY_TARGET || "http://192.168.0.222:8082";
|
||||||
|
const csProxyTarget =
|
||||||
|
env.VITE_CS_API_BASE_URL || proxyTarget;
|
||||||
|
|
||||||
const devPort = Number(env.VITE_DEV_SERVER_PORT) || 5173;
|
const devPort = Number(env.VITE_DEV_SERVER_PORT) || 5173;
|
||||||
|
|
||||||
@@ -15,6 +17,20 @@ export default defineConfig(({ mode }) => {
|
|||||||
host: true,
|
host: true,
|
||||||
port: devPort,
|
port: devPort,
|
||||||
proxy: {
|
proxy: {
|
||||||
|
"/cs-app": {
|
||||||
|
target: csProxyTarget,
|
||||||
|
changeOrigin: true,
|
||||||
|
ws: true,
|
||||||
|
rewrite: (path) => path.replace(/^\/cs-app/, "/app"),
|
||||||
|
},
|
||||||
|
"/app/cs/upload": {
|
||||||
|
target: csProxyTarget,
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
"/resource": {
|
||||||
|
target: proxyTarget,
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
"/app": {
|
"/app": {
|
||||||
target: proxyTarget,
|
target: proxyTarget,
|
||||||
changeOrigin: true,
|
changeOrigin: true,
|
||||||
|
|||||||
Reference in New Issue
Block a user