@yoonion/mimi-seed-mcp 0.25.4 → 0.25.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/assets/agent-guide.md +27 -2
- package/dist/crosspost/ledger.d.ts +52 -0
- package/dist/crosspost/ledger.js +269 -0
- package/dist/crosspost/tools.d.ts +136 -0
- package/dist/crosspost/tools.js +821 -0
- package/dist/facebook/api.d.ts +3 -2
- package/dist/facebook/api.js +6 -2
- package/dist/i18n/manifest-en.js +3 -0
- package/dist/i18n/tools-en/crosspost.d.ts +23 -0
- package/dist/i18n/tools-en/crosspost.js +22 -0
- package/dist/i18n/tools-en/index.js +2 -0
- package/dist/instagram/api.d.ts +3 -2
- package/dist/instagram/api.js +6 -2
- package/dist/lib/meta-auth.d.ts +9 -0
- package/dist/lib/meta-auth.js +12 -3
- package/dist/lib/tool-menu.js +2 -1
- package/dist/registers/crosspost.d.ts +2 -0
- package/dist/registers/crosspost.js +81 -0
- package/dist/server.js +2 -0
- package/dist/threads/api.d.ts +4 -3
- package/dist/threads/api.js +9 -7
- package/dist/tiktok-business/posting.d.ts +11 -1
- package/dist/tiktok-business/posting.js +18 -1
- package/dist/video/youtube-publish.d.ts +41 -1
- package/dist/video/youtube-publish.js +16 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/tool-manifest.json +20 -2
|
@@ -0,0 +1,821 @@
|
|
|
1
|
+
// social_publish — one post, several platforms.
|
|
2
|
+
//
|
|
3
|
+
// It composes the same functions the per-platform tools call (facebook/instagram/threads api, youtube upload, TikTok
|
|
4
|
+
// planned publish), so every platform keeps its own validation and error translation. What this layer adds:
|
|
5
|
+
// 1. a plan: each target's action, text, and media, plus everything that would make that target fail, computed
|
|
6
|
+
// without any network call. The tool returns it as the dry-run preview;
|
|
7
|
+
// 2. all-or-nothing validation: if any target has a problem, nothing is posted, so a typo never leaves you with
|
|
8
|
+
// the post on three platforms and missing from two;
|
|
9
|
+
// 3. a preflight: every target's network-side checks (tokens, the YouTube channel and video stream, the TikTok
|
|
10
|
+
// publish scope) run before anything is sent, so one platform cannot fail after others have posted;
|
|
11
|
+
// 4. per-platform results and an at-most-once record per post (ledger.ts), so sending again finishes only what is
|
|
12
|
+
// left and never posts the same thing twice.
|
|
13
|
+
//
|
|
14
|
+
// The one rule (decide()). A **post** is a platform + the account it resolves to + exactly what that platform
|
|
15
|
+
// receives (targetKey). An **account** is a platform + the account it resolves to (accountKey). While a send to an
|
|
16
|
+
// account has no known outcome, that account is *pending* (ledger.ts) — whatever content the send carried.
|
|
17
|
+
//
|
|
18
|
+
// post record | account pending | approval | decision
|
|
19
|
+
// -----------------+-----------------+----------------------------------+------------------------------------
|
|
20
|
+
// posted | any | none | skip, report already_posted
|
|
21
|
+
// posted | no | repost names this record's `at` | send again (a deliberate repost)
|
|
22
|
+
// any (to send) | yes | none for this pending `at` | block: a send to this account may
|
|
23
|
+
// | | | be live, even for different content
|
|
24
|
+
// sending/unknown | — | none for this record's `at` | block (an older record, no marker)
|
|
25
|
+
// none / failed | no | — | send
|
|
26
|
+
// (otherwise) | | resendUnknown names the `at` | send: a person checked it is not live
|
|
27
|
+
//
|
|
28
|
+
// An approval (repost / resendUnknown) names the exact record it overrides by its `at`, shown in the plan. Once
|
|
29
|
+
// used, that record changes (a new `at`), so the same arguments on a retry cannot repost again or resend a newer
|
|
30
|
+
// unknown outcome nobody checked. A post that is only skipped never needs the account, its marker, or its lock.
|
|
31
|
+
//
|
|
32
|
+
// Changing a platform's content (text, images, a re-rendered video, the title) makes a different post with its own
|
|
33
|
+
// record, so it is sent — unless that account is pending. Another Page or account is another post and account.
|
|
34
|
+
//
|
|
35
|
+
// Media rules mirror the per-platform tools: Meta fetches public HTTPS URLs; YouTube uploads a local file; TikTok
|
|
36
|
+
// publishes a plan made by tiktok_business_plan_video_post (its own consent, settings, and duplicate checks).
|
|
37
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
38
|
+
import fs from 'node:fs';
|
|
39
|
+
import path from 'node:path';
|
|
40
|
+
import { catalog } from '#core/lang.js';
|
|
41
|
+
import { requireFacebookConfig } from '../facebook/config.js';
|
|
42
|
+
import { requireInstagramConfig } from '../instagram/config.js';
|
|
43
|
+
import { requireThreadsConfig } from '../threads/config.js';
|
|
44
|
+
import * as facebook from '../facebook/api.js';
|
|
45
|
+
import * as instagram from '../instagram/api.js';
|
|
46
|
+
import * as threads from '../threads/api.js';
|
|
47
|
+
import { requireAuth } from '../helpers.js';
|
|
48
|
+
import { YOUTUBE_SCOPE, prepareYouTubeUpload, uploadYouTubeVideo, } from '../video/youtube-publish.js';
|
|
49
|
+
import { preflightPlannedVideo, publishPlannedVideo } from '../tiktok-business/posting.js';
|
|
50
|
+
import { TikTokApiError } from '../tiktok-business/api.js';
|
|
51
|
+
import { loadTikTokBusinessConfig } from '../tiktok-business/config.js';
|
|
52
|
+
import { ensureTikTokPublishConfig } from '../tiktok-business/auth.js';
|
|
53
|
+
import { extractHttpStatus } from '../lib/google-errors.js';
|
|
54
|
+
import { metaErrorStatus } from '../lib/meta-auth.js';
|
|
55
|
+
import { getStoredTokens } from '../auth/google-auth.js';
|
|
56
|
+
import { summarizeGrantedDomains } from '../auth/scopes.js';
|
|
57
|
+
import { acquireAccountLock, inProgressMessage, replacePendingIfOurs, isAccountLocked, readPending, readRecord, writePending, writeRecord, } from './ledger.js';
|
|
58
|
+
export const SOCIAL_TARGETS = ['facebook', 'instagram', 'threads', 'youtube', 'tiktok'];
|
|
59
|
+
const M = catalog({
|
|
60
|
+
duplicateTarget: (p) => `${p} 가 targets 에 두 번 있습니다.`,
|
|
61
|
+
notConnected: (msg) => `연결되지 않았습니다: ${msg} — 연결하거나, 이 플랫폼을 targets 에서 빼고 나머지만 보내세요.`,
|
|
62
|
+
textTooLong: (platform, max, len) => `본문이 ${max}자를 넘습니다 (${len}자). ${platform}.text 로 따로 지정하세요.`,
|
|
63
|
+
textRequired: '본문(text)이 비어 있습니다.',
|
|
64
|
+
needsImages: (p, max) => `${p} 는 이미지가 필요합니다 (1~${max}장의 public HTTPS imageUrls). 텍스트·영상 게시는 지원하지 않습니다.`,
|
|
65
|
+
tooManyImages: (max, n) => `이미지가 너무 많습니다 (${n}장, 최대 ${max}장).`,
|
|
66
|
+
imageAndVideo: 'Threads 는 이미지와 영상을 한 게시물에 함께 올릴 수 없습니다. imageUrls 와 videoUrl 중 하나만 주세요.',
|
|
67
|
+
youtubeOptions: 'youtube 옵션(expectedChannelId 필수)이 필요합니다.',
|
|
68
|
+
youtubeFile: 'YouTube 는 로컬 영상 파일(videoFilePath)이 필요합니다.',
|
|
69
|
+
youtubeTitle: 'YouTube 제목이 비었거나 100자를 넘습니다. youtube.title 을 지정하세요.',
|
|
70
|
+
youtubeDescription: 'YouTube 설명이 5,000자를 넘습니다. youtube.description 을 지정하세요.',
|
|
71
|
+
youtubeTags: 'YouTube 태그를 쉼표로 이은 길이가 500자를 넘습니다.',
|
|
72
|
+
youtubeNotSignedIn: (profile) => `YouTube 에 로그인돼 있지 않습니다${profile ? ` (프로필 ${profile})` : ''}. mimi-seed auth social 로 연결하세요.`,
|
|
73
|
+
youtubeNoUpload: (profile) => `Google 로그인${profile ? ` (프로필 ${profile})` : ''}에 YouTube 업로드 권한이 없습니다. mimi-seed auth login${profile ? ` --profile ${profile}` : ''} --domains youtube 로 추가하세요.`,
|
|
74
|
+
tiktokPlan: 'TikTok 은 tiktok_business_plan_video_post 로 만든 planId 가 필요합니다 (tiktok.planId).',
|
|
75
|
+
tiktokPlanInvalid: (msg) => `TikTok 계획을 쓸 수 없습니다: ${msg}`,
|
|
76
|
+
previousUnknown: (p, at) => `이전 시도(${at})의 결과를 알 수 없습니다 — 게시됐을 수 있습니다. ${p} 에서 직접 확인하세요. 올라가 있다면 markPosted: [{ "platform": "${p}", "at": "${at}" }], 없다면 resendUnknown: [{ "platform": "${p}", "at": "${at}" }] 를 더해 보내세요.`,
|
|
77
|
+
resendingUnknown: (at) => `이전 시도(${at})의 결과를 알 수 없었지만 확인 후 다시 보냄 (resendUnknown)`,
|
|
78
|
+
accountPending: (p, at) => `${p} 계정에 결과를 알 수 없는 이전 게시(${at})가 있습니다 — 내용이 달라도 막습니다. ${p} 에서 직접 확인하세요. 올라가 있다면 markPosted: [{ "platform": "${p}", "at": "${at}" }], 없다면 resendUnknown: [{ "platform": "${p}", "at": "${at}" }] 를 더해 보내세요.`,
|
|
79
|
+
reposting: (at) => `같은 내용이 이미 게시됨 (${at}) — repost 로 다시 게시`,
|
|
80
|
+
alreadyPostedHint: (p, at) => `이미 게시됨 (${at}) — 건너뜀. 일부러 다시 올리려면 repost: [{ "platform": "${p}", "at": "${at}" }]`,
|
|
81
|
+
alreadyPostedTikTok: (at) => `이미 게시됨 (${at}) — 건너뜀. TikTok 에 다시 올리려면 tiktok_business_plan_video_post 로 새 계획을 만드세요.`,
|
|
82
|
+
pendingNotCleared: (reason) => `(계정의 진행 중 표시를 지우지 못했습니다: ${reason}. 다음 호출에서 이 계정이 막히면 표시 파일을 확인하세요.)`,
|
|
83
|
+
accountUnresolved: (p) => `${p} 의 대상 계정을 확인할 수 없습니다 (연결 또는 옵션을 확인하세요).`,
|
|
84
|
+
pendingTakenOver: '(이 호출의 잠금이 오래 멈춘 사이 다른 호출이 이 계정에 게시를 시작해 계정 표시를 바꿨습니다. 이 결과는 계정 표시에 남지 않았으니 플랫폼에서 직접 확인하세요.)',
|
|
85
|
+
postedUnrecorded: (p, at, reason) => `게시됐지만 기록하지 못했습니다 (${reason}). 다음 호출에서 이 계정은 "결과 알 수 없음"으로 막힙니다. ${p} 에서 게시물을 확인한 뒤 markPosted: [{ "platform": "${p}", "at": "${at}" }] 를 넘기면 풀립니다.`,
|
|
86
|
+
privacy: (p) => `공개 상태: ${p}`,
|
|
87
|
+
youtubeAngle: 'YouTube 제목·설명·태그에는 < 와 > 를 쓸 수 없습니다.',
|
|
88
|
+
preflightFailed: (p, msg) => `게시 전 확인 실패 (${p}): ${msg}`,
|
|
89
|
+
notSentPreflight: (p) => `보내지 않음: ${p} 의 게시 전 확인이 실패해 어느 플랫폼에도 게시하지 않았습니다.`,
|
|
90
|
+
youtubeFileMissing: (f) => `영상 파일을 찾을 수 없거나 비어 있습니다: ${f}`,
|
|
91
|
+
youtubeFileType: 'YouTube 영상은 .mp4, .mov, .webm 만 올릴 수 있습니다.',
|
|
92
|
+
markedPosted: (at) => `이전 게시(${at})는 확인 결과 올라가 있음 — 게시됨으로 기록`,
|
|
93
|
+
planBlocked: '검증을 통과하지 못한 계획은 게시하지 않습니다.',
|
|
94
|
+
notSentNoLedger: (reason) => `게시 기록을 쓸 수 없어 보내지 않았습니다 (${reason}). 기록 문제를 고친 뒤 다시 보내세요.`,
|
|
95
|
+
youtubeFileChanged: '사전 확인 뒤 영상 파일이 바뀌었습니다 (크기·수정 시각). 파일이 다 써진 뒤 다시 보내세요.',
|
|
96
|
+
tiktokCaption: '캡션은 TikTok 계획에 저장된 값을 씁니다 (text 무시).',
|
|
97
|
+
}, {
|
|
98
|
+
duplicateTarget: (p) => `${p} is listed twice in targets.`,
|
|
99
|
+
notConnected: (msg) => `Not connected: ${msg} — connect it, or drop this platform from targets to post to the others.`,
|
|
100
|
+
textTooLong: (platform, max, len) => `The text is over ${max} characters (${len}). Set ${platform}.text separately.`,
|
|
101
|
+
textRequired: 'The text is empty.',
|
|
102
|
+
needsImages: (p, max) => `${p} needs images (1–${max} public HTTPS imageUrls). Text-only and video posts are not supported.`,
|
|
103
|
+
tooManyImages: (max, n) => `Too many images (${n}, at most ${max}).`,
|
|
104
|
+
imageAndVideo: 'Threads cannot post images and a video together. Pass either imageUrls or videoUrl.',
|
|
105
|
+
youtubeOptions: 'YouTube needs youtube options (expectedChannelId is required).',
|
|
106
|
+
youtubeFile: 'YouTube needs a local video file (videoFilePath).',
|
|
107
|
+
youtubeTitle: 'The YouTube title is empty or over 100 characters. Set youtube.title.',
|
|
108
|
+
youtubeDescription: 'The YouTube description is over 5,000 characters. Set youtube.description.',
|
|
109
|
+
youtubeTags: 'The YouTube tags joined with commas are over 500 characters.',
|
|
110
|
+
youtubeNotSignedIn: (profile) => `YouTube is not signed in${profile ? ` (profile ${profile})` : ''}. Connect it with mimi-seed auth social.`,
|
|
111
|
+
youtubeNoUpload: (profile) => `The Google login${profile ? ` (profile ${profile})` : ''} lacks the YouTube upload permission. Add it with mimi-seed auth login${profile ? ` --profile ${profile}` : ''} --domains youtube.`,
|
|
112
|
+
tiktokPlan: 'TikTok needs a planId made by tiktok_business_plan_video_post (tiktok.planId).',
|
|
113
|
+
tiktokPlanInvalid: (msg) => `Cannot use the TikTok plan: ${msg}`,
|
|
114
|
+
previousUnknown: (p, at) => `The outcome of the previous attempt (${at}) is unknown — it may have been posted. Check ${p}: if it is there, send with markPosted: [{ "platform": "${p}", "at": "${at}" }]; if not, with resendUnknown: [{ "platform": "${p}", "at": "${at}" }].`,
|
|
115
|
+
resendingUnknown: (at) => `the previous attempt (${at}) had an unknown outcome; resending after a check (resendUnknown)`,
|
|
116
|
+
accountPending: (p, at) => `This ${p} account has an earlier send (${at}) whose outcome is unknown — blocked even for different content. Check ${p}: if it is there, send with markPosted: [{ "platform": "${p}", "at": "${at}" }]; if not, with resendUnknown: [{ "platform": "${p}", "at": "${at}" }].`,
|
|
117
|
+
reposting: (at) => `the same content was already posted (${at}) — posting it again (repost)`,
|
|
118
|
+
alreadyPostedHint: (p, at) => `already posted (${at}) — skipped. To post it again on purpose: repost: [{ "platform": "${p}", "at": "${at}" }]`,
|
|
119
|
+
alreadyPostedTikTok: (at) => `already posted (${at}) — skipped. To post to TikTok again, make a new plan with tiktok_business_plan_video_post.`,
|
|
120
|
+
pendingNotCleared: (reason) => `(The account's pending marker could not be cleared: ${reason}. If the next call is blocked for this account, check that file.)`,
|
|
121
|
+
accountUnresolved: (p) => `Cannot tell which ${p} account to post to (check its connection or options).`,
|
|
122
|
+
pendingTakenOver: '(While this call\'s lock was stalled, another call started publishing to this account and replaced its marker. This outcome is not on the marker: check the platform directly.)',
|
|
123
|
+
postedUnrecorded: (p, at, reason) => `Posted, but it could not be recorded (${reason}). The next call will find this account blocked as "outcome unknown". Check the post on ${p}, then pass markPosted: [{ "platform": "${p}", "at": "${at}" }] to clear it.`,
|
|
124
|
+
privacy: (p) => `privacy: ${p}`,
|
|
125
|
+
youtubeAngle: 'YouTube titles, descriptions, and tags cannot contain < or >.',
|
|
126
|
+
preflightFailed: (p, msg) => `Pre-send check failed (${p}): ${msg}`,
|
|
127
|
+
notSentPreflight: (p) => `Not sent: the pre-send check for ${p} failed, so nothing was posted anywhere.`,
|
|
128
|
+
youtubeFileMissing: (f) => `The video file is missing or empty: ${f}`,
|
|
129
|
+
youtubeFileType: 'YouTube uploads must be .mp4, .mov, or .webm.',
|
|
130
|
+
markedPosted: (at) => `the earlier send (${at}) was checked and is live — recorded as posted`,
|
|
131
|
+
planBlocked: 'A plan that failed validation is never published.',
|
|
132
|
+
notSentNoLedger: (reason) => `Not sent: the publish record cannot be written (${reason}). Fix it, then send again.`,
|
|
133
|
+
youtubeFileChanged: 'The video file changed after the pre-send check (size or modification time). Send again once it is fully written.',
|
|
134
|
+
tiktokCaption: 'The caption comes from the TikTok plan (text is ignored).',
|
|
135
|
+
});
|
|
136
|
+
const TEXT_LIMIT = { facebook: 63_206, instagram: 2_200, threads: 500 };
|
|
137
|
+
const IMAGE_LIMIT = { facebook: 10, instagram: 10, threads: 20 };
|
|
138
|
+
/** The Page or account a Meta profile resolves to (project mapping, default file), or null when not connected. */
|
|
139
|
+
function metaAccount(platform, input) {
|
|
140
|
+
const profile = input[platform]?.profile;
|
|
141
|
+
try {
|
|
142
|
+
return platform === 'facebook'
|
|
143
|
+
? `page:${requireFacebookConfig({ profile }).pageId}`
|
|
144
|
+
: `user:${(platform === 'instagram' ? requireInstagramConfig : requireThreadsConfig)({ profile }).userId}`;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
// Not connected: targetKey/accountKey return null, and the plan blocks the target (connect it or drop it).
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The identity of one post: exactly what one platform would receive (the account, text, media, and options). Null
|
|
153
|
+
* when a Meta target's account cannot be resolved (not connected): its identity is unknown, and the plan blocks it.
|
|
154
|
+
*/
|
|
155
|
+
export function targetKey(platform, input,
|
|
156
|
+
/** The video file's identity, captured once per call so the key and the upload check describe the same file. */
|
|
157
|
+
videoFile = input.videoFilePath ? fileIdentity(input.videoFilePath) : null) {
|
|
158
|
+
const images = input.imageUrls ?? [];
|
|
159
|
+
const payload = platform === 'youtube'
|
|
160
|
+
? {
|
|
161
|
+
youtube: input.youtube ?? null,
|
|
162
|
+
title: youtubeTitle(input),
|
|
163
|
+
description: input.youtube?.description ?? input.text,
|
|
164
|
+
// The path alone would treat a re-rendered file as the same video: include its size and modification time.
|
|
165
|
+
videoFile: input.videoFilePath ? { path: input.videoFilePath, ...videoFile } : null,
|
|
166
|
+
}
|
|
167
|
+
: platform === 'tiktok'
|
|
168
|
+
? { planId: input.tiktok?.planId ?? null }
|
|
169
|
+
: {
|
|
170
|
+
// The account the profile resolves to (project mapping, default file), not just the requested name: the same
|
|
171
|
+
// content for another Page or account is a different post.
|
|
172
|
+
account: metaAccount(platform, input) ?? UNRESOLVED,
|
|
173
|
+
text: input[platform]?.text ?? input.text,
|
|
174
|
+
images,
|
|
175
|
+
videoUrl: platform === 'threads' ? input.videoUrl ?? null : null,
|
|
176
|
+
};
|
|
177
|
+
if (payload.account === UNRESOLVED)
|
|
178
|
+
return null;
|
|
179
|
+
return createHash('sha256').update(JSON.stringify({ platform, payload })).digest('hex');
|
|
180
|
+
}
|
|
181
|
+
const UNRESOLVED = Symbol('unresolved account');
|
|
182
|
+
/**
|
|
183
|
+
* The account a target posts to: the resolved Page/user (Meta), the channel (YouTube), the TikTok account the plan
|
|
184
|
+
* belongs to. Null when it cannot be resolved; the plan blocks such a target.
|
|
185
|
+
*/
|
|
186
|
+
export function accountKey(platform, input) {
|
|
187
|
+
if (platform === 'youtube')
|
|
188
|
+
return input.youtube ? `channel:${input.youtube.expectedChannelId}` : null;
|
|
189
|
+
// The connected TikTok account (publishing refuses a plan made for another one). Read from the config, not the plan:
|
|
190
|
+
// a published or expired plan must still resolve, or a retry could never skip it.
|
|
191
|
+
if (platform === 'tiktok') {
|
|
192
|
+
const openId = loadTikTokBusinessConfig()?.openId;
|
|
193
|
+
return input.tiktok && openId ? `openid:${openId}` : null;
|
|
194
|
+
}
|
|
195
|
+
return metaAccount(platform, input);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* An error raised after the request may already have taken effect (e.g. a YouTube upload that failed while reading
|
|
199
|
+
* the response). Recorded as `unknown`, never `failed`, so a retry cannot publish the same post twice.
|
|
200
|
+
*/
|
|
201
|
+
class AmbiguousOutcomeError extends Error {
|
|
202
|
+
original;
|
|
203
|
+
constructor(original) {
|
|
204
|
+
super(original instanceof Error ? original.message : String(original), { cause: original });
|
|
205
|
+
this.original = original;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function isAmbiguous(error) {
|
|
209
|
+
return error instanceof AmbiguousOutcomeError;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Runs one platform's publishing call and classifies a failure by **whether the publishing request had been sent**.
|
|
213
|
+
* Each platform function calls onPublishStart right before the request that makes the post visible (Meta's publish
|
|
214
|
+
* step, YouTube's upload, TikTok's publish). Before it, any failure — a timeout, a dropped
|
|
215
|
+
* connection, a rejected container — published nothing and is a clean `failed`. After it, only a definite rejection
|
|
216
|
+
* (`definite(error)`) proves nothing was published; anything else (a 5xx, a timeout, a lost response, a write that
|
|
217
|
+
* failed after success) is ambiguous and recorded `unknown`, so it is never resent.
|
|
218
|
+
*/
|
|
219
|
+
async function tracked(run, definite) {
|
|
220
|
+
let started = false;
|
|
221
|
+
try {
|
|
222
|
+
return await run(() => { started = true; });
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
if (started && !definite(error))
|
|
226
|
+
throw new AmbiguousOutcomeError(error);
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** Meta answered the publishing request with a 4xx: it refused it, so nothing was published. */
|
|
231
|
+
const metaRejected = (error) => {
|
|
232
|
+
const status = metaErrorStatus(error);
|
|
233
|
+
return status !== undefined && status >= 400 && status < 500;
|
|
234
|
+
};
|
|
235
|
+
/** TikTok's known failures are rethrown as-is; its unknown outcomes are wrapped or flagged. */
|
|
236
|
+
const tiktokRejected = (error) => error instanceof TikTokApiError && !error.outcomeUnknown;
|
|
237
|
+
/**
|
|
238
|
+
* Google answered the upload with a 4xx (quotaExceeded, uploadLimitExceeded, invalidTitle, …): it refused it, so no
|
|
239
|
+
* video was created. friendlyGoogleError keeps the original error as `cause`, which carries the status.
|
|
240
|
+
*/
|
|
241
|
+
const youtubeRejected = (error) => {
|
|
242
|
+
const status = extractHttpStatus(error) ?? extractHttpStatus(error?.cause);
|
|
243
|
+
return status !== undefined && status >= 400 && status < 500;
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Replaces (or, for null, clears) this send's own account marker — compare-and-set, so a marker another call wrote
|
|
247
|
+
* meanwhile is never erased. Returns a note to report instead of throwing (callers keep their own error), or null.
|
|
248
|
+
*/
|
|
249
|
+
function settlePending(platform, account, ours, next) {
|
|
250
|
+
try {
|
|
251
|
+
return replacePendingIfOurs(platform, account, ours, next) ? null : M().pendingTakenOver;
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
return M().pendingNotCleared(errorText(error));
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* `base` (default: now), but always after every `previous`. An approval names a record or marker by its `at`, so
|
|
259
|
+
* whatever a send writes must carry an `at` the record and marker it replaces did not — even within one millisecond
|
|
260
|
+
* or after the clock stepped back — or an approval for the old one (repost, resendUnknown) would still match the new.
|
|
261
|
+
*/
|
|
262
|
+
function laterThan(previous, base = Date.now()) {
|
|
263
|
+
const floors = previous.map((at) => (at === undefined ? Number.NaN : Date.parse(at) + 1)).filter((ms) => !Number.isNaN(ms));
|
|
264
|
+
return new Date(Math.max(base, ...floors)).toISOString();
|
|
265
|
+
}
|
|
266
|
+
/** The `at` a marked-posted send gets: its own, moved past an earlier `posted` record so a repost approval is used up. */
|
|
267
|
+
function markedAt(pendingAt, itsPost) {
|
|
268
|
+
return itsPost?.state === 'posted' ? laterThan([itsPost.at], Date.parse(pendingAt)) : pendingAt;
|
|
269
|
+
}
|
|
270
|
+
function errorText(error) {
|
|
271
|
+
return (error instanceof Error ? error.message : String(error)).slice(0, 500);
|
|
272
|
+
}
|
|
273
|
+
function metaTextProblems(platform, text) {
|
|
274
|
+
const max = TEXT_LIMIT[platform];
|
|
275
|
+
return text.length > max ? [M().textTooLong(platform, max, text.length)] : [];
|
|
276
|
+
}
|
|
277
|
+
function planMeta(platform, input) {
|
|
278
|
+
const options = input[platform];
|
|
279
|
+
const text = options?.text ?? input.text;
|
|
280
|
+
const images = input.imageUrls ?? [];
|
|
281
|
+
const problems = metaTextProblems(platform, text);
|
|
282
|
+
try {
|
|
283
|
+
const load = { facebook: requireFacebookConfig, instagram: requireInstagramConfig, threads: requireThreadsConfig }[platform];
|
|
284
|
+
load({ profile: options?.profile });
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
problems.push(M().notConnected(errorText(error)));
|
|
288
|
+
}
|
|
289
|
+
if (images.length > IMAGE_LIMIT[platform])
|
|
290
|
+
problems.push(M().tooManyImages(IMAGE_LIMIT[platform], images.length));
|
|
291
|
+
if (platform === 'threads') {
|
|
292
|
+
if (input.videoUrl && images.length > 0)
|
|
293
|
+
problems.push(M().imageAndVideo);
|
|
294
|
+
if (!input.videoUrl && images.length === 0 && !text.trim())
|
|
295
|
+
problems.push(M().textRequired);
|
|
296
|
+
const action = input.videoUrl ? 'threads video'
|
|
297
|
+
: images.length > 1 ? `threads carousel (${images.length} images)`
|
|
298
|
+
: images.length === 1 ? 'threads image' : 'threads text';
|
|
299
|
+
return { platform, action, text, media: input.videoUrl ? [input.videoUrl] : images, problems };
|
|
300
|
+
}
|
|
301
|
+
if (images.length === 0)
|
|
302
|
+
problems.push(M().needsImages(platform, IMAGE_LIMIT[platform]));
|
|
303
|
+
const action = images.length > 1 ? `${platform} ${platform === 'facebook' ? 'multi-photo' : 'carousel'} (${images.length} images)` : `${platform} photo`;
|
|
304
|
+
return { platform, action, text, media: images, problems };
|
|
305
|
+
}
|
|
306
|
+
function fileIdentity(file) {
|
|
307
|
+
try {
|
|
308
|
+
const stat = fs.statSync(file);
|
|
309
|
+
return { size: stat.size, mtimeMs: Math.trunc(stat.mtimeMs) };
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
// A missing file is part of the identity too; the plan reports it as a problem separately.
|
|
313
|
+
return { missing: true };
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function fileSize(file) {
|
|
317
|
+
try {
|
|
318
|
+
const stat = fs.statSync(file);
|
|
319
|
+
return stat.isFile() ? stat.size : 0;
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
// A path that cannot be stat'ed is reported as missing (size 0); the plan then blocks the publish.
|
|
323
|
+
return 0;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function youtubeTitle(input) {
|
|
327
|
+
return input.youtube?.title ?? input.text.split('\n').map((l) => l.trim()).find(Boolean) ?? '';
|
|
328
|
+
}
|
|
329
|
+
function planYouTube(input) {
|
|
330
|
+
const yt = input.youtube;
|
|
331
|
+
const problems = [];
|
|
332
|
+
if (!yt)
|
|
333
|
+
problems.push(M().youtubeOptions);
|
|
334
|
+
if (!input.videoFilePath) {
|
|
335
|
+
problems.push(M().youtubeFile);
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
// Local checks only — the same ones the upload makes first — so a typo is caught before approval.
|
|
339
|
+
if (fileSize(input.videoFilePath) <= 0)
|
|
340
|
+
problems.push(M().youtubeFileMissing(input.videoFilePath));
|
|
341
|
+
if (!['.mp4', '.mov', '.webm'].includes(path.extname(input.videoFilePath).toLowerCase()))
|
|
342
|
+
problems.push(M().youtubeFileType);
|
|
343
|
+
}
|
|
344
|
+
const title = youtubeTitle(input);
|
|
345
|
+
if (!title.trim() || title.length > 100)
|
|
346
|
+
problems.push(M().youtubeTitle);
|
|
347
|
+
const description = yt?.description ?? input.text;
|
|
348
|
+
if (description.length > 5_000)
|
|
349
|
+
problems.push(M().youtubeDescription);
|
|
350
|
+
// Same rule as the upload's tag check, so YouTube cannot fail after the other platforms have posted.
|
|
351
|
+
if ((yt?.tags ?? []).join(',').length > 500)
|
|
352
|
+
problems.push(M().youtubeTags);
|
|
353
|
+
if (/[<>]/.test(title) || /[<>]/.test(description) || (yt?.tags ?? []).some((tag) => /[<>]/.test(tag)))
|
|
354
|
+
problems.push(M().youtubeAngle);
|
|
355
|
+
if (yt) {
|
|
356
|
+
// The stored grant only (no network): a missing login or a grant without the upload permission would fail later.
|
|
357
|
+
const tokens = getStoredTokens(yt.profile);
|
|
358
|
+
if (!tokens?.refresh_token)
|
|
359
|
+
problems.push(M().youtubeNotSignedIn(yt.profile));
|
|
360
|
+
else if (tokens.scope && !summarizeGrantedDomains(tokens.scope).granted.includes('youtube'))
|
|
361
|
+
problems.push(M().youtubeNoUpload(yt.profile));
|
|
362
|
+
}
|
|
363
|
+
const privacy = yt?.privacyStatus ?? 'private';
|
|
364
|
+
return {
|
|
365
|
+
platform: 'youtube',
|
|
366
|
+
action: `youtube upload — ${M().privacy(privacy)}`,
|
|
367
|
+
text: `${title}\n\n${description}`,
|
|
368
|
+
media: input.videoFilePath ? [input.videoFilePath] : [],
|
|
369
|
+
problems,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function planTikTok(input) {
|
|
373
|
+
const problems = [];
|
|
374
|
+
let caption;
|
|
375
|
+
if (!input.tiktok?.planId) {
|
|
376
|
+
problems.push(M().tiktokPlan);
|
|
377
|
+
}
|
|
378
|
+
else {
|
|
379
|
+
try {
|
|
380
|
+
// Every local check publishPlannedVideo makes (plan, account, duplicate audit), so TikTok cannot fail after
|
|
381
|
+
// the other platforms have posted.
|
|
382
|
+
caption = preflightPlannedVideo(input.tiktok.planId).request.post_info.caption;
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
problems.push(M().tiktokPlanInvalid(errorText(error)));
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return { platform: 'tiktok', action: `tiktok planned video — ${M().tiktokCaption}`, text: caption, problems };
|
|
389
|
+
}
|
|
390
|
+
const approves = (list, platform, at) => list.some((a) => a.platform === platform && a.at === at);
|
|
391
|
+
/** The single rule — the table at the top of this file. Same answer in the plan, under the lock, and before each send. */
|
|
392
|
+
export function decide(platform, record, pending, { resendUnknown, repost }) {
|
|
393
|
+
// A skip sends nothing, so nothing else (another call's pending send, a lock) can stand in its way.
|
|
394
|
+
const reposting = record?.state === 'posted' && approves(repost, platform, record.at);
|
|
395
|
+
if (record?.state === 'posted' && !reposting) {
|
|
396
|
+
return { kind: 'skip', outcome: { platform, status: 'already_posted', id: record.id, url: record.url, at: record.at } };
|
|
397
|
+
}
|
|
398
|
+
if (pending && !approves(resendUnknown, platform, pending.at)) {
|
|
399
|
+
return { kind: 'block', problem: M().accountPending(platform, pending.at) };
|
|
400
|
+
}
|
|
401
|
+
if (reposting && record)
|
|
402
|
+
return { kind: 'send', note: M().reposting(record.at) };
|
|
403
|
+
if (record?.state === 'sending' || record?.state === 'unknown') {
|
|
404
|
+
if (approves(resendUnknown, platform, record.at))
|
|
405
|
+
return { kind: 'send', note: M().resendingUnknown(record.at) };
|
|
406
|
+
// The marker for this record is already approved above; an older record without a marker needs its own approval.
|
|
407
|
+
if (!pending || pending.at !== record.at)
|
|
408
|
+
return { kind: 'block', problem: M().previousUnknown(platform, record.at) };
|
|
409
|
+
}
|
|
410
|
+
if (pending)
|
|
411
|
+
return { kind: 'send', note: M().resendingUnknown(pending.at) };
|
|
412
|
+
return { kind: 'send' };
|
|
413
|
+
}
|
|
414
|
+
const options = (input) => ({ resendUnknown: input.resendUnknown ?? [], repost: input.repost ?? [], markPosted: input.markPosted ?? [] });
|
|
415
|
+
/**
|
|
416
|
+
* What the records say once a person's markPosted approvals are applied: a pending send they found live is posted
|
|
417
|
+
* (and no longer blocks its account), and so is an older unknown record they named. executePublish writes exactly
|
|
418
|
+
* this to disk (persistMarks) before deciding, so the plan and the publish agree.
|
|
419
|
+
*/
|
|
420
|
+
function applyMarks(platform, key, record, pending, opts) {
|
|
421
|
+
let marked = null;
|
|
422
|
+
let view = { record, pending };
|
|
423
|
+
if (pending && approves(opts.markPosted, platform, pending.at)) {
|
|
424
|
+
marked = pending.at;
|
|
425
|
+
// The marked send becomes this post's latest `posted` record — a repost's too (keeping the original's id/url), so
|
|
426
|
+
// the repost approval that named the older `at` is used up and cannot send the post once more.
|
|
427
|
+
view = {
|
|
428
|
+
record: pending.postKey === key ? { ...(record?.state === 'posted' ? record : {}), state: 'posted', at: markedAt(pending.at, record) } : record,
|
|
429
|
+
pending: null,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
if (view.record && (view.record.state === 'unknown' || view.record.state === 'sending') && approves(opts.markPosted, platform, view.record.at)) {
|
|
433
|
+
marked = view.record.at;
|
|
434
|
+
view = { ...view, record: { ...view.record, state: 'posted' } };
|
|
435
|
+
}
|
|
436
|
+
return { ...view, marked };
|
|
437
|
+
}
|
|
438
|
+
/** No network: config files, the TikTok plan file, and the post and account records are all local. */
|
|
439
|
+
export function planPublish(input) {
|
|
440
|
+
const seen = new Set();
|
|
441
|
+
const posts = input.targets.map((platform) => {
|
|
442
|
+
const post = platform === 'youtube' ? planYouTube(input)
|
|
443
|
+
: platform === 'tiktok' ? planTikTok(input)
|
|
444
|
+
: planMeta(platform, input);
|
|
445
|
+
const duplicate = seen.has(platform);
|
|
446
|
+
seen.add(platform);
|
|
447
|
+
const key = targetKey(platform, input);
|
|
448
|
+
// Null: not connected, already reported by the platform's own plan check.
|
|
449
|
+
if (key !== null) {
|
|
450
|
+
const record = readRecord(platform, key);
|
|
451
|
+
if (record)
|
|
452
|
+
post.record = record;
|
|
453
|
+
const resolved = resolveDecision(platform, key, record, input);
|
|
454
|
+
if (resolved.view.pending)
|
|
455
|
+
post.pending = resolved.view.pending;
|
|
456
|
+
const { decision } = resolved;
|
|
457
|
+
const markNote = resolved.view.marked ? M().markedPosted(resolved.view.marked) : null;
|
|
458
|
+
if (decision.kind === 'skip') {
|
|
459
|
+
// It will not be sent, so its current state (an expired token or TikTok plan, a pending send of other
|
|
460
|
+
// content, another call's lock) must not block the others.
|
|
461
|
+
// TikTok's own duplicate guard refuses a published plan, so a repost there needs a new plan instead.
|
|
462
|
+
const at = resolved.view.record.at;
|
|
463
|
+
post.action = platform === 'tiktok' ? M().alreadyPostedTikTok(at) : M().alreadyPostedHint(platform, at);
|
|
464
|
+
post.problems = [];
|
|
465
|
+
}
|
|
466
|
+
else if (resolved.locked) {
|
|
467
|
+
// A live lock is not a crash: another call is publishing to this account right now.
|
|
468
|
+
post.problems.push(inProgressMessage());
|
|
469
|
+
}
|
|
470
|
+
else if (decision.kind === 'block') {
|
|
471
|
+
// An unresolved account is already explained by the platform's own check; only say it if nothing else did.
|
|
472
|
+
if (!resolved.unresolved || post.problems.length === 0)
|
|
473
|
+
post.problems.push(decision.problem);
|
|
474
|
+
}
|
|
475
|
+
else if (decision.note) {
|
|
476
|
+
post.action = `${post.action} — ${decision.note}`;
|
|
477
|
+
}
|
|
478
|
+
if (markNote)
|
|
479
|
+
post.action = `${post.action} — ${markNote}`;
|
|
480
|
+
}
|
|
481
|
+
if (duplicate)
|
|
482
|
+
post.problems.push(M().duplicateTarget(platform));
|
|
483
|
+
return post;
|
|
484
|
+
});
|
|
485
|
+
return { ok: posts.every((p) => p.problems.length === 0), posts };
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* decide() with the account only when it matters: a post that is only skipped needs neither the account, its
|
|
489
|
+
* pending marker, nor its lock (a published TikTok plan, a disconnected account, another call's send).
|
|
490
|
+
*/
|
|
491
|
+
function resolveDecision(platform, key, record, input) {
|
|
492
|
+
const opts = options(input);
|
|
493
|
+
const own = applyMarks(platform, key, record, null, opts);
|
|
494
|
+
const skipOnly = decide(platform, own.record, null, opts);
|
|
495
|
+
if (skipOnly.kind === 'skip')
|
|
496
|
+
return { decision: skipOnly, account: null, view: own, locked: false, unresolved: false };
|
|
497
|
+
const account = accountKey(platform, input);
|
|
498
|
+
if (account === null) {
|
|
499
|
+
// The platform's own plan check normally says why (no youtube options, TikTok not connected); this is the fallback.
|
|
500
|
+
const decision = { kind: 'block', problem: M().accountUnresolved(platform) };
|
|
501
|
+
return { decision, account, view: own, locked: false, unresolved: true };
|
|
502
|
+
}
|
|
503
|
+
const view = applyMarks(platform, key, record, effectivePending(platform, account), opts);
|
|
504
|
+
return { decision: decide(platform, view.record, view.pending, opts), account, view, locked: isAccountLocked(platform, account), unresolved: false };
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* The account's pending marker, unless the send it names did finish: when that send's own outcome was recorded
|
|
508
|
+
* (`posted`, cleanly `failed`, or marked posted — the record's settledAttempt is the marker's attempt), the marker
|
|
509
|
+
* only failed to be cleared and must not block the account as "outcome unknown". Matched by attempt id, not by time:
|
|
510
|
+
* a repost's marker can carry the same millisecond as — or, after a clock step, an earlier one than — the `posted`
|
|
511
|
+
* record it reposts, and must still block until its own outcome is known.
|
|
512
|
+
*/
|
|
513
|
+
function effectivePending(platform, account) {
|
|
514
|
+
const pending = readPending(platform, account);
|
|
515
|
+
if (!pending)
|
|
516
|
+
return null;
|
|
517
|
+
const itsPost = readRecord(platform, pending.postKey);
|
|
518
|
+
const settled = (itsPost?.state === 'posted' || itsPost?.state === 'failed')
|
|
519
|
+
&& pending.attempt !== undefined && itsPost.settledAttempt === pending.attempt;
|
|
520
|
+
return settled ? null : pending;
|
|
521
|
+
}
|
|
522
|
+
function youtubeUploadInput(input) {
|
|
523
|
+
const yt = input.youtube;
|
|
524
|
+
const privacyStatus = yt.privacyStatus ?? 'private';
|
|
525
|
+
return {
|
|
526
|
+
expectedChannelId: yt.expectedChannelId,
|
|
527
|
+
filePath: input.videoFilePath,
|
|
528
|
+
title: youtubeTitle(input),
|
|
529
|
+
description: yt.description ?? input.text,
|
|
530
|
+
tags: yt.tags,
|
|
531
|
+
privacyStatus,
|
|
532
|
+
madeForKids: yt.madeForKids ?? false,
|
|
533
|
+
containsSyntheticMedia: yt.containsSyntheticMedia,
|
|
534
|
+
// The person approved this exact plan (privacy shown in it) through social_publish's confirm gate.
|
|
535
|
+
confirmVisible: privacyStatus !== 'private',
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* The network-side checks each platform's publish makes before sending: a live token (Meta), the sign-in, channel
|
|
540
|
+
* and video stream (YouTube), the publish scope and the plan (TikTok). Run for every target before sending to any.
|
|
541
|
+
*/
|
|
542
|
+
async function preflight(platform, input, prepared) {
|
|
543
|
+
switch (platform) {
|
|
544
|
+
case 'facebook':
|
|
545
|
+
await facebook.getPage(requireFacebookConfig({ profile: input.facebook?.profile }));
|
|
546
|
+
return;
|
|
547
|
+
case 'instagram':
|
|
548
|
+
await instagram.getAccount(requireInstagramConfig({ profile: input.instagram?.profile }));
|
|
549
|
+
return;
|
|
550
|
+
case 'threads':
|
|
551
|
+
await threads.getAccount(requireThreadsConfig({ profile: input.threads?.profile }));
|
|
552
|
+
return;
|
|
553
|
+
case 'youtube': {
|
|
554
|
+
const auth = await requireAuth(YOUTUBE_SCOPE, input.youtube?.profile);
|
|
555
|
+
const upload = await prepareYouTubeUpload(auth, youtubeUploadInput(input));
|
|
556
|
+
// The file must still be the one the post's key was built from (captured once, before any check).
|
|
557
|
+
if (JSON.stringify(fileIdentity(input.videoFilePath)) !== JSON.stringify(prepared.videoFile))
|
|
558
|
+
throw new Error(M().youtubeFileChanged);
|
|
559
|
+
prepared.youtube = { auth, upload, file: prepared.videoFile };
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
case 'tiktok':
|
|
563
|
+
await ensureTikTokPublishConfig();
|
|
564
|
+
preflightPlannedVideo(input.tiktok.planId);
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
async function send(platform, input, post, prepared) {
|
|
569
|
+
const text = post.text ?? '';
|
|
570
|
+
const images = input.imageUrls ?? [];
|
|
571
|
+
switch (platform) {
|
|
572
|
+
case 'facebook': {
|
|
573
|
+
const cfg = requireFacebookConfig({ profile: input.facebook?.profile });
|
|
574
|
+
const r = await tracked((onPublishStart) => (images.length > 1
|
|
575
|
+
? facebook.postMultiPhoto(cfg, images, text, { onPublishStart })
|
|
576
|
+
: facebook.postPhoto(cfg, images[0], text, { onPublishStart })), metaRejected);
|
|
577
|
+
return { id: r.id, url: r.permalink };
|
|
578
|
+
}
|
|
579
|
+
case 'instagram': {
|
|
580
|
+
const cfg = requireInstagramConfig({ profile: input.instagram?.profile });
|
|
581
|
+
const r = await tracked((onPublishStart) => (images.length > 1
|
|
582
|
+
? instagram.postCarousel(cfg, images, text, { onPublishStart })
|
|
583
|
+
: instagram.postImage(cfg, images[0], text, { onPublishStart })), metaRejected);
|
|
584
|
+
return { id: r.id, url: r.permalink };
|
|
585
|
+
}
|
|
586
|
+
case 'threads': {
|
|
587
|
+
const cfg = requireThreadsConfig({ profile: input.threads?.profile });
|
|
588
|
+
const r = await tracked((onPublishStart) => (input.videoUrl
|
|
589
|
+
? threads.postVideo(cfg, input.videoUrl, text, undefined, { onPublishStart })
|
|
590
|
+
: images.length > 1
|
|
591
|
+
? threads.postCarousel(cfg, images, text, { onPublishStart })
|
|
592
|
+
: threads.postText(cfg, text, images[0], { onPublishStart })), metaRejected);
|
|
593
|
+
return { id: r.id, url: r.permalink };
|
|
594
|
+
}
|
|
595
|
+
case 'youtube': {
|
|
596
|
+
const auth = prepared.youtube?.auth ?? await requireAuth(YOUTUBE_SCOPE, input.youtube.profile);
|
|
597
|
+
// Other platforms may have taken minutes. A file still being written would upload bytes nobody checked, and its
|
|
598
|
+
// fingerprint (in targetKey) would no longer match: refuse before the upload starts, which is a clean failure.
|
|
599
|
+
if (prepared.youtube && JSON.stringify(fileIdentity(input.videoFilePath)) !== JSON.stringify(prepared.youtube.file)) {
|
|
600
|
+
throw new Error(M().youtubeFileChanged);
|
|
601
|
+
}
|
|
602
|
+
// After the upload starts, only a 4xx proves no video was created.
|
|
603
|
+
const r = await tracked((onUploadStart) => uploadYouTubeVideo(auth, youtubeUploadInput(input), { onUploadStart }, prepared.youtube?.upload), youtubeRejected);
|
|
604
|
+
return { id: r.videoId ?? undefined, url: r.videoId ? `https://www.youtube.com/watch?v=${r.videoId}` : undefined };
|
|
605
|
+
}
|
|
606
|
+
case 'tiktok': {
|
|
607
|
+
const r = await tracked((onPublishStart) => publishPlannedVideo(input.tiktok.planId, true, { onPublishStart }), tiktokRejected);
|
|
608
|
+
return { id: r.publishId };
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Write the person's markPosted approvals (applyMarks) to disk, each under its account's lock: the approved pending
|
|
614
|
+
* send — or older unknown record — becomes `posted`, and that send's marker is cleared (compare-and-set). Nothing is
|
|
615
|
+
* sent for it.
|
|
616
|
+
*/
|
|
617
|
+
function persistMarks(input, videoFile) {
|
|
618
|
+
const marks = input.markPosted ?? [];
|
|
619
|
+
for (const platform of new Set(marks.map((m) => m.platform))) {
|
|
620
|
+
if (!input.targets.includes(platform))
|
|
621
|
+
continue;
|
|
622
|
+
const key = targetKey(platform, input, videoFile);
|
|
623
|
+
const account = accountKey(platform, input);
|
|
624
|
+
if (key === null || account === null)
|
|
625
|
+
continue;
|
|
626
|
+
const lock = acquireAccountLock(platform, account);
|
|
627
|
+
try {
|
|
628
|
+
const pending = readPending(platform, account);
|
|
629
|
+
if (pending && approves(marks, platform, pending.at)) {
|
|
630
|
+
// Also when the post is already `posted` (the marker is a repost's): move its `at` forward, so a repost
|
|
631
|
+
// approval naming the older `at` no longer matches (same as applyMarks).
|
|
632
|
+
const itsPost = readRecord(platform, pending.postKey);
|
|
633
|
+
writeRecord(platform, pending.postKey, { ...(itsPost?.state === 'posted' ? itsPost : {}), state: 'posted', at: markedAt(pending.at, itsPost), settledAttempt: pending.attempt });
|
|
634
|
+
replacePendingIfOurs(platform, account, pending, null);
|
|
635
|
+
}
|
|
636
|
+
const record = readRecord(platform, key);
|
|
637
|
+
if (record && (record.state === 'unknown' || record.state === 'sending') && approves(marks, platform, record.at)) {
|
|
638
|
+
writeRecord(platform, key, { ...record, state: 'posted' });
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
finally {
|
|
642
|
+
lock.release();
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Publish to every target in order. Call only with an approved plan whose `ok` is true.
|
|
648
|
+
* 1. Lock every account that a post will be sent to (posts that are only skipped need no lock), then re-apply
|
|
649
|
+
* decide() to the records under the locks.
|
|
650
|
+
* 2. Preflight every post that will be sent; if one fails, nothing is sent.
|
|
651
|
+
* 3. Before each publishing call, confirm the lock is still ours and decide() once more (a long earlier upload, or
|
|
652
|
+
* a suspend, may have let another call in); mark the account pending; send; record the outcome.
|
|
653
|
+
*/
|
|
654
|
+
export async function executePublish(input, plan) {
|
|
655
|
+
// The tool checks this too; refusing here keeps a future caller from posting a plan that failed validation.
|
|
656
|
+
if (!plan.ok)
|
|
657
|
+
throw new Error(M().planBlocked);
|
|
658
|
+
const opts = options(input);
|
|
659
|
+
const prepared = { videoFile: input.videoFilePath ? fileIdentity(input.videoFilePath) : null };
|
|
660
|
+
const locks = [];
|
|
661
|
+
try {
|
|
662
|
+
persistMarks(input, prepared.videoFile);
|
|
663
|
+
const decisions = plan.posts.map((post) => {
|
|
664
|
+
const { platform } = post;
|
|
665
|
+
const key = targetKey(platform, input, prepared.videoFile);
|
|
666
|
+
if (key === null)
|
|
667
|
+
throw new Error(M().planBlocked); // the plan already blocks these
|
|
668
|
+
const { decision: preliminary, account, locked } = resolveDecision(platform, key, readRecord(platform, key), input);
|
|
669
|
+
// Blocked because a send to this account is still running: say so, rather than "outcome unknown".
|
|
670
|
+
if (preliminary.kind === 'block' && locked)
|
|
671
|
+
throw new Error(inProgressMessage());
|
|
672
|
+
let lock = null;
|
|
673
|
+
if (preliminary.kind === 'send' && account !== null) {
|
|
674
|
+
lock = acquireAccountLock(platform, account);
|
|
675
|
+
locks.push(lock);
|
|
676
|
+
}
|
|
677
|
+
// Re-read under the lock: a concurrent call may have changed the records since the plan was made.
|
|
678
|
+
const decision = lock && account !== null
|
|
679
|
+
? decide(platform, readRecord(platform, key), effectivePending(platform, account), opts)
|
|
680
|
+
: preliminary;
|
|
681
|
+
return { post, key, account: account ?? '', lock, decision };
|
|
682
|
+
});
|
|
683
|
+
const blocked = decisions.find((d) => d.decision.kind === 'block');
|
|
684
|
+
if (blocked && blocked.decision.kind === 'block')
|
|
685
|
+
throw new Error(blocked.decision.problem);
|
|
686
|
+
// Preflight every post that will be sent, before sending to any.
|
|
687
|
+
for (const { post, decision } of decisions) {
|
|
688
|
+
if (decision.kind !== 'send')
|
|
689
|
+
continue;
|
|
690
|
+
try {
|
|
691
|
+
await preflight(post.platform, input, prepared);
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
const reason = M().preflightFailed(post.platform, errorText(error));
|
|
695
|
+
return decisions.map(({ post: p, decision: d }) => (d.kind === 'skip'
|
|
696
|
+
? d.outcome
|
|
697
|
+
: { platform: p.platform, status: 'failed', error: p.platform === post.platform ? reason : M().notSentPreflight(post.platform) }));
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
const outcomes = [];
|
|
701
|
+
let ledgerBroken = null;
|
|
702
|
+
for (const { post, key, account, lock, decision } of decisions) {
|
|
703
|
+
const { platform } = post;
|
|
704
|
+
if (decision.kind === 'skip' || !lock) {
|
|
705
|
+
if (decision.kind === 'skip')
|
|
706
|
+
outcomes.push(decision.outcome);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (ledgerBroken) {
|
|
710
|
+
// Nothing can be recorded, so nothing more is sent: a resend could not be told apart from a first send.
|
|
711
|
+
outcomes.push({ platform, status: 'failed', error: M().notSentNoLedger(ledgerBroken) });
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
// Last check before the publishing call: still our lock, and still a send by the rule.
|
|
715
|
+
let now;
|
|
716
|
+
let current;
|
|
717
|
+
let replacedMarkerAt;
|
|
718
|
+
try {
|
|
719
|
+
lock.confirmHeld();
|
|
720
|
+
current = readRecord(platform, key);
|
|
721
|
+
// The raw marker (even one effectivePending ignores) is overwritten below: the new one must not reuse its `at`.
|
|
722
|
+
replacedMarkerAt = readPending(platform, account)?.at;
|
|
723
|
+
now = decide(platform, current, effectivePending(platform, account), opts);
|
|
724
|
+
}
|
|
725
|
+
catch (error) {
|
|
726
|
+
outcomes.push({ platform, status: 'failed', error: errorText(error) });
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
if (now.kind === 'skip') {
|
|
730
|
+
outcomes.push(now.outcome);
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
if (now.kind === 'block') {
|
|
734
|
+
outcomes.push({ platform, status: 'failed', error: now.problem });
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
// A repost must never downgrade the `posted` record: that content is live, and a later plain call has to keep
|
|
738
|
+
// skipping it even if this repost fails. The attempt is tracked on the account marker alone.
|
|
739
|
+
const reposting = current?.state === 'posted';
|
|
740
|
+
const startedAt = laterThan([current?.at, replacedMarkerAt]);
|
|
741
|
+
const attempt = randomUUID();
|
|
742
|
+
const ours = { postKey: key, at: startedAt, attempt };
|
|
743
|
+
try {
|
|
744
|
+
writePending(platform, account, { ...ours, state: 'sending' });
|
|
745
|
+
try {
|
|
746
|
+
if (!reposting)
|
|
747
|
+
writeRecord(platform, key, { state: 'sending', at: startedAt });
|
|
748
|
+
}
|
|
749
|
+
catch (recordError) {
|
|
750
|
+
// Nothing was sent: do not leave the account looking pending. Report the record error, not a cleanup one.
|
|
751
|
+
settlePending(platform, account, ours, null);
|
|
752
|
+
throw recordError;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
catch (error) {
|
|
756
|
+
// Not sent. Stop here instead of throwing, so the results of platforms already posted are not lost.
|
|
757
|
+
ledgerBroken = errorText(error);
|
|
758
|
+
outcomes.push({ platform, status: 'failed', error: M().notSentNoLedger(ledgerBroken) });
|
|
759
|
+
continue;
|
|
760
|
+
}
|
|
761
|
+
let sent;
|
|
762
|
+
try {
|
|
763
|
+
sent = await send(platform, input, post, prepared);
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
const ambiguous = isAmbiguous(error);
|
|
767
|
+
// Record and marker share the send's start time, whatever is written when: that is the one `at` a person
|
|
768
|
+
// approves with resendUnknown, even if one of the two writes below fails.
|
|
769
|
+
const at = ambiguous ? startedAt : laterThan([startedAt]);
|
|
770
|
+
let reported = errorText(error);
|
|
771
|
+
try {
|
|
772
|
+
// Unknown keeps the account pending (blocks even edited content); a clean failure releases it.
|
|
773
|
+
if (ambiguous) {
|
|
774
|
+
const note = settlePending(platform, account, ours, { postKey: key, state: 'unknown', at, attempt });
|
|
775
|
+
if (!reposting)
|
|
776
|
+
writeRecord(platform, key, { state: 'unknown', at, error: reported });
|
|
777
|
+
if (note)
|
|
778
|
+
reported = `${reported} ${note}`;
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
// A repost keeps its `posted` record as is, but names this attempt on it: nothing went out, so its marker
|
|
782
|
+
// must not block the account as unknown if clearing it fails.
|
|
783
|
+
writeRecord(platform, key, reposting && current
|
|
784
|
+
? { ...current, settledAttempt: attempt }
|
|
785
|
+
: { state: 'failed', at, error: reported, settledAttempt: attempt });
|
|
786
|
+
const note = settlePending(platform, account, ours, null);
|
|
787
|
+
if (note)
|
|
788
|
+
reported = `${reported} ${note}`;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
catch (writeError) {
|
|
792
|
+
// Both records stay `sending`, which decide() treats like unknown: safe, at worst it needs a manual check.
|
|
793
|
+
ledgerBroken = errorText(writeError);
|
|
794
|
+
}
|
|
795
|
+
outcomes.push(ambiguous
|
|
796
|
+
? { platform, status: 'unknown_outcome', error: reported, at }
|
|
797
|
+
: { platform, status: 'failed', error: reported });
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
// Posted. A failure to write that down must never turn into `failed` (which would be resent): the records keep
|
|
801
|
+
// `sending`, so the next call reports the account as pending instead of posting again.
|
|
802
|
+
let warning = null;
|
|
803
|
+
try {
|
|
804
|
+
writeRecord(platform, key, { state: 'posted', at: laterThan([startedAt]), ...sent, settledAttempt: attempt });
|
|
805
|
+
// Posted and recorded. A marker that could not be cleared would block this account: say so in the result.
|
|
806
|
+
warning = settlePending(platform, account, ours, null);
|
|
807
|
+
}
|
|
808
|
+
catch (writeError) {
|
|
809
|
+
// Live but unrecorded: the marker stays, so the account reads as pending until a person confirms the post.
|
|
810
|
+
ledgerBroken = errorText(writeError);
|
|
811
|
+
warning = M().postedUnrecorded(platform, startedAt, ledgerBroken);
|
|
812
|
+
}
|
|
813
|
+
outcomes.push({ platform, status: 'posted', ...sent, ...(warning ? { warning } : {}) });
|
|
814
|
+
}
|
|
815
|
+
return outcomes;
|
|
816
|
+
}
|
|
817
|
+
finally {
|
|
818
|
+
for (const lock of locks.reverse())
|
|
819
|
+
lock.release();
|
|
820
|
+
}
|
|
821
|
+
}
|