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

7.5 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from 'react';
import socket from '../services/socket';
import {
  getMusicVideoPublishDrafts,
  prepareMusicVideoPublishDraft,
  previewMusicVideoPublishPost,
  discardMusicVideoPublishDraft,
  getMusicVideoPublishPlatforms,
  updateMusicVideoPublishPlatforms,
  recordMusicVideoPublishPost,
  removeMusicVideoPublishPost,
  setMusicVideoPublishCrossLinks,
  prepareMusicVideoCrossLinkEdit,
} from '../services/apiMusicVideo.js';

const EMPTY_POSTING = { drafts: {}, busy: {}, errors: {} };

/**
 * Music Video posting (#9282). `prepare` fills the post in the PortOS Browser
 * and returns what it filled (a summary and a screenshot) for the director to
 * review. Manual posting is handled outside this hook. Errors are kept per
 * platform so a sign-in prompt stays beside the platform that needs it.
 *
 * Platforms are opt-in (#9287): `platforms` is the director's saved choice of
 * where they post (with an optional account each), `history` their posts and
 * ratings per platform across projects. `recordPost` saves a post made by hand
 * (a link, or `{ posted: true }` to mark it done without one) or rates one;
 * `removePost` undoes the done mark. `preview` reads what Fill draft would
 * post, without opening anything.
 */
export default function useMusicVideoPublishing({ project, replaceProject } = {}) {
  const projectId = project?.id || null;
  // A selection lifetime, rather than just the id, also rejects an old reply
  // after switching A → B → A. Hide the previous state in the first render.
  const selection = useRef({ projectId });
  if (selection.current.projectId !== projectId) selection.current = { projectId };
  const scope = selection.current;
  const [posting, setPosting] = useState({ ...EMPTY_POSTING, scope });
  const { drafts, busy, errors } = posting.scope === scope ? posting : EMPTY_POSTING;
  const [platforms, setPlatforms] = useState(null);
  const [history, setHistory] = useState({});
  // The socket handler below outlives renders; it reads the latest callback.
  const replaceProjectRef = useRef(replaceProject);
  replaceProjectRef.current = replaceProject;

  const loadPlatforms = useCallback(() => getMusicVideoPublishPlatforms({ silent: true })
    .then((res) => { setPlatforms(res?.platforms || {}); setHistory(res?.history || {}); })
    .catch(() => setPlatforms((prev) => prev || {})), []);
  useEffect(() => { loadPlatforms(); }, [loadPlatforms]);

  const setFor = (field, target, value) => setPosting((prev) => {
    if (selection.current !== scope) return prev;
    const state = prev.scope === scope ? prev : { ...EMPTY_POSTING, scope };
    const next = { ...state[field] };
    if (value == null) delete next[target];
    else next[target] = value;
    return { ...state, [field]: next };
  });
  const fail = (target, err) => {
    setFor('errors', target, { message: err?.message || 'Failed', code: err?.code || null, url: err?.context?.url || null });
  };

  // Rehydrate from the server after a reload, and follow its draft events
  // (a tab filled elsewhere, closed by hand, discarded, or posted from by the
  // director, in which case the server has already recorded the post's link).
  useEffect(() => {
    if (!projectId) return undefined;
    let cancelled = false;
    const apply = (list) => { if (cancelled) return; for (const d of list) if (d.state !== 'discarded') setFor('drafts', d.target, d); };
    getMusicVideoPublishDrafts(projectId, { silent: true }).then((res) => apply(res?.drafts || [])).catch(() => {});
    const onDraft = (e) => {
      if (e?.projectId !== projectId) return;
      if (e.state === 'posted') {
        if (e.project) replaceProjectRef.current?.(e.project);
        loadPlatforms();
      }
      if (e.state === 'discarded' || e.state === 'posted') {
        setPosting((prev) => {
          const current = prev.scope === scope ? prev.drafts[e.target] : null;
          if (!current || current.draftId !== e.draftId) return prev;
          const next = { ...prev.drafts };
          delete next[e.target];
          return { ...prev, drafts: next };
        });
      } else if (e.state === 'closed') {
        setPosting((prev) => {
          const current = prev.scope === scope ? prev.drafts[e.target] : null;
          if (!current || current.draftId !== e.draftId) return prev;
          return { ...prev, drafts: { ...prev.drafts, [e.target]: { ...current, state: 'closed' } } };
        });
      }
    };
    socket.on('music-video:publish-draft', onDraft);
    return () => { cancelled = true; socket.off('music-video:publish-draft', onDraft); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId, scope, loadPlatforms]);

  const prepare = (target, options = {}) => {
    setFor('busy', target, 'prepare');
    setFor('errors', target, null);
    return prepareMusicVideoPublishDraft(projectId, target, options, { silent: true })
      .then((draft) => { setFor('drafts', target, draft); return draft; })
      .catch((err) => { setFor('drafts', target, null); fail(target, err); return null; })
      .finally(() => setFor('busy', target, null));
  };

  // What Fill draft would post with these options; null when the preview itself failed.
  const preview = (target, options = {}) => previewMusicVideoPublishPost(projectId, target, options, { silent: true }).catch(() => null);

  const discard = (target) => {
    const draft = drafts[target];
    setFor('drafts', target, null);
    if (draft) discardMusicVideoPublishDraft(projectId, draft.draftId, { silent: true }).catch(() => {});
  };

  const setPlatform = (target, change) => {
    // Optimistic: the toggle flips at once and settles to the server's answer.
    // `defaults` merges per answer (null forgets one), as the server does.
    setPlatforms((prev) => {
      const current = prev?.[target] || {};
      const next = { ...current, ...change };
      if (change.defaults) {
        next.defaults = { ...(current.defaults || {}) };
        for (const [k, v] of Object.entries(change.defaults)) { if (v == null || v === '') delete next.defaults[k]; else next.defaults[k] = v; }
      }
      return { ...(prev || {}), [target]: next };
    });
    return updateMusicVideoPublishPlatforms({ [target]: change })
      .then((res) => { if (res?.platforms) setPlatforms(res.platforms); return res?.platforms || null; })
      .catch(() => { loadPlatforms(); return null; });
  };

  const recordPost = (target, body) => recordMusicVideoPublishPost(projectId, target, body)
    .then((res) => { if (res?.project) replaceProject?.(res.project); loadPlatforms(); return res?.post || null; })
    .catch(() => null);

  const removePost = (target) => removeMusicVideoPublishPost(projectId, target)
    .then((res) => { if (res?.project) replaceProject?.(res.project); loadPlatforms(); return true; })
    .catch(() => false);

  // Cross-links: whether new drafts list the release's other posts.
  const setCrossLinks = (enabled) => setMusicVideoPublishCrossLinks(projectId, enabled)
    .then((res) => { if (res?.project) replaceProject?.(res.project); return true; })
    .catch(() => false);
  // Fill a posted platform's edit (or a reply under it) with the links it lacks; errors stay with the caller.
  const prepareCrossLinks = (target) => prepareMusicVideoCrossLinkEdit(projectId, target, { silent: true });

  const enabledTargets = Object.entries(platforms || {}).filter(([, p]) => p?.enabled).map(([t]) => t);

  return { drafts, busy, errors, prepare, preview, discard, platforms, history, enabledTargets, setPlatform, recordPost, removePost, setCrossLinks, prepareCrossLinks };
}