@senseihq/emaki-cli 0.1.0 → 0.1.1
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 +42 -7
- package/package.json +4 -2
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/modules/campaign/README.md +10 -3
- package/plugin/modules/campaign/day-script.template.md +2 -1
- package/plugin/modules/posting-desk/README.md +2 -2
- package/plugin/skills/emaki/references/03-content-model.md +7 -4
- package/plugin/skills/emaki/references/04-scene-authoring.md +3 -0
- package/plugin/skills/emaki/references/05-voice-and-video.md +41 -8
- package/plugin/skills/emaki/references/09-publishing.md +5 -2
- package/plugin/skills/story-media/SKILL.md +2 -0
- package/plugin/skills/story-publish/SKILL.md +18 -4
- package/src/api.js +12 -1
- package/src/campaign.js +157 -0
- package/src/capture.js +69 -33
- package/src/carousel.js +91 -0
- package/src/day-script.js +66 -0
- package/src/desk-client.js +37 -0
- package/src/desk-plan.js +57 -0
- package/src/films.js +12 -5
- package/src/http.js +30 -0
- package/src/index.js +161 -3
- package/src/init.js +5 -4
- package/src/media.js +236 -0
- package/src/migrate.js +67 -0
- package/src/publish.js +118 -0
- package/src/stage.js +107 -0
- package/src/stories.js +66 -0
- package/src/upload/instagram.js +34 -0
- package/src/upload/youtube.js +90 -0
- package/src/util.js +7 -0
- package/src/voice.js +119 -40
- package/src/youtube-text.js +58 -0
- package/templates/content/films/measure-the-right-work/film.json +9 -0
- package/templates/content/films/measure-the-right-work/look.css +1 -0
- package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
- package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
- package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
- package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
- package/templates/film/look.css +1 -0
package/src/publish.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// emaki publish youtube|instagram <slug>: post a finished, checked film straight to a platform (no desk approval),
|
|
2
|
+
// then write the link into the story's entry in content/stories/index.json (an existing id or link is never
|
|
3
|
+
// overwritten). --dry-run prints exactly what would post and touches nothing; --verify checks the credentials
|
|
4
|
+
// read-only and names the account.
|
|
5
|
+
//
|
|
6
|
+
// YouTube: the 16:9 film, the description (out/description.txt, else title + chapters + link), the story's tags,
|
|
7
|
+
// the captions and the 16:9 cover as thumbnail. Unlisted unless --privacy public. --update <id> refreshes an uploaded
|
|
8
|
+
// video in place. Needs YT_CLIENT_ID, YT_CLIENT_SECRET, YT_REFRESH_TOKEN.
|
|
9
|
+
// Instagram: the 9:16 film as a Reel with its cover. Meta fetches media from a public URL: pass --video-url and
|
|
10
|
+
// --cover-url, or the files go to the desk's media store and are linked for an hour with the desk's signature
|
|
11
|
+
// (STAGER_CLIENT_ID, STAGER_CLIENT_SECRET, MEDIA_URL_SECRET). Needs IG_USER_ID, IG_ACCESS_TOKEN.
|
|
12
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
13
|
+
import { basename, join } from 'node:path'
|
|
14
|
+
import { signMedia } from '@senseihq/emaki-posting'
|
|
15
|
+
import { deskClient } from './desk-client.js'
|
|
16
|
+
import { need } from './http.js'
|
|
17
|
+
import { filmFiles, hashtags, recordLinks, storiesIndex, storyFor, storyUrl } from './stories.js'
|
|
18
|
+
import { instagram } from './upload/instagram.js'
|
|
19
|
+
import { youtube } from './upload/youtube.js'
|
|
20
|
+
import { die, exists, load, mediaLength } from './util.js'
|
|
21
|
+
import { mergeDescription, youtubeDescription } from './youtube-text.js'
|
|
22
|
+
|
|
23
|
+
const PRIVACY = ['public', 'unlisted', 'private']
|
|
24
|
+
const kb = (f) => `${Math.round(statSync(f).size / 1024)} KB`
|
|
25
|
+
|
|
26
|
+
export async function publish(p, channel, slug, opts = {}) {
|
|
27
|
+
if (channel === 'youtube') return publishYoutube(p, slug, opts)
|
|
28
|
+
if (channel === 'instagram') return publishInstagram(p, slug, opts)
|
|
29
|
+
die(`publish to youtube or instagram (got "${channel}")`)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ytClient(env, fetch, log) {
|
|
33
|
+
need(env, 'YT_CLIENT_ID', 'YT_CLIENT_SECRET', 'YT_REFRESH_TOKEN')
|
|
34
|
+
return youtube({ clientId: env.YT_CLIENT_ID, clientSecret: env.YT_CLIENT_SECRET, refreshToken: env.YT_REFRESH_TOKEN, fetch, log })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function publishYoutube(p, slug, { locale, verify, dryRun, privacy = 'unlisted', update, forceNew, descriptionMode = 'prepend', env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
|
|
38
|
+
if (verify) return log(`YouTube posts as: ${await ytClient(env, fetch, log).verify()}`)
|
|
39
|
+
if (!PRIVACY.includes(privacy)) die('--privacy: public, unlisted or private')
|
|
40
|
+
if (!['prepend', 'replace'].includes(descriptionMode)) die('--description-mode: prepend or replace')
|
|
41
|
+
locale ??= p.site.defaultLocale
|
|
42
|
+
const yt = dryRun ? null : ytClient(env, fetch, log)
|
|
43
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
44
|
+
if (!f.wide) die(`${slug}: no built 16:9 video (${p.rel(f.expect.wide)}); run \`emaki render ${slug}\` and \`emaki build ${slug}\` first`)
|
|
45
|
+
const desc = youtubeDescription(p, slug, locale, story.title), tags = story.tags
|
|
46
|
+
const srt = f.srt ? readFileSync(f.srt) : null, thumb = f.thumb ? readFileSync(f.thumb) : null
|
|
47
|
+
if (update) {
|
|
48
|
+
const remote = dryRun ? null : (await yt.getVideo(update)).snippet
|
|
49
|
+
const merged = remote ? mergeDescription(remote.description ?? '', desc, descriptionMode) : desc
|
|
50
|
+
log(`YouTube update · ${story.title} · https://www.youtube.com/watch?v=${update}`)
|
|
51
|
+
log(` title: ${remote ? JSON.stringify(remote.title) : '(remote)'} → ${JSON.stringify(story.title)}`)
|
|
52
|
+
log(` desc: ${descriptionMode}, ${merged.length} chars`)
|
|
53
|
+
log(` tags: ${tags.length ? tags.join(', ') : '(keep remote)'}`)
|
|
54
|
+
log(` captions: ${f.srt ? `replace uploaded tracks with ${basename(f.srt)}` : 'none (skipped)'}`)
|
|
55
|
+
log(` thumb: ${f.thumb ? `set ${basename(f.thumb)}` : 'skipped (none rendered)'}`)
|
|
56
|
+
if (dryRun) return log('dry run: nothing changed'), { dryRun: true }
|
|
57
|
+
await yt.updateMetadata(update, { title: story.title, description: merged, tags: tags.length ? tags : undefined })
|
|
58
|
+
if (srt) await yt.replaceCaptions(update, srt, locale)
|
|
59
|
+
if (thumb) await yt.setThumbnail(update, thumb)
|
|
60
|
+
recordLinks(p, slug, { youtube: update })
|
|
61
|
+
log(`updated; recorded in ${p.rel(storiesIndex(p))}`)
|
|
62
|
+
return { id: update, updated: true }
|
|
63
|
+
}
|
|
64
|
+
if (story.youtube && !forceNew)
|
|
65
|
+
die(`${slug} is already on YouTube as ${story.youtube}; pass --update ${story.youtube} to refresh it, or --force-new to upload again`)
|
|
66
|
+
log(`YouTube · ${story.title} · privacy ${privacy}`)
|
|
67
|
+
log(` video: ${basename(f.wide)} (${kb(f.wide)})`)
|
|
68
|
+
log(` desc: ${desc.length} chars, ${desc.split('\n').filter((l) => /^\d+:\d\d /.test(l)).length} chapters`)
|
|
69
|
+
log(` tags: ${tags.slice(0, 10).join(', ')}`)
|
|
70
|
+
log(` captions: ${f.srt ? basename(f.srt) : 'none (continues without)'}`)
|
|
71
|
+
log(` thumb: ${f.thumb ? basename(f.thumb) : 'none (continues without)'}`)
|
|
72
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
73
|
+
const r = await yt.publish(readFileSync(f.wide), { title: story.title, description: desc, tags, privacy, srt, thumb, language: locale })
|
|
74
|
+
recordLinks(p, slug, { youtube: r.id })
|
|
75
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
76
|
+
return r
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Public URLs Meta can fetch: the flags, else the files staged on the desk and signed for an hour. */
|
|
80
|
+
async function reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now }) {
|
|
81
|
+
if (videoUrl && coverUrl) return [videoUrl, coverUrl]
|
|
82
|
+
need(env, 'STAGER_CLIENT_ID', 'STAGER_CLIENT_SECRET', 'MEDIA_URL_SECRET')
|
|
83
|
+
if (!f.coverTall) die(`${slug}: no 9:16 cover; run \`emaki render ${slug}\` first`)
|
|
84
|
+
const desk = deskClient(p, { env, fetch }), urls = []
|
|
85
|
+
for (const [key, file, type] of [[`${slug}/${basename(f.tall)}`, f.tall, 'video/mp4'], [`${slug}/instagram-${basename(f.coverTall)}`, f.coverTall, 'image/jpeg']]) {
|
|
86
|
+
await desk.putMedia(key.toLowerCase(), readFileSync(file), type)
|
|
87
|
+
urls.push(await signMedia(key.toLowerCase(), env.MEDIA_URL_SECRET, desk.origin, 3600, now(), env.MEDIA_PATH || '/m'))
|
|
88
|
+
}
|
|
89
|
+
return urls
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function publishInstagram(p, slug, { locale, verify, dryRun, videoUrl, coverUrl, env = process.env, fetch = globalThis.fetch, log = console.info, length = mediaLength, sleep, now = Date.now } = {}) {
|
|
93
|
+
const client = () => {
|
|
94
|
+
need(env, 'IG_USER_ID', 'IG_ACCESS_TOKEN')
|
|
95
|
+
return instagram({ userId: env.IG_USER_ID, token: env.IG_ACCESS_TOKEN, version: env.IG_GRAPH_VERSION || 'v21.0', fetch, ...(sleep ? { sleep } : {}) })
|
|
96
|
+
}
|
|
97
|
+
if (verify) return log(`Instagram posts as: @${await client().verify()}`)
|
|
98
|
+
if (Boolean(videoUrl) !== Boolean(coverUrl)) die('pass both --video-url and --cover-url, or neither (to stage them on the desk)')
|
|
99
|
+
locale ??= p.site.defaultLocale
|
|
100
|
+
const ig = dryRun ? null : client()
|
|
101
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
102
|
+
if (!f.tall) die(`${slug}: no built 9:16 video (${p.rel(f.expect.tall)}); render and build the portrait film first`)
|
|
103
|
+
const dur = length(f.tall)
|
|
104
|
+
if (dur > 15 * 60) die(`${slug}: ${Math.round(dur)} s is over the 15-minute Reels limit`)
|
|
105
|
+
const pj = join(p.films, slug, `post.${locale}.json`)
|
|
106
|
+
const staged = exists(pj) ? load(pj).instagram_reel?.caption : null
|
|
107
|
+
const caption = staged || `${story.title}. ${story.dek}\n\nRead the story: ${storyUrl(p, slug, locale)}\n\n${hashtags(story.tags)}`
|
|
108
|
+
log(`Instagram Reel · ${slug} · ${Math.round(dur)} s`)
|
|
109
|
+
log(` video: ${basename(f.tall)} (${kb(f.tall)})`)
|
|
110
|
+
log(` cover: ${f.coverTall ? basename(f.coverTall) : 'none!'}`)
|
|
111
|
+
log(` caption: ${caption.length} chars`)
|
|
112
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
113
|
+
const [video, cover] = await reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now })
|
|
114
|
+
const r = await ig.publishReel(video, caption, cover)
|
|
115
|
+
recordLinks(p, slug, { instagram: r.url })
|
|
116
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
117
|
+
return r
|
|
118
|
+
}
|
package/src/stage.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// emaki stage <slug>: upload a finished piece's media and post text to the posting desk, so a person can review and
|
|
2
|
+
// approve exactly that. Restaging changes a post's fingerprint, so an earlier approval for that channel no longer
|
|
3
|
+
// applies (the desk's rule). --dry-run prints the posts and sends nothing.
|
|
4
|
+
//
|
|
5
|
+
// A campaign day (a day script in <campaign>/days/): every channel's text from the script; the film's 9:16 video for
|
|
6
|
+
// YouTube (a Short), the Reel and X; <campaign>/carousels/<slug>/*.png (as JPEG) for the carousel.
|
|
7
|
+
// A film: the 16:9 video (+ captions, + the 16:9 cover as thumbnail) for YouTube and X, the 9:16 video (+ cover) for
|
|
8
|
+
// the Reel, and the text in content/films/<slug>/post.<locale>.json, which the first run drafts for a read-through.
|
|
9
|
+
import { createHash } from 'node:crypto'
|
|
10
|
+
import { mkdtempSync, readdirSync, readFileSync } from 'node:fs'
|
|
11
|
+
import { tmpdir } from 'node:os'
|
|
12
|
+
import { basename, join } from 'node:path'
|
|
13
|
+
import { CHANNELS } from '@senseihq/emaki-posting'
|
|
14
|
+
import { campaignDir, channelCopy, dayScript } from './day-script.js'
|
|
15
|
+
import { deskClient } from './desk-client.js'
|
|
16
|
+
import { filmFiles, hashtags, storyFor, storyUrl } from './stories.js'
|
|
17
|
+
import { die, exists, load, run, save } from './util.js'
|
|
18
|
+
|
|
19
|
+
const TYPES = { mp4: 'video/mp4', srt: 'text/plain', vtt: 'text/vtt' }
|
|
20
|
+
const typeOf = (f) => TYPES[f.split('.').pop()] ?? 'image/jpeg'
|
|
21
|
+
|
|
22
|
+
/** PNG → JPEG with ffmpeg (Instagram takes JPEG only), into a temp folder. */
|
|
23
|
+
export function pngToJpeg(png) {
|
|
24
|
+
const out = join(mkdtempSync(join(tmpdir(), 'emaki-jpeg-')), basename(png).replace(/\.png$/i, '.jpg'))
|
|
25
|
+
run('ffmpeg', ['-y', '-loglevel', 'error', '-i', png, '-q:v', '2', out])
|
|
26
|
+
return out
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The draft text for a film's channels, from its story. */
|
|
30
|
+
function draftPosts(p, slug, locale, story, files) {
|
|
31
|
+
const link = storyUrl(p, slug, locale), tags = hashtags(story.tags)
|
|
32
|
+
const desc = files.description ? readFileSync(files.description, 'utf-8').trim() : `${story.dek}\n\nRead the story: ${link}\n${tags}`
|
|
33
|
+
return {
|
|
34
|
+
youtube: { title: story.title.slice(0, 100), description: desc, tags: story.tags, short: false },
|
|
35
|
+
instagram_reel: { caption: `${story.title}. ${story.dek}\n\nFull story: link in bio.\n\n${tags}` },
|
|
36
|
+
x: { text: `${story.title}: ${story.dek}`.slice(0, 270), thread: [`The full story, with the film: ${link}`] }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** { channel: [post text, [{ path, expect, name? }]] } for one piece. `path` null = missing; `expect` names it. */
|
|
41
|
+
export function postsFor(p, slug, locale) {
|
|
42
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
43
|
+
const tall = { path: f.tall, expect: f.expect.tall }, wide = { path: f.wide, expect: f.expect.wide }
|
|
44
|
+
const md = dayScript(p, slug, locale)
|
|
45
|
+
if (md) {
|
|
46
|
+
const c = channelCopy(md), dir = join(campaignDir(p), 'carousels', slug)
|
|
47
|
+
const slides = exists(dir) ? readdirSync(dir).filter((n) => n.endsWith('.png')).sort().map((n) => ({ path: join(dir, n) })) : []
|
|
48
|
+
return {
|
|
49
|
+
youtube: [{ ...c.youtube, short: true }, [tall]],
|
|
50
|
+
instagram_reel: [{ caption: c.caption }, [tall]],
|
|
51
|
+
instagram_carousel: [{ caption: c.caption }, slides.length ? slides : [{ path: null, expect: dir }]],
|
|
52
|
+
x: [c.x, [tall]]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const pj = join(p.films, slug, `post.${locale}.json`)
|
|
56
|
+
if (!exists(pj)) {
|
|
57
|
+
save(pj, draftPosts(p, slug, locale, story, f))
|
|
58
|
+
die(`wrote ${p.rel(pj)}: check the text, then run \`emaki stage ${slug}\` again`)
|
|
59
|
+
}
|
|
60
|
+
const text = load(pj), opt = (path, name) => (path ? [{ path, name }] : [])
|
|
61
|
+
const files = {
|
|
62
|
+
youtube: [wide, ...opt(f.srt), ...opt(f.thumb, `${slug}-${locale}-thumb.jpg`)], // -thumb.jpg: the poster sets it as the thumbnail
|
|
63
|
+
instagram_reel: [tall, ...opt(f.coverTall)],
|
|
64
|
+
x: [wide]
|
|
65
|
+
}
|
|
66
|
+
return Object.fromEntries(Object.keys(files).filter((c) => text[c]).map((c) => [c, [text[c], files[c]]]))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex')
|
|
70
|
+
|
|
71
|
+
export async function stage(p, slug, { locale, channels, dryRun = false, env = process.env, fetch = globalThis.fetch, log = console.info, toJpeg = pngToJpeg } = {}) {
|
|
72
|
+
locale ??= p.site.defaultLocale
|
|
73
|
+
const want = channels ? [channels].flat().flatMap((c) => String(c).split(',')).map((c) => c.trim()).filter(Boolean) : [...CHANNELS]
|
|
74
|
+
for (const c of want) if (!CHANNELS.includes(c)) die(`unknown channel "${c}" (${CHANNELS.join(', ')})`)
|
|
75
|
+
const posts = postsFor(p, slug, locale)
|
|
76
|
+
const desk = dryRun ? null : deskClient(p, { env, fetch })
|
|
77
|
+
const uploaded = new Map(), result = { staged: [], skipped: [], posts: {} }
|
|
78
|
+
for (const channel of CHANNELS.filter((c) => want.includes(c) && posts[c])) {
|
|
79
|
+
const [text, files] = posts[channel]
|
|
80
|
+
const missing = files.filter((x) => !x.path).map((x) => p.rel(x.expect))
|
|
81
|
+
if (missing.length) {
|
|
82
|
+
log(` ${channel}: skipped, missing ${missing.join(', ')}`)
|
|
83
|
+
result.skipped.push({ channel, missing })
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
const media = []
|
|
87
|
+
for (const x of files) {
|
|
88
|
+
const path = x.path.endsWith('.png') ? toJpeg(x.path) : x.path
|
|
89
|
+
const name = (x.name ?? basename(path)).toLowerCase(), type = typeOf(path)
|
|
90
|
+
const key = `${slug}/${type === 'image/jpeg' ? `${channel.split('_')[0]}-${name}` : name}`
|
|
91
|
+
const bytes = readFileSync(path)
|
|
92
|
+
if (desk && !uploaded.has(key)) uploaded.set(key, await desk.putMedia(key, bytes, type))
|
|
93
|
+
media.push({ key, sha256: uploaded.get(key) ?? sha(bytes), type })
|
|
94
|
+
}
|
|
95
|
+
const post = { ...text, media }
|
|
96
|
+
result.posts[channel] = post
|
|
97
|
+
if (!desk) {
|
|
98
|
+
log(`--- ${channel}\n${JSON.stringify(post, null, 2)}`)
|
|
99
|
+
continue
|
|
100
|
+
}
|
|
101
|
+
const r = await desk.stage(slug, channel, post)
|
|
102
|
+
log(` ${channel}: staged (${String(r.content_sha).slice(0, 10)}), ${media.length} file(s)`)
|
|
103
|
+
result.staged.push({ channel, content_sha: r.content_sha, files: media.length })
|
|
104
|
+
}
|
|
105
|
+
if (desk) log(`Review and approve on ${desk.origin}/admin`)
|
|
106
|
+
return result
|
|
107
|
+
}
|
package/src/stories.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// A story as the media pipeline needs it: its index entry with the reader-facing text of one locale, its public
|
|
2
|
+
// link, the built files of its film, and the links of its posts written back into the stories index.
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { SUFFIX } from './config.js'
|
|
5
|
+
import { die, exists, load, save } from './util.js'
|
|
6
|
+
|
|
7
|
+
export const storiesIndex = (p) => join(p.content, 'stories', 'index.json')
|
|
8
|
+
|
|
9
|
+
/** The index entry merged with title/dek/… from stories/<locale>/<slug>.json (else the default locale's). */
|
|
10
|
+
export function storyFor(p, slug, locale) {
|
|
11
|
+
const ip = storiesIndex(p)
|
|
12
|
+
const entry = exists(ip) ? load(ip).find((e) => e.slug === slug) : null
|
|
13
|
+
if (!entry) die(`${slug} is not in ${p.rel(ip)}`)
|
|
14
|
+
const body = [locale, p.site.defaultLocale].map((l) => join(p.content, 'stories', l, `${slug}.json`)).find(exists)
|
|
15
|
+
const text = body ? load(body) : {}
|
|
16
|
+
const film = exists(join(p.films, slug, 'film.json')) ? load(join(p.films, slug, 'film.json')) : {}
|
|
17
|
+
return { ...entry, title: text.title ?? entry.title ?? film.title ?? slug, dek: text.dek ?? entry.dek ?? '', tags: entry.tags ?? [] }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The public link of a story: emaki.config.json "storyUrl" ({url}, {locale}, {slug}), default {url}/{locale}/stories/{slug}. */
|
|
21
|
+
export function storyUrl(p, slug, locale) {
|
|
22
|
+
const tpl = p.cfg.storyUrl ?? '{url}/{locale}/stories/{slug}'
|
|
23
|
+
return tpl.replaceAll('{url}', (p.site.url ?? '').replace(/\/$/, '')).replaceAll('{locale}', locale).replaceAll('{slug}', slug)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** #tag #tag from a story's first five tags (dashes dropped). */
|
|
27
|
+
export const hashtags = (tags) => tags.slice(0, 5).map((t) => '#' + t.replace(/-/g, '')).join(' ')
|
|
28
|
+
|
|
29
|
+
/** What `emaki build` and `emaki render` made for a film in one locale; a missing file is null. */
|
|
30
|
+
export function filmFiles(p, slug, locale) {
|
|
31
|
+
const out = p.prod(slug, locale, 'out'), render = p.prod(slug, locale, 'render')
|
|
32
|
+
const has = (f) => (exists(f) ? f : null)
|
|
33
|
+
return {
|
|
34
|
+
wide: has(join(out, `${slug}-${locale}-${SUFFIX.landscape}.mp4`)),
|
|
35
|
+
tall: has(join(out, `${slug}-${locale}-${SUFFIX.portrait}.mp4`)),
|
|
36
|
+
srt: has(join(out, `${slug}-${locale}.srt`)),
|
|
37
|
+
thumb: has(join(render, `${slug}-${locale}-cover-${SUFFIX.landscape}.jpg`)),
|
|
38
|
+
coverTall: has(join(render, `${slug}-${locale}-cover-${SUFFIX.portrait}.jpg`)),
|
|
39
|
+
description: has(join(out, 'description.txt')),
|
|
40
|
+
expect: {
|
|
41
|
+
wide: join(out, `${slug}-${locale}-${SUFFIX.landscape}.mp4`),
|
|
42
|
+
tall: join(out, `${slug}-${locale}-${SUFFIX.portrait}.mp4`)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Writes post links into the story's index entry: `youtube` (the id) and social.youtube / social.instagram / social.x.
|
|
49
|
+
* Without `overwrite`, an existing id or link is never replaced. A Short (entry.video === 'short') links /shorts/.
|
|
50
|
+
*/
|
|
51
|
+
export function recordLinks(p, slug, { youtube, instagram, x } = {}, { overwrite = false } = {}) {
|
|
52
|
+
const ip = storiesIndex(p), index = load(ip)
|
|
53
|
+
const entry = index.find((e) => e.slug === slug)
|
|
54
|
+
if (!entry) die(`${slug} is not in ${p.rel(ip)}`)
|
|
55
|
+
const social = (entry.social ??= {})
|
|
56
|
+
const set = (obj, k, v) => { if (v && (overwrite || !obj[k])) obj[k] = v }
|
|
57
|
+
if (youtube && !/^https?:/.test(youtube)) {
|
|
58
|
+
set(entry, 'youtube', youtube)
|
|
59
|
+
youtube = entry.video === 'short' ? `https://www.youtube.com/shorts/${youtube}` : `https://www.youtube.com/watch?v=${youtube}`
|
|
60
|
+
}
|
|
61
|
+
set(social, 'youtube', youtube)
|
|
62
|
+
set(social, 'instagram', instagram)
|
|
63
|
+
set(social, 'x', x)
|
|
64
|
+
save(ip, index)
|
|
65
|
+
return entry
|
|
66
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Instagram Graph API (instagram_content_publish): verify the account, and post a Reel from a public video URL
|
|
2
|
+
// (Meta fetches the media itself): create the container, wait until it is processed, publish, read the permalink.
|
|
3
|
+
import { callJson } from '../http.js'
|
|
4
|
+
import { die } from '../util.js'
|
|
5
|
+
|
|
6
|
+
export function instagram({ userId, token, version = 'v21.0', fetch = globalThis.fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), tries = 60 }) {
|
|
7
|
+
const base = `https://graph.facebook.com/${version}`
|
|
8
|
+
const graph = (method, path, params = {}) => {
|
|
9
|
+
const q = new URLSearchParams({ ...params, access_token: token }).toString()
|
|
10
|
+
return method === 'GET'
|
|
11
|
+
? callJson(fetch, 'GET', `${base}/${path}?${q}`)
|
|
12
|
+
: callJson(fetch, method, `${base}/${path}`, { body: q, headers: { 'content-type': 'application/x-www-form-urlencoded' } })
|
|
13
|
+
}
|
|
14
|
+
return {
|
|
15
|
+
/** The account this token posts as (read-only). */
|
|
16
|
+
async verify() {
|
|
17
|
+
return (await graph('GET', String(userId), { fields: 'username' })).username ?? String(userId)
|
|
18
|
+
},
|
|
19
|
+
/** Posts a Reel; returns { url (permalink), id }. */
|
|
20
|
+
async publishReel(videoUrl, caption, coverUrl, { shareToFeed = true } = {}) {
|
|
21
|
+
const params = { media_type: 'REELS', video_url: videoUrl, caption, share_to_feed: shareToFeed ? 'true' : 'false', ...(coverUrl ? { cover_url: coverUrl } : {}) }
|
|
22
|
+
const container = (await graph('POST', `${userId}/media`, params)).id
|
|
23
|
+
for (let i = 0; ; i++) {
|
|
24
|
+
const st = (await graph('GET', container, { fields: 'status_code' })).status_code
|
|
25
|
+
if (st === 'FINISHED') break
|
|
26
|
+
if (st === 'ERROR' || st === 'EXPIRED') die(`Instagram could not process the media (${st})`)
|
|
27
|
+
if (i + 1 >= tries) die('Instagram took too long to process the media')
|
|
28
|
+
await sleep(10000)
|
|
29
|
+
}
|
|
30
|
+
const id = (await graph('POST', `${userId}/media_publish`, { creation_id: container })).id
|
|
31
|
+
return { url: (await graph('GET', id, { fields: 'permalink' })).permalink ?? null, id }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// YouTube Data API v3 with an OAuth refresh token (scopes youtube.upload + youtube.force-ssl): verify the channel,
|
|
2
|
+
// upload a video (resumable) with its caption track and custom thumbnail, and refresh an uploaded video in place.
|
|
3
|
+
import { randomBytes } from 'node:crypto'
|
|
4
|
+
import { call, callJson } from '../http.js'
|
|
5
|
+
import { die } from '../util.js'
|
|
6
|
+
|
|
7
|
+
const API = 'https://www.googleapis.com/youtube/v3', UPLOAD = 'https://www.googleapis.com/upload/youtube/v3'
|
|
8
|
+
|
|
9
|
+
/** multipart/related body from [contentType, bytes | string] parts. */
|
|
10
|
+
function multipart(parts) {
|
|
11
|
+
const boundary = 'emaki' + randomBytes(8).toString('hex')
|
|
12
|
+
const chunks = parts.flatMap(([type, data]) => [Buffer.from(`--${boundary}\r\nContent-Type: ${type}\r\n\r\n`), Buffer.from(data), Buffer.from('\r\n')])
|
|
13
|
+
return { body: Buffer.concat([...chunks, Buffer.from(`--${boundary}--\r\n`)]), type: `multipart/related; boundary=${boundary}` }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const languageName = (code) => {
|
|
17
|
+
try {
|
|
18
|
+
return new Intl.DisplayNames(['en'], { type: 'language' }).of(code) ?? code
|
|
19
|
+
} catch {
|
|
20
|
+
return code
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function youtube({ clientId, clientSecret, refreshToken, fetch = globalThis.fetch, log = console.info }) {
|
|
25
|
+
let access
|
|
26
|
+
const token = async () => (access ??= (await callJson(fetch, 'POST', 'https://oauth2.googleapis.com/token', {
|
|
27
|
+
body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, refresh_token: refreshToken, grant_type: 'refresh_token' }).toString(),
|
|
28
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
|
29
|
+
})).access_token)
|
|
30
|
+
const auth = async (extra = {}) => ({ authorization: `Bearer ${await token()}`, ...extra })
|
|
31
|
+
const get = async (url) => callJson(fetch, 'GET', url, { headers: await auth() })
|
|
32
|
+
|
|
33
|
+
async function uploadCaption(videoId, srt, language = 'en') {
|
|
34
|
+
const m = multipart([['application/json; charset=UTF-8', JSON.stringify({ snippet: { videoId, language, name: languageName(language) } })], ['application/octet-stream', srt]])
|
|
35
|
+
await callJson(fetch, 'POST', `${UPLOAD}/captions?part=snippet`, { body: m.body, headers: await auth({ 'content-type': m.type }) })
|
|
36
|
+
}
|
|
37
|
+
async function setThumbnail(videoId, jpg) {
|
|
38
|
+
const m = multipart([['image/jpeg', jpg]])
|
|
39
|
+
await callJson(fetch, 'POST', `${UPLOAD}/thumbnails/set?videoId=${encodeURIComponent(videoId)}`, { body: m.body, headers: await auth({ 'content-type': m.type }) })
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
/** The channel this credential posts as (read-only). */
|
|
44
|
+
async verify() {
|
|
45
|
+
const r = await get(`${API}/channels?part=snippet&mine=true`)
|
|
46
|
+
if (!r.items?.length) die('this YouTube credential has no channel')
|
|
47
|
+
return r.items[0].snippet.title
|
|
48
|
+
},
|
|
49
|
+
async getVideo(id) {
|
|
50
|
+
const r = await get(`${API}/videos?part=snippet,contentDetails,status&id=${encodeURIComponent(id)}`)
|
|
51
|
+
if (!r.items?.length) die(`no YouTube video ${id} on this channel`)
|
|
52
|
+
return r.items[0]
|
|
53
|
+
},
|
|
54
|
+
/** Metadata in place; an omitted field keeps the remote value. The video file itself is never replaced. */
|
|
55
|
+
async updateMetadata(id, { title, description, tags, categoryId } = {}) {
|
|
56
|
+
const r = await get(`${API}/videos?part=snippet&id=${encodeURIComponent(id)}`)
|
|
57
|
+
if (!r.items?.length) die(`no YouTube video ${id} on this channel`)
|
|
58
|
+
const cur = r.items[0].snippet
|
|
59
|
+
const snippet = { title: title ?? cur.title, description: description ?? cur.description ?? '', tags: tags ?? cur.tags ?? [], categoryId: categoryId ?? cur.categoryId ?? '28' }
|
|
60
|
+
await callJson(fetch, 'PUT', `${API}/videos?part=snippet`, { body: JSON.stringify({ id, snippet }), headers: await auth({ 'content-type': 'application/json; charset=UTF-8' }) })
|
|
61
|
+
},
|
|
62
|
+
/** Replaces uploaded caption tracks with ours; automatic (ASR) tracks are left alone. */
|
|
63
|
+
async replaceCaptions(id, srt, language = 'en') {
|
|
64
|
+
const r = await get(`${API}/captions?part=snippet&videoId=${encodeURIComponent(id)}`)
|
|
65
|
+
for (const c of r.items ?? [])
|
|
66
|
+
if (String(c.snippet?.trackKind ?? '').toUpperCase() !== 'ASR') await call(fetch, 'DELETE', `${API}/captions?id=${encodeURIComponent(c.id)}`, { headers: await auth() })
|
|
67
|
+
await uploadCaption(id, srt, language)
|
|
68
|
+
},
|
|
69
|
+
setThumbnail,
|
|
70
|
+
/** Uploads a video; returns { id, url, privacy }. srt and thumb are optional. */
|
|
71
|
+
async publish(video, { title, description = '', tags = [], privacy = 'unlisted', srt, thumb, short = false, categoryId = '28', language = 'en' }) {
|
|
72
|
+
const meta = {
|
|
73
|
+
snippet: { title: title.slice(0, 100), description: description.slice(0, 5000), tags: tags.slice(0, 30), categoryId },
|
|
74
|
+
status: { privacyStatus: privacy, selfDeclaredMadeForKids: false }
|
|
75
|
+
}
|
|
76
|
+
const init = await call(fetch, 'POST', `${UPLOAD}/videos?uploadType=resumable&part=snippet,status`, {
|
|
77
|
+
body: JSON.stringify(meta),
|
|
78
|
+
headers: await auth({ 'content-type': 'application/json; charset=UTF-8', 'x-upload-content-type': 'video/mp4', 'x-upload-content-length': String(video.length) })
|
|
79
|
+
})
|
|
80
|
+
const session = init.headers.get('location')
|
|
81
|
+
if (!session) die('YouTube did not return an upload session (no Location header)')
|
|
82
|
+
const got = await callJson(fetch, 'PUT', session, { body: video, headers: await auth({ 'content-type': 'video/mp4' }) })
|
|
83
|
+
const id = got.id, set = got.status?.privacyStatus ?? privacy
|
|
84
|
+
if (set !== privacy) log(`warning: YouTube set privacy to "${set}" instead of "${privacy}"`)
|
|
85
|
+
if (srt) await uploadCaption(id, srt, language)
|
|
86
|
+
if (thumb) await setThumbnail(id, thumb)
|
|
87
|
+
return { id, url: short ? `https://www.youtube.com/shorts/${id}` : `https://www.youtube.com/watch?v=${id}`, privacy: set }
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
package/src/util.js
CHANGED
|
@@ -39,6 +39,10 @@ export function which(cmd) {
|
|
|
39
39
|
export const mediaLength = (p) =>
|
|
40
40
|
parseFloat(run('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', p]).trim())
|
|
41
41
|
|
|
42
|
+
/** True when a media file has an audio stream (ffprobe). */
|
|
43
|
+
export const hasAudio = (p) =>
|
|
44
|
+
run('ffprobe', ['-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=codec_type', '-of', 'csv=p=0', p]).includes('audio')
|
|
45
|
+
|
|
42
46
|
/** key=value pairs from --opt, values parsed as JSON when they are JSON (numbers, booleans). */
|
|
43
47
|
export function parseOpts(items) {
|
|
44
48
|
const out = {}
|
|
@@ -55,5 +59,8 @@ export function parseOpts(items) {
|
|
|
55
59
|
return out
|
|
56
60
|
}
|
|
57
61
|
|
|
62
|
+
/** A scene's running time: its fitted `dur` (timing.<locale>.json, longer or shorter than the design), else the
|
|
63
|
+
* design time plus its pauses. The core's loadFilm resolves it the same way. */
|
|
64
|
+
export const runningTime = (scene, tm = {}) => tm.dur ?? scene.dur + (tm.holds ?? []).reduce((n, h) => n + h[1], 0)
|
|
58
65
|
export const pad2 = (n) => String(n).padStart(2, '0')
|
|
59
66
|
export const today = () => new Date().toISOString().slice(0, 10)
|