@appeeky/open-slideshow 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +227 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +9 -0
- package/dist/brand.d.ts +55 -0
- package/dist/brand.js +246 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +261 -0
- package/dist/decks.d.ts +44 -0
- package/dist/decks.js +90 -0
- package/dist/fonts.d.ts +45 -0
- package/dist/fonts.js +243 -0
- package/dist/gallery.d.ts +35 -0
- package/dist/gallery.js +109 -0
- package/dist/images.d.ts +49 -0
- package/dist/images.js +223 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +13 -0
- package/dist/lint.d.ts +33 -0
- package/dist/lint.js +181 -0
- package/dist/mcp.d.ts +3 -0
- package/dist/mcp.js +233 -0
- package/dist/publish.d.ts +100 -0
- package/dist/publish.js +401 -0
- package/dist/render.d.ts +73 -0
- package/dist/render.js +515 -0
- package/dist/schedule.d.ts +19 -0
- package/dist/schedule.js +114 -0
- package/dist/schema.d.ts +1004 -0
- package/dist/schema.js +174 -0
- package/dist/shape.d.ts +31 -0
- package/dist/shape.js +169 -0
- package/dist/skill.d.ts +7 -0
- package/dist/skill.js +17 -0
- package/dist/templates.d.ts +44 -0
- package/dist/templates.js +185 -0
- package/dist/text.d.ts +40 -0
- package/dist/text.js +230 -0
- package/dist/themes.d.ts +43 -0
- package/dist/themes.js +202 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/viral.d.ts +12 -0
- package/dist/viral.js +35 -0
- package/dist/workspace.d.ts +80 -0
- package/dist/workspace.js +306 -0
- package/package.json +65 -4
- package/skills/open-slideshow/SKILL.md +52 -0
- package/skills/open-slideshow/references/brand.md +54 -0
- package/skills/open-slideshow/references/channels.md +63 -0
- package/skills/open-slideshow/references/images.md +53 -0
- package/skills/open-slideshow/references/languages.md +41 -0
- package/skills/open-slideshow/references/publishing.md +70 -0
- package/skills/open-slideshow/references/review.md +74 -0
- package/skills/open-slideshow/references/templates.md +59 -0
- package/skills/open-slideshow/references/troubleshooting.md +82 -0
- package/skills/open-slideshow/references/writing.md +76 -0
package/dist/fonts.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import opentype from "opentype.js";
|
|
6
|
+
import { COMPLEX, initShaper, shaperReady, shapedWidth } from "./shape.js";
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
/** Latin, Cyrillic, Greek and Vietnamese fonts are OFL and ship inside the package. */
|
|
9
|
+
const FAMILIES = {
|
|
10
|
+
"TikTok Sans": { pkg: "tiktok-sans", prefix: "tiktok-sans", weights: [500, 600, 700, 800], subsets: ["latin", "latin-ext", "cyrillic", "cyrillic-ext", "greek", "vietnamese"], styles: ["normal"] },
|
|
11
|
+
Inter: { pkg: "inter", prefix: "inter", weights: [400, 600, 700], subsets: ["latin", "latin-ext", "cyrillic", "cyrillic-ext", "greek", "vietnamese"], styles: ["normal"] },
|
|
12
|
+
Anton: { pkg: "anton", prefix: "anton", weights: [400], subsets: ["latin", "latin-ext", "vietnamese"], styles: ["normal"] },
|
|
13
|
+
"Instrument Serif": { pkg: "instrument-serif", prefix: "instrument-serif", weights: [400], subsets: ["latin", "latin-ext"], styles: ["normal", "italic"] },
|
|
14
|
+
};
|
|
15
|
+
let faces = null;
|
|
16
|
+
const fontData = new WeakMap();
|
|
17
|
+
/** The file bytes behind a parsed font, for the shaper. */
|
|
18
|
+
export const fontBytes = (f) => fontData.get(f);
|
|
19
|
+
function filesDir(pkg) {
|
|
20
|
+
return join(dirname(require.resolve(`@fontsource/${pkg}`)), "files");
|
|
21
|
+
}
|
|
22
|
+
function loadFaces() {
|
|
23
|
+
if (faces)
|
|
24
|
+
return faces;
|
|
25
|
+
const out = [];
|
|
26
|
+
for (const [family, spec] of Object.entries(FAMILIES)) {
|
|
27
|
+
const dir = filesDir(spec.pkg);
|
|
28
|
+
for (const weight of spec.weights)
|
|
29
|
+
for (const style of spec.styles)
|
|
30
|
+
for (const subset of spec.subsets) {
|
|
31
|
+
const file = join(dir, `${spec.prefix}-${subset}-${weight}-${style}.woff`);
|
|
32
|
+
if (!existsSync(file))
|
|
33
|
+
continue;
|
|
34
|
+
const data = readFileSync(file);
|
|
35
|
+
const font = opentype.parse(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
|
|
36
|
+
fontData.set(font, { key: file, data });
|
|
37
|
+
out.push({ family, weight, style, subset, data, font });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
faces = out;
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
const faceName = (family, subset) => (subset === "latin" ? family : `${family} ${subset}`);
|
|
44
|
+
let fontList = null;
|
|
45
|
+
/** All faces, for satori. Satori does not fall back between faces of one name, so every subset gets its own name. The same array is kept between calls so satori can cache the parsed fonts. */
|
|
46
|
+
export function satoriFonts() {
|
|
47
|
+
fontList ??= [
|
|
48
|
+
...loadFaces().map((f) => ({ name: faceName(f.family, f.subset), data: f.data, weight: f.weight, style: f.style })),
|
|
49
|
+
...scriptFaces.map((f) => ({ name: SCRIPTS[f.pack].name, data: f.data, weight: f.weight, style: "normal" })),
|
|
50
|
+
];
|
|
51
|
+
return fontList;
|
|
52
|
+
}
|
|
53
|
+
/** The CSS font-family list: the family's subsets, Inter's for letters it lacks, then any loaded script fonts (in the deck language's order). */
|
|
54
|
+
export function fontStack(family, locale) {
|
|
55
|
+
const names = (fam) => FAMILIES[fam].subsets.map((sub) => `"${faceName(fam, sub)}"`);
|
|
56
|
+
const scripts = orderedPacks(locale)
|
|
57
|
+
.filter((p) => scriptFaces.some((f) => f.pack === p))
|
|
58
|
+
.map((p) => `"${SCRIPTS[p].name}"`);
|
|
59
|
+
return [...names(family), ...(family === "Inter" ? [] : names("Inter")), ...scripts].join(", ");
|
|
60
|
+
}
|
|
61
|
+
export const SCRIPTS = {
|
|
62
|
+
jp: { pkg: "noto-sans-jp", version: "5.3.1", subset: "japanese", name: "Noto Sans JP", label: "Japanese" },
|
|
63
|
+
sc: { pkg: "noto-sans-sc", version: "5.3.1", subset: "chinese-simplified", name: "Noto Sans SC", label: "Simplified Chinese" },
|
|
64
|
+
tc: { pkg: "noto-sans-tc", version: "5.3.1", subset: "chinese-traditional", name: "Noto Sans TC", label: "Traditional Chinese" },
|
|
65
|
+
kr: { pkg: "noto-sans-kr", version: "5.3.1", subset: "korean", name: "Noto Sans KR", label: "Korean" },
|
|
66
|
+
ar: { pkg: "noto-sans-arabic", version: "5.3.0", subset: "arabic", name: "Noto Sans Arabic", label: "Arabic" },
|
|
67
|
+
he: { pkg: "noto-sans-hebrew", version: "5.3.0", subset: "hebrew", name: "Noto Sans Hebrew", label: "Hebrew" },
|
|
68
|
+
th: { pkg: "noto-sans-thai", version: "5.3.0", subset: "thai", name: "Noto Sans Thai", label: "Thai" },
|
|
69
|
+
hi: { pkg: "noto-sans-devanagari", version: "5.3.0", subset: "devanagari", name: "Noto Sans Devanagari", label: "Devanagari (Hindi, Marathi, Nepali)" },
|
|
70
|
+
};
|
|
71
|
+
const SCRIPT_WEIGHTS = [400, 700];
|
|
72
|
+
const scriptFaces = [];
|
|
73
|
+
/** Han characters are drawn differently in Japan, China, Taiwan and Korea: the deck's language picks the font. */
|
|
74
|
+
function hanPack(locale, text) {
|
|
75
|
+
const l = (locale ?? "").toLowerCase();
|
|
76
|
+
if (l.startsWith("ja"))
|
|
77
|
+
return "jp";
|
|
78
|
+
if (/^zh-(tw|hk|mo|hant)/.test(l))
|
|
79
|
+
return "tc";
|
|
80
|
+
if (l.startsWith("zh"))
|
|
81
|
+
return "sc";
|
|
82
|
+
if (l.startsWith("ko"))
|
|
83
|
+
return "kr";
|
|
84
|
+
if (/[\u3040-\u30ff]/u.test(text))
|
|
85
|
+
return "jp";
|
|
86
|
+
return "sc";
|
|
87
|
+
}
|
|
88
|
+
export function orderedPacks(locale) {
|
|
89
|
+
const first = hanPack(locale, "");
|
|
90
|
+
return [first, ...["jp", "sc", "tc", "kr", "ar", "he", "th", "hi"].filter((p) => p !== first)];
|
|
91
|
+
}
|
|
92
|
+
/** The script fonts a text needs. */
|
|
93
|
+
export function packsFor(text, locale) {
|
|
94
|
+
const need = new Set();
|
|
95
|
+
if (/[\u3040-\u30ff]/u.test(text))
|
|
96
|
+
need.add("jp");
|
|
97
|
+
if (/\p{Script=Hangul}/u.test(text))
|
|
98
|
+
need.add("kr");
|
|
99
|
+
if (/\p{Script=Han}/u.test(text))
|
|
100
|
+
need.add(hanPack(locale, text));
|
|
101
|
+
if (/\p{Script=Arabic}/u.test(text))
|
|
102
|
+
need.add("ar");
|
|
103
|
+
if (/\p{Script=Hebrew}/u.test(text))
|
|
104
|
+
need.add("he");
|
|
105
|
+
if (/\p{Script=Thai}/u.test(text))
|
|
106
|
+
need.add("th");
|
|
107
|
+
if (/\p{Script=Devanagari}/u.test(text))
|
|
108
|
+
need.add("hi");
|
|
109
|
+
return [...need];
|
|
110
|
+
}
|
|
111
|
+
function fontCache() {
|
|
112
|
+
return join(process.env.OPEN_SLIDESHOW_CACHE ?? join(homedir(), ".cache", "open-slideshow"), "fonts");
|
|
113
|
+
}
|
|
114
|
+
function parseFont(data) {
|
|
115
|
+
return opentype.parse(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
|
|
116
|
+
}
|
|
117
|
+
async function fetchFace(pack, weight) {
|
|
118
|
+
const s = SCRIPTS[pack];
|
|
119
|
+
const file = join(fontCache(), `${s.pkg}-${s.version}-${s.subset}-${weight}.woff`);
|
|
120
|
+
if (existsSync(file))
|
|
121
|
+
return readFileSync(file);
|
|
122
|
+
if (process.env.OPEN_SLIDESHOW_OFFLINE === "1")
|
|
123
|
+
throw new Error("offline");
|
|
124
|
+
const res = await fetch(`https://cdn.jsdelivr.net/fontsource/fonts/${s.pkg}@${s.version}/${s.subset}-${weight}-normal.woff`, { signal: AbortSignal.timeout(60_000) });
|
|
125
|
+
if (!res.ok)
|
|
126
|
+
throw new Error(`HTTP ${res.status}`);
|
|
127
|
+
const data = Buffer.from(await res.arrayBuffer());
|
|
128
|
+
if (data.length > 15_000_000 || data.toString("latin1", 0, 4) !== "wOFF")
|
|
129
|
+
throw new Error("not a font file");
|
|
130
|
+
parseFont(data); // throws on a broken file, before it is cached
|
|
131
|
+
mkdirSync(fontCache(), { recursive: true });
|
|
132
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
133
|
+
writeFileSync(tmp, data);
|
|
134
|
+
renameSync(tmp, file);
|
|
135
|
+
return data;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Loads (downloading once, then from the cache) the fonts a text needs.
|
|
139
|
+
* Returns the scripts that could not be loaded, e.g. offline on first use.
|
|
140
|
+
*/
|
|
141
|
+
export async function ensureScriptFonts(text, locale) {
|
|
142
|
+
const failed = [];
|
|
143
|
+
if (COMPLEX.test(text))
|
|
144
|
+
await initShaper();
|
|
145
|
+
for (const pack of packsFor(text, locale)) {
|
|
146
|
+
if (scriptFaces.some((f) => f.pack === pack))
|
|
147
|
+
continue;
|
|
148
|
+
try {
|
|
149
|
+
const loaded = await Promise.all(SCRIPT_WEIGHTS.map(async (weight) => ({ pack, weight, data: await fetchFace(pack, weight) })));
|
|
150
|
+
for (const l of loaded) {
|
|
151
|
+
const font = parseFont(l.data);
|
|
152
|
+
fontData.set(font, { key: `${SCRIPTS[pack].pkg}-${l.weight}`, data: l.data });
|
|
153
|
+
scriptFaces.push({ ...l, font });
|
|
154
|
+
}
|
|
155
|
+
fontList = null;
|
|
156
|
+
glyphCache.clear();
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
failed.push(pack);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return failed;
|
|
163
|
+
}
|
|
164
|
+
/** The font that draws `ch` for a role: the role's own, Inter, then the script fonts. */
|
|
165
|
+
export function pickFont(role, ch, locale) {
|
|
166
|
+
return fontForChar(role, ch) ?? fontForChar(fallbackRole(role), ch) ?? scriptFontFor(ch, scriptWeight(role), locale);
|
|
167
|
+
}
|
|
168
|
+
/** Anton is a heavy face at weight 400: other scripts beside it take the bold cut. */
|
|
169
|
+
const scriptWeight = (role) => (role.family === "Anton" ? 700 : role.weight);
|
|
170
|
+
function scriptFontFor(ch, weight, locale) {
|
|
171
|
+
for (const pack of orderedPacks(locale)) {
|
|
172
|
+
const faces = scriptFaces.filter((f) => f.pack === pack);
|
|
173
|
+
if (!faces.length)
|
|
174
|
+
continue;
|
|
175
|
+
const face = faces.reduce((best, f) => (Math.abs(f.weight - weight) < Math.abs(best.weight - weight) ? f : best));
|
|
176
|
+
if (face.font.charToGlyphIndex(ch) > 0)
|
|
177
|
+
return face.font;
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
function facesFor(role) {
|
|
182
|
+
const all = loadFaces().filter((f) => f.family === role.family && f.style === (role.italic ? "italic" : "normal"));
|
|
183
|
+
const weights = [...new Set(all.map((f) => f.weight))];
|
|
184
|
+
const weight = weights.reduce((best, w) => (Math.abs(w - role.weight) < Math.abs(best - role.weight) ? w : best), weights[0] ?? 400);
|
|
185
|
+
return all.filter((f) => f.weight === weight);
|
|
186
|
+
}
|
|
187
|
+
const glyphCache = new Map();
|
|
188
|
+
function fontForChar(role, ch) {
|
|
189
|
+
const key = `${role.family}|${role.weight}|${role.italic ? 1 : 0}|${ch}`;
|
|
190
|
+
if (glyphCache.has(key))
|
|
191
|
+
return glyphCache.get(key);
|
|
192
|
+
const found = facesFor(role).find((f) => f.font.charToGlyphIndex(ch) > 0)?.font ?? null;
|
|
193
|
+
glyphCache.set(key, found);
|
|
194
|
+
return found;
|
|
195
|
+
}
|
|
196
|
+
const fallbackRole = (role) => ({ family: "Inter", weight: role.weight });
|
|
197
|
+
const invisible = (ch) => ch === "\u200d" || ch === "\ufe0f";
|
|
198
|
+
/** Characters no font here can draw. Whitespace and emoji are not counted: emoji are drawn as images. */
|
|
199
|
+
export function missingChars(role, text, locale) {
|
|
200
|
+
return glyphReport(role, text, locale).missing;
|
|
201
|
+
}
|
|
202
|
+
/** `fallback`: drawn in Inter because the theme's font lacks them. `missing`: no font here can draw them. */
|
|
203
|
+
export function glyphReport(role, text, locale) {
|
|
204
|
+
const fallback = new Set();
|
|
205
|
+
const missing = new Set();
|
|
206
|
+
for (const ch of text) {
|
|
207
|
+
if (/\s/u.test(ch) || isEmoji(ch) || invisible(ch))
|
|
208
|
+
continue;
|
|
209
|
+
if (fontForChar(role, ch))
|
|
210
|
+
continue;
|
|
211
|
+
if (fontForChar(fallbackRole(role), ch))
|
|
212
|
+
fallback.add(ch);
|
|
213
|
+
else if (!scriptFontFor(ch, scriptWeight(role), locale))
|
|
214
|
+
missing.add(ch);
|
|
215
|
+
}
|
|
216
|
+
return { fallback: [...fallback], missing: [...missing] };
|
|
217
|
+
}
|
|
218
|
+
export function isEmoji(ch) {
|
|
219
|
+
return /\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(ch);
|
|
220
|
+
}
|
|
221
|
+
/** Width of `text` in px at `size`, the way satori lays it out (advances plus letter spacing). */
|
|
222
|
+
export function measure(role, text, size, locale) {
|
|
223
|
+
let width = 0;
|
|
224
|
+
const tracking = (role.tracking ?? 0) * size;
|
|
225
|
+
// Joined letters are narrower than the letters alone: measure them as the shaper draws them.
|
|
226
|
+
if (COMPLEX.test(text) && shaperReady())
|
|
227
|
+
return shapedWidth(role, text, size, locale);
|
|
228
|
+
for (const ch of text) {
|
|
229
|
+
if (isEmoji(ch)) {
|
|
230
|
+
width += size * 1.15;
|
|
231
|
+
}
|
|
232
|
+
else if (ch === "" || ch === "️") {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
// A letter no font has (e.g. its font could not be downloaded) gets an average width.
|
|
237
|
+
const font = pickFont(role, ch, locale);
|
|
238
|
+
width += font ? (font.getAdvanceWidth(ch, size, { kerning: false }) || size * 0.3) : size * 0.6;
|
|
239
|
+
}
|
|
240
|
+
width += tracking;
|
|
241
|
+
}
|
|
242
|
+
return width;
|
|
243
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type Workspace } from "./workspace.js";
|
|
2
|
+
export interface Gallery {
|
|
3
|
+
sheet: string;
|
|
4
|
+
themes: {
|
|
5
|
+
id: string;
|
|
6
|
+
name: string;
|
|
7
|
+
design: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Every theme side by side. With a deck: its own cover and second slide; without: a sample about the app.
|
|
13
|
+
* The user looks at one picture and picks a theme.
|
|
14
|
+
*/
|
|
15
|
+
export declare function themeGallery(ws: Workspace, opts?: {
|
|
16
|
+
deck?: string;
|
|
17
|
+
slides?: number;
|
|
18
|
+
}): Promise<Gallery>;
|
|
19
|
+
export interface TemplateGallery {
|
|
20
|
+
sheet: string;
|
|
21
|
+
theme: string;
|
|
22
|
+
templates: {
|
|
23
|
+
id: string;
|
|
24
|
+
name: string;
|
|
25
|
+
description: string;
|
|
26
|
+
}[];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Every template as one row of example slides, in one theme, so the user sees the shapes and picks.
|
|
30
|
+
* Photo themes use the workspace's own photos when there are some, otherwise a made-up photo.
|
|
31
|
+
*/
|
|
32
|
+
export declare function templateGallery(ws: Workspace, opts?: {
|
|
33
|
+
theme?: string;
|
|
34
|
+
templates?: string[];
|
|
35
|
+
}): Promise<TemplateGallery>;
|
package/dist/gallery.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
import { contactSheet, laySlide, rasterize, tipNumbers } from "./render.js";
|
|
4
|
+
import { renderContext } from "./lint.js";
|
|
5
|
+
import { listImages } from "./images.js";
|
|
6
|
+
import { deckSchema, SIZES } from "./schema.js";
|
|
7
|
+
import { THEMES, getTheme } from "./themes.js";
|
|
8
|
+
import { TEMPLATES, assignSlots, getTemplate } from "./templates.js";
|
|
9
|
+
import { UserError } from "./workspace.js";
|
|
10
|
+
import { loadDeck, writeAtomic } from "./workspace.js";
|
|
11
|
+
/** A soft made-up photo so photo themes can be seen without any real image. */
|
|
12
|
+
async function samplePhoto() {
|
|
13
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1600"><defs><linearGradient id="s" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f3c9a0"/><stop offset="0.55" stop-color="#c98a6a"/><stop offset="1" stop-color="#3d3a4a"/></linearGradient><radialGradient id="g" cx="0.5" cy="0.62" r="0.5"><stop offset="0" stop-color="#ffe6b8" stop-opacity="0.9"/><stop offset="1" stop-color="#ffe6b8" stop-opacity="0"/></radialGradient></defs><rect width="1200" height="1600" fill="url(#s)"/><circle cx="600" cy="990" r="380" fill="url(#g)"/><path d="M0 1250 Q300 1150 600 1230 T1200 1200 V1600 H0Z" fill="#2b2a36"/></svg>`;
|
|
14
|
+
return sharp(Buffer.from(svg)).jpeg({ quality: 88 }).toBuffer();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Every theme side by side. With a deck: its own cover and second slide; without: a sample about the app.
|
|
18
|
+
* The user looks at one picture and picks a theme.
|
|
19
|
+
*/
|
|
20
|
+
export async function themeGallery(ws, opts = {}) {
|
|
21
|
+
let deck;
|
|
22
|
+
const own = listImages(ws).find((m) => m.width >= 600 && m.source !== "app-store");
|
|
23
|
+
let tmpPhoto;
|
|
24
|
+
if (opts.deck)
|
|
25
|
+
deck = loadDeck(ws, opts.deck);
|
|
26
|
+
else {
|
|
27
|
+
const name = ws.settings.brand.name ?? ws.settings.app.name ?? "your app";
|
|
28
|
+
if (!own) {
|
|
29
|
+
tmpPhoto = join(ws.state, "cache", "sample-photo.jpg");
|
|
30
|
+
writeAtomic(tmpPhoto, await samplePhoto());
|
|
31
|
+
}
|
|
32
|
+
const image = own ? own.ref : tmpPhoto;
|
|
33
|
+
const slides = [
|
|
34
|
+
{ kind: "cover", title: `3 things I wish I knew *before* ${name}`, image },
|
|
35
|
+
{ kind: "tip", title: "Start *smaller* than you think", body: "Five minutes a day beats one perfect hour a week.", image },
|
|
36
|
+
{ kind: "app", title: `This is why I use *${name}*`, body: ws.settings.brand.cta ?? "Free on the App Store." },
|
|
37
|
+
];
|
|
38
|
+
deck = deckSchema.parse({ id: "theme-preview", size: ws.settings.defaults.size, slides });
|
|
39
|
+
}
|
|
40
|
+
const count = Math.min(opts.slides ?? 2, deck.slides.length);
|
|
41
|
+
const buffers = [];
|
|
42
|
+
const labels = [];
|
|
43
|
+
const resolve = (ref) => (tmpPhoto && ref === tmpPhoto ? tmpPhoto : null);
|
|
44
|
+
for (const theme of THEMES) {
|
|
45
|
+
const ctx = { ...renderContext(ws, { ...deck, theme: theme.id }), images: new Map() };
|
|
46
|
+
const base = ctx.resolveImage;
|
|
47
|
+
ctx.resolveImage = (ref) => resolve(ref) ?? base(ref);
|
|
48
|
+
const nums = tipNumbers(deck.slides);
|
|
49
|
+
for (let i = 0; i < count; i++) {
|
|
50
|
+
const laid = await laySlide(ctx, { deck, slide: deck.slides[i], index: i, tipNumber: nums[i] });
|
|
51
|
+
buffers.push(await rasterize(laid.tree, deck.size, 80));
|
|
52
|
+
labels.push(i === 0 ? theme.id : "");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const sheet = join(ws.state, "cache", opts.deck ? `themes-${opts.deck}.jpg` : "themes.jpg");
|
|
56
|
+
writeAtomic(sheet, await contactSheet(buffers, deck.size, count * 2, labels));
|
|
57
|
+
return { sheet, themes: THEMES.map((t) => ({ id: t.id, name: t.name, design: t.design, description: t.description })) };
|
|
58
|
+
}
|
|
59
|
+
/** Which slot of the template each example slide fills, for the labels under the preview. */
|
|
60
|
+
function slotLabels(t, slides) {
|
|
61
|
+
const slots = assignSlots(t, slides.map((s) => s.kind));
|
|
62
|
+
return slides.map((_, i) => (slots ? t.slots[slots[i]].label : ""));
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Every template as one row of example slides, in one theme, so the user sees the shapes and picks.
|
|
66
|
+
* Photo themes use the workspace's own photos when there are some, otherwise a made-up photo.
|
|
67
|
+
*/
|
|
68
|
+
export async function templateGallery(ws, opts = {}) {
|
|
69
|
+
const themeId = opts.theme ?? ws.settings.defaults.theme;
|
|
70
|
+
if (!getTheme(themeId))
|
|
71
|
+
throw new UserError(`unknown theme "${themeId}"`);
|
|
72
|
+
const list = opts.templates?.length ? opts.templates.map((id) => getTemplate(id) ?? (() => { throw new UserError(`unknown template "${id}"`); })()) : TEMPLATES;
|
|
73
|
+
const name = ws.settings.brand.name ?? ws.settings.app.name ?? "your app";
|
|
74
|
+
const photos = listImages(ws).filter((m) => m.width >= 600 && m.source !== "app-store").map((m) => m.ref);
|
|
75
|
+
let fallback;
|
|
76
|
+
if (!photos.length) {
|
|
77
|
+
fallback = join(ws.state, "cache", "sample-photo.jpg");
|
|
78
|
+
writeAtomic(fallback, await samplePhoto());
|
|
79
|
+
}
|
|
80
|
+
const size = ws.settings.defaults.size;
|
|
81
|
+
const columns = Math.max(...list.map((t) => t.example(name).length));
|
|
82
|
+
const { width, height } = SIZES[size];
|
|
83
|
+
const blank = await sharp({ create: { width, height, channels: 3, background: "#f2f2f2" } }).jpeg().toBuffer();
|
|
84
|
+
const buffers = [];
|
|
85
|
+
const labels = [];
|
|
86
|
+
let p = 0;
|
|
87
|
+
for (const t of list) {
|
|
88
|
+
const slides = t.example(name).map((s) => ({ ...s, image: s.kind === "app" ? undefined : photos.length ? photos[p++ % photos.length] : fallback }));
|
|
89
|
+
const deck = deckSchema.parse({ id: "template-preview", size, theme: themeId, language: ws.settings.defaults.language, template: t.id, slides });
|
|
90
|
+
const ctx = { ...renderContext(ws, deck), images: new Map() };
|
|
91
|
+
const base = ctx.resolveImage;
|
|
92
|
+
ctx.resolveImage = (ref) => (fallback && ref === fallback ? fallback : base(ref));
|
|
93
|
+
const nums = tipNumbers(deck.slides);
|
|
94
|
+
const parts = slotLabels(t, deck.slides);
|
|
95
|
+
for (let i = 0; i < columns; i++) {
|
|
96
|
+
if (i >= deck.slides.length) {
|
|
97
|
+
buffers.push(blank);
|
|
98
|
+
labels.push("");
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const laid = await laySlide(ctx, { deck, slide: deck.slides[i], index: i, tipNumber: nums[i] });
|
|
102
|
+
buffers.push(await rasterize(laid.tree, size, 80));
|
|
103
|
+
labels.push(i === 0 ? `${t.name.toUpperCase()} · ${parts[i]}` : parts[i]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const sheet = join(ws.state, "cache", `templates-${themeId}.jpg`);
|
|
107
|
+
writeAtomic(sheet, await contactSheet(buffers, size, columns, labels));
|
|
108
|
+
return { sheet, theme: themeId, templates: list.map((t) => ({ id: t.id, name: t.name, description: t.description })) };
|
|
109
|
+
}
|
package/dist/images.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Workspace } from "./workspace.js";
|
|
2
|
+
export declare const MAX_IMAGE_BYTES: number;
|
|
3
|
+
export interface ImageMeta {
|
|
4
|
+
ref: string;
|
|
5
|
+
width: number;
|
|
6
|
+
height: number;
|
|
7
|
+
source: string;
|
|
8
|
+
license: string;
|
|
9
|
+
author?: string;
|
|
10
|
+
url?: string;
|
|
11
|
+
landing_url?: string;
|
|
12
|
+
attribution?: string;
|
|
13
|
+
note?: string;
|
|
14
|
+
imported_at: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function isPrivateAddress(ip: string): boolean;
|
|
17
|
+
/** Refuses URLs that point at this machine or a private network, before every hop. */
|
|
18
|
+
export declare function assertPublicUrl(raw: string): Promise<URL>;
|
|
19
|
+
export declare function download(raw: string, retried?: boolean): Promise<Buffer>;
|
|
20
|
+
/** Decodes, turns upright, strips metadata (GPS too) and stores the image as JPEG under images/. */
|
|
21
|
+
export declare function storeImage(ws: Workspace, input: Buffer, meta: Omit<ImageMeta, "ref" | "width" | "height" | "imported_at">): Promise<ImageMeta>;
|
|
22
|
+
export declare function importImageFromUrl(ws: Workspace, url: string, meta?: Partial<Omit<ImageMeta, "ref" | "width" | "height" | "imported_at">>): Promise<ImageMeta>;
|
|
23
|
+
/** A file the user has. Paths outside the workspace are fine to read (it is the user's machine), never to reference. */
|
|
24
|
+
export declare function importImageFromFile(ws: Workspace, path: string, meta?: Partial<Omit<ImageMeta, "ref" | "width" | "height" | "imported_at">>): Promise<ImageMeta>;
|
|
25
|
+
export declare function listImages(ws: Workspace): ImageMeta[];
|
|
26
|
+
export declare function imageMeta(ws: Workspace, ref: string): ImageMeta | null;
|
|
27
|
+
/** Licenses that need the author named somewhere: we put it in credits.txt and the caption suggestion. */
|
|
28
|
+
export declare function needsAttribution(m: ImageMeta | null): boolean;
|
|
29
|
+
export interface ImageHit {
|
|
30
|
+
provider: "openverse" | "unsplash" | "pexels";
|
|
31
|
+
id: string;
|
|
32
|
+
url: string;
|
|
33
|
+
thumb: string;
|
|
34
|
+
width?: number;
|
|
35
|
+
height?: number;
|
|
36
|
+
author?: string;
|
|
37
|
+
license: string;
|
|
38
|
+
landing_url?: string;
|
|
39
|
+
attribution?: string;
|
|
40
|
+
download_location?: string;
|
|
41
|
+
}
|
|
42
|
+
export declare function searchImages(query: string, opts?: {
|
|
43
|
+
provider?: ImageHit["provider"];
|
|
44
|
+
orientation?: "portrait" | "landscape" | "square";
|
|
45
|
+
limit?: number;
|
|
46
|
+
}): Promise<ImageHit[]>;
|
|
47
|
+
export declare function importHit(ws: Workspace, hit: ImageHit): Promise<ImageMeta>;
|
|
48
|
+
/** Thumbnails of the hits in one numbered picture, so the agent can look before it picks. */
|
|
49
|
+
export declare function hitsSheet(hits: ImageHit[]): Promise<Buffer | null>;
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lookup } from "node:dns/promises";
|
|
3
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
|
+
import { isIP } from "node:net";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import sharp from "sharp";
|
|
7
|
+
import { imagesDir, isInside, readJson, UserError, writeAtomic } from "./workspace.js";
|
|
8
|
+
export const MAX_IMAGE_BYTES = 25 * 1024 * 1024;
|
|
9
|
+
const MAX_PIXELS = 80_000_000;
|
|
10
|
+
const ALLOWED_FORMATS = new Set(["jpeg", "png", "webp", "avif", "heif", "gif", "tiff"]);
|
|
11
|
+
// ---------- network safety ----------
|
|
12
|
+
function privateV4(ip) {
|
|
13
|
+
const [a, b] = ip.split(".").map(Number);
|
|
14
|
+
return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224 || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19));
|
|
15
|
+
}
|
|
16
|
+
export function isPrivateAddress(ip) {
|
|
17
|
+
if (isIP(ip) === 4)
|
|
18
|
+
return privateV4(ip);
|
|
19
|
+
const v6 = ip.toLowerCase();
|
|
20
|
+
if (v6 === "::" || v6 === "::1")
|
|
21
|
+
return true;
|
|
22
|
+
const mapped = v6.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
|
|
23
|
+
if (mapped)
|
|
24
|
+
return privateV4(mapped[1]);
|
|
25
|
+
return v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe8") || v6.startsWith("fe9") || v6.startsWith("fea") || v6.startsWith("feb") || v6.startsWith("ff");
|
|
26
|
+
}
|
|
27
|
+
/** Refuses URLs that point at this machine or a private network, before every hop. */
|
|
28
|
+
export async function assertPublicUrl(raw) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(raw);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new UserError(`not a URL: ${raw}`);
|
|
35
|
+
}
|
|
36
|
+
if (url.protocol !== "https:")
|
|
37
|
+
throw new UserError("only https image URLs are allowed");
|
|
38
|
+
if (url.username || url.password)
|
|
39
|
+
throw new UserError("URLs with credentials are not allowed");
|
|
40
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
41
|
+
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal"))
|
|
42
|
+
throw new UserError("local addresses are not allowed");
|
|
43
|
+
const addrs = isIP(host) ? [{ address: host }] : await lookup(host, { all: true }).catch(() => {
|
|
44
|
+
throw new UserError(`cannot resolve ${host}`);
|
|
45
|
+
});
|
|
46
|
+
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address)))
|
|
47
|
+
throw new UserError(`${host} points to a private address`);
|
|
48
|
+
return url;
|
|
49
|
+
}
|
|
50
|
+
export async function download(raw, retried = false) {
|
|
51
|
+
let current = raw;
|
|
52
|
+
for (let hop = 0; hop < 4; hop++) {
|
|
53
|
+
const url = await assertPublicUrl(current);
|
|
54
|
+
const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(20_000), headers: { "user-agent": "open-slideshow" } });
|
|
55
|
+
if (res.status >= 300 && res.status < 400) {
|
|
56
|
+
const loc = res.headers.get("location");
|
|
57
|
+
if (!loc)
|
|
58
|
+
throw new UserError("redirect without a location");
|
|
59
|
+
current = new URL(loc, url).toString();
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (res.status === 429 || res.status === 503) {
|
|
63
|
+
const wait = Math.min(Number(res.headers.get("retry-after") ?? 2) || 2, 5);
|
|
64
|
+
if (!retried) {
|
|
65
|
+
await new Promise((r) => setTimeout(r, wait * 1000));
|
|
66
|
+
return download(raw, true);
|
|
67
|
+
}
|
|
68
|
+
throw new UserError(`${url.hostname} is limiting requests right now (HTTP ${res.status}); wait a minute or pick another image`);
|
|
69
|
+
}
|
|
70
|
+
if (!res.ok)
|
|
71
|
+
throw new UserError(`download failed: HTTP ${res.status}`);
|
|
72
|
+
const type = (res.headers.get("content-type") ?? "").split(";")[0].trim();
|
|
73
|
+
if (type && !type.startsWith("image/") && type !== "application/octet-stream")
|
|
74
|
+
throw new UserError(`not an image (${type})`);
|
|
75
|
+
if (type === "image/svg+xml")
|
|
76
|
+
throw new UserError("SVG images are not accepted");
|
|
77
|
+
const len = Number(res.headers.get("content-length") ?? 0);
|
|
78
|
+
if (len > MAX_IMAGE_BYTES)
|
|
79
|
+
throw new UserError("image is larger than 25 MB");
|
|
80
|
+
const chunks = [];
|
|
81
|
+
let total = 0;
|
|
82
|
+
for await (const chunk of res.body) {
|
|
83
|
+
total += chunk.byteLength;
|
|
84
|
+
if (total > MAX_IMAGE_BYTES)
|
|
85
|
+
throw new UserError("image is larger than 25 MB");
|
|
86
|
+
chunks.push(Buffer.from(chunk));
|
|
87
|
+
}
|
|
88
|
+
return Buffer.concat(chunks);
|
|
89
|
+
}
|
|
90
|
+
throw new UserError("too many redirects");
|
|
91
|
+
}
|
|
92
|
+
// ---------- storing ----------
|
|
93
|
+
/** Decodes, turns upright, strips metadata (GPS too) and stores the image as JPEG under images/. */
|
|
94
|
+
export async function storeImage(ws, input, meta) {
|
|
95
|
+
let info;
|
|
96
|
+
try {
|
|
97
|
+
info = await sharp(input, { limitInputPixels: MAX_PIXELS }).metadata();
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
throw new UserError("the file is not an image that can be read");
|
|
101
|
+
}
|
|
102
|
+
if (!info.format || !ALLOWED_FORMATS.has(info.format))
|
|
103
|
+
throw new UserError(`image format ${info.format ?? "unknown"} is not accepted (use JPEG, PNG, WebP, AVIF or HEIC)`);
|
|
104
|
+
if ((info.width ?? 0) < 200 || (info.height ?? 0) < 200)
|
|
105
|
+
throw new UserError(`image is too small (${info.width}×${info.height}); use at least 600 px`);
|
|
106
|
+
const out = await sharp(input, { limitInputPixels: MAX_PIXELS, animated: false })
|
|
107
|
+
.rotate()
|
|
108
|
+
.resize({ width: 2160, height: 2700, fit: "inside", withoutEnlargement: true })
|
|
109
|
+
.flatten({ background: "#ffffff" })
|
|
110
|
+
.jpeg({ quality: 90, mozjpeg: true })
|
|
111
|
+
.toBuffer({ resolveWithObject: true });
|
|
112
|
+
const sha = createHash("sha256").update(out.data).digest("hex").slice(0, 16);
|
|
113
|
+
const ref = `${sha}.jpg`;
|
|
114
|
+
const dir = imagesDir(ws);
|
|
115
|
+
const file = join(dir, ref);
|
|
116
|
+
const full = { ref, width: out.info.width, height: out.info.height, ...meta, imported_at: new Date().toISOString() };
|
|
117
|
+
if (!existsSync(file))
|
|
118
|
+
writeAtomic(file, out.data);
|
|
119
|
+
const metaFile = join(dir, `${sha}.json`);
|
|
120
|
+
if (!existsSync(metaFile))
|
|
121
|
+
writeAtomic(metaFile, JSON.stringify(full, null, 2));
|
|
122
|
+
return readJson(metaFile, full);
|
|
123
|
+
}
|
|
124
|
+
export async function importImageFromUrl(ws, url, meta = {}) {
|
|
125
|
+
const buf = await download(url);
|
|
126
|
+
return storeImage(ws, buf, { source: meta.source ?? "url", license: meta.license ?? "unknown", url, ...meta });
|
|
127
|
+
}
|
|
128
|
+
/** A file the user has. Paths outside the workspace are fine to read (it is the user's machine), never to reference. */
|
|
129
|
+
export async function importImageFromFile(ws, path, meta = {}) {
|
|
130
|
+
if (!existsSync(path))
|
|
131
|
+
throw new UserError(`no file at ${path}`);
|
|
132
|
+
const st = statSync(path);
|
|
133
|
+
if (!st.isFile())
|
|
134
|
+
throw new UserError(`${path} is not a file`);
|
|
135
|
+
if (st.size > MAX_IMAGE_BYTES)
|
|
136
|
+
throw new UserError("image is larger than 25 MB");
|
|
137
|
+
if (/\.svgz?$/i.test(path))
|
|
138
|
+
throw new UserError("SVG images are not accepted");
|
|
139
|
+
return storeImage(ws, readFileSync(path), { source: meta.source ?? "local", license: meta.license ?? "own", ...meta });
|
|
140
|
+
}
|
|
141
|
+
export function listImages(ws) {
|
|
142
|
+
const dir = imagesDir(ws);
|
|
143
|
+
if (!existsSync(dir))
|
|
144
|
+
return [];
|
|
145
|
+
return readdirSync(dir)
|
|
146
|
+
.filter((f) => /^[0-9a-f]{16}\.json$/.test(f))
|
|
147
|
+
.map((f) => readJson(join(dir, f), null))
|
|
148
|
+
.filter((m) => !!m && existsSync(join(dir, m.ref)) && isInside(dir, join(dir, m.ref)));
|
|
149
|
+
}
|
|
150
|
+
export function imageMeta(ws, ref) {
|
|
151
|
+
const m = ref.match(/([0-9a-f]{16})\.jpg$/);
|
|
152
|
+
if (!m)
|
|
153
|
+
return null;
|
|
154
|
+
return readJson(join(imagesDir(ws), `${m[1]}.json`), null);
|
|
155
|
+
}
|
|
156
|
+
/** Licenses that need the author named somewhere: we put it in credits.txt and the caption suggestion. */
|
|
157
|
+
export function needsAttribution(m) {
|
|
158
|
+
return !!m && /^(by|cc-by|cc by)/i.test(m.license);
|
|
159
|
+
}
|
|
160
|
+
const OPENVERSE_PAGE = 20;
|
|
161
|
+
export async function searchImages(query, opts = {}) {
|
|
162
|
+
const limit = Math.min(Math.max(opts.limit ?? 12, 1), 30);
|
|
163
|
+
const provider = opts.provider ?? (process.env.UNSPLASH_ACCESS_KEY ? "unsplash" : process.env.PEXELS_API_KEY ? "pexels" : "openverse");
|
|
164
|
+
const q = encodeURIComponent(query.slice(0, 200));
|
|
165
|
+
if (provider === "unsplash") {
|
|
166
|
+
const key = process.env.UNSPLASH_ACCESS_KEY;
|
|
167
|
+
if (!key)
|
|
168
|
+
throw new UserError("set UNSPLASH_ACCESS_KEY (your own key from unsplash.com/developers) to search Unsplash");
|
|
169
|
+
const res = await fetch(`https://api.unsplash.com/search/photos?query=${q}&per_page=${limit}${opts.orientation ? `&orientation=${opts.orientation === "square" ? "squarish" : opts.orientation}` : ""}`, { headers: { authorization: `Client-ID ${key}`, "accept-version": "v1" }, signal: AbortSignal.timeout(15_000) });
|
|
170
|
+
if (!res.ok)
|
|
171
|
+
throw new UserError(`Unsplash: HTTP ${res.status}`);
|
|
172
|
+
const data = (await res.json());
|
|
173
|
+
return data.results.map((r) => ({ provider, id: r.id, url: r.urls.full, thumb: r.urls.small, width: r.width, height: r.height, author: r.user.name, license: "unsplash", landing_url: r.links.html, attribution: `Photo by ${r.user.name} on Unsplash`, download_location: r.links.download_location }));
|
|
174
|
+
}
|
|
175
|
+
if (provider === "pexels") {
|
|
176
|
+
const key = process.env.PEXELS_API_KEY;
|
|
177
|
+
if (!key)
|
|
178
|
+
throw new UserError("set PEXELS_API_KEY (your own key from pexels.com/api) to search Pexels");
|
|
179
|
+
const res = await fetch(`https://api.pexels.com/v1/search?query=${q}&per_page=${limit}${opts.orientation ? `&orientation=${opts.orientation}` : ""}`, { headers: { authorization: key }, signal: AbortSignal.timeout(15_000) });
|
|
180
|
+
if (!res.ok)
|
|
181
|
+
throw new UserError(`Pexels: HTTP ${res.status}`);
|
|
182
|
+
const data = (await res.json());
|
|
183
|
+
return data.photos.map((p) => ({ provider, id: String(p.id), url: p.src.original, thumb: p.src.medium, width: p.width, height: p.height, author: p.photographer, license: "pexels", landing_url: p.url, attribution: `Photo by ${p.photographer} on Pexels` }));
|
|
184
|
+
}
|
|
185
|
+
// Openverse needs no key; anonymous requests get at most 20 results a page (more is a 401). Only licenses that allow changes and commercial use: no ND, no NC, no SA.
|
|
186
|
+
const res = await fetch(`https://api.openverse.org/v1/images/?q=${q}&license=cc0,pdm,by&size=large&page_size=${Math.min(limit * 2, OPENVERSE_PAGE)}&mature=false${opts.orientation ? `&aspect_ratio=${opts.orientation === "portrait" ? "tall" : opts.orientation === "landscape" ? "wide" : "square"}` : ""}`, { headers: { "user-agent": "open-slideshow" }, signal: AbortSignal.timeout(15_000) });
|
|
187
|
+
if (!res.ok)
|
|
188
|
+
throw new UserError(`Openverse: HTTP ${res.status}`);
|
|
189
|
+
const data = (await res.json());
|
|
190
|
+
return data.results
|
|
191
|
+
.filter((r) => ["cc0", "pdm", "by"].includes(r.license) && (!r.width || !r.height || Math.min(r.width, r.height) >= 700))
|
|
192
|
+
.slice(0, limit)
|
|
193
|
+
.map((r) => ({ provider: "openverse", id: r.id, url: r.url, thumb: r.thumbnail, width: r.width, height: r.height, author: r.creator, license: r.license === "by" ? `by-${r.license_version ?? "4.0"}` : r.license, landing_url: r.foreign_landing_url, attribution: r.attribution }));
|
|
194
|
+
}
|
|
195
|
+
export async function importHit(ws, hit) {
|
|
196
|
+
if (hit.provider === "unsplash" && hit.download_location && process.env.UNSPLASH_ACCESS_KEY) {
|
|
197
|
+
// Unsplash's rules: count a download when a photo is used.
|
|
198
|
+
await fetch(hit.download_location, { headers: { authorization: `Client-ID ${process.env.UNSPLASH_ACCESS_KEY}` }, signal: AbortSignal.timeout(10_000) }).catch(() => undefined);
|
|
199
|
+
}
|
|
200
|
+
return importImageFromUrl(ws, hit.url, { source: hit.provider, license: hit.license, author: hit.author, landing_url: hit.landing_url, attribution: hit.attribution });
|
|
201
|
+
}
|
|
202
|
+
/** Thumbnails of the hits in one numbered picture, so the agent can look before it picks. */
|
|
203
|
+
export async function hitsSheet(hits) {
|
|
204
|
+
const thumbs = await Promise.all(hits.map(async (h) => {
|
|
205
|
+
try {
|
|
206
|
+
// Openverse's own thumbnails fail now and then (HTTP 424): fall back to the image itself.
|
|
207
|
+
const buf = await download(h.thumb).catch(() => download(h.url));
|
|
208
|
+
return await sharp(buf, { limitInputPixels: MAX_PIXELS }).rotate().resize(300, 375).jpeg().toBuffer();
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}));
|
|
214
|
+
const ok = [];
|
|
215
|
+
thumbs.forEach((t, i) => {
|
|
216
|
+
if (t)
|
|
217
|
+
ok.push({ t, i });
|
|
218
|
+
});
|
|
219
|
+
if (!ok.length)
|
|
220
|
+
return null;
|
|
221
|
+
const { contactSheet } = await import("./render.js");
|
|
222
|
+
return contactSheet(ok.map((x) => x.t), "4:5", Math.min(ok.length, 6), ok.map((x) => `${x.i + 1}. ${hits[x.i].license}`));
|
|
223
|
+
}
|