-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(tiktok): add tiktok trigger, block #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
Merged
Merged
Changes from all commits
Commits
Show all changes
22 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 d3b624a
Merge branch 'staging' into feature/tiktok-integration
icecrasher321 165fc4b
cleanup code
icecrasher321 a8b6081
fix type issues
icecrasher321 1416219
misc code cleanup
icecrasher321 694a33f
remove photos and add upload for videos
562ba12
move shared video output properties to types.ts so docs generation re…
e857ece
hide TikTok from toolbar and docs until the integration is ready to ship
d491684
Merge branch 'staging' into feature/tiktok-integration
BillLeoutsakosvl346 2521ba8
fix(ci): ratchet API validation baseline to 924 after staging merge
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 |
|---|---|---|
| @@ -0,0 +1,287 @@ | ||
| 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, readResponseTextWithLimit } 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' | ||
| import { tiktokPublishInitApiDataSchema } from '@/tools/tiktok/api-schemas' | ||
| import { readTikTokApiResponse } from '@/tools/tiktok/utils' | ||
|
|
||
| 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 | ||
| const TIKTOK_ERROR_RESPONSE_MAX_BYTES = 64 * 1024 | ||
|
|
||
| /** 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. */ | ||
| 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 | null { | ||
| if (fileType && TIKTOK_VIDEO_MIME_TYPES.has(fileType)) return fileType | ||
| const fromExtension = getMimeTypeFromExtension(getFileExtension(fileName)) | ||
| return TIKTOK_VIDEO_MIME_TYPES.has(fromExtension) ? fromExtension : null | ||
| } | ||
|
|
||
| async function validateDirectPostSettings( | ||
| accessToken: string, | ||
| postInfo: { privacy_level: string; brand_content_toggle: boolean }, | ||
| requestId: string | ||
| ): Promise<string | null> { | ||
| if (postInfo.brand_content_toggle && postInfo.privacy_level === 'SELF_ONLY') { | ||
| return 'Branded content cannot use Only Me privacy.' | ||
| } | ||
|
|
||
| const response = await fetch('https://open.tiktokapis.com/v2/post/publish/creator_info/query/', { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${accessToken}`, | ||
| 'Content-Type': 'application/json; charset=UTF-8', | ||
| }, | ||
| body: '{}', | ||
| }) | ||
| const data = await response.json() | ||
| if (!response.ok || (data.error?.code && data.error.code !== 'ok')) { | ||
| logger.warn(`[${requestId}] TikTok creator-info preflight failed`, { | ||
| status: response.status, | ||
| code: data.error?.code, | ||
| }) | ||
| return data.error?.message || 'TikTok creator information could not be verified.' | ||
| } | ||
|
|
||
| const privacyOptions: unknown = data.data?.privacy_level_options | ||
| if ( | ||
| !Array.isArray(privacyOptions) || | ||
| !privacyOptions.some((option) => option === postInfo.privacy_level) | ||
| ) { | ||
| return `The selected privacy level (${postInfo.privacy_level}) is not currently available for this TikTok account. Run Query Creator Info and choose one of the returned options.` | ||
| } | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| 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 readResponseTextWithLimit(response, { | ||
| maxBytes: TIKTOK_ERROR_RESPONSE_MAX_BYTES, | ||
| label: 'TikTok upload error response', | ||
| }).catch(() => 'Error response exceeded the allowed size') | ||
| 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 | ||
|
|
||
| if (data.mode === 'direct') { | ||
| const settingsError = await validateDirectPostSettings( | ||
| data.accessToken, | ||
| data.postInfo, | ||
| requestId | ||
| ) | ||
| if (settingsError) { | ||
| return NextResponse.json({ success: false, error: settingsError }, { status: 400 }) | ||
| } | ||
| } | ||
|
|
||
| const mimeType = resolveVideoMimeType(userFile.name, userFile.type) | ||
| if (!mimeType) { | ||
| return NextResponse.json( | ||
| { | ||
| success: false, | ||
| error: 'Unsupported video type. TikTok accepts MP4, MOV/QuickTime, or WebM files.', | ||
| }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
|
|
||
| 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, | ||
| }) | ||
| if (fileBuffer.length === 0) { | ||
| return NextResponse.json( | ||
| { success: false, error: 'The video file is empty.' }, | ||
| { status: 400 } | ||
| ) | ||
| } | ||
| 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 { data: initData, error: initError } = await readTikTokApiResponse( | ||
| initResponse, | ||
| tiktokPublishInitApiDataSchema | ||
| ) | ||
|
|
||
| if (initError) { | ||
| logger.error(`[${requestId}] TikTok init failed`, { error: initError }) | ||
| return NextResponse.json( | ||
| { success: false, error: initError.message || 'Failed to initialize TikTok upload' }, | ||
| { status: initResponse.status >= 400 ? initResponse.status : 502 } | ||
| ) | ||
| } | ||
|
|
||
| const publishId = initData?.publish_id | ||
| const uploadUrl = initData?.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.`, | ||
| }, | ||
| { 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.