Skip to content

Let's use AI to Earn!

feat: Initial integration of browser plugins (#350)

Gao4b92741f9651
diff --git a/project/web/@types/resources.d.ts b/project/web/@types/resources.d.ts
index 1fd0c0f2..51963344 100644
--- a/project/web/@types/resources.d.ts
+++ b/project/web/@types/resources.d.ts
@@ -30,7 +30,17 @@ interface Resources {
"subtitle": "选择平台添加账号",
"currentSpace": "当前空间",
"pleaseChooseSpaceFirst": "请先选择空间",
- "addTo": "添加到:"
+ "addTo": "添加到:",
+ "pluginNotReady": "浏览器插件未就绪,请先安装并授权插件",
+ "platformNotLoggedIn": "{{platform}} 未登录,请先在插件中登录",
+ "syncSuccess": "账号同步成功",
+ "syncFailed": "账号同步失败"
+ },
+ "noAccountWarning": {
+ "title": "提示",
+ "content": "您还没有添加任何频道账户,建议先添加频道后再创建作品以便发布。",
+ "addAccount": "添加频道",
+ "continuePublish": "继续发布"
},
"facebookPages": {
"title": "选择Facebook页面",
@@ -214,6 +224,25 @@ interface Resources {
"selectAccountsButton": "选择账户",
"create": "创建",
"cancel": "取消"
+ },
+ "keyDetail": {
+ "title": "MCP Key 详情",
+ "keyName": "Key名称:",
+ "keyValue": "Key值:",
+ "createdTime": "创建时间:",
+ "associatedAccounts": "关联账户:",
+ "accountsCount": "{{count}} 个",
+ "associatedAccountsList": "关联账户列表",
+ "noAccounts": "暂无关联账户",
+ "fetchAccountsFailed": "获取关联账户列表失败",
+ "unlinkSuccess": "解除关联成功",
+ "unlinkFailed": "解除关联失败",
+ "unlinkConfirm": "确定要解除关联吗?",
+ "unlinkButton": "解除关联",
+ "copyKey": "复制Key",
+ "ok": "确定",
+ "cancel": "取消",
+ "paginationText": "第 {{start}}-{{end}} 条,共 {{total}} 条"
}
},
"mediaTypes": {
@@ -601,40 +630,6 @@ interface Resources {
}
}
},
- "dataStatistics": {
- "title": "数据统计",
- "description": "在这里查看和分析您的数据统计信息。",
- "accountData": "账号数据",
- "selectSpace": "选择空间",
- "inputAccountName": "请输入账号名称",
- "noAccount": "暂无账号",
- "totalAccount": "累计账号数",
- "online": "在线",
- "offline": "离线",
- "fansCount": "粉丝数",
- "growthFansCount": "涨粉数",
- "loginFailed": "登陆失败",
- "relogin": "重新登录",
- "dataDetails": "数据明细",
- "timeRange": "时间范围:",
- "yesterdayIncrease": "昨日新增",
- "readCount": "播放数",
- "commentCount": "评论数",
- "likeCount": "点赞数",
- "collectCount": "收藏数",
- "forwardCount": "分享数",
- "congratulations": "恭喜你!",
- "achieveMilestone": "达成数据里程碑",
- "newHigh": "新高",
- "tenThousand": "万",
- "savePoster": "保存海报",
- "appName": "爱团团AiToEarn",
- "keepGoing": "继续加油,再创佳绩!",
- "viewMilestone": "查看里程碑",
- "milestone": "里程碑",
- "milestoneProgress": "里程碑进度",
- "recentWeek": "最近一周"
- },
"dataMonitoring": {
"title": "笔记传播监测",
"description": "按分钟级频率监测笔记的点赞、收藏、评论、转发等传播数据,有效验证笔记传播效果",
@@ -657,14 +652,14 @@ interface Resources {
"addSuccess": "添加成功",
"addFailed": "添加失败"
},
- "list": {
- "empty": "暂无监测数据,点击上方按钮添加笔记链接",
- "untitled": "未命名笔记",
- "createdAt": "创建时间",
- "updatedAt": "更新时间",
- "error": "错误",
- "totalRecords": "共 {{count}} 条记录"
- },
+ "list": {
+ "empty": "暂无监测数据,点击上方按钮添加笔记链接",
+ "untitled": "未命名笔记",
+ "createdAt": "创建时间",
+ "updatedAt": "更新时间",
+ "error": "错误",
+ "totalRecords": "共 {{count}} 条记录"
+ },
"stats": {
"views": "阅读数",
"likes": "点赞数",
@@ -672,75 +667,75 @@ interface Resources {
"favorites": "收藏数",
"shares": "分享数"
},
- "status": {
- "pending": "等待中",
- "processing": "处理中",
- "completed": "已完成",
- "success": "成功",
- "failed": "失败",
- "enabled": "已启用",
- "disabled": "已禁用"
- },
- "detail": {
- "back": "返回",
- "backToList": "返回列表",
- "notFound": "未找到监测数据",
- "pause": "暂停监测",
- "resume": "恢复监测",
- "paused": "已暂停",
- "resumed": "已恢复",
- "export": "导出数据",
- "exportSuccess": "导出成功",
- "viewNote": "查看笔记",
- "pageTitle": "笔记监测详情",
- "startTime": "开始时间",
- "updateTime": "更新时间",
- "noteCover": "笔记封面",
- "viewOriginal": "查看原文",
- "dailyIncrement": "每日数据增量",
- "noData": "暂无数据",
- "taskId": "任务编号",
- "createdTime": "任务提交时间",
- "publishTime": "发布时间",
- "firstMonitoring": "首次监测时间",
- "monitoringDuration": "监测时长",
- "duration": "{{count}}天",
- "monitoringFrequency": "监测频率",
- "minutesPerTime": "分钟/次",
- "lastMonitoring": "最近一次监测",
- "completionRate": "监测完成度",
- "monitoringComplete": "监测已完成",
- "dataDetail": "数据详情",
- "downloadRecord": "下载记录",
- "exportResult": "导出结果",
- "postInfo": "笔记信息",
- "mediaPreview": "媒体预览",
- "dataHistory": "数据历史",
- "noHistory": "暂无历史数据",
- "status": {
- "active": "监测中",
- "paused": "已暂停"
- },
- "tabs": {
- "chart": "累计视图",
- "table": "增量视图"
- },
- "table": {
- "time": "时间",
- "date": "日期",
- "likeIncrement": "点赞增量",
- "favoriteIncrement": "收藏增量",
- "commentIncrement": "评论增量",
- "totalLikes": "即时点赞",
- "newLikes": "新增点赞",
- "totalComments": "即时评论",
- "newComments": "新增评论",
- "totalFavorites": "即时收藏",
- "newFavorites": "新增收藏",
- "total": "共 {{count}} 条",
- "totalDays": "共 {{count}} 天"
- }
- },
+ "status": {
+ "pending": "等待中",
+ "processing": "处理中",
+ "completed": "已完成",
+ "success": "成功",
+ "failed": "失败",
+ "enabled": "已启用",
+ "disabled": "已禁用"
+ },
+ "detail": {
+ "back": "返回",
+ "backToList": "返回列表",
+ "notFound": "未找到监测数据",
+ "pause": "暂停监测",
+ "resume": "恢复监测",
+ "paused": "已暂停",
+ "resumed": "已恢复",
+ "export": "导出数据",
+ "exportSuccess": "导出成功",
+ "viewNote": "查看笔记",
+ "pageTitle": "笔记监测详情",
+ "startTime": "开始时间",
+ "updateTime": "更新时间",
+ "noteCover": "笔记封面",
+ "viewOriginal": "查看原文",
+ "dailyIncrement": "每日数据增量",
+ "noData": "暂无数据",
+ "taskId": "任务编号",
+ "createdTime": "任务提交时间",
+ "publishTime": "发布时间",
+ "firstMonitoring": "首次监测时间",
+ "monitoringDuration": "监测时长",
+ "duration": "{{count}}天",
+ "monitoringFrequency": "监测频率",
+ "minutesPerTime": "分钟/次",
+ "lastMonitoring": "最近一次监测",
+ "completionRate": "监测完成度",
+ "monitoringComplete": "监测已完成",
+ "dataDetail": "数据详情",
+ "downloadRecord": "下载记录",
+ "exportResult": "导出结果",
+ "postInfo": "笔记信息",
+ "mediaPreview": "媒体预览",
+ "dataHistory": "数据历史",
+ "noHistory": "暂无历史数据",
+ "status": {
+ "active": "监测中",
+ "paused": "已暂停"
+ },
+ "tabs": {
+ "chart": "累计视图",
+ "table": "增量视图"
+ },
+ "table": {
+ "time": "时间",
+ "date": "日期",
+ "likeIncrement": "点赞增量",
+ "favoriteIncrement": "收藏增量",
+ "commentIncrement": "评论增量",
+ "totalLikes": "即时点赞",
+ "newLikes": "新增点赞",
+ "totalComments": "即时评论",
+ "newComments": "新增评论",
+ "totalFavorites": "即时收藏",
+ "newFavorites": "新增收藏",
+ "total": "共 {{count}} 条",
+ "totalDays": "共 {{count}} 天"
+ }
+ },
"error": {
"loadFailed": "加载失败",
"addFailed": "添加失败",
@@ -749,6 +744,40 @@ interface Resources {
"getDetailFailed": "获取详情失败"
}
},
+ "dataStatistics": {
+ "title": "数据统计",
+ "description": "在这里查看和分析您的数据统计信息。",
+ "accountData": "账号数据",
+ "selectSpace": "选择空间",
+ "inputAccountName": "请输入账号名称",
+ "noAccount": "暂无账号",
+ "totalAccount": "累计账号数",
+ "online": "在线",
+ "offline": "离线",
+ "fansCount": "粉丝数",
+ "growthFansCount": "涨粉数",
+ "loginFailed": "登陆失败",
+ "relogin": "重新登录",
+ "dataDetails": "数据明细",
+ "timeRange": "时间范围:",
+ "yesterdayIncrease": "昨日新增",
+ "readCount": "播放数",
+ "commentCount": "评论数",
+ "likeCount": "点赞数",
+ "collectCount": "收藏数",
+ "forwardCount": "分享数",
+ "congratulations": "恭喜你!",
+ "achieveMilestone": "达成数据里程碑",
+ "newHigh": "新高",
+ "tenThousand": "万",
+ "savePoster": "保存海报",
+ "appName": "爱团团AiToEarn",
+ "keepGoing": "继续加油,再创佳绩!",
+ "viewMilestone": "查看里程碑",
+ "milestone": "里程碑",
+ "milestoneProgress": "里程碑进度",
+ "recentWeek": "最近一周"
+ },
"engagement": {
"title": "互动数据",
"columns": {
@@ -802,6 +831,31 @@ interface Resources {
"getStarted": "立即开始",
"useMobilePhone": "使用移动设备"
},
+ "aiGeneration": {
+ "inputPlaceholder": "输入你想创作的内容,AI将为你生成完整的作品...",
+ "generateButton": "生成作品",
+ "generating": "生成中...",
+ "emptyPromptAlert": "请输入生成内容的提示词",
+ "createTaskFailed": "创建任务失败",
+ "thinking": "AI思考中...",
+ "topicPrefix": "创作主题:",
+ "generatedTitlePrefix": "生成主题:",
+ "descriptionPrefix": "📄 ",
+ "failedReasonPrefix": "失败原因: ",
+ "taskTimeout": "任务超时,请稍后重试",
+ "unknownError": "未知错误",
+ "status": {
+ "thinking": "AI思考中...",
+ "waiting": "等待处理...",
+ "generatingContent": "内容生成中",
+ "generatingImage": "图片生成中",
+ "generatingVideo": "视频生成中",
+ "generatingText": "文本生成中",
+ "completed": "生成完成!",
+ "failed": "生成失败",
+ "cancelled": "已取消"
+ }
+ },
"brandBar": {
"title": "支持的社交媒体平台"
},
@@ -1751,6 +1805,92 @@ interface Resources {
"cancel": "取消"
}
},
+ "plugin": {
+ "status": {
+ "unknown": "未检测",
+ "checking": "检测中...",
+ "ready": "插件已就绪",
+ "installedNoPermission": "插件已安装,待授权",
+ "notInstalled": "插件未安装",
+ "connected": "已连接"
+ },
+ "stage": {
+ "download": "下载资源",
+ "upload": "上传文件",
+ "publish": "发布中",
+ "complete": "完成",
+ "error": "错误"
+ },
+ "error": {
+ "pluginNotInstalled": "请先安装 AIToEarn 浏览器插件",
+ "publishingInProgress": "当前正在发布中,请稍后再试",
+ "loginFailed": "登录失败",
+ "publishFailed": "发布失败"
+ },
+ "publishList": {
+ "title": "发布列表",
+ "empty": "暂无发布记录",
+ "platforms": "平台",
+ "status": "状态",
+ "time": "时间",
+ "viewDetail": "查看详情"
+ },
+ "publishDetail": {
+ "title": "发布详情",
+ "platform": "平台",
+ "progress": "进度",
+ "status": "状态",
+ "message": "消息",
+ "result": "结果",
+ "workId": "作品ID",
+ "shareLink": "分享链接",
+ "failReason": "失败原因",
+ "close": "关闭"
+ },
+ "common": {
+ "confirm": "确定",
+ "cancel": "取消",
+ "loading": "加载中...",
+ "success": "成功",
+ "failed": "失败",
+ "pending": "待发布",
+ "publishing": "发布中",
+ "completed": "已完成",
+ "error": "失败",
+ "action": "操作",
+ "total": "共",
+ "items": "条",
+ "viewLink": "查看链接",
+ "startTime": "开始时间",
+ "endTime": "结束时间",
+ "createdAt": "创建时间",
+ "PENDING": "待发布",
+ "PUBLISHING": "发布中",
+ "COMPLETED": "已完成",
+ "ERROR": "失败"
+ },
+ "header": {
+ "pluginActive": "插件已激活",
+ "pluginInactive": "插件未激活",
+ "downloadPlugin": "下载插件",
+ "downloadDescription": "AIToEarn 浏览器插件可以帮助您快速发布内容到各大平台。请点击下方按钮下载安装。",
+ "downloadButton": "立即下载",
+ "chromeWebStore": "Chrome 应用商店",
+ "githubRelease": "GitHub 下载",
+ "activeDescription": "您的浏览器插件已成功激活,可以开始使用发布功能了!",
+ "platformAccounts": "平台账号",
+ "notLoggedIn": "未登录",
+ "loginNow": "立即登录",
+ "viewPublishList": "查看发布列表",
+ "permissionRequired": "需要授权",
+ "permissionDescription": "插件已安装,但需要授予必需的权限才能正常使用。请在浏览器扩展设置中授权插件所需权限。",
+ "checkPermission": "重新检查权限",
+ "sync": "同步",
+ "syncToAccount": "同步到账号管理",
+ "syncSuccess": "账号同步成功",
+ "syncFailed": "账号同步失败"
+ }
+ },
"pricing": {
"title": "套餐与定价",
"subtitle": "选择最适合您需求的套餐,开始您的AI创作之旅",
@@ -2387,7 +2527,13 @@ interface Resources {
"title": "发布作品",
"confirmClose": {
"title": "确认关闭",
- "content": "关闭后,已填写的内容将丢失,是否确认关闭?"
+ "content": "关闭后,已填写的内容将被保存,您下次打开可以恢复,是否确认关闭?"
+ },
+ "restoreData": {
+ "title": "温馨提示",
+ "content": "系统检测到您有未完成的发布记录,是否要恢复?",
+ "okText": "恢复",
+ "cancelText": "不恢复"
},
"buttons": {
"customizePerAccount": "自定义每个账户",
@@ -2455,6 +2601,89 @@ interface Resources {
"descriptionPlaceholder": "开始写"
},
"writingAssistant": "写作助手",
+ "aiAssistant": "AI助手",
+ "aiFeatures": {
+ "shorten": "缩写",
+ "expand": "扩写",
+ "polish": "润色",
+ "translate": "翻译",
+ "generateImage": "制图",
+ "imageToImage": "图生图",
+ "generateVideo": "创作视频",
+ "generateHashtags": "生成话题",
+ "syncToEditor": "同步到编辑器",
+ "targetLanguage": "目标语言",
+ "targetLanguagePlaceholder": "请输入目标语言,如:英文、日文、法文",
+ "inputPrompt": "请输入提示词...",
+ "send": "发送",
+ "defaultPrompts": {
+ "shorten": "请将以下文本缩短,保持核心信息:",
+ "expand": "请将以下文本增加更多细节和描述扩写成适合发布使用的内容,内容翻倍即可不要写的太多,并且回复不要带图片。",
+ "polish": "请润色以下文本,使其更加流畅和专业:",
+ "translate": "你现在是个翻译。如果下面内容是中文,请翻译成英文。如果下面内容是英文,请翻译成中文。只输出翻译结果,不要有其他解释。",
+ "generateImage": "根据我下面提供的内容生成图片,必须生成一张与内容相关的图片。",
+ "imageToImage": "根据用户给出的图片和用户要求生成新的图片。",
+ "generateVideo": "根据我下面提供的内容生成视频创作提示词,确保内容适合发布且不含违规内容。",
+ "generateHashtags": "请按照下面给的内容生成带#的话题生成3-6个,如果是中文内容回复中文话题如果是英文内容回复英文话题,无法区分的优先英文话题,只要回复话题不要其他任何回复"
+ },
+ "processing": "处理中...",
+ "selectText": "请选择要处理的文本",
+ "syncSuccess": "已同步到编辑器",
+ "settings": "设置",
+ "close": "关闭",
+ "chatModel": "聊天模型(缩写/扩写/润色/翻译/话题)",
+ "imageModel": "图片生成模型",
+ "videoModel": "视频生成模型",
+ "selectChatModel": "选择聊天模型",
+ "selectImageModel": "选择图片生成模型",
+ "selectVideoModel": "选择视频模型",
+ "chatModelSaved": "聊天模型设置已保存",
+ "imageModelSaved": "图片生成模型设置已保存",
+ "videoModelSaved": "视频模型设置已保存",
+ "defaultDuration": "默认时长",
+ "defaultResolution": "默认分辨率",
+ "seconds": "秒",
+ "emptyChat": "输入内容开始对话,或选择功能快速处理文本",
+ "copied": "已复制到剪贴板",
+ "hideRaw": "隐藏原始",
+ "showRaw": "查看原始",
+ "imageMissing": "⚠️ 图片数据缺失",
+ "imageLoadFailed": "⚠️ 图片加载失败",
+ "downloadingImages": "正在下载图片...",
+ "downloadingVideo": "正在下载视频...",
+ "imagesSynced": "图片同步成功",
+ "videoSynced": "视频同步成功",
+ "hashtagsAppended": "话题追加成功",
+ "selectVideoModelFirst": "请先选择视频模型",
+ "videoModelUnavailable": "视频模型 {{model}} 不可用,请在设置中重新选择",
+ "generatingVideo": "正在生成视频...",
+ "taskSubmitted": "任务已提交,等待处理...",
+ "generatingStatus": "正在生成视频...",
+ "videoFailed": "视频生成失败",
+ "videoTaskSubmitted": "视频生成任务已提交",
+ "videoGenerationFailed": "视频生成失败,请重试",
+ "videoGenerated": "视频生成成功",
+ "loadingVideoModels": "正在加载视频模型...",
+ "videoModelLoadTimeout": "视频模型加载超时,请稍后重试",
+ "videoProcessingFailed": "视频处理失败,请重试",
+ "imageProcessingFailed": "图片 {{index}} 处理失败: {{error}}",
+ "videoReady": "✅ 视频生成完成!",
+ "uploadImage": "上传图片",
+ "removeImage": "移除图片",
+ "uploadImageFirst": "请先上传图片",
+ "imageUploading": "图片上传中,请稍候...",
+ "imageUploadFailed": "图片上传失败,请重试",
+ "imageUploadSuccess": "图片上传成功",
+ "uploading": "上传中...",
+ "uploadSuccess": "上传成功",
+ "customPrompts": {
+ "title": "自定义提示词",
+ "description": "为每个功能配置自定义提示词。留空则使用默认行为(不添加额外提示词)。",
+ "placeholder": "留空使用默认行为",
+ "clearAll": "清空所有自定义提示词",
+ "clearSuccess": "已清空所有自定义提示词"
+ }
+ },
"upload": {
"finishingUp": "正在完成...",
"uploadImageOrVideo": "上传图片或视频",
@@ -2577,7 +2806,9 @@ interface Resources {
"facebookAuthFailed": "Facebook授权失败",
"accountListRefreshed": "账号列表已刷新",
"refreshAccountListFailed": "刷新账号列表失败",
- "authFailed": "授权失败"
+ "authFailed": "授权失败",
+ "parseCachedChatModelsFailed": "解析缓存的聊天模型失败",
+ "getChatModelsFailed": "获取聊天模型失败"
},
"badges": {
"offline": "已离线",
@@ -2634,6 +2865,7 @@ interface Resources {
"interactive": "作品互动",
"engagement": "互动数据",
"dataStatistics": "数据统计",
+ "dataMonitoring": "数据监控",
"navigation": "导航",
"aiRank": "AI热榜"
},
diff --git a/project/web/src/api/plat/publish.ts b/project/web/src/api/plat/publish.ts
index 0297b1f9..1888b008 100644
--- a/project/web/src/api/plat/publish.ts
+++ b/project/web/src/api/plat/publish.ts
@@ -6,7 +6,6 @@ import type {
import type { PlatType } from '@/app/config/platConfig'
import type { IPlatOption } from '@/components/PublishDialog/publishDialog.type'
import { parseTopicString } from '@/utils'
-// 创建发布
import { request } from '@/utils/request'
// 根据平台类型过滤option参数
@@ -17,7 +16,16 @@ function filterOptionByPlatform(option: IPlatOption, accountType: PlatType): IPl
return option[key] ? ({ [key]: option[key] } as IPlatOption) : {}
}
-// 创建发布
+// 创建发布记录
+export function apiCreatePublishRecord(data: Partial<PublishRecordItem>) {
+ return request({
+ url: 'plat/publish/createRecord',
+ method: 'POST',
+ data,
+ })
+}
+
+// 创建发布任务
export function apiCreatePublish(data: PublishParams) {
const { topics, cleanedString } = parseTopicString(data.desc || '')
data.topics = [...new Set(data.topics?.concat(topics))]
diff --git a/project/web/src/api/types/account.type.ts b/project/web/src/api/types/account.type.ts
index c9d267ad..dfe1abd8 100644
--- a/project/web/src/api/types/account.type.ts
+++ b/project/web/src/api/types/account.type.ts
@@ -1,3 +1,4 @@
+import type { ClientType } from '@/app/[lng]/accounts/accounts.enums'
import type { PlatType } from '@/app/config/platConfig'
export enum AccountType {
@@ -41,6 +42,7 @@ export interface SocialAccount {
updateTime: string
rank: number
groupId: string
+ clientType?: ClientType
}
// 更新账户统计数据
diff --git a/project/web/src/app/[lng]/accounts/accounts.enums.ts b/project/web/src/app/[lng]/accounts/accounts.enums.ts
new file mode 100644
index 00000000..b113be6b
--- /dev/null
+++ b/project/web/src/app/[lng]/accounts/accounts.enums.ts
@@ -0,0 +1,4 @@
+export enum ClientType {
+ WEB = 'web',
+ APP = 'app',
+}
diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss
index c206a438..ceaca708 100644
--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss
+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss
@@ -333,6 +333,29 @@
}
}
}
+
+ // 客户端来源标签样式
+ .accountPopoverInfo-clientType {
+ display: inline-block;
+ padding: 2px 8px;
+ border-radius: 4px;
+ font-size: 12px;
+ font-weight: 500;
+
+ // Web 来源标签 - 蓝色调
+ &[data-type='web'] {
+ background-color: #e6f7ff;
+ color: #1890ff;
+ border: 1px solid #91d5ff;
+ }
+
+ // App/Flutter 来源标签 - 绿色调
+ &[data-type='app'] {
+ background-color: #f6ffed;
+ color: #52c41a;
+ border: 1px solid #b7eb8f;
+ }
+ }
}
}
diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx
index 96505c67..a036f99c 100644
--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx
+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx
@@ -4,6 +4,7 @@ import type {
import type { IMCPManagerModalRef } from './MCPManagerModal'
import type { IUserManageModalRef } from './UserManageModal'
import type { SocialAccount } from '@/api/types/account.type'
+import { ClientType } from '@/app/[lng]/accounts/accounts.enums'
import type {
IpLocationInfo,
} from '@/utils/ipLocation'
@@ -132,6 +133,22 @@ function AccountPopoverInfo({
const platInfo = AccountPlatInfoMap.get(accountInfo.type)!
const [detLoading, setDetLoading] = useState(false)
+ /**
+ * 根据 clientType 获取显示的标签文本
+ * @param clientType 客户端类型(web/app)
+ * @returns 标签显示文本
+ */
+ const getClientTypeLabel = (clientType?: ClientType) => {
+ if (!clientType) return null
+ if (clientType === ClientType.WEB) {
+ return t('clientType.web' as any)
+ }
+ if (clientType === ClientType.APP) {
+ return t('clientType.app' as any)
+ }
+ return null
+ }
+
return (
<div
className={styles.accountPopoverInfo}
@@ -185,6 +202,24 @@ function AccountPopoverInfo({
</Button>
</p>
</div>
+
+ {/* 客户端来源标签(web/flutter app),为空不显示 */}
+ {accountInfo.clientType && (
+ <div className="accountPopoverInfo-item">
+ <p>
+ {t('clientType.label' as any)}
+ :
+ </p>
+ <p>
+ <span
+ className="accountPopoverInfo-clientType"
+ data-type={accountInfo.clientType}
+ >
+ {getClientTypeLabel(accountInfo.clientType)}
+ </span>
+ </p>
+ </div>
+ )}
</div>
)
}
diff --git a/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx b/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx
index beaea313..ec52a74a 100644
--- a/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx
+++ b/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx
@@ -1,14 +1,16 @@
import type { ForwardedRef } from 'react'
import type { SocialAccount } from '@/api/types/account.type'
import type { IpLocationInfo } from '@/utils/ipLocation'
-import { Button, Modal, Select, Space, Tooltip, Typography } from 'antd'
+import { Button, message, Modal, Select, Space, Tooltip, Typography } from 'antd'
import { forwardRef, memo, useEffect, useMemo, useState } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { kwaiSkip } from '@/app/[lng]/accounts/plat/kwaiLogin'
-import { AccountPlatInfoArr, PlatType } from '@/app/config/platConfig'
+import { AccountPlatInfoArr, AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'
import { useTransClient } from '@/app/i18n/client'
import DownloadAppModal from '@/components/common/DownloadAppModal'
import { useAccountStore } from '@/store/account'
+import type { PluginPlatformType } from '@/store/plugin'
+import { PLUGIN_SUPPORTED_PLATFORMS, PluginStatus, usePluginStore } from '@/store/plugin'
import { getIpLocation } from '@/utils/ipLocation'
import { bilibiliSkip } from '../../plat/BilibiliLogin'
import { FacebookPagesModal, facebookSkip } from '../../plat/FacebookLogin'
@@ -56,6 +58,13 @@ const AddAccountModal = memo(
const [downloadPlatform, setDownloadPlatform] = useState<string>('')
const aitoearnDownloadUrl = process.env.NEXT_PUBLIC_AITOEARN_APP_DOWNLOAD_URL || ''
+ // 插件相关状态
+ const pluginStatus = usePluginStore(state => state.status)
+ const platformAccounts = usePluginStore(state => state.platformAccounts)
+ const syncAccountToDatabase = usePluginStore(state => state.syncAccountToDatabase)
+ const init = usePluginStore(state => state.init)
+ const [syncLoadingPlatform, setSyncLoadingPlatform] = useState<PlatType | null>(null)
+
// 空间选择相关状态
const [selectedSpaceId, setSelectedSpaceId] = useState<string | undefined>(targetGroupId)
const [spaceSelectionRequired, setSpaceSelectionRequired] = useState(false)
@@ -204,6 +213,56 @@ const AddAccountModal = memo(
// 可以在这里添加成功提示或其他逻辑
}
+ /**
+ * 检查平台是否为插件支持的平台
+ */
+ const isPluginSupportedPlatform = (platform: PlatType): platform is PluginPlatformType => {
+ return PLUGIN_SUPPORTED_PLATFORMS.includes(platform as PluginPlatformType)
+ }
+
+ /**
+ * 处理从插件同步账号
+ * @param platform 平台类型(必须是插件支持的平台)
+ */
+ const handlePluginPlatformSync = async (platform: PluginPlatformType) => {
+ const platformName = AccountPlatInfoMap.get(platform)?.name || platform
+
+ // 检查插件是否就绪
+ if (pluginStatus !== PluginStatus.READY) {
+ // 插件未就绪,显示下载弹框(带插件Tab)
+ setDownloadPlatform(platformName)
+ setDownloadVisible(true)
+ return
+ }
+
+ // 检查是否有账号
+ const account = platformAccounts[platform]
+ if (!account) {
+ message.warning(t('addAccountModal.platformNotLoggedIn' as any, { platform: platformName }))
+ return
+ }
+
+ setSyncLoadingPlatform(platform)
+ try {
+ const result = await syncAccountToDatabase(platform, selectedSpaceId)
+ if (result) {
+ message.success(t('addAccountModal.syncSuccess' as any))
+ onAddSuccess(result)
+ onClose()
+ }
+ else {
+ message.error(t('addAccountModal.syncFailed' as any))
+ }
+ }
+ catch (error) {
+ console.error('同步账号失败:', error)
+ message.error(t('addAccountModal.syncFailed' as any))
+ }
+ finally {
+ setSyncLoadingPlatform(null)
+ }
+ }
+
// 处理平台点击
const handlePlatformClick = async (key: PlatType, value: any) => {
// 如果需要选择空间但未选择,提示用户
@@ -223,6 +282,12 @@ const AddAccountModal = memo(
return
}
+ // 检查是否为插件支持的平台
+ if (isPluginSupportedPlatform(key)) {
+ await handlePluginPlatformSync(key)
+ return
+ }
+
// 记录授权前的账号数量,用于后续识别新账号
const beforeAuthCount = accountGroupList.reduce((total, group) => total + group.children.length, 0)
@@ -337,6 +402,7 @@ const AddAccountModal = memo(
<div className="addAccountModal_plats">
{AccountPlatInfoArr.map(([key, value]) => {
const isAvailable = isPlatformAvailable(key as PlatType)
+ const isLoading = syncLoadingPlatform === key
return (
<Tooltip title={value.tips?.account} key={key}>
<Button
@@ -344,8 +410,8 @@ const AddAccountModal = memo(
style={{ width: '84px' }}
className={`addAccountModal_plats-item ${!isAvailable ? 'disabled' : ''}`}
disabled={!isAvailable || (spaceSelectionRequired && !selectedSpaceId)}
+ loading={isLoading}
onClick={() => handlePlatformClick(key as PlatType, value)}
-
>
<div className="addAccountModal_plats-item-con">
<img
@@ -410,6 +476,17 @@ const AddAccountModal = memo(
platform={downloadPlatform}
appName="Aitoearn App"
downloadUrl={aitoearnDownloadUrl}
+ // 如果是插件支持的平台且插件未就绪,显示插件Tab
+ showPluginTab={pluginStatus !== PluginStatus.READY}
+ defaultTab="plugin"
+ pluginStatus={
+ pluginStatus === PluginStatus.INSTALLED_NO_PERMISSION
+ ? 'no_permission'
+ : pluginStatus === PluginStatus.NOT_INSTALLED || pluginStatus === PluginStatus.UNKNOWN
+ ? 'not_installed'
+ : 'ready'
+ }
+ onCheckPermission={() => init()}
/>
</>
)
diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx
index 44cebbca..916a85f4 100644
--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx
+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx
@@ -34,6 +34,7 @@ import { deletePlatWorkApi, deletePublishRecordApi, nowPubTaskApi } from '@/api/
import {
PublishStatus,
} from '@/api/plat/types/publish.types'
+import { ClientType } from '@/app/[lng]/accounts/accounts.enums'
import { getDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'
import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'
import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'
@@ -212,6 +213,22 @@ const RecordCore = memo(
)?.icon
}, [publishRecord])
+ /**
+ * 根据 clientType 获取显示的标签文本
+ * @param clientType 客户端类型(web/app)
+ * @returns 标签显示文本
+ */
+ const getClientTypeLabel = (clientType?: ClientType) => {
+ if (!clientType) return null
+ if (clientType === ClientType.WEB) {
+ return t('clientType.web' as any)
+ }
+ if (clientType === ClientType.APP) {
+ return t('clientType.app' as any)
+ }
+ return null
+ }
+
const recordInfo = useMemo(() => {
return [
{
@@ -262,6 +279,15 @@ const RecordCore = memo(
<span className="recordDetails-center-title">
{account?.nickname}
</span>
+ {/* 客户端来源标签(web/flutter app),为空不显示 */}
+ {account?.clientType && (
+ <span
+ className="recordDetails-center-clientType"
+ data-type={account.clientType}
+ >
+ {getClientTypeLabel(account.clientType)}
+ </span>
+ )}
</div>
<div
title={desc}
diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss
index d69f8c0d..6cfe06e3 100644
--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss
+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss
@@ -108,6 +108,30 @@
display: inline-block;
font-weight: 700;
}
+
+ // 客户端来源标签样式
+ &-clientType {
+ display: inline-block;
+ padding: 2px 6px;
+ border-radius: 4px;
+ font-size: 11px;
+ font-weight: 500;
+ margin-left: 8px;
+
+ // Web 来源标签 - 蓝色调
+ &[data-type='web'] {
+ background-color: #e6f7ff;
+ color: #1890ff;
+ border: 1px solid #91d5ff;
+ }
+
+ // App/Flutter 来源标签 - 绿色调
+ &[data-type='app'] {
+ background-color: #f6ffed;
+ color: #52c41a;
+ border: 1px solid #b7eb8f;
+ }
+ }
}
.recordDetails-bottom {
diff --git a/project/web/src/app/config/platConfig.ts b/project/web/src/app/config/platConfig.ts
index 1230ebaf..ecc68f3d 100644
--- a/project/web/src/app/config/platConfig.ts
+++ b/project/web/src/app/config/platConfig.ts
@@ -81,13 +81,12 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([
icon: xhsSvg,
url: 'https://www.xiaohongshu.com/',
themeColor: 'red',
- pubTypes: new Set([]),
+ pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),
commonPubParamsConfig: {
titleMax: 100,
topicMax: 100,
desMax: 1000,
},
- pcNoThis: true,
jiancha: true,
},
],
@@ -145,14 +144,13 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([
name: 'douyin',
icon: douyinSvg,
url: 'https://www.douyin.com/',
- pubTypes: new Set([]),
+ pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),
commonPubParamsConfig: {
titleMax: 30,
topicMax: 5,
desMax: 1000,
},
themeColor: '#FF4D00',
- pcNoThis: true,
jiancha: true,
},
],
diff --git a/project/web/src/app/i18n/locales/en/account.json b/project/web/src/app/i18n/locales/en/account.json
index 90b60f0b..6b6c2c40 100644
--- a/project/web/src/app/i18n/locales/en/account.json
+++ b/project/web/src/app/i18n/locales/en/account.json
@@ -29,7 +29,11 @@
"subtitle": "Select Platform",
"currentSpace": "Current Space",
"pleaseChooseSpaceFirst": "Please choose a space first",
- "addTo": "Add to:"
+ "addTo": "Add to:",
+ "pluginNotReady": "Browser plugin is not ready. Please install and authorize the plugin first.",
+ "platformNotLoggedIn": "{{platform}} is not logged in. Please log in via the plugin first.",
+ "syncSuccess": "Account synced successfully",
+ "syncFailed": "Account sync failed"
},
"noAccountWarning": {
"title": "Notice",
@@ -262,5 +266,10 @@
"username": "username",
"password": "password"
}
+ },
+ "clientType": {
+ "label": "Source",
+ "web": "Web",
+ "app": "App"
}
}
diff --git a/project/web/src/app/i18n/locales/en/plugin.json b/project/web/src/app/i18n/locales/en/plugin.json
new file mode 100644
index 00000000..ec8c03bb
--- /dev/null
+++ b/project/web/src/app/i18n/locales/en/plugin.json
@@ -0,0 +1,87 @@
+{
+ "status": {
+ "unknown": "Unknown",
+ "checking": "Checking...",
+ "ready": "Plugin Ready",
+ "installedNoPermission": "Plugin Installed, Pending Authorization",
+ "notInstalled": "Plugin Not Installed",
+ "connected": "Connected"
+ },
+ "stage": {
+ "download": "Downloading",
+ "upload": "Uploading",
+ "publish": "Publishing",
+ "complete": "Complete",
+ "error": "Error"
+ },
+ "error": {
+ "pluginNotInstalled": "Please install AIToEarn browser plugin first",
+ "publishingInProgress": "Publishing in progress, please try again later",
+ "loginFailed": "Login failed",
+ "publishFailed": "Publish failed"
+ },
+ "publishList": {
+ "title": "Publish List",
+ "empty": "No publish records",
+ "platforms": "Platforms",
+ "status": "Status",
+ "time": "Time",
+ "viewDetail": "View Detail"
+ },
+ "publishDetail": {
+ "title": "Publish Detail",
+ "platform": "Platform",
+ "progress": "Progress",
+ "status": "Status",
+ "message": "Message",
+ "result": "Result",
+ "workId": "Work ID",
+ "shareLink": "Share Link",
+ "failReason": "Fail Reason",
+ "close": "Close",
+ "unknownAccount": "Unknown Account"
+ },
+ "common": {
+ "confirm": "Confirm",
+ "cancel": "Cancel",
+ "loading": "Loading...",
+ "success": "Success",
+ "failed": "Failed",
+ "pending": "Pending",
+ "publishing": "Publishing",
+ "completed": "Completed",
+ "error": "Error",
+ "action": "Action",
+ "total": "Total",
+ "items": "items",
+ "viewLink": "View Link",
+ "startTime": "Start Time",
+ "endTime": "End Time",
+ "createdAt": "Created At",
+ "PENDING": "Pending",
+ "PUBLISHING": "Publishing",
+ "COMPLETED": "Completed",
+ "ERROR": "Error"
+ },
+ "header": {
+ "pluginActive": "Plugin Active",
+ "pluginInactive": "Plugin Inactive",
+ "downloadPlugin": "Download Plugin",
+ "downloadDescription": "AIToEarn browser plugin helps you quickly publish content to various platforms. Click the button below to download and install.",
+ "downloadButton": "Download Now",
+ "chromeWebStore": "Chrome Web Store",
+ "githubRelease": "GitHub Release",
+ "activeDescription": "Your browser plugin is activated. You can start using the publish feature!",
+ "platformAccounts": "Platform Accounts",
+ "notLoggedIn": "Not Logged In",
+ "loginNow": "Login Now",
+ "viewPublishList": "View Publish List",
+ "permissionRequired": "Permission Required",
+ "permissionDescription": "Plugin is installed but requires necessary permissions to work properly. Please grant the required permissions in your browser extension settings.",
+ "checkPermission": "Check Permission Again",
+ "sync": "Sync",
+ "syncToAccount": "Sync to Account Manager",
+ "syncSuccess": "Account synced successfully",
+ "syncFailed": "Account sync failed"
+ }
+}
diff --git a/project/web/src/app/i18n/locales/en/publish.json b/project/web/src/app/i18n/locales/en/publish.json
index a5e370bd..7a1b8bae 100644
--- a/project/web/src/app/i18n/locales/en/publish.json
+++ b/project/web/src/app/i18n/locales/en/publish.json
@@ -72,7 +72,8 @@
"location": "Location",
"searchLocation": "Search location",
"selectLocation": "Select location",
- "descriptionPlaceholder": "Start writing"
+ "descriptionPlaceholder": "Start writing",
+ "fans": "Fans"
},
"writingAssistant": "AI Assistant",
"aiAssistant": "AI Assistant",
@@ -325,5 +326,14 @@
"shares": "Shares"
},
"viewWork": "View Work"
+ },
+ "clientType": {
+ "label": "Source",
+ "web": "Web",
+ "app": "App"
+ },
+ "pluginPublish": {
+ "ready": "Plugin",
+ "notReady": "Plugin Not Ready"
}
}
diff --git a/project/web/src/app/i18n/locales/zh-CN/account.json b/project/web/src/app/i18n/locales/zh-CN/account.json
index 06b5f41e..4279f9d0 100644
--- a/project/web/src/app/i18n/locales/zh-CN/account.json
+++ b/project/web/src/app/i18n/locales/zh-CN/account.json
@@ -29,7 +29,11 @@
"subtitle": "选择平台添加账号",
"currentSpace": "当前空间",
"pleaseChooseSpaceFirst": "请先选择空间",
- "addTo": "添加到:"
+ "addTo": "添加到:",
+ "pluginNotReady": "浏览器插件未就绪,请先安装并授权插件",
+ "platformNotLoggedIn": "{{platform}} 未登录,请先在插件中登录",
+ "syncSuccess": "账号同步成功",
+ "syncFailed": "账号同步失败"
},
"noAccountWarning": {
"title": "提示",
@@ -262,5 +266,10 @@
"username": "代理账号",
"password": "代理密码"
}
+ },
+ "clientType": {
+ "label": "来源",
+ "web": "网页端",
+ "app": "App端"
}
}
diff --git a/project/web/src/app/i18n/locales/zh-CN/plugin.json b/project/web/src/app/i18n/locales/zh-CN/plugin.json
new file mode 100644
index 00000000..d33348ce
--- /dev/null
+++ b/project/web/src/app/i18n/locales/zh-CN/plugin.json
@@ -0,0 +1,87 @@
+{
+ "status": {
+ "unknown": "未检测",
+ "checking": "检测中...",
+ "ready": "插件已就绪",
+ "installedNoPermission": "插件已安装,待授权",
+ "notInstalled": "插件未安装",
+ "connected": "已连接"
+ },
+ "stage": {
+ "download": "下载资源",
+ "upload": "上传文件",
+ "publish": "发布中",
+ "complete": "完成",
+ "error": "错误"
+ },
+ "error": {
+ "pluginNotInstalled": "请先安装 AIToEarn 浏览器插件",
+ "publishingInProgress": "当前正在发布中,请稍后再试",
+ "loginFailed": "登录失败",
+ "publishFailed": "发布失败"
+ },
+ "publishList": {
+ "title": "发布列表",
+ "empty": "暂无发布记录",
+ "platforms": "平台",
+ "status": "状态",
+ "time": "时间",
+ "viewDetail": "查看详情"
+ },
+ "publishDetail": {
+ "title": "发布详情",
+ "platform": "平台",
+ "progress": "进度",
+ "status": "状态",
+ "message": "消息",
+ "result": "结果",
+ "workId": "作品ID",
+ "shareLink": "分享链接",
+ "failReason": "失败原因",
+ "close": "关闭",
+ "unknownAccount": "未知账号"
+ },
+ "common": {
+ "confirm": "确定",
+ "cancel": "取消",
+ "loading": "加载中...",
+ "success": "成功",
+ "failed": "失败",
+ "pending": "待发布",
+ "publishing": "发布中",
+ "completed": "已完成",
+ "error": "失败",
+ "action": "操作",
+ "total": "共",
+ "items": "条",
+ "viewLink": "查看链接",
+ "startTime": "开始时间",
+ "endTime": "结束时间",
+ "createdAt": "创建时间",
+ "PENDING": "待发布",
+ "PUBLISHING": "发布中",
+ "COMPLETED": "已完成",
+ "ERROR": "失败"
+ },
+ "header": {
+ "pluginActive": "插件已激活",
+ "pluginInactive": "插件未激活",
+ "downloadPlugin": "下载插件",
+ "downloadDescription": "AIToEarn 浏览器插件可以帮助您快速发布内容到各大平台。请点击下方按钮下载安装。",
+ "downloadButton": "立即下载",
+ "chromeWebStore": "Chrome 应用商店",
+ "githubRelease": "GitHub 下载",
+ "activeDescription": "您的浏览器插件已成功激活,可以开始使用发布功能了!",
+ "platformAccounts": "平台账号",
+ "notLoggedIn": "未登录",
+ "loginNow": "立即登录",
+ "viewPublishList": "查看发布列表",
+ "permissionRequired": "需要授权",
+ "permissionDescription": "插件已安装,但需要授予必需的权限才能正常使用。请在浏览器扩展设置中授权插件所需权限。",
+ "checkPermission": "重新检查权限",
+ "sync": "同步",
+ "syncToAccount": "同步到账号管理",
+ "syncSuccess": "账号同步成功",
+ "syncFailed": "账号同步失败"
+ }
+}
diff --git a/project/web/src/app/i18n/locales/zh-CN/publish.json b/project/web/src/app/i18n/locales/zh-CN/publish.json
index 4fed7cb8..f6aa9cde 100644
--- a/project/web/src/app/i18n/locales/zh-CN/publish.json
+++ b/project/web/src/app/i18n/locales/zh-CN/publish.json
@@ -73,7 +73,8 @@
"searchLocation": "搜索位置",
"selectLocation": "请选择位置",
"description": "描述",
- "descriptionPlaceholder": "开始写"
+ "descriptionPlaceholder": "开始写",
+ "fans": "粉丝"
},
"writingAssistant": "写作助手",
"aiAssistant": "AI助手",
@@ -326,5 +327,14 @@
"shares": "分享数"
},
"viewWork": "查看作品"
+ },
+ "clientType": {
+ "label": "来源",
+ "web": "网页端",
+ "app": "App端"
+ },
+ "pluginPublish": {
+ "ready": "插件发布",
+ "notReady": "插件未就绪"
}
}
diff --git a/project/web/src/app/layout/LyaoutHeader.tsx b/project/web/src/app/layout/LyaoutHeader.tsx
index 475eaea9..80e6ccae 100644
--- a/project/web/src/app/layout/LyaoutHeader.tsx
+++ b/project/web/src/app/layout/LyaoutHeader.tsx
@@ -4,6 +4,7 @@ import type {
ForwardedRef,
} from 'react'
import {
+ ApiOutlined,
ArrowLeftOutlined,
BellOutlined,
BookOutlined,
@@ -15,13 +16,14 @@ import {
UserOutlined,
} from '@ant-design/icons'
import { NoSSR } from '@kwooshung/react-no-ssr'
-import { Badge, Button, Popover } from 'antd'
+import { Badge, Button, Popover, Tooltip } from 'antd'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import {
forwardRef,
memo,
+ useEffect,
useMemo,
useRef,
useState,
@@ -36,6 +38,8 @@ import NotificationPanel from '@/components/notification/NotificationPanel'
import SignInCalendar from '@/components/SignInCalendar'
import { useNotification } from '@/hooks/useNotification'
import { useGetClientLng } from '@/hooks/useSystem'
+import { PluginStatusModal, usePluginStore } from '@/store/plugin'
+import { PluginStatus } from '@/store/plugin/types/baseTypes'
import { useUserStore } from '@/store/user'
import styles from './styles/lyaoutHeader.module.scss'
@@ -172,12 +176,47 @@ const LyaoutHeader = memo(
const router = useRouter()
const { t } = useTransClient('common')
const { t: tVip } = useTransClient('vip')
+ const { t: tPlugin } = useTransClient('plugin')
const lng = useGetClientLng()
const [notificationVisible, setNotificationVisible] = useState(false)
const [vipModalVisible, setVipModalVisible] = useState(false)
const [pointsModalVisible, setPointsModalVisible] = useState(false)
+ const [pluginModalVisible, setPluginModalVisible] = useState(false)
const { unreadCount } = useNotification()
+ // 插件状态
+ const pluginStatus = usePluginStore(state => state.status)
+
+ // 判断插件状态
+ const isPluginReady = pluginStatus === PluginStatus.READY
+ const isPluginInstalled = pluginStatus === PluginStatus.INSTALLED_NO_PERMISSION
+ const isPluginNotInstalled = pluginStatus === PluginStatus.NOT_INSTALLED || pluginStatus === PluginStatus.UNKNOWN
+
+ /**
+ * 获取插件图标颜色
+ * 未安装:灰色 #bfbfbf
+ * 已安装未授权:警告色 #f59e0b
+ * 已就绪:主题色 #a66ae4
+ */
+ const getPluginIconColor = () => {
+ if (isPluginReady)
+ return '#a66ae4' // 主题色 theColor5
+ if (isPluginInstalled)
+ return '#f59e0b' // 警告色
+ return '#bfbfbf' // 灰色(明显一点)
+ }
+
+ /**
+ * 获取插件状态提示文字
+ */
+ const getPluginTooltip = () => {
+ if (isPluginReady)
+ return tPlugin('status.ready')
+ if (isPluginInstalled)
+ return tPlugin('status.installedNoPermission')
+ return tPlugin('status.notInstalled')
+ }
+
const [isVisible, setIsVisible] = useState(true)
const [isClosing, setIsClosing] = useState(false)
const handleClose = (e: React.MouseEvent) => {
@@ -217,6 +256,22 @@ const LyaoutHeader = memo(
fontSize: '12px',
}}
/>
+ {/* 插件状态图标 */}
+ <Tooltip title={getPluginTooltip()}>
+ <Button
+ type="text"
+ icon={(
+ <ApiOutlined
+ style={{
+ fontSize: 18,
+ color: getPluginIconColor(),
+ }}
+ />
+ )}
+ onClick={() => setPluginModalVisible(true)}
+ className={styles.pluginButton}
+ />
+ </Tooltip>
<NoSSR>
{userStore.token && (
<SignInCalendar className={styles.signInCalendarButton} />
@@ -302,13 +357,14 @@ const LyaoutHeader = memo(
<div className={styles.bannerContent} onClick={() => setVipModalVisible(true)}>
{' '}
{/* 点击横幅打开VIP弹窗,而不是跳转 */}
- <span className={styles.releaseText}>Join Plus —
- Enjoy Unlimited Free Sora-2,
- <span style={{ color: '#FFD700', fontSize: '14px', fontWeight: 'bold', padding: '0 5px', fontStyle: 'italic' }}>
- NEW
- </span>
- Nano Banana Pro !
+ <span className={styles.releaseText}>
+ Join Plus —
+ Enjoy Unlimited Free Sora-2,
+ <span style={{ color: '#FFD700', fontSize: '14px', fontWeight: 'bold', padding: '0 5px', fontStyle: 'italic' }}>
+ NEW
</span>
+ Nano Banana Pro !
+ </span>
</div>
<button
className={styles.closeButton}
@@ -336,6 +392,11 @@ const LyaoutHeader = memo(
open={pointsModalVisible}
onClose={() => setPointsModalVisible(false)}
/>
+ {/* 插件状态弹窗 */}
+ <PluginStatusModal
+ visible={pluginModalVisible}
+ onClose={() => setPluginModalVisible(false)}
+ />
</>
)
}),
diff --git a/project/web/src/app/layout/styles/lyaoutHeader.module.scss b/project/web/src/app/layout/styles/lyaoutHeader.module.scss
index e5df963e..cc78e9ac 100644
--- a/project/web/src/app/layout/styles/lyaoutHeader.module.scss
+++ b/project/web/src/app/layout/styles/lyaoutHeader.module.scss
@@ -227,6 +227,25 @@
color: #666;
}
}
+
+ .pluginButton {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+ transition: all 0.3s ease;
+
+ &:hover {
+ background-color: #f5f5f5;
+ transform: scale(1.05);
+ }
+
+ .anticon {
+ font-size: 18px;
+ }
+ }
}
}
}
diff --git a/project/web/src/components/AvatarPlat/index.tsx b/project/web/src/components/AvatarPlat/index.tsx
index a5dfcff7..bc24aeda 100644
--- a/project/web/src/components/AvatarPlat/index.tsx
+++ b/project/web/src/components/AvatarPlat/index.tsx
@@ -10,7 +10,7 @@ import styles from './avatarPlat.module.scss'
export interface IAvatarPlatRef {}
export interface IAvatarPlatProps {
- account?: SocialAccount
+ account?: Partial<SocialAccount>
size?: AvatarSize
className?: string
width?: number
@@ -56,7 +56,7 @@ const AvatarPlat = memo(
<>
<div className={`${styles.avatarPlat} ${className} ${disabled ? styles.disabled : ''}`}>
<Avatar
- src={getAvatar(account.avatar)}
+ src={getAvatar(account!.avatar!)}
size={avatarWidth || size}
style={disabled ? { opacity: 0.5 } : undefined}
/>
diff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx
index 6824bf3e..da21f5b1 100644
--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx
+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx
@@ -4,7 +4,7 @@ import type {
} from '@/components/PublishDialog/compoents/PubParmasTextarea'
import type { IImgFile, PubItem } from '@/components/PublishDialog/publishDialog.type'
import { Alert } from 'antd'
-import { useCallback, useEffect, useMemo } from 'react'
+import { useCallback, useMemo } from 'react'
import { useShallow } from 'zustand/react/shallow'
import { PubParamsVerifyInfo } from '@/components/PublishDialog/hooks/usePubParamsVerify'
import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'
diff --git a/project/web/src/components/PublishDialog/index.tsx b/project/web/src/components/PublishDialog/index.tsx
index 507e7984..23a231a3 100644
--- a/project/web/src/components/PublishDialog/index.tsx
+++ b/project/web/src/components/PublishDialog/index.tsx
@@ -4,6 +4,12 @@ import type {
import type { SocialAccount } from '@/api/types/account.type'
import type { AIAction, IPublishDialogAiRef } from '@/components/PublishDialog/compoents/PublishDialogAi'
import type { IImgFile, IVideoFile } from '@/components/PublishDialog/publishDialog.type'
+import type {
+ PlatformPublishTask,
+ PluginPlatformType,
+ PublishParams as PluginPublishParams,
+} from '@/store/plugin'
+
import {
ArrowRightOutlined,
CloseOutlined,
@@ -13,6 +19,7 @@ import {
} from '@ant-design/icons'
import { Button, message, Modal, Tooltip } from 'antd'
+import dayjs from 'dayjs'
import {
forwardRef,
memo,
@@ -27,12 +34,13 @@ import { CSSTransition } from 'react-transition-group'
import { useWindowSize } from 'react-use'
import { useShallow } from 'zustand/react/shallow'
import { getChatModels } from '@/api/ai'
-import { apiCreatePublish } from '@/api/plat/publish'
+import { apiCreatePublish, apiCreatePublishRecord } from '@/api/plat/publish'
import { toolsApi } from '@/api/tools'
import {
getDays,
getUtcDays,
} from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'
+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'
import { bilibiliSkip } from '@/app/[lng]/accounts/plat/BilibiliLogin'
import {
FacebookPagesModal,
@@ -65,7 +73,15 @@ import usePubParamsVerify from '@/components/PublishDialog/hooks/usePubParamsVer
import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'
import { usePublishDialogStorageStore } from '@/components/PublishDialog/usePublishDialogStorageStore'
import { useAccountStore } from '@/store/account'
+import {
+ PlatformTaskStatus,
+ PLUGIN_SUPPORTED_PLATFORMS,
+ PluginStatus,
+ PublishDetailModal,
+ usePluginStore,
+} from '@/store/plugin'
import { generateUUID } from '@/utils'
+import { getOssUrl } from '@/utils/oss'
import styles from './publishDialog.module.scss'
export interface IPublishDialogRef {
@@ -171,6 +187,9 @@ const PublishDialog = memo(
// Facebook页面选择弹窗状态
const [showFacebookPagesModal, setShowFacebookPagesModal]
= useState(false)
+ // 发布详情弹框状态
+ const [publishDetailVisible, setPublishDetailVisible] = useState(false)
+ const [currentPublishTaskId, setCurrentPublishTaskId] = useState<string | undefined>(undefined)
const { t } = useTransClient('publish')
// AI助手ref
const aiAssistantRef = useRef<IPublishDialogAiRef>(null)
@@ -422,6 +441,9 @@ const PublishDialog = memo(
useEffect(() => {
if (!open)
return
+ if (!expandedPubItem?.params.des && expandedPubItem?.params.images?.length === 0 && !expandedPubItem?.params.video) {
+ return
+ }
if (isClear.current) {
isClear.current = false
return
@@ -429,7 +451,6 @@ const PublishDialog = memo(
setPubData(pubListChoosed)
}, [pubListChoosed])
useEffect(() => {
- console.log(expandedPubItem)
if (!expandedPubItem || pubList.length === 0)
return
if (isInit.current) {
@@ -568,8 +589,182 @@ const PublishDialog = memo(
setWarningParamsMap(warningParamsMap)
}, [warningParamsMap])
+ /**
+ * 检查平台是否由插件支持
+ * @param platType 平台类型
+ * @returns 是否由插件支持
+ */
+ const isPluginSupportedPlatform = useCallback((platType: PlatType): boolean => {
+ return PLUGIN_SUPPORTED_PLATFORMS.includes(platType as PluginPlatformType)
+ }, [])
+
+ /**
+ * 执行插件发布
+ * @param pluginItems 需要通过插件发布的项目列表
+ * @param taskId 任务ID
+ * @param platformTaskIdMap 账号ID到平台任务ID的映射
+ */
+ const executePluginPublish = useCallback(async (
+ pluginItems: typeof pubListChoosed,
+ taskId: string,
+ platformTaskIdMap: Map<string, string>,
+ ) => {
+ const { status, publish, updatePlatformTask } = usePluginStore.getState()
+
+ // 检查插件状态
+ if (status !== PluginStatus.READY) {
+ console.warn('插件未就绪,无法执行插件发布')
+ const { updatePlatformTaskByRequestId } = usePluginStore.getState()
+ // 将所有插件任务标记为失败
+ for (const item of pluginItems) {
+ const requestId = platformTaskIdMap.get(item.account.id)
+ if (requestId) {
+ updatePlatformTaskByRequestId(requestId, {
+ status: PlatformTaskStatus.ERROR,
+ error: '浏览器插件未就绪,请先安装并授权插件',
+ endTime: Date.now(),
+ })
+ }
+ }
+ return
+ }
+
+ // 并行执行插件发布(不等待,同时发布多个平台)
+ const publishTasks = pluginItems.map(async (item) => {
+ const platform = item.account.type as PluginPlatformType
+ const accountId = item.account.id
+ // 获取该账号对应的 requestId(用于进度匹配)
+ const requestId = platformTaskIdMap.get(accountId)!
+ const { updatePlatformTaskByRequestId } = usePluginStore.getState()
+
+ // 更新任务状态为发布中
+ updatePlatformTaskByRequestId(requestId, {
+ status: PlatformTaskStatus.PUBLISHING,
+ startTime: Date.now(),
+ })
+
+ try {
+ // 构建插件发布参数
+ // 优先传递 File 对象,避免插件需要重新下载
+ const publishParams: PluginPublishParams = {
+ platform,
+ accountId, // 传入账号ID,用于区分同一平台的多个账号
+ requestId, // 传入 requestId,插件回调时带回用于匹配
+ type: item.params.video ? 'video' : 'image',
+ title: item.params.title || '',
+ desc: item.params.des || '',
+ topics: item.params.topics || [],
+ }
+
+ // 视频发布 - 优先传 file,没有 file 才传 URL
+ if (item.params.video) {
+ // 视频:优先传 file(转换 Blob 为 File),没有则传 ossUrl
+ if (item.params.video.file) {
+ // 将 Blob 转换为 File
+ const videoFile = new File(
+ [item.params.video.file],
+ item.params.video.filename || 'video.mp4',
+ { type: item.params.video.file.type },
+ )
+ publishParams.video = videoFile
+ }
+ else if (item.params.video.ossUrl) {
+ publishParams.video = getOssUrl(item.params.video.ossUrl)
+ }
+
+ // 封面:优先传 file,没有则传 ossUrl
+ if (item.params.video.cover?.file) {
+ publishParams.cover = item.params.video.cover.file
+ }
+ else if (item.params.video.cover?.ossUrl) {
+ publishParams.cover = getOssUrl(item.params.video.cover.ossUrl)
+ }
+ }
+ // 图文发布 - 优先传 file,没有 file 才传 URL
+ else if (item.params.images && item.params.images.length > 0) {
+ publishParams.images = item.params.images.map((img) => {
+ // 优先传 file,没有则传 ossUrl
+ if (img.file) {
+ return img.file
+ }
+ return img.ossUrl ? getOssUrl(img.ossUrl) : ''
+ }).filter(item => item !== '')
+ }
+
+ // 执行发布,通过 requestId 匹配进度
+ const result = await publish(publishParams, (progress) => {
+ // 使用 requestId 精确更新进度
+ updatePlatformTaskByRequestId(requestId, {
+ progress,
+ })
+ })
+
+ // 发布成功,更新任务状态
+ updatePlatformTaskByRequestId(requestId, {
+ status: PlatformTaskStatus.COMPLETED,
+ result: {
+ success: true,
+ workId: result.workId,
+ shareLink: result.shareLink,
+ },
+ endTime: Date.now(),
+ })
+
+ // 发布成功后,创建发布记录
+ try {
+ await apiCreatePublishRecord({
+ flowId: generateUUID(),
+ type: item.params.video ? 'video' : 'article',
+ title: item.params.title || '',
+ desc: item.params.des || '',
+ accountId: item.account.id,
+ accountType: item.account.type,
+ videoUrl: item.params.video?.ossUrl,
+ coverUrl: item.params.video?.cover?.ossUrl
+ || (item.params.images && item.params.images.length > 0
+ ? item.params.images[0].ossUrl
+ : undefined),
+ imgUrlList: item.params.images
+ ?.map(v => v.ossUrl)
+ .filter((url): url is string => url !== undefined) || [],
+ topics: item.params.topics || [],
+ status: 1, // 已发布
+ dataId: `${result.workId}`,
+ workLink: result.shareLink,
+ uid: item.account.uid,
+ // @ts-ignore
+ publishTime: dayjs(Date.now()).utc().format(),
+ })
+ }
+ catch (recordError) {
+ console.error('创建发布记录失败:', recordError)
+ }
+ }
+ catch (error) {
+ // 发布失败
+ updatePlatformTaskByRequestId(requestId, {
+ status: PlatformTaskStatus.ERROR,
+ error: error instanceof Error ? error.message : '发布失败',
+ result: {
+ success: false,
+ failReason: error instanceof Error ? error.message : '发布失败',
+ },
+ endTime: Date.now(),
+ })
+ }
+ })
+
+ // 并行执行所有发布任务
+ await Promise.all(publishTasks)
+
+ useCalendarTiming.getState().getPubRecord()
+ }, [])
+
/**
* Publish content with scheduled time (from calendar picker)
+ * 1. 先执行 API 发布(非插件支持平台)
+ * 2. 再执行插件发布(插件支持平台)
+ * 3. 显示发布详情弹框
*/
const pubClick = useCallback(async () => {
setCreateLoading(true)
@@ -578,7 +773,66 @@ const PublishDialog = memo(
pubTime || getDays().add(5, 'second'),
).format()
- for (const item of pubListChoosed) {
+ // 分离 API 发布列表和插件发布列表
+ const apiPublishItems = pubListChoosed.filter(
+ item => !isPluginSupportedPlatform(item.account.type),
+ )
+ const pluginPublishItems = pubListChoosed.filter(
+ item => isPluginSupportedPlatform(item.account.type),
+ )
+
+ // 如果有插件发布项,创建发布任务并显示详情弹框
+ let taskId: string | null = null
+ // 存储每个发布项对应的平台任务ID,用于后续精确更新
+ const platformTaskIdMap = new Map<string, string>()
+
+ if (pluginPublishItems.length > 0) {
+ const { addPublishTask, getPublishTask } = usePluginStore.getState()
+
+ // 创建平台任务列表,为每个任务生成唯一ID和requestId
+ const platformTasks: PlatformPublishTask[] = pluginPublishItems.map((item) => {
+ // 使用账号ID生成唯一的平台任务ID
+ const platformTaskId = `${item.account.type}-${item.account.id}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
+ // 生成唯一的 requestId,用于插件回调匹配
+ const requestId = `req-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
+ // 保存映射关系,用于后续更新(保存 requestId 而非 platformTaskId)
+ platformTaskIdMap.set(item.account.id, requestId)
+
+ return {
+ id: platformTaskId,
+ requestId, // 创建时就指定,传给插件后回调时匹配
+ platform: item.account.type as PluginPlatformType,
+ accountId: item.account.id,
+ params: {
+ platform: item.account.type as PluginPlatformType,
+ type: item.params.video?.ossUrl ? 'video' : 'image',
+ title: item.params.title || '',
+ desc: item.params.des || '',
+ topics: item.params.topics || [],
+ } as PluginPublishParams,
+ status: PlatformTaskStatus.PENDING,
+ progress: null,
+ result: null,
+ startTime: null,
+ endTime: null,
+ error: null,
+ }
+ })
+
+ // 添加发布任务
+ taskId = addPublishTask({
+ title: pubListChoosed[0]?.params.title || pubListChoosed[0]?.params.des?.slice(0, 20) || t('title'),
+ description: pubListChoosed[0]?.params.des?.slice(0, 100),
+ platformTasks,
+ })
+
+ // 设置任务ID并显示弹框
+ setCurrentPublishTaskId(taskId)
+ setPublishDetailVisible(true)
+ }
+
+ // 1. 先执行 API 发布(非插件支持平台)
+ for (const item of apiPublishItems) {
const res = await apiCreatePublish({
topics: item.params.topics ?? [],
flowId: generateUUID(),
@@ -603,9 +857,18 @@ const PublishDialog = memo(
option: item.params.option,
})
if (res?.code !== 0) {
- return setCreateLoading(false)
+ setCreateLoading(false)
+ return
}
}
+
+ // 2. 再执行插件发布(插件支持平台)
+ if (pluginPublishItems.length > 0 && taskId) {
+ // 异步执行插件发布,不阻塞主流程
+ executePluginPublish(pluginPublishItems, taskId, platformTaskIdMap)
+ }
+
+ // 关闭发布弹框
onClose()
setCreateLoading(false)
@@ -613,7 +876,7 @@ const PublishDialog = memo(
onPubSuccess()
}
usePublishDialogStorageStore.getState().clearPubData()
- }, [pubListChoosed, pubTime])
+ }, [pubListChoosed, pubTime, isPluginSupportedPlatform, executePluginPublish, t])
// 处理划词操作
const handleTextSelection = useCallback((action: AIAction, selectedText: string) => {
@@ -1243,6 +1506,16 @@ const PublishDialog = memo(
onClose={() => setShowFacebookPagesModal(false)}
onSuccess={handleFacebookPagesSuccess}
/>
+
+ {/* 发布详情弹框 - 显示插件发布进度 */}
+ <PublishDetailModal
+ visible={publishDetailVisible}
+ onClose={() => {
+ setPublishDetailVisible(false)
+ setCurrentPublishTaskId(undefined)
+ }}
+ taskId={currentPublishTaskId}
+ />
</>
)
},
diff --git a/project/web/src/components/common/DownloadAppModal.tsx b/project/web/src/components/common/DownloadAppModal.tsx
index bab04ee3..ab219bba 100644
--- a/project/web/src/components/common/DownloadAppModal.tsx
+++ b/project/web/src/components/common/DownloadAppModal.tsx
@@ -1,9 +1,11 @@
-import { CheckOutlined, CopyOutlined, DownloadOutlined, QrcodeOutlined } from '@ant-design/icons'
-import { Button, message, Modal, Space, Typography } from 'antd'
+import { ApiOutlined, CheckOutlined, CopyOutlined, DownloadOutlined, MobileOutlined, QrcodeOutlined } from '@ant-design/icons'
+import { Button, message, Modal, Space, Tabs, Typography } from 'antd'
import React, { useState } from 'react'
+import { useTranslation } from 'react-i18next'
import { QRCode } from 'react-qrcode-logo'
import { getMainAppDownloadUrlSync, MAIN_APP_DOWNLOAD_URL } from '@/app/config/appDownloadConfig'
import { useTransClient } from '@/app/i18n/client'
+import { PluginDownloadContent } from '@/store/plugin/components/PluginDownloadContent'
import logo from '@/assets/images/logo.png'
const { Text, Paragraph } = Typography
@@ -16,11 +18,17 @@ interface DownloadAppModalProps {
downloadUrl?: string // 下载链接
qrCodeUrl?: string // 二维码图片URL
zIndex?: number // 弹窗层级
+ // 插件相关配置
+ showPluginTab?: boolean // 是否显示插件Tab
+ defaultTab?: 'plugin' | 'app' // 默认显示哪个Tab
+ pluginStatus?: 'not_installed' | 'no_permission' | 'ready' // 插件状态
+ onCheckPermission?: () => void // 检查权限回调
}
/**
* 下载App提示弹窗组件
* 用于提示用户下载对应的移动端应用
+ * 支持显示插件下载Tab(通过 showPluginTab 配置)
*/
const DownloadAppModal: React.FC<DownloadAppModalProps> = ({
visible,
@@ -30,9 +38,15 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({
downloadUrl,
qrCodeUrl = '',
zIndex = 1000,
+ showPluginTab = false,
+ defaultTab = 'app',
+ pluginStatus = 'not_installed',
+ onCheckPermission,
}) => {
const { t } = useTransClient('common')
+ const { t: tPlugin } = useTranslation('plugin')
const [copySuccess, setCopySuccess] = useState(false)
+ const [activeTab, setActiveTab] = useState(defaultTab)
const handleDownload = () => {
const linkToOpen = downloadUrl || getMainAppDownloadUrlSync()
@@ -52,6 +66,192 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({
}
}
+ /**
+ * 渲染插件Tab内容
+ */
+ const renderPluginContent = () => (
+ <PluginDownloadContent
+ pluginStatus={pluginStatus}
+ onCheckPermission={onCheckPermission}
+ />
+ )
+
+ /**
+ * 渲染App下载Tab内容
+ */
+ const renderAppContent = () => (
+ <div style={{ textAlign: 'center', padding: '20px 0' }}>
+ {/* App Logo */}
+ <div style={{ marginBottom: '24px' }}>
+ <img src={logo.src} alt="Aitoearn" style={{ width: 64, height: 64, borderRadius: 16, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }} />
+ </div>
+
+ {/* 标题 */}
+ <Typography.Title level={4} style={{ marginBottom: '16px', color: '#1f2937' }}>
+ Aitoearn
+ </Typography.Title>
+
+ {/* 描述 */}
+ <Paragraph style={{ color: '#6b7280', marginBottom: '32px', fontSize: '14px', lineHeight: '1.6' }}>
+ <span dangerouslySetInnerHTML={{ __html: t('downloadApp.operationDescription' as any, { platform }) }} />
+ </Paragraph>
+
+ {/* 二维码区域 */}
+ <div style={{
+ marginBottom: '32px',
+ padding: '20px',
+ backgroundColor: '#f9fafb',
+ borderRadius: '12px',
+ border: '1px solid #e5e7eb',
+ }}
+ >
+ {qrCodeUrl
+ ? (
+ <img
+ src={qrCodeUrl}
+ alt="QR Code"
+ style={{
+ width: 120,
+ height: 120,
+ borderRadius: '8px',
+ boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
+ }}
+ />
+ )
+ : (
+ <QRCode
+ value={downloadUrl || getMainAppDownloadUrlSync()}
+ size={120}
+ logoImage={logo.src}
+ logoWidth={30}
+ logoHeight={30}
+ logoOpacity={0.8}
+ qrStyle="squares"
+ eyeRadius={0}
+ style={{ borderRadius: '8px' }}
+ />
+ )}
+ </div>
+
+ {/* 下载链接区域 */}
+ <div style={{
+ marginBottom: '24px',
+ padding: '16px',
+ backgroundColor: '#f3f4f6',
+ borderRadius: '8px',
+ border: '1px solid #d1d5db',
+ }}
+ >
+ <Text type="secondary" style={{ fontSize: '12px', display: 'block', marginBottom: '8px' }}>
+ {t('downloadApp.downloadLink')}
+ </Text>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '8px',
+ }}
+ >
+ <Text
+ style={{
+ flex: 1,
+ fontSize: '13px',
+ wordBreak: 'break-all',
+ textAlign: 'left',
+ }}
+ >
+ {downloadUrl || getMainAppDownloadUrlSync()}
+ </Text>
+ <Button
+ size="small"
+ icon={copySuccess ? <CheckOutlined /> : <CopyOutlined />}
+ onClick={handleCopyLink}
+ type={copySuccess ? 'primary' : 'default'}
+ >
+ {copySuccess ? t('downloadApp.copied' as any) : t('downloadApp.copy' as any)}
+ </Button>
+ </div>
+ </div>
+
+ {/* 提示信息 */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: '#eff6ff',
+ borderRadius: '8px',
+ border: '1px solid #dbeafe',
+ }}
+ >
+ <Text type="secondary" style={{ fontSize: '13px', color: '#1e40af' }}>
+ {t('downloadApp.tip')}
+ </Text>
+ </div>
+
+ {/* 下载按钮 */}
+ {!showPluginTab && (
+ <div style={{ marginTop: '24px' }}>
+ <Button
+ type="primary"
+ size="large"
+ icon={<DownloadOutlined />}
+ onClick={handleDownload}
+ block
+ >
+ {t('downloadApp.downloadNow' as any)}
+ </Button>
+ </div>
+ )}
+ </div>
+ )
+
+ // 如果显示插件Tab,使用Tab布局
+ if (showPluginTab) {
+ const tabItems = [
+ {
+ key: 'plugin',
+ label: (
+ <span>
+ <ApiOutlined />
+ {' '}
+ {tPlugin('header.downloadPlugin')}
+ </span>
+ ),
+ children: renderPluginContent(),
+ },
+ {
+ key: 'app',
+ label: (
+ <span>
+ <MobileOutlined />
+ {' '}
+ Download App
+ </span>
+ ),
+ children: renderAppContent(),
+ },
+ ]
+
+ return (
+ <Modal
+ title={activeTab === 'plugin' ? (pluginStatus === 'no_permission' ? tPlugin('status.installedNoPermission') : tPlugin('status.notInstalled')) : 'Download Aitoearn App'}
+ open={visible}
+ onCancel={onClose}
+ footer={null}
+ width={520}
+ centered
+ destroyOnHidden
+ zIndex={zIndex}
+ >
+ <Tabs
+ activeKey={activeTab}
+ onChange={key => setActiveTab(key as 'plugin' | 'app')}
+ items={tabItems}
+ centered
+ />
+ </Modal>
+ )
+ }
+
+ // 不显示插件Tab,只显示App下载(向后兼容)
return (
<Modal
title={(
@@ -80,114 +280,7 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({
destroyOnHidden
zIndex={zIndex}
>
- <div style={{ textAlign: 'center', padding: '20px 0' }}>
- {/* App Logo */}
- <div style={{ marginBottom: '24px' }}>
- <img src={logo.src} alt="Aitoearn" style={{ width: 64, height: 64, borderRadius: 16, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }} />
- </div>
-
- {/* 标题 */}
- <Typography.Title level={4} style={{ marginBottom: '16px', color: '#1f2937' }}>
- Aitoearn
- </Typography.Title>
-
- {/* 描述 */}
- <Paragraph style={{ color: '#6b7280', marginBottom: '32px', fontSize: '14px', lineHeight: '1.6' }}>
- <span dangerouslySetInnerHTML={{ __html: t('downloadApp.operationDescription' as any, { platform }) }} />
- </Paragraph>
-
- {/* 二维码区域 */}
- <div style={{
- marginBottom: '32px',
- padding: '20px',
- backgroundColor: '#f9fafb',
- borderRadius: '12px',
- border: '1px solid #e5e7eb',
- }}
- >
- {qrCodeUrl
- ? (
- <img
- src={qrCodeUrl}
- alt="QR Code"
- style={{
- width: 120,
- height: 120,
- borderRadius: '8px',
- boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
- }}
- />
- )
- : (
- <QRCode
- value={downloadUrl || getMainAppDownloadUrlSync()}
- size={120}
- logoImage={logo.src}
- logoWidth={30}
- logoHeight={30}
- logoOpacity={0.8}
- qrStyle="squares"
- eyeRadius={0}
- style={{ borderRadius: '8px' }}
- />
- )}
- </div>
-
- {/* 下载链接区域 */}
- <div style={{
- marginBottom: '24px',
- padding: '16px',
- backgroundColor: '#f3f4f6',
- borderRadius: '8px',
- border: '1px solid #d1d5db',
- }}
- >
- <Text type="secondary" style={{ fontSize: '12px', display: 'block', marginBottom: '8px' }}>
- {t('downloadApp.downloadLink')}
- </Text>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- gap: '8px',
- }}
- >
- <Text
- // code
- style={{
- flex: 1,
- fontSize: '13px',
- wordBreak: 'break-all',
- textAlign: 'left',
-
- }}
- >
- {downloadUrl || getMainAppDownloadUrlSync()}
- </Text>
- <Button
- size="small"
- icon={copySuccess ? <CheckOutlined /> : <CopyOutlined />}
- onClick={handleCopyLink}
- type={copySuccess ? 'primary' : 'default'}
- >
- {copySuccess ? t('downloadApp.copied' as any) : t('downloadApp.copy' as any)}
- </Button>
- </div>
- </div>
-
- {/* 提示信息 */}
- <div style={{
- padding: '16px',
- backgroundColor: '#eff6ff',
- borderRadius: '8px',
- border: '1px solid #dbeafe',
- }}
- >
- <Text type="secondary" style={{ fontSize: '13px', color: '#1e40af' }}>
- {t('downloadApp.tip')}
- </Text>
- </div>
- </div>
+ {renderAppContent()}
</Modal>
)
}
diff --git a/project/web/src/hooks/index.ts b/project/web/src/hooks/index.ts
new file mode 100644
index 00000000..5fcebc1b
--- /dev/null
+++ b/project/web/src/hooks/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Hooks 统一导出
+ */
+
+export * from './useNotification';
+export * from './useSystem';
+
diff --git a/project/web/src/store/account.ts b/project/web/src/store/account.ts
index 1619a05b..14cd5cbd 100644
--- a/project/web/src/store/account.ts
+++ b/project/web/src/store/account.ts
@@ -5,6 +5,7 @@ import { combine } from 'zustand/middleware'
import { getAccountGroupApi, getAccountListApi } from '@/api/account'
import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'
import { directTrans } from '@/app/i18n/client'
+import { usePluginStore } from '@/store/plugin'
import { useUserStore } from '@/store/user'
export interface AccountGroup extends AccountGroupItem {
@@ -66,7 +67,7 @@ export const useAccountStore = create(
/**
* 异步获取账户列表(含稳健的loading与错误处理),避免阻塞UI
*/
- async getAccountList() {
+ async getAccountList(isBackground = false) {
if (get().accountLoading)
return
set({ accountLoading: true })
@@ -101,6 +102,10 @@ export const useAccountStore = create(
accountAccountMap,
})
+ if (isBackground) {
+ await usePluginStore.getState().init()
+ }
+
void useDataStatisticsStore
.getState()
.init()
@@ -119,9 +124,8 @@ export const useAccountStore = create(
/**
* 后台异步启动账户列表加载(不等待,不阻塞首屏/刷新渲染)
*/
- getAccountListInBackground() {
- // fire-and-forget,内部自行处理loading与错误
- void methods.getAccountList()
+ async getAccountListInBackground() {
+ await methods.getAccountList(true)
},
// 获取用户组的数据并且将用户放到对应组下
diff --git a/project/web/src/store/index.ts b/project/web/src/store/index.ts
new file mode 100644
index 00000000..a36f6fbc
--- /dev/null
+++ b/project/web/src/store/index.ts
@@ -0,0 +1,11 @@
+/**
+ * Store 统一导出
+ */
+
+export * from './account'
+export * from './config'
+// 浏览器插件模块
+export * from './plugin'
+export * from './system'
+
+export * from './user'
diff --git a/project/web/src/store/plugin/CHANGELOG.md b/project/web/src/store/plugin/CHANGELOG.md
new file mode 100644
index 00000000..50113ad6
--- /dev/null
+++ b/project/web/src/store/plugin/CHANGELOG.md
@@ -0,0 +1,190 @@
+# 更新日志
+
+## v2.0.0 (2025-12-02)
+
+### ✨ 新功能
+
+#### 1. 发布任务列表管理
+
+- **发布任务持久化**: 使用 zustand persist 中间件,自动保存发布任务到 localStorage
+- **任务状态管理**:
+ - 支持多平台任务管理(一次发布可包含多个平台)
+ - 实时更新平台任务状态和进度
+ - 自动计算整体任务状态
+- **任务配置**:
+ - 可配置最大任务数(默认100)
+ - 支持自动清理已完成任务
+ - 可自定义清理时间
+
+#### 2. 发布列表弹框组件 (PublishListModal)
+
+- 展示所有发布任务列表
+- 显示任务状态(待发布、发布中、已完成、失败)
+- 显示包含的平台标签
+- 支持点击查看详情
+- 表格分页展示
+- 响应式设计,适配移动端
+
+#### 3. 发布详情弹框组件 (PublishDetailModal)
+
+- 显示任务基本信息(标题、描述、创建时间)
+- 展示每个平台的详细进度
+- 实时显示发布状态(进度条 + 消息)
+- 显示发布结果(作品ID、分享链接)
+- 显示错误信息
+- 支持两种使用方式:
+ - 传入 task 对象
+ - 传入 taskId(自动从 store 获取)
+- 美观的卡片式设计
+- 完整的时间信息展示
+
+#### 4. 完整的国际化支持
+
+- **中文 (zh-CN)**: 完整的中文文案
+- **英文 (en)**: 完整的英文文案
+- **国际化覆盖**:
+ - 插件状态文本
+ - 发布阶段文本
+ - 错误消息
+ - 组件界面文本
+ - 按钮和操作文本
+
+#### 5. 新增 Store 方法
+
+```typescript
+// 添加发布任务
+addPublishTask(task): string
+
+// 更新平台任务
+updatePlatformTask(taskId, platform, updates): void
+
+// 删除发布任务
+deletePublishTask(taskId): void
+
+// 清空所有任务
+clearPublishTasks(): void
+
+// 获取任务详情
+getPublishTask(taskId): PublishTask | undefined
+
+// 更新任务列表配置
+updateTaskListConfig(config): void
+```
+
+### 📦 新增文件
+
+```
+src/store/plugin/
+├── locales/ # 国际化文件
+│ ├── zh-CN.json # 中文
+│ └── en.json # 英文
+├── types/
+│ └── publishTask.baseTypes.ts # 发布任务类型定义
+├── components/ # 组件目录
+│ ├── PublishListModal.tsx # 发布列表弹框
+│ ├── PublishListModal.module.scss # 样式
+│ ├── PublishDetailModal.tsx # 发布详情弹框
+│ ├── PublishDetailModal.module.scss # 样式
+│ ├── index.ts # 组件导出
+│ ├── example.tsx # 使用示例
+│ └── README.md # 组件文档
+├── QUICK_START.md # 快速开始文档
+└── CHANGELOG.md # 本文件
+```
+
+### 🔄 变更
+
+- **store.ts**: 扩展为支持任务列表管理的 ExtendedPluginStore
+- **baseTypes.ts**: 添加任务相关类型定义
+- **constants.ts**: 添加国际化 key 映射
+- **index.ts**: 导出新增的组件和类型
+
+### 🎨 样式优化
+
+- 使用 CSS 变量,支持主题定制
+- BEM 命名规范(修改为单下划线)
+- SCSS Module 模块化
+- 响应式设计
+
+### 📚 文档
+
+- ✅ 组件使用文档 (`components/README.md`)
+- ✅ 快速开始指南 (`QUICK_START.md`)
+- ✅ 完整示例代码 (`components/example.tsx`)
+- ✅ 类型定义说明
+- ✅ 国际化配置说明
+
+### 🔧 技术栈
+
+- **zustand**: 状态管理
+- **zustand/middleware**: persist 中间件(任务持久化)
+- **react-i18next**: 国际化
+- **ant-design**: UI 组件库
+- **dayjs**: 时间格式化
+- **TypeScript**: 类型支持
+
+### 💡 使用场景
+
+1. **单次发布多个平台**: 一次性发布到抖音、小红书等多个平台
+2. **实时进度追踪**: 查看每个平台的发布进度和状态
+3. **历史记录查看**: 查看所有发布历史记录
+4. **发布结果管理**: 统一管理所有平台的发布结果
+
+### 🚀 快速开始
+
+```tsx
+import {
+ usePluginStore,
+ PublishListModal,
+ PublishDetailModal,
+ PlatformTaskStatus,
+} from '@/store/plugin'
+
+// 创建任务
+const taskId = addPublishTask({
+ title: '我的视频',
+ platformTasks: [...]
+})
+
+// 更新进度
+updatePlatformTask(taskId, 'douyin', {
+ status: PlatformTaskStatus.PUBLISHING,
+ progress: { stage: 'upload', progress: 50 }
+})
+
+// 显示列表和详情
+<PublishListModal visible={true} />
+<PublishDetailModal taskId={taskId} />
+```
+
+### 📝 迁移指南
+
+#### 从 v1.x 迁移
+
+v2.0 完全向后兼容 v1.x 版本,无需修改现有代码。
+
+新功能为可选功能:
+- 不使用任务列表功能,行为与 v1.x 完全一致
+- 可选择性地使用新组件和功能
+
+### ⚠️ 注意事项
+
+1. **localStorage 大小**: 任务列表持久化在 localStorage,注意存储空间限制
+2. **最大任务数**: 默认保存最多 100 个任务,可通过配置调整
+3. **国际化配置**: 需要项目已配置 react-i18next
+4. **类型兼容**: 某些 Store 方法为可选方法,使用时需检查是否存在
+
+### 🎯 下一步计划
+
+- [ ] 支持任务导出(JSON、CSV)
+- [ ] 支持任务筛选和搜索
+- [ ] 添加任务统计图表
+- [ ] 支持任务分组管理
+- [ ] 添加任务备注功能
+
+---
+
+**完整文档**: [README.md](./README.md)
+**快速开始**: [QUICK_START.md](./QUICK_START.md)
+**组件文档**: [components/README.md](./components/README.md)
+
diff --git a/project/web/src/store/plugin/QUICK_START.md b/project/web/src/store/plugin/QUICK_START.md
new file mode 100644
index 00000000..7743ede8
--- /dev/null
+++ b/project/web/src/store/plugin/QUICK_START.md
@@ -0,0 +1,353 @@
+# 快速开始 - 发布任务管理
+
+## 🚀 5分钟上手
+
+### 1. 安装依赖
+
+```bash
+pnpm install dayjs
+```
+
+### 2. 导入组件和 Hook
+
+```tsx
+import {
+ usePluginStore,
+ PublishListModal,
+ PublishDetailModal,
+ PlatformTaskStatus,
+ type PublishTask,
+} from '@/store/plugin'
+```
+
+### 3. 创建发布页面
+
+```tsx
+'use client'
+
+import { useState } from 'react'
+import { Button } from 'antd'
+import {
+ usePluginStore,
+ PublishListModal,
+ PublishDetailModal,
+ PlatformTaskStatus,
+ type PublishTask,
+} from '@/store/plugin'
+
+export default function PublishPage() {
+ const [listVisible, setListVisible] = useState(false)
+ const [detailVisible, setDetailVisible] = useState(false)
+ const [selectedTask, setSelectedTask] = useState<PublishTask>()
+
+ const { addPublishTask, updatePlatformTask } = usePluginStore()
+
+ // 创建并发布任务
+ const handlePublish = async () => {
+ // 1. 创建任务
+ const taskId = addPublishTask!({
+ title: '我的视频',
+ description: '发布到抖音和小红书',
+ platformTasks: [
+ {
+ platform: 'douyin',
+ params: {
+ platform: 'douyin',
+ type: 'video',
+ title: '我的视频',
+ desc: '视频描述',
+ // video: videoFile,
+ // cover: coverFile,
+ },
+ status: PlatformTaskStatus.PENDING,
+ progress: null,
+ result: null,
+ startTime: null,
+ endTime: null,
+ error: null,
+ },
+ {
+ platform: 'xhs',
+ params: {
+ platform: 'xhs',
+ type: 'video',
+ title: '我的视频',
+ desc: '视频描述',
+ },
+ status: PlatformTaskStatus.PENDING,
+ progress: null,
+ result: null,
+ startTime: null,
+ endTime: null,
+ error: null,
+ },
+ ],
+ })
+
+ // 2. 开始发布
+ await publishToPlatforms(taskId)
+
+ // 3. 发布完成后自动打开详情
+ setSelectedTask(usePluginStore.getState().getPublishTask!(taskId))
+ setDetailVisible(true)
+ }
+
+ // 发布到各个平台
+ const publishToPlatforms = async (taskId: string) => {
+ // 发布到抖音
+ updatePlatformTask!(taskId, 'douyin', {
+ status: PlatformTaskStatus.PUBLISHING,
+ startTime: Date.now(),
+ })
+
+ // 模拟发布过程
+ await simulatePublish(taskId, 'douyin')
+
+ // 发布到小红书
+ updatePlatformTask!(taskId, 'xhs', {
+ status: PlatformTaskStatus.PUBLISHING,
+ startTime: Date.now(),
+ })
+
+ await simulatePublish(taskId, 'xhs')
+ }
+
+ // 模拟发布过程
+ const simulatePublish = async (taskId: string, platform: 'douyin' | 'xhs') => {
+ // 上传进度
+ for (let i = 0; i <= 100; i += 20) {
+ await new Promise(resolve => setTimeout(resolve, 500))
+ updatePlatformTask!(taskId, platform, {
+ progress: {
+ stage: 'upload',
+ progress: i,
+ message: `上传中 ${i}%`,
+ timestamp: Date.now(),
+ },
+ })
+ }
+
+ // 发布完成
+ updatePlatformTask!(taskId, platform, {
+ status: PlatformTaskStatus.COMPLETED,
+ endTime: Date.now(),
+ progress: {
+ stage: 'complete',
+ progress: 100,
+ message: '发布成功',
+ timestamp: Date.now(),
+ },
+ result: {
+ success: true,
+ workId: `${platform}_${Date.now()}`,
+ shareLink: `https://${platform}.com/video/${Date.now()}`,
+ publishTime: Date.now(),
+ },
+ })
+ }
+
+ // 查看详情
+ const handleViewDetail = (task: PublishTask) => {
+ setSelectedTask(task)
+ setDetailVisible(true)
+ setListVisible(false)
+ }
+
+ return (
+ <div style={{ padding: 20 }}>
+ <h1>发布管理</h1>
+
+ <div style={{ marginBottom: 20 }}>
+ <Button type="primary" onClick={handlePublish}>
+ 开始发布
+ </Button>
+ {' '}
+ <Button onClick={() => setListVisible(true)}>
+ 查看发布列表
+ </Button>
+ </div>
+
+ {/* 发布列表弹框 */}
+ <PublishListModal
+ visible={listVisible}
+ onClose={() => setListVisible(false)}
+ onViewDetail={handleViewDetail}
+ />
+
+ {/* 发布详情弹框 */}
+ <PublishDetailModal
+ visible={detailVisible}
+ onClose={() => {
+ setDetailVisible(false)
+ setSelectedTask(undefined)
+ }}
+ task={selectedTask}
+ />
+ </div>
+ )
+}
+```
+
+## 📦 核心概念
+
+### 1. 发布任务 (PublishTask)
+
+一次发布操作,可能包含多个平台。
+
+```typescript
+{
+ id: 'task_123',
+ title: '我的视频',
+ platformTasks: [
+ { platform: 'douyin', ... },
+ { platform: 'xhs', ... },
+ ],
+ overallStatus: 'publishing',
+ ...
+}
+```
+
+### 2. 平台任务 (PlatformPublishTask)
+
+单个平台的发布任务。
+
+```typescript
+{
+ platform: 'douyin',
+ status: 'publishing',
+ progress: {
+ stage: 'upload',
+ progress: 45,
+ message: '上传中...',
+ },
+ result: null,
+ ...
+}
+```
+
+### 3. 任务状态 (PlatformTaskStatus)
+
+- `PENDING` - 待发布
+- `PUBLISHING` - 发布中
+- `COMPLETED` - 已完成
+- `ERROR` - 失败
+
+## 🔄 典型流程
+
+```
+1. 创建任务 (addPublishTask)
+ ↓
+2. 更新状态为 PUBLISHING (updatePlatformTask)
+ ↓
+3. 更新进度 (updatePlatformTask)
+ ↓
+4. 更新结果 (updatePlatformTask)
+ ↓
+5. 显示详情 (PublishDetailModal)
+```
+
+## 🎯 最佳实践
+
+### 1. 错误处理
+
+```tsx
+try {
+ await publishToPlatform(taskId, 'douyin')
+} catch (error) {
+ updatePlatformTask!(taskId, 'douyin', {
+ status: PlatformTaskStatus.ERROR,
+ error: error.message,
+ endTime: Date.now(),
+ })
+}
+```
+
+### 2. 实时进度更新
+
+```tsx
+const publishWithProgress = async (taskId, platform) => {
+ updatePlatformTask!(taskId, platform, {
+ status: PlatformTaskStatus.PUBLISHING,
+ startTime: Date.now(),
+ })
+
+ // 使用插件的 publish 方法,带进度回调
+ await window.AIToEarnPlugin.publish(params, (progress) => {
+ updatePlatformTask!(taskId, platform, {
+ progress,
+ })
+ })
+}
+```
+
+### 3. 批量发布
+
+```tsx
+const publishToMultiplePlatforms = async (taskId, platforms) => {
+ // 并行发布
+ await Promise.all(
+ platforms.map(platform =>
+ publishToPlatform(taskId, platform)
+ )
+ )
+}
+```
+
+## 🌍 国际化
+
+组件自动支持国际化,只需确保项目已配置 `react-i18next`。
+
+```tsx
+import { useTranslation } from 'react-i18next'
+
+const { t } = useTranslation()
+t('plugin.publishList.title') // "发布列表"
+```
+
+## 📱 响应式设计
+
+组件已针对移动端优化,自动适配不同屏幕尺寸。
+
+## 🔧 配置任务列表
+
+```tsx
+const { updateTaskListConfig } = usePluginStore()
+
+// 设置最大任务数
+updateTaskListConfig!({
+ maxTasks: 50, // 最多保存50个任务
+ autoCleanCompleted: true, // 自动清理已完成任务
+ cleanAfter: 7 * 24 * 60 * 60 * 1000, // 7天后清理
+})
+```
+
+## 📚 更多文档
+
+- [组件详细文档](./components/README.md)
+- [完整示例](./components/example.tsx)
+- [API 参考](./README.md)
+
+## 💡 常见问题
+
+### Q: 如何持久化任务列表?
+
+A: 任务列表已通过 zustand persist 自动持久化到 localStorage。
+
+### Q: 如何清空所有任务?
+
+```tsx
+const { clearPublishTasks } = usePluginStore()
+clearPublishTasks!()
+```
+
+### Q: 如何删除单个任务?
+
+```tsx
+const { deletePublishTask } = usePluginStore()
+deletePublishTask!('task_id')
+```
+
+## 🎉 完成!
+
+现在你已经掌握了发布任务管理的基本用法,开始构建你的发布功能吧!
+
diff --git a/project/web/src/store/plugin/README.md b/project/web/src/store/plugin/README.md
new file mode 100644
index 00000000..d390a12b
--- /dev/null
+++ b/project/web/src/store/plugin/README.md
@@ -0,0 +1,408 @@
+# 浏览器插件模块
+
+## 📁 文件结构
+
+```
+src/store/plugin/
+├── index.ts # 统一导出
+├── store.ts # Zustand Store 状态管理
+├── hooks.ts # 自定义 Hooks
+├── baseTypes.ts # TypeScript 类型定义
+├── constants.ts # 常量定义
+├── utils.ts # 工具函数
+├── README.md # 本文档
+└── examples/ # 使用示例
+ ├── basic.example.tsx
+ └── advanced.example.tsx
+```
+
+## 🚀 快速开始
+
+### 1. 基础使用
+
+```typescript
+import { usePlugin } from '@/store/plugin';
+
+export function MyComponent() {
+ // 自动轮询插件状态,每2秒检测一次
+ const { isConnected, status } = usePlugin(true, 2000);
+
+ return (
+ <div>
+ 状态: {isConnected ? '已连接' : '未连接'}
+ </div>
+ );
+}
+```
+
+### 2. 登录功能
+
+```typescript
+import { usePluginLogin } from '@/store/plugin';
+
+export function LoginButton() {
+ const { login } = usePluginLogin();
+
+ const handleLogin = async () => {
+ const result = await login('douyin');
+ if (result.success) {
+ console.log('登录成功:', result.data?.nickname);
+ }
+ };
+
+ return <button onClick={handleLogin}>登录抖音</button>;
+}
+```
+
+### 3. 发布视频
+
+```typescript
+import { usePluginPublish } from '@/store/plugin';
+
+export function PublishVideo() {
+ const { publishVideo, isPublishing, publishProgress } = usePluginPublish();
+
+ const handlePublish = async (videoFile: File, coverFile: File) => {
+ const result = await publishVideo(
+ 'douyin',
+ videoFile,
+ coverFile,
+ { title: '我的视频', desc: '描述' },
+ (progress) => console.log(`进度: ${progress.progress}%`)
+ );
+
+ if (result.success) {
+ alert('发布成功!');
+ }
+ };
+
+ return (
+ <div>
+ <button onClick={() => handlePublish(...)} disabled={isPublishing}>
+ {isPublishing ? '发布中...' : '发布视频'}
+ </button>
+ {publishProgress && <div>进度: {publishProgress.progress}%</div>}
+ </div>
+ );
+}
+```
+
+### 4. 完整工作流
+
+```typescript
+import { usePluginWorkflow } from '@/store/plugin';
+
+export function OneClickPublish() {
+ const { loginAndPublishVideo } = usePluginWorkflow();
+
+ const handleOneClick = async (videoFile: File, coverFile: File) => {
+ // 自动登录 + 发布
+ const result = await loginAndPublishVideo(
+ 'douyin',
+ videoFile,
+ coverFile,
+ { title: '标题' }
+ );
+
+ if (result.success) {
+ alert('发布成功!');
+ }
+ };
+
+ return <button onClick={() => handleOneClick(...)}>一键发布</button>;
+}
+```
+
+## 📚 API 文档
+
+### Hooks
+
+#### `usePlugin(autoPolling?, pollingInterval?)`
+
+基础插件状态和方法
+
+**参数:**
+- `autoPolling` - 是否自动轮询,默认 `true`
+- `pollingInterval` - 轮询间隔(毫秒),默认 `2000`
+
+**返回:**
+```typescript
+{
+ status: PluginStatus;
+ isConnected: boolean;
+ isNotInstalled: boolean;
+ isChecking: boolean;
+ isPublishing: boolean;
+ publishProgress: ProgressEvent | null;
+ checkPlugin: () => boolean;
+ startPolling: (interval?: number) => void;
+ stopPolling: () => void;
+ login: (platform: PlatformType) => Promise<PlatAccountInfo>;
+ publish: (params: PublishParams, onProgress?) => Promise<PublishResult>;
+ resetPublishState: () => void;
+}
+```
+
+#### `usePluginLogin()`
+
+登录功能
+
+**返回:**
+```typescript
+{
+ login: (platform: PlatformType) => Promise<OperationResult<PlatAccountInfo>>;
+}
+```
+
+#### `usePluginPublish()`
+
+发布功能
+
+**返回:**
+```typescript
+{
+ publish: (params: PublishParams, onProgress?) => Promise<OperationResult>;
+ publishVideo: (platform, video, cover, options?, onProgress?) => Promise<OperationResult>;
+ publishImages: (platform, images, options?, onProgress?) => Promise<OperationResult>;
+ isPublishing: boolean;
+ publishProgress: ProgressEvent | null;
+ resetPublishState: () => void;
+}
+```
+
+#### `usePluginWorkflow()`
+
+完整工作流(登录+发布)
+
+**返回:**
+```typescript
+{
+ isConnected: boolean;
+ loginAndPublishVideo: (...) => Promise<OperationResult>;
+ loginAndPublishImages: (...) => Promise<OperationResult>;
+}
+```
+
+### 工具函数
+
+```typescript
+// 状态文本
+getPluginStatusText(status: PluginStatus): string;
+getPublishStageText(stage: ProgressEvent['stage']): string;
+
+// 状态判断
+isPluginConnected(status: PluginStatus): boolean;
+isPluginNotInstalled(status: PluginStatus): boolean;
+
+// 格式化
+formatProgress(progress: number): string;
+formatFileSize(bytes: number): string;
+
+// 文件验证
+validateFileType(file: File, acceptTypes: string[]): boolean;
+isValidVideoFile(file: File): boolean;
+isValidImageFile(file: File): boolean;
+validateFileSize(file: File, maxSize: number): boolean;
+
+// 重试机制
+withRetry<T>(fn: () => Promise<T>, maxRetries?, delay?): () => Promise<T>;
+```
+
+### 类型定义
+
+```typescript
+// 插件状态
+enum PluginStatus {
+ UNKNOWN = 'UNKNOWN',
+ CHECKING = 'CHECKING',
+ CONNECTED = 'CONNECTED',
+ NOT_INSTALLED = 'NOT_INSTALLED',
+}
+
+// 平台类型
+type PlatformType = 'douyin' | 'xhs' | 'kwai' | 'bilibili';
+
+// 发布参数
+interface PublishParams {
+ platform: PlatformType;
+ type: 'video' | 'image';
+ title?: string;
+ desc?: string;
+ video?: File | string;
+ cover?: File | string;
+ images?: (File | string)[];
+ topics?: string[];
+ visibility?: 'public' | 'private' | 'friends';
+ // ...更多字段
+}
+
+// 操作结果
+interface OperationResult<T = any> {
+ success: boolean;
+ data?: T;
+ error?: string;
+}
+```
+
+### 常量
+
+```typescript
+// 默认轮询间隔(2秒)
+DEFAULT_POLLING_INTERVAL = 2000
+
+// 插件状态文本
+PLUGIN_STATUS_TEXT = {
+ UNKNOWN: '未检测',
+ CHECKING: '检测中...',
+ CONNECTED: '已连接',
+ NOT_INSTALLED: '未安装',
+}
+
+// 发布阶段文本
+PUBLISH_STAGE_TEXT = {
+ download: '下载资源',
+ upload: '上传文件',
+ publish: '发布中',
+ complete: '完成',
+ error: '错误',
+}
+
+// 错误消息
+ERROR_MESSAGES = {
+ PLUGIN_NOT_INSTALLED: '请先安装 AIToEarn 浏览器插件',
+ PUBLISHING_IN_PROGRESS: '当前正在发布中,请稍后再试',
+ LOGIN_FAILED: '登录失败',
+ PUBLISH_FAILED: '发布失败',
+}
+```
+
+## 💡 使用示例
+
+### 示例 1: 插件状态显示
+
+```typescript
+import { usePlugin, getPluginStatusText } from '@/store/plugin';
+
+export function PluginStatus() {
+ const { status } = usePlugin();
+
+ return (
+ <div>
+ 插件状态: {getPluginStatusText(status)}
+ </div>
+ );
+}
+```
+
+### 示例 2: 文件验证
+
+```typescript
+import { isValidVideoFile, validateFileSize } from '@/store/plugin';
+
+function handleFileSelect(file: File) {
+ if (!isValidVideoFile(file)) {
+ alert('请选择有效的视频文件');
+ return;
+ }
+
+ if (!validateFileSize(file, 500 * 1024 * 1024)) {
+ alert('视频文件不能超过 500MB');
+ return;
+ }
+
+ // 处理文件...
+}
+```
+
+### 示例 3: 带重试的发布
+
+```typescript
+import { usePluginPublish, withRetry } from '@/store/plugin';
+
+export function PublishWithRetry() {
+ const { publish } = usePluginPublish();
+
+ const handlePublish = async (params: PublishParams) => {
+ // 最多重试 3 次,每次延迟 2 秒
+ const publishWithRetry = withRetry(
+ () => publish(params),
+ 3,
+ 2000
+ );
+
+ try {
+ const result = await publishWithRetry();
+ console.log('发布成功:', result);
+ } catch (error) {
+ console.error('重试后仍然失败:', error);
+ }
+ };
+
+ return <button onClick={() => handlePublish(...)}>发布</button>;
+}
+```
+
+### 示例 4: 进度展示
+
+```typescript
+import { usePluginPublish, formatProgress, getPublishStageText } from '@/store/plugin';
+import { Progress } from 'antd';
+
+export function PublishWithProgress() {
+ const { publishVideo, publishProgress } = usePluginPublish();
+
+ return (
+ <div>
+ {publishProgress && (
+ <>
+ <Progress percent={publishProgress.progress} />
+ <p>
+ {getPublishStageText(publishProgress.stage)}: {formatProgress(publishProgress.progress)}
+ </p>
+ </>
+ )}
+ </div>
+ );
+}
+```
+
+## 📝 注意事项
+
+1. **轮询管理**
+ - 使用 `usePlugin` 时会自动管理轮询
+ - 组件卸载时会自动清理定时器
+ - 无需手动调用 `stopPolling()`
+
+2. **错误处理**
+ - Hooks 返回的方法都使用 `OperationResult` 格式
+ - 包含 `success`、`data` 和 `error` 字段
+ - 建议使用这种方式而不是 try-catch
+
+3. **文件大小限制**
+ - 视频: 建议 ≤ 500MB
+ - 图片: 建议每张 ≤ 10MB
+ - 图文: 最多 9 张
+
+4. **并发限制**
+ - 同一时间只能有一个发布任务
+ - `isPublishing` 为 `true` 时无法开始新发布
+
+5. **平台差异**
+ - 不同平台支持的功能可能不同
+ - 参考各平台的具体文档
+
+## 🔗 相关链接
+
+- [Web API 文档](../../../demo/docs/WEB_API.md)
+- [类型定义](../../../demo/PublishType/)
+- [示例代码](./examples/)
+
+## 📞 技术支持
+
+如有问题或建议,请联系技术支持团队。
+
+---
+
+**版本**: 1.0.0
+**最后更新**: 2025-12-01
+
diff --git a/project/web/src/store/plugin/components/PluginDownloadContent.tsx b/project/web/src/store/plugin/components/PluginDownloadContent.tsx
new file mode 100644
index 00000000..fee6fa43
--- /dev/null
+++ b/project/web/src/store/plugin/components/PluginDownloadContent.tsx
@@ -0,0 +1,121 @@
+/**
+ * 插件下载内容组件(可复用)
+ * 用于在不同弹框中显示插件下载或授权内容
+ */
+
+'use client'
+
+import {
+ ApiOutlined,
+ ChromeOutlined,
+ ExclamationCircleOutlined,
+ GithubOutlined,
+} from '@ant-design/icons'
+import { Button, Space, Spin, Typography } from 'antd'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { PLUGIN_DOWNLOAD_LINKS } from '../constants'
+import { usePluginStore } from '../store'
+
+const { Paragraph } = Typography
+
+/**
+ * 组件属性
+ */
+export interface PluginDownloadContentProps {
+ /** 插件状态 */
+ pluginStatus: 'not_installed' | 'no_permission' | 'ready'
+
+ /** 检查权限回调 */
+ onCheckPermission?: () => void | Promise<void>
+}
+
+/**
+ * 插件下载内容组件
+ */
+export function PluginDownloadContent({
+ pluginStatus,
+ onCheckPermission,
+}: PluginDownloadContentProps) {
+ const { t } = useTranslation('plugin')
+ const init = usePluginStore(state => state.init)
+ const [checkingPermission, setCheckingPermission] = useState(false)
+
+ const handleCheckPermission = async () => {
+ setCheckingPermission(true)
+ try {
+ if (onCheckPermission) {
+ await onCheckPermission()
+ }
+ else {
+ await init()
+ }
+ }
+ finally {
+ setCheckingPermission(false)
+ }
+ }
+
+ // 已安装但未授权
+ if (pluginStatus === 'no_permission') {
+ return (
+ <Spin spinning={checkingPermission}>
+ <div style={{ textAlign: 'center', padding: '20px 0' }}>
+ <div style={{ marginBottom: '24px' }}>
+ <ExclamationCircleOutlined style={{ fontSize: 64, color: '#faad14' }} />
+ </div>
+ <Typography.Title level={4} style={{ marginBottom: '16px', color: '#1f2937' }}>
+ {t('header.permissionRequired')}
+ </Typography.Title>
+ <Paragraph style={{ color: '#6b7280', marginBottom: '32px', fontSize: '14px', lineHeight: '1.6' }}>
+ {t('header.permissionDescription')}
+ </Paragraph>
+ <Button
+ type="primary"
+ size="large"
+ loading={checkingPermission}
+ onClick={handleCheckPermission}
+ >
+ {t('header.checkPermission')}
+ </Button>
+ </div>
+ </Spin>
+ )
+ }
+
+ // 未安装
+ return (
+ <div style={{ textAlign: 'center', padding: '20px 0' }}>
+ <div style={{ marginBottom: '24px' }}>
+ <ApiOutlined style={{ fontSize: 64, color: '#667eea' }} />
+ </div>
+ <Typography.Title level={4} style={{ marginBottom: '16px', color: '#1f2937' }}>
+ {t('header.downloadPlugin')}
+ </Typography.Title>
+ <Paragraph style={{ color: '#6b7280', marginBottom: '32px', fontSize: '14px', lineHeight: '1.6' }}>
+ {t('header.downloadDescription')}
+ </Paragraph>
+ <Space direction="vertical" size="middle" style={{ width: '100%' }}>
+ {/* <Button */}
+ {/* type="primary" */}
+ {/* size="large" */}
+ {/* icon={<ChromeOutlined />} */}
+ {/* href={PLUGIN_DOWNLOAD_LINKS.chrome} */}
+ {/* target="_blank" */}
+ {/* block */}
+ {/* > */}
+ {/* {t('header.chromeWebStore')} */}
+ {/* </Button> */}
+ <Button
+ size="large"
+ icon={<GithubOutlined />}
+ href={PLUGIN_DOWNLOAD_LINKS.github}
+ target="_blank"
+ block
+ >
+ {t('header.githubRelease')}
+ </Button>
+ </Space>
+ </div>
+ )
+}
diff --git a/project/web/src/store/plugin/components/PluginStatusModal.module.scss b/project/web/src/store/plugin/components/PluginStatusModal.module.scss
new file mode 100644
index 00000000..2fb32c89
--- /dev/null
+++ b/project/web/src/store/plugin/components/PluginStatusModal.module.scss
@@ -0,0 +1,233 @@
+/**
+ * 插件状态弹框样式
+ */
+
+.pluginStatusModal {
+ :global {
+ .ant-modal-content {
+ border-radius: 12px;
+ overflow: hidden;
+ }
+
+ .ant-modal-header {
+ border-bottom: 1px solid var(--border-color-base, #f0f0f0);
+ padding: 16px 24px;
+ }
+
+ .ant-modal-body {
+ padding: 0;
+ }
+ }
+}
+
+/* ==================== 未激活状态 ==================== */
+
+.inactiveContent {
+ padding: 40px 24px;
+ text-align: center;
+}
+
+.iconWrapper {
+ width: 80px;
+ height: 80px;
+ margin: 0 auto 24px;
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ &.warningIcon {
+ background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
+ }
+}
+
+.downloadIcon {
+ font-size: 36px;
+ color: #fff;
+}
+
+.title {
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--text-color, #1f1f1f);
+ margin-bottom: 12px;
+}
+
+.description {
+ font-size: 14px;
+ color: var(--text-color-secondary, #666);
+ line-height: 1.6;
+ margin-bottom: 32px;
+ max-width: 360px;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+.downloadButtons {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ max-width: 280px;
+ margin: 0 auto;
+
+ :global {
+ .ant-btn {
+ height: 44px;
+ border-radius: 8px;
+ font-size: 15px;
+ }
+ }
+}
+
+/* ==================== 已激活状态 ==================== */
+
+.activeContent {
+ padding: 20px 24px 24px;
+}
+
+.statusBanner {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 16px;
+ background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
+ border-radius: 8px;
+ margin-bottom: 20px;
+}
+
+.checkIcon {
+ font-size: 20px;
+ color: #28a745;
+}
+
+/* ==================== 平台账号部分 ==================== */
+
+.platformSection {
+ margin-bottom: 8px;
+}
+
+.sectionTitle {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--text-color, #1f1f1f);
+ margin-bottom: 12px;
+}
+
+.platformList {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.platformCard {
+ border-radius: 8px;
+ transition: box-shadow 0.2s;
+
+ &:hover {
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
+ }
+
+ :global {
+ .ant-card-body {
+ padding: 12px 16px;
+ }
+ }
+}
+
+.platformInfo {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.platformLeft {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.avatar {
+ flex-shrink: 0;
+}
+
+.accountInfo {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.platformName {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--text-color, #1f1f1f);
+}
+
+.accountName {
+ font-size: 12px;
+ color: var(--text-color-secondary, #666);
+}
+
+.notLoggedIn {
+ font-size: 12px;
+ color: var(--text-color-quaternary, #999);
+}
+
+.platformRight {
+ flex-shrink: 0;
+}
+
+/* ==================== 发布任务部分 ==================== */
+
+.publishSection {
+ margin-top: 8px;
+}
+
+.sectionHeader {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 12px;
+
+ .sectionTitle {
+ margin-bottom: 0;
+ }
+}
+
+.recentTasks {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+
+.taskItem {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 12px;
+ background: var(--bg-color-light, #fafafa);
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background-color 0.2s;
+
+ &:hover {
+ background: var(--bg-color-hover, #f0f0f0);
+ }
+}
+
+.taskInfo {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ flex: 1;
+ min-width: 0;
+}
+
+.taskTitle {
+ font-size: 13px;
+ color: var(--text-color, #1f1f1f);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
diff --git a/project/web/src/store/plugin/components/PluginStatusModal.tsx b/project/web/src/store/plugin/components/PluginStatusModal.tsx
new file mode 100644
index 00000000..b62135c1
--- /dev/null
+++ b/project/web/src/store/plugin/components/PluginStatusModal.tsx
@@ -0,0 +1,375 @@
+/**
+ * 插件状态弹框组件
+ * 三种状态:未安装、已安装未授权、已就绪
+ */
+
+'use client'
+
+import type { PluginPlatformType, PublishTask } from '../types/baseTypes'
+import {
+ CheckCircleOutlined,
+ LoginOutlined,
+ SyncOutlined,
+ UserOutlined,
+} from '@ant-design/icons'
+import { Avatar, Button, Card, Divider, Empty, message, Modal, Space, Spin, Tag, Tooltip } from 'antd'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { AccountPlatInfoMap } from '@/app/config/platConfig'
+import AvatarPlat from '@/components/AvatarPlat'
+import { useAccountStore } from '@/store/account'
+import { PLUGIN_DOWNLOAD_LINKS } from '../constants'
+import { usePluginStore } from '../store'
+import { PLUGIN_SUPPORTED_PLATFORMS, PluginStatus } from '../types/baseTypes'
+import { PluginDownloadContent } from './PluginDownloadContent'
+import styles from './PluginStatusModal.module.scss'
+import { PublishDetailModal } from './PublishDetailModal'
+import { PublishListModal } from './PublishListModal'
+
+/**
+ * 组件属性
+ */
+export interface PluginStatusModalProps {
+ /** 是否显示 */
+ visible: boolean
+
+ /** 关闭回调 */
+ onClose: () => void
+}
+
+/**
+ * 获取平台显示名称
+ * @param platform 平台类型(PlatType)
+ * @returns 平台显示名称
+ */
+function getPlatformName(platform: PluginPlatformType): string {
+ const platInfo = AccountPlatInfoMap.get(platform)
+ return platInfo?.name || platform
+}
+
+/**
+ * 插件状态弹框组件
+ */
+export function PluginStatusModal({ visible, onClose }: PluginStatusModalProps) {
+ const { t } = useTranslation('plugin')
+ const status = usePluginStore(state => state.status)
+ const platformAccounts = usePluginStore(state => state.platformAccounts)
+ const publishTasks = usePluginStore(state => state.publishTasks)
+ const init = usePluginStore(state => state.init)
+ const login = usePluginStore(state => state.login)
+ const syncAccountToDatabase = usePluginStore(state => state.syncAccountToDatabase)
+ const accountGroupList = useAccountStore(state => state.accountGroupList)
+
+ const [loading, setLoading] = useState(false)
+ const [loginLoading, setLoginLoading] = useState<PluginPlatformType | null>(null)
+ const [syncLoading, setSyncLoading] = useState<PluginPlatformType | null>(null)
+ const [showPublishList, setShowPublishList] = useState(false)
+ const [showPublishDetail, setShowPublishDetail] = useState(false)
+ const [selectedTask, setSelectedTask] = useState<PublishTask | null>(null)
+
+ // 状态判断
+ const isReady = status === PluginStatus.READY
+ const isInstalledNoPermission = status === PluginStatus.INSTALLED_NO_PERMISSION
+ const isNotInstalled = status === PluginStatus.NOT_INSTALLED || status === PluginStatus.UNKNOWN
+
+ /**
+ * 处理平台登录
+ */
+ const handleLogin = async (platform: PluginPlatformType) => {
+ setLoginLoading(platform)
+ try {
+ await login(platform)
+ }
+ catch (error) {
+ console.error('登录失败:', error)
+ }
+ finally {
+ setLoginLoading(null)
+ }
+ }
+
+ /**
+ * 处理同步账号到数据库
+ */
+ const handleSyncAccount = async (platform: PluginPlatformType) => {
+ setSyncLoading(platform)
+ try {
+ // 使用默认分组
+ const defaultGroup = accountGroupList.find(g => g.isDefault)
+ const result = await syncAccountToDatabase(platform, defaultGroup?.id)
+
+ if (result) {
+ message.success(t('header.syncSuccess' as any))
+ }
+ else {
+ message.error(t('header.syncFailed' as any))
+ }
+ }
+ catch (error) {
+ console.error('同步账号失败:', error)
+ message.error(t('header.syncFailed' as any))
+ }
+ finally {
+ setSyncLoading(null)
+ }
+ }
+
+ /**
+ * 处理查看发布详情
+ */
+ const handleViewDetail = (task: PublishTask) => {
+ setSelectedTask(task)
+ setShowPublishDetail(true)
+ }
+
+ /**
+ * 获取弹框标题
+ */
+ const getModalTitle = () => {
+ if (isReady)
+ return t('status.ready')
+ if (isInstalledNoPermission)
+ return t('status.installedNoPermission')
+ return t('status.notInstalled')
+ }
+
+ /**
+ * 渲染插件未就绪状态内容(未安装或未授权)
+ */
+ const renderPluginNotReadyContent = () => {
+ const pluginStatusType = isInstalledNoPermission ? 'no_permission' : 'not_installed'
+
+ return (
+ <div className={styles.inactiveContent}>
+ <PluginDownloadContent
+ pluginStatus={pluginStatusType}
+ onCheckPermission={init}
+ />
+ </div>
+ )
+ }
+
+ /**
+ * 渲染已就绪状态内容
+ */
+ const renderReadyContent = () => (
+ <Spin spinning={loading}>
+ <div className={styles.activeContent}>
+ {/* 顶部状态提示 */}
+ <div className={styles.statusBanner}>
+ <CheckCircleOutlined className={styles.checkIcon} />
+ <span>{t('header.activeDescription')}</span>
+ </div>
+
+ {/* 平台账号列表 */}
+ <div className={styles.platformSection}>
+ <h4 className={styles.sectionTitle}>{t('header.platformAccounts')}</h4>
+ <div className={styles.platformList}>
+ {PLUGIN_SUPPORTED_PLATFORMS.map((platform) => {
+ const account = platformAccounts[platform]
+ const isLogging = loginLoading === platform
+
+ return (
+ <Card
+ key={platform}
+ size="small"
+ className={styles.platformCard}
+ >
+ <div className={styles.platformInfo}>
+ <div className={styles.platformLeft}>
+ {/* 使用 AvatarPlat 组件显示带平台图标的头像 */}
+ {account
+ ? (
+ <AvatarPlat
+ account={{
+ type: platform,
+ avatar: account.avatar || '',
+ nickname: account.nickname || '',
+ uid: account.uid || '',
+ id: '0',
+ fansCount: account.fansCount || 0,
+ }}
+ size="large"
+ avatarWidth={40}
+ />
+ )
+ : (
+ <Avatar
+ size={40}
+ icon={<UserOutlined />}
+ className={styles.avatar}
+ />
+ )}
+ <div className={styles.accountInfo}>
+ <div className={styles.platformName}>
+ {getPlatformName(platform)}
+ </div>
+ {account
+ ? (
+ <div className={styles.accountName}>
+ {account.nickname || account.uid}
+ </div>
+ )
+ : (
+ <div className={styles.notLoggedIn}>
+ {t('header.notLoggedIn')}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className={styles.platformRight}>
+ {account
+ ? (
+ <Space size={4}>
+ <Tag color="success">{t('status.connected')}</Tag>
+ <Tooltip title={t('header.syncToAccount' as any)}>
+ <Button
+ type="link"
+ size="small"
+ loading={syncLoading === platform}
+ icon={<SyncOutlined />}
+ onClick={() => handleSyncAccount(platform)}
+ >
+ {t('header.sync' as any)}
+ </Button>
+ </Tooltip>
+ </Space>
+ )
+ : (
+ <Tooltip title={t('header.loginNow')}>
+ <Button
+ type="link"
+ size="small"
+ loading={isLogging}
+ icon={<LoginOutlined />}
+ onClick={() => {
+ window.open(AccountPlatInfoMap.get(platform)?.url || '')
+ }}
+ >
+ {t('header.loginNow')}
+ </Button>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ </Card>
+ )
+ })}
+ </div>
+ </div>
+
+ <Divider />
+
+ {/* 最近发布任务 */}
+ <div className={styles.publishSection}>
+ <div className={styles.sectionHeader}>
+ <h4 className={styles.sectionTitle}>{t('publishList.title')}</h4>
+ <Button
+ type="link"
+ size="small"
+ onClick={() => setShowPublishList(true)}
+ >
+ {t('header.viewPublishList')}
+ </Button>
+ </div>
+
+ {publishTasks.length === 0
+ ? (
+ <Empty
+ image={Empty.PRESENTED_IMAGE_SIMPLE}
+ description={t('publishList.empty')}
+ />
+ )
+ : (
+ <div className={styles.recentTasks}>
+ {publishTasks.slice(0, 3).map(task => (
+ <div
+ key={task.id}
+ className={styles.taskItem}
+ onClick={() => handleViewDetail(task)}
+ >
+ <div className={styles.taskInfo}>
+ <span className={styles.taskTitle}>{task.title}</span>
+ <Space size={4}>
+ {task.platformTasks.map(pt => (
+ <Tag key={pt.platform} color="blue">
+ {getPlatformName(pt.platform as PluginPlatformType)}
+ </Tag>
+ ))}
+ </Space>
+ </div>
+ <Tag color={getStatusColor(task.overallStatus)}>
+ {t(`common.${task.overallStatus}`)}
+ </Tag>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </Spin>
+ )
+
+ /**
+ * 渲染内容
+ */
+ const renderContent = () => {
+ if (isReady) {
+ return renderReadyContent()
+ }
+ return renderPluginNotReadyContent()
+ }
+
+ return (
+ <>
+ <Modal
+ title={getModalTitle()}
+ open={visible}
+ onCancel={onClose}
+ footer={null}
+ width={500}
+ className={styles.pluginStatusModal}
+ centered
+ >
+ {renderContent()}
+ </Modal>
+
+ {/* 发布列表弹框 */}
+ <PublishListModal
+ visible={showPublishList}
+ onClose={() => setShowPublishList(false)}
+ onViewDetail={(task) => {
+ setSelectedTask(task)
+ setShowPublishList(false)
+ setShowPublishDetail(true)
+ }}
+ />
+
+ {/* 发布详情弹框 */}
+ <PublishDetailModal
+ visible={showPublishDetail}
+ onClose={() => {
+ setShowPublishDetail(false)
+ setSelectedTask(null)
+ }}
+ task={selectedTask || undefined}
+ />
+ </>
+ )
+}
+
+/**
+ * 获取状态颜色
+ */
+function getStatusColor(status: string): string {
+ switch (status) {
+ case 'COMPLETED':
+ return 'success'
+ case 'PUBLISHING':
+ return 'processing'
+ case 'ERROR':
+ return 'error'
+ default:
+ return 'default'
+ }
+}
diff --git a/project/web/src/store/plugin/components/PublishDetailModal.module.scss b/project/web/src/store/plugin/components/PublishDetailModal.module.scss
new file mode 100644
index 00000000..6e3d7783
--- /dev/null
+++ b/project/web/src/store/plugin/components/PublishDetailModal.module.scss
@@ -0,0 +1,234 @@
+.publishDetailModal {
+ :global {
+ .ant-modal-body {
+ padding: 20px;
+ max-height: 600px;
+ overflow-y: auto;
+ }
+ }
+
+ .modalHeader {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ }
+
+ &_content {
+ .taskInfo {
+ margin-bottom: 24px;
+ padding-bottom: 20px;
+ border-bottom: 1px solid var(--border-color, #e8e8e8);
+
+ .title {
+ font-size: 18px;
+ font-weight: 600;
+ margin-bottom: 8px;
+ color: var(--text-primary);
+ }
+
+ .description {
+ font-size: 14px;
+ color: var(--text-secondary);
+ margin-bottom: 12px;
+ }
+
+ .meta {
+ font-size: 12px;
+ color: var(--text-tertiary);
+ }
+ }
+
+ .platformTasks {
+ .sectionTitle {
+ font-size: 16px;
+ font-weight: 600;
+ margin-bottom: 16px;
+ color: var(--text-primary);
+ }
+
+ .taskList {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+ }
+ }
+}
+
+.platformCard {
+ padding: 16px;
+ background: var(--bg-secondary, #f9f9f9);
+ border-radius: 8px;
+ border: 1px solid var(--border-color, #e8e8e8);
+
+ &_header {
+ margin-bottom: 12px;
+
+ .platform {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+
+ // 账号头像容器(带平台角标)
+ .accountAvatar {
+ position: relative;
+ flex-shrink: 0;
+
+ // 平台角标
+ .platformBadge {
+ position: absolute;
+ right: -4px;
+ bottom: -4px;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
+ border: 1px solid #eee;
+
+ img {
+ border-radius: 50%;
+ }
+ }
+ }
+
+ // 账号信息
+ .accountInfo {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+
+ .accountName {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text-primary, #1a1a1a);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .platformName {
+ font-size: 12px;
+ color: var(--text-secondary, #666);
+ }
+ }
+ }
+ }
+
+ &_progress {
+ margin-bottom: 16px;
+
+ .progressInfo {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-top: 8px;
+ font-size: 13px;
+
+ .stage {
+ color: var(--text-primary);
+ font-weight: 500;
+ }
+
+ .message {
+ color: var(--text-secondary);
+ }
+ }
+ }
+
+ &_result {
+ padding: 12px;
+ background: var(--bg-primary, #fff);
+ border-radius: 6px;
+ margin-bottom: 12px;
+
+ .resultTitle {
+ font-weight: 600;
+ margin-bottom: 8px;
+ color: var(--text-primary);
+ }
+
+ .resultItem {
+ display: flex;
+ align-items: center;
+ margin-bottom: 6px;
+ font-size: 13px;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ .label {
+ color: var(--text-secondary);
+ margin-right: 8px;
+ min-width: 80px;
+ }
+
+ .value {
+ color: var(--text-primary);
+ word-break: break-all;
+ }
+
+ .link {
+ color: var(--primary-color, #667eea);
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ :global {
+ .anticon {
+ margin-right: 4px;
+ }
+ }
+ }
+
+ .error {
+ color: var(--error-color, #f44336);
+ }
+ }
+ }
+
+ &_error {
+ padding: 12px;
+ background: var(--error-bg, #ffebee);
+ border-radius: 6px;
+ margin-bottom: 12px;
+
+ .errorTitle {
+ font-weight: 600;
+ margin-bottom: 6px;
+ color: var(--error-color, #f44336);
+ }
+
+ .errorMessage {
+ font-size: 13px;
+ color: var(--error-color-dark, #c62828);
+ }
+ }
+
+ &_time {
+ display: flex;
+ gap: 16px;
+ flex-wrap: wrap;
+ font-size: 12px;
+
+ .timeItem {
+ .label {
+ color: var(--text-secondary);
+ margin-right: 4px;
+ }
+
+ .value {
+ color: var(--text-tertiary);
+ }
+ }
+ }
+}
+
diff --git a/project/web/src/store/plugin/components/PublishDetailModal.tsx b/project/web/src/store/plugin/components/PublishDetailModal.tsx
new file mode 100644
index 00000000..42891f36
--- /dev/null
+++ b/project/web/src/store/plugin/components/PublishDetailModal.tsx
@@ -0,0 +1,314 @@
+/**
+ * 发布详情弹框组件
+ * 显示单次发布任务中多个平台的详细进度
+ */
+
+'use client'
+
+import type { PlatformPublishTask, PluginPlatformType, PublishTask } from '../types/baseTypes'
+import { CloseOutlined, LinkOutlined } from '@ant-design/icons'
+import { Avatar, Button, Modal, Progress, Tag } from 'antd'
+import dayjs from 'dayjs'
+import Image from 'next/image'
+import { useTranslation } from 'react-i18next'
+import { AccountPlatInfoMap } from '@/app/config/platConfig'
+import { useAccountStore } from '@/store/account'
+import { getOssUrl } from '@/utils/oss'
+import { usePluginStore } from '../store'
+import { PlatformTaskStatus } from '../types/baseTypes'
+import styles from './PublishDetailModal.module.scss'
+
+/**
+ * 组件属性
+ */
+export interface PublishDetailModalProps {
+ /** 是否显示 */
+ visible: boolean
+
+ /** 关闭回调 */
+ onClose: () => void
+
+ /** 任务ID(二选一) */
+ taskId?: string
+
+ /** 任务对象(二选一) */
+ task?: PublishTask
+}
+
+/**
+ * 获取状态对应的标签颜色
+ */
+function getStatusColor(status: PlatformTaskStatus): string {
+ switch (status) {
+ case PlatformTaskStatus.COMPLETED:
+ return 'success'
+ case PlatformTaskStatus.PUBLISHING:
+ return 'processing'
+ case PlatformTaskStatus.ERROR:
+ return 'error'
+ case PlatformTaskStatus.PENDING:
+ return 'default'
+ default:
+ return 'default'
+ }
+}
+
+/**
+ * 获取进度条状态
+ */
+function getProgressStatus(status: PlatformTaskStatus): 'success' | 'exception' | 'active' | 'normal' {
+ switch (status) {
+ case PlatformTaskStatus.COMPLETED:
+ return 'success'
+ case PlatformTaskStatus.ERROR:
+ return 'exception'
+ case PlatformTaskStatus.PUBLISHING:
+ return 'active'
+ default:
+ return 'normal'
+ }
+}
+
+/**
+ * 获取平台显示名称
+ * @param platform 平台类型(PlatType)
+ * @returns 平台显示名称
+ */
+function getPlatformName(platform: PluginPlatformType): string {
+ const platInfo = AccountPlatInfoMap.get(platform)
+ return platInfo?.name || platform
+}
+
+/**
+ * 平台任务卡片组件
+ */
+function PlatformTaskCard({ platformTask }: { platformTask: PlatformPublishTask }) {
+ const { t } = useTranslation('plugin')
+ const accountMap = useAccountStore(state => state.accountMap)
+
+ // 获取账号信息
+ const account = platformTask.accountId ? accountMap.get(platformTask.accountId) : null
+ const platInfo = AccountPlatInfoMap.get(platformTask.platform)
+
+ return (
+ <div className={styles.platformCard}>
+ {/* 平台信息 - 包含账号头像 */}
+ <div className={styles.platformCard_header}>
+ <div className={styles.platform}>
+ {/* 账号头像(带平台角标) */}
+ <div className={styles.accountAvatar}>
+ <Avatar
+ src={account?.avatar ? getOssUrl(account.avatar) : undefined}
+ size={40}
+ style={{ backgroundColor: '#f0f0f0' }}
+ >
+ {account?.nickname?.charAt(0) || '?'}
+ </Avatar>
+ {/* 平台角标 */}
+ {platInfo?.icon && (
+ <div className={styles.platformBadge}>
+ <Image src={platInfo.icon} alt={platInfo.name} width={16} height={16} />
+ </div>
+ )}
+ </div>
+
+ {/* 账号信息 */}
+ <div className={styles.accountInfo}>
+ <span className={styles.accountName} title={account?.nickname}>
+ {account?.nickname || t('publishDetail.unknownAccount' as any)}
+ </span>
+ <span className={styles.platformName}>
+ {getPlatformName(platformTask.platform as PluginPlatformType)}
+ </span>
+ </div>
+
+ {/* 状态标签 */}
+ <Tag color={getStatusColor(platformTask.status)}>
+ {t(`common.${platformTask.status}`)}
+ </Tag>
+ </div>
+ </div>
+
+ {/* 进度信息 */}
+ {platformTask.progress && (
+ <div className={styles.platformCard_progress}>
+ <Progress
+ percent={Math.round(platformTask.progress.progress || 0)}
+ status={getProgressStatus(platformTask.status)}
+ strokeColor={{
+ '0%': '#667eea',
+ '100%': '#764ba2',
+ }}
+ />
+ <div className={styles.progressInfo}>
+ <span className={styles.stage}>
+ {t(`stage.${platformTask.progress.stage}`)}
+ </span>
+ {platformTask.progress.message && (
+ <span className={styles.message}>
+ {platformTask.progress.message}
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* 结果信息 */}
+ {platformTask.result && (
+ <div className={styles.platformCard_result}>
+ <div className={styles.resultTitle}>{t('publishDetail.result')}</div>
+ {platformTask.result.workId && (
+ <div className={styles.resultItem}>
+ <span className={styles.label}>
+ {t('publishDetail.workId')}
+ :
+ </span>
+ <span className={styles.value}>{platformTask.result.workId}</span>
+ </div>
+ )}
+ {platformTask.result.shareLink && (
+ <div className={styles.resultItem}>
+ <span className={styles.label}>
+ {t('publishDetail.shareLink')}
+ :
+ </span>
+ <a
+ href={platformTask.result.shareLink}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={styles.link}
+ >
+ <LinkOutlined />
+ {' '}
+ {t('common.viewLink')}
+ </a>
+ </div>
+ )}
+ {platformTask.result.failReason && (
+ <div className={styles.resultItem}>
+ <span className={styles.label}>
+ {t('publishDetail.failReason')}
+ :
+ </span>
+ <span className={styles.error}>{platformTask.result.failReason}</span>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* 错误信息 */}
+ {platformTask.error && (
+ <div className={styles.platformCard_error}>
+ <div className={styles.errorTitle}>{t('common.error')}</div>
+ <div className={styles.errorMessage}>{platformTask.error}</div>
+ </div>
+ )}
+
+ {/* 时间信息 */}
+ <div className={styles.platformCard_time}>
+ {platformTask.startTime && (
+ <div className={styles.timeItem}>
+ <span className={styles.label}>
+ {t('common.startTime')}
+ :
+ </span>
+ <span className={styles.value}>
+ {dayjs(platformTask.startTime).format('YYYY-MM-DD HH:mm:ss')}
+ </span>
+ </div>
+ )}
+ {platformTask.endTime && (
+ <div className={styles.timeItem}>
+ <span className={styles.label}>
+ {t('common.endTime')}
+ :
+ </span>
+ <span className={styles.value}>
+ {dayjs(platformTask.endTime).format('YYYY-MM-DD HH:mm:ss')}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+/**
+ * 发布详情弹框组件
+ */
+export function PublishDetailModal({ visible, onClose, taskId, task }: PublishDetailModalProps) {
+ const { t } = useTranslation('plugin')
+
+ // 订阅 store 中的任务列表,实现实时更新
+ // 使用选择器直接获取目标任务,确保每次状态更新都能触发重新渲染
+ const currentTask = usePluginStore((state) => {
+ if (taskId) {
+ return state.publishTasks.find(t => t.id === taskId)
+ }
+ return task
+ })
+
+ if (!currentTask) {
+ return null
+ }
+
+ return (
+ <Modal
+ title={(
+ <div className={styles.modalHeader}>
+ <span>{t('publishDetail.title')}</span>
+ <Tag color={getStatusColor(currentTask.overallStatus)}>
+ {t(`common.${currentTask.overallStatus}`)}
+ </Tag>
+ </div>
+ )}
+ open={visible}
+ onCancel={onClose}
+ footer={(
+ <Button type="primary" onClick={onClose}>
+ {t('publishDetail.close')}
+ </Button>
+ )}
+ width={700}
+ className={styles.publishDetailModal}
+ closeIcon={<CloseOutlined />}
+ >
+ <div className={styles.publishDetailModal_content}>
+ {/* 任务基本信息 */}
+ <div className={styles.taskInfo}>
+ <h3 className={styles.title}>{currentTask.title}</h3>
+ {currentTask.description && (
+ <p className={styles.description}>{currentTask.description}</p>
+ )}
+ <div className={styles.meta}>
+ <span>
+ {t('common.createdAt')}
+ :
+ {' '}
+ {dayjs(currentTask.createdAt).format('YYYY-MM-DD HH:mm:ss')}
+ </span>
+ </div>
+ </div>
+
+ {/* 平台任务列表 */}
+ <div className={styles.platformTasks}>
+ <h4 className={styles.sectionTitle}>
+ {t('publishList.platforms')}
+ {' '}
+ (
+ {currentTask.platformTasks.length}
+ )
+ </h4>
+ <div className={styles.taskList}>
+ {currentTask.platformTasks.map(platformTask => (
+ <PlatformTaskCard
+ key={platformTask.id}
+ platformTask={platformTask}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ </Modal>
+ )
+}
diff --git a/project/web/src/store/plugin/components/PublishListModal.module.scss b/project/web/src/store/plugin/components/PublishListModal.module.scss
new file mode 100644
index 00000000..02dca6ba
--- /dev/null
+++ b/project/web/src/store/plugin/components/PublishListModal.module.scss
@@ -0,0 +1,22 @@
+.publishListModal {
+ :global {
+ .ant-modal-body {
+ padding: 20px;
+ }
+ }
+
+ &_content {
+ .empty {
+ text-align: center;
+ padding: 40px 0;
+ color: var(--text-secondary);
+ }
+
+ .platformTags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ }
+ }
+}
+
diff --git a/project/web/src/store/plugin/components/PublishListModal.tsx b/project/web/src/store/plugin/components/PublishListModal.tsx
new file mode 100644
index 00000000..600b7090
--- /dev/null
+++ b/project/web/src/store/plugin/components/PublishListModal.tsx
@@ -0,0 +1,148 @@
+/**
+ * 发布任务列表弹框组件
+ */
+
+'use client'
+
+import type { ColumnsType } from 'antd/es/table'
+import type { PluginPlatformType, PublishTask } from '../types/baseTypes'
+import { Modal, Table, Tag } from 'antd'
+import dayjs from 'dayjs'
+import { useTranslation } from 'react-i18next'
+import { AccountPlatInfoMap } from '@/app/config/platConfig'
+import { usePluginStore } from '../store'
+import { PlatformTaskStatus } from '../types/baseTypes'
+import styles from './PublishListModal.module.scss'
+
+/**
+ * 组件属性
+ */
+export interface PublishListModalProps {
+ /** 是否显示 */
+ visible: boolean
+
+ /** 关闭回调 */
+ onClose: () => void
+
+ /** 点击查看详情回调 */
+ onViewDetail?: (task: PublishTask) => void
+}
+
+/**
+ * 获取状态对应的标签颜色
+ */
+function getStatusColor(status: PlatformTaskStatus): string {
+ switch (status) {
+ case PlatformTaskStatus.COMPLETED:
+ return 'success'
+ case PlatformTaskStatus.PUBLISHING:
+ return 'processing'
+ case PlatformTaskStatus.ERROR:
+ return 'error'
+ case PlatformTaskStatus.PENDING:
+ return 'default'
+ default:
+ return 'default'
+ }
+}
+
+/**
+ * 获取平台显示名称
+ * @param platform 平台类型(PlatType)
+ * @returns 平台显示名称
+ */
+function getPlatformName(platform: PluginPlatformType): string {
+ const platInfo = AccountPlatInfoMap.get(platform)
+ return platInfo?.name || platform
+}
+
+/**
+ * 发布任务列表弹框组件
+ */
+export function PublishListModal({ visible, onClose, onViewDetail }: PublishListModalProps) {
+ const { t } = useTranslation('plugin')
+ const publishTasks = usePluginStore(state => state.publishTasks) || []
+
+ const columns: ColumnsType<PublishTask> = [
+ {
+ title: t('publishList.title'),
+ dataIndex: 'title',
+ key: 'title',
+ ellipsis: true,
+ width: 200,
+ },
+ {
+ title: t('publishList.platforms'),
+ key: 'platforms',
+ width: 150,
+ render: (_, record) => (
+ <div className={styles.platformTags}>
+ {record.platformTasks.map(task => (
+ <Tag key={task.platform} color="blue">
+ {getPlatformName(task.platform as PluginPlatformType)}
+ </Tag>
+ ))}
+ </div>
+ ),
+ },
+ {
+ title: t('publishList.status'),
+ key: 'status',
+ width: 100,
+ render: (_, record) => (
+ <Tag color={getStatusColor(record.overallStatus)}>
+ {t(`common.${record.overallStatus}`)}
+ </Tag>
+ ),
+ },
+ {
+ title: t('publishList.time'),
+ dataIndex: 'createdAt',
+ key: 'createdAt',
+ width: 180,
+ render: time => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
+ },
+ {
+ title: t('common.action'),
+ key: 'action',
+ width: 120,
+ render: (_, record) => (
+ <a onClick={() => onViewDetail?.(record)}>
+ {t('publishList.viewDetail')}
+ </a>
+ ),
+ },
+ ]
+
+ return (
+ <Modal
+ title={t('publishList.title')}
+ open={visible}
+ onCancel={onClose}
+ footer={null}
+ width={800}
+ className={styles.publishListModal}
+ >
+ <div className={styles.publishListModal_content}>
+ {publishTasks.length === 0
+ ? (
+ <div className={styles.empty}>
+ <p>{t('publishList.empty')}</p>
+ </div>
+ )
+ : (
+ <Table
+ columns={columns}
+ dataSource={publishTasks}
+ rowKey="id"
+ pagination={{
+ pageSize: 10,
+ showSizeChanger: false,
+ showTotal: total => `${t('common.total')} ${total} ${t('common.items')}`,
+ }}
+ />
+ )}
+ </div>
+ </Modal>
+ )
+}
diff --git a/project/web/src/store/plugin/components/README.md b/project/web/src/store/plugin/components/README.md
new file mode 100644
index 00000000..5989c4f9
--- /dev/null
+++ b/project/web/src/store/plugin/components/README.md
@@ -0,0 +1,413 @@
+# 插件组件使用文档
+
+## 📦 组件列表
+
+### 1. PublishListModal - 发布任务列表弹框
+
+显示所有发布任务的列表,每个任务可能包含多个平台的发布。
+
+**功能:**
+- 展示发布任务列表
+- 显示任务状态(待发布、发布中、已完成、失败)
+- 显示包含的平台
+- 点击查看详情
+
+**使用示例:**
+
+```tsx
+import { useState } from 'react'
+import { Button } from 'antd'
+import { PublishListModal } from '@/store/plugin'
+
+export function MyComponent() {
+ const [visible, setVisible] = useState(false)
+ const [detailTask, setDetailTask] = useState()
+
+ const handleViewDetail = (task) => {
+ setDetailTask(task)
+ // 可以在这里打开详情弹框
+ }
+
+ return (
+ <>
+ <Button onClick={() => setVisible(true)}>
+ 查看发布列表
+ </Button>
+
+ <PublishListModal
+ visible={visible}
+ onClose={() => setVisible(false)}
+ onViewDetail={handleViewDetail}
+ />
+ </>
+ )
+}
+```
+
+### 2. PublishDetailModal - 发布详情弹框
+
+显示单次发布任务中多个平台的详细进度和结果。
+
+**功能:**
+- 显示任务基本信息
+- 显示每个平台的发布进度
+- 显示发布结果(作品ID、分享链接等)
+- 显示错误信息
+- 支持两种使用方式:传入 task 对象或 taskId
+
+**使用方式一:传入 task 对象**
+
+```tsx
+import { useState } from 'react'
+import { PublishDetailModal } from '@/store/plugin'
+import type { PublishTask } from '@/store/plugin'
+
+export function MyComponent() {
+ const [visible, setVisible] = useState(false)
+ const [task, setTask] = useState<PublishTask>()
+
+ return (
+ <PublishDetailModal
+ visible={visible}
+ onClose={() => setVisible(false)}
+ task={task}
+ />
+ )
+}
+```
+
+**使用方式二:传入 taskId**
+
+```tsx
+import { useState } from 'react'
+import { PublishDetailModal } from '@/store/plugin'
+
+export function MyComponent() {
+ const [visible, setVisible] = useState(false)
+ const [taskId, setTaskId] = useState<string>()
+
+ return (
+ <PublishDetailModal
+ visible={visible}
+ onClose={() => setVisible(false)}
+ taskId={taskId}
+ />
+ )
+}
+```
+
+## 🔧 完整使用流程
+
+### 1. 创建发布任务
+
+```tsx
+import { usePluginStore } from '@/store/plugin'
+import { PlatformTaskStatus } from '@/store/plugin'
+
+export function PublishPage() {
+ const { addPublishTask } = usePluginStore()
+
+ const handlePublish = () => {
+ // 创建发布任务
+ const taskId = addPublishTask({
+ title: '我的视频',
+ description: '发布到多个平台',
+ platformTasks: [
+ {
+ platform: 'douyin',
+ params: {
+ platform: 'douyin',
+ type: 'video',
+ title: '我的视频',
+ desc: '视频描述',
+ video: videoFile,
+ cover: coverFile,
+ },
+ status: PlatformTaskStatus.PENDING,
+ progress: null,
+ result: null,
+ startTime: null,
+ endTime: null,
+ error: null,
+ },
+ {
+ platform: 'xhs',
+ params: {
+ platform: 'xhs',
+ type: 'video',
+ title: '我的视频',
+ desc: '视频描述',
+ video: videoFile,
+ cover: coverFile,
+ },
+ status: PlatformTaskStatus.PENDING,
+ progress: null,
+ result: null,
+ startTime: null,
+ endTime: null,
+ error: null,
+ },
+ ],
+ })
+
+ console.log('任务ID:', taskId)
+ }
+
+ return <button onClick={handlePublish}>发布</button>
+}
+```
+
+### 2. 更新发布进度
+
+```tsx
+import { usePluginStore } from '@/store/plugin'
+import { PlatformTaskStatus } from '@/store/plugin'
+
+export function PublishService() {
+ const { updatePlatformTask } = usePluginStore()
+
+ const startPublish = async (taskId: string) => {
+ // 开始发布到抖音
+ updatePlatformTask(taskId, 'douyin', {
+ status: PlatformTaskStatus.PUBLISHING,
+ startTime: Date.now(),
+ progress: {
+ stage: 'upload',
+ progress: 0,
+ message: '开始上传...',
+ timestamp: Date.now(),
+ },
+ })
+
+ // 模拟上传进度
+ for (let i = 0; i <= 100; i += 10) {
+ await new Promise(resolve => setTimeout(resolve, 500))
+
+ updatePlatformTask(taskId, 'douyin', {
+ progress: {
+ stage: 'upload',
+ progress: i,
+ message: `上传中 ${i}%`,
+ timestamp: Date.now(),
+ },
+ })
+ }
+
+ // 发布完成
+ updatePlatformTask(taskId, 'douyin', {
+ status: PlatformTaskStatus.COMPLETED,
+ endTime: Date.now(),
+ progress: {
+ stage: 'complete',
+ progress: 100,
+ message: '发布成功',
+ timestamp: Date.now(),
+ },
+ result: {
+ success: true,
+ workId: '123456',
+ shareLink: 'https://douyin.com/video/123456',
+ publishTime: Date.now(),
+ },
+ })
+ }
+
+ return null
+}
+```
+
+### 3. 集成发布列表和详情
+
+```tsx
+import { useState } from 'react'
+import { Button } from 'antd'
+import {
+ PublishListModal,
+ PublishDetailModal,
+ type PublishTask
+} from '@/store/plugin'
+
+export function PublishManagePage() {
+ const [listVisible, setListVisible] = useState(false)
+ const [detailVisible, setDetailVisible] = useState(false)
+ const [selectedTask, setSelectedTask] = useState<PublishTask>()
+
+ const handleViewDetail = (task: PublishTask) => {
+ setSelectedTask(task)
+ setDetailVisible(true)
+ setListVisible(false) // 关闭列表,打开详情
+ }
+
+ return (
+ <div>
+ <Button type="primary" onClick={() => setListVisible(true)}>
+ 查看发布列表
+ </Button>
+
+ {/* 发布列表弹框 */}
+ <PublishListModal
+ visible={listVisible}
+ onClose={() => setListVisible(false)}
+ onViewDetail={handleViewDetail}
+ />
+
+ {/* 发布详情弹框 */}
+ <PublishDetailModal
+ visible={detailVisible}
+ onClose={() => {
+ setDetailVisible(false)
+ setSelectedTask(undefined)
+ }}
+ task={selectedTask}
+ />
+ </div>
+ )
+}
+```
+
+### 4. 发布完成后自动弹出详情
+
+```tsx
+import { useState, useEffect } from 'react'
+import { PublishDetailModal } from '@/store/plugin'
+import { usePluginStore } from '@/store/plugin'
+import { PlatformTaskStatus } from '@/store/plugin'
+
+export function PublishWithAutoDetail() {
+ const [detailVisible, setDetailVisible] = useState(false)
+ const [currentTaskId, setCurrentTaskId] = useState<string>()
+
+ const { publishTasks, addPublishTask, updatePlatformTask } = usePluginStore()
+
+ // 监听任务完成
+ useEffect(() => {
+ if (!publishTasks || !currentTaskId) return
+
+ const task = publishTasks.find(t => t.id === currentTaskId)
+ if (!task) return
+
+ // 检查是否所有平台都完成了
+ const allCompleted = task.platformTasks.every(
+ pt => pt.status === PlatformTaskStatus.COMPLETED ||
+ pt.status === PlatformTaskStatus.ERROR
+ )
+
+ if (allCompleted) {
+ // 自动弹出详情
+ setDetailVisible(true)
+ }
+ }, [publishTasks, currentTaskId])
+
+ const handlePublish = async () => {
+ // 创建任务
+ const taskId = addPublishTask({
+ title: '测试发布',
+ platformTasks: [
+ // ... 平台任务
+ ],
+ })
+
+ setCurrentTaskId(taskId)
+
+ // 开始发布...
+ // updatePlatformTask(...)
+ }
+
+ return (
+ <>
+ <button onClick={handlePublish}>开始发布</button>
+
+ <PublishDetailModal
+ visible={detailVisible}
+ onClose={() => setDetailVisible(false)}
+ taskId={currentTaskId}
+ />
+ </>
+ )
+}
+```
+
+## 🌍 国际化支持
+
+组件内置国际化支持,会自动根据项目的语言设置显示对应文本。
+
+**支持的语言:**
+- 中文 (`zh-CN`)
+- 英文 (`en`)
+
+**国际化文件位置:**
+- `src/store/plugin/locales/zh-CN.json`
+- `src/store/plugin/locales/en.json`
+
+## 📝 类型定义
+
+```typescript
+// 发布任务
+interface PublishTask {
+ id: string
+ title: string
+ description?: string
+ platformTasks: PlatformPublishTask[]
+ createdAt: number
+ updatedAt: number
+ overallStatus: PlatformTaskStatus
+}
+
+// 平台任务
+interface PlatformPublishTask {
+ platform: PlatformType
+ params: PublishParams
+ status: PlatformTaskStatus
+ progress: ProgressEvent | null
+ result: PublishResult | null
+ startTime: number | null
+ endTime: number | null
+ error: string | null
+}
+
+// 任务状态
+enum PlatformTaskStatus {
+ PENDING = 'pending',
+ PUBLISHING = 'publishing',
+ COMPLETED = 'completed',
+ ERROR = 'error',
+}
+```
+
+## 🎨 样式定制
+
+组件使用 SCSS Module,可以通过 CSS 变量进行样式定制:
+
+```scss
+// 在你的全局样式中定义这些变量
+:root {
+ --text-primary: #333;
+ --text-secondary: #666;
+ --text-tertiary: #999;
+ --bg-primary: #fff;
+ --bg-secondary: #f9f9f9;
+ --border-color: #e8e8e8;
+ --primary-color: #667eea;
+ --error-color: #f44336;
+ --error-bg: #ffebee;
+ --error-color-dark: #c62828;
+}
+```
+
+## 📖 更多示例
+
+查看 `src/store/plugin/components/example.tsx` 获取更多完整示例。
+
+## 💡 注意事项
+
+1. **任务持久化**: 发布任务会通过 zustand persist 中间件自动持久化到 localStorage
+2. **最大任务数**: 默认最多保存 100 个任务,可通过 `updateTaskListConfig` 修改
+3. **自动清理**: 可配置自动清理已完成任务的时间
+4. **实时更新**: 组件会自动响应 store 的变化,无需手动刷新
+
+## 🔗 相关链接
+
+- [插件 Store 文档](../README.md)
+- [类型定义](../types/)
+- [完整示例](./example.tsx)
+
diff --git a/project/web/src/store/plugin/components/index.ts b/project/web/src/store/plugin/components/index.ts
new file mode 100644
index 00000000..e63f9fb3
--- /dev/null
+++ b/project/web/src/store/plugin/components/index.ts
@@ -0,0 +1,8 @@
+/**
+ * 插件组件统一导出
+ */
+
+export * from './PublishListModal'
+export * from './PublishDetailModal'
+export * from './PluginStatusModal'
+export * from './PluginDownloadContent'
diff --git a/project/web/src/store/plugin/constants.ts b/project/web/src/store/plugin/constants.ts
new file mode 100644
index 00000000..c91ec2f9
--- /dev/null
+++ b/project/web/src/store/plugin/constants.ts
@@ -0,0 +1,60 @@
+/**
+ * 浏览器插件相关常量定义
+ */
+
+/**
+ * 默认轮询间隔(毫秒)
+ */
+export const DEFAULT_POLLING_INTERVAL = 2000
+
+/**
+ * 插件下载链接配置
+ */
+export const PLUGIN_DOWNLOAD_LINKS = {
+ chrome: 'https://chromewebstore.google.com/detail/aitoearn',
+ github: 'https://github.com/yikart/AiToEarn/releases/download/v1.4.0/aitoearn-extension.zip',
+} as const
+
+/**
+ * 插件状态国际化 key 映射
+ */
+export const PLUGIN_STATUS_I18N_KEY = {
+ UNKNOWN: 'plugin:status.unknown',
+ CHECKING: 'plugin:status.checking',
+ READY: 'plugin:status.ready',
+ INSTALLED_NO_PERMISSION: 'plugin:status.installedNoPermission',
+ NOT_INSTALLED: 'plugin:status.notInstalled',
+ // 兼容旧代码
+ CONNECTED: 'plugin:status.ready',
+} as const
+
+/**
+ * 发布阶段国际化 key 映射
+ */
+export const PUBLISH_STAGE_I18N_KEY = {
+ download: 'plugin:stage.download',
+ upload: 'plugin:stage.upload',
+ publish: 'plugin:stage.publish',
+ complete: 'plugin:stage.complete',
+ error: 'plugin:stage.error',
+} as const
+
+/**
+ * 错误消息国际化 key
+ */
+export const ERROR_MESSAGE_I18N_KEY = {
+ PLUGIN_NOT_INSTALLED: 'plugin:error.pluginNotInstalled',
+ PUBLISHING_IN_PROGRESS: 'plugin:error.publishingInProgress',
+ LOGIN_FAILED: 'plugin:error.loginFailed',
+ PUBLISH_FAILED: 'plugin:error.publishFailed',
+} as const
+
+/**
+ * 任务状态国际化 key 映射
+ */
+export const TASK_STATUS_I18N_KEY = {
+ pending: 'plugin:common.pending',
+ publishing: 'plugin:common.publishing',
+ completed: 'plugin:common.completed',
+ error: 'plugin:common.error',
+} as const
diff --git a/project/web/src/store/plugin/hooks.ts b/project/web/src/store/plugin/hooks.ts
new file mode 100644
index 00000000..ec63eb5e
--- /dev/null
+++ b/project/web/src/store/plugin/hooks.ts
@@ -0,0 +1,280 @@
+/**
+ * 浏览器插件相关的自定义 Hooks
+ */
+
+'use client'
+
+import type {
+ OperationResult,
+ PluginPlatformType,
+ ProgressCallback,
+ PublishParams,
+} from './types/baseTypes'
+import { useCallback, useEffect } from 'react'
+import { DEFAULT_POLLING_INTERVAL } from './constants'
+import { usePluginStore } from './store'
+import { PluginStatus } from './types/baseTypes'
+
+/**
+ * 使用插件状态和方法的 Hook
+ * @param autoPolling 是否自动轮询插件状态,默认 true
+ * @param pollingInterval 轮询间隔(毫秒),默认 2000ms
+ */
+export function usePlugin(
+ autoPolling = true,
+ pollingInterval = DEFAULT_POLLING_INTERVAL,
+) {
+ const {
+ status,
+ isPublishing,
+ publishProgress,
+ checkPlugin,
+ startPolling,
+ stopPolling,
+ login,
+ publish,
+ resetPublishState,
+ } = usePluginStore()
+
+ // 自动轮询
+ useEffect(() => {
+ if (autoPolling) {
+ startPolling(pollingInterval)
+ return () => {
+ stopPolling()
+ }
+ }
+ }, [autoPolling, pollingInterval, startPolling, stopPolling])
+
+ // 判断插件是否已就绪
+ const isReady = status === PluginStatus.READY
+
+ // 判断插件是否已连接(兼容旧代码)
+ const isConnected = isReady
+
+ // 判断插件是否未安装
+ const isNotInstalled = status === PluginStatus.NOT_INSTALLED
+
+ // 判断是否正在检测
+ const isChecking = status === PluginStatus.CHECKING
+
+ // 判断插件是否已安装但未授权
+ const isInstalledNoPermission = status === PluginStatus.INSTALLED_NO_PERMISSION
+
+ return {
+ // 状态
+ status,
+ isReady,
+ isConnected,
+ isNotInstalled,
+ isChecking,
+ isInstalledNoPermission,
+ isPublishing,
+ publishProgress,
+
+ // 方法
+ checkPlugin,
+ startPolling,
+ stopPolling,
+ login,
+ publish,
+ resetPublishState,
+ }
+}
+
+/**
+ * 使用平台登录的 Hook
+ */
+export function usePluginLogin() {
+ const { login } = usePluginStore()
+
+ /**
+ * 登录到指定平台
+ * @param platform 平台类型
+ * @returns Promise<账号信息>
+ */
+ const loginToPlatform = useCallback(
+ async (platform: PluginPlatformType) => {
+ try {
+ const accountInfo = await login(platform)
+ return { success: true, data: accountInfo } as OperationResult
+ }
+ catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '登录失败',
+ } as OperationResult
+ }
+ },
+ [login],
+ )
+
+ return {
+ login: loginToPlatform,
+ }
+}
+
+/**
+ * 使用发布功能的 Hook
+ */
+export function usePluginPublish() {
+ const { publish, isPublishing, publishProgress, resetPublishState }
+ = usePluginStore()
+
+ /**
+ * 发布内容
+ * @param params 发布参数
+ * @param onProgress 进度回调
+ * @returns Promise<发布结果>
+ */
+ const publishContent = useCallback(
+ async (params: PublishParams, onProgress?: ProgressCallback) => {
+ try {
+ const result = await publish(params, onProgress)
+ return { success: true, data: result } as OperationResult
+ }
+ catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : '发布失败',
+ } as OperationResult
+ }
+ },
+ [publish],
+ )
+
+ /**
+ * 发布视频
+ */
+ const publishVideo = useCallback(
+ async (
+ platform: PluginPlatformType,
+ video: File | string,
+ cover: File | string,
+ options: {
+ title?: string
+ desc?: string
+ topics?: string[]
+ visibility?: 'public' | 'private' | 'friends'
+ } = {},
+ onProgress?: ProgressCallback,
+ ) => {
+ return publishContent(
+ {
+ platform,
+ type: 'video',
+ video,
+ cover,
+ ...options,
+ },
+ onProgress,
+ )
+ },
+ [publishContent],
+ )
+
+ /**
+ * 发布图文
+ */
+ const publishImages = useCallback(
+ async (
+ platform: PluginPlatformType,
+ images: (File | string)[],
+ options: {
+ title?: string
+ desc?: string
+ topics?: string[]
+ visibility?: 'public' | 'private' | 'friends'
+ } = {},
+ onProgress?: ProgressCallback,
+ ) => {
+ return publishContent(
+ {
+ platform,
+ type: 'image',
+ images,
+ ...options,
+ },
+ onProgress,
+ )
+ },
+ [publishContent],
+ )
+
+ return {
+ publish: publishContent,
+ publishVideo,
+ publishImages,
+ isPublishing,
+ publishProgress,
+ resetPublishState,
+ }
+}
+
+/**
+ * 完整的插件工作流 Hook(登录 + 发布)
+ */
+export function usePluginWorkflow() {
+ const { isReady } = usePlugin()
+ const { login } = usePluginLogin()
+ const { publishVideo, publishImages } = usePluginPublish()
+
+ /**
+ * 登录并发布视频
+ */
+ const loginAndPublishVideo = useCallback(
+ async (
+ platform: PluginPlatformType,
+ video: File | string,
+ cover: File | string,
+ options: {
+ title?: string
+ desc?: string
+ topics?: string[]
+ } = {},
+ onProgress?: ProgressCallback,
+ ) => {
+ // 第一步:登录
+ const loginResult = await login(platform)
+ if (!loginResult.success) {
+ return loginResult
+ }
+
+ // 第二步:发布
+ return publishVideo(platform, video, cover, options, onProgress)
+ },
+ [login, publishVideo],
+ )
+
+ /**
+ * 登录并发布图文
+ */
+ const loginAndPublishImages = useCallback(
+ async (
+ platform: PluginPlatformType,
+ images: (File | string)[],
+ options: {
+ title?: string
+ desc?: string
+ topics?: string[]
+ } = {},
+ onProgress?: ProgressCallback,
+ ) => {
+ // 第一步:登录
+ const loginResult = await login(platform)
+ if (!loginResult.success) {
+ return loginResult
+ }
+
+ // 第二步:发布
+ return publishImages(platform, images, options, onProgress)
+ },
+ [login, publishImages],
+ )
+
+ return {
+ isReady,
+ loginAndPublishVideo,
+ loginAndPublishImages,
+ }
+}
diff --git a/project/web/src/store/plugin/index.ts b/project/web/src/store/plugin/index.ts
new file mode 100644
index 00000000..53481060
--- /dev/null
+++ b/project/web/src/store/plugin/index.ts
@@ -0,0 +1,68 @@
+/**
+ * 浏览器插件模块统一导出
+ */
+
+// Components
+export * from './components'
+
+// Constants
+export {
+ DEFAULT_POLLING_INTERVAL,
+ ERROR_MESSAGE_I18N_KEY,
+ PLUGIN_DOWNLOAD_LINKS,
+ PLUGIN_STATUS_I18N_KEY,
+ PUBLISH_STAGE_I18N_KEY,
+ TASK_STATUS_I18N_KEY,
+} from './constants'
+
+// Hooks
+export {
+ usePlugin,
+ usePluginLogin,
+ usePluginPublish,
+ usePluginWorkflow,
+} from './hooks'
+
+// Store
+export { usePluginStore } from './store'
+export type { PlatformAccountsMap, PlatformProgressMap } from './store'
+
+// Types
+export type {
+ AIToEarnPluginAPI,
+ OperationResult,
+ PermissionCheckResult,
+ PlatAccountInfo,
+ PlatformPublishTask,
+ PluginPlatformType,
+ PluginStore,
+ ProgressCallback,
+ ProgressEvent,
+ PublishParams,
+ PublishResult,
+ PublishTask,
+ PublishTaskListConfig,
+} from './types/baseTypes'
+
+export {
+ PlatformTaskStatus,
+ PLUGIN_SUPPORTED_PLATFORMS,
+ PluginStatus,
+} from './types/baseTypes'
+
+// Utils
+export {
+ formatFileSize,
+ formatProgress,
+ getPluginStatusI18nKey,
+ getPublishStageI18nKey,
+ isPluginConnected,
+ isPluginInstalledNoPermission,
+ isPluginNotInstalled,
+ isPluginReady,
+ isValidImageFile,
+ isValidVideoFile,
+ validateFileSize,
+ validateFileType,
+ withRetry,
+} from './utils'
diff --git a/project/web/src/store/plugin/plugin.utils.ts b/project/web/src/store/plugin/plugin.utils.ts
new file mode 100644
index 00000000..c44d25c9
--- /dev/null
+++ b/project/web/src/store/plugin/plugin.utils.ts
@@ -0,0 +1,34 @@
+/**
+ * 插件相关工具函数
+ */
+
+import type { PlatAccountInfo, PlatformPublishTask, PluginPlatformType } from './types/baseTypes'
+import { PlatformTaskStatus, PLUGIN_SUPPORTED_PLATFORMS } from './types/baseTypes'
+
+/** 生成唯一ID */
+export function generateId() {
+ return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
+}
+
+/** 计算整体任务状态 */
+export function calculateOverallStatus(platformTasks: PlatformPublishTask[]) {
+ if (platformTasks.every(task => task.status === PlatformTaskStatus.COMPLETED)) {
+ return PlatformTaskStatus.COMPLETED
+ }
+ if (platformTasks.some(task => task.status === PlatformTaskStatus.PUBLISHING)) {
+ return PlatformTaskStatus.PUBLISHING
+ }
+ if (platformTasks.some(task => task.status === PlatformTaskStatus.ERROR)) {
+ return PlatformTaskStatus.ERROR
+ }
+ return PlatformTaskStatus.PENDING
+}
+
+/** 创建初始平台账号映射 */
+export function createInitialPlatformAccounts() {
+ const accounts: Record<PluginPlatformType, PlatAccountInfo | null> = {} as any
+ for (const platform of PLUGIN_SUPPORTED_PLATFORMS) {
+ accounts[platform] = null
+ }
+ return accounts
+}
diff --git a/project/web/src/store/plugin/store.ts b/project/web/src/store/plugin/store.ts
new file mode 100644
index 00000000..7d904873
--- /dev/null
+++ b/project/web/src/store/plugin/store.ts
@@ -0,0 +1,574 @@
+/**
+ * 浏览器插件状态管理 Store
+ */
+
+import type {
+ PlatAccountInfo,
+ PlatformPublishTask,
+ PluginPlatformType,
+ ProgressCallback,
+ ProgressEvent,
+ PublishParams,
+ PublishTask,
+ PublishTaskListConfig,
+} from './types/baseTypes'
+import type { SocialAccount } from '@/api/types/account.type'
+import lodash from 'lodash'
+import { create } from 'zustand'
+import { combine } from 'zustand/middleware'
+import { createOrUpdateAccountApi } from '@/api/account'
+import { ClientType } from '@/app/[lng]/accounts/accounts.enums'
+import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'
+import { AccountStatus } from '@/app/config/accountConfig'
+import { useAccountStore } from '@/store/account'
+import { DEFAULT_POLLING_INTERVAL } from './constants'
+import { calculateOverallStatus, createInitialPlatformAccounts, generateId } from './plugin.utils'
+import { PLUGIN_SUPPORTED_PLATFORMS, PluginStatus as Status } from './types/baseTypes'
+
+/** 平台账号信息映射 */
+export type PlatformAccountsMap = Record<PluginPlatformType, PlatAccountInfo | null>
+
+/** 错误消息 */
+const ERROR_MESSAGES = {
+ PLUGIN_NOT_INSTALLED: '请先安装 AIToEarn 浏览器插件',
+ PLUGIN_NOT_READY: '插件未就绪,请先授权插件权限',
+ PUBLISHING_IN_PROGRESS: '当前正在发布中,请稍后再试',
+} as const
+
+/**
+ * 生成发布标识key(用于区分不同账号的发布)
+ * @param platform 平台类型
+ * @param accountId 账号ID(可选)
+ */
+function getPublishKey(platform: PluginPlatformType, accountId?: string): string {
+ return accountId ? `${platform}-${accountId}` : platform
+}
+
+/** 平台发布进度映射,key 为 platform 或 platform-accountId */
+export type PlatformProgressMap = Map<string, ProgressEvent>
+
+/** 插件 Store 状态接口(只定义属性) */
+export interface IPluginStore {
+ status: Status
+ pollingTimer: NodeJS.Timeout | null
+ /** @deprecated 使用 publishingPlatforms 代替 */
+ isPublishing: boolean
+ /** 正在发布的集合,key 为 platform 或 platform-accountId,支持同一平台多账号同时发布 */
+ publishingPlatforms: Set<string>
+ /** @deprecated 使用 platformProgress 代替 */
+ publishProgress: ProgressEvent | null
+ /** 各平台发布进度,key 为 platform 或 platform-accountId */
+ platformProgress: PlatformProgressMap
+ publishTasks: PublishTask[]
+ taskListConfig: PublishTaskListConfig
+ platformAccounts: PlatformAccountsMap
+}
+
+const store: IPluginStore = {
+ status: Status.UNKNOWN,
+ pollingTimer: null,
+ isPublishing: false,
+ publishingPlatforms: new Set(),
+ publishProgress: null,
+ platformProgress: new Map(),
+ publishTasks: [],
+ taskListConfig: {
+ maxTasks: 100,
+ autoCleanCompleted: false,
+ cleanAfter: 24 * 60 * 60 * 1000,
+ },
+ platformAccounts: createInitialPlatformAccounts(),
+}
+
+function getStore() {
+ return lodash.cloneDeep(store)
+}
+
+/** 创建插件管理 Store */
+export const usePluginStore = create(
+ combine(
+ { ...getStore() },
+ (set, get) => {
+ const methods = {
+ clear() {
+ set({ ...getStore() })
+ },
+
+ /** 检查插件是否安装 */
+ checkPlugin() {
+ const isAvailable = typeof window !== 'undefined' && !!window.AIToEarnPlugin
+ if (!isAvailable) {
+ set({ status: Status.NOT_INSTALLED })
+ return false
+ }
+ const currentStatus = get().status
+ if (currentStatus === Status.UNKNOWN || currentStatus === Status.NOT_INSTALLED) {
+ set({ status: Status.CHECKING })
+ }
+ return true
+ },
+
+ /** 检查插件权限 */
+ async checkPermission() {
+ const isInstalled = typeof window !== 'undefined' && !!window.AIToEarnPlugin
+ if (!isInstalled) {
+ set({ status: Status.NOT_INSTALLED })
+ return false
+ }
+ try {
+ const result = await window.AIToEarnPlugin!.checkPermission()
+ if (result.granted) {
+ set({ status: Status.READY })
+ return true
+ }
+ else {
+ set({ status: Status.INSTALLED_NO_PERMISSION })
+ return false
+ }
+ }
+ catch (error) {
+ console.error('权限检查失败:', error)
+ set({ status: Status.INSTALLED_NO_PERMISSION })
+ return false
+ }
+ },
+
+ /** 开始轮询插件状态 */
+ startPolling(interval = DEFAULT_POLLING_INTERVAL) {
+ const { pollingTimer } = get()
+ if (pollingTimer)
+ methods.stopPolling()
+
+ set({ status: Status.CHECKING })
+
+ const poll = async () => {
+ const isInstalled = methods.checkPlugin()
+ if (!isInstalled)
+ return
+
+ const hasPermission = await methods.checkPermission()
+ // 已安装且已授权,停止轮询并刷新账号信息
+ if (hasPermission) {
+ methods.stopPolling()
+ await methods.refreshAllPlatformAccounts()
+ }
+ }
+
+ poll()
+ const timer = setInterval(poll, interval)
+ set({ pollingTimer: timer })
+ },
+
+ /** 停止轮询插件状态 */
+ stopPolling() {
+ const { pollingTimer } = get()
+ if (pollingTimer) {
+ clearInterval(pollingTimer)
+ set({ pollingTimer: null })
+ }
+ },
+
+ /**
+ * 初始化方法
+ * 1. 先将所有抖音和小红书账号设为离线
+ * 2. 检查插件状态,未安装或未授权则轮询,已就绪则刷新账号
+ */
+ async init() {
+ // 先将所有插件支持的平台账号设为离线
+ methods.setAllPluginAccountsOffline()
+
+ const isInstalled = methods.checkPlugin()
+ if (!isInstalled) {
+ // 未安装,开始轮询
+ methods.startPolling()
+ return
+ }
+
+ const hasPermission = await methods.checkPermission()
+ if (!hasPermission) {
+ // 未授权,开始轮询
+ methods.startPolling()
+ return
+ }
+
+ // 已就绪,刷新账号信息
+ await methods.refreshAllPlatformAccounts()
+ },
+
+ /** 将所有插件支持的平台账号设为离线 */
+ setAllPluginAccountsOffline() {
+ const { accountList, accountMap, accountAccountMap } = useAccountStore.getState()
+ let hasChange = false
+
+ const updatedAccountList = accountList.map((acc) => {
+ if (!PLUGIN_SUPPORTED_PLATFORMS.includes(acc.type as any))
+ return acc
+
+ if (acc.status !== AccountStatus.DISABLE) {
+ hasChange = true
+ const updatedAccount = { ...acc, status: AccountStatus.DISABLE }
+ accountMap.set(acc.id, updatedAccount)
+ accountAccountMap.set(acc.account, updatedAccount)
+ return updatedAccount
+ }
+ return acc
+ })
+
+ if (hasChange) {
+ useAccountStore.setState({
+ accountList: updatedAccountList,
+ accountMap: new Map(accountMap),
+ accountAccountMap: new Map(accountAccountMap),
+ })
+ }
+ },
+
+ /** 刷新所有平台账号信息,并同步更新 accountList 中的在线/离线状态 */
+ async refreshAllPlatformAccounts() {
+ const { status } = get()
+ if (status !== Status.READY)
+ return
+
+ const accounts: Partial<PlatformAccountsMap> = {}
+
+ await Promise.all(
+ PLUGIN_SUPPORTED_PLATFORMS.map(async (platform) => {
+ try {
+ accounts[platform] = await window.AIToEarnPlugin!.login(platform)
+ }
+ catch {
+ accounts[platform] = null
+ }
+ }),
+ )
+
+ set({ platformAccounts: accounts as PlatformAccountsMap })
+
+ // 根据 platformAccounts 更新 accountList 中的在线/离线状态
+ const { accountList, accountMap, accountAccountMap } = useAccountStore.getState()
+ let hasChange = false
+
+ const updatedAccountList = accountList.map((acc) => {
+ if (!PLUGIN_SUPPORTED_PLATFORMS.includes(acc.type as any))
+ return acc
+
+ const platformAccount = accounts[acc.type as keyof typeof accounts]
+ const shouldBeOnline = platformAccount?.uid === acc.uid
+ const newStatus = shouldBeOnline ? AccountStatus.USABLE : AccountStatus.DISABLE
+
+ if (acc.status !== newStatus) {
+ hasChange = true
+ const updatedAccount = { ...acc, status: newStatus }
+ accountMap.set(acc.id, updatedAccount)
+ accountAccountMap.set(acc.account, updatedAccount)
+ return updatedAccount
+ }
+ return acc
+ })
+
+ if (hasChange) {
+ useAccountStore.setState({
+ accountList: updatedAccountList,
+ accountMap: new Map(accountMap),
+ accountAccountMap: new Map(accountAccountMap),
+ })
+ }
+ },
+
+ /** 同步插件账号到数据库 */
+ async syncAccountToDatabase(platform: PluginPlatformType, groupId?: string) {
+ const { platformAccounts } = get()
+ const account = platformAccounts[platform]
+
+ if (!account) {
+ console.warn('同步账号失败:该平台未登录', platform)
+ return null
+ }
+
+ try {
+ const accountData: Partial<SocialAccount> = {
+ type: platform,
+ uid: account.uid,
+ account: account.account || account.uid,
+ avatar: account.avatar,
+ nickname: account.nickname,
+ fansCount: account.fansCount || 0,
+ loginCookie: account.loginCookie,
+ status: AccountStatus.USABLE,
+ // @ts-ignore
+ clientType: ClientType.WEB,
+ }
+
+ if (groupId)
+ accountData.groupId = groupId
+
+ const result = await createOrUpdateAccountApi(accountData)
+
+ if (result?.code === 0) {
+ await useAccountStore.getState().getAccountList()
+ return result.data || null
+ }
+ else {
+ console.error('同步账号失败:', result?.message)
+ return null
+ }
+ }
+ catch (error) {
+ console.error('同步账号到数据库失败:', error)
+ return null
+ }
+ },
+
+ /** 登录到指定平台 */
+ async login(platform: PluginPlatformType) {
+ const { status, platformAccounts } = get()
+
+ if (status === Status.NOT_INSTALLED)
+ throw new Error(ERROR_MESSAGES.PLUGIN_NOT_INSTALLED)
+
+ if (status !== Status.READY)
+ throw new Error(ERROR_MESSAGES.PLUGIN_NOT_READY)
+
+ try {
+ const result = await window.AIToEarnPlugin!.login(platform)
+ set({
+ platformAccounts: { ...platformAccounts, [platform]: result },
+ })
+ return result
+ }
+ catch (error) {
+ console.error('登录失败:', error)
+ throw error
+ }
+ },
+
+ /** 发布内容到指定平台 */
+ async publish(params: PublishParams, onProgress?: ProgressCallback) {
+ const { status, publishingPlatforms, platformProgress } = get()
+ const platform = params.platform
+ const accountId = params.accountId
+ // 使用 platform + accountId 作为唯一标识,支持同一平台多账号同时发布
+ const publishKey = getPublishKey(platform, accountId)
+
+ if (status === Status.NOT_INSTALLED)
+ throw new Error(ERROR_MESSAGES.PLUGIN_NOT_INSTALLED)
+
+ if (status !== Status.READY)
+ throw new Error(ERROR_MESSAGES.PLUGIN_NOT_READY)
+
+ // 检查该账号是否正在发布(同一平台不同账号可以同时发布)
+ if (publishingPlatforms.has(publishKey))
+ throw new Error(`${platform} ${ERROR_MESSAGES.PUBLISHING_IN_PROGRESS}`)
+
+ // 标记该账号正在发布,并初始化进度
+ const newPublishingPlatforms = new Set(publishingPlatforms)
+ newPublishingPlatforms.add(publishKey)
+ const newPlatformProgress = new Map(platformProgress)
+ const initialProgress: ProgressEvent = { stage: 'download', progress: 0, message: '准备发布...', timestamp: Date.now() }
+ newPlatformProgress.set(publishKey, initialProgress)
+
+ set({
+ isPublishing: newPublishingPlatforms.size > 0,
+ publishingPlatforms: newPublishingPlatforms,
+ publishProgress: initialProgress, // 兼容旧代码
+ platformProgress: newPlatformProgress,
+ })
+
+ try {
+ const result = await window.AIToEarnPlugin!.publish(params, (progress) => {
+ // 更新该账号的进度
+ const updatedProgress = new Map(get().platformProgress)
+ updatedProgress.set(publishKey, progress)
+ set({
+ publishProgress: progress, // 兼容旧代码
+ platformProgress: updatedProgress,
+ })
+ onProgress?.(progress)
+ })
+
+ // 发布完成,移除该账号的发布状态,更新进度为完成
+ const updatedPlatforms = new Set(get().publishingPlatforms)
+ updatedPlatforms.delete(publishKey)
+ const completedProgress: ProgressEvent = { stage: 'complete', progress: 100, message: '发布成功', timestamp: Date.now() }
+ const updatedPlatformProgress = new Map(get().platformProgress)
+ updatedPlatformProgress.set(publishKey, completedProgress)
+
+ set({
+ isPublishing: updatedPlatforms.size > 0,
+ publishingPlatforms: updatedPlatforms,
+ publishProgress: completedProgress, // 兼容旧代码
+ platformProgress: updatedPlatformProgress,
+ })
+
+ return result
+ }
+ catch (error) {
+ // 发布失败,移除该账号的发布状态,更新进度为错误
+ const updatedPlatforms = new Set(get().publishingPlatforms)
+ updatedPlatforms.delete(publishKey)
+ const errorProgress: ProgressEvent = {
+ stage: 'error',
+ progress: 0,
+ message: error instanceof Error ? error.message : '发布失败',
+ timestamp: Date.now(),
+ }
+ const updatedPlatformProgress = new Map(get().platformProgress)
+ updatedPlatformProgress.set(publishKey, errorProgress)
+
+ set({
+ isPublishing: updatedPlatforms.size > 0,
+ publishingPlatforms: updatedPlatforms,
+ publishProgress: errorProgress, // 兼容旧代码
+ platformProgress: updatedPlatformProgress,
+ })
+ console.error('发布失败:', error)
+ throw error
+ }
+ },
+
+ /** 重置发布状态 */
+ resetPublishState() {
+ set({
+ isPublishing: false,
+ publishingPlatforms: new Set(),
+ publishProgress: null,
+ platformProgress: new Map(),
+ })
+ },
+
+ /** 获取指定平台/账号的发布进度 */
+ getPlatformProgress(platform: PluginPlatformType, accountId?: string) {
+ const publishKey = getPublishKey(platform, accountId)
+ return get().platformProgress.get(publishKey) || null
+ },
+
+ /** 清除指定平台/账号的发布进度 */
+ clearPlatformProgress(platform: PluginPlatformType, accountId?: string) {
+ const publishKey = getPublishKey(platform, accountId)
+ const updatedProgress = new Map(get().platformProgress)
+ updatedProgress.delete(publishKey)
+ set({ platformProgress: updatedProgress })
+ },
+
+ /** 添加发布任务 */
+ addPublishTask(task: Omit<PublishTask, 'id' | 'createdAt' | 'updatedAt' | 'overallStatus'>) {
+ const id = generateId()
+ const now = Date.now()
+
+ const newTask: PublishTask = {
+ ...task,
+ id,
+ createdAt: now,
+ updatedAt: now,
+ overallStatus: calculateOverallStatus(task.platformTasks),
+ }
+
+ set((state) => {
+ const tasks = [newTask, ...state.publishTasks]
+ if (state.taskListConfig.maxTasks && tasks.length > state.taskListConfig.maxTasks) {
+ tasks.splice(state.taskListConfig.maxTasks)
+ }
+ return { publishTasks: tasks }
+ })
+
+ return id
+ },
+
+ /**
+ * 更新平台任务(使用平台任务ID精确匹配)
+ * @param taskId 发布任务ID
+ * @param platformTaskId 平台任务ID(精确匹配)
+ * @param updates 更新内容
+ */
+ updatePlatformTask(
+ taskId: string,
+ platformTaskId: string,
+ updates: Partial<PlatformPublishTask>,
+ ) {
+ set((state) => {
+ const tasks = state.publishTasks.map((task) => {
+ if (task.id !== taskId)
+ return task
+
+ const platformTasks = task.platformTasks.map((pt: PlatformPublishTask) => {
+ // 使用平台任务ID精确匹配
+ if (pt.id !== platformTaskId)
+ return pt
+ return { ...pt, ...updates }
+ })
+
+ return {
+ ...task,
+ platformTasks,
+ updatedAt: Date.now(),
+ overallStatus: calculateOverallStatus(platformTasks),
+ }
+ })
+ return { publishTasks: tasks }
+ })
+ },
+
+ /**
+ * 通过 requestId 更新平台任务进度(插件回调使用)
+ * @param requestId 插件返回的请求ID
+ * @param updates 更新内容
+ */
+ updatePlatformTaskByRequestId(
+ requestId: string,
+ updates: Partial<PlatformPublishTask>,
+ ) {
+ set((state) => {
+ const tasks = state.publishTasks.map((task) => {
+ // 在该任务的所有平台任务中查找匹配的 requestId
+ const hasMatch = task.platformTasks.some(pt => pt.requestId === requestId)
+
+ if (!hasMatch)
+ return task
+
+ const platformTasks = task.platformTasks.map((pt: PlatformPublishTask) => {
+ // 使用 requestId 精确匹配
+ if (pt.requestId !== requestId)
+ return pt
+ return { ...pt, ...updates }
+ })
+
+ return {
+ ...task,
+ platformTasks,
+ updatedAt: Date.now(),
+ overallStatus: calculateOverallStatus(platformTasks),
+ }
+ })
+ return { publishTasks: tasks }
+ })
+ },
+
+ /** 删除发布任务 */
+ deletePublishTask(taskId: string) {
+ set(state => ({
+ publishTasks: state.publishTasks.filter(task => task.id !== taskId),
+ }))
+ },
+
+ /** 清空所有任务 */
+ clearPublishTasks() {
+ set({ publishTasks: [] })
+ },
+
+ /** 获取任务详情 */
+ getPublishTask(taskId: string) {
+ return get().publishTasks.find(task => task.id === taskId)
+ },
+
+ /** 更新任务列表配置 */
+ updateTaskListConfig(config: Partial<PublishTaskListConfig>) {
+ set(state => ({
+ taskListConfig: { ...state.taskListConfig, ...config },
+ }))
+ },
+ }
+
+ return methods
+ },
+ ),
+)
diff --git a/project/web/src/store/plugin/types/baseTypes.ts b/project/web/src/store/plugin/types/baseTypes.ts
new file mode 100644
index 00000000..34817d20
--- /dev/null
+++ b/project/web/src/store/plugin/types/baseTypes.ts
@@ -0,0 +1,153 @@
+/**
+ * 浏览器插件相关类型定义
+ */
+
+import type {
+ PublishParams as BasePublishParams,
+ PlatformPublishTask,
+ ProgressEvent,
+ PublishTask,
+ PublishTaskListConfig,
+} from './index'
+import type { PlatAccountInfo } from './plat.type'
+import { PlatType } from '@/app/config/platConfig'
+
+// 导出任务相关类型
+export type { PlatformPublishTask, PublishTask, PublishTaskListConfig }
+export { PlatformTaskStatus } from './publishTask.types'
+
+/**
+ * 发布结果
+ */
+interface PublishResult {
+ success: boolean
+ workId?: string
+ shareLink?: string
+ publishTime?: number
+ failReason?: string
+ errorCode?: string
+}
+
+/**
+ * 导出基础类型
+ */
+export type { PlatAccountInfo, ProgressEvent, PublishResult }
+
+/**
+ * 插件连接状态
+ */
+export enum PluginStatus {
+ /** 未检测 */
+ UNKNOWN = 'UNKNOWN',
+ /** 检测中 */
+ CHECKING = 'CHECKING',
+ /** 已就绪(已安装且已授权) */
+ READY = 'READY',
+ /** 已安装但未授权 */
+ INSTALLED_NO_PERMISSION = 'INSTALLED_NO_PERMISSION',
+ /** 未安装 */
+ NOT_INSTALLED = 'NOT_INSTALLED',
+ /** 已连接(兼容旧代码) */
+ CONNECTED = 'READY',
+}
+
+/**
+ * 插件支持的平台列表
+ */
+export const PLUGIN_SUPPORTED_PLATFORMS = [
+ PlatType.Douyin,
+ PlatType.Xhs,
+] as const
+
+/**
+ * 插件支持的平台类型(直接复用 PlatType)
+ */
+export type PluginPlatformType = typeof PLUGIN_SUPPORTED_PLATFORMS[number]
+
+/**
+ * 发布参数(扩展基础类型,添加 platform 字段)
+ */
+export interface PublishParams extends BasePublishParams {
+ platform: PluginPlatformType
+}
+
+/**
+ * 进度回调函数类型
+ */
+export type ProgressCallback = (event: ProgressEvent) => void
+
+/**
+ * 权限检查结果
+ */
+export interface PermissionCheckResult {
+ /** 是否已授予所有必需权限 */
+ granted: boolean
+ /** 已授予的权限列表 */
+ permissions?: string[]
+}
+
+/**
+ * 插件 API 接口定义
+ */
+export interface AIToEarnPluginAPI {
+ /**
+ * 检查插件权限
+ * @returns Promise<权限检查结果>
+ */
+ checkPermission: () => Promise<PermissionCheckResult>
+
+ /**
+ * 登录到指定平台
+ * @param platform 平台类型
+ * @returns Promise<账号信息>
+ */
+ login: (platform: PluginPlatformType) => Promise<PlatAccountInfo>
+
+ /**
+ * 发布内容到指定平台
+ * @param params 发布参数
+ * @param onProgress 进度回调函数
+ * @returns Promise<发布结果>
+ */
+ publish: (
+ params: PublishParams,
+ onProgress?: ProgressCallback,
+ ) => Promise<PublishResult>
+}
+
+/**
+ * 扩展 Window 接口
+ */
+declare global {
+ interface Window {
+ // @ts-ignore
+ AIToEarnPlugin?: AIToEarnPluginAPI
+ }
+}
+
+/**
+ * 插件 Store 状态接口(只定义属性,方法在 store 中实现)
+ */
+export interface PluginStore {
+ /** 插件连接状态 */
+ status: PluginStatus
+ /** 轮询定时器 ID */
+ pollingTimer: NodeJS.Timeout | null
+ /** 是否正在发布 */
+ isPublishing: boolean
+ /** 当前发布进度 */
+ publishProgress: ProgressEvent | null
+ /** 发布任务列表 */
+ publishTasks?: PublishTask[]
+ /** 任务列表配置 */
+ taskListConfig?: PublishTaskListConfig
+}
+
+/**
+ * 操作结果类型
+ */
+export interface OperationResult<T = any> {
+ success: boolean
+ data?: T
+ error?: string
+}
diff --git a/project/web/src/store/plugin/types/index.ts b/project/web/src/store/plugin/types/index.ts
new file mode 100644
index 00000000..4c866b56
--- /dev/null
+++ b/project/web/src/store/plugin/types/index.ts
@@ -0,0 +1,8 @@
+/**
+ * 类型定义统一导出
+ */
+
+export * from './plat.type'
+export * from './progress.types'
+export * from './publish.types'
+export * from './publishTask.types'
diff --git a/project/web/src/store/plugin/types/plat.type.ts b/project/web/src/store/plugin/types/plat.type.ts
new file mode 100644
index 00000000..0b0a7314
--- /dev/null
+++ b/project/web/src/store/plugin/types/plat.type.ts
@@ -0,0 +1,11 @@
+import type { PluginPlatformType } from '@/store/plugin/types/baseTypes'
+
+export interface PlatAccountInfo {
+ type: PluginPlatformType
+ loginCookie: string
+ uid: string
+ account: string
+ avatar: string
+ nickname: string
+ fansCount?: number
+}
diff --git a/project/web/src/store/plugin/types/progress.types.ts b/project/web/src/store/plugin/types/progress.types.ts
new file mode 100644
index 00000000..cf74c95b
--- /dev/null
+++ b/project/web/src/store/plugin/types/progress.types.ts
@@ -0,0 +1,105 @@
+/**
+ * 进度事件类型定义
+ */
+
+/**
+ * 发布阶段
+ */
+export type PublishStage
+ = | 'download'
+ | 'upload'
+ | 'publish'
+ | 'complete'
+ | 'error'
+
+/**
+ * 进度事件
+ */
+export interface ProgressEvent {
+ /** 当前阶段 */
+ stage: PublishStage
+
+ /** 进度百分比 (0-100) */
+ progress: number
+
+ /** 进度消息 */
+ message?: string
+
+ /** 请求ID(用于区分不同的发布任务) */
+ requestId?: string
+
+ /** 附加数据 */
+ data?: any
+
+ /** 时间戳 */
+ timestamp?: number
+}
+
+/**
+ * 下载进度事件
+ */
+export interface DownloadProgressEvent extends ProgressEvent {
+ stage: 'download'
+ data?: {
+ /** 已下载字节数 */
+ loaded: number
+ /** 总字节数 */
+ total: number
+ /** 下载速度 (bytes/s) */
+ speed?: number
+ }
+}
+
+/**
+ * 上传进度事件
+ */
+export interface UploadProgressEvent extends ProgressEvent {
+ stage: 'upload'
+ data?: {
+ /** 已上传字节数 */
+ loaded: number
+ /** 总字节数 */
+ total: number
+ /** 当前分片索引 */
+ chunkIndex?: number
+ /** 总分片数 */
+ totalChunks?: number
+ }
+}
+
+/**
+ * 发布进度事件
+ */
+export interface PublishProgressEvent extends ProgressEvent {
+ stage: 'publish'
+ data?: {
+ /** 发布步骤 */
+ step: 'preparing' | 'signing' | 'submitting' | 'verifying'
+ }
+}
+
+/**
+ * 完成事件
+ */
+export interface CompleteEvent extends ProgressEvent {
+ stage: 'complete'
+ data?: {
+ /** 作品ID */
+ workId: string
+ /** 分享链接 */
+ shareLink?: string
+ }
+}
+
+/**
+ * 错误事件
+ */
+export interface ErrorEvent extends ProgressEvent {
+ stage: 'error'
+ data?: {
+ /** 错误代码 */
+ code?: string
+ /** 错误详情 */
+ error: Error
+ }
+}
diff --git a/project/web/src/store/plugin/types/publish.types.ts b/project/web/src/store/plugin/types/publish.types.ts
new file mode 100644
index 00000000..38ea0c50
--- /dev/null
+++ b/project/web/src/store/plugin/types/publish.types.ts
@@ -0,0 +1,100 @@
+/**
+ * 发布参数类型定义
+ */
+
+/**
+ * 发布类型
+ */
+export type PublishType = 'video' | 'image'
+
+/**
+ * 可见性类型
+ */
+export type VisibilityType = 'public' | 'private' | 'friends'
+
+/**
+ * 位置信息
+ */
+export interface LocationInfo {
+ /** 位置ID */
+ id: string
+ /** 位置名称 */
+ name: string
+ /** 位置类型 */
+ poiType?: number
+ /** 详细地址 */
+ address?: string
+ /** 简短地址 */
+ simpleAddress?: string
+ /** 纬度 */
+ latitude?: number
+ /** 经度 */
+ longitude?: number
+}
+
+/**
+ * @用户信息
+ */
+export interface MentionUserInfo {
+ /** 用户ID */
+ id: string
+ /** 用户昵称 */
+ nickname: string
+}
+
+/**
+ * 发布参数
+ */
+export interface PublishParams {
+ /** 发布类型 */
+ type: PublishType
+
+ /** 账号ID(用于区分同一平台的多个账号) */
+ accountId?: string
+
+ /** 请求ID(用于进度回调匹配,由调用方生成) */
+ requestId?: string
+
+ /** 标题 */
+ title?: string
+
+ /** 描述/正文 */
+ desc?: string
+
+ /** 视频文件或URL(发布视频时必需) */
+ video?: File | string
+
+ /** 图片文件或URL数组(发布图文时必需) */
+ images?: (File | string)[]
+
+ /** 封面图片(视频发布时必需) */
+ cover?: File | string
+
+ /** 话题标签 */
+ topics?: string[]
+
+ /** 位置信息 */
+ location?: LocationInfo
+
+ /** 可见性 */
+ visibility?: VisibilityType
+
+ /** @的用户 */
+ mentionedUsers?: MentionUserInfo[]
+
+ /** 定时发布时间戳(毫秒) */
+ scheduledTime?: number
+
+ /** 平台特定配置 */
+ platformConfig?: Record<string, any>
+}
+
+/**
+ * 参数验证结果
+ */
+export interface ValidationResult {
+ /** 是否有效 */
+ valid: boolean
+ /** 错误信息 */
+ errors?: string[]
+}
diff --git a/project/web/src/store/plugin/types/publishTask.types.ts b/project/web/src/store/plugin/types/publishTask.types.ts
new file mode 100644
index 00000000..016f5d68
--- /dev/null
+++ b/project/web/src/store/plugin/types/publishTask.types.ts
@@ -0,0 +1,97 @@
+/**
+ * 发布任务相关类型定义
+ */
+
+import type { PluginPlatformType, ProgressEvent, PublishParams, PublishResult } from './baseTypes'
+
+/**
+ * 平台发布任务状态
+ */
+export enum PlatformTaskStatus {
+ /** 待发布 */
+ PENDING = 'pending',
+ /** 发布中 */
+ PUBLISHING = 'publishing',
+ /** 已完成 */
+ COMPLETED = 'completed',
+ /** 失败 */
+ ERROR = 'error',
+}
+
+/**
+ * 单个平台的发布任务
+ */
+export interface PlatformPublishTask {
+ /** 任务唯一ID(用于精确匹配更新) */
+ id: string
+
+ /** 插件返回的请求ID(用于匹配进度回调) */
+ requestId?: string
+
+ /** 平台类型 */
+ platform: PluginPlatformType
+
+ /** 账号ID,用于关联账号信息 */
+ accountId?: string
+
+ /** 发布参数 */
+ params: PublishParams
+
+ /** 任务状态 */
+ status: PlatformTaskStatus
+
+ /** 进度信息 */
+ progress: ProgressEvent | null
+
+ /** 发布结果 */
+ result: PublishResult | null
+
+ /** 开始时间 */
+ startTime: number | null
+
+ /** 结束时间 */
+ endTime: number | null
+
+ /** 错误信息 */
+ error: string | null
+}
+
+/**
+ * 发布任务(包含多个平台)
+ */
+export interface PublishTask {
+ /** 任务ID */
+ id: string
+
+ /** 任务标题(用于展示) */
+ title: string
+
+ /** 任务描述 */
+ description?: string
+
+ /** 包含的平台任务列表 */
+ platformTasks: PlatformPublishTask[]
+
+ /** 创建时间 */
+ createdAt: number
+
+ /** 更新时间 */
+ updatedAt: number
+
+ /** 整体任务状态 */
+ overallStatus: PlatformTaskStatus
+}
+
+/**
+ * 发布任务列表配置
+ */
+export interface PublishTaskListConfig {
+ /** 最大保存任务数 */
+ maxTasks?: number
+
+ /** 是否自动清理已完成任务 */
+ autoCleanCompleted?: boolean
+
+ /** 自动清理的时间(毫秒,默认24小时) */
+ cleanAfter?: number
+}
diff --git a/project/web/src/store/plugin/utils.ts b/project/web/src/store/plugin/utils.ts
new file mode 100644
index 00000000..63f657a0
--- /dev/null
+++ b/project/web/src/store/plugin/utils.ts
@@ -0,0 +1,179 @@
+/**
+ * 浏览器插件相关工具函数
+ */
+
+import type { ProgressEvent } from '@/store'
+import { PluginStatus } from '@/store'
+import { PLUGIN_STATUS_I18N_KEY, PUBLISH_STAGE_I18N_KEY } from './constants'
+
+/**
+ * 获取插件状态的国际化 key
+ * @param status 插件状态
+ * @returns i18n key
+ */
+export function getPluginStatusI18nKey(status: PluginStatus): string {
+ return PLUGIN_STATUS_I18N_KEY[status] || 'plugin:status.unknown'
+}
+
+/**
+ * 获取发布阶段的国际化 key
+ * @param stage 发布阶段
+ * @returns i18n key
+ */
+export function getPublishStageI18nKey(
+ stage: ProgressEvent['stage'],
+): string {
+ return PUBLISH_STAGE_I18N_KEY[stage] || stage
+}
+
+/**
+ * 判断插件是否已就绪(已安装且已授权)
+ * @param status 插件状态
+ * @returns 是否已就绪
+ */
+export function isPluginReady(status: PluginStatus): boolean {
+ return status === PluginStatus.READY
+}
+
+/**
+ * 判断插件是否已连接(兼容旧代码,等同于 isPluginReady)
+ * @param status 插件状态
+ * @returns 是否已连接
+ */
+export function isPluginConnected(status: PluginStatus): boolean {
+ return status === PluginStatus.READY
+}
+
+/**
+ * 判断插件是否已安装但未授权
+ * @param status 插件状态
+ * @returns 是否已安装未授权
+ */
+export function isPluginInstalledNoPermission(status: PluginStatus): boolean {
+ return status === PluginStatus.INSTALLED_NO_PERMISSION
+}
+
+/**
+ * 判断插件是否未安装
+ * @param status 插件状态
+ * @returns 是否未安装
+ */
+export function isPluginNotInstalled(status: PluginStatus): boolean {
+ return status === PluginStatus.NOT_INSTALLED || status === PluginStatus.UNKNOWN
+}
+
+/**
+ * 格式化进度百分比
+ * @param progress 进度值(0-100)
+ * @returns 格式化的百分比文本
+ */
+export function formatProgress(progress: number): string {
+ return `${Math.round(progress)}%`
+}
+
+/**
+ * 格式化文件大小
+ * @param bytes 字节数
+ * @returns 格式化的文件大小
+ */
+export function formatFileSize(bytes: number): string {
+ if (bytes === 0)
+ return '0 B'
+
+ const k = 1024
+ const sizes = ['B', 'KB', 'MB', 'GB']
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+
+ return `${(bytes / k ** i).toFixed(2)} ${sizes[i]}`
+}
+
+/**
+ * 验证文件类型
+ * @param file 文件对象
+ * @param acceptTypes 接受的文件类型数组
+ * @returns 是否有效
+ */
+export function validateFileType(
+ file: File,
+ acceptTypes: string[],
+): boolean {
+ return acceptTypes.some((type) => {
+ if (type.endsWith('/*')) {
+ const prefix = type.slice(0, -2)
+ return file.type.startsWith(prefix)
+ }
+ return file.type === type
+ })
+}
+
+/**
+ * 验证视频文件
+ * @param file 文件对象
+ * @returns 是否是有效的视频文件
+ */
+export function isValidVideoFile(file: File): boolean {
+ return validateFileType(file, [
+ 'video/mp4',
+ 'video/mpeg',
+ 'video/quicktime',
+ 'video/x-msvideo',
+ 'video/x-ms-wmv',
+ ])
+}
+
+/**
+ * 验证图片文件
+ * @param file 文件对象
+ * @returns 是否是有效的图片文件
+ */
+export function isValidImageFile(file: File): boolean {
+ return validateFileType(file, [
+ 'image/jpeg',
+ 'image/png',
+ 'image/gif',
+ 'image/webp',
+ 'image/jpg',
+ ])
+}
+
+/**
+ * 验证文件大小
+ * @param file 文件对象
+ * @param maxSize 最大大小(字节)
+ * @returns 是否在限制内
+ */
+export function validateFileSize(file: File, maxSize: number): boolean {
+ return file.size <= maxSize
+}
+
+/**
+ * 创建带重试的异步函数
+ * @param fn 异步函数
+ * @param maxRetries 最大重试次数
+ * @param delay 重试延迟(毫秒)
+ * @returns 包装后的函数
+ */
+export function withRetry<T>(
+ fn: () => Promise<T>,
+ maxRetries = 3,
+ delay = 1000,
+): () => Promise<T> {
+ return async () => {
+ let lastError: any
+
+ for (let i = 0; i < maxRetries; i++) {
+ try {
+ return await fn()
+ }
+ catch (error) {
+ lastError = error
+
+ if (i < maxRetries - 1) {
+ await new Promise(resolve => setTimeout(resolve, delay))
+ }
+ }
+ }
+
+ throw lastError
+ }
+}