提示词保存
This commit is contained in:
129
frontend/api/README.md
Normal file
129
frontend/api/README.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# Mono 级别 API 架构
|
||||
|
||||
## 📁 目录结构
|
||||
|
||||
```
|
||||
frontend/api/
|
||||
├── axios/
|
||||
│ └── client.js # Mono 级别的 C 端 Axios 实例
|
||||
├── services/
|
||||
│ ├── tikhub.js # TikHub API 服务
|
||||
│ └── index.js # 服务统一导出
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 🎯 设计理念
|
||||
|
||||
### 1. 分层清晰
|
||||
- **Mono 级别** (`frontend/api/`): 可在 monorepo 中所有应用复用的代码
|
||||
- **应用级别** (`frontend/app/web-gold/src/api/`): 应用特定的 API 封装
|
||||
|
||||
### 2. 模块化设计
|
||||
- **Axios 实例**: 统一的 HTTP 客户端配置
|
||||
- **API 服务**: 按功能模块组织(如 `TikHubService`)
|
||||
- **Hooks**: 直接使用服务,无需全局注入
|
||||
|
||||
### 3. 人类可读
|
||||
- 清晰的命名和注释
|
||||
- 直观的导入路径
|
||||
- 易于理解和维护
|
||||
|
||||
## 🚀 使用方式
|
||||
|
||||
### 在 Mono 级别使用
|
||||
|
||||
```javascript
|
||||
// 直接使用服务
|
||||
import { TikHubService } from '@gold/api/services'
|
||||
|
||||
const result = await TikHubService.videoToCharacters({
|
||||
fileLinkList: ['https://example.com/audio.mp3']
|
||||
})
|
||||
```
|
||||
|
||||
### 在应用层使用
|
||||
|
||||
```javascript
|
||||
// 使用应用层封装的服务
|
||||
import { CommonService } from '@/api/common'
|
||||
|
||||
const result = await CommonService.videoToCharacters({
|
||||
fileLinkList: ['https://example.com/audio.mp3']
|
||||
})
|
||||
```
|
||||
|
||||
### 在 Hooks 中使用
|
||||
|
||||
```typescript
|
||||
// useVoiceText 直接使用 TikHubService,无需配置
|
||||
import useVoiceText from '@gold/hooks/web/useVoiceText'
|
||||
|
||||
const { getVoiceText } = useVoiceText()
|
||||
const transcriptions = await getVoiceText([
|
||||
{ audio_url: 'https://example.com/audio.mp3' }
|
||||
])
|
||||
```
|
||||
|
||||
## 📦 添加新的 API 服务
|
||||
|
||||
### 1. 创建服务文件
|
||||
|
||||
```javascript
|
||||
// frontend/api/services/my-service.js
|
||||
import { clientAxios } from '@gold/api/axios/client'
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
const BASE_URL = API_BASE.MY_SERVICE || ''
|
||||
|
||||
export const MyService = {
|
||||
async getData(params) {
|
||||
return await clientAxios.get(`${BASE_URL}/data`, { params })
|
||||
},
|
||||
|
||||
async createData(data) {
|
||||
return await clientAxios.post(`${BASE_URL}/data`, data)
|
||||
},
|
||||
}
|
||||
|
||||
export default MyService
|
||||
```
|
||||
|
||||
### 2. 导出服务
|
||||
|
||||
```javascript
|
||||
// frontend/api/services/index.js
|
||||
export { TikHubService } from './tikhub'
|
||||
export { MyService } from './my-service'
|
||||
```
|
||||
|
||||
### 3. 使用服务
|
||||
|
||||
```javascript
|
||||
import { MyService } from '@gold/api/services'
|
||||
|
||||
const data = await MyService.getData({ id: 1 })
|
||||
```
|
||||
|
||||
## 🔧 自定义 Axios 实例
|
||||
|
||||
如果需要创建自定义的 Axios 实例:
|
||||
|
||||
```javascript
|
||||
import { createClientAxios } from '@gold/api/axios/client'
|
||||
|
||||
const customAxios = createClientAxios({
|
||||
baseURL: '/custom-api',
|
||||
timeout: 60000,
|
||||
on401: () => {
|
||||
// 自定义 401 处理
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## 📝 注意事项
|
||||
|
||||
1. **Mono 级别代码**应该保持通用,不依赖特定应用的逻辑
|
||||
2. **应用层代码**可以依赖应用特定的 store、组件等
|
||||
3. **服务模块**应该按功能划分,保持单一职责
|
||||
4. **Axios 实例**统一管理,避免重复配置
|
||||
|
||||
152
frontend/api/axios/client.js
Normal file
152
frontend/api/axios/client.js
Normal file
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Mono 级别的 C 端 Axios 实例
|
||||
* 供 monorepo 中所有应用使用的统一 HTTP 客户端
|
||||
*/
|
||||
|
||||
import axios from 'axios'
|
||||
import { getAuthHeader, clearAllTokens } from '@gold/utils/token-manager'
|
||||
|
||||
/**
|
||||
* 不需要 token 的接口白名单
|
||||
*/
|
||||
const WHITE_LIST = [
|
||||
'/auth/login',
|
||||
'/auth/send-sms-code',
|
||||
'/auth/sms-login',
|
||||
'/auth/validate-sms-code',
|
||||
'/auth/register',
|
||||
'/auth/reset-password',
|
||||
'/auth/refresh-token',
|
||||
]
|
||||
|
||||
/**
|
||||
* 检查 URL 是否在白名单中
|
||||
*/
|
||||
function isInWhiteList(url) {
|
||||
if (!url) return false
|
||||
return WHITE_LIST.some((path) => url.includes(path))
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 401 未授权错误
|
||||
*/
|
||||
let isHandling401 = false
|
||||
function handle401Error() {
|
||||
if (isHandling401) return
|
||||
|
||||
isHandling401 = true
|
||||
|
||||
try {
|
||||
clearAllTokens()
|
||||
} catch (e) {
|
||||
console.error('清空 token 失败:', e)
|
||||
}
|
||||
|
||||
// 延迟重置标志
|
||||
setTimeout(() => {
|
||||
isHandling401 = false
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 C 端 Axios 实例
|
||||
* @param {Object} options - 配置选项
|
||||
* @param {string} options.baseURL - 基础 URL
|
||||
* @param {number} options.timeout - 超时时间(毫秒)
|
||||
* @param {Function} options.on401 - 401 错误处理函数
|
||||
* @param {Function} options.on403 - 403 错误处理函数
|
||||
* @returns {AxiosInstance} Axios 实例
|
||||
*/
|
||||
export function createClientAxios(options = {}) {
|
||||
const {
|
||||
baseURL = '/',
|
||||
timeout = 180000,
|
||||
on401 = handle401Error,
|
||||
on403 = null,
|
||||
} = options
|
||||
|
||||
const client = axios.create({
|
||||
baseURL,
|
||||
timeout,
|
||||
})
|
||||
|
||||
// 请求拦截器
|
||||
client.interceptors.request.use((config) => {
|
||||
// 添加 tenant-id
|
||||
const tenantId =
|
||||
(typeof import.meta !== 'undefined' && import.meta.env?.VITE_TENANT_ID) ||
|
||||
(typeof process !== 'undefined' && process.env?.VITE_TENANT_ID) ||
|
||||
'1'
|
||||
|
||||
if (tenantId) {
|
||||
config.headers['tenant-id'] = tenantId
|
||||
}
|
||||
|
||||
// 添加 Authorization header
|
||||
const needToken = config.headers?.isToken !== false && !isInWhiteList(config.url || '')
|
||||
if (needToken) {
|
||||
const authHeader = getAuthHeader()
|
||||
if (authHeader) {
|
||||
config.headers.Authorization = authHeader
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
})
|
||||
|
||||
// 响应拦截器
|
||||
client.interceptors.response.use(
|
||||
(response) => {
|
||||
const data = response.data
|
||||
|
||||
// 检查业务状态码
|
||||
if (data && typeof data.code === 'number') {
|
||||
if (data.code === 0 || data.code === 200) {
|
||||
return data
|
||||
}
|
||||
|
||||
// 处理 401
|
||||
if (data.code === 401 && typeof on401 === 'function') {
|
||||
on401()
|
||||
}
|
||||
|
||||
// 处理 403(业务状态码)
|
||||
if (data.code === 403 && typeof on403 === 'function') {
|
||||
on403()
|
||||
}
|
||||
|
||||
// 抛出业务错误
|
||||
const error = new Error(data?.message || data?.msg || '请求失败')
|
||||
error.code = data?.code
|
||||
error.data = data
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
||||
return data
|
||||
},
|
||||
(error) => {
|
||||
// 处理 HTTP 401
|
||||
if (error.response?.status === 401 && typeof on401 === 'function') {
|
||||
on401()
|
||||
}
|
||||
|
||||
// 处理 HTTP 403
|
||||
if (error.response?.status === 403 && typeof on403 === 'function') {
|
||||
on403()
|
||||
}
|
||||
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认导出的 C 端 Axios 实例
|
||||
* 可在应用层覆盖配置
|
||||
*/
|
||||
export const clientAxios = createClientAxios()
|
||||
|
||||
export default clientAxios
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
/**
|
||||
* 公共 API 服务
|
||||
* 封装可在 monorepo 各个应用中复用的 API 调用
|
||||
*
|
||||
* 使用方式:
|
||||
* import { createApiService } from '@gold/config/api/services'
|
||||
*
|
||||
* const apiService = createApiService({
|
||||
* http: axiosInstance,
|
||||
* getAuthHeader: () => 'Bearer token',
|
||||
* baseUrl: API_BASE.TIKHUB_APP
|
||||
* })
|
||||
*
|
||||
* await apiService.videoToCharacters({ fileLinkList: [...] })
|
||||
*/
|
||||
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
/**
|
||||
* 创建 API 服务实例
|
||||
* @param {Object} options - 配置选项
|
||||
* @param {Object} options.http - HTTP 客户端实例(如 axios)
|
||||
* @param {Function} options.getAuthHeader - 获取 Authorization header 的函数
|
||||
* @param {string} options.baseUrl - API 基础 URL(可选,默认使用 TIKHUB_APP)
|
||||
* @returns {Object} API 服务对象
|
||||
*/
|
||||
export function createApiService(options = {}) {
|
||||
const { http, getAuthHeader, baseUrl } = options
|
||||
|
||||
if (!http) {
|
||||
throw new Error('createApiService: http 实例是必需的')
|
||||
}
|
||||
|
||||
// 确定 API 基础路径
|
||||
// 如果没有提供 baseUrl,尝试使用 TIKHUB_APP 或 TIKHUB
|
||||
const apiBaseUrl = baseUrl || API_BASE.TIKHUB_APP || API_BASE.TIKHUB || ''
|
||||
|
||||
/**
|
||||
* 视频转字符(音频转文字)
|
||||
* @param {Object} data - 请求数据
|
||||
* @param {string[]} data.fileLinkList - 音频文件链接列表
|
||||
* @returns {Promise<Object>} 响应数据
|
||||
*/
|
||||
async function videoToCharacters(data) {
|
||||
const url = `${apiBaseUrl}/videoToCharacters2`
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
// 添加 Authorization header(如果提供了 getAuthHeader 函数)
|
||||
if (getAuthHeader) {
|
||||
const authHeader = getAuthHeader()
|
||||
if (authHeader) {
|
||||
headers.Authorization = authHeader
|
||||
}
|
||||
}
|
||||
|
||||
// 获取 tenant-id(从环境变量或默认值)
|
||||
const tenantId =
|
||||
(typeof import.meta !== 'undefined' && import.meta.env?.VITE_TENANT_ID) ||
|
||||
(typeof process !== 'undefined' && process.env?.VITE_TENANT_ID) ||
|
||||
'1'
|
||||
|
||||
if (tenantId) {
|
||||
headers['tenant-id'] = tenantId
|
||||
}
|
||||
|
||||
return await http.post(url, data, { headers })
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用工作流
|
||||
* @param {Object} data - 请求数据
|
||||
* @returns {Promise<Object>} 响应数据
|
||||
*/
|
||||
async function callWorkflow(data) {
|
||||
const url = `${apiBaseUrl}/callWorkflow`
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
if (getAuthHeader) {
|
||||
const authHeader = getAuthHeader()
|
||||
if (authHeader) {
|
||||
headers.Authorization = authHeader
|
||||
}
|
||||
}
|
||||
|
||||
const tenantId =
|
||||
(typeof import.meta !== 'undefined' && import.meta.env?.VITE_TENANT_ID) ||
|
||||
(typeof process !== 'undefined' && process.env?.VITE_TENANT_ID) ||
|
||||
'1'
|
||||
|
||||
if (tenantId) {
|
||||
headers['tenant-id'] = tenantId
|
||||
}
|
||||
|
||||
return await http.post(url, data, { headers })
|
||||
}
|
||||
|
||||
return {
|
||||
videoToCharacters,
|
||||
callWorkflow,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认导出(便于直接使用)
|
||||
*/
|
||||
export default createApiService
|
||||
|
||||
11
frontend/api/services/index.js
Normal file
11
frontend/api/services/index.js
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* API 服务统一导出
|
||||
* 按功能模块组织,便于维护和扩展
|
||||
*/
|
||||
|
||||
export { TikHubService } from './tikhub'
|
||||
|
||||
// 可以继续添加其他服务模块
|
||||
// export { UserService } from './user'
|
||||
// export { ChatService } from './chat'
|
||||
|
||||
43
frontend/api/services/tikhub.js
Normal file
43
frontend/api/services/tikhub.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* TikHub API 服务
|
||||
* 封装 TikHub 相关的 API 调用
|
||||
*/
|
||||
|
||||
import { clientAxios } from '@gold/api/axios/client'
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
/**
|
||||
* TikHub API 基础路径
|
||||
*/
|
||||
const BASE_URL = API_BASE.TIKHUB_APP || API_BASE.TIKHUB || ''
|
||||
|
||||
/**
|
||||
* TikHub API 服务
|
||||
*/
|
||||
export const TikHubService = {
|
||||
/**
|
||||
* 视频转字符(音频转文字)
|
||||
* @param {Object} params - 请求参数
|
||||
* @param {string[]} params.fileLinkList - 音频文件链接列表
|
||||
* @returns {Promise<{ data: string }>} 响应数据
|
||||
*/
|
||||
async videoToCharacters(params) {
|
||||
const { fileLinkList } = params
|
||||
|
||||
return await clientAxios.post(`${BASE_URL}/videoToCharacters2`, {
|
||||
fileLinkList,
|
||||
})
|
||||
},
|
||||
|
||||
/**
|
||||
* 调用工作流
|
||||
* @param {Object} data - 请求数据
|
||||
* @returns {Promise<Object>} 响应数据
|
||||
*/
|
||||
async callWorkflow(data) {
|
||||
return await clientAxios.post(`${BASE_URL}/callWorkflow`, data)
|
||||
},
|
||||
}
|
||||
|
||||
export default TikHubService
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
# API 统一管理说明
|
||||
|
||||
## 📁 目录结构
|
||||
|
||||
```
|
||||
api/
|
||||
├── config.js # API 基础配置(统一管理所有基础 URL)
|
||||
├── index.js # 统一导出入口(所有 API 服务从这里导出)
|
||||
├── http.js # Axios 实例和拦截器
|
||||
├── auth.js # 认证相关 API
|
||||
├── chat.js # 聊天相关 API
|
||||
├── common.js # 通用服务 API
|
||||
└── tikhub/ # TikHub 相关 API
|
||||
├── index.js
|
||||
├── tikhub.js
|
||||
└── types.js
|
||||
```
|
||||
|
||||
## 🚀 使用方式
|
||||
|
||||
### 方式一:从统一入口导入(推荐)
|
||||
|
||||
```javascript
|
||||
// 导入所有 API
|
||||
import { ChatMessageApi, AuthApi, CommonService, TikhubService } from '@/api'
|
||||
|
||||
// 或按需导入
|
||||
import { ChatMessageApi } from '@/api'
|
||||
import { AuthApi } from '@/api'
|
||||
```
|
||||
|
||||
### 方式二:从具体文件导入(兼容旧代码)
|
||||
|
||||
```javascript
|
||||
// 仍然支持原有的导入方式
|
||||
import { ChatMessageApi } from '@/api/chat'
|
||||
import { CommonService } from '@/api/common'
|
||||
```
|
||||
|
||||
### 方式三:使用配置工具函数
|
||||
|
||||
```javascript
|
||||
import { getApiUrl, API_BASE } from '@/api/config'
|
||||
|
||||
// 获取完整 API URL
|
||||
const url = getApiUrl('ADMIN_AI', '/chat/conversation/create-my')
|
||||
// 结果: /admin-api/ai/chat/conversation/create-my
|
||||
|
||||
// 直接使用配置
|
||||
const baseUrl = API_BASE.ADMIN_AI
|
||||
```
|
||||
|
||||
## 📝 API 配置说明
|
||||
|
||||
### config.js
|
||||
|
||||
所有 API 基础 URL 统一在 `config.js` 中管理:
|
||||
|
||||
```javascript
|
||||
export const API_BASE = {
|
||||
ADMIN: '/admin-api', // 管理后台基础路径
|
||||
APP: '/app-api', // 会员端基础路径
|
||||
ADMIN_AI: '/admin-api/ai', // AI 模块(管理后台)
|
||||
APP_MEMBER: '/app-api/member', // 会员模块
|
||||
TIKHUB: '/webApi/admin-api/ai/tikHup', // TikHub(管理后台)
|
||||
TIKHUB_APP: '/app-api/api/tikHup', // TikHub(会员端)
|
||||
}
|
||||
```
|
||||
|
||||
### 添加新的 API 模块
|
||||
|
||||
1. 在 `config.js` 中添加新的基础路径:
|
||||
```javascript
|
||||
export const API_BASE = {
|
||||
// ... 现有配置
|
||||
NEW_MODULE: `${BASE_URL}/admin-api/new-module`,
|
||||
}
|
||||
```
|
||||
|
||||
2. 创建新的 API 文件(如 `new-module.js`):
|
||||
```javascript
|
||||
import request from '@/api/http'
|
||||
import { API_BASE } from '@/api/config'
|
||||
|
||||
const BASE = API_BASE.NEW_MODULE
|
||||
|
||||
export const NewModuleApi = {
|
||||
getList: () => request.get(`${BASE}/list`),
|
||||
create: (data) => request.post(`${BASE}/create`, data),
|
||||
}
|
||||
```
|
||||
|
||||
3. 在 `index.js` 中导出:
|
||||
```javascript
|
||||
export { NewModuleApi } from './new-module'
|
||||
```
|
||||
|
||||
## 🔧 HTTP 实例
|
||||
|
||||
所有 API 都使用统一的 HTTP 实例(`http.js`),已配置:
|
||||
- ✅ 自动 Token 注入
|
||||
- ✅ 统一错误处理
|
||||
- ✅ 请求/响应拦截器
|
||||
- ✅ 白名单机制(无需 Token 的接口)
|
||||
|
||||
## 📌 注意事项
|
||||
|
||||
1. **基础 URL 配置**:所有 API 的基础 URL 都应该在 `config.js` 中定义,不要在业务文件中硬编码
|
||||
2. **统一导出**:新增 API 服务后,记得在 `index.js` 中导出
|
||||
3. **向后兼容**:保持原有的导入方式仍然可用,方便逐步迁移
|
||||
|
||||
## 🎯 最佳实践
|
||||
|
||||
1. **使用统一入口**:优先使用 `@/api` 统一导入
|
||||
2. **配置集中管理**:所有 URL 配置都在 `config.js`
|
||||
3. **类型安全**:使用 TypeScript 时,可以为 API 添加类型定义
|
||||
4. **错误处理**:利用 HTTP 拦截器统一处理错误
|
||||
|
||||
@@ -4,7 +4,8 @@ import { getAccessToken } from '@/utils/auth'
|
||||
// 使用公共配置
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
const SERVER_BASE_AI = API_BASE.ADMIN_AI
|
||||
// C 端使用 APP_AI,如果不存在则回退到 ADMIN_AI
|
||||
const SERVER_BASE_AI = API_BASE.APP_AI || API_BASE.ADMIN_AI
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,36 +1,41 @@
|
||||
import http from '@/api/http'
|
||||
/**
|
||||
* 应用层 API 服务
|
||||
* 封装应用特定的 API 调用,使用 mono 级别的服务
|
||||
*/
|
||||
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source'
|
||||
import { getAuthHeader } from '@gold/utils/token-manager'
|
||||
// 使用公共配置和 API 服务创建器
|
||||
import { TikHubService } from '@gold/api/services'
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
import { createApiService } from '@gold/api/services'
|
||||
// 初始化公共 hook 的 API 服务
|
||||
import { setApiService } from '@gold/hooks/web/useVoiceText'
|
||||
|
||||
// 使用本地代理前缀 /tikhub,开发环境通过 Vite 代理到 https://api.tikhub.io
|
||||
// 注意:API_BASE.TIKHUB 不存在,应该使用 TIKHUB_APP
|
||||
const SERVER_BASE = API_BASE.TIKHUB_APP || API_BASE.TIKHUB || ''
|
||||
|
||||
// 创建公共 API 服务实例
|
||||
const apiService = createApiService({
|
||||
http,
|
||||
getAuthHeader,
|
||||
baseUrl: SERVER_BASE,
|
||||
})
|
||||
|
||||
// 设置全局 API 服务(供 useVoiceText hook 使用)
|
||||
setApiService(apiService)
|
||||
/**
|
||||
* TikHub API 基础路径
|
||||
*/
|
||||
const TIKHUB_BASE = API_BASE.TIKHUB_APP || API_BASE.TIKHUB || ''
|
||||
|
||||
/**
|
||||
* 应用层通用服务
|
||||
*/
|
||||
export const CommonService = {
|
||||
/**
|
||||
* 视频转字符(音频转文字)
|
||||
* 直接使用 mono 级别的 TikHub 服务
|
||||
*/
|
||||
videoToCharacters(data) {
|
||||
return apiService.videoToCharacters(data)
|
||||
return TikHubService.videoToCharacters(data)
|
||||
},
|
||||
|
||||
/**
|
||||
* 调用工作流
|
||||
*/
|
||||
callWorkflow(data) {
|
||||
return apiService.callWorkflow(data)
|
||||
return TikHubService.callWorkflow(data)
|
||||
},
|
||||
|
||||
// 流式调用 workflow
|
||||
callWorkflowStream: async (options) => {
|
||||
/**
|
||||
* 流式调用工作流(SSE)
|
||||
*/
|
||||
async callWorkflowStream(options) {
|
||||
const {
|
||||
data,
|
||||
ctrl,
|
||||
@@ -42,9 +47,9 @@ export const CommonService = {
|
||||
const authHeader = getAuthHeader()
|
||||
|
||||
let retryCount = 0
|
||||
const maxRetries = 0 // 禁用自动重试
|
||||
const maxRetries = 0
|
||||
|
||||
return fetchEventSource(`${SERVER_BASE}/callWorkflow`, {
|
||||
return fetchEventSource(`${TIKHUB_BASE}/callWorkflow`, {
|
||||
method: 'post',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -57,18 +62,15 @@ export const CommonService = {
|
||||
retryCount++
|
||||
console.error('SSE错误,重试次数:', retryCount, err)
|
||||
|
||||
// 调用自定义错误处理
|
||||
if (typeof onError === 'function') {
|
||||
onError(err)
|
||||
}
|
||||
|
||||
// 超过最大重试次数,停止重连
|
||||
if (retryCount > maxRetries) {
|
||||
throw err // 抛出错误,停止自动重连
|
||||
throw err
|
||||
}
|
||||
},
|
||||
onclose: () => {
|
||||
// 调用自定义关闭处理
|
||||
if (typeof onClose === 'function') {
|
||||
onClose()
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* API 基础配置
|
||||
* 统一管理所有 API 的基础 URL
|
||||
*
|
||||
* 注意:此文件已迁移到公共模块 @gold/config/api
|
||||
* 为了保持向后兼容,这里重新导出公共配置
|
||||
* 新代码建议直接使用 @gold/config/api
|
||||
*/
|
||||
|
||||
// 从公共模块导入
|
||||
export { API_BASE, getApiUrl } from '@gold/config/api'
|
||||
|
||||
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* API 使用示例
|
||||
* 此文件仅作为参考,展示如何使用统一的 API 管理
|
||||
*/
|
||||
|
||||
// ========== 方式一:从统一入口导入(推荐) ==========
|
||||
import {
|
||||
ChatMessageApi,
|
||||
CommonService,
|
||||
TikhubService,
|
||||
API_BASE,
|
||||
getApiUrl,
|
||||
http
|
||||
} from '@/api'
|
||||
|
||||
// 使用示例
|
||||
async function example1() {
|
||||
// 使用 ChatMessageApi
|
||||
const conversationId = await ChatMessageApi.createChatConversationMy({
|
||||
roleId: 1
|
||||
})
|
||||
|
||||
// 使用 CommonService
|
||||
const result = await CommonService.videoToCharacters({ videoUrl: 'xxx' })
|
||||
|
||||
// 使用 TikhubService
|
||||
await TikhubService.postTikHup({
|
||||
type: 'DOUYIN_WEB_HOT_SEARCH',
|
||||
methodType: 'GET',
|
||||
urlParams: { keyword: '测试' }
|
||||
})
|
||||
|
||||
// 使用配置
|
||||
const baseUrl = API_BASE.ADMIN_AI
|
||||
const fullUrl = getApiUrl('ADMIN_AI', '/chat/conversation/create-my')
|
||||
|
||||
// 直接使用 http 实例
|
||||
await http.get('/some-endpoint')
|
||||
}
|
||||
|
||||
// ========== 方式二:从具体文件导入(兼容旧代码) ==========
|
||||
import { ChatMessageApi } from '@/api/chat'
|
||||
import { CommonService } from '@/api/common'
|
||||
// 使用公共配置
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
async function example2() {
|
||||
// 原有方式仍然可用
|
||||
await ChatMessageApi.createChatConversationMy({ roleId: 1 })
|
||||
}
|
||||
|
||||
// ========== 方式三:按需导入认证 API ==========
|
||||
import {
|
||||
loginBySms,
|
||||
sendSmsCode,
|
||||
SMS_SCENE
|
||||
} from '@/api'
|
||||
|
||||
async function example3() {
|
||||
// 发送验证码
|
||||
await sendSmsCode('13800138000', SMS_SCENE.MEMBER_LOGIN)
|
||||
|
||||
// 短信登录
|
||||
await loginBySms('13800138000', '123456')
|
||||
}
|
||||
|
||||
export default {
|
||||
example1,
|
||||
example2,
|
||||
example3
|
||||
}
|
||||
|
||||
@@ -1,126 +1,168 @@
|
||||
import axios from 'axios'
|
||||
/**
|
||||
* 应用层 HTTP 客户端
|
||||
* 使用 mono 级别的 axios 实例,添加应用特定的 401 处理
|
||||
*/
|
||||
|
||||
import { message } from 'ant-design-vue'
|
||||
import { getAuthHeader, clearAllTokens } from '@gold/utils/token-manager'
|
||||
import { clearAllTokens, getRefreshToken } from '@gold/utils/token-manager'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import { createClientAxios } from '@gold/api/axios/client'
|
||||
import { refreshToken } from '@/api/auth'
|
||||
|
||||
// 刷新 token 的状态管理
|
||||
let isRefreshing = false
|
||||
let refreshPromise = null
|
||||
|
||||
/**
|
||||
* 不需要 token 的接口白名单
|
||||
* 支持完整路径匹配或路径包含匹配
|
||||
* 处理 403 禁止访问错误(应用层特定逻辑)
|
||||
* 先尝试刷新 token,如果失败或没有 refresh token 才提示用户
|
||||
*/
|
||||
const WHITE_LIST = [
|
||||
'/auth/login', // 密码登录
|
||||
'/auth/send-sms-code', // 发送验证码
|
||||
'/auth/sms-login', // 短信登录
|
||||
'/auth/validate-sms-code', // 验证验证码
|
||||
'/auth/register', // 注册(如果有)
|
||||
'/auth/reset-password', // 重置密码
|
||||
'/auth/refresh-token', // 刷新token(可选,根据后端要求)
|
||||
]
|
||||
|
||||
/**
|
||||
* 检查 URL 是否在白名单中
|
||||
* @param {string} url - 请求 URL
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isInWhiteList(url) {
|
||||
if (!url) return false
|
||||
return WHITE_LIST.some((path) => url.includes(path))
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 创建 axios 实例
|
||||
const http = axios.create({
|
||||
baseURL: '/',
|
||||
timeout: 180000, // 3分钟
|
||||
})
|
||||
|
||||
// 请求拦截:自动注入 Token
|
||||
http.interceptors.request.use((config) => {
|
||||
// 检查是否需要 token(不在白名单中且未显式设置 isToken = false)
|
||||
const needToken = config.headers?.isToken !== false && !isInWhiteList(config.url || '')
|
||||
config.headers['tenant-id'] = import.meta.env.VITE_TENANT_ID
|
||||
if (needToken) {
|
||||
// 使用统一的 token 管理器获取 header
|
||||
const authHeader = getAuthHeader()
|
||||
if (authHeader) {
|
||||
config.headers.Authorization = authHeader
|
||||
}
|
||||
}
|
||||
|
||||
// 允许跨域第三方域名,使用绝对地址时保持原样
|
||||
return config
|
||||
})
|
||||
|
||||
http.interceptors.response.use(
|
||||
(resp) => {
|
||||
const data = resp.data
|
||||
// 检查响应数据中的 code 字段
|
||||
if (data && typeof data.code === 'number' && (data.code === 0 || data.code === 200)) {
|
||||
return data
|
||||
} else {
|
||||
// code 不为 0 时,检查是否为401
|
||||
if (data && typeof data.code === 'number' && data.code === 401) {
|
||||
handle401Error()
|
||||
}
|
||||
// code 不为 0 时,抛出错误
|
||||
const error = new Error(data?.message || data?.msg || '请求失败')
|
||||
error.code = data?.code
|
||||
error.data = data
|
||||
return Promise.reject(error)
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
// 处理 HTTP 状态码 401
|
||||
if (error.response && error.response.status === 401) {
|
||||
handle401Error()
|
||||
}
|
||||
// 统一错误处理:输出关键信息,便于排查 403 等问题
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
/**
|
||||
* 处理 401 未授权错误
|
||||
* 清空 token 并退出登录
|
||||
*
|
||||
* 注意:使用防抖机制避免多个请求同时401时重复处理
|
||||
*/
|
||||
function handle401Error() {
|
||||
// 避免重复处理(防止多个请求同时401导致多次调用)
|
||||
if (handle401Error.processed) {
|
||||
async function handleApp403Error() {
|
||||
// 避免重复处理
|
||||
if (handleApp403Error.processed) {
|
||||
return
|
||||
}
|
||||
|
||||
handle401Error.processed = true
|
||||
handleApp403Error.processed = true
|
||||
|
||||
// 1. 清空所有 token
|
||||
try {
|
||||
clearAllTokens() // 统一使用 token-manager 的清空函数
|
||||
// 检查是否有 refresh token
|
||||
const refreshTokenValue = getRefreshToken()
|
||||
|
||||
if (refreshTokenValue) {
|
||||
// 如果有 refresh token,尝试刷新
|
||||
try {
|
||||
// 如果正在刷新,等待刷新完成
|
||||
if (isRefreshing && refreshPromise) {
|
||||
await refreshPromise
|
||||
handleApp403Error.processed = false
|
||||
return
|
||||
}
|
||||
|
||||
// 开始刷新 token
|
||||
isRefreshing = true
|
||||
refreshPromise = refreshToken()
|
||||
|
||||
await refreshPromise
|
||||
|
||||
// 刷新成功,重置状态
|
||||
isRefreshing = false
|
||||
refreshPromise = null
|
||||
handleApp403Error.processed = false
|
||||
|
||||
// 刷新成功,不提示用户(静默刷新)
|
||||
return
|
||||
} catch (refreshError) {
|
||||
// 刷新失败,清除状态
|
||||
isRefreshing = false
|
||||
refreshPromise = null
|
||||
console.error('刷新 token 失败:', refreshError)
|
||||
|
||||
// 刷新失败才提示用户
|
||||
message.warning('登录状态已过期,请重新登录', 3)
|
||||
handleApp403Error.processed = false
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// 没有 refresh token,提示用户
|
||||
message.warning('登录状态已过期,请重新登录', 3)
|
||||
handleApp403Error.processed = false
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('清空 token 失败:', e)
|
||||
console.error('处理 403 错误失败:', e)
|
||||
handleApp403Error.processed = false
|
||||
}
|
||||
|
||||
// 2. 退出登录状态(清空用户信息)
|
||||
try {
|
||||
const userStore = useUserStore()
|
||||
// logout() 会清空用户信息和本地存储
|
||||
userStore.logout()
|
||||
} catch (e) {
|
||||
console.error('退出登录失败:', e)
|
||||
}
|
||||
|
||||
// 3. 提示用户(延迟显示,避免在清空过程中显示)
|
||||
setTimeout(() => {
|
||||
message.warning('登录已过期,请重新登录', 3)
|
||||
}, 100)
|
||||
|
||||
// 4. 延迟重置标志,避免短时间内重复处理
|
||||
setTimeout(() => {
|
||||
handle401Error.processed = false
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 401 未授权错误(应用层特定逻辑)
|
||||
* 先尝试刷新 token,如果失败或没有 refresh token 才退出登录
|
||||
*/
|
||||
async function handleApp401Error() {
|
||||
// 避免重复处理
|
||||
if (handleApp401Error.processed) {
|
||||
return
|
||||
}
|
||||
|
||||
handleApp401Error.processed = true
|
||||
|
||||
try {
|
||||
// 检查是否有 refresh token
|
||||
const refreshTokenValue = getRefreshToken()
|
||||
|
||||
if (refreshTokenValue) {
|
||||
// 如果有 refresh token,尝试刷新
|
||||
try {
|
||||
// 如果正在刷新,等待刷新完成
|
||||
if (isRefreshing && refreshPromise) {
|
||||
await refreshPromise
|
||||
handleApp401Error.processed = false
|
||||
return
|
||||
}
|
||||
|
||||
// 开始刷新 token
|
||||
isRefreshing = true
|
||||
refreshPromise = refreshToken()
|
||||
|
||||
await refreshPromise
|
||||
|
||||
// 刷新成功,重置状态
|
||||
isRefreshing = false
|
||||
refreshPromise = null
|
||||
handleApp401Error.processed = false
|
||||
|
||||
// 刷新成功,不提示用户(静默刷新)
|
||||
return
|
||||
} catch (refreshError) {
|
||||
// 刷新失败,清除状态
|
||||
isRefreshing = false
|
||||
refreshPromise = null
|
||||
console.error('刷新 token 失败:', refreshError)
|
||||
|
||||
// 继续执行退出登录逻辑
|
||||
}
|
||||
}
|
||||
|
||||
// 没有 refresh token 或刷新失败,执行退出登录
|
||||
try {
|
||||
clearAllTokens()
|
||||
} catch (e) {
|
||||
console.error('清空 token 失败:', e)
|
||||
}
|
||||
|
||||
try {
|
||||
const userStore = useUserStore()
|
||||
userStore.logout()
|
||||
} catch (e) {
|
||||
console.error('退出登录失败:', e)
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
message.warning('登录已过期,请重新登录', 3)
|
||||
}, 100)
|
||||
|
||||
} catch (e) {
|
||||
console.error('处理 401 错误失败:', e)
|
||||
} finally {
|
||||
setTimeout(() => {
|
||||
handleApp401Error.processed = false
|
||||
}, 2000)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建应用层 HTTP 客户端
|
||||
* 基于 mono 级别的 axios 实例,添加应用特定的错误处理
|
||||
*/
|
||||
const http = createClientAxios({
|
||||
baseURL: '/',
|
||||
timeout: 180000,
|
||||
on401: handleApp401Error,
|
||||
on403: handleApp403Error,
|
||||
})
|
||||
|
||||
// 注意:403 处理已在 createClientAxios 的响应拦截器中通过 on403 回调处理
|
||||
|
||||
export default http
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,6 @@
|
||||
* 所有 API 服务都从这里导出,方便统一管理和使用
|
||||
*/
|
||||
|
||||
// 配置
|
||||
export { default as API_BASE, getApiUrl } from './config'
|
||||
|
||||
// HTTP 实例
|
||||
export { default as http, default as request } from './http'
|
||||
|
||||
@@ -15,6 +12,9 @@ export * from './auth'
|
||||
// 聊天相关 API
|
||||
export { ChatMessageApi } from './chat'
|
||||
|
||||
// 用户提示词 API
|
||||
export { UserPromptApi } from './userPrompt'
|
||||
|
||||
// 通用服务 API
|
||||
export { CommonService } from './common'
|
||||
export { default as CommonServiceDefault } from './common'
|
||||
@@ -23,20 +23,3 @@ export { default as CommonServiceDefault } from './common'
|
||||
export { TikhubService, default as TikhubServiceDefault } from './tikhub'
|
||||
export { InterfaceType, MethodType, InterfaceUrlMap, ParamType } from './tikhub/types'
|
||||
|
||||
/**
|
||||
* 统一导出所有 API 服务(便于按需导入)
|
||||
*/
|
||||
export default {
|
||||
// 配置
|
||||
config: () => import('./config'),
|
||||
|
||||
// HTTP 实例
|
||||
http: () => import('./http'),
|
||||
|
||||
// API 服务
|
||||
auth: () => import('./auth'),
|
||||
chat: () => import('./chat'),
|
||||
common: () => import('./common'),
|
||||
tikhub: () => import('./tikhub'),
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// TikHub API 统一导出入口
|
||||
export { TikhubService } from './tikhub/tikhub.js'
|
||||
export { default } from './tikhub/tikhub.js'
|
||||
export { InterfaceType, MethodType, InterfaceUrlMap, ParamType } from './tikhub/types.js'
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
# TikHub API 模块
|
||||
|
||||
本模块提供了统一的 TikHub 接口调用中间层,支持多种平台的 API 接口。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
tikhub/
|
||||
├── types.js # 枚举定义:InterfaceType、MethodType
|
||||
├── tikhub.js # 核心服务类 TikhubService
|
||||
├── index.js # 统一导出入口
|
||||
├── example.js # 使用示例
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 导入模块
|
||||
|
||||
```javascript
|
||||
import TikhubService, { InterfaceType, MethodType } from '@/api/tikhub'
|
||||
```
|
||||
|
||||
### 2. 调用接口
|
||||
|
||||
```javascript
|
||||
// 调用抖音热门搜索接口
|
||||
const response = await TikhubService.postTikHup(
|
||||
InterfaceType.DOUYIN_WEB_HOT_SEARCH, // 接口类型
|
||||
MethodType.GET, // HTTP 方法
|
||||
{ keyword: '测试关键词' } // 实际接口参数
|
||||
)
|
||||
```
|
||||
|
||||
## API 说明
|
||||
|
||||
### TikhubService.postTikHup(type, methodType, urlParams)
|
||||
|
||||
统一调用 TikHub 接口的中间层方法。
|
||||
|
||||
**参数:**
|
||||
- `type` (String) - 接口类型,使用 `InterfaceType` 枚举值
|
||||
- `methodType` (String) - HTTP 方法类型,使用 `MethodType` 枚举值
|
||||
- `urlParams` (Object|String) - 实际接口的参数
|
||||
|
||||
**返回:**
|
||||
- Promise - axios 响应对象
|
||||
|
||||
**示例:**
|
||||
|
||||
```javascript
|
||||
// 获取小红书热门榜单
|
||||
await TikhubService.postTikHup(
|
||||
InterfaceType.XIAOHONGSHU_WEB_HOT_LIST,
|
||||
MethodType.GET,
|
||||
{ page: 1, page_size: 20 }
|
||||
)
|
||||
|
||||
// 搜索抖音内容
|
||||
await TikhubService.postTikHup(
|
||||
InterfaceType.DOUYIN_GENERAL_SEARCH_V4,
|
||||
MethodType.POST,
|
||||
{
|
||||
keyword: '热门内容',
|
||||
sort_type: 0,
|
||||
publish_time: 0,
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## 枚举说明
|
||||
|
||||
### InterfaceType - 接口类型
|
||||
|
||||
支持的所有接口类型:
|
||||
|
||||
| 枚举值 | 说明 |
|
||||
|--------|------|
|
||||
| `XIAOHONGSHU_USER_INFO` | 小红书 - 获取用户信息 |
|
||||
| `DOUYIN_WEB_USER_POST_VIDEOS` | 抖音 - 网页端获取用户发布的视频 |
|
||||
| `DOUYIN_APP_USER_POST_VIDEOS` | 抖音 - APP端V3获取用户发布的视频 |
|
||||
| `DOUYIN_APP_GENERAL_SEARCH` | 抖音 - APP端V3通用搜索结果 |
|
||||
| `DOUYIN_SEARCH_SUGGEST` | 抖音 - 搜索建议 |
|
||||
| `DOUYIN_GENERAL_SEARCH_V4` | 抖音 - 通用搜索V4 |
|
||||
| `XIAOHONGSHU_WEB_HOT_LIST` | 小红书 - 网页端V2热门榜单 |
|
||||
| `DOUYIN_WEB_HOT_SEARCH` | 抖音 - 网页端热门搜索结果 |
|
||||
| `KUAISHOU_WEB_HOT_LIST` | 快手 - 网页端热门榜单V2 |
|
||||
| `BILIBILI_WEB_POPULAR` | B站 - 网页端流行内容 |
|
||||
| `WEIBO_WEB_HOT_SEARCH` | 微博 - 网页端V2热门搜索指数 |
|
||||
| `DOUYIN_WEB_GENERAL_SEARCH` | 抖音 - 网页端通用搜索结果 |
|
||||
|
||||
### MethodType - HTTP 方法
|
||||
|
||||
| 枚举值 | 说明 |
|
||||
|--------|------|
|
||||
| `GET` | GET 请求 |
|
||||
| `POST` | POST 请求 |
|
||||
| `PUT` | PUT 请求 |
|
||||
| `DELETE` | DELETE 请求 |
|
||||
| `PATCH` | PATCH 请求 |
|
||||
|
||||
## 使用示例
|
||||
|
||||
详细的使用示例请参考 `example.js` 文件。
|
||||
|
||||
### 示例 1:获取抖音热门搜索
|
||||
|
||||
```javascript
|
||||
import TikhubService, { InterfaceType, MethodType } from '@/api/tikhub'
|
||||
|
||||
async function getDouyinHotSearch() {
|
||||
try {
|
||||
const response = await TikhubService.postTikHup(
|
||||
InterfaceType.DOUYIN_WEB_HOT_SEARCH,
|
||||
MethodType.GET,
|
||||
{ keyword: '测试关键词' }
|
||||
)
|
||||
return response
|
||||
} catch (error) {
|
||||
console.error('调用失败:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 示例 2:获取用户发布的视频
|
||||
|
||||
```javascript
|
||||
async function getUserVideos() {
|
||||
return await TikhubService.postTikHup(
|
||||
InterfaceType.DOUYIN_WEB_USER_POST_VIDEOS,
|
||||
MethodType.GET,
|
||||
{
|
||||
sec_user_id: 'MS4wLjABAAAxxxxxxxx',
|
||||
count: 20,
|
||||
max_cursor: 0,
|
||||
}
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
```javascript
|
||||
try {
|
||||
const response = await TikhubService.postTikHup(
|
||||
InterfaceType.DOUYIN_WEB_HOT_SEARCH,
|
||||
MethodType.GET,
|
||||
{ keyword: '测试' }
|
||||
)
|
||||
console.log('成功:', response)
|
||||
} catch (error) {
|
||||
if (error.message.includes('无效的接口类型')) {
|
||||
console.error('接口类型错误')
|
||||
} else {
|
||||
console.error('请求失败:', error.message)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 后端接口格式
|
||||
|
||||
本模块会调用后端接口 `/webApi/admin-api/ai/tikHup/post_tik_hup`,传递的参数格式为:
|
||||
|
||||
```json
|
||||
{
|
||||
"interface_type": "8",
|
||||
"method_type": "GET",
|
||||
"platform_url": "https://api.tikhub.io/api/v1/douyin/web/fetch_hot_search_result",
|
||||
"url_params": { "keyword": "测试" }
|
||||
}
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 所有接口类型必须使用 `InterfaceType` 枚举,不能使用字符串数字
|
||||
2. HTTP 方法必须使用 `MethodType` 枚举
|
||||
3. `urlParams` 可以是对象或字符串,取决于实际接口的要求
|
||||
4. 后端会根据 `interface_type` 从数据库中获取对应的 `platform_token`
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/**
|
||||
* TikHub API 统一导出
|
||||
*/
|
||||
export { TikhubService } from './tikhub.js'
|
||||
export { default } from './tikhub.js'
|
||||
export { TikhubService, default } from './tikhub.js'
|
||||
export { InterfaceType, MethodType, InterfaceUrlMap, ParamType } from './types.js'
|
||||
|
||||
|
||||
68
frontend/app/web-gold/src/api/userPrompt.js
Normal file
68
frontend/app/web-gold/src/api/userPrompt.js
Normal file
@@ -0,0 +1,68 @@
|
||||
import http from '@/api/http'
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
// C 端使用 APP_AI,如果不存在则回退到 ADMIN_AI
|
||||
// 后端路径是 /app-api/ai/user-prompt,参考 chat API 的实现
|
||||
const SERVER_BASE_AI = API_BASE.APP_AI || API_BASE.ADMIN_AI
|
||||
|
||||
/**
|
||||
* 用户提示词 API
|
||||
*/
|
||||
export const UserPromptApi = {
|
||||
/**
|
||||
* 创建用户提示词
|
||||
* @param {Object} data - 提示词数据
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
createUserPrompt: async (data) => {
|
||||
return await http.post(`${SERVER_BASE_AI}/user-prompt/create`, data)
|
||||
},
|
||||
|
||||
/**
|
||||
* 更新用户提示词
|
||||
* @param {Object} data - 提示词数据
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
updateUserPrompt: async (data) => {
|
||||
return await http.put(`${SERVER_BASE_AI}/user-prompt/update`, data)
|
||||
},
|
||||
|
||||
/**
|
||||
* 分页查询用户提示词
|
||||
* @param {Object} params - 查询参数
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
getUserPromptPage: async (params) => {
|
||||
return await http.get(`${SERVER_BASE_AI}/user-prompt/page`, { params })
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取单个用户提示词
|
||||
* @param {Number} id - 提示词ID
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
getUserPrompt: async (id) => {
|
||||
return await http.get(`${SERVER_BASE_AI}/user-prompt/get`, { params: { id } })
|
||||
},
|
||||
|
||||
/**
|
||||
* 删除用户提示词
|
||||
* @param {Number} id - 提示词ID
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
deleteUserPrompt: async (id) => {
|
||||
return await http.delete(`${SERVER_BASE_AI}/user-prompt/delete`, { params: { id } })
|
||||
},
|
||||
|
||||
/**
|
||||
* 批量删除用户提示词
|
||||
* @param {Array<Number>} ids - 提示词ID列表
|
||||
* @returns {Promise} 响应数据
|
||||
*/
|
||||
deleteUserPromptList: async (ids) => {
|
||||
return await http.delete(`${SERVER_BASE_AI}/user-prompt/delete-list`, { params: { ids } })
|
||||
},
|
||||
}
|
||||
|
||||
export default UserPromptApi
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, computed } from 'vue'
|
||||
import { ref, watch, onUnmounted } from 'vue'
|
||||
import { renderMarkdown } from '@/utils/markdown'
|
||||
|
||||
const props = defineProps({
|
||||
@@ -17,196 +17,152 @@ const props = defineProps({
|
||||
}
|
||||
})
|
||||
|
||||
// 已完成的 chunks(包含已渲染的 HTML)
|
||||
const chunks = ref([])
|
||||
// chunk ID 计数器
|
||||
const chunkIdCounter = ref(0)
|
||||
// 当前显示的内容(用于打字机效果)
|
||||
const displayedContent = ref('')
|
||||
// 目标内容(完整内容)
|
||||
const targetContent = ref('')
|
||||
// 动画帧 ID
|
||||
let animationFrameId = null
|
||||
// 打字机速度(字符/帧,可根据性能调整)
|
||||
const TYPING_SPEED = 3
|
||||
// 是否正在执行打字机动画
|
||||
const isTyping = ref(false)
|
||||
|
||||
/**
|
||||
* 创建 chunk 对象(包含预渲染的 HTML)
|
||||
* 高性能打字机效果渲染
|
||||
* 使用 requestAnimationFrame 实现平滑的逐字符显示
|
||||
*/
|
||||
function createChunk(text) {
|
||||
return {
|
||||
id: chunkIdCounter.value++,
|
||||
text: text.trim(),
|
||||
rendered: renderMarkdown(text.trim()) // 预渲染,避免重复渲染
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 智能分块:业界成熟方案
|
||||
*/
|
||||
function splitIntoChunks(text) {
|
||||
if (!text || !text.trim()) return []
|
||||
function typewriterEffect() {
|
||||
if (!isTyping.value) return
|
||||
|
||||
const result = []
|
||||
const currentLength = displayedContent.value.length
|
||||
const targetLength = targetContent.value.length
|
||||
|
||||
// 第一级:按段落分割(双换行)
|
||||
const paragraphs = text.split(/\n\s*\n/)
|
||||
|
||||
for (const paragraph of paragraphs) {
|
||||
if (!paragraph.trim()) continue
|
||||
|
||||
// 如果段落长度适中(< 500字符),直接作为一个 chunk
|
||||
if (paragraph.trim().length < 500) {
|
||||
result.push(createChunk(paragraph))
|
||||
continue
|
||||
}
|
||||
|
||||
// 第二级:段落太长,按句子分割
|
||||
const sentences = paragraph.split(/([。!?.!?]\s*)/)
|
||||
let currentChunk = ''
|
||||
|
||||
for (let i = 0; i < sentences.length; i++) {
|
||||
currentChunk += sentences[i]
|
||||
|
||||
// 如果累积的句子达到一定长度(> 300字符),创建一个 chunk
|
||||
if (currentChunk.trim().length > 300) {
|
||||
result.push(createChunk(currentChunk))
|
||||
currentChunk = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 处理剩余的文本
|
||||
if (currentChunk.trim()) {
|
||||
if (currentChunk.trim().length > 500) {
|
||||
// 第三级:按固定长度分割
|
||||
const fixedLength = 400
|
||||
let start = 0
|
||||
while (start < currentChunk.length) {
|
||||
const end = Math.min(start + fixedLength, currentChunk.length)
|
||||
const chunkText = currentChunk.slice(start, end).trim()
|
||||
if (chunkText) {
|
||||
result.push(createChunk(chunkText))
|
||||
}
|
||||
start = end
|
||||
}
|
||||
} else {
|
||||
result.push(createChunk(currentChunk))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算流式传输中的文本
|
||||
*/
|
||||
const streamingText = computed(() => {
|
||||
if (!props.isStreaming || !props.content) return ''
|
||||
|
||||
const text = props.content
|
||||
|
||||
// 优先查找最后一个段落分隔符
|
||||
const lastParagraphIndex = text.lastIndexOf('\n\n')
|
||||
if (lastParagraphIndex !== -1) {
|
||||
return text.slice(lastParagraphIndex + 2)
|
||||
}
|
||||
|
||||
// 查找最后一个句子结束符
|
||||
const lastSentenceMatch = text.match(/([。!?.!?]\s*)(?!.*[。!?.!?]\s*)/)
|
||||
if (lastSentenceMatch) {
|
||||
return text.slice(lastSentenceMatch.index + lastSentenceMatch[0].length)
|
||||
}
|
||||
|
||||
// 全部作为流式文本
|
||||
return text
|
||||
})
|
||||
|
||||
/**
|
||||
* 计算最终渲染的内容(合并所有 chunks 和流式文本)
|
||||
*/
|
||||
const renderedContent = computed(() => {
|
||||
let html = ''
|
||||
|
||||
// 添加已完成的 chunks
|
||||
for (const chunk of chunks.value) {
|
||||
html += chunk.rendered
|
||||
}
|
||||
|
||||
// 添加流式传输中的文本
|
||||
if (props.isStreaming && streamingText.value) {
|
||||
html += renderMarkdown(streamingText.value)
|
||||
}
|
||||
|
||||
return html
|
||||
})
|
||||
|
||||
/**
|
||||
* 增量更新 chunks(避免全量重新渲染)
|
||||
*/
|
||||
function updateChunksIncremental(content) {
|
||||
if (!content) {
|
||||
chunks.value = []
|
||||
if (currentLength >= targetLength) {
|
||||
// 已完成,停止动画
|
||||
isTyping.value = false
|
||||
displayedContent.value = targetContent.value
|
||||
return
|
||||
}
|
||||
|
||||
const text = content
|
||||
// 每次增加多个字符以提高性能
|
||||
const nextLength = Math.min(currentLength + TYPING_SPEED, targetLength)
|
||||
displayedContent.value = targetContent.value.slice(0, nextLength)
|
||||
|
||||
// 查找最后一个段落分隔符
|
||||
const lastParagraphIndex = text.lastIndexOf('\n\n')
|
||||
let completedText = ''
|
||||
|
||||
if (lastParagraphIndex !== -1) {
|
||||
completedText = text.slice(0, lastParagraphIndex)
|
||||
} else {
|
||||
// 没有段落分隔符,查找最后一个句子结束符
|
||||
const lastSentenceMatch = text.match(/([。!?.!?]\s*)(?!.*[。!?.!?]\s*)/)
|
||||
if (lastSentenceMatch && lastSentenceMatch.index > 300) {
|
||||
completedText = text.slice(0, lastSentenceMatch.index + lastSentenceMatch[0].length)
|
||||
} else {
|
||||
// 流式传输中,还没有完整的段落或句子
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 分割已完成的文本
|
||||
const newChunks = splitIntoChunks(completedText)
|
||||
|
||||
// 增量更新:只添加新的 chunks,保留已存在的
|
||||
if (newChunks.length > chunks.value.length) {
|
||||
// 只添加新增的 chunks
|
||||
const existingTexts = new Set(chunks.value.map(c => c.text))
|
||||
for (let i = chunks.value.length; i < newChunks.length; i++) {
|
||||
if (!existingTexts.has(newChunks[i].text)) {
|
||||
chunks.value.push(newChunks[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
// 继续下一帧
|
||||
animationFrameId = requestAnimationFrame(typewriterEffect)
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始打字机效果
|
||||
*/
|
||||
function startTypewriter() {
|
||||
if (animationFrameId) {
|
||||
cancelAnimationFrame(animationFrameId)
|
||||
}
|
||||
|
||||
isTyping.value = true
|
||||
animationFrameId = requestAnimationFrame(typewriterEffect)
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止打字机效果
|
||||
*/
|
||||
function stopTypewriter() {
|
||||
if (animationFrameId) {
|
||||
cancelAnimationFrame(animationFrameId)
|
||||
animationFrameId = null
|
||||
}
|
||||
isTyping.value = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算渲染的 HTML 内容
|
||||
*/
|
||||
const renderedContent = ref('')
|
||||
|
||||
/**
|
||||
* 更新渲染内容
|
||||
*/
|
||||
function updateRenderedContent() {
|
||||
const content = displayedContent.value
|
||||
if (!content) {
|
||||
renderedContent.value = ''
|
||||
return
|
||||
}
|
||||
|
||||
// 渲染 markdown 为 HTML
|
||||
renderedContent.value = renderMarkdown(content)
|
||||
}
|
||||
|
||||
// 监听 displayedContent 变化,更新渲染
|
||||
watch(displayedContent, () => {
|
||||
updateRenderedContent()
|
||||
}, { immediate: true })
|
||||
|
||||
/**
|
||||
* 处理内容更新
|
||||
*/
|
||||
function updateChunks(content) {
|
||||
if (!content) {
|
||||
chunks.value = []
|
||||
function handleContentUpdate(newContent) {
|
||||
if (!newContent) {
|
||||
targetContent.value = ''
|
||||
displayedContent.value = ''
|
||||
stopTypewriter()
|
||||
return
|
||||
}
|
||||
|
||||
// 更新目标内容
|
||||
targetContent.value = newContent
|
||||
|
||||
if (props.isStreaming) {
|
||||
// 流式模式:增量更新
|
||||
updateChunksIncremental(content)
|
||||
// 流式传输模式:使用打字机效果显示内容
|
||||
// 流式传输时,内容会逐步到达,使用打字机效果增强体验
|
||||
const currentLength = displayedContent.value.length
|
||||
const newLength = newContent.length
|
||||
|
||||
if (newLength !== currentLength) {
|
||||
// 内容发生变化
|
||||
if (newLength < currentLength) {
|
||||
// 内容被重置或缩短,直接显示新内容
|
||||
displayedContent.value = newContent
|
||||
stopTypewriter()
|
||||
} else {
|
||||
// 内容增加,使用打字机效果显示新增部分
|
||||
if (!isTyping.value) {
|
||||
startTypewriter()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 非流式模式:完整分割
|
||||
chunks.value = splitIntoChunks(content)
|
||||
// 静态内容模式:直接显示全部内容,不使用打字机效果
|
||||
displayedContent.value = newContent
|
||||
stopTypewriter()
|
||||
}
|
||||
}
|
||||
|
||||
// 监听 content 变化
|
||||
watch(() => props.content, (newContent) => {
|
||||
updateChunks(newContent)
|
||||
handleContentUpdate(newContent)
|
||||
}, { immediate: true })
|
||||
|
||||
// 监听 isStreaming 变化:流式结束时处理最后一个未完成的块
|
||||
// 监听 isStreaming 变化
|
||||
watch(() => props.isStreaming, (newVal, oldVal) => {
|
||||
if (!newVal && oldVal && props.content) {
|
||||
// 流式结束,完整重新分割
|
||||
const newChunks = splitIntoChunks(props.content)
|
||||
chunks.value = newChunks
|
||||
if (!newVal && oldVal) {
|
||||
// 流式传输结束,确保显示完整内容,停止打字机效果
|
||||
if (targetContent.value) {
|
||||
displayedContent.value = targetContent.value
|
||||
}
|
||||
stopTypewriter()
|
||||
} else if (newVal) {
|
||||
// 开始流式传输,如果内容有变化,启动打字机效果
|
||||
// 打字机效果会在 handleContentUpdate 中根据内容变化自动启动
|
||||
}
|
||||
})
|
||||
|
||||
// 组件卸载时清理
|
||||
onUnmounted(() => {
|
||||
stopTypewriter()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -34,6 +34,12 @@ const items = computed(() => {
|
||||
{ path: '/digital-human/voice-generate', label: '生成配音', icon: 'wave' },
|
||||
]
|
||||
},
|
||||
{
|
||||
title: '系统',
|
||||
children: [
|
||||
{ path: '/system/style-settings', label: '风格设置', icon: 'text' },
|
||||
]
|
||||
},
|
||||
// {
|
||||
// title: '视频',
|
||||
// children: [
|
||||
|
||||
@@ -37,6 +37,14 @@ const routes = [
|
||||
{ path: 'avatar', name: '生成数字人', component: () => import('../views/dh/Avatar.vue') },
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/system',
|
||||
name: '系统',
|
||||
children: [
|
||||
{ path: '', redirect: '/system/style-settings' },
|
||||
{ path: 'style-settings', name: '风格设置', component: () => import('../views/system/StyleSettings.vue') },
|
||||
]
|
||||
},
|
||||
{ path: '/realtime-hot', name: '实时热点推送', component: () => import('../views/realtime/RealtimeHot.vue') },
|
||||
{ path: '/mix-editor', name: '素材混剪', component: () => import('../views/mix/MixEditor.vue') },
|
||||
{ path: '/capcut-import', name: '剪映导入', component: () => import('../views/capcut/CapcutImport.vue') },
|
||||
|
||||
@@ -211,7 +211,12 @@ export async function streamChat(options = {}) {
|
||||
return
|
||||
}
|
||||
|
||||
// 获取内容片段
|
||||
// 忽略只有 send 没有 receive 的消息(用户消息确认,不需要处理内容)
|
||||
if (responseData.send && !responseData.receive) {
|
||||
return
|
||||
}
|
||||
|
||||
// 获取 AI 回复的内容片段(增量更新,需要累加)
|
||||
const piece = responseData.receive?.content || responseData.receive?.reasoningContent || ''
|
||||
if (piece) {
|
||||
fullText += piece
|
||||
@@ -222,7 +227,11 @@ export async function streamChat(options = {}) {
|
||||
// 兼容其他格式
|
||||
try {
|
||||
const obj = JSON.parse(dataStr)
|
||||
const piece = obj?.content || obj?.data || obj?.text || ''
|
||||
// 跳过只有 send 的消息
|
||||
if (obj?.data?.send && !obj?.data?.receive) {
|
||||
return
|
||||
}
|
||||
const piece = obj?.content || obj?.data?.receive?.content || obj?.text || ''
|
||||
if (piece) {
|
||||
fullText += piece
|
||||
smoothUpdate(fullText)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,16 @@
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { ref, onMounted, computed, watch } from 'vue'
|
||||
import { usePromptStore } from '@/stores/prompt'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { CommonService } from '@/api/common'
|
||||
import useVoiceText from '@gold/hooks/web/useVoiceText'
|
||||
import GmIcon from '@/components/icons/Icon.vue'
|
||||
import { UserPromptApi } from '@/api/userPrompt'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const promptStore = usePromptStore()
|
||||
const userStore = useUserStore()
|
||||
const md = new MarkdownIt()
|
||||
|
||||
// 表单数据(合并为单一输入)
|
||||
@@ -29,11 +32,171 @@ const originalContent = ref('')
|
||||
const isLoading = ref(false)
|
||||
const { getVoiceText } = useVoiceText()
|
||||
|
||||
// 页面加载时,如果有提示词则自动填充
|
||||
onMounted(() => {
|
||||
// 提示词相关状态
|
||||
const allPrompts = ref([])
|
||||
const loadingPrompts = ref(false)
|
||||
const showAllPromptsModal = ref(false)
|
||||
const selectedPromptId = ref(null)
|
||||
const promptSearchKeyword = ref('')
|
||||
const DISPLAY_COUNT = 6 // 展示的提示词数量
|
||||
|
||||
// 计算属性:展示的部分提示词
|
||||
const displayPrompts = computed(() => {
|
||||
return allPrompts.value.slice(0, DISPLAY_COUNT)
|
||||
})
|
||||
|
||||
// 计算属性:过滤后的全部提示词(用于"更多"弹窗)
|
||||
const filteredPrompts = computed(() => {
|
||||
if (!promptSearchKeyword.value.trim()) {
|
||||
return allPrompts.value
|
||||
}
|
||||
const keyword = promptSearchKeyword.value.trim().toLowerCase()
|
||||
return allPrompts.value.filter(p =>
|
||||
p.name.toLowerCase().includes(keyword) ||
|
||||
(p.content && p.content.toLowerCase().includes(keyword))
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* 加载用户提示词列表
|
||||
* 从服务器获取当前用户的提示词,并按创建时间倒序排列
|
||||
*/
|
||||
async function loadUserPrompts() {
|
||||
const userId = Number(userStore.userId)
|
||||
if (!userId) {
|
||||
console.warn('无法获取用户ID,跳过加载提示词')
|
||||
return
|
||||
}
|
||||
|
||||
loadingPrompts.value = true
|
||||
try {
|
||||
const response = await UserPromptApi.getUserPromptPage({
|
||||
userId: userId,
|
||||
status: 1, // 只加载启用的提示词
|
||||
pageNo: 1,
|
||||
pageSize: 100, // 加载前100个
|
||||
})
|
||||
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
const list = response.data?.list || []
|
||||
// 按创建时间倒序排列(最新的在前)
|
||||
allPrompts.value = list.sort((a, b) => {
|
||||
const timeA = a.createTime ? new Date(a.createTime).getTime() : 0
|
||||
const timeB = b.createTime ? new Date(b.createTime).getTime() : 0
|
||||
return timeB - timeA
|
||||
})
|
||||
|
||||
// 如果用户没有选择提示词,默认选中第一个
|
||||
autoSelectFirstPromptIfNeeded()
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '加载失败')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载提示词列表失败:', error)
|
||||
// 不显示错误提示,避免影响用户体验
|
||||
} finally {
|
||||
loadingPrompts.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动选中第一个提示词(如果用户还没有选择)
|
||||
*/
|
||||
function autoSelectFirstPromptIfNeeded() {
|
||||
const hasPrompts = allPrompts.value.length > 0
|
||||
const hasNoSelection = !selectedPromptId.value && !form.value.prompt
|
||||
|
||||
if (hasPrompts && hasNoSelection) {
|
||||
const firstPrompt = allPrompts.value[0]
|
||||
if (firstPrompt?.content) {
|
||||
selectedPromptId.value = firstPrompt.id
|
||||
form.value.prompt = firstPrompt.content
|
||||
promptStore.setPrompt(firstPrompt.content, firstPrompt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 选择提示词
|
||||
function selectPrompt(prompt) {
|
||||
if (!prompt || !prompt.content) {
|
||||
message.warning('提示词内容为空')
|
||||
return
|
||||
}
|
||||
|
||||
selectedPromptId.value = prompt.id
|
||||
form.value.prompt = prompt.content
|
||||
promptStore.setPrompt(prompt.content, prompt)
|
||||
showAllPromptsModal.value = false
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 等待用户信息初始化完成
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function waitForUserInfo() {
|
||||
// 等待 store 从本地存储恢复完成(最多等待 500ms)
|
||||
let waitCount = 0
|
||||
const maxWait = 50 // 50 * 10ms = 500ms
|
||||
while (!userStore.isHydrated && waitCount < maxWait) {
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
waitCount++
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保用户信息已加载
|
||||
* 如果已登录但 userId 为空,则从服务器获取用户信息
|
||||
*/
|
||||
async function ensureUserInfoLoaded() {
|
||||
const isLoggedIn = userStore.isLoggedIn
|
||||
const hasNoUserId = !userStore.userId
|
||||
|
||||
if (isLoggedIn && hasNoUserId) {
|
||||
try {
|
||||
await userStore.fetchUserInfo()
|
||||
} catch (error) {
|
||||
console.error('获取用户信息失败:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化页面数据
|
||||
* 1. 恢复之前保存的提示词(如果有)
|
||||
* 2. 等待用户信息初始化
|
||||
* 3. 确保用户信息已加载
|
||||
* 4. 加载提示词列表
|
||||
*/
|
||||
async function initializePage() {
|
||||
// 1. 恢复之前保存的提示词
|
||||
if (promptStore.currentPrompt) {
|
||||
form.value.prompt = promptStore.currentPrompt
|
||||
}
|
||||
|
||||
// 2. 等待用户信息初始化完成
|
||||
await waitForUserInfo()
|
||||
|
||||
// 3. 确保用户信息已加载
|
||||
await ensureUserInfoLoaded()
|
||||
|
||||
// 4. 加载提示词列表
|
||||
await loadUserPrompts()
|
||||
}
|
||||
|
||||
// 页面加载时初始化
|
||||
onMounted(() => {
|
||||
initializePage()
|
||||
})
|
||||
|
||||
// 监听 userId 变化:如果之前没有 userId,现在有了,则自动加载提示词
|
||||
watch(() => userStore.userId, async (newUserId, oldUserId) => {
|
||||
const userIdChanged = newUserId && !oldUserId
|
||||
const hasNoPrompts = allPrompts.value.length === 0
|
||||
|
||||
if (userIdChanged && hasNoPrompts) {
|
||||
await loadUserPrompts()
|
||||
}
|
||||
})
|
||||
|
||||
// 生成文案(流式)
|
||||
@@ -45,6 +208,17 @@ async function generateCopywriting() {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否选择了提示词风格
|
||||
if (!form.value.prompt || !form.value.prompt.trim()) {
|
||||
message.warning('请先选择提示词风格')
|
||||
return
|
||||
}
|
||||
|
||||
if (!selectedPromptId.value) {
|
||||
message.warning('请先选择提示词风格')
|
||||
return
|
||||
}
|
||||
|
||||
isLoading.value = true
|
||||
generatedContent.value = '' // 清空之前的内容
|
||||
|
||||
@@ -244,21 +418,54 @@ defineOptions({ name: 'ContentStyleCopywriting' })
|
||||
<a-form :model="form" layout="vertical" class="form-container">
|
||||
<a-form-item class="form-item">
|
||||
<template #label>
|
||||
基础提示词
|
||||
<span class="form-tip-inline">从视频分析提取的提示词,将作为文案生成的基础参考</span>
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span>
|
||||
选择提示词风格
|
||||
<span class="form-tip-inline">从已保存的提示词中选择</span>
|
||||
</span>
|
||||
<a-space>
|
||||
<a-button
|
||||
size="small"
|
||||
type="link"
|
||||
@click="showAllPromptsModal = true"
|
||||
:disabled="allPrompts.length === 0">
|
||||
更多 ({{ allPrompts.length }})
|
||||
</a-button>
|
||||
</a-space>
|
||||
</div>
|
||||
</template>
|
||||
<a-textarea
|
||||
v-model:value="form.prompt"
|
||||
placeholder="这里显示从视频分析中提取的创作提示词,将作为文案生成的基础参考"
|
||||
:auto-size="{ minRows: 6, maxRows: 12 }"
|
||||
class="custom-textarea"
|
||||
/>
|
||||
|
||||
<!-- 提示词标签展示区域 -->
|
||||
<div v-if="displayPrompts.length > 0" class="prompt-tags-container">
|
||||
<div class="prompt-tags-grid">
|
||||
<div
|
||||
v-for="prompt in displayPrompts"
|
||||
:key="prompt.id"
|
||||
class="prompt-tag"
|
||||
:class="{ 'prompt-tag-selected': selectedPromptId === prompt.id }"
|
||||
@click="selectPrompt(prompt)">
|
||||
<span class="prompt-tag-name">{{ prompt.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else-if="!loadingPrompts" class="prompt-empty">
|
||||
<div style="color: var(--color-text-secondary); font-size: 12px; text-align: center; padding: 20px;">
|
||||
您可以在视频分析页面保存风格
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载状态 -->
|
||||
<div v-else class="prompt-loading">
|
||||
<a-spin size="small" />
|
||||
</div>
|
||||
</a-form-item>
|
||||
|
||||
<!-- 统一输入:文本或视频链接 -->
|
||||
<a-form-item class="form-item">
|
||||
<template #label>
|
||||
输入内容/视频链接
|
||||
输入内容
|
||||
<span class="form-tip-inline">输入要生成的主题/段落,或粘贴视频链接以自动转写</span>
|
||||
</template>
|
||||
<a-textarea
|
||||
@@ -296,7 +503,7 @@ defineOptions({ name: 'ContentStyleCopywriting' })
|
||||
<a-button
|
||||
type="primary"
|
||||
@click="generateCopywriting"
|
||||
:disabled="!getCurrentInputValue() || isLoading"
|
||||
:disabled="!getCurrentInputValue() || !selectedPromptId || isLoading"
|
||||
:loading="isLoading"
|
||||
block
|
||||
size="large"
|
||||
@@ -361,20 +568,67 @@ defineOptions({ name: 'ContentStyleCopywriting' })
|
||||
<div v-else class="generated-content" v-html="md.render(generatedContent)"></div>
|
||||
</div>
|
||||
|
||||
<a-empty v-else class="custom-empty">
|
||||
<template #description>
|
||||
<div class="empty-description">
|
||||
<div class="empty-icon"><GmIcon name="icon-empty-doc" :size="36" /></div>
|
||||
<div class="empty-title">等待生成文案</div>
|
||||
<div class="empty-desc">请选择内容类型并填写相关信息,然后点击"生成文案"按钮</div>
|
||||
</div>
|
||||
</template>
|
||||
</a-empty>
|
||||
<div v-else class="custom-empty">
|
||||
<div class="empty-description">
|
||||
<div class="empty-icon"><GmIcon name="icon-empty-doc" :size="36" /></div>
|
||||
<div class="empty-title">等待生成文案</div>
|
||||
<div class="empty-desc">请选择内容类型并填写相关信息,然后点击"生成文案"按钮</div>
|
||||
</div>
|
||||
</div>
|
||||
</a-card>
|
||||
</div>
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
|
||||
<!-- 更多提示词弹窗 -->
|
||||
<a-modal
|
||||
v-model:open="showAllPromptsModal"
|
||||
title="选择提示词"
|
||||
:width="800"
|
||||
:maskClosable="false">
|
||||
<div class="all-prompts-modal">
|
||||
<!-- 搜索框 -->
|
||||
<a-input
|
||||
v-model:value="promptSearchKeyword"
|
||||
placeholder="搜索提示词名称或内容..."
|
||||
allow-clear
|
||||
style="margin-bottom: 16px;">
|
||||
<template #prefix>
|
||||
<GmIcon name="icon-search" :size="16" />
|
||||
</template>
|
||||
</a-input>
|
||||
|
||||
<!-- 提示词列表(标签形式) -->
|
||||
<div v-if="filteredPrompts.length > 0" class="all-prompts-tags">
|
||||
<div
|
||||
v-for="prompt in filteredPrompts"
|
||||
:key="prompt.id"
|
||||
class="all-prompt-tag"
|
||||
:class="{ 'all-prompt-tag-selected': selectedPromptId === prompt.id }"
|
||||
@click="selectPrompt(prompt)">
|
||||
<span class="all-prompt-tag-name">{{ prompt.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空状态 -->
|
||||
<div v-else style="text-align: center; padding: 40px; color: var(--color-text-secondary);">
|
||||
没有找到匹配的提示词
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<a-space>
|
||||
<a-button @click="showAllPromptsModal = false">取消</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
@click="loadUserPrompts"
|
||||
:loading="loadingPrompts">
|
||||
刷新列表
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -848,6 +1102,111 @@ defineOptions({ name: 'ContentStyleCopywriting' })
|
||||
color: #e3e6ea;
|
||||
}
|
||||
|
||||
/* 提示词标签样式 */
|
||||
.prompt-tags-container {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.prompt-tags-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.prompt-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 6px 14px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 16px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.prompt-tag:hover {
|
||||
border-color: var(--color-primary);
|
||||
background: rgba(22, 119, 255, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.prompt-tag-selected {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.prompt-tag-selected:hover {
|
||||
background: var(--color-primary);
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.prompt-tag-name {
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.prompt-empty {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.prompt-loading {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 更多提示词弹窗样式 */
|
||||
.all-prompts-modal {
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.all-prompts-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.all-prompt-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 8px 16px;
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 16px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.all-prompt-tag:hover {
|
||||
border-color: var(--color-primary);
|
||||
background: rgba(22, 119, 255, 0.08);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.all-prompt-tag-selected {
|
||||
border-color: var(--color-primary);
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.all-prompt-tag-selected:hover {
|
||||
background: var(--color-primary);
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
.all-prompt-tag-name {
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.page-header {
|
||||
@@ -898,6 +1257,15 @@ defineOptions({ name: 'ContentStyleCopywriting' })
|
||||
padding: 14px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.prompt-tags-grid {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.prompt-tag {
|
||||
font-size: 12px;
|
||||
padding: 5px 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import { EditOutlined, CopyOutlined } from '@ant-design/icons-vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import ChatMessageRenderer from '@/components/ChatMessageRenderer.vue'
|
||||
import { ChatMessageApi } from '@/api/chat'
|
||||
import { streamChat } from '@/utils/streamChat'
|
||||
|
||||
const props = defineProps({
|
||||
visible: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
mergedText: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
textCount: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:visible', 'copy', 'save', 'use'])
|
||||
|
||||
const batchPrompt = ref('')
|
||||
const batchPromptEditMode = ref(false)
|
||||
const batchPromptGenerating = ref(false)
|
||||
const hasGenerated = ref(false)
|
||||
|
||||
watch(() => props.visible, (newVal) => {
|
||||
if (newVal && props.mergedText && !hasGenerated.value) {
|
||||
generateBatchPrompt()
|
||||
} else if (!newVal) {
|
||||
batchPrompt.value = ''
|
||||
batchPromptEditMode.value = false
|
||||
batchPromptGenerating.value = false
|
||||
hasGenerated.value = false
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => props.mergedText, (newVal) => {
|
||||
if (props.visible && newVal && !hasGenerated.value) {
|
||||
generateBatchPrompt()
|
||||
}
|
||||
})
|
||||
|
||||
async function generateBatchPrompt() {
|
||||
if (!props.mergedText || hasGenerated.value) return
|
||||
|
||||
hasGenerated.value = true
|
||||
try {
|
||||
batchPromptGenerating.value = true
|
||||
const createPayload = { roleId: 20 }
|
||||
console.debug('createChatConversationMy payload(batch):', createPayload)
|
||||
const conversationResp = await ChatMessageApi.createChatConversationMy(createPayload)
|
||||
|
||||
let conversationId = null
|
||||
if (conversationResp?.data) {
|
||||
conversationId = typeof conversationResp.data === 'object' ? conversationResp.data.id : conversationResp.data
|
||||
}
|
||||
|
||||
if (!conversationId) {
|
||||
throw new Error('创建对话失败:未获取到 conversationId')
|
||||
}
|
||||
|
||||
const aiContent = await streamChat({
|
||||
conversationId,
|
||||
content: props.mergedText,
|
||||
onUpdate: (fullText) => {
|
||||
batchPrompt.value = fullText
|
||||
},
|
||||
enableTypewriter: true,
|
||||
typewriterSpeed: 10,
|
||||
typewriterBatchSize: 2
|
||||
})
|
||||
|
||||
if (aiContent && aiContent !== batchPrompt.value) {
|
||||
batchPrompt.value = aiContent
|
||||
}
|
||||
|
||||
message.success(`批量分析完成:已基于 ${props.textCount} 个视频的文案生成综合提示词`)
|
||||
} catch (aiError) {
|
||||
console.error('AI生成失败:', aiError)
|
||||
message.error('AI生成失败,请稍后重试')
|
||||
} finally {
|
||||
batchPromptGenerating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function handleCopy() {
|
||||
emit('copy', batchPrompt.value)
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
emit('save', batchPrompt.value)
|
||||
}
|
||||
|
||||
function handleUse() {
|
||||
emit('use', batchPrompt.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-modal
|
||||
:open="visible"
|
||||
title="综合分析结果"
|
||||
:width="800"
|
||||
:maskClosable="false"
|
||||
:keyboard="false"
|
||||
@cancel="handleClose">
|
||||
<div class="batch-prompt-modal">
|
||||
<div v-if="!batchPromptEditMode" class="batch-prompt-display">
|
||||
<ChatMessageRenderer
|
||||
:content="batchPrompt"
|
||||
:is-streaming="batchPromptGenerating"
|
||||
/>
|
||||
</div>
|
||||
<a-textarea
|
||||
v-else
|
||||
v-model:value="batchPrompt"
|
||||
:rows="15"
|
||||
placeholder="内容将在这里显示..." />
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<a-space>
|
||||
<a-button size="small" :title="batchPromptEditMode ? '取消编辑' : '编辑'" @click="batchPromptEditMode = !batchPromptEditMode">
|
||||
<template #icon>
|
||||
<EditOutlined />
|
||||
</template>
|
||||
</a-button>
|
||||
<a-button size="small" title="复制" @click="handleCopy">
|
||||
<template #icon>
|
||||
<CopyOutlined />
|
||||
</template>
|
||||
</a-button>
|
||||
<a-button size="small" title="保存提示词" @click="handleSave" :disabled="!batchPrompt.trim()">
|
||||
保存提示词
|
||||
</a-button>
|
||||
<a-button @click="handleClose">取消</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
:disabled="batchPromptGenerating || !batchPrompt.trim()"
|
||||
@click="handleUse">去创作</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</a-modal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.batch-prompt-modal {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
.batch-prompt-display {
|
||||
min-height: 300px;
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
background: #0d0d0d;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(h1) {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
margin: 12px 0;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(h2) {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
margin: 16px 0 8px 0;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(h3) {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin: 12px 0 6px 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(p) {
|
||||
margin: 8px 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(ul),
|
||||
.batch-prompt-display :deep(ol) {
|
||||
margin: 8px 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(li) {
|
||||
margin: 4px 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(strong) {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(code) {
|
||||
background: #1a1a1a;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
color: #e11d48;
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(pre) {
|
||||
background: #1a1a1a;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(pre code) {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.batch-prompt-display :deep(blockquote) {
|
||||
border-left: 3px solid var(--color-primary);
|
||||
padding-left: 12px;
|
||||
margin: 8px 0;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
loading: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:modelValue', 'analyze', 'reset'])
|
||||
|
||||
const form = ref({ ...props.modelValue })
|
||||
|
||||
function handleAnalyze() {
|
||||
emit('update:modelValue', { ...form.value })
|
||||
emit('analyze')
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
form.value = { platform: '抖音', url: '', count: 20, sort_type: 0 }
|
||||
emit('update:modelValue', { ...form.value })
|
||||
emit('reset')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="card">
|
||||
<a-form :model="form" layout="vertical">
|
||||
<a-form-item label="平台">
|
||||
<a-radio-group v-model:value="form.platform" button-style="solid">
|
||||
<a-radio-button value="抖音">抖音</a-radio-button>
|
||||
</a-radio-group>
|
||||
</a-form-item>
|
||||
<a-form-item label="主页/视频链接">
|
||||
<a-input
|
||||
v-model:value="form.url"
|
||||
placeholder="粘贴抖音主页或视频链接,或点击下方示例试一试"
|
||||
allow-clear
|
||||
size="large"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="最大数量(建议保持默认值20)">
|
||||
<div class="slider-row">
|
||||
<a-slider v-model:value="form.count" :min="1" :max="100" :tooltip-open="true" style="flex:1" />
|
||||
<a-input-number v-model:value="form.count" :min="1" :max="100" style="width:96px; margin-left:12px;" />
|
||||
</div>
|
||||
<div class="form-hint">数量越大越全面,但分析时间更长;建议 20–30。</div>
|
||||
</a-form-item>
|
||||
<a-space>
|
||||
<a-button type="primary" :loading="loading" @click="handleAnalyze">
|
||||
{{ loading ? '分析中…' : '开始分析' }}
|
||||
</a-button>
|
||||
<a-button @click="handleReset">清空</a-button>
|
||||
</a-space>
|
||||
</a-form>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card {
|
||||
background: var(--color-surface);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
box-shadow: var(--shadow-inset-card);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.slider-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
:deep(.ant-input), :deep(.ant-input-affix-wrapper), :deep(textarea) {
|
||||
background: #0f0f0f;
|
||||
border-color: var(--color-border);
|
||||
}
|
||||
|
||||
:deep(.ant-input:hover), :deep(.ant-input-affix-wrapper:hover), :deep(textarea:hover) {
|
||||
border-color: color-mix(in oklab, var(--color-primary) 60%, var(--color-border));
|
||||
}
|
||||
|
||||
:deep(.ant-input:focus), :deep(.ant-input-affix-wrapper-focused), :deep(textarea:focus) {
|
||||
border-color: var(--color-primary);
|
||||
box-shadow: 0 0 0 2px color-mix(in oklab, var(--color-primary) 25%, transparent);
|
||||
}
|
||||
|
||||
:deep(.ant-slider) {
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
:deep(.ant-slider-rail) {
|
||||
background-color: #252525;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
:deep(.ant-slider-track) {
|
||||
background-color: var(--color-primary);
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
:deep(.ant-slider:hover .ant-slider-track) {
|
||||
background-color: var(--color-primary);
|
||||
}
|
||||
|
||||
:deep(.ant-slider-handle::after) {
|
||||
box-shadow: 0 0 0 2px var(--color-primary);
|
||||
}
|
||||
|
||||
:deep(.ant-slider-handle:focus-visible::after),
|
||||
:deep(.ant-slider-handle:hover::after),
|
||||
:deep(.ant-slider-handle:active::after) {
|
||||
box-shadow: 0 0 0 3px var(--color-primary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
<script setup>
|
||||
import { reactive, h } from 'vue'
|
||||
import { DownloadOutlined } from '@ant-design/icons-vue'
|
||||
import { formatTime } from '../utils/benchmarkUtils'
|
||||
import ExpandedRowContent from './ExpandedRowContent.vue'
|
||||
|
||||
const props = defineProps({
|
||||
data: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
selectedRowKeys: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
expandedRowKeys: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
loading: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits([
|
||||
'update:selectedRowKeys',
|
||||
'update:expandedRowKeys',
|
||||
'analyze',
|
||||
'export',
|
||||
'batchAnalyze',
|
||||
'copy',
|
||||
'saveToServer',
|
||||
'createContent',
|
||||
])
|
||||
|
||||
const defaultColumns = [
|
||||
{ title: '封面', key: 'cover', dataIndex: 'cover', width: 120, resizable: true },
|
||||
{ title: '描述', key: 'desc', dataIndex: 'desc', width: 280, resizable: true, ellipsis: true },
|
||||
{ title: '点赞', key: 'digg_count', dataIndex: 'digg_count', width: 90, resizable: true,
|
||||
sorter: (a, b) => (a.digg_count || 0) - (b.digg_count || 0), defaultSortOrder: 'descend' },
|
||||
{ title: '评论', key: 'comment_count', dataIndex: 'comment_count', width: 90, resizable: true,
|
||||
sorter: (a, b) => (a.comment_count || 0) - (b.comment_count || 0) },
|
||||
{ title: '分享', key: 'share_count', dataIndex: 'share_count', width: 90, resizable: true,
|
||||
sorter: (a, b) => (a.share_count || 0) - (b.share_count || 0) },
|
||||
{ title: '收藏', key: 'collect_count', dataIndex: 'collect_count', width: 90, resizable: true,
|
||||
sorter: (a, b) => (a.collect_count || 0) - (b.collect_count || 0) },
|
||||
{ title: '时长(s)', key: 'duration_s', dataIndex: 'duration_s', width: 90, resizable: true,
|
||||
sorter: (a, b) => (a.duration_s || 0) - (b.duration_s || 0) },
|
||||
{ title: '置顶', key: 'is_top', dataIndex: 'is_top', width: 70, resizable: true },
|
||||
{ title: '创建时间', key: 'create_time', dataIndex: 'create_time', width: 160, resizable: true,
|
||||
sorter: (a, b) => (a.create_time || 0) - (b.create_time || 0) },
|
||||
{ title: '链接', key: 'share_url', dataIndex: 'share_url', width: 80, resizable: true,
|
||||
customRender: ({ record }) => record.share_url ? h('a', { href: record.share_url, target: '_blank' }, '打开') : null },
|
||||
{ title: '操作', key: 'action', width: 100, resizable: true, fixed: 'right' },
|
||||
]
|
||||
|
||||
const columns = reactive([...defaultColumns])
|
||||
|
||||
function onSelectChange(selectedKeys) {
|
||||
emit('update:selectedRowKeys', selectedKeys)
|
||||
}
|
||||
|
||||
function onExpandedRowKeysChange(keys) {
|
||||
emit('update:expandedRowKeys', keys)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="card results-card" v-if="data.length > 0">
|
||||
<div class="section-header">
|
||||
<div class="section-title">分析结果</div>
|
||||
<a-space align="center">
|
||||
<a-button
|
||||
size="small"
|
||||
type="default"
|
||||
@click="$emit('export')"
|
||||
:disabled="data.length === 0 || selectedRowKeys.length === 0 || selectedRowKeys.length > 10">
|
||||
<template #icon>
|
||||
<DownloadOutlined />
|
||||
</template>
|
||||
导出Excel ({{ selectedRowKeys.length }}/10)
|
||||
</a-button>
|
||||
<a-button size="small" type="primary" class="batch-btn" @click="$emit('batchAnalyze')">
|
||||
批量分析 ({{ selectedRowKeys.length }})
|
||||
</a-button>
|
||||
</a-space>
|
||||
</div>
|
||||
<a-table
|
||||
:dataSource="data"
|
||||
:columns="columns"
|
||||
:pagination="false"
|
||||
:row-selection="{ selectedRowKeys, onChange: onSelectChange, hideSelectAll: true }"
|
||||
:expandedRowKeys="expandedRowKeys"
|
||||
@expandedRowsChange="onExpandedRowKeysChange"
|
||||
:expandable="{
|
||||
expandRowByClick: false
|
||||
}"
|
||||
:rowKey="(record) => String(record.id)"
|
||||
:loading="loading"
|
||||
class="benchmark-table">
|
||||
<template #expandedRowRender="{ record }">
|
||||
<ExpandedRowContent
|
||||
:record="record"
|
||||
@analyze="(row) => $emit('analyze', row)"
|
||||
@copy="(row) => $emit('copy', row)"
|
||||
@save-to-server="(row) => $emit('saveToServer', row)"
|
||||
@create-content="(row) => $emit('createContent', row)"
|
||||
/>
|
||||
</template>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'cover'">
|
||||
<img v-if="record.cover" :src="record.cover" alt="cover" loading="lazy"
|
||||
style="width:120px;height:68px;object-fit:cover;border-radius:6px;border:1px solid #eee;" />
|
||||
<span v-else style="color:#999;font-size:12px;">无封面</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'desc'">
|
||||
<span :title="record.desc">{{ record.desc || '-' }}</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'play_count'">
|
||||
{{ record.play_count ? (record.play_count / 10000).toFixed(1) + 'w' : '0' }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'digg_count'">
|
||||
{{ record.digg_count ? record.digg_count.toLocaleString('zh-CN') : '0' }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'comment_count'">
|
||||
{{ record.comment_count ? record.comment_count.toLocaleString('zh-CN') : '0' }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'share_count'">
|
||||
{{ record.share_count ? record.share_count.toLocaleString('zh-CN') : '0' }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'collect_count'">
|
||||
{{ record.collect_count ? record.collect_count.toLocaleString('zh-CN') : '0' }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'is_top'">
|
||||
<a-tag v-if="record.is_top" color="red">置顶</a-tag>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'create_time'">
|
||||
{{ formatTime(record.create_time) }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'share_url'">
|
||||
<a v-if="record.share_url" :href="record.share_url" target="_blank" class="link-btn">打开</a>
|
||||
<span v-else>-</span>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'action'">
|
||||
<a-space>
|
||||
<a-button size="small" type="primary" :loading="record._analyzing" :disabled="record._analyzing" @click="$emit('analyze', record)">
|
||||
{{ record._analyzing ? '分析中…' : '分析' }}
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</a-table>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card {
|
||||
background: var(--color-surface);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
box-shadow: var(--shadow-inset-card);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.results-card {
|
||||
min-height: 420px;
|
||||
}
|
||||
|
||||
.section-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.section-header .ant-space {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.section-header .ant-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.batch-btn {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.batch-btn:hover {
|
||||
box-shadow: var(--glow-primary);
|
||||
filter: brightness(1.03);
|
||||
}
|
||||
|
||||
.link-btn {
|
||||
color: #1677ff;
|
||||
text-decoration: none;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.link-btn:hover {
|
||||
opacity: 0.8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.benchmark-table :deep(.ant-table-expand-icon-th),
|
||||
.benchmark-table :deep(.ant-table-row-expand-icon-cell) {
|
||||
width: 48px;
|
||||
min-width: 48px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.benchmark-table :deep(.ant-table-row-expand-icon) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<script setup>
|
||||
import { CopyOutlined, SaveOutlined } from '@ant-design/icons-vue'
|
||||
import ChatMessageRenderer from '@/components/ChatMessageRenderer.vue'
|
||||
|
||||
const props = defineProps({
|
||||
record: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['analyze', 'copy', 'saveToServer', 'createContent'])
|
||||
|
||||
function handleCopy() {
|
||||
emit('copy', props.record)
|
||||
}
|
||||
|
||||
function handleSaveToServer() {
|
||||
emit('saveToServer', props.record)
|
||||
}
|
||||
|
||||
function handleCreateContent() {
|
||||
emit('createContent', props.record)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="expanded-content">
|
||||
<!-- 未分析的行显示提示 -->
|
||||
<div v-if="!record.transcriptions && !record.prompt" class="no-analysis-tip">
|
||||
<a-empty description="该视频尚未分析">
|
||||
<template #image>
|
||||
<svg width="120" height="120" viewBox="0 0 120 120" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="20" y="30" width="80" height="60" rx="4" stroke="currentColor" stroke-width="2" fill="none" opacity="0.3"/>
|
||||
<circle cx="40" cy="50" r="8" fill="currentColor" opacity="0.4"/>
|
||||
<rect x="54" y="47" width="40" height="6" rx="3" fill="currentColor" opacity="0.4"/>
|
||||
<rect x="54" y="60" width="32" height="6" rx="3" fill="currentColor" opacity="0.4"/>
|
||||
</svg>
|
||||
</template>
|
||||
<a-button type="primary" @click="$emit('analyze', record)" :loading="record._analyzing">
|
||||
{{ record._analyzing ? '分析中…' : '开始分析' }}
|
||||
</a-button>
|
||||
</a-empty>
|
||||
</div>
|
||||
|
||||
<!-- 已分析的行显示内容 -->
|
||||
<div v-else class="two-col">
|
||||
<!-- 左侧:原配音内容 -->
|
||||
<section class="col left-col">
|
||||
<div class="sub-title">原配音</div>
|
||||
<div class="transcript-box" v-if="record.transcriptions">
|
||||
<div class="transcript-content">{{ record.transcriptions }}</div>
|
||||
</div>
|
||||
<div v-else class="no-transcript">暂无转写文本,请先点击"分析"获取</div>
|
||||
</section>
|
||||
|
||||
<!-- 右侧:提示词 -->
|
||||
<section class="col right-col">
|
||||
<div class="sub-title">提示词</div>
|
||||
|
||||
<div class="prompt-display-wrapper">
|
||||
<ChatMessageRenderer
|
||||
:content="record.prompt || ''"
|
||||
:is-streaming="record._analyzing || false"
|
||||
/>
|
||||
<div v-if="!record.prompt" class="no-prompt">暂无提示词</div>
|
||||
</div>
|
||||
|
||||
<div class="right-actions">
|
||||
<a-space>
|
||||
<a-button
|
||||
size="small"
|
||||
type="text"
|
||||
class="copy-btn"
|
||||
:title="'复制'"
|
||||
@click="handleCopy">
|
||||
<template #icon>
|
||||
<CopyOutlined />
|
||||
</template>
|
||||
</a-button>
|
||||
<a-button
|
||||
v-if="record.prompt"
|
||||
size="small"
|
||||
type="text"
|
||||
class="save-server-btn"
|
||||
:title="'保存'"
|
||||
@click="handleSaveToServer">
|
||||
<template #icon>
|
||||
<SaveOutlined />
|
||||
</template>
|
||||
保存
|
||||
</a-button>
|
||||
<a-button
|
||||
type="dashed"
|
||||
:disabled="!record.prompt || record._analyzing"
|
||||
@click="handleCreateContent">基于提示词去创作</a-button>
|
||||
</a-space>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.expanded-content {
|
||||
padding: 16px;
|
||||
background: #161616;
|
||||
border-radius: 6px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.two-col {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.col {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.left-col .transcript-content {
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.6;
|
||||
color: var(--color-text-secondary);
|
||||
background: #0d0d0d;
|
||||
border: 1px dashed var(--color-border);
|
||||
border-radius: 6px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.sub-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.no-transcript {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.prompt-display-wrapper {
|
||||
min-height: 200px;
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
background: #0d0d0d;
|
||||
border: 1px dashed var(--color-border);
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.no-prompt {
|
||||
padding: 16px;
|
||||
text-align: center;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.right-actions {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.copy-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--color-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.copy-btn:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
|
||||
.no-analysis-tip {
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.no-analysis-tip :deep(.ant-empty) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.no-analysis-tip :deep(.ant-empty-description) {
|
||||
color: var(--color-text-secondary);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { UserPromptApi } from '@/api/userPrompt'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
const props = defineProps({
|
||||
visible: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
promptContent: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:visible', 'success'])
|
||||
|
||||
const userStore = useUserStore()
|
||||
const savingPrompt = ref(false)
|
||||
const savePromptForm = ref({
|
||||
name: '',
|
||||
category: '',
|
||||
content: '',
|
||||
})
|
||||
|
||||
watch(() => props.visible, (newVal) => {
|
||||
if (newVal) {
|
||||
savePromptForm.value = {
|
||||
name: '',
|
||||
category: '',
|
||||
content: props.promptContent,
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
async function handleSave() {
|
||||
if (!savePromptForm.value.name.trim()) {
|
||||
message.warning('请输入提示词名称')
|
||||
return
|
||||
}
|
||||
|
||||
if (!savePromptForm.value.content.trim()) {
|
||||
message.warning('提示词内容不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
const userId = Number(userStore.userId)
|
||||
if (!userId) {
|
||||
message.error('无法获取用户ID,请先登录')
|
||||
return
|
||||
}
|
||||
|
||||
savingPrompt.value = true
|
||||
try {
|
||||
const payload = {
|
||||
userId: userId,
|
||||
name: savePromptForm.value.name.trim(),
|
||||
content: savePromptForm.value.content.trim(),
|
||||
category: savePromptForm.value.category.trim() || null,
|
||||
isPublic: false,
|
||||
sort: 0,
|
||||
useCount: 0,
|
||||
status: 1,
|
||||
}
|
||||
|
||||
const response = await UserPromptApi.createUserPrompt(payload)
|
||||
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
message.success('提示词保存成功')
|
||||
emit('update:visible', false)
|
||||
emit('success')
|
||||
// 重置表单
|
||||
savePromptForm.value = {
|
||||
name: '',
|
||||
category: '',
|
||||
content: '',
|
||||
}
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '保存失败')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存提示词失败:', error)
|
||||
message.error(error?.message || '保存失败,请稍后重试')
|
||||
} finally {
|
||||
savingPrompt.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handleCancel() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a-modal
|
||||
:open="visible"
|
||||
title="保存提示词"
|
||||
:width="600"
|
||||
:maskClosable="false"
|
||||
@cancel="handleCancel">
|
||||
<a-form :model="savePromptForm" layout="vertical">
|
||||
<a-form-item label="提示词名称" required>
|
||||
<a-input
|
||||
v-model:value="savePromptForm.name"
|
||||
placeholder="请输入提示词名称"
|
||||
:maxlength="50"
|
||||
show-count />
|
||||
</a-form-item>
|
||||
<a-form-item label="分类/标签">
|
||||
<a-input
|
||||
v-model:value="savePromptForm.category"
|
||||
placeholder="可选:输入分类或标签"
|
||||
:maxlength="20" />
|
||||
</a-form-item>
|
||||
<a-form-item label="提示词内容">
|
||||
<a-textarea
|
||||
v-model:value="savePromptForm.content"
|
||||
:rows="8"
|
||||
:readonly="true"
|
||||
placeholder="提示词内容" />
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
|
||||
<template #footer>
|
||||
<a-space>
|
||||
<a-button @click="handleCancel">取消</a-button>
|
||||
<a-button
|
||||
type="primary"
|
||||
:loading="savingPrompt"
|
||||
:disabled="!savePromptForm.name.trim()"
|
||||
@click="handleSave">保存</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
</a-modal>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { ref } from 'vue'
|
||||
import { message } from 'ant-design-vue'
|
||||
import { ChatMessageApi } from '@/api/chat'
|
||||
import useVoiceText from '@gold/hooks/web/useVoiceText'
|
||||
import { streamChat } from '@/utils/streamChat'
|
||||
import { buildPromptFromTranscription } from '../utils/benchmarkUtils'
|
||||
|
||||
export function useBenchmarkAnalysis(data, expandedRowKeys, saveTableDataToSession) {
|
||||
const loading = ref(false)
|
||||
const batchAnalyzeLoading = ref(false)
|
||||
const globalLoading = ref(false)
|
||||
const globalLoadingText = ref('')
|
||||
const { getVoiceText } = useVoiceText()
|
||||
|
||||
/**
|
||||
* 分析单个视频,获取提示词
|
||||
*/
|
||||
async function analyzeVideo(row) {
|
||||
try {
|
||||
if (row._analyzing) return
|
||||
|
||||
row._analyzing = true
|
||||
|
||||
// 1) 获取音频转写
|
||||
message.info('正在获取音频转写...')
|
||||
const transcriptions = await getVoiceText([row])
|
||||
row.transcriptions = transcriptions.find(item => item.audio_url === row.audio_url)?.value
|
||||
|
||||
// 2) 检查是否有语音文案
|
||||
if (!row.transcriptions || !row.transcriptions.trim()) {
|
||||
message.warning('未提取到语音内容,请检查音频文件或稍后重试')
|
||||
row._analyzing = false
|
||||
return false
|
||||
}
|
||||
|
||||
// 3) 创建对话
|
||||
message.info('正在创建对话...')
|
||||
const createPayload = { roleId: 20, role_id: 20 }
|
||||
console.debug('createChatConversationMy payload:', createPayload)
|
||||
const conversationResp = await ChatMessageApi.createChatConversationMy(createPayload)
|
||||
|
||||
let conversationId = null
|
||||
if (conversationResp?.data) {
|
||||
conversationId = typeof conversationResp.data === 'object' ? conversationResp.data.id : conversationResp.data
|
||||
}
|
||||
|
||||
if (!conversationId) {
|
||||
throw new Error('创建对话失败:未获取到 conversationId')
|
||||
}
|
||||
|
||||
// 4) 基于转写构建提示,流式生成并实时写入 UI
|
||||
message.info('正在生成提示词...')
|
||||
const content = buildPromptFromTranscription(row.transcriptions)
|
||||
const index = data.value.findIndex(item => item.id === row.id)
|
||||
const aiContent = await streamChat({
|
||||
conversationId,
|
||||
content,
|
||||
onUpdate: (fullText) => {
|
||||
if (index !== -1) data.value[index].prompt = fullText
|
||||
},
|
||||
enableTypewriter: true,
|
||||
typewriterSpeed: 10,
|
||||
typewriterBatchSize: 2
|
||||
})
|
||||
|
||||
// 5) 兜底处理
|
||||
const finalPrompt = aiContent || row.transcriptions || ''
|
||||
if (index !== -1) data.value[index].prompt = finalPrompt
|
||||
|
||||
// 6) 分析完成后自动展开该行
|
||||
const rowId = String(row.id) // 确保类型一致
|
||||
if (!expandedRowKeys.value.includes(rowId)) {
|
||||
expandedRowKeys.value.push(rowId)
|
||||
}
|
||||
|
||||
// 7) 保存数据到 session
|
||||
await saveTableDataToSession()
|
||||
|
||||
message.success('分析完成')
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('分析视频失败:', error)
|
||||
message.error('分析失败,请稍后重试')
|
||||
return false
|
||||
} finally {
|
||||
row._analyzing = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量分析选中的视频
|
||||
*/
|
||||
async function batchAnalyze(selectedRowKeys, onBatchComplete) {
|
||||
if (selectedRowKeys.value.length === 0) {
|
||||
message.warning('请先选择要分析的视频')
|
||||
return
|
||||
}
|
||||
|
||||
batchAnalyzeLoading.value = true
|
||||
globalLoading.value = true
|
||||
globalLoadingText.value = `正在批量分析 ${selectedRowKeys.value.length} 个视频...`
|
||||
|
||||
try {
|
||||
// 1. 获取所有选中视频的语音转写
|
||||
globalLoadingText.value = '正在获取中...'
|
||||
const selectedRows = data.value.filter(item => selectedRowKeys.value.includes(item.id))
|
||||
const transcriptions = await getVoiceText(selectedRows)
|
||||
|
||||
// 2. 收集所有转写内容
|
||||
const allTexts = []
|
||||
for (const id of selectedRowKeys.value) {
|
||||
const row = data.value.find(item => item.id === id)
|
||||
if (row && row.audio_url) {
|
||||
const transcription = transcriptions.find(item => item.audio_url === row.audio_url)
|
||||
if (transcription && transcription.value && transcription.value.trim()) {
|
||||
allTexts.push({ id: row.id, url: row.audio_url, text: transcription.value })
|
||||
row.transcriptions = transcription.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 检查是否有可用的语音内容
|
||||
if (allTexts.length === 0) {
|
||||
message.warning('未提取到任何语音内容,请检查音频文件或稍后重试')
|
||||
batchAnalyzeLoading.value = false
|
||||
globalLoading.value = false
|
||||
globalLoadingText.value = ''
|
||||
return
|
||||
}
|
||||
|
||||
await saveTableDataToSession()
|
||||
const mergedText = allTexts.map(item => item.text).join('\n\n---\n\n')
|
||||
|
||||
// 4. 通知父组件打开弹窗并开始生成
|
||||
if (onBatchComplete) {
|
||||
await onBatchComplete(mergedText, allTexts.length)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量分析失败:', error)
|
||||
message.error('批量分析失败,请稍后重试')
|
||||
} finally {
|
||||
batchAnalyzeLoading.value = false
|
||||
globalLoading.value = false
|
||||
globalLoadingText.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
loading,
|
||||
batchAnalyzeLoading,
|
||||
globalLoading,
|
||||
globalLoadingText,
|
||||
analyzeVideo,
|
||||
batchAnalyze,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { ref, reactive } from 'vue'
|
||||
import storage from '@/utils/storage'
|
||||
import { mapFromDouyin, mapFromXhs } from '../utils/benchmarkUtils'
|
||||
|
||||
const TABLE_DATA_STORAGE_KEY = 'benchmark_table_data'
|
||||
|
||||
export function useBenchmarkData() {
|
||||
const data = ref([])
|
||||
const selectedRowKeys = ref([])
|
||||
const expandedRowKeys = ref([])
|
||||
|
||||
/**
|
||||
* 保存表格数据到 session
|
||||
*/
|
||||
async function saveTableDataToSession() {
|
||||
try {
|
||||
// 过滤掉不需要持久化的临时字段(如 _analyzing)
|
||||
const persistData = (data.value || []).map((item) => {
|
||||
const rest = { ...(item || {}) }
|
||||
delete rest._analyzing
|
||||
return rest
|
||||
})
|
||||
await storage.setJSON(TABLE_DATA_STORAGE_KEY, persistData)
|
||||
} catch (error) {
|
||||
console.warn('保存表格数据到session失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 session 加载表格数据
|
||||
*/
|
||||
async function loadTableDataFromSession() {
|
||||
try {
|
||||
const savedData = await storage.getJSON(TABLE_DATA_STORAGE_KEY)
|
||||
if (savedData && Array.isArray(savedData) && savedData.length > 0) {
|
||||
// 强制恢复临时字段的初始状态
|
||||
data.value = savedData.map((item) => ({ ...item, _analyzing: false }))
|
||||
console.log('从session加载了表格数据:', savedData.length, '条')
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('从session加载表格数据失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 API 响应数据
|
||||
*/
|
||||
function processApiResponse(resp, platform) {
|
||||
if (platform === '抖音') {
|
||||
const awemeList = resp?.data?.aweme_list || []
|
||||
console.log('抖音返回的原始数据:', awemeList[0])
|
||||
data.value = mapFromDouyin(awemeList)
|
||||
console.log('映射后的第一条数据:', data.value[0])
|
||||
} else {
|
||||
const notes = resp?.data?.notes || resp?.data?.data || []
|
||||
data.value = mapFromXhs(notes)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空数据
|
||||
*/
|
||||
async function clearData() {
|
||||
data.value = []
|
||||
selectedRowKeys.value = []
|
||||
expandedRowKeys.value = []
|
||||
await storage.remove(TABLE_DATA_STORAGE_KEY)
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
selectedRowKeys,
|
||||
expandedRowKeys,
|
||||
saveTableDataToSession,
|
||||
loadTableDataFromSession,
|
||||
processApiResponse,
|
||||
clearData,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
/**
|
||||
* 映射抖音数据结构
|
||||
*/
|
||||
export function mapFromDouyin(awemeList) {
|
||||
return awemeList.map((item, idx) => ({
|
||||
id: item?.statistics?.aweme_id || item?.aweme_id || idx + 1,
|
||||
cover: item?.video?.origin_cover?.url_list?.[0] || item?.video?.cover?.url_list?.[0]
|
||||
|| item?.video?.dynamic_cover?.url_list?.[0] || item?.video?.animated_cover?.url_list?.[0] || '',
|
||||
is_top: item?.is_top ? 1 : 0,
|
||||
create_time: item?.create_time,
|
||||
audio_url: item?.video?.play_addr?.url_list?.reverse()[0] || '',
|
||||
desc: item?.desc || item?.caption || '',
|
||||
duration_s: Math.round((item?.video?.duration ?? 0) / 1000),
|
||||
digg_count: item?.statistics?.digg_count ?? 0,
|
||||
comment_count: item?.statistics?.comment_count ?? 0,
|
||||
share_count: item?.statistics?.share_count ?? 0,
|
||||
collect_count: item?.statistics?.collect_count ?? 0,
|
||||
play_count: item?.statistics?.play_count ?? 0,
|
||||
share_url: item?.share_info?.share_url || '',
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 映射小红书数据结构
|
||||
*/
|
||||
export function mapFromXhs(notes) {
|
||||
return notes.map((note, idx) => ({
|
||||
id: note?.note_id || note?.id || idx + 1,
|
||||
cover: note?.cover?.url || note?.image_list?.[0]?.url || '',
|
||||
is_top: 0,
|
||||
create_time: note?.time || note?.create_time,
|
||||
desc: note?.desc || note?.title || '',
|
||||
duration_s: 0,
|
||||
digg_count: note?.liked_count ?? note?.likes ?? 0,
|
||||
comment_count: note?.comment_count ?? 0,
|
||||
share_count: note?.share_count ?? 0,
|
||||
play_count: note?.view_count ?? 0,
|
||||
share_url: note?.link || '',
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间戳
|
||||
*/
|
||||
export function formatTime(ts) {
|
||||
if (!ts) return ''
|
||||
const ms = ts > 1e12 ? ts : ts * 1000
|
||||
return dayjs(ms).format('YYYY-MM-DD HH:mm:ss')
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据转写内容构建 AI 提示
|
||||
*/
|
||||
export function buildPromptFromTranscription(text) {
|
||||
if (text && text.trim()) return `${text}`
|
||||
return '没有可用的语音转写内容,请给出一份适合短视频脚本创作的通用高质量提示词模板(包含框架、角色、语气、风格、内容要点等)。'
|
||||
}
|
||||
|
||||
489
frontend/app/web-gold/src/views/system/StyleSettings.vue
Normal file
489
frontend/app/web-gold/src/views/system/StyleSettings.vue
Normal file
@@ -0,0 +1,489 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, reactive, h } from 'vue'
|
||||
import { message, Modal } from 'ant-design-vue'
|
||||
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
|
||||
import { UserPromptApi } from '@/api/userPrompt'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
const userStore = useUserStore()
|
||||
|
||||
// 表格数据
|
||||
const dataSource = ref([])
|
||||
const loading = ref(false)
|
||||
const pagination = reactive({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
showSizeChanger: true,
|
||||
showTotal: (total) => `共 ${total} 条`,
|
||||
})
|
||||
|
||||
// 搜索表单
|
||||
const searchForm = reactive({
|
||||
name: '',
|
||||
category: '',
|
||||
status: undefined,
|
||||
})
|
||||
|
||||
// 编辑弹窗
|
||||
const editModalVisible = ref(false)
|
||||
const editForm = reactive({
|
||||
id: null,
|
||||
name: '',
|
||||
content: '',
|
||||
category: '',
|
||||
status: 1,
|
||||
_originalRecord: null, // 保存原始记录,用于更新时获取必需字段
|
||||
})
|
||||
const editFormRef = ref(null)
|
||||
|
||||
// 表格列定义
|
||||
const columns = [
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
key: 'id',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 200,
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: '内容',
|
||||
dataIndex: 'content',
|
||||
key: 'content',
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => {
|
||||
if (!text) return '-'
|
||||
const preview = text.length > 100 ? text.substring(0, 100) + '...' : text
|
||||
return h('span', { title: text }, preview)
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '分类',
|
||||
dataIndex: 'category',
|
||||
key: 'category',
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
width: 100,
|
||||
customRender: ({ text }) => {
|
||||
return h('span', {
|
||||
style: {
|
||||
color: text === 1 ? '#52c41a' : '#ff4d4f',
|
||||
},
|
||||
}, text === 1 ? '启用' : '禁用')
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '使用次数',
|
||||
dataIndex: 'useCount',
|
||||
key: 'useCount',
|
||||
width: 120,
|
||||
sorter: (a, b) => (a.useCount || 0) - (b.useCount || 0),
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'createTime',
|
||||
key: 'createTime',
|
||||
width: 180,
|
||||
customRender: ({ text }) => {
|
||||
return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 150,
|
||||
fixed: 'right',
|
||||
customRender: ({ record }) => {
|
||||
return h('div', { style: { display: 'flex', gap: '8px' } }, [
|
||||
h('a-button', {
|
||||
type: 'link',
|
||||
size: 'small',
|
||||
onClick: () => handleEdit(record),
|
||||
}, [
|
||||
h(EditOutlined),
|
||||
'编辑',
|
||||
]),
|
||||
h('a-button', {
|
||||
type: 'link',
|
||||
size: 'small',
|
||||
danger: true,
|
||||
onClick: () => handleDelete(record),
|
||||
}, [
|
||||
h(DeleteOutlined),
|
||||
'删除',
|
||||
]),
|
||||
])
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
// 加载数据
|
||||
async function loadData() {
|
||||
loading.value = true
|
||||
try {
|
||||
const params = {
|
||||
pageNo: pagination.current,
|
||||
pageSize: pagination.pageSize,
|
||||
name: searchForm.name || undefined,
|
||||
category: searchForm.category || undefined,
|
||||
status: searchForm.status,
|
||||
}
|
||||
|
||||
const response = await UserPromptApi.getUserPromptPage(params)
|
||||
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
dataSource.value = response.data?.list || []
|
||||
pagination.total = response.data?.total || 0
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '加载失败')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载提示词列表失败:', error)
|
||||
message.error(error?.message || '加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索
|
||||
function handleSearch() {
|
||||
pagination.current = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// 重置搜索
|
||||
function handleReset() {
|
||||
searchForm.name = ''
|
||||
searchForm.category = ''
|
||||
searchForm.status = undefined
|
||||
pagination.current = 1
|
||||
loadData()
|
||||
}
|
||||
|
||||
// 新增
|
||||
function handleAdd() {
|
||||
editForm.id = null
|
||||
editForm.name = ''
|
||||
editForm.content = ''
|
||||
editForm.category = ''
|
||||
editForm.status = 1
|
||||
editForm._originalRecord = null
|
||||
editModalVisible.value = true
|
||||
}
|
||||
|
||||
// 编辑
|
||||
function handleEdit(record) {
|
||||
editForm.id = record.id
|
||||
editForm.name = record.name || ''
|
||||
editForm.content = record.content || ''
|
||||
editForm.category = record.category || ''
|
||||
editForm.status = record.status ?? 1
|
||||
// 保存原始记录的完整信息,用于更新时传递必需字段
|
||||
editForm._originalRecord = record
|
||||
editModalVisible.value = true
|
||||
}
|
||||
|
||||
// 保存(新增/编辑)
|
||||
async function handleSave() {
|
||||
try {
|
||||
await editFormRef.value.validate()
|
||||
} catch (error) {
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const payload = {
|
||||
name: editForm.name.trim(),
|
||||
content: editForm.content.trim(),
|
||||
category: editForm.category.trim() || null,
|
||||
status: editForm.status,
|
||||
}
|
||||
|
||||
if (editForm.id) {
|
||||
// 更新:只需要传递要修改的字段,后端会自动填充其他字段
|
||||
payload.id = editForm.id
|
||||
// 注意:sort、useCount、isPublic 等字段后端会自动从数据库获取,无需前端传递
|
||||
|
||||
const response = await UserPromptApi.updateUserPrompt(payload)
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
message.success('更新成功')
|
||||
editModalVisible.value = false
|
||||
loadData()
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '更新失败')
|
||||
}
|
||||
} else {
|
||||
// 新增:需要包含所有必需字段
|
||||
payload.sort = 0
|
||||
payload.useCount = 0
|
||||
payload.isPublic = false
|
||||
|
||||
const response = await UserPromptApi.createUserPrompt(payload)
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
message.success('创建成功')
|
||||
editModalVisible.value = false
|
||||
loadData()
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '创建失败')
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存提示词失败:', error)
|
||||
message.error(error?.message || '保存失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 删除
|
||||
function handleDelete(record) {
|
||||
Modal.confirm({
|
||||
title: '确认删除',
|
||||
content: `确定要删除提示词"${record.name}"吗?`,
|
||||
onOk: async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await UserPromptApi.deleteUserPrompt(record.id)
|
||||
if (response && (response.code === 0 || response.code === 200)) {
|
||||
message.success('删除成功')
|
||||
loadData()
|
||||
} else {
|
||||
throw new Error(response?.msg || response?.message || '删除失败')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除提示词失败:', error)
|
||||
message.error(error?.message || '删除失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 分页变化
|
||||
function handleTableChange(pag) {
|
||||
pagination.current = pag.current
|
||||
pagination.pageSize = pag.pageSize
|
||||
loadData()
|
||||
}
|
||||
|
||||
// 初始化
|
||||
onMounted(() => {
|
||||
loadData()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="style-settings-page">
|
||||
<div class="page-header">
|
||||
<h1 class="page-title">风格设置</h1>
|
||||
<p class="page-description">管理您的提示词模板,用于内容创作和风格定制</p>
|
||||
</div>
|
||||
|
||||
<div class="page-content">
|
||||
<!-- 搜索表单 -->
|
||||
<div class="search-card card">
|
||||
<a-form :model="searchForm" layout="inline" class="search-form">
|
||||
<a-form-item label="名称">
|
||||
<a-input
|
||||
v-model:value="searchForm.name"
|
||||
placeholder="请输入提示词名称"
|
||||
allow-clear
|
||||
style="width: 200px"
|
||||
@pressEnter="handleSearch"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="分类">
|
||||
<a-input
|
||||
v-model:value="searchForm.category"
|
||||
placeholder="请输入分类"
|
||||
allow-clear
|
||||
style="width: 200px"
|
||||
@pressEnter="handleSearch"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="状态">
|
||||
<a-select
|
||||
v-model:value="searchForm.status"
|
||||
placeholder="请选择状态"
|
||||
allow-clear
|
||||
style="width: 120px"
|
||||
>
|
||||
<a-select-option :value="1">启用</a-select-option>
|
||||
<a-select-option :value="0">禁用</a-select-option>
|
||||
</a-select>
|
||||
</a-form-item>
|
||||
<a-form-item>
|
||||
<a-space>
|
||||
<a-button type="primary" @click="handleSearch">搜索</a-button>
|
||||
<a-button @click="handleReset">重置</a-button>
|
||||
</a-space>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</div>
|
||||
|
||||
<!-- 操作栏 -->
|
||||
<div class="action-bar">
|
||||
<a-button type="primary" @click="handleAdd">
|
||||
<template #icon>
|
||||
<PlusOutlined />
|
||||
</template>
|
||||
新增提示词
|
||||
</a-button>
|
||||
</div>
|
||||
|
||||
<!-- 表格 -->
|
||||
<div class="table-card card">
|
||||
<a-table
|
||||
:dataSource="dataSource"
|
||||
:columns="columns"
|
||||
:loading="loading"
|
||||
:pagination="pagination"
|
||||
rowKey="id"
|
||||
@change="handleTableChange"
|
||||
:scroll="{ x: 1200 }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 编辑弹窗 -->
|
||||
<a-modal
|
||||
v-model:visible="editModalVisible"
|
||||
:title="editForm.id ? '编辑提示词' : '新增提示词'"
|
||||
width="800px"
|
||||
@ok="handleSave"
|
||||
@cancel="editModalVisible = false"
|
||||
>
|
||||
<a-form
|
||||
ref="editFormRef"
|
||||
:model="editForm"
|
||||
:label-col="{ span: 4 }"
|
||||
:wrapper-col="{ span: 20 }"
|
||||
>
|
||||
<a-form-item
|
||||
label="名称"
|
||||
name="name"
|
||||
:rules="[{ required: true, message: '请输入提示词名称' }]"
|
||||
>
|
||||
<a-input v-model:value="editForm.name" placeholder="请输入提示词名称" />
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
label="内容"
|
||||
name="content"
|
||||
:rules="[{ required: true, message: '请输入提示词内容' }]"
|
||||
>
|
||||
<a-textarea
|
||||
v-model:value="editForm.content"
|
||||
placeholder="请输入提示词内容"
|
||||
:rows="8"
|
||||
/>
|
||||
</a-form-item>
|
||||
<a-form-item label="分类" name="category">
|
||||
<a-input v-model:value="editForm.category" placeholder="请输入分类(可选)" />
|
||||
</a-form-item>
|
||||
<a-form-item
|
||||
label="状态"
|
||||
name="status"
|
||||
:rules="[{ required: true, message: '请选择状态' }]"
|
||||
>
|
||||
<a-radio-group v-model:value="editForm.status">
|
||||
<a-radio :value="1">启用</a-radio>
|
||||
<a-radio :value="0">禁用</a-radio>
|
||||
</a-radio-group>
|
||||
</a-form-item>
|
||||
</a-form>
|
||||
</a-modal>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.style-settings-page {
|
||||
padding: 24px;
|
||||
min-height: calc(100vh - 70px);
|
||||
background: var(--color-bg);
|
||||
}
|
||||
|
||||
.page-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
margin: 0 0 8px 0;
|
||||
}
|
||||
|
||||
.page-description {
|
||||
font-size: 14px;
|
||||
color: var(--color-text-secondary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-card);
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.search-card {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.search-form {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.action-bar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.table-card {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:deep(.ant-table) {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
:deep(.ant-table-thead > tr > th) {
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
:deep(.ant-table-tbody > tr > td) {
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
:deep(.ant-table-tbody > tr:hover > td) {
|
||||
background: var(--color-bg);
|
||||
}
|
||||
|
||||
:deep(.ant-pagination) {
|
||||
margin: 16px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -30,10 +30,12 @@ export const API_BASE = {
|
||||
APP: `${BASE_URL}`,
|
||||
// 具体模块路径
|
||||
ADMIN_AI: `${BASE_URL}/admin-api/ai`,
|
||||
APP_AI: `${BASE_URL}/app-api/ai`,
|
||||
APP_MEMBER: `${BASE_URL}/app-api/member`,
|
||||
|
||||
// 特殊路径
|
||||
TIKHUB_APP: `${BASE_URL}/api/tikHup`,
|
||||
AI_APP: `${BASE_URL}/api/ai`,
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -107,34 +107,13 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
语音文本转换 Hook,将音频文件转换为文本转录。
|
||||
|
||||
#### 初始化(在应用启动时)
|
||||
|
||||
```javascript
|
||||
// 在应用的 API 服务文件中(如 common.js)
|
||||
import { createApiService } from '@gold/config/api/services'
|
||||
import { setApiService } from '@gold/hooks/web/useVoiceText'
|
||||
import http from '@/api/http'
|
||||
import { getAuthHeader } from '@/utils/token-manager'
|
||||
import { API_BASE } from '@gold/config/api'
|
||||
|
||||
// 创建 API 服务实例
|
||||
const apiService = createApiService({
|
||||
http,
|
||||
getAuthHeader,
|
||||
baseUrl: API_BASE.TIKHUB_APP,
|
||||
})
|
||||
|
||||
// 设置全局 API 服务(供 useVoiceText hook 使用)
|
||||
setApiService(apiService)
|
||||
```
|
||||
|
||||
#### 使用方式
|
||||
|
||||
```javascript
|
||||
import useVoiceText from '@gold/hooks/web/useVoiceText'
|
||||
import type { AudioItem } from '@gold/config/types'
|
||||
|
||||
// 在组件中使用
|
||||
// 在组件中使用(无需任何初始化)
|
||||
const { getVoiceText } = useVoiceText()
|
||||
|
||||
const audioList: AudioItem[] = [
|
||||
@@ -145,6 +124,11 @@ const transcriptions = await getVoiceText(audioList)
|
||||
// transcriptions: [{ key: 'url', value: 'transcribed text', audio_url: '...' }]
|
||||
```
|
||||
|
||||
#### 说明
|
||||
|
||||
`useVoiceText` Hook 直接使用 mono 级别的 `TikHubService`,无需任何初始化或配置。
|
||||
所有 API 服务都在 `@gold/api/services` 中统一管理,开箱即用。
|
||||
|
||||
#### 类型定义
|
||||
|
||||
```typescript
|
||||
@@ -159,7 +143,8 @@ import type {
|
||||
- `vue`: Vue 3 Composition API
|
||||
- `axios`: HTTP 请求库(用于 useUserInfo)
|
||||
- `@gold/config/api`: 公共 API 配置
|
||||
- `@gold/config/api/services`: 公共 API 服务创建器
|
||||
- `@gold/api/services`: Mono 级别的 API 服务
|
||||
- `@gold/api/axios/client`: Mono 级别的 Axios 客户端
|
||||
- `@gold/config/types`: 公共类型定义
|
||||
|
||||
## 🔧 配置要求
|
||||
|
||||
@@ -106,8 +106,6 @@ export function useUserInfo(options = {}) {
|
||||
// code 为 0 或 200 表示成功
|
||||
if (response.data.code === 0 || response.data.code === 200) {
|
||||
data = response.data.data || response.data
|
||||
} else {
|
||||
throw new Error(response.data.msg || response.data.message || '获取用户信息失败')
|
||||
}
|
||||
} else {
|
||||
// 没有 code 字段,直接使用 data
|
||||
@@ -118,8 +116,6 @@ export function useUserInfo(options = {}) {
|
||||
if (data) {
|
||||
userInfo.value = data
|
||||
return data
|
||||
} else {
|
||||
throw new Error('获取用户信息失败:响应数据为空')
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = err
|
||||
|
||||
@@ -6,28 +6,12 @@ import type {
|
||||
TranscriptionData
|
||||
} from '@gold/config/types'
|
||||
|
||||
/**
|
||||
* API 服务接口(需要从应用层注入)
|
||||
*/
|
||||
interface ApiService {
|
||||
videoToCharacters: (data: { fileLinkList: string[] }) => Promise<{ data: string }>
|
||||
}
|
||||
|
||||
// 全局 API 服务实例(由应用层设置)
|
||||
let apiServiceInstance: ApiService | null = null
|
||||
|
||||
/**
|
||||
* 设置 API 服务实例
|
||||
* @param service - API 服务对象
|
||||
*/
|
||||
export function setApiService(service: ApiService) {
|
||||
apiServiceInstance = service
|
||||
}
|
||||
// 直接导入 TikHub 服务,无需全局注入
|
||||
import { TikHubService } from '@gold/api/services'
|
||||
|
||||
/**
|
||||
* 将音频列表转换为文本转录
|
||||
* @param list - 音频项列表
|
||||
* @param apiService - API 服务实例(可选,如果已通过 setApiService 设置则不需要)
|
||||
* @returns 转录结果数组
|
||||
* @throws 当转录过程出错时抛出错误
|
||||
*
|
||||
@@ -37,18 +21,10 @@ export function setApiService(service: ApiService) {
|
||||
* console.log(transcriptions) // [{ key: 'url', value: 'transcribed text' }]
|
||||
*/
|
||||
export async function getVoiceText(
|
||||
list: AudioItem[],
|
||||
apiService?: ApiService
|
||||
list: AudioItem[]
|
||||
): Promise<TranscriptionResult[]> {
|
||||
// 使用传入的 apiService 或全局实例
|
||||
const service = apiService || apiServiceInstance
|
||||
|
||||
if (!service) {
|
||||
throw new Error('getVoiceText: 需要提供 API 服务实例。请使用 setApiService() 设置或传入 apiService 参数')
|
||||
}
|
||||
|
||||
// 调用API将视频转换为文本
|
||||
const ret = await service.videoToCharacters({
|
||||
// 直接使用 TikHub 服务
|
||||
const ret = await TikHubService.videoToCharacters({
|
||||
fileLinkList: list.map(item => item.audio_url),
|
||||
})
|
||||
|
||||
@@ -85,28 +61,20 @@ export async function getVoiceText(
|
||||
* Hook 返回值接口
|
||||
*/
|
||||
interface UseVoiceTextReturn {
|
||||
getVoiceText: (list: AudioItem[], apiService?: ApiService) => Promise<TranscriptionResult[]>
|
||||
getVoiceText: (list: AudioItem[]) => Promise<TranscriptionResult[]>
|
||||
}
|
||||
|
||||
/**
|
||||
* 语音文本转换 Hook
|
||||
* @param apiService - API 服务实例(可选,如果已通过 setApiService 设置则不需要)
|
||||
* @returns 包含 getVoiceText 方法的对象
|
||||
*
|
||||
* @example
|
||||
* // 方式一:使用全局设置的 API 服务
|
||||
* setApiService(myApiService)
|
||||
* const { getVoiceText } = useVoiceText()
|
||||
* const result = await getVoiceText(audioList)
|
||||
*
|
||||
* @example
|
||||
* // 方式二:传入 API 服务实例
|
||||
* const { getVoiceText } = useVoiceText()
|
||||
* const result = await getVoiceText(audioList, myApiService)
|
||||
*/
|
||||
export default function useVoiceText(apiService?: ApiService): UseVoiceTextReturn {
|
||||
export default function useVoiceText(): UseVoiceTextReturn {
|
||||
return {
|
||||
getVoiceText: (list: AudioItem[]) => getVoiceText(list, apiService)
|
||||
getVoiceText
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
# Token 存储位置说明
|
||||
|
||||
## 📍 Token 存储位置总览
|
||||
|
||||
Token 在项目中有 **3 个存储位置**,按读取优先级排序:
|
||||
|
||||
### 1. **Dev Token(开发手动输入的 token)**
|
||||
- **存储位置**:`sessionStorage`
|
||||
- **键名**:`DEV_MANUAL_TOKEN`
|
||||
- **设置方式**:`setDevToken(token)`
|
||||
- **特点**:
|
||||
- 优先级最高(读取时优先使用)
|
||||
- 关闭浏览器标签页后自动清除
|
||||
- 用于开发测试
|
||||
|
||||
**浏览器查看方式:**
|
||||
```javascript
|
||||
// 在浏览器控制台执行
|
||||
sessionStorage.getItem('DEV_MANUAL_TOKEN')
|
||||
```
|
||||
|
||||
### 2. **正式登录的 Token(主要存储)**
|
||||
- **存储位置**:`localStorage`(通过 WebStorageCache 封装)
|
||||
- **键名**:
|
||||
- `ACCESS_TOKEN` 或 `access_token`(访问令牌)
|
||||
- `REFRESH_TOKEN` 或 `refresh_token`(刷新令牌)
|
||||
- **设置方式**:`setToken({ accessToken, refreshToken })`
|
||||
- **特点**:
|
||||
- 持久化存储(关闭浏览器后仍然存在)
|
||||
- 使用 `WebStorageCache` 库管理
|
||||
- 支持大小写不同的键名变体(兼容性)
|
||||
|
||||
**浏览器查看方式:**
|
||||
```javascript
|
||||
// 在浏览器控制台执行
|
||||
localStorage.getItem('ACCESS_TOKEN')
|
||||
localStorage.getItem('REFRESH_TOKEN')
|
||||
// 或者
|
||||
localStorage.getItem('access_token')
|
||||
localStorage.getItem('refresh_token')
|
||||
```
|
||||
|
||||
**实际存储结构:**
|
||||
```
|
||||
localStorage:
|
||||
├── ACCESS_TOKEN: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
└── REFRESH_TOKEN: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
```
|
||||
|
||||
### 3. **环境变量 Token(兜底)**
|
||||
- **存储位置**:代码中(不存储在浏览器)
|
||||
- **变量名**:`VITE_DEV_TOKEN`
|
||||
- **设置方式**:`.env` 文件或环境变量
|
||||
- **特点**:
|
||||
- 只在代码中读取,不写入浏览器存储
|
||||
- 优先级最低(前两者都没有时才使用)
|
||||
- 用于开发环境默认配置
|
||||
|
||||
## 🔄 Token 读取优先级
|
||||
|
||||
当调用 `getToken()` 时,按以下顺序查找:
|
||||
|
||||
```
|
||||
1. sessionStorage['DEV_MANUAL_TOKEN'] ← 最高优先级
|
||||
↓ (如果没有)
|
||||
2. localStorage['ACCESS_TOKEN'] 或 localStorage['access_token']
|
||||
↓ (如果没有)
|
||||
3. import.meta.env.VITE_DEV_TOKEN ← 最低优先级
|
||||
```
|
||||
|
||||
## 📝 代码示例
|
||||
|
||||
### 设置 Token
|
||||
|
||||
```javascript
|
||||
import { setToken, setDevToken } from '@gold/utils/token-manager'
|
||||
|
||||
// 设置正式登录的 token(存储到 localStorage)
|
||||
setToken({
|
||||
accessToken: 'xxx',
|
||||
refreshToken: 'yyy'
|
||||
})
|
||||
|
||||
// 设置开发 token(存储到 sessionStorage)
|
||||
setDevToken('dev-token-123')
|
||||
```
|
||||
|
||||
### 读取 Token
|
||||
|
||||
```javascript
|
||||
import { getToken } from '@gold/utils/token-manager'
|
||||
|
||||
// 自动按优先级读取
|
||||
const token = getToken()
|
||||
```
|
||||
|
||||
### 清除 Token
|
||||
|
||||
```javascript
|
||||
import { clearAllTokens } from '@gold/utils/token-manager'
|
||||
|
||||
// 清除所有位置的 token
|
||||
clearAllTokens()
|
||||
// 会清除:
|
||||
// 1. sessionStorage['DEV_MANUAL_TOKEN']
|
||||
// 2. localStorage['ACCESS_TOKEN'] 和 'access_token'
|
||||
// 3. localStorage['REFRESH_TOKEN'] 和 'refresh_token'
|
||||
```
|
||||
|
||||
## 🔍 在浏览器中查看
|
||||
|
||||
### Chrome DevTools
|
||||
|
||||
1. **打开 DevTools** (F12)
|
||||
2. **Application 标签页**
|
||||
3. **Storage 部分**:
|
||||
- **Local Storage** → 查看 `ACCESS_TOKEN`、`REFRESH_TOKEN`
|
||||
- **Session Storage** → 查看 `DEV_MANUAL_TOKEN`
|
||||
|
||||
### 控制台命令
|
||||
|
||||
```javascript
|
||||
// 查看所有 token
|
||||
console.log('Dev Token:', sessionStorage.getItem('DEV_MANUAL_TOKEN'))
|
||||
console.log('Access Token:', localStorage.getItem('ACCESS_TOKEN'))
|
||||
console.log('Refresh Token:', localStorage.getItem('REFRESH_TOKEN'))
|
||||
|
||||
// 查看所有 localStorage
|
||||
console.table(localStorage)
|
||||
|
||||
// 查看所有 sessionStorage
|
||||
console.table(sessionStorage)
|
||||
```
|
||||
|
||||
## ⚠️ 注意事项
|
||||
|
||||
1. **WebStorageCache 封装**:
|
||||
- `useCache()` 默认使用 `localStorage`
|
||||
- 通过 `WebStorageCache` 库管理,支持过期时间等功能
|
||||
- 实际存储位置仍然是 `localStorage`
|
||||
|
||||
2. **键名大小写**:
|
||||
- 代码中统一使用 `ACCESS_TOKEN` 和 `REFRESH_TOKEN`(大写)
|
||||
- 但为了兼容,也支持 `access_token` 和 `refresh_token`(小写)
|
||||
- 读取时会尝试所有变体
|
||||
|
||||
3. **清除逻辑**:
|
||||
- `clearAllTokens()` 会清除所有位置的 token
|
||||
- 包括 sessionStorage、localStorage 的所有变体键名
|
||||
- 确保完全清除,避免残留
|
||||
|
||||
## 📊 存储位置总结表
|
||||
|
||||
| Token 类型 | 存储位置 | 键名 | 持久化 | 优先级 |
|
||||
|-----------|---------|------|--------|--------|
|
||||
| Dev Token | sessionStorage | `DEV_MANUAL_TOKEN` | ❌ 关闭标签页清除 | 1 (最高) |
|
||||
| Access Token | localStorage | `ACCESS_TOKEN` / `access_token` | ✅ 持久化 | 2 |
|
||||
| Refresh Token | localStorage | `REFRESH_TOKEN` / `refresh_token` | ✅ 持久化 | 2 |
|
||||
| Env Token | 代码中 | `VITE_DEV_TOKEN` | N/A | 3 (最低) |
|
||||
|
||||
Reference in New Issue
Block a user