π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
import {
AnalyticsData,
AuthTokenDetails,
PendingCheckResponse,
PostDetails,
PostResponse,
SocialProvider,
} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import dayjs from 'dayjs';
import { makeSecureId } from '@gitroom/nestjs-libraries/services/make.secure.id';
import {
BadBody,
Disconnect,
RefreshToken,
SocialAbstract,
ValidityMedia,
} from '@gitroom/nestjs-libraries/integrations/social.abstract';
import { TikTokDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/tiktok.dto';
import { timer } from '@gitroom/helpers/utils/timer';
import { hasExtension } from '@gitroom/helpers/utils/has.extension';
import { createReadStream } from 'fs';
import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import { Integration } from '@prisma/client';
import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';
@Rules(
[
'TikTok can have one video or one picture or multiple pictures, it cannot be without an attachment.',
'content_posting_method=DIRECT_POST publishes the post to the account. content_posting_method=UPLOAD does NOT publish: it only sends the media to the user inbox of the TikTok app, where the user must manually complete and publish it within 24 hours or it is discarded. Use DIRECT_POST unless the user explicitly asks to review or edit the post inside the TikTok app first.',
'With content_posting_method=UPLOAD, TikTok ignores every setting except the title / post content. Never tell the user that video_made_with_ai, privacy_level, duet, stitch, comment, autoAddMusic, brand_content_toggle or brand_organic_toggle will be applied in UPLOAD mode - they are silently discarded. If the user asks for any of those settings, tell them it requires DIRECT_POST.',
'video_made_with_ai, duet and stitch apply to video posts only. TikTok has no equivalent field for photo posts, so those settings are discarded when the attachment is a picture.',
].join(' ')
)
export class TiktokProvider extends SocialAbstract implements SocialProvider {
identifier = 'tiktok';
name = 'Tiktok';
isBetweenSteps = false;
convertToJPEG = true;
scopes = [
'video.list',
'user.info.basic',
'video.publish',
'video.upload',
'user.info.profile',
'user.info.stats',
];
override maxConcurrentJob = 10000;
dto = TikTokDto;
editor = 'normal' as const;
maxLength() {
return 2000;
}
override async checkValidity(
items: Array<ValidityMedia[]>
): Promise<string | true> {
const [firstItems] = items ?? [];
if ((firstItems?.length ?? 0) === 0) {
return 'No video / images selected';
}
if (
(firstItems?.length ?? 0) > 1 &&
firstItems?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1)
) {
return 'Only pictures are supported when selecting multiple items';
} else if (
firstItems?.length !== 1 &&
(firstItems?.[0]?.path?.indexOf?.('mp4') ?? -1) > -1
) {
return 'You need one media';
}
// TikTok fails the whole photo post when a single image is oversized, and
// the status only says `picture_size_check_failed` without naming it.
if (firstItems?.every((p) => (p?.path?.indexOf?.('mp4') ?? -1) === -1)) {
const dimensions = await Promise.all(
firstItems?.map((p) => this.getImageDimensions(p?.path)) ?? []
);
const tooBig = dimensions.findIndex(
(p) => Math.min(p?.width ?? 0, p?.height ?? 0) > 1080
);
if (tooBig > -1) {
return `Image ${tooBig + 1} is ${dimensions[tooBig]?.width}x${
dimensions[tooBig]?.height
}, TikTok allows a maximum of 1080px on the shorter side`;
}
}
return true;
}
override handleErrors(body: string):
| {
type: 'refresh-token' | 'bad-body' | 'disconnect';
value: string;
}
| undefined {
// Authentication/Authorization errors - require re-authentication
if (body.indexOf('access_token_invalid') > -1) {
return {
type: 'refresh-token' as const,
value:
'Access token invalid, please re-authenticate your TikTok account',
};
}
if (body.indexOf('scope_not_authorized') > -1) {
return {
type: 'bad-body' as const,
value:
'Missing required permissions, please re-authenticate with all scopes',
};
}
if (body.indexOf('scope_permission_missed') > -1) {
return {
type: 'bad-body' as const,
value: 'Additional permissions required, please re-authenticate',
};
}
// Rate limiting errors
if (body.indexOf('rate_limit_exceeded') > -1) {
return {
type: 'bad-body' as const,
value: 'TikTok API rate limit exceeded, please try again later',
};
}
if (body.indexOf('file_format_check_failed') > -1) {
return {
type: 'bad-body' as const,
value: 'File format is invalid, please check video specifications',
};
}
if (body.indexOf('app_version_check_failed') > -1) {
return {
type: 'bad-body' as const,
value:
'In order to use the TikTok upload feature, you have to update your app to the latest version',
};
}
if (body.indexOf('duration_check_failed') > -1) {
return {
type: 'bad-body' as const,
value: 'Video duration is invalid, please check video specifications',
};
}
if (body.indexOf('frame_rate_check_failed') > -1) {
return {
type: 'bad-body' as const,
value: 'Video frame rate is invalid, please check video specifications',
};
}
if (body.indexOf('video_pull_failed') > -1) {
return {
type: 'bad-body' as const,
value: 'Failed to pull video from URL, please check the URL',
};
}
if (body.indexOf('photo_pull_failed') > -1) {
return {
type: 'bad-body' as const,
value: 'Failed to pull photo from URL, please check the URL',
};
}
if (body.indexOf('spam_risk_user_banned_from_posting') > -1) {
return {
type: 'bad-body' as const,
value:
'Account banned from posting, please check TikTok account status',
};
}
if (body.indexOf('spam_risk_text') > -1) {
return {
type: 'bad-body' as const,
value: 'TikTok detected potential spam in the post text',
};
}
if (body.indexOf('spam_risk_too_many_posts') > -1) {
return {
type: 'bad-body' as const,
value:
'TikTok says your daily post limit reached, please try again tomorrow',
};
}
if (body.indexOf('spam_risk_too_many_pending_share') > -1) {
return {
type: 'bad-body' as const,
value:
'TikTok limits pending posts to 5 within any 24-hour period. Please check your TikTok inbox in the TikTok mobile app and try again after 24 hours.',
};
}
if (body.indexOf('spam_risk_user_banned_from_posting') > -1) {
return {
type: 'bad-body' as const,
value:
'Account banned from posting, please check TikTok account status',
};
}
if (body.indexOf('spam_risk') > -1) {
return {
type: 'bad-body' as const,
value: 'TikTok detected potential spam',
};
}
// TikTok limits how many users of this app can post per day: refreshing
// the token cannot help, the channel must be re-connected (and can be
// migrated to another app via MIGRATE_PROVIDERS).
if (body.indexOf('reached_active_user_cap') > -1) {
return {
type: 'disconnect' as const,
value:
'TikTok daily user limit reached, please re-connect your account',
};
}
if (
body.indexOf('unaudited_client_can_only_post_to_private_accounts') > -1
) {
return {
type: 'bad-body' as const,
value: 'App not approved for public posting, contact support',
};
}
if (body.indexOf('url_ownership_unverified') > -1) {
return {
type: 'bad-body' as const,
value:
'You have to upload the picture/video to Postiz when sending a URL',
};
}
if (body.indexOf('privacy_level_option_mismatch') > -1) {
return {
type: 'bad-body' as const,
value: 'Privacy level mismatch, please check privacy settings',
};
}
// Content/Format validation errors
if (body.indexOf('invalid_file_upload') > -1) {
return {
type: 'bad-body' as const,
value: 'Invalid file format or specifications not met',
};
}
if (body.indexOf('invalid_params') > -1) {
return {
type: 'bad-body' as const,
value: 'Invalid request parameters, please check content format',
};
}
// Server errors
if (body.indexOf('internal') > -1) {
return {
type: 'bad-body' as const,
value: 'There is a problem with TikTok servers, please try again later',
};
}
// Generic TikTok API errors
if (body.indexOf('picture_size_check_failed') > -1) {
return {
type: 'bad-body' as const,
value:
'Media size not supported by TikTok: images up to 1080px on the shorter side, videos at least 360px on both sides',
};
}
if (body.indexOf('TikTok API error') > -1) {
return {
type: 'bad-body' as const,
value: 'TikTok API error, please try again',
};
}
// Fall back to parent class error handling
return undefined;
}
async refreshToken(refreshToken: string): Promise<AuthTokenDetails> {
const value = {
client_key: process.env.TIKTOK_CLIENT_ID!,
client_secret: process.env.TIKTOK_CLIENT_SECRET!,
grant_type: 'refresh_token',
refresh_token: refreshToken,
};
const { access_token, refresh_token, ...all } = await (
await fetch('https://open.tiktokapis.com/v2/oauth/token/', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
method: 'POST',
body: new URLSearchParams(value).toString(),
})
).json();
const {
data: {
user: { avatar_url, display_name, open_id, username },
},
} = await (
await fetch(
'https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_url,display_name,union_id,username',
{
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
}
)
).json();
return {
refreshToken: refresh_token,
expiresIn: dayjs().add(23, 'hours').unix() - dayjs().unix(),
accessToken: access_token,
id: open_id.replace(/-/g, ''),
name: display_name,
picture: avatar_url || '',
username: username,
};
}
async generateAuthUrl() {
const state = makeSecureId(16);
return {
url:
'https://www.tiktok.com/v2/auth/authorize/' +
`?client_key=${process.env.TIKTOK_CLIENT_ID}` +
`&redirect_uri=${encodeURIComponent(
`${
process?.env?.FRONTEND_URL?.indexOf('https') === -1
? 'https://redirectmeto.com/'
: ''
}${process?.env?.FRONTEND_URL}/integrations/social/tiktok`
)}` +
`&state=${state}` +
`&response_type=code` +
`&scope=${encodeURIComponent(this.scopes.join(','))}`,
codeVerifier: state,
state,
};
}
async authenticate(params: {
code: string;
codeVerifier: string;
refresh?: string;
}) {
const value = {
client_key: process.env.TIKTOK_CLIENT_ID!,
client_secret: process.env.TIKTOK_CLIENT_SECRET!,
code: params.code,
grant_type: 'authorization_code',
code_verifier: params.codeVerifier,
redirect_uri: `${
process?.env?.FRONTEND_URL?.indexOf('https') === -1
? 'https://redirectmeto.com/'
: ''
}${process?.env?.FRONTEND_URL}/integrations/social/tiktok`,
};
const { access_token, refresh_token, scope } = await (
await fetch('https://open.tiktokapis.com/v2/oauth/token/', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
method: 'POST',
body: new URLSearchParams(value).toString(),
})
).json();
this.checkScopes(this.scopes, scope);
const {
data: {
user: { avatar_url, display_name, open_id, username },
},
} = await (
await fetch(
'https://open.tiktokapis.com/v2/user/info/?fields=open_id,avatar_url,display_name,union_id,username',
{
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
}
)
).json();
return {
id: open_id.replace(/-/g, ''),
name: display_name,
accessToken: access_token,
refreshToken: refresh_token,
expiresIn: dayjs().add(23, 'hours').unix() - dayjs().unix(),
picture: avatar_url,
username: username,
};
}
async maxVideoLength(accessToken: string) {
const {
data: { max_video_post_duration_sec },
} = await (
await fetch(
'https://open.tiktokapis.com/v2/post/publish/creator_info/query/',
{
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: `Bearer ${accessToken}`,
},
}
)
).json();
return {
maxDurationSeconds: max_video_post_duration_sec,
};
}
// Single status check for a publish_id, no loops and no timers: `post` returns
// a `pending` PostResponse right after the upload, and the post workflow polls
// this method with durable timers, so a stuck/retried check can never re-run
// the publish and duplicate the post.
override async checkPostStatus(
accessToken: string,
pendingData: { publishId: string },
integration: Integration
): Promise<PendingCheckResponse> {
let post: any;
let publicPostId: string | undefined;
try {
const raw = 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: pendingData.publishId,
}),
},
'',
0,
true
)
).text();
({ post, publicPostId } = this.parsePublishStatus(raw));
} catch (err) {
if (err instanceof RefreshToken || err instanceof Disconnect) {
throw err;
}
// Transient API error while checking the status: the post may already
// be live, so keep polling instead of failing it - if the API stays
// broken the caller exhausts its checks and warns the user properly.
return { status: 'pending', pendingData };
}
const { status } = post?.data || {};
if (status === 'SEND_TO_USER_INBOX') {
// the id stays 'missing' until the user publishes the draft - the
// publish id rides in the URL fragment so resolveReleaseId can ask later
return {
status: 'completed',
releaseURL: `https://www.tiktok.com/messages?lang=en#${pendingData.publishId}`,
postId: 'missing',
};
}
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
? `https://www.tiktok.com/@${integration.profile}`
: this.postUrl(integration, pendingData.publishId, publicPostId),
postId: !publicPostId ? pendingData.publishId : publicPostId,
};
}
if (status === 'FAILED') {
const handleError = this.handleErrors(JSON.stringify(post));
throw new BadBody(
'titok-error-upload',
JSON.stringify(post),
Buffer.from(JSON.stringify(post)),
handleError?.value || ''
);
}
return { status: 'pending', pendingData };
}
// photo posts (p_pub_... / p_inbox_...) live under /photo/, TikTok rejects
// /video/ for them
private postUrl(integration: Integration, publishId: string, postId: string) {
return `https://www.tiktok.com/@${integration.profile}/${
publishId.indexOf('p_') === 0 ? 'photo' : 'video'
}/${postId}`;
}
// TikTok returns publicaly_available_post_id as an int64, which JSON.parse
// rounds past 2^53 - pull the digits out of the raw body before parsing.
private parsePublishStatus(raw: string) {
const [, publicPostId] =
raw.match(/"publicaly_available_post_id"\s*:\s*\[\s*"?(\d+)/) || [];
return { post: JSON.parse(raw), publicPostId };
}
// UPLOAD does not publish - it only drops the media into the user's TikTok
// inbox - so only an explicit UPLOAD selects it. A missing value (drafts, or
// any caller that skipped the setting) publishes instead of silently landing
// in the inbox.
private contentPostingMethod(
firstPost: PostDetails<TikTokDto>
): TikTokDto['content_posting_method'] {
return firstPost?.settings?.content_posting_method === 'UPLOAD'
? 'UPLOAD'
: 'DIRECT_POST';
}
private postingMethod(
method: TikTokDto['content_posting_method'],
isPhoto: boolean
): string {
switch (method) {
case 'UPLOAD':
return isPhoto ? '/content/init/' : '/inbox/video/init/';
case 'DIRECT_POST':
default:
return isPhoto ? '/content/init/' : '/video/init/';
}
}
private buildTikokPostInfoBody(firstPost: PostDetails<TikTokDto>) {
const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
const method = this.contentPostingMethod(firstPost);
if (method === 'DIRECT_POST') {
return {
post_info: {
...(isPhoto && firstPost.settings.title
? { title: firstPost.settings.title.slice(0, 90) }
: {}),
...(!isPhoto && firstPost.message
? { title: firstPost.message }
: {}),
...(isPhoto ? { description: firstPost.message } : {}),
privacy_level:
firstPost.settings.privacy_level || 'PUBLIC_TO_EVERYONE',
...(isPhoto
? {}
: { disable_duet: !this.assetBoolean(firstPost.settings.duet) }),
disable_comment: !this.assetBoolean(firstPost.settings.comment),
...(isPhoto
? {}
: {
disable_stitch: !this.assetBoolean(firstPost.settings.stitch),
}),
...(isPhoto
? {}
: {
is_aigc: this.assetBoolean(
firstPost.settings.video_made_with_ai
),
}),
brand_content_toggle: this.assetBoolean(
firstPost.settings.brand_content_toggle
),
brand_organic_toggle: this.assetBoolean(
firstPost.settings.brand_organic_toggle
),
...(isPhoto
? {
auto_add_music: firstPost.settings.autoAddMusic === 'yes',
}
: {}),
...(!isPhoto && firstPost?.media?.[0]?.thumbnailTimestamp != null
? {
video_cover_timestamp_ms:
firstPost?.media?.[0]?.thumbnailTimestamp,
}
: {}),
},
};
}
return {
post_info: {
...(isPhoto && firstPost.settings.title
? { title: firstPost.settings.title }
: {}),
...(!isPhoto && firstPost.message ? { title: firstPost.message } : {}),
...(isPhoto ? { description: firstPost.message } : {}),
},
};
}
// ---------------------------------------------------------------------------
// OLD PULL_FROM_URL IMPLEMENTATION (kept for when the TikTok PULL bug is fixed)
// ---------------------------------------------------------------------------
// private buildTikokSourceInfoBody(firstPost: PostDetails<TikTokDto>) {
// const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
//
// if (isPhoto) {
// return {
// post_mode:
// firstPost?.settings?.content_posting_method === 'DIRECT_POST'
// ? 'DIRECT_POST'
// : 'MEDIA_UPLOAD',
// media_type: 'PHOTO',
// source_info: {
// source: 'PULL_FROM_URL',
// photo_cover_index: 0,
// photo_images: firstPost.media?.map((p) => p.path),
// },
// };
// }
//
// return {
// source_info: {
// source: 'PULL_FROM_URL',
// video_url: firstPost?.media?.[0]?.path!,
// ...(firstPost?.media?.[0]?.thumbnailTimestamp!
// ? {
// video_cover_timestamp_ms:
// firstPost?.media?.[0]?.thumbnailTimestamp!,
// }
// : {}),
// },
// };
// }
//
// async post(
// id: string,
// accessToken: string,
// postDetails: PostDetails<TikTokDto>[],
// integration: Integration
// ): Promise<PostResponse[]> {
// const [firstPost] = postDetails;
// const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
//
// console.log({
// ...this.buildTikokPostInfoBody(firstPost),
// ...this.buildTikokSourceInfoBody(firstPost),
// });
// const {
// data: { publish_id },
// } = await (
// await this.fetch(
// `https://open.tiktokapis.com/v2/post/publish${this.postingMethod(
// firstPost.settings.content_posting_method,
// !hasExtension(firstPost?.media?.[0]?.path, 'mp4')
// )}`,
// {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json; charset=UTF-8',
// Authorization: `Bearer ${accessToken}`,
// },
// body: JSON.stringify({
// ...this.buildTikokPostInfoBody(firstPost),
// ...this.buildTikokSourceInfoBody(firstPost),
// }),
// }
// )
// ).json();
//
// const { url, id: videoId } = await this.uploadedVideoSuccess(
// integration.profile!,
// publish_id,
// accessToken
// );
//
// return [
// {
// id: firstPost.id,
// releaseURL: url,
// postId: String(videoId),
// status: 'success',
// },
// ];
// }
// ---------------------------------------------------------------------------
// NEW FILE_UPLOAD IMPLEMENTATION (no PULL_FROM_URL for videos)
// ---------------------------------------------------------------------------
// TikTok video chunk constraints: a chunk must be between 5MB and 64MB.
// When the whole file fits in a single chunk (<= 64MB) we upload it in one
// request; otherwise we split it into 10MB chunks (the final chunk carries
// the remainder, which TikTok allows to exceed chunk_size).
private static readonly TIKTOK_MAX_SINGLE_CHUNK = 64 * 1024 * 1024;
private static readonly TIKTOK_CHUNK_SIZE = 10 * 1024 * 1024;
private tiktokChunkPlan(videoSize: number) {
if (videoSize <= TiktokProvider.TIKTOK_MAX_SINGLE_CHUNK) {
return { chunkSize: videoSize, totalChunkCount: 1 };
}
const chunkSize = TiktokProvider.TIKTOK_CHUNK_SIZE;
return {
chunkSize,
totalChunkCount: Math.floor(videoSize / chunkSize),
};
}
// Returns a streaming body for the [start, end] byte range of the media so we
// never hold the whole file in memory: a ranged GET for remote URLs, a ranged
// read stream for local files.
private async tiktokChunkStream(path: string, start: number, end: number) {
if (path.indexOf('http') === 0) {
// identity encoding so the store keeps content-length and can answer
// with the requested range, matching every other media read
const response = await fetch(path, {
headers: {
Range: `bytes=${start}-${end}`,
'accept-encoding': 'identity',
},
dispatcher: getSsrfSafeDispatcher(),
} as any);
// A store that ignores Range (200 with the full file) or answers with an
// error page would corrupt the upload at this offset.
if (response.status !== 206) {
throw new BadBody(
'tiktok-error-upload',
'{}',
'{}',
'The media storage did not return the requested byte range, please try again'
);
}
return response.body;
}
return createReadStream(this.localMediaPath(path, 'tiktok-error-upload'), {
start,
end,
});
}
// Streams the video bytes to the upload_url returned by the init call.
// We use the global fetch (not this.fetch) because chunked uploads answer
// with 206 (Partial Content), which this.fetch would treat as an error.
private async uploadTikTokVideoBytes(
uploadUrl: string,
path: string,
videoSize: number,
contentType: string
) {
const { chunkSize, totalChunkCount } = this.tiktokChunkPlan(videoSize);
for (let i = 0; i < totalChunkCount; i++) {
const start = i * chunkSize;
const end =
i === totalChunkCount - 1 ? videoSize - 1 : start + chunkSize - 1;
const contentLength = end - start + 1;
const body = await this.tiktokChunkStream(path, start, end);
const upload = await fetch(uploadUrl, {
method: 'PUT',
headers: {
'Content-Type': contentType,
'Content-Length': String(contentLength),
'Content-Range': `bytes ${start}-${end}/${videoSize}`,
},
body,
// Required by undici when streaming a request body.
duplex: 'half',
} as any);
if (
upload.status !== 200 &&
upload.status !== 201 &&
upload.status !== 206
) {
const text = await upload.text().catch(() => '{}');
const handleError = this.handleErrors(text);
throw new BadBody(
'tiktok-error-upload',
text,
Buffer.from(text),
handleError?.value || 'Failed to upload the video to TikTok'
);
}
}
}
private buildTikokSourceInfoBody(
firstPost: PostDetails<TikTokDto>,
videoSize?: number
) {
const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
// TikTok photo posts only support PULL_FROM_URL, there is no FILE_UPLOAD
// path for photos, so this branch keeps pulling from the URL.
if (isPhoto) {
return {
post_mode:
this.contentPostingMethod(firstPost) === 'DIRECT_POST'
? 'DIRECT_POST'
: 'MEDIA_UPLOAD',
media_type: 'PHOTO',
source_info: {
source: 'PULL_FROM_URL',
photo_cover_index: 0,
photo_images: firstPost.media?.map((p) => p.path),
},
};
}
const { chunkSize, totalChunkCount } = this.tiktokChunkPlan(videoSize || 0);
return {
source_info: {
source: 'FILE_UPLOAD',
video_size: videoSize,
chunk_size: chunkSize,
total_chunk_count: totalChunkCount,
},
};
}
async postPending(
id: string,
accessToken: string,
postDetails: PostDetails<TikTokDto>[],
integration: Integration
): Promise<PostResponse[]> {
const [firstPost] = postDetails;
const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
const videoPath = firstPost?.media?.[0]?.path!;
// For videos we only need the total size up front (HEAD / statSync) so we
// can init the upload; the bytes themselves are streamed later, never fully
// loaded into memory.
const videoSize = isPhoto
? undefined
: await this.mediaSize(videoPath, 'tiktok-error-upload');
const {
data: { publish_id, upload_url },
} = await (
await this.fetch(
`https://open.tiktokapis.com/v2/post/publish${this.postingMethod(
this.contentPostingMethod(firstPost),
isPhoto
)}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
...this.buildTikokPostInfoBody(firstPost),
...this.buildTikokSourceInfoBody(firstPost, videoSize),
}),
}
)
).json();
// Videos: stream the bytes to the upload_url returned by the init call.
if (!isPhoto && upload_url && videoSize) {
try {
await this.uploadTikTokVideoBytes(
upload_url,
videoPath,
videoSize,
'video/mp4'
);
} catch (err) {
// An explicit rejection from TikTok: the post won't publish, fail it
if (err instanceof BadBody) {
throw err;
}
// A network error here is ambiguous - TikTok may have received all
// the bytes and still publish. Return pending and let checkPostStatus
// deliver TikTok's own verdict instead of letting the caller retry
// the publish.
}
}
// The publish is now irreversible on TikTok's side: return `pending` so the
// workflow polls checkPostStatus instead of blocking (and possibly timing
// out and re-posting) inside this activity.
return [
{
id: firstPost.id,
releaseURL: '',
postId: '',
status: 'pending',
pendingData: { publishId: publish_id },
},
];
}
// Old blocking behavior, kept for workflow versions before v1.0.6 that still
// run (scheduled posts sleep inside them until publish time) and don't know
// how to resolve a `pending` response - they keep polling inside the
// activity exactly like before.
async post(
id: string,
accessToken: string,
postDetails: PostDetails<TikTokDto>[],
integration: Integration
): Promise<PostResponse[]> {
const [response] = await this.postPending(
id,
accessToken,
postDetails,
integration
);
const started = Date.now();
for (const _ of Array(27).keys()) {
// ~9 minutes at 20s interval
const check = await this.checkPostStatus(
accessToken,
response.pendingData,
integration
);
if (check.status === 'completed') {
return [
{
id: response.id,
releaseURL: check.releaseURL,
postId: String(check.postId),
status: 'success',
},
];
}
// Cap below the 10-minute activity timeout of the old workflows using
// this method: failing here (non-retryable) is safe, timing the activity
// out is not - a retried activity would publish the post again.
if (Date.now() - started > 8 * 60 * 1000) {
break;
}
await timer(20000);
}
throw new BadBody(
'titok-error-upload',
JSON.stringify({}),
Buffer.from(JSON.stringify({})),
'TikTok refused to publish your post'
);
}
async analytics(
id: string,
accessToken: string,
date: number
): Promise<AnalyticsData[]> {
const today = dayjs().format('YYYY-MM-DD');
try {
// Get user stats (follower_count, following_count, likes_count, video_count)
const userStatsResponse = await fetch(
'https://open.tiktokapis.com/v2/user/info/?fields=follower_count,following_count,likes_count,video_count',
{
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
const userStatsData = await userStatsResponse.json();
const userStats = userStatsData?.data?.user;
const result: AnalyticsData[] = [];
if (userStats) {
if (userStats.follower_count !== undefined) {
result.push({
label: 'Followers',
percentageChange: 0,
data: [{ total: String(userStats.follower_count), date: today }],
});
}
if (userStats.following_count !== undefined) {
result.push({
label: 'Following',
percentageChange: 0,
data: [{ total: String(userStats.following_count), date: today }],
});
}
if (userStats.likes_count !== undefined) {
result.push({
label: 'Total Likes',
percentageChange: 0,
data: [{ total: String(userStats.likes_count), date: today }],
});
}
if (userStats.video_count !== undefined) {
result.push({
label: 'Videos',
percentageChange: 0,
data: [{ total: String(userStats.video_count), date: today }],
});
}
}
// Get recent videos and aggregate their stats
const videoListResponse = await fetch(
'https://open.tiktokapis.com/v2/video/list/?fields=id',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ max_count: 20 }),
}
);
const videoListData = await videoListResponse.json();
const videos = videoListData?.data?.videos;
if (videos && videos.length > 0) {
const videoIds = videos.map((v: { id: string }) => v.id);
// Query video details to get engagement metrics
const videoQueryResponse = await fetch(
'https://open.tiktokapis.com/v2/video/query/?fields=id,like_count,comment_count,share_count,view_count',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
filters: { video_ids: videoIds },
}),
}
);
const videoQueryData = await videoQueryResponse.json();
const videoDetails = videoQueryData?.data?.videos;
if (videoDetails && videoDetails.length > 0) {
let totalViews = 0;
let totalLikes = 0;
let totalComments = 0;
let totalShares = 0;
for (const video of videoDetails) {
totalViews += video.view_count || 0;
totalLikes += video.like_count || 0;
totalComments += video.comment_count || 0;
totalShares += video.share_count || 0;
}
result.push({
label: 'Views',
percentageChange: 0,
data: [{ total: String(totalViews), date: today }],
});
result.push({
label: 'Recent Likes',
percentageChange: 0,
data: [{ total: String(totalLikes), date: today }],
});
result.push({
label: 'Recent Comments',
percentageChange: 0,
data: [{ total: String(totalComments), date: today }],
});
result.push({
label: 'Recent Shares',
percentageChange: 0,
data: [{ total: String(totalShares), date: today }],
});
}
}
return result;
} catch (err) {
console.error('Error fetching TikTok analytics:', err);
return [];
}
}
async missing(
id: string,
accessToken: string
): Promise<{ id: string; url: string }[]> {
try {
const videoListResponse = await this.fetch(
'https://open.tiktokapis.com/v2/video/list/?fields=id,cover_image_url,title',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ max_count: 20 }),
}
);
const videoListData = await videoListResponse.json();
const videos = videoListData?.data?.videos;
if (!videos || videos.length === 0) {
return [];
}
return videos.map((v: { id: string; cover_image_url: string }) => ({
id: String(v.id),
url: v.cover_image_url,
}));
} catch (err) {
console.error('Error fetching TikTok missing content:', err);
return [];
}
}
// Posts published before moderation finished keep their publish_id
// (v_pub_file~... / p_pub_url~...) as releaseId - resolve it to the post id
async resolveReleaseId(
accessToken: string,
releaseId: string,
integration: Integration,
settings: any,
releaseURL: string
) {
// a draft sent to the inbox (UPLOAD) is stored as 'missing' with its
// publish id in the URL fragment
const draft = releaseId === 'missing';
const publishId = draft ? releaseURL?.split('#')[1] || '' : releaseId;
if (
publishId.indexOf('_pub_') === -1 &&
publishId.indexOf('_inbox_') === -1
) {
return undefined;
}
// TikTok only gives a post id to posts published for public viewership
// (a draft ignores the privacy setting, the user picks it in the app)
if (
!draft &&
['SELF_ONLY', 'MUTUAL_FOLLOW_FRIENDS'].includes(settings?.privacy_level)
) {
return { unavailable: true as const };
}
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: publishId,
}),
}
)
).text()
);
if (!publicPostId) {
// a draft with no public post (not published yet, or published as
// non-public) keeps opening the inbox instead of asking to retry
return draft ? undefined : { pending: true as const };
}
return {
postId: publicPostId,
releaseURL: this.postUrl(integration, publishId, publicPostId),
};
}
async releaseUrl(accessToken: string, releaseId: string) {
const data = await (
await this.fetch(
'https://open.tiktokapis.com/v2/video/query/?fields=id,share_url',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
filters: {
video_ids: [releaseId],
},
}),
}
)
).json();
// share_url carries tracking params (the app's client key among them)
return data?.data?.videos?.[0]?.share_url?.split('?')[0] as
| string
| undefined;
}
async postAnalytics(
integrationId: string,
accessToken: string,
postId: string,
fromDate: number
): Promise<AnalyticsData[]> {
const today = dayjs().format('YYYY-MM-DD');
try {
// Query video details using the video ID
const response = await fetch(
'https://open.tiktokapis.com/v2/video/query/?fields=id,like_count,comment_count,share_count,view_count',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
filters: {
video_ids: [postId],
},
}),
}
);
const data = await response.json();
const video = data?.data?.videos?.[0];
if (!video) {
return [];
}
const result: AnalyticsData[] = [];
if (video.view_count !== undefined) {
result.push({
label: 'Views',
percentageChange: 0,
data: [{ total: String(video.view_count), date: today }],
});
}
if (video.like_count !== undefined) {
result.push({
label: 'Likes',
percentageChange: 0,
data: [{ total: String(video.like_count), date: today }],
});
}
if (video.comment_count !== undefined) {
result.push({
label: 'Comments',
percentageChange: 0,
data: [{ total: String(video.comment_count), date: today }],
});
}
if (video.share_count !== undefined) {
result.push({
label: 'Shares',
percentageChange: 0,
data: [{ total: String(video.share_count), date: today }],
});
}
return result;
} catch (err) {
console.error('Error fetching TikTok post analytics:', err);
return [];
}
}
}