π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
fix(tiktok): resolve and persist the public post id for analytics
Gilad Resisibcbc1195a75f
diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.tsindex 51056e57f..2d24173e2 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts@@ -430,6 +430,24 @@ export class PostsRepository {});}+ updateResolvedRelease(+ id: string,+ orgId: string,+ releaseId: string,+ releaseURL: string+ ) {+ return this._post.model.post.update({+ where: {+ id,+ organizationId: orgId,+ },+ data: {+ releaseId,+ releaseURL,+ },+ });+ }+async changeState(id: string, state: State, err?: any, body?: any) {const update = await this._post.model.post.update({where: {diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 31ecc48bf..6a9c88a0b 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -214,10 +214,28 @@ export class PostsService {// }try {+ let releaseId = post.releaseId;+ if (integrationProvider.resolveReleaseId) {+ const resolved = await integrationProvider.resolveReleaseId(+ getIntegration.token,+ releaseId,+ getIntegration+ );+ if (resolved && resolved.postId !== releaseId) {+ await this._postRepository.updateResolvedRelease(+ post.id,+ orgId,+ resolved.postId,+ resolved.releaseURL+ );+ releaseId = resolved.postId;+ }+ }+const loadAnalytics = await integrationProvider.postAnalytics(getIntegration.internalId,getIntegration.token,- post.releaseId,+ releaseId,date);await ioRedis.set(diff --git a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.tsindex a8a29c600..5b6a7a94a 100644--- a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts+++ b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts@@ -34,6 +34,11 @@ export interface IAuthenticator {postId: string,fromDate: number,): Promise<AnalyticsData[]>;+ resolveReleaseId?(+ accessToken: string,+ releaseId: string,+ integration: Integration+ ): Promise<{ postId: string; releaseURL: string } | undefined>; // Final id + URL to persist when the stored releaseId is still a publish id, undefined when nothing to resolve (yet)changeNickname?(id: string,accessToken: string,diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.tsindex 3fdaeb3f7..f3c78fced 100644--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts@@ -425,9 +425,10 @@ export class TiktokBusinessProviderpendingData: { publishId: string },integration: Integration): Promise<PendingCheckResponse> {+ let body: string;let post: any;try {- post = await (+ body = await (await this.fetch(`${this.baseUrl}/business/publish/status/?business_id=${encodeURIComponent(integration.internalId@@ -442,7 +443,8 @@ export class TiktokBusinessProvider0,true)- ).json();+ ).text();+ post = JSON.parse(body);} catch (err) {if (err instanceof RefreshToken || err instanceof Disconnect) {throw err;@@ -469,7 +471,7 @@ export class TiktokBusinessProviderreturn { status: 'pending', pendingData };}- const { status, post_ids, reason } = post?.data || {};+ const { status, reason } = post?.data || {};if (status === 'SEND_TO_USER_INBOX') {return {@@ -482,15 +484,15 @@ export class TiktokBusinessProviderif (status === 'PUBLISH_COMPLETE') {// post_ids can lag up to 3 minutes behind PUBLISH_COMPLETE, and never// shows up at all for non-public posts - fall back to the profile URL- // and keep the share_id (postAnalytics resolves it later).- const publicPostId = post_ids?.[0];+ // and keep the share_id (resolveReleaseId fixes it later).+ const publicPostId = this.publicPostId(body);return {status: 'completed',releaseURL: !publicPostId? `https://www.tiktok.com/@${integration.profile}`: `https://www.tiktok.com/@${integration.profile}/video/${publicPostId}`,- postId: !publicPostId ? pendingData.publishId : String(publicPostId),+ postId: !publicPostId ? pendingData.publishId : publicPostId,};}@@ -929,6 +931,12 @@ export class TiktokBusinessProviderreturn videoListData?.data?.videos;}+ // post_ids holds int64 ids that exceed Number.MAX_SAFE_INTEGER, so the id+ // must be read from the raw body instead of the parsed JSON+ private publicPostId(body: string) {+ return body.match(/"post_ids"\s*:\s*\[\s*"?(\d+)"?/)?.[1];+ }+private throwIfTokenError(body: { code?: number }) {if (body?.code === 0) {return;@@ -1099,6 +1107,44 @@ export class TiktokBusinessProvider}}+ // Posts saved before post_ids became available keep their share_id+ // (v_pub_... / p_pub_...) as releaseId - resolve it to the public post id+ async resolveReleaseId(+ accessToken: string,+ releaseId: string,+ integration: Integration+ ) {+ if (releaseId.indexOf('_pub_') === -1) {+ return undefined;+ }++ const body = await (+ await this.fetch(+ `${this.baseUrl}/business/publish/status/?business_id=${encodeURIComponent(+ integration.internalId+ )}&publish_id=${encodeURIComponent(releaseId)}`,+ {+ method: 'GET',+ headers: {+ 'Access-Token': accessToken,+ },+ }+ )+ ).text();++ this.throwIfTokenError(JSON.parse(body));++ const publicPostId = this.publicPostId(body);+ if (!publicPostId) {+ return undefined;+ }++ return {+ postId: publicPostId,+ releaseURL: `https://www.tiktok.com/@${integration.profile}/video/${publicPostId}`,+ };+ }+async postAnalytics(integrationId: string,accessToken: string,@@ -1107,33 +1153,6 @@ export class TiktokBusinessProvider): Promise<AnalyticsData[]> {const today = dayjs().format('YYYY-MM-DD');- // Posts saved before post_ids became available keep their share_id- // (v_pub_url~... / p_pub_url~...) as releaseId - resolve it to the public- // post id first.- if (postId.indexOf('_pub_url') > -1) {- const post = await (- await this.fetch(- `${this.baseUrl}/business/publish/status/?business_id=${encodeURIComponent(- integrationId- )}&publish_id=${encodeURIComponent(postId)}`,- {- method: 'GET',- headers: {- 'Access-Token': accessToken,- },- }- )- ).json();-- this.throwIfTokenError(post);-- if (!post?.data?.post_ids?.[0]) {- return [];- }-- postId = String(post.data.post_ids[0]);- }-try {const videoQueryData = await (await this.fetch(diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.tsindex c40bec89d..4e7af617f 100644--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts@@ -491,6 +491,8 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {}if (status === 'PUBLISH_COMPLETE') {+ // the id only shows up once moderation approves the post - fall back to+ // the profile URL and keep the publish_id (resolveReleaseId fixes it later)return {status: 'completed',releaseURL: !publicPostId@@ -1140,6 +1142,45 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {}}+ // Posts published before moderation finished keep their publish_id+ // (v_pub_url~... / v_pub_file~...) as releaseId - resolve it to the video id+ async resolveReleaseId(+ accessToken: string,+ releaseId: string,+ integration: Integration+ ) {+ if (releaseId.indexOf('v_pub_') === -1) {+ return undefined;+ }++ const { publicPostId } = this.parsePublishStatus(+ await (+ await this.fetch(+ 'https://open.tiktokapis.com/v2/post/publish/status/fetch/',+ {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json; charset=UTF-8',+ Authorization: `Bearer ${accessToken}`,+ },+ body: JSON.stringify({+ publish_id: releaseId,+ }),+ }+ )+ ).text()+ );++ if (!publicPostId) {+ return undefined;+ }++ return {+ postId: publicPostId,+ releaseURL: `https://www.tiktok.com/@${integration.profile}/video/${publicPostId}`,+ };+ }+async postAnalytics(integrationId: string,accessToken: string,@@ -1148,35 +1189,6 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {): Promise<AnalyticsData[]> {const today = dayjs().format('YYYY-MM-DD');- // Posts whose public id was not available yet when publishing keep the- // publish_id (v_pub_url~... / v_pub_file~...) as releaseId - resolve it- // to the public post id first.- if (postId.indexOf('_pub_') > -1) {- const { publicPostId } = this.parsePublishStatus(- await (- await fetch(- 'https://open.tiktokapis.com/v2/post/publish/status/fetch/',- {- method: 'POST',- headers: {- 'Content-Type': 'application/json; charset=UTF-8',- Authorization: `Bearer ${accessToken}`,- },- body: JSON.stringify({- publish_id: postId,- }),- }- )- ).text()- );-- if (!publicPostId) {- return [];- }-- postId = publicPostId;- }-try {// Query video details using the video IDconst response = await fetch(