Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: tiktok business music, location and random music

Nevo David885f9a5c284b
diff --git a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.location.tsx b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.location.tsx
new file mode 100644
index 000000000..582ea3e39
--- /dev/null
+++ b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.location.tsx
@@ -0,0 +1,183 @@
+'use client';
+
+import { FC, useCallback, useEffect, useState } from 'react';
+import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';
+import { useCustomProviderFunction } from '@gitroom/frontend/components/launches/helpers/use.custom.provider.function';
+import { useT } from '@gitroom/react/translation/get.transation.service.client';
+
+interface LocationResult {
+ id: string;
+ name: string;
+ address: string;
+}
+
+interface SelectedLocation {
+ id: string;
+ name: string;
+ address?: string;
+}
+
+export const TikTokLocationSelector: FC<{
+ name: string;
+ label: string;
+ onChange: (event: {
+ target: {
+ value: SelectedLocation | undefined;
+ name: string;
+ };
+ }) => void;
+}> = (props) => {
+ const { onChange, name, label } = props;
+ const t = useT();
+ const { getValues } = useSettings();
+ const customFunc = useCustomProviderFunction();
+ const [value, setValue] = useState<SelectedLocation | undefined>();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<LocationResult[]>([]);
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ const settings = getValues()[name];
+ if (settings?.id) {
+ setValue(settings);
+ }
+ }, []);
+
+ const emit = useCallback(
+ (newValue: SelectedLocation | undefined) => {
+ setValue(newValue);
+ onChange({
+ target: {
+ value: newValue,
+ name,
+ },
+ });
+ },
+ [onChange, name]
+ );
+
+ useEffect(() => {
+ if (!open || !query) {
+ setResults([]);
+ setLoading(false);
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ const search = setTimeout(async () => {
+ try {
+ const list = await customFunc.get('locationSearch', { q: query });
+ if (!cancelled) {
+ setResults(Array.isArray(list) ? list : []);
+ }
+ } catch (err) {
+ if (!cancelled) {
+ setResults([]);
+ }
+ } finally {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ }
+ }, 500);
+ return () => {
+ cancelled = true;
+ clearTimeout(search);
+ };
+ }, [query, open]);
+
+ const selectLocation = useCallback(
+ (location: LocationResult) => {
+ setOpen(false);
+ emit({
+ id: location.id,
+ name: location.name,
+ address: location.address,
+ });
+ },
+ [emit]
+ );
+
+ const removeLocation = useCallback(() => {
+ emit(undefined);
+ }, [emit]);
+
+ return (
+ <div className="flex flex-col gap-[6px]">
+ <div className="text-[14px]">{label}</div>
+ {value?.id ? (
+ <div className="flex items-center gap-[12px] bg-newBgColorInner border-newTableBorder border rounded-[8px] p-[12px]">
+ <div className="flex-1 flex flex-col">
+ <div className="text-[14px]">{value.name}</div>
+ {!!value.address && (
+ <div className="text-[12px] opacity-70">{value.address}</div>
+ )}
+ </div>
+ <div
+ className="cursor-pointer text-[14px] opacity-70 hover:opacity-100"
+ onClick={removeLocation}
+ >
+ X
+ </div>
+ </div>
+ ) : !open ? (
+ <div>
+ <div
+ className="h-[42px] px-[16px] inline-flex items-center cursor-pointer bg-newBgColorInner border-newTableBorder border rounded-[8px] text-[14px]"
+ onClick={() => setOpen(true)}
+ >
+ {t('tiktok_add_location', 'Add location')}
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-[6px]">
+ <div className="flex gap-[6px]">
+ <div className="flex-1 h-[42px] bg-newBgColorInner border-newTableBorder border rounded-[8px] flex items-center">
+ <input
+ className="h-full w-full bg-transparent outline-none px-[16px] text-[14px] text-textColor placeholder-textColor"
+ placeholder={t('tiktok_search_location', 'Search location')}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <div
+ className="h-[42px] px-[16px] flex items-center cursor-pointer bg-newBgColorInner border-newTableBorder border rounded-[8px] text-[14px]"
+ onClick={() => setOpen(false)}
+ >
+ {t('cancel', 'Cancel')}
+ </div>
+ </div>
+ {!!query && (
+ <div className="max-h-[250px] overflow-y-auto flex flex-col bg-newBgColorInner border-newTableBorder border rounded-[8px]">
+ {loading ? (
+ <div className="p-[12px] text-[14px] opacity-70">
+ {t('loading', 'Loading...')}
+ </div>
+ ) : !results.length ? (
+ <div className="p-[12px] text-[14px] opacity-70">
+ {t('tiktok_no_location_found', 'No location found')}
+ </div>
+ ) : (
+ results.map((location) => (
+ <div
+ key={location.id}
+ className="flex flex-col p-[8px] hover:bg-newTableBorder cursor-pointer"
+ onClick={() => selectLocation(location)}
+ >
+ <div className="text-[14px]">{location.name}</div>
+ {!!location.address && (
+ <div className="text-[12px] opacity-70">
+ {location.address}
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.music.tsx b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.music.tsx
new file mode 100644
index 000000000..3c395fb31
--- /dev/null
+++ b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.music.tsx
@@ -0,0 +1,327 @@
+'use client';
+
+import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';
+import { useCustomProviderFunction } from '@gitroom/frontend/components/launches/helpers/use.custom.provider.function';
+import { useT } from '@gitroom/react/translation/get.transation.service.client';
+import clsx from 'clsx';
+
+interface MusicResult {
+ id: string;
+ title: string;
+ artist: string;
+ image: string;
+ duration: number;
+ previewUrl: string;
+}
+
+interface SelectedMusic {
+ id: string;
+ title?: string;
+ artist?: string;
+ image?: string;
+ audio_volume?: number;
+ video_volume?: number;
+}
+
+const formatDuration = (ms: number) => {
+ const seconds = Math.floor(ms / 1000);
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(
+ 2,
+ '0'
+ )}`;
+};
+
+export const TikTokMusicSelector: FC<{
+ name: string;
+ label: string;
+ showVolumes: boolean;
+ onChange: (event: {
+ target: {
+ value: SelectedMusic | undefined;
+ name: string;
+ };
+ }) => void;
+}> = (props) => {
+ const { onChange, name, label, showVolumes } = props;
+ const t = useT();
+ const { getValues } = useSettings();
+ const customFunc = useCustomProviderFunction();
+ const [value, setValue] = useState<SelectedMusic | undefined>();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<MusicResult[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [playingId, setPlayingId] = useState<string>('');
+ const player = useRef<HTMLAudioElement | undefined>(undefined);
+
+ useEffect(() => {
+ const settings = getValues()[name];
+ if (settings?.id) {
+ setValue(settings);
+ }
+ }, []);
+
+ const stopPreview = useCallback(() => {
+ player.current?.pause();
+ player.current = undefined;
+ setPlayingId('');
+ }, []);
+
+ useEffect(() => stopPreview, []);
+
+ const emit = useCallback(
+ (newValue: SelectedMusic | undefined) => {
+ setValue(newValue);
+ onChange({
+ target: {
+ value: newValue,
+ name,
+ },
+ });
+ },
+ [onChange, name]
+ );
+
+ // The commercial music library trending list has no text search parameter,
+ // so the full list is loaded once and the query filters it locally.
+ useEffect(() => {
+ if (!open || results.length) {
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ customFunc
+ .get('musicSearch')
+ .then((list) => {
+ if (!cancelled) {
+ setResults(Array.isArray(list) ? list : []);
+ }
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setResults([]);
+ }
+ })
+ .finally(() => {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open]);
+
+ const filteredResults = useMemo(() => {
+ if (!query) {
+ return results;
+ }
+ const lowerQuery = query.toLowerCase();
+ return results.filter(
+ (track) =>
+ track.title.toLowerCase().indexOf(lowerQuery) > -1 ||
+ track.artist.toLowerCase().indexOf(lowerQuery) > -1
+ );
+ }, [results, query]);
+
+ const togglePreview = useCallback(
+ (track: MusicResult) => {
+ if (playingId === track.id) {
+ stopPreview();
+ return;
+ }
+ stopPreview();
+ if (!track.previewUrl) {
+ return;
+ }
+ const newPlayer = new Audio(track.previewUrl);
+ newPlayer.onended = () => setPlayingId('');
+ newPlayer.play();
+ player.current = newPlayer;
+ setPlayingId(track.id);
+ },
+ [playingId, stopPreview]
+ );
+
+ const selectMusic = useCallback(
+ (track: MusicResult) => {
+ stopPreview();
+ setOpen(false);
+ emit({
+ id: track.id,
+ title: track.title,
+ artist: track.artist,
+ image: track.image,
+ audio_volume: 50,
+ video_volume: 50,
+ });
+ },
+ [emit, stopPreview]
+ );
+
+ const removeMusic = useCallback(() => {
+ emit(undefined);
+ }, [emit]);
+
+ const changeVolume = useCallback(
+ (key: 'audio_volume' | 'video_volume', volume: number) => {
+ if (!value) {
+ return;
+ }
+ emit({
+ ...value,
+ [key]: volume,
+ });
+ },
+ [emit, value]
+ );
+
+ return (
+ <div className="flex flex-col gap-[6px]">
+ <div className="text-[14px]">{label}</div>
+ {value?.id ? (
+ <div className="flex flex-col gap-[12px] bg-newBgColorInner border-newTableBorder border rounded-[8px] p-[12px]">
+ <div className="flex items-center gap-[12px]">
+ {!!value.image && (
+ <img
+ src={value.image}
+ className="w-[42px] h-[42px] rounded-[8px] object-cover"
+ />
+ )}
+ <div className="flex-1 flex flex-col">
+ <div className="text-[14px]">{value.title}</div>
+ {!!value.artist && (
+ <div className="text-[12px] opacity-70">{value.artist}</div>
+ )}
+ </div>
+ <div
+ className="cursor-pointer text-[14px] opacity-70 hover:opacity-100"
+ onClick={removeMusic}
+ >
+ X
+ </div>
+ </div>
+ {showVolumes && (
+ <div className="flex gap-[18px]">
+ <div className="flex-1 flex flex-col gap-[6px]">
+ <div className="text-[12px]">
+ {t('tiktok_music_volume', 'Music volume')} (
+ {value.audio_volume ?? 50})
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={value.audio_volume ?? 50}
+ onChange={(e) =>
+ changeVolume('audio_volume', +e.target.value)
+ }
+ />
+ </div>
+ <div className="flex-1 flex flex-col gap-[6px]">
+ <div className="text-[12px]">
+ {t('tiktok_video_volume', 'Original video volume')} (
+ {value.video_volume ?? 50})
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={value.video_volume ?? 50}
+ onChange={(e) =>
+ changeVolume('video_volume', +e.target.value)
+ }
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ ) : !open ? (
+ <div>
+ <div
+ className="h-[42px] px-[16px] inline-flex items-center cursor-pointer bg-newBgColorInner border-newTableBorder border rounded-[8px] text-[14px]"
+ onClick={() => setOpen(true)}
+ >
+ {t('tiktok_add_music', 'Add music')}
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-[6px]">
+ <div className="flex gap-[6px]">
+ <div className="flex-1 h-[42px] bg-newBgColorInner border-newTableBorder border rounded-[8px] flex items-center">
+ <input
+ className="h-full w-full bg-transparent outline-none px-[16px] text-[14px] text-textColor placeholder-textColor"
+ placeholder={t(
+ 'tiktok_search_music',
+ 'Filter trending tracks by name or artist'
+ )}
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </div>
+ <div
+ className="h-[42px] px-[16px] flex items-center cursor-pointer bg-newBgColorInner border-newTableBorder border rounded-[8px] text-[14px]"
+ onClick={() => {
+ stopPreview();
+ setOpen(false);
+ }}
+ >
+ {t('cancel', 'Cancel')}
+ </div>
+ </div>
+ <div className="max-h-[250px] overflow-y-auto flex flex-col bg-newBgColorInner border-newTableBorder border rounded-[8px]">
+ {loading ? (
+ <div className="p-[12px] text-[14px] opacity-70">
+ {t('loading', 'Loading...')}
+ </div>
+ ) : !filteredResults.length ? (
+ <div className="p-[12px] text-[14px] opacity-70">
+ {t('tiktok_no_music_found', 'No music found')}
+ </div>
+ ) : (
+ filteredResults.map((track) => (
+ <div
+ key={track.id}
+ className="flex items-center gap-[12px] p-[8px] hover:bg-newTableBorder cursor-pointer"
+ onClick={() => selectMusic(track)}
+ >
+ {!!track.image && (
+ <img
+ src={track.image}
+ className="w-[36px] h-[36px] rounded-[8px] object-cover"
+ />
+ )}
+ <div className="flex-1 flex flex-col">
+ <div className="text-[14px]">{track.title}</div>
+ <div className="text-[12px] opacity-70">
+ {[track.artist, track.duration ? formatDuration(track.duration) : '']
+ .filter((f) => f)
+ .join(' Β· ')}
+ </div>
+ </div>
+ {!!track.previewUrl && (
+ <div
+ className={clsx(
+ 'px-[12px] text-[12px] opacity-70 hover:opacity-100',
+ playingId === track.id && 'opacity-100'
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePreview(track);
+ }}
+ >
+ {playingId === track.id
+ ? t('stop', 'Stop')
+ : t('play', 'Play')}
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx
index 907c29fd1..68813df24 100644
--- a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx
+++ b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx
@@ -17,14 +17,20 @@ import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useIntegration } from '@gitroom/frontend/components/launches/helpers/use.integration';
import { Input } from '@gitroom/react/form/input';
import { TiktokPreview } from '@gitroom/frontend/components/new-launch/providers/tiktok/tiktok.preview';
+import { TikTokMusicSelector } from '@gitroom/frontend/components/new-launch/providers/tiktok/tiktok.music';
+import { TikTokLocationSelector } from '@gitroom/frontend/components/new-launch/providers/tiktok/tiktok.location';
const TikTokSettings: FC<{
values?: any;
}> = (props) => {
const { watch, register } = useSettings();
- const { value } = useIntegration();
+ const { value, integration } = useIntegration();
const t = useT();
+ // Music and location come from the Business API (v1.3) - the legacy Content
+ // Posting API used by the "tiktok" identifier has no such fields.
+ const isBusiness = integration?.identifier === 'tiktok-business';
+
const isTitle = useMemo(() => {
return value?.[0]?.image?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) === -1);
}, [value]);
@@ -33,6 +39,7 @@ const TikTokSettings: FC<{
const isVideo = hasMedia && !isTitle;
const disclose = watch('disclose');
+ const autoAddMusic = watch('autoAddMusic');
const brand_organic_toggle = watch('brand_organic_toggle');
const brand_content_toggle = watch('brand_content_toggle');
const content_posting_method = watch('content_posting_method');
@@ -165,7 +172,11 @@ const TikTokSettings: FC<{
{isUploadMode && <div className="-mt-[23px] mb-[23px] text-red-600">After posting you fill find a notification inside your Inbox about your post (not content studio)</div>}
<div className={clsx('flex flex-col', directPostOnly)}>
<Select
- label={t('label_auto_add_music', 'Auto add music')}
+ label={
+ isBusiness
+ ? t('label_add_random_music', 'Add random music')
+ : t('label_auto_add_music', 'Auto add music')
+ }
disabled={isUploadMode}
{...register('autoAddMusic', {
value: 'no',
@@ -179,11 +190,39 @@ const TikTokSettings: FC<{
))}
</Select>
<div className="text-[14px] mt-[10px] mb-[24px] text-balance">
- {t(
- 'this_feature_available_only_for_photos',
- 'This feature available only for photos, it will add a default music that\n you can change later.'
- )}
+ {isBusiness
+ ? t(
+ 'tiktok_random_music_only_for_photos',
+ 'This feature available only for photos, it will add a random trending track from TikTok\'s commercial music library.'
+ )
+ : t(
+ 'this_feature_available_only_for_photos',
+ 'This feature available only for photos, it will add a default music that\n you can change later.'
+ )}
</div>
+ {isBusiness && (
+ <div className="flex flex-col gap-[18px] mb-[24px]">
+ {/* Random music replaces a manual choice for photos, so the
+ selector is hidden (but stays registered) while it's on. */}
+ <div
+ className={clsx(
+ !isVideo &&
+ autoAddMusic === 'yes' &&
+ 'invisible h-0 overflow-hidden'
+ )}
+ >
+ <TikTokMusicSelector
+ label={t('tiktok_music_label', 'Music')}
+ showVolumes={isVideo}
+ {...register('music')}
+ />
+ </div>
+ <TikTokLocationSelector
+ label={t('tiktok_location_label', 'Location')}
+ {...register('location')}
+ />
+ </div>
+ )}
<hr className="mb-[15px] border-tableBorder" />
<div className="text-[14px] mb-[10px]">
{t('tiktok_video_features', 'Video features')}
diff --git a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/tiktok.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/tiktok.dto.ts
index c5fc64704..f5be6b0c7 100644
--- a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/tiktok.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/tiktok.dto.ts
@@ -1,14 +1,71 @@
import {
- IsBoolean, ValidateIf, IsIn, IsString, MaxLength, IsOptional
+ IsBoolean, ValidateIf, IsIn, IsString, MaxLength, IsOptional, IsDefined, IsNumber, Min, Max, ValidateNested
} from 'class-validator';
+import { Type } from 'class-transformer';
import { JSONSchema } from 'class-validator-jsonschema';
+export class TikTokMusic {
+ @IsDefined()
+ @IsString()
+ @JSONSchema({
+ description:
+ 'The commercial music library track id, taken from the "id" returned by the musicSearch function.',
+ })
+ id: string;
+
+ @IsOptional()
+ @IsString()
+ title?: string;
+
+ @IsOptional()
+ @IsString()
+ artist?: string;
+
+ @IsOptional()
+ @IsString()
+ image?: string;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsNumber()
+ @Min(0)
+ @Max(100)
+ audio_volume?: number;
+
+ @IsOptional()
+ @Type(() => Number)
+ @IsNumber()
+ @Min(0)
+ @Max(100)
+ video_volume?: number;
+}
+
+export class TikTokLocation {
+ @IsDefined()
+ @IsString()
+ @JSONSchema({
+ description:
+ 'The location tag id, taken from the "id" returned by the locationSearch function.',
+ })
+ id: string;
+
+ @IsDefined()
+ @IsString()
+ name: string;
+
+ @IsOptional()
+ @IsString()
+ address?: string;
+}
+
// TikTok only honors most of these settings on a DIRECT_POST. With
// content_posting_method=UPLOAD the media lands in the user's TikTok inbox as a
// draft, and TikTok's inbox/upload endpoints accept nothing but the title /
// description - every other field below is silently discarded.
// video_made_with_ai / duet / stitch are additionally video-only: TikTok's photo
// post_info has no is_aigc, disable_duet or disable_stitch field.
+// music / location are TikTok Business only: the legacy TikTok provider ignores
+// them (its Content Posting API has no music_sound_info / location fields).
// Fields stay required here (existing clients depend on it); the constraints are
// documented, not enforced.
export class TikTokDto {
@@ -61,7 +118,9 @@ export class TikTokDto {
@IsIn(['yes', 'no'])
@JSONSchema({
description:
- 'Photo posts only, and only when content_posting_method=DIRECT_POST. Ignored by TikTok on UPLOAD.',
+ 'Photo posts only, and only when content_posting_method=DIRECT_POST. Ignored by TikTok on UPLOAD. ' +
+ 'On TikTok Business, "yes" attaches a random commercial music library track and overrides the music setting; ' +
+ 'on legacy TikTok, "yes" lets TikTok auto-add its recommended music.',
})
autoAddMusic: 'yes' | 'no';
@@ -87,6 +146,24 @@ export class TikTokDto {
})
brand_organic_toggle: boolean;
+ @Type(() => TikTokMusic)
+ @ValidateNested()
+ @IsOptional()
+ @JSONSchema({
+ description:
+ 'TikTok Business only, and only when content_posting_method=DIRECT_POST. Attaches a commercial music library track to the post (use the musicSearch function to find one). audio_volume / video_volume apply to video posts only. For photos, ignored when autoAddMusic is "yes" (a random track is attached instead).',
+ })
+ music?: TikTokMusic;
+
+ @Type(() => TikTokLocation)
+ @ValidateNested()
+ @IsOptional()
+ @JSONSchema({
+ description:
+ 'TikTok Business only, and only when content_posting_method=DIRECT_POST. Tags the post with a location (use the locationSearch function to find one).',
+ })
+ location?: TikTokLocation;
+
@IsIn(['DIRECT_POST', 'UPLOAD'])
@IsString()
@JSONSchema({
diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
index d60e954c8..cd9f8de37 100644
--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
@@ -19,13 +19,15 @@ import { timer } from '@gitroom/helpers/utils/timer';
import { hasExtension } from '@gitroom/helpers/utils/has.extension';
import { Integration } from '@prisma/client';
import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';
+import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
@Rules(
[
'TikTok Business can have one video or one picture or multiple pictures (up to 35), 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 saves the media as a draft in the user inbox of the TikTok app, where the user must manually complete and publish it. 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. privacy_level and autoAddMusic apply to photo posts only - the TikTok Business API has no privacy or music field for video posts, so those settings are discarded when the attachment is a video.',
+ 'video_made_with_ai, duet and stitch apply to video posts only. privacy_level and autoAddMusic apply to photo posts only - the TikTok Business API has no privacy field for video posts, so those settings are discarded when the attachment is a video.',
+ 'The music setting attaches a commercial music library track (found via the musicSearch function) to a video or photo post, and the location setting tags the post with a location (found via the locationSearch function). Both apply only with content_posting_method=DIRECT_POST. music.audio_volume / music.video_volume (0-100, default 50) apply to video posts only. For photos, autoAddMusic=yes attaches a RANDOM commercial music library track and overrides any music selection - use autoAddMusic=no when the user wants a specific track.',
'Media is pulled by TikTok from its URL, so the media must be uploaded to Postiz and the media domain must be a verified URL property of the TikTok Business app.',
].join(' ')
)
@@ -519,14 +521,69 @@ export class TiktokBusinessProvider
is_ai_generated: this.assetBoolean(
firstPost.settings.video_made_with_ai
),
+ ...(firstPost.settings.location?.id
+ ? {
+ location_id: firstPost.settings.location.id,
+ location_name: firstPost.settings.location.name,
+ }
+ : {}),
+ // The API defaults both volumes to 0 (muted) - the TikTok app
+ // defaults to 50, so a selected track without explicit volumes
+ // follows the app behavior instead of publishing a silent post.
+ ...(firstPost.settings.music?.id
+ ? {
+ music_sound_info: {
+ music_sound_id: firstPost.settings.music.id,
+ music_sound_volume:
+ typeof firstPost.settings.music.audio_volume !==
+ 'undefined'
+ ? +firstPost.settings.music.audio_volume
+ : 50,
+ video_original_sound_volume:
+ typeof firstPost.settings.music.video_volume !==
+ 'undefined'
+ ? +firstPost.settings.music.video_volume
+ : 50,
+ },
+ }
+ : {}),
}),
},
};
}
- private buildPhotoBody(businessId: string, firstPost: PostDetails<TikTokDto>) {
+ // autoAddMusic picks a random commercial-library track instead of TikTok's
+ // auto_add_music flag, so the attached music is chosen by Postiz rather than
+ // silently by TikTok. Returns undefined when the trending list is empty or
+ // unavailable - the photo body then falls back to auto_add_music.
+ private async pickRandomMusicId(
+ accessToken: string,
+ businessId: string
+ ): Promise<string | undefined> {
+ const tracks = await this.musicSearch(accessToken, {}, businessId);
+ if (!tracks.length) {
+ return undefined;
+ }
+ return tracks[Math.floor(Math.random() * tracks.length)].id;
+ }
+
+ private async buildPhotoBody(
+ businessId: string,
+ firstPost: PostDetails<TikTokDto>,
+ accessToken: string
+ ) {
const isDraft = this.contentPostingMethod(firstPost) === 'UPLOAD';
+ // Random music wins over an explicitly selected track: the UI hides the
+ // music selector while "add random music" is on, so a stale selection must
+ // not silently override it.
+ const musicId =
+ firstPost.settings.autoAddMusic === 'yes'
+ ? !isDraft
+ ? await this.pickRandomMusicId(accessToken, businessId)
+ : undefined
+ : firstPost.settings.music?.id;
+
return {
business_id: businessId,
photo_images: firstPost.media?.map((p) => p.path),
@@ -548,7 +605,24 @@ export class TiktokBusinessProvider
privacy_level:
firstPost.settings.privacy_level || 'PUBLIC_TO_EVERYONE',
disable_comment: !this.assetBoolean(firstPost.settings.comment),
- auto_add_music: firstPost.settings.autoAddMusic === 'yes',
+ // TikTok's own recommended-music flag is only a fallback for
+ // when no track could be picked from the trending list.
+ auto_add_music:
+ !musicId && firstPost.settings.autoAddMusic === 'yes',
+ ...(firstPost.settings.location?.id
+ ? {
+ location_id: firstPost.settings.location.id,
+ location_name: firstPost.settings.location.name,
+ }
+ : {}),
+ // Unlike videos, the photo music_sound_info has no volume fields.
+ ...(musicId
+ ? {
+ music_sound_info: {
+ music_sound_id: musicId,
+ },
+ }
+ : {}),
}),
},
};
@@ -564,7 +638,7 @@ export class TiktokBusinessProvider
const isPhoto = !hasExtension(firstPost?.media?.[0]?.path, 'mp4');
const body = isPhoto
- ? this.buildPhotoBody(id, firstPost)
+ ? await this.buildPhotoBody(id, firstPost, accessToken)
: this.buildVideoBody(id, firstPost);
const publish = await (
@@ -681,6 +755,114 @@ export class TiktokBusinessProvider
);
}
+ // The trending list has no text search parameter - genre / country / date
+ // range are the only filters - so the UI filters the returned list locally.
+ @Tool({
+ description:
+ 'Load commercial music library tracks that can be attached to a post via the "music" setting',
+ dataSchema: [
+ {
+ key: 'genre',
+ type: 'string',
+ description:
+ 'Genre to filter the tracks by (for example POP, ROCK, ELECTRONIC), leave empty for all genres',
+ },
+ ],
+ })
+ async musicSearch(
+ accessToken: string,
+ data: { genre?: string },
+ id: string
+ ) {
+ const music = await (
+ await this.fetch(
+ `${this.baseUrl}/discovery/cml/trending_list/?business_id=${encodeURIComponent(
+ id
+ )}${data?.genre ? `&genre=${encodeURIComponent(data.genre)}` : ''}`,
+ {
+ method: 'GET',
+ headers: {
+ 'Access-Token': accessToken,
+ },
+ }
+ )
+ ).json();
+
+ // Errors arrive as HTTP 200 with a non-zero code, invisible to this.fetch:
+ // a token error must surface as RefreshToken so the function endpoint
+ // refreshes and retries, anything else just returns no tracks.
+ if (music?.code !== 0) {
+ const asString = JSON.stringify(music);
+ const handleError = this.handleErrors(asString);
+ if (handleError?.type === 'refresh-token') {
+ throw new RefreshToken('tiktok-business', asString, '{}', handleError.value);
+ }
+ return [];
+ }
+
+ return (music?.data?.list || [])
+ .map((track: any) => ({
+ // song_clip_id is the value music_sound_id expects; older responses
+ // only carry commercial_music_id, which TikTok accepts as well.
+ id:
+ track?.full_duration_song_clip?.song_clip_id ||
+ track?.commercial_music_id,
+ title: track?.commercial_music_name || '',
+ artist: track?.artist || '',
+ image: track?.thumbnail_url || '',
+ duration: (track?.duration || 0) * 1000,
+ previewUrl: track?.preview_url || '',
+ }))
+ .filter((track: { id?: string }) => track.id);
+ }
+
+ @Tool({
+ description:
+ 'Search location tags that can be attached to a post via the "location" setting',
+ dataSchema: [
+ {
+ key: 'q',
+ type: 'string',
+ description: 'Search query for the location',
+ },
+ ],
+ })
+ async locationSearch(accessToken: string, data: { q: string }, id: string) {
+ if (!data?.q) {
+ return [];
+ }
+
+ const locations = await (
+ await this.fetch(
+ `${this.baseUrl}/business/publish/location/?business_id=${encodeURIComponent(
+ id
+ )}&search_query=${encodeURIComponent(data.q.slice(0, 100))}`,
+ {
+ method: 'GET',
+ headers: {
+ 'Access-Token': accessToken,
+ },
+ }
+ )
+ ).json();
+
+ // Same HTTP 200 + non-zero code envelope as musicSearch.
+ if (locations?.code !== 0) {
+ const asString = JSON.stringify(locations);
+ const handleError = this.handleErrors(asString);
+ if (handleError?.type === 'refresh-token') {
+ throw new RefreshToken('tiktok-business', asString, '{}', handleError.value);
+ }
+ return [];
+ }
+
+ return (locations?.data?.locations || []).map((location: any) => ({
+ id: location?.location_id,
+ name: location?.location_name || '',
+ address: location?.location_address || '',
+ }));
+ }
+
private async loadVideoList(
accessToken: string,
businessId: string,