返回 AiToEarn
asset.ts
根目录 / project / aitoearn-web / src / utils / agent / asset.ts
1 /**
2 * Agent 素材工具函数
3 * 提供 Agent 素材的类型判断和数据转换功能
4 */
5
6 import type { MediaItem } from '@/api/materials/material.types'
7 import type { AssetType, AssetVo } from '@/types/agent-asset'
8 import { VIDEO_ASSET_TYPES } from '@/types/agent-asset'
9
10 /**
11 * 判断是否为视频类型的 Asset
12 * @param type - Asset 类型
13 * @returns 是否为视频类型
14 */
15 function isVideoAssetType(type: AssetType): boolean {
16 return VIDEO_ASSET_TYPES.includes(type)
17 }
18
19 /**
20 * 将 AssetVo 转换为 MediaItem 格式
21 * 用于在素材选择器等组件中统一使用 MediaItem 类型
22 * @param asset - Agent 素材
23 * @returns MediaItem 格式的数据
24 */
25 export function convertAssetToMediaItem(asset: AssetVo): MediaItem {
26 const isVideo = isVideoAssetType(asset.type)
27
28 return {
29 _id: asset.id,
30 userId: asset.userId || '',
31 userType: 'user',
32 groupId: 'agent-assets', // 虚拟分组 ID
33 type: isVideo ? 'video' : 'img',
34 url: asset.url,
35 // 缩略图:视频使用 cover(无封面则为空字符串),图片使用原图
36 thumbUrl: isVideo ? asset.metadata?.cover || '' : asset.url,
37 title: asset.filename || '',
38 desc: '',
39 useCount: 0,
40 metadata: {
41 size: 0,
42 mimeType: asset.mimeType || '',
43 },
44 createdAt: asset.createdAt,
45 updatedAt: asset.updatedAt || asset.createdAt,
46 }
47 }
48
49 /**
50 * 媒体类型
51 */
52 export type MediaType = 'video' | 'img'
53
54 /**
55 * 根据媒体类型过滤 Asset 列表
56 * @param assets - Agent 素材列表
57 * @param mediaTypes - 媒体类型,可以是单个类型或类型数组
58 * @returns 过滤后的素材列表
59 */
60 export function filterAssetsByMediaType(
61 assets: AssetVo[],
62 mediaTypes: MediaType | MediaType[],
63 ): AssetVo[] {
64 const types = Array.isArray(mediaTypes) ? mediaTypes : [mediaTypes]
65
66 return assets.filter((asset) => {
67 // 判断 asset 是视频还是图片
68 const isVideo = isVideoAssetType(asset.type)
69 const assetMediaType: MediaType = isVideo ? 'video' : 'img'
70
71 return types.includes(assetMediaType)
72 })
73 }
74
75 /**
76 * 获取素材的缩略图 URL
77 * @param asset - Agent 素材
78 * @returns 缩略图 URL,视频无封面时返回空字符串
79 */
80 export function getAssetThumbUrl(asset: AssetVo): string {
81 if (isVideoAssetType(asset.type)) {
82 return asset.metadata?.cover || '' // 视频无封面时返回空字符串,由调用方处理占位图
83 }
84 return asset.url
85 }
86
87 /**
88 * 获取素材的媒体类型
89 * @param asset - Agent 素材
90 * @returns 媒体类型 'video' | 'img'
91 */
92 export function getAssetMediaType(asset: AssetVo): MediaType {
93 return isVideoAssetType(asset.type) ? 'video' : 'img'
94 }
95
95 lines TYPESCRIPT