@senseihq/emaki-cli 0.1.0 → 0.1.2
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/build-media.js +166 -0
- package/src/build-video.js +113 -0
- package/src/campaign.js +138 -0
- package/src/capture.js +6 -118
- package/src/carousel.js +91 -0
- package/src/commands/campaign.js +63 -0
- package/src/commands/posting.js +74 -0
- package/src/commands/production.js +128 -0
- package/src/commands/run.js +19 -0
- package/src/commands/setup.js +97 -0
- package/src/csv.js +42 -0
- package/src/day-script.js +66 -0
- package/src/desk-client.js +37 -0
- package/src/desk-plan.js +57 -0
- package/src/film-checks.js +102 -0
- package/src/films.js +7 -75
- package/src/fit.js +79 -0
- package/src/http.js +30 -0
- package/src/index.js +10 -184
- package/src/init.js +10 -13
- package/src/media.js +80 -0
- package/src/migrate.js +84 -0
- package/src/publish.js +136 -0
- package/src/render.js +125 -0
- package/src/show-page.js +75 -0
- package/src/stage.js +120 -0
- package/src/stories.js +66 -0
- package/src/takes.js +18 -0
- package/src/tts-cloud.js +122 -0
- package/src/tts-io.js +51 -0
- package/src/tts-offline.js +85 -0
- package/src/tts.js +5 -237
- package/src/upload/instagram.js +34 -0
- package/src/upload/youtube.js +90 -0
- package/src/util.js +7 -0
- package/src/voice.js +8 -118
- 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/migrate.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// emaki migrate <website>: moves a sensei-hq.com-style site's motion content into emaki's layout, once, so `emaki`
|
|
2
|
+
// can take over its films (issue #1, gap 4). Nothing that already exists is overwritten; the report lists what was
|
|
3
|
+
// written and what was kept, and `emaki validate` checks the result.
|
|
4
|
+
//
|
|
5
|
+
// src/lib/motion/films/<slug>/ → content/films/<slug>/ (base.css becomes look.css)
|
|
6
|
+
// src/lib/motion/logos/ → content/logos/
|
|
7
|
+
// src/lib/content/articles/index.json → content/stories/index.json, minus the reader-facing text …
|
|
8
|
+
// src/lib/content/articles/<slug>.json → content/stories/<locale>/<slug>.json, plus that text (title, dek, …)
|
|
9
|
+
// films/<slug>/film.json scenes → content/films/<slug>/voice/<locale>.json (the narration)
|
|
10
|
+
// films/<slug>/takes/*.wav → production/<slug>/<locale>/takes/ (recorded takes: keep, don't regenerate)
|
|
11
|
+
import { copyFileSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join } from 'node:path'
|
|
13
|
+
import { die, exists, load } from './util.js'
|
|
14
|
+
|
|
15
|
+
/** Index fields that are words for the reader: emaki keeps them per locale, in the story body. */
|
|
16
|
+
const TEXT = ['title', 'dek', 'kanjiGloss', 'series']
|
|
17
|
+
|
|
18
|
+
/** Writes that never overwrite: each target lands in `wrote`, or in `kept` when it already exists. */
|
|
19
|
+
function writer(p) {
|
|
20
|
+
const wrote = [], kept = []
|
|
21
|
+
const put = (dst, write) => {
|
|
22
|
+
const rel = p.rel(dst)
|
|
23
|
+
if (exists(dst)) return kept.push(rel)
|
|
24
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
25
|
+
write(dst)
|
|
26
|
+
wrote.push(rel)
|
|
27
|
+
}
|
|
28
|
+
const copy = (src, dst) => put(dst, (d) => copyFileSync(src, d))
|
|
29
|
+
const json = (dst, data) => put(dst, (d) => writeFileSync(d, JSON.stringify(data, null, 1) + '\n'))
|
|
30
|
+
const tree = (src, dst, rename = (n) => n) => {
|
|
31
|
+
for (const e of readdirSync(src, { withFileTypes: true }))
|
|
32
|
+
if (e.isDirectory()) tree(join(src, e.name), join(dst, e.name))
|
|
33
|
+
else copy(join(src, e.name), join(dst, rename(e.name)))
|
|
34
|
+
}
|
|
35
|
+
return { wrote, kept, copy, json, tree }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The sub-folders of `dir` that hold a film.json (none when `dir` is missing). */
|
|
39
|
+
const filmFolders = (dir) => (exists(dir) ? readdirSync(dir).filter((d) => exists(join(dir, d, 'film.json'))) : [])
|
|
40
|
+
|
|
41
|
+
/** src/lib/motion/films/<slug>/ → content/films/<slug>/ (base.css becomes look.css), then the logos. */
|
|
42
|
+
function moveFilms(p, from, w) {
|
|
43
|
+
const films = join(from, 'src/lib/motion/films')
|
|
44
|
+
for (const slug of filmFolders(films)) w.tree(join(films, slug), join(p.films, slug), (n) => (n === 'base.css' ? 'look.css' : n))
|
|
45
|
+
const logos = join(from, 'src/lib/motion/logos')
|
|
46
|
+
if (exists(logos)) w.tree(logos, join(p.content, 'logos'))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The articles index without its reader-facing text, and each article's body with that text, in `locale`. */
|
|
50
|
+
function moveArticles(p, articles, locale, w) {
|
|
51
|
+
if (!exists(join(articles, 'index.json'))) return
|
|
52
|
+
const index = load(join(articles, 'index.json'))
|
|
53
|
+
w.json(join(p.content, 'stories', 'index.json'), index.map((e) => Object.fromEntries(Object.entries(e).filter(([k]) => !TEXT.includes(k)))))
|
|
54
|
+
for (const e of index) {
|
|
55
|
+
const src = join(articles, `${e.slug}.json`)
|
|
56
|
+
if (!exists(src)) continue
|
|
57
|
+
const text = Object.fromEntries(TEXT.filter((k) => k in e).map((k) => [k, e[k]]))
|
|
58
|
+
w.json(join(p.content, 'stories', locale, `${e.slug}.json`), { ...text, ...load(src) })
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** films/<slug>/: the narration (into a film that was moved) and the recorded takes. */
|
|
63
|
+
function moveMasters(p, from, locale, w) {
|
|
64
|
+
const masters = join(from, 'films')
|
|
65
|
+
for (const slug of filmFolders(masters)) {
|
|
66
|
+
const scenes = load(join(masters, slug, 'film.json')).scenes ?? []
|
|
67
|
+
if (scenes.length && exists(join(p.films, slug)))
|
|
68
|
+
w.json(join(p.films, slug, 'voice', `${locale}.json`), scenes.map((s) => ({ scene: s.id, text: s.text ?? '', say: s.say ?? null })))
|
|
69
|
+
const takes = join(masters, slug, 'takes')
|
|
70
|
+
const wavs = exists(takes) ? readdirSync(takes).filter((n) => n.endsWith('.wav')) : []
|
|
71
|
+
for (const f of wavs) w.copy(join(takes, f), p.prod(slug, locale, 'takes', f))
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function migrate(p, from, { locale = 'en' } = {}) {
|
|
76
|
+
const films = join(from, 'src/lib/motion/films'), articles = join(from, 'src/lib/content/articles')
|
|
77
|
+
if (!exists(films) && !exists(articles)) die(`${from} has neither src/lib/motion/films nor src/lib/content/articles`)
|
|
78
|
+
const w = writer(p)
|
|
79
|
+
moveFilms(p, from, w)
|
|
80
|
+
moveArticles(p, articles, locale, w)
|
|
81
|
+
moveMasters(p, from, locale, w)
|
|
82
|
+
if (!exists(join(p.content, 'site.json'))) w.json(join(p.content, 'site.json'), { name: '', url: '', locales: [locale], defaultLocale: locale })
|
|
83
|
+
return { wrote: w.wrote, kept: w.kept }
|
|
84
|
+
}
|
package/src/publish.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
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
|
+
const DESCRIPTION_MODES = ['prepend', 'replace']
|
|
38
|
+
const chapterCount = (desc) => desc.split('\n').filter((l) => /^\d+:\d\d /.test(l)).length
|
|
39
|
+
|
|
40
|
+
/** What a YouTube post carries: the built 16:9 film, the description, the story's tags, captions and thumbnail. */
|
|
41
|
+
function youtubePiece(p, slug, locale) {
|
|
42
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
43
|
+
if (!f.wide) die(`${slug}: no built 16:9 video (${p.rel(f.expect.wide)}); run \`emaki render ${slug}\` and \`emaki build ${slug}\` first`)
|
|
44
|
+
return {
|
|
45
|
+
story, f, desc: youtubeDescription(p, slug, locale, story.title), tags: story.tags,
|
|
46
|
+
srt: f.srt ? readFileSync(f.srt) : null, thumb: f.thumb ? readFileSync(f.thumb) : null
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** --update: refreshes the uploaded video's title, description (merged with the remote one), tags, captions, thumbnail. */
|
|
51
|
+
async function updateYoutube(p, slug, yt, { story, f, desc, tags, srt, thumb }, { update, dryRun, descriptionMode, locale, log }) {
|
|
52
|
+
const remote = dryRun ? null : (await yt.getVideo(update)).snippet
|
|
53
|
+
const merged = remote ? mergeDescription(remote.description ?? '', desc, descriptionMode) : desc
|
|
54
|
+
log(`YouTube update · ${story.title} · https://www.youtube.com/watch?v=${update}`)
|
|
55
|
+
log(` title: ${remote ? JSON.stringify(remote.title) : '(remote)'} → ${JSON.stringify(story.title)}`)
|
|
56
|
+
log(` desc: ${descriptionMode}, ${merged.length} chars`)
|
|
57
|
+
log(` tags: ${tags.length ? tags.join(', ') : '(keep remote)'}`)
|
|
58
|
+
log(` captions: ${f.srt ? `replace uploaded tracks with ${basename(f.srt)}` : 'none (skipped)'}`)
|
|
59
|
+
log(` thumb: ${f.thumb ? `set ${basename(f.thumb)}` : 'skipped (none rendered)'}`)
|
|
60
|
+
if (dryRun) return log('dry run: nothing changed'), { dryRun: true }
|
|
61
|
+
await yt.updateMetadata(update, { title: story.title, description: merged, tags: tags.length ? tags : undefined })
|
|
62
|
+
if (srt) await yt.replaceCaptions(update, srt, locale)
|
|
63
|
+
if (thumb) await yt.setThumbnail(update, thumb)
|
|
64
|
+
recordLinks(p, slug, { youtube: update })
|
|
65
|
+
log(`updated; recorded in ${p.rel(storiesIndex(p))}`)
|
|
66
|
+
return { id: update, updated: true }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A new upload; refused when the story already has a video, unless --force-new. */
|
|
70
|
+
async function uploadYoutube(p, slug, yt, { story, f, desc, tags, srt, thumb }, { privacy, forceNew, dryRun, locale, log }) {
|
|
71
|
+
if (story.youtube && !forceNew)
|
|
72
|
+
die(`${slug} is already on YouTube as ${story.youtube}; pass --update ${story.youtube} to refresh it, or --force-new to upload again`)
|
|
73
|
+
log(`YouTube · ${story.title} · privacy ${privacy}`)
|
|
74
|
+
log(` video: ${basename(f.wide)} (${kb(f.wide)})`)
|
|
75
|
+
log(` desc: ${desc.length} chars, ${chapterCount(desc)} chapters`)
|
|
76
|
+
log(` tags: ${tags.slice(0, 10).join(', ')}`)
|
|
77
|
+
log(` captions: ${f.srt ? basename(f.srt) : 'none (continues without)'}`)
|
|
78
|
+
log(` thumb: ${f.thumb ? basename(f.thumb) : 'none (continues without)'}`)
|
|
79
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
80
|
+
const r = await yt.publish(readFileSync(f.wide), { title: story.title, description: desc, tags, privacy, srt, thumb, language: locale })
|
|
81
|
+
recordLinks(p, slug, { youtube: r.id })
|
|
82
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
83
|
+
return r
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function publishYoutube(p, slug, { locale, verify, dryRun, privacy = 'unlisted', update, forceNew, descriptionMode = 'prepend', env = process.env, fetch = globalThis.fetch, log = console.info } = {}) {
|
|
87
|
+
if (verify) return log(`YouTube posts as: ${await ytClient(env, fetch, log).verify()}`)
|
|
88
|
+
if (!PRIVACY.includes(privacy)) die('--privacy: public, unlisted or private')
|
|
89
|
+
if (!DESCRIPTION_MODES.includes(descriptionMode)) die('--description-mode: prepend or replace')
|
|
90
|
+
locale ??= p.site.defaultLocale
|
|
91
|
+
const yt = dryRun ? null : ytClient(env, fetch, log)
|
|
92
|
+
const piece = youtubePiece(p, slug, locale)
|
|
93
|
+
if (update) return updateYoutube(p, slug, yt, piece, { update, dryRun, descriptionMode, locale, log })
|
|
94
|
+
return uploadYoutube(p, slug, yt, piece, { privacy, forceNew, dryRun, locale, log })
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Public URLs Meta can fetch: the flags, else the files staged on the desk and signed for an hour. */
|
|
98
|
+
async function reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now }) {
|
|
99
|
+
if (videoUrl && coverUrl) return [videoUrl, coverUrl]
|
|
100
|
+
need(env, 'STAGER_CLIENT_ID', 'STAGER_CLIENT_SECRET', 'MEDIA_URL_SECRET')
|
|
101
|
+
if (!f.coverTall) die(`${slug}: no 9:16 cover; run \`emaki render ${slug}\` first`)
|
|
102
|
+
const desk = deskClient(p, { env, fetch }), urls = []
|
|
103
|
+
for (const [key, file, type] of [[`${slug}/${basename(f.tall)}`, f.tall, 'video/mp4'], [`${slug}/instagram-${basename(f.coverTall)}`, f.coverTall, 'image/jpeg']]) {
|
|
104
|
+
await desk.putMedia(key.toLowerCase(), readFileSync(file), type)
|
|
105
|
+
urls.push(await signMedia(key.toLowerCase(), env.MEDIA_URL_SECRET, desk.origin, 3600, now(), env.MEDIA_PATH || '/m'))
|
|
106
|
+
}
|
|
107
|
+
return urls
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
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 } = {}) {
|
|
111
|
+
const client = () => {
|
|
112
|
+
need(env, 'IG_USER_ID', 'IG_ACCESS_TOKEN')
|
|
113
|
+
return instagram({ userId: env.IG_USER_ID, token: env.IG_ACCESS_TOKEN, version: env.IG_GRAPH_VERSION || 'v21.0', fetch, ...(sleep ? { sleep } : {}) })
|
|
114
|
+
}
|
|
115
|
+
if (verify) return log(`Instagram posts as: @${await client().verify()}`)
|
|
116
|
+
if (Boolean(videoUrl) !== Boolean(coverUrl)) die('pass both --video-url and --cover-url, or neither (to stage them on the desk)')
|
|
117
|
+
locale ??= p.site.defaultLocale
|
|
118
|
+
const ig = dryRun ? null : client()
|
|
119
|
+
const story = storyFor(p, slug, locale), f = filmFiles(p, slug, locale)
|
|
120
|
+
if (!f.tall) die(`${slug}: no built 9:16 video (${p.rel(f.expect.tall)}); render and build the portrait film first`)
|
|
121
|
+
const dur = length(f.tall)
|
|
122
|
+
if (dur > 15 * 60) die(`${slug}: ${Math.round(dur)} s is over the 15-minute Reels limit`)
|
|
123
|
+
const pj = join(p.films, slug, `post.${locale}.json`)
|
|
124
|
+
const staged = exists(pj) ? load(pj).instagram_reel?.caption : null
|
|
125
|
+
const caption = staged || `${story.title}. ${story.dek}\n\nRead the story: ${storyUrl(p, slug, locale)}\n\n${hashtags(story.tags)}`
|
|
126
|
+
log(`Instagram Reel · ${slug} · ${Math.round(dur)} s`)
|
|
127
|
+
log(` video: ${basename(f.tall)} (${kb(f.tall)})`)
|
|
128
|
+
log(` cover: ${f.coverTall ? basename(f.coverTall) : 'none!'}`)
|
|
129
|
+
log(` caption: ${caption.length} chars`)
|
|
130
|
+
if (dryRun) return log('dry run: nothing posted'), { dryRun: true }
|
|
131
|
+
const [video, cover] = await reelUrls(p, slug, f, { videoUrl, coverUrl, env, fetch, now })
|
|
132
|
+
const r = await ig.publishReel(video, caption, cover)
|
|
133
|
+
recordLinks(p, slug, { instagram: r.url })
|
|
134
|
+
log(`posted: ${r.url}\nrecorded in ${p.rel(storiesIndex(p))}`)
|
|
135
|
+
return r
|
|
136
|
+
}
|
package/src/render.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// render: the film frame by frame to MP4 with its music, plus a cover JPEG per orientation (render.py). One job is
|
|
2
|
+
// shared by every layout; each layout captures its frames (or lays the music), then saves its covers.
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
import { SUFFIX } from './config.js'
|
|
7
|
+
import { encodeArgs, frameRange, musicFor, muxArgs, renderOut, renderSteps, staleRender } from './media.js'
|
|
8
|
+
import { chromium, evaluate, openShow, openSite } from './show-page.js'
|
|
9
|
+
import { die, mediaLength, run } from './util.js'
|
|
10
|
+
|
|
11
|
+
/** The score for the whole run, read once: the exported film's audio, the page's synthesised score (saved as
|
|
12
|
+
* score.wav), or null for a silent picture. */
|
|
13
|
+
async function scoreFor(job, call) {
|
|
14
|
+
if (job.music.kind !== 'synth') return job.music.kind === 'file' ? job.music.file : null
|
|
15
|
+
const b64 = await call(() => window.__show.audio())
|
|
16
|
+
if (!b64) return job.log(' the film has no score: silent picture'), null
|
|
17
|
+
const audio = join(job.out, 'score.wav')
|
|
18
|
+
writeFileSync(audio, Buffer.from(b64, 'base64'))
|
|
19
|
+
job.log(` score: ${job.p.rel(audio)}`)
|
|
20
|
+
return audio
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Seeks the page to each frame of the range and writes its JPEG to ffmpeg's stdin, waiting when the pipe is full. */
|
|
24
|
+
async function pipeFrames(job, page, call, ff, { layout, t0, end, frames }) {
|
|
25
|
+
const { fps, log } = job
|
|
26
|
+
for (let i = 0; i < frames; i++) {
|
|
27
|
+
await call((t) => window.__show.seek(t), t0 + i / fps)
|
|
28
|
+
const jpg = await page.screenshot({ type: 'jpeg', quality: 94 })
|
|
29
|
+
if (!ff.stdin.write(jpg)) await new Promise((r) => ff.stdin.once('drain', r))
|
|
30
|
+
if (i % (fps * 10) === 0) log(` ${layout} ${(t0 + i / fps).toFixed(1).padStart(6)}s / ${end.toFixed(1)}s`)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Captures the frames into <dst>.part.mp4 through ffmpeg (the score under them), then moves it into place. */
|
|
35
|
+
async function captureFrames(job, { page, meta, errors }, call, layout, dst) {
|
|
36
|
+
const { p, slug, fps, audio, log } = job
|
|
37
|
+
const range = frameRange(meta.duration, fps, job.from, job.to), { t0, end, frames, seconds } = range
|
|
38
|
+
log(`${slug}: ${layout} at ${fps} fps, ${t0 ? `${t0.toFixed(1)}–` : ''}${end.toFixed(1)} s, ${audio ? `music: ${job.mode}` : 'no music'}`)
|
|
39
|
+
const tmp = dst.replace(/\.mp4$/i, '.part.mp4')
|
|
40
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
41
|
+
const ff = spawn('ffmpeg', encodeArgs({ fps, seconds, dst: tmp, audio, t0 }), { stdio: ['pipe', 'inherit', 'inherit'] })
|
|
42
|
+
const done = new Promise((ok, bad) => { ff.on('close', (c) => (c ? bad(new Error('ffmpeg failed')) : ok())); ff.on('error', bad) })
|
|
43
|
+
const began = Date.now()
|
|
44
|
+
await pipeFrames(job, page, call, ff, { layout, ...range })
|
|
45
|
+
ff.stdin.end()
|
|
46
|
+
await done.catch((e) => die(e.message))
|
|
47
|
+
if (errors.length) die('the page reported errors: ' + errors.slice(0, 3).join('; '))
|
|
48
|
+
renameSync(tmp, dst)
|
|
49
|
+
log(` wrote ${p.rel(dst)} (${frames} frames, ${Math.round((Date.now() - began) / 1000)}s)`)
|
|
50
|
+
return dst
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** --audio-only: lays the score on the existing render, warning when the render no longer runs as long as the film. */
|
|
54
|
+
function layMusic(job, { meta }, dst) {
|
|
55
|
+
const { p, audio, from, to, log } = job
|
|
56
|
+
if (!existsSync(dst)) die(`--audio-only needs ${p.rel(dst)}; render it first`)
|
|
57
|
+
const dur = mediaLength(dst)
|
|
58
|
+
const stale = staleRender(dur, meta.duration, Boolean(from) || to != null)
|
|
59
|
+
if (stale) log(` warning: ${p.rel(dst)}: ${stale}`)
|
|
60
|
+
if (!audio) return log(` no music to lay on ${p.rel(dst)}`), dst
|
|
61
|
+
const tmp = dst.replace(/\.mp4$/i, '.mux.mp4')
|
|
62
|
+
run('ffmpeg', muxArgs(dst, audio, Number(from) || 0, dur, tmp))
|
|
63
|
+
renameSync(tmp, dst)
|
|
64
|
+
log(` music laid on ${p.rel(dst)}`)
|
|
65
|
+
return dst
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The cover frame as a JPEG; for landscape, also the site's cover (emaki.config.json coversDir) at 1600 px wide. */
|
|
69
|
+
async function saveCovers(job, { page, meta }, call, layout) {
|
|
70
|
+
const { p, slug, locale, log } = job
|
|
71
|
+
await call((t) => window.__show.seek(t), meta.cover)
|
|
72
|
+
const cover = join(job.out, `${slug}-${locale}-cover-${SUFFIX[layout]}.jpg`)
|
|
73
|
+
writeFileSync(cover, await page.screenshot({ type: 'jpeg', quality: 92 }))
|
|
74
|
+
log(` cover: ${p.rel(cover)} (film time ${meta.cover.toFixed(1)} s)`)
|
|
75
|
+
if (layout !== 'landscape' || !p.cfg.coversDir) return
|
|
76
|
+
const siteCover = join(p.root, p.cfg.coversDir, locale === p.site.defaultLocale ? `${slug}.jpg` : `${slug}.${locale}.jpg`)
|
|
77
|
+
mkdirSync(dirname(siteCover), { recursive: true })
|
|
78
|
+
run('ffmpeg', ['-y', '-loglevel', 'error', '-i', cover, '-vf', 'scale=1600:-2', '-q:v', '3', siteCover])
|
|
79
|
+
log(` cover for the site: ${p.rel(siteCover)}`)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One layout: the frames (or, with --audio-only, the music) as the steps say, then the covers. Returns the video. */
|
|
83
|
+
async function renderLayout(job, browser, site, layout) {
|
|
84
|
+
const show = await openShow(browser, site, job.slug, layout, job.locale)
|
|
85
|
+
const call = (fn, arg) => evaluate(show.page, fn, arg)
|
|
86
|
+
const dst = renderOut(job.out, job.slug, job.locale, layout, { out: job.target, layouts: job.layouts })
|
|
87
|
+
if (job.steps.music && job.audio === undefined) job.audio = await scoreFor(job, call)
|
|
88
|
+
let made = null
|
|
89
|
+
if (job.steps.frames) made = await captureFrames(job, show, call, layout, dst)
|
|
90
|
+
else if (job.steps.music) made = layMusic(job, show, dst)
|
|
91
|
+
await saveCovers(job, show, call, layout)
|
|
92
|
+
await show.page.close()
|
|
93
|
+
return made
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Frame-by-frame capture to MP4 with its music, plus a cover JPEG per orientation (render.py).
|
|
97
|
+
* `from`/`to` capture a range of film time; `out` is a file (one layout) or a folder. `music`: synth (the page's
|
|
98
|
+
* score, saved as score.wav), export (the audio of production/<slug>/<locale>/<slug>.mp4) or none. `audioOnly` lays
|
|
99
|
+
* the music on the existing render without capturing frames; `coverOnly` saves just the covers. */
|
|
100
|
+
export async function render(p, slug, {
|
|
101
|
+
locale, url, o = 'both', fps = 30, from = 0, to = undefined, out: target = undefined, music: mode = 'synth',
|
|
102
|
+
audioOnly = false, coverOnly = false, log = console.info
|
|
103
|
+
} = {}) {
|
|
104
|
+
p.filmDir(slug)
|
|
105
|
+
const steps = renderSteps({ audioOnly, coverOnly })
|
|
106
|
+
const layouts = o === 'both' ? ['landscape', 'portrait'] : [o]
|
|
107
|
+
const out = p.prod(slug, locale, 'render')
|
|
108
|
+
mkdirSync(out, { recursive: true })
|
|
109
|
+
const music = musicFor(mode, { exportFile: p.prod(slug, locale, `${slug}.mp4`), exists: existsSync })
|
|
110
|
+
if (steps.music && music.note) log(` ${music.note}`)
|
|
111
|
+
// What every layout shares; `audio` (the score) is read with the first layout's page and kept.
|
|
112
|
+
const job = { p, slug, locale, steps, music, mode, out, target, layouts: layouts.length, fps, from, to, log, audio: undefined }
|
|
113
|
+
const site = await openSite(p, url), made = []
|
|
114
|
+
const browser = await (await chromium()).launch()
|
|
115
|
+
try {
|
|
116
|
+
for (const layout of layouts) {
|
|
117
|
+
const dst = await renderLayout(job, browser, site, layout)
|
|
118
|
+
if (dst) made.push(dst)
|
|
119
|
+
}
|
|
120
|
+
return made
|
|
121
|
+
} finally {
|
|
122
|
+
await browser.close()
|
|
123
|
+
site.close()
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/show-page.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The capture page in headless Chromium: the site to capture (a running one, or the dev server started for the run),
|
|
2
|
+
// /show/<slug>?capture=1 opened at a layout's size, and page.evaluate that survives a reload. sheet, render and
|
|
3
|
+
// carousel use it. Playwright is an optional dependency: `npm i -D playwright && npx playwright install chromium`.
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import { connect } from 'node:net'
|
|
6
|
+
import { SIZES } from './config.js'
|
|
7
|
+
import { retrying } from './media.js'
|
|
8
|
+
import { die } from './util.js'
|
|
9
|
+
|
|
10
|
+
/** page.evaluate that survives the dev server reloading the page under it (a file saved mid-render): it waits for
|
|
11
|
+
* the show to come back and repeats the same call (render.py's call()). */
|
|
12
|
+
export const evaluate = (page, fn, arg) => retrying(() => page.evaluate(fn, arg), async () => {
|
|
13
|
+
await page.waitForFunction(() => window.__show, null, { timeout: 30000 })
|
|
14
|
+
await page.evaluate(() => window.__show.ready)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
export async function chromium() {
|
|
18
|
+
try {
|
|
19
|
+
return (await import('playwright')).chromium
|
|
20
|
+
} catch {
|
|
21
|
+
return die('sheet, render and carousel need Playwright: npm i -D playwright && npx playwright install chromium')
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const portOpen = (port) => new Promise((ok) => {
|
|
26
|
+
const s = connect({ port, host: '127.0.0.1' })
|
|
27
|
+
s.setTimeout(500)
|
|
28
|
+
s.once('connect', () => { s.destroy(); ok(true) })
|
|
29
|
+
s.once('error', () => ok(false))
|
|
30
|
+
s.once('timeout', () => { s.destroy(); ok(false) })
|
|
31
|
+
})
|
|
32
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
33
|
+
|
|
34
|
+
/** The site to capture: `url` if given (must answer), else the dev server (emaki.config.json devCommand), started if
|
|
35
|
+
* nothing listens on the port yet and stopped afterwards. */
|
|
36
|
+
export async function openSite(p, url) {
|
|
37
|
+
const port = p.cfg.port ?? 5199
|
|
38
|
+
let proc = null
|
|
39
|
+
const base = (url ?? `http://localhost:${port}`).replace(/\/$/, '')
|
|
40
|
+
if (url) {
|
|
41
|
+
try {
|
|
42
|
+
await fetch(url, { signal: AbortSignal.timeout(10000) })
|
|
43
|
+
} catch (e) {
|
|
44
|
+
die(`the site at ${url} is not responding (${e.message}); start it, or leave out --url to let emaki start it`)
|
|
45
|
+
}
|
|
46
|
+
} else if (!(await portOpen(port))) {
|
|
47
|
+
const cmd = (p.cfg.devCommand ?? 'npm run dev -- --port {port} --strictPort').replaceAll('{port}', String(port))
|
|
48
|
+
proc = spawn(cmd, { shell: true, cwd: p.root, stdio: 'ignore', detached: process.platform !== 'win32' })
|
|
49
|
+
let up = false
|
|
50
|
+
for (let i = 0; i < 120 && !(up = await portOpen(port)); i++) await sleep(500)
|
|
51
|
+
if (!up) { stop(); die(`the dev server did not start (${cmd})`) }
|
|
52
|
+
}
|
|
53
|
+
function stop() {
|
|
54
|
+
if (!proc) return
|
|
55
|
+
try { process.kill(-proc.pid) } catch { proc.kill() }
|
|
56
|
+
}
|
|
57
|
+
const showPath = p.cfg.showPath ?? '/show/{slug}?capture=1&o={layout}&locale={locale}'
|
|
58
|
+
return {
|
|
59
|
+
base,
|
|
60
|
+
show: (slug, layout, locale) => base + showPath.replaceAll('{slug}', slug).replaceAll('{layout}', layout).replaceAll('{locale}', locale),
|
|
61
|
+
close: stop
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A page on the capture route at the layout's size, once the show is ready; its meta and the errors it reports. */
|
|
66
|
+
export async function openShow(browser, site, slug, layout, locale) {
|
|
67
|
+
const [width, height] = SIZES[layout]
|
|
68
|
+
const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 })
|
|
69
|
+
const errors = []
|
|
70
|
+
page.on('pageerror', (e) => errors.push(String(e)))
|
|
71
|
+
await page.goto(site.show(slug, layout, locale))
|
|
72
|
+
await page.waitForFunction(() => window.__show, null, { timeout: 30000 })
|
|
73
|
+
await page.evaluate(() => window.__show.ready)
|
|
74
|
+
return { page, meta: await page.evaluate(() => window.__show.meta), errors }
|
|
75
|
+
}
|
package/src/stage.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
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
|
+
/** --channels (a list, or comma-separated) or every channel; an unknown name is refused. */
|
|
72
|
+
function wantedChannels(channels) {
|
|
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
|
+
return want
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Uploads a channel's files to the desk (once per key across channels; PNG as JPEG) and lists them with their hashes.
|
|
79
|
+
* Without a desk (dry run) nothing is sent and each hash is computed here. */
|
|
80
|
+
async function channelMedia(files, { slug, channel, desk, uploaded, toJpeg }) {
|
|
81
|
+
const media = []
|
|
82
|
+
for (const x of files) {
|
|
83
|
+
const path = x.path.endsWith('.png') ? toJpeg(x.path) : x.path
|
|
84
|
+
const name = (x.name ?? basename(path)).toLowerCase(), type = typeOf(path)
|
|
85
|
+
const key = `${slug}/${type === 'image/jpeg' ? `${channel.split('_')[0]}-${name}` : name}`
|
|
86
|
+
const bytes = readFileSync(path)
|
|
87
|
+
if (desk && !uploaded.has(key)) uploaded.set(key, await desk.putMedia(key, bytes, type))
|
|
88
|
+
media.push({ key, sha256: uploaded.get(key) ?? sha(bytes), type })
|
|
89
|
+
}
|
|
90
|
+
return media
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** One channel: skipped when a file is missing, printed on a dry run (no desk), else staged on the desk. */
|
|
94
|
+
async function stageChannel(p, slug, channel, [text, files], ctx) {
|
|
95
|
+
const { desk, log, result } = ctx
|
|
96
|
+
const missing = files.filter((x) => !x.path).map((x) => p.rel(x.expect))
|
|
97
|
+
if (missing.length) {
|
|
98
|
+
log(` ${channel}: skipped, missing ${missing.join(', ')}`)
|
|
99
|
+
result.skipped.push({ channel, missing })
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
const media = await channelMedia(files, { slug, channel, ...ctx })
|
|
103
|
+
const post = { ...text, media }
|
|
104
|
+
result.posts[channel] = post
|
|
105
|
+
if (!desk) return log(`--- ${channel}\n${JSON.stringify(post, null, 2)}`)
|
|
106
|
+
const r = await desk.stage(slug, channel, post)
|
|
107
|
+
log(` ${channel}: staged (${String(r.content_sha).slice(0, 10)}), ${media.length} file(s)`)
|
|
108
|
+
result.staged.push({ channel, content_sha: r.content_sha, files: media.length })
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function stage(p, slug, { locale, channels, dryRun = false, env = process.env, fetch = globalThis.fetch, log = console.info, toJpeg = pngToJpeg } = {}) {
|
|
112
|
+
locale ??= p.site.defaultLocale
|
|
113
|
+
const want = wantedChannels(channels)
|
|
114
|
+
const posts = postsFor(p, slug, locale)
|
|
115
|
+
const desk = dryRun ? null : deskClient(p, { env, fetch })
|
|
116
|
+
const ctx = { desk, log, toJpeg, uploaded: new Map(), result: { staged: [], skipped: [], posts: {} } }
|
|
117
|
+
for (const channel of CHANNELS.filter((c) => want.includes(c) && posts[c])) await stageChannel(p, slug, channel, posts[channel], ctx)
|
|
118
|
+
if (desk) log(`Review and approve on ${desk.origin}/admin`)
|
|
119
|
+
return ctx.result
|
|
120
|
+
}
|
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
|
+
}
|
package/src/takes.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// The recorded or synthesised takes of a film in a locale: production/<slug>/<locale>/takes/take-NN.<ext>, one per
|
|
2
|
+
// voice line, in voice/<locale>.json order.
|
|
3
|
+
import { existsSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { load, pad2 } from './util.js'
|
|
6
|
+
|
|
7
|
+
/** scene id → [take file, voice line] for the takes that exist. */
|
|
8
|
+
export function takesFor(p, slug, locale) {
|
|
9
|
+
const d = p.filmDir(slug), lines = load(join(d, 'voice', `${locale}.json`)), folder = p.prod(slug, locale, 'takes')
|
|
10
|
+
const out = new Map()
|
|
11
|
+
lines.forEach((l, i) => {
|
|
12
|
+
for (const ext of ['wav', 'mp3', 'm4a', 'aiff']) {
|
|
13
|
+
const f = join(folder, `take-${pad2(i + 1)}.${ext}`)
|
|
14
|
+
if (existsSync(f)) { out.set(l.scene, [f, l]); break }
|
|
15
|
+
}
|
|
16
|
+
})
|
|
17
|
+
return out
|
|
18
|
+
}
|