Skip to content

Let's use AI to Earn!

fix(update-published-post): support update youtube video metadata" (#255)

wheatb71977847242
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 a6491067..5a6c57c0 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
@@ -31,7 +31,7 @@ export class MetaBaseService extends PlatformBaseService {
}
let credential = await this.redisService.getJson<MetaUserOAuthCredential>(key)
if (!credential) {
- this.logger.debug(`No access token found for accountId: ${accountId} in redis`)
+ this.logger.error(`No access token found for accountId: ${this.platform} ${accountId} in redis`)
const oauth2Credential = await this.oAuth2CredentialModel.findOne(
{
accountId,
@@ -39,6 +39,7 @@ export class MetaBaseService extends PlatformBaseService {
},
)
if (!oauth2Credential) {
+ this.logger.error(`No access token found for accountId: ${this.platform} ${accountId} in database`)
return null
}
credential = JSON.parse(oauth2Credential.raw) as MetaUserOAuthCredential
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 8e8f3037..827bf535 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
@@ -24,7 +24,9 @@ export class PlatformService {
for (const account of accounts) {
const svc = this.platformServices[account.type]
if (svc) {
- account.status = await svc.getAccessTokenStatus(account._id.toString())
+ const status = await svc.getAccessTokenStatus(account._id.toString())
+ this.logger.log(`${account.type} access token status: ${status}`)
+ account.status = status
}
}
return accounts
diff --git a/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts
index 440c1e8b..de98c4cd 100644
--- a/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts
+++ b/project/backend/apps/aitoearn-channel/src/core/platforms/tiktok/tiktok.service.ts
@@ -29,6 +29,7 @@ import {
TikTokUserInfoResponse,
} from '../../../libs/tiktok/tiktok.interfaces'
import { TiktokService as TiktokApiService } from '../../../libs/tiktok/tiktok.service'
+import { PlatformBaseService } from '../base.service'
import { TIKTOK_DEFAULT_SCOPES, TIKTOK_TIME_CONSTANTS, TiktokRedisKeys } from './constants'
import {
PhotoSourceInfoDto,
@@ -46,10 +47,10 @@ export interface AuthTaskInfo {
}
@Injectable()
-export class TiktokService {
- private readonly platform = AccountType.TIKTOK
+export class TiktokService extends PlatformBaseService {
+ protected override readonly platform: string = AccountType.TIKTOK
private readonly defaultScopes: string[]
- private readonly logger = new Logger(TiktokService.name)
+ protected override readonly logger = new Logger(TiktokService.name)
constructor(
private readonly redisService: RedisService,
@@ -58,6 +59,7 @@ export class TiktokService {
@InjectModel(OAuth2Credential.name)
private OAuth2CredentialModel: Model<OAuth2Credential>,
) {
+ super()
this.defaultScopes = config.tiktok.scopes.length > 0
? config.tiktok.scopes
: TIKTOK_DEFAULT_SCOPES
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 6a9fb0e6..2afa92cd 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
@@ -28,7 +28,6 @@ import {
UpdateCommentDto,
UpdatePlayItemsDto,
UpdatePlayListDto,
- UpdateVideoDto,
UploadVideoDto,
UploadVideoPartDto,
VideoCategoriesDto,
@@ -573,48 +572,6 @@ export class YoutubeController {
}
}
- // 更新视频
- // @NatsMessagePattern('plat.youtube.updateVideo')
- @ApiDoc({
- summary: 'Update Video Metadata',
- body: UpdateVideoDto.schema,
- })
- @Post('plat/youtube/updateVideo')
- async updateVideo(@Body() data: UpdateVideoDto) {
- try {
- const snippet = {
- title: data.title,
- categoryId: data.categoryId,
- description: data?.description,
- tags: data?.tags?.split(','),
- defaultLanguage: data?.defaultLanguage,
-
- }
-
- const recordingDetails = {
- recordingDate: data?.recordingDate,
- }
-
- const status = {
- privacyStatus: data?.privacyStatus,
- publishAt: data?.publishAt,
- }
-
- const res = await this.youtubeService.updateVideo(
- data.accountId,
- data.id,
- snippet,
- status,
- recordingDetails,
- )
- return res
- }
- catch (error) {
- this.logger.error('更新视频失败:', error)
- return error
- }
- }
-
// 创建播放列表
// @NatsMessagePattern('plat.youtube.insertPlayList')
@ApiDoc({
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 1a7c95b2..872a4c92 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
@@ -13,7 +13,7 @@ import { AccountStatus, AccountType, AitoearnServerClientService, NewAccount } f
import { AppException, ResponseCode } from '@yikart/common'
import { RedisService } from '@yikart/redis'
import axios from 'axios'
-import { Auth, google } from 'googleapis'
+import { Auth, google, youtube_v3 } from 'googleapis'
import { Model } from 'mongoose'
import { v4 as uuidv4 } from 'uuid'
import { getCurrentTimestamp } from '../../../common'
@@ -1406,38 +1406,20 @@ export class YoutubeService extends PlatformBaseService {
/**
* 更新视频。
*/
- async updateVideo(accountId: string, videoId: string, snippet: any, status: any, recordingDetails: any) {
- try {
- // 使用封装的辅助方法
- if (!(await this.ensureValidAccessToken(accountId))) {
- this.logger.log(`get youtube access token error. accountId" ${accountId}`)
- return new AppException(ResponseCode.ChannelAccessTokenFailed)
- }
-
- const requestBody: any = {
- id: videoId,
- snippet,
- status,
- recordingDetails,
- }
- this.logger.log(requestBody)
-
- // 调用 YouTube API 上传视频
- const response = await this.youtubeClient.videos.update(
- {
- auth: this.oauth2Client,
- part: ['snippet', 'status', 'id'],
- requestBody,
- },
- )
- this.logger.log('Playlist insert successfully:', response.data)
-
- return response
- }
- catch (error) {
- this.logger.error('Error uploading video:', error)
- return error
+ async updateVideo(accountId: string, videoSchema: youtube_v3.Schema$Video) {
+ if (!(await this.ensureValidAccessToken(accountId))) {
+ this.logger.log(`get youtube access token error. accountId" ${accountId}`)
+ throw new AppException(ResponseCode.ChannelAccessTokenFailed)
}
+ const response = await this.youtubeClient.videos.update(
+ {
+ auth: this.oauth2Client,
+ part: ['snippet', 'status', 'id'],
+ requestBody: videoSchema,
+ },
+ )
+ this.logger.log('Video updated successfully:', response.data)
+ return true
}
/**
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 15356bd3..b9fce5b8 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
@@ -160,6 +160,9 @@ export const UpdatePublishTaskSchema = z.object({
videoUrl: z.string().optional(),
imgUrlList: z.array(z.string()).optional(),
topics: z.array(z.string()).optional(),
+ option: z.object({
+ youtube: YouTubePublishOptionSchema.optional(),
+ }).optional(),
})
export class UpdatePublishTaskDto extends createZodDto(UpdatePublishTaskSchema) {}
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 67a6a241..c975a7ba 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
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common'
+import { youtube_v3 } from 'googleapis'
import { chunkedDownloadFile, getFileSizeFromUrl } from '../../../common'
import {
PublishStatus,
@@ -83,11 +84,22 @@ export class YoutubePubService extends PublishService {
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, {})
+ const videoSchema: youtube_v3.Schema$Video = {
+ id: publishTask.dataId,
+ snippet: {
+ title: publishTask.title,
+ description: publishTask.desc,
+ tags: publishTask.topics,
+ categoryId: publishTask.option?.youtube?.categoryId,
+ },
+ status: {
+ privacyStatus: publishTask.option?.youtube?.privacyStatus,
+ selfDeclaredMadeForKids: publishTask.option?.youtube?.selfDeclaredMadeForKids,
+ embeddable: publishTask.option?.youtube?.embeddable,
+ license: publishTask.option?.youtube?.license,
+ },
+ }
+ await this.youtubeService.updateVideo(publishTask.accountId, videoSchema)
return {
status: PublishStatus.PUBLISHED,
}
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 dec29927..d27ece64 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
@@ -3,15 +3,19 @@ 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 { youtube_v3 } from 'googleapis'
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 { FacebookService } from '../platforms/meta/facebook.service'
+import { YoutubeService } from '../platforms/youtube/youtube.service'
import { IMMEDIATE_PUBLISH_TOLERANCE_SECONDS } from './constant'
import { CreatePublishDto, PublishRecordListFilterDto, UpdatePublishTaskDto } from './dto/publish.dto'
import { TiktokWebhookDto } from './dto/tiktok-webhook.dto'
import { TiktokPubService } from './providers/tiktok.service'
+import { generatePostMessage } from './util'
@Injectable()
export class PublishingService implements OnModuleDestroy {
@@ -24,6 +28,8 @@ export class PublishingService implements OnModuleDestroy {
@InjectModel(PublishTask.name)
private readonly publishTaskModel: Model<PublishTask>,
private readonly publishRecordService: PublishRecordService,
+ private readonly youtubeService: YoutubeService,
+ private readonly facebookService: FacebookService,
) {}
private determineMetaPostCategory(data: CreatePublishDto) {
@@ -101,6 +107,41 @@ export class PublishingService implements OnModuleDestroy {
return newTask
}
+ async updatePublishedFacebookTask(publishTask: PublishTask) {
+ const message = generatePostMessage(publishTask.desc, publishTask.topics)
+ const result = await this.facebookService.updatePost(publishTask.accountId, publishTask.dataId, { message })
+ return result.success
+ }
+
+ async updatePublishedYoutubePost(publishTask: PublishTask) {
+ const videoSchema: youtube_v3.Schema$Video = {
+ id: publishTask.dataId,
+ snippet: {
+ title: publishTask.title,
+ description: publishTask.desc,
+ tags: publishTask.topics,
+ categoryId: publishTask.option?.youtube?.categoryId,
+ },
+ status: {
+ privacyStatus: publishTask.option?.youtube?.privacyStatus,
+ selfDeclaredMadeForKids: publishTask.option?.youtube?.selfDeclaredMadeForKids,
+ embeddable: publishTask.option?.youtube?.embeddable,
+ license: publishTask.option?.youtube?.license,
+ },
+ }
+ return await this.youtubeService.updateVideo(publishTask.accountId, videoSchema)
+ }
+
+ async updatePublishedTextTask(publishTask: PublishTask) {
+ if (publishTask.accountType === AccountType.YOUTUBE) {
+ return await this.updatePublishedYoutubePost(publishTask)
+ }
+ else if (publishTask.accountType === AccountType.FACEBOOK) {
+ return await this.updatePublishedFacebookTask(publishTask)
+ }
+ throw new AppException(ResponseCode.PlatformNotSupported, 'only Facebook and Youtube are supported for update')
+ }
+
async updatePublishingTask(data: UpdatePublishTaskDto) {
const supportPlatforms = [AccountType.FACEBOOK, AccountType.YOUTUBE]
const task = await this.publishTaskModel.findById(data.id).exec()
@@ -127,16 +168,24 @@ export class PublishingService implements OnModuleDestroy {
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
+ try {
+ if (updatedContentType === 'text') {
+ return await this.updatePublishedTextTask(task)
+ }
+ await this.publishTaskModel.updateOne({ _id: data.id }, {
+ desc: data.desc,
+ videoUrl: data.videoUrl,
+ imgUrlList: data.imgUrlList,
+ topics: data.topics,
+ status: PublishStatus.WAITING_FOR_UPDATE,
+ option: data.option,
+ }).exec()
+ await this.enqueueUpdatePublishedPostTask(task, updatedContentType)
+ return true
+ }
+ catch (error) {
+ throw new AppException(ResponseCode.PublishTaskUpdateFailed, error.message)
+ }
}
async enqueuePublishingTask(task: PublishTask): Promise<boolean> {
diff --git a/project/backend/apps/aitoearn-channel/src/core/publishing/util.ts b/project/backend/apps/aitoearn-channel/src/core/publishing/util.ts
new file mode 100644
index 00000000..8cd8bd23
--- /dev/null
+++ b/project/backend/apps/aitoearn-channel/src/core/publishing/util.ts
@@ -0,0 +1,6 @@
+export function generatePostMessage(message: string, topics: string[]): string {
+ if (topics && topics.length > 0) {
+ return `${message} #${topics.join(' #')}`
+ }
+ return message
+}
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 0e8c098d..58ff0f0e 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
@@ -80,11 +80,37 @@ export const listPostHistorySchema = z.object({
})
export class ListPostHistoryDto extends createZodDto(listPostHistorySchema) {}
+export enum YouTubePrivacyStatus {
+ Public = 'public',
+ Unlisted = 'unlisted',
+ Private = 'private',
+}
+
+export enum YouTubeLicense {
+ CreativeCommon = 'creativeCommon',
+ YouTube = 'youtube',
+}
+
+export const YouTubePublishOptionSchema = z.object({
+ privacyStatus: z.enum([
+ YouTubePrivacyStatus.Public,
+ YouTubePrivacyStatus.Unlisted,
+ YouTubePrivacyStatus.Private,
+ ]),
+ license: z.enum(YouTubeLicense).optional(),
+ categoryId: z.string(),
+ embeddable: z.boolean().optional().default(false),
+ selfDeclaredMadeForKids: z.boolean().optional().default(false),
+})
+
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(),
+ option: z.object({
+ youtube: YouTubePublishOptionSchema.optional(),
+ }).optional(),
})
export class UpdatePublishTaskDto extends createZodDto(UpdatePublishTaskSchema) {}
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 4dfa0423..c98a9810 100644
--- a/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
+++ b/project/backend/apps/aitoearn-server/src/channel/publish.service.ts
@@ -262,6 +262,13 @@ export class PublishService {
}
async updatePublishTask(data: UpdatePublishTaskDto, userId: string) {
- return await this.platPublishNatsApi.updatePublishTask(data, userId)
+ try {
+ const success = await this.platPublishNatsApi.updatePublishTask(data, userId)
+ return { success }
+ }
+ catch (error: any) {
+ this.logger.error(`Failed to update publish task for userId ${userId}: ${error.message}`, error.stack)
+ throw new AppException(ResponseCode.PublishTaskUpdateFailed, error.message)
+ }
}
}
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 aea2afe6..da3c390d 100755
--- a/project/backend/libs/common/src/enums/response-code.enum.ts
+++ b/project/backend/libs/common/src/enums/response-code.enum.ts
@@ -98,4 +98,5 @@ export enum ResponseCode {
PublishTaskAlreadyWaitingForUpdate = 15030,
PostCategoryNotSupported = 15031,
PlatformNotSupported = 15032,
+ PublishTaskUpdateFailed = 15033,
}
diff --git a/project/backend/libs/common/src/i18n/messages.ts b/project/backend/libs/common/src/i18n/messages.ts
index 493b22cc..c2cdde90 100644
--- a/project/backend/libs/common/src/i18n/messages.ts
+++ b/project/backend/libs/common/src/i18n/messages.ts
@@ -296,4 +296,8 @@ export const messages: Record<ResponseCode, Record<Locale, MessageValue>> = {
'en-US': 'Publish task is already waiting for update',
'zh-CN': '发布任务已等待更新',
},
+ [ResponseCode.PublishTaskUpdateFailed]: {
+ 'en-US': 'Failed to update publish task',
+ 'zh-CN': '更新发布任务失败',
+ },
}