Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions apps/docs/components/icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1274,6 +1274,31 @@ export function xAIIcon(props: SVGProps<SVGSVGElement>) {
)
}

export function TikTokIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 520.48 520.48'
width='1em'
height='1em'
{...props}
>
<path
fill='#ff004f'
d='m392.19,206.7v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63v-193.01h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.32,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
<path
fill='#00f7ef'
d='m375.32,166.81v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63V97.74h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.33,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
<path
fill='#fff'
d='m386.06,188.29v49.13c-8.6-.84-19.74-2.78-32.09-7.31-16.13-5.91-28.13-13.99-35.98-20.25v99.32l-.19-.31c.14,1.96.19,3.97.19,5.99,0,49.33-40.13,89.48-89.48,89.48s-89.48-40.15-89.48-89.48,40.13-89.5,89.48-89.5c4.82,0,9.57.39,14.2,1.13v48.43c-4.45-1.6-9.22-2.45-14.2-2.45-23.36,0-42.38,19-42.38,42.38s19.02,42.38,42.38,42.38,42.38-19.02,42.38-42.38c0-.88-.02-1.75-.08-2.63V119.22h49.11c.18,4.16.35,8.34.53,12.51.33,8.19,3.25,16.05,8.32,22.49,5.97,7.57,14.76,16.36,27.13,23.38,11.57,6.56,22.45,9.38,30.15,10.7Z'
/>
</svg>
)
}

export function xIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 50 50' width='1em' height='1em' {...props}>
Expand Down
2 changes: 2 additions & 0 deletions apps/docs/components/ui/icon-mapping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ import {
TemporalIcon,
TextractIcon,
ThriveIcon,
TikTokIcon,
TinybirdIcon,
TrelloIcon,
TriggerDevIcon,
Expand Down Expand Up @@ -473,6 +474,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
textract: TextractIcon,
textract_v2: TextractIcon,
thrive: ThriveIcon,
tiktok: TikTokIcon,
tinybird: TinybirdIcon,
trello: TrelloIcon,
trigger_dev: TriggerDevIcon,
Expand Down
1 change: 1 addition & 0 deletions apps/docs/content/docs/en/integrations/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@
"temporal",
"textract",
"thrive",
"tiktok",
"tinybird",
"trello",
"trigger_dev",
Expand Down
384 changes: 384 additions & 0 deletions apps/docs/content/docs/en/integrations/tiktok.mdx

Large diffs are not rendered by default.

215 changes: 215 additions & 0 deletions apps/sim/app/api/tools/tiktok/publish-video/route.ts
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 }
Comment thread
cursor[bot] marked this conversation as resolved.
}

function resolveVideoMimeType(fileName: string, fileType: string | undefined): string {
Comment thread
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 }
)
}
})
Loading
Loading