Skip to content

Let's use AI to Earn!

feat(publishing): support update published posts for Youtube/Facebook (#241)

wheat37fca5aa2e1a
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/base.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/base.service.ts
new file mode 100644
index 00000000..96607356
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/base.service.ts
@@ -0,0 +1,14 @@
+import { Injectable, Logger } from '@nestjs/common'
+
+@Injectable()
+export abstract class PlatformBaseService {
+ protected readonly platform: string = 'platform'
+ protected readonly logger = new Logger(PlatformBaseService.name)
+
+ constructor() { }
+
+ abstract getAccessTokenStatus(accountId: string): Promise<number>
+ async deletePost(_accountId: string, _postId: string): Promise<boolean> {
+ throw new Error(`${this.platform} delete post is not supported`)
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts
index 4bb53d65..a6491067 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/base.service.ts
@@ -5,13 +5,14 @@ import { Model } from 'mongoose'
import { getCurrentTimestamp } from '../../../common'
import { OAuth2Credential } from '../../../libs/database/schema/oauth2Credential.schema'
+import { PlatformBaseService } from '../base.service'
import { META_TIME_CONSTANTS, MetaRedisKeys } from './constants'
import { MetaUserOAuthCredential } from './meta.interfaces'
@Injectable()
-export class MetaBaseService {
- protected readonly platform: string = 'meta'
- protected readonly logger = new Logger(MetaBaseService.name)
+export class MetaBaseService extends PlatformBaseService {
+ protected override readonly platform: string = 'meta'
+ protected override readonly logger = new Logger(MetaBaseService.name)
@InjectModel(OAuth2Credential.name)
protected readonly oAuth2CredentialModel: Model<OAuth2Credential>
@@ -19,7 +20,9 @@ export class MetaBaseService {
@Inject(RedisService)
protected readonly redisService: RedisService
- constructor() { }
+ constructor() {
+ super()
+ }
protected async getOAuth2Credential(accountId: string): Promise<MetaUserOAuthCredential | null> {
let key = MetaRedisKeys.getAccessTokenKey(this.platform, accountId)
@@ -71,4 +74,14 @@ export class MetaBaseService {
const saved = cached && (persistResult.modifiedCount > 0 || persistResult.upsertedCount > 0)
return saved
}
+
+ override async getAccessTokenStatus(
+ accountId: string,
+ ): Promise<number> {
+ const credential = await this.getOAuth2Credential(accountId)
+ if (!credential) {
+ return 0
+ }
+ return credential.expires_in > getCurrentTimestamp() ? 1 : 0
+ }
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts
index b9e1b789..843039b7 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/facebook.service.ts
@@ -33,6 +33,8 @@ import {
PublishMediaPostResponse,
PublishVideoPostRequest,
publishVideoPostResponse,
+ UpdatePostRequest,
+ UpdatePostResponse,
UploadPhotoResponse,
} from '../../../libs/facebook/facebook.interfaces'
import { FacebookService as FacebookAPIService } from '../../../libs/facebook/facebook.service'
@@ -205,12 +207,12 @@ export class FacebookService extends MetaBaseService {
return await this.facebookAPIService.publishFeedPost(credential.id, credential.access_token, req)
}
- async publishVideoPost(
+ async publishVideo(
accountId: string,
req: PublishVideoPostRequest,
): Promise<publishVideoPostResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.publishVideoPost(credential.id, credential.access_token, req)
+ return await this.facebookAPIService.publishVideo(credential.id, credential.access_token, req)
}
async uploadImage(
@@ -221,13 +223,13 @@ export class FacebookService extends MetaBaseService {
return await this.facebookAPIService.uploadPostPhotoByFile(credential.id, credential.access_token, file)
}
- async publicPhotoPost(
+ async publicPhotos(
accountId: string,
imageUrlList: string[],
caption?: string,
): Promise<PublishMediaPostResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.publishMultiplePhotoPost(credential.id, credential.access_token, imageUrlList, caption)
+ return await this.facebookAPIService.publishPhotos(credential.id, credential.access_token, imageUrlList, caption)
}
async getObjectInfo(accountId: string, objectId: string, fields?: string): Promise<FacebookObjectInfo> {
@@ -335,21 +337,21 @@ export class FacebookService extends MetaBaseService {
}
}
- async initReelUpload(
+ async initReelVideoUpload(
accountId: string,
req: FacebookReelRequest,
): Promise<FacebookReelResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.initReelUpload(credential.id, credential.access_token, req)
+ return await this.facebookAPIService.initReelVideoUpload(credential.id, credential.access_token, req)
}
- async uploadReel(
+ async uploadReelVideo(
accountId: string,
uploadURL: string,
req: FacebookReelUploadRequest,
): Promise<FacebookReelUploadResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.uploadReel(credential.access_token, uploadURL, req)
+ return await this.facebookAPIService.uploadReelVideo(credential.access_token, uploadURL, req)
}
async publishReel(
@@ -360,21 +362,21 @@ export class FacebookService extends MetaBaseService {
return await this.facebookAPIService.publishReelPost(credential.id, credential.access_token, req)
}
- async initVideoStoryUpload(
+ async initStoryVideoUpload(
accountId: string,
req: FacebookReelRequest,
): Promise<FacebookReelResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.initVideoStoryUpload(credential.id, credential.access_token, req)
+ return await this.facebookAPIService.initStoryVideoUpload(credential.id, credential.access_token, req)
}
- async uploadVideoStory(
+ async uploadStoryVideo(
accountId: string,
uploadURL: string,
req: FacebookReelUploadRequest,
): Promise<FacebookReelUploadResponse> {
const credential = await this.authorizePage(accountId)
- return await this.facebookAPIService.uploadVideoStory(credential.access_token, uploadURL, req)
+ return await this.facebookAPIService.uploadStoryVideo(credential.access_token, uploadURL, req)
}
async publishVideoStory(
@@ -457,12 +459,13 @@ export class FacebookService extends MetaBaseService {
return await this.facebookAPIService.fetchPostAttachments(postId, credential.access_token)
}
- async deletePost(
+ override async deletePost(
accountId: string,
postId: string,
- ): Promise<void> {
+ ): Promise<boolean> {
const credential = await this.authorizePage(accountId)
- await this.facebookAPIService.deletePost(postId, credential.access_token)
+ const result = await this.facebookAPIService.deletePost(postId, credential.access_token)
+ return result.success
}
async likePost(
@@ -482,4 +485,13 @@ export class FacebookService extends MetaBaseService {
const objectId = postId.includes('_') ? postId : `${credential.id}_${postId}`
return await this.facebookAPIService.unlikeObject(objectId, credential.access_token)
}
+
+ async updatePost(
+ accountId: string,
+ postId: string,
+ req: UpdatePostRequest,
+ ): Promise<UpdatePostResponse> {
+ const credential = await this.authorizePage(accountId)
+ return await this.facebookAPIService.updatePost(postId, credential.access_token, req)
+ }
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts
index 859584dc..cdf92f89 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/linkedin.service.ts
@@ -161,11 +161,12 @@ export class LinkedinService extends MetaBaseService {
return await this.linkedinAPIService.createShare(credential.access_token, createShareReq)
}
- async deletePost(accountId: string, shareId: string) {
+ override async deletePost(accountId: string, shareId: string) {
const credential = await this.authorize(accountId)
if (!credential) {
throw new Error('Failed to authorize')
}
- return await this.linkedinAPIService.deletePost(credential.access_token, shareId)
+ await this.linkedinAPIService.deletePost(credential.access_token, shareId)
+ return true
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
index 4c4d6a2d..37a0d0f7 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/meta/threads.service.ts
@@ -269,10 +269,16 @@ export class ThreadsService extends MetaBaseService {
return result
}
- async deletePost(
+ override async deletePost(
+ accountId: string,
postId: string,
- accessToken: string,
- ): Promise<void> {
- return await this.threadsAPIService.deletePost(postId, accessToken)
+ ): Promise<boolean> {
+ const credential = await this.authorize(accountId)
+ if (!credential) {
+ this.logger.error(`No valid access token found for accountId: ${accountId}`)
+ return false
+ }
+ const result = await this.threadsAPIService.deletePost(postId, credential.access_token)
+ return result.success
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts
index acd2049c..55158932 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.controller.ts
@@ -92,7 +92,7 @@ export class PinterestController {
})
@Post('plat/pinterest/delPinById')
delPinById(@Body() data: { id: string, accountId: string }) {
- return this.pinterestService.delPinById(data.id, data.accountId)
+ return this.pinterestService.deletePost(data.accountId, data.id)
}
// 上传视频获取视频id
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
index b0df018f..5342541f 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/pinterest/pinterest.service.ts
@@ -21,11 +21,13 @@ import {
ILoginStatus,
} from '../../../libs/pinterest/common'
import { PinterestApiService } from '../../../libs/pinterest/pinterestApi.service'
+import { PlatformBaseService } from '../base.service'
import { META_TIME_CONSTANTS } from '../meta/constants'
@Injectable()
-export class PinterestService {
- private readonly logger = new Logger(PinterestService.name)
+export class PinterestService extends PlatformBaseService {
+ protected override readonly platform: string = AccountType.PINTEREST
+ protected override readonly logger = new Logger(PinterestService.name)
private readonly redirectURL = config.pinterest.authBackHost
private readonly client_id = config.pinterest.id
@@ -36,7 +38,9 @@ export class PinterestService {
private readonly accountService: AccountService,
@InjectModel(OAuth2Credential.name)
private readonly oAuth2CredentialModel: Model<OAuth2Credential>,
- ) {}
+ ) {
+ super()
+ }
private getAuthDataCacheKey(taskId: string) {
return `channel:pinterest:authTask:${taskId}`
@@ -243,10 +247,11 @@ export class PinterestService {
* @param accountId
* @returns
*/
- async delPinById(id: string, accountId: string) {
+ override async deletePost(accountId: string, postId: string): Promise<boolean> {
const tokenInfo = await this.getUserStat(accountId)
const accessToken = tokenInfo.access_token as string
- return await this.pinterestApiService.deletePin(id, accessToken)
+ await this.pinterestApiService.deletePin(postId, accessToken)
+ return true
}
/**
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/platform.interface.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platform.interface.ts
new file mode 100644
index 00000000..e69de29b
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
index a9ff68d2..40abb958 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.controller.ts
@@ -1,8 +1,7 @@
import { Body, Controller, Logger, Param, Post } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { AccountStatus } from '@yikart/aitoearn-server-client'
-import { ApiDoc } from '@yikart/common'
-import { GenAuthURLDto } from './platforms.dto'
+import { AccountType, ApiDoc } from '@yikart/common'
import { PlatformService } from './platforms.service'
@ApiTags('OpenSource/Core/Platforms/Platforms')
@@ -28,7 +27,6 @@ export class PlatformController {
return await this.platformService.getUserAccounts(userId)
}
- // @NatsMessagePattern('platform.accounts.updateStatus')
@ApiDoc({
summary: 'Update Account Status',
})
@@ -37,13 +35,11 @@ export class PlatformController {
return await this.platformService.updateAccountStatus(data.accountId, data.status)
}
- // @NatsMessagePattern('platform.oauth.authorization.url')
@ApiDoc({
- summary: 'Generate Authorization URL',
+ summary: 'Delete Post',
})
- @Post('platform/oauth/authorization/url')
- async getAuthorizationUrl(@Body() data: GenAuthURLDto) {
- this.logger.debug(`Getting authorization URL for platform: ${data.platform}`)
- return await this.platformService.generateAuthorizationUrl(data)
+ @Post('platform/post/delete')
+ async deletePost(@Body() data: { accountId: string, platform: AccountType, postId: string }) {
+ return await this.platformService.deletePost(data.accountId, data.platform, data.postId)
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
index 0eae5dee..8f952b02 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.module.ts
@@ -1,15 +1,26 @@
import { Module } from '@nestjs/common'
+import { AccountType } from '@yikart/common'
import { BilibiliModule } from './bilibili/bilibili.module'
+import { BilibiliService } from './bilibili/bilibili.service'
import { DumpAvatarConsumer } from './dump-avatar.consumer'
import { KwaiModule } from './kwai/kwai.module'
+import { KwaiService } from './kwai/kwai.service'
+import { FacebookService } from './meta/facebook.service'
+import { InstagramService } from './meta/instagram.service'
+import { LinkedinService } from './meta/linkedin.service'
import { MetaModule } from './meta/meta.module'
+import { ThreadsService } from './meta/threads.service'
import { PinterestModule } from './pinterest/pinterest.module'
+import { PinterestService } from './pinterest/pinterest.service'
import { PlatformController } from './platforms.controller'
import { PlatformService } from './platforms.service'
import { TiktokModule } from './tiktok/tiktok.module'
+import { TiktokService } from './tiktok/tiktok.service'
import { TwitterModule } from './twitter/twitter.module'
+import { TwitterService } from './twitter/twitter.service'
import { WxPlatModule } from './wx-plat/wx-plat.module'
import { YoutubeModule } from './youtube/youtube.module'
+import { YoutubeService } from './youtube/youtube.service'
@Module({
imports: [
@@ -23,7 +34,48 @@ import { YoutubeModule } from './youtube/youtube.module'
YoutubeModule,
],
controllers: [PlatformController],
- providers: [PlatformService, DumpAvatarConsumer],
+ providers: [
+ PlatformService,
+ DumpAvatarConsumer,
+ {
+ provide: 'CHANNEL_PROVIDERS',
+ useFactory: (
+ bilibili: BilibiliService,
+ kwai: KwaiService,
+ youtube: YoutubeService,
+ facebook: FacebookService,
+ instagram: InstagramService,
+ threads: ThreadsService,
+ tiktok: TiktokService,
+ twitter: TwitterService,
+ pinterest: PinterestService,
+ linkedin: LinkedinService,
+ ) => ({
+ [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: [
+ BilibiliService,
+ KwaiService,
+ YoutubeService,
+ FacebookService,
+ InstagramService,
+ ThreadsService,
+ TiktokService,
+ TwitterService,
+ PinterestService,
+ LinkedinService,
+ ],
+ },
+ ],
exports: [],
})
export class PlatModule {}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
index c0253e61..940e1c38 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/platforms.service.ts
@@ -1,46 +1,20 @@
-import { Injectable, Logger } from '@nestjs/common'
+import { Inject, Injectable, Logger } from '@nestjs/common'
import { AccountType } from '@yikart/aitoearn-server-client'
import { RedisService } from '@yikart/redis'
-import { isInstance } from 'class-validator'
import { AccountService } from '../account/account.service'
-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 './platforms.dto'
-import { TiktokService } from './tiktok/tiktok.service'
-import { TwitterService } from './twitter/twitter.service'
-import { YoutubeService } from './youtube/youtube.service'
-// import { WxPlatService } from './wxPlat/wxPlat.service';
+import { PlatformBaseService } from './base.service'
@Injectable()
export class PlatformService {
private readonly logger = new Logger(PlatformService.name)
- private platformServiceMap: { [key in AccountType]?: any } = {}
- constructor(
- private readonly redisService: RedisService,
- private readonly bilibiliService: BilibiliService,
- private readonly kwaiService: KwaiService,
- private readonly metaService: MetaService,
- private readonly pinterestService: PinterestService,
- private readonly tiktokService: TiktokService,
- private readonly twitterService: TwitterService,
- private readonly accountService: AccountService,
- private readonly youtubeService: YoutubeService,
- // private readonly wxPlatService: WxPlatService,
- ) {
- this.platformServiceMap[AccountType.BILIBILI] = this.bilibiliService
- this.platformServiceMap[AccountType.KWAI] = this.kwaiService
- this.platformServiceMap[AccountType.FACEBOOK] = this.metaService
- this.platformServiceMap[AccountType.INSTAGRAM] = this.metaService
- this.platformServiceMap[AccountType.THREADS] = this.metaService
- this.platformServiceMap[AccountType.LINKEDIN] = this.metaService
- this.platformServiceMap[AccountType.PINTEREST] = this.pinterestService
- this.platformServiceMap[AccountType.TIKTOK] = this.tiktokService
- this.platformServiceMap[AccountType.TWITTER] = this.twitterService
- this.platformServiceMap[AccountType.YOUTUBE] = this.youtubeService
- // this.platformServiceMap[AccountType.WxGzh] = this.wxPlatService;
- }
+ @Inject('CHANNEL_PROVIDERS')
+ private readonly platformServices: Record<AccountType, PlatformBaseService>
+
+ @Inject(RedisService)
+ private readonly redisService: RedisService
+
+ @Inject(AccountService)
+ private readonly accountService: AccountService
async getUserAccounts(userId: string) {
const accounts = await this.accountService.getUserAccountList(userId)
@@ -48,89 +22,24 @@ export class PlatformService {
return []
}
for (const account of accounts) {
- const svc = this.platformServiceMap[account.type]
- if (svc && svc.getAccessTokenStatus) {
- if (isInstance(svc, MetaService)) {
- account.status = await svc.getAccessTokenStatus(account._id.toString(), account.type)
- }
- else {
- account.status = await svc.getAccessTokenStatus(account._id.toString())
- }
+ const svc = this.platformServices[account.type]
+ if (svc) {
+ account.status = await svc.getAccessTokenStatus(account._id.toString())
}
}
return accounts
}
+ async deletePost(accountId: string, platform: AccountType, postId: string) {
+ const svc = this.platformServices[platform]
+ if (svc) {
+ return await svc.deletePost(accountId, postId)
+ }
+ return false
+ }
+
async updateAccountStatus(accountId: string, status: number) {
const res = await this.accountService.updateAccountStatus(accountId, status)
return res
}
-
- async generateAuthorizationUrl(data: GenAuthURLDto) {
- const platform = data.platform as AccountType
- const svc = this.platformServiceMap[platform]
- if (!svc) {
- throw new Error(`Unsupported platform: ${data.platform}`)
- }
- let resp: any = null
- switch (platform) {
- case AccountType.BILIBILI:
- resp = await svc.createAuthTask({
- userId: data.userId,
- type: data.type,
- })
- break
- case AccountType.WxGzh:
- resp = await svc.createAuthTask({
- userId: data.userId,
- type: data.type,
- })
- break
- case AccountType.KWAI:
- resp = await svc.createAuthTask({
- userId: data.userId,
- type: data.type,
- })
- break
- case AccountType.FACEBOOK:
- case AccountType.INSTAGRAM:
- case AccountType.THREADS:
- case AccountType.LINKEDIN:
- resp = await svc.generateAuthorizationUrl({
- userId: data.userId,
- platform,
- scopes: data.scopes,
- })
- break
- case AccountType.TIKTOK:
- resp = await svc.getAuthUrl(data.userId, data.scopes)
- break
- case AccountType.TWITTER:
- resp = await svc.generateAuthorizationUrl({
- userId: data.userId,
- platform,
- scopes: data.scopes,
- })
- break
- case AccountType.PINTEREST:
- resp = await svc.getAuth({
- userId: data.userId,
- })
- break
- default:
- throw new Error(`Unsupported platform: ${data.platform}`)
- }
- if (!resp || !resp.taskId) {
- throw new Error(`Failed to generate authorization URL for platform: ${data.platform}`)
- }
- const spaceInfoCached = await this.redisService.setJson(
- `platform:oauth:space:${resp.taskId}`,
- data.spaceId,
- 600,
- )
- if (!spaceInfoCached) {
- throw new Error(`Failed to generate authorization URL for platform: ${data.platform}`)
- }
- return resp
- }
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
index fb8226b3..1891f189 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/twitter/twitter.service.ts
@@ -9,19 +9,20 @@ import { chunkedDownloadFile, fileUrlToBlob, getCurrentTimestamp, getFileSizeFro
import { AccountService } from '../../../core/account/account.service'
import { OAuth2Credential } from '../../../libs/database/schema/oauth2Credential.schema'
import { XMediaCategory, XMediaType } from '../../../libs/twitter/twitter.enum'
-import { TwitterOAuthCredential, XChunkedMediaUploadRequest, XCreatePostRequest, XCreatePostResponse, XDeletePostResponse, XLikePostResponse, XMediaUploadInitRequest, XMediaUploadResponse, XPostDetailResponse, XRePostResponse, XUserTimelineRequest } from '../../../libs/twitter/twitter.interfaces'
+import { TwitterOAuthCredential, XChunkedMediaUploadRequest, XCreatePostRequest, XCreatePostResponse, XLikePostResponse, XMediaUploadInitRequest, XMediaUploadResponse, XPostDetailResponse, XRePostResponse, XUserTimelineRequest } from '../../../libs/twitter/twitter.interfaces'
import { TwitterService as TwitterApiService } from '../../../libs/twitter/twitter.service'
+import { PlatformBaseService } from '../base.service'
import { TWITTER_TIME_CONSTANTS, TwitterRedisKeys } from './constants'
import { UserTimelineDto } from './dto/twitter.dto'
import { TwitterOAuthTaskInfo } from './twitter.interfaces'
@Injectable()
-export class TwitterService {
- private readonly platform = AccountType.TWITTER
+export class TwitterService extends PlatformBaseService {
+ protected override readonly platform: string = AccountType.TWITTER
+ protected override readonly logger = new Logger(TwitterService.name)
private readonly redisService: RedisService
private readonly twitterApiService: TwitterApiService
private readonly accountService: AccountService
- private readonly logger = new Logger(TwitterService.name)
private readonly defaultScopes = [
'tweet.read', // All the Tweets you can view, including Tweets from protected accounts.
'tweet.write', // Tweet and Retweet for you.
@@ -52,6 +53,7 @@ export class TwitterService {
@InjectModel(OAuth2Credential.name)
private OAuth2CredentialModel: Model<OAuth2Credential>,
) {
+ super()
this.redisService = redisService
this.twitterApiService = twitterApiService
this.accountService = accountService
@@ -377,16 +379,13 @@ export class TwitterService {
return await this.twitterApiService.createPost(credential.access_token, post)
}
- public async deletePost(userId: string, tweetId: string): Promise<XDeletePostResponse | null> {
+ override async deletePost(userId: string, tweetId: string): Promise<boolean> {
const credential = await this.authorize(userId)
- if (!credential) {
- this.logger.warn(`No access token found for userId: ${userId}`)
- return null
- }
- return await this.twitterApiService.deletePost(
+ const result = await this.twitterApiService.deletePost(
credential.access_token,
tweetId,
)
+ return result.data.deleted
}
public async getMediaUploadStatus(
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts
index aabc0c40..6a9fb0e6 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.controller.ts
@@ -561,7 +561,7 @@ export class YoutubeController {
@Post('plat/youtube/deleteVideo')
async deleteVideo(@Body() data: DeleteVideoDto) {
try {
- const res = await this.youtubeService.deleteVideo(
+ const res = await this.youtubeService.deletePost(
data.accountId,
data.id,
)
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts
index 96fe1f28..1a7c95b2 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/youtube/youtube.service.ts
@@ -25,6 +25,7 @@ import {
TokenStatus,
} from '../../../libs/database/schema/oauth2Credential.schema'
import { YoutubeApiService } from '../../../libs/youtube/youtubeApi.service'
+import { PlatformBaseService } from '../base.service'
interface AuthTaskInfo {
state: string
@@ -41,14 +42,14 @@ interface AuthTaskInfo {
}
@Injectable()
-export class YoutubeService {
+export class YoutubeService extends PlatformBaseService {
private youtubeClient = google.youtube('v3')
private webClientSecret: string
private webClientId: string
private webRenderBaseUrl: string
private oauth2Client: Auth.OAuth2Client
- private readonly platform = AccountType.YOUTUBE
- private readonly logger = new Logger(YoutubeService.name)
+ protected override readonly platform: string = AccountType.YOUTUBE
+ protected override readonly logger = new Logger(YoutubeService.name)
constructor(
private readonly redisService: RedisService,
@@ -59,6 +60,7 @@ export class YoutubeService {
@InjectModel(OAuth2Credential.name)
private OAuth2CredentialModel: Model<OAuth2Credential>,
) {
+ super()
this.webClientSecret = config.youtube.secret
this.webClientId = config.youtube.id
this.webRenderBaseUrl = config.youtube.authBackHost
@@ -1379,25 +1381,25 @@ export class YoutubeService {
/**
* 删除视频
*/
- async deleteVideo(accountId: string, videoId: string) {
+ override async deletePost(accountId: string, postId: string): Promise<boolean> {
// 使用封装的辅助方法
if (!(await this.ensureValidAccessToken(accountId))) {
this.logger.log(`get youtube access token error. accountId" ${accountId}`)
- return new AppException(ResponseCode.ChannelAccessTokenFailed)
+ throw new AppException(ResponseCode.ChannelAccessTokenFailed)
}
try {
const response = await this.youtubeClient.videos.delete({
auth: this.oauth2Client,
- id: videoId,
+ id: postId,
})
this.logger.log('Video deleted:', response.data)
- return response
+ return true
}
catch (error) {
this.logger.error('Error deleting video:', error)
- return error
+ throw new Error(error.message)
}
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/update-published-post.consumer.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/update-published-post.consumer.ts
new file mode 100644
index 00000000..2228766f
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/consumers/update-published-post.consumer.ts
@@ -0,0 +1,125 @@
+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 } from 'bullmq'
+import { PublishStatus } from '../../../libs/database/schema/publishTask.schema'
+import { PublishingErrorHandler } from '../error-handler.service'
+import { PublishService } from '../providers/base.service'
+import { PublishingTaskResult } from '../publishing.interface'
+import { PublishingService } from '../publishing.service'
+
+@Processor(QueueName.UpdatePublishedPost, {
+ concurrency: 3,
+ stalledInterval: 15000,
+ maxStalledCount: 1,
+})
+export class UpdatePublishedPostConsumer extends WorkerHost implements OnModuleDestroy {
+ private readonly logger = new Logger(UpdatePublishedPostConsumer.name)
+ @Inject('PUBLISHING_PROVIDERS')
+ private readonly publishingProviders: Record<AccountType, PublishService>
+
+ constructor(
+ readonly publishingService: PublishingService,
+ private readonly publishingErrorHandler: PublishingErrorHandler,
+ ) {
+ super()
+ }
+
+ async process(
+ job: Job<{
+ taskId: string
+ updatedContentType: string
+ attempts: number
+ jobId?: string
+ timeout?: number
+ }>,
+ ): Promise<PublishingTaskResult | void> {
+ const { taskId, updatedContentType, attempts } = job.data
+ this.logger.log(`[task-${taskId}] Processing Update Published Post Task, data: ${JSON.stringify(job.data)}, Attempts: ${attempts}`)
+
+ try {
+ const publishTaskInfo = await this.publishingService.getPublishTaskInfo(taskId)
+ if (!publishTaskInfo) {
+ this.logger.error(`[task-${taskId}] Update published post task not found: ${taskId}`)
+ return
+ }
+
+ if (publishTaskInfo.status !== PublishStatus.WAITING_FOR_UPDATE) {
+ this.logger.warn(`[task-${taskId}] Update published post task not waiting for update: ${taskId}`)
+ return
+ }
+
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.UPDATING,
+ 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.updatePublishedPost(taskInfo, updatedContentType)
+ if (result.status === PublishStatus.PUBLISHED) {
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: PublishStatus.PUBLISHED,
+ errorMsg: '',
+ inQueue: false,
+ queued: false,
+ })
+ }
+ else {
+ await this.publishingService.updatePublishTaskStatus(taskId, {
+ status: result.status,
+ errorMsg: '',
+ inQueue: false,
+ queued: false,
+ })
+ }
+ }
+ catch (error: unknown) {
+ await this.publishingErrorHandler.handle(taskId, error, job)
+ }
+ }
+
+ @OnWorkerEvent('completed')
+ async onCompleted(job: Job<{
+ taskId: string
+ attempts: number
+ jobId?: string
+ }>) {
+ const { taskId, attempts, jobId } = job.data
+ this.logger.log(`[task-${taskId}] Update published post task 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}] Update published post 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}] Update published post task failed after ${job.attemptsMade} attempts, error: ${error.toString()}`)
+ await this.publishingService.updatePublishTaskStatus(job.data.taskId, {
+ status: PublishStatus.UPDATED_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('UpdatePublishedPostConsumer is being destroyed, closing worker...')
+ await this.worker.close()
+ this.logger.log('UpdatePublishedPostConsumer closed successfully')
+ }
+}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts
index c77fdbe5..15356bd3 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/dto/publish.dto.ts
@@ -153,6 +153,16 @@ export const CreatePublishSchema = z.object({
})
export class CreatePublishDto extends createZodDto(CreatePublishSchema) {}
+export const UpdatePublishTaskSchema = z.object({
+ id: z.string({ message: '任务ID' }),
+ userId: z.string({ message: '用户ID' }),
+ desc: z.string().optional(),
+ videoUrl: z.string().optional(),
+ imgUrlList: z.array(z.string()).optional(),
+ topics: z.array(z.string()).optional(),
+})
+export class UpdatePublishTaskDto extends createZodDto(UpdatePublishTaskSchema) {}
+
/**
* 创建发布记录
*/
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
index c10abff8..951f0a09 100644
--- 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
@@ -43,6 +43,13 @@ export abstract class PublishService {
): Promise<PublishingTaskResult | void> {
}
+ async updatePublishedPost(
+ publishTask: PublishTask,
+ _updatedContentType: string,
+ ): Promise<PublishingTaskResult> {
+ throw new Error(`${publishTask.accountType} does not support update published post`)
+ }
+
protected async getMediaProcessingStatus(
_accountId: string,
_mediaId: string,
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
index 9e3c8d91..ecd2e4da 100644
--- 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
@@ -52,12 +52,67 @@ export class FacebookPublishService
return uploadReq.id
}
+ async uploadVideo(accountId: string, videoUrl: string): Promise<string> {
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('Video requires a video URL')
+ }
+ const contentLength = await getRemoteFileSize(videoUrl)
+ if (!contentLength) {
+ throw PublishingException.nonRetryable('get video meta failed')
+ }
+ 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')
+ }
+ return initUploadRes.video_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(
+ const initUploadRes = await this.facebookService.initReelVideoUpload(
accountId,
initUploadReq,
)
@@ -67,7 +122,7 @@ export class FacebookPublishService
}
const videoFile = await chunkedDownloadFile(videoUrl, [0, contentLength - 1])
- const uploadRes = await this.facebookService.uploadReel(
+ const uploadRes = await this.facebookService.uploadReelVideo(
accountId,
initUploadRes.upload_url,
{
@@ -82,12 +137,12 @@ export class FacebookPublishService
return initUploadRes.video_id
}
- async uploadVideoStory(accountId: string, videoUrl: string): Promise<string> {
+ async uploadStoryVideo(accountId: string, videoUrl: string): Promise<string> {
const contentLength = await getRemoteFileSize(videoUrl)
const initUploadReq: FacebookReelRequest = {
upload_phase: 'start',
}
- const initUploadRes = await this.facebookService.initVideoStoryUpload(
+ const initUploadRes = await this.facebookService.initStoryVideoUpload(
accountId,
initUploadReq,
)
@@ -96,7 +151,7 @@ export class FacebookPublishService
throw new Error('Video initialization upload failed')
}
const videoFile = await chunkedDownloadFile(videoUrl, [0, contentLength - 1])
- await this.facebookService.uploadVideoStory(
+ await this.facebookService.uploadStoryVideo(
accountId,
initUploadRes.upload_url,
{
@@ -108,7 +163,7 @@ export class FacebookPublishService
return initUploadRes.video_id
}
- async publishFeedPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ async publishFeed(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')
@@ -129,7 +184,7 @@ export class FacebookPublishService
}
}
- async publishReelPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ async publishReel(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) {
@@ -176,7 +231,7 @@ export class FacebookPublishService
if (!publishTask.videoUrl) {
throw PublishingException.nonRetryable('Story requires a video URL')
}
- const videoId = await this.uploadVideoStory(publishTask.accountId, publishTask.videoUrl)
+ const videoId = await this.uploadStoryVideo(publishTask.accountId, publishTask.videoUrl)
await this.processUploadMedia(publishTask, 'facebook', PostCategory.STORY, PostSubCategory.VIDEO, videoId)
return {
status: PublishStatus.PUBLISHING,
@@ -196,101 +251,49 @@ export class FacebookPublishService
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
+ async publishPhotos(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { imgUrlList, accountId } = publishTask
+ if (!imgUrlList) {
+ throw PublishingException.nonRetryable('Photos requires images')
}
+ const medias: string[] = []
+ for (const imgUrl of imgUrlList) {
+ const mediaId = await this.uploadImage(accountId, imgUrl)
+ medias.push(mediaId)
+ }
+ if (medias.length === 0) {
+ throw PublishingException.nonRetryable('Image upload failed')
+ }
+ const publishPost = await this.facebookService.publicPhotos(
+ accountId,
+ medias,
+ this.generatePostMessage(publishTask),
+ )
+ const permalink = `https://www.facebook.com/${publishTask.uid}_${publishPost.id}`
+ return {
+ postId: publishPost.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
+ }
+ }
- 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
+ async publishVideo(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const videoId = await this.uploadVideo(publishTask.accountId, publishTask.videoUrl)
+ const videoPostReq: PublishVideoPostRequest = {
+ description: this.generatePostMessage(publishTask),
+ crossposted_video_id: videoId,
+ published: true,
+ }
+ const postRes = await this.facebookService.publishVideo(
+ publishTask.accountId,
+ videoPostReq,
+ )
+ const permalink = `https://www.facebook.com/${publishTask.uid}_${postRes.id}`
+ return {
+ postId: postRes.id,
+ permalink,
+ status: PublishStatus.PUBLISHED,
}
- throw PublishingException.nonRetryable('Invalid publish task: no media and no description')
}
async immediatePublish(publishTask: PublishTask): Promise<PublishingTaskResult> {
@@ -305,13 +308,16 @@ export class FacebookPublishService
switch (contentCategory) {
case 'post':
if (!imgUrlList && !videoUrl) {
- return await this.publishFeedPost(publishTask)
+ return await this.publishFeed(publishTask)
}
- else {
+ else if (videoUrl) {
return await this.publishVideo(publishTask)
}
+ else {
+ return await this.publishPhotos(publishTask)
+ }
case 'reel':
- return await this.publishReelPost(publishTask)
+ return await this.publishReel(publishTask)
case 'story':
return await this.publishStory(publishTask)
default:
@@ -381,4 +387,83 @@ export class FacebookPublishService
status: PublishStatus.PUBLISHED,
}
}
+
+ async updateTextPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { desc, dataId } = publishTask
+ if (!desc) {
+ throw PublishingException.nonRetryable('Invalid publish task: no description')
+ }
+ if (!dataId) {
+ throw PublishingException.nonRetryable('Invalid publish task: no postId')
+ }
+ const message = this.generatePostMessage(publishTask)
+ await this.facebookService.updatePost(publishTask.accountId, publishTask.dataId, {
+ message,
+ })
+ return {
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async updateVideoPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { videoUrl, dataId } = publishTask
+ if (!videoUrl) {
+ throw PublishingException.nonRetryable('Invalid publish task: no video URL')
+ }
+ if (!dataId) {
+ throw PublishingException.nonRetryable('Invalid publish task: no postId')
+ }
+ const videoId = await this.uploadVideo(publishTask.accountId, videoUrl)
+ await this.facebookService.updatePost(publishTask.accountId, publishTask.dataId, {
+ attachments: [{
+ media_fbid: videoId,
+ }],
+ })
+ return {
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ async updatePhotosPost(publishTask: PublishTask): Promise<PublishingTaskResult> {
+ const { imgUrlList, dataId } = publishTask
+ if (!imgUrlList) {
+ throw PublishingException.nonRetryable('Invalid publish task: no images')
+ }
+ if (!dataId) {
+ throw PublishingException.nonRetryable('Invalid publish task: no postId')
+ }
+ const medias: string[] = []
+ for (const imgUrl of imgUrlList) {
+ const mediaId = await this.uploadImage(publishTask.accountId, imgUrl)
+ medias.push(mediaId)
+ }
+ if (medias.length === 0) {
+ throw PublishingException.nonRetryable('Image upload failed')
+ }
+ await this.facebookService.updatePost(publishTask.accountId, publishTask.dataId, {
+ attachments: medias.map(mediaId => ({
+ media_fbid: mediaId,
+ })),
+ })
+ return {
+ status: PublishStatus.PUBLISHED,
+ }
+ }
+
+ override async updatePublishedPost(publishTask: PublishTask, updatedContentType: string): Promise<PublishingTaskResult> {
+ const contentCategory = publishTask.option?.facebook?.content_category
+ if (!contentCategory) {
+ throw PublishingException.nonRetryable('Invalid publish task: no Facebook page contentCategory specified')
+ }
+ switch (updatedContentType) {
+ case 'text':
+ return await this.updateTextPost(publishTask)
+ case 'video':
+ return await this.updateVideoPost(publishTask)
+ case 'image':
+ return await this.updatePhotosPost(publishTask)
+ default:
+ throw PublishingException.nonRetryable(`Unsupported content category: ${contentCategory} for update`)
+ }
+ }
}
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
index f2100c0a..67a6a241 100644
--- 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
@@ -78,4 +78,18 @@ export class YoutubePubService extends PublishService {
throw PublishingException.nonRetryable('error publishing video', error)
}
}
+
+ override async updatePublishedPost(publishTask: PublishTask, _updatedContentType: string): Promise<PublishingTaskResult> {
+ if (!publishTask.dataId) {
+ throw PublishingException.nonRetryable('Invalid publish task: no postId')
+ }
+ await this.youtubeService.updateVideo(publishTask.accountId, publishTask.dataId, {
+ title: publishTask.title,
+ description: publishTask.desc,
+ tags: publishTask.topics,
+ }, publishTask.option?.youtube?.privacyStatus, {})
+ return {
+ status: PublishStatus.PUBLISHED,
+ }
+ }
}
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
index 247d7cfc..96918c3e 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.controller.ts
@@ -6,6 +6,7 @@ import {
DeletePublishTaskDto,
NowPubTaskDto,
PublishRecordListFilterDto,
+ UpdatePublishTaskDto,
UpPublishTaskTimeDto,
} from './dto/publish.dto'
import { TiktokWebhookDto, TiktokWebhookSchema } from './dto/tiktok-webhook.dto'
@@ -23,6 +24,11 @@ export class PublishingController {
return await this.publishingService.createPublishingTask(data)
}
+ @Post('plat/publish/update')
+ async updatePublishingTask(@Body() data: UpdatePublishTaskDto) {
+ return await this.publishingService.updatePublishingTask(data)
+ }
+
@Post('plat/publish/changeTime')
async changeTaskTime(@Body() data: UpPublishTaskTimeDto) {
data.publishTime = new Date(data.publishTime)
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
index 31a5e57d..dec29927 100644
--- a/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/publishing.service.ts
@@ -9,7 +9,7 @@ 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 { CreatePublishDto, PublishRecordListFilterDto, UpdatePublishTaskDto } from './dto/publish.dto'
import { TiktokWebhookDto } from './dto/tiktok-webhook.dto'
import { TiktokPubService } from './providers/tiktok.service'
@@ -88,7 +88,7 @@ export class PublishingService implements OnModuleDestroy {
now - IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS,
]
- const publishImmediately = publishTime.getTime() >= immediatePublishWindow[0] && publishTime.getTime() <= immediatePublishWindow[1]
+ const publishImmediately = publishTime.getTime() <= immediatePublishWindow[1]
if (!publishImmediately) {
this.logger.log(`Publish task ${newTask.id} created, scheduled for ${publishTime.toISOString()}`)
return newTask
@@ -101,6 +101,44 @@ export class PublishingService implements OnModuleDestroy {
return newTask
}
+ async updatePublishingTask(data: UpdatePublishTaskDto) {
+ const supportPlatforms = [AccountType.FACEBOOK, AccountType.YOUTUBE]
+ const task = await this.publishTaskModel.findById(data.id).exec()
+ if (!task || task.userId !== data.userId) {
+ throw new AppException(ResponseCode.PublishTaskNotFound)
+ }
+ if (task.status !== PublishStatus.PUBLISHED) {
+ throw new AppException(ResponseCode.PublishTaskNotPublished)
+ }
+
+ if (!supportPlatforms.includes(task.accountType)) {
+ throw new AppException(ResponseCode.PlatformNotSupported, 'Facebook and Youtube are supported for update')
+ }
+
+ if (task.option && task.option.facebook) {
+ if (task.option.facebook.content_category !== 'post') {
+ throw new AppException(ResponseCode.PostCategoryNotSupported, 'only post category is supported for Facebook')
+ }
+ }
+ let updatedContentType = 'text'
+ if (data.videoUrl) {
+ updatedContentType = 'video'
+ }
+ else if (data.imgUrlList) {
+ updatedContentType = 'image'
+ }
+
+ await this.publishTaskModel.updateOne({ _id: data.id }, {
+ desc: data.desc,
+ videoUrl: data.videoUrl,
+ imgUrlList: data.imgUrlList,
+ topics: data.topics,
+ status: PublishStatus.WAITING_FOR_UPDATE,
+ }).exec()
+ await this.enqueueUpdatePublishedPostTask(task, updatedContentType)
+ return true
+ }
+
async enqueuePublishingTask(task: PublishTask): Promise<boolean> {
const jobId = uuidv4().toString()
await this.publishTaskModel.updateOne({ _id: task.id }, { queueId: jobId })
@@ -124,12 +162,33 @@ export class PublishingService implements OnModuleDestroy {
return jobRes.id === jobId
}
+ async enqueueUpdatePublishedPostTask(task: PublishTask, updatedContentType: string): Promise<boolean> {
+ const jobId = uuidv4().toString()
+ await this.publishTaskModel.updateOne({ _id: task.id }, { queueId: jobId })
+ const jobRes = await this.queueService.addUpdatePublishedPostJob(
+ {
+ taskId: task.id,
+ updatedContentType,
+ },
+ {
+ 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 },
+ publishTime: { $lte: end },
status: PublishStatus.WaitingForPublish,
}
const list = await this.publishTaskModel.find(filters).sort({
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
index 9b4c82f9..fba42a8b 100644
--- 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
@@ -16,27 +16,21 @@ export class EnqueuePublishingTaskScheduler {
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 cutoffTime = new Date(now + IMMEDIATE_PUBLISH_TOLERANCE_SECONDS)
- const tasks = await this.publishingService.getPublishTaskListByTime(start, end)
+ const tasks = await this.publishingService.getPublishTaskListByTime(cutoffTime)
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()}`)
+ this.logger.log(`Pushing scheduled publish tasks completed: No scheduled publish tasks found before ${cutoffTime.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()}`)
+ this.logger.log(`Pushing scheduled publish tasks completed: ${tasks.length} tasks found before ${cutoffTime.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/libs/database/schema/publishTask.schema.ts b/project/backend/apps/aitoearn-channel/src/libs/database/schema/publishTask.schema.ts
index 31796aec..8e839da5 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
@@ -14,6 +14,9 @@ export enum PublishStatus {
WaitingForPublish = 0, // 未发布
PUBLISHED = 1, // 已发布
PUBLISHING = 2, // 发布中
+ WAITING_FOR_UPDATE = 3, // 等待更新
+ UPDATING = 4, // 更新中
+ UPDATED_FAILED = 5, // 更新失败
}
@Schema({
diff --git a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.interfaces.ts b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.interfaces.ts
index 7e8b2201..283e8ba4 100644
--- a/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.interfaces.ts
+++ b/project/backend/apps/aitoearn-channel/src/libs/facebook/facebook.interfaces.ts
@@ -403,3 +403,24 @@ export interface FacebookPostAttachmentsResponse {
export interface FacebookLikeResponse {
success: boolean
}
+
+export interface MetaPostAttachment {
+ media_fbid: string
+ message?: string
+ link?: string
+}
+
+export interface UpdatePostRequest {
+ attachments?: MetaPostAttachment[]
+ message?: string
+}
+
+export interface UpdatePostResponse {
+ id?: string
+ success: boolean
+ message?: string
+}
+
+export interface FacebookDeletePostResponse {
+ success: boolean
+}
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 4ade2e4d..88ee99a5 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
@@ -7,6 +7,7 @@ import { FacebookError } from './facebook.exception'
import {
ChunkedVideoUploadRequest,
ChunkedVideoUploadResponse,
+ FacebookDeletePostResponse,
FacebookInitialVideoUploadRequest,
FacebookInitialVideoUploadResponse,
FacebookInsightsRequest,
@@ -41,6 +42,8 @@ import {
PublishVideoForPageResponse,
PublishVideoPostRequest,
publishVideoPostResponse,
+ UpdatePostRequest,
+ UpdatePostResponse,
UploadPhotoResponse,
} from './facebook.interfaces'
import { FacebookOperation } from './facebook.operations'
@@ -170,7 +173,7 @@ export class FacebookService {
// see https://developers.facebook.com/docs/graph-api/reference/page/videos/?locale=en_US#Creating
// https://developers.facebook.com/docs/pages-api/posts#publish-a-video
// https://stackoverflow.com/questions/47284140/facebook-graph-api-publish-post-with-multiple-videos-and-photos
- async publishVideoPost(
+ async publishVideo(
pageId: string,
pageAccessToken: string,
req: PublishVideoPostRequest,
@@ -274,7 +277,7 @@ export class FacebookService {
// immediately publish multiple photos as a single post
// first upload the photos to get their IDs, then use those IDs to create a post
// see https://developers.facebook.com/docs/graph-api/reference/page/photos/#upload
- async publishMultiplePhotoPost(
+ async publishPhotos(
pageId: string,
pageAccessToken: string,
imageIDList: string[],
@@ -451,7 +454,7 @@ export class FacebookService {
return this.request<FacebookInsightsResponse>(url, config, { operation: FacebookOperation.GET_OBJECT_INSIGHTS })
}
- async initReelUpload(
+ async initReelVideoUpload(
pageId: string,
pageAccessToken: string,
req: FacebookReelRequest,
@@ -471,7 +474,7 @@ export class FacebookService {
return this.request<FacebookReelResponse>(url, config, { operation: FacebookOperation.INIT_REEL_UPLOAD })
}
- async uploadReel(
+ async uploadReelVideo(
pageAccessToken: string,
uploadURL: string,
req: FacebookReelUploadRequest,
@@ -505,7 +508,7 @@ export class FacebookService {
return this.request<FacebookReelResponse>(url, config, { operation: FacebookOperation.PUBLISH_REEL_POST })
}
- async initVideoStoryUpload(
+ async initStoryVideoUpload(
pageId: string,
pageAccessToken: string,
req: FacebookReelRequest,
@@ -523,7 +526,7 @@ export class FacebookService {
return this.request<FacebookReelResponse>(url, config, { operation: FacebookOperation.INIT_VIDEO_STORY_UPLOAD })
}
- async uploadVideoStory(
+ async uploadStoryVideo(
pageAccessToken: string,
uploadURL: string,
req: FacebookReelUploadRequest,
@@ -652,7 +655,7 @@ export class FacebookService {
async deletePost(
postId: string,
pageAccessToken: string,
- ): Promise<void> {
+ ): Promise<FacebookDeletePostResponse> {
const url = `${this.apiBaseUrl}/${postId}`
const config: AxiosRequestConfig = {
method: 'DELETE',
@@ -660,7 +663,7 @@ export class FacebookService {
Authorization: `Bearer ${pageAccessToken}`,
},
}
- await this.request<void>(url, config, { operation: FacebookOperation.DELETE_POST })
+ return await this.request<FacebookDeletePostResponse>(url, config, { operation: FacebookOperation.DELETE_POST })
}
async likeObject(
@@ -690,4 +693,20 @@ export class FacebookService {
}
return this.request<FacebookLikeResponse>(url, config, { operation: 'UNLIKE_OBJECT' })
}
+
+ async updatePost(
+ postId: string,
+ pageAccessToken: string,
+ req: UpdatePostRequest,
+ ): Promise<UpdatePostResponse> {
+ const url = `${this.apiBaseUrl}/${postId}`
+ const config: AxiosRequestConfig = {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${pageAccessToken}`,
+ },
+ data: req,
+ }
+ return this.request<UpdatePostResponse>(url, config, { operation: 'UPDATE_POST' })
+ }
}
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 751f7b6d..ec515443 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
@@ -142,3 +142,7 @@ export interface ThreadsLocation {
export interface ThreadsSearchLocationResponse {
data: ThreadsLocation[]
}
+
+export interface ThreadsDeletePostResponse {
+ success: boolean
+}
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 d94571cd..313d4f5d 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
@@ -6,6 +6,7 @@ import { ThreadsError } from './threads.exception'
import {
publicProfileResponse,
ThreadsContainerRequest,
+ ThreadsDeletePostResponse,
ThreadsInsightsRequest,
ThreadsInsightsResponse,
ThreadsObjectCommentsRequest,
@@ -243,7 +244,7 @@ export class ThreadsService {
async deletePost(
postId: string,
accessToken: string,
- ): Promise<void> {
+ ): Promise<ThreadsDeletePostResponse> {
const url = `${this.apiBaseUrl}/${postId}`
const config: AxiosRequestConfig = {
method: 'DELETE',
@@ -251,6 +252,6 @@ export class ThreadsService {
Authorization: `Bearer ${accessToken}`,
},
}
- await this.request<void>(url, config, { operation: 'deletePost' })
+ return await this.request<ThreadsDeletePostResponse>(url, config, { operation: 'deletePost' })
}
}
diff --git a/project/backend/apps/aitoearn-server/src/account/account.module.ts b/project/backend/apps/aitoearn-server/src/account/account.module.ts
index 6612447a..f86dc0e6 100644
--- a/project/backend/apps/aitoearn-server/src/account/account.module.ts
+++ b/project/backend/apps/aitoearn-server/src/account/account.module.ts
@@ -1,4 +1,4 @@
-import { Global, Module } from '@nestjs/common'
+import { forwardRef, Global, Module } from '@nestjs/common'
import { ChannelModule } from '../channel/channel.module'
import { FingerprintController } from '../fingerprint/fingerprint.controller'
import { FingerprintService } from '../fingerprint/fingerprint.service'
@@ -10,7 +10,7 @@ import { AccountGroupService } from './accountGroup.service'
@Global()
@Module({
- imports: [ChannelModule, StatisticsModule],
+ imports: [forwardRef(() => ChannelModule), StatisticsModule],
providers: [FingerprintService, AccountService, AccountGroupService],
controllers: [AccountController, AccountGroupController, FingerprintController],
exports: [AccountService, AccountGroupService],
diff --git a/project/backend/apps/aitoearn-server/src/account/account.service.ts b/project/backend/apps/aitoearn-server/src/account/account.service.ts
index 8a9ef23c..380926a1 100644
--- a/project/backend/apps/aitoearn-server/src/account/account.service.ts
+++ b/project/backend/apps/aitoearn-server/src/account/account.service.ts
@@ -17,6 +17,7 @@ export class AccountService {
private readonly accountRepository: AccountRepository,
@Inject(forwardRef(() => AccountGroupService))
private readonly accountGroupService: AccountGroupService,
+ @Inject(forwardRef(() => ChannelService))
private readonly channelService: ChannelService,
private readonly statisticsService: StatisticsService,
private readonly queueService: QueueService,
diff --git a/project/backend/apps/aitoearn-server/src/channel/channel.controller.ts b/project/backend/apps/aitoearn-server/src/channel/channel.controller.ts
index 51dbc268..4f7c1bb3 100644
--- a/project/backend/apps/aitoearn-server/src/channel/channel.controller.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/channel.controller.ts
@@ -1,9 +1,23 @@
-import { Controller } from '@nestjs/common'
+import { Controller, Delete, Param } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
+import { GetToken, TokenInfo } from '@yikart/aitoearn-auth'
+import { ApiDoc } from '@yikart/common'
import { ChannelService } from './channel.service'
@ApiTags('OpenSource/Channel/Channel')
@Controller('channel')
export class ChannelController {
- constructor(private readonly taskService: ChannelService) { }
+ constructor(private readonly channelService: ChannelService) { }
+
+ @ApiDoc({
+ summary: 'Delete Post',
+ })
+ @Delete(':accountId/post/:postId')
+ async deletePost(
+ @Param('accountId') accountId: string,
+ @Param('postId') postId: string,
+ @GetToken() token: TokenInfo,
+ ) {
+ return await this.channelService.deletePost(accountId, token.id, postId)
+ }
}
diff --git a/project/backend/apps/aitoearn-server/src/channel/channel.module.ts b/project/backend/apps/aitoearn-server/src/channel/channel.module.ts
index 06973a3f..5295519c 100644
--- a/project/backend/apps/aitoearn-server/src/channel/channel.module.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/channel.module.ts
@@ -1,5 +1,6 @@
import { HttpModule } from '@nestjs/axios'
-import { Global, Module } from '@nestjs/common'
+import { forwardRef, Global, Module } from '@nestjs/common'
+import { AccountModule } from '../account/account.module'
import { PublishModule } from '../publishRecord/publishRecord.module'
import { PostModule } from '../statistics/post/post.module'
import { ChannelApiModule } from '../transports/channel/channelApi.module'
@@ -41,6 +42,7 @@ import { YoutubeModule } from './youtube/youtube.module'
EngagementModule,
PostModule,
PublishModule,
+ forwardRef(() => AccountModule),
],
providers: [ChannelService, PublishService],
controllers: [
diff --git a/project/backend/apps/aitoearn-server/src/channel/channel.service.ts b/project/backend/apps/aitoearn-server/src/channel/channel.service.ts
index 6c3ad1bd..a013b9a9 100644
--- a/project/backend/apps/aitoearn-server/src/channel/channel.service.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/channel.service.ts
@@ -1,11 +1,15 @@
-import { Injectable } from '@nestjs/common'
+import { forwardRef, Inject, Injectable } from '@nestjs/common'
+import { AppException, ResponseCode } from '@yikart/common'
import { AccountStatus } from '@yikart/mongodb'
+import { AccountService } from '../account/account.service'
import { ChannelApi } from '../transports/channel/channel.api'
@Injectable()
export class ChannelService {
constructor(
private readonly channelApi: ChannelApi,
+ @Inject(forwardRef(() => AccountService))
+ private readonly accountService: AccountService,
) { }
/**
@@ -25,4 +29,15 @@ export class ChannelService {
)
return res
}
+
+ async deletePost(accountId: string, userId: string, postId: string) {
+ const account = await this.accountService.getAccountById(accountId)
+ if (!account || account.userId !== userId) {
+ throw new AppException(ResponseCode.AccountNotFound)
+ }
+ const res = await this.channelApi.deletePost(
+ { accountId, platform: account.type, postId },
+ )
+ return res
+ }
}
diff --git a/project/backend/apps/aitoearn-server/src/channel/dto/publish.dto.ts b/project/backend/apps/aitoearn-server/src/channel/dto/publish.dto.ts
index c098257f..0e8c098d 100644
--- a/project/backend/apps/aitoearn-server/src/channel/dto/publish.dto.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/dto/publish.dto.ts
@@ -79,3 +79,12 @@ export const listPostHistorySchema = z.object({
accountType: z.enum(AccountType),
})
export class ListPostHistoryDto extends createZodDto(listPostHistorySchema) {}
+
+export const UpdatePublishTaskSchema = z.object({
+ id: z.string({ message: '任务ID' }),
+ desc: z.string().optional(),
+ videoUrl: z.string().optional(),
+ imgUrlList: z.array(z.string()).optional(),
+ topics: z.array(z.string()).optional(),
+})
+export class UpdatePublishTaskDto extends createZodDto(UpdatePublishTaskSchema) {}
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 fec315c8..b775a31e 100644
--- a/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/publish.controller.ts
@@ -18,6 +18,7 @@ import {
PublishDayInfoListFiltersDto,
PubRecordListFilterDto,
UpdatePublishRecordTimeDto,
+ UpdatePublishTaskDto,
} from './dto/publish.dto'
import { PublishService } from './publish.service'
@@ -167,4 +168,13 @@ export class PublishController {
async getPublishRecordDetail(@GetToken() token: TokenInfo, @Param('flowId') flowId: string) {
return this.publishService.getPublishRecordDetail(flowId, token.id)
}
+
+ @ApiDoc({
+ summary: 'Update Publish Task',
+ body: UpdatePublishTaskDto.schema,
+ })
+ @Post('updateTask')
+ async updatePublishTask(@GetToken() token: TokenInfo, @Body() data: UpdatePublishTaskDto) {
+ return this.publishService.updatePublishTask(data, token.id)
+ }
}
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 9ac7e1df..4dfa0423 100644
--- a/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
@@ -11,7 +11,7 @@ import { ChannelApi } from '../transports/channel/channel.api'
import { PublishingChannel } from '../transports/channel/common'
import { NewPublishData, NewPublishRecordData, PlatOptions } from './common'
import { PostHistoryItemVoSchema } from './dto/publish-response.vo'
-import { PublishDayInfoListFiltersDto, PubRecordListFilterDto } from './dto/publish.dto'
+import { PublishDayInfoListFiltersDto, PubRecordListFilterDto, UpdatePublishTaskDto } from './dto/publish.dto'
type PostHistoryItem = z.infer<typeof PostHistoryItemVoSchema>
@@ -254,10 +254,14 @@ export class PublishService {
this.logger.error(`Failed to get publish record detail for flowId ${flowId} and userId ${userId}: ${error.message}`, error.stack)
}
- const task = await this.channelApi.getPublishTaskInfoWithFlowId({ flowId, userId })
+ const task = await this.platPublishNatsApi.getPublishTaskDetail(flowId, userId)
if (!task) {
throw new AppException(ResponseCode.PublishRecordNotFound, { flowId })
}
return task
}
+
+ async updatePublishTask(data: UpdatePublishTaskDto, userId: string) {
+ return await this.platPublishNatsApi.updatePublishTask(data, userId)
+ }
}
diff --git a/project/backend/apps/aitoearn-server/src/transports/channel/api/publish.natsApi.ts b/project/backend/apps/aitoearn-server/src/transports/channel/api/publish.natsApi.ts
index 77b4c014..bc39ec4a 100644
--- a/project/backend/apps/aitoearn-server/src/transports/channel/api/publish.natsApi.ts
+++ b/project/backend/apps/aitoearn-server/src/transports/channel/api/publish.natsApi.ts
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common'
import { AccountType, TableDto } from '@yikart/common'
import { PublishStatus, PublishType } from '@yikart/mongodb'
import { NewPublishData, NewPublishRecordData, PlatOptions } from '../../../channel/common'
-import { PublishDayInfoListFiltersDto } from '../../../channel/dto/publish.dto'
+import { PublishDayInfoListFiltersDto, UpdatePublishTaskDto } from '../../../channel/dto/publish.dto'
import { ChannelBaseApi } from '../../channelBase.api'
import { PublishRecordItem } from './types/publish.interfaces'
@@ -145,4 +145,12 @@ export class PlatPublishNatsApi extends ChannelBaseApi {
)
return res
}
+
+ async updatePublishTask(data: UpdatePublishTaskDto, userId: string) {
+ const res = await this.sendMessage<boolean>(
+ `plat/publish/update`,
+ { ...data, userId },
+ )
+ return res
+ }
}
diff --git a/project/backend/apps/aitoearn-server/src/transports/channel/channel.api.ts b/project/backend/apps/aitoearn-server/src/transports/channel/channel.api.ts
index 5462b739..f4a41a86 100644
--- a/project/backend/apps/aitoearn-server/src/transports/channel/channel.api.ts
+++ b/project/backend/apps/aitoearn-server/src/transports/channel/channel.api.ts
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common'
+import { AccountType } from '@yikart/common'
import { AccountStatus } from '@yikart/mongodb'
import { ChannelBaseApi } from '../channelBase.api'
@@ -30,4 +31,16 @@ export class ChannelApi extends ChannelBaseApi {
)
return res
}
+
+ async deletePost(payload: {
+ accountId: string
+ platform: AccountType
+ postId: string
+ }) {
+ const res = await this.sendMessage<any>(
+ `platform/post/delete`,
+ payload,
+ )
+ return res
+ }
}
diff --git a/project/backend/apps/aitoearn-server/src/transports/channel/common.ts b/project/backend/apps/aitoearn-server/src/transports/channel/common.ts
index f58646c0..fed921c5 100644
--- a/project/backend/apps/aitoearn-server/src/transports/channel/common.ts
+++ b/project/backend/apps/aitoearn-server/src/transports/channel/common.ts
@@ -10,6 +10,9 @@ export enum PublishStatus {
WaitingForPublish = 0, // 未发布
PUBLISHED = 1, // 已发布
PUBLISHING = 2, // 发布中
+ WAITING_FOR_UPDATE = 3, // 等待更新
+ UPDATING = 4, // 更新中
+ UPDATED_FAILED = 5, // 更新失败
}
export interface PublishRecord {
diff --git a/project/backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts b/project/backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts
index 373d84be..12db74ef 100644
--- a/project/backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts
+++ b/project/backend/libs/aitoearn-queue/src/enums/queue-name.enum.ts
@@ -23,4 +23,7 @@ export enum QueueName {
/** dump social media avatar queue */
DumpSocialMediaAvatar = 'dump_social_media_avatar',
+
+ /** 更新发布任务队列 */
+ UpdatePublishedPost = 'update_published_post',
}
diff --git a/project/backend/libs/aitoearn-queue/src/queue.service.ts b/project/backend/libs/aitoearn-queue/src/queue.service.ts
index 89dd25ec..dd3b9401 100644
--- a/project/backend/libs/aitoearn-queue/src/queue.service.ts
+++ b/project/backend/libs/aitoearn-queue/src/queue.service.ts
@@ -36,6 +36,8 @@ export class QueueService {
private engagementReplyToCommentQueue: Queue,
@InjectQueue(QueueName.DumpSocialMediaAvatar)
private dumpSocialMediaAvatarQueue: Queue,
+ @InjectQueue(QueueName.UpdatePublishedPost)
+ private updatePublishedPostQueue: Queue,
) {
// 从配置中读取默认的 job options
this.defaultOptions = config.jobOptions || {
@@ -188,4 +190,11 @@ export class QueueService {
...options,
})
}
+
+ async addUpdatePublishedPostJob(data: { taskId: string, updatedContentType: string }, options?: JobsOptions) {
+ return await this.updatePublishedPostQueue.add('update-published-post', data, {
+ ...this.defaultOptions,
+ ...options,
+ })
+ }
}
diff --git a/project/backend/libs/aitoearn-server-client/src/interfaces/account.interface.ts b/project/backend/libs/aitoearn-server-client/src/interfaces/account.interface.ts
index c51e87f3..44d6cda4 100644
--- a/project/backend/libs/aitoearn-server-client/src/interfaces/account.interface.ts
+++ b/project/backend/libs/aitoearn-server-client/src/interfaces/account.interface.ts
@@ -80,6 +80,9 @@ export enum PublishStatus {
WaitingForPublish = 0, // 未发布
PUBLISHED = 1, // 已发布
PUBLISHING = 2, // 发布中
+ WAITING_FOR_UPDATE = 3, // 等待更新
+ UPDATING = 4, // 更新中
+ UPDATED_FAILED = 5, // 更新失败
}
export interface PublishRecord {
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 b412f482..aea2afe6 100755
--- a/project/backend/libs/common/src/enums/response-code.enum.ts
+++ b/project/backend/libs/common/src/enums/response-code.enum.ts
@@ -93,4 +93,9 @@ export enum ResponseCode {
ChannelPublishTaskAlreadyExists = 15025,
PublishTaskAlreadyPublishing = 15026,
PublishTaskAlreadyCompleted = 15027,
+ PublishTaskNotPublished = 15028,
+ PublishTaskAlreadyUpdating = 15029,
+ PublishTaskAlreadyWaitingForUpdate = 15030,
+ PostCategoryNotSupported = 15031,
+ PlatformNotSupported = 15032,
}
diff --git a/project/backend/libs/common/src/i18n/messages.ts b/project/backend/libs/common/src/i18n/messages.ts
index afc77176..493b22cc 100644
--- a/project/backend/libs/common/src/i18n/messages.ts
+++ b/project/backend/libs/common/src/i18n/messages.ts
@@ -276,4 +276,24 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {
'en-US': 'publish task with flowId {{flowId}} already exists',
'zh-CN': '发布任务已存在',
},
+ [ResponseCode.PublishTaskNotPublished]: {
+ 'en-US': 'Publish task not published',
+ 'zh-CN': '发布任务未发布',
+ },
+ [ResponseCode.PublishTaskAlreadyUpdating]: {
+ 'en-US': 'Publish task is already updating',
+ 'zh-CN': '发布任务正在更新中',
+ },
+ [ResponseCode.PlatformNotSupported]: {
+ 'en-US': 'Platform not supported for update published post',
+ 'zh-CN': '暂不支持该平台',
+ },
+ [ResponseCode.PostCategoryNotSupported]: {
+ 'en-US': 'Post category not supported for update published post',
+ 'zh-CN': '暂不支持该帖子类型',
+ },
+ [ResponseCode.PublishTaskAlreadyWaitingForUpdate]: {
+ 'en-US': 'Publish task is already waiting for update',
+ 'zh-CN': '发布任务已等待更新',
+ },
}
diff --git a/project/backend/libs/mongodb/src/enums/publish.enum.ts b/project/backend/libs/mongodb/src/enums/publish.enum.ts
index 6b769c25..a71544f5 100644
--- a/project/backend/libs/mongodb/src/enums/publish.enum.ts
+++ b/project/backend/libs/mongodb/src/enums/publish.enum.ts
@@ -8,4 +8,7 @@ export enum PublishStatus {
WaitingForPublish = 0, // 未发布
PUBLISHED = 1, // 已发布
PUBLISHING = 2, // 发布中
+ WAITING_FOR_UPDATE = 3, // 等待更新
+ UPDATING = 4, // 更新中
+ UPDATED_FAILED = 5, // 更新失败
}