Skip to content

A motion design studio on your own machine: Claude makes the video step by step, you approve every stage. Bring your own Claude Code or API key.

Publishing: pick Upload-Post or your own Postiz in setup

Gerrod Noordsy8c86e83fa09c
diff --git a/README.md b/README.md
index da7467d..37ec701 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,8 @@ Mortiflix runs on your own accounts: there's nothing to sign up for. `mortiflix
```
Anthropic API key only for the anthropic-api backend (Claude Code uses your own login)
ElevenLabs API key only for ElevenLabs narration, sound effects and music
-Upload-Post API key only for `mortiflix publish` (optional; sessions never get it)
+Upload-Post API key only for `mortiflix publish` through Upload-Post (optional; sessions never get it)
+Postiz API key only for `mortiflix publish` through your own Postiz (optional; sessions never get it)
Other keys anything a pipeline's tools read from the environment, e.g. GEMINI_API_KEY
```
@@ -197,8 +198,17 @@ Everything goes into the studio folder, never system-wide. Full details: [docs/S
## Publishing (optional)
-Once you approve a final, the video is yours to download. If you'd rather post it straight from the studio, connect
-your accounts on [Upload-Post](https://upload-post.com), add its key with `mortiflix keys`, and:
+Once you approve a final, the video is yours to download. If you'd rather post it straight from the studio, pick a
+service in setup (`mortiflix setup publish`, or Settings › Setup), add its key with `mortiflix keys`:
+
+- **[Upload-Post](https://upload-post.com)**: hosted, with paid plans. Connect your accounts there, under a profile.
+- **[Postiz](https://postiz.com)**: free and open source (AGPL-3.0, like Mortiflix), on your own server or this
+ computer ([Docker Compose](https://docs.postiz.com/self-host/installation/docker-compose)). Connect your accounts in
+ it. You register a developer app with each platform yourself, and TikTok keeps posts private until it has reviewed
+ yours. Mortiflix talks to it over its API (`http://localhost:4007/api` for the official Docker image, or
+ `https://api.postiz.com` for Postiz Cloud); none of its code is bundled.
+
+Then:
```sh
mortiflix publish <project> # where the brief said (TikTok / Reels / Shorts), asks first
@@ -209,8 +219,12 @@ mortiflix publish <project> --status # per platform, wi
Only you publish: it's a command you run, never something a session can reach (`mfx` has no way to it), and only a
delivered project's approved final goes out. It shows what goes where and asks before sending (`--yes` skips the
-question in scripts). Running it again never posts the same video twice. `--profile` is the Upload-Post profile your
-accounts are connected under; it's remembered after the first time.
+question in scripts). Running it again never posts the same video twice (`--again` does, on purpose). With Postiz,
+the plan names each connected account it goes to. `--profile` is the Upload-Post profile your accounts are connected
+under; it's remembered after the first time.
+
+Publishing was started by [@mutonby](https://github.com/mutonby) ([#3](https://github.com/GTKottman/mortiflix-oss/pull/3)),
+who built the Upload-Post side; Postiz came after, as the free choice.
## Make your own pipeline
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 56dd4d4..f827f04 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -132,10 +132,15 @@ work makes sound. `verifyKey` proves a key with a free, read-only call (`GET /v1
project that lacks a key for its next steps pauses with `NEEDS_YOU` instead of starting a session) all ask it. Other
keys for sessions go to `session.env` through `setSessionKey`; only their names are ever shown.
-The Upload-Post key is the studio's, not a session's: `publish.mjs` reads it (`keyValue`) when you run
-`mortiflix publish`, which takes a delivered project's approved video, shows the plan, asks, and posts it with an
-idempotency key (the same video to the same place and time is one post). It records the post in `project.json`
-(`published`) and the log (`PUBLISHED`).
+The publishing keys (Upload-Post, Postiz) are the studio's, not a session's: `publish.mjs` reads the chosen service's
+key (`keyValue`) when you run `mortiflix publish`. `config.json` › `publish` holds the choice (`service`: `uploadpost`,
+`postiz` or `none`, the Upload-Post `profile`, the Postiz `url`). `publishPlan` takes a delivered project's approved
+video and checks everything; for Postiz, `postizChannels` looks up the connected channels so the plan names them. The
+CLI shows the plan, asks, and `publish` sends it: Upload-Post as one form with an `Idempotency-Key`; Postiz as an upload
+then one `POST /public/v1/posts` with a post per channel (scheduled times converted to UTC). Each post carries a key
+(video, service, platforms, time); the studio refuses one it already sent unless `--again`. It records the post in
+`project.json` (`published`) and the log (`PUBLISHED`); `publishStatus` reads it back per platform. Started by @mutonby
+(PR #3, Upload-Post).
## Narration (`src/voice/`)
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 1713049..ef500ea 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -69,6 +69,9 @@ key is checked with a free, read-only API call before it's saved.
Sessions don't get it.
- The ElevenLabs key is stored in `secrets.json` too, and given to a session only while ElevenLabs is the narration
engine.
+- The publishing keys (Upload-Post, Postiz) are stored in `secrets.json` too and never given to a session. Only
+ `mortiflix publish`, run by you, uses one, and sends it only to the service you picked (for Postiz, the address you
+ gave in setup).
- Other keys go to `session.env` (mode 600) and are given to every session's environment. The UI shows their names,
never their values. Only add keys that sessions need, and prefer keys with spending limits.
- The runner checks a project's keys before each session: if one is missing, the project pauses and tells you which,
diff --git a/plugin/skills/mortiflix/SKILL.md b/plugin/skills/mortiflix/SKILL.md
index ce22139..e0f5ec5 100644
--- a/plugin/skills/mortiflix/SKILL.md
+++ b/plugin/skills/mortiflix/SKILL.md
@@ -59,7 +59,7 @@ Change it with `mortiflix config backend <name>`.
## 2. Setup (first run, or `/mortiflix setup`)
Run `mortiflix setup status --json`. Take the parts in order (`parts[]`: claude, transitions, narration, music,
-assets, 3d). For each one, say in a sentence or two why it exists and what it needs (`parts[].why`, `parts[].needs`).
+assets, publish, 3d). For each one, say in a sentence or two why it exists and what it needs (`parts[].why`, `parts[].needs`).
Say what's already there (`tools`), then ask. Use AskUserQuestion for choices. Every part can be skipped.
- **Transitions**: needed by explainer and social-short. `mortiflix setup install transitions`.
@@ -73,6 +73,9 @@ Say what's already there (`tools`), then ask. Use AskUserQuestion for choices. E
`mortiflix setup install strudel chrome`. Chrome reuses theirs when they have one.
- **Assets**: only if they use a stock site. `mortiflix setup assets <url> …`, then
`mortiflix setup install browser-harness`. They sign in to the site in their own Chrome.
+- **Publishing**: optional. `mortiflix setup publish uploadpost [--profile <name>]` (hosted, paid plans),
+ `mortiflix setup publish postiz [--url <their Postiz API address>]` (free, open source, they run it with Docker), or
+ `mortiflix setup publish none`. The key is theirs to type: `mortiflix keys set uploadpost` or `mortiflix keys set postiz`.
- **3D**: only if they want it. `mortiflix setup install blender blender-addons`.
Before each install, say what it is, where it goes and how big it is (`tool_info[id]`). Installs can take minutes, so
@@ -162,5 +165,7 @@ each one: `mortiflix checks approve <id>` or `reject <id>`.
## 7. Delivered
-`mortiflix status <id> --json` → `deliverables[].path`. Open the final for them, and say where it is. If they change
+`mortiflix status <id> --json` → `deliverables[].path`. Open the final for them, and say where it is. If publishing is
+set up and they want it posted, they run `mortiflix publish <id>` in their own terminal (it shows the plan and asks).
+Never run `publish` yourself: posting is theirs to do. If they change
their mind about an approved step later: `mortiflix reopen <id> <step> "what to change"`, then run again.
diff --git a/src/cli.mjs b/src/cli.mjs
index bf15ac6..17016e3 100644
--- a/src/cli.mjs
+++ b/src/cli.mjs
@@ -48,8 +48,9 @@ export const HELP = `${C.b('mortiflix')}: a motion design studio on your machine
${C.b('Publishing')}
mortiflix publish <project> [--to tiktok,instagram,youtube] [--profile <name>] [--title "…"] [--description "…"]
- [--at 2026-10-20T18:00 [--timezone Europe/Madrid]] [--yes]
- post a delivered video through Upload-Post (asks first)
+ [--at 2026-10-20T18:00 [--timezone Europe/Madrid]] [--yes] [--again]
+ post a delivered video through Upload-Post or your own
+ Postiz, whichever setup picked (asks first)
mortiflix publish <project> --status how it went, per platform, with the links
${C.b('The web studio')}
@@ -76,8 +77,8 @@ export const HELP = `${C.b('mortiflix')}: a motion design studio on your machine
${C.b('Settings')}
mortiflix config [key [value]] show or change settings
- mortiflix keys set <anthropic|elevenlabs|uploadpost|NAME> set one key (typed hidden, or piped on stdin)
- mortiflix keys remove <anthropic|elevenlabs|uploadpost|NAME>
+ mortiflix keys set <anthropic|elevenlabs|uploadpost|postiz|NAME> set one key (typed hidden, or piped on stdin)
+ mortiflix keys remove <anthropic|elevenlabs|uploadpost|postiz|NAME>
mortiflix checks [approve|reject <id>] the error checklist sessions proposed
--studio <dir> works with every command. --json prints what pipelines, list, status, review, keys and
@@ -86,7 +87,8 @@ export const HELP = `${C.b('mortiflix')}: a motion design studio on your machine
${C.b('Without a terminal')} (scripts, Claude Code)
mortiflix setup install <${setup.TOOLS.join('|')}>
mortiflix setup music <strudel|none> [--midi|--no-midi]
- mortiflix setup assets <url>… | --clear`;
+ mortiflix setup assets <url>… | --clear
+ mortiflix setup publish <uploadpost|postiz|none> [--url <your Postiz>] [--profile <Upload-Post profile>]`;
const LISTS = ['set', 'file', 'note', 'answer'];
@@ -406,18 +408,22 @@ async function publishCmd(root, given, a) {
const opt = (k) => (typeof a[k] === 'string' ? a[k] : undefined);
if (a.status) {
const st = await pub.publishStatus(root, id);
- console.log(`${C.b(st.status)}${st.message ? C.dim(` · ${st.message}`) : ''} ${C.dim(st.job_id ? `job ${st.job_id}` : `request ${st.request_id}`)}`);
+ console.log(`${C.b(st.status)}${st.message ? C.dim(` · ${st.message}`) : ''} ${C.dim(st.ref)}`);
for (const r of st.results) {
const icon = { completed: C.green('✔'), failed: C.red('✖') }[r.state] || C.acc('●');
- console.log(` ${icon} ${r.platform.padEnd(10)} ${r.url || C.dim(r.message || r.state)}`);
+ console.log(` ${icon} ${String(r.platform || '?').padEnd(10)} ${r.url || C.dim(r.message || r.state)}`);
}
if (!st.results.length) console.log(C.dim(st.scheduled_for ? ` Scheduled for ${st.scheduled_for}.` : ' Nothing back from the platforms yet.'));
return;
}
- const plan = pub.publishPlan(root, id, { to: opt('to'), profile: opt('profile'), title: opt('title'), description: opt('description'), at: opt('at'), timezone: opt('timezone') });
+ let plan = pub.publishPlan(root, id, { to: opt('to'), profile: opt('profile'), title: opt('title'), description: opt('description'), at: opt('at'), timezone: opt('timezone'), again: Boolean(a.again) });
+ // Postiz posts to the channels connected in it: look them up first, so the plan names every account.
+ if (plan.service === 'postiz') plan = await pub.postizChannels(root, plan);
console.log(`\n${C.b(plan.project)} ${C.dim(`${(plan.size / 1024 ** 2).toFixed(1)} MB`)}`);
+ console.log(` Via ${pub.SERVICES[plan.service].name}${plan.service === 'postiz' ? C.dim(` at ${pub.publishConfig(loadConfig(root)).postiz.url}`) : ''}`);
console.log(` To ${plan.platforms.join(', ')}${plan.from_brief ? C.dim(' (from the brief; --to changes it)') : ''}`);
- console.log(` Profile ${plan.profile}`);
+ if (plan.channels) for (const c of plan.channels) console.log(` ${C.dim(`${c.platform}:`)} ${c.name}`);
+ if (plan.profile) console.log(` Profile ${plan.profile}`);
console.log(` Title ${plan.title}`);
if (plan.description) console.log(` Text ${plan.description.slice(0, 200)}`);
console.log(` When ${plan.at ? `${plan.at} ${plan.timezone || 'UTC'}` : 'now'}\n`);
@@ -425,7 +431,8 @@ async function publishCmd(root, given, a) {
if (!a.yes && !(await confirm(`Post it${plan.at ? ' at that time' : ' now'}?`))) return console.log('Nothing sent.');
const sent = await pub.publish(root, plan);
console.log(`${C.green('✔')} ${plan.at ? 'Scheduled' : 'Sent'}. ${C.b(`mortiflix publish ${id} --status`)} shows how it went.`);
- console.log(C.dim(` ${sent.job_id ? `job ${sent.job_id}` : `request ${sent.request_id}`} · also at https://app.upload-post.com`));
+ if (plan.service === 'postiz') console.log(C.dim(` ${sent.posts.length} post${sent.posts.length === 1 ? '' : 's'} · also in your Postiz calendar`));
+ else console.log(C.dim(` ${sent.job_id ? `job ${sent.job_id}` : `request ${sent.request_id}`} · also at https://app.upload-post.com`));
}
// Review in the terminal: what was sent, then answers, notes and a decision.
@@ -846,6 +853,31 @@ async function setupPart(root, id, st) {
console.log(C.dim(' Sign in to them in Chrome. The first time, Chrome may ask to allow remote debugging: chrome://inspect/#remote-debugging'));
return;
}
+ if (id === 'publish') {
+ const cur = pub.publishConfig(loadConfig(root));
+ console.log(` Now: ${C.b(cur.service === 'none' ? 'not set up' : cur.service === 'postiz' ? `your own Postiz at ${cur.postiz.url}` : `Upload-Post${cur.profile ? ` (profile ${cur.profile})` : ''}`)}`);
+ console.log(' 1. Upload-Post: a hosted service with paid plans. You connect your accounts on upload-post.com. Needs its API key.');
+ console.log(' 2. Postiz: free and open source (AGPL-3.0). You run it yourself (Docker) and connect your accounts in it.');
+ console.log(C.dim(' Install: https://docs.postiz.com/self-host/installation/docker-compose. Each platform needs a developer app you register;'));
+ console.log(C.dim(' TikTok keeps posts private until it has reviewed yours.'));
+ console.log(' 3. Don\'t publish from the studio: you download finals and post them yourself.');
+ const choice = (await prompterOnce(` Which? ${C.dim(`[Enter keeps ${cur.service}]`)} `)).trim();
+ if (choice === '3') { pub.savePublish(root, { service: 'none' }); return console.log(' Publishing off.'); }
+ if (choice === '1' || (!choice && cur.service === 'uploadpost')) {
+ pub.savePublish(root, { service: 'uploadpost' });
+ await askKey(root, 'uploadpost');
+ const profile = (await prompterOnce(` Upload-Post profile your accounts are connected under${cur.profile ? C.dim(` (Enter keeps ${cur.profile})`) : ''}: `)).trim();
+ if (profile) pub.savePublish(root, { profile });
+ return console.log(` ${C.green('✔')} Publishing through Upload-Post. Post a delivered video with ${C.b('mortiflix publish <project>')}.`);
+ }
+ if (choice === '2' || (!choice && cur.service === 'postiz')) {
+ const url = (await prompterOnce(` Your Postiz API address ${C.dim(`(Enter keeps ${cur.postiz.url}; Postiz Cloud is https://api.postiz.com)`)}: `)).trim();
+ pub.savePublish(root, { service: 'postiz', url: url || undefined });
+ await askKey(root, 'postiz');
+ return console.log(` ${C.green('✔')} Publishing through your Postiz. Post a delivered video with ${C.b('mortiflix publish <project>')}.`);
+ }
+ return undefined;
+ }
if (id === '3d') {
if (!(await confirm(' Set up 3D (Blender and the toolkits)?', st.blender.ok))) return console.log(C.dim(' Skipped: 2D only.'));
if (!st.blender.ok) { if (!(await offerInstall(root, 'blender'))) return; }
@@ -871,6 +903,9 @@ async function showSetup(root) {
row(st.transitions.ok, 'Transitions', st.transitions.ok ? `remotion-transitions: ${st.transitions.detail}` : 'library not installed (mortiflix setup transitions)');
row(st.music.engine === 'none' ? null : st.strudel.ok && st.chrome.ok, 'Music', st.music.engine === 'none' ? 'none' : `Strudel: ${st.strudel.detail}; Chrome: ${st.chrome.ok ? 'found' : 'missing'}${st.music.midi ? '; MIDI pack on' : ''}`);
row(st.assets.sites.length ? st['browser-harness'].ok : null, 'Assets', st.assets.sites.length ? `${st.assets.sites.map((x) => x.url).join(', ')} (browser-harness ${st['browser-harness'].ok ? st['browser-harness'].detail : 'missing'})` : 'no sites: sessions make every visual themselves');
+ const pubCfg = st.publish;
+ row(pubCfg.service === 'none' ? null : Boolean(pubCfg.key), 'Publishing', pubCfg.service === 'none' ? 'off: you post finals yourself'
+ : `${pub.SERVICES[pubCfg.service].name}${pubCfg.service === 'postiz' ? ` at ${pubCfg.postiz.url}` : pubCfg.profile ? `, profile ${pubCfg.profile}` : ''}${pubCfg.key ? '' : ', key missing'}`);
row(st.blender.ok ? st['blender-addons'].ok : null, '3D', st.blender.ok ? `${st.blender.detail}; ${st['blender-addons'].detail}` : 'not set up');
}
@@ -919,6 +954,10 @@ async function setupCmd(root, [part, ...args], a) {
const now = setup.assetsConfig(loadConfig(root)).sites;
return console.log(now.length ? `${C.green('✔')} Asset sites: ${now.map((x) => x.url).join(', ')}` : 'No asset sites.');
}
+ if (part === 'publish' && args.length) {
+ const c = pub.savePublish(root, { service: args[0], url: typeof a.url === 'string' ? a.url : undefined, profile: typeof a.profile === 'string' ? a.profile : undefined });
+ return console.log(c.service === 'none' ? 'Publishing off.' : `${C.green('✔')} Publishing through ${pub.SERVICES[c.service].name}${c.service === 'postiz' ? ` at ${c.postiz.url}` : ''}. Its key: mortiflix keys set ${c.service}`);
+ }
if (part === 'status' && a.json) return json(await setupView(root));
if (part === 'status' || !process.stdin.isTTY) return showSetup(root);
if (part && !PART_IDS.includes(part)) throw new Error(`mortiflix setup [${PART_IDS.join('|')}|status]`);
diff --git a/src/keys.mjs b/src/keys.mjs
index 5b42230..cceb0d7 100644
--- a/src/keys.mjs
+++ b/src/keys.mjs
@@ -28,7 +28,14 @@ export const KEYS = {
secret: 'upload_post_api_key',
env: 'UPLOAD_POST_API_KEY',
get: 'app.upload-post.com › API Keys',
- for: 'publishing a delivered video to TikTok, Instagram, YouTube and others with `mortiflix publish`. Optional: nothing is ever posted on its own.',
+ for: 'publishing a delivered video to TikTok, Instagram, YouTube and others with `mortiflix publish`, when Upload-Post is your publishing service. Optional: nothing is ever posted on its own.',
+ },
+ postiz: {
+ name: 'Postiz API key',
+ secret: 'postiz_api_key',
+ env: 'POSTIZ_API_KEY',
+ get: 'your Postiz › Settings › Developers › Public API',
+ for: 'publishing a delivered video with `mortiflix publish`, when your own Postiz is your publishing service. Optional: nothing is ever posted on its own.',
},
};
@@ -110,6 +117,17 @@ export async function verifyKey(root, id, value, { fetch = globalThis.fetch } =
if (res.status === 401 || res.status === 403) return { ok: false, detail: 'Upload-Post refused it (check that you copied the whole key)' };
return { ok: null, detail: `couldn't check it (Upload-Post answered ${res.status})` };
}
+ if (id === 'postiz') {
+ // Your own Postiz, at the address chosen in setup: listing its channels is free and read-only.
+ const base = (loadConfig(root).publish?.postiz?.url || 'http://localhost:4007/api').replace(/\/+$/, '');
+ const res = await fetch(`${base}/public/v1/integrations`, { headers: { Authorization: key } });
+ if (res.ok) {
+ const list = [].concat(await res.json().catch(() => [])).filter((c) => c && !c.disabled);
+ return { ok: true, detail: list.length ? `${list.length} channel${list.length === 1 ? '' : 's'} connected (${[...new Set(list.map((c) => c.identifier))].join(', ')})` : 'Postiz accepted it, but no channels are connected there yet' };
+ }
+ if (res.status === 401 || res.status === 403) return { ok: false, detail: 'your Postiz refused it (check that you copied the whole key)' };
+ return { ok: null, detail: `couldn't check it (your Postiz at ${base} answered ${res.status})` };
+ }
if (id === 'elevenlabs') {
const a = await new ElevenLabs({ key, server: voiceConfig(root).elevenlabs.server, fetch }).account();
const left = Number.isFinite(a.characters_left) ? ` · ${a.characters_left.toLocaleString()} credits left` : '';
diff --git a/src/publish.mjs b/src/publish.mjs
index 9778148..ef3e583 100644
--- a/src/publish.mjs
+++ b/src/publish.mjs
@@ -1,4 +1,7 @@
-// Publishing a delivered video to your social accounts, through Upload-Post (https://upload-post.com).
+// Publishing a delivered video to your social accounts, through the service you picked in setup:
+// uploadpost Upload-Post (https://upload-post.com), hosted, paid plans
+// postiz your own Postiz (https://postiz.com), free and open source (AGPL-3.0), self-hosted
+// Started by @mutonby (Upload-Post, PR #3); Postiz added alongside it.
//
// Only you publish. It's reachable from the CLI, never from `mfx`, so a session can't post anything; and only a
// delivered project's approved video goes out, never a version still in review. Nothing here runs on its own.
@@ -12,13 +15,57 @@ import { keyValue } from './keys.mjs';
// UPLOAD_POST_API moves it (e.g. to a staging server); the key is sent there.
export const API = () => process.env.UPLOAD_POST_API || 'https://api.upload-post.com';
-export const PLATFORMS = ['tiktok', 'instagram', 'youtube', 'linkedin', 'x', 'facebook', 'threads', 'pinterest', 'bluesky'];
+// The official Postiz Docker image answers its API here; Postiz Cloud is https://api.postiz.com.
+export const POSTIZ_DEFAULT = 'http://localhost:4007/api';
+
+export const SERVICES = {
+ uploadpost: { name: 'Upload-Post', key: 'uploadpost', platforms: ['tiktok', 'instagram', 'youtube', 'linkedin', 'x', 'facebook', 'threads', 'pinterest', 'bluesky'] },
+ // Pinterest is left out: Postiz needs a board for it, which the studio has no way to know.
+ postiz: { name: 'Postiz', key: 'postiz', platforms: ['tiktok', 'instagram', 'youtube', 'linkedin', 'x', 'facebook', 'threads', 'bluesky', 'mastodon'] },
+};
+
+// The platforms by every name they're shown under, and which Postiz channel types post to each.
+const POSTIZ_TYPES = { instagram: ['instagram', 'instagram-standalone'], linkedin: ['linkedin', 'linkedin-page'] };
// Where the brief said it will run (the social-short intake), as the accounts to post to.
const FROM_BRIEF = { 'TikTok / Reels / Shorts': ['tiktok', 'instagram', 'youtube'], LinkedIn: ['linkedin'], X: ['x'] };
+// ---- the choice (setup) ----
+
+export function publishConfig(config) {
+ const p = config.publish || {};
+ return { service: SERVICES[p.service] ? p.service : 'none', profile: p.profile || null, postiz: { url: p.postiz?.url || POSTIZ_DEFAULT } };
+}
+
+// The service (uploadpost, postiz or none), the Upload-Post profile, and where your Postiz is.
+export function savePublish(root, { service, profile, url } = {}) {
+ const cur = publishConfig(loadConfig(root));
+ if (service !== undefined && service !== 'none' && !SERVICES[service]) throw new UserError('publishing: uploadpost, postiz or none');
+ let postizUrl = cur.postiz.url;
+ if (url !== undefined && url !== null && String(url).trim()) {
+ let u;
+ try { u = new URL(String(url).trim()); } catch { throw new UserError(`"${url}" isn't a web address (e.g. ${POSTIZ_DEFAULT})`); }
+ if (!/^https?:$/.test(u.protocol)) throw new UserError('your Postiz address starts with http:// or https://');
+ if (u.username || u.password) throw new UserError('no login in the address: Postiz takes its API key instead');
+ postizUrl = u.href.replace(/\/+$/, '');
+ }
+ saveConfig(root, { publish: {
+ service: service ?? cur.service,
+ profile: profile !== undefined ? (String(profile || '').trim() || null) : cur.profile,
+ postiz: { url: postizUrl },
+ } });
+ return publishConfig(loadConfig(root));
+}
+
+const postizBase = (root) => `${publishConfig(loadConfig(root)).postiz.url}/public/v1`;
+
+// ---- the plan ----
+
// Everything a post needs, checked before anything is sent: what you see is what goes out.
-export function publishPlan(root, id, { to, profile, title, description, at, timezone } = {}) {
+export function publishPlan(root, id, { to, profile, title, description, at, timezone, again } = {}) {
+ const service = publishConfig(loadConfig(root)).service;
+ if (service === 'none') throw new UserError('publishing isn\'t set up: pick Upload-Post or your own Postiz with `mortiflix setup publish` (or in Settings › Setup)');
+ const svc = SERVICES[service];
const p = loadProject(root, id);
if (p.state !== 'delivered') throw new UserError(`"${p.title}" isn't delivered yet (${p.state}): only an approved final is published`);
const video = p.deliverables.find((f) => f.kind === 'video');
@@ -28,27 +75,85 @@ export function publishPlan(root, id, { to, profile, title, description, at, tim
const fromBrief = FROM_BRIEF[p.intake.answers.platform];
const platforms = to ? String(to).split(',').map((s) => s.trim().toLowerCase()).filter(Boolean) : fromBrief || [];
- if (!platforms.length) throw new UserError(`where to? Pass --to with one or more of: ${PLATFORMS.join(', ')}`);
- const unknown = platforms.filter((s) => !PLATFORMS.includes(s));
- if (unknown.length) throw new UserError(`can't publish to ${unknown.join(', ')} (one or more of: ${PLATFORMS.join(', ')})`);
+ if (!platforms.length) throw new UserError(`where to? Pass --to with one or more of: ${svc.platforms.join(', ')}`);
+ const unknown = platforms.filter((s) => !svc.platforms.includes(s));
+ if (unknown.length) throw new UserError(`can't publish to ${unknown.join(', ')} through ${svc.name} (one or more of: ${svc.platforms.join(', ')})`);
- const who = String(profile || loadConfig(root).publish?.profile || '').trim();
- if (!who) throw new UserError('which Upload-Post profile? Pass --profile with the name your accounts are connected under (it\'s remembered)');
+ // Upload-Post posts under one of your profiles there; Postiz posts to the channels connected in it.
+ const who = service === 'uploadpost' ? String(profile || publishConfig(loadConfig(root)).profile || '').trim() : null;
+ if (service === 'uploadpost' && !who) throw new UserError('which Upload-Post profile? Pass --profile with the name your accounts are connected under (it\'s remembered)');
const caption = String(title ?? p.title).trim();
if (!caption) throw new UserError('a post needs a title: pass --title');
+ if (service === 'postiz' && platforms.includes('youtube') && caption.length < 2) throw new UserError('YouTube needs a title of at least 2 characters: pass --title');
if (timezone && !at) throw new UserError('--timezone only goes with --at');
+ if (timezone) { try { new Intl.DateTimeFormat('en', { timeZone: timezone }); } catch { throw new UserError(`--timezone "${timezone}" isn't a time zone (e.g. Europe/Madrid)`); } }
if (at && Number.isNaN(Date.parse(at))) throw new UserError(`--at "${at}" isn't a date and time (e.g. 2026-10-20T18:00)`);
const st = statSync(file);
- // The same video to the same place at the same time is the same post: a retry never posts it twice.
- const key = createHash('sha256').update([id, video.file, st.size, who, platforms.join(','), at || '', timezone || ''].join('\n')).digest('hex').slice(0, 32);
- return { id, project: p.title, file, size: st.size, platforms, profile: who, title: caption, description: description ? String(description) : null, at: at || null, timezone: timezone || null, key, from_brief: !to && Boolean(fromBrief) };
+ // The same video to the same place at the same time is the same post: a retry never posts it twice. --again is a
+ // new post on purpose.
+ const key = createHash('sha256').update([id, video.file, st.size, service, who || '', platforms.join(','), at || '', timezone || '', again ? now() : ''].join('\n')).digest('hex').slice(0, 32);
+ return { id, service, project: p.title, file, size: st.size, platforms, profile: who, title: caption, description: description ? String(description) : null, at: at || null, timezone: timezone || null, key, from_brief: !to && Boolean(fromBrief) };
+}
+
+// A time without an offset is read in `timezone` (UTC without one), the same way Upload-Post reads it.
+export function utcDate(at, timezone) {
+ if (/(Z|[+-]\d\d:?\d\d)$/i.test(at)) return new Date(at).toISOString();
+ const asUtc = new Date(`${at}${/T\d\d:\d\d/.test(at) ? '' : 'T00:00'}Z`);
+ if (!timezone) return asUtc.toISOString();
+ const offset = (t) => {
+ const g = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
+ .formatToParts(new Date(t)).map((x) => [x.type, x.value]));
+ return Date.UTC(g.year, g.month - 1, g.day, g.hour, g.minute, g.second) - t;
+ };
+ const guess = asUtc.getTime() - offset(asUtc.getTime());
+ return new Date(asUtc.getTime() - offset(guess)).toISOString();
+}
+
+// Postiz: the connected channels each platform goes to, so the plan can show them before anything is sent.
+export async function postizChannels(root, plan, { fetch = globalThis.fetch } = {}) {
+ const apiKey = needKey(root, 'postiz');
+ let res;
+ try { res = await fetch(`${postizBase(root)}/integrations`, { headers: { Authorization: apiKey } }); }
+ catch (e) { throw new UserError(`couldn't reach your Postiz at ${publishConfig(loadConfig(root)).postiz.url} (${e.message}): is it running?`); }
+ if (res.status === 401 || res.status === 403) throw new UserError('your Postiz refused the API key (check it with `mortiflix keys`)');
+ if (!res.ok) throw new UserError(`your Postiz couldn't list its channels (${res.status})`);
+ const all = [].concat(await res.json().catch(() => [])).filter((c) => c && !c.disabled);
+ const channels = [];
+ const missing = [];
+ for (const platform of plan.platforms) {
+ const types = POSTIZ_TYPES[platform] || [platform];
+ const found = all.filter((c) => types.includes(c.identifier));
+ if (!found.length) missing.push(platform);
+ for (const c of found) channels.push({ id: c.id, platform, type: c.identifier, name: c.name || c.profile || c.id });
+ }
+ if (missing.length) throw new UserError(`no ${missing.join(', ')} channel connected in your Postiz: connect ${missing.length > 1 ? 'them' : 'it'} there, or leave ${missing.length > 1 ? 'them' : 'it'} out with --to`);
+ return { ...plan, channels };
}
-// Sends the plan. Returns Upload-Post's ids: `request_id` for a post that goes out now, `job_id` for a scheduled one.
+// ---- sending ----
+
+function needKey(root, id) {
+ const apiKey = keyValue(root, id);
+ if (!apiKey) throw new UserError(`publishing needs your ${SERVICES[id].name} API key: add it with \`mortiflix keys set ${id}\``);
+ return apiKey;
+}
+
+// Sends the plan and records it. Returns the ids the service gave back.
export async function publish(root, plan, { fetch = globalThis.fetch } = {}) {
- const apiKey = keyValue(root, 'uploadpost');
- if (!apiKey) throw new UserError('publishing needs your Upload-Post API key: add it with `mortiflix keys set uploadpost`');
+ const p = loadProject(root, plan.id);
+ if ((p.published || []).some((x) => x.key === plan.key)) throw new UserError('this exact post was already sent (`--status` shows how it went). Add --again to post it once more');
+ const sent = plan.service === 'postiz' ? await sendPostiz(root, plan, { fetch }) : await sendUploadPost(root, plan, { fetch });
+ const record = { service: plan.service, key: plan.key, platforms: plan.platforms, profile: plan.profile, scheduled_for: plan.at, timezone: plan.timezone, sent_at: now(), ...sent };
+ update(root, plan.id, (x) => { x.published = [...(x.published || []), record]; });
+ event(root, plan.id, { event: 'PUBLISHED', actor: 'you', details: `${plan.platforms.join(', ')} via ${SERVICES[plan.service].name}${plan.at ? ` at ${plan.at}${plan.timezone ? ` ${plan.timezone}` : ''}` : ''}` });
+ if (plan.profile && publishConfig(loadConfig(root)).profile !== plan.profile) savePublish(root, { profile: plan.profile });
+ return record;
+}
+
+// Upload-Post: one form with the video. `request_id` for a post that goes out now, `job_id` for a scheduled one.
+async function sendUploadPost(root, plan, { fetch }) {
+ const apiKey = needKey(root, 'uploadpost');
const form = new FormData();
form.append('user', plan.profile);
for (const s of plan.platforms) form.append('platform[]', s);
@@ -68,29 +173,103 @@ export async function publish(root, plan, { fetch = globalThis.fetch } = {}) {
const body = await res.json().catch(() => ({}));
if (res.status === 401 || res.status === 403) throw new UserError('Upload-Post refused the API key (check it with `mortiflix keys`)');
if (!res.ok) throw new UserError(`Upload-Post didn't take it (${res.status}): ${body.message || body.error || 'no reason given'}`);
+ return { request_id: body.request_id || null, job_id: body.job_id || null };
+}
+
+// Postiz: upload the video, then one post per channel in a single request (its rate limit counts requests).
+async function sendPostiz(root, plan, { fetch }) {
+ const apiKey = needKey(root, 'postiz');
+ const ready = plan.channels ? plan : await postizChannels(root, plan, { fetch });
+ const base = postizBase(root);
+ const where = publishConfig(loadConfig(root)).postiz.url;
+
+ const form = new FormData();
+ form.append('file', await openAsBlob(plan.file, { type: 'video/mp4' }), `${plan.id}.mp4`);
+ let res;
+ try { res = await fetch(`${base}/upload`, { method: 'POST', body: form, headers: { Authorization: apiKey } }); }
+ catch (e) { throw new UserError(`couldn't reach your Postiz at ${where} (${e.message}): nothing was posted`); }
+ const media = await res.json().catch(() => ({}));
+ if (res.status === 401 || res.status === 403) throw new UserError('your Postiz refused the API key (check it with `mortiflix keys`)');
+ if (!res.ok || !media.id || !media.path) throw new UserError(`your Postiz didn't take the video (${res.status}): ${media.message || media.error || 'no reason given'}. Nothing was posted`);
- const sent = { request_id: body.request_id || null, job_id: body.job_id || null, platforms: plan.platforms, profile: plan.profile, scheduled_for: plan.at, sent_at: now() };
- update(root, plan.id, (p) => { p.published = [...(p.published || []), sent]; });
- event(root, plan.id, { event: 'PUBLISHED', actor: 'you', details: `${plan.platforms.join(', ')}${plan.at ? ` at ${plan.at}${plan.timezone ? ` ${plan.timezone}` : ''}` : ''}` });
- if (loadConfig(root).publish?.profile !== plan.profile) saveConfig(root, { publish: { ...loadConfig(root).publish, profile: plan.profile } });
- return sent;
+ const text = [plan.title, plan.description].filter(Boolean).join('\n\n');
+ const posts = ready.channels.map((c) => ({
+ integration: { id: c.id },
+ value: [{ content: c.type === 'youtube' ? plan.description || plan.title : text, image: [{ id: media.id, path: media.path }] }],
+ settings: postizSettings(c.type, plan),
+ }));
+ const body = { type: plan.at ? 'schedule' : 'now', date: plan.at ? utcDate(plan.at, plan.timezone) : new Date().toISOString(), shortLink: false, tags: [], posts };
+ try {
+ res = await fetch(`${base}/posts`, { method: 'POST', body: JSON.stringify(body), headers: { Authorization: apiKey, 'Content-Type': 'application/json' } });
+ } catch (e) {
+ // Postiz has no idempotency key: if the request got there, the post exists. Look before sending it again.
+ throw new UserError(`lost your Postiz at ${where} while posting (${e.message}). Check its calendar before running this again: it may have gone through`);
+ }
+ const out = await res.json().catch(() => null);
+ if (!res.ok) throw new UserError(`your Postiz didn't take the post (${res.status}): ${out?.message || out?.error || 'no reason given'}`);
+ const byId = Object.fromEntries(ready.channels.map((c) => [c.id, c]));
+ return {
+ date: body.date,
+ posts: (Array.isArray(out) ? out : []).map((x) => ({ id: x.postId, channel: x.integration, platform: byId[x.integration]?.platform || null, name: byId[x.integration]?.name || null })),
+ };
}
+// What each kind of channel needs besides the text: public, with the platform's own defaults for everything else.
+export function postizSettings(type, plan) {
+ switch (type) {
+ case 'tiktok': return { __type: 'tiktok', title: plan.title.slice(0, 90), privacy_level: 'PUBLIC_TO_EVERYONE', duet: false, stitch: false, comment: true, autoAddMusic: 'no', brand_content_toggle: false, brand_organic_toggle: false, content_posting_method: 'DIRECT_POST' };
+ case 'youtube': return { __type: 'youtube', title: plan.title.slice(0, 100), type: 'public' };
+ case 'instagram': case 'instagram-standalone': return { __type: type, post_type: 'post' };
+ case 'x': return { __type: 'x', who_can_reply_post: 'everyone' };
+ default: return { __type: type };
+ }
+}
+
+// ---- how it went ----
+
// How the last post of a project is going, per platform, with the links once they're live.
export async function publishStatus(root, id, { fetch = globalThis.fetch } = {}) {
const last = (loadProject(root, id).published || []).at(-1);
if (!last) throw new UserError('this project hasn\'t been published');
- const apiKey = keyValue(root, 'uploadpost');
- if (!apiKey) throw new UserError('checking needs your Upload-Post API key: add it with `mortiflix keys set uploadpost`');
+ return (last.service || 'uploadpost') === 'postiz' ? postizStatus(root, last, { fetch }) : uploadPostStatus(root, last, { fetch });
+}
+
+async function uploadPostStatus(root, last, { fetch }) {
+ const apiKey = needKey(root, 'uploadpost');
const q = last.job_id ? `job_id=${encodeURIComponent(last.job_id)}` : `request_id=${encodeURIComponent(last.request_id)}`;
const res = await fetch(`${API()}/api/uploadposts/status?${q}`, { headers: { Authorization: `Apikey ${apiKey}` } });
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new UserError(`Upload-Post couldn't say (${res.status}): ${body.message || body.error || 'no reason given'}`);
return {
...last,
+ ref: last.job_id ? `job ${last.job_id}` : `request ${last.request_id}`,
status: body.status || 'unknown',
message: body.message || null,
// Each platform: completed, failed, or still on its way (queued, processing…), as Upload-Post reports it.
results: (body.results || []).map((r) => ({ platform: r.platform, state: r.status || (r.success ? 'completed' : 'failed'), url: r.post_url || null, message: r.error_message || r.message || null })),
};
}
+
+const POSTIZ_STATES = { QUEUE: 'queued', PUBLISHED: 'completed', ERROR: 'failed', DRAFT: 'draft' };
+
+async function postizStatus(root, last, { fetch }) {
+ const apiKey = needKey(root, 'postiz');
+ // Postiz lists posts by date: a window around when it was sent and when it was due.
+ const times = [Date.parse(last.sent_at), Date.parse(last.date || last.sent_at)];
+ const day = 24 * 3600 * 1000;
+ const q = `startDate=${encodeURIComponent(new Date(Math.min(...times) - day).toISOString())}&endDate=${encodeURIComponent(new Date(Math.max(...times) + 2 * day).toISOString())}`;
+ let res;
+ try { res = await fetch(`${postizBase(root)}/posts?${q}`, { headers: { Authorization: apiKey } }); }
+ catch (e) { throw new UserError(`couldn't reach your Postiz (${e.message}): is it running?`); }
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new UserError(`your Postiz couldn't say (${res.status}): ${body.message || body.error || 'no reason given'}`);
+ const found = Object.fromEntries((body.posts || []).map((x) => [x.id, x]));
+ const results = (last.posts || []).map((x) => {
+ const post = found[x.id];
+ if (!post) return { platform: x.platform, state: 'gone', url: null, message: 'not in your Postiz any more (deleted there?)' };
+ return { platform: x.platform || post.integration?.providerIdentifier, state: POSTIZ_STATES[post.state] || String(post.state || 'unknown').toLowerCase(), url: post.releaseURL || null, message: post.error || null };
+ });
+ const states = new Set(results.map((r) => r.state));
+ const status = states.has('queued') ? 'queued' : states.has('failed') || states.has('gone') ? (states.has('completed') ? 'partly done' : 'failed') : results.length ? 'completed' : 'unknown';
+ return { ...last, ref: `Postiz, ${results.length} post${results.length === 1 ? '' : 's'}`, status, message: null, results };
+}
diff --git a/src/setup.mjs b/src/setup.mjs
index 10fd788..ffe6a3c 100644
--- a/src/setup.mjs
+++ b/src/setup.mjs
@@ -20,6 +20,8 @@ import { loadConfig, saveConfig, UserError } from './studio.mjs';
import { voiceConfig } from './voice/index.mjs';
import * as qwen from './voice/qwen.mjs';
import * as plat from './platform.mjs';
+import { publishConfig } from './publish.mjs';
+import { keySource } from './keys.mjs';
export const STRUDEL_VERSION = '1.3.0';
const OS = platform();
@@ -64,6 +66,12 @@ export const PARTS = [
needs: 'browser-harness (from browser-use on GitHub, installed with uv) and the addresses of the sites you use.',
tools: ['browser-harness'],
},
+ {
+ id: 'publish',
+ title: 'Publishing',
+ why: 'Once you approve a final, `mortiflix publish` can post it to your social accounts: where the brief said, at a time you pick, after it shows you the plan and you say yes. Sessions can never post.',
+ needs: 'Optional. Upload-Post (hosted, paid plans, your accounts connected on upload-post.com) or Postiz (free and open source, AGPL-3.0, runs on your own server with Docker, your accounts connected in it). Either one\'s API key. Without one, you download finals and post them yourself.',
+ },
{
id: '3d',
title: '3D',
@@ -216,6 +224,7 @@ export async function setupStatus(root) {
'blender-addons': addonsStatus(root),
music: musicConfig(config),
assets: assetsConfig(config),
+ publish: (({ service, ...rest }) => ({ service, ...rest, key: service === 'none' ? null : keySource(root, service) }))(publishConfig(config)),
gpu: qwen.recommend(qwen.detectGpus()),
};
}
diff --git a/src/studio.mjs b/src/studio.mjs
index a0868ed..9b24789 100644
--- a/src/studio.mjs
+++ b/src/studio.mjs
@@ -2,7 +2,7 @@
//
// <studio>/
// config.json settings (backend, model, port...). No secrets.
-// secrets.json your Anthropic, ElevenLabs and Upload-Post keys (mode 600), set with `mortiflix keys`. Never served, never logged.
+// secrets.json your Anthropic, ElevenLabs, Upload-Post and Postiz keys (mode 600), set with `mortiflix keys`. Never served, never logged.
// session.env other keys handed to every session (e.g. GEMINI_API_KEY=...), mode 600, also set with `mortiflix keys`
// checks.json the studio's error checklist (grows from your feedback)
// pipelines/<slug>/ your own pipelines (override the built-in ones with the same slug)
diff --git a/src/web/server.mjs b/src/web/server.mjs
index 24c8494..7e0b09c 100644
--- a/src/web/server.mjs
+++ b/src/web/server.mjs
@@ -19,6 +19,7 @@ import * as keys from '../keys.mjs';
import * as setup from '../setup.mjs';
import * as booth from '../booth.mjs';
import * as music from '../music.mjs';
+import * as pub from '../publish.mjs';
import { costText } from '../usage.mjs';
const MIME = {
@@ -114,6 +115,7 @@ export async function startServer(root, { port = 4646, host = '127.0.0.1', runne
if (p === '/setup' && method === 'GET') return send(res, 200, await setupInfo(root, installs));
if (p === '/setup/music' && method === 'PUT') { setup.saveMusic(root, await json(req)); return after(await setupInfo(root, installs)); }
if (p === '/setup/assets' && method === 'PUT') { setup.saveAssetSites(root, (await json(req)).sites); return after(await setupInfo(root, installs)); }
+ if (p === '/setup/publish' && method === 'PUT') { const b = await json(req); pub.savePublish(root, { service: b.service, url: b.url, profile: b.profile }); return after(await setupInfo(root, installs)); }
if (p === '/setup/recordings' && method === 'PUT') { setup.browserHarnessRecordings(Boolean((await json(req)).enable)); return after(await setupInfo(root, installs)); }
if (p === '/setup/blender' && method === 'POST') {
if (!loopback) throw new BadRequest('Blender opens on the studio\'s own screen: use mortiflix blender there');
diff --git a/test/publish.test.mjs b/test/publish.test.mjs
index 4541f18..9bf56f5 100644
--- a/test/publish.test.mjs
+++ b/test/publish.test.mjs
@@ -6,13 +6,16 @@ import { tempStudio } from './helpers.mjs';
import { loadConfig } from '../src/studio.mjs';
import { createProject, projectPaths, update, loadProject, readEvents } from '../src/projects.mjs';
import * as keys from '../src/keys.mjs';
-import { publishPlan, publish, publishStatus } from '../src/publish.mjs';
+import { publishPlan, publish, publishStatus, postizChannels, savePublish, publishConfig, utcDate, POSTIZ_DEFAULT } from '../src/publish.mjs';
+import { run } from '../src/cli.mjs';
delete process.env.UPLOAD_POST_API_KEY;
delete process.env.UPLOAD_POST_API;
+delete process.env.POSTIZ_API_KEY;
// A social short that went through every gate: its approved final sits in the record.
-function delivered(root, answers = { message: 'Bikes are faster than you think', platform: 'TikTok / Reels / Shorts' }) {
+function delivered(root, answers = { message: 'Bikes are faster than you think', platform: 'TikTok / Reels / Shorts' }, service = 'uploadpost') {
+ if (service && publishConfig(loadConfig(root)).service === 'none') savePublish(root, { service });
const p = createProject(root, { pipeline: 'social-short', title: 'Fast bikes', answers });
const file = 'reviews/final/v2/files/final.mp4';
mkdirSync(join(projectPaths(root, p.id).state, 'reviews/final/v2/files'), { recursive: true });
@@ -34,6 +37,8 @@ function fakeApi(reply) {
test('publish: only a delivered video, to where the brief said, after the owner names a profile', (t) => {
const root = tempStudio(t);
+ assert.throws(() => publishPlan(root, 'x'), /isn't set up.*mortiflix setup publish/);
+ savePublish(root, { service: 'uploadpost' });
const draft = createProject(root, { pipeline: 'social-short', title: 'Not yet', answers: { message: 'x' } });
assert.throws(() => publishPlan(root, draft.id, { profile: 'me' }), /isn't delivered yet \(draft\)/);
@@ -130,3 +135,130 @@ test('keys: the Upload-Post key is checked with a free call and never handed to
assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', steps: [{ work: ['motion', 'audio'] }] }), []);
assert.throws(() => keys.setSessionKey(root, 'UPLOAD_POST_API_KEY', 'x'), /its own place/);
});
+
+// ---- your own Postiz ----
+
+const CHANNELS = [
+ { id: 'ch-tt', name: 'Fast Bikes TT', identifier: 'tiktok', disabled: false },
+ { id: 'ch-ig', name: 'fastbikes', identifier: 'instagram-standalone', disabled: false },
+ { id: 'ch-yt', name: 'Fast Bikes', identifier: 'youtube', disabled: false },
+ { id: 'ch-old', name: 'Old YouTube', identifier: 'youtube', disabled: true },
+ { id: 'ch-x', name: '@fastbikes', identifier: 'x', disabled: false },
+];
+
+// A fake Postiz: channels, uploads, posts and the post list.
+function fakePostiz({ channels = CHANNELS, posts = [] } = {}) {
+ return fakeApi((url, init) => {
+ if (url.endsWith('/integrations')) return init.headers.Authorization === 'pz-secret' ? [200, channels] : [401, { message: 'Unauthorized' }];
+ if (url.endsWith('/upload')) return [200, { id: 'media-1', path: 'http://localhost:4007/uploads/final.mp4' }];
+ if (url.endsWith('/posts') && init.method === 'POST') return [200, JSON.parse(init.body).posts.map((x, i) => ({ postId: `post-${i + 1}`, integration: x.integration.id }))];
+ if (url.includes('/posts?')) return [200, { posts }];
+ return [404, {}];
+ });
+}
+
+test('postiz: chosen in setup, its address checked, its key separate', async (t) => {
+ const root = tempStudio(t);
+ assert.equal(publishConfig(loadConfig(root)).service, 'none');
+ assert.equal(publishConfig(loadConfig(root)).postiz.url, POSTIZ_DEFAULT);
+ assert.throws(() => savePublish(root, { service: 'myspace' }), /uploadpost, postiz or none/);
+ assert.throws(() => savePublish(root, { service: 'postiz', url: 'ftp://box' }), /http:\/\/ or https:\/\//);
+ assert.throws(() => savePublish(root, { service: 'postiz', url: 'https://me:[email protected]' }), /no login in the address/);
+ assert.equal(savePublish(root, { service: 'postiz', url: 'https://postiz.example/api/' }).postiz.url, 'https://postiz.example/api');
+
+ const ok = await keys.verifyKey(root, 'postiz', 'k', { fetch: async (url) => { assert.equal(url, 'https://postiz.example/api/public/v1/integrations'); return new Response(JSON.stringify(CHANNELS)); } });
+ assert.equal(ok.ok, true);
+ assert.match(ok.detail, /4 channels connected \(tiktok, instagram-standalone, youtube, x\)/);
+ assert.equal((await keys.verifyKey(root, 'postiz', 'k', { fetch: async () => new Response('{}', { status: 401 }) })).ok, false);
+ assert.deepEqual(keys.keysFor(root, { backend: 'claude-code', steps: [{ work: ['motion', 'audio'] }] }), []);
+ assert.throws(() => keys.setSessionKey(root, 'POSTIZ_API_KEY', 'x'), /its own place/);
+
+ // Without a terminal, the same choice.
+ const out = [];
+ const log = console.log;
+ console.log = (...a) => out.push(a.join(' '));
+ try { await run(['--studio', root, 'setup', 'publish', 'uploadpost', '--profile', 'studio']); } finally { console.log = log; }
+ assert.match(out.join('\n'), /Publishing through Upload-Post/);
+ assert.deepEqual(publishConfig(loadConfig(root)), { service: 'uploadpost', profile: 'studio', postiz: { url: 'https://postiz.example/api' } });
+});
+
+test('postiz: names the channels first, uploads the final, posts to each, and never twice by accident', async (t) => {
+ const root = tempStudio(t);
+ savePublish(root, { service: 'postiz' });
+ const id = delivered(root);
+ const plan = publishPlan(root, id, { description: 'Link in bio', at: '2026-10-20T18:00', timezone: 'Europe/Madrid' });
+ assert.equal(plan.profile, null);
+ assert.throws(() => publishPlan(root, id, { to: 'pinterest' }), /can't publish to pinterest through Postiz/);
+ await assert.rejects(postizChannels(root, plan, { fetch: fakePostiz().fetch }), /needs your Postiz API key.*mortiflix keys set postiz/);
+
+ keys.saveKey(root, 'postiz', 'pz-secret');
+ const ready = await postizChannels(root, plan, { fetch: fakePostiz().fetch });
+ // The disabled channel is left out; Instagram matches the standalone kind too.
+ assert.deepEqual(ready.channels.map((c) => [c.platform, c.id]), [['tiktok', 'ch-tt'], ['instagram', 'ch-ig'], ['youtube', 'ch-yt']]);
+ await assert.rejects(postizChannels(root, { ...plan, platforms: ['linkedin'] }, { fetch: fakePostiz().fetch }), /no linkedin channel connected in your Postiz/);
+
+ const api = fakePostiz();
+ const sent = await publish(root, ready, { fetch: api.fetch });
+ const [up, post] = api.calls;
+ assert.equal(up.url, 'http://localhost:4007/api/public/v1/upload');
+ assert.equal(up.init.headers.Authorization, 'pz-secret');
+ assert.equal(up.form.get('file').size, 2048);
+ assert.equal(post.url, 'http://localhost:4007/api/public/v1/posts');
+ const body = JSON.parse(post.init.body);
+ assert.equal(body.type, 'schedule');
+ assert.equal(body.date, '2026-10-20T16:00:00.000Z'); // 18:00 in Madrid (summer time)
+ assert.deepEqual(body.posts.map((x) => x.settings.__type), ['tiktok', 'instagram-standalone', 'youtube']);
+ assert.equal(body.posts[0].settings.content_posting_method, 'DIRECT_POST');
+ assert.equal(body.posts[0].settings.privacy_level, 'PUBLIC_TO_EVERYONE');
+ assert.deepEqual(body.posts[2].settings, { __type: 'youtube', title: 'Fast bikes', type: 'public' });
+ assert.equal(body.posts[0].value[0].content, 'Fast bikes\n\nLink in bio');
+ assert.equal(body.posts[2].value[0].content, 'Link in bio');
+ assert.deepEqual(body.posts[1].value[0].image, [{ id: 'media-1', path: 'http://localhost:4007/uploads/final.mp4' }]);
+
+ assert.deepEqual(sent.posts.map((x) => [x.id, x.platform]), [['post-1', 'tiktok'], ['post-2', 'instagram'], ['post-3', 'youtube']]);
+ assert.equal(loadProject(root, id).published[0].service, 'postiz');
+ assert.match(readEvents(root, id).at(-1).details, /via Postiz at 2026-10-20T18:00 Europe\/Madrid/);
+
+ // Postiz has no idempotency key: the studio refuses the same post again, unless you ask for it.
+ await assert.rejects(publish(root, ready, { fetch: api.fetch }), /already sent.*--again/);
+ const again = publishPlan(root, id, { description: 'Link in bio', at: '2026-10-20T18:00', timezone: 'Europe/Madrid', again: true });
+ assert.notEqual(again.key, plan.key);
+ await publish(root, again, { fetch: fakePostiz().fetch });
+ assert.equal(loadProject(root, id).published.length, 2);
+});
+
+test('postiz: a refused upload or post records nothing; status reads each post back with its link', async (t) => {
+ const root = tempStudio(t);
+ savePublish(root, { service: 'postiz' });
+ const id = delivered(root);
+ keys.saveKey(root, 'postiz', 'pz-secret');
+ const plan = await postizChannels(root, publishPlan(root, id, { to: 'tiktok,youtube' }), { fetch: fakePostiz().fetch });
+ // Fails at one endpoint; the upload before it works.
+ const failing = (where, status) => fakeApi((url) => (url.endsWith(where) ? [status, { message: 'Bad video' }] : [200, { id: 'm', path: 'p' }]));
+ await assert.rejects(publish(root, plan, { fetch: failing('/upload', 400).fetch }), /didn't take the video \(400\): Bad video\. Nothing was posted/);
+ await assert.rejects(publish(root, plan, { fetch: failing('/posts', 400).fetch }), /didn't take the post \(400\): Bad video/);
+ await assert.rejects(publish(root, plan, { fetch: async () => { throw new Error('ECONNREFUSED'); } }), /couldn't reach your Postiz at http:\/\/localhost:4007\/api/);
+ assert.equal(loadProject(root, id).published, undefined);
+
+ await publish(root, plan, { fetch: fakePostiz().fetch });
+ const api = fakePostiz({ posts: [
+ { id: 'post-1', state: 'PUBLISHED', releaseURL: 'https://www.tiktok.com/@me/video/1', integration: { providerIdentifier: 'tiktok' } },
+ { id: 'post-2', state: 'ERROR', error: 'Daily upload limit reached', integration: { providerIdentifier: 'youtube' } },
+ { id: 'someone-else', state: 'QUEUE' },
+ ] });
+ const st = await publishStatus(root, id, { fetch: api.fetch });
+ assert.match(api.calls[0].url, /^http:\/\/localhost:4007\/api\/public\/v1\/posts\?startDate=.+&endDate=/);
+ assert.equal(st.status, 'partly done');
+ assert.deepEqual(st.results, [
+ { platform: 'tiktok', state: 'completed', url: 'https://www.tiktok.com/@me/video/1', message: null },
+ { platform: 'youtube', state: 'failed', url: null, message: 'Daily upload limit reached' },
+ ]);
+});
+
+test('publish: a time without an offset is read in its time zone', () => {
+ assert.equal(utcDate('2026-10-20T18:00'), '2026-10-20T18:00:00.000Z');
+ assert.equal(utcDate('2026-10-20T18:00', 'Europe/Madrid'), '2026-10-20T16:00:00.000Z');
+ assert.equal(utcDate('2026-12-20T18:00', 'Europe/Madrid'), '2026-12-20T17:00:00.000Z');
+ assert.equal(utcDate('2026-12-20T18:00', 'America/Chicago'), '2026-12-21T00:00:00.000Z');
+ assert.equal(utcDate('2026-10-20T18:00+02:00', 'America/Chicago'), '2026-10-20T16:00:00.000Z');
+});
diff --git a/web/app.js b/web/app.js
index f5e4fdf..8b40228 100644
--- a/web/app.js
+++ b/web/app.js
@@ -731,6 +731,37 @@ async function setupSection() {
}, 1200);
};
+ // Publishing: which service posts a delivered video (`mortiflix publish`), and what it needs.
+ const PUBLISH = { 'Upload-Post': 'uploadpost', 'Postiz (self-hosted)': 'postiz', Off: 'none' };
+ const savePublish = async (body, done) => {
+ try { info = await api('/api/setup/publish', { method: 'PUT', body }); draw(); if (done) toast(done); } catch (e) { toast(e.message, true); }
+ };
+ const publishSetup = () => {
+ const pb = info.status.publish;
+ const label = Object.keys(PUBLISH).find((k) => PUBLISH[k] === pb.service);
+ const keyNote = pb.key ? chip(true, `key ${pb.key === 'saved' ? 'saved' : `from ${pb.key}`}`, '') : chip(false, '', 'key missing: add it below, in Keys');
+ let detail = null;
+ if (pb.service === 'uploadpost') {
+ let profile = pb.profile || '';
+ detail = h('div', null,
+ h('input', { type: 'text', placeholder: 'Upload-Post profile your accounts are under', value: profile, oninput: (e) => { profile = e.target.value; } }),
+ h('div', { class: 'actions', style: { marginTop: '8px' } },
+ h('button', { class: 'btn', onclick: () => savePublish({ profile }, 'Profile saved') }, 'Save'), keyNote),
+ h('p', { class: 'meta' }, 'Connect your accounts on upload-post.com, under a profile. Paid plans.'));
+ } else if (pb.service === 'postiz') {
+ let url = pb.postiz.url;
+ detail = h('div', null,
+ h('input', { type: 'text', inputmode: 'url', placeholder: 'http://localhost:4007/api', value: url, oninput: (e) => { url = e.target.value; } }),
+ h('div', { class: 'actions', style: { marginTop: '8px' } },
+ h('button', { class: 'btn', onclick: () => savePublish({ url }, 'Postiz address saved') }, 'Save'), keyNote),
+ h('p', { class: 'meta' }, 'Your Postiz\'s API address: the official Docker image answers at http://localhost:4007/api, Postiz Cloud at https://api.postiz.com. Install it with Docker Compose (docs.postiz.com › Self-host), then connect your accounts in it. Each platform needs a developer app you register there; TikTok keeps posts private until it has reviewed yours.'));
+ }
+ return h('div', null,
+ choiceChips(Object.keys(PUBLISH), label, (v) => savePublish({ service: PUBLISH[v] })),
+ detail,
+ pb.service === 'none' ? null : h('p', { class: 'meta' }, 'Post a delivered video from a terminal: mortiflix publish <project>. It shows the plan and asks first.'));
+ };
+
function draw() {
const st = info.status;
const part = (id) => info.parts.find((x) => x.id === id);
@@ -761,6 +792,7 @@ async function setupSection() {
st['browser-harness'].ok && info.recordings ? h('label', { class: 'toggle' }, h('input', { type: 'checkbox', checked: /enabled/i.test(info.recordings) && !/disabled/i.test(info.recordings), onchange: async (e) => { info = await api('/api/setup/recordings', { method: 'PUT', body: { enable: e.target.checked } }); draw(); } }),
'Keep local browser recordings (screenshots and traces of what sessions do, on this machine only)') : null,
h('p', { class: 'meta' }, 'Sessions use your own Chrome: sign in to these sites there. The first time, Chrome may ask you to allow remote debugging (chrome://inspect/#remote-debugging).')) : null)),
+ field(part('publish').title, h('div', null, ...intro('publish'), publishSetup())),
field(part('3d').title, h('div', null, ...intro('3d'),
toolRow('blender'),
st.blender.ok ? toolRow('blender-addons') : null,