Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Add Spotify (via DistroKid) as a music video publish destination

Claude9003ff89039f
diff --git a/client/src/components/musicVideo/PublishPlatformsPanel.jsx b/client/src/components/musicVideo/PublishPlatformsPanel.jsx
index 9b967d22a4..3cfd8a8717 100644
--- a/client/src/components/musicVideo/PublishPlatformsPanel.jsx
+++ b/client/src/components/musicVideo/PublishPlatformsPanel.jsx
@@ -8,10 +8,10 @@ function historyLine(h) {
return `${h.posts} post${h.posts === 1 ? '' : 's'}${rated.length ? ` · ${rated.join(' · ')}` : ''}`;
}
-function AccountInput({ id, label, initial, onSave, disabled }) {
+function AccountInput({ id, label, initial, placeholder, onSave, disabled }) {
const [value, setValue] = useState(initial || '');
return (
- <input id={id} value={value} disabled={disabled} aria-label={`${label} account`} placeholder="@handle (optional)"
+ <input id={id} value={value} disabled={disabled} aria-label={`${label} account`} placeholder={placeholder || '@handle (optional)'}
onChange={(e) => setValue(e.target.value)}
onBlur={() => { if (value.trim() !== (initial || '')) onSave(value.trim() || null); }}
className="w-full sm:w-40 bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0 disabled:opacity-50" />
@@ -36,7 +36,7 @@ export default function PublishPlatformsPanel({ publishing }) {
{enabledCount ? 'Copy is drafted and posts are offered only for the platforms turned on here.' : 'No platforms yet. Turn on the ones you use; copy and posting cover only those.'}
</p>
<ul className="divide-y divide-port-border">
- {PUBLISH_TARGETS.map(({ target, label }) => {
+ {PUBLISH_TARGETS.map(({ target, label, accountPlaceholder }) => {
const p = platforms[target] || {};
const h = history?.[target];
const latest = h?.notes?.[0];
@@ -46,7 +46,7 @@ export default function PublishPlatformsPanel({ publishing }) {
<input type="checkbox" checked={!!p.enabled} onChange={(e) => setPlatform(target, { enabled: e.target.checked })} />
<span className="font-medium">{label}</span>
</label>
- <AccountInput key={`${target}-${p.account || ''}`} id={`mv-platform-${target}-account`} label={label} initial={p.account}
+ <AccountInput key={`${target}-${p.account || ''}`} id={`mv-platform-${target}-account`} label={label} initial={p.account} placeholder={accountPlaceholder}
disabled={!p.enabled} onSave={(account) => setPlatform(target, { account })} />
<div className="min-w-0 flex-1 text-[11px] text-port-text-muted">
<span>{historyLine(h)}</span>
diff --git a/client/src/components/musicVideo/PublishPostingPanel.jsx b/client/src/components/musicVideo/PublishPostingPanel.jsx
index dde485897c..4be5328b5d 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.jsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';
+import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage.js';
import { ExternalLink, X as XIcon, LogIn, Link as LinkIcon } from 'lucide-react';
// Where the release goes, in posting order: the full video first so every
@@ -13,8 +14,16 @@ export const PUBLISH_TARGETS = [
{ target: 'instagram', label: 'Instagram Reels', note: 'A 9:16 cut (the newest by default), with the AI label' },
{ target: 'reddit', label: 'Reddit', note: 'A native video post to r/aivideo (title and flair, no body)' },
{ target: 'stackerNews', label: 'Stacker News', note: 'A link post to the full video' },
+ {
+ target: 'distrokid', label: 'Spotify (via DistroKid)', accountPlaceholder: 'Artist name',
+ note: 'The song as a single for Spotify and other stores, with a square cover and the AI disclosure. You tick the agreements and press Upload',
+ linkPlaceholder: 'Live on Spotify? Paste the Spotify link',
+ },
];
+// The songwriter's legal name DistroKid asks for, remembered on this device only.
+const SONGWRITER_KEY = 'portos.musicVideo.distrokidSongwriter';
+
const inputCls = 'w-full bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs min-h-[44px] sm:min-h-0';
const summaryRows = (summary) => Object.entries(summary || {})
@@ -37,7 +46,7 @@ function verticalCutChoices(project) {
return cuts;
}
-function TargetOptions({ target, kit, project, options, setOption, flairs, idFor }) {
+function TargetOptions({ target, kit, project, options, setOption, flairs, idFor, account }) {
const field = (key, label, input) => (
<div key={key} className="space-y-0.5 min-w-0">
<label htmlFor={idFor(key)} className="block text-[11px] text-port-text-muted">{label}</label>
@@ -92,6 +101,35 @@ function TargetOptions({ target, kit, project, options, setOption, flairs, idFor
</div>
);
}
+ if (target === 'distrokid') {
+ const check = (key, label, fallback) => (
+ <label key={key} className="flex items-center gap-1.5 text-xs min-h-[44px] sm:min-h-0">
+ <input type="checkbox" checked={options[key] ?? fallback} onChange={(e) => setOption(key, e.target.checked)} /> {label}
+ </label>
+ );
+ const hasLyrics = (project?.lyricCues || []).some((cue) => cue?.text?.trim());
+ return (
+ <div className="space-y-2">
+ <div className="grid sm:grid-cols-2 gap-2">
+ {text('artistName', 'Artist name', account || 'Your artist name')}
+ {field('releaseDate', 'Release date (blank = as soon as possible)',
+ <input id={idFor('releaseDate')} type="date" value={options.releaseDate || ''} onChange={(e) => setOption('releaseDate', e.target.value)} className={inputCls} />)}
+ {text('songwriterFirst', 'Songwriter legal first name', 'First')}
+ {text('songwriterLast', 'Songwriter legal last name', 'Last')}
+ </div>
+ <div className="flex flex-wrap gap-x-4">
+ {check('explicit', 'Explicit lyrics', false)}
+ {check('instrumental', 'Instrumental', !hasLyrics)}
+ </div>
+ <div role="group" aria-label="Parts made with AI" className="flex flex-wrap gap-x-4">
+ <span className="text-[11px] text-port-text-muted self-center">Made with AI:</span>
+ {check('aiMusic', 'Music', true)}
+ {check('aiVocals', 'All of the audio', true)}
+ {check('aiLyrics', 'Lyrics', false)}
+ </div>
+ </div>
+ );
+ }
if (target === 'x') {
return (
<div className="space-y-2">
@@ -134,12 +172,12 @@ function PostFeedback({ idFor, label, post, onSave }) {
}
/** Record a post made outside PortOS, so its reception can be tracked too. */
-function ManualLink({ idFor, label, onSave }) {
+function ManualLink({ idFor, label, placeholder, onSave }) {
const [url, setUrl] = useState('');
const valid = /^https?:\/\/\S+$/.test(url.trim());
return (
<div className="flex flex-wrap items-center gap-2">
- <input id={idFor('manual-url')} aria-label={`Link to a ${label} post made by hand`} value={url} placeholder="Posted by hand? Paste the link"
+ <input id={idFor('manual-url')} aria-label={`Link to a ${label} post made by hand`} value={url} placeholder={placeholder || 'Posted by hand? Paste the link'}
onChange={(e) => setUrl(e.target.value)} className={`${inputCls} flex-1 min-w-0`} />
<button type="button" disabled={!valid} onClick={() => onSave({ url: url.trim() }).then((post) => { if (post) setUrl(''); })}
className="flex items-center gap-1 border border-port-border disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
@@ -150,7 +188,7 @@ function ManualLink({ idFor, label, onSave }) {
}
function TargetRow({ project, kit, entry, publishing }) {
- const { target, label, note } = entry;
+ const { target, label, note, linkPlaceholder } = entry;
const idFor = (key) => `mv-post-${project.id}-${target}-${key}`;
const [options, setOptions] = useState(() => {
// Prefill Suno URL from autonomous run if available
@@ -158,6 +196,11 @@ function TargetRow({ project, kit, entry, publishing }) {
const songId = project.autonomousRun.output.sunoSongIds[0];
return { songUrl: `https://suno.com/song/${encodeURIComponent(songId)}` };
}
+ if (target === 'distrokid') {
+ const saved = safeReadJsonStorage(SONGWRITER_KEY, {}) || {};
+ // A song whose lyrics an LLM wrote in the autonomous run discloses AI lyrics by default.
+ return { songwriterFirst: saved.first || '', songwriterLast: saved.last || '', aiLyrics: !!project?.autonomousRun?.output?.lyrics };
+ }
return {};
});
const setOption = (key, value) => setOptions((prev) => ({ ...prev, [key]: value }));
@@ -182,15 +225,18 @@ function TargetRow({ project, kit, entry, publishing }) {
</a>
)}
</div>
- <button type="button" onClick={() => publishing.prepare(target, clean)} disabled={!!busy}
+ <button type="button" onClick={() => {
+ if (target === 'distrokid' && clean.songwriterFirst && clean.songwriterLast) safeWriteJsonStorage(SONGWRITER_KEY, { first: clean.songwriterFirst, last: clean.songwriterLast });
+ publishing.prepare(target, clean);
+ }} disabled={!!busy}
className="flex items-center gap-1 bg-port-accent/20 text-port-accent disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[44px] sm:min-h-0">
{busy === 'prepare' ? 'Filling…' : (draft ? 'Fill again' : 'Fill draft')}
</button>
</div>
{posted
? <PostFeedback key={posted.url || 'post'} idFor={idFor} label={label} post={posted} onSave={(body) => publishing.recordPost(target, body)} />
- : <ManualLink idFor={idFor} label={label} onSave={(body) => publishing.recordPost(target, body)} />}
- <TargetOptions target={target} kit={kit} project={project} options={options} setOption={setOption} flairs={flairs} idFor={idFor} />
+ : <ManualLink idFor={idFor} label={label} placeholder={linkPlaceholder} onSave={(body) => publishing.recordPost(target, body)} />}
+ <TargetOptions target={target} kit={kit} project={project} options={options} setOption={setOption} flairs={flairs} idFor={idFor} account={account} />
{error && (
<div role="alert" className="text-[11px] text-port-error space-y-0.5">
<div className="flex items-center gap-1">{error.code === 'PUBLISH_LOGIN_REQUIRED' && <LogIn size={11} />}{error.message}</div>
diff --git a/client/src/components/musicVideo/PublishPostingPanel.test.jsx b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
index 35bc234f9e..2573de045a 100644
--- a/client/src/components/musicVideo/PublishPostingPanel.test.jsx
+++ b/client/src/components/musicVideo/PublishPostingPanel.test.jsx
@@ -7,7 +7,7 @@ import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, within, act } from '@testing-library/react';
import PublishPostingPanel, { PUBLISH_TARGETS } from './PublishPostingPanel.jsx';
-const ALL = ['youtube', 'suno', 'x', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews'];
+const ALL = ['youtube', 'suno', 'x', 'shorts', 'tiktok', 'instagram', 'reddit', 'stackerNews', 'distrokid'];
const hook = (over = {}) => ({ drafts: {}, busy: {}, errors: {}, prepare: vi.fn(), submit: vi.fn(), discard: vi.fn(), enabledTargets: ALL, platforms: {}, recordPost: vi.fn(async () => null), ...over });
const project = (kit = {}) => ({ id: 'mv-1', publishKit: { builtAt: '2026-01-01T00:00:00.000Z', thumbnails: ['t1.jpg'], ...kit } });
const row = (label) => screen.getByText(label, { selector: 'div' }).closest('li');
@@ -48,6 +48,23 @@ describe('PublishPostingPanel (#9282)', () => {
expect(publishing.prepare).toHaveBeenCalledWith('shorts', { cutId: 'kit-vertical' });
});
+ it('fills a DistroKid release with the songwriter and AI parts, and remembers the songwriter on this device', () => {
+ const publishing = hook({ platforms: { distrokid: { enabled: true, account: 'Example Artist' } } });
+ const p = { ...project(), autonomousRun: { output: { lyrics: 'la la' } } };
+ const { unmount } = render(<PublishPostingPanel project={p} publishing={publishing} />);
+ const dk = row('Spotify (via DistroKid)');
+ expect(within(dk).getByLabelText('Artist name')).toHaveAttribute('placeholder', 'Example Artist');
+ expect(within(dk).getByLabelText('Instrumental')).toBeChecked(); // no lyric cues
+ fireEvent.change(within(dk).getByLabelText('Songwriter legal first name'), { target: { value: 'Alice' } });
+ fireEvent.change(within(dk).getByLabelText('Songwriter legal last name'), { target: { value: 'Example' } });
+ fireEvent.click(within(dk).getByLabelText('Explicit lyrics'));
+ fireEvent.click(within(dk).getByRole('button', { name: 'Fill draft' }));
+ expect(publishing.prepare).toHaveBeenCalledWith('distrokid', { songwriterFirst: 'Alice', songwriterLast: 'Example', aiLyrics: true, explicit: true });
+ unmount();
+ render(<PublishPostingPanel project={project()} publishing={hook()} />);
+ expect(within(row('Spotify (via DistroKid)')).getByLabelText('Songwriter legal first name')).toHaveValue('Alice');
+ });
+
it('shows no cut picker when there is only one 9:16 cut', () => {
render(<PublishPostingPanel project={project()} publishing={hook()} />);
expect(within(row('TikTok')).queryByLabelText('Vertical cut to post')).toBeNull();
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b3b25369dc..bbeee290a2 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -688,7 +688,7 @@ export const musicVideoPublishThumbnailSchema = z.object({ filename: z.string().
// #9282: posting to a platform through the PortOS Browser. One strict options
// object covers every target; each target's payload builder reads only its own.
-export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'reddit', 'stackerNews', 'suno']);
+export const MUSIC_VIDEO_PUBLISH_TARGETS = Object.freeze(['youtube', 'shorts', 'tiktok', 'instagram', 'x', 'reddit', 'stackerNews', 'suno', 'distrokid']);
export const musicVideoPublishTargetSchema = z.enum(MUSIC_VIDEO_PUBLISH_TARGETS);
const publishUrl = z.string().url().max(500);
// #9287: which platforms the director posts to (opt-in), the account for each,
@@ -713,6 +713,16 @@ export const musicVideoPublishPrepareSchema = z.object({
prompt: kitText(25000),
storyImage: z.string().min(1).max(300),
cutId: z.string().min(1).max(100),
+ // DistroKid (the song as a Spotify single): who it is by and the store flags.
+ artistName: z.string().trim().min(1).max(100),
+ songwriterFirst: z.string().trim().min(1).max(100),
+ songwriterLast: z.string().trim().min(1).max(100),
+ releaseDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
+ explicit: z.boolean(),
+ instrumental: z.boolean(),
+ aiLyrics: z.boolean(),
+ aiMusic: z.boolean(),
+ aiVocals: z.boolean(),
}).partial().strict();
export const musicVideoExcerptNoteSchema = z.object({
diff --git a/server/services/musicVideo/publish/distrokid.js b/server/services/musicVideo/publish/distrokid.js
new file mode 100644
index 0000000000..14ed31e259
--- /dev/null
+++ b/server/services/musicVideo/publish/distrokid.js
@@ -0,0 +1,125 @@
+/**
+ * DistroKid adapter: the song goes to Spotify (and the other stores DistroKid
+ * delivers to) as a single. Spotify has no upload for independent artists, so
+ * a distributor is the only route. prepare() fills DistroKid's upload form
+ * with the song's audio, a square cover, title, artist, songwriter, explicit
+ * and instrumental flags, the AI disclosure, and the release date. It never
+ * ticks the agreement boxes or presses Upload: those attest the director owns
+ * the rights, so they stay with the director.
+ *
+ * DistroKid restyles this form often, so every field is found by its name or
+ * its label text, and a field that is no longer there is reported in the
+ * summary as left for the director rather than failing the whole draft.
+ */
+import { PUBLISH_STEP_TIMEOUT_MS as T, loginRequired, step } from './browser.js';
+
+const label = 'DistroKid';
+const UPLOAD_URL = 'https://distrokid.com/new/';
+
+/** Set a form control's value the way DistroKid's own scripts listen for. */
+async function setValue(page, selector, value) {
+ return page.evaluate(([sel, val]) => {
+ const el = [...document.querySelectorAll(sel)].find((e) => e.type !== 'hidden');
+ if (!el) return false;
+ if (el.tagName === 'SELECT') {
+ const want = String(val).toLowerCase();
+ const opt = [...el.options].find((o) => o.value === String(val) || o.textContent.trim().toLowerCase() === want);
+ if (!opt) return false;
+ el.value = opt.value;
+ } else {
+ el.focus();
+ el.value = val;
+ }
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+ el.dispatchEvent(new Event('change', { bubbles: true }));
+ el.blur?.();
+ return true;
+ }, [selector, value]);
+}
+
+/** Check the first radio/checkbox whose label text matches `pattern` (a RegExp source). */
+async function checkByLabel(page, selector, pattern) {
+ return page.evaluate(([sel, src]) => {
+ const re = new RegExp(src, 'i');
+ const box = [...document.querySelectorAll(sel)].find((b) => re.test((b.closest('label')?.innerText || b.parentElement?.innerText || '').replace(/\s+/g, ' ')));
+ if (!box) return false;
+ if (!box.checked) box.click();
+ return true;
+ }, [selector, pattern]);
+}
+
+/** Answer DistroKid's AI question and tick the parts the director says AI made. */
+async function discloseAi(page, ai) {
+ const any = ai.lyrics || ai.music || ai.vocals;
+ const answered = await page.evaluate((yes) => {
+ const radio = document.querySelector(`input[type=radio][name^="ai_gate_"][value="${yes ? 1 : 0}"]`);
+ if (!radio) return false;
+ radio.scrollIntoView({ block: 'center' });
+ if (!radio.checked) radio.click();
+ return true;
+ }, any);
+ if (!answered || !any) return answered;
+ await page.waitForTimeout(1000);
+ return page.evaluate((want) => {
+ const popup = [...document.querySelectorAll('.swal2-popup')].find((p) => /which parts|ai-generated/i.test(p.innerText || ''));
+ if (!popup) return false;
+ const tick = (re, on) => {
+ const box = [...popup.querySelectorAll('input[type=checkbox]')].find((b) => re.test(b.closest('label')?.innerText || b.parentElement?.innerText || ''));
+ if (box && box.checked !== on) box.click();
+ return !!box;
+ };
+ const found = [
+ tick(/lyrics/i, want.lyrics),
+ tick(/music\s*\(composed/i, want.music),
+ tick(/all of the audio/i, want.vocals),
+ ];
+ const save = [...popup.querySelectorAll('button')].find((b) => /^save$/i.test((b.innerText || '').trim()));
+ save?.click();
+ return found.every(Boolean) && !!save;
+ }, ai);
+}
+
+export const distrokidAdapter = {
+ label,
+ async prepare(page, payload) {
+ await step(label, 'open the upload form', () => page.goto(UPLOAD_URL, { waitUntil: 'domcontentloaded', timeout: T }));
+ await page.waitForTimeout(4000);
+ if (/signin|login/i.test(page.url()) || !(await page.locator('#artistName, [name=bandname]').count())) throw loginRequired(label, UPLOAD_URL);
+
+ const leftForYou = [];
+ const soft = async (what, fn) => { if (!(await fn().catch(() => false))) leftForYou.push(what); };
+
+ // The song count rebuilds the form, so it goes first.
+ await soft('number of songs (1)', () => setValue(page, '#howManySongsOnThisAlbum, select[name=howmanysongs]', '1'));
+ await page.waitForTimeout(1500);
+ await step(label, 'set the artist', async () => {
+ if (!(await setValue(page, '#artistName, [name=bandname]', payload.artist))) throw new Error(`no artist field accepted "${payload.artist}"`);
+ });
+ await step(label, 'upload the cover', () => page.locator('#artwork, input[type=file][name=artwork]').first().setInputFiles(payload.cover.path, { timeout: T }));
+ await step(label, 'upload the audio', () => page.locator('#js-track-upload-1').first().setInputFiles(payload.audio.path, { timeout: T }));
+ await step(label, 'set the song title', async () => {
+ if (!(await setValue(page, 'input[name^="title_"]', payload.title))) throw new Error('no song title field');
+ });
+ await soft('songwriter', async () => (await setValue(page, 'input[name^="songwriter_real_name_first"]', payload.songwriter.first))
+ && setValue(page, 'input[name^="songwriter_real_name_last"]', payload.songwriter.last));
+ await soft(payload.explicit ? 'explicit: yes' : 'explicit: no', async () => {
+ await page.locator(payload.explicit ? '#js-explicit-radio-button-1' : '#js-not-explicit-radio-button-1').first().check({ timeout: 5000 });
+ return true;
+ });
+ await soft(payload.instrumental ? 'instrumental' : 'contains lyrics', () => checkByLabel(page, 'input[type=radio]', payload.instrumental ? 'instrumental|no lyrics' : 'contains lyrics'));
+ if (payload.releaseDate) await soft(`release date ${payload.releaseDate}`, () => setValue(page, '#release-date-dp, input[name=releaseDate]', payload.releaseDate));
+ await soft('AI disclosure', () => discloseAi(page, payload.ai));
+ await page.evaluate(() => document.querySelector('#js-track-upload-1')?.scrollIntoView({ block: 'center' })).catch(() => {});
+
+ const aiParts = [payload.ai.lyrics && 'lyrics', payload.ai.music && 'music', payload.ai.vocals && 'all of the audio'].filter(Boolean);
+ return {
+ artist: payload.artist,
+ title: payload.title,
+ songwriter: `${payload.songwriter.first} ${payload.songwriter.last}`,
+ releaseDate: payload.releaseDate || 'As soon as possible',
+ explicit: payload.explicit ? 'Yes' : 'No',
+ ai: aiParts.length ? aiParts.join(', ') : 'None',
+ leftForYou: [...leftForYou, 'the agreement checkboxes', 'Upload'],
+ };
+ },
+};
diff --git a/server/services/musicVideo/publish/index.js b/server/services/musicVideo/publish/index.js
index b904f129b4..a1c6959e9c 100644
--- a/server/services/musicVideo/publish/index.js
+++ b/server/services/musicVideo/publish/index.js
@@ -22,11 +22,12 @@ import { xAdapter } from './x.js';
import { redditAdapter } from './reddit.js';
import { stackerNewsAdapter } from './stackerNews.js';
import { sunoAdapter } from './suno.js';
+import { distrokidAdapter } from './distrokid.js';
import { musicVideoEvents } from '../events.js';
export const PUBLISH_ADAPTERS = Object.freeze({
youtube: youtubeAdapter, shorts: shortsAdapter, tiktok: tiktokAdapter, instagram: instagramAdapter,
- x: xAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, suno: sunoAdapter,
+ x: xAdapter, reddit: redditAdapter, stackerNews: stackerNewsAdapter, suno: sunoAdapter, distrokid: distrokidAdapter,
});
// The tab stays open past this: the human publishes from it. After the TTL only
// the CDP session is dropped; the tab closes on Discard, Fill again, or by hand.
@@ -96,21 +97,44 @@ function resolveFiles(value) {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveFiles(v)]));
}
-/** Cut the frame a platform shows before play: TikTok's cover (9:16 frame) and Suno's (square). */
+// Square cover sizes: Suno shows 1500px; stores ask distributors for 3000px.
+const SQUARE_COVER_PX = { suno: 1500, distrokid: 3000 };
+
+/** Cut the frame a platform shows before play: TikTok's cover (9:16 frame), Suno's and DistroKid's (square). */
async function withCovers(target, payload, deps) {
- if (target !== 'tiktok' && target !== 'suno') return payload;
+ if (target !== 'tiktok' && !SQUARE_COVER_PX[target]) return payload;
const source = target === 'tiktok' ? payload.video?.path : payload.cover?.path;
if (!source) return payload;
const { findFfmpeg, runFfmpegProcess } = await import('../../../lib/ffmpeg.js');
+ // A store rejects a non-square cover, so DistroKid gets no draft rather than the 16:9 frame.
+ const uncut = () => {
+ if (target === 'distrokid') throw new ServerError('Could not cut the square cover art: ffmpeg is unavailable or failed', { status: 422, code: 'PUBLISH_ASSET_MISSING' });
+ return payload;
+ };
const ffmpeg = await (deps.findFfmpeg || findFfmpeg)();
- if (!ffmpeg) return payload;
+ if (!ffmpeg) return uncut();
await ensureDir(PATHS.videoThumbnails);
const out = join(PATHS.videoThumbnails, `publish-cover-${target}-${Date.now()}.jpg`);
const args = target === 'tiktok'
? ['-hide_banner', '-loglevel', 'error', '-ss', String(payload.coverAtSec || 0), '-i', source, '-frames:v', '1', '-q:v', '2', '-y', out]
- : ['-hide_banner', '-loglevel', 'error', '-i', source, '-vf', "crop='min(iw,ih)':'min(iw,ih)',scale=1500:1500", '-frames:v', '1', '-q:v', '2', '-y', out];
+ : ['-hide_banner', '-loglevel', 'error', '-i', source, '-vf', `crop='min(iw,ih)':'min(iw,ih)',scale=${SQUARE_COVER_PX[target]}:${SQUARE_COVER_PX[target]}:flags=lanczos`, '-frames:v', '1', '-q:v', '2', '-y', out];
const result = await (deps.runFfmpegProcess || runFfmpegProcess)({ bin: ffmpeg, args });
- return result.ok ? { ...payload, cover: { dir: 'videoThumbnails', name: out.split(/[\\/]/).pop(), path: out } } : payload;
+ return result.ok ? { ...payload, cover: { dir: 'videoThumbnails', name: out.split(/[\\/]/).pop(), path: out } } : uncut();
+}
+
+/** DistroKid's options default the artist to the account named under Where you post. */
+function withPlatformDefaults(target, options, platforms) {
+ if (target !== 'distrokid' || options?.artistName) return options;
+ return { ...options, artistName: platforms?.distrokid?.account || '' };
+}
+
+/** The release audio a distributor uploads: the project's own source song. */
+async function withAudio(target, payload, project, deps) {
+ if (target !== 'distrokid') return payload;
+ const resolveAudio = deps.resolveAudio || (await import('../projectAudio.js')).resolveProjectAudioPath;
+ const path = await resolveAudio(project);
+ if (!existsSync(path)) throw new ServerError('The song file is missing on disk: set the project audio again', { status: 422, code: 'PUBLISH_ASSET_MISSING' });
+ return { ...payload, audio: { path } };
}
/**
@@ -124,7 +148,8 @@ export async function preparePublishDraft(projectId, target, options = {}, deps
assertPlatformEnabled(platforms, target);
const project = await getProject(projectId);
if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
- let payload = resolveFiles(buildPublishPayload(target, project, options));
+ let payload = resolveFiles(buildPublishPayload(target, project, withPlatformDefaults(target, options, platforms)));
+ payload = await withAudio(target, payload, project, deps);
payload = await withCovers(target, payload, deps);
for (const draft of [...drafts.values()]) if (draft.projectId === projectId && draft.target === target) await closeDraft(draft, deps);
return serialize(async () => {
diff --git a/server/services/musicVideo/publish/index.test.js b/server/services/musicVideo/publish/index.test.js
index 4436f0a961..c5d5406928 100644
--- a/server/services/musicVideo/publish/index.test.js
+++ b/server/services/musicVideo/publish/index.test.js
@@ -185,4 +185,30 @@ describe('publish drafts (#9282)', () => {
await preparePublishDraft(id, 'youtube', {}, { connect, adapters, platforms });
expect(adapters.youtube.prepare.mock.calls[0][1].video.path).toBe(join(PATHS.videos, 'master.mp4'));
});
+
+ it('sends the song to DistroKid with its audio, a square store cover, and the account as the artist', async () => {
+ const id = await readyProject();
+ await projects.mutateProjectRecord(id, (current) => ({ project: { ...current, uploadedAudioFilename: 'song.wav', publishKit: { ...current.publishKit, thumbnail: 'thumb.jpg' } } }));
+ await mkdir(PATHS.videoThumbnails, { recursive: true });
+ await writeFile(join(PATHS.videoThumbnails, 'thumb.jpg'), 'x');
+ const audio = join(PATHS.videoThumbnails, 'thumb.jpg'); // any file on disk stands in for the song
+ const dk = { distrokid: { enabled: true, account: 'Example Artist' } };
+ const { connect } = fakeBrowser();
+ const adapters = { distrokid: adapter({ label: 'DistroKid' }) };
+ const options = { songwriterFirst: 'Alice', songwriterLast: 'Example' };
+ const resolveAudio = vi.fn(async () => audio);
+
+ // Without ffmpeg the 16:9 frame would be uploaded as the cover; the store rejects it, so no tab opens.
+ await expect(preparePublishDraft(id, 'distrokid', options, { connect, adapters, platforms: dk, resolveAudio, findFfmpeg: async () => null }))
+ .rejects.toMatchObject({ status: 422, code: 'PUBLISH_ASSET_MISSING' });
+ expect(connect).not.toHaveBeenCalled();
+
+ const runFfmpegProcess = vi.fn(async () => ({ ok: true }));
+ await preparePublishDraft(id, 'distrokid', options, { connect, adapters, platforms: dk, resolveAudio, findFfmpeg: async () => 'ffmpeg', runFfmpegProcess });
+ const payload = adapters.distrokid.prepare.mock.calls[0][1];
+ expect(payload).toMatchObject({ title: 'Release', artist: 'Example Artist', songwriter: { first: 'Alice', last: 'Example' }, audio: { path: audio }, instrumental: true });
+ expect(payload.cover.name).toMatch(/^publish-cover-distrokid-/);
+ expect(runFfmpegProcess.mock.calls[0][0].args.join(' ')).toContain('scale=3000:3000');
+ expect(resolveAudio.mock.calls[0][0]).toMatchObject({ id, uploadedAudioFilename: 'song.wav' });
+ });
});
diff --git a/server/services/musicVideo/publish/payloads.js b/server/services/musicVideo/publish/payloads.js
index e1da7ac71b..4d14681126 100644
--- a/server/services/musicVideo/publish/payloads.js
+++ b/server/services/musicVideo/publish/payloads.js
@@ -164,6 +164,27 @@ const BUILDERS = {
const caption = [lead, video ? `Music video: ${video}` : ''].filter(Boolean).join(' ').slice(0, 500);
return { songUrl: song, caption, cover: kit.thumbnail ? { dir: 'videoThumbnails', name: kit.thumbnail } : null, pin: options.pin !== false };
},
+ // The song as a single for Spotify and the other stores. The service adds the
+ // project's source audio; the cover is cut square from the kit's thumbnail.
+ distrokid: (project, kit, options = {}) => {
+ const title = text(project?.name);
+ if (!title) throw missing('Name the project first: it is the song title on Spotify');
+ const artist = text(options.artistName);
+ if (!artist) throw missing('Give the artist name the song is released under (or set it as the DistroKid account under Where you post)');
+ const songwriter = { first: text(options.songwriterFirst), last: text(options.songwriterLast) };
+ if (!songwriter.first || !songwriter.last) throw missing("DistroKid needs the songwriter's real first and last name");
+ if (!kit.thumbnail) throw missing('Pick a thumbnail in the publishing kit first: it becomes the cover art');
+ const releaseDate = text(options.releaseDate);
+ if (releaseDate && !/^\d{4}-\d{2}-\d{2}$/.test(releaseDate)) throw missing('Give the release date as YYYY-MM-DD');
+ const hasLyrics = (project?.lyricCues || []).some((cue) => text(cue?.text));
+ return {
+ title, artist, songwriter, releaseDate: releaseDate || null,
+ explicit: options.explicit === true,
+ instrumental: typeof options.instrumental === 'boolean' ? options.instrumental : !hasLyrics,
+ ai: { lyrics: options.aiLyrics === true, music: options.aiMusic !== false, vocals: options.aiVocals !== false },
+ cover: { dir: 'videoThumbnails', name: kit.thumbnail },
+ };
+ },
};
/** The payload one platform posts, or a 422 naming the first missing piece. */
diff --git a/server/services/musicVideo/publish/payloads.test.js b/server/services/musicVideo/publish/payloads.test.js
index 741182794c..1440b8dafa 100644
--- a/server/services/musicVideo/publish/payloads.test.js
+++ b/server/services/musicVideo/publish/payloads.test.js
@@ -123,4 +123,18 @@ describe('buildPublishPayload (#9282)', () => {
it('rejects an unknown target', () => {
expect(() => buildPublishPayload('myspace', project())).toThrow(expect.objectContaining({ status: 400 }));
});
+
+ it('names what DistroKid still needs, and defaults the store flags from the song', () => {
+ const song = (over = {}) => ({ ...project(), name: 'Song', lyricCues: [{ text: 'a line', startSec: 0, endSec: 1 }], ...over });
+ const who = { artistName: 'Example Artist', songwriterFirst: 'Alice', songwriterLast: 'Example' };
+ expect(() => buildPublishPayload('distrokid', song(), { ...who, artistName: '' })).toThrow(/artist name/);
+ expect(() => buildPublishPayload('distrokid', song(), { ...who, songwriterLast: '' })).toThrow(/songwriter/);
+ expect(() => buildPublishPayload('distrokid', { ...song(), publishKit: kit({ thumbnail: null }) }, who)).toThrow(/cover art/);
+ expect(buildPublishPayload('distrokid', song(), who)).toMatchObject({
+ title: 'Song', artist: 'Example Artist', explicit: false, instrumental: false, releaseDate: null,
+ ai: { lyrics: false, music: true, vocals: true }, cover: { name: 'thumb-1.jpg' },
+ });
+ expect(buildPublishPayload('distrokid', song({ lyricCues: [] }), { ...who, aiLyrics: true, releaseDate: '2026-11-06' }))
+ .toMatchObject({ instrumental: true, releaseDate: '2026-11-06', ai: { lyrics: true } });
+ });
});