-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(tiktok): add basic TikTok integration #5504
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BillLeoutsakosvl346
wants to merge
13
commits into
staging
Choose a base branch
from
feature/tiktok-integration
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,519
−5
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4f29765
feat(tiktok): add TikTok integration
909144b
fix(tiktok): add avatarFile output to Get User Info
f3f8215
fix(tiktok): lower upload memory cap, drop redundant avatar string ou…
71f3fac
chore(ci): bump API validation route-count baseline for TikTok publis…
d8608aa
chore(tiktok): drop unused avatar_url_100 from default user fields
b177848
fix(tiktok): stop returning raw 'credential' subBlock id from tools.c…
c856f33
fix(tiktok): send empty JSON body on Query Creator Info POST
e52669a
fix(tiktok): stop dropping valid zero values in optional numeric fields
68bb622
fix(tiktok): accept newline-separated video IDs in Query Videos
83841a3
feat(tiktok): add app-level webhook ingress and triggers
1e2e927
fix(tiktok): only count actually queued webhook executions
84bd3f6
chore(tiktok): bump API validation baseline for staging merge
cb1a766
Merge branch 'staging' into feature/tiktok-integration
BillLeoutsakosvl346 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -214,6 +214,7 @@ | |
| "temporal", | ||
| "textract", | ||
| "thrive", | ||
| "tiktok", | ||
| "tinybird", | ||
| "trello", | ||
| "trigger_dev", | ||
|
|
||
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { tiktokPublishVideoContract } from '@/lib/api/contracts/tiktok-tools' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { checkInternalAuth } from '@/lib/auth/hybrid' | ||
| import { generateRequestId } from '@/lib/core/utils/request' | ||
| import { isPayloadSizeLimitError } from '@/lib/core/utils/stream-limits' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { | ||
| getFileExtension, | ||
| getMimeTypeFromExtension, | ||
| processSingleFileToUserFile, | ||
| } from '@/lib/uploads/utils/file-utils' | ||
| import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server' | ||
| import { assertToolFileAccess } from '@/app/api/files/authorization' | ||
| import type { UserFile } from '@/executor/types' | ||
|
|
||
| export const dynamic = 'force-dynamic' | ||
|
|
||
| const logger = createLogger('TikTokPublishVideoAPI') | ||
|
|
||
| const TIKTOK_VIDEO_MIME_TYPES = new Set(['video/mp4', 'video/quicktime', 'video/webm']) | ||
|
|
||
| /** TikTok requires each chunk between 5MB and 64MB; the final chunk absorbs the remainder (up to ~2x this size, well under the 128MB cap). Capped at 1000 chunks total, which this default comfortably satisfies up to TikTok's 4GB video size limit. */ | ||
| const DEFAULT_CHUNK_SIZE = 10_000_000 | ||
|
|
||
| /** Maximum size this route will buffer in memory for a single file-upload request. TikTok's | ||
| * own limit is 4GB, but relaying that much through this server's memory per request isn't | ||
| * safe under concurrent load. Enforced before downloading the file so an oversized upload | ||
| * fails fast with a clean 413 instead of materializing hundreds of MB to multiple GB | ||
| * in-process. Users with larger files can use the "Public URL" source instead, since | ||
| * PULL_FROM_URL never routes bytes through this process. */ | ||
| const TIKTOK_MAX_VIDEO_BYTES = 250 * 1024 * 1024 | ||
|
|
||
| function computeChunkPlan(totalBytes: number): { chunkSize: number; totalChunkCount: number } { | ||
| if (totalBytes <= DEFAULT_CHUNK_SIZE) { | ||
| return { chunkSize: totalBytes, totalChunkCount: 1 } | ||
| } | ||
| const totalChunkCount = Math.floor(totalBytes / DEFAULT_CHUNK_SIZE) | ||
| return { chunkSize: DEFAULT_CHUNK_SIZE, totalChunkCount } | ||
| } | ||
|
|
||
| function resolveVideoMimeType(fileName: string, fileType: string | undefined): string { | ||
|
icecrasher321 marked this conversation as resolved.
|
||
| if (fileType && TIKTOK_VIDEO_MIME_TYPES.has(fileType)) return fileType | ||
| const fromExtension = getMimeTypeFromExtension(getFileExtension(fileName)) | ||
| return TIKTOK_VIDEO_MIME_TYPES.has(fromExtension) ? fromExtension : 'video/mp4' | ||
| } | ||
|
|
||
| async function uploadChunks( | ||
| uploadUrl: string, | ||
| buffer: Buffer, | ||
| mimeType: string, | ||
| requestId: string | ||
| ): Promise<void> { | ||
| const totalBytes = buffer.length | ||
| const { chunkSize, totalChunkCount } = computeChunkPlan(totalBytes) | ||
|
|
||
| for (let i = 0; i < totalChunkCount; i++) { | ||
| const start = i * chunkSize | ||
| const isLastChunk = i === totalChunkCount - 1 | ||
| const end = isLastChunk ? totalBytes - 1 : start + chunkSize - 1 | ||
| const chunk = buffer.subarray(start, end + 1) | ||
|
|
||
| const response = await fetch(uploadUrl, { | ||
| method: 'PUT', | ||
| headers: { | ||
| 'Content-Type': mimeType, | ||
| 'Content-Length': String(chunk.length), | ||
| 'Content-Range': `bytes ${start}-${end}/${totalBytes}`, | ||
| }, | ||
| body: new Uint8Array(chunk), | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| const errorText = await response.text().catch(() => '') | ||
| logger.error(`[${requestId}] TikTok chunk upload failed`, { | ||
| chunkIndex: i, | ||
| status: response.status, | ||
| errorText, | ||
| }) | ||
| throw new Error( | ||
| `TikTok rejected video chunk ${i + 1}/${totalChunkCount}: ${response.status} ${errorText || response.statusText}` | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export const POST = withRouteHandler(async (request: NextRequest) => { | ||
| const requestId = generateRequestId() | ||
|
|
||
| try { | ||
| const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) | ||
| if (!authResult.success || !authResult.userId) { | ||
| logger.warn(`[${requestId}] Unauthorized TikTok publish-video attempt: ${authResult.error}`) | ||
| return NextResponse.json( | ||
| { success: false, error: authResult.error || 'Authentication required' }, | ||
| { status: 401 } | ||
| ) | ||
| } | ||
|
|
||
| const parsed = await parseRequest(tiktokPublishVideoContract, request, {}) | ||
| if (!parsed.success) return parsed.response | ||
| const data = parsed.data.body | ||
|
|
||
| let userFile: UserFile | ||
| try { | ||
| userFile = processSingleFileToUserFile(data.file, requestId, logger) | ||
| } catch (error) { | ||
| return NextResponse.json( | ||
| { success: false, error: getErrorMessage(error, 'Failed to process file') }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger) | ||
| if (denied) return denied | ||
|
|
||
| logger.info(`[${requestId}] Downloading video from storage`, { | ||
| fileName: userFile.name, | ||
| size: userFile.size, | ||
| }) | ||
|
|
||
| const fileBuffer = await downloadFileFromStorage(userFile, requestId, logger, { | ||
| maxBytes: TIKTOK_MAX_VIDEO_BYTES, | ||
| }) | ||
| const mimeType = resolveVideoMimeType(userFile.name, userFile.type) | ||
| const { chunkSize, totalChunkCount } = computeChunkPlan(fileBuffer.length) | ||
|
|
||
| const initUrl = | ||
| data.mode === 'draft' | ||
| ? 'https://open.tiktokapis.com/v2/post/publish/inbox/video/init/' | ||
| : 'https://open.tiktokapis.com/v2/post/publish/video/init/' | ||
|
|
||
| const initBody: Record<string, unknown> = { | ||
| source_info: { | ||
| source: 'FILE_UPLOAD', | ||
| video_size: fileBuffer.length, | ||
| chunk_size: chunkSize, | ||
| total_chunk_count: totalChunkCount, | ||
| }, | ||
| } | ||
| if (data.mode === 'direct') { | ||
| initBody.post_info = data.postInfo ?? {} | ||
| } | ||
|
|
||
| logger.info(`[${requestId}] Initializing TikTok video ${data.mode}`, { | ||
| videoSize: fileBuffer.length, | ||
| chunkSize, | ||
| totalChunkCount, | ||
| }) | ||
|
|
||
| const initResponse = await fetch(initUrl, { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${data.accessToken}`, | ||
| 'Content-Type': 'application/json; charset=UTF-8', | ||
| }, | ||
| body: JSON.stringify(initBody), | ||
| }) | ||
|
|
||
| const initData = await initResponse.json() | ||
|
|
||
| if (initData.error?.code && initData.error.code !== 'ok') { | ||
| logger.error(`[${requestId}] TikTok init failed`, { error: initData.error }) | ||
| return NextResponse.json( | ||
| { success: false, error: initData.error.message || 'Failed to initialize TikTok upload' }, | ||
| { status: initResponse.status >= 400 ? initResponse.status : 502 } | ||
| ) | ||
| } | ||
|
|
||
| const publishId: string | undefined = initData.data?.publish_id | ||
| const uploadUrl: string | undefined = initData.data?.upload_url | ||
|
|
||
| if (!publishId || !uploadUrl) { | ||
| return NextResponse.json( | ||
| { success: false, error: 'TikTok did not return a publish ID and upload URL' }, | ||
| { status: 502 } | ||
| ) | ||
| } | ||
|
|
||
| try { | ||
| await uploadChunks(uploadUrl, fileBuffer, mimeType, requestId) | ||
| } catch (error) { | ||
| return NextResponse.json( | ||
| { success: false, error: getErrorMessage(error, 'Failed to upload video to TikTok') }, | ||
| { status: 502 } | ||
| ) | ||
| } | ||
|
|
||
| logger.info(`[${requestId}] TikTok video upload complete`, { publishId }) | ||
|
|
||
| return NextResponse.json({ success: true, output: { publishId } }) | ||
| } catch (error) { | ||
| if (isPayloadSizeLimitError(error)) { | ||
| logger.warn(`[${requestId}] Rejected oversized TikTok video upload`, { | ||
| maxBytes: error.maxBytes, | ||
| observedBytes: error.observedBytes, | ||
| }) | ||
| const maxMb = Math.floor(TIKTOK_MAX_VIDEO_BYTES / (1024 * 1024)) | ||
| return NextResponse.json( | ||
| { | ||
| success: false, | ||
| error: `Video exceeds the ${maxMb}MB limit for file uploads. Use a public video URL instead to post larger files.`, | ||
| }, | ||
| { status: 413 } | ||
| ) | ||
| } | ||
| logger.error(`[${requestId}] Error publishing video to TikTok:`, error) | ||
| return NextResponse.json( | ||
| { success: false, error: getErrorMessage(error, 'Internal server error') }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| }) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.