Skip to content

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

feat: reel audio

Nevo Davideaf866ad8b33
diff --git a/apps/frontend/src/components/new-launch/providers/instagram/instagram.audio.tsx b/apps/frontend/src/components/new-launch/providers/instagram/instagram.audio.tsx
new file mode 100644
index 000000000..d49c36cca
--- /dev/null
+++ b/apps/frontend/src/components/new-launch/providers/instagram/instagram.audio.tsx
@@ -0,0 +1,353 @@
+'use client';
+
+import { FC, useCallback, useEffect, 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 { Select } from '@gitroom/react/form/select';
+import { useT } from '@gitroom/react/translation/get.transation.service.client';
+import clsx from 'clsx';
+
+interface AudioResult {
+ id: string;
+ title: string;
+ artist: string;
+ image: string;
+ duration: number;
+ previewUrl: string;
+}
+
+interface SelectedAudio {
+ 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 InstagramAudioSelector: FC<{
+ name: string;
+ label: string;
+ disabled?: boolean;
+ onChange: (event: {
+ target: {
+ value: SelectedAudio | undefined;
+ name: string;
+ };
+ }) => void;
+}> = (props) => {
+ const { onChange, name, label, disabled } = props;
+ const t = useT();
+ const { getValues } = useSettings();
+ const customFunc = useCustomProviderFunction();
+ const [value, setValue] = useState<SelectedAudio | undefined>();
+ const [open, setOpen] = useState(false);
+ const [audioType, setAudioType] = useState<'music' | 'original_sound'>(
+ 'music'
+ );
+ const [query, setQuery] = useState('');
+ const [results, setResults] = useState<AudioResult[]>([]);
+ 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: SelectedAudio | undefined) => {
+ setValue(newValue);
+ onChange({
+ target: {
+ value: newValue,
+ name,
+ },
+ });
+ },
+ [onChange, name]
+ );
+
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ const search = setTimeout(async () => {
+ try {
+ const list = await customFunc.get('audioSearch', {
+ q: query,
+ type: audioType,
+ });
+ if (!cancelled) {
+ setResults(Array.isArray(list) ? list : []);
+ }
+ } catch (err) {
+ if (!cancelled) {
+ setResults([]);
+ }
+ } finally {
+ if (!cancelled) {
+ setLoading(false);
+ }
+ }
+ }, 500);
+ return () => {
+ cancelled = true;
+ clearTimeout(search);
+ };
+ }, [query, audioType, open]);
+
+ const togglePreview = useCallback(
+ (audio: AudioResult) => {
+ if (playingId === audio.id) {
+ stopPreview();
+ return;
+ }
+ stopPreview();
+ if (!audio.previewUrl) {
+ return;
+ }
+ const newPlayer = new Audio(audio.previewUrl);
+ newPlayer.onended = () => setPlayingId('');
+ newPlayer.play();
+ player.current = newPlayer;
+ setPlayingId(audio.id);
+ },
+ [playingId, stopPreview]
+ );
+
+ const selectAudio = useCallback(
+ (audio: AudioResult) => {
+ stopPreview();
+ setOpen(false);
+ emit({
+ id: audio.id,
+ title: audio.title,
+ artist: audio.artist,
+ image: audio.image,
+ audio_volume: 100,
+ video_volume: 100,
+ });
+ },
+ [emit, stopPreview]
+ );
+
+ const removeAudio = useCallback(() => {
+ emit(undefined);
+ }, [emit]);
+
+ const changeVolume = useCallback(
+ (key: 'audio_volume' | 'video_volume', volume: number) => {
+ if (!value) {
+ return;
+ }
+ emit({
+ ...value,
+ [key]: volume,
+ });
+ },
+ [emit, value]
+ );
+
+ if (disabled) {
+ return (
+ <div className="flex flex-col gap-[6px]">
+ <div className="text-[14px]">{label}</div>
+ <div>
+ <div
+ data-tooltip-id="tooltip"
+ data-tooltip-content={t(
+ 'instagram_audio_facebook_login_only',
+ 'Only available on Instagram with Facebook Login'
+ )}
+ className="h-[42px] px-[16px] inline-flex items-center cursor-not-allowed opacity-50 bg-newBgColorInner border-newTableBorder border rounded-[8px] text-[14px]"
+ >
+ {t('instagram_add_audio', 'Add audio')}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ 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={removeAudio}
+ >
+ X
+ </div>
+ </div>
+ <div className="flex gap-[18px]">
+ <div className="flex-1 flex flex-col gap-[6px]">
+ <div className="text-[12px]">
+ {t('instagram_audio_volume', 'Audio volume')} (
+ {value.audio_volume ?? 100})
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={value.audio_volume ?? 100}
+ onChange={(e) =>
+ changeVolume('audio_volume', +e.target.value)
+ }
+ />
+ </div>
+ <div className="flex-1 flex flex-col gap-[6px]">
+ <div className="text-[12px]">
+ {t('instagram_video_volume', 'Original video volume')} (
+ {value.video_volume ?? 100})
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={100}
+ value={value.video_volume ?? 100}
+ 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('instagram_add_audio', 'Add audio')}
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-[6px]">
+ <div className="flex gap-[6px]">
+ <Select
+ label=""
+ name="instagram_audio_type"
+ disableForm={true}
+ hideErrors={true}
+ value={audioType}
+ onChange={(e) =>
+ setAudioType(e.target.value as 'music' | 'original_sound')
+ }
+ >
+ <option value="music">{t('instagram_music', 'Music')}</option>
+ <option value="original_sound">
+ {t('instagram_original_sound', 'Original sound')}
+ </option>
+ </Select>
+ <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(
+ 'instagram_search_audio',
+ 'Search audio (empty shows trending)'
+ )}
+ 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>
+ ) : !results.length ? (
+ <div className="p-[12px] text-[14px] opacity-70">
+ {t('instagram_no_audio_found', 'No audio found')}
+ </div>
+ ) : (
+ results.map((audio) => (
+ <div
+ key={audio.id}
+ className="flex items-center gap-[12px] p-[8px] hover:bg-newTableBorder cursor-pointer"
+ onClick={() => selectAudio(audio)}
+ >
+ {!!audio.image && (
+ <img
+ src={audio.image}
+ className="w-[36px] h-[36px] rounded-[8px] object-cover"
+ />
+ )}
+ <div className="flex-1 flex flex-col">
+ <div className="text-[14px]">{audio.title}</div>
+ <div className="text-[12px] opacity-70">
+ {[audio.artist, formatDuration(audio.duration)]
+ .filter((f) => f)
+ .join(' Β· ')}
+ </div>
+ </div>
+ {!!audio.previewUrl && (
+ <div
+ className={clsx(
+ 'px-[12px] text-[12px] opacity-70 hover:opacity-100',
+ playingId === audio.id && 'opacity-100'
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ togglePreview(audio);
+ }}
+ >
+ {playingId === audio.id
+ ? t('stop', 'Stop')
+ : t('play', 'Play')}
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx b/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx
index b16fb3cf9..d7ffc86ae 100644
--- a/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx
+++ b/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx
@@ -10,6 +10,8 @@ import { Checkbox } from '@gitroom/react/form/checkbox';
import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';
import { InstagramDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/instagram.dto';
import { InstagramCollaboratorsTags } from '@gitroom/frontend/components/new-launch/providers/instagram/instagram.tags';
+import { InstagramAudioSelector } from '@gitroom/frontend/components/new-launch/providers/instagram/instagram.audio';
+import { useIntegration } from '@gitroom/frontend/components/launches/helpers/use.integration';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { InstagramPreview } from '@gitroom/frontend/components/new-launch/providers/instagram/instagram.preview';
const postType = [
@@ -38,8 +40,11 @@ const InstagramCollaborators: FC<{
}> = (props) => {
const t = useT();
const { watch, register, formState, control } = useSettings();
+ const { integration } = useIntegration();
const postCurrentType = watch('post_type');
const isTrialReel = watch('is_trial_reel');
+ // The Audio API is only available with Facebook Login, not Instagram Login
+ const supportsAudio = integration?.identifier === 'instagram';
return (
<>
<Select
@@ -65,6 +70,19 @@ const InstagramCollaborators: FC<{
/>
)}
+ {postCurrentType === 'post' && (
+ <div className="mt-[18px]">
+ <InstagramAudioSelector
+ label={t(
+ 'instagram_audio_label',
+ 'Audio (Reels only - single video)'
+ )}
+ disabled={!supportsAudio}
+ {...register('audio')}
+ />
+ </div>
+ )}
+
{postCurrentType === 'post' && (
<div className="mt-[18px] flex flex-col gap-[18px]">
<Checkbox
diff --git a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/instagram.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/instagram.dto.ts
index 20b254466..38e2500d3 100644
--- a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/instagram.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/instagram.dto.ts
@@ -3,7 +3,10 @@ import {
IsArray,
IsDefined,
IsIn,
+ IsNumber,
IsString,
+ Max,
+ Min,
ValidateNested,
IsOptional,
} from 'class-validator';
@@ -13,6 +16,38 @@ export class Collaborators {
@IsString()
label: string;
}
+
+export class InstagramAudio {
+ @IsDefined()
+ @IsString()
+ 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 InstagramDto {
@IsIn(['post', 'story'])
@IsDefined()
@@ -30,4 +65,9 @@ export class InstagramDto {
@IsArray()
@IsOptional()
collaborators: Collaborators[];
+
+ @Type(() => InstagramAudio)
+ @ValidateNested()
+ @IsOptional()
+ audio?: InstagramAudio;
}
diff --git a/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts b/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts
index 675b273aa..d9461d590 100644
--- a/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts
@@ -15,6 +15,7 @@ import {
import { InstagramDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/instagram.dto';
import { Integration } from '@prisma/client';
import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';
+import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';
import { hasExtension } from '@gitroom/helpers/utils/has.extension';
@Rules(
@@ -65,6 +66,20 @@ export class InstagramProvider
return 'Trial Reels must be a video';
}
}
+ if (settings?.audio?.id) {
+ if (settings?.post_type === 'story') {
+ return 'Audio can only be added to Reels, not to Stories';
+ }
+ if ((firstPost?.length ?? 0) > 1) {
+ return 'Audio can only be added to a single video Reel';
+ }
+ const hasVideo = firstPost?.some(
+ (f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1
+ );
+ if (!hasVideo) {
+ return 'Audio can only be added to a video Reel';
+ }
+ }
return true;
}
@@ -633,9 +648,32 @@ export class InstagramProvider
)}`
: ``;
+ // audio_configuration is only supported for Reels (single video, not a story)
+ // and only with Facebook Login (not Instagram Login / graph.instagram.com)
+ const audioConfiguration =
+ firstPost?.settings?.audio?.id &&
+ type === 'graph.facebook.com' &&
+ !isStory &&
+ firstPost?.media?.length === 1 &&
+ hasExtension(m.path, 'mp4')
+ ? `&audio_configuration=${encodeURIComponent(
+ JSON.stringify({
+ audio_id: firstPost.settings.audio.id,
+ ...(typeof firstPost.settings.audio.audio_volume !==
+ 'undefined'
+ ? { audio_volume: +firstPost.settings.audio.audio_volume }
+ : {}),
+ ...(typeof firstPost.settings.audio.video_volume !==
+ 'undefined'
+ ? { video_volume: +firstPost.settings.audio.video_volume }
+ : {}),
+ })
+ )}`
+ : ``;
+
const { id: photoId } = await (
await this.fetch(
- `https://${type}/v20.0/${id}/media?${mediaType}${isCarousel}${collaborators}${trialParams}&access_token=${accessToken}${caption}`,
+ `https://${type}/v20.0/${id}/media?${mediaType}${isCarousel}${collaborators}${trialParams}${audioConfiguration}&access_token=${accessToken}${caption}`,
{
method: 'POST',
}
@@ -925,6 +963,55 @@ export class InstagramProvider
);
}
+ // https://developers.facebook.com/docs/instagram-platform/content-publishing/audio-api/
+ // empty search_query returns trending audio
+ @Tool({
+ description:
+ 'Search audio (music or original sounds) to attach to a Reel via the "audio" setting, an empty query returns trending audio',
+ dataSchema: [
+ {
+ key: 'q',
+ type: 'string',
+ description: 'Search query, leave empty for trending audio',
+ },
+ {
+ key: 'type',
+ type: 'string',
+ description: 'Either "music" or "original_sound", defaults to "music"',
+ },
+ ],
+ })
+ async audioSearch(
+ token: string,
+ data: { q?: string; type?: 'music' | 'original_sound' },
+ internalId?: string
+ ) {
+ const [accessToken, userToken] = token.split('___');
+ const audioType =
+ data?.type === 'original_sound' ? 'original_sound' : 'music';
+
+ const { audio } = await (
+ await this.fetch(
+ `https://graph.facebook.com/v22.0/ig_audio?audio_type=${audioType}&user_id=${internalId}${
+ data?.q ? `&search_query=${encodeURIComponent(data.q)}` : ''
+ }&access_token=${userToken || accessToken}`
+ )
+ ).json();
+
+ return (audio || []).map((audio: any) => ({
+ id: audio.audio_id,
+ title: audio.title || '',
+ artist: audio.display_artist || audio.ig_username || '',
+ image:
+ audio.cover_artwork_thumbnail_uri ||
+ audio.cover_artwork_thumbnail_url ||
+ audio.profile_picture_url ||
+ '',
+ duration: audio.duration_in_ms || 0,
+ previewUrl: audio.download_url || '',
+ }));
+ }
+
async postAnalytics(
integrationId: string,
token: string,