Skip to content

Commit 897eefe

Browse files
committed
fix: align agency-client-report-videos with cookbook standards
1 parent f4a5ab1 commit 897eefe

5 files changed

Lines changed: 228 additions & 49 deletions

File tree

Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
11
# Agency client report videos
22

3-
Render one monthly report video for each client an agency manages. Each client record has a brand
4-
color and an accent color. It also has the month's numbers: accounts reached, engagement rate,
5-
new followers, reach by week and the top post. The script builds a vertical 1080 x 1920 video from
6-
the numbers: three animated figures, a bar chart and the top post. You get one 20 second MP4 per
7-
client, in the client's colors, and a file that records which render belongs to which client.
3+
Render one monthly report video for each agency client. Each video shows three figures, a weekly reach chart and the top post. You get one 20-second vertical MP4 per client, with the client's colours.
84

95
## Requirements
106

11-
- A [Shotstack account](https://dashboard.shotstack.io/register) and your **sandbox** API key
7+
- A [Shotstack account](https://dashboard.shotstack.io/register) and your sandbox API key
128
- Node.js 20 or later
139

14-
Sandbox renders are watermarked. Your account needs at least one credit to use the sandbox.
10+
Sandbox videos have a watermark.
1511

1612
## Setup
1713

@@ -20,18 +16,17 @@ git clone https://github.com/shotstack/shotstack-cookbook.git
2016
cd shotstack-cookbook/examples/agency-client-report-videos
2117
```
2218

23-
Copy the environment file. Add your sandbox key to `.env`.
19+
Copy the environment file:
2420

2521
```bash
2622
cp .env.example .env
2723
```
2824

29-
Load the file into your shell. Do this in each new terminal:
25+
Add your sandbox API key to `.env`. Load the file in each new terminal:
3026

3127
```bash
32-
set -a
3328
source .env
34-
set +a
29+
export SHOTSTACK_API_KEY SHOTSTACK_ENV
3530
```
3631

3732
## Run
@@ -42,38 +37,39 @@ Submit one render per client:
4237
node render.mjs
4338
```
4439

45-
Then check them:
40+
Check each render:
4641

4742
```bash
4843
node status.mjs
4944
```
5045

51-
Run `status.mjs` again until each render shows `done`.
46+
Run `status.mjs` again until each render shows `done` or `failed`.
47+
48+
To run the local checks without an API key:
49+
50+
```bash
51+
node regression-check.mjs
52+
```
5253

5354
## What happens
5455

55-
`render.mjs` reads `clients.json` and checks each client record. A record needs a slug, a name of
56-
30 characters or fewer, a month and two hex colors. It also needs the three figures and at least
57-
two weekly values. The top post needs a caption, a likes number and an HTTPS image. The script
58-
reports every problem it finds, then stops.
59-
For each client it builds one Edit JSON and submits one render. The video has four scenes. A
60-
title card names the client and the month. Three tiles show accounts reached, engagement rate and
61-
new followers. A bar chart shows accounts reached by week. The top post appears with its caption
62-
and its likes. The client name and the month stay at the top from the second scene. The agency
63-
name stays at the bottom. A music track plays under the whole video. The background is the
64-
client's brand color. The figures and the bars use the accent color. The script appends one line per render to `renders.jsonl` and ends with the count
65-
of submitted renders.
56+
`render.mjs` checks all records in `clients.json` before it submits any renders. Each record needs a slug, a client name, a month and two six-digit hex colours. The client name must have 30 characters or fewer.
57+
58+
Each record also needs reach, engagement rate, new followers and at least two weekly reach numbers. The top post needs a caption, a likes number and a public HTTPS image URL. The script reports invalid records and stops before it submits any renders.
6659

67-
`status.mjs` reads `renders.jsonl` and checks each render once. A `done` render prints its video
68-
URL.
60+
Each 1080 x 1920 video has four scenes: a title, three figure tiles, a weekly reach chart and the top post. The client name and month appear above the last three scenes. The agency name appears below every scene. Music plays throughout the video.
6961

70-
The tiles and the chart are `html5` assets. The script writes the numbers into the HTML before
71-
the render. GSAP fades and lifts the tiles, and grows the bars. D3 draws the chart. Both libraries
72-
are available inside every `html5` asset. You do not need a script tag.
62+
The tiles and chart use `html5` assets. D3 draws the chart. GSAP animates the tiles and bars. Both libraries are available inside these assets.
7363

74-
To render your own clients, replace the records in `clients.json`. The top post image must be a
75-
public HTTPS URL. To change the agency name at the bottom, the scenes or the layout, edit `edit.mjs`.
64+
`render.mjs` appends each render ID and client slug to `renders.jsonl`. It prints the number of submitted renders. `status.mjs` checks each recorded render once. A completed render prints its video URL.
7665

77-
`renders.jsonl` only appends. Delete the file to start a new batch.
66+
Replace the records in `clients.json` to render your own clients. Edit `edit.mjs` to change the agency name, scenes or layout.
7867

79-
To render in production, set `SHOTSTACK_ENV=v1` and put your production key in `.env`.
68+
Each run of `render.mjs` submits another batch. Delete `renders.jsonl` to clear the local render records. This does not delete submitted renders.
69+
70+
For production renders, export your production environment and API key:
71+
72+
```bash
73+
export SHOTSTACK_ENV="v1"
74+
export SHOTSTACK_API_KEY="your_production_api_key"
75+
```

‎examples/agency-client-report-videos/api.mjs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,7 @@ function stopBatch(message) {
2424
return Object.assign(new Error(message), { fatal: true });
2525
}
2626

27-
async function apiError(response) {
28-
const text = await response.text();
29-
27+
function apiError(text) {
3028
try {
3129
const body = JSON.parse(text);
3230
return (
@@ -39,6 +37,7 @@ async function apiError(response) {
3937

4038
async function request(path, options, label) {
4139
let response;
40+
let text;
4241

4342
try {
4443
response = await fetch(`${API}${path}`, {
@@ -50,6 +49,7 @@ async function request(path, options, label) {
5049
},
5150
signal: AbortSignal.timeout(TIMEOUT_MS)
5251
});
52+
text = await response.text();
5353
} catch {
5454
throw stopBatch(
5555
`${label}: the network request failed. Check your connection and run again.`
@@ -63,10 +63,22 @@ async function request(path, options, label) {
6363
}
6464

6565
if (!response.ok) {
66-
throw new Error(`${label}: ${response.status} ${await apiError(response)}`);
66+
throw new Error(
67+
`${label}: ${response.status} ${String(apiError(text)).replace(/\s+/g, ' ')}`
68+
);
6769
}
6870

69-
return (await response.json()).response;
71+
try {
72+
const data = JSON.parse(text).response;
73+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
74+
throw new Error();
75+
}
76+
return data;
77+
} catch {
78+
throw stopBatch(
79+
`${label}: the API returned an invalid response. Try again later.`
80+
);
81+
}
7082
}
7183

7284
export async function submitRender(edit, label) {
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
const INPUT = 'clients.json';
2+
const BAD_FIELDS = [
3+
['name', 42],
4+
['month', 8],
5+
['topPost', null],
6+
['brandColor', { toString: null }]
7+
];
8+
9+
import assert from 'node:assert/strict';
10+
import { spawnSync } from 'node:child_process';
11+
import {
12+
copyFileSync,
13+
mkdtempSync,
14+
readFileSync,
15+
readdirSync,
16+
rmSync,
17+
writeFileSync
18+
} from 'node:fs';
19+
import { tmpdir } from 'node:os';
20+
import { join } from 'node:path';
21+
22+
// Only fetch is replaced; each check runs the actual CLI and file handling.
23+
const source = new URL('.', import.meta.url);
24+
const directory = mkdtempSync(join(tmpdir(), 'cookbook-check-'));
25+
const log = join(directory, 'requests.log');
26+
let passed = 0;
27+
28+
try {
29+
for (const file of readdirSync(source).filter(name =>
30+
/\.(mjs|json)$/.test(name)
31+
)) {
32+
copyFileSync(new URL(file, source), join(directory, file));
33+
}
34+
const sample = JSON.parse(readFileSync(join(directory, INPUT), 'utf8'));
35+
const loader = join(directory, 'fetch.mjs');
36+
writeFileSync(
37+
loader,
38+
`
39+
import { appendFileSync } from 'node:fs';
40+
globalThis.fetch = async () => {
41+
appendFileSync(process.env.REQUEST_LOG, 'request\\n');
42+
if (process.env.CHECK_CASE === 'network') throw new TypeError('fetch failed');
43+
if (process.env.CHECK_CASE.startsWith('body')) {
44+
return new Response(new ReadableStream({
45+
start(controller) { controller.error(new TypeError('terminated')); }
46+
}), { status: process.env.CHECK_CASE === 'body-error' ? 500 : 200 });
47+
}
48+
if (process.env.CHECK_CASE === 'auth') return Response.json({}, { status: 403 });
49+
if (process.env.CHECK_CASE === 'invalid-response') return new Response('not json');
50+
return Response.json({ response: { id: 'test-render', status: 'done', url: 'https://example.com/video.mp4' } });
51+
};
52+
`
53+
);
54+
55+
function run(mode, data = sample, script = 'render.mjs') {
56+
writeFileSync(join(directory, INPUT), JSON.stringify(data));
57+
writeFileSync(log, '');
58+
const result = spawnSync(
59+
process.execPath,
60+
['--import', loader, join(directory, script)],
61+
{
62+
encoding: 'utf8',
63+
env: {
64+
PATH: process.env.PATH,
65+
SHOTSTACK_API_KEY: mode === 'missing' ? '' : 'test-key',
66+
SHOTSTACK_ENV: mode === 'environment' ? 'invalid' : 'stage',
67+
CHECK_CASE: mode,
68+
REQUEST_LOG: log
69+
}
70+
}
71+
);
72+
const requests = readFileSync(log, 'utf8')
73+
.trim()
74+
.split('\n')
75+
.filter(Boolean).length;
76+
return { ...result, requests };
77+
}
78+
79+
for (const mode of [
80+
'missing',
81+
'environment',
82+
'auth',
83+
'network',
84+
'body',
85+
'body-error',
86+
'invalid-response'
87+
]) {
88+
const result = run(mode);
89+
assert.equal(result.status, 1, mode);
90+
assert.equal(result.stderr.trim().split('\n').length, 1, mode);
91+
assert.match(result.stderr, /Set |Check |must be|Try again/i, mode);
92+
assert.equal(
93+
result.requests,
94+
['missing', 'environment'].includes(mode) ? 0 : 1,
95+
mode
96+
);
97+
passed++;
98+
}
99+
100+
const invalid = [null, ...(Array.isArray(sample) ? [[null]] : [])];
101+
for (const [field, value] of BAD_FIELDS) {
102+
const data = structuredClone(sample);
103+
(Array.isArray(data) ? data[0] : data)[field] = value;
104+
invalid.push(data);
105+
}
106+
for (const data of invalid) {
107+
const result = run('valid', data);
108+
assert.equal(result.status, 1);
109+
assert.equal(
110+
result.requests,
111+
0,
112+
'Invalid input must fail before submission'
113+
);
114+
assert.doesNotMatch(result.stderr, /TypeError|at file:|at ModuleJob/);
115+
passed++;
116+
}
117+
118+
const result = run('valid');
119+
assert.equal(result.status, 0, result.stderr);
120+
const count = Array.isArray(sample) ? sample.length : 1;
121+
assert.equal(result.requests, count);
122+
assert.equal(
123+
readFileSync(join(directory, 'renders.jsonl'), 'utf8').trim().split('\n')
124+
.length,
125+
count
126+
);
127+
passed++;
128+
129+
writeFileSync(join(directory, 'renders.jsonl'), 'null\n');
130+
const status = run('valid', sample, 'status.mjs');
131+
assert.equal(status.status, 1);
132+
assert.equal(
133+
status.requests,
134+
0,
135+
'Invalid tracking rows must fail before requests'
136+
);
137+
assert.doesNotMatch(status.stderr, /TypeError|at file:|at ModuleJob/);
138+
assert.match(status.stderr, /renders\.jsonl.*(Fix|Check)/);
139+
passed++;
140+
141+
console.log(passed + ' checks passed');
142+
} finally {
143+
rmSync(directory, { recursive: true, force: true });
144+
}

‎examples/agency-client-report-videos/render.mjs‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,28 @@ if (!Array.isArray(clients) || clients.length === 0) {
2626
const problems = [];
2727

2828
clients.forEach((client, index) => {
29-
const label = client.slug ?? `client ${index + 1}`;
29+
if (!client || typeof client !== 'object' || Array.isArray(client)) {
30+
problems.push(`client ${index + 1}: provide a client object.`);
31+
return;
32+
}
33+
34+
const label =
35+
typeof client.slug === 'string' && client.slug.trim()
36+
? client.slug
37+
: `client ${index + 1}`;
3038

3139
for (const field of REQUIRED_TEXT) {
32-
if (!client[field]) {
33-
problems.push(`${label}: ${field} is required.`);
40+
if (typeof client[field] !== 'string' || !client[field].trim()) {
41+
problems.push(`${label}: set ${field} to a nonempty string.`);
3442
}
3543
}
3644

37-
if (client.name && client.name.length > 30) {
45+
if (typeof client.name === 'string' && client.name.length > 30) {
3846
problems.push(`${label}: name must be 30 characters or fewer.`);
3947
}
4048

4149
for (const field of ['brandColor', 'accentColor']) {
42-
if (client[field] && !HEX_COLOR.test(client[field])) {
50+
if (typeof client[field] === 'string' && !HEX_COLOR.test(client[field])) {
4351
problems.push(`${label}: ${field} must be a six-digit hex color.`);
4452
}
4553
}
@@ -58,13 +66,28 @@ clients.forEach((client, index) => {
5866
problems.push(`${label}: weeklyReach must list at least two numbers.`);
5967
}
6068

61-
const post = client.topPost ?? {};
69+
const post = client.topPost;
70+
71+
if (!post || typeof post !== 'object' || Array.isArray(post)) {
72+
problems.push(`${label}: provide a topPost object.`);
73+
return;
74+
}
6275

63-
if (!post.caption || !Number.isFinite(post.likes)) {
64-
problems.push(`${label}: topPost needs a caption and a likes number.`);
76+
if (
77+
typeof post.caption !== 'string' ||
78+
!post.caption.trim() ||
79+
!Number.isFinite(post.likes)
80+
) {
81+
problems.push(
82+
`${label}: topPost needs a caption string and a likes number.`
83+
);
6584
}
6685

67-
if (!/^https:\/\//.test(post.image ?? '')) {
86+
if (
87+
typeof post.image !== 'string' ||
88+
!URL.canParse(post.image) ||
89+
new URL(post.image).protocol !== 'https:'
90+
) {
6891
problems.push(`${label}: topPost.image must be an HTTPS URL.`);
6992
}
7093
});

‎examples/agency-client-report-videos/renders.mjs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,14 @@ export async function readRenders() {
3030
.filter(line => line.trim())
3131
.map((line, index) => {
3232
try {
33-
return JSON.parse(line);
33+
const row = JSON.parse(line);
34+
if (!row || typeof row.renderId !== 'string' || !row.renderId.trim()) {
35+
throw new Error();
36+
}
37+
return row;
3438
} catch {
3539
throw new Error(
36-
`renders.jsonl line ${index + 1} is not valid JSON. Fix or delete the file and submit again.`
40+
`renders.jsonl line ${index + 1} must contain a JSON object with a renderId. Fix the file and run again.`
3741
);
3842
}
3943
});

0 commit comments

Comments
 (0)