Skip to content

Let's use AI to Earn!

refactor(publishing): consolidate social media API error handling and retry strategy in publishing (#188)

Sakura604e52f76afa
diff --git a/project/backend/apps/aitoearn-channel/src/common/guards/sk-key-auth.guard.ts b/project/backend/apps/aitoearn-channel/src/common/guards/sk-key-auth.guard.ts
new file mode 100644
index 00000000..ecd45051
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/common/guards/sk-key-auth.guard.ts
@@ -0,0 +1,45 @@
+import {
+ CanActivate,
+ createParamDecorator,
+ ExecutionContext,
+ Injectable,
+ Logger,
+ UnauthorizedException,
+} from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { SkKeyService } from '../../core/sk-key/sk-key.service'
+
+export const GetSkKey = createParamDecorator(
+ (data: string, ctx: ExecutionContext) => {
+ const req = ctx.switchToHttp().getRequest()
+ return req['skKey']
+ },
+)
+
+@Injectable()
+export class SkKeyAuthGuard implements CanActivate {
+ private readonly logger = new Logger(SkKeyAuthGuard.name)
+ constructor(
+ private reflector: Reflector,
+ private readonly skKeyService: SkKeyService,
+ ) {}
+
+ async canActivate(context: ExecutionContext): Promise<boolean> {
+ const request = context.switchToHttp().getRequest()
+ // 获取令牌sk
+ const key = request.headers['sk-key'] || request.query['sk-key']
+
+ try {
+ const keyInfo = await this.skKeyService.getInfo(key)
+ if (!keyInfo) {
+ throw new UnauthorizedException('令牌验证失败')
+ }
+ request['skKey'] = keyInfo
+ }
+ catch (error) {
+ this.logger.error(error)
+ throw new UnauthorizedException('令牌验证失败')
+ }
+ return true
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/common/guards/skKeyAuth.guard.ts b/project/backend/apps/aitoearn-channel/src/common/guards/skKeyAuth.guard.ts
index 73372e6e..ecd45051 100644
--- a/project/backend/apps/aitoearn-channel/src/common/guards/skKeyAuth.guard.ts
+++ b/project/backend/apps/aitoearn-channel/src/common/guards/skKeyAuth.guard.ts
@@ -7,7 +7,7 @@ import {
UnauthorizedException,
} from '@nestjs/common'
import { Reflector } from '@nestjs/core'
-import { SkKeyService } from '../../core/skKey/skKey.service'
+import { SkKeyService } from '../../core/sk-key/sk-key.service'
export const GetSkKey = createParamDecorator(
(data: string, ctx: ExecutionContext) => {
diff --git a/project/backend/apps/aitoearn-channel/src/core/account/account.module.ts b/project/backend/apps/aitoearn-channel/src/core/account/account.module.ts
index 5288288b..e843c049 100644
--- a/project/backend/apps/aitoearn-channel/src/core/account/account.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/account/account.module.ts
@@ -2,7 +2,7 @@ import { Global, Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { Account, AccountSchema } from '../../libs/database/schema/account.schema'
import { AccountService } from './account.service'
-import { PublishRecordService } from './publishRecord.service'
+import { PublishRecordService } from './publish-record.service'
@Global()
@Module({
diff --git a/project/backend/apps/aitoearn-channel/src/core/account/publishRecord.service.ts b/project/backend/apps/aitoearn-channel/src/core/account/publish-record.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/account/publishRecord.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/account/publish-record.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/core.module.ts b/project/backend/apps/aitoearn-channel/src/core/core.module.ts
index 306b1b2e..52e58c1d 100644
--- a/project/backend/apps/aitoearn-channel/src/core/core.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/core.module.ts
@@ -1,21 +1,18 @@
import { Module } from '@nestjs/common'
-import { McpModule as TheMcpModule } from '@rekog/mcp-nest'
-import { SkKeyAuthGuard } from '../common/guards/skKeyAuth.guard'
import { AliGreenModule } from '../core/ali-green/ali-green.module'
-import { PublishModule } from '../core/publish/publish.module'
import { AccountModule } from './account/account.module'
-import { DataCubeModule } from './dataCube/dataCube.module'
+import { DataCubeModule } from './data-cube/data-cube.module'
import { EngagementModule } from './engagement/engagement.module'
import { FileModule } from './file/file.module'
import { InteracteModule } from './interact/interact.module'
-import { McpModule } from './mcp/mcp.module'
-import { MetaModule } from './plat/meta/meta.module'
-import { PlatModule } from './plat/plat.module'
-import { TiktokModule } from './plat/tiktok/tiktok.module'
-import { TwitterModule } from './plat/twitter/twitter.module'
-import { WxPlatModule } from './plat/wxPlat/wxPlat.module'
-import { YoutubeModule } from './plat/youtube/youtube.module'
-import { SkKeyModule } from './skKey/skKey.module'
+import { MetaModule } from './platforms/meta/meta.module'
+import { PlatModule } from './platforms/platforms.module'
+import { TiktokModule } from './platforms/tiktok/tiktok.module'
+import { TwitterModule } from './platforms/twitter/twitter.module'
+import { WxPlatModule } from './platforms/wx-plat/wx-plat.module'
+import { YoutubeModule } from './platforms/youtube/youtube.module'
+import { PublishModule } from './publishing/publishing.module'
+import { SkKeyModule } from './sk-key/sk-key.module'
import { TestModule } from './test/test.module'
@Module({
@@ -23,12 +20,6 @@ import { TestModule } from './test/test.module'
TestModule,
FileModule,
SkKeyModule,
- McpModule,
- TheMcpModule.forRoot({
- name: 'channel-mcp-server',
- version: '1.0.0',
- guards: [SkKeyAuthGuard],
- }),
AccountModule,
PublishModule,
TwitterModule,
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/bilibiliData.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/bilibili-data.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/bilibiliData.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/bilibili-data.service.ts
index 3795dad2..781f20c4 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/bilibiliData.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/bilibili-data.service.ts
@@ -8,7 +8,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { BilibiliService } from '../plat/bilibili/bilibili.service'
+import { BilibiliService } from '../platforms/bilibili/bilibili.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.controller.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.controller.ts
similarity index 91%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.controller.ts
index 8a8767f6..2ebbcdb5 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.controller.ts
@@ -9,11 +9,11 @@ import { Body, Controller, Post } from '@nestjs/common'
import { AccountType } from '@yikart/aitoearn-server-client'
import { AppException, ResponseCode } from '@yikart/common'
import { AccountService } from '../account/account.service'
-import { BilibiliDataService } from './bilibiliData.service'
+import { BilibiliDataService } from './bilibili-data.service'
import { DataCubeBase } from './data.base'
-import { AccountDto, ArcDto } from './dto/dataCube.dto'
-import { WxGzhDataService } from './wxGzhData.service'
-import { YoutubeDataService } from './youtubeData.service'
+import { AccountDto, ArcDto } from './dto/data-cube.dto'
+import { WxGzhDataService } from './wx-gzh-data.service'
+import { YoutubeDataService } from './youtube-data.service'
@Controller()
export class DataCubeController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.module.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.module.ts
new file mode 100644
index 00000000..d48855ab
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/data-cube.module.ts
@@ -0,0 +1,23 @@
+import { Module } from '@nestjs/common'
+import { PinterestDataService } from '../../core/data-cube/pinterest-data.service'
+import { PinterestModule } from '../../core/platforms/pinterest/pinterest.module'
+import { AccountModule } from '../account/account.module'
+import { BilibiliModule } from '../platforms/bilibili/bilibili.module'
+import { MetaModule } from '../platforms/meta/meta.module'
+import { WxPlatModule } from '../platforms/wx-plat/wx-plat.module'
+import { YoutubeModule } from '../platforms/youtube/youtube.module'
+import { BilibiliDataService } from './bilibili-data.service'
+import { DataCubeController } from './data-cube.controller'
+import { FacebookDataService } from './facebook-data.service'
+import { InstagramDataService } from './instagram.service'
+import { ThreadsDataService } from './threads.service'
+import { WxGzhDataService } from './wx-gzh-data.service'
+import { YoutubeDataService } from './youtube-data.service'
+
+@Module({
+ imports: [BilibiliModule, MetaModule, YoutubeModule, WxPlatModule, PinterestModule, AccountModule],
+ controllers: [DataCubeController],
+ providers: [BilibiliDataService, FacebookDataService, InstagramDataService, ThreadsDataService, YoutubeDataService, WxGzhDataService, PinterestDataService],
+ exports: [BilibiliDataService, FacebookDataService, InstagramDataService, ThreadsDataService, YoutubeDataService, WxGzhDataService, PinterestDataService],
+})
+export class DataCubeModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/data.base.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/data.base.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/data.base.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/data.base.ts
index 982d2fa5..af850194 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/data.base.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/data.base.ts
@@ -3,7 +3,7 @@ import {
ChannelAccountDataCube,
ChannelArcDataBulk,
ChannelArcDataCube,
-} from '../plat/common'
+} from '../platforms/common'
export abstract class DataCubeBase {
/**
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/dto/dataCube.dto.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/dto/data-cube.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/dto/dataCube.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/dto/data-cube.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/facebookData.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/facebook-data.service.ts
similarity index 95%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/facebookData.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/facebook-data.service.ts
index 50855b73..d567039b 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/facebookData.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/facebook-data.service.ts
@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { FacebookService } from '../plat/meta/facebook.service'
+import { FacebookService } from '../platforms/meta/facebook.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/instagram.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/instagram.service.ts
similarity index 97%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/instagram.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/instagram.service.ts
index 308f8771..398414d0 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/instagram.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/instagram.service.ts
@@ -2,7 +2,7 @@ import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
import { InstagramInsightsRequest, InstagramMediaInsightsRequest } from '../../libs/instagram/instagram.interfaces'
-import { InstagramService } from '../plat/meta/instagram.service'
+import { InstagramService } from '../platforms/meta/instagram.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/pinterestData.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/pinterest-data.service.ts
similarity index 95%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/pinterestData.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/pinterest-data.service.ts
index f7f2e79f..76b3f490 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/pinterestData.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/pinterest-data.service.ts
@@ -8,7 +8,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { PinterestService } from '../../core/plat/pinterest/pinterest.service'
+import { PinterestService } from '../../core/platforms/pinterest/pinterest.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/threads.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/threads.service.ts
similarity index 97%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/threads.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/threads.service.ts
index 5f5774b2..af3c5eda 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/threads.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/threads.service.ts
@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { ThreadsService } from '../plat/meta/threads.service'
+import { ThreadsService } from '../platforms/meta/threads.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/wxGzhData.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/wx-gzh-data.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/wxGzhData.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/wx-gzh-data.service.ts
index add95e87..e343e52e 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/wxGzhData.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/wx-gzh-data.service.ts
@@ -9,7 +9,7 @@ import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
import dayjs from 'dayjs'
-import { WxGzhService } from '../plat/wxPlat/wxGzh.service'
+import { WxGzhService } from '../platforms/wx-plat/wx-gzh.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/youtubeData.service.ts b/project/backend/apps/aitoearn-channel/src/core/data-cube/youtube-data.service.ts
similarity index 97%
rename from project/backend/apps/aitoearn-channel/src/core/dataCube/youtubeData.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/data-cube/youtube-data.service.ts
index ac5d579b..9c855424 100644
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/youtubeData.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/data-cube/youtube-data.service.ts
@@ -8,7 +8,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { OnEvent } from '@nestjs/event-emitter'
import { AccountType, AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { YoutubeService } from '../plat/youtube/youtube.service'
+import { YoutubeService } from '../platforms/youtube/youtube.service'
import { DataCubeBase } from './data.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.module.ts b/project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.module.ts
deleted file mode 100644
index 985140cd..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/dataCube/dataCube.module.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Module } from '@nestjs/common'
-import { PinterestDataService } from '../../core/dataCube/pinterestData.service'
-import { PinterestModule } from '../../core/plat/pinterest/pinterest.module'
-import { AccountModule } from '../account/account.module'
-import { BilibiliModule } from '../plat/bilibili/bilibili.module'
-import { MetaModule } from '../plat/meta/meta.module'
-import { WxPlatModule } from '../plat/wxPlat/wxPlat.module'
-import { YoutubeModule } from '../plat/youtube/youtube.module'
-import { BilibiliDataService } from './bilibiliData.service'
-import { DataCubeController } from './dataCube.controller'
-import { FacebookDataService } from './facebookData.service'
-import { InstagramDataService } from './instagram.service'
-import { ThreadsDataService } from './threads.service'
-import { WxGzhDataService } from './wxGzhData.service'
-import { YoutubeDataService } from './youtubeData.service'
-
-@Module({
- imports: [BilibiliModule, MetaModule, YoutubeModule, WxPlatModule, PinterestModule, AccountModule],
- controllers: [DataCubeController],
- providers: [BilibiliDataService, FacebookDataService, InstagramDataService, ThreadsDataService, YoutubeDataService, WxGzhDataService, PinterestDataService],
- exports: [BilibiliDataService, FacebookDataService, InstagramDataService, ThreadsDataService, YoutubeDataService, WxGzhDataService, PinterestDataService],
-})
-export class DataCubeModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/engagement/engagement.module.ts b/project/backend/apps/aitoearn-channel/src/core/engagement/engagement.module.ts
index 365ba8af..8ba036fd 100644
--- a/project/backend/apps/aitoearn-channel/src/core/engagement/engagement.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/engagement/engagement.module.ts
@@ -1,8 +1,8 @@
import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { EngagementSubTask, EngagementSubTaskSchema, EngagementTask, EngagementTaskSchema } from '../../libs/database/schema/engagement.task.schema'
-import { MetaModule } from '../plat/meta/meta.module'
-import { YoutubeModule } from '../plat/youtube/youtube.module'
+import { MetaModule } from '../platforms/meta/meta.module'
+import { YoutubeModule } from '../platforms/youtube/youtube.module'
import { EngagementController } from './engagement.controller'
import { EngagementRecordService } from './engagement.record.service'
import { EngagementService } from './engagement.service'
diff --git a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/facebook.provider.ts b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/facebook.provider.ts
index 4ca2173d..3b932460 100644
--- a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/facebook.provider.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/facebook.provider.ts
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common'
import { PostsResponseVo } from '@yikart/common'
-import { FacebookService } from '../../../core/plat/meta/facebook.service'
+import { FacebookService } from '../../../core/platforms/meta/facebook.service'
import { FacebookPagePostRequest, FacebookPostCommentsRequest } from '../../../libs/facebook/facebook.interfaces'
import { KeysetPagination, OffsetPagination } from '../engagement.dto'
import { EngagementComment, EngagementProvider, FetchPostCommentsResponse, PublishCommentResponse } from '../engagement.interface'
diff --git a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/instagram.provider.ts b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/instagram.provider.ts
index 416dd995..9203b87f 100644
--- a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/instagram.provider.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/instagram.provider.ts
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common'
import { PostsResponseVo } from '@yikart/common'
-import { InstagramService } from '../../../core/plat/meta/instagram.service'
+import { InstagramService } from '../../../core/platforms/meta/instagram.service'
import { InstagramMediaType } from '../../../libs/instagram/instagram.enum'
import { IGPostCommentsRequest, InstagramUserPostRequest } from '../../../libs/instagram/instagram.interfaces'
import { KeysetPagination, OffsetPagination } from '../engagement.dto'
diff --git a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/threads.provider.ts b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/threads.provider.ts
index bca19af6..2f60f48f 100644
--- a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/threads.provider.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/threads.provider.ts
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common'
import { PostsResponseVo } from '@yikart/common'
-import { ThreadsService } from '../../../core/plat/meta/threads.service'
+import { ThreadsService } from '../../../core/platforms/meta/threads.service'
import { ThreadsObjectCommentsRequest, ThreadsPostsRequest } from '../../../libs/threads/threads.interfaces'
import { KeysetPagination, OffsetPagination } from '../engagement.dto'
import { EngagementComment, EngagementProvider, FetchPostCommentsResponse, PublishCommentResponse } from '../engagement.interface'
diff --git a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/youtube.provider.ts b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/youtube.provider.ts
index 5d5054fd..36623bc2 100644
--- a/project/backend/apps/aitoearn-channel/src/core/engagement/providers/youtube.provider.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/engagement/providers/youtube.provider.ts
@@ -1,6 +1,6 @@
import { Injectable, Logger } from '@nestjs/common'
import { PostsResponseVo } from '@yikart/common'
-import { YoutubeService } from '../../../core/plat/youtube/youtube.service'
+import { YoutubeService } from '../../../core/platforms/youtube/youtube.service'
import { KeysetPagination, OffsetPagination } from '../engagement.dto'
import { EngagementComment, EngagementProvider, FetchPostCommentsResponse, PublishCommentResponse } from '../engagement.interface'
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/dto/interactionRecord.dto.ts b/project/backend/apps/aitoearn-channel/src/core/interact/dto/interaction-record.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/interact/dto/interactionRecord.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/dto/interaction-record.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/dto/replyCommentRecord.dto.ts b/project/backend/apps/aitoearn-channel/src/core/interact/dto/reply-comment-record.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/interact/dto/replyCommentRecord.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/dto/reply-comment-record.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/interact.controller.ts b/project/backend/apps/aitoearn-channel/src/core/interact/interact.controller.ts
index 11a5432e..76cceb9e 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/interact.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/interact.controller.ts
@@ -9,7 +9,7 @@ import { Body, Controller, Post } from '@nestjs/common'
import { AccountType } from '@yikart/aitoearn-server-client'
import { AppException, ResponseCode } from '@yikart/common'
import { AccountService } from '../account/account.service'
-import { PublishRecordService } from '../account/publishRecord.service'
+import { PublishRecordService } from '../account/publish-record.service'
import {
AddArcCommentDto,
DelCommentDto,
@@ -17,7 +17,7 @@ import {
ReplyCommentDto,
} from './dto/interact.dto'
import { InteracteBase } from './interact.base'
-import { WxGzhInteractService } from './wxGzhInteract.service'
+import { WxGzhInteractService } from './wx-gzh-interact.service'
@Controller()
export class InteracteController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/interact.module.ts b/project/backend/apps/aitoearn-channel/src/core/interact/interact.module.ts
index 7f7234b9..4e4c3695 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/interact.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/interact.module.ts
@@ -2,14 +2,14 @@ import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { InteractionRecord, InteractionRecordSchema } from '../../libs/database/schema/interactionRecord.schema'
import { ReplyCommentRecord, ReplyCommentRecordSchema } from '../../libs/database/schema/replyCommentRecord.schema'
-import { WxPlatModule } from '../plat/wxPlat/wxPlat.module'
-import { PublishModule } from '../publish/publish.module'
+import { WxPlatModule } from '../platforms/wx-plat/wx-plat.module'
+import { PublishModule } from '../publishing/publishing.module'
import { InteracteController } from './interact.controller'
-import { InteractionRecordController } from './interactionRecord.controller'
-import { InteractionRecordService } from './interactionRecord.service'
-import { ReplyCommentRecordController } from './replyCommentRecord.controller'
-import { ReplyCommentRecordService } from './replyCommentRecord.service'
-import { WxGzhInteractService } from './wxGzhInteract.service'
+import { InteractionRecordController } from './interaction-record.controller'
+import { InteractionRecordService } from './interaction-record.service'
+import { ReplyCommentRecordController } from './reply-comment-record.controller'
+import { ReplyCommentRecordService } from './reply-comment-record.service'
+import { WxGzhInteractService } from './wx-gzh-interact.service'
@Module({
imports: [
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.controller.ts b/project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.controller.ts
similarity index 91%
rename from project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.controller.ts
index 42ca104a..de2b5b63 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.controller.ts
@@ -6,8 +6,8 @@
* @Description: 渠道互动记录
*/
import { Body, Controller, Post } from '@nestjs/common'
-import { AddInteractionRecordDto, InteractionRecordListDto } from './dto/interactionRecord.dto'
-import { InteractionRecordService } from './interactionRecord.service'
+import { AddInteractionRecordDto, InteractionRecordListDto } from './dto/interaction-record.dto'
+import { InteractionRecordService } from './interaction-record.service'
@Controller()
export class InteractionRecordController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.service.ts b/project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.service.ts
index 551265bb..c30e00fc 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/interactionRecord.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/interaction-record.service.ts
@@ -4,7 +4,7 @@ import { AccountType } from '@yikart/aitoearn-server-client'
import { Model, RootFilterQuery } from 'mongoose'
import { TableDto } from '../../common/global/dto/table.dto'
import { InteractionRecord } from '../../libs/database/schema/interactionRecord.schema'
-import { AddInteractionRecordDto } from './dto/interactionRecord.dto'
+import { AddInteractionRecordDto } from './dto/interaction-record.dto'
@Injectable()
export class InteractionRecordService {
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.controller.ts b/project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.controller.ts
similarity index 91%
rename from project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.controller.ts
index bc3febc4..bfc29205 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.controller.ts
@@ -6,8 +6,8 @@
* @Description: 评论回复记录 replyCommentRecord ReplyCommentRecord
*/
import { Body, Controller, Post } from '@nestjs/common'
-import { AddReplyCommentRecordDto, ReplyCommentRecordListDto } from './dto/replyCommentRecord.dto'
-import { ReplyCommentRecordService } from './replyCommentRecord.service'
+import { AddReplyCommentRecordDto, ReplyCommentRecordListDto } from './dto/reply-comment-record.dto'
+import { ReplyCommentRecordService } from './reply-comment-record.service'
@Controller()
export class ReplyCommentRecordController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.service.ts b/project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.service.ts
index eb30ac40..5fede06b 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/replyCommentRecord.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/reply-comment-record.service.ts
@@ -4,7 +4,7 @@ import { AccountType } from '@yikart/aitoearn-server-client'
import { Model, RootFilterQuery } from 'mongoose'
import { TableDto } from '../../common/global/dto/table.dto'
import { ReplyCommentRecord } from '../../libs/database/schema/replyCommentRecord.schema'
-import { AddReplyCommentRecordDto } from './dto/replyCommentRecord.dto'
+import { AddReplyCommentRecordDto } from './dto/reply-comment-record.dto'
@Injectable()
export class ReplyCommentRecordService {
diff --git a/project/backend/apps/aitoearn-channel/src/core/interact/wxGzhInteract.service.ts b/project/backend/apps/aitoearn-channel/src/core/interact/wx-gzh-interact.service.ts
similarity index 95%
rename from project/backend/apps/aitoearn-channel/src/core/interact/wxGzhInteract.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/interact/wx-gzh-interact.service.ts
index 58af584f..db2c6d17 100644
--- a/project/backend/apps/aitoearn-channel/src/core/interact/wxGzhInteract.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/interact/wx-gzh-interact.service.ts
@@ -8,7 +8,7 @@
import { Injectable, Logger } from '@nestjs/common'
import { PublishRecord } from '@yikart/aitoearn-server-client'
import { Account } from '../../libs/database/schema/account.schema'
-import { WxGzhService } from '../plat/wxPlat/wxGzh.service'
+import { WxGzhService } from '../platforms/wx-plat/wx-gzh.service'
import { InteracteBase } from './interact.base'
@Injectable()
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/bilibili.controller.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/bilibili.controller.ts
deleted file mode 100644
index 3d57ddfa..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/bilibili.controller.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Controller, Get, HttpCode, Param, UseGuards } from '@nestjs/common'
-import { SkKeyAuthGuard } from '../../common/guards/skKeyAuth.guard'
-import { BilibiliService } from '../plat/bilibili/bilibili.service'
-
-@Controller()
-export class BilibiliController {
- constructor(private readonly bilibiliService: BilibiliService) {}
-
- @HttpCode(200)
- @UseGuards(SkKeyAuthGuard)
- @Get('archiveTypeList/:accountId')
- async publishRecordList(@Param('accountId') accountId: string) {
- const res = await this.bilibiliService.archiveTypeList(accountId)
-
- return res
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/account.dto.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/dto/account.dto.ts
deleted file mode 100644
index 524eacf8..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/account.dto.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { createZodDto } from '@yikart/common'
-import { z } from 'zod'
-
-export const GetAccountInfoSchema = z.object({
- id: z.string().describe('账号ID'),
-})
-export class GetAccountInfoDto extends createZodDto(
- GetAccountInfoSchema,
-) {}
-
-export const GetAccountListQuerySchema = z.object({
- type: z.enum(AccountType).optional(),
-})
-export class GetAccountListQueryDto extends createZodDto(
- GetAccountListQuerySchema,
-) {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/mcp.dto.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/dto/mcp.dto.ts
deleted file mode 100644
index 8a7a1e4c..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/mcp.dto.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { z } from 'zod'
-import { PublishType } from '../../../libs/database/schema/publishTask.schema'
-
-export const GetAuthPageSchema = z.object({
- accountType: z.nativeEnum(AccountType).describe('平台类型'),
-})
-
-export const McpPublishSchema = z.object({
- skKey: z.string().describe('skKey'),
- type: z.nativeEnum(PublishType).describe('类型'),
- title: z.string().nullable().optional().transform(val => !val ? undefined : val),
- desc: z.string().nullable().optional().transform(val => !val ? undefined : val),
- videoUrl: z.string().nullable().optional().transform(val => !val ? undefined : val),
- coverUrl: z.string().nullable().optional().transform(val => !val ? undefined : val),
- imgUrlList: z.string().nullable().optional().transform(val => !val ? undefined : val),
- publishTime: z.string().nullable().optional().transform(val => !val ? undefined : val),
- topics: z.string(),
-})
-
-export const McpPromptPublishSchema = z.object({
- id: z.string(),
- userId: z.string(),
-})
-
-export const UpdatePublishTaskTimeSchema = z.object({
- id: z.string().describe('publishing task ID'),
- publishingTime: z.date().default(() => new Date()),
- userId: z.string(),
-})
-
-export const McpAuthedAccountSchema = z.object({
- accountId: z.string().describe('accountId'),
- userId: z.string().describe('userId'),
- platform: z.nativeEnum(AccountType).describe('平台类型'),
- nickname: z.string().nullable().optional().describe('昵称'),
-})
-
-export const McpAuthedAccountsResponseSchema = z.object({
- accounts: z.array(McpAuthedAccountSchema).describe('已授权账号列表'),
-})
-
-export const CreatePublishingTaskRespItemSchema = z.object({
- id: z.string().describe('任务ID'),
-}).describe('创建的发布任务信息')
-
-export const CreatePublishingTaskRespSchema = z.object({
- tasks: z.array(CreatePublishingTaskRespItemSchema).describe('创建的发布任务列表'),
-})
-
-export const UpdatePublishingTimeRespSchema = z.object({
- id: z.string().describe('任务ID'),
- publishTime: z.string().describe('新的发布时间'),
-}).describe('更新发布任务时间响应')
-
-export type McpPublishDto = z.infer<typeof McpPublishSchema>
-export type UpdatePublishTaskTimeDto = z.infer<typeof UpdatePublishTaskTimeSchema>
-export type McpAuthedAccountVo = z.infer<typeof McpAuthedAccountSchema>
-export type McpAuthedAccountsRespVo = z.infer<typeof McpAuthedAccountsResponseSchema>
-export type CreatePublishingTaskResp = z.infer<typeof CreatePublishingTaskRespSchema>
-export type UpdatePublishingTimeResp = z.infer<typeof UpdatePublishingTimeRespSchema>
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/publish.dto.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/dto/publish.dto.ts
deleted file mode 100644
index d21145c9..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/dto/publish.dto.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { createZodDto } from '@yikart/common'
-import { z } from 'zod'
-import { PublishType } from '../../../libs/database/schema/publishTask.schema'
-
-export const CreatePublishingTaskSchema = z.object({
- accounts: z.array(z.string()).describe('账户ID数组').optional(),
- mediaType: z.enum(PublishType).describe('类型'),
- title: z.string().nullish().describe('标题'),
- desc: z.string().nullish().describe('内容'),
- videoUrl: z.string().nullish().describe('视频链接'),
- coverUrl: z.string().nullish().describe('封面链接'),
- imgUrlList: z.string().nullish().describe('图片链接数组,逗号分隔'),
- publishingTime: z.string().nullish().describe('发布时间,格式:YYYY-MM-DD HH:mm:ss'),
- topics: z.string(),
-})
-
-export const CreatePublishSchema = z.object({
- flowId: z.string().describe('流水ID').nullable().optional().transform(val => !val ? undefined : val),
- accountId: z.string().describe('账户ID'),
- type: z.enum(PublishType).describe('类型'),
- title: z.string().nullable().optional().transform(val => !val ? undefined : val),
- desc: z.string().nullable().optional().transform(val => !val ? undefined : val),
- videoUrl: z.string().nullable().optional().transform(val => !val ? undefined : val),
- coverUrl: z.string().nullable().optional().transform(val => !val ? undefined : val),
- imgUrlList: z.string().nullable().optional().transform(val => !val ? undefined : val),
- publishTime: z.string().nullable().optional().transform(val => !val ? undefined : val),
- topics: z.string(),
-})
-
-export class CreatePublishDto extends createZodDto(CreatePublishSchema) {}
-export class CreatePublishingTaskDto extends createZodDto(CreatePublishingTaskSchema) {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.controller.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.controller.ts
deleted file mode 100644
index 41140d28..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.controller.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Controller } from '@nestjs/common'
-import { Prompt, PromptOptions, Tool, ToolOptions } from '@rekog/mcp-nest'
-import { AppException, ResponseCode } from '@yikart/common'
-import { Request } from 'express'
-import { z } from 'zod'
-import { CreatePublishingTaskRespSchema, McpAuthedAccountsResponseSchema, McpPromptPublishSchema, UpdatePublishingTimeRespSchema, UpdatePublishTaskTimeDto, UpdatePublishTaskTimeSchema } from './dto/mcp.dto'
-import { CreatePublishingTaskDto, CreatePublishingTaskSchema } from './dto/publish.dto'
-import { McpService } from './mcp.service'
-
-@Controller()
-export class McpController {
- constructor(
- private readonly mcpService: McpService,
- ) { }
-
- @Prompt({
- name: 'generate_publishing_prompt',
- description: 'Generate a publishing prompt',
- parameters: McpPromptPublishSchema as unknown as PromptOptions['parameters'],
- })
- async generatePublishingPrompt() {
- return this.mcpService.generatePublishingPrompt()
- }
-
- @Tool({
- name: 'list_linked_accounts',
- description: 'List linked accounts',
- parameters: z.object({}).describe('无参数'),
- outputSchema: McpAuthedAccountsResponseSchema as unknown as ToolOptions['outputSchema'],
- })
- async listLinkedAccounts(request: Request) {
- const skKey = request.headers['sk-key'] || request.query['sk-key']
- if (!skKey || typeof skKey !== 'string') {
- throw new AppException(ResponseCode.ChannelSkKeyRequired)
- }
- return await this.mcpService.listLinkedAccounts(skKey)
- }
-
- @Tool({
- name: 'create_publishing_task',
- description: 'Create a publishing task',
- parameters: CreatePublishingTaskSchema,
- outputSchema: CreatePublishingTaskRespSchema as unknown as ToolOptions['outputSchema'],
- })
- async createPublishingTask(data: CreatePublishingTaskDto, request: Request) {
- const skKey = request.headers['sk-key'] || request.query['sk-key']
- if (!skKey || typeof skKey !== 'string') {
- throw new AppException(ResponseCode.ChannelSkKeyRequired)
- }
- return await this.mcpService.bulkCreatePublishingTask(skKey, data)
- }
-
- @Tool({
- name: 'update_publishing_time',
- description: 'update publishing time',
- parameters: UpdatePublishTaskTimeSchema as unknown as ToolOptions['parameters'],
- outputSchema: UpdatePublishingTimeRespSchema as unknown as ToolOptions['outputSchema'],
- })
- async changeTaskTime(data: UpdatePublishTaskTimeDto) {
- const res = await this.mcpService.updatePublishingTime(data)
- return res
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.module.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.module.ts
deleted file mode 100644
index 1c0565b5..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.module.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Module } from '@nestjs/common'
-import { MongooseModule } from '@nestjs/mongoose'
-import { SkKey, SkKeySchema } from '../../libs/database/schema/skKey.schema'
-import {
- SkKeyRefAccount,
- SkKeyRefAccountSchema,
-} from '../../libs/database/schema/skKeyRefAccount.schema'
-import { BilibiliModule } from '../plat/bilibili/bilibili.module'
-import { PublishModule } from '../publish/publish.module'
-import { BilibiliController } from './bilibili.controller'
-import { McpController } from './mcp.controller'
-import { McpService } from './mcp.service'
-import { PluginController } from './plugin.controller'
-
-@Module({
- imports: [
- MongooseModule.forFeature([
- { name: SkKey.name, schema: SkKeySchema },
- { name: SkKeyRefAccount.name, schema: SkKeyRefAccountSchema },
- ]),
- BilibiliModule,
- PublishModule,
- ],
- providers: [McpService],
- controllers: [McpController, PluginController, BilibiliController],
- exports: [],
-})
-export class McpModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.service.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.service.ts
deleted file mode 100644
index 372ae20f..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/mcp.service.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import {
- GetPromptResult,
-} from '@modelcontextprotocol/sdk/types'
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { AppException, ResponseCode } from '@yikart/common'
-import moment from 'moment'
-import { AccountService } from '../account/account.service'
-import { PlatPulOption } from '../publish/common'
-import { PublishTaskService } from '../publish/publishTask.service'
-import { SkKeyService } from '../skKey/skKey.service'
-import { CreatePublishingTaskResp, McpAuthedAccountsRespVo, McpAuthedAccountVo, UpdatePublishTaskTimeDto } from './dto/mcp.dto'
-import { CreatePublishingTaskDto } from './dto/publish.dto'
-
-@Injectable()
-export class McpService {
- private readonly logger = new Logger(McpService.name)
- constructor(
- private readonly publishTaskService: PublishTaskService,
- private readonly accountService: AccountService,
- private readonly skKeyService: SkKeyService,
- ) { }
-
- private async createPublishingTask(accountId: string, data: CreatePublishingTaskDto) {
- const now = new Date()
- const defaultPublishingTime = moment(now).add(2, 'minute').toDate()
- const publishingTime = data.publishingTime ? moment(data.publishingTime).toDate() : defaultPublishingTime
- if (publishingTime < now) {
- throw new AppException(ResponseCode.PublishTimeInvalid)
- }
-
- const accountInfo = await this.accountService.getAccountInfo(accountId)
- if (!accountInfo)
- throw new AppException(ResponseCode.AccountNotFound)
-
- const { imgUrlList, topics } = data
-
- const option: PlatPulOption = {
- bilibili: {
- tid: 160,
- copyright: 1,
- },
- }
- const task = await this.publishTaskService.createPub({
- inQueue: false,
- queueId: '',
- accountId,
- type: data.mediaType,
- uid: accountInfo.uid,
- userId: accountInfo.userId,
- accountType: accountInfo.type,
- title: data.title || '',
- desc: data.desc || '',
- videoUrl: data.videoUrl || '',
- coverUrl: data.coverUrl || '',
- option,
- publishTime: publishingTime,
- imgUrlList: imgUrlList?.split(','),
- topics: topics?.split(','),
- dataId: '',
- })
- return task.id
- }
-
- async bulkCreatePublishingTask(skKey: string, data: CreatePublishingTaskDto): Promise<CreatePublishingTaskResp> {
- const now = new Date()
- const defaultPublishingTime = moment(now).add(2, 'minute').toDate()
- const publishingTime = data.publishingTime ? moment(data.publishingTime).toDate() : defaultPublishingTime
- if (publishingTime < now) {
- throw new AppException(ResponseCode.PublishTimeInvalid)
- }
- let accountIdList = data.accounts
- if (!accountIdList || accountIdList.length === 0) {
- const accounts = await this.skKeyService.getRefAccountAll(skKey)
- accountIdList = accounts.map(acc => acc.accountId)
- }
- if (accountIdList.length === 0) {
- throw new AppException(ResponseCode.ChannelNoAccountsFound)
- }
- const resp: CreatePublishingTaskResp = {
- tasks: [],
- }
- for (const accountId of accountIdList) {
- const taskId = await this.createPublishingTask(accountId, data)
- resp.tasks.push(taskId)
- }
- return resp
- }
-
- async generatePublishingPrompt(): Promise<GetPromptResult> {
- const res: GetPromptResult = {
- role: 'assistant',
- content: {
- type: 'text',
- text: `平台账号类型: 微信公众号:${AccountType.WxGzh},bilibili:${AccountType.BILIBILI},抖音: ${AccountType.Douyin},快手:${AccountType.KWAI},twitter:${AccountType.TWITTER},instagram:${AccountType.INSTAGRAM},threads:${AccountType.THREADS},youtube:${AccountType.YOUTUBE}}`,
- },
- messages: [
- {
- role: 'user',
- content: {
- type: 'text',
- text: `帮我写一个发布任务,内容是:desc,标题是:title, 类型是:type,视频链接是:videoUrl,封面链接地址是:coverUrl,图片链接地址数组是:imgUrlList,发布时间是:publishTime, 话题数组是:topics `,
- },
- },
- ],
- }
- return res
- }
-
- async updatePublishingTime(data: UpdatePublishTaskTimeDto) {
- await this.publishTaskService.updatePublishTaskTime(
- data.id,
- data.publishingTime,
- data.userId,
- )
- return {
- id: data.id,
- publishTime: data.publishingTime,
- }
- }
-
- async listLinkedAccounts(skKey: string): Promise<McpAuthedAccountsRespVo> {
- const authedAccounts = await this.skKeyService.getRefAccountAll(skKey)
- const accounts: McpAuthedAccountVo[] = []
- for (const acc of authedAccounts) {
- const accountInfo = await this.accountService.getAccountInfo(acc.accountId)
- if (accountInfo) {
- accounts.push({
- accountId: accountInfo.id,
- userId: accountInfo.userId,
- platform: accountInfo.type,
- nickname: accountInfo.nickname || '',
- })
- }
- }
- return { accounts }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/mcp/plugin.controller.ts b/project/backend/apps/aitoearn-channel/src/core/mcp/plugin.controller.ts
deleted file mode 100644
index 406b3fd0..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/mcp/plugin.controller.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { Body, Controller, Get, HttpCode, Logger, Param, Post, UseGuards } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { AppException, ResponseCode } from '@yikart/common'
-import { plainToInstance } from 'class-transformer'
-import moment from 'moment'
-import { GetSkKey, SkKeyAuthGuard } from '../../common/guards/skKeyAuth.guard'
-import { PublishType } from '../../libs/database/schema/publishTask.schema'
-import { SkKey } from '../../libs/database/schema/skKey.schema'
-import { AccountService } from '../account/account.service'
-import { PublishTaskService } from '../publish/publishTask.service'
-import { SkKeyService } from '../skKey/skKey.service'
-import { CreatePublishDto } from './dto/publish.dto'
-
-@Controller()
-export class PluginController {
- logger = new Logger(PluginController.name)
- constructor(
- private readonly accountService: AccountService,
- private readonly skKeyService: SkKeyService,
- private readonly publishTaskService: PublishTaskService,
- ) { }
-
- /**
- * 获取key的账号列表
- * @param body
- * @returns
- */
- @HttpCode(200)
- @UseGuards(SkKeyAuthGuard)
- @Get('account/list')
- async accountList(@GetSkKey() skKey: SkKey) {
- const list = await this.skKeyService.getRefAccountAll(skKey.key)
- return list
- }
-
- /**
- * 创建发布
- * @param body
- * @returns
- */
- @HttpCode(200)
- @UseGuards(SkKeyAuthGuard)
- @Post('publish/create')
- async createPub(@Body() body: CreatePublishDto) {
- try {
- body = plainToInstance(CreatePublishDto, body)
- // 发布时间处理
- let publishTimeDate: Date = new Date(Date.now() + 2 * 60 * 1000)
-
- const { publishTime } = body
-
- // 如果publishTime为空,或者转换时间有误,则使用publishTimeDate
- if (!publishTime || !moment(publishTime).isValid()) {
- publishTimeDate = new Date(Date.now() + 2 * 60 * 1000)
- }
- else {
- publishTimeDate = new Date(publishTime)
- }
-
- const accountInfo = await this.accountService.getAccountInfo(
- body.accountId,
- )
- if (!accountInfo) {
- throw new AppException(ResponseCode.ChannelAccountInfoFailed)
- }
- const { imgUrlList, topics } = body
-
- // B站默认值
- if (accountInfo.type === AccountType.BILIBILI) {
- (body as any).option = {
- bilibili: {
- tid: 160,
- copyright: 1,
- },
- }
- }
-
- if (accountInfo.type === AccountType.FACEBOOK) {
- (body as any).option = {
- facebook: {
- content_category: 'post',
- },
- }
- }
-
- if (accountInfo.type === AccountType.INSTAGRAM) {
- const contentCategory = body.type === PublishType.VIDEO ? 'reel' : 'post';
- (body as any).option = {
- instagram: {
- content_category: contentCategory, // post、reel、story
- },
- }
- }
-
- if (accountInfo.type === AccountType.YOUTUBE) {
- (body as any).option = {
- youtube: {
- categoryId: '43',
- },
- }
- }
-
- const ret = await this.publishTaskService.createPub({
- inQueue: false,
- queueId: '',
- uid: accountInfo.uid,
- userId: accountInfo.userId,
- accountType: accountInfo.type,
- ...body,
- publishTime: publishTimeDate,
- imgUrlList: imgUrlList?.split(','),
- topics: topics?.split(','),
- dataId: '',
- })
-
- return ret
- }
- catch (error) {
- this.logger.error('----------- plugin createPub error ------------', error)
- throw error
- }
- }
-
- /**
- * 获取流水的发布任务列表
- * @returns
- */
- @HttpCode(200)
- @UseGuards(SkKeyAuthGuard)
- @Get('publish/task/list/:flowId')
- async publishTaskList(
- @Param('flowId') flowId: string,
- ) {
- const res = await this.publishTaskService.getPublishTaskListByFlowId(flowId)
- return res
- }
-
- /**
- * 获取发布记录列表
- * @param body
- * @returns
- */
- @HttpCode(200)
- @UseGuards(SkKeyAuthGuard)
- @Get('publish/task/info/:taskId')
- async publishRecordList(
- @GetSkKey() skKey: SkKey,
- @Param('taskId') taskId: string,
- ) {
- const res = await this.publishTaskService.getPublishTaskInfo(taskId)
-
- return res
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.module.ts b/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.module.ts
deleted file mode 100644
index 57580e68..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.module.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { forwardRef, Module } from '@nestjs/common'
-import { PublishModule } from '../../../core/publish/publish.module'
-import { MyWxPlatApiModule } from '../../../libs/myWxPlat/myWxPlatApi.module'
-import { WxGzhApiModule } from '../../../libs/wxGzh/wxGzhApi.module'
-import { WxGzhService } from './wxGzh.service'
-import { WxPlatController } from './wxPlat.controller'
-import { WxPlatService } from './wxPlat.service'
-
-@Module({
- imports: [MyWxPlatApiModule, WxGzhApiModule, forwardRef(() => PublishModule)],
- controllers: [WxPlatController],
- providers: [WxPlatService, WxGzhService],
- exports: [WxPlatService, WxGzhService],
-})
-export class WxPlatModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/bilibili/bilibili.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/bilibili.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/bilibili/common.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/common.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/bilibili/common.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/common.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/bilibili/dto/bilibili.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/dto/bilibili.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/bilibili/dto/bilibili.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/bilibili/dto/bilibili.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/common.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/common.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/common.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/common.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/constants.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/constants.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/kwai/constants.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/kwai/constants.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/dto/kwai.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/dto/kwai.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/kwai/dto/kwai.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/kwai/dto/kwai.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.module.ts
similarity index 90%
rename from project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.module.ts
index efb164c4..b7a6e37b 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.module.ts
@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'
import { MongooseModule } from '@nestjs/mongoose'
import { OAuth2Credential, OAuth2CredentialSchema } from '../../../libs/database/schema/oauth2Credential.schema'
-import { KwaiApiModule } from '../../../libs/kwai/kwaiApi.module'
+import { KwaiApiModule } from '../../../libs/kwai/kwai.module'
import { KwaiController } from './kwai.controller'
import { KwaiService } from './kwai.service'
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.service.ts
similarity index 88%
rename from project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.service.ts
index df1f3976..1649ab7b 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/kwai/kwai.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/kwai/kwai.service.ts
@@ -7,11 +7,11 @@ import { Model } from 'mongoose'
import { v4 as uuidv4 } from 'uuid'
import { getCurrentTimestamp } from '../../../common'
import { AccountService } from '../../../core/account/account.service'
-import { BilibiliAuthInfo } from '../../../core/plat/bilibili/common'
-import { AuthTaskInfo } from '../../../core/plat/common'
+import { BilibiliAuthInfo } from '../../../core/platforms/bilibili/common'
+import { AuthTaskInfo } from '../../../core/platforms/common'
import { OAuth2Credential } from '../../../libs/database/schema/oauth2Credential.schema'
-import { KwaiOAuthCredentialsResponse, KwaiVideoPubParams } from '../../../libs/kwai/kwaiApi.interfaces'
-import { KwaiApiService } from '../../../libs/kwai/kwaiApi.service'
+import { KwaiOAuthCredentialsResponse } from '../../../libs/kwai/kwai.interfaces'
+import { KwaiApiService } from '../../../libs/kwai/kwai.service'
import { KWAI_TIME_CONSTANTS } from './constants'
@Injectable()
@@ -262,14 +262,49 @@ export class KwaiService {
return accountInfo
}
+ async initVideoUpload(accountId) {
+ const accountToken = await this.getAccessTokenAndRefresh(accountId)
+ if (accountToken === null) {
+ this.logger.warn(`Kwai account ${accountId} access_token is expired or invalid`)
+ throw new Error('kwai account access_token is expired or invalid')
+ }
+ return await this.kwaiApiService.startUpload(accountToken)
+ }
+
+ async chunkedUploadVideo(
+ upload_token: string,
+ fragment_id: number,
+ endpoint: string,
+ video: Buffer,
+ ) {
+ return await this.kwaiApiService.fragmentUploadVideo(
+ upload_token,
+ fragment_id,
+ endpoint,
+ video,
+ )
+ }
+
+ async finalizeVideoUpload(
+ upload_token: string,
+ total_parts: number,
+ endpoint: string,
+ ) {
+ return await this.kwaiApiService.completeFragmentUpload(
+ upload_token,
+ total_parts,
+ endpoint,
+ )
+ }
+
// 视频发布
- async publishVideo(accountId: string, pubParams: KwaiVideoPubParams) {
+ async publishVideo(accountId: string, caption: string, thumbnail: Blob, uploadToken: string) {
const accountToken = await this.getAccessTokenAndRefresh(accountId)
if (accountToken === null) {
this.logger.warn(`Kwai account ${accountId} access_token is expired or invalid`)
throw new Error('kwai account access_token is expired or invalid')
}
- return await this.kwaiApiService.publishVideo(accountToken, pubParams)
+ return await this.kwaiApiService.publishVideo(accountToken, caption, thumbnail, uploadToken)
}
// 获取用户公开信息
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/base.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/base.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/constants.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/constants.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/constants.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/constants.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/dto/meta.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/dto/meta.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/dto/meta.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/dto/meta.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/facebook.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/facebook.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/instagram.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/instagram.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/instagram.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/instagram.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/linkedin.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/linkedin.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.interfaces.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.interfaces.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.interfaces.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.interfaces.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/meta.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/meta.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/meta/threads.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/plat/meta/threads.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
index 5066074d..18210245 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/meta/threads.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
@@ -7,6 +7,7 @@ import {
ThreadsInsightsResponse,
ThreadsObjectCommentsRequest,
ThreadsObjectCommentsResponse,
+ ThreadsObjectInfo,
ThreadsPostResponse,
ThreadsPostsRequest,
ThreadsPostsResponse,
@@ -29,11 +30,11 @@ export class ThreadsService extends MetaBaseService {
private async authorize(
accountId: string,
- ): Promise<MetaUserOAuthCredential | null> {
+ ): Promise<MetaUserOAuthCredential> {
const credential = await this.getOAuth2Credential(accountId)
if (!credential) {
this.logger.warn(`No access token found for accountId: ${accountId}`)
- return null
+ throw new Error(`No access token found for accountId: ${accountId}`)
}
const now = getCurrentTimestamp()
if (now >= credential.expires_in) {
@@ -105,12 +106,8 @@ export class ThreadsService extends MetaBaseService {
)
}
- async getObjectInfo(accountId: string, objectId: string, pageId: string, fields?: string): Promise<any> {
+ async getObjectInfo(accountId: string, objectId: string, pageId: string, fields?: string): Promise<ThreadsObjectInfo> {
const credential = await this.authorize(accountId)
- if (!credential) {
- this.logger.error(`No valid access token found for accountId: ${accountId} ${pageId}`)
- return null
- }
return await this.threadsAPIService.getObjectInfo(credential.access_token, objectId, fields)
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/pinterest/dto/pinterest.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/dto/pinterest.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/pinterest/dto/pinterest.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/dto/pinterest.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
similarity index 94%
rename from project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
index 2c59b245..b0df018f 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/pinterest/pinterest.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
@@ -12,7 +12,7 @@ import { v4 as uuidv4 } from 'uuid'
import { getCurrentTimestamp } from '../../../common'
import { config } from '../../../config'
import { AccountService } from '../../../core/account/account.service'
-import { WebhookDto } from '../../../core/plat/pinterest/dto/pinterest.dto'
+import { WebhookDto } from '../../../core/platforms/pinterest/dto/pinterest.dto'
import { OAuth2Credential } from '../../../libs/database/schema/oauth2Credential.schema'
import {
AuthInfo,
@@ -176,7 +176,6 @@ export class PinterestService {
async getBoardList(accountId: string) {
const tokenInfo = await this.getUserStat(accountId)
const accessToken = tokenInfo.access_token as string
- this.logger.log(JSON.stringify({ hasToken: !!accessToken }))
return this.pinterestApiService.getBoards(accessToken)
}
@@ -209,16 +208,10 @@ export class PinterestService {
* @param body
* @returns
*/
- async createPin(body: CreatePinBody) {
- this.logger.log('--createPin--', JSON.stringify(body))
- const accountId: string = _.get(body, 'accountId') || ''
- _.unset(body, 'accountId')
- const tokenInfo = await this.getUserStat(accountId)
+ async createPin(data: CreatePinBody) {
+ const tokenInfo = await this.getUserStat(data.accountId)
const accessToken = tokenInfo.access_token as string
- if (_.isEmpty(accessToken))
- throw new AppException(ResponseCode.ChannelAuthorizationExpired)
- const data = await this.pinterestApiService.createPin(body, accessToken)
- return { code: 0, data }
+ return await this.pinterestApiService.createPin(data, accessToken)
}
/**
@@ -251,11 +244,9 @@ export class PinterestService {
* @returns
*/
async delPinById(id: string, accountId: string) {
- this.logger.log(`--delPinById--${id}, ${accountId}`)
const tokenInfo = await this.getUserStat(accountId)
const accessToken = tokenInfo.access_token as string
- const data = await this.pinterestApiService.deletePin(id, accessToken)
- return { code: 0, data }
+ return await this.pinterestApiService.deletePin(id, accessToken)
}
/**
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/plat.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
similarity index 92%
rename from project/backend/apps/aitoearn-channel/src/core/plat/plat.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
index 7c1a7645..70be90fb 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/plat.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
@@ -1,7 +1,7 @@
import { Body, Controller, Logger, Param, Post } from '@nestjs/common'
import { AccountStatus } from '@yikart/aitoearn-server-client'
-import { GenAuthURLDto } from './plat.dto'
-import { PlatformService } from './plat.service'
+import { GenAuthURLDto } from './platforms.dto'
+import { PlatformService } from './platforms.service'
@Controller()
export class PlatformController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/plat.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/plat.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/platforms.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/plat.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
similarity index 80%
rename from project/backend/apps/aitoearn-channel/src/core/plat/plat.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
index 53d7c92b..4552bd05 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/plat.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
@@ -3,11 +3,11 @@ import { BilibiliModule } from './bilibili/bilibili.module'
import { KwaiModule } from './kwai/kwai.module'
import { MetaModule } from './meta/meta.module'
import { PinterestModule } from './pinterest/pinterest.module'
-import { PlatformController } from './plat.controller'
-import { PlatformService } from './plat.service'
+import { PlatformController } from './platforms.controller'
+import { PlatformService } from './platforms.service'
import { TiktokModule } from './tiktok/tiktok.module'
import { TwitterModule } from './twitter/twitter.module'
-import { WxPlatModule } from './wxPlat/wxPlat.module'
+import { WxPlatModule } from './wx-plat/wx-plat.module'
import { YoutubeModule } from './youtube/youtube.module'
@Module({
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/plat.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
similarity index 99%
rename from project/backend/apps/aitoearn-channel/src/core/plat/plat.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
index 8996d2e4..c0253e61 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/plat.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
@@ -7,7 +7,7 @@ import { BilibiliService } from './bilibili/bilibili.service'
import { KwaiService } from './kwai/kwai.service'
import { MetaService } from './meta/meta.service'
import { PinterestService } from './pinterest/pinterest.service'
-import { GenAuthURLDto } from './plat.dto'
+import { GenAuthURLDto } from './platforms.dto'
import { TiktokService } from './tiktok/tiktok.service'
import { TwitterService } from './twitter/twitter.service'
import { YoutubeService } from './youtube/youtube.service'
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/tiktok/constants.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/constants.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/tiktok/constants.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/constants.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/tiktok/dto/tiktok.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/dto/tiktok.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/tiktok/dto/tiktok.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/dto/tiktok.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/tiktok/tiktok.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/constants.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/constants.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/constants.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/constants.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/dto/twitter.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/dto/twitter.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/dto/twitter.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/dto/twitter.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.interfaces.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.interfaces.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.interfaces.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.interfaces.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
similarity index 98%
rename from project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
index 92975f45..fb8226b3 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/twitter/twitter.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
@@ -100,11 +100,11 @@ export class TwitterService {
private async authorize(
accountId: string,
- ): Promise<TwitterOAuthCredential | null> {
+ ): Promise<TwitterOAuthCredential> {
const credential = await this.getOAuth2Credential(accountId)
if (!credential) {
this.logger.warn(`No access token found for accountId: ${accountId}`)
- return null
+ throw new Error(`No access token found for accountId: ${accountId}`)
}
const now = getCurrentTimestamp()
if (now >= credential.expires_in) {
@@ -128,7 +128,7 @@ export class TwitterService {
this.logger.error(
`Failed to save refreshed access token for accountId: ${accountId}`,
)
- return null
+ throw new Error(`Failed to save refreshed access token for accountId: ${accountId}`)
}
return credential
}
@@ -392,12 +392,8 @@ export class TwitterService {
public async getMediaUploadStatus(
userId: string,
mediaId: string,
- ): Promise<XMediaUploadResponse | null> {
+ ): Promise<XMediaUploadResponse> {
const credential = await this.authorize(userId)
- if (!credential) {
- this.logger.warn(`No access token found for userId: ${userId}`)
- return null
- }
return await this.twitterApiService.getMediaStatus(
credential.access_token,
mediaId,
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/common.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/common.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/common.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/common.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/dto/wxPlat.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/dto/wx-plat.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/dto/wxPlat.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/dto/wx-plat.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxGzh.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-gzh.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxGzh.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-gzh.service.ts
index 6e6aaa02..6a254d7e 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxGzh.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-gzh.service.ts
@@ -5,9 +5,9 @@ import {
MediaType,
WxGzhArticleNews,
WxGzhArticleNewsPic,
-} from '../../../libs/wxGzh/common'
-import { WxGzhApiService } from '../../../libs/wxGzh/wxGzhApi.service'
-import { WxPlatService } from './wxPlat.service'
+} from '../../../libs/wx-gzh/common'
+import { WxGzhApiService } from '../../../libs/wx-gzh/wx-gzh.service'
+import { WxPlatService } from './wx-plat.service'
@Injectable()
export class WxGzhService {
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/WXMsgCrypto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-msg-crypto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/WXMsgCrypto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-msg-crypto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.controller.ts
similarity index 95%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.controller.ts
index 595f647a..82cc4008 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.controller.ts
@@ -1,11 +1,11 @@
import { Body, Controller, Delete, Logger, Param, Post } from '@nestjs/common'
-import { PublishRecordService } from '../../../core/account/publishRecord.service'
+import { PublishRecordService } from '../../../core/account/publish-record.service'
import {
DisposeAuthTaskDto,
GetAuthUrlDto,
-} from './dto/wxPlat.dto'
-import { WxGzhService } from './wxGzh.service'
-import { WxPlatService } from './wxPlat.service'
+} from './dto/wx-plat.dto'
+import { WxGzhService } from './wx-gzh.service'
+import { WxPlatService } from './wx-plat.service'
@Controller()
export class WxPlatController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.module.ts
new file mode 100644
index 00000000..4621b445
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.module.ts
@@ -0,0 +1,15 @@
+import { forwardRef, Module } from '@nestjs/common'
+import { MyWxPlatApiModule } from '../../../libs/my-wx-plat/my-wx-plat.module'
+import { WxGzhApiModule } from '../../../libs/wx-gzh/wx-gzh.module'
+import { PublishModule } from '../../publishing/publishing.module'
+import { WxGzhService } from './wx-gzh.service'
+import { WxPlatController } from './wx-plat.controller'
+import { WxPlatService } from './wx-plat.service'
+
+@Module({
+ imports: [MyWxPlatApiModule, WxGzhApiModule, forwardRef(() => PublishModule)],
+ controllers: [WxPlatController],
+ providers: [WxPlatService, WxGzhService],
+ exports: [WxPlatService, WxGzhService],
+})
+export class WxPlatModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.service.ts
similarity index 96%
rename from project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.service.ts
index f8650eb1..ae5a25e5 100644
--- a/project/backend/apps/aitoearn-channel/src/core/plat/wxPlat/wxPlat.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/wx-plat/wx-plat.service.ts
@@ -1,10 +1,3 @@
-/*
- * @Author: nevin
- * @Date: 2025-02-15 20:59:55
- * @LastEditTime: 2025-04-27 17:58:21
- * @LastEditors: nevin
- * @Description: WxPlat
- */
import { Injectable, Logger } from '@nestjs/common'
import { AccountStatus, AccountType, NewAccount } from '@yikart/aitoearn-server-client'
import { AppException, ResponseCode } from '@yikart/common'
@@ -12,11 +5,11 @@ import { RedisService } from '@yikart/redis'
import { v4 as uuidv4 } from 'uuid'
import { config } from '../../../config'
import { AccountService } from '../../../core/account/account.service'
-import { MyWxPlatApiService } from '../../../libs/myWxPlat/myWxPlatApi.service'
-import { WxPlatAuthorizerInfo } from '../../../libs/wxPlat/comment'
+import { WxPlatAuthorizerInfo } from '../../../libs/my-wx-plat/comment'
+import { MyWxPlatApiService } from '../../../libs/my-wx-plat/my-wx-plat.service'
import { AuthTaskInfo } from '../common'
import { WxPlatAuthInfo } from './common'
-import { decode } from './WXMsgCrypto'
+import { decode } from './wx-msg-crypto'
@Injectable()
export class WxPlatService {
@@ -114,7 +107,7 @@ export class WxPlatService {
if (!res)
throw new AppException(ResponseCode.ChannelPlatformTokenNotFound)
- return res
+ return res.data
}
async checkAuth(accountId: string): Promise<{
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/youtube/comment.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/comment.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/youtube/comment.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/youtube/comment.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/youtube/dto/youtube.dto.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/dto/youtube.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/youtube/dto/youtube.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/youtube/dto/youtube.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.module.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.module.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/plat/youtube/youtube.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/bilibiliPub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/bilibiliPub.service.ts
deleted file mode 100644
index bf484724..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/bilibiliPub.service.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import {
- fileUrlToBase64,
- getFileTypeFromUrl,
- streamDownloadAndUpload,
-} from '../../../common'
-import { BilibiliService } from '../../../core/plat/bilibili/bilibili.service'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../libs/database/schema/publishTask.schema'
-import { DoPubRes } from '../common'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class BilibiliPubService extends PublishBase {
- override queueName: string = AccountType.BILIBILI
- private readonly logger = new Logger(BilibiliPubService.name)
-
- constructor(
- readonly bilibiliService: BilibiliService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- doPub(publishTask: PublishTask): Promise<DoPubRes> {
- return new Promise(async (resolve) => {
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
-
- // 封面上传
- const { coverUrl, accountId, videoUrl } = publishTask
- let biblCoverUrl = ''
- // 有封面
- if (coverUrl) {
- try {
- this.logger.log('正在上传封面...')
- const urlBase64 = await fileUrlToBase64(coverUrl)
- const coverRes = await this.bilibiliService.coverUpload(
- accountId,
- urlBase64,
- )
- if (!coverRes) {
- res.message = '封面上传失败'
- return resolve(res)
- }
- biblCoverUrl = coverRes
-
- this.logger.log('封面上传成功:', coverRes)
- }
- catch (e) {
- res.message = '封面上传失败'
- this.logger.log('封面上传失败', e)
- return resolve(res)
- }
- }
-
- if (!videoUrl) {
- res.message = '视频不存在'
- res.noRetry = true
- return resolve(res)
- }
- const fileName = getFileTypeFromUrl(videoUrl)
-
- this.logger.log('正在分片上传...')
- // 视频分片上传初始化
- const videoUpToken = await this.bilibiliService.videoInit(
- accountId,
- fileName,
- 0,
- )
- if (!videoUpToken) {
- res.message = '视频初始化失败'
- return resolve(res)
- }
-
- // 视频URL分片上传
- void streamDownloadAndUpload(
- videoUrl,
- async (upData: Buffer, partNumber: number) => {
- this.logger.log(`分片:${partNumber}`)
- await this.bilibiliService.uploadVideoPart(
- accountId,
- upData,
- videoUpToken,
- partNumber,
- )
- },
- async () => {
- this.logger.log('合并分片...')
- // 合并
- await this.bilibiliService.videoComplete(accountId, videoUpToken)
-
- this.logger.log('发布...')
- // 发布
- const resourceId = await this.bilibiliService.archiveAddByUtoken(
- accountId,
- videoUpToken,
- {
- title: publishTask.title || '',
- cover: biblCoverUrl,
- desc: publishTask.desc,
- ...publishTask.option!.bilibili!,
- tag: publishTask.topics?.join(','),
- },
- )
-
- if (!resourceId) {
- res.message = '稿件发布失败'
- return resolve(res)
- }
-
- // 完成发布任务
- void this.completePublishTask(publishTask, resourceId, {
- workLink: `https://www.bilibili.com/video/${resourceId}`,
- })
- res.message = '发布成功'
- res.status = 1
-
- resolve(res)
- },
- ).catch((e) => {
- resolve({
- message: e.message,
- status: PublishStatus.FAILED,
- })
- })
- })
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/kwaiPub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/kwaiPub.service.ts
deleted file mode 100644
index 4ddec644..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/kwaiPub.service.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * @Author: nevin
- * @Date: 2025-02-15 20:59:55
- * @LastEditTime: 2025-04-27 17:58:21
- * @LastEditors: nevin
- * @Description: b站
- */
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { KwaiService } from '../../../core/plat/kwai/kwai.service'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../libs/database/schema/publishTask.schema'
-import { DoPubRes } from '../common'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class kwaiPubService extends PublishBase {
- override queueName: string = AccountType.KWAI
-
- private readonly logger: Logger = new Logger(kwaiPubService.name)
- constructor(
- readonly kwaiService: KwaiService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- this.logger.log(`Processing Kwai Publish Task: ${publishTask.id}`)
- try {
- const res = await this.kwaiService.publishVideo(publishTask.accountId, {
- coverUrl: publishTask.coverUrl!,
- videoUrl: publishTask.videoUrl!,
- describe: publishTask.desc,
- })
- this.logger.log(`Kwai Publish Result: ${JSON.stringify(res)}`)
-
- if (res.success) {
- void this.completePublishTask(publishTask, res.worksId!, {
- workLink: `https://www.kuaishou.com/short-video/${res.worksId}`,
- })
- return {
- message: '发布成功',
- status: PublishStatus.PUBLISHED,
- }
- }
- else {
- return {
- message: res.failMsg || '发布失败,未知原因',
- status: PublishStatus.FAILED,
- }
- }
- }
- catch (e) {
- return {
- message: e.message || '发布失败,未知原因',
- status: PublishStatus.FAILED,
- }
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/facebook.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/facebook.service.ts
deleted file mode 100644
index 25b083c8..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/facebook.service.ts
+++ /dev/null
@@ -1,573 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import {
- chunkedDownloadFile,
- fileUrlToBlob,
- getRemoteFileSize,
-} from '../../../../common'
-import { FacebookService } from '../../../../core/plat/meta/facebook.service'
-import {
- PostCategory,
- PostMediaStatus,
- PostSubCategory,
-} from '../../../../libs/database/schema/postMediaContainer.schema'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../../libs/database/schema/publishTask.schema'
-import {
- ChunkedVideoUploadRequest,
- FacebookInitialVideoUploadRequest,
- FacebookReelRequest,
- finalizeVideoUploadRequest,
- PublishFeedPostRequest,
- PublishVideoPostRequest,
-} from '../../../../libs/facebook/facebook.interfaces'
-import { DoPubRes } from '../../common'
-import { PublishBase } from '../publish.base'
-import { PostMediaContainerService } from './container.service'
-import { MetaPostPublisher, PublishMetaPostTask } from './meta.interface'
-
-@Injectable()
-export class FacebookPublishService
- extends PublishBase
- implements MetaPostPublisher {
- override queueName: string = 'facebook'
-
- private readonly logger = new Logger(FacebookPublishService.name, {
- timestamp: true,
- })
-
- constructor(
- readonly facebookService: FacebookService,
- private readonly postMediaContainerService: PostMediaContainerService,
- ) {
- super()
- this.postMediaContainerService = postMediaContainerService
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- private generatePostMessage(publishTask: PublishTask): string {
- if (!publishTask) {
- return ''
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- return `${publishTask.desc || ''} #${publishTask.topics.join(' #')}`
- }
- return publishTask.desc || ''
- }
-
- async uploadImage(accountId: string, imgUrl: string): Promise<string> {
- const imgBlob = await fileUrlToBlob(imgUrl)
- const uploadReq = await this.facebookService.uploadImage(
- accountId,
- imgBlob.blob,
- )
- return uploadReq.id
- }
-
- async publishFeedPost(publishTask: PublishTask): Promise<PublishStatus> {
- this.logger.log(`Received publish task: ${publishTask.id} for Facebook Feed Post`)
- this.logger.debug(`Publish task details: ${JSON.stringify(publishTask)}`)
- if (!publishTask.desc) {
- this.logger.error('Feed Post requires a description')
- throw new Error('Feed Post requires a description')
- }
- const feedPostReq: PublishFeedPostRequest = {
- message: this.generatePostMessage(publishTask),
- published: true,
- }
- const postRes = await this.facebookService.publishFeedPost(
- publishTask.accountId,
- feedPostReq,
- )
- const permalink = `https://www.facebook.com/${publishTask.uid}_${postRes.id}`
- await this.completePublishTask(publishTask, postRes.id, {
- workLink: permalink,
- })
- return PublishStatus.PUBLISHED
- }
-
- async publishReelPost(publishTask: PublishTask): Promise<PublishStatus> {
- this.logger.log(`Received publish task: ${publishTask.id} for Facebook Reel`)
- this.logger.debug(`Publish task details: ${JSON.stringify(publishTask)}`)
- let status = PublishStatus.FAILED
-
- const { imgUrlList, accountId, videoUrl } = publishTask
- if (imgUrlList && imgUrlList.length > 0) {
- this.logger.error('Reel does not support image uploads')
- throw new Error('Reel does not support image uploads')
- }
- if (!videoUrl) {
- this.logger.error('Reel requires a video URL')
- throw new Error('Reel requires a video URL')
- }
-
- const contentLength = await getRemoteFileSize(videoUrl)
- const initUploadReq: FacebookReelRequest = {
- upload_phase: 'start',
- }
- const initUploadRes = await this.facebookService.initReelUpload(
- accountId,
- initUploadReq,
- )
- if (!initUploadRes || !initUploadRes.upload_url) {
- this.logger.error(`Video initialization upload failed, response: ${JSON.stringify(initUploadRes)}`)
- throw new Error('Video initialization upload failed')
- }
-
- const videoFile = await chunkedDownloadFile(videoUrl, [0, contentLength - 1])
- await this.facebookService.uploadReel(
- accountId,
- initUploadRes.upload_url,
- {
- offset: 0,
- file_size: contentLength,
- file: videoFile,
- },
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'facebook',
- taskId: initUploadRes.video_id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.STORY,
- subCategory: PostSubCategory.VIDEO,
- })
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000, // 每次重试间隔 10 秒, 总共尝试 30 次
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publishPhotoStory(publishTask: PublishTask): Promise<PublishStatus> {
- this.logger.log(`Received publish task: ${publishTask.id} for Facebook Story`)
- this.logger.debug(`Publish task details: ${JSON.stringify(publishTask)}`)
- let status = PublishStatus.FAILED
- const { imgUrlList, accountId } = publishTask
- if (!imgUrlList) {
- this.logger.error('Story requires images')
- throw new Error('Story requires images')
- }
-
- if (imgUrlList && imgUrlList.length < 1) {
- this.logger.error('Story requires at least one image')
- throw new Error('Story requires at least one image')
- }
-
- const imgUrl = imgUrlList[0]
- const containerId = await this.uploadImage(accountId, imgUrl)
-
- await this.facebookService.publishPhotoStory(
- accountId,
- containerId,
- )
- const permalink = `https://www.facebook.com/stories/${containerId}`
- await this.completePublishTask(publishTask, containerId, {
- workLink: permalink,
- })
- await this.completePublishTask(publishTask, containerId)
- status = PublishStatus.PUBLISHED
- return status
- }
-
- async publishVideoStory(publishTask: PublishTask): Promise<PublishStatus> {
- let status = PublishStatus.FAILED
- if (!publishTask.videoUrl) {
- this.logger.error('Story requires a video URL')
- throw new Error('Story requires a video URL')
- }
- const contentLength = await getRemoteFileSize(publishTask.videoUrl)
- const initUploadReq: FacebookReelRequest = {
- upload_phase: 'start',
- }
- const initUploadRes = await this.facebookService.initVideoStoryUpload(
- publishTask.accountId,
- initUploadReq,
- )
- if (!initUploadRes || !initUploadRes.upload_url) {
- this.logger.error(`Video initialization upload failed, response: ${JSON.stringify(initUploadRes)}`)
- throw new Error('Video initialization upload failed')
- }
- const videoFile = await chunkedDownloadFile(publishTask.videoUrl, [0, contentLength - 1])
- await this.facebookService.uploadVideoStory(
- publishTask.accountId,
- initUploadRes.upload_url,
- {
- offset: 0,
- file_size: contentLength,
- file: videoFile,
- },
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'facebook',
- taskId: initUploadRes.video_id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.STORY,
- subCategory: PostSubCategory.VIDEO,
- })
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publishStory(publishTask: PublishTask): Promise<PublishStatus> {
- this.logger.log(`Received publish task: ${publishTask.id} for Facebook Story`)
- this.logger.debug(`Publish task details: ${JSON.stringify(publishTask)}`)
- const { imgUrlList, videoUrl } = publishTask
- if (!videoUrl && !imgUrlList) {
- this.logger.error('Story requires a video or images')
- throw new Error('Story requires a video or images')
- }
-
- if (imgUrlList && imgUrlList.length > 0) {
- return await this.publishPhotoStory(publishTask)
- }
- return await this.publishVideoStory(publishTask)
- }
-
- async publishVideo(publishTask: PublishTask): Promise<PublishStatus> {
- this.logger.log(`Received publish task: ${publishTask.id} for Facebook`)
- this.logger.debug(`Publish task details: ${JSON.stringify(publishTask)}`)
- let status = PublishStatus.FAILED
- const { imgUrlList, accountId, videoUrl } = publishTask
- const facebookMediaIdList: string[] = []
- if (imgUrlList && imgUrlList.length > 0) {
- for (const imgUrl of imgUrlList) {
- const imgBlob = await fileUrlToBlob(imgUrl)
- const uploadReq = await this.facebookService.uploadImage(
- accountId,
- imgBlob.blob,
- )
- facebookMediaIdList.push(uploadReq.id)
- }
- if (facebookMediaIdList.length === 0) {
- throw new Error('Image upload failed')
- }
- const publishMediaPost = await this.facebookService.publicPhotoPost(
- accountId,
- facebookMediaIdList,
- this.generatePostMessage(publishTask),
- )
- const permalink = `https://www.facebook.com/${publishTask.uid}_${publishMediaPost.id}`
- await this.completePublishTask(publishTask, publishMediaPost.id, {
- workLink: permalink,
- })
- status = PublishStatus.PUBLISHED
- return status
- }
-
- if (videoUrl) {
- const contentLength = await getRemoteFileSize(videoUrl)
-
- const initUploadReq: FacebookInitialVideoUploadRequest = {
- upload_phase: 'start',
- file_size: contentLength,
- published: false,
- }
- const initUploadRes = await this.facebookService.initVideoUpload(
- accountId,
- initUploadReq,
- )
- let startOffset = initUploadRes.start_offset
- let endOffset = initUploadRes.end_offset
-
- while (startOffset < contentLength - 1) {
- const range: [number, number] = [startOffset, endOffset - 1]
- const videoBlob = await chunkedDownloadFile(videoUrl, range)
- const chunkedUploadReq: ChunkedVideoUploadRequest = {
- upload_phase: 'transfer',
- upload_session_id: initUploadRes.upload_session_id,
- start_offset: startOffset,
- end_offset: endOffset,
- video_file_chunk: videoBlob,
- published: false,
- }
- this.logger.log(`Chunked upload request: start_offset=${startOffset}, end_offset=${endOffset}`)
- const chunkedUploadRes
- = await this.facebookService.chunkedMediaUpload(
- accountId,
- chunkedUploadReq,
- )
- startOffset = chunkedUploadRes.start_offset
- endOffset = chunkedUploadRes.end_offset
- }
- const finalizeReq: finalizeVideoUploadRequest = {
- upload_phase: 'finish',
- upload_session_id: initUploadRes.upload_session_id,
- published: false,
- }
- const finalizeRes = await this.facebookService.finalizeMediaUpload(
- accountId,
- finalizeReq,
- )
- if (!finalizeRes.success) {
- throw new Error('Video upload finalization failed')
- }
- const videoPostReq: PublishVideoPostRequest = {
- description: this.generatePostMessage(publishTask),
- crossposted_video_id: initUploadRes.video_id,
- published: true,
- }
- const postRes = await this.facebookService.publishVideoPost(
- accountId,
- videoPostReq,
- )
- const permalink = `https://www.facebook.com/${publishTask.uid}_${postRes.id}`
- await this.completePublishTask(publishTask, postRes.id, {
- workLink: permalink,
- })
- status = PublishStatus.PUBLISHED
- return status
- }
- return status
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: 'Publish task not found',
- }
-
- const contentCategory = publishTask.option?.facebook?.content_category
- if (!contentCategory) {
- this.logger.error('Invalid publish task: no Facebook page contentCategory specified')
- res.message = 'Invalid publish task: no Facebook page contentCategory specified'
- return res
- }
- const { imgUrlList, videoUrl, desc } = publishTask
- if (!imgUrlList && !videoUrl && !desc) {
- this.logger.error('Invalid publish task: no media and no description')
- res.message = 'Invalid publish task: no media and no description'
- return res
- }
-
- try {
- switch (contentCategory) {
- case 'post':
- if (!imgUrlList && !videoUrl) {
- res.status = await this.publishFeedPost(publishTask)
- res.message = 'Publish feed post successfully'
- return res
- }
- else {
- res.status = await this.publishVideo(publishTask)
- res.message = 'Video post published successfully'
- return res
- }
- case 'reel':
- res.status = await this.publishReelPost(publishTask)
- res.message = 'Waiting for media processing'
- return res
- case 'story':
- res.status = await this.publishStory(publishTask)
- res.message = 'Story published successfully'
- if (res.status === PublishStatus.PUBLISHING) {
- res.message = 'Waiting for media processing'
- }
- return res
- default:
- this.logger.error(`Unsupported content category: ${contentCategory}`)
- res.message = `Unsupported content category: ${contentCategory}`
- return res
- }
- }
- catch (error) {
- this.logger.error(`Publish task failed: ${error.message}`, error.stack)
- res.message = error.message || 'Publish task failed'
- return res
- }
- }
-
- async publish(task: PublishTask): Promise<DoPubRes> {
- try {
- this.logger.log(`publish: Starting to process task ID: ${task.id}`)
- const medias = await this.postMediaContainerService.getContainers(
- task.id,
- )
- if (!medias || medias.length === 0) {
- return {
- status: PublishStatus.FAILED,
- message: 'Media not found for the task',
- noRetry: true,
- }
- }
- const unProcessedMedias = medias.filter(
- media => media.status !== PostMediaStatus.FINISHED,
- )
- this.logger.log(
- `Found ${medias.length} media files for task ID: ${task.id}`,
- )
- let processedCount = 0
- for (const media of unProcessedMedias) {
- const mediaStatusInfo = await this.facebookService.getObjectInfo(task.accountId, media.taskId, 'status')
- this.logger.log(`Media status for task ID ${task.id}, media ID ${media.taskId}: ${JSON.stringify(mediaStatusInfo)}`)
- if (mediaStatusInfo.status.video_status === 'error') {
- this.logger.error(
- `Media processing failed for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- await this.postMediaContainerService.updateContainer(media.id, {
- status: PostMediaStatus.FAILED,
- })
- return {
- status: PublishStatus.FAILED,
- message: 'Media processing failed',
- noRetry: true,
- }
- }
- let mediaStatus = PostMediaStatus.CREATED
- if (
- mediaStatusInfo.status.video_status === 'processing'
- || mediaStatusInfo.status.video_status === 'encoded'
- ) {
- mediaStatus = PostMediaStatus.IN_PROGRESS
- }
- if (mediaStatusInfo.status.video_status === 'upload_complete') {
- this.logger.log(
- `Media processing finished for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- mediaStatus = PostMediaStatus.FINISHED
- processedCount++
- }
- await this.postMediaContainerService.updateContainer(media.id, {
- status: mediaStatus,
- })
- }
- const isMediaCompleted = processedCount === unProcessedMedias.length
- if (!isMediaCompleted) {
- this.logger.warn(`Not all media files processed for task ID: ${task.id}. Processed: ${processedCount}, Total: ${medias.length}`)
- throw new Error(`Media files are still processing. Processed: ${processedCount}, Total: ${medias.length}`)
- }
- this.logger.log(`All media files processed for task ID: ${task.id}`)
- let publishRes
- if (task.option?.facebook?.content_category === 'reel') {
- publishRes = await this.facebookService.publishReel(task.accountId, {
- upload_phase: 'finish',
- video_state: 'published',
- video_id: unProcessedMedias[0].taskId,
- description: this.generatePostMessage(task),
- })
- }
- if (task.option?.facebook?.content_category === 'story') {
- publishRes = await this.facebookService.publishVideoStory(
- task.accountId,
- {
- upload_phase: 'finish',
- video_state: 'published',
- video_id: unProcessedMedias[0].taskId,
- description: this.generatePostMessage(task),
- },
- )
- }
- this.logger.log(
- `publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(publishRes)}`,
- )
- if (!publishRes || !publishRes.success) {
- this.logger.log(
- `Failed to publish media container for task ID: ${task.id}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: '发布媒体容器失败',
- noRetry: true,
- }
- }
- let category = 'stories'
- if (task.option?.facebook?.content_category === 'reel') {
- category = 'reel'
- }
- const permalink = `https://www.facebook.com/${category}/${unProcessedMedias[0].taskId}`
-
- this.logger.log(
- `Successfully published media container for task ID: ${task.id}`,
- )
- await this.completePublishTask(task, unProcessedMedias[0].taskId, {
- workLink: permalink,
- })
- this.logger.log(`completed: Task ID ${task.id} processed successfully`)
- return {
- status: PublishStatus.PUBLISHED,
- message: '所有媒体文件已处理完成',
- }
- }
- catch (error) {
- this.logger.error(
- `Error processing task ID ${task.id}: ${error.message || error}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: `发布失败: ${error.message || error}`,
- noRetry: true,
- }
- }
- }
-
- override async pushPubTask(newData: PublishTask, attempts = 0): Promise<boolean> {
- await this.publishQueueOpen(newData.id)
- const jobRes = await this.queueService.addPostPublishJob(
- {
- taskId: newData.id,
- attempts: attempts++, // 进行次数
- jobId: newData.queueId,
- },
- {
- attempts: this.queueAttempts,
- backoff: {
- type: 'exponential',
- delay: 20000, // 每次重试间隔 20 秒
- },
- removeOnComplete: true,
- jobId: newData.queueId, // 确保任务id唯一,防止重复执行
- },
- )
- return jobRes.id === newData.queueId
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/instgram.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/instgram.service.ts
deleted file mode 100644
index 50285667..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/instgram.service.ts
+++ /dev/null
@@ -1,442 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { InstagramService } from '../../../../core/plat/meta/instagram.service'
-import {
- PostCategory,
- PostMediaStatus,
- PostSubCategory,
-} from '../../../../libs/database/schema/postMediaContainer.schema'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../../libs/database/schema/publishTask.schema'
-import { InstagramMediaType } from '../../../../libs/instagram/instagram.enum'
-import { CreateMediaContainerRequest } from '../../../../libs/instagram/instagram.interfaces'
-import { DoPubRes } from '../../common'
-import { PublishBase } from '../publish.base'
-import { PostMediaContainerService } from './container.service'
-import { MetaPostPublisher, PublishMetaPostTask } from './meta.interface'
-
-@Injectable()
-export class InstagramPublishService
- extends PublishBase
- implements MetaPostPublisher {
- override queueName: string = 'instagram'
- private readonly logger = new Logger(InstagramPublishService.name, {
- timestamp: true,
- })
-
- constructor(
- readonly instagramService: InstagramService,
- private readonly postMediaContainerService: PostMediaContainerService,
- ) {
- super()
- this.postMediaContainerService = postMediaContainerService
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- private generatePostMessage(publishTask: PublishTask): string {
- if (!publishTask) {
- return ''
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- return `${publishTask.desc || ''} #${publishTask.topics.join(' #')}`
- }
- return publishTask.desc || ''
- }
-
- private async createMediaContainer(publishTask: PublishTask, srcImgURL, mediaType = InstagramMediaType.IMAGE, isCarouselItem = false): Promise<void> {
- const createContainerReq: CreateMediaContainerRequest = {
- media_type: mediaType,
- image_url: srcImgURL,
- caption: this.generatePostMessage(publishTask) || publishTask.title || '',
- }
- if (isCarouselItem) {
- createContainerReq.is_carousel_item = true
- }
- const initUploadRes = await this.instagramService.createMediaContainer(
- publishTask.accountId,
- createContainerReq,
- )
- try {
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'instagram',
- taskId: initUploadRes.id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.POST,
- subCategory: PostSubCategory.PHOTO,
- })
- }
- catch (error) {
- this.logger.error(`Create media record failed: ${error.message || error}`, error.stack)
- throw new Error(`Create media record failed: ${error.message || error}`)
- }
- }
-
- async publishPost(publishTask: PublishTask): Promise<PublishStatus> {
- let status = PublishStatus.FAILED
- if (!publishTask.imgUrlList || publishTask.imgUrlList.length === 0) {
- throw new Error('No image resources')
- }
- const isCarouselItem = publishTask.imgUrlList.length > 1
- for (const imgUrl of publishTask.imgUrlList) {
- await this.createMediaContainer(publishTask, imgUrl, InstagramMediaType.IMAGE, isCarouselItem)
- }
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
-
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publishReel(publishTask: PublishTask): Promise<PublishStatus> {
- let status = PublishStatus.FAILED
- if (!publishTask.videoUrl) {
- throw new Error('No video resources')
- }
-
- const createContainerReq: CreateMediaContainerRequest = {
- video_url: publishTask.videoUrl,
- media_type: InstagramMediaType.REELS,
- caption: publishTask.desc || publishTask.title || '',
- }
- const initUploadRes = await this.instagramService.createMediaContainer(
- publishTask.accountId,
- createContainerReq,
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'instagram',
- taskId: initUploadRes.id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.REELS,
- subCategory: PostSubCategory.VIDEO,
- })
-
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publishVideoStory(publishTask: PublishTask): Promise<PublishStatus> {
- let status = PublishStatus.FAILED
- if (!publishTask.videoUrl) {
- throw new Error('No video resources')
- }
- const createContainerReq: CreateMediaContainerRequest = {
- video_url: publishTask.videoUrl,
- media_type: InstagramMediaType.STORIES,
- caption: this.generatePostMessage(publishTask) || publishTask.title || '',
- }
- const initUploadRes = await this.instagramService.createMediaContainer(
- publishTask.accountId,
- createContainerReq,
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'instagram',
- taskId: initUploadRes.id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.STORY,
- subCategory: PostSubCategory.VIDEO,
- })
-
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publishPhotoStory(publishTask: PublishTask): Promise<PublishStatus> {
- let status = PublishStatus.FAILED
- if (!publishTask.imgUrlList || publishTask.imgUrlList.length === 0) {
- throw new Error('No image resources')
- }
- const createContainerReq: CreateMediaContainerRequest = {
- media_type: InstagramMediaType.STORIES,
- image_url: publishTask.imgUrlList[0],
- }
- const initUploadRes = await this.instagramService.createMediaContainer(
- publishTask.accountId,
- createContainerReq,
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'instagram',
- taskId: initUploadRes.id,
- status: PostMediaStatus.CREATED,
- category: PostCategory.STORY,
- subCategory: PostSubCategory.PHOTO,
- })
-
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- await this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- status = PublishStatus.PUBLISHING
- return status
- }
-
- async publish(task: PublishTask): Promise<DoPubRes> {
- try {
- this.logger.log(`publish: Starting to process task ID: ${task.id}`)
- const medias = await this.postMediaContainerService.getContainers(
- task.id,
- )
- if (!medias || medias.length === 0) {
- return {
- status: PublishStatus.FAILED,
- message: 'Media not found for the task',
- }
- }
- for (const media of medias) {
- if (media.status === PostMediaStatus.FINISHED) {
- continue
- }
- const mediaStatusInfo = await this.instagramService.getObjectInfo(
- task.accountId,
- media.taskId,
- '',
- )
- if (!mediaStatusInfo || !mediaStatusInfo.id) {
- this.logger.error(
- `Failed to get media status for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- continue
- }
- this.logger.log(
- `Media status for task ID ${task.id}, media ID ${media.taskId}: ${JSON.stringify(mediaStatusInfo)}`,
- )
- if (mediaStatusInfo.status === 'FAILED') {
- this.logger.error(
- `Media processing failed for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- await this.postMediaContainerService.updateContainer(media.id, {
- status: PostMediaStatus.FAILED,
- })
- return {
- status: PublishStatus.FAILED,
- message: 'Media processing failed',
- noRetry: true,
- }
- }
- let mediaStatus = PostMediaStatus.CREATED
- if (mediaStatusInfo.status === 'IN_PROGRESS') {
- mediaStatus = PostMediaStatus.IN_PROGRESS
- }
- if (mediaStatusInfo.status === 'FINISHED') {
- this.logger.log(
- `Media processing finished for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- mediaStatus = PostMediaStatus.FINISHED
- }
- await this.postMediaContainerService.updateContainer(media.id, {
- status: mediaStatus,
- })
- }
- const completedCount = await this.postMediaContainerService.getCompletedContainersCount(task.id)
- const isMediaCompleted = completedCount === medias.length
- if (!isMediaCompleted) {
- this.logger.warn(`Not all media files processed for task ID: ${task.id}. Processed: ${completedCount}, Total: ${medias.length}`)
- throw new Error(`Media files are still processing. Processed: ${completedCount}, Total: ${medias.length}`)
- }
- this.logger.log(`All media files processed for task ID: ${task.id}`)
-
- const postCategory = medias[0].category
-
- let containerTypes = InstagramMediaType.IMAGE
- if (postCategory === PostCategory.STORY) {
- containerTypes = InstagramMediaType.STORIES
- }
- else if (postCategory === PostCategory.REELS) {
- containerTypes = InstagramMediaType.REELS
- }
-
- let containerId = medias[0].taskId
-
- const isCarousel = postCategory === PostCategory.POST && medias.length > 1
- if (isCarousel) {
- containerTypes = InstagramMediaType.CAROUSEL
- const containerIdList = medias.map(media => media.taskId)
- const createContainerReq: CreateMediaContainerRequest = {
- media_type: containerTypes,
- children: containerIdList,
- caption: this.generatePostMessage(task) || task.title || '',
- }
- const postContainer = await this.instagramService.createMediaContainer(
- task.accountId,
- createContainerReq,
- )
- containerId = postContainer.id
- }
- this.logger.log(`Container ID for task ID ${task.id}: ${containerId}`)
- const publishRes = await this.instagramService.publishMediaContainer(
- task.accountId,
- containerId,
- )
- this.logger.log(`publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(publishRes)}`)
- let permalink = ''
- try {
- const objectInfo = await this.instagramService.getObjectInfo(
- task.accountId,
- publishRes.id,
- '',
- 'permalink',
- )
- this.logger.log(
- `publish: Retrieved object info for task ID: ${task.id}, response: ${JSON.stringify(objectInfo)}`,
- )
- if (objectInfo && objectInfo.permalink) {
- permalink = objectInfo.permalink
- }
- }
- catch (error) {
- this.logger.error(
- `Failed to get permalink for task ID: ${task.id}, error: ${error.message || error}`,
- )
- }
- this.logger.log(
- `Successfully published media container for task ID: ${task.id}`,
- )
- await this.completePublishTask(task, publishRes.id, {
- workLink: permalink,
- })
- this.logger.log(`completed: Task ID ${task.id} processed successfully`)
- return {
- status: PublishStatus.PUBLISHED,
- message: 'Post published successfully',
- }
- }
- catch (error) {
- this.logger.error(
- `Error processing task ID ${task.id}: ${error.message || error}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: error.message || 'Post publish failed',
- noRetry: true,
- }
- }
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: PublishStatus.FAILED,
- message: 'Publish task not found',
- }
- try {
- const postCategory = publishTask.option?.instagram?.content_category
- switch (postCategory) {
- case 'post':
- res.status = await this.publishPost(publishTask)
- break
- case 'reel':
- res.status = await this.publishReel(publishTask)
- break
- case 'story':
- if (publishTask.videoUrl) {
- res.status = await this.publishVideoStory(publishTask)
- }
- else {
- res.status = await this.publishPhotoStory(publishTask)
- }
- break
- default:
- res.message = 'Unknown content category'
- return res
- }
- res.message = 'Post published successfully'
- if (res.status === PublishStatus.PUBLISHING) {
- res.message = 'Media processing, publishing in progress'
- }
- return res
- }
- catch (error) {
- this.logger.error(`Publish error for task ID ${publishTask.id}: ${error.message || error}`, error.stack)
- res.message = error.message || 'Post publish failed'
- return res
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.interface.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.interface.ts
deleted file mode 100644
index a9613bcb..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.interface.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { PublishTask } from '../../../../libs/database/schema/publishTask.schema'
-import { DoPubRes } from '../../common'
-
-export interface PublishMetaPostTask {
- id: string
-}
-
-export interface MetaPostPublisher {
- publish: (task: PublishTask) => Promise<DoPubRes>
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.module.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.module.ts
deleted file mode 100644
index 60f39d5e..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.module.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { BullModule } from '@nestjs/bullmq'
-import { Module } from '@nestjs/common'
-import { MongooseModule } from '@nestjs/mongoose'
-import { MetaModule } from '../../../../core/plat/meta/meta.module'
-import { TwitterModule } from '../../../../core/plat/twitter/twitter.module'
-import { Account, AccountSchema } from '../../../../libs/database/schema/account.schema'
-import { PostMediaContainer, PostMediaContainerSchema } from '../../../../libs/database/schema/postMediaContainer.schema'
-import { PublishTask, PublishTaskSchema } from '../../../../libs/database/schema/publishTask.schema'
-import { PostMediaContainerService } from './container.service'
-import { FacebookPublishService } from './facebook.service'
-import { InstagramPublishService } from './instgram.service'
-import { LinkedinPublishService } from './linkedin.service'
-import { MetaPublishService } from './meta.service'
-import { ThreadsPublishService } from './threads.service'
-import { TwitterPublishService } from './twitter.service'
-
-@Module({
- controllers: [],
- providers: [
- MetaPublishService,
- FacebookPublishService,
- InstagramPublishService,
- ThreadsPublishService,
- PostMediaContainerService,
- TwitterPublishService,
- LinkedinPublishService,
- ],
- exports: [
- MetaPublishService,
- FacebookPublishService,
- InstagramPublishService,
- ThreadsPublishService,
- PostMediaContainerService,
- TwitterPublishService,
- LinkedinPublishService,
- ],
- imports: [
- MetaModule,
- TwitterModule,
- BullModule.registerQueue({
- name: 'post_publish',
- }),
- BullModule.registerQueue({
- name: 'post_media_task',
- defaultJobOptions: {
- delay: 60000, // 60 seconds
- removeOnComplete: true,
- },
- }),
- MongooseModule.forFeature([
- { name: Account.name, schema: AccountSchema },
- { name: PublishTask.name, schema: PublishTaskSchema },
- { name: PostMediaContainer.name, schema: PostMediaContainerSchema },
- ]),
- ],
-})
-export class MetaPublishModule { }
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.service.ts
deleted file mode 100644
index 81f8d00d..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/meta.service.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { PublishStatus, PublishTask } from '../../../../libs/database/schema/publishTask.schema'
-import { DoPubRes } from '../../common'
-import { FacebookPublishService } from './facebook.service'
-import { InstagramPublishService } from './instgram.service'
-import { MetaPostPublisher } from './meta.interface'
-import { ThreadsPublishService } from './threads.service'
-import { TwitterPublishService } from './twitter.service'
-
-@Injectable()
-export class MetaPublishService {
- private readonly publishSrvMap = new Map<AccountType, MetaPostPublisher>()
- private readonly logger = new Logger(MetaPublishService.name)
- constructor(
- private readonly instagramPublishService: InstagramPublishService,
- private readonly threadPublishService: ThreadsPublishService,
- private readonly twitterPublishService: TwitterPublishService,
- private readonly facebookPublishService: FacebookPublishService,
- ) {
- this.publishSrvMap.set(AccountType.INSTAGRAM, this.instagramPublishService)
- this.publishSrvMap.set(AccountType.THREADS, this.threadPublishService)
- this.publishSrvMap.set(AccountType.TWITTER, this.twitterPublishService)
- this.publishSrvMap.set(AccountType.FACEBOOK, this.facebookPublishService)
- }
-
- async publishPost(publishTask: PublishTask): Promise<DoPubRes> {
- this.logger.log(`accountType: ${publishTask.accountType}, taskId: ${publishTask.id}`)
- this.logger.log(this.publishSrvMap.keys())
- const service = this.publishSrvMap.get(publishTask.accountType)
- if (!service) {
- return {
- status: PublishStatus.FAILED,
- message: '未找到该平台的发布服务',
- noRetry: true,
- }
- }
- const res = await service.publish(publishTask)
- return res
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/publish.consumer.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/publish.consumer.ts
deleted file mode 100644
index 6c3057c0..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/publish.consumer.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'
-import { Logger, OnModuleDestroy } from '@nestjs/common'
-import { QueueName } from '@yikart/aitoearn-queue'
-import { Job } from 'bullmq'
-import { PublishStatus } from '../../../../libs/database/schema/publishTask.schema'
-import { PublishTaskService } from '../../publishTask.service'
-import { MetaPublishService } from './meta.service'
-
-@Processor(QueueName.PostMediaTask, {
- concurrency: 3,
- stalledInterval: 15000,
- maxStalledCount: 1,
-})
-export class MetaPublishConsumer extends WorkerHost implements OnModuleDestroy {
- private readonly logger = new Logger(MetaPublishConsumer.name)
- constructor(
- readonly publishTaskService: PublishTaskService,
- readonly metaPublishService: MetaPublishService,
- ) {
- super()
- }
-
- async process(job: Job<{
- taskId: string
- attempts: number
- }>): Promise<any> {
- this.logger.log(`[task-${job.data.taskId}] Processing Meta Post Publish Task: ${job.data.taskId}`)
- try {
- const publishTaskInfo = await this.publishTaskService.getPublishTaskInfo(job.data.taskId)
- const publishTask = publishTaskInfo!.toObject()
- if (!publishTask) {
- this.logger.error(`[task-${job.data.taskId}] Publish task not found: ${job.data.taskId}`)
- return
- }
- publishTask.publishTime = new Date()
- this.logger.log(`[task-${job.data.taskId}] Publish task details: ${JSON.stringify(publishTask)}`)
- const { status, message } = await this.metaPublishService.publishPost(publishTask)
-
- if (status !== PublishStatus.PUBLISHED) {
- this.logger.error(`[task-${job.data.taskId}] Publish task failed: ${job.data.taskId}, Message: ${message}`)
- throw new Error(message)
- }
- this.logger.debug(`[task-${job.data.taskId}] Publish task details: ${JSON.stringify(publishTask)}`)
- return { status: 'success', message: 'Post published successfully' }
- }
- catch (error) {
- this.logger.error(`[task-${job.data.taskId}] Error processing job ${job.id}: ${error.message}`, error.stack)
- throw new Error(`[task-${job.data.taskId}] Job ${job.id} failed: ${error.message}`)
- }
- }
-
- @OnWorkerEvent('completed')
- async onCompleted(job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- }>) {
- const { attempts } = job.data
- this.logger.log(`[task-${job.data.taskId}] Publish Post Task completed: ${job.data.taskId} after ${job.attemptsMade} attempts (max: ${attempts})`)
- }
-
- @OnWorkerEvent('failed')
- async onFailed(job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- }>, error: Error) {
- const { taskId } = job.data
- if (job.attemptsMade === job.opts.attempts) {
- this.logger.error(`[task-${job.data.taskId}] Job ${taskId} failed after all attempts: ${error.message}`)
- await this.publishTaskService.updatePublishTaskStatus(taskId, {
- status: PublishStatus.FAILED,
- errorMsg: error.message,
- })
- this.logger.log(`[task-${job.data.taskId}] Publish task ${taskId} marked as failed after all attempts. and removed from queue.`)
- return
- }
- this.logger.warn(`[task-${job.data.taskId}] Job ${taskId} failed, retrying... Attempts made: ${job.attemptsMade}`)
- }
-
- @OnWorkerEvent('stalled')
- onStalled(job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- }>) {
- this.logger.error(`[task-${job.data.taskId}] Job stalled: ${job.id}`)
- }
-
- async onModuleDestroy() {
- this.logger.log('MetaPublishConsumer is being destroyed, closing worker...')
- await this.worker.close()
- this.logger.log('MetaPublishConsumer closed successfully')
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/threads.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/threads.service.ts
deleted file mode 100644
index 64f795df..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/threads.service.ts
+++ /dev/null
@@ -1,344 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { ThreadsService } from '../../../../core/plat/meta/threads.service'
-import { PostMediaStatus } from '../../../../libs/database/schema/postMediaContainer.schema'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../../libs/database/schema/publishTask.schema'
-import { ThreadsMediaType } from '../../../../libs/threads/threads.enum'
-import { ThreadsContainerRequest } from '../../../../libs/threads/threads.interfaces'
-import { DoPubRes } from '../../common'
-import { PublishBase } from '../publish.base'
-import { PostMediaContainerService } from './container.service'
-import { MetaPostPublisher, PublishMetaPostTask } from './meta.interface'
-
-@Injectable()
-export class ThreadsPublishService
- extends PublishBase
- implements MetaPostPublisher {
- override queueName: string = 'threads'
- private readonly logger = new Logger(ThreadsPublishService.name, {
- timestamp: true,
- })
-
- constructor(
- readonly threadsService: ThreadsService,
- private readonly postMediaContainerService: PostMediaContainerService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: 'Task not found',
- }
- try {
- const { imgUrlList, accountId, videoUrl } = publishTask
- if (imgUrlList && imgUrlList.length > 0) {
- const isCarouselItem = imgUrlList.length > 1
- for (const imgUrl of imgUrlList) {
- const createContainerReq: ThreadsContainerRequest = {
- media_type: 'IMAGE',
- image_url: imgUrl,
- text: publishTask.desc || '',
- }
- if (
- publishTask.option
- && publishTask.option.threads
- && publishTask.option.threads.location_id
- ) {
- createContainerReq.location_id
- = publishTask.option.threads.location_id
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- createContainerReq.topic_tag = publishTask.topics[0]
- }
- if (isCarouselItem) {
- createContainerReq.is_carousel_item = true
- }
- const container = await this.threadsService.createItemContainer(
- accountId,
- createContainerReq,
- )
- if (!container) {
- res.message = 'Create image container failed'
- return res
- }
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'threads',
- taskId: container.id,
- status: PostMediaStatus.CREATED,
- })
- }
- }
- else if (videoUrl) {
- const createContainerReq: ThreadsContainerRequest = {
- media_type: 'VIDEO',
- video_url: videoUrl,
- text: publishTask.desc || '',
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- createContainerReq.topic_tag = publishTask.topics[0]
- }
- if (imgUrlList && imgUrlList.length > 0) {
- createContainerReq.is_carousel_item = true
- }
- if (
- publishTask.option
- && publishTask.option.threads
- && publishTask.option.threads.location_id
- ) {
- createContainerReq.location_id
- = publishTask.option.threads.location_id
- }
- const container = await this.threadsService.createItemContainer(
- accountId,
- createContainerReq,
- )
- if (!container) {
- res.message = 'Create video container failed'
- return res
- }
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'threads',
- taskId: container.id,
- status: PostMediaStatus.CREATED,
- })
- }
- else {
- const createContainerReq: ThreadsContainerRequest = {
- media_type: 'TEXT',
- text: publishTask.desc || '',
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- createContainerReq.topic_tag = publishTask.topics[0]
- }
- if (
- publishTask.option
- && publishTask.option.threads
- && publishTask.option.threads.location_id
- ) {
- createContainerReq.location_id
- = publishTask.option.threads.location_id
- }
- const container = await this.threadsService.createItemContainer(
- accountId,
- createContainerReq,
- )
- if (!container) {
- res.message = 'Create video container failed'
- return res
- }
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'threads',
- taskId: container.id,
- status: PostMediaStatus.CREATED,
- })
- }
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- const result = this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 30,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
-
- this.logger.log(`Media task added to queue: ${result}`)
- res.status = PublishStatus.PUBLISHING
- res.message = 'Publish task is being processed'
- return res
- }
- catch (error) {
- res.message = error.message
- return res
- }
- }
-
- async publish(task: PublishTask): Promise<DoPubRes> {
- const containers = await this.postMediaContainerService.getContainers(
- task.id,
- )
- if (!containers || containers.length === 0) {
- return {
- status: PublishStatus.FAILED,
- message: 'Media container not found',
- noRetry: true,
- }
- }
- const unProcessedContainers = containers.filter(
- media => media.status !== PostMediaStatus.FINISHED,
- )
- this.logger.log(
- `Found ${containers.length} media files for task ID: ${task.id}`,
- )
- let processedCount = 0
- for (const media of unProcessedContainers) {
- const mediaStatusInfo = await this.threadsService.getObjectInfo(
- task.accountId,
- media.taskId,
- '',
- )
- if (!mediaStatusInfo || !mediaStatusInfo.id) {
- this.logger.error(
- `Failed to get media status for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- continue
- }
- this.logger.log(
- `Media status for task ID ${task.id}, media ID ${media.taskId}: ${JSON.stringify(mediaStatusInfo)}`,
- )
- if (mediaStatusInfo.status === 'FAILED') {
- this.logger.error(
- `Media processing failed for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- await this.postMediaContainerService.updateContainer(media.id, {
- status: PostMediaStatus.FAILED,
- })
- return {
- status: PublishStatus.FAILED,
- message: 'Media processing failed',
- noRetry: true,
- }
- }
- let mediaStatus = PostMediaStatus.CREATED
- if (mediaStatusInfo.status === 'IN_PROGRESS') {
- mediaStatus = PostMediaStatus.IN_PROGRESS
- }
- if (mediaStatusInfo.status === 'FINISHED') {
- this.logger.log(
- `Media processing finished for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- mediaStatus = PostMediaStatus.FINISHED
- processedCount++
- }
- await this.postMediaContainerService.updateContainer(media.id, {
- status: mediaStatus,
- })
- }
- const isMediaCompleted = processedCount === unProcessedContainers.length
- if (!isMediaCompleted) {
- this.logger.warn(
- `Not all media files processed for task ID: ${task.id}. Processed: ${processedCount}, Total: ${containers.length}`,
- )
- return {
- status: PublishStatus.PUBLISHING,
- message: 'Media files are still processing',
- }
- }
- this.logger.log(`All media files processed for task ID: ${task.id}`)
- let containerTypes = ThreadsMediaType.VIDEO
- let containerId = containers[0].taskId
-
- if (containers.length > 1) {
- containerTypes = ThreadsMediaType.CAROUSEL
- const containerIdList = containers.map(media => media.taskId)
- const createContainerReq: ThreadsContainerRequest = {
- media_type: containerTypes,
- children: containerIdList,
- text: task.desc || '',
- }
- if (task.topics && task.topics.length > 0) {
- createContainerReq.topic_tag = task.topics[0]
- }
- if (
- task.option
- && task.option.threads
- && task.option.threads.location_id
- ) {
- createContainerReq.location_id = task.option.threads.location_id
- }
- const postContainer = await this.threadsService.createItemContainer(
- task.accountId,
- createContainerReq,
- )
- if (!postContainer || !postContainer.id) {
- this.logger.error(
- `Failed to create media container for task ID: ${task.id}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: 'Create media container failed',
- noRetry: true,
- }
- }
- containerId = postContainer.id
- }
- this.logger.log(`Container ID for task ID ${task.id}: ${containerId}`)
- const publishRes = await this.threadsService.publishPost(
- task.accountId,
- containerId,
- )
- if (!publishRes || !publishRes.id) {
- this.logger.error(
- `Failed to publish media container for task ID: ${task.id}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: 'Publish media container failed',
- noRetry: true,
- }
- }
- this.logger.log(
- `Successfully published media container for task ID: ${task.id}`,
- )
- let permalink = ''
- try {
- const objectInfo = await this.threadsService.getObjectInfo(
- task.accountId,
- publishRes.id,
- '',
- 'permalink',
- )
- if (objectInfo && objectInfo.permalink) {
- permalink = objectInfo.permalink
- }
- }
- catch (error) {
- this.logger.error(
- `Failed to get object info for published post: ${error.message}`,
- error.stack,
- )
- }
- await this.completePublishTask(task, publishRes.id, {
- workLink: permalink,
- })
- this.logger.log(`completed: Task ID ${task.id} processed successfully`)
- return {
- status: PublishStatus.PUBLISHED,
- message: 'All media files have been processed',
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/twitter.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/twitter.service.ts
deleted file mode 100644
index 2ad837ae..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/twitter.service.ts
+++ /dev/null
@@ -1,471 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { InjectModel } from '@nestjs/mongoose'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { Model } from 'mongoose'
-import {
- chunkedDownloadFile,
- fileUrlToBlob,
- getFileTypeFromUrl,
- getRemoteFileSize,
-} from '../../../../common'
-import { TwitterService } from '../../../../core/plat/twitter/twitter.service'
-import { Account } from '../../../../libs/database/schema/account.schema'
-import {
- PostMediaStatus,
- PostSubCategory,
-} from '../../../../libs/database/schema/postMediaContainer.schema'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../../libs/database/schema/publishTask.schema'
-import { XMediaCategory, XMediaType } from '../../../../libs/twitter/twitter.enum'
-import {
- PostMedia,
- XChunkedMediaUploadRequest,
- XCreatePostRequest,
- XMediaUploadInitRequest,
-} from '../../../../libs/twitter/twitter.interfaces'
-import { DoPubRes } from '../../common'
-import { PublishBase } from '../publish.base'
-import { PostMediaContainerService } from './container.service'
-import { MetaPostPublisher, PublishMetaPostTask } from './meta.interface'
-
-@Injectable()
-export class TwitterPublishService
- extends PublishBase
- implements MetaPostPublisher {
- override queueName: string = AccountType.TWITTER
-
- private readonly logger = new Logger(TwitterPublishService.name, {
- timestamp: true,
- })
-
- constructor(
- @InjectModel(Account.name)
- readonly AccountModel: Model<Account>,
- readonly twitterService: TwitterService,
- private readonly postMediaContainerService: PostMediaContainerService,
- ) {
- super()
- this.postMediaContainerService = postMediaContainerService
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- private generatePostMessage(publishTask: PublishTask): string {
- if (!publishTask) {
- return ''
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- return `${publishTask.desc || ''} #${publishTask.topics.join(' #')}`
- }
- return publishTask.desc || ''
- }
-
- private isPlainTextPost(publishTask: PublishTask): boolean {
- const { imgUrlList, videoUrl } = publishTask
- return (!imgUrlList || imgUrlList.length === 0) && !videoUrl
- }
-
- async publishPlainTextPost(task: PublishTask): Promise<DoPubRes> {
- const post: XCreatePostRequest = {
- text: this.generatePostMessage(task) || '',
- }
- const createPostRes = await this.twitterService.createPost(
- task.accountId,
- post,
- )
- this.logger.log(
- `publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(createPostRes)}`,
- )
- if (!createPostRes || !createPostRes.data.id) {
- this.logger.log(
- `Failed to publish media container for task ID: ${task.id}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: 'Failed to publish text post',
- noRetry: true,
- }
- }
- let permalink = `https://x.com/${task.uid}/status/${createPostRes.data.id}`
- const account = await this.AccountModel.findOne({ _id: task.accountId })
- if (account && account.account) {
- permalink = `https://x.com/${account.account}/status/${createPostRes.data.id}`
- }
-
- this.logger.log(
- `Successfully published media container for task ID: ${task.id}`,
- )
- await this.completePublishTask(task, createPostRes.data.id, {
- workLink: permalink,
- })
- this.logger.log(`completed: Task ID ${task.id} processed successfully`)
- return {
- status: PublishStatus.PUBLISHED,
- message: '所有媒体文件已处理完成',
- }
- }
-
- async publishImagePost(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: 'publish task not found',
- }
- const { accountId, imgUrlList } = publishTask
- if (!imgUrlList || imgUrlList.length === 0) {
- return {
- status: PublishStatus.FAILED,
- message: 'No images found for image post',
- noRetry: true,
- }
- }
- for (const imgUrl of imgUrlList) {
- const imgBlob = await fileUrlToBlob(imgUrl)
- if (!imgBlob) {
- res.message = `Download image failed: ${imgUrl}`
- return res
- }
- const fileName = getFileTypeFromUrl(imgUrl)
- const ext = fileName.split('.').pop()?.toLowerCase()
- const mimeType = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
- const initUploadReq: XMediaUploadInitRequest = {
- media_type: mimeType as XMediaType,
- total_bytes: imgBlob.blob.size,
- media_category: XMediaCategory.TWEET_IMAGE,
- shared: false,
- }
- const initUploadRes = await this.twitterService.initMediaUpload(
- accountId,
- initUploadReq,
- )
- if (!initUploadRes || !initUploadRes.data.id) {
- res.message = 'init image upload failed'
- return res
- }
- this.logger.log(`initUploadRes: ${JSON.stringify(initUploadRes)}`)
- const uploadReq: XChunkedMediaUploadRequest = {
- media: await imgBlob.blob,
- media_id: initUploadRes.data.id,
- segment_index: 0,
- }
-
- const updateRes = await this.twitterService.chunkedMediaUploadRequest(
- accountId,
- uploadReq,
- )
- if (!updateRes || !updateRes.data.expires_at) {
- res.message = 'image upload failed'
- return res
- }
- this.logger.log(
- `chunkedMediaUploadRequest: ${JSON.stringify(updateRes)}`,
- )
- const finalizeUploadRes = await this.twitterService.finalizeMediaUpload(
- accountId,
- initUploadRes.data.id,
- )
- if (!finalizeUploadRes || !finalizeUploadRes.data.id) {
- res.message = 'finalize image upload failed'
- return res
- }
- this.logger.log(
- `finalizeMediaUpload: ${JSON.stringify(finalizeUploadRes)}`,
- )
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'twitter',
- taskId: initUploadRes.data.id,
- status: PostMediaStatus.FINISHED,
- subCategory: PostSubCategory.PHOTO,
- })
- }
-
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 5,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- res.status = PublishStatus.PUBLISHING
- res.message = 'Medias processing'
- return res
- }
-
- async publishVideoPost(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: 'publish task not found',
- }
- const { accountId, videoUrl } = publishTask
- if (!videoUrl) {
- return {
- status: PublishStatus.FAILED,
- message: 'No video found for video post',
- noRetry: true,
- }
- }
- const fileName = getFileTypeFromUrl(videoUrl, true)
- const ext = fileName.split('.').pop()?.toLowerCase()
- const mimeType = ext === 'mp4' ? 'video/mp4' : `video/${ext}`
-
- const contentLength = await getRemoteFileSize(videoUrl)
- if (!contentLength) {
- res.message = 'Get video size failed'
- return res
- }
- const initUploadReq: XMediaUploadInitRequest = {
- media_type: mimeType as XMediaType,
- total_bytes: contentLength,
- media_category: XMediaCategory.TWEET_VIDEO,
- shared: false,
- }
-
- const initUploadRes = await this.twitterService.initMediaUpload(
- accountId,
- initUploadReq,
- )
- if (!initUploadRes || !initUploadRes.data.id) {
- res.message = 'init video upload failed'
- return res
- }
- const chunkSize = 4 * 1024 * 1024 // 4MB
- const totalChunks = Math.ceil(contentLength / chunkSize)
- for (let sequenceNum = 0; sequenceNum < totalChunks; sequenceNum++) {
- const start = sequenceNum * chunkSize
- const end = Math.min(start + chunkSize - 1, contentLength - 1)
- const range: [number, number] = [start, end]
- const fileSegment = await chunkedDownloadFile(videoUrl, range)
- if (!fileSegment) {
- res.message = 'Download video segment failed'
- return res
- }
- this.logger.log(
- `chunked upload, Size: ${fileSegment.length}, Range: ${start}-${end}, Sequence: ${sequenceNum}`,
- )
- const uploadReq: XChunkedMediaUploadRequest = {
- media: new Blob([fileSegment]),
- media_id: initUploadRes.data.id,
- segment_index: sequenceNum,
- }
- const upload = await this.twitterService.chunkedMediaUploadRequest(
- accountId,
- uploadReq,
- )
- this.logger.log(`chunkedMediaUploadRequest: ${JSON.stringify(upload)}`)
- if (!upload || !upload.data.expires_at) {
- res.message = 'Upload video segment failed'
- return res
- }
- }
- const finalizeUploadRes = await this.twitterService.finalizeMediaUpload(
- accountId,
- initUploadRes.data.id,
- )
- if (!finalizeUploadRes || !finalizeUploadRes.data.id) {
- res.message = 'finalize video upload failed'
- return res
- }
- await this.postMediaContainerService.createMetaPostMedia({
- accountId: publishTask.accountId,
- publishId: publishTask.id,
- userId: publishTask.userId,
- platform: 'twitter',
- taskId: initUploadRes.data.id,
- status: PostMediaStatus.CREATED,
- subCategory: PostSubCategory.VIDEO,
- })
-
- const task: PublishMetaPostTask = {
- id: publishTask.id,
- }
- this.queueService.addPostMediaTaskJob(
- {
- taskId: task.id,
- attempts: 0,
- },
- {
- attempts: 5,
- backoff: {
- type: 'fixed',
- delay: 10000,
- },
- removeOnComplete: true,
- removeOnFail: true,
- },
- )
- res.status = PublishStatus.PUBLISHING
- res.message = 'Medias processing'
- return res
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: 'publish task not found',
- }
-
- const { imgUrlList, videoUrl } = publishTask
- if (this.isPlainTextPost(publishTask)) {
- return this.publishPlainTextPost(publishTask)
- }
- if (imgUrlList && imgUrlList.length > 0) {
- return this.publishImagePost(publishTask)
- }
- if (videoUrl) {
- return this.publishVideoPost(publishTask)
- }
- return res
- }
-
- async publish(task: PublishTask): Promise<DoPubRes> {
- try {
- this.logger.log(`publish: Starting to process task ID: ${task.id}`)
- const medias = await this.postMediaContainerService.getContainers(
- task.id,
- )
- if (!medias || medias.length === 0) {
- return {
- status: PublishStatus.FAILED,
- message: '没有找到媒体文件',
- noRetry: true,
- }
- }
- const unProcessedMedias = medias.filter(
- media => media.status !== PostMediaStatus.FINISHED,
- )
- this.logger.log(
- `Found ${medias.length} media files for task ID: ${task.id}`,
- )
- let processedCount = 0
- for (const media of unProcessedMedias) {
- const mediaStatusInfo = await this.twitterService.getMediaUploadStatus(
- task.accountId,
- media.taskId,
- )
- if (!mediaStatusInfo || !mediaStatusInfo.data.processing_info.state) {
- this.logger.error(
- `Failed to get media status for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- continue
- }
- this.logger.log(
- `Media status for task ID ${task.id}, media ID ${media.taskId}: ${JSON.stringify(mediaStatusInfo)}`,
- )
- if (mediaStatusInfo.data.processing_info.state === 'failed') {
- this.logger.error(
- `Media processing failed for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- await this.postMediaContainerService.updateContainer(media.id, {
- status: PostMediaStatus.FAILED,
- })
- return {
- status: PublishStatus.FAILED,
- message: '资源处理失败',
- noRetry: true,
- }
- }
- let mediaStatus = PostMediaStatus.CREATED
- if (mediaStatusInfo.data.processing_info.state === 'in_progress') {
- mediaStatus = PostMediaStatus.IN_PROGRESS
- }
- if (mediaStatusInfo.data.processing_info.state === 'succeeded') {
- this.logger.log(
- `Media processing finished for task ID: ${task.id}, media ID: ${media.taskId}`,
- )
- mediaStatus = PostMediaStatus.FINISHED
- processedCount++
- }
- await this.postMediaContainerService.updateContainer(media.id, {
- status: mediaStatus,
- })
- }
- const isMediaCompleted = processedCount === unProcessedMedias.length
- if (!isMediaCompleted) {
- this.logger.warn(
- `Not all media files processed for task ID: ${task.id}. Processed: ${processedCount}, Total: ${medias.length}`,
- )
- return {
- status: PublishStatus.PUBLISHING,
- message: '媒体文件处理中',
- }
- }
- this.logger.log(`All media files processed for task ID: ${task.id}`)
- const postMedia: PostMedia = {
- media_ids: medias.map(media => media.taskId),
- }
- const post: XCreatePostRequest = {
- text: this.generatePostMessage(task) || '',
- media: postMedia,
- }
- const createPostRes = await this.twitterService.createPost(
- task.accountId,
- post,
- )
- this.logger.log(
- `publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(createPostRes)}`,
- )
- if (!createPostRes || !createPostRes.data.id) {
- this.logger.log(
- `Failed to publish media container for task ID: ${task.id}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: '发布媒体容器失败',
- noRetry: true,
- }
- }
- let permalink = `https://x.com/${task.uid}/status/${createPostRes.data.id}`
- const account = await this.AccountModel.findOne({ _id: task.accountId })
- if (account && account.account) {
- permalink = `https://x.com/${account.account}/status/${createPostRes.data.id}`
- }
-
- this.logger.log(
- `Successfully published media container for task ID: ${task.id}`,
- )
- await this.completePublishTask(task, createPostRes.data.id, {
- workLink: permalink,
- })
- this.logger.log(`completed: Task ID ${task.id} processed successfully`)
- return {
- status: PublishStatus.PUBLISHED,
- message: '所有媒体文件已处理完成',
- }
- }
- catch (error) {
- this.logger.error(
- `Error processing task ID ${task.id}: ${error.message || error}`,
- )
- return {
- status: PublishStatus.FAILED,
- message: `${error.message || error}`,
- noRetry: true,
- }
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/pinterestPub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/pinterestPub.service.ts
deleted file mode 100644
index ccff3540..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/pinterestPub.service.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import * as _ from 'lodash'
-import { PinterestService } from '../../../core/plat/pinterest/pinterest.service'
-import { PublishStatus, PublishTask } from '../../../libs/database/schema/publishTask.schema'
-import { SourceType } from '../../../libs/pinterest/common'
-import { DoPubRes } from '../common'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class PinterestPubService extends PublishBase {
- override queueName: string = AccountType.PINTEREST
- private readonly logger = new Logger(PinterestPubService.name)
-
- constructor(
- readonly pinterestService: PinterestService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- doPub(publishTask: PublishTask): Promise<DoPubRes> {
- return new Promise(async (resolve) => {
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
- // 判断是创建图片还是上传视频pin
- const { imgUrlList, videoUrl } = publishTask
-
- if (videoUrl)
- return this.handleVideoUpload(publishTask, resolve, res)
- if (imgUrlList)
- return this.handlePicUpload(publishTask, resolve, res)
- })
- }
-
- async handlePicUpload(publishTask: PublishTask, resolve: any, res: DoPubRes) {
- const { desc: description, accountId, imgUrlList, title, option } = publishTask
- if (_.isEmpty(option) || _.isEmpty(option?.pinterest)) {
- return resolve({
- message: '必须要上传board_id',
- status: PublishStatus.FAILED,
- })
- }
- const { boardId: board_id } = option.pinterest
- const body: any
- = {
- accountId,
- board_id,
- description,
- title,
- media_source:
- {
- source_type: SourceType.image_url,
- url: _.first(imgUrlList),
- },
- }
- const data = await this.pinterestService.createPin(body)
- if (_.isEmpty(data)) {
- res.message = '稿件发布失败'
- return resolve(res)
- }
- await this.completePublishTask(publishTask, data.data.id, {
- workLink: `https://www.pinterest.com/pin/${data.data.id}/`,
- })
- res.message = '发布成功'
- res.status = PublishStatus.PUBLISHED
- resolve(res)
- }
-
- async handleVideoUpload(publishTask: PublishTask, resolve: any, res: DoPubRes) {
- const { desc: description, accountId, coverUrl, title, videoUrl, option } = publishTask
- if (_.isEmpty(option) || _.isEmpty(option?.pinterest) || !_.isString(videoUrl)) {
- return resolve({
- message: '必须要上传board_id',
- status: PublishStatus.FAILED,
- })
- }
- // 上传视频获取到视频id
- const result = await this.pinterestService.uploadVideo(videoUrl, accountId)
- if (_.isEmpty(result) || _.isEmpty(result?.data) || !_.isString(result.data.media_id)) {
- return resolve({
- message: '上传视频失败',
- status: PublishStatus.FAILED,
- })
- }
- const { media_id } = result.data
- const { boardId: board_id } = option.pinterest
- const body: any
- = {
- accountId,
- board_id,
- description,
- title,
- media_source:
- {
- source_type: SourceType.video_id,
- media_id,
- cover_image_url: coverUrl,
- },
- }
- const data = await this.pinterestService.createPin(body)
- if (_.isEmpty(data)) {
- res.message = '稿件发布失败'
- return resolve(res)
- }
- res.message = '发布成功'
- res.status = PublishStatus.PUBLISHED
- await this.completePublishTask(publishTask, data.data.id, {
- workLink: `https://www.pinterest.com/pin/${data.data.id}/`,
- })
- resolve(res)
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/publish.base.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/publish.base.ts
deleted file mode 100644
index b707d480..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/publish.base.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { Inject, Injectable } from '@nestjs/common'
-import { EventEmitter2 } from '@nestjs/event-emitter'
-import { InjectModel } from '@nestjs/mongoose'
-
-import { QueueService } from '@yikart/aitoearn-queue'
-import { PublishRecord } from '@yikart/aitoearn-server-client'
-import { Model } from 'mongoose'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../libs/database/schema/publishTask.schema'
-import { PublishRecordService } from '../../account/publishRecord.service'
-import { DoPubRes } from '../common'
-
-@Injectable()
-export abstract class PublishBase {
- protected readonly queueName: string = 'unknown'
- protected readonly queueAttempts: number = 3 // 并发数量
- protected readonly queueDelay: number = 5 // 延迟时间
-
- @Inject(QueueService)
- protected readonly queueService: QueueService
-
- @Inject(EventEmitter2)
- protected readonly eventEmitter: EventEmitter2
-
- @InjectModel(PublishTask.name)
- protected readonly publishTaskModel: Model<PublishTask>
-
- @Inject(PublishRecordService)
- protected readonly publishRecordService: PublishRecordService
-
- constructor() {}
-
- // 检测授权是否失效
- abstract checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }>
-
- // 进行发布(给队列调用)
- abstract doPub(publishTask: PublishTask): Promise<DoPubRes>
-
- protected async createPublishTask(newData: Partial<PublishTask>) {
- return await this.publishTaskModel.create(newData)
- }
-
- protected async createPublishRecord(newData: Partial<PublishRecord>) {
- newData.publishTime = newData.publishTime || new Date()
- await this.publishRecordService.createPublishRecord(newData)
- }
-
- /**
- * 推送任务
- * @param newData
- * @param doNum
- * @returns
- */
- async pushPubTask(task: PublishTask, attempts = 0): Promise<boolean> {
- await this.publishQueueOpen(task.id)
- const jobRes = await this.queueService.addPostPublishJob(
- {
- taskId: task.id,
- attempts: attempts++,
- jobId: task.queueId,
- },
- {
- attempts: this.queueAttempts,
- backoff: {
- type: 'exponential',
- delay: this.queueDelay, // 每次重试间隔 5 秒
- },
- removeOnComplete: true,
- removeOnFail: true,
- jobId: task.queueId, // 确保任务id唯一,防止重复执行
- },
- )
- return jobRes.id === task.queueId
- }
-
- // 将数据的队列状态改为 true
- async publishQueueOpen(id: string) {
- this.publishTaskModel.updateOne({ _id: id }, { inQueue: true })
- }
-
- // 获取发布任务信息
- protected async getPublishTaskInfo(id: string) {
- return this.publishTaskModel.findOne({ _id: id })
- }
-
- // 完成发布任务
- protected async completePublishTask(
- newData: PublishTask,
- dataId: string,
- data?: {
- // 作品链接
- workLink: string
- dataOption?: Record<string, any>
- },
- ) {
- newData.status = PublishStatus.PUBLISHED
- await this.publishTaskModel.updateOne(
- { _id: newData.id },
- { status: PublishStatus.PUBLISHED, dataId, workLink: data?.workLink },
- ).exec()
- await this.createPublishRecord({
- ...newData,
- ...(data || {}),
- dataId,
- })
- }
-
- protected async failPublishTask(id: string, errMsg: string) {
- await this.publishTaskModel.updateOne(
- { _id: id },
- { status: PublishStatus.FAILED, errorMsg: errMsg },
- ).exec()
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/tiktokPub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/tiktokPub.service.ts
deleted file mode 100644
index 434a1d60..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/tiktokPub.service.ts
+++ /dev/null
@@ -1,246 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AitoearnServerClientService } from '@yikart/aitoearn-server-client'
-import { chunkedDownloadFile, getFileTypeFromUrl, getRemoteFileSize } from '../../../common'
-import { config } from '../../../config'
-import { PostInfoDto, VideoFileUploadSourceDto, VideoPullUrlSourceDto } from '../../../core/plat/tiktok/dto/tiktok.dto'
-import { TiktokService } from '../../../core/plat/tiktok/tiktok.service'
-import { PublishStatus, PublishTask } from '../../../libs/database/schema/publishTask.schema'
-import { TiktokPrivacyLevel, TiktokSourceType } from '../../../libs/tiktok/tiktok.enum'
-import { DoPubRes } from '../common'
-import { TiktokWebhookDto } from '../dto/tiktok.webhook.dto'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class TiktokPubService extends PublishBase {
- override queueName: string = 'tiktok'
- private readonly logger = new Logger(TiktokPubService.name, {
- timestamp: true,
- })
-
- constructor(
- readonly tiktokService: TiktokService,
- private readonly serverClient: AitoearnServerClientService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- private generatePostMessage(publishTask: PublishTask): string {
- if (!publishTask) {
- return ''
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- return `${publishTask.desc || ''} #${publishTask.topics.join(' #')}`
- }
- return publishTask.desc || ''
- }
-
- private isDevEnv(): boolean {
- return config.tiktok.redirectUri.includes('dev')
- }
-
- async publishVideoViaUpload(publishTask: PublishTask): Promise<string> {
- const { accountId, videoUrl } = publishTask
- if (!videoUrl) {
- throw new Error('video url is required')
- }
- const fileName = getFileTypeFromUrl(videoUrl, true)
- const ext = fileName.split('.').pop()?.toLowerCase()
- const mimeType = ext === 'mp4' ? 'video/mp4' : `video/${ext}`
-
- const contentLength = await getRemoteFileSize(videoUrl)
- if (!contentLength) {
- throw new Error('get video meta failed')
- }
- let chunkSize = 6 * 1024 * 1024 // 6MB
- if (contentLength < chunkSize) {
- chunkSize = contentLength
- }
- const privacy_level = publishTask.option?.tiktok?.privacy_level ? publishTask.option.tiktok.privacy_level as TiktokPrivacyLevel : TiktokPrivacyLevel.PUBLIC
- const postInfo: PostInfoDto = {
- title: publishTask.title || publishTask.desc || '',
- privacy_level,
- brand_content_toggle: publishTask.option?.tiktok?.brand_content_toggle || false,
- brand_organic_toggle: publishTask.option?.tiktok?.brand_organic_toggle || false,
- disable_comment: publishTask.option?.tiktok?.disable_comment || false,
- disable_duet: publishTask.option?.tiktok?.disable_duet || false,
- disable_stitch: publishTask.option?.tiktok?.disable_stitch || false,
- }
-
- const sourceInfo: VideoFileUploadSourceDto = {
- source: TiktokSourceType.FILE_UPLOAD,
- video_size: contentLength,
- chunk_size: chunkSize,
- total_chunk_count: Math.floor(contentLength / chunkSize),
- }
-
- this.logger.log(`init video upload: accountId: ${accountId}, postInfo: ${JSON.stringify(postInfo)}, sourceInfo: ${JSON.stringify(sourceInfo)}`)
- const initUploadRes = await this.tiktokService.initVideoPublish(
- accountId,
- postInfo,
- sourceInfo,
- )
- this.logger.log(`视频初始化上传结果: ${JSON.stringify(initUploadRes)}`)
- if (!initUploadRes || !initUploadRes.upload_url) {
- throw new Error('init upload video failed')
- }
- const totalParts = Math.floor(contentLength / chunkSize)
- const chunks: [number, number][] = []
- let start = 0
- for (let partNumber = 0; partNumber < totalParts - 1; partNumber++) {
- const end = start + chunkSize - 1
- chunks.push([start, end])
- start += chunkSize
- }
- chunks.push([start, contentLength - 1])
-
- for (const chunk of chunks) {
- const videoBlob = await chunkedDownloadFile(videoUrl, chunk)
- if (!videoBlob) {
- throw new Error('download video chunk failed')
- }
-
- const uploadResult = await this.tiktokService.chunkedUploadVideoFile(
- initUploadRes.upload_url,
- videoBlob,
- chunk,
- contentLength,
- mimeType,
- )
- this.logger.log(`视频分片上传完成: ${JSON.stringify(uploadResult)}`)
- }
- return initUploadRes.publish_id
- }
-
- async publishVideoViaURL(publishTask: PublishTask): Promise<string> {
- try {
- const { accountId, videoUrl } = publishTask
- if (!videoUrl) {
- throw new Error('video url is required')
- }
- const privacyLevel = this.isDevEnv() ? TiktokPrivacyLevel.SELF_ONLY : TiktokPrivacyLevel.PUBLIC
- const postInfo: PostInfoDto = {
- title: this.generatePostMessage(publishTask),
- privacy_level: privacyLevel,
- brand_content_toggle: false,
- brand_organic_toggle: false,
- }
-
- const sourceInfo: VideoPullUrlSourceDto = {
- source: TiktokSourceType.PULL_FROM_URL,
- video_url: videoUrl,
- }
-
- const publishRes = await this.tiktokService.initVideoPublish(
- accountId,
- postInfo,
- sourceInfo,
- )
- this.logger.log(`视频发布结果: ${JSON.stringify(publishRes)}`)
- if (!publishRes || !publishRes.publish_id) {
- throw new Error('publish video failed')
- }
- return publishRes.publish_id
- }
- catch (error) {
- this.logger.error('publishVideoViaUrl error', error)
- throw error
- }
- }
-
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
-
- try {
- const { videoUrl } = publishTask
- if (videoUrl) {
- const publishId = await this.publishVideoViaUpload(publishTask)
- publishTask.status = PublishStatus.PUBLISHING
- await this.createPublishRecord({
- ...publishTask,
- dataId: publishId,
- publishTime: new Date(),
- })
- res.status = PublishStatus.PUBLISHING
- res.message = '发布任务已提交,等待处理'
- return res
- }
- }
- catch (error) {
- this.logger.error(`Publish TikTok video failed: ${error.message}`, error.stack)
- res.status = PublishStatus.FAILED
- res.message = error.message || 'Publish TikTok video failed with unknown error'
- return res
- }
- return res
- }
-
- async handleTiktokPostWebhook(dto: TiktokWebhookDto): Promise<void> {
- try {
- const content = JSON.parse(dto.content)
- if (!dto.event.startsWith('post.publish')) {
- this.logger.error(`未知 TikTok 事件类型: ${dto.event}`)
- return
- }
- const publishId = content?.publish_id
- if (!publishId) {
- this.logger.error(`invalid publish_id in webhook: ${JSON.stringify(content)}`)
- return
- }
- const publishRecord = await this.serverClient.publishing.getPublishRecordByDataId(publishId, dto.user_openid)
- if (!publishRecord) {
- this.logger.error(`未找到发布记录: ${publishId}, 用户: ${dto.user_openid}`)
- return
- }
- switch (dto.event) {
- case 'post.publish.failed':
- this.logger.error(`发布失败: ${JSON.stringify(content)}`)
- publishRecord.status = PublishStatus.FAILED
- publishRecord.errorMsg = content.reason || '发布失败'
- await this.publishRecordService.updatePublishRecordStatus(publishRecord._id, publishRecord.status, publishRecord.errorMsg)
- await this.publishTaskModel.updateOne({ queueId: publishRecord.queueId }, {
- status: PublishStatus.FAILED,
- errorMsg: content.reason || '发布失败',
- })
- break
- case 'post.publish.complete':
- this.logger.log(`发布成功: ${JSON.stringify(content)}`)
- publishRecord.status = PublishStatus.PUBLISHED
- await this.publishRecordService.updatePublishRecordStatus(publishRecord._id, publishRecord.status, publishRecord.errorMsg)
- this.publishTaskModel.deleteOne({ queueId: publishRecord.queueId })
- break
- case 'post.publish.inbox_delivered':
- this.logger.log(`发布已送达: ${JSON.stringify(content)}`)
- publishRecord.status = PublishStatus.PUBLISHED
- await this.publishRecordService.updatePublishRecordStatus(publishRecord._id, publishRecord.status, publishRecord.errorMsg)
- this.publishTaskModel.deleteOne({ queueId: publishRecord.queueId })
- break
- case 'post.publish.publicly_available':
- publishRecord.status = PublishStatus.PUBLISHED
- publishRecord.dataId = content.post_id || publishRecord.dataId
- await this.publishRecordService.updatePublishRecordStatus(publishRecord._id, publishRecord.status, publishRecord.errorMsg)
- break
- default:
- this.logger.error(`未知事件类型: ${dto.event}`)
- break
- }
- }
- catch (error) {
- this.logger.error(`处理 TikTok webhook 失败: ${error.message}`, error.stack)
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/wxGzhPub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/wxGzhPub.service.ts
deleted file mode 100644
index 58b72b18..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/wxGzhPub.service.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { WxGzhService } from '../../../core/plat/wxPlat/wxGzh.service'
-import {
- PublishTask,
- PublishType,
-} from '../../../libs/database/schema/publishTask.schema'
-import { MediaType } from '../../../libs/wxGzh/common'
-import { DoPubRes } from '../common'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class WxGzhPubService extends PublishBase {
- logger = new Logger(WxGzhPubService.name)
- override queueName: string = AccountType.WxGzh
-
- constructor(
- readonly wxGzhService: WxGzhService,
- ) {
- super()
- }
-
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- return this.wxGzhService.checkAuth(accountId)
- }
-
- async doPub(publishTask: PublishTask) {
- // 开始任务
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
-
- const { coverUrl, accountId, imgUrlList, title, desc, type, option }
- = publishTask
- if (!imgUrlList || imgUrlList.length === 0) {
- res.message = '图片列表不能为空'
- return res
- }
- if (!title) {
- res.message = '标题不能为空'
- return res
- }
- if (!desc) {
- res.message = '描述不能为空'
- return res
- }
- if (type !== PublishType.ARTICLE) {
- res.message = '公众号只有文章发布'
- return res
- }
-
- // 上传图片
- const wxGzhImgMaterialIdList: {
- image_media_id: string
- }[] = []
-
- // 封面
- if (coverUrl) {
- this.logger.log('正在上传封面...')
- const coverUrlRes = await this.wxGzhService.addMaterial(
- accountId,
- MediaType.image,
- coverUrl,
- )
- this.logger.log(coverUrlRes)
- if (!coverUrlRes || coverUrlRes.errcode) {
- res.message = '封面上传失败'
- return res
- }
- wxGzhImgMaterialIdList.push({
- image_media_id: coverUrlRes.media_id,
- })
- this.logger.log('封面上传成功:', coverUrlRes)
- }
-
- // 图片
- for (const imgUrl of imgUrlList) {
- this.logger.log('正在上传图片...')
- const imgUrlRes = await this.wxGzhService.addMaterial(
- accountId,
- MediaType.image,
- imgUrl,
- )
- if (!imgUrlRes || imgUrlRes.errcode) {
- res.message = '图片上传失败'
- return res
- }
- wxGzhImgMaterialIdList.push({ image_media_id: imgUrlRes.media_id })
- this.logger.log('图片上传成功:', imgUrlRes)
- }
-
- // 创建草稿
- const draftAddRes = await this.wxGzhService.draftAdd(accountId, {
- article_type: 'newspic',
- title,
- content: desc,
- image_info: {
- image_list: wxGzhImgMaterialIdList,
- },
- ...option?.wxGzh,
- })
-
- if (draftAddRes.errcode) {
- res.message = `稿件草稿创建失败: ${draftAddRes.errmsg}`
- return res
- }
-
- // 发布
- const freePublishRes = await this.wxGzhService.freePublish(
- accountId,
- draftAddRes.media_id,
- )
-
- if (freePublishRes.errcode) {
- res.message = `发布任务创建失败: ${freePublishRes.errmsg}`
- return res
- }
-
- // 完成发布任务
- void this.completePublishTask(publishTask, freePublishRes.publish_id, {
- // workLink: `https://mp.weixin.qq.com/s/${freePublishRes.publish_id}`,
- workLink: '',
- dataOption: {
- publish_id: freePublishRes.publish_id,
- msg_data_id: freePublishRes.msg_data_id,
- article_id: '',
- },
- })
- res.message = '发布成功'
- res.status = 1
-
- // 进行发布
- return res
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/youtubePub.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/plat/youtubePub.service.ts
deleted file mode 100644
index 3a6bd072..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/youtubePub.service.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { getFileSizeFromUrl, streamDownloadAndUpload } from '../../../common'
-import { YoutubeService } from '../../../core/plat/youtube/youtube.service'
-import {
- PublishStatus,
- PublishTask,
-} from '../../../libs/database/schema/publishTask.schema'
-import { DoPubRes } from '../common'
-import { PublishBase } from './publish.base'
-
-@Injectable()
-export class YoutubePubService extends PublishBase {
- override queueName: string = AccountType.YOUTUBE
- private readonly logger = new Logger(YoutubePubService.name)
-
- constructor(
- readonly youtubeService: YoutubeService,
- ) {
- super()
- }
-
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- doPub(publishTask: PublishTask): Promise<DoPubRes> {
- return new Promise(async (resolve) => {
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
-
- // const { coverUrl, accountId, videoUrl } = publishTask
-
- const TaskInfo = {
- coverUrl: publishTask.coverUrl,
- accountId: publishTask.accountId,
- videoUrl: publishTask.videoUrl,
- title: publishTask.title,
- desc: publishTask.desc,
- tag: publishTask.topics.join(','),
- categoryId: publishTask?.option?.youtube?.categoryId,
- privacyStatus: publishTask?.option?.youtube?.privacyStatus,
- }
-
- if (!TaskInfo.videoUrl) {
- res.message = '视频不存在'
- res.noRetry = true
- return resolve(res)
- }
-
- this.logger.log('TaskInfo:----', TaskInfo)
- // const fileName = this.fileToolsService.getFileTypeFromUrl(TaskInfo.videoUrl)
- const contentLength = await getFileSizeFromUrl(TaskInfo.videoUrl)
- this.logger.log('视频大小:----', contentLength)
- if (!contentLength) {
- res.message = '视频大小获取失败'
- return resolve(res)
- }
- this.logger.log('正在分片上传...')
- // 视频分片上传初始化
- const videoUpToken = await this.youtubeService.initVideoUpload(
- TaskInfo.accountId,
- TaskInfo.title || '',
- TaskInfo.desc || '',
- TaskInfo.tag?.split(',') || [],
- publishTask?.option?.youtube?.license || 'youtube',
- TaskInfo.categoryId || '22',
- TaskInfo.privacyStatus || 'private',
- publishTask?.option?.youtube?.notifySubscribers || false,
- publishTask?.option?.youtube?.embeddable || false,
- publishTask?.option?.youtube?.selfDeclaredMadeForKids || false,
- Number(contentLength),
- )
- if (!videoUpToken) {
- res.message = '视频初始化失败'
- return resolve(res)
- }
-
- // 视频URL分片上传
- void streamDownloadAndUpload(
- TaskInfo.videoUrl,
- async (upData: Buffer, partNumber: number) => {
- this.logger.log(`分片:${partNumber}`)
- await this.youtubeService.uploadVideoPart(
- TaskInfo.accountId,
- upData,
- videoUpToken,
- partNumber,
- )
- },
- async () => {
- this.logger.log('发布...')
- // 发布
- const resourceId = await this.youtubeService.videoComplete(
- TaskInfo.accountId,
- videoUpToken,
- Number(contentLength),
- )
- if (!resourceId) {
- res.message = '稿件发布失败'
- return resolve(res)
- }
-
- if (!resourceId) {
- res.message = '稿件发布失败'
- return resolve(res)
- }
-
- // 封面上传
- // 有封面
- // if (TaskInfo.coverUrl) {
- // this.logger.log('正在上传封面...')
- // const urlBase64 = await this.fileToolsService.fileUrlToBase64(TaskInfo.coverUrl)
- // const coverRes = await this.youtubeService.uploadThumbnails(
- // TaskInfo.accountId,
- // resourceId,
- // urlBase64,
- // )
- // if (!coverRes) {
- // res.message = '封面上传失败'
- // return resolve(res)
- // }
-
- // this.logger.log('封面上传成功:', coverRes)
-
- // publishTask.coverUrl = coverRes
- // }
-
- // 设置封面
- // await this.youtubeService.uploadThumbnails(
- // TaskInfo.accountId,
- // resourceId,
- // TaskInfo.coverUrl,
- // )
-
- // 完成发布任务
- void this.completePublishTask(publishTask, resourceId, {
- workLink: `https://www.youtube.com/watch?v=${resourceId}`,
- })
- res.message = '发布成功'
- res.status = 1
-
- resolve(res)
- },
- ).catch((e) => {
- resolve({
- message: e.message,
- status: PublishStatus.FAILED,
- })
- })
- })
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/post-publish.consumer.ts b/project/backend/apps/aitoearn-channel/src/core/publish/post-publish.consumer.ts
deleted file mode 100644
index bfd3d430..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/post-publish.consumer.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * @Author: nevin
- * @Date: 2024-07-03 15:16:12
- * @LastEditTime: 2025-02-10 17:18:50
- * @LastEditors: nevin
- * @Description: 视频发布队列
- */
-import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'
-import { Logger, OnModuleDestroy } from '@nestjs/common'
-import { QueueName } from '@yikart/aitoearn-queue'
-import { Job } from 'bullmq'
-import { PublishStatus } from '../../libs/database/schema/publishTask.schema'
-import { PublishTaskService } from './publishTask.service'
-
-@Processor(QueueName.PostPublish, {
- concurrency: 3,
- stalledInterval: 15000,
- maxStalledCount: 1,
-})
-export class PostPublishConsumer extends WorkerHost implements OnModuleDestroy {
- private readonly logger = new Logger(PostPublishConsumer.name)
- constructor(readonly publishTaskService: PublishTaskService) {
- super()
- }
-
- // Todo: doPub timeout control
- async process(
- job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- timeout?: number
- }>,
- ): Promise<any> {
- const { taskId, attempts, timeout } = job.data
- this.logger.log(`[task-${taskId}] Processing Publish Task, data: ${JSON.stringify(job.data)}, Attempts: ${attempts}`)
-
- try {
- const taskDoc = await this.publishTaskService.getPublishTaskInfo(taskId)
- if (!taskDoc) {
- this.logger.error(`[task-${taskId}] Publish task not found: ${taskId}`)
- return
- }
-
- const taskInfo = taskDoc.toObject()
- if (timeout && timeout > 0) {
- this.logger.log(`[task-${taskId}] Publish task timeout set to ${timeout}ms`)
-
- const publishPromise = this.publishTaskService.doPub(taskInfo)
- const timeoutPromise = new Promise<never>((_, reject) => {
- setTimeout(() => {
- reject(new Error(`[task-${taskId}] Publish task timeout after ${timeout}ms`))
- }, timeout)
- })
-
- const result = await Promise.race([publishPromise, timeoutPromise])
-
- if (result.status === PublishStatus.FAILED) {
- this.logger.error(`[task-${taskId}] Publish task failed: ${taskId}, Message: ${result.message}`)
- throw new Error(result.message)
- }
-
- this.logger.log(`[task-${taskId}] Publish task completed successfully with timeout control`)
- return result
- }
- else {
- const result = await this.publishTaskService.doPub(taskInfo)
-
- if (result.status === PublishStatus.FAILED) {
- this.logger.error(`[task-${taskId}] Publish task failed: ${taskId}, Message: ${result.message}`)
- throw new Error(result.message)
- }
-
- this.logger.log(`[task-${taskId}] Publish task completed successfully`)
- return result
- }
- }
- catch (error) {
- this.logger.error(`[task-${taskId}] Error processing job ${job.id}: ${error.message}`, error.stack)
- throw new Error(`[task-${taskId}] Job ${job.id} failed: ${error.message}`)
- }
- }
-
- @OnWorkerEvent('completed')
- async onCompleted(job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- }>) {
- const { taskId, attempts, jobId } = job.data
- this.logger.log(`[task-${taskId}] Processing completed for job ${jobId}, taskId: ${taskId}, Attempts: ${attempts}`)
- }
-
- @OnWorkerEvent('failed')
- async onFailed(job: Job<{
- taskId: string
- attempts: number
- jobId?: string
- }>, error: Error) {
- if (job.attemptsMade === job.opts.attempts) {
- this.logger.error(`[task-${job.data.taskId}] Job ${job.id} failed after all attempts: ${error.message}`)
- await this.publishTaskService.updatePublishTaskStatus(job.data.taskId, {
- status: PublishStatus.FAILED,
- errorMsg: error.message,
- })
- this.logger.log(`[task-${job.data.taskId}] Publish task ${job.data.taskId} marked as failed after all attempts.`)
- return
- }
- this.logger.warn(`[task-${job.data.taskId}] Job ${job.data.taskId} failed, retrying... Attempts made: ${job.attemptsMade}`)
- }
-
- @OnWorkerEvent('stalled')
- onStalled(job: Job) {
- this.logger.error(`Job ${job.id}] is stalled, data ${job.data}`)
- }
-
- async onModuleDestroy() {
- this.logger.log('PostPublishConsumer is being destroyed, closing worker...')
- await this.worker.close()
- this.logger.log('PostPublishConsumer closed successfully')
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/publish.module.ts b/project/backend/apps/aitoearn-channel/src/core/publish/publish.module.ts
deleted file mode 100644
index eaabf099..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/publish.module.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { forwardRef, Module } from '@nestjs/common'
-import { MongooseModule } from '@nestjs/mongoose'
-import { PinterestModule } from '../../core/plat/pinterest/pinterest.module'
-import { PinterestPubService } from '../../core/publish/plat/pinterestPub.service'
-import { Account, AccountSchema } from '../../libs/database/schema/account.schema'
-import {
- PostMediaContainer,
- PostMediaContainerSchema,
-} from '../../libs/database/schema/postMediaContainer.schema'
-import {
- PublishTask,
- PublishTaskSchema,
-} from '../../libs/database/schema/publishTask.schema'
-import { BilibiliModule } from '../plat/bilibili/bilibili.module'
-import { KwaiModule } from '../plat/kwai/kwai.module'
-import { MetaModule } from '../plat/meta/meta.module'
-import { TiktokModule } from '../plat/tiktok/tiktok.module'
-import { TwitterModule } from '../plat/twitter/twitter.module'
-import { WxPlatModule } from '../plat/wxPlat/wxPlat.module'
-import { YoutubeModule } from '../plat/youtube/youtube.module'
-import { BilibiliPubService } from './plat/bilibiliPub.service'
-import { kwaiPubService } from './plat/kwaiPub.service'
-import { FacebookPublishService } from './plat/meta/facebook.service'
-import { InstagramPublishService } from './plat/meta/instgram.service'
-import { LinkedinPublishService } from './plat/meta/linkedin.service'
-import { MetaPublishModule } from './plat/meta/meta.module'
-import { MetaPublishConsumer } from './plat/meta/publish.consumer'
-import { ThreadsPublishService } from './plat/meta/threads.service'
-import { TiktokPubService } from './plat/tiktokPub.service'
-import { WxGzhPubService } from './plat/wxGzhPub.service'
-import { YoutubePubService } from './plat/youtubePub.service'
-import { PostPublishConsumer } from './post-publish.consumer'
-import { PublishTaskController } from './publishTask.controller'
-import { PublishTaskService } from './publishTask.service'
-
-@Module({
- imports: [
- MongooseModule.forFeature([
- { name: Account.name, schema: AccountSchema },
- { name: PublishTask.name, schema: PublishTaskSchema },
- { name: PostMediaContainer.name, schema: PostMediaContainerSchema },
- ]),
- BilibiliModule,
- PinterestModule,
- KwaiModule,
- YoutubeModule,
- forwardRef(() => WxPlatModule),
- MetaModule,
- TiktokModule,
- MetaPublishModule,
- TwitterModule,
- PinterestModule,
- ],
- providers: [
- PublishTaskService,
- PostPublishConsumer,
- BilibiliPubService,
- PinterestPubService,
- kwaiPubService,
- YoutubePubService,
- WxGzhPubService,
- FacebookPublishService,
- InstagramPublishService,
- ThreadsPublishService,
- TiktokPubService,
- MetaPublishConsumer,
- LinkedinPublishService,
- ],
- controllers: [PublishTaskController],
- exports: [PublishTaskService],
-})
-export class PublishModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/publishTask.service.ts b/project/backend/apps/aitoearn-channel/src/core/publish/publishTask.service.ts
deleted file mode 100644
index 2de7c6c5..00000000
--- a/project/backend/apps/aitoearn-channel/src/core/publish/publishTask.service.ts
+++ /dev/null
@@ -1,424 +0,0 @@
-import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
-import { InjectModel } from '@nestjs/mongoose'
-import { Cron } from '@nestjs/schedule'
-import { QueueService } from '@yikart/aitoearn-queue'
-import { AccountType } from '@yikart/aitoearn-server-client'
-import { AppException, ResponseCode } from '@yikart/common'
-import { Model, RootFilterQuery } from 'mongoose'
-import { v4 as uuidv4 } from 'uuid'
-import { IMMEDIATE_PUBLISH_TOLERANCE_SECONDS, PUbLISHING_SCHEDULED_TASK_CRON_EXPRESSION } from '../../core/publish/constant'
-import { PinterestPubService } from '../../core/publish/plat/pinterestPub.service'
-import { PublishStatus, PublishTask } from '../../libs/database/schema/publishTask.schema'
-import { AccountService } from '../account/account.service'
-import { NewPulData, PlatPulOption } from './common'
-import { CreatePublishDto, PublishRecordListFilterDto } from './dto/publish.dto'
-import { TiktokWebhookDto } from './dto/tiktok.webhook.dto'
-import { BilibiliPubService } from './plat/bilibiliPub.service'
-import { kwaiPubService } from './plat/kwaiPub.service'
-import { FacebookPublishService } from './plat/meta/facebook.service'
-import { InstagramPublishService } from './plat/meta/instgram.service'
-import { LinkedinPublishService } from './plat/meta/linkedin.service'
-import { ThreadsPublishService } from './plat/meta/threads.service'
-import { TwitterPublishService } from './plat/meta/twitter.service'
-import { PublishBase } from './plat/publish.base'
-import { TiktokPubService } from './plat/tiktokPub.service'
-import { WxGzhPubService } from './plat/wxGzhPub.service'
-import { YoutubePubService } from './plat/youtubePub.service'
-
-@Injectable()
-export class PublishTaskService implements OnModuleDestroy {
- private readonly publishServiceMap = new Map<AccountType, PublishBase>()
- private readonly logger = new Logger(PublishTaskService.name)
-
- constructor(
- private readonly accountService: AccountService,
- @InjectModel(PublishTask.name)
- private readonly publishTaskModel: Model<PublishTask>,
- private readonly bilibiliPubService: BilibiliPubService,
- private readonly kwaiPubService: kwaiPubService,
- private readonly youtubePubService: YoutubePubService,
- private readonly wxGzhPubService: WxGzhPubService,
- private readonly facebookPubService: FacebookPublishService,
- private readonly instagramPubService: InstagramPublishService,
- private readonly threadPubService: ThreadsPublishService,
- private readonly tiktokPubService: TiktokPubService,
- private readonly twitterPubService: TwitterPublishService,
- private readonly pinterestPubService: PinterestPubService,
- private readonly linkedInPubService: LinkedinPublishService,
- private readonly queueService: QueueService,
- ) {
- this.publishServiceMap.set(AccountType.BILIBILI, this.bilibiliPubService)
- this.publishServiceMap.set(AccountType.KWAI, this.kwaiPubService)
- this.publishServiceMap.set(AccountType.YOUTUBE, this.youtubePubService)
- this.publishServiceMap.set(AccountType.FACEBOOK, this.facebookPubService)
- this.publishServiceMap.set(AccountType.INSTAGRAM, this.instagramPubService)
- this.publishServiceMap.set(AccountType.THREADS, this.threadPubService)
- this.publishServiceMap.set(AccountType.WxGzh, this.wxGzhPubService)
- this.publishServiceMap.set(AccountType.TIKTOK, this.tiktokPubService)
- this.publishServiceMap.set(AccountType.TWITTER, this.twitterPubService)
- this.publishServiceMap.set(AccountType.PINTEREST, this.pinterestPubService)
- this.publishServiceMap.set(AccountType.LINKEDIN, this.linkedInPubService)
- }
-
- async createPub(taskInfo: NewPulData<PlatPulOption>) {
- const { publishTime, accountType } = taskInfo
- taskInfo['queueId'] = `publish:${accountType}:${uuidv4()}`
- const newTask = await this.publishTaskModel.create(taskInfo)
-
- const now = Date.now()
- const immediatePublishWindow = [
- now - IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
- now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
- ]
- const publishImmediately = publishTime.getTime() >= immediatePublishWindow[0] && publishTime.getTime() <= immediatePublishWindow[1]
- if (!publishImmediately) {
- this.logger.log(`Publish task ${newTask.id} created, scheduled for ${publishTime.toISOString()}`)
- return newTask
- }
-
- const res = await this.pushPubTask(newTask)
- if (!res)
- throw new AppException(ResponseCode.PublishTaskFailed, { accountType })
- this.logger.log(`Publish task ${newTask.id} created and pushed to queue immediately`)
- return newTask
- }
-
- /**
- * 推送任务-定时器使用
- * @param publishTask
- * @returns
- */
- async pushPubTask(publishTask: PublishTask) {
- const pubService = this.publishServiceMap.get(publishTask.accountType)
- if (!pubService)
- throw new AppException(ResponseCode.PublishServiceNotFound, { accountType: publishTask.accountType })
-
- const res = await pubService.pushPubTask(publishTask)
- if (!res)
- throw new AppException(ResponseCode.PublishTaskFailed, { accountType: publishTask.accountType })
- return res
- }
-
- /**
- * 给任务调用的方法
- * @param publishTask 任务
- * @returns 推送结果
- */
- async doPub(publishTask: PublishTask) {
- const pubService = this.publishServiceMap.get(publishTask.accountType)
- this.logger.log(`Processing Publish Task: ${publishTask.id}, Account Type: ${publishTask.accountType}`)
- if (!pubService) {
- return {
- status: PublishStatus.FAILED,
- message: `publish service for ${publishTask.accountType} not found`,
- noRetry: true,
- }
- }
- await this.updatePublishTaskStatus(publishTask.id, {
- status: PublishStatus.PUBLISHING,
- })
- const res = await pubService.doPub(publishTask)
-
- // 更新任务状态
- this.updatePublishTaskStatus(publishTask.id, {
- status: res.status,
- })
- return res
- }
-
- /**
- * 获取时间段内发布任务列表
- * @param start
- * @param end
- * @returns
- */
- async getPublishTaskListByTime(
- start: Date,
- end: Date,
- ): Promise<PublishTask[]> {
- const filters: RootFilterQuery<PublishTask> = {
- publishTime: { $gte: start, $lte: end },
- status: PublishStatus.WaitingForPublish,
- }
- const list = await this.publishTaskModel.find(filters).sort({
- publishTime: 1,
- })
-
- return list
- }
-
- /**
- * 获取发布记录列表
- * @param query
- * @returns
- */
- async getPublishTasks(
- query: PublishRecordListFilterDto,
- ): Promise<PublishTask[]> {
- const filters: RootFilterQuery<PublishTask> = {
- userId: query.userId,
- ...(query.accountId !== undefined && { accountId: query.accountId }),
- ...(query.accountType !== undefined && {
- accountType: query.accountType,
- }),
- ...(query.status !== undefined && {
- status: query.status,
- }),
- ...(query.type !== undefined && { type: query.type }),
- ...(query.time !== undefined
- && query.time.length === 2 && {
- publishTime: { $gte: query.time[0], $lte: query.time[1] },
- }),
- ...(query.uid !== undefined && { uid: query.uid }),
- }
- const db = this.publishTaskModel.find(filters).sort({
- createdAt: -1,
- })
- const list = await db.exec()
-
- return list
- }
-
- async getQueuedPublishTasks(query: {
- userId: string
- accountId?: string
- accountType?: AccountType
- time?: [Date, Date]
- }): Promise<PublishTask[]> {
- const filters: RootFilterQuery<PublishTask> = {
- status: { $ne: PublishStatus.PUBLISHED },
- userId: query.userId,
- }
- if (query.accountId) {
- filters.accountId = query.accountId
- }
- if (query.accountType) {
- filters.accountType = query.accountType
- }
- if (query.time && query.time.length === 2) {
- filters.publishTime = { $gte: query.time[0], $lte: query.time[1] }
- }
- return this.publishTaskModel.find(filters).sort({
- createdAt: -1,
- })
- }
-
- /**
- * 获取时间段内发布任务列表
- * @param start
- * @param end
- * @returns
- */
- async getPublishTaskListByFlowId(
- flowId: string,
- ): Promise<PublishTask[]> {
- const filters: RootFilterQuery<PublishTask> = {
- flowId,
- }
- const list = await this.publishTaskModel.find(filters).sort({
- publishTime: 1,
- })
- return list
- }
-
- /**
- * 更新任务状态
- * @param id
- * @param newData
- * @returns
- */
- async updatePublishTaskStatus(
- id: string,
- newData: {
- errorMsg?: string
- status: PublishStatus
- },
- ): Promise<boolean> {
- const res = await this.publishTaskModel.updateOne({ _id: id }, newData)
- return res.modifiedCount > 0
- }
-
- // 查询任务是否在队列中,如果在,删除队列中的任务
- async deleteQueueTask(queueId: string) {
- const job = await this.queueService.getPostPublishJob(queueId)
- if (job) {
- const state = await job.getState()
- if (state === 'waiting' || state === 'delayed') {
- // 如果任务处于等待或延迟状态,则移除它
- await job.remove()
- this.logger.log(`任务 ${queueId} 已从队列中移除`)
- }
- else if (state === 'active') {
- // 如果任务正在执行中,不建议删除
- throw new AppException(ResponseCode.PublishTaskInProgress)
- }
- }
- }
-
- // 删除任务
- async deletePublishTaskById(id: string, userId: string): Promise<boolean> {
- // 获取数据
- const task = await this.publishTaskModel.findById(id).exec()
- if (!task) {
- throw new AppException(ResponseCode.PublishTaskNotFound)
- }
- if (task.inQueue && !!task.queueId) {
- await this.deleteQueueTask(task.queueId)
- }
-
- // 删除数据库数据
- const res = await this.publishTaskModel.deleteOne({ _id: id, userId })
- return res.deletedCount > 0
- }
-
- // 更新任务时间
- async updatePublishTaskTime(id: string, publishTime: Date, userId: string) {
- const task = await this.publishTaskModel.findById(id).exec()
- if (!task) {
- throw new AppException(ResponseCode.PublishTaskNotFound)
- }
-
- const res = await this.publishTaskModel.updateOne(
- { _id: id, userId },
- { publishTime },
- )
- if (task.inQueue && !!task.queueId) {
- await this.deleteQueueTask(task.queueId)
- }
- return res.modifiedCount > 0
- }
-
- // 获取发布任务信息
- async getPublishTaskInfo(id: string) {
- return this.publishTaskModel.findOne({ _id: id })
- }
-
- async getPublishTaskInfoWithFlowId(flowId: string, userId: string) {
- return this.publishTaskModel.findOne({ flowId, userId })
- }
-
- async getPublishTaskInfoWithUserId(id: string, userId: string) {
- return this.publishTaskModel.findOne({ _id: id, userId })
- }
-
- // 立即发布任务
- async publishTaskNow(id: string) {
- const taskDoc = await this.getPublishTaskInfo(id)
- const taskInfo = taskDoc!.toObject()
- if (!taskInfo) {
- throw new AppException(ResponseCode.PublishTaskNotFound)
- }
- if (taskInfo.status !== PublishStatus.WaitingForPublish) {
- throw new AppException(ResponseCode.PublishTaskStatusInvalid)
- }
- const pubService = this.publishServiceMap.get(taskInfo.accountType)
-
- taskInfo.publishTime = new Date()
- await this.publishTaskModel.updateOne({ _id: id }, taskInfo)
- await pubService?.pushPubTask(taskInfo)
- return true
- }
-
- async handleTiktokPostWebhook(data: TiktokWebhookDto) {
- return this.tiktokPubService.handleTiktokPostWebhook(data)
- }
-
- // push scheduled publish tasks
- @Cron(PUbLISHING_SCHEDULED_TASK_CRON_EXPRESSION, { waitForCompletion: true })
- async pushScheduledPubTasks() {
- this.logger.log(`Start pushing scheduled publish tasks, current time: ${new Date().toISOString()}`)
- try {
- const now = Date.now()
- const start = new Date(now - IMMEDIATE_PUBLISH_TOLERANCE_SECONDS)
- const end = new Date(now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS)
-
- const tasks = await this.getPublishTaskListByTime(start, end)
- if (tasks.length === 0) {
- this.logger.log(`Pushing scheduled publish tasks from ${start.toISOString()} to ${end.toISOString()}: No scheduled publish tasks found`)
- this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
- return
- }
- this.logger.log(
- `Pushing scheduled publish tasks from ${start.toISOString()} to ${end.toISOString()}, found ${tasks.length} tasks`,
- )
-
- for (const task of tasks) {
- await this.pushPubTask(task)
- }
- this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
- }
- catch (error) {
- this.logger.error(`Error pushing scheduled publish tasks: ${error.message}`, error.stack)
- this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
- }
- }
-
- private determineMetaPostCategory(data: CreatePublishDto) {
- switch (data.accountType) {
- case AccountType.FACEBOOK:
- if (!data.option || !data.option.facebook || !data.option.facebook.content_category) {
- data.option = {
- ...data.option,
- facebook: {
- ...data.option?.facebook,
- content_category: 'post',
- },
- }
- }
- break
- case AccountType.INSTAGRAM: {
- if (!data.option || !data.option.instagram || !data.option.instagram.content_category) {
- let category = 'post'
- if (data.videoUrl) {
- category = 'reel'
- }
- data.option = {
- ...data.option,
- instagram: {
- ...data.option?.instagram,
- content_category: category,
- },
- }
- }
- break
- }
- }
- }
-
- async createPublishingTask(data: CreatePublishDto) {
- try {
- const metaPlatforms = [AccountType.FACEBOOK, AccountType.INSTAGRAM]
- if (metaPlatforms.includes(data.accountType)) {
- this.determineMetaPostCategory(data)
- }
- this.logger.log(`Creating publish task with data: ${JSON.stringify(data)}`)
- data.publishTime = new Date(data.publishTime)
-
- const accountInfo = await this.accountService.getAccountInfo(
- data.accountId,
- )
- if (!accountInfo)
- throw new AppException(ResponseCode.ChannelAccountInfoFailed)
-
- const res = await this.createPub({
- ...data,
- uid: accountInfo.uid,
- userId: accountInfo.userId,
- inQueue: false,
- queueId: '',
- publishTime: data.publishTime,
- })
- return res
- }
- catch (e) {
- this.logger.error(e)
- return new AppException(ResponseCode.ChannelAccountInfoFailed)
- }
- }
-
- async onModuleDestroy() {
- this.logger.log('Module is being destroyed, closing publish queue...')
- await this.queueService.closePostPublishQueue()
- this.logger.log('Publish queue closed successfully')
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/common.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/common.ts
similarity index 90%
rename from project/backend/apps/aitoearn-channel/src/core/publish/common.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/common.ts
index 2dff0892..f1ca0be9 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/common.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/common.ts
@@ -1,4 +1,4 @@
-import { InitUploadVideoDto } from '../../core/plat/youtube/dto/youtube.dto'
+import { InitUploadVideoDto } from '../../core/platforms/youtube/dto/youtube.dto'
import { AddArchiveData } from '../../libs/bilibili/common'
import {
PublishStatus,
@@ -9,7 +9,7 @@ import { InstagramPost } from '../../libs/instagram/instagram.interfaces'
import { IPinterestOptions } from '../../libs/pinterest/common'
import { ThreadsPost } from '../../libs/threads/threads.interfaces'
import { TiktokPostOptions } from '../../libs/tiktok/tiktok.interfaces'
-import { WxGzhArticleNewsPic } from '../../libs/wxGzh/common'
+import { WxGzhArticleNewsPic } from '../../libs/wx-gzh/common'
export interface PlatPulOption {
bilibili?: Partial<Pick<
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/constant.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/constant.ts
similarity index 68%
rename from project/backend/apps/aitoearn-channel/src/core/publish/constant.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/constant.ts
index e651d5bf..02ecfec8 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/constant.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/constant.ts
@@ -1,4 +1,4 @@
import { CronExpression } from '@nestjs/schedule'
-export const PUbLISHING_SCHEDULED_TASK_CRON_EXPRESSION = CronExpression.EVERY_10_SECONDS
+export const PUBLISHING_SCHEDULED_TASK_CRON_EXPRESSION = CronExpression.EVERY_10_SECONDS
export const IMMEDIATE_PUBLISH_TOLERANCE_SECONDS = 10 * 1000
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/finalize-publish.consumer.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/finalize-publish.consumer.ts
new file mode 100644
index 00000000..32ce1e4a
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/finalize-publish.consumer.ts
@@ -0,0 +1,123 @@
+import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'
+import { Inject, Logger, OnModuleDestroy } from '@nestjs/common'
+import { QueueName } from '@yikart/aitoearn-queue'
+import { AccountType } from '@yikart/common'
+import { Job, UnrecoverableError } from 'bullmq'
+import { PublishStatus } from '../../../libs/database/schema/publishTask.schema'
+import { SocialMediaError } from '../../../libs/exception'
+import { PublishService } from '../providers/base.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingService } from '../publishing.service'
+
+@Processor(QueueName.PostMediaTask, {
+ concurrency: 3,
+ stalledInterval: 15000,
+ maxStalledCount: 1,
+})
+export class FinalizePublishPostConsumer extends WorkerHost implements OnModuleDestroy {
+ private readonly logger = new Logger(FinalizePublishPostConsumer.name)
+
+ @Inject('PUBLISHING_PROVIDERS')
+ private readonly publishingProviders: Record<AccountType, PublishService>
+
+ constructor(
+ readonly publishingService: PublishingService,
+ ) {
+ super()
+ }
+
+ async process(job: Job<{
+ taskId: string
+ attempts: number
+ }>): Promise<any> {
+ this.logger.log(`[task-${job.data.taskId}] Processing Meta Post Publish Task: ${job.data.taskId}`)
+ try {
+ const publishTaskInfo = await this.publishingService.getPublishTaskInfo(job.data.taskId)
+ const publishTask = publishTaskInfo!.toObject()
+ if (!publishTask) {
+ this.logger.error(`[task-${job.data.taskId}] Publish task not found: ${job.data.taskId}`)
+ return
+ }
+ const publishingProvider = this.publishingProviders[publishTask.accountType]
+ if (!publishingProvider) {
+ this.logger.error(`[task-${job.data.taskId}] Publishing provider not found for account type: ${publishTask.accountType}`)
+ return
+ }
+ const result = await publishingProvider.finalizePublish(publishTask)
+ if (result && result.status === PublishStatus.PUBLISHED) {
+ await this.publishingService.completePublishTask(publishTask, result.postId, {
+ workLink: result.permalink,
+ ...result.extra,
+ })
+ }
+ }
+ catch (error) {
+ if (error instanceof PublishingException) {
+ if (error.retryable) {
+ throw error
+ }
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.message,
+ })
+ throw new UnrecoverableError(error.message)
+ }
+ if (error instanceof SocialMediaError) {
+ if (error.isNetworkError) {
+ throw error
+ }
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.message,
+ })
+ throw new UnrecoverableError(error.message)
+ }
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.toString(),
+ })
+ throw new UnrecoverableError(error.toString())
+ }
+ }
+
+ @OnWorkerEvent('completed')
+ async onCompleted(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>) {
+ const { attempts } = job.data
+ this.logger.log(`[task-${job.data.taskId}] Publish Post Task completed: ${job.data.taskId} after ${job.attemptsMade} attempts (max: ${attempts})`)
+ }
+
+ @OnWorkerEvent('failed')
+ async onFailed(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>, error: unknown) {
+ this.logger.warn(`[task-${job.data.taskId}] finalize publish task failed, error: ${error.toString()}, retrying... Attempts made: ${job.attemptsMade}`)
+ if (job.opts.attempts && job.attemptsMade >= job.opts.attempts) {
+ this.logger.error(`[task-${job.data.taskId}] Finalize publish task failed after ${job.attemptsMade} attempts, error: ${error.toString()}`)
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.toString(),
+ })
+ }
+ }
+
+ @OnWorkerEvent('stalled')
+ onStalled(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>) {
+ this.logger.error(`[task-${job.data.taskId}] Job stalled: ${job.id}`)
+ }
+
+ async onModuleDestroy() {
+ this.logger.log('FinalizePublishPostConsumer is being destroyed, closing worker...')
+ await this.worker.close()
+ this.logger.log('FinalizePublishPostConsumer closed successfully')
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/immediate-publish.consumer.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/immediate-publish.consumer.ts
new file mode 100644
index 00000000..7ef0dcc9
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/immediate-publish.consumer.ts
@@ -0,0 +1,156 @@
+import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq'
+import { Inject, Logger, OnModuleDestroy } from '@nestjs/common'
+import { QueueName } from '@yikart/aitoearn-queue'
+import { AccountType } from '@yikart/common'
+import { Job, UnrecoverableError } from 'bullmq'
+import { PublishStatus } from '../../../libs/database/schema/publishTask.schema'
+import { SocialMediaError } from '../../../libs/exception'
+import { PublishService } from '../providers/base.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishingService } from '../publishing.service'
+
+@Processor(QueueName.PostPublish, {
+ concurrency: 3,
+ stalledInterval: 15000,
+ maxStalledCount: 1,
+})
+export class ImmediatePublishPostConsumer extends WorkerHost implements OnModuleDestroy {
+ private readonly logger = new Logger(ImmediatePublishPostConsumer.name)
+ @Inject('PUBLISHING_PROVIDERS')
+ private readonly publishingProviders: Record<AccountType, PublishService>
+
+ constructor(readonly publishingService: PublishingService) {
+ super()
+ }
+
+ async process(
+ job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ timeout?: number
+ }>,
+ ): Promise<PublishingTaskResult | void> {
+ const { taskId, attempts } = job.data
+ this.logger.log(`[task-${taskId}] Processing Publish Task, data: ${JSON.stringify(job.data)}, Attempts: ${attempts}`)
+
+ try {
+ const publishTaskInfo = await this.publishingService.getPublishTaskInfo(taskId)
+ if (!publishTaskInfo) {
+ this.logger.error(`[task-${taskId}] Publish task not found: ${taskId}`)
+ return
+ }
+ if (publishTaskInfo.status === PublishStatus.PUBLISHED) {
+ this.logger.warn(`[task-${taskId}] Publish task already published: ${taskId}`)
+ return
+ }
+
+ if (publishTaskInfo.status === PublishStatus.PUBLISHING) {
+ this.logger.warn(`[task-${taskId}] Publish task already publishing: ${taskId}`)
+ return
+ }
+
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.PUBLISHING,
+ errorMsg: '',
+ inQueue: true,
+ queued: true,
+ })
+
+ const taskInfo = publishTaskInfo.toObject()
+ const publishingProvider = this.publishingProviders[taskInfo.accountType]
+ if (!publishingProvider) {
+ this.logger.error(`[task-${taskId}] Publishing provider not found for account type: ${taskInfo.accountType}`)
+ return
+ }
+ const result = await publishingProvider.immediatePublish(taskInfo)
+ if (result.status === PublishStatus.PUBLISHED) {
+ await this.publishingService.completePublishTask(taskInfo, result.postId, {
+ workLink: result.permalink,
+ ...result.extra,
+ })
+ }
+ else {
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: result.status,
+ errorMsg: '',
+ inQueue: false,
+ queued: false,
+ })
+ }
+ }
+ catch (error: unknown) {
+ if (error instanceof PublishingException) {
+ if (error.retryable) {
+ throw error
+ }
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.message,
+ inQueue: false,
+ queued: false,
+ })
+ throw new UnrecoverableError(error.message)
+ }
+ if (error instanceof SocialMediaError) {
+ if (error.isNetworkError) {
+ if (job.opts.backoff) {
+ throw error
+ }
+ }
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.message,
+ inQueue: false,
+ queued: false,
+ })
+ throw new UnrecoverableError(error.message)
+ }
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.toString(),
+ inQueue: false,
+ queued: false,
+ })
+ throw new UnrecoverableError(error.toString())
+ }
+ }
+
+ @OnWorkerEvent('completed')
+ async onCompleted(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>) {
+ const { taskId, attempts, jobId } = job.data
+ this.logger.log(`[task-${taskId}] Processing completed for job ${jobId}, taskId: ${taskId}, Attempts: ${attempts}`)
+ }
+
+ @OnWorkerEvent('failed')
+ async onFailed(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>, error: unknown) {
+ this.logger.warn(`[task-${job.data.taskId}] finalize publish task failed, error: ${error.toString()}, retrying... Attempts made: ${job.attemptsMade}`)
+ if (job.opts.attempts && job.attemptsMade >= job.opts.attempts) {
+ this.logger.error(`[task-${job.data.taskId}] Finalize publish task failed after ${job.attemptsMade} attempts, error: ${error.toString()}`)
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.FAILED,
+ errorMsg: error.toString(),
+ })
+ }
+ }
+
+ @OnWorkerEvent('stalled')
+ onStalled(job: Job) {
+ this.logger.error(`Job ${job.id}] is stalled, data ${job.data}`)
+ }
+
+ async onModuleDestroy() {
+ this.logger.log('PostPublishConsumer is being destroyed, closing worker...')
+ await this.worker.close()
+ this.logger.log('PostPublishConsumer closed successfully')
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/dto/meta.container.dto.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/meta.container.dto.ts
similarity index 80%
rename from project/backend/apps/aitoearn-channel/src/core/publish/dto/meta.container.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/dto/meta.container.dto.ts
index deead9d3..c32fcab5 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/dto/meta.container.dto.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/meta.container.dto.ts
@@ -1,9 +1,11 @@
+import { createZodDto } from '@yikart/common'
import { z } from 'zod'
import { PostCategory, PostMediaStatus, PostSubCategory } from '../../../libs/database/schema/postMediaContainer.schema'
export const PostMediaContainer = z.object({
publishId: z.string().describe('发布任务ID'),
userId: z.string().describe('用户ID'),
+ jobId: z.string().describe('任务ID'),
platform: z.string().describe('平台'),
taskId: z.string().describe('任务ID'),
status: z.enum(PostMediaStatus).describe('任务状态').default(PostMediaStatus.CREATED),
@@ -13,8 +15,4 @@ export const PostMediaContainer = z.object({
option: z.any().optional(),
})
-export class CreatePostMediaContainerDto {
- constructor(data: z.infer<typeof PostMediaContainer>) {
- Object.assign(this, data)
- }
-}
+export class CreatePostMediaContainerDto extends createZodDto(PostMediaContainer) {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/dto/publish.dto.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/publish/dto/publish.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/dto/tiktok.webhook.dto.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/tiktok.webhook.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/publish/dto/tiktok.webhook.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/dto/tiktok.webhook.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/base.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/base.service.ts
new file mode 100644
index 00000000..20e91ba6
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/base.service.ts
@@ -0,0 +1,256 @@
+import { Inject, Injectable } from '@nestjs/common'
+import { InjectModel } from '@nestjs/mongoose'
+
+import { QueueService } from '@yikart/aitoearn-queue'
+import { PublishRecord } from '@yikart/aitoearn-server-client'
+import { Model } from 'mongoose'
+import { PostCategory, PostMediaStatus, PostSubCategory } from '../../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { PublishRecordService } from '../../account/publish-record.service'
+import { PublishingException } from '../publishing.exception'
+import { MediaProcessingStatus, MediaProcessingStatusResult, PublishingTaskResult } from '../publishing.interface'
+import { PostMediaContainerService } from './container.service'
+
+@Injectable()
+export abstract class PublishService {
+ protected readonly queueAttempts: number = 3
+ protected readonly queueDelay: number = 5
+ protected readonly ProcessMediaFailed: string = 'failed'
+ protected readonly ProcessMediaInProgress: string = 'processing'
+ protected readonly ProcessMediaCompleted: string = 'completed'
+
+ @Inject(QueueService)
+ protected readonly queueService: QueueService
+
+ @InjectModel(PublishTask.name)
+ protected readonly publishTaskModel: Model<PublishTask>
+
+ @Inject(PublishRecordService)
+ protected readonly publishRecordService: PublishRecordService
+
+ @Inject(PostMediaContainerService)
+ protected readonly postMediaContainerService: PostMediaContainerService
+
+ constructor() {}
+
+ abstract immediatePublish(_publishTask: PublishTask): Promise<PublishingTaskResult>
+
+ async finalizePublish(
+ _publishTask: PublishTask,
+ ): Promise<PublishingTaskResult | void> {
+ }
+
+ protected async getMediaProcessingStatus(
+ _accountId: string,
+ _mediaId: string,
+ ): Promise<string | void> {
+ }
+
+ protected async createPublishingTask(newData: Partial<PublishTask>) {
+ return await this.publishTaskModel.create(newData)
+ }
+
+ protected async createPublishingRecord(newData: Partial<PublishRecord>) {
+ newData.publishTime = newData.publishTime || new Date()
+ await this.publishRecordService.createPublishRecord(newData)
+ }
+
+ async enqueue(task: PublishTask): Promise<boolean> {
+ const jobRes = await this.queueService.addPostPublishJob(
+ {
+ taskId: task.id,
+ jobId: task.id,
+ attempts: 0,
+ },
+ {
+ attempts: this.queueAttempts,
+ backoff: {
+ type: 'exponential',
+ delay: this.queueDelay,
+ },
+ removeOnComplete: true,
+ removeOnFail: true,
+ jobId: task.id,
+ },
+ )
+ return jobRes.id === task.id
+ }
+
+ async updateQueueId(id: string, queueId: string) {
+ return await this.publishTaskModel.updateOne({ _id: id }, { queueId, queued: true }).exec()
+ }
+
+ protected async getPublishingTaskInfo(id: string) {
+ return await this.publishTaskModel.findOne({ _id: id }).exec()
+ }
+
+ protected async completePublishingTask(
+ newData: PublishTask,
+ dataId: string,
+ data?: {
+ workLink: string
+ dataOption?: Record<string, any>
+ },
+ ) {
+ newData.status = PublishStatus.PUBLISHED
+ await this.publishTaskModel.updateOne(
+ { _id: newData.id },
+ { status: PublishStatus.PUBLISHED, dataId, workLink: data?.workLink },
+ ).exec()
+ await this.createPublishingRecord({
+ ...newData,
+ ...(data || {}),
+ dataId,
+ })
+ }
+
+ protected async failPublishingTask(id: string, errMsg: string) {
+ await this.publishTaskModel.updateOne(
+ { _id: id },
+ { status: PublishStatus.FAILED, errorMsg: errMsg },
+ ).exec()
+ }
+
+ protected generatePostMessage(publishTask: PublishTask): string {
+ if (!publishTask) {
+ return ''
+ }
+ if (publishTask.topics && publishTask.topics.length > 0) {
+ if (publishTask.desc) {
+ return `${publishTask.desc} #${publishTask.topics.join(' #')}`
+ }
+ return `#${publishTask.topics.join(' #')}`
+ }
+ return publishTask.desc || ''
+ }
+
+ protected async processUploadMedia(
+ publishTask: PublishTask,
+ platform: string,
+ category: PostCategory,
+ subCategory: PostSubCategory,
+ taskId: string,
+ ): Promise<void> {
+ await this.savePostMedia(publishTask, platform, category, subCategory, taskId)
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ }
+
+ protected async savePostMedia(
+ publishTask: PublishTask,
+ platform: string,
+ category: PostCategory,
+ subCategory: PostSubCategory,
+ taskId: string,
+ status: PostMediaStatus = PostMediaStatus.CREATED,
+ ): Promise<void> {
+ await this.postMediaContainerService.createMetaPostMedia({
+ jobId: publishTask.queueId,
+ accountId: publishTask.accountId,
+ publishId: publishTask.id,
+ userId: publishTask.userId,
+ platform,
+ taskId,
+ status,
+ category,
+ subCategory,
+ })
+ }
+
+ protected async publishPostMediaTask(taskId: string, jobId: string) {
+ await this.queueService.addPostMediaTaskJob(
+ {
+ taskId,
+ attempts: 0,
+ jobId: `${jobId}-medias`,
+ },
+ {
+ attempts: 5,
+ backoff: {
+ type: 'fixed',
+ delay: 15000,
+ },
+ removeOnComplete: true,
+ removeOnFail: true,
+ },
+ )
+ }
+
+ protected async getMediasProcessingStatus(
+ task: PublishTask,
+ ): Promise<MediaProcessingStatusResult> {
+ const mediasStatus: MediaProcessingStatus[] = []
+ let hasFailed = false
+ const medias = await this.postMediaContainerService.getContainers(
+ task.id,
+ task.queueId,
+ )
+ if (!medias || medias.length === 0) {
+ throw PublishingException.nonRetryable(`Media not found for task ID: ${task.id}`)
+ }
+ // check if all media files are processed
+ let completedCount = 0
+ for (const media of medias) {
+ if (media.status === PostMediaStatus.FINISHED) {
+ mediasStatus.push({ id: media.id, status: media.status, taskId: media.taskId, category: media.category })
+ completedCount++
+ continue
+ }
+ let status = PostMediaStatus.IN_PROGRESS
+ const mediaStatus = await this.getMediaProcessingStatus(task.accountId, media.taskId)
+ // if media processing failed, update the media status to failed and break the loop
+ if (mediaStatus === this.ProcessMediaFailed) {
+ status = PostMediaStatus.FAILED
+ hasFailed = true
+ break
+ }
+ if (mediaStatus === this.ProcessMediaCompleted) {
+ status = PostMediaStatus.FINISHED
+ completedCount++
+ }
+ await this.postMediaContainerService.updateContainer(media.id, {
+ status,
+ })
+ mediasStatus.push({ id: media.id, status, taskId: media.taskId, category: media.category })
+ }
+ return {
+ medias: mediasStatus,
+ isCompleted: completedCount === medias.length,
+ hasFailed,
+ }
+ }
+
+ protected async createPublishRecord(newData: Partial<PublishRecord>) {
+ newData.publishTime = newData.publishTime || new Date()
+ await this.publishRecordService.createPublishRecord(newData)
+ }
+
+ async completePublishTask(
+ newData: PublishTask,
+ dataId: string,
+ data?: {
+ workLink: string
+ dataOption?: Record<string, any>
+ },
+ ) {
+ newData.status = PublishStatus.PUBLISHED
+ await this.publishTaskModel.updateOne(
+ { _id: newData.id },
+ { status: PublishStatus.PUBLISHED, dataId, workLink: data?.workLink },
+ ).exec()
+ await this.createPublishRecord({
+ ...newData,
+ ...(data || {}),
+ dataId,
+ })
+ }
+
+ async updatePublishTaskStatus(id: string, status: PublishStatus, errMsg?: string) {
+ await this.publishTaskModel.updateOne(
+ { _id: id },
+ { status, errorMsg: errMsg },
+ ).exec()
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/bilibili.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/bilibili.service.ts
new file mode 100644
index 00000000..0278e8a8
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/bilibili.service.ts
@@ -0,0 +1,90 @@
+import { Injectable, Logger } from '@nestjs/common'
+import {
+ chunkedDownloadFile,
+ fileUrlToBase64,
+ getFileTypeFromUrl,
+ getRemoteFileSize,
+} from '../../../common'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { BilibiliService } from '../../platforms/bilibili/bilibili.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class BilibiliPubService extends PublishService {
+ private readonly logger = new Logger(BilibiliPubService.name)
+
+ constructor(
+ readonly bilibiliService: BilibiliService,
+ ) {
+ super()
+ }
+
+ async uploadThumbnail(accountId: string, rawThumbnailURL: string) {
+ if (!rawThumbnailURL) {
+ return ''
+ }
+ this.logger.log(`upload thumbnail, url: ${rawThumbnailURL}`)
+ const urlBase64 = await fileUrlToBase64(rawThumbnailURL)
+ const thumbnailURL = await this.bilibiliService.coverUpload(
+ accountId,
+ urlBase64,
+ )
+ return thumbnailURL
+ }
+
+ async uploadVideo(accountId: string, videoUrl: string) {
+ const fileName = getFileTypeFromUrl(videoUrl)
+ const contentLength = await getRemoteFileSize(videoUrl)
+ const uploadToken = await this.bilibiliService.videoInit(
+ accountId,
+ fileName,
+ 0,
+ )
+ const chunkSize = 1024 * 1024 * 5
+ const chunkCount = Math.ceil(contentLength / chunkSize)
+
+ for (let seq = 1; seq <= chunkCount; seq++) {
+ const start = (seq - 1) * chunkSize
+ const end = Math.min(seq * chunkSize - 1, contentLength - 1)
+ const chunkFile = await chunkedDownloadFile(videoUrl, [start, end])
+ await this.bilibiliService.uploadVideoPart(
+ accountId,
+ chunkFile,
+ uploadToken,
+ seq,
+ )
+ }
+ await this.bilibiliService.videoComplete(accountId, uploadToken)
+ return uploadToken
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { coverUrl, accountId, videoUrl } = publishTask
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('video url is required')
+ }
+ const thumbnail = await this.uploadThumbnail(accountId, coverUrl)
+ const videoUpToken = await this.uploadVideo(accountId, videoUrl)
+ const postId = await this.bilibiliService.archiveAddByUtoken(
+ accountId,
+ videoUpToken,
+ {
+ title: publishTask.title || '',
+ cover: thumbnail,
+ desc: publishTask.desc,
+ ...publishTask.option!.bilibili!,
+ tag: publishTask.topics?.join(','),
+ },
+ )
+ return {
+ postId,
+ permalink: `https://www.bilibili.com/video/${postId}`,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/container.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/container.service.ts
similarity index 56%
rename from project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/container.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/providers/container.service.ts
index d23b31e6..3819c694 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/container.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/container.service.ts
@@ -1,8 +1,8 @@
import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
-import { PostMediaContainer, PostMediaStatus } from '../../../../libs/database/schema/postMediaContainer.schema'
-import { CreatePostMediaContainerDto } from '../../dto/meta.container.dto'
+import { PostMediaContainer, PostMediaStatus } from '../../../libs/database/schema/postMediaContainer.schema'
+import { CreatePostMediaContainerDto } from '../dto/meta.container.dto'
@Injectable()
export class PostMediaContainerService {
@@ -14,12 +14,25 @@ export class PostMediaContainerService {
async createMetaPostMedia(
data: CreatePostMediaContainerDto,
): Promise<PostMediaContainer> {
- const subPublishTask = new this.metaPostMediaModel(data)
- return subPublishTask.save()
+ return await this.metaPostMediaModel.insertOne(data)
}
- async getContainers(publishId: string): Promise<PostMediaContainer[]> {
- return this.metaPostMediaModel.find({ publishId }).sort({ createdAt: 1 })
+ async deleteMetaPostMedia(publishId: string): Promise<void> {
+ await this.metaPostMediaModel.deleteMany({ publishId }).exec()
+ }
+
+ async upsertMetaPostMedia(
+ data: CreatePostMediaContainerDto,
+ ): Promise<PostMediaContainer> {
+ return await this.metaPostMediaModel.findOneAndUpdate(
+ { publishId: data.publishId, platform: data.platform },
+ data,
+ { upsert: true, new: true },
+ ).exec()
+ }
+
+ async getContainers(publishId: string, jobId: string): Promise<PostMediaContainer[]> {
+ return this.metaPostMediaModel.find({ publishId, jobId }).sort({ createdAt: 1 })
}
async getUnProcessedContainers(publishId: string): Promise<PostMediaContainer[]> {
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/facebook.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/facebook.service.ts
new file mode 100644
index 00000000..9e3c8d91
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/facebook.service.ts
@@ -0,0 +1,384 @@
+import { Injectable, Logger } from '@nestjs/common'
+import {
+ chunkedDownloadFile,
+ fileUrlToBlob,
+ getRemoteFileSize,
+} from '../../../common'
+import { FacebookService } from '../../../core/platforms/meta/facebook.service'
+import {
+ PostCategory,
+ PostSubCategory,
+} from '../../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import {
+ ChunkedVideoUploadRequest,
+ FacebookInitialVideoUploadRequest,
+ FacebookReelRequest,
+ FacebookReelResponse,
+ finalizeVideoUploadRequest,
+ PublishFeedPostRequest,
+ PublishVideoPostRequest,
+} from '../../../libs/facebook/facebook.interfaces'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class FacebookPublishService
+ extends PublishService {
+ private readonly logger = new Logger(FacebookPublishService.name, {
+ timestamp: true,
+ })
+
+ protected override readonly ProcessMediaFailed = 'error'
+ protected override readonly ProcessMediaInProgress = 'processing'
+ protected override readonly ProcessMediaCompleted = 'upload_complete'
+
+ constructor(
+ readonly facebookService: FacebookService,
+ ) {
+ super()
+ }
+
+ async uploadImage(accountId: string, imgUrl: string): Promise<string> {
+ const imgBlob = await fileUrlToBlob(imgUrl)
+ const uploadReq = await this.facebookService.uploadImage(
+ accountId,
+ imgBlob.blob,
+ )
+ return uploadReq.id
+ }
+
+ async uploadReelVideo(accountId: string, videoUrl: string): Promise<string> {
+ const contentLength = await getRemoteFileSize(videoUrl)
+ const initUploadReq: FacebookReelRequest = {
+ upload_phase: 'start',
+ }
+ const initUploadRes = await this.facebookService.initReelUpload(
+ accountId,
+ initUploadReq,
+ )
+ if (!initUploadRes || !initUploadRes.upload_url) {
+ this.logger.error(`Video initialization upload failed, response: ${JSON.stringify(initUploadRes)}`)
+ throw PublishingException.nonRetryable('Video initialization upload failed')
+ }
+
+ const videoFile = await chunkedDownloadFile(videoUrl, [0, contentLength - 1])
+ const uploadRes = await this.facebookService.uploadReel(
+ accountId,
+ initUploadRes.upload_url,
+ {
+ offset: 0,
+ file_size: contentLength,
+ file: videoFile,
+ },
+ )
+ if (!uploadRes || !uploadRes.success) {
+ throw PublishingException.nonRetryable('Video upload failed')
+ }
+ return initUploadRes.video_id
+ }
+
+ async uploadVideoStory(accountId: string, videoUrl: string): Promise<string> {
+ const contentLength = await getRemoteFileSize(videoUrl)
+ const initUploadReq: FacebookReelRequest = {
+ upload_phase: 'start',
+ }
+ const initUploadRes = await this.facebookService.initVideoStoryUpload(
+ accountId,
+ initUploadReq,
+ )
+ if (!initUploadRes || !initUploadRes.upload_url) {
+ this.logger.error(`Video initialization upload failed, response: ${JSON.stringify(initUploadRes)}`)
+ throw new Error('Video initialization upload failed')
+ }
+ const videoFile = await chunkedDownloadFile(videoUrl, [0, contentLength - 1])
+ await this.facebookService.uploadVideoStory(
+ accountId,
+ initUploadRes.upload_url,
+ {
+ offset: 0,
+ file_size: contentLength,
+ file: videoFile,
+ },
+ )
+ return initUploadRes.video_id
+ }
+
+ async publishFeedPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ this.logger.log(`Received publish task: ${publishTask.id} for Facebook Feed Post`)
+ if (!publishTask.desc) {
+ throw PublishingException.nonRetryable('Feed Post requires a description')
+ }
+ const feedPostReq: PublishFeedPostRequest = {
+ message: this.generatePostMessage(publishTask),
+ published: true,
+ }
+ const postRes = await this.facebookService.publishFeedPost(
+ publishTask.accountId,
+ feedPostReq,
+ )
+ const permalink = `https://www.facebook.com/${publishTask.uid}_${postRes.id}`
+ return {
+ status: PublishStatus.PUBLISHED,
+ postId: postRes.id,
+ permalink,
+ }
+ }
+
+ async publishReelPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ this.logger.log(`Received publish task: ${publishTask.id} for Facebook Reel`)
+ const { imgUrlList, accountId, videoUrl } = publishTask
+ if (imgUrlList && imgUrlList.length > 0) {
+ throw PublishingException.nonRetryable('Reel does not support image uploads')
+ }
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('Reel requires a video URL')
+ }
+
+ const videoId = await this.uploadReelVideo(accountId, videoUrl)
+ await this.processUploadMedia(publishTask, 'facebook', PostCategory.STORY, PostSubCategory.VIDEO, videoId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishPhotoStory(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ this.logger.log(`Received publish task: ${publishTask.id} for Facebook Story`)
+ const { imgUrlList, accountId } = publishTask
+ if (!imgUrlList) {
+ throw PublishingException.nonRetryable('Story requires images')
+ }
+
+ if (imgUrlList && imgUrlList.length < 1) {
+ throw PublishingException.nonRetryable('Story requires at least one image')
+ }
+
+ const imgUrl = imgUrlList[0]
+ const containerId = await this.uploadImage(accountId, imgUrl)
+
+ await this.facebookService.publishPhotoStory(
+ accountId,
+ containerId,
+ )
+ const permalink = `https://www.facebook.com/stories/${containerId}`
+ return {
+ postId: containerId,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async publishVideoStory(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ if (!publishTask.videoUrl) {
+ throw PublishingException.nonRetryable('Story requires a video URL')
+ }
+ const videoId = await this.uploadVideoStory(publishTask.accountId, publishTask.videoUrl)
+ await this.processUploadMedia(publishTask, 'facebook', PostCategory.STORY, PostSubCategory.VIDEO, videoId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishStory(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ this.logger.log(`Received publish task: ${publishTask.id} for Facebook Story`)
+ const { imgUrlList, videoUrl } = publishTask
+ if (!videoUrl && !imgUrlList) {
+ throw PublishingException.nonRetryable('Story requires a video or images')
+ }
+
+ if (imgUrlList && imgUrlList.length > 0) {
+ return await this.publishPhotoStory(publishTask)
+ }
+ return await this.publishVideoStory(publishTask)
+ }
+
+ async publishVideo(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ this.logger.log(`Received publish task: ${publishTask.id} for Facebook`)
+ const { imgUrlList, accountId, videoUrl } = publishTask
+ const facebookMediaIdList: string[] = []
+ if (imgUrlList && imgUrlList.length > 0) {
+ for (const imgUrl of imgUrlList) {
+ const imgBlob = await fileUrlToBlob(imgUrl)
+ const uploadReq = await this.facebookService.uploadImage(
+ accountId,
+ imgBlob.blob,
+ )
+ facebookMediaIdList.push(uploadReq.id)
+ }
+ if (facebookMediaIdList.length === 0) {
+ throw PublishingException.nonRetryable('Image upload failed')
+ }
+ const publishPost = await this.facebookService.publicPhotoPost(
+ accountId,
+ facebookMediaIdList,
+ this.generatePostMessage(publishTask),
+ )
+ const permalink = `https://www.facebook.com/${publishTask.uid}_${publishPost.id}`
+ const result = {
+ postId: publishPost.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ return result
+ }
+
+ if (videoUrl) {
+ const contentLength = await getRemoteFileSize(videoUrl)
+
+ const initUploadReq: FacebookInitialVideoUploadRequest = {
+ upload_phase: 'start',
+ file_size: contentLength,
+ published: false,
+ }
+ const initUploadRes = await this.facebookService.initVideoUpload(
+ accountId,
+ initUploadReq,
+ )
+ let startOffset = initUploadRes.start_offset
+ let endOffset = initUploadRes.end_offset
+
+ while (startOffset < contentLength - 1) {
+ const range: [number, number] = [startOffset, endOffset - 1]
+ const videoBlob = await chunkedDownloadFile(videoUrl, range)
+ const chunkedUploadReq: ChunkedVideoUploadRequest = {
+ upload_phase: 'transfer',
+ upload_session_id: initUploadRes.upload_session_id,
+ start_offset: startOffset,
+ end_offset: endOffset,
+ video_file_chunk: videoBlob,
+ published: false,
+ }
+ this.logger.log(`Chunked upload request: start_offset=${startOffset}, end_offset=${endOffset}`)
+ const chunkedUploadRes
+ = await this.facebookService.chunkedMediaUpload(
+ accountId,
+ chunkedUploadReq,
+ )
+ startOffset = chunkedUploadRes.start_offset
+ endOffset = chunkedUploadRes.end_offset
+ }
+ const finalizeReq: finalizeVideoUploadRequest = {
+ upload_phase: 'finish',
+ upload_session_id: initUploadRes.upload_session_id,
+ published: false,
+ }
+ const finalizeRes = await this.facebookService.finalizeMediaUpload(
+ accountId,
+ finalizeReq,
+ )
+ if (!finalizeRes.success) {
+ throw new Error('Video upload finalization failed')
+ }
+ const videoPostReq: PublishVideoPostRequest = {
+ description: this.generatePostMessage(publishTask),
+ crossposted_video_id: initUploadRes.video_id,
+ published: true,
+ }
+ const postRes = await this.facebookService.publishVideoPost(
+ accountId,
+ videoPostReq,
+ )
+ const permalink = `https://www.facebook.com/${publishTask.uid}_${postRes.id}`
+ const result = {
+ postId: postRes.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ return result
+ }
+ throw PublishingException.nonRetryable('Invalid publish task: no media and no description')
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const contentCategory = publishTask.option?.facebook?.content_category
+ if (!contentCategory) {
+ throw PublishingException.nonRetryable('Invalid publish task: no Facebook page contentCategory specified')
+ }
+ const { imgUrlList, videoUrl, desc } = publishTask
+ if (!imgUrlList && !videoUrl && !desc) {
+ throw PublishingException.nonRetryable('Invalid publish task: no media and no description')
+ }
+ switch (contentCategory) {
+ case 'post':
+ if (!imgUrlList && !videoUrl) {
+ return await this.publishFeedPost(publishTask)
+ }
+ else {
+ return await this.publishVideo(publishTask)
+ }
+ case 'reel':
+ return await this.publishReelPost(publishTask)
+ case 'story':
+ return await this.publishStory(publishTask)
+ default:
+ throw PublishingException.nonRetryable(`Unsupported content category: ${contentCategory}`)
+ }
+ }
+
+ override async getMediaProcessingStatus(accountId: string, mediaId: string): Promise<string | void> {
+ const mediaStatusInfo = await this.facebookService.getObjectInfo(accountId, mediaId, 'status')
+ if (!mediaStatusInfo || !mediaStatusInfo.id) {
+ throw PublishingException.nonRetryable(`Failed to get media status, media ID: ${mediaId}`)
+ }
+ return mediaStatusInfo.status.video_status
+ }
+
+ override async finalizePublish(task: PublishTask): Promise<PublishingTaskResult> {
+ const mediasStatus = await this.getMediasProcessingStatus(task)
+ if (mediasStatus.hasFailed) {
+ throw PublishingException.nonRetryable(`Media processing failed for task ID: ${task.id}`)
+ }
+ if (!mediasStatus.isCompleted) {
+ throw PublishingException.retryable(`Media files are still processing. Please wait for media processing to complete.`)
+ }
+ this.logger.log(`All media files processed for task ID: ${task.id}`)
+ let publishRes: FacebookReelResponse = null
+ if (task.option?.facebook?.content_category === 'reel') {
+ publishRes = await this.facebookService.publishReel(
+ task.accountId,
+ {
+ upload_phase: 'finish',
+ video_state: 'published',
+ video_id: mediasStatus.medias[0].taskId,
+ description: this.generatePostMessage(task),
+ },
+ )
+ }
+
+ if (task.option?.facebook?.content_category === 'story') {
+ publishRes = await this.facebookService.publishVideoStory(
+ task.accountId,
+ {
+ upload_phase: 'finish',
+ video_state: 'published',
+ video_id: mediasStatus.medias[0].taskId,
+ description: this.generatePostMessage(task),
+ },
+ )
+ }
+ this.logger.log(
+ `publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(publishRes)}`,
+ )
+ if (!publishRes || !publishRes.success) {
+ this.logger.log(
+ `Failed to publish media container for task ID: ${task.id}`,
+ )
+ throw PublishingException.nonRetryable(`Failed to publish media container for task ID: ${task.id}`)
+ }
+ let category = 'stories'
+ if (task.option?.facebook?.content_category === 'reel') {
+ category = 'reel'
+ }
+ const postId = mediasStatus.medias[0].taskId
+ const permalink = `https://www.facebook.com/${category}/${postId}`
+ return {
+ postId,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/instgram.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/instgram.service.ts
new file mode 100644
index 00000000..c9aac928
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/instgram.service.ts
@@ -0,0 +1,218 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { UnrecoverableError } from 'bullmq'
+import { v4 as uuidv4 } from 'uuid'
+import { InstagramService } from '../../../core/platforms/meta/instagram.service'
+import {
+ PostCategory,
+ PostMediaStatus,
+ PostSubCategory,
+} from '../../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { InstagramMediaType } from '../../../libs/instagram/instagram.enum'
+import { CreateMediaContainerRequest } from '../../../libs/instagram/instagram.interfaces'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class InstagramPublishService
+ extends PublishService {
+ private readonly logger = new Logger(InstagramPublishService.name, {
+ timestamp: true,
+ })
+
+ protected override readonly ProcessMediaFailed = 'FAILED'
+ protected override readonly ProcessMediaInProgress = 'IN_PROGRESS'
+ protected override readonly ProcessMediaCompleted = 'FINISHED'
+
+ constructor(
+ readonly instagramService: InstagramService,
+ ) {
+ super()
+ }
+
+ override async getMediaProcessingStatus(accountId: string, mediaId: string): Promise<string | void> {
+ const mediaStatusInfo = await this.instagramService.getObjectInfo(accountId, mediaId, 'status')
+ return mediaStatusInfo.status
+ }
+
+ private async getPostPermalink(accountId: string, postId: string): Promise<string> {
+ try {
+ const postInfo = await this.instagramService.getObjectInfo(accountId, postId, '', 'permalink')
+ return postInfo.permalink
+ }
+ catch (error) {
+ this.logger.error(`Failed to get post permalink for accountId: ${accountId}, postId: ${postId}, error: ${error}`)
+ return ''
+ }
+ }
+
+ private async createMediaContainer(publishTask: PublishTask, srcImgURL: string, mediaType = InstagramMediaType.IMAGE, isCarouselItem = false): Promise<void> {
+ const createContainerReq: CreateMediaContainerRequest = {
+ media_type: mediaType,
+ image_url: srcImgURL,
+ caption: this.generatePostMessage(publishTask) || publishTask.title || '',
+ }
+ if (isCarouselItem) {
+ createContainerReq.is_carousel_item = true
+ }
+ const initUploadRes = await this.instagramService.createMediaContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.savePostMedia(publishTask, 'instagram', PostCategory.POST, PostSubCategory.PHOTO, initUploadRes.id, PostMediaStatus.CREATED)
+ }
+
+ async publishPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ if (!publishTask.imgUrlList || publishTask.imgUrlList.length === 0) {
+ throw new UnrecoverableError('No image resources')
+ }
+ const isCarouselItem = publishTask.imgUrlList.length > 1
+ for (const imgUrl of publishTask.imgUrlList) {
+ await this.createMediaContainer(publishTask, imgUrl, InstagramMediaType.IMAGE, isCarouselItem)
+ }
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishReel(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ if (!publishTask.videoUrl) {
+ throw new UnrecoverableError('No video resources')
+ }
+
+ const createContainerReq: CreateMediaContainerRequest = {
+ video_url: publishTask.videoUrl,
+ media_type: InstagramMediaType.REELS,
+ caption: publishTask.desc || publishTask.title || '',
+ }
+ const initUploadRes = await this.instagramService.createMediaContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.savePostMedia(publishTask, 'instagram', PostCategory.REELS, PostSubCategory.VIDEO, initUploadRes.id)
+
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishVideoStory(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ if (!publishTask.videoUrl) {
+ throw new Error('No video resources')
+ }
+ const createContainerReq: CreateMediaContainerRequest = {
+ video_url: publishTask.videoUrl,
+ media_type: InstagramMediaType.STORIES,
+ caption: this.generatePostMessage(publishTask) || publishTask.title || '',
+ }
+ const initUploadRes = await this.instagramService.createMediaContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.savePostMedia(publishTask, 'instagram', PostCategory.STORY, PostSubCategory.VIDEO, initUploadRes.id)
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishPhotoStory(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ if (!publishTask.imgUrlList || publishTask.imgUrlList.length === 0) {
+ throw new Error('No image resources')
+ }
+ const createContainerReq: CreateMediaContainerRequest = {
+ media_type: InstagramMediaType.STORIES,
+ image_url: publishTask.imgUrlList[0],
+ }
+ const initUploadRes = await this.instagramService.createMediaContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.savePostMedia(publishTask, 'instagram', PostCategory.STORY, PostSubCategory.PHOTO, initUploadRes.id)
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ override async finalizePublish(task: PublishTask): Promise<PublishingTaskResult> {
+ const mediasStatus = await this.getMediasProcessingStatus(task)
+ if (mediasStatus.hasFailed) {
+ throw PublishingException.nonRetryable(`Media processing failed for task ID: ${task.id}`)
+ }
+ if (!mediasStatus.isCompleted) {
+ throw PublishingException.retryable(`Task-[${task.id}] Media files are still processing. Please wait for media processing to complete.`)
+ }
+ this.logger.log(`All media files processed for task ID: ${task.id}`)
+ const postCategory = mediasStatus.medias[0].category
+
+ let containerTypes = InstagramMediaType.IMAGE
+ if (postCategory === PostCategory.STORY) {
+ containerTypes = InstagramMediaType.STORIES
+ }
+ else if (postCategory === PostCategory.REELS) {
+ containerTypes = InstagramMediaType.REELS
+ }
+
+ const isCarousel = postCategory === PostCategory.POST && mediasStatus.medias.length > 1
+ if (isCarousel) {
+ containerTypes = InstagramMediaType.CAROUSEL
+ const containerIdList = mediasStatus.medias.map(media => media.taskId)
+ const createContainerReq: CreateMediaContainerRequest = {
+ media_type: containerTypes,
+ children: containerIdList,
+ caption: this.generatePostMessage(task) || task.title || '',
+ }
+ const postContainer = await this.instagramService.createMediaContainer(
+ task.accountId,
+ createContainerReq,
+ )
+ const queueId = uuidv4().toString()
+ task.queueId = queueId
+ await this.publishTaskModel.updateOne({ _id: task.id }, { queueId }).exec()
+ await this.savePostMedia(task, 'instagram', PostCategory.POST, PostSubCategory.PHOTO, postContainer.id)
+ await this.publishPostMediaTask(task.id, task.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+ const containerId = mediasStatus.medias[0].taskId
+ this.logger.log(`Container ID for task ID ${task.id}: ${containerId}`)
+ const publishRes = await this.instagramService.publishMediaContainer(
+ task.accountId,
+ containerId,
+ )
+ this.logger.log(`publish: Media container published for task ID: ${task.id}, response: ${JSON.stringify(publishRes)}`)
+ const permalink = await this.getPostPermalink(task.accountId, publishRes.id)
+ return {
+ postId: publishRes.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const postCategory = publishTask.option?.instagram?.content_category
+ switch (postCategory) {
+ case 'post':
+ return await this.publishPost(publishTask)
+ case 'reel':
+ return await this.publishReel(publishTask)
+ case 'story':
+ if (publishTask.videoUrl) {
+ return await this.publishVideoStory(publishTask)
+ }
+ else {
+ return await this.publishPhotoStory(publishTask)
+ }
+ default:
+ throw new UnrecoverableError('Invalid or missing content category for Instagram publish task')
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/kwai.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/kwai.service.ts
new file mode 100644
index 00000000..9440960f
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/kwai.service.ts
@@ -0,0 +1,120 @@
+/*
+ * @Author: nevin
+ * @Date: 2025-02-15 20:59:55
+ * @LastEditTime: 2025-04-27 17:58:21
+ * @LastEditors: nevin
+ * @Description: b站
+ */
+import { Injectable, Logger } from '@nestjs/common'
+import { chunkedDownloadFile, fileUrlToBase64, getRemoteFileSize } from '../../../common'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { KwaiService } from '../../platforms/kwai/kwai.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class kwaiPubService extends PublishService {
+ private readonly logger: Logger = new Logger(kwaiPubService.name)
+ constructor(
+ private readonly kwaiService: KwaiService,
+ ) {
+ super()
+ }
+
+ private getCaption(publishiTask: PublishTask) {
+ const { desc, topics } = publishiTask
+ let caption = ''
+
+ if (desc) {
+ caption += `${desc} `
+ }
+
+ if (topics && topics.length !== 0) {
+ for (const topic of topics) {
+ caption += `#${topic} `
+ }
+ }
+
+ return caption.trim()
+ }
+
+ async uploadVideo(publishTask: PublishTask): Promise<string> {
+ const { accountId, videoUrl } = publishTask
+ const startUploadInfo = await this.kwaiService.initVideoUpload(accountId)
+ if (startUploadInfo.result !== 1) {
+ throw PublishingException.nonRetryable('init kwai video upload failed')
+ }
+
+ const contentLength = await getRemoteFileSize(videoUrl)
+ if (!contentLength) {
+ throw PublishingException.nonRetryable('get video meta failed')
+ }
+ let chunkSize = 5 * 1024 * 1024 // 5MB
+ if (contentLength < chunkSize) {
+ chunkSize = contentLength
+ }
+
+ const totalParts = Math.ceil(contentLength / chunkSize)
+ for (let seq = 0; seq < totalParts; seq++) {
+ const start = seq * chunkSize
+ const end = Math.min(start + chunkSize - 1, contentLength - 1)
+ const range: [number, number] = [start, end]
+ const videoBlob = await chunkedDownloadFile(videoUrl, range)
+ if (!videoBlob) {
+ throw new Error('download video chunk failed')
+ }
+
+ const uploadResult = await this.kwaiService.chunkedUploadVideo(
+ startUploadInfo.upload_token,
+ seq,
+ startUploadInfo.endpoint,
+ videoBlob,
+ )
+ this.logger.log(`chunked upload complete: ${JSON.stringify(uploadResult)}`)
+ }
+
+ const finalizeUploadRes = await this.kwaiService.finalizeVideoUpload(
+ startUploadInfo.upload_token,
+ totalParts,
+ startUploadInfo.endpoint,
+ )
+ if (finalizeUploadRes.result !== 1) {
+ throw PublishingException.nonRetryable('finalize kwai video upload failed')
+ }
+
+ this.logger.log('Video upload complete, proceed to publish')
+ return startUploadInfo.upload_token
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, coverUrl, videoUrl } = publishTask
+
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('videoUrl is required for kwai publish')
+ }
+
+ if (!coverUrl) {
+ throw PublishingException.nonRetryable('coverUrl is required for kwai publish')
+ }
+ const uploadToken = await this.uploadVideo(publishTask)
+ const coverBase64 = await fileUrlToBase64(coverUrl)
+ const buffer = Buffer.from(coverBase64, 'base64')
+ const coverBlob = new Blob([buffer], { type: 'image/jpeg' })
+
+ const result = await this.kwaiService.publishVideo(
+ accountId,
+ this.getCaption(publishTask),
+ coverBlob,
+ uploadToken,
+ )
+ return {
+ postId: result.video_info.photo_id,
+ permalink: `https://www.kuaishou.com/short-video/${result.video_info.photo_id}`,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/linkedin.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/linkedin.service.ts
similarity index 60%
rename from project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/linkedin.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/providers/linkedin.service.ts
index a8295c00..9bfa5fc8 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/plat/meta/linkedin.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/linkedin.service.ts
@@ -1,10 +1,10 @@
import { Injectable, Logger } from '@nestjs/common'
-import { LinkedinService } from '../../../../core/plat/meta/linkedin.service'
+import { LinkedinService } from '../../../core/platforms/meta/linkedin.service'
import {
PublishStatus,
PublishTask,
-} from '../../../../libs/database/schema/publishTask.schema'
+} from '../../../libs/database/schema/publishTask.schema'
import {
LinkedinShareCategory,
LinkedInShareRequest,
@@ -12,14 +12,13 @@ import {
ShareMedia,
ShareMediaCategory,
UploadRecipe,
-} from '../../../../libs/linkedin/linkedin.interface'
-import { DoPubRes } from '../../common'
-import { PublishBase } from '../publish.base'
+} from '../../../libs/linkedin/linkedin.interface'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
@Injectable()
-export class LinkedinPublishService extends PublishBase {
- override queueName: string = 'linkedin'
-
+export class LinkedinPublishService extends PublishService {
private readonly logger = new Logger(LinkedinPublishService.name, {
timestamp: true,
})
@@ -30,28 +29,6 @@ export class LinkedinPublishService extends PublishBase {
super()
}
- // TODO: 校验账户授权状态
- async checkAuth(accountId: string): Promise<{
- status: 0 | 1
- timeout?: number // 秒
- }> {
- this.logger.log(`checkAuth: ${accountId}`)
- return {
- status: 1,
- timeout: 10000,
- }
- }
-
- private generatePostMessage(publishTask: PublishTask): string {
- if (!publishTask) {
- return ''
- }
- if (publishTask.topics && publishTask.topics.length > 0) {
- return `${publishTask.desc || ''} #${publishTask.topics.join(' #')}`
- }
- return publishTask.desc || ''
- }
-
private determinePostCategory(
publishTask: PublishTask,
): LinkedinShareCategory {
@@ -65,7 +42,7 @@ export class LinkedinPublishService extends PublishBase {
return LinkedinShareCategory.TEXT
}
- private async publishTextPost(publishTask: PublishTask): Promise<string> {
+ private async publishTextPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
const createShareReq: LinkedInShareRequest = {
author: this.linkedinService.generateURN(publishTask.uid),
lifecycleState: 'PUBLISHED',
@@ -81,13 +58,18 @@ export class LinkedinPublishService extends PublishBase {
},
}
this.logger.log(`Create share request: ${JSON.stringify(createShareReq)}`)
- return await this.linkedinService.publish(
+ const postId = await this.linkedinService.publish(
publishTask.accountId,
createShareReq,
)
+ return {
+ postId,
+ permalink: `https://www.linkedin.com/feed/update/${postId}`,
+ status: PublishStatus.PUBLISHED,
+ }
}
- private async publishImagePost(publishTask: PublishTask): Promise<string> {
+ private async publishImagePost(publishTask: PublishTask): Promise<PublishingTaskResult> {
if (!publishTask.imgUrlList || publishTask.imgUrlList.length < 1) {
throw new Error('imgUrlList is empty')
}
@@ -99,7 +81,7 @@ export class LinkedinPublishService extends PublishBase {
UploadRecipe.IMAGE,
)
if (!resourceId) {
- throw new Error(`upload image failed: ${imgUrl}`)
+ throw PublishingException.nonRetryable(`upload image failed: ${imgUrl}`)
}
const media: ShareMedia = {
status: 'READY',
@@ -124,24 +106,28 @@ export class LinkedinPublishService extends PublishBase {
MemberNetworkVisibility.PUBLIC,
},
}
- return await this.linkedinService.publish(
+ const postId = await this.linkedinService.publish(
publishTask.accountId,
createShareReq,
)
+ return {
+ postId,
+ permalink: `https://www.linkedin.com/feed/update/${postId}`,
+ status: PublishStatus.PUBLISHED,
+ }
}
- private async publishVideoPost(publishTask: PublishTask): Promise<string> {
+ private async publishVideoPost(publishTask: PublishTask): Promise<
+ PublishingTaskResult
+ > {
if (!publishTask.videoUrl) {
- throw new Error('视频 URL 不能为空')
+ throw PublishingException.nonRetryable('videoUrl is empty')
}
const resourceId = await this.linkedinService.uploadMedia(
publishTask.accountId,
publishTask.videoUrl,
UploadRecipe.VIDEO,
)
- if (!resourceId) {
- throw new Error(`upload video failed: ${publishTask.videoUrl}`)
- }
const createShareReq: LinkedInShareRequest = {
author: this.linkedinService.generateURN(publishTask.uid),
lifecycleState: 'PUBLISHED',
@@ -164,45 +150,28 @@ export class LinkedinPublishService extends PublishBase {
MemberNetworkVisibility.PUBLIC,
},
}
- return await this.linkedinService.publish(
+ const postId = await this.linkedinService.publish(
publishTask.accountId,
createShareReq,
)
+ return {
+ postId,
+ permalink: `https://www.linkedin.com/feed/update/${postId}`,
+ status: PublishStatus.PUBLISHED,
+ }
}
- async doPub(publishTask: PublishTask): Promise<DoPubRes> {
- const res: DoPubRes = {
- status: -1,
- message: '任务不存在',
- }
- try {
- const category = this.determinePostCategory(publishTask)
- let resourceId: string | undefined
- if (category === LinkedinShareCategory.TEXT) {
- resourceId = await this.publishTextPost(publishTask)
- }
- if (category === LinkedinShareCategory.IMAGE) {
- resourceId = await this.publishImagePost(publishTask)
- }
- if (category === LinkedinShareCategory.VIDEO) {
- resourceId = await this.publishVideoPost(publishTask)
- }
- if (resourceId) {
- await this.completePublishTask(publishTask, resourceId, {
- workLink: `https://www.linkedin.com/feed/update/${resourceId}`,
- })
- res.status = PublishStatus.PUBLISHED
- res.message = '发布成功'
- return res
- }
- res.status = PublishStatus.FAILED
- res.message = 'failed to get resourceId'
- return res
- }
- catch (error) {
- this.logger.error(`发布任务失败: ${error.message}`, error.stack)
- res.message = `发布任务失败: ${error.message}`
- return res
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const category = this.determinePostCategory(publishTask)
+ switch (category) {
+ case LinkedinShareCategory.TEXT:
+ return await this.publishTextPost(publishTask)
+ case LinkedinShareCategory.IMAGE:
+ return await this.publishImagePost(publishTask)
+ case LinkedinShareCategory.VIDEO:
+ return await this.publishVideoPost(publishTask)
+ default:
+ throw PublishingException.nonRetryable('Unsupported post category')
}
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/pinterest.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/pinterest.service.ts
new file mode 100644
index 00000000..e10842c1
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/pinterest.service.ts
@@ -0,0 +1,72 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { PublishStatus, PublishTask } from '../../../libs/database/schema/publishTask.schema'
+import { CreatePinBody, SourceType } from '../../../libs/pinterest/common'
+import { PinterestService } from '../../platforms/pinterest/pinterest.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class PinterestPubService extends PublishService {
+ private readonly logger = new Logger(PinterestPubService.name)
+
+ constructor(
+ readonly pinterestService: PinterestService,
+ ) {
+ super()
+ }
+
+ async publishImagePost(boardId: string, publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const data: CreatePinBody = {
+ accountId: publishTask.accountId,
+ board_id: boardId,
+ description: publishTask.desc,
+ title: publishTask.title,
+ media_source:
+ {
+ source_type: SourceType.image_url,
+ url: publishTask.imgUrlList?.[0],
+ },
+ }
+ const resp = await this.pinterestService.createPin(data)
+ return {
+ postId: resp.id,
+ permalink: `https://www.pinterest.com/pin/${resp.id}/`,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async publishVideoPost(boardId: string, publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const result = await this.pinterestService.uploadVideo(publishTask.videoUrl, publishTask.accountId)
+ const body: CreatePinBody
+ = {
+ accountId: publishTask.accountId,
+ board_id: boardId,
+ description: publishTask.desc,
+ title: publishTask.title,
+ media_source:
+ {
+ source_type: SourceType.video_id,
+ media_id: result.data.media_id,
+ cover_image_url: publishTask.coverUrl,
+ },
+ }
+ const resp = await this.pinterestService.createPin(body)
+ return {
+ postId: resp.id,
+ permalink: `https://www.pinterest.com/pin/${resp.id}/`,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const boardId = publishTask.option?.pinterest?.boardId
+ if (!boardId) {
+ throw PublishingException.nonRetryable('Pinterest boardId is required')
+ }
+ if (publishTask.videoUrl) {
+ return this.publishVideoPost(boardId, publishTask)
+ }
+ return this.publishImagePost(boardId, publishTask)
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/threads.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/threads.service.ts
new file mode 100644
index 00000000..20deb6ba
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/threads.service.ts
@@ -0,0 +1,220 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { v4 as uuidv4 } from 'uuid'
+import { ThreadsService } from '../../../core/platforms/meta/threads.service'
+import { PostCategory, PostSubCategory } from '../../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { ThreadsMediaType } from '../../../libs/threads/threads.enum'
+import { ThreadsContainerRequest } from '../../../libs/threads/threads.interfaces'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class ThreadsPublishService extends PublishService {
+ private readonly logger = new Logger(ThreadsPublishService.name, {
+ timestamp: true,
+ })
+
+ protected override readonly ProcessMediaFailed = 'FAILED'
+ protected override readonly ProcessMediaInProgress = 'IN_PROGRESS'
+ protected override readonly ProcessMediaCompleted = 'FINISHED'
+
+ constructor(
+ readonly threadsService: ThreadsService,
+ ) {
+ super()
+ }
+
+ private async getPostPermalink(accountId: string, postId: string): Promise<string> {
+ try {
+ const objectInfo = await this.threadsService.getObjectInfo(
+ accountId,
+ postId,
+ '',
+ 'permalink',
+ )
+ return objectInfo.permalink ?? ''
+ }
+ catch (error) {
+ this.logger.error(`Failed to get threads post permalink, accountId: ${accountId}, postId: ${postId}, error: ${error}`)
+ return ''
+ }
+ }
+
+ protected override generatePostMessage(publishTask: PublishTask): string {
+ if (!publishTask) {
+ return ''
+ }
+ if (publishTask.topics && publishTask.topics.length > 1) {
+ const topics = publishTask.topics.slice(1)
+ if (publishTask.desc) {
+ return `${publishTask.desc} #${topics.join(' #')}`
+ }
+ return `#${topics.join(' #')}`
+ }
+ return publishTask.desc || ''
+ }
+
+ async determinePostType(publishTask: PublishTask): Promise<string> {
+ const { imgUrlList, videoUrl } = publishTask
+ if (imgUrlList && imgUrlList.length > 0) {
+ return 'image'
+ }
+ if (videoUrl) {
+ return 'video'
+ }
+ return 'plainText'
+ }
+
+ async publishPlainTextPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const locationId = publishTask.option?.threads?.location_id
+ const createContainerReq: ThreadsContainerRequest = {
+ media_type: 'TEXT',
+ text: this.generatePostMessage(publishTask),
+ }
+ if (publishTask.topics && publishTask.topics.length > 0) {
+ createContainerReq.topic_tag = publishTask.topics[0]
+ }
+ if (locationId) {
+ createContainerReq.location_id = locationId
+ }
+ const container = await this.threadsService.createItemContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.processUploadMedia(publishTask, 'threads', PostCategory.POST, PostSubCategory.PLAINTEXT, container.id)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishImagePost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, imgUrlList } = publishTask
+ const locationId = publishTask.option?.threads?.location_id
+ const isCarouselItem = imgUrlList.length > 1
+ for (const imgUrl of imgUrlList) {
+ const createContainerReq: ThreadsContainerRequest = {
+ media_type: 'IMAGE',
+ image_url: imgUrl,
+ text: publishTask.desc || '',
+ }
+ if (locationId) {
+ createContainerReq.location_id
+ = publishTask.option.threads.location_id
+ }
+ if (publishTask.topics && publishTask.topics.length > 0) {
+ createContainerReq.topic_tag = publishTask.topics[0]
+ }
+ if (isCarouselItem) {
+ createContainerReq.is_carousel_item = true
+ }
+ const container = await this.threadsService.createItemContainer(
+ accountId,
+ createContainerReq,
+ )
+ await this.savePostMedia(publishTask, 'threads', PostCategory.POST, PostSubCategory.PHOTO, container.id)
+ }
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishVideoPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const locationId = publishTask.option?.threads?.location_id
+ const createContainerReq: ThreadsContainerRequest = {
+ media_type: 'VIDEO',
+ video_url: publishTask.videoUrl,
+ text: this.generatePostMessage(publishTask),
+ }
+ if (publishTask.topics && publishTask.topics.length > 0) {
+ createContainerReq.topic_tag = publishTask.topics[0]
+ }
+ if (locationId) {
+ createContainerReq.location_id = locationId
+ }
+ const container = await this.threadsService.createItemContainer(
+ publishTask.accountId,
+ createContainerReq,
+ )
+ await this.processUploadMedia(publishTask, 'threads', PostCategory.POST, PostSubCategory.VIDEO, container.id)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const postType = await this.determinePostType(publishTask)
+ switch (postType) {
+ case 'image':
+ return this.publishImagePost(publishTask)
+ case 'video':
+ return this.publishVideoPost(publishTask)
+ case 'plainText':
+ return this.publishPlainTextPost(publishTask)
+ default:
+ throw PublishingException.nonRetryable('Unsupported post type for Threads publishing')
+ }
+ }
+
+ override async getMediaProcessingStatus(accountId: string, mediaId: string): Promise<string | void> {
+ const mediaStatusInfo = await this.threadsService.getObjectInfo(accountId, mediaId, '')
+ return mediaStatusInfo.status
+ }
+
+ override async finalizePublish(task: PublishTask): Promise<PublishingTaskResult> {
+ const locationId = task.option?.threads?.location_id
+ const mediasStatus = await this.getMediasProcessingStatus(task)
+ if (mediasStatus.hasFailed) {
+ throw PublishingException.nonRetryable(`Media processing failed for task ID: ${task.id}`)
+ }
+ if (!mediasStatus.isCompleted) {
+ throw PublishingException.retryable(`Media files are still processing. Please wait for media processing to complete.`)
+ }
+ this.logger.log(`All media files processed for task ID: ${task.id}`)
+ let containerTypes = ThreadsMediaType.VIDEO
+
+ if (mediasStatus.medias.length > 1) {
+ containerTypes = ThreadsMediaType.CAROUSEL
+ const containerIdList = mediasStatus.medias.map(media => media.taskId)
+ const createContainerReq: ThreadsContainerRequest = {
+ media_type: containerTypes,
+ children: containerIdList,
+ text: this.generatePostMessage(task),
+ }
+ if (task.topics && task.topics.length > 0) {
+ createContainerReq.topic_tag = task.topics[0]
+ }
+ if (locationId) {
+ createContainerReq.location_id = locationId
+ }
+ const postContainer = await this.threadsService.createItemContainer(
+ task.accountId,
+ createContainerReq,
+ )
+ const queueId = uuidv4().toString()
+ task.queueId = queueId
+ await this.publishTaskModel.updateOne({ _id: task.id }, { queueId }).exec()
+ await this.savePostMedia(task, 'threads', PostCategory.POST, PostSubCategory.PHOTO, postContainer.id)
+ await this.publishPostMediaTask(task.id, task.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+ const containerId = mediasStatus.medias[0].taskId
+ this.logger.log(`Container ID for task ID ${task.id}: ${containerId}`)
+ const publishRes = await this.threadsService.publishPost(
+ task.accountId,
+ containerId,
+ )
+ const permalink = await this.getPostPermalink(task.accountId, publishRes.id)
+ return {
+ postId: publishRes.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/tiktok.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/tiktok.service.ts
new file mode 100644
index 00000000..a048d4ee
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/tiktok.service.ts
@@ -0,0 +1,184 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { chunkedDownloadFile, getFileTypeFromUrl, getRemoteFileSize } from '../../../common'
+import { config } from '../../../config'
+import { PublishStatus, PublishTask } from '../../../libs/database/schema/publishTask.schema'
+import { TiktokPrivacyLevel, TiktokSourceType } from '../../../libs/tiktok/tiktok.enum'
+import { PostInfoDto, VideoFileUploadSourceDto, VideoPullUrlSourceDto } from '../../platforms/tiktok/dto/tiktok.dto'
+import { TiktokService } from '../../platforms/tiktok/tiktok.service'
+import { TiktokWebhookDto } from '../dto/tiktok.webhook.dto'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class TiktokPubService extends PublishService {
+ private readonly logger = new Logger(TiktokPubService.name, {
+ timestamp: true,
+ })
+
+ constructor(
+ private readonly tiktokService: TiktokService,
+ ) {
+ super()
+ }
+
+ private isDevEnv(): boolean {
+ return config.tiktok.redirectUri.includes('dev')
+ }
+
+ async publishVideoViaUpload(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, videoUrl } = publishTask
+ if (!videoUrl) {
+ throw new Error('video url is required')
+ }
+ const fileName = getFileTypeFromUrl(videoUrl, true)
+ const ext = fileName.split('.').pop()?.toLowerCase()
+ const mimeType = ext === 'mp4' ? 'video/mp4' : `video/${ext}`
+
+ const contentLength = await getRemoteFileSize(videoUrl)
+ if (!contentLength) {
+ throw new Error('get video meta failed')
+ }
+ let chunkSize = 5 * 1024 * 1024 // 6MB
+ const totalChunkCount = Math.floor(contentLength / chunkSize) || 1
+ if (contentLength < chunkSize || totalChunkCount === 1) {
+ chunkSize = contentLength
+ }
+ const privacy_level = publishTask.option?.tiktok?.privacy_level ? publishTask.option.tiktok.privacy_level as TiktokPrivacyLevel : TiktokPrivacyLevel.PUBLIC
+ const postInfo: PostInfoDto = {
+ title: publishTask.title || publishTask.desc || '',
+ privacy_level,
+ brand_content_toggle: publishTask.option?.tiktok?.brand_content_toggle || false,
+ brand_organic_toggle: publishTask.option?.tiktok?.brand_organic_toggle || false,
+ disable_comment: publishTask.option?.tiktok?.disable_comment || false,
+ disable_duet: publishTask.option?.tiktok?.disable_duet || false,
+ disable_stitch: publishTask.option?.tiktok?.disable_stitch || false,
+ }
+
+ const sourceInfo: VideoFileUploadSourceDto = {
+ source: TiktokSourceType.FILE_UPLOAD,
+ video_size: contentLength,
+ chunk_size: chunkSize,
+ total_chunk_count: totalChunkCount,
+ }
+
+ this.logger.log(`init video upload: accountId: ${accountId}, postInfo: ${JSON.stringify(postInfo)}, sourceInfo: ${JSON.stringify(sourceInfo)}`)
+ const initUploadRes = await this.tiktokService.initVideoPublish(
+ accountId,
+ postInfo,
+ sourceInfo,
+ )
+ const chunks: [number, number][] = []
+ let start = 0
+ for (let partNumber = 0; partNumber < totalChunkCount - 1; partNumber++) {
+ const end = start + chunkSize - 1
+ chunks.push([start, end])
+ start += chunkSize
+ }
+ chunks.push([start, contentLength - 1])
+
+ for (const chunk of chunks) {
+ const videoBlob = await chunkedDownloadFile(videoUrl, chunk)
+ if (!videoBlob) {
+ throw PublishingException.nonRetryable('download raw video chunk failed')
+ }
+
+ await this.tiktokService.chunkedUploadVideoFile(
+ initUploadRes.upload_url,
+ videoBlob,
+ chunk,
+ contentLength,
+ mimeType,
+ )
+ }
+ return {
+ postId: initUploadRes.publish_id,
+ permalink: `https://www.tiktok.com/@${publishTask.uid}/video/${initUploadRes.publish_id}`,
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishVideoViaURL(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, videoUrl } = publishTask
+ if (!videoUrl) {
+ throw new Error('video url is required')
+ }
+ const privacyLevel = this.isDevEnv() ? TiktokPrivacyLevel.SELF_ONLY : TiktokPrivacyLevel.PUBLIC
+ const postInfo: PostInfoDto = {
+ title: this.generatePostMessage(publishTask),
+ privacy_level: privacyLevel,
+ brand_content_toggle: false,
+ brand_organic_toggle: false,
+ }
+
+ const sourceInfo: VideoPullUrlSourceDto = {
+ source: TiktokSourceType.PULL_FROM_URL,
+ video_url: videoUrl,
+ }
+
+ const publishRes = await this.tiktokService.initVideoPublish(
+ accountId,
+ postInfo,
+ sourceInfo,
+ )
+ this.logger.log(`视频发布结果: ${JSON.stringify(publishRes)}`)
+ if (!publishRes || !publishRes.publish_id) {
+ throw new Error('publish video failed')
+ }
+ return {
+ postId: publishRes.publish_id,
+ permalink: `https://www.tiktok.com/@${publishTask.uid}/video/${publishRes.publish_id}`,
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ return await this.publishVideoViaUpload(publishTask)
+ }
+
+ async handleTiktokPostWebhook(dto: TiktokWebhookDto): Promise<void> {
+ try {
+ const content = JSON.parse(dto.content)
+ if (!dto.event.startsWith('post.publish')) {
+ this.logger.error(`未知 TikTok 事件类型: ${dto.event}`)
+ return
+ }
+ const publishId = content?.publish_id
+ if (!publishId) {
+ this.logger.error(`invalid publish_id in webhook: ${JSON.stringify(content)}`)
+ return
+ }
+ const publishRecord = await this.publishTaskModel.findOne({ dataId: publishId, uid: dto.user_openid }).exec()
+ if (!publishRecord) {
+ this.logger.error(`未找到发布记录: ${publishId}`)
+ return
+ }
+ switch (dto.event) {
+ case 'post.publish.complete':
+ this.logger.log(`发布成功: ${JSON.stringify(content)}`)
+ publishRecord.status = PublishStatus.PUBLISHED
+ await this.publishRecordService.updatePublishRecordStatus(publishRecord.id, publishRecord.status, publishRecord.errorMsg)
+ await this.publishTaskModel.updateOne({ _id: publishRecord.id }, { status: PublishStatus.PUBLISHED }).exec()
+ break
+ case 'post.publish.inbox_delivered':
+ this.logger.log(`发布已送达: ${JSON.stringify(content)}`)
+ publishRecord.status = PublishStatus.PUBLISHED
+ await this.publishRecordService.updatePublishRecordStatus(publishRecord.id, publishRecord.status, publishRecord.errorMsg)
+ await this.publishTaskModel.updateOne({ _id: publishRecord.id }, { status: PublishStatus.PUBLISHED }).exec()
+ break
+ case 'post.publish.publicly_available':
+ publishRecord.status = PublishStatus.PUBLISHED
+ publishRecord.dataId = content.post_id || publishRecord.dataId
+ await this.publishRecordService.updatePublishRecordStatus(publishRecord.id, publishRecord.status, publishRecord.errorMsg)
+ await this.publishTaskModel.updateOne({ _id: publishRecord.id }, { status: PublishStatus.PUBLISHED }).exec()
+ break
+ default:
+ this.logger.error(`未知事件类型: ${dto.event}`)
+ break
+ }
+ }
+ catch (error) {
+ this.logger.error(`处理 TikTok webhook 失败: ${error.message}`, error.stack)
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/twitter.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/twitter.service.ts
new file mode 100644
index 00000000..c98a081e
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/twitter.service.ts
@@ -0,0 +1,220 @@
+import { Injectable, Logger } from '@nestjs/common'
+import {
+ chunkedDownloadFile,
+ fileUrlToBlob,
+ getFileTypeFromUrl,
+ getRemoteFileSize,
+} from '../../../common'
+import { TwitterService } from '../../../core/platforms/twitter/twitter.service'
+import {
+ PostCategory,
+ PostMediaStatus,
+ PostSubCategory,
+} from '../../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { XMediaCategory, XMediaType } from '../../../libs/twitter/twitter.enum'
+import {
+ PostMedia,
+ XChunkedMediaUploadRequest,
+ XCreatePostRequest,
+ XMediaUploadInitRequest,
+} from '../../../libs/twitter/twitter.interfaces'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class TwitterPubService extends PublishService {
+ private readonly logger = new Logger(TwitterPubService.name, {
+ timestamp: true,
+ })
+
+ protected override readonly ProcessMediaInProgress: string = 'in_progress'
+ protected override readonly ProcessMediaCompleted: string = 'succeeded'
+
+ constructor(
+ private readonly twitterService: TwitterService,
+ ) {
+ super()
+ }
+
+ private isPlainTextPost(publishTask: PublishTask): boolean {
+ const { imgUrlList, videoUrl } = publishTask
+ return (!imgUrlList || imgUrlList.length === 0) && !videoUrl
+ }
+
+ override async getMediaProcessingStatus(accountId: string, mediaId: string): Promise<string | void> {
+ const mediaStatusInfo = await this.twitterService.getMediaUploadStatus(accountId, mediaId)
+ return mediaStatusInfo.data.processing_info.state
+ }
+
+ async publishPlainTextPost(task: PublishTask): Promise<PublishingTaskResult> {
+ const post: XCreatePostRequest = {
+ text: this.generatePostMessage(task) || '',
+ }
+ const createPostRes = await this.twitterService.createPost(
+ task.accountId,
+ post,
+ )
+ const permalink = `https://x.com/${task.uid}/status/${createPostRes.data.id}`
+ return {
+ postId: createPostRes.data.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async publishImagePost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, imgUrlList } = publishTask
+ if (!imgUrlList || imgUrlList.length === 0) {
+ throw PublishingException.nonRetryable('No images found for image post')
+ }
+ for (const imgUrl of imgUrlList) {
+ const imgBlob = await fileUrlToBlob(imgUrl)
+ if (!imgBlob) {
+ throw PublishingException.nonRetryable(`Download image failed: ${imgUrl}`)
+ }
+ const fileName = getFileTypeFromUrl(imgUrl)
+ const ext = fileName.split('.').pop()?.toLowerCase()
+ const mimeType = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
+ const initUploadReq: XMediaUploadInitRequest = {
+ media_type: mimeType as XMediaType,
+ total_bytes: imgBlob.blob.size,
+ media_category: XMediaCategory.TWEET_IMAGE,
+ shared: false,
+ }
+ const initUploadRes = await this.twitterService.initMediaUpload(
+ accountId,
+ initUploadReq,
+ )
+ const uploadReq: XChunkedMediaUploadRequest = {
+ media: await imgBlob.blob,
+ media_id: initUploadRes.data.id,
+ segment_index: 0,
+ }
+
+ await this.twitterService.chunkedMediaUploadRequest(
+ accountId,
+ uploadReq,
+ )
+ await this.twitterService.finalizeMediaUpload(
+ accountId,
+ initUploadRes.data.id,
+ )
+ await this.savePostMedia(publishTask, 'twitter', PostCategory.POST, PostSubCategory.PHOTO, initUploadRes.data.id, PostMediaStatus.FINISHED)
+ }
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async publishVideoPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { accountId, videoUrl } = publishTask
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('No video found for video post')
+ }
+ const fileName = getFileTypeFromUrl(videoUrl, true)
+ const ext = fileName.split('.').pop()?.toLowerCase()
+ const mimeType = ext === 'mp4' ? 'video/mp4' : `video/${ext}`
+
+ const contentLength = await getRemoteFileSize(videoUrl)
+ if (!contentLength) {
+ throw PublishingException.nonRetryable('Get video size failed')
+ }
+ const initUploadReq: XMediaUploadInitRequest = {
+ media_type: mimeType as XMediaType,
+ total_bytes: contentLength,
+ media_category: XMediaCategory.TWEET_VIDEO,
+ shared: false,
+ }
+
+ const initUploadRes = await this.twitterService.initMediaUpload(
+ accountId,
+ initUploadReq,
+ )
+
+ const chunkSize = 4 * 1024 * 1024 // 4MB
+ const totalChunks = Math.ceil(contentLength / chunkSize)
+ for (let sequenceNum = 0; sequenceNum < totalChunks; sequenceNum++) {
+ const start = sequenceNum * chunkSize
+ const end = Math.min(start + chunkSize - 1, contentLength - 1)
+ const range: [number, number] = [start, end]
+ const fileSegment = await chunkedDownloadFile(videoUrl, range)
+ if (!fileSegment) {
+ throw PublishingException.nonRetryable('Download video segment failed')
+ }
+ this.logger.log(
+ `chunked upload, Size: ${fileSegment.length}, Range: ${start}-${end}, Sequence: ${sequenceNum}`,
+ )
+ const uploadReq: XChunkedMediaUploadRequest = {
+ media: new Blob([fileSegment]),
+ media_id: initUploadRes.data.id,
+ segment_index: sequenceNum,
+ }
+ await this.twitterService.chunkedMediaUploadRequest(
+ accountId,
+ uploadReq,
+ )
+ }
+ await this.twitterService.finalizeMediaUpload(
+ accountId,
+ initUploadRes.data.id,
+ )
+ await this.savePostMedia(publishTask, 'twitter', PostCategory.POST, PostSubCategory.VIDEO, initUploadRes.data.id)
+ await this.publishPostMediaTask(publishTask.id, publishTask.queueId)
+ return {
+ status: PublishStatus.PUBLISHING,
+ }
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { imgUrlList, videoUrl } = publishTask
+ if (this.isPlainTextPost(publishTask)) {
+ return this.publishPlainTextPost(publishTask)
+ }
+ if (imgUrlList && imgUrlList.length > 0) {
+ return this.publishImagePost(publishTask)
+ }
+ if (videoUrl) {
+ return this.publishVideoPost(publishTask)
+ }
+ throw PublishingException.nonRetryable('No media found for post')
+ }
+
+ override async finalizePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const mediasStatus = await this.getMediasProcessingStatus(publishTask)
+ if (mediasStatus.hasFailed) {
+ throw PublishingException.nonRetryable(`Media processing failed for task ID: ${publishTask.id}`)
+ }
+ if (!mediasStatus.isCompleted) {
+ throw PublishingException.retryable(`Media files are still processing. Please wait for media processing to complete.`)
+ }
+
+ this.logger.log(`All media files processed for task ID: ${publishTask.id}`)
+ const postMedia: PostMedia = {
+ media_ids: mediasStatus.medias.map(media => media.taskId),
+ }
+ const post: XCreatePostRequest = {
+ text: this.generatePostMessage(publishTask) || '',
+ media: postMedia,
+ }
+ const createPostRes = await this.twitterService.createPost(
+ publishTask.accountId,
+ post,
+ )
+ this.logger.log(
+ `publish: Media container published for task ID: ${publishTask.id}, response: ${JSON.stringify(createPostRes)}`,
+ )
+
+ const permalink = `https://x.com/${publishTask.uid}/status/${createPostRes.data.id}`
+ return {
+ postId: createPostRes.data.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/wx-gzh.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/wx-gzh.service.ts
new file mode 100644
index 00000000..10e11db4
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/wx-gzh.service.ts
@@ -0,0 +1,93 @@
+import { Injectable, Logger } from '@nestjs/common'
+import {
+ PublishStatus,
+ PublishTask,
+ PublishType,
+} from '../../../libs/database/schema/publishTask.schema'
+import { MediaType } from '../../../libs/wx-gzh/common'
+import { WxGzhService } from '../../platforms/wx-plat/wx-gzh.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class WxGzhPubService extends PublishService {
+ logger = new Logger(WxGzhPubService.name)
+
+ constructor(
+ readonly wxGzhService: WxGzhService,
+ ) {
+ super()
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ // 开始任务
+ const { coverUrl, accountId, imgUrlList, title, desc, type, option }
+ = publishTask
+ if (!imgUrlList || imgUrlList.length === 0) {
+ this.logger.error('No images found for image post')
+ throw PublishingException.nonRetryable('No images found for image post')
+ }
+ if (!title) {
+ this.logger.error('Title is required')
+ throw PublishingException.nonRetryable('Title is required')
+ }
+ if (!desc) {
+ this.logger.error('Description is required')
+ throw PublishingException.nonRetryable('Description is required')
+ }
+ if (type !== PublishType.ARTICLE) {
+ this.logger.error('Only article publishing is supported for WeChat Official Account')
+ throw PublishingException.nonRetryable('Only article publishing is supported for WeChat Official Account')
+ }
+
+ const wxGzhImgMaterialIdList: {
+ image_media_id: string
+ }[] = []
+
+ if (coverUrl) {
+ const coverUrlRes = await this.wxGzhService.addMaterial(
+ accountId,
+ MediaType.image,
+ coverUrl,
+ )
+ wxGzhImgMaterialIdList.push({
+ image_media_id: coverUrlRes.media_id,
+ })
+ }
+
+ for (const imgUrl of imgUrlList) {
+ const imgUrlRes = await this.wxGzhService.addMaterial(
+ accountId,
+ MediaType.image,
+ imgUrl,
+ )
+ wxGzhImgMaterialIdList.push({ image_media_id: imgUrlRes.media_id })
+ }
+
+ const draftAddRes = await this.wxGzhService.draftAdd(accountId, {
+ article_type: 'newspic',
+ title,
+ content: desc,
+ image_info: {
+ image_list: wxGzhImgMaterialIdList,
+ },
+ ...option?.wxGzh,
+ })
+
+ const freePublishRes = await this.wxGzhService.freePublish(
+ accountId,
+ draftAddRes.media_id,
+ )
+
+ return {
+ postId: freePublishRes.publish_id,
+ permalink: `https://mp.weixin.qq.com/s/${freePublishRes.publish_id}`,
+ extra: {
+ publish_id: freePublishRes.publish_id,
+ msg_data_id: freePublishRes.msg_data_id,
+ },
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/providers/youtube.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/youtube.service.ts
new file mode 100644
index 00000000..f2100c0a
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/providers/youtube.service.ts
@@ -0,0 +1,81 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { chunkedDownloadFile, getFileSizeFromUrl } from '../../../common'
+import {
+ PublishStatus,
+ PublishTask,
+} from '../../../libs/database/schema/publishTask.schema'
+import { YoutubeService } from '../../platforms/youtube/youtube.service'
+import { PublishingException } from '../publishing.exception'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishService } from './base.service'
+
+@Injectable()
+export class YoutubePubService extends PublishService {
+ private readonly logger = new Logger(YoutubePubService.name)
+
+ constructor(
+ private readonly youtubeService: YoutubeService,
+ ) {
+ super()
+ }
+
+ async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ try {
+ if (!publishTask.videoUrl) {
+ this.logger.error('Video URL is required')
+ throw PublishingException.nonRetryable('Video URL is required')
+ }
+ const contentLength = await getFileSizeFromUrl(publishTask.videoUrl)
+ const videoUpToken = await this.youtubeService.initVideoUpload(
+ publishTask.accountId,
+ publishTask.title || '',
+ publishTask.desc || '',
+ publishTask.topics,
+ publishTask?.option?.youtube?.license || 'youtube',
+ publishTask?.option?.youtube?.categoryId || '22',
+ publishTask?.option?.youtube?.privacyStatus || 'private',
+ publishTask?.option?.youtube?.notifySubscribers || false,
+ publishTask?.option?.youtube?.embeddable || false,
+ publishTask?.option?.youtube?.selfDeclaredMadeForKids || false,
+ contentLength,
+ )
+ if (!videoUpToken) {
+ this.logger.error('error initializing video upload')
+ throw PublishingException.nonRetryable('error initializing video upload')
+ }
+
+ const chunkSize = 1024 * 1024 * 5
+ const chunkCount = Math.ceil(contentLength / chunkSize)
+
+ for (let seq = 1; seq <= chunkCount; seq++) {
+ const start = (seq - 1) * chunkSize
+ const end = Math.min(seq * chunkSize - 1, contentLength - 1)
+ const chunkFile = await chunkedDownloadFile(publishTask.videoUrl, [start, end])
+ await this.youtubeService.uploadVideoPart(
+ publishTask.accountId,
+ chunkFile,
+ videoUpToken,
+ seq,
+ )
+ }
+ const resourceId = await this.youtubeService.videoComplete(
+ publishTask.accountId,
+ videoUpToken,
+ contentLength,
+ )
+ if (!resourceId) {
+ this.logger.error('error completing video upload')
+ throw PublishingException.nonRetryable('error completing video upload')
+ }
+ return {
+ postId: resourceId,
+ permalink: `https://www.youtube.com/watch?v=${resourceId}`,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+ catch (error) {
+ this.logger.error('error publishing video', error)
+ throw PublishingException.nonRetryable('error publishing video', error)
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publish/publishTask.controller.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
similarity index 54%
rename from project/backend/apps/aitoearn-channel/src/core/publish/publishTask.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
index 547e29bf..e70d14dc 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publish/publishTask.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
@@ -1,14 +1,6 @@
-/*
- * @Author: nevin
- * @Date: 2024-06-17 19:19:20
- * @LastEditTime: 2024-12-23 12:45:22
- * @LastEditors: nevin
- * @Description: 发布
- */
import { Body, Controller, Logger, Post } from '@nestjs/common'
import { AppException, ResponseCode } from '@yikart/common'
import { PublishStatus } from '../../libs/database/schema/publishTask.schema'
-import { AccountService } from '../account/account.service'
import {
CreatePublishDto,
DeletePublishTaskDto,
@@ -17,29 +9,24 @@ import {
UpPublishTaskTimeDto,
} from './dto/publish.dto'
import { TiktokWebhookDto, TiktokWebhookSchema } from './dto/tiktok.webhook.dto'
-import { PublishTaskService } from './publishTask.service'
+import { PublishingService } from './publishing.service'
@Controller()
-export class PublishTaskController {
- private readonly logger = new Logger(PublishTaskController.name)
+export class PublishingController {
+ private readonly logger = new Logger(PublishingController.name)
constructor(
- private readonly publishTaskService: PublishTaskService,
- private readonly accountService: AccountService,
+ private readonly publishingService: PublishingService,
) {}
- // 创建发布任务
- // @NatsMessagePattern('plat.publish.create')
@Post('plat/publish/create')
- async createPub(@Body() data: CreatePublishDto) {
- return await this.publishTaskService.createPublishingTask(data)
+ async createPublishingTask(@Body() data: CreatePublishDto) {
+ return await this.publishingService.createPublishingTask(data)
}
- // 更新任务时间
- // @NatsMessagePattern('publish.task.changeTime')
@Post('plat/publish/changeTime')
async changeTaskTime(@Body() data: UpPublishTaskTimeDto) {
data.publishTime = new Date(data.publishTime)
- const res = await this.publishTaskService.updatePublishTaskTime(
+ const res = await this.publishingService.updatePublishTaskTime(
data.id,
data.publishTime,
data.userId,
@@ -47,36 +34,36 @@ export class PublishTaskController {
return res
}
- // 删除任务
- // @NatsMessagePattern('publish.task.delete')
@Post('publish/task/delete')
async deletePublishTask(@Body() data: DeletePublishTaskDto) {
- return await this.publishTaskService.deletePublishTaskById(
+ return await this.publishingService.deletePublishTaskById(
data.id,
data.userId,
)
}
- // 立即发布任务
- // @NatsMessagePattern('publish.task.run')
@Post('publish/task/run')
async nowPubTask(@Body() data: NowPubTaskDto) {
- const info = await this.publishTaskService.getPublishTaskInfo(data.id)
+ const info = await this.publishingService.getPublishTaskInfo(data.id)
if (!info)
throw new AppException(ResponseCode.PublishTaskNotFound)
-
- await this.publishTaskService.pushPubTask(info)
+ if (info.status === PublishStatus.PUBLISHING) {
+ throw new AppException(ResponseCode.PublishTaskAlreadyPublishing)
+ }
+ if (info.status === PublishStatus.PUBLISHED) {
+ throw new AppException(ResponseCode.PublishTaskAlreadyCompleted)
+ }
+ await this.publishingService.enqueuePublishingTask(info)
return PublishStatus.PUBLISHING
}
- // @NatsMessagePattern('publish.tiktok.post.webhook')
@Post('publish/tiktok/post/webhook')
async handleTiktokWebhook(@Body() data: any) {
this.logger.log(`Received TikTok webhook: ${JSON.stringify(data)}`)
try {
const dto: TiktokWebhookDto = TiktokWebhookSchema.parse(data)
- await this.publishTaskService.handleTiktokPostWebhook(dto)
+ await this.publishingService.handleTiktokPostWebhook(dto)
}
catch (error) {
this.logger.error(`Error handling TikTok webhook: ${error.message}`, error.stack)
@@ -85,30 +72,33 @@ export class PublishTaskController {
return { status: 'success', message: 'Webhook processed' }
}
- // @NatsMessagePattern('channel.publishTask.list')
@Post('channel/publishTask/list')
async getPublishTaskList(@Body() data: PublishRecordListFilterDto) {
- const res = await this.publishTaskService.getPublishTasks(data)
+ const res = await this.publishingService.getPublishTasks(data)
return res
}
@Post('channel/status/queued/tasks')
async getQueuedPublishTaskList(@Body() data: PublishRecordListFilterDto) {
- const res = await this.publishTaskService.getQueuedPublishTasks(data)
+ const res = await this.publishingService.getQueuedPublishTasks(data)
+ return res
+ }
+
+ @Post('channel/status/published/tasks')
+ async getPublishedPublishTaskList(@Body() data: PublishRecordListFilterDto) {
+ const res = await this.publishingService.getPublishedPublishTasks(data)
return res
}
- // @NatsMessagePattern('channel.publishTask.detail')
@Post('channel/publishTask/detail')
async getPublishingTaskDetail(@Body() data: { flowId: string, userId: string }) {
- const res = await this.publishTaskService.getPublishTaskInfoWithFlowId(data.flowId, data.userId)
+ const res = await this.publishingService.getPublishTaskInfoWithFlowId(data.flowId, data.userId)
return res
}
- // @NatsMessagePattern('channel.publishing.task.detail')
@Post('channel/publishing/task/detail')
async getPublishTaskInfoWithUserId(@Body() data: { taskId: string, userId: string }) {
- const res = await this.publishTaskService.getPublishTaskInfoWithUserId(data.taskId, data.userId)
+ const res = await this.publishingService.getPublishTaskInfoWithUserId(data.taskId, data.userId)
return res
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.exception.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.exception.ts
new file mode 100644
index 00000000..81501bb9
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.exception.ts
@@ -0,0 +1,39 @@
+/**
+ * PublishingException
+ * - message: user-facing error summary (safe to display to end users)
+ * - details: developer-facing diagnostics (stack, cause, context, etc.)
+ */
+export class PublishingException extends Error {
+ /** Whether the operation can be retried safely */
+ readonly retryable: boolean
+ /** Developer-facing diagnostics; DO NOT expose directly to clients */
+ readonly details?: Record<string, unknown>
+
+ constructor(message: string, retryable: boolean, details?: Record<string, unknown>) {
+ super(message)
+ this.name = 'PublishingException'
+ this.retryable = retryable
+ this.details = details
+ }
+
+ static retryable(message: string, details?: Record<string, unknown>): PublishingException {
+ return new PublishingException(message, true, details)
+ }
+
+ static nonRetryable(message: string, details?: Record<string, unknown>): PublishingException {
+ return new PublishingException(message, false, details)
+ }
+
+ toJSON() {
+ return {
+ name: this.name,
+ message: this.message,
+ retryable: this.retryable,
+ details: this.details,
+ }
+ }
+}
+
+export function isPublishingException(e: unknown): e is PublishingException {
+ return e instanceof PublishingException
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.interface.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.interface.ts
new file mode 100644
index 00000000..00ebb62d
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.interface.ts
@@ -0,0 +1,22 @@
+import { PostCategory, PostMediaStatus } from '../../libs/database/schema/postMediaContainer.schema'
+import { PublishStatus } from '../../libs/database/schema/publishTask.schema'
+
+export interface PublishingTaskResult {
+ status: PublishStatus
+ postId?: string
+ permalink?: string
+ extra?: Record<string, any>
+}
+
+export interface MediaProcessingStatus {
+ id: string
+ taskId: string
+ category: PostCategory
+ status: PostMediaStatus
+}
+
+export interface MediaProcessingStatusResult {
+ medias: MediaProcessingStatus[]
+ isCompleted: boolean
+ hasFailed: boolean
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.module.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.module.ts
new file mode 100644
index 00000000..30b59056
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.module.ts
@@ -0,0 +1,115 @@
+import { forwardRef, Module } from '@nestjs/common'
+import { MongooseModule } from '@nestjs/mongoose'
+import { AccountType } from '@yikart/common'
+import { Account, AccountSchema } from '../../libs/database/schema/account.schema'
+import {
+ PostMediaContainer,
+ PostMediaContainerSchema,
+} from '../../libs/database/schema/postMediaContainer.schema'
+import {
+ PublishTask,
+ PublishTaskSchema,
+} from '../../libs/database/schema/publishTask.schema'
+import { BilibiliModule } from '../platforms/bilibili/bilibili.module'
+import { KwaiModule } from '../platforms/kwai/kwai.module'
+import { MetaModule } from '../platforms/meta/meta.module'
+import { PinterestModule } from '../platforms/pinterest/pinterest.module'
+import { TiktokModule } from '../platforms/tiktok/tiktok.module'
+import { TwitterModule } from '../platforms/twitter/twitter.module'
+import { WxPlatModule } from '../platforms/wx-plat/wx-plat.module'
+import { YoutubeModule } from '../platforms/youtube/youtube.module'
+import { FinalizePublishPostConsumer } from './consumers/finalize-publish.consumer'
+import { ImmediatePublishPostConsumer } from './consumers/immediate-publish.consumer'
+import { BilibiliPubService } from './providers/bilibili.service'
+import { PostMediaContainerService } from './providers/container.service'
+import { FacebookPublishService } from './providers/facebook.service'
+import { InstagramPublishService } from './providers/instgram.service'
+import { kwaiPubService } from './providers/kwai.service'
+import { LinkedinPublishService } from './providers/linkedin.service'
+import { PinterestPubService } from './providers/pinterest.service'
+import { ThreadsPublishService } from './providers/threads.service'
+import { TiktokPubService } from './providers/tiktok.service'
+import { TwitterPubService } from './providers/twitter.service'
+import { WxGzhPubService } from './providers/wx-gzh.service'
+import { YoutubePubService } from './providers/youtube.service'
+import { PublishingController } from './publishing.controller'
+import { PublishingService } from './publishing.service'
+import { EnqueuePublishingTaskScheduler } from './scheduler/enqueue-publishing-task.scheduler'
+
+@Module({
+ imports: [
+ MongooseModule.forFeature([
+ { name: Account.name, schema: AccountSchema },
+ { name: PublishTask.name, schema: PublishTaskSchema },
+ { name: PostMediaContainer.name, schema: PostMediaContainerSchema },
+ ]),
+ BilibiliModule,
+ PinterestModule,
+ KwaiModule,
+ YoutubeModule,
+ forwardRef(() => WxPlatModule),
+ MetaModule,
+ TiktokModule,
+ TwitterModule,
+ PinterestModule,
+ ],
+ providers: [
+ PostMediaContainerService,
+ PublishingService,
+ ImmediatePublishPostConsumer,
+ FinalizePublishPostConsumer,
+ BilibiliPubService,
+ kwaiPubService,
+ PinterestPubService,
+ YoutubePubService,
+ WxGzhPubService,
+ FacebookPublishService,
+ InstagramPublishService,
+ ThreadsPublishService,
+ TiktokPubService,
+ LinkedinPublishService,
+ TwitterPubService,
+ EnqueuePublishingTaskScheduler,
+ {
+ provide: 'PUBLISHING_PROVIDERS',
+ useFactory: (
+ bilibili: BilibiliPubService,
+ kwai: kwaiPubService,
+ youtube: YoutubePubService,
+ facebook: FacebookPublishService,
+ instagram: InstagramPublishService,
+ threads: ThreadsPublishService,
+ tiktok: TiktokPubService,
+ twitter: TwitterPubService,
+ pinterest: PinterestPubService,
+ linkedin: LinkedinPublishService,
+ ) => ({
+ [AccountType.BILIBILI]: bilibili,
+ [AccountType.KWAI]: kwai,
+ [AccountType.YOUTUBE]: youtube,
+ [AccountType.FACEBOOK]: facebook,
+ [AccountType.INSTAGRAM]: instagram,
+ [AccountType.THREADS]: threads,
+ [AccountType.TIKTOK]: tiktok,
+ [AccountType.TWITTER]: twitter,
+ [AccountType.PINTEREST]: pinterest,
+ [AccountType.LINKEDIN]: linkedin,
+ }),
+ inject: [
+ BilibiliPubService,
+ kwaiPubService,
+ YoutubePubService,
+ FacebookPublishService,
+ InstagramPublishService,
+ ThreadsPublishService,
+ TiktokPubService,
+ TwitterPubService,
+ PinterestPubService,
+ LinkedinPublishService,
+ ],
+ },
+ ],
+ controllers: [PublishingController],
+ exports: [PublishingService],
+})
+export class PublishModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.service.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.service.ts
new file mode 100644
index 00000000..e35c99a3
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.service.ts
@@ -0,0 +1,355 @@
+import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common'
+import { InjectModel } from '@nestjs/mongoose'
+import { QueueService } from '@yikart/aitoearn-queue'
+import { AccountType, PublishRecord, PublishStatus } from '@yikart/aitoearn-server-client'
+import { AppException, ResponseCode } from '@yikart/common'
+import { Model, RootFilterQuery } from 'mongoose'
+import { v4 as uuidv4 } from 'uuid'
+import { PublishTask } from '../../libs/database/schema/publishTask.schema'
+import { AccountService } from '../account/account.service'
+import { PublishRecordService } from '../account/publish-record.service'
+import { IMMEDIATE_PUBLISH_TOLERANCE_SECONDS } from './constant'
+import { CreatePublishDto, PublishRecordListFilterDto } from './dto/publish.dto'
+import { TiktokWebhookDto } from './dto/tiktok.webhook.dto'
+import { TiktokPubService } from './providers/tiktok.service'
+
+@Injectable()
+export class PublishingService implements OnModuleDestroy {
+ private readonly logger = new Logger(PublishingService.name)
+
+ constructor(
+ private readonly accountService: AccountService,
+ private readonly queueService: QueueService,
+ private readonly tiktokPubService: TiktokPubService,
+ @InjectModel(PublishTask.name)
+ private readonly publishTaskModel: Model<PublishTask>,
+ private readonly publishRecordService: PublishRecordService,
+ ) {}
+
+ private determineMetaPostCategory(data: CreatePublishDto) {
+ switch (data.accountType) {
+ case AccountType.FACEBOOK:
+ if (!data.option || !data.option.facebook || !data.option.facebook.content_category) {
+ data.option = {
+ ...data.option,
+ facebook: {
+ ...data.option?.facebook,
+ content_category: 'post',
+ },
+ }
+ }
+ break
+ case AccountType.INSTAGRAM: {
+ if (!data.option || !data.option.instagram || !data.option.instagram.content_category) {
+ let category = 'post'
+ if (data.videoUrl) {
+ category = 'reel'
+ }
+ data.option = {
+ ...data.option,
+ instagram: {
+ ...data.option?.instagram,
+ content_category: category,
+ },
+ }
+ }
+ break
+ }
+ }
+ }
+
+ async createPublishingTask(taskInfo: CreatePublishDto) {
+ const isTaskExists = await this.publishTaskModel.findOne({
+ flowId: taskInfo.flowId,
+ })
+ if (isTaskExists) {
+ throw new AppException(ResponseCode.ChannelPublishTaskAlreadyExists, `publish task with flowId ${taskInfo.flowId} already exists`)
+ }
+ const metaPlatforms = [AccountType.FACEBOOK, AccountType.INSTAGRAM]
+ if (metaPlatforms.includes(taskInfo.accountType)) {
+ this.determineMetaPostCategory(taskInfo)
+ }
+ this.logger.log(`Creating publish task with data: ${JSON.stringify(taskInfo)}`)
+ taskInfo.publishTime = new Date(taskInfo.publishTime)
+
+ const accountInfo = await this.accountService.getAccountInfo(
+ taskInfo.accountId,
+ )
+ if (!accountInfo)
+ throw new AppException(ResponseCode.ChannelAccountInfoFailed)
+ const { publishTime, accountType } = taskInfo
+ taskInfo['queueId'] = `publish:${accountType}:${uuidv4()}`
+ taskInfo['uid'] = accountInfo.uid
+ taskInfo['userId'] = accountInfo.userId
+ const newTask = await this.publishTaskModel.create(taskInfo)
+
+ const now = Date.now()
+ const immediatePublishWindow = [
+ now - IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
+ now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
+ ]
+ const publishImmediately = publishTime.getTime() >= immediatePublishWindow[0] && publishTime.getTime() <= immediatePublishWindow[1]
+ if (!publishImmediately) {
+ this.logger.log(`Publish task ${newTask.id} created, scheduled for ${publishTime.toISOString()}`)
+ return newTask
+ }
+
+ const res = await this.enqueuePublishingTask(newTask)
+ if (!res)
+ throw new AppException(ResponseCode.PublishTaskFailed, { accountType })
+ this.logger.log(`Publish task ${newTask.id} created and pushed to queue immediately`)
+ return newTask
+ }
+
+ async enqueuePublishingTask(task: PublishTask): Promise<boolean> {
+ const jobId = uuidv4().toString()
+ await this.publishTaskModel.updateOne({ _id: task.id }, { queueId: jobId })
+ const jobRes = await this.queueService.addPostPublishJob(
+ {
+ taskId: task.id,
+ jobId,
+ attempts: 0,
+ },
+ {
+ attempts: 3,
+ backoff: {
+ type: 'exponential',
+ delay: 5,
+ },
+ removeOnComplete: true,
+ removeOnFail: true,
+ jobId,
+ },
+ )
+ return jobRes.id === jobId
+ }
+
+ async getPublishTaskListByTime(
+ start: Date,
+ end: Date,
+ ): Promise<PublishTask[]> {
+ const filters: RootFilterQuery<PublishTask> = {
+ publishTime: { $gte: start, $lte: end },
+ status: PublishStatus.WaitingForPublish,
+ }
+ const list = await this.publishTaskModel.find(filters).sort({
+ publishTime: 1,
+ })
+
+ return list
+ }
+
+ async getPublishTasks(
+ query: PublishRecordListFilterDto,
+ ): Promise<PublishTask[]> {
+ const filters: RootFilterQuery<PublishTask> = {
+ userId: query.userId,
+ ...(query.accountId !== undefined && { accountId: query.accountId }),
+ ...(query.accountType !== undefined && {
+ accountType: query.accountType,
+ }),
+ ...(query.status !== undefined && {
+ status: query.status,
+ }),
+ ...(query.type !== undefined && { type: query.type }),
+ ...(query.time !== undefined
+ && query.time.length === 2 && {
+ publishTime: { $gte: query.time[0], $lte: query.time[1] },
+ }),
+ ...(query.uid !== undefined && { uid: query.uid }),
+ }
+ const db = this.publishTaskModel.find(filters).sort({
+ createdAt: -1,
+ })
+ const list = await db.exec()
+
+ return list
+ }
+
+ async getQueuedPublishTasks(query: {
+ userId: string
+ accountId?: string
+ accountType?: AccountType
+ time?: [Date, Date]
+ }): Promise<PublishTask[]> {
+ const filters: RootFilterQuery<PublishTask> = {
+ status: PublishStatus.WaitingForPublish,
+ userId: query.userId,
+ }
+ if (query.accountId) {
+ filters.accountId = query.accountId
+ }
+ if (query.accountType) {
+ filters.accountType = query.accountType
+ }
+ if (query.time && query.time.length === 2) {
+ filters.publishTime = { $gte: query.time[0], $lte: query.time[1] }
+ }
+ return this.publishTaskModel.find(filters).sort({
+ createdAt: -1,
+ })
+ }
+
+ async getPublishedPublishTasks(query: {
+ userId: string
+ accountId?: string
+ accountType?: AccountType
+ time?: [Date, Date]
+ }): Promise<PublishTask[]> {
+ const filters: RootFilterQuery<PublishTask> = {
+ status: PublishStatus.PUBLISHING,
+ userId: query.userId,
+ }
+ if (query.accountId) {
+ filters.accountId = query.accountId
+ }
+ if (query.accountType) {
+ filters.accountType = query.accountType
+ }
+ if (query.time && query.time.length === 2) {
+ filters.publishTime = { $gte: query.time[0], $lte: query.time[1] }
+ }
+ return this.publishTaskModel.find(filters).sort({
+ createdAt: -1,
+ })
+ }
+
+ async getPublishTaskListByFlowId(
+ flowId: string,
+ ): Promise<PublishTask[]> {
+ const filters: RootFilterQuery<PublishTask> = {
+ flowId,
+ }
+ const list = await this.publishTaskModel.find(filters).sort({
+ publishTime: 1,
+ })
+ return list
+ }
+
+ async updatePublishTaskStatus(
+ id: string,
+ newData: {
+ errorMsg?: string
+ status: PublishStatus
+ publishTime?: Date
+ queued?: boolean
+ inQueue?: boolean
+ },
+ ): Promise<boolean> {
+ const res = await this.publishTaskModel.updateOne({ _id: id }, newData)
+ return res.modifiedCount > 0
+ }
+
+ async deleteQueueTask(queueId: string) {
+ const job = await this.queueService.getPostPublishJob(queueId)
+ if (!job) {
+ throw new AppException(ResponseCode.PublishTaskNotFound)
+ }
+ const state = await job.getState()
+ if (state === 'waiting' || state === 'delayed') {
+ await job.remove()
+ }
+ else {
+ throw new AppException(ResponseCode.PublishTaskInProgress)
+ }
+ }
+
+ async deletePublishTaskById(id: string, userId: string): Promise<boolean> {
+ const task = await this.publishTaskModel.findById(id).exec()
+ if (!task) {
+ throw new AppException(ResponseCode.PublishTaskNotFound)
+ }
+ if (task.queued && !!task.queueId) {
+ await this.deleteQueueTask(task.queueId)
+ }
+
+ // 删除数据库数据
+ const res = await this.publishTaskModel.deleteOne({ _id: id, userId })
+ return res.deletedCount > 0
+ }
+
+ async updatePublishTaskTime(id: string, publishTime: Date, userId: string) {
+ const task = await this.publishTaskModel.findById(id).exec()
+ if (!task) {
+ throw new AppException(ResponseCode.PublishTaskNotFound)
+ }
+
+ const res = await this.publishTaskModel.updateOne(
+ { _id: id, userId },
+ { publishTime },
+ )
+ if (task.inQueue && !!task.queueId) {
+ await this.deleteQueueTask(task.queueId)
+ }
+ return res.modifiedCount > 0
+ }
+
+ async getPublishTaskInfo(id: string) {
+ return await this.publishTaskModel.findOne({ _id: id }).exec()
+ }
+
+ async getPublishTaskInfoWithFlowId(flowId: string, userId: string) {
+ return await this.publishTaskModel.findOne({ flowId, userId }).exec()
+ }
+
+ async getPublishTaskInfoWithUserId(id: string, userId: string) {
+ return await this.publishTaskModel.findOne({ _id: id, userId }).exec()
+ }
+
+ async publishTaskImmediately(id: string) {
+ const taskDoc = await this.getPublishTaskInfo(id)
+ const taskInfo = taskDoc!.toObject()
+ if (!taskInfo) {
+ throw new AppException(ResponseCode.PublishTaskNotFound)
+ }
+ if (taskInfo.status !== PublishStatus.WaitingForPublish) {
+ throw new AppException(ResponseCode.PublishTaskStatusInvalid)
+ }
+
+ await this.publishTaskModel.updateOne({ _id: id }, { publishTime: new Date(), queued: true })
+ await this.enqueuePublishingTask(taskInfo)
+ }
+
+ async handleTiktokPostWebhook(data: TiktokWebhookDto) {
+ return this.tiktokPubService.handleTiktokPostWebhook(data)
+ }
+
+ async createPublishRecord(newData: Partial<PublishRecord>) {
+ newData.publishTime = newData.publishTime || new Date()
+ await this.publishRecordService.createPublishRecord(newData)
+ }
+
+ async completePublishTask(
+ newData: PublishTask,
+ dataId: string,
+ data?: {
+ workLink: string
+ dataOption?: Record<string, any>
+ },
+ ) {
+ newData.status = PublishStatus.PUBLISHED
+ newData.publishTime = new Date()
+ newData.queued = false
+ newData.inQueue = false
+ await this.publishTaskModel.updateOne(
+ { _id: newData.id },
+ { status: PublishStatus.PUBLISHED, errorMsg: '', dataId, workLink: data?.workLink, publishTime: newData.publishTime, queued: false, inQueue: false },
+ ).exec()
+ try {
+ await this.createPublishRecord({
+ ...newData,
+ ...(data || {}),
+ dataId,
+ })
+ }
+ catch (error) {
+ this.logger.error(`Failed to create publish record ${newData.id}: ${error}`)
+ }
+ }
+
+ async onModuleDestroy() {
+ this.logger.log('Module is being destroyed, closing publish queue...')
+ await this.queueService.closePostPublishQueue()
+ this.logger.log('Publish queue closed successfully')
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/scheduler/enqueue-publishing-task.scheduler.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/scheduler/enqueue-publishing-task.scheduler.ts
new file mode 100644
index 00000000..9b4c82f9
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/scheduler/enqueue-publishing-task.scheduler.ts
@@ -0,0 +1,42 @@
+import { Injectable, Logger } from '@nestjs/common'
+import { Cron } from '@nestjs/schedule'
+import { IMMEDIATE_PUBLISH_TOLERANCE_SECONDS, PUBLISHING_SCHEDULED_TASK_CRON_EXPRESSION } from '../constant'
+import { PublishingService } from '../publishing.service'
+
+@Injectable()
+export class EnqueuePublishingTaskScheduler {
+ private readonly logger = new Logger(EnqueuePublishingTaskScheduler.name)
+
+ constructor(
+ private readonly publishingService: PublishingService,
+ ) {}
+
+ @Cron(PUBLISHING_SCHEDULED_TASK_CRON_EXPRESSION, { waitForCompletion: true })
+ async enqueueScheduledPublishingTasks() {
+ this.logger.log(`Start pushing scheduled publish tasks, current time: ${new Date().toISOString()}`)
+ try {
+ const now = Date.now()
+ const start = new Date(now - IMMEDIATE_PUBLISH_TOLERANCE_SECONDS)
+ const end = new Date(now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS)
+
+ const tasks = await this.publishingService.getPublishTaskListByTime(start, end)
+ if (tasks.length === 0) {
+ this.logger.log(`Pushing scheduled publish tasks from ${start.toISOString()} to ${end.toISOString()}: No scheduled publish tasks found`)
+ this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
+ return
+ }
+ this.logger.log(
+ `Pushing scheduled publish tasks from ${start.toISOString()} to ${end.toISOString()}, found ${tasks.length} tasks`,
+ )
+
+ for (const task of tasks) {
+ await this.publishingService.enqueuePublishingTask(task)
+ }
+ this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
+ }
+ catch (error) {
+ this.logger.error(`Error pushing scheduled publish tasks: ${error.message}`, error.stack)
+ this.logger.log(`Pushing scheduled publish tasks completed, current time: ${new Date().toISOString()}`)
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/skKey/dto/skKey.dto.ts b/project/backend/apps/aitoearn-channel/src/core/sk-key/dto/sk-key.dto.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/skKey/dto/skKey.dto.ts
rename to project/backend/apps/aitoearn-channel/src/core/sk-key/dto/sk-key.dto.ts
diff --git a/project/backend/apps/aitoearn-channel/src/core/skKey/skKey.controller.ts b/project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.controller.ts
similarity index 97%
rename from project/backend/apps/aitoearn-channel/src/core/skKey/skKey.controller.ts
rename to project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.controller.ts
index 2b863920..ac39a33a 100644
--- a/project/backend/apps/aitoearn-channel/src/core/skKey/skKey.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.controller.ts
@@ -8,8 +8,8 @@ import {
GetSkKeyListDto,
SkKeyKeyDto,
UpSkKeyInfoDto,
-} from './dto/skKey.dto'
-import { SkKeyService } from './skKey.service'
+} from './dto/sk-key.dto'
+import { SkKeyService } from './sk-key.service'
@Controller()
export class SkKeyController {
diff --git a/project/backend/apps/aitoearn-channel/src/core/skKey/skKey.module.ts b/project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.module.ts
similarity index 78%
rename from project/backend/apps/aitoearn-channel/src/core/skKey/skKey.module.ts
rename to project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.module.ts
index 162dc787..00af2226 100644
--- a/project/backend/apps/aitoearn-channel/src/core/skKey/skKey.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.module.ts
@@ -5,9 +5,9 @@ import {
SkKeyRefAccount,
SkKeyRefAccountSchema,
} from '../../libs/database/schema/skKeyRefAccount.schema'
-import { PublishModule } from '../publish/publish.module'
-import { SkKeyController } from './skKey.controller'
-import { SkKeyService } from './skKey.service'
+import { PublishModule } from '../publishing/publishing.module'
+import { SkKeyController } from './sk-key.controller'
+import { SkKeyService } from './sk-key.service'
@Global()
@Module({
diff --git a/project/backend/apps/aitoearn-channel/src/core/skKey/skKey.service.ts b/project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.service.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/core/skKey/skKey.service.ts
rename to project/backend/apps/aitoearn-channel/src/core/sk-key/sk-key.service.ts
diff --git a/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibili.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibili.exception.ts
new file mode 100644
index 00000000..d119f602
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibili.exception.ts
@@ -0,0 +1,57 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface BilibiliRawError {
+ message: string
+ code: number
+}
+
+/**
+ * Bilibili error class.
+ */
+export class BilibiliError extends SocialMediaError<BilibiliRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: BilibiliRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'bilibili'
+ }
+
+ protected static override extractRawError(data: unknown): BilibiliRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse: BilibiliRawError = {
+ code: data['code'],
+ message: data['message'],
+ }
+ return errResponse
+ }
+
+ protected static override buildMessage(
+ rawError: BilibiliRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.message || 'Unknown error'}, error code: ${rawError.code || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibiliApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibiliApi.service.ts
index 3b140fb7..5b23938c 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibiliApi.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/bilibili/bilibiliApi.service.ts
@@ -11,29 +11,23 @@ import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { getRandomString } from '../../common'
import { config } from '../../config'
+import { BilibiliError } from './bilibili.exception'
import {
AccessToken,
- AccessTokenResponse,
AddArchiveData,
- ArchiveAddByUtokenResponse,
+ ArchiveAddByUtokenData,
ArchiveListData,
- ArchiveListResponse,
ArchiveStatus,
ArchiveTypeItem,
- ArchiveTypeListResponse,
ArcIncStatData,
- ArcIncStatResponse,
ArcStatData,
- ArcStatResponse,
BilibiliUser,
- BilibiliUserInfoResponse,
- DeleteVideoResponse,
- EtagResponse,
- GrantScopesResponse,
- UploadCoverImgResponse,
+ CommonResponse,
+ DeleteVideoData,
+ etagData,
+ GrantScopes,
UserStatData,
- UserStatResponse,
- VideoInitialResponse,
+ videoInitialData,
VideoUTypes,
} from './common'
@@ -42,6 +36,7 @@ export class BilibiliApiService {
private readonly logger = new Logger(BilibiliApiService.name)
private readonly appId: string
private readonly appSecret: string
+ private readonly provider = 'bilibili'
constructor() {
const cfg = config.bilibili
this.appId = cfg.id
@@ -55,23 +50,25 @@ export class BilibiliApiService {
}
}
- private async request<CommonResponse>(url: string, config: AxiosRequestConfig = {}): Promise<CommonResponse> {
- this.logger.debug(`Bilibili API Request: ${url}`)
+ private generateOperation(url: string, method: string) {
+ return `${method} ${url.split('?')?.[0]?.split('.com')?.[1] || 'unknown'}`
+ }
+
+ private async request<T>(url: string, config: AxiosRequestConfig = {}): Promise<CommonResponse<T>> {
+ const method = (config.method || 'GET').toUpperCase()
+ const operation = this.generateOperation(url, method)
+ this.logger.debug(`Bilibili API Request: ${operation}, params=${config.params ? JSON.stringify(config.params) : '{}'} `)
try {
- const response: AxiosResponse<CommonResponse> = await axios(url, config)
- if (response.data['code'] !== 0) {
- this.logger.error(`Bilibili API returned an error: ${url}, response: ${JSON.stringify(response.data)}`)
- throw new Error(response.data['message'] || 'Bilibili API returned an error')
+ const response: AxiosResponse<CommonResponse<T>> = await axios(url, config)
+ if (response.data && response.data.code !== 0) {
+ throw BilibiliError.buildFromResponse(response.data, operation)
}
return response.data
}
catch (error) {
- if (error.response) {
- this.logger.error(`Bilibili API request failed: ${url}, status: ${error.response.status}, data: ${JSON.stringify(error.response.data)}`)
- throw new Error(`Bilibili API request failed: ${error.response.data.error.message}`)
- }
- this.logger.error(`Bilibili API request failed: ${url}`, error)
- throw new Error(`Bilibili API request failed: ${error.message}`)
+ const err = BilibiliError.buildFromError(error, operation)
+ this.logger.error(`Bilibili API Error: ${operation} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
}
}
@@ -110,7 +107,7 @@ export class BilibiliApiService {
},
}
- const resp = await this.request<AccessTokenResponse>('https://api.bilibili.com/x/account-oauth2/v1/token', config)
+ const resp = await this.request<AccessToken>('https://api.bilibili.com/x/account-oauth2/v1/token', config)
return resp.data
}
@@ -130,7 +127,7 @@ export class BilibiliApiService {
refresh_token: refreshToken,
},
}
- const resp = await this.request<AccessTokenResponse>(url, config)
+ const resp = await this.request<AccessToken>(url, config)
return resp.data
}
@@ -193,7 +190,7 @@ export class BilibiliApiService {
method: 'GET',
headers: this.generateHeader({ accessToken }),
}
- const resp = await this.request<BilibiliUserInfoResponse>(url, config)
+ const resp = await this.request<BilibiliUser>(url, config)
return resp.data
}
@@ -209,7 +206,7 @@ export class BilibiliApiService {
headers: this.generateHeader({ accessToken }),
}
- const resp = await this.request<GrantScopesResponse>(url, config)
+ const resp = await this.request<GrantScopes>(url, config)
return resp.data
}
@@ -235,7 +232,7 @@ export class BilibiliApiService {
headers: this.generateHeader({ accessToken, body: data }),
data,
}
- const resp = await this.request<VideoInitialResponse>(url, config)
+ const resp = await this.request<videoInitialData>(url, config)
return resp.data.upload_token
}
@@ -263,7 +260,7 @@ export class BilibiliApiService {
},
data: file,
}
- const result = await this.request<EtagResponse>(url, config)
+ const result = await this.request<etagData>(url, config)
return result.data.etag
}
@@ -282,7 +279,7 @@ export class BilibiliApiService {
upload_token: uploadToken,
},
}
- return await this.request<{ code: number, message: string }>(url, config)
+ return await this.request<unknown>(url, config)
}
/**
@@ -303,7 +300,7 @@ export class BilibiliApiService {
headers: this.generateHeader({ accessToken }, true),
data: formData,
}
- const resp = await this.request<UploadCoverImgResponse>(url, config)
+ const resp = await this.request<{ url: string }>(url, config)
return resp.data.url
}
@@ -315,20 +312,13 @@ export class BilibiliApiService {
* @returns
*/
async uploadLitVideo(accessToken: string, file: Buffer, uploadToken: string) {
- const result = await axios.post<{
- code: number // 0;
- message: string // '0';
- }>(
- `https://https://openupos.bilivideo.com/video/v2/upload?upload_token=${uploadToken}`,
- file,
- {
- headers: this.generateHeader({
- accessToken,
- }),
- },
- )
-
- return result.data
+ const url = `https://openupos.bilivideo.com/video/v2/upload?upload_token=${uploadToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ headers: this.generateHeader({ accessToken }),
+ data: file,
+ }
+ return await this.request<unknown>(url, config)
}
/**
@@ -350,10 +340,7 @@ export class BilibiliApiService {
params: { upload_token: uploadToken },
data: inData,
}
- const result = await this.request<ArchiveAddByUtokenResponse>(url, config)
- if (result.code !== 0) {
- throw new Error(result.message)
- }
+ const result = await this.request<ArchiveAddByUtokenData>(url, config)
return result.data.resource_id
}
@@ -368,7 +355,7 @@ export class BilibiliApiService {
method: 'GET',
headers: this.generateHeader({ accessToken }),
}
- const result = await this.request<ArchiveTypeListResponse>(url, config)
+ const result = await this.request<ArchiveTypeItem[]>(url, config)
return result.data
}
@@ -393,7 +380,7 @@ export class BilibiliApiService {
headers: this.generateHeader({ accessToken }),
params,
}
- const result = await this.request<ArchiveListResponse>(url, config)
+ const result = await this.request<ArchiveListData>(url, config)
return result.data
}
@@ -408,7 +395,7 @@ export class BilibiliApiService {
method: 'GET',
headers: this.generateHeader({ accessToken }),
}
- const result = await this.request<UserStatResponse>(url, config)
+ const result = await this.request<UserStatData>(url, config)
return result.data
}
@@ -427,7 +414,7 @@ export class BilibiliApiService {
method: 'GET',
headers: this.generateHeader({ accessToken }),
}
- const result = await this.request<ArcStatResponse>(url, config)
+ const result = await this.request<ArcStatData>(url, config)
return result.data
}
@@ -442,11 +429,11 @@ export class BilibiliApiService {
method: 'GET',
headers: this.generateHeader({ accessToken }),
}
- const result = await this.request<ArcIncStatResponse>(url, config)
+ const result = await this.request<ArcIncStatData>(url, config)
return result.data
}
- async deleteArchive(accessToken: string, videoId: string): Promise<DeleteVideoResponse> {
+ async deleteArchive(accessToken: string, videoId: string): Promise<CommonResponse<DeleteVideoData>> {
const url = 'https://member.bilibili.com/arcopen/fn/archive/delete'
const config: AxiosRequestConfig = {
method: 'POST',
@@ -455,7 +442,7 @@ export class BilibiliApiService {
resource_id: videoId,
},
}
- const result = await this.request<DeleteVideoResponse>(url, config)
+ const result = await this.request<DeleteVideoData>(url, config)
return result
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/database/schema/postMediaContainer.schema.ts b/project/backend/apps/aitoearn-channel/src/libs/database/schema/postMediaContainer.schema.ts
index ac7083a1..22079d98 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/database/schema/postMediaContainer.schema.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/database/schema/postMediaContainer.schema.ts
@@ -1,6 +1,6 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import mongoose from 'mongoose'
-import { PlatPulOption } from '../../../core/publish/common'
+import { PlatPulOption } from '../../../core/publishing/common'
import { BaseTemp } from './time.tamp'
export enum PostMediaStatus {
@@ -38,6 +38,12 @@ export class PostMediaContainer extends BaseTemp {
})
publishId: string
+ @Prop({
+ required: false,
+ type: String,
+ })
+ jobId?: string
+
@Prop({
required: true,
})
diff --git a/project/backend/apps/aitoearn-channel/src/libs/database/schema/publishTask.schema.ts b/project/backend/apps/aitoearn-channel/src/libs/database/schema/publishTask.schema.ts
index 55ff1956..31796aec 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/database/schema/publishTask.schema.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/database/schema/publishTask.schema.ts
@@ -1,7 +1,7 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
import { AccountType } from '@yikart/common'
import mongoose from 'mongoose'
-import { PlatPulOption } from '../../../core/publish/common'
+import { PlatPulOption } from '../../../core/publishing/common'
import { BaseTemp } from './time.tamp'
export enum PublishType {
@@ -137,6 +137,12 @@ export class PublishTask extends BaseTemp {
})
inQueue: boolean
+ @Prop({
+ required: false,
+ default: false,
+ })
+ queued: boolean
+
// 错误信息
@Prop({
required: false,
diff --git a/project/backend/apps/aitoearn-channel/src/libs/exception/base.ts b/project/backend/apps/aitoearn-channel/src/libs/exception/base.ts
new file mode 100644
index 00000000..c5273e62
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/exception/base.ts
@@ -0,0 +1,256 @@
+import type { IErrorContext, ISocialMediaError } from './interfaces'
+import { generateOperation } from './utils'
+
+/**
+ * Base class for social media platform errors.
+ * Platform-specific error classes extend this and implement abstract methods.
+ */
+export class SocialMediaError<TPlatformRawError = unknown>
+ extends Error
+ implements ISocialMediaError {
+ readonly platform: string
+ readonly operation: string
+ readonly status?: number
+ readonly rawStatus?: number
+ readonly rawError: TPlatformRawError
+ readonly isNetworkError: boolean
+ readonly context?: IErrorContext
+
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: TPlatformRawError,
+ isNetworkError: boolean,
+ context?: IErrorContext,
+ ) {
+ super(message)
+ this.name = name
+ this.platform = platform
+ this.operation = operation
+ this.status = status
+ this.rawStatus = rawStatus
+ this.rawError = rawError
+ this.isNetworkError = isNetworkError
+ this.context = context
+
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, SocialMediaError)
+ }
+ }
+
+ /**
+ * Builds error from exception (for network errors and unknown errors).
+ */
+ static buildFromError(
+ error: unknown,
+ operation?: string,
+ context?: IErrorContext,
+ ): SocialMediaError {
+ if (error instanceof SocialMediaError) {
+ return error
+ }
+ const axiosError = error as {
+ isAxiosError?: boolean
+ response?: { status?: number, data?: unknown }
+ config?: { method?: string, url?: string }
+ message?: string
+ code?: string
+ status?: number
+ }
+
+ const isAxios = !!axiosError?.isAxiosError
+ if (!isAxios) {
+ return this.buildFromUnknownError(error, operation, context)
+ }
+
+ const isNetworkError = isAxios && !axiosError?.response
+ const finalOperation = operation || this.resolveOperation(axiosError, context)
+ if (isNetworkError) {
+ const message = `${axiosError?.code || 'NetworkError'}: ${axiosError?.message || 'A network error occurred.'}`
+ return this.buildFromNetworkError(
+ message,
+ finalOperation,
+ context,
+ )
+ }
+
+ const rawStatus = axiosError?.status
+ const responseData = axiosError?.response?.data
+ const platform = this.getPlatformName()
+ const rawError = this.extractRawError(responseData) || {}
+ const message = this.buildMessage(rawError, finalOperation)
+ const errorName = this.determineErrorName(rawStatus, isNetworkError)
+
+ return new SocialMediaError(
+ platform,
+ finalOperation,
+ errorName,
+ message,
+ rawStatus,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ static buildFromUnknownError(
+ error: unknown,
+ operation?: string,
+ context?: IErrorContext,
+ ): SocialMediaError {
+ const unknownError = error as { message?: string }
+ const message = `UnknownError: ${unknownError?.message || 'An unknown error occurred.'}`
+ return new SocialMediaError(
+ this.getPlatformName(),
+ operation,
+ 'UnknownError',
+ message,
+ undefined,
+ undefined,
+ {},
+ true,
+ context,
+ )
+ }
+
+ /**
+ * Builds error specifically for network errors.
+ */
+ static buildFromNetworkError(
+ message: string,
+ operation: string,
+ context?: IErrorContext,
+ ): SocialMediaError {
+ const platform = this.getPlatformName()
+ return new SocialMediaError(
+ platform,
+ operation,
+ 'NetworkError',
+ message,
+ undefined,
+ undefined,
+ {},
+ true,
+ context,
+ )
+ }
+
+ /**
+ * Builds error from API response (for business errors).
+ */
+ static buildFromResponse<TPlatformRawError = unknown>(
+ response: unknown,
+ operation?: string,
+ context?: IErrorContext,
+ ): SocialMediaError {
+ const platform = this.getPlatformName()
+ const rawError = this.extractRawError(response) || ({} as TPlatformRawError)
+ const message = this.buildMessage(rawError, operation)
+ const finalOperation = operation || generateOperation(context?.method, context?.url)
+ const errorName = this.determineErrorName(400, false)
+
+ return new SocialMediaError(
+ platform,
+ finalOperation,
+ errorName,
+ message,
+ 400,
+ 200,
+ rawError,
+ false,
+ context,
+ )
+ }
+
+ /**
+ * Resolves operation name from context or axiosError.config.
+ */
+ static resolveOperation(
+ axiosError: { config?: { method?: string, url?: string } },
+ context?: IErrorContext,
+ ): string {
+ if (context?.method && context?.url) {
+ return generateOperation(context.method, context.url)
+ }
+ if (axiosError?.config?.method && axiosError?.config?.url) {
+ return generateOperation(axiosError.config.method, axiosError.config.url)
+ }
+ return 'unknown'
+ }
+
+ /**
+ * Gets platform name from class name (implemented by subclass or default).
+ */
+ protected static getPlatformName(): string {
+ // Default: 'FacebookError' -> 'facebook'.
+ const className = this.name
+ return className.replace(/Error$/, '').toLowerCase()
+ }
+
+ /**
+ * Extracts raw error from data (implemented by subclass).
+ */
+ protected static extractRawError(_data: unknown): any {
+ throw new Error('extractRawError must be implemented by subclass')
+ }
+
+ /**
+ * Builds error message (implemented by subclass).
+ */
+ protected static buildMessage(
+ _rawError: unknown,
+ _operation: string,
+ ): string {
+ throw new Error('buildMessage must be implemented by subclass')
+ }
+
+ /**
+ * Determines error name (implemented by subclass).
+ */
+ protected static determineErrorName(
+ status: number | undefined,
+ isNetworkError: boolean,
+ ): string {
+ if (isNetworkError) {
+ return 'NetworkError'
+ }
+ if (!status) {
+ return 'UnknownError'
+ }
+ if (status === 401 || status === 403) {
+ return 'AuthError'
+ }
+ if (status === 429) {
+ return 'RateLimitError'
+ }
+ if (status >= 400 && status < 500) {
+ return 'ClientError'
+ }
+ if (status >= 500) {
+ return 'ServerError'
+ }
+ return 'ApiError'
+ }
+
+ /**
+ * Converts error to JSON (for logging, serialization, etc.).
+ */
+ toJSON(): Record<string, unknown> {
+ return {
+ platform: this.platform,
+ operation: this.operation,
+ status: this.status,
+ rawStatus: this.rawStatus,
+ name: this.name,
+ message: this.message,
+ isNetworkError: this.isNetworkError,
+ rawError: this.rawError,
+ context: this.context,
+ }
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/exception/index.ts b/project/backend/apps/aitoearn-channel/src/libs/exception/index.ts
new file mode 100644
index 00000000..95511eb9
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/exception/index.ts
@@ -0,0 +1,11 @@
+// Base class.
+export { SocialMediaError } from './base'
+
+// Interfaces.
+export type {
+ IErrorContext,
+ ISocialMediaError,
+} from './interfaces'
+
+// Utility functions.
+export { generateOperation } from './utils'
diff --git a/project/backend/apps/aitoearn-channel/src/libs/exception/interfaces.ts b/project/backend/apps/aitoearn-channel/src/libs/exception/interfaces.ts
new file mode 100644
index 00000000..6ebf3b6d
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/exception/interfaces.ts
@@ -0,0 +1,46 @@
+/**
+ * Interface for social media platform errors.
+ * All platform error classes must implement this interface.
+ */
+export interface ISocialMediaError {
+ /** Platform name (e.g., 'twitter', 'facebook'). */
+ readonly platform: string
+
+ /** Operation name (e.g., 'createPost', 'uploadMedia'). */
+ readonly operation: string
+
+ /** Normalized status code for error classification. Undefined for network errors, 400 for HTTP 200 business failures. */
+ readonly status?: number
+
+ /** Original HTTP status code from response. Undefined for network errors. */
+ readonly rawStatus?: number
+
+ /** Error name/type (e.g., 'NetworkError', 'ApiError', 'ClientError'). */
+ readonly name: string
+
+ /** Error message. */
+ readonly message: string
+
+ /** Raw error data in platform-specific format. */
+ readonly rawError: unknown
+
+ /** Whether this is a network error (connection failure, timeout, DNS resolution failure, etc.). */
+ readonly isNetworkError: boolean
+}
+
+/**
+ * Error context information.
+ */
+export interface IErrorContext {
+ /** Request URL. */
+ url?: string
+
+ /** HTTP method. */
+ method?: string
+
+ /** Request parameters. */
+ params?: Record<string, unknown>
+
+ /** Additional custom information. */
+ extra?: Record<string, unknown>
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/exception/utils.ts b/project/backend/apps/aitoearn-channel/src/libs/exception/utils.ts
new file mode 100644
index 00000000..4a68a703
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/exception/utils.ts
@@ -0,0 +1,29 @@
+/**
+ * Auto-generates operation name from HTTP method and URL.
+ *
+ * Examples:
+ * - method: 'POST', url: 'https://graph.facebook.com/v23.0/me/feed' -> 'POST /v23.0/me/feed'
+ * - method: 'GET', url: 'https://graph.facebook.com/v23.0/me' -> 'GET /v23.0/me'
+ *
+ * @param method - HTTP method (e.g., 'GET', 'POST').
+ * @param url - Request URL.
+ * @returns Generated operation name.
+ */
+export function generateOperation(method?: string, url?: string): string {
+ if (!method || !url) {
+ return 'unknown'
+ }
+
+ try {
+ const urlObj = new URL(url)
+ const path = urlObj.pathname
+ return `${method.toUpperCase()} ${path}`
+ }
+ catch {
+ const match = url.match(/https?:\/\/[^/]+(\/[^?#]*)/)
+ if (match) {
+ return `${method.toUpperCase()} ${match[1]}`
+ }
+ return `${method.toUpperCase()} ${url}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook-api.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook-api.exception.ts
deleted file mode 100644
index 2c41891b..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook-api.exception.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { AxiosError } from 'axios'
-
-export interface FacebookRawError {
- message: string
- type: string
- code: number
- fbtrace_id: string
-}
-
-export interface NormalizedFacebookError {
- status?: number
- raw?: FacebookRawError
- isNetwork: boolean
- isAxios: boolean
- original: unknown
-}
-
-export interface FacebookApiExceptionMeta {
- url?: string
- method?: string
- operation?: string
- attempt?: number
- extra?: Record<string, unknown>
-}
-
-export class FacebookApiException extends Error {
- readonly operation: string
- readonly normalized: NormalizedFacebookError
- readonly meta?: FacebookApiExceptionMeta
-
- constructor(
- operation: string,
- normalized: NormalizedFacebookError,
- meta?: FacebookApiExceptionMeta,
- ) {
- super(FacebookApiException.buildMessage(operation, normalized))
- this.name = 'FacebookApiException'
- this.operation = operation
- this.normalized = normalized
- this.meta = meta
- }
-
- static buildMessage(op: string, n: NormalizedFacebookError): string {
- if (n.raw) {
- const { message, code } = n.raw
- return `${op} failed: ${message} (code=${code})`
- }
- if (n.isNetwork) {
- return `${op} failed: network error`
- }
- return `${op} failed: unexpected error`
- }
-
- toJSON() {
- return {
- name: this.name,
- message: this.message,
- operation: this.operation,
- status: this.normalized.status,
- facebook: this.normalized.raw && {
- code: this.normalized.raw.code,
- type: this.normalized.raw.type,
- trace: this.normalized.raw.fbtrace_id,
- },
- meta: this.meta,
- }
- }
-
- static fromAxiosError(
- operation: string,
- error: AxiosError,
- meta?: FacebookApiExceptionMeta,
- ): FacebookApiException {
- const normalized: NormalizedFacebookError = {
- status: error.response?.status,
- raw: (error.response?.data as { error?: FacebookRawError } | undefined)?.error,
- isNetwork: !!error.isAxiosError && !error.response,
- isAxios: true,
- original: error,
- }
- return new FacebookApiException(operation, normalized, meta)
- }
-}
-
-export function normalizeFacebookError(e: unknown): NormalizedFacebookError {
- const err = e as { isAxiosError?: boolean, response?: { status?: number, data?: { error?: FacebookRawError } } }
- const isAxios = !!err?.isAxiosError
- const raw = err?.response?.data?.error
- return {
- status: err?.response?.status,
- raw,
- isNetwork: isAxios && !err?.response,
- isAxios,
- original: e,
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.exception.ts
new file mode 100644
index 00000000..9cdf256a
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.exception.ts
@@ -0,0 +1,63 @@
+import type { IErrorContext } from '../exception/interfaces'
+import { SocialMediaError } from '../exception/base'
+
+/**
+ * Facebook API raw error format.
+ */
+export interface FacebookRawError {
+ message: string
+ type?: string
+ code?: number
+ fbtrace_id?: string
+ error_subcode?: number
+ error_user_title?: string
+ error_user_msg?: string
+}
+
+/**
+ * Facebook error class.
+ */
+export class FacebookError extends SocialMediaError<FacebookRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: FacebookRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'facebook'
+ }
+
+ protected static override extractRawError(data: unknown): FacebookRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as { error?: FacebookRawError }
+ return errResponse.error
+ }
+
+ protected static override buildMessage(
+ rawError: FacebookRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.error_user_title || rawError.message}, error code: ${rawError.code}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.service.ts b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.service.ts
index 14fb1b88..4ade2e4d 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.service.ts
@@ -1,9 +1,9 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { config } from '../../config'
-import { MetaOAuthLongLivedCredential } from '../../core/plat/meta/meta.interfaces'
+import { MetaOAuthLongLivedCredential } from '../../core/platforms/meta/meta.interfaces'
import { FacebookOAuth2Config } from './constants'
-import { FacebookApiException, normalizeFacebookError } from './facebook-api.exception'
+import { FacebookError } from './facebook.exception'
import {
ChunkedVideoUploadRequest,
ChunkedVideoUploadResponse,
@@ -70,12 +70,9 @@ export class FacebookService {
return response.data
}
catch (error: unknown) {
- const normalized = normalizeFacebookError(error)
- const status = normalized.status
- const code = normalized.raw?.code
- const message = normalized.raw?.message || (error as Error)?.message
- this.logger.error(`[FB:${operation}] Failed url=${url} status=${status} code=${code} msg=${message}`)
- throw new FacebookApiException(operation, normalized, { url, method: config.method })
+ const err = FacebookError.buildFromError(error, operation)
+ this.logger.error(`[FB:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram-api.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram-api.exception.ts
deleted file mode 100644
index 52b1163d..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram-api.exception.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { AxiosError } from 'axios'
-
-export interface InstagramRawError {
- message: string
- type: string
- code: number
- error_subcode?: number
- fbtrace_id?: string
- error_user_msg?: string
- error_user_title?: string
-}
-
-export interface NormalizedInstagramError {
- status?: number
- raw?: InstagramRawError
- isNetwork: boolean
- isAxios: boolean
- original: unknown
-}
-
-export interface InstagramApiExceptionMeta {
- url?: string
- method?: string
- operation?: string
- extra?: Record<string, unknown>
-}
-
-export class InstagramApiException extends Error {
- readonly operation: string
- readonly normalized: NormalizedInstagramError
- readonly meta?: InstagramApiExceptionMeta
-
- constructor(
- operation: string,
- normalized: NormalizedInstagramError,
- meta?: InstagramApiExceptionMeta,
- ) {
- super(InstagramApiException.buildMessage(operation, normalized))
- this.name = 'InstagramApiException'
- this.operation = operation
- this.normalized = normalized
- this.meta = meta
- }
-
- static buildMessage(op: string, n: NormalizedInstagramError): string {
- if (n.raw) {
- const { message, code, error_subcode, error_user_title } = n.raw
- const sub = error_subcode != null ? `, subcode=${error_subcode}` : ''
- return `${op} failed: ${error_user_title || message} (code=${code}${sub})`
- }
- if (n.isNetwork) {
- return `${op} failed: network error`
- }
- return `${op} failed: unexpected error`
- }
-
- toJSON() {
- return {
- name: this.name,
- message: this.message,
- operation: this.operation,
- status: this.normalized.status,
- instagram: this.normalized.raw && {
- code: this.normalized.raw.code,
- subcode: this.normalized.raw.error_subcode,
- type: this.normalized.raw.type,
- trace: this.normalized.raw.fbtrace_id,
- },
- meta: this.meta,
- }
- }
-
- static fromAxiosError(
- operation: string,
- error: AxiosError,
- meta?: InstagramApiExceptionMeta,
- ): InstagramApiException {
- const normalized: NormalizedInstagramError = {
- status: error.response?.status,
- raw: (error.response?.data as { error?: InstagramRawError } | undefined)?.error,
- isNetwork: !!error.isAxiosError && !error.response,
- isAxios: true,
- original: error,
- }
- return new InstagramApiException(operation, normalized, meta)
- }
-}
-
-export function normalizeInstagramError(e: unknown): NormalizedInstagramError {
- const err = e as { isAxiosError?: boolean, response?: { status?: number, data?: { error?: InstagramRawError } } }
- const isAxios = !!err?.isAxiosError
- const raw = err?.response?.data?.error
- return {
- status: err?.response?.status,
- raw,
- isNetwork: isAxios && !err?.response,
- isAxios,
- original: e,
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.exception.ts
new file mode 100644
index 00000000..90ae4145
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.exception.ts
@@ -0,0 +1,59 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface InstagramRawError {
+ message: string
+ type: string
+ code: number
+ error_subcode?: number
+ fbtrace_id?: string
+ error_user_msg?: string
+ error_user_title?: string
+}
+
+/**
+ * Instagram error class.
+ */
+export class InstagramError extends SocialMediaError<InstagramRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: InstagramRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'instagram'
+ }
+
+ protected static override extractRawError(data: unknown): InstagramRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as { error?: InstagramRawError }
+ return errResponse.error
+ }
+
+ protected static override buildMessage(
+ rawError: InstagramRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.error_user_title || rawError.message}, error code: ${rawError.code}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.service.ts b/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.service.ts
index 55abc9f6..f5dede0f 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/instagram/instagram.service.ts
@@ -1,9 +1,9 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { config } from '../../config'
-import { MetaOAuthLongLivedCredential } from '../../core/plat/meta/meta.interfaces'
+import { MetaOAuthLongLivedCredential } from '../../core/platforms/meta/meta.interfaces'
import { InstagramOAuth2Config } from './constants'
-import { InstagramApiException, normalizeInstagramError } from './instagram-api.exception'
+import { InstagramError } from './instagram.exception'
import {
ChunkedMediaUploadRequest,
CreateMediaContainerRequest,
@@ -43,19 +43,12 @@ export class InstagramService {
return response.data
}
catch (error: unknown) {
- const normalized = normalizeInstagramError(error)
- if (normalized.raw) {
- this.logger.error(
- `[IG:${operation}] request ${url} failed: ${normalized.raw.error_user_title || normalized.raw.message} status=${normalized.status} code=${normalized.raw.code} sub=${normalized.raw.error_subcode} detail=${normalized.raw.error_user_msg}`,
- )
- }
- else if (normalized.isNetwork) {
- this.logger.error(`[IG:${operation}] network error ${url}`)
- }
- else {
- this.logger.error(`[IG:${operation}] unexpected error ${url}: ${(error as any)?.message}`)
- }
- throw new InstagramApiException(operation, normalized, { url, method: config.method, operation })
+ const err = InstagramError.buildFromError(
+ error,
+ operation,
+ )
+ this.logger.error(`[IG:${operation}] error ${url} message=${err.message} status=${err.status} rawStatus=${err.rawStatus} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.exception.ts
new file mode 100644
index 00000000..560b50ee
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.exception.ts
@@ -0,0 +1,54 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface KwaiRawError {
+ result?: number
+ error_msg?: string
+}
+
+/**
+ * Kwai error class.
+ */
+export class KwaiError extends SocialMediaError<KwaiRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: KwaiRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'kwai'
+ }
+
+ protected static override extractRawError(data: unknown): KwaiRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as KwaiRawError
+ return errResponse
+ }
+
+ protected static override buildMessage(
+ rawError: KwaiRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.error_msg || 'Unknown error'}, error code: ${rawError.result || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.interfaces.ts b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.interfaces.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.interfaces.ts
rename to project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.interfaces.ts
diff --git a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.module.ts b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.module.ts
similarity index 75%
rename from project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.module.ts
rename to project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.module.ts
index ed84b011..1ebc03dd 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.module.ts
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'
-import { KwaiApiService } from './kwaiApi.service'
+import { KwaiApiService } from './kwai.service'
@Module({
imports: [],
diff --git a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.service.ts
similarity index 62%
rename from project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.service.ts
rename to project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.service.ts
index e58208fd..a820b65e 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.service.ts
@@ -1,7 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
-import { chunkedDownloadFile, fileUrlToBase64, getRemoteFileSize } from '../../common'
import { config } from '../../config'
+import { KwaiError } from './kwai.exception'
import {
KwaiAccessTokenQuery,
KwaiApiResponse,
@@ -19,15 +19,14 @@ import {
KwaiUserInfoResponse,
KwaiVideoListResponse,
KwaiVideoPubParams,
- KwaiVideoPubResult,
KwaiVideoUploadResponse,
-} from './kwaiApi.interfaces'
+} from './kwai.interfaces'
@Injectable()
export class KwaiApiService {
private readonly appId: string
private readonly appSecret: string
- private readonly redirectUri
+ private readonly redirectUri: string
private readonly kwaiAPIHost = 'https://open.kuaishou.com'
private readonly logger = new Logger(KwaiApiService.name)
@@ -38,20 +37,32 @@ export class KwaiApiService {
this.redirectUri = cfg.authBackHost
}
- private async request<T>(url: string, config: AxiosRequestConfig = {}): Promise<KwaiApiResponse<T>> {
+ private async request<T>(
+ url: string,
+ config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
+ ): Promise<KwaiApiResponse<T>> {
+ const operation = options.operation || `${config.method || 'GET'} ${url}`
this.logger.log(`Kwai API Request:${config.method || 'GET'} ${url} with params: ${JSON.stringify(config.params)}`)
try {
const response: AxiosResponse<KwaiApiResponse<T>> = await axios(url, config)
const data = response.data
+ this.logger.log(`Kwai API Response:${config.method || 'GET'} ${url} status=${response.status} data=${JSON.stringify(data)}`)
if (typeof data?.result === 'number' && data.result !== 1) {
- this.logger.error(`${config.method || 'GET'} ${url} failed, response: ${JSON.stringify(data)}`)
- throw new Error(data.error_msg || 'Kwai API business error')
+ throw KwaiError.buildFromResponse(data, operation, {
+ url,
+ method: config.method,
+ })
}
return data
}
catch (error: unknown) {
- this.logger.error(`Kwai API request failed (network): ${url}`, error)
- throw new Error('Kwai API network error')
+ const err = KwaiError.buildFromError(error, operation, {
+ url,
+ method: config.method,
+ })
+ this.logger.error(`Kwai API Error:${config.method || 'GET'} ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
}
}
@@ -67,7 +78,7 @@ export class KwaiApiService {
grant_type: 'refresh_token',
}
const url = `${this.kwaiAPIHost}/oauth2/refresh_token`
- return await this.request<KwaiOAuthCredentialsResponse>(url, { params })
+ return await this.request<KwaiOAuthCredentialsResponse>(url, { params }, { operation: 'refreshToken' })
}
/**
@@ -99,7 +110,7 @@ export class KwaiApiService {
grant_type: 'authorization_code',
}
const url = `${this.kwaiAPIHost}/oauth2/access_token`
- return await this.request<KwaiOAuthCredentialsResponse>(url, { method: 'POST', params })
+ return await this.request<KwaiOAuthCredentialsResponse>(url, { method: 'POST', params }, { operation: 'getLoginAccountToken' })
}
/**
@@ -112,7 +123,7 @@ export class KwaiApiService {
access_token: accessToken,
}
const url = `${this.kwaiAPIHost}/openapi/user_info`
- const data = await this.request<KwaiUserInfoResponse>(url, { params })
+ const data = await this.request<KwaiUserInfoResponse>(url, { params }, { operation: 'getAccountInfo' })
return data.user_info
}
@@ -126,7 +137,7 @@ export class KwaiApiService {
access_token: accessToken,
}
const url = `${this.kwaiAPIHost}/openapi/photo/start_upload`
- const data = await this.request<KwaiStartUploadResponse>(url, { method: 'POST', params })
+ const data = await this.request<KwaiStartUploadResponse>(url, { method: 'POST', params }, { operation: 'startUpload' })
this.logger.log(`Kwai video upload initialized: ${JSON.stringify(data)}`)
return data
}
@@ -146,12 +157,16 @@ export class KwaiApiService {
) {
const params: KwaiChunkedUploadQuery = { fragment_id, upload_token }
const url = `http://${endpoint}/api/upload/fragment`
- return await this.request<KwaiVideoUploadResponse>(url, {
- method: 'POST',
- params,
- headers: { 'Content-Type': 'application/octet-stream' },
- data: video,
- })
+ return await this.request<KwaiVideoUploadResponse>(
+ url,
+ {
+ method: 'POST',
+ params,
+ headers: { 'Content-Type': 'application/octet-stream' },
+ data: video,
+ },
+ { operation: 'fragmentUploadVideo' },
+ )
}
/**
@@ -167,7 +182,7 @@ export class KwaiApiService {
) {
const params: KwaiFinalizeUploadQuery = { fragment_count, upload_token }
const url = `http://${endpoint}/api/upload/complete`
- return await this.request<KwaiVideoUploadResponse>(url, { method: 'POST', params })
+ return await this.request<KwaiVideoUploadResponse>(url, { method: 'POST', params }, { operation: 'completeFragmentUpload' })
}
// 处理描述和话题,获取caption
@@ -195,87 +210,24 @@ export class KwaiApiService {
*/
async publishVideo(
accountToken: string,
- pubParams: KwaiVideoPubParams,
- ): Promise<KwaiVideoPubResult> {
- try {
- const { coverUrl, videoUrl } = pubParams
- this.logger.log(`start kwai video publish, videoUrl: ${videoUrl}, coverUrl: ${coverUrl}`)
- const startUploadInfo = await this.startUpload(accountToken)
- if (startUploadInfo.result !== 1)
- throw new Error('发起上传失败')
-
- const contentLength = await getRemoteFileSize(videoUrl)
- if (!contentLength) {
- throw new Error('get video meta failed')
- }
- let chunkSize = 5 * 1024 * 1024 // 5MB
- if (contentLength < chunkSize) {
- chunkSize = contentLength
- }
-
- const totalParts = Math.ceil(contentLength / chunkSize)
- for (let partNumber = 0; partNumber < totalParts; partNumber++) {
- const start = partNumber * chunkSize
- const end = Math.min(start + chunkSize - 1, contentLength - 1)
- const range: [number, number] = [start, end]
- const videoBlob = await chunkedDownloadFile(videoUrl, range)
- if (!videoBlob) {
- throw new Error('download video chunk failed')
- }
-
- const uploadResult = await this.fragmentUploadVideo(
- startUploadInfo.upload_token,
- partNumber,
- startUploadInfo.endpoint,
- videoBlob,
- )
- this.logger.log(`chunked upload complete: ${JSON.stringify(uploadResult)}`)
- }
-
- const finalizeUploadRes = await this.completeFragmentUpload(
- startUploadInfo.upload_token,
- totalParts,
- startUploadInfo.endpoint,
- )
- if (finalizeUploadRes.result !== 1)
- throw new Error('finalize video upload failed')
-
- this.logger.log('Video upload complete, proceed to publish')
- // 获取封面
- const coverBase64 = await fileUrlToBase64(coverUrl)
- const buffer = Buffer.from(coverBase64, 'base64')
- const coverBlob = new Blob([buffer], { type: 'image/jpeg' })
- this.logger.log('Cover image fetched and converted to Blob')
-
- const formData = new FormData()
- formData.append('caption', this.getCaption(pubParams))
- formData.append('cover', coverBlob)
- const params: KwaiPublishVideoQuery = {
- upload_token: startUploadInfo.upload_token,
- app_id: this.appId,
- access_token: accountToken,
- }
- const publishUrl = `${this.kwaiAPIHost}/openapi/photo/publish`
- const pubRes = await this.request<KwaiPublishVideoResponse>(publishUrl, {
- method: 'POST',
- params,
- data: formData,
- })
- this.logger.log(`Kwai video publish response: ${JSON.stringify(pubRes)}`)
- if (pubRes.result !== 1)
- throw new Error('视频发布失败!')
- return {
- success: true,
- worksId: pubRes.video_info.photo_id,
- }
- }
- catch (e) {
- this.logger.error(e)
- return {
- success: false,
- failMsg: e.message || '视频发布失败',
- }
+ caption: string,
+ thumbnail: Blob,
+ uploadToken: string,
+ ): Promise<KwaiPublishVideoResponse> {
+ const formData = new FormData()
+ formData.append('caption', caption)
+ formData.append('cover', thumbnail)
+ const params: KwaiPublishVideoQuery = {
+ upload_token: uploadToken,
+ app_id: this.appId,
+ access_token: accountToken,
}
+ const publishUrl = `${this.kwaiAPIHost}/openapi/photo/publish`
+ return await this.request<KwaiPublishVideoResponse>(publishUrl, {
+ method: 'POST',
+ params,
+ data: formData,
+ }, { operation: 'publishVideo' })
}
/**
@@ -292,7 +244,7 @@ export class KwaiApiService {
...(count ? { count } : {}),
}
const url = `${this.kwaiAPIHost}/openapi/photo/list`
- const data = await this.request<KwaiVideoListResponse>(url, { params })
+ const data = await this.request<KwaiVideoListResponse>(url, { params }, { operation: 'fetchVideoList' })
if (!data.video_list)
throw new Error('快手获取快手视频列表失败')
return data.video_list
@@ -305,7 +257,7 @@ export class KwaiApiService {
photo_id: videoId,
}
const url = `${this.kwaiAPIHost}/openapi/photo/delete`
- const data = await this.request<KwaiDeleteVideoResponse>(url, { method: 'POST', data: body })
+ const data = await this.request<KwaiDeleteVideoResponse>(url, { method: 'POST', data: body }, { operation: 'deleteVideo' })
if (!data.result)
throw new Error('快手删除视频失败')
return data.result
diff --git a/project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.spec.ts b/project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.spec.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/libs/kwai/kwaiApi.spec.ts
rename to project/backend/apps/aitoearn-channel/src/libs/kwai/kwai.spec.ts
diff --git a/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.exception.ts
new file mode 100644
index 00000000..b0cbcfa5
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.exception.ts
@@ -0,0 +1,55 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface LinkedInRawError {
+ message?: string
+ serviceErrorCode?: number
+ status?: number
+}
+
+/**
+ * LinkedIn error class.
+ */
+export class LinkedInError extends SocialMediaError<LinkedInRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: LinkedInRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'linkedin'
+ }
+
+ protected static override extractRawError(data: unknown): LinkedInRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as LinkedInRawError
+ return errResponse
+ }
+
+ protected static override buildMessage(
+ rawError: LinkedInRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.message || 'Unknown error'}, error code: ${rawError.serviceErrorCode || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.service.ts b/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.service.ts
index 2b14b804..f1a1c1f7 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/linkedin/linkedin.service.ts
@@ -1,8 +1,9 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { config } from '../../config'
-import { OAuth2Credential } from '../../core/plat/meta/meta.interfaces'
+import { OAuth2Credential } from '../../core/platforms/meta/meta.interfaces'
import { LinkedinOAuth2Config } from './constants'
+import { LinkedInError } from './linkedin.exception'
import { LinkedInShareRequest, LinkedInUploadRequest, LinkedInUploadResponse } from './linkedin.interface'
@Injectable()
@@ -13,6 +14,25 @@ export class LinkedinService {
private readonly refreshAccessToken: string = LinkedinOAuth2Config.refreshTokenURL
private readonly apiBaseUrl: string = LinkedinOAuth2Config.apiBaseUrl
+ private async request<T = unknown>(
+ url: string,
+ config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
+ ): Promise<T> {
+ const operation = options.operation || 'LinkedIn request'
+ this.logger.debug(`[LinkedIn:${operation}] Request -> ${url} ${config.method || 'GET'} ${config.params ? `params=${JSON.stringify(config.params)}` : ''}`)
+ try {
+ const response: AxiosResponse<T> = await axios(url, config)
+ this.logger.debug(`[LinkedIn:${operation}] Response <- ${url} status=${response.status} data=${JSON.stringify(response.data)}`)
+ return response.data
+ }
+ catch (error: unknown) {
+ const err = LinkedInError.buildFromError(error, operation)
+ this.logger.error(`[LinkedIn:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
+ }
+ }
+
async refreshOAuthCredential(refresh_token: string) {
const params: Record<string, string> = {
grant_type: 'refresh_token',
@@ -20,11 +40,18 @@ export class LinkedinService {
client_id: this.clientId,
client_secret: this.clientSecret,
}
-
- const refreshTokenReqParams = new URLSearchParams(params)
- const tokenResponse: AxiosResponse<OAuth2Credential>
- = await axios.post(this.refreshAccessToken, refreshTokenReqParams)
- return tokenResponse.data
+ const config: AxiosRequestConfig = {
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ params: new URLSearchParams(params),
+ method: 'POST',
+ }
+ return this.request<OAuth2Credential>(
+ this.refreshAccessToken,
+ config,
+ { operation: 'refreshOAuthCredential' },
+ )
}
async initMediaUpload(accessToken: string, req: LinkedInUploadRequest): Promise<LinkedInUploadResponse> {
@@ -35,20 +62,14 @@ export class LinkedinService {
'Content-type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0',
},
+ method: 'POST',
+ data: req,
}
- try {
- const response: AxiosResponse<LinkedInUploadResponse> = await axios.post(url, req, config)
- const data = response.data
- this.logger.log(`Init upload response: ${JSON.stringify(data)}`)
- return data
- }
- catch (error) {
- if (error.response) {
- this.logger.error(`Error init upload: ${error.response.status} - ${JSON.stringify(error.response.data)}`)
- }
- this.logger.error(`Error init upload: ${error.message}`)
- throw new Error(`Error init upload: ${error.message}`)
- }
+ return this.request<LinkedInUploadResponse>(
+ url,
+ config,
+ { operation: 'initMediaUpload' },
+ )
}
async streamUpload(accessToken: string, src: string, dest: string) {
@@ -57,26 +78,15 @@ export class LinkedinService {
'Authorization': `Bearer ${accessToken}`,
'Content-type': 'application/octet-stream',
},
+ method: 'POST',
}
- this.logger.log(`Upload URL: ${dest}`)
- try {
- const dlStream = await axios.get(src, { responseType: 'stream' })
- const response = await axios.post(
- dest,
- dlStream.data,
- config,
- )
- const data = response.data
- this.logger.log(`Reel upload response: ${JSON.stringify(data)}`)
- return data
- }
- catch (error) {
- if (error.response) {
- this.logger.error(`Error uploading reel: ${error.response.status} - ${JSON.stringify(error.response.data)}`)
- }
- this.logger.error(`Error uploading reel: ${error.message}`)
- throw new Error(`Error uploading reel: ${error.message}`)
- }
+ const dlStream = await axios.get(src, { responseType: 'stream' })
+ config.data = dlStream.data
+ return this.request<void>(
+ dest,
+ config,
+ { operation: 'streamUpload' },
+ )
}
async createShare(accessToken: string, req: LinkedInShareRequest) {
@@ -87,25 +97,27 @@ export class LinkedinService {
'Content-type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0',
},
+ method: 'POST',
+ data: req,
}
try {
- const response: AxiosResponse = await axios.post(url, req, config)
- if (response.status !== 201) {
- throw new Error(`Unexpected response status: ${response.status}`)
- }
+ const response = await axios.post(url, req, config)
const shareId: string = response.headers['x-restli-id']
if (!shareId) {
- throw new Error('Missing x-restli-id header in response')
+ throw LinkedInError.buildFromResponse(
+ response,
+ 'createShare',
+ )
}
this.logger.log(`Create share response: ${JSON.stringify(response.data)}, shareId: ${shareId}`)
return shareId
}
catch (error) {
- if (error.response) {
- this.logger.error(`Error creating share: ${error.response.status} - ${JSON.stringify(error.response.data)}`)
- }
- this.logger.error(`Error creating share: ${error.message}`)
- throw new Error(`Error creating share: ${error.message}`)
+ throw LinkedInError.buildFromError(
+ error,
+ 'createShare',
+ { url, method: 'POST' },
+ )
}
}
@@ -117,21 +129,12 @@ export class LinkedinService {
'Content-type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0',
},
+ method: 'DELETE',
}
- try {
- const response: AxiosResponse = await axios.delete(url, config)
- if (response.status !== 204) {
- throw new Error(`Unexpected response status: ${response.status}`)
- }
- this.logger.log(`Delete share response: ${JSON.stringify(response.data)}, shareId: ${shareId}`)
- return shareId
- }
- catch (error) {
- if (error.response) {
- this.logger.error(`Error deleting share: ${error.response.status} - ${JSON.stringify(error.response.data)}`)
- }
- this.logger.error(`Error deleting share: ${error.message}`)
- throw new Error(`Error deleting share: ${error.message}`)
- }
+ return this.request<void>(
+ url,
+ config,
+ { operation: 'deletePost' },
+ )
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/comment.ts b/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/comment.ts
similarity index 100%
rename from project/backend/apps/aitoearn-channel/src/libs/myWxPlat/comment.ts
rename to project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/comment.ts
diff --git a/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.module.ts b/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.module.ts
similarity index 74%
rename from project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.module.ts
rename to project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.module.ts
index daafe7fc..1be6cb71 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.module.ts
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'
-import { MyWxPlatApiService } from './myWxPlatApi.service'
+import { MyWxPlatApiService } from './my-wx-plat.service'
@Module({
imports: [],
diff --git a/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.service.ts b/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.service.ts
new file mode 100644
index 00000000..4a104fd8
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/my-wx-plat/my-wx-plat.service.ts
@@ -0,0 +1,131 @@
+/*
+ * @Author: nevin
+ * @Date: 2025-02-15 20:59:55
+ * @LastEditTime: 2025-04-27 17:58:21
+ * @LastEditors: nevin
+ * @Description: MyWxPlat
+ */
+import { Injectable, Logger } from '@nestjs/common'
+import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
+import { config } from '../../config'
+import { WxGZHError } from '../wx-gzh/wx-gzh.exception'
+import { WxPlatAuthorizerInfo } from './comment'
+
+@Injectable()
+export class MyWxPlatApiService {
+ private id = ''
+ private secret = ''
+ private hostUrl = ''
+ private readonly logger = new Logger(MyWxPlatApiService.name)
+ constructor() {
+ const cfg = config.myWxPlat
+ this.id = cfg.id
+ this.secret = cfg.secret
+ this.hostUrl = cfg.hostUrl
+ }
+
+ private async request<T = unknown>(
+ url: string,
+ config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
+ ): Promise<T> {
+ if (!config.headers) {
+ config.headers = {
+ 'Content-Type': 'application/json',
+ 'secret': this.secret,
+ }
+ }
+ const operation = options.operation || 'myWxPlat request'
+ this.logger.debug(`[myWxPlat:${operation}] Request -> ${url} ${config.method || 'GET'} ${config.params ? `params=${JSON.stringify(config.params)}` : ''}`)
+ try {
+ const response: AxiosResponse<T> = await axios(url, config)
+ this.logger.debug(`[myWxPlat:${operation}] Response <- ${url} status=${response.status} data=${JSON.stringify(response.data)}`)
+ return response.data
+ }
+ catch (error: unknown) {
+ const err = WxGZHError.buildFromError(error, operation)
+ this.logger.error(`[myWxPlat:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
+ }
+ }
+
+ /**
+ * 获取授权链接
+ * @param type
+ * @param stat 透传数据
+ * @returns
+ */
+ async getAuthPageUrl(type: 'h5' | 'pc', stat?: string) {
+ const url = `${this.hostUrl}/wxPlat/auth/url?type=${type}&key=${this.id}&stat=${stat}`
+ return this.request<{
+ data: string
+ code: string
+ messgage: string
+ }>(url, { method: 'GET' }, { operation: 'getAuthPageUrl' })
+ }
+
+ /**
+ * 使用获取授权
+ * @param authorizationCode
+ * @returns
+ */
+ async getQueryAuth(authorizationCode: string) {
+ const url = `${this.hostUrl}/wxPlat/queryAuth/${authorizationCode}`
+ return this.request<WxPlatAuthorizerInfo>(url, { method: 'GET' }, { operation: 'getQueryAuth' })
+ }
+
+ /**
+ * 使用授权码获取授权信息
+ * @param authorizerAppid
+ * @returns
+ */
+ async getAuthorizerInfo(authorizerAppid: string) {
+ const url = `${this.hostUrl}/wxPlat/authorizer/info/${authorizerAppid}`
+ return this.request<{
+ nick_name: string
+ user_name: string
+ head_img: string
+ }>(url, { method: 'GET' }, { operation: 'getAuthorizerInfo' })
+ }
+
+ /**
+ * 刷新用户的authorizer_access_token
+ * @param authorizerAppId 用的应用的appid
+ * @param authorizerRefreshToken 刷新token
+ * @returns
+ */
+ async getAuthorizerAccessToken(
+ authorizerAppId: string,
+ authorizerRefreshToken: string,
+ ) {
+ const url = `${this.hostUrl}/wxPlat/authorizerAccessToken`
+ const config: AxiosRequestConfig = {
+ method: 'GET',
+ params: { authorizerAppId, authorizerRefreshToken },
+ }
+ return this.request<any>(url, config, { operation: 'getAuthorizerAccessToken' })
+ }
+
+ /**
+ * 获取用户的授权信息
+ * @param componentAccessToken
+ * @param authorizationCode
+ * @returns
+ */
+ async setUserAppAccessTokenInfo(
+ componentAccessToken: string,
+ authorizationCode: string,
+ ) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?access_token==${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ authorization_code: authorizationCode,
+ },
+ }
+ return this.request<{
+ authorization_info: WxPlatAuthorizerInfo
+ }>(url, config, { operation: 'setUserAppAccessTokenInfo' })
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.service.ts
deleted file mode 100644
index c913218b..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/myWxPlat/myWxPlatApi.service.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * @Author: nevin
- * @Date: 2025-02-15 20:59:55
- * @LastEditTime: 2025-04-27 17:58:21
- * @LastEditors: nevin
- * @Description: MyWxPlat
- */
-import { Injectable, Logger } from '@nestjs/common'
-import axios from 'axios'
-import { config } from '../../config'
-import { WxPlatAuthorizerInfo } from './comment'
-
-@Injectable()
-export class MyWxPlatApiService {
- private id = ''
- private secret = ''
- private hostUrl = ''
- private readonly logger = new Logger(MyWxPlatApiService.name)
- constructor() {
- const cfg = config.myWxPlat
- this.id = cfg.id
- this.secret = cfg.secret
- this.hostUrl = cfg.hostUrl
- }
-
- /**
- * 获取授权链接
- * @param type
- * @param stat 透传数据
- * @returns
- */
- async getAuthPageUrl(type: 'h5' | 'pc', stat?: string) {
- try {
- const result = await axios.get<{
- data: string
- code: string
- messgage: string
- }>(
- `${this.hostUrl}/wxPlat/auth/url?type=${type}&key=${this.id}&stat=${stat}`,
- {
- headers: {
- 'Content-Type': 'application/json',
- 'secret': this.secret,
- },
- },
- )
- if (result.data.code)
- throw new Error(result.data.messgage)
-
- return result.data.data
- }
- catch (error) {
- this.logger.error('------ Error wxPlat getAuthPageUrl: ------', error)
- return null
- }
- }
-
- /**
- * 使用获取授权
- * @param authorizationCode
- * @returns
- */
- async getQueryAuth(authorizationCode: string) {
- try {
- const result = await axios.get<{
- data: WxPlatAuthorizerInfo
- code: string
- messgage: string
- }
-
- >(
- `${this.hostUrl}/wxPlat/queryAuth/${authorizationCode}`,
- {
- headers: {
- 'Content-Type': 'application/json',
- 'secret': this.secret,
- },
- },
- )
- if (result.data.code)
- throw new Error(result.data.messgage)
-
- return result.data.data
- }
- catch (error) {
- this.logger.error('------ Error wxPlat getQueryAuth: ------', error)
- return null
- }
- }
-
- /**
- * 使用授权码获取授权信息
- * @param authorizerAppid
- * @returns
- */
- async getAuthorizerInfo(authorizerAppid: string) {
- try {
- const result = await axios.get(
- `${this.hostUrl}/wxPlat/authorizer/info/${authorizerAppid}`,
- {
- headers: {
- 'Content-Type': 'application/json',
- 'secret': this.secret,
- },
- },
- )
-
- if (result.data.code)
- throw new Error(result.data.messgage)
-
- return result.data.data
- }
- catch (error) {
- this.logger.error('------ Error wxPlat getAuthorizerInfo: ------', error)
- return null
- }
- }
-
- /**
- * 刷新用户的authorizer_access_token
- * @param componentAccessToken
- * @param appId 用的应用的appid
- * @param authorizerRefreshToken 刷新token
- * @returns
- */
- async getAuthorizerAccessToken(
- authorizerAppId: string,
- authorizerRefreshToken: string,
- ) {
- try {
- const result = await axios.get(
- `${this.hostUrl}/wxPlat/authorizerAccessToken`,
- {
- headers: {
- 'Content-Type': 'application/json',
- 'secret': this.secret,
- },
- params: { authorizerAppId, authorizerRefreshToken },
- },
- )
-
- if (result.data.code)
- throw new Error(result.data.messgage)
-
- return result.data.data
- }
- catch (error) {
- this.logger.error(
- '------ Error wxPlat getAuthorizerAccessToken: ------',
- error,
- )
-
- return null
- }
- }
-
- /**
- * 获取用户的授权信息
- * @param userId
- * @param authorizationCode
- * @returns
- */
- async setUserAppAccessTokenInfo(
- componentAccessToken: string,
- authorizationCode: string,
- ) {
- try {
- const result = await axios.post<{
- authorization_info: WxPlatAuthorizerInfo
- errcode?: number
- errmsg?: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?access_token==${componentAccessToken}`,
- {
- component_appid: this.id,
- authorization_code: authorizationCode,
- },
- )
- if (result.data.errcode)
- throw new Error(result.data.errcode + (result.data.errmsg || ''))
- return result.data
- }
- catch (error) {
- this.logger.log('Error setUserAppAccessTokenInfo :', error)
- return null
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/pinterest/common.ts b/project/backend/apps/aitoearn-channel/src/libs/pinterest/common.ts
index 1f3d6d7a..7b9cec09 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/pinterest/common.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/pinterest/common.ts
@@ -22,7 +22,7 @@ export interface CreateBoardBody {
}
export interface CreatePinBody {
- link: string // 点击链接;
+ link?: string // 点击链接;
title?: string // 标题
description?: string // 描述
dominant_color?: string // RGB表示的颜色 主引脚颜色。十六进制数,例如“#6E7874”。
diff --git a/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest-api.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest-api.exception.ts
deleted file mode 100644
index 2df598bc..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest-api.exception.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { AxiosError } from 'axios'
-
-export interface PinterestRawError {
- // Pinterest error payload shape may vary by endpoint; keep flexible
- // Docs: https://developers.pinterest.com/docs/api/v5/
- message?: string
- code?: number | string
- type?: string
- status?: number
-}
-
-export interface NormalizedPinterestError {
- status?: number
- raw?: unknown
- isNetwork: boolean
- isAxios: boolean
- original: unknown
-}
-
-export interface PinterestApiExceptionMeta {
- url?: string
- method?: string
- operation?: string
- attempt?: number
- extra?: Record<string, unknown>
-}
-
-export class PinterestApiException extends Error {
- readonly operation: string
- readonly normalized: NormalizedPinterestError
- readonly meta?: PinterestApiExceptionMeta
-
- constructor(
- operation: string,
- normalized: NormalizedPinterestError,
- meta?: PinterestApiExceptionMeta,
- ) {
- super(PinterestApiException.buildMessage(operation, normalized))
- this.name = 'PinterestApiException'
- this.operation = operation
- this.normalized = normalized
- this.meta = meta
- }
-
- static buildMessage(op: string, n: NormalizedPinterestError): string {
- // Attempt to derive message from common Pinterest error shapes
- const raw = n.raw as { message?: string, code?: number | string } | undefined
- if (raw?.message) {
- return `${op} failed: ${raw.message}${raw.code ? ` (code=${raw.code})` : ''}`
- }
- if (n.isNetwork)
- return `${op} failed: network error`
- return `${op} failed: unexpected error`
- }
-
- toJSON() {
- return {
- name: this.name,
- message: this.message,
- operation: this.operation,
- status: this.normalized.status,
- meta: this.meta,
- }
- }
-
- static fromAxiosError(
- operation: string,
- error: AxiosError,
- meta?: PinterestApiExceptionMeta,
- ): PinterestApiException {
- const normalized: NormalizedPinterestError = {
- status: error.response?.status,
- raw: error.response?.data,
- isNetwork: !!error.isAxiosError && !error.response,
- isAxios: true,
- original: error,
- }
- return new PinterestApiException(operation, normalized, meta)
- }
-}
-
-export function normalizePinterestError(e: unknown): NormalizedPinterestError {
- const err = e as { isAxiosError?: boolean, response?: { status?: number, data?: unknown } }
- const isAxios = !!err?.isAxiosError
- return {
- status: err?.response?.status,
- raw: err?.response?.data,
- isNetwork: isAxios && !err?.response,
- isAxios,
- original: e,
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest.exception.ts
new file mode 100644
index 00000000..00b2edeb
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterest.exception.ts
@@ -0,0 +1,54 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface PinterestRawError {
+ message?: string
+ code?: number | string
+}
+
+/**
+ * Pinterest error class.
+ */
+export class PinterestError extends SocialMediaError<PinterestRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: PinterestRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'pinterest'
+ }
+
+ protected static override extractRawError(data: unknown): PinterestRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as PinterestRawError
+ return errResponse
+ }
+
+ protected static override buildMessage(
+ rawError: PinterestRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.message || 'Unknown error'}, error code: ${rawError.code || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterestApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterestApi.service.ts
index 33058acf..8d098957 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterestApi.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/pinterest/pinterestApi.service.ts
@@ -11,7 +11,7 @@ import qs from 'qs'
import { config } from '../../config'
import { CreateBoardBody, CreatePinBody } from './common'
import { PinterestAPIConfig } from './constants'
-import { normalizePinterestError, PinterestApiException } from './pinterest-api.exception'
+import { PinterestError } from './pinterest.exception'
import { PinterestBoard, PinterestBoardsListResponse, PinterestInitMediaUploadResponse, PinterestOAuthCredential, PinterestPin, PinterestPinsListResponse, PinterestUserAccount } from './pinterest.interfaces'
import { PinterestOperation } from './pinterest.operations'
@@ -40,11 +40,9 @@ export class PinterestApiService {
return response.data
}
catch (error: unknown) {
- const normalized = normalizePinterestError(error)
- const status = normalized.status
- const message = (normalized.raw as { message?: string } | undefined)?.message || (error as Error)?.message
- this.logger.error(`[PIN:${operation}] Failed url=${url} status=${status} msg=${message}`)
- throw new PinterestApiException(operation, normalized, { url, method: config.method })
+ const err = PinterestError.buildFromError(error, operation)
+ this.logger.error(`[PIN:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/threads/threads.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.exception.ts
new file mode 100644
index 00000000..62081a7f
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.exception.ts
@@ -0,0 +1,59 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface ThreadsRawError {
+ message: string
+ type: string
+ code: number
+ fbtrace_id?: string
+ error_subcode?: number
+ error_user_title?: string
+ error_user_msg?: string
+}
+
+/**
+ * Threads error class.
+ */
+export class ThreadsError extends SocialMediaError<ThreadsRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: ThreadsRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'threads'
+ }
+
+ protected static override extractRawError(data: unknown): ThreadsRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as { error?: ThreadsRawError }
+ return errResponse.error
+ }
+
+ protected static override buildMessage(
+ rawError: ThreadsRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.error_user_title || rawError.message}, error code: ${rawError.code}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/threads/threads.interfaces.ts b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.interfaces.ts
index 15e0b536..751f7b6d 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/threads/threads.interfaces.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.interfaces.ts
@@ -26,6 +26,7 @@ export interface ThreadsPostResponse {
export interface ThreadsObjectInfo {
id: string
status: string
+ permalink?: string
}
export interface ThreadsInsightsRequest {
diff --git a/project/backend/apps/aitoearn-channel/src/libs/threads/threads.service.ts b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.service.ts
index e132868e..d1791311 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/threads/threads.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/threads/threads.service.ts
@@ -1,7 +1,8 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
-import { MetaOAuthLongLivedCredential } from '../../core/plat/meta/meta.interfaces'
+import { MetaOAuthLongLivedCredential } from '../../core/platforms/meta/meta.interfaces'
import { ThreadsOAuth2Config } from './constants'
+import { ThreadsError } from './threads.exception'
import {
publicProfileResponse,
ThreadsContainerRequest,
@@ -28,30 +29,25 @@ export class ThreadsService {
private async request<T = unknown>(
url: string,
config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
): Promise<T> {
+ const operation = options.operation || 'threads request'
this.logger.debug(
- `Threads API Request: ${url}`,
+ `[THREADS:${operation}] Request -> ${url} ${config.method || 'GET'} ${config.params ? `params=${JSON.stringify(config.params)}` : ''}`,
)
try {
const response: AxiosResponse<T> = await axios(url, config)
+ this.logger.debug(
+ `[THREADS:${operation}] Response <- ${url} status=${response.status} data=${JSON.stringify(response.data)}`,
+ )
return response.data
}
catch (error) {
- if (error.response) {
- this.logger.error(
- `Threads API request failed: ${url}, status: ${error.response.status}, data: ${JSON.stringify(error.response.data)}`,
- )
- if (error.response.data?.error) {
- const { error_user_title, message, code, error_subcode } = error.response.data.error
- const errMsg = `Threads API request failed: ${error_user_title || message} status=${error.response.status} code=${code} sub=${error_subcode}`
- throw new Error(errMsg)
- }
- else {
- throw new Error('Threads API request failed: An unknown error occurred')
- }
- }
- this.logger.error(`Threads API request failed: ${url}`, error)
- throw new Error(`Threads API request failed: ${error.message}`)
+ const err = ThreadsError.buildFromError(error, operation)
+ this.logger.error(
+ `[THREADS:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`,
+ )
+ throw err
}
}
@@ -66,6 +62,7 @@ export class ThreadsService {
return await this.request<MetaOAuthLongLivedCredential>(
this.longLivedAccessTokenURL,
config,
+ { operation: 'refreshOAuthCredential' },
)
}
@@ -94,7 +91,7 @@ export class ThreadsService {
data: formData,
}
- return await this.request<ThreadsPostResponse>(url, config)
+ return await this.request<ThreadsPostResponse>(url, config, { operation: 'createItemContainer' })
}
async publishPost(
@@ -109,7 +106,7 @@ export class ThreadsService {
Authorization: `Bearer ${accessToken}`,
},
}
- return await this.request<ThreadsPostResponse>(url, config)
+ return await this.request<ThreadsPostResponse>(url, config, { operation: 'publishPost' })
}
async getObjectInfo(
@@ -127,7 +124,7 @@ export class ThreadsService {
if (fields) {
config.params = { fields }
}
- return await this.request<ThreadsObjectInfo>(url, config)
+ return await this.request<ThreadsObjectInfo>(url, config, { operation: 'getObjectInfo' })
}
async getAccountInsights(
@@ -143,7 +140,7 @@ export class ThreadsService {
},
params: query,
}
- return await this.request<ThreadsInsightsResponse>(url, config)
+ return await this.request<ThreadsInsightsResponse>(url, config, { operation: 'getAccountInsights' })
}
async getPublicProfile(
@@ -158,7 +155,7 @@ export class ThreadsService {
},
params: { username },
}
- return await this.request<publicProfileResponse>(url, config)
+ return await this.request<publicProfileResponse>(url, config, { operation: 'getPublicProfile' })
}
async getMediaInsights(
@@ -174,7 +171,7 @@ export class ThreadsService {
},
params: query,
}
- return await this.request<ThreadsInsightsResponse>(url, config)
+ return await this.request<ThreadsInsightsResponse>(url, config, { operation: 'getMediaInsights' })
}
async getAccountAllPosts(
@@ -190,7 +187,7 @@ export class ThreadsService {
},
params: query,
}
- return await this.request<ThreadsPostsResponse>(url, config)
+ return await this.request<ThreadsPostsResponse>(url, config, { operation: 'getAccountAllPosts' })
}
async fetchObjectComments(
@@ -206,7 +203,7 @@ export class ThreadsService {
},
params: query,
}
- return await this.request<ThreadsObjectCommentsResponse>(url, config)
+ return await this.request<ThreadsObjectCommentsResponse>(url, config, { operation: 'fetchObjectComments' })
}
async searchLocations(
@@ -223,7 +220,7 @@ export class ThreadsService {
q: query.query,
},
}
- return await this.request<ThreadsSearchLocationResponse>(url, config)
+ return await this.request<ThreadsSearchLocationResponse>(url, config, { operation: 'searchLocations' })
}
async deletePost(
@@ -237,6 +234,6 @@ export class ThreadsService {
Authorization: `Bearer ${accessToken}`,
},
}
- await this.request<void>(url, config)
+ await this.request<void>(url, config, { operation: 'deletePost' })
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.exception.ts
new file mode 100644
index 00000000..f3d2b578
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.exception.ts
@@ -0,0 +1,54 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface TiktokRawError {
+ code?: number | string
+ message?: string
+}
+
+/**
+ * Tiktok error class.
+ */
+export class TiktokError extends SocialMediaError<TiktokRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: TiktokRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'tiktok'
+ }
+
+ protected static override extractRawError(data: unknown): TiktokRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as { error?: TiktokRawError }
+ return errResponse.error
+ }
+
+ protected static override buildMessage(
+ rawError: TiktokRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.message || 'Unknown error'}, error code: ${rawError.code || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.service.ts b/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.service.ts
index fca7135a..b02461b2 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/tiktok/tiktok.service.ts
@@ -8,6 +8,7 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { config } from '../../config'
+import { TiktokError } from './tiktok.exception'
import {
TiktokCreatorInfo,
TikTokListVideosParams,
@@ -45,7 +46,9 @@ export class TiktokService {
url: string,
options: AxiosRequestConfig = {},
accessToken?: string,
+ operation?: string,
): Promise<T> {
+ const method = (options.method || 'GET').toUpperCase()
try {
const config: AxiosRequestConfig = {
...options,
@@ -65,13 +68,11 @@ export class TiktokService {
return response.data
}
catch (error) {
- if (error.response) {
- this.logger.error(`TikTok API request failed: ${url}, status: ${error.response.status}, data: ${JSON.stringify(error.response.data)}`)
- const errMsg = error.response.error?.message || `TikTok API request failed: ${url}, status: ${error.response.status}`
- throw new Error(errMsg)
- }
- this.logger.error(`TikTok API request failed: ${url}, error: ${error}`)
- throw new Error(`TikTok API request failed: ${url}, error: ${error}`)
+ const err = TiktokError.buildFromError(error, operation)
+ this.logger.error(
+ `[TIKTOK:${operation || 'apiRequest'}] Error !! ${method} ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`,
+ )
+ throw err
}
}
@@ -81,6 +82,7 @@ export class TiktokService {
private async oauthRequest<T = unknown>(
url: string,
data: Record<string, string>,
+ operation: string,
): Promise<T> {
return this.apiRequest<T>(url, {
method: 'POST',
@@ -88,7 +90,7 @@ export class TiktokService {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
- })
+ }, undefined, operation)
}
/**
@@ -98,6 +100,7 @@ export class TiktokService {
url: string,
data: unknown,
accessToken: string,
+ operation: string,
): Promise<T> {
const response = await this.apiRequest<{ data: T }>(
url,
@@ -106,6 +109,7 @@ export class TiktokService {
data,
},
accessToken,
+ operation,
)
return response.data
}
@@ -138,6 +142,7 @@ export class TiktokService {
grant_type: 'authorization_code',
redirect_uri: this.redirectUri,
},
+ 'getAccessToken',
)
}
@@ -153,6 +158,7 @@ export class TiktokService {
grant_type: 'refresh_token',
refresh_token: refreshToken,
},
+ 'refreshAccessToken',
)
}
@@ -167,6 +173,7 @@ export class TiktokService {
client_secret: this.clientSecret,
token: accessToken,
},
+ 'revokeAccessToken',
)
}
@@ -181,6 +188,7 @@ export class TiktokService {
},
},
accessToken,
+ 'getUserInfo',
)
}
@@ -192,6 +200,7 @@ export class TiktokService {
`${this.apiBaseUrl}/post/publish/creator_info/query/`,
{},
accessToken,
+ 'getCreatorInfo',
)
}
@@ -206,6 +215,7 @@ export class TiktokService {
`${this.apiBaseUrl}/post/publish/inbox/video/init/`,
publishRequest,
accessToken,
+ 'initVideoPublish',
)
}
@@ -220,6 +230,7 @@ export class TiktokService {
`${this.apiBaseUrl}/post/publish/content/init/`,
publishRequest,
accessToken,
+ 'initPhotoPublish',
)
}
@@ -234,6 +245,7 @@ export class TiktokService {
`${this.apiBaseUrl}/post/publish/status/fetch/`,
{ publish_id: publishId },
accessToken,
+ 'getPublishStatus',
)
}
@@ -254,7 +266,7 @@ export class TiktokService {
'Content-Type': contentType,
'Content-Range': `bytes 0-${fileSize - 1}/${fileSize}`,
},
- })
+ }, undefined, 'uploadVideoFile')
}
/**
@@ -275,7 +287,7 @@ export class TiktokService {
'Content-Length': videoBuffer.length,
'Content-Range': `bytes ${range[0]}-${range[1]}/${fileSize}`,
},
- })
+ }, undefined, 'chunkedUploadVideoFile')
}
/**
@@ -309,16 +321,16 @@ export class TiktokService {
): Promise<TikTokListVideosResponse> {
const url = `${this.apiBaseUrl}/video/list/`
const config: AxiosRequestConfig = {
+ method: 'POST',
params: { fields: query?.fields },
headers: {
'Content-Type': 'application/json; charset=UTF-8',
- 'Authorization': `Bearer ${accessToken}`,
+ },
+ data: {
+ cursor: query?.cursor,
+ max_count: query?.max_count,
},
}
- const resp = await axios.post<TikTokListVideosResponse>(url, {
- cursor: query?.cursor,
- max_count: query?.max_count,
- }, config)
- return resp.data
+ return await this.apiRequest<TikTokListVideosResponse>(url, config, accessToken, 'getUserVideos')
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.exception.ts
new file mode 100644
index 00000000..7afbf8fd
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.exception.ts
@@ -0,0 +1,59 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+/**
+ * Twitter API 原始错误格式
+ */
+export interface TwitterRawError {
+ title?: string
+ detail?: string
+ type?: string
+ status?: number
+}
+
+/**
+ * Twitter error class.
+ */
+export class TwitterError extends SocialMediaError<TwitterRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: TwitterRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'twitter'
+ }
+
+ protected static override extractRawError(data: unknown): TwitterRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as { errors?: TwitterRawError[] }
+ return errResponse.errors ? errResponse.errors[0] : undefined
+ }
+
+ protected static override buildMessage(
+ rawError: TwitterRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.title || rawError.detail || 'Unknown error'}, error code: ${rawError.type || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.service.ts b/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.service.ts
index c4160019..aa0cb0ec 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/twitter/twitter.service.ts
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { config } from '../../config'
+import { TwitterError } from './twitter.exception'
import {
TwitterFollowingResponse,
TwitterOAuthCredential,
@@ -48,35 +49,27 @@ export class TwitterService {
private async request<T = unknown>(
url: string,
config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
): Promise<T> {
+ const method = (config.method || 'GET').toUpperCase()
+ const operation = options.operation || `${method} ${url}`
this.logger.debug(
- `Twitter API Request: ${url}`,
+ `[twitter:${operation}] Request -> ${url} ${method}, params=${JSON.stringify(config.params)}`,
)
try {
const response: AxiosResponse<T> = await axios(url, config)
- const data = response.data
this.logger.debug(
- `Twitter API Response: ${url} with data: ${JSON.stringify(data)}`,
+ `[twitter:${operation}] Response -> ${url} ${method} ${JSON.stringify(response.data)}`,
)
+ const data = response.data
return data
}
catch (error) {
- if (error.response) {
- this.logger.error(
- `Twitter API request failed: ${url}, status: ${error.response.status}, data: ${JSON.stringify(error.response.data)}`,
- )
- const apiError = error.response.data
- let errMsg = `Twitter API request failed: ${url}`
- if (apiError?.title) {
- errMsg = `${apiError.title}: ${apiError.detail ?? 'No detail'}`
- }
- else if (apiError) {
- errMsg = `Twitter API Error: ${JSON.stringify(apiError)}`
- }
- throw new Error(errMsg)
- }
- this.logger.error(`Twitter API request failed: ${url}`, error)
- throw new Error(`Twitter API request failed, error: ${error.message}`)
+ const err = TwitterError.buildFromError(error, operation)
+ this.logger.error(
+ `[twitter:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`,
+ )
+ throw err
}
}
@@ -117,7 +110,7 @@ export class TwitterService {
headers: this.oAuthRequestHeader,
data: params.toString(),
}
- return await this.request<TwitterOAuthCredential>(url, config)
+ return await this.request<TwitterOAuthCredential>(url, config, { operation: 'getOAuthCredential' })
}
async refreshOAuthCredential(
@@ -135,7 +128,7 @@ export class TwitterService {
headers: this.oAuthRequestHeader,
data: params.toString(),
}
- return await this.request<TwitterOAuthCredential>(url, config)
+ return await this.request<TwitterOAuthCredential>(url, config, { operation: 'refreshOAuthCredential' })
}
async revokeOAuthCredential(
@@ -150,7 +143,7 @@ export class TwitterService {
method: 'POST',
data: params.toString(),
}
- return await this.request<TwitterRevokeAccessResponse>(url, config)
+ return await this.request<TwitterRevokeAccessResponse>(url, config, { operation: 'revokeOAuthCredential' })
}
async getUserInfo(accessToken: string): Promise<TwitterUserInfo> {
@@ -165,9 +158,8 @@ export class TwitterService {
'id,name,profile_image_url,username,verified,created_at,protected,public_metrics',
},
}
- return await this.request<TwitterUserInfoResponse>(url, config).then(
- res => res.data,
- )
+ const response = await this.request<TwitterUserInfoResponse>(url, config, { operation: 'getUserInfo' })
+ return response.data
}
async followUser(
@@ -185,7 +177,7 @@ export class TwitterService {
method: 'POST',
data: params.toString(),
}
- return await this.request<TwitterFollowingResponse>(url, config)
+ return await this.request<TwitterFollowingResponse>(url, config, { operation: 'followUser' })
}
async initMediaUpload(
@@ -201,7 +193,7 @@ export class TwitterService {
},
data: req,
}
- return await this.request<XMediaUploadResponse>(url, config)
+ return await this.request<XMediaUploadResponse>(url, config, { operation: 'initMediaUpload' })
}
async chunkedMediaUploadRequest(
@@ -220,7 +212,7 @@ export class TwitterService {
},
data: formData,
}
- return await this.request<XMediaUploadResponse>(url, config)
+ return await this.request<XMediaUploadResponse>(url, config, { operation: 'chunkedMediaUpload' })
}
async finalizeMediaUpload(
@@ -234,7 +226,7 @@ export class TwitterService {
Authorization: `Bearer ${accessToken}`,
},
}
- return await this.request<XMediaUploadResponse>(url, config)
+ return await this.request<XMediaUploadResponse>(url, config, { operation: 'finalizeMediaUpload' })
}
async createPost(
@@ -250,7 +242,7 @@ export class TwitterService {
},
data: tweet,
}
- return await this.request<XCreatePostResponse>(url, config)
+ return await this.request<XCreatePostResponse>(url, config, { operation: 'createPost' })
}
async deletePost(
@@ -264,7 +256,7 @@ export class TwitterService {
Authorization: `Bearer ${accessToken}`,
},
}
- return await this.request<XDeletePostResponse>(url, config)
+ return await this.request<XDeletePostResponse>(url, config, { operation: 'deletePost' })
}
async getUserPosts(
@@ -284,7 +276,7 @@ export class TwitterService {
'id,text,author_id,created_at,public_metrics,attachments,media_metadata',
},
}
- return await this.request<XUserTimelineResponse>(url, config)
+ return await this.request<XUserTimelineResponse>(url, config, { operation: 'getUserPosts' })
}
async getUserTimeline(
@@ -304,7 +296,7 @@ export class TwitterService {
'id,text,author_id,created_at,public_metrics,attachments',
},
}
- return await this.request<XUserTimelineResponse>(url, config)
+ return await this.request<XUserTimelineResponse>(url, config, { operation: 'getUserTimeline' })
}
async getPostDetail(
@@ -323,7 +315,7 @@ export class TwitterService {
'user.fields': 'id,name,username,profile_image_url,verified',
},
}
- return await this.request<XPostDetailResponse>(url, config)
+ return await this.request<XPostDetailResponse>(url, config, { operation: 'getPostDetail' })
}
async getMediaStatus(
@@ -340,7 +332,7 @@ export class TwitterService {
media_id: mediaId,
},
}
- return await this.request<XMediaUploadResponse>(url, config)
+ return await this.request<XMediaUploadResponse>(url, config, { operation: 'getMediaStatus' })
}
async repost(
@@ -357,7 +349,7 @@ export class TwitterService {
},
data: { tweet_id: tweetId },
}
- return await this.request<XRePostResponse>(url, config)
+ return await this.request<XRePostResponse>(url, config, { operation: 'repost' })
}
async unRepost(
@@ -372,7 +364,7 @@ export class TwitterService {
Authorization: `Bearer ${accessToken}`,
},
}
- return await this.request<XRePostResponse>(url, config)
+ return await this.request<XRePostResponse>(url, config, { operation: 'unRepost' })
}
async likePost(
@@ -389,7 +381,7 @@ export class TwitterService {
},
data: { tweet_id: tweetId },
}
- return await this.request<XLikePostResponse>(url, config)
+ return await this.request<XLikePostResponse>(url, config, { operation: 'likePost' })
}
async unlikePost(
@@ -404,7 +396,7 @@ export class TwitterService {
Authorization: `Bearer ${accessToken}`,
},
}
- return await this.request<XLikePostResponse>(url, config)
+ return await this.request<XLikePostResponse>(url, config, { operation: 'unlikePost' })
}
async deleteTweet(
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/common.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/common.ts
similarity index 90%
rename from project/backend/apps/aitoearn-channel/src/libs/wxGzh/common.ts
rename to project/backend/apps/aitoearn-channel/src/libs/wx-gzh/common.ts
index 1fce0124..78a8e3c5 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/common.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/common.ts
@@ -45,3 +45,10 @@ export interface WxGzhArticleNewsPic {
}
}
}
+
+export interface WechatApiCommonResponse {
+ errcode?: number
+ errmsg?: string
+}
+
+export type WechatApiResponse<T> = T & WechatApiCommonResponse
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.exception.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.exception.ts
new file mode 100644
index 00000000..e25d3b8b
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.exception.ts
@@ -0,0 +1,54 @@
+import { IErrorContext, SocialMediaError } from '../exception'
+
+export interface WxGZHRawError {
+ errcode?: number
+ errmsg?: string
+}
+
+/**
+ * WxGZH error class.
+ */
+export class WxGZHError extends SocialMediaError<WxGZHRawError> {
+ constructor(
+ platform: string,
+ operation: string,
+ name: string,
+ message: string,
+ status: number | undefined,
+ rawStatus: number | undefined,
+ rawError: WxGZHRawError,
+ isNetworkError: boolean,
+ context: IErrorContext | undefined,
+ ) {
+ super(
+ platform,
+ operation,
+ name,
+ message,
+ status,
+ rawStatus,
+ rawError,
+ isNetworkError,
+ context,
+ )
+ }
+
+ protected static override getPlatformName(): string {
+ return 'wxgzh'
+ }
+
+ protected static override extractRawError(data: unknown): WxGZHRawError | undefined {
+ if (!data || typeof data !== 'object') {
+ return undefined
+ }
+ const errResponse = data as WxGZHRawError
+ return errResponse
+ }
+
+ protected static override buildMessage(
+ rawError: WxGZHRawError,
+ operation: string,
+ ): string {
+ return `Failed to ${operation}. ${rawError.errmsg || 'Unknown error'}, error code: ${rawError.errcode || 'N/A'}`
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.module.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.module.ts
similarity index 73%
rename from project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.module.ts
rename to project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.module.ts
index 39618cbf..6b1daf61 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.module.ts
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'
-import { WxGzhApiService } from './wxGzhApi.service'
+import { WxGzhApiService } from './wx-gzh.service'
@Module({
providers: [WxGzhApiService],
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.service.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.service.ts
new file mode 100644
index 00000000..89112211
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-gzh/wx-gzh.service.ts
@@ -0,0 +1,420 @@
+/*
+ * @Author: nevin
+ * @Date: 2025-02-15 20:59:55
+ * @LastEditTime: 2025-04-27 17:58:21
+ * @LastEditors: nevin
+ * @Description: WxGzh
+ */
+import { Injectable, Logger } from '@nestjs/common'
+import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
+import { WechatApiResponse, WxGzhArticleNews, WxGzhArticleNewsPic } from './common'
+import { WxGZHError } from './wx-gzh.exception'
+
+@Injectable()
+export class WxGzhApiService {
+ /**
+ * 上传临时素材
+ * @param accessToken
+ * @param media
+ * @param type
+ * @returns
+ */
+ private readonly logger = new Logger(WxGzhApiService.name)
+
+ private async request<T>(
+ url: string,
+ config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
+ ): Promise<T> {
+ const operation = options.operation || 'wx-gzh request'
+ this.logger.debug(`[WXGZH:${operation}] Request -> ${url} ${config.method || 'GET'} ${config.params ? `params=${JSON.stringify(config.params)}` : ''}`)
+ try {
+ const response: AxiosResponse<WechatApiResponse<T>> = await axios(url, config)
+ if (response.data && response.data.errcode) {
+ throw WxGZHError.buildFromResponse(response.data, operation)
+ }
+ return response.data
+ }
+ catch (error) {
+ const err = WxGZHError.buildFromError(error, options.operation || 'wx-gzh request')
+ this.logger.error(
+ `[WXGZH:${operation}] Error !! message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`,
+ )
+ throw err
+ }
+ }
+
+ async uploadTempMedia(
+ accessToken: string,
+ type: 'image' | 'voice' | 'video' | 'thumb',
+ file: Blob,
+ fileName: string,
+ ) {
+ const formData = new FormData()
+ formData.append('media', file, fileName)
+
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: formData,
+ }
+ return await this.request<{
+ type: 'image' | 'voice' | 'video' | 'thumb'
+ media_id: string
+ created_at: number
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${accessToken}&type=${type}`,
+ config,
+ { operation: 'uploadTempMedia' },
+ )
+ }
+
+ /**
+ * 获取临时素材
+ * @param accessToken
+ * @param mediaId
+ * @returns
+ */
+ async getTempMedia(accessToken: string, mediaId: string) {
+ const config: AxiosRequestConfig = {
+ method: 'GET',
+ params: {
+ media_id: mediaId,
+ },
+ }
+ return await this.request<{
+ video_url?: string
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/media/get?access_token=${accessToken}&media_id=${mediaId}`,
+ config,
+ { operation: 'getTempMedia' },
+ )
+ }
+
+ /**
+ * 上传图文中的图片素材(不占用限制)
+ * @param accessToken
+ * @param file
+ * @returns
+ */
+ async uploadImg(accessToken: string, file: Blob, fileName: string) {
+ const formData = new FormData()
+ formData.append('media', file, fileName)
+
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: formData,
+ }
+ return await this.request<{ url: string }>(
+ `https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=${accessToken}`,
+ config,
+ { operation: 'uploadImg' },
+ )
+ }
+
+ /**
+ * 上传永久素材
+ * @param accessToken
+ * @param type
+ * @param file
+ * @returns
+ */
+ async addMaterial(
+ accessToken: string,
+ type: 'image' | 'voice' | 'video' | 'thumb',
+ file: Blob,
+ fileName: string,
+ videoOptions?: {
+ title: string
+ introduction?: string
+ },
+ ) {
+ const formData = new FormData()
+ formData.append('media', file, fileName)
+
+ if (type === 'video')
+ formData.append('description', JSON.stringify(videoOptions))
+
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: formData,
+ }
+ return await this.request<{
+ media_id: string
+ url: string
+ errcode?: number
+ errmsg?: string
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${accessToken}&type=${type}`,
+ config,
+ { operation: 'addMaterial' },
+ )
+ }
+
+ /**
+ * 获取永久素材
+ * @param accessToken
+ * @param mediaId
+ * @returns
+ */
+ async getMaterial(accessToken: string, mediaId: string) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: { media_id: mediaId },
+ }
+ return await this.request<{
+ news_item: {
+ title: string
+ thumb_media_id: string
+ show_cover_pic: string
+ author: string
+ digest: string
+ content: string
+ url: string
+ content_source_url: string
+ }[] | {
+ title: string
+ description: string
+ down_url: string
+ }
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=${accessToken}`,
+ config,
+ { operation: 'getMaterial' },
+ )
+ }
+
+ /**
+ * 新建草稿
+ * @param accessToken
+ * @param data
+ * @returns
+ */
+ async draftAdd(
+ accessToken: string,
+ data: WxGzhArticleNews | WxGzhArticleNewsPic,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: { articles: [data] },
+ }
+ return await this.request<{
+ media_id: string
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${accessToken}`,
+ config,
+ { operation: 'draftAdd' },
+ )
+ }
+
+ /**
+ * 发布
+ * @param accessToken
+ * @param mediaId
+ * @returns
+ */
+ async freePublish(accessToken: string, mediaId: string) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: { media_id: mediaId },
+ }
+ return await this.request<{
+ publish_id: string
+ msg_data_id: string
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token=${accessToken}`,
+ config,
+ { operation: 'freePublish' },
+ )
+ }
+
+ // -------- 留言管理 -----
+ /**
+ * 回复评论
+ * @param accessToken
+ * @param msgDataId 消息ID
+ * @param userCommentId 用户评论ID
+ * @param content 评论内容
+ * @returns
+ */
+ async listComment(
+ accessToken: string,
+ msgDataId: string,
+ begin: number,
+ count: number, // <=50
+ ) {
+ count = Math.min(count, 50)
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ msg_data_id: msgDataId,
+ index: 0,
+ begin,
+ count,
+ },
+ }
+ return await this.request<{
+ comment: {
+ user_comment_id: string
+ openid: string
+ create_time: string
+ content: string
+ comment_type: number
+ reply: {
+ content: string
+ create_time: string
+ }
+ }[]
+ total: number
+ }>(
+ `https://api.weixin.qq.com/cgi-bin/comment/list?access_token=${accessToken}`,
+ config,
+ { operation: 'listComment' },
+ )
+ }
+
+ /**
+ * 回复评论
+ * @param accessToken
+ * @param msgDataId 消息ID
+ * @param userCommentId 用户评论ID
+ * @param content 评论内容
+ * @returns
+ */
+ async replycomment(
+ accessToken: string,
+ msgDataId: string,
+ userCommentId: string,
+ content: string,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ msg_data_id: msgDataId,
+ index: 0,
+ user_comment_id: userCommentId,
+ content,
+ },
+ }
+ return await this.request(
+ `https://api.weixin.qq.com/cgi-bin/comment/reply/add?access_token=${accessToken}`,
+ config,
+ { operation: 'replycomment' },
+ )
+ }
+
+ // -------- datacube 统计数据 -----
+ /**
+ * 获取用户增减数据
+ * @param accessToken
+ * @param beginDate yyyy-MM-dd
+ * @param endDate yyyy-MM-dd 结束日期(最大跨度7天)
+ * @returns
+ */
+ async getusersummary(
+ accessToken: string,
+ beginDate: string,
+ endDate: string,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ begin_date: beginDate,
+ end_date: endDate,
+ },
+ }
+ return await this.request<{
+ list: {
+ ref_date: string
+ user_source: number
+ new_user: number
+ cancel_user: number
+ }[]
+ }>(
+ `https://api.weixin.qq.com/datacube/getusersummary?access_token=${accessToken}`,
+ config,
+ { operation: 'getusersummary' },
+ )
+ }
+
+ /**
+ * 获取累计用户数据
+ * @param accessToken
+ * @param beginDate yyyy-MM-dd
+ * @param endDate yyyy-MM-dd 结束日期(最大跨度7天)
+ * @returns
+ */
+ async getusercumulate(
+ accessToken: string,
+ beginDate: string,
+ endDate: string,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ begin_date: beginDate,
+ end_date: endDate,
+ },
+ }
+ return await this.request<{
+ list: {
+ ref_date: string // '2014-12-07';
+ cumulate_user: number // 0;
+ }[]
+ }>(
+ `https://api.weixin.qq.com/datacube/getusercumulate?access_token=${accessToken}`,
+ config,
+ { operation: 'getusercumulate' },
+ )
+ }
+
+ /**
+ * 获取图文阅读概况数据
+ * @param accessToken
+ * @param beginDate yyyy-MM-dd
+ * @param endDate yyyy-MM-dd 结束日期(最大值为昨日)
+ * @returns
+ */
+ async getuserread(
+ accessToken: string,
+ beginDate: string,
+ endDate: string,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ begin_date: beginDate,
+ end_date: endDate,
+ },
+ }
+ return await this.request<{
+ list: {
+ ref_date: string
+ user_source: number
+ int_page_read_count: number
+ share_count: number
+ add_to_fav_count: number
+ }[]
+ }>(
+ `https://api.weixin.qq.com/datacube/getuserread?access_token=${accessToken}`,
+ config,
+ { operation: 'getuserread' },
+ )
+ }
+
+ async deleteArticle(
+ accessToken: string,
+ article_id: string,
+ ) {
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ article_id,
+ },
+ }
+ return await this.request(
+ `https://api.weixin.qq.com/cgi-bin/freepublish/delete?access_token=${accessToken}`,
+ config,
+ { operation: 'deleteArticle' },
+ )
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/comment.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/comment.ts
similarity index 94%
rename from project/backend/apps/aitoearn-channel/src/libs/wxPlat/comment.ts
rename to project/backend/apps/aitoearn-channel/src/libs/wx-plat/comment.ts
index df90ae6d..68fef3e4 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/comment.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/comment.ts
@@ -70,4 +70,9 @@ export interface WxPlatAuthorizerInfo {
errmsg?: string
}
-// ----- 公众号 STR -----
+export interface WechatApiCommonResponse {
+ errcode?: number
+ errmsg?: string
+}
+
+export type WechatApiResponse<T> = T & WechatApiCommonResponse
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.module.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.module.ts
similarity index 75%
rename from project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.module.ts
rename to project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.module.ts
index 83818bef..9315247c 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.module.ts
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common'
-import { WxPlatApiService } from './wxPlatApi.service'
+import { WxPlatApiService } from './wx-plat.service'
@Module({
imports: [],
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.service.ts b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.service.ts
new file mode 100644
index 00000000..3d11aedd
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/libs/wx-plat/wx-plat.service.ts
@@ -0,0 +1,203 @@
+/*
+ * @Author: nevin
+ * @Date: 2025-02-15 20:59:55
+ * @LastEditTime: 2025-04-27 17:58:21
+ * @LastEditors: nevin
+ * @Description: WxPlat
+ */
+import { Injectable, Logger } from '@nestjs/common'
+import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
+import { config } from '../../config'
+import { WxGZHError } from '../wx-gzh/wx-gzh.exception'
+import { WechatApiResponse, WxPlatAuthorizerInfo } from './comment'
+
+@Injectable()
+export class WxPlatApiService {
+ private id = ''
+ private secret = ''
+
+ private readonly logger = new Logger(WxPlatApiService.name)
+ constructor() {
+ const cfg = config.wxPlat
+
+ this.id = cfg.id
+ this.secret = cfg.secret
+ }
+
+ private async request<T>(
+ url: string,
+ config: AxiosRequestConfig = {},
+ options: { operation?: string } = {},
+ ): Promise<T> {
+ const operation = options.operation || 'myWxPlat request'
+ this.logger.debug(`[myWxPlat:${operation}] Request -> ${url} ${config.method || 'GET'} ${config.params ? `params=${JSON.stringify(config.params)}` : ''}`)
+ try {
+ const response: AxiosResponse<WechatApiResponse<T>> = await axios(url, config)
+ if (response.data && response.data.errcode) {
+ throw WxGZHError.buildFromResponse(response.data, operation)
+ }
+ this.logger.debug(`[myWxPlat:${operation}] Response <- ${url} status=${response.status} data=${JSON.stringify(response.data)}`)
+ return response.data
+ }
+ catch (error: unknown) {
+ const err = WxGZHError.buildFromError(error, operation)
+ this.logger.error(`[myWxPlat:${operation}] Error !! ${url} message=${err.message} status=${err.status} rawError=${JSON.stringify(err.rawError)}`)
+ throw err
+ }
+ }
+
+ /**
+ * 设置component_access_token企业授权token
+ * componentVerifyTicket
+ * @returns
+ */
+ async getComponentAccessToken(componentVerifyTicket: string): Promise<{
+ component_access_token: string
+ expires_in: number // 有效期,单位:秒
+ }> {
+ const url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token'
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ component_appsecret: this.secret,
+ component_verify_ticket: componentVerifyTicket,
+ },
+ }
+ return this.request<{
+ component_access_token: string
+ expires_in: number
+ }>(url, config, { operation: 'getComponentAccessToken' })
+ }
+
+ /**
+ * 获取预授权码
+ * @returns
+ */
+ async getPreAuthCode(componentAccessToken: string) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ },
+ }
+ return this.request<{
+ pre_auth_code: string
+ expires_in: number // 有效期 1800,单位:秒
+ }>(url, config, { operation: 'getPreAuthCode' })
+ }
+
+ /**
+ * 获取授权链接
+ * @param preAuthCode
+ * @param redirectUri
+ * @param type
+ * @returns
+ */
+ getAuthPageUrl(preAuthCode: string, redirectUri: string, type: 'h5' | 'pc') {
+ const url
+ = type === 'pc'
+ ? `https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=${this.id}&pre_auth_code=${preAuthCode}&redirect_uri=${redirectUri}&auth_type=1`
+ : `https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&no_scan=1&component_appid=${this.id}&pre_auth_code=${preAuthCode}&redirect_uri=${redirectUri}&auth_type=1#wechat_redirect`
+ return url
+ }
+
+ /**
+ * 使用授权码获取授权信息
+ * @param componentAccessToken
+ * @param authorizationCode
+ * @returns
+ */
+ async getQueryAuth(componentAccessToken: string, authorizationCode: string) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ authorization_code: authorizationCode,
+ },
+ }
+ return this.request<{
+ authorization_info: WxPlatAuthorizerInfo
+ }>(url, config, { operation: 'getQueryAuth' })
+ }
+
+ /**
+ * 刷新用户的authorizer_access_token
+ * @param componentAccessToken
+ * @param appId 用的应用的appid
+ * @param authorizerRefreshToken 刷新token
+ * @returns
+ */
+ async getAuthorizerAccessToken(
+ componentAccessToken: string,
+ authorizerAppId: string,
+ authorizerRefreshToken: string,
+ ) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ authorizer_appid: authorizerAppId,
+ authorizer_refresh_token: authorizerRefreshToken,
+ },
+ }
+ return this.request<{
+ authorizer_access_token: string
+ authorizer_refresh_token: string
+ expires_in: number // 有效期,单位:秒 2小时
+ }>(url, config, { operation: 'getAuthorizerAccessToken' })
+ }
+
+ /**
+ * 获取用户的授权信息
+ * @param userId
+ * @param authorizationCode
+ * @returns
+ */
+ async setUserAppAccessTokenInfo(
+ componentAccessToken: string,
+ authorizationCode: string,
+ ) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?access_token==${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ authorization_code: authorizationCode,
+ },
+ }
+ return this.request<{
+ authorization_info: WxPlatAuthorizerInfo
+ }>(url, config, { operation: 'setUserAppAccessTokenInfo' })
+ }
+
+ /**
+ * 获取授权账号的详情
+ * @param componentAccessToken
+ * @param authorizerAppid
+ * @returns
+ */
+ async getAuthorizerInfo(
+ componentAccessToken: string,
+ authorizerAppid: string,
+ ) {
+ const url = `https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?access_token=${componentAccessToken}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ data: {
+ component_appid: this.id,
+ authorizer_appid: authorizerAppid,
+ },
+ }
+ return this.request<{
+ authorizer_info: {
+ nick_name: string
+ user_name: string
+ head_img: string
+ }
+ }>(url, config, { operation: 'getAuthorizerInfo' })
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.service.ts
deleted file mode 100644
index a51e0cfb..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/wxGzh/wxGzhApi.service.ts
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * @Author: nevin
- * @Date: 2025-02-15 20:59:55
- * @LastEditTime: 2025-04-27 17:58:21
- * @LastEditors: nevin
- * @Description: WxGzh
- */
-import { Injectable, Logger } from '@nestjs/common'
-import axios from 'axios'
-import { WxGzhArticleNews, WxGzhArticleNewsPic } from './common'
-
-@Injectable()
-export class WxGzhApiService {
- /**
- * 上传临时素材
- * @param accessToken
- * @param media
- * @param type
- * @returns
- */
- private readonly logger = new Logger(WxGzhApiService.name)
-
- async uploadTempMedia(
- accessToken: string,
- type: 'image' | 'voice' | 'video' | 'thumb',
- file: Blob,
- fileName: string,
- ) {
- try {
- const formData = new FormData()
- formData.append('media', file, fileName)
-
- const result = await axios.post<{
- type: 'image' | 'voice' | 'video' | 'thumb' // 'TYPE';
- media_id: string // 'MEDIA_ID';
- created_at: number // 123456789;
- }>(
- `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${accessToken}&type=${type}`,
- formData,
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return null
- }
- }
-
- /**
- * 获取临时素材
- * @param accessToken
- * @param mediaId
- * @returns
- */
- async getTempMedia(accessToken: string, mediaId: string) {
- try {
- const result = await axios.get<{
- video_url?: string // url;
- errcode?: number // 40007;
- errmsg?: string // 'invalid media_id';
- }>(
- `https://api.weixin.qq.com/cgi-bin/media/get?access_token=${accessToken}&media_id=${mediaId}`,
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return null
- }
- }
-
- /**
- * 上传图文中的图片素材(不占用限制)
- * @param accessToken
- * @param file
- * @returns
- */
- async uploadImg(accessToken: string, file: Blob, fileName: string) {
- try {
- const formData = new FormData()
- formData.append('media', file, fileName)
-
- const result = await axios.post<{
- url: string // url;
- }>(
- `https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=${accessToken}`,
- formData,
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return null
- }
- }
-
- /**
- * 上传永久素材
- * @param accessToken
- * @param type
- * @param file
- * @returns
- */
- async addMaterial(
- accessToken: string,
- type: 'image' | 'voice' | 'video' | 'thumb',
- file: Blob,
- fileName: string,
- videoOptions?: {
- title: string
- introduction?: string
- },
- ) {
- try {
- const formData = new FormData()
- formData.append('media', file, fileName)
-
- // 如果是视频,则添加 description 参数
- if (type === 'video')
- formData.append('description', JSON.stringify(videoOptions))
-
- const result = await axios.post<{
- media_id: string // 'MEDIA_ID';
- url: string // 123456789;
- errcode?: number // 40007;
- errmsg?: string // 'invalid media_id';
- }>(
- `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${accessToken}&type=${type}`,
- formData,
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('wx Error during addMaterial:', error)
- return null
- }
- }
-
- /**
- * 获取永久素材
- * @param accessToken
- * @param mediaId
- * @returns
- */
- async getMaterial(accessToken: string, mediaId: string) {
- try {
- const result = await axios.post<
- | {
- news_item: {
- title: string // 'TITLE';
- thumb_media_id: string // 'THUMB_MEDIA_ID';
- show_cover_pic: string // 'SHOW_COVER_PIC';
- author: string // 'AUTHOR';
- digest: string // 'DIGEST';
- content: string // 'CONTENT';
- url: string // 'URL';
- content_source_url: string // 'CONTENT_SOURCE_URL';
- }[]
- }
- | {
- title: string // TITLE;
- description: string // DESCRIPTION;
- down_url: string // DOWN_URL;
- }
- | {
- errcode: number // 40007;
- errmsg: string // 'invalid media_id';
- }
- >(
- `https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=${accessToken}`,
- { media_id: mediaId },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return null
- }
- }
-
- /**
- * 新建草稿
- * @param accessToken
- * @param data
- * @returns
- */
- async draftAdd(
- accessToken: string,
- data: WxGzhArticleNews | WxGzhArticleNewsPic,
- ) {
- try {
- const result = await axios.post<{
- media_id: string // MEDIA_ID
- errcode?: number // 40007;
- errmsg?: string // 'invalid media_id';
- }>(
- `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${accessToken}`,
- {
- articles: [data],
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return {
- media_id: '',
- errcode: 1,
- errmsg: '新建草稿请求出错',
- }
- }
- }
-
- /**
- * 发布
- * @param accessToken
- * @param mediaId
- * @returns
- */
- async freePublish(accessToken: string, mediaId: string) {
- try {
- const result = await axios.post<{
- errcode: number // 40007;
- errmsg: string // 'invalid media_id';
- publish_id: string // '100000001';
- msg_data_id: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token=${accessToken}`,
- {
- media_id: mediaId,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during component_access_token:', error)
- return {
- publish_id: '',
- msg_data_id: '',
- errcode: 1,
- errmsg: '发布请求失败',
- }
- }
- }
-
- // -------- 留言管理 -----
- /**
- * 回复评论
- * @param accessToken
- * @param msgDataId 消息ID
- * @param userCommentId 用户评论ID
- * @param content 评论内容
- * @returns
- */
- async listComment(
- accessToken: string,
- msgDataId: string,
- begin: number,
- count: number, // <=50
- ) {
- if (count > 50)
- count = 50
- try {
- const result = await axios.post<{
- errmsg?: string // 'invalid media_id';
- errcode?: number // 40007;
- comment: {
- user_comment_id: string // USER_COMMENT_ID,
- openid: string // openid,用户如果用非微信身份评论,不返回openid
- create_time: string // CREATE_TIME,
- content: string // CONTENT,
- comment_type: number
- reply: {
- content: string // CONTENT,
- create_time: string // CREATE_TIME
- }
- }[]
- total: number
- }>(
- `https://api.weixin.qq.com/cgi-bin/comment/list?access_token=${accessToken}`,
- {
- msg_data_id: msgDataId,
- index: 0,
- begin,
- count,
- type: 0,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during getusersummary:', error)
- return {
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-
- /**
- * 回复评论
- * @param accessToken
- * @param msgDataId 消息ID
- * @param userCommentId 用户评论ID
- * @param content 评论内容
- * @returns
- */
- async replycomment(
- accessToken: string,
- msgDataId: string,
- userCommentId: string,
- content: string,
- ) {
- try {
- const result = await axios.post<{
- errmsg?: string // 'invalid media_id';
- errcode?: number // 40007;
- }>(
- `https://api.weixin.qq.com/cgi-bin/comment/reply/add?access_token=${accessToken}`,
- {
- msg_data_id: msgDataId,
- index: 0,
- user_comment_id: userCommentId,
- content,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during getusersummary:', error)
- return {
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-
- // -------- datacube 统计数据 -----
- /**
- * 获取用户增减数据
- * @param accessToken
- * @param beginDate yyyy-MM-dd
- * @param endDate yyyy-MM-dd 结束日期(最大跨度7天)
- * @returns
- */
- async getusersummary(
- accessToken: string,
- beginDate: string,
- endDate: string,
- ) {
- try {
- const result = await axios.post<{
- list:
- {
- ref_date: string // '2014-12-07';
- user_source: number // 0;
- new_user: number // 0;
- cancel_user: number // 0;
- }[]
- errmsg?: string // 'invalid media_id';
- errcode?: number // 40007;
- }>(
- `https://api.weixin.qq.com/datacube/getusersummary?access_token=${accessToken}`,
- {
- begin_date: beginDate,
- end_date: endDate,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during getusersummary:', error)
- return {
- list: [],
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-
- /**
- * 获取累计用户数据
- * @param accessToken
- * @param beginDate yyyy-MM-dd
- * @param endDate yyyy-MM-dd 结束日期(最大跨度7天)
- * @returns
- */
- async getusercumulate(
- accessToken: string,
- beginDate: string,
- endDate: string,
- ) {
- try {
- const result = await axios.post<{
- list:
- {
- ref_date: string // '2014-12-07';
- cumulate_user: number // 0;
- }[]
- errmsg?: string // 'invalid media_id';
- errcode?: number // 40007;
- }>(
- `https://api.weixin.qq.com/datacube/getusercumulate?access_token=${accessToken}`,
- {
- begin_date: beginDate,
- end_date: endDate,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during getusersummary:', error)
- return {
- list: [],
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-
- /**
- * 获取图文阅读概况数据
- * @param accessToken
- * @param beginDate yyyy-MM-dd
- * @param endDate yyyy-MM-dd 结束日期(最大值为昨日)
- * @returns
- */
- async getuserread(
- accessToken: string,
- beginDate: string,
- endDate: string,
- ) {
- try {
- const result = await axios.post<{
- list:
- {
- ref_date: string // 数据的日期,需在begin_date和end_date之间;
- user_source: number // 用户从哪里进入来阅读该图文。99999999.全部;0:会话;1.好友;2.朋友圈;4.历史消息页;5.其他;6.看一看;7.搜一搜;
- int_page_read_count: number // 图文页的阅读次数
- share_count: number // 分享的次数
- add_to_fav_count: number // 收藏的次数
- }[]
- errmsg?: string // 'invalid media_id';
- errcode?: number // 40007;
- }>(
- `https://api.weixin.qq.com/datacube/getuserread?access_token=${accessToken}`,
- {
- begin_date: beginDate,
- end_date: endDate,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during getusersummary:', error)
- return {
- list: [],
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-
- async deleteArticle(
- accessToken: string,
- article_id: string,
- ) {
- try {
- const result = await axios.post<{
- errcode?: number
- errmsg?: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/freepublish/delete?access_token=${accessToken}`,
- {
- article_id,
- },
- )
-
- return result.data
- }
- catch (error) {
- this.logger.log('Error during deleteArticle:', error)
- return {
- errcode: 1,
- errmsg: '请求失败',
- }
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.service.ts
deleted file mode 100644
index 78c481fd..00000000
--- a/project/backend/apps/aitoearn-channel/src/libs/wxPlat/wxPlatApi.service.ts
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * @Author: nevin
- * @Date: 2025-02-15 20:59:55
- * @LastEditTime: 2025-04-27 17:58:21
- * @LastEditors: nevin
- * @Description: WxPlat
- */
-import { Injectable, Logger } from '@nestjs/common'
-import axios from 'axios'
-import { config } from '../../config'
-import { WxPlatAuthorizerInfo } from './comment'
-
-@Injectable()
-export class WxPlatApiService {
- private id = ''
- private secret = ''
-
- private readonly logger = new Logger(WxPlatApiService.name)
- constructor() {
- const cfg = config.wxPlat
-
- this.id = cfg.id
- this.secret = cfg.secret
- }
-
- /**
- * 设置component_access_token企业授权token
- * componentVerifyTicket
- * @returns
- */
- async getComponentAccessToken(componentVerifyTicket: string): Promise<{
- component_access_token: string
- expires_in: number // 有效期,单位:秒
- } | null> {
- try {
- const result = await axios.post<{
- component_access_token: string
- expires_in: number // 有效期,单位:秒
- errcode?: number
- errmsg?: string
- }>('https://api.weixin.qq.com/cgi-bin/component/api_component_token', {
- component_appid: this.id,
- component_appsecret: this.secret,
- component_verify_ticket: componentVerifyTicket,
- })
-
- if (result.data.errcode)
- throw new Error(result.data.errcode + (result.data.errmsg || ''))
- return result.data
- }
- catch (error) {
- this.logger.error(
- '------ Error wxPlat getComponentAccessToken: ------',
- error,
- )
- return null
- }
- }
-
- /**
- * 获取预授权码
- * @returns
- */
- async getPreAuthCode(componentAccessToken: string) {
- try {
- const result = await axios.post<{
- pre_auth_code: string
- expires_in: number // 有效期 1800,单位:秒
- errcode?: number
- errmsg?: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=${componentAccessToken}`,
- {
- component_appid: this.id,
- },
- )
- if (result.data.errcode)
- throw new Error(result.data.errcode + (result.data.errmsg || ''))
- return result.data
- }
- catch (error) {
- this.logger.error('------ Error wxPlat getPreAuthCode: ------', error)
- return null
- }
- }
-
- /**
- * 获取授权链接
- * @param preAuthCode
- * @param redirectUri
- * @param type
- * @returns
- */
- getAuthPageUrl(preAuthCode: string, redirectUri: string, type: 'h5' | 'pc') {
- const url
- = type === 'pc'
- ? `https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=${this.id}&pre_auth_code=${preAuthCode}&redirect_uri=${redirectUri}&auth_type=1`
- : `https://open.weixin.qq.com/wxaopen/safe/bindcomponent?action=bindcomponent&no_scan=1&component_appid=${this.id}&pre_auth_code=${preAuthCode}&redirect_uri=${redirectUri}&auth_type=1#wechat_redirect`
- return url
- }
-
- /**
- * 使用授权码获取授权信息
- * @param componentAccessToken
- * @param authorizationCode
- * @returns
- */
- async getQueryAuth(componentAccessToken: string, authorizationCode: string) {
- try {
- const result = await axios.post<{
- authorization_info: WxPlatAuthorizerInfo
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=${componentAccessToken}`,
- {
- component_appid: this.id,
- authorization_code: authorizationCode,
- },
- )
-
- return result.data.authorization_info
- }
- catch (error) {
- this.logger.error('------ Error wxPlat getQueryAuth: ------', error)
- return null
- }
- }
-
- /**
- * 刷新用户的authorizer_access_token
- * @param componentAccessToken
- * @param appId 用的应用的appid
- * @param authorizerRefreshToken 刷新token
- * @returns
- */
- async getAuthorizerAccessToken(
- componentAccessToken: string,
- authorizerAppId: string,
- authorizerRefreshToken: string,
- ) {
- try {
- const result = await axios.post<{
- authorizer_access_token: string
- authorizer_refresh_token: string
- expires_in: number // 有效期,单位:秒 2小时
- errcode?: number
- errmsg?: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=${componentAccessToken}`,
- {
- component_appid: this.id,
- authorizer_appid: authorizerAppId,
- authorizer_refresh_token: authorizerRefreshToken,
- },
- )
-
- if (result.data.errcode)
- throw new Error(result.data.errcode + (result.data.errmsg || ''))
- return result.data
- }
- catch (error) {
- this.logger.error(
- '------ Error wxPlat getAuthorizerAccessToken: ------',
- error,
- )
-
- return null
- }
- }
-
- /**
- * 获取用户的授权信息
- * @param userId
- * @param authorizationCode
- * @returns
- */
- async setUserAppAccessTokenInfo(
- componentAccessToken: string,
- authorizationCode: string,
- ) {
- try {
- const result = await axios.post<{
- authorization_info: WxPlatAuthorizerInfo
- errcode?: number
- errmsg?: string
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?access_token==${componentAccessToken}`,
- {
- component_appid: this.id,
- authorization_code: authorizationCode,
- },
- )
- if (result.data.errcode)
- throw new Error(result.data.errcode + (result.data.errmsg || ''))
- return result.data
- }
- catch (error) {
- this.logger.log('Error setUserAppAccessTokenInfo :', error)
- return null
- }
- }
-
- /**
- * 获取授权账号的详情
- * @param componentAccessToken
- * @param authorizerAppid
- * @returns
- */
- async getAuthorizerInfo(
- componentAccessToken: string,
- authorizerAppid: string,
- ) {
- this.logger.debug('getAuthorizerInfo---args', {
- componentAccessToken,
- authorizerAppid,
- })
- try {
- const result = await axios.post<{
- authorizer_info: {
- nick_name: string
- user_name: string
- head_img: string
- errcode?: number
- errmsg?: string
- }
- }>(
- `https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?access_token=${componentAccessToken}`,
- {
- component_appid: this.id,
- authorizer_appid: authorizerAppid,
- },
- )
-
- return result.data.authorizer_info
- }
- catch (error) {
- this.logger.error('Error getAuthorizerInfo :', error)
- return null
- }
- }
-}
diff --git a/project/backend/apps/aitoearn-channel/src/libs/youtube/youtubeApi.service.ts b/project/backend/apps/aitoearn-channel/src/libs/youtube/youtubeApi.service.ts
index 877ab0b7..143f6cf7 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/youtube/youtubeApi.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/youtube/youtubeApi.service.ts
@@ -20,8 +20,6 @@ export class YoutubeApiService {
private oauth2Client: any
private webClientSecret: string
private webClientId: string
- private webRenderBaseUrl: string
- private youtubeClient = google.youtube('v3')
private readonly logger = new Logger(YoutubeApiService.name)
constructor() {
@@ -32,7 +30,6 @@ export class YoutubeApiService {
private async initYoutubeSecrets() {
this.webClientSecret = config.youtube.secret
this.webClientId = config.youtube.id
- this.webRenderBaseUrl = config.youtube.authBackHost
}
/**
@@ -252,88 +249,4 @@ export class YoutubeApiService {
return error
}
}
-
- // async publishVideo(
- // accountToken: string,
- // pubParams: YoutubeVideoPubParams,
- // ): Promise<YoutubeVideoPubResult> {
- // return new Promise(async (resolve) => {
- // try {
- // const { coverUrl, videoUrl } = pubParams
-
- // // 发起上传
- // const startUploadInfo = await this.startUpload(accountToken)
- // if (startUploadInfo.result !== 1)
- // throw new Error('发起上传失败')
-
- // // 获取封面
- // const coverBase64
- // = await this.fileToolsService.fileUrlToBase64(coverUrl)
-
- // const buffer = Buffer.from(coverBase64, 'base64')
- // const coverBlob = new Blob([buffer], { type: 'image/jpeg' })
-
- // Logger.log('封面获取成功:', coverBlob)
-
- // // 视频URL分片上传
- // void this.fileToolsService.streamDownloadAndUpload(
- // videoUrl,
- // async (upData: Buffer, partNumber: number) => {
- // const res = await this.fragmentUploadVideo(
- // startUploadInfo.upload_token,
- // partNumber - 1,
- // startUploadInfo.endpoint,
- // upData,
- // )
- // Logger.log('分片:', partNumber, res)
- // if (res.result !== 1)
- // throw new Error('分片上传失败')
- // },
- // async (partCount) => {
- // // 合并
- // const res = await this.completeFragmentUpload(
- // startUploadInfo.upload_token,
- // partCount - 1,
- // startUploadInfo.endpoint,
- // )
- // if (res.result !== 1)
- // throw new Error('合并分片上传失败')
-
- // // 发布
- // const formData = new FormData()
- // formData.append('caption', this.getCaption(pubParams))
- // formData.append('cover', coverBlob)
- // const pubRes = await axios<{
- // video_info: KwaiPublishVideoInfo
- // result: number
- // }>({
- // url: `${this.kwaiHost}/openapi/photo/publish`,
- // method: 'POST',
- // params: {
- // upload_token: startUploadInfo.upload_token,
- // app_id: this.appId,
- // access_token: accountToken,
- // },
- // data: formData,
- // })
- // if (pubRes.data.result !== 1)
- // throw new Error('视频发布失败!')
-
- // resolve({
- // success: true,
- // worksId: pubRes.data.video_info.photo_id,
- // })
- // },
- // 4194304,
- // )
- // }
- // catch (e) {
- // this.logger.error(e)
- // resolve({
- // success: false,
- // failMsg: e.message || '发布错误',
- // })
- // }
- // })
- // }
}
diff --git a/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts b/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts
index d65ac5fd..21295767 100644
--- a/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts
@@ -88,6 +88,20 @@ export class PublishController {
return this.publishService.getQueuedPublishingTasks(data, token.id)
}
+ @ApiOperation({ summary: '获取指定平台的已经发布作品' })
+ @Post('/statuses/published/posts')
+ @ApiOkResponse({
+ type: PostHistoryItemDto,
+ isArray: true,
+ description: '获取指定平台的已经发布作品',
+ })
+ async getPublishedPosts(
+ @GetToken() token: TokenInfo,
+ @Body() data: PubRecordListFilterDto,
+ ) {
+ return this.publishService.getPublishedPosts(data, token.id)
+ }
+
@ApiOperation({ summary: '修改发布任务时间' })
@Post('updateTaskTime')
async updatePublishRecordTime(
diff --git a/project/backend/apps/aitoearn-server/src/channel/publish.service.ts b/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
index e246fc31..c3882643 100644
--- a/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
@@ -61,7 +61,7 @@ export class PublishService {
type: post.mediaType,
title: post.title || '',
desc: post.content || '',
- accountId: '',
+ accountId: post.accountId || '',
accountType: post.platform as AccountType,
uid: '',
videoUrl: post.mediaType === 'video' ? post.permaLink || '' : undefined,
@@ -207,12 +207,29 @@ export class PublishService {
}
async getQueuedPublishingTasks(data: PubRecordListFilterDto, userId: string) {
- const publishRecords = await this.publishRecordService.getQueuedPublishRecords({
+ const publishTasks = await this.publishTaskNatsApi.getQueuedPublishTasks(userId, data)
+ const posts = this.mergePostHistory([], publishTasks, [])
+ return posts
+ }
+
+ async getPublishedPosts(data: PubRecordListFilterDto, userId: string) {
+ const publishRecords = await this.publishRecordService.getPublishRecordList({
...data,
userId,
})
- const publishTasks = await this.publishTaskNatsApi.getQueuedPublishTasks(userId, data)
- const posts = this.mergePostHistory(publishRecords, publishTasks, [])
+ const publishTasks = await this.publishTaskNatsApi.getPublishedPublishTasks(userId, data)
+ const range = { start: '', end: '' }
+ if (data.time) {
+ range.start = data.time[0].toISOString()
+ range.end = data.time[1].toISOString()
+ }
+ const postsHistory = await this.postService.getUserAllPostsByPlatform({
+ ...data,
+ range,
+ userId,
+ platform: data.accountType as any,
+ })
+ const posts = this.mergePostHistory(publishRecords, publishTasks, postsHistory.posts)
return posts
}
diff --git a/project/backend/apps/aitoearn-server/src/transports/channel/api/publishTask.natsApi.ts b/project/backend/apps/aitoearn-server/src/transports/channel/api/publishTask.natsApi.ts
index 85ce5acb..79ad62f3 100644
--- a/project/backend/apps/aitoearn-server/src/transports/channel/api/publishTask.natsApi.ts
+++ b/project/backend/apps/aitoearn-server/src/transports/channel/api/publishTask.natsApi.ts
@@ -19,4 +19,12 @@ export class PublishTaskNatsApi extends ChannelBaseApi {
)
return res
}
+
+ async getPublishedPublishTasks(userId: string, query: PubRecordListFilterDto) {
+ const res = await this.sendMessage<any[]>(
+ `channel/status/published/tasks`,
+ { userId, ...query },
+ )
+ return res
+ }
}
diff --git a/project/backend/libs/common/src/enums/response-code.enum.ts b/project/backend/libs/common/src/enums/response-code.enum.ts
index 716f6fb4..b412f482 100755
--- a/project/backend/libs/common/src/enums/response-code.enum.ts
+++ b/project/backend/libs/common/src/enums/response-code.enum.ts
@@ -90,4 +90,7 @@ export enum ResponseCode {
InteractAccountTypeNotSupported = 15022,
InteractRecordNotFound = 15023,
DataCubeAccountTypeNotSupported = 15024,
+ ChannelPublishTaskAlreadyExists = 15025,
+ PublishTaskAlreadyPublishing = 15026,
+ PublishTaskAlreadyCompleted = 15027,
}
diff --git a/project/backend/libs/common/src/i18n/messages.ts b/project/backend/libs/common/src/i18n/messages.ts
index 324c50d1..afc77176 100644
--- a/project/backend/libs/common/src/i18n/messages.ts
+++ b/project/backend/libs/common/src/i18n/messages.ts
@@ -168,6 +168,14 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {
'en-US': 'publish record with flowId {{flowId}} not found.',
'zh-CN': '发布记录未找到',
},
+ [ResponseCode.PublishTaskAlreadyPublishing]: {
+ 'en-US': 'Publish task is already publishing',
+ 'zh-CN': '发布任务正在执行中',
+ },
+ [ResponseCode.PublishTaskAlreadyCompleted]: {
+ 'en-US': 'Publish task is already completed',
+ 'zh-CN': '发布任务已完成',
+ },
[ResponseCode.ChannelAccountNotAuthorized]: {
'en-US': 'Account not authorized',
'zh-CN': '账号未授权',
@@ -264,4 +272,8 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {
'en-US': 'Account type not supported for data cube',
'zh-CN': '暂不支持该账户类型',
},
+ [ResponseCode.ChannelPublishTaskAlreadyExists]: {
+ 'en-US': 'publish task with flowId {{flowId}} already exists',
+ 'zh-CN': '发布任务已存在',
+ },
}
diff --git a/project/backend/libs/statistics-db/src/common/post.ts b/project/backend/libs/statistics-db/src/common/post.ts
index 28f4305e..b859c790 100644
--- a/project/backend/libs/statistics-db/src/common/post.ts
+++ b/project/backend/libs/statistics-db/src/common/post.ts
@@ -1,5 +1,6 @@
export interface PostData {
id: string // '记录ID',
+ accountId: string // '账户ID',
postId: string // '帖子ID',
platform: string // describe('平台'),
title: string // nullable;.describe('标题'),
diff --git a/project/backend/libs/statistics-db/src/repositories/post.repository.ts b/project/backend/libs/statistics-db/src/repositories/post.repository.ts
index c7b7a283..f8734440 100644
--- a/project/backend/libs/statistics-db/src/repositories/post.repository.ts
+++ b/project/backend/libs/statistics-db/src/repositories/post.repository.ts
@@ -109,6 +109,7 @@ export class PostRepository extends BaseRepository<PostModel> {
const posts: PostData[] = (postDocs).map(doc => ({
id: doc._id.toString(),
+ accountId: doc.accountId ?? '',
postId: doc.postId ?? '',
platform: doc.platform ?? platform,
title: doc.title ?? '',
@@ -168,6 +169,7 @@ export class PostRepository extends BaseRepository<PostModel> {
const posts: PostData[] = (postDocs).map(doc => ({
id: doc._id.toString(),
+ accountId: doc.accountId ?? '',
postId: doc.postId ?? '',
platform: doc.platform ?? platform,
title: doc.title ?? null,
@@ -369,6 +371,7 @@ export class PostRepository extends BaseRepository<PostModel> {
})
const posts: PostData[] = postDocs.map(doc => ({
id: doc.id,
+ accountId: doc.accountId ?? '',
postId: doc.postId ?? '',
platform: doc.platform,
title: doc.title ?? null,
@@ -430,6 +433,7 @@ export class PostRepository extends BaseRepository<PostModel> {
const posts: PostData[] = postDocs.map(doc => ({
id: doc._id.toString(),
+ accountId: doc.accountId ?? '',
postId: doc.postId ?? '',
platform: doc.platform ?? platform,
title: doc.title ?? null,
diff --git a/project/backend/libs/statistics-db/src/schemas/posts.schema.ts b/project/backend/libs/statistics-db/src/schemas/posts.schema.ts
index 5366e933..f3231eca 100644
--- a/project/backend/libs/statistics-db/src/schemas/posts.schema.ts
+++ b/project/backend/libs/statistics-db/src/schemas/posts.schema.ts
@@ -150,6 +150,11 @@ export class PostDatas extends WithTimestampSchema {
})
userId: string
+ @Prop({
+ required: false, // 平台账户的唯一ID˝
+ })
+ accountId?: string
+
@Prop({
required: false,
})