diff --git a/apps/skills/tests/author-verify.test.ts b/apps/skills/tests/author-verify.test.ts index e3baace..756ac1e 100644 --- a/apps/skills/tests/author-verify.test.ts +++ b/apps/skills/tests/author-verify.test.ts @@ -139,8 +139,12 @@ describe.concurrent('every type file', () => { for (const path of paths(source.params)) if (!/^https?:/.test(path)) await writeFile(join(folder, path), sample(path)) const output = join(folder, 'example.h5p') const result = await buildPackage(source, output, { base: folder }) - // The demo's clip, every video's sample, has no sound, and the build says so (#218). - expect(result.notes.filter(({ message }) => !/\.mp4 has no sound$/.test(message))).toEqual([]) + // The demo's clip, every video's sample, has no sound, and the build says so (#218). And what + // an example places on its picture or times on its video by numbers alone is noted in every + // build, for whoever looks at the preview (#260). + const expected = (message: string) => /\.mp4 has no sound$/.test(message) || + /^holds \d+ \w+ (?:placed by numbers, which a build cannot hold to the (?:picture|map): look at (?:it|each) in the preview|shown at the times written, which a build cannot hold to what the video shows then: play it through in the preview)$/.test(message) + expect(result.notes.filter(({ message }) => !expected(message))).toEqual([]) await checksAsSaved(output) await playsBothWays(output) }, 180_000) diff --git a/design/author.md b/design/author.md index bcfcd08..d59c3ec 100644 --- a/design/author.md +++ b/design/author.md @@ -125,6 +125,50 @@ text to the content check's rules, and `apps/skills` plays every example untrust media goes through the normalizer's `normalizeArchive`, stored and laid out to stream. An addon whose pattern the text matches, H5P.MathDisplay for LaTeX, is carried as a site with it installed exports it. +- **A file's facts are one command away, and what only eyes can check is a note** (#260). For five + types a source holds numbers that mean something only against a file: an Interactive Video's + times, and the places of Image Hotspots' hotspots, of Find the Hotspot's and Find Multiple + Hotspots' areas and of Game Map's stages. + - `h5p-author media …`, `describeMedia` and the local MCP server's + `h5p_media` say what a file is before a source names it, by the build's own readers + (`MediaStore.describe`): a picture's size, a played file's container, an mp4's length and + what a build notes of its tracks, a hosted video's host and the length it says; a file at a + web address is downloaded as a check downloads it. `mediaLine` is each in a line. It needs + no pack. Measured on 2026-11-25 in Claude Code, a 10 s mp4 attached and nothing said of its + length: with the skill's "know the video's length" alone, Haiku and Sonnet each wrote an mp4 + parser of their own before the source in 6 of 6 runs, over routes 1 to 3; with `media` + named in the skill, they ran it and wrote none in 4 of 4 on route 1. + - **Vimeo says a video's length, and an Interactive Video's times are held to it.** Its oEmbed + answer for a video it has carries `duration` in whole seconds (`length` in `HOSTED`); + YouTube's carries none, and Panopto and Echo360 are not asked. It counts only as JSON that + names Vimeo with a length above zero, so a box that answers 200 for the host says none. A + time is past such a video's end only a second beyond the length, for the rounding, and the + problem says whose word the length is. + - **A build says the length it held the times to.** A result's `lengths` has it for each + Interactive Video's video, by the name the source gives it, and the command line and both + servers say each (`lengthLine`), so that whoever changes the times next starts from it. + - **What is placed or timed by numbers alone is a note of the build's**, one for each list of + hotspots, areas, stages or an Interactive Video's interactions (not its bookmarks or end + screens), saying how many and to look at them in the preview (`byNumber` in `types.mjs`). It + is said whether or not a model looked at the file, since only a person's eyes check a place + or a moment; and by the build, not `checkContent`, so a check of saved content says none. + The skill passes a build's notes on. Its own sentence in the brief, to ask the user to check + them, reached the reply in 6 of 16 runs; with the note, in 8 of 8. + - Not built: the length of a WebM, an Ogg, a WAV or an MP3; asking the person for a video's + moments; a grid drawn over a picture. Shown a picture of five shapes 5 % of its width + across, Haiku and Sonnet placed a hotspot on each within one percent in 14 of 14 runs with + no grid, and opened a picture named only by its path in 5 of 5; other chats' models were not + measured. +- **A chat's attachment is copied beside the source and named by its name** (#266). Measured on + 2026-11-25 in Claude Code as a chat with a code sandbox, the attachment's folder said as a + chat's sandbox says it, with a picture for an Image Hotspots and a 10 s mp4 for an Interactive + Video, on routes 1 to 3, and with a picture named only by its path on route 2: Haiku and Sonnet built + in 16 of 16 runs, 14 at the first build, each + copying the file beside its source and naming it by its name alone, none by a path made up. + The build's line said "1 media file" in all, and the verifier, where npm answered, passed. + The two that lost a round: an Interactive Video's text written as H5P.AdvancedText, which its + field does not take, as the type file now says; and a bundle unzipped into `parts/`, leaving + the index at `parts/parts`. - **A build that acts on what a model wrote can be confined** (#220, for the local MCP server of #219). The command line reads any path a source names and fetches any address, which is right for a person's own command. @@ -480,7 +524,7 @@ text to the content check's rules, and `apps/skills` plays every example untrust `poolSize` is set, Memory Game draws pairs, at least 2, and Crossword keeps the words fixed on the grid and draws only among the rest. Not looked for: a select tied to the content, as Multiple Choice's single or multiple answers; Advanced Blanks' gaps against its - list and its snippets by name; a Game Map restriction's stage id; video times (#260). + list and its snippets by name; a Game Map restriction's stage id. Each says what to write. `lib/mistakes.mjs` runs in `checkContent`, so a build says them and so does a check of saved content, and every type file's example says none. Of the owner's 88 real packages, the 79 checked against their own libraries give 36 notes of a picture with no alt diff --git a/design/mcp.md b/design/mcp.md index 76fd706..128212e 100644 --- a/design/mcp.md +++ b/design/mcp.md @@ -14,11 +14,18 @@ below. `previewPackage`, `openBrowser`) are h5p-verify's. A rule a tool needs goes into those packages first, exported, so the author package and the verifier are published before a server that uses something new of theirs. -- **Four tools, and the skill's flow as the instructions.** `h5p_types` lists the pack's content +- **Five tools, and the skill's flow as the instructions.** `h5p_types` lists the pack's content types, those with a type file marked, and the skill's brief; given a type, read as a build reads one (`sourceType`, so "true false" works), it answers with the type's file, or with `schemaOf` for a type with none. `h5p_build` builds a source, `h5p_preview` opens a package, and `h5p_read` - reads one back into its source. The instructions are the flow in a few lines: the type is the one + reads one back into its source. `h5p_media` says what a file is before a source names it, an + mp4's or a Vimeo video's length first (`describeMedia`, author's #260): an app with no shell cannot read one + another way. It reads as a build reads a source's files, a name alone from the first folder, a + local file only in the folders, a web address only on the public internet, and answers in + words alone. Asked for an Interactive Video of a 10 s clip in the folder, Haiku in Claude Code + with these tools alone built twice in 3 of 3 runs without it, once after a refusal and twice + leaving a first package whose question started as the clip ended; with it, it asked the + length first and built once in 3 of 3 (2026-11-25). The instructions are the flow in a few lines: the type is the one question, its answer is read before the source is written, then the build, where the file is and what the check found, and the preview offered; a package the person has is read, its source changed, and built. Not `SKILL.md`, which is served as a skill instead (below): it is mostly @@ -63,7 +70,8 @@ below. goes its source, `.source.json`, which the build page opens to change and build again; it is made new, never written over or through a link, and where it cannot be, the answer says so. - **A build answers with the content, the check and a picture.** The build's line, the H5P core a - site needs (`coreApiLine`), its notes, the + site needs (`coreApiLine`), the length an Interactive Video's times were held to + (`lengthLine`), its notes, the outline (80 lines at most) and, with `verify`, the default, the verifier's summary of a check run in a temporary folder, with its screenshot as an image. Where neither Chrome, Edge nor Playwright's Chromium is found, the answer says "Not verified" and why. A source with problems @@ -86,8 +94,8 @@ below. - **Tested as an app runs it.** `tests/server.test.ts` starts the command over standard input and output with the SDK's own client, given one folder, and calls each tool: the list, a type by a loose name and one with no file, a build checked in Chromium, a taken name and a link at one, - two builds at once, a source with a problem, an output outside the folder, a preview served and - one refused. Each test builds what it needs, so each runs alone. The test script first copies + two builds at once, a source with a problem, an output outside the folder, a file's facts and + one outside the folder, a preview served and one refused. Each test builds what it needs, so each runs alone. The test script first copies the skill's type files into the author package, as the author's `prepack` does. Not built yet: the MCP registry's `server.json` and Claude Desktop's one-click bundle. diff --git a/packages/author/README.md b/packages/author/README.md index 1467226..58d96c0 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -197,6 +197,31 @@ styles pasted from Word, is said, to fix before building. It never writes over a is untrusted: only the files its content names are written, only under the folder, and a file named by a path that could lead out of it is left out of the source. +## What a file is + +```bash +npx @missing-elements/h5p-author@latest media clip.mp4 delta.png https://vimeo.com/76979871 +``` + +``` +clip.mp4: an MP4 video, 10 s long +delta.png: a PNG picture, 1200 by 800 pixels +https://vimeo.com/76979871: a video on Vimeo, about 62 s long +``` + +For whoever writes a source that names a file: an Interactive Video's starts have to be within its +video's length, and an agent with no way to learn it wrote a parser of its own, or guessed. Each +file is read as a build reads it: a picture's size from its header, an mp4's length and whether it +has sound from its index, a Vimeo video's length as Vimeo gives it, in whole seconds. A WebM's, an +Ogg's, a WAV's or an MP3's length is not read, and YouTube says none. A file that no source can +name is said on standard error, and the command then exits with 1. It needs no libraries. + +A build of an Interactive Video says the length it held the times to, and refuses a start, a +bookmark or an end screen past it (for a Vimeo video, more than a second past the length Vimeo +gives, which is whole seconds); an interaction may end past it. What a source places on a picture or times on a video by +numbers alone, hotspots, areas, stages and interactions, it notes, since only a look at the preview +says whether a hotspot sits on what it names. + ## A content type's bundle ```bash @@ -272,6 +297,12 @@ source, the media written beside it by the paths it names them by, and what was not come back as it is, each `{ path, message }`. With `within`, the package and the folder must be inside those folders, on their real paths. +`describeMedia(sources, { base, within, fetch })` says what files are, as `h5p-author media` +does: for each path or web address, in their order, `{ source, kind, format, width, height, +seconds, host, notes, problem }`, with only what was read, and `mediaLine(facts)` is one in a +line. A result's `lengths` is the length each Interactive Video's times were held to, `{ file, +seconds, host }` by the name the source gives the video, and `lengthLine(length)` says one. + A result's `builtWith` is the content type and the pack's version of it, `H5P.Blanks 1.14`, and its `source` the source as built, naming it: what to keep with the package, as the command line writes it beside one; `buildPackage` writes the package alone. A result's `libraries` are the diff --git a/packages/author/bin/h5p-author.mjs b/packages/author/bin/h5p-author.mjs index acbab33..58bc337 100755 --- a/packages/author/bin/h5p-author.mjs +++ b/packages/author/bin/h5p-author.mjs @@ -2,13 +2,14 @@ import { lstat, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises' import { dirname, relative, resolve } from 'node:path' import { parseArgs } from 'node:util' -import { buildPackage, coreApiLine, readPackage, schemaOf, SourceError, writeBundle, writeBundles } from '../lib/author.mjs' +import { buildPackage, coreApiLine, describeMedia, lengthLine, mediaLine, readPackage, schemaOf, SourceError, writeBundle, writeBundles } from '../lib/author.mjs' import { packVersion } from '../lib/node.mjs' const USAGE = `Usage: h5p-author build [--libraries ] h5p-author build --check [--libraries ] h5p-author read [--libraries ] + h5p-author media ... h5p-author schema [--markdown] [--all] [--libraries ] h5p-author bundle [--libraries ] h5p-author bundle --all [--libraries ] @@ -21,6 +22,9 @@ build Makes a playable .h5p from a source: { "type", "title", "language", "lic read Writes the source a build would take to make a package again into a folder, with the package's media beside it: to change it and build it again. Reads content made for the pack's versions of its libraries; never writes over a file. +media Says what each file is before a source names it: a picture's size, a video's + length and whether it has sound; of a video on Vimeo, the length Vimeo gives. + Run it before writing an Interactive Video's times. Needs no libraries. schema Prints a content type's fields as a source writes them: --markdown as a skill's type file carries them, --all with the interface texts. bundle Writes the libraries a build of one content type reads, as a zip of a parts/ @@ -147,6 +151,8 @@ try { const install = result.install.length ? `, ${result.install.length} more for installing on an H5P site` : '' console.log(`${check ? 'Checked, no package written' : `Built ${result.output}`}: ${result.manifest.mainLibrary}, ${result.libraries.length} libraries from ${from}${install}${result.media.length ? `, ${result.media.length} media file${result.media.length === 1 ? '' : 's'}` : ''}.`) if (!check) console.log(coreApiLine(result.coreApi)) + // The length an Interactive Video's times were held to, for whoever changes them next (#260). + for (const length of result.lengths) console.log(lengthLine(length)) if (kept) console.log(`Its source, naming ${result.builtWith} as what it was built with, is ${kept}: hand it over with the package.`) const language = String(result.manifest.language) if (!/^en(?:-|$)/i.test(language)) { @@ -161,6 +167,12 @@ try { } for (const { path, message } of result.notes) console.warn(`Note: ${path} ${message}`) if (!check) console.log('Not verified: run npx @missing-elements/h5p-verify@latest on it and look at its screenshot before handing it over.') + } else if (command === 'media') { + if (!rest.length) throw new Error('media takes the files to look at: h5p-author media clip.mp4 map.png') + for (const flag of Object.keys(flags)) throw new Error(`media does not take --${flag}`) + const facts = await describeMedia(rest) + for (const each of facts) (each.problem ? console.error : console.log)(mediaLine(each)) + if (facts.some((each) => each.problem)) process.exitCode = 1 } else if (command === 'read') { if (rest.length !== 2) throw new Error('read takes a package and a folder to write its source in: h5p-author read quiz.h5p quiz') for (const flag of Object.keys(flags)) if (flag !== 'libraries') throw new Error(`read does not take --${flag}`) diff --git a/packages/author/lib/author.mjs b/packages/author/lib/author.mjs index 2ca75e0..9378eeb 100644 --- a/packages/author/lib/author.mjs +++ b/packages/author/lib/author.mjs @@ -6,7 +6,8 @@ * loads them (`openPack`, `loadLibraries`, and `packageLibraries` for a package's own), its rules * for text (`markupText`, `plainText`, `allowedTags`), and the check it runs last on what it writes, * for saved content (`checkContent`). `readPackage` reads a package back into its source, to change - * it and build it again. A content type's bundle (`writeBundle`) carries the parts a + * it and build it again. `describeMedia` says what a picture, a video or a recording is before a + * source names it: a video's length, a picture's size. A content type's bundle (`writeBundle`) carries the parts a * build of it reads, for a build where the pack cannot be installed. This is the entry for Node: * `./core` is what of it needs no Node, and `./browser` builds in a page. */ @@ -17,12 +18,14 @@ import { schemaLines, schemaMarkdown } from './schema.mjs' import { LAYOUTS } from './types.mjs' export * from './core.mjs' -export { buildPackage, inside, openPack, publicFetch, readPackage, writeBundle, writeBundles } from './node.mjs' +export { buildPackage, describeMedia, inside, openPack, publicFetch, readPackage, writeBundle, writeBundles } from './node.mjs' /** * @typedef {import('./node.mjs').BuildResult} BuildResult * @typedef {import('./node.mjs').BuildOptions} BuildOptions * @typedef {import('./node.mjs').BundleResult} BundleResult + * @typedef {import('./node.mjs').DescribeOptions} DescribeOptions + * @typedef {import('./node.mjs').MediaFacts} MediaFacts * @typedef {import('./node.mjs').ReadResult} ReadResult * @typedef {import('./node.mjs').ReadOptions} ReadOptions */ diff --git a/packages/author/lib/browser.mjs b/packages/author/lib/browser.mjs index d8f8c21..adb2fc4 100644 --- a/packages/author/lib/browser.mjs +++ b/packages/author/lib/browser.mjs @@ -29,14 +29,15 @@ export * from './core.mjs' * library with its part's URL * @typedef {{ * blob: Blob, source: import('./build.mjs').Source, builtWith: string, manifest: Record, content: Record, libraries: string[], install: string[], - * coreApi: import('./install.mjs').CoreApi, translations: import('./translate.mjs').TranslationReport[], notes: import('./build.mjs').Problem[], media: string[], linked: string[], outline: string + * coreApi: import('./install.mjs').CoreApi, translations: import('./translate.mjs').TranslationReport[], notes: import('./build.mjs').Problem[], media: string[], lengths: import('./media.mjs').MediaLength[], linked: string[], outline: string * }} BuildResult the package, and what is worth telling about it: `libraries`, the folders it plays * with; `install`, those it carries for an H5P site's upload check; `coreApi`, the newest H5P core * they ask for, which a site needs to take the package (`coreApiLine` says it); `outline`, the * content as text for a review (`outlineOf`); `builtWith`, the content type and the pack's version * of it, "H5P.Blanks 1.14", and `source`, the source as built, naming it: what to keep with the - * package, so that a build with a later pack can say the type has moved; `media`, the files it - * carries, and `linked`, the files the source names that were left at an address: where there is + * package, so that a build with a later pack can say the type has moved; `lengths`, the length + * of each video an Interactive Video's times were held to (`lengthLine` says one); `media`, the + * files it carries, and `linked`, the files the source names that were left at an address: where there is * one, the package is a preview and not a file to keep, since the address may stop answering * @typedef {{ libraries: Pack | PackIndex | string | URL, files?: Map | Record, linked?: Map | Record, fetch?: typeof fetch }} BuildOptions * `libraries`, a pack `openPack` opened, which a page keeps for its builds, or what to open one @@ -216,6 +217,7 @@ export async function buildPackage(input, options) { translations: built.translations, notes: built.notes, media: media.files.map((item) => item.name), + lengths: built.lengths, linked: [...media.linked], get outline() { return built.outline } } diff --git a/packages/author/lib/build.mjs b/packages/author/lib/build.mjs index ab63f16..4edeadc 100644 --- a/packages/author/lib/build.mjs +++ b/packages/author/lib/build.mjs @@ -11,7 +11,7 @@ import { outlineOf } from './outline.mjs' import { SourceError } from './source-error.mjs' import { authorHolds, holds, NO_FIELD, NO_SOURCE, sourceSchema, TYPE } from './source-schema.mjs' import { escapeText } from './text.mjs' -import { LAYOUTS, placesOf, videoTimes } from './types.mjs' +import { byNumber, LAYOUTS, placesOf, videoTimes } from './types.mjs' export { SourceError } @@ -257,11 +257,12 @@ function stamped(source, builtWith) { * @param {import('./media.mjs').MediaStore} media * @param {Problem[]} [said] the problems `sourceOf` found in the source's own fields, which come * first among the content's: all of them in one round (#174) - * @returns {Promise<{ source: Source, builtWith: string, manifest: Record, content: Record, selected: Map, install: Map, coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], outline: string }>} + * @returns {Promise<{ source: Source, builtWith: string, manifest: Record, content: Record, selected: Map, install: Map, coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], lengths: import('./media.mjs').MediaLength[], outline: string }>} * `selected`, the libraries the package plays with; `install`, those an H5P site's upload check wants with them; `coreApi`, the * newest H5P core any of them asks for (`coreApiOf`); `outline`, the * content as text for a review (`outlineOf`), made when it is first read; `builtWith`, the - * content type and the version the pack has of it, and `source`, the source naming it (`stamped`) + * content type and the version the pack has of it, and `source`, the source naming it (`stamped`); + * `lengths`, the length of each video an Interactive Video's times were held to (#260) * @internal */ export async function composePackage(source, pack, media, said = []) { @@ -334,8 +335,17 @@ export async function composePackage(source, pack, media, said = []) { // Times past the end of a video whose length was read, which only a build, with the file, knows; // none in a list an item of which was refused, whose indices are no longer the source's. const timed = (/** @type {string} */ path, /** @type {string} */ message) => { if (!shortened(path)) report(path, message) } + // The length each Interactive Video's times were held to, which a build's output says (#260). + /** @type {import('./media.mjs').MediaLength[]} */ + const lengths = [] for (const place of placesOf(main, checked.params)) { - if (place.library === 'H5P.InteractiveVideo') videoTimes(place.params, inSource(place.path), (file) => media.lengthOf(file), timed) + if (place.library === 'H5P.InteractiveVideo') { + const length = videoTimes(place.params, inSource(place.path), (file) => media.lengthOf(file), timed) + if (length && !lengths.some(({ file }) => file === length.file)) lengths.push(length) + } + // What is placed or timed by numbers alone, which only a person looking at it can check. + const numbered = byNumber(place.library, place.params) + if (numbered) note(`${inSource(place.path)}.${numbered.at}`, numbered.message) } // What the source was last built with, where this pack has another version of the type: said // with the problems, which a field that changed since may have made, and a note where it builds. @@ -375,7 +385,7 @@ export async function composePackage(source, pack, media, said = []) { let outline return { source: stamped(source, builtWith), builtWith, - manifest, content, selected, install, translations, notes, + manifest, content, selected, install, translations, notes, lengths, coreApi: coreApiOf([...selected.values(), ...install.values()].map((part) => part.library)), // Made when it is first read: it is for a review, which only some callers make, and a build // that never reads it never runs it. diff --git a/packages/author/lib/core.mjs b/packages/author/lib/core.mjs index ccbfe39..41928fe 100644 --- a/packages/author/lib/core.mjs +++ b/packages/author/lib/core.mjs @@ -2,8 +2,9 @@ * @missing-elements/h5p-author/core: what the package does that needs neither Node nor a page, for * a tool that runs beside a build in either: the generator, the libraries loaded as a build loads * them from any source of them, the parts a content type's build can read, the check of saved - * content, the rules for text, which content type a source is written in, as a build reads it, and - * a source's own fields as the schema a build holds them to. The package's entry for Node (`.`) and + * content, the rules for text, which content type a source is written in, as a build reads it, a + * source's own fields as the schema a build holds them to, and the lines that say what a file is + * and how long a video is. The package's entry for Node (`.`) and * the one for a page (`./browser`) carry all of it, each with its own `buildPackage` and `openPack`. */ @@ -13,6 +14,7 @@ export { outlineOf } from './outline.mjs' export { ContentGenerator, librariesIn, libraryString } from './generator.mjs' export { coreApiLine, coreApiOf, missingForInstall } from './install.mjs' export { loadLibraries, packageLibraries } from './libraries.mjs' +export { lengthLine, mediaLine } from './media.mjs' export { sourceType } from './names.mjs' export { GENERATED_END, GENERATED_START } from './schema.mjs' export { SourceError } from './source-error.mjs' diff --git a/packages/author/lib/media.mjs b/packages/author/lib/media.mjs index 4bc6640..6a9832f 100644 --- a/packages/author/lib/media.mjs +++ b/packages/author/lib/media.mjs @@ -53,8 +53,10 @@ const under = (host, domains) => domains.some((domain) => host === domain || hos * what each status it answers there means, as seen on 2026-11-20: a problem (`gone`) or a note * (`closed`), each with the words for it. A status not listed says nothing. `sends` is how the * host itself sends such a status, its body and the type it gives it, by which its own answer is - * told from one a box in between gives for it (`#ask`). - * @type {{ host: string, mime: string, plays: RegExp, on: (url: URL) => boolean, form: string, oembed?: (address: string) => string, sends?: { type: string, body: (status: number) => string }, answers?: Record }[]} + * told from one a box in between gives for it (`#ask`). `length` reads a video's length in seconds + * from the host's answer for one it has, where that answer carries it (#260): Vimeo's does, in + * whole seconds, and YouTube's does not. + * @type {{ host: string, mime: string, plays: RegExp, on: (url: URL) => boolean, form: string, oembed?: (address: string) => string, sends?: { type: string, body: (status: number) => string }, answers?: Record, length?: (answer: any) => number | undefined }[]} */ const HOSTED = [ { @@ -72,7 +74,9 @@ const HOSTED = [ // 200, and a 403 is Vimeo refusing the asker's network, which says nothing of the video. answers: { 404: { gone: 'has no video there that others can play: give https://vimeo.com/ and the number of a public video, or all of an unlisted video\'s link, which has more after the number' } - } + }, + // Its own answer names it, and a video being made ready has no length yet. + length: (answer) => (answer?.provider_name === 'Vimeo' && Number.isFinite(answer.duration) && answer.duration > 0 ? answer.duration : undefined) }, { host: 'YouTube', @@ -179,6 +183,19 @@ const IDLE_MS = 60_000 * @typedef {{ path: string, message: string }} Problem */ +/** + * @typedef {{ file: string, seconds: number, host?: string }} MediaLength a video's or a + * recording's length: `file`, as the source names it; `seconds`, from its index, or as `host` + * said it, which is in whole seconds + * @typedef {{ + * source: string, kind?: 'image' | 'video' | 'audio', format?: string, width?: number, height?: number, + * seconds?: number, host?: string, notes: string[], problem?: string + * }} MediaFacts what a file is (`MediaStore.describe`): `source`, as it was named; `format`, a + * picture's type or a played file's container; a picture's `width` and `height` in pixels; + * `seconds`, an mp4's length, or a hosted video's as its `host` said it; `notes`, what is worth + * saying besides; `problem`, why it is none a source can name, with nothing else read + */ + /** * Where a build's files are, and where a download is kept, which differ between Node and a page. * @template F a kept file: a path on disk, or a `Blob` @@ -299,6 +316,95 @@ function containerOf(head) { return /^\s*} */ ({ png: 'PNG', jpg: 'JPEG', jpeg: 'JPEG', gif: 'GIF', bmp: 'BMP', mp4: 'MP4', webm: 'WebM', ogg: 'Ogg', wav: 'WAV', mp3: 'MP3' }) + +/** Seconds as a message gives them: to a hundredth. @param {number} seconds */ +const rounded = (seconds) => Math.round(seconds * 100) / 100 + +/** + * The line a build's output says of the video an Interactive Video's times were held to (#260), + * so that whoever changes them next starts from its length: a file's as its index gives it, a + * hosted video's as its host said it, in whole seconds. + * @param {MediaLength} length + */ +export function lengthLine({ file, seconds, host }) { + return `The video ${file} is ${host ? `about ${rounded(seconds)} s long, as ${host} says` : `${rounded(seconds)} s long`}: keep every time within it.` +} + +/** + * What a file is, in one line (`MediaStore.describe`, #260): the problem with it, or its kind and + * what was read of it, then what is worth saying besides. + * @param {MediaFacts} facts + */ +export function mediaLine({ source, kind, format, width, height, seconds, host, notes, problem }) { + if (problem) return problem + const a = (/** @type {string} */ word) => (/^(?:MP|Ogg)/.test(word) ? `an ${word}` : `a ${word}`) + /** @type {string} */ + let what + if (host) what = `a video on ${host}, ${seconds === undefined ? 'which does not say how long it is' : `about ${rounded(seconds)} s long`}` + else if (kind === 'image') what = `${a(String(format))} picture, ${width} by ${height} pixels` + else { + // A WebM or an Ogg file is a video's or a recording's, and nothing here reads which. + const noun = format === 'WebM' || format === 'Ogg' ? 'file' : kind === 'video' ? 'video' : 'recording' + what = `${a(String(format))} ${noun}, ${seconds === undefined ? 'whose length a build does not read' : `${rounded(seconds)} s long`}` + } + return [`${source}: ${what}`, ...notes].join('; ') +} + +/** The most a host's answer for a video may hold and still be read: Vimeo's is about 1.5 kB. */ +const MAX_ANSWER = 64 * 1024 + +/** + * A short answer's JSON, or nothing where it is none or runs longer than a host's answer does: + * what answers is not always the host, and nothing here reads a body of any length whole. + * @param {Response} response + * @returns {Promise} + */ +async function shortJson(response) { + const reader = response.body?.getReader() + if (!reader) return undefined + /** @type {Uint8Array[]} */ + const chunks = [] + let size = 0 + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + size += value.length + if (size > MAX_ANSWER) return undefined + chunks.push(value) + } + const bytes = new Uint8Array(size) + let at = 0 + for (const chunk of chunks) { + bytes.set(chunk, at) + at += chunk.length + } + return JSON.parse(new TextDecoder().decode(bytes)) + } catch { + return undefined + } finally { + await reader.cancel().catch(() => {}) + } +} + /** @template F */ export class MediaStore { /** @@ -316,9 +422,9 @@ export class MediaStore { this.known = new Map() /** @type {Set} */ this.names = new Set() - /** @type {Map} a video's or a recording's length in seconds, by its path in the package, where its index gave one */ + /** @type {Map} a video's or a recording's length, by its path in the package or the address it stays at, where its index or its host gave one */ this.lengths = new Map() - /** @type {Map>} what a host answered of a video, by the address asked, so one video named twice is asked of once */ + /** @type {Map>} what a host answered of a video, by the address asked, so one video named twice is asked of once */ this.asked = new Map() /** @type {Set} the hosts that gave no answer at all, none of which is asked again in this build */ this.unanswered = new Set() @@ -329,8 +435,10 @@ export class MediaStore { } /** - * A video's or a recording's length in seconds, by its path in the package, where it was read. + * A video's or a recording's length, by its path in the package or the address it stays at: + * read from a file's index, or as its host said it. * @param {string} path + * @returns {MediaLength | undefined} */ lengthOf(path) { return this.lengths.get(path) @@ -357,7 +465,8 @@ export class MediaStore { const address = short ? `https://www.youtube.com/watch?v=${short[1]}` : source const hosted = HOSTED.find(({ plays }) => plays.test(address)) if (hosted) { - if (!this.access.unread) await this.#there(hosted, address, source, `${at}.path`, report, note) + const seconds = this.access.unread ? undefined : await this.#there(hosted, address, source, `${at}.path`, report, note) + if (seconds !== undefined) this.lengths.set(address, { file: source, seconds, host: hosted.host }) return { path: address, mime: hosted.mime, copyright } } const url = URL.canParse(address) ? new URL(address) : null @@ -397,8 +506,8 @@ export class MediaStore { } else if (kind === 'video' || kind === 'audio') { const file = await this.access.open(staged.from) try { - const length = await this.#played(file, kind, source, web, `${at}.path`, report, note) - if (length) this.lengths.set(name, length) + const played = await this.#played(file, kind, source, web, `${at}.path`, report, note) + if (played?.seconds) this.lengths.set(name, { file: source, seconds: played.seconds }) } finally { await file.close() } @@ -440,6 +549,61 @@ export class MediaStore { return out } + /** + * What a file is, before a source names it (#260): a picture's size, a video's or a recording's + * container, and for an mp4 its length and what is worth saying of its tracks, by the readers a + * build holds a source's files to; of a video on YouTube, Vimeo, Panopto or Echo360, its host, + * and its length where the host's answer gives one. A file named by a web address is downloaded + * as a build downloads it. Nothing is staged for a package. + * @param {string} written a path, or a web address + * @returns {Promise} + */ + async describe(written) { + const source = written.trim() + /** @type {string[]} */ + const problems = [] + /** @type {string[]} */ + const notes = [] + // A problem names the file; a note comes after its facts, where the file is named already. + const own = (/** @type {string} */ message) => (/^it /.test(message) ? `${source}: ${message}` : message) + const report = (/** @type {string} */ _at, /** @type {string} */ message) => { problems.push(own(message)) } + const note = (/** @type {string} */ _at, /** @type {string} */ message) => { notes.push(message.startsWith(`${source}: `) ? message.slice(source.length + 2) : message) } + const failed = () => ({ source, notes, problem: problems[0] }) + const web = /^https?:\/\//i.test(source) + if (web) { + const short = YOUTUBE_SHORT.exec(source) + const address = short ? `https://www.youtube.com/watch?v=${short[1]}` : source + const hosted = HOSTED.find(({ plays }) => plays.test(address)) + if (hosted) { + const seconds = await this.#there(hosted, address, source, '', report, note) + if (problems.length) return failed() + return { source, kind: 'video', host: hosted.host, ...(seconds === undefined ? {} : { seconds }), notes } + } + const url = URL.canParse(address) ? new URL(address) : null + const other = url ? HOSTED.find(({ on }) => on(url)) : undefined + if (other) return { source, notes, problem: `${source} is an address on ${other.host} that H5P.Video cannot play: give ${other.form}` } + } else if (/^[a-z][a-z0-9+.-]+:/i.test(source)) { + // Two letters or more before the colon: one alone is a Windows drive. + return { source, notes, problem: `${source}: expected a file or an http(s) address` } + } + const staged = web ? await this.#download(source, 'file', DESCRIBED, '', report, DESCRIBED_AS, SERVED_AUDIO) : await this.#local(source, DESCRIBED, '', report, DESCRIBED_AS) + if (!staged) return failed() + const file = await this.access.open(staged.from) + try { + if (Object.hasOwn(TYPES.image, staged.extension)) { + const size = await imageSize((offset, length) => file.read(offset, length)) + if (!size) return { source, notes, problem: `${source} is not a ${staged.extension.toUpperCase()} image whose size can be read` } + return { source, kind: 'image', format: FORMATS[staged.extension], ...size, notes } + } + const kind = Object.hasOwn(TYPES.video, staged.extension) ? 'video' : 'audio' + const played = await this.#played(file, kind, 'it', web, '', report, note) + if (!played) return failed() + return { source, kind, format: FORMATS[played.container], ...(played.seconds ? { seconds: played.seconds } : {}), notes } + } finally { + await file.close() + } + } + /** * A video's or a recording's bytes held to what its field takes: its container, from its first * bytes, a problem where it is none of those; for an mp4, its index, a problem where there is @@ -452,7 +616,8 @@ export class MediaStore { * @param {string} at * @param {(path: string, message: string) => void} report * @param {(path: string, message: string) => void} note - * @returns {Promise} its length in seconds, where its index gives one + * @returns {Promise<{ container: string, seconds?: number } | undefined>} its container, and its + * length in seconds where its index gives one; nothing where it is refused */ async #played(file, kind, source, web, at, report, note) { const { takes, what } = PLAYS[kind] @@ -470,14 +635,14 @@ export class MediaStore { } if (!info) { if (container === 'mp4') report(at, `${source} has no index (moov) a player can read: is the file whole?`) - return undefined + return container === 'mp4' ? undefined : { container } } const held = new Set(info.tracks.map((track) => track.kind)) if (held.size && !held.has('audio')) note(at, `${source} has no sound`) if (held.size && kind === 'video' && !held.has('video')) note(at, `${source} has no picture`) const codecs = new Set(info.tracks.filter((track) => track.kind === 'video').map((track) => NOT_EVERYWHERE[track.codec]).filter(Boolean)) for (const codec of codecs) note(at, `${source} is ${codec}, which not every browser plays; H.264 plays in all of them`) - return info.duration + return { container, ...(info.duration ? { seconds: info.duration } : {}) } } /** @@ -485,12 +650,13 @@ export class MediaStore { * @param {Record} types * @param {string} at * @param {(path: string, message: string) => void} report + * @param {string} [takes] what takes those types, for a problem */ - async #local(source, types, at, report) { + async #local(source, types, at, report, takes = 'this field takes') { const name = this.access.name(source) const extension = extensionOf(name) if (!Object.hasOwn(types, extension)) { - report(`${at}.path`, `${source}: this field takes ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) + report(`${at}.path`, `${source}: ${takes} ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) return null } const found = await this.access.local(source) @@ -576,46 +742,53 @@ export class MediaStore { * @param {string} at * @param {(path: string, message: string) => void} report * @param {(path: string, message: string) => void} note + * @returns {Promise} the video's length in seconds, where the host's answer gives one (#260) */ async #there(hosted, address, source, at, report, note) { const ask = hosted.oembed?.(address) - if (!ask || !hosted.answers) return + if (!ask || !hosted.answers) return undefined let answer = this.asked.get(ask) if (!answer) { // One at a time, and a host that does not answer costs its ten seconds once, not a video. - if (this.unanswered.has(hosted.host)) return + if (this.unanswered.has(hosted.host)) return undefined answer = this.#ask(ask, hosted) this.asked.set(ask, answer) } - const status = await answer + const { status, seconds } = await answer if (status === 0) this.unanswered.add(hosted.host) const meaning = hosted.answers[status] if (meaning?.gone) report(at, `${source}: ${hosted.host} ${meaning.gone} (it answered ${status})`) else if (meaning?.closed) note(at, `${source}: ${hosted.host} ${meaning.closed} (it answered ${status})`) + return seconds } /** * The status a host's oEmbed endpoint answers; 0 where it does not answer in time, and -1 where * a status that would say something of the video is not sent as the host sends it (`sends`): - * that status's own words and nothing else, under the host's type. + * that status's own words and nothing else, under the host's type. With it, the video's length + * in seconds, where the host's answer for a video it has carries one (`length`, #260): JSON + * that names the host, so a box in between that answers 200 for it says no length. * @param {string} url * @param {(typeof HOSTED)[number]} hosted - * @returns {Promise} + * @returns {Promise<{ status: number, seconds?: number }>} */ async #ask(url, hosted) { try { const response = await this.fetch(url, { signal: AbortSignal.timeout(ASK_MS) }) const { status } = response + const type = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() + if (status === 200 && hosted.length && type === 'application/json') { + return { status, seconds: hosted.length(await shortJson(response)) } + } if (!hosted.answers || !hosted.sends || !Object.hasOwn(hosted.answers, status)) { await response.body?.cancel().catch(() => {}) - return status + return { status } } - const type = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() const own = type === hosted.sends.type && (await response.text()).trim() === hosted.sends.body(status) if (!own) await response.body?.cancel().catch(() => {}) - return own ? status : -1 + return { status: own ? status : -1 } } catch { - return 0 + return { status: 0 } } } @@ -627,8 +800,10 @@ export class MediaStore { * @param {Record} types * @param {string} at * @param {(path: string, message: string) => void} report + * @param {string} [takes] what takes those types, for a problem + * @param {Record} [served] an extension, by a served type `types` does not map to one */ - async #download(source, kind, types, at, report) { + async #download(source, kind, types, at, report, takes = 'this field takes', served = /** @type {Record} */ ({})) { let url try { url = new URL(source) @@ -664,11 +839,11 @@ export class MediaStore { return null } const named = extensionOf(lastSegment(new URL(response.url || url.href).pathname)) - const served = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() - const extension = Object.hasOwn(types, named) ? named : Object.keys(types).find((each) => types[each] === served) + const type = (response.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase() + const extension = Object.hasOwn(types, named) ? named : Object.keys(types).find((each) => types[each] === type) ?? (Object.hasOwn(served, type) ? served[type] : undefined) if (!extension) { await response.body.cancel() - report(`${at}.path`, `${source} is ${served || 'of an unknown type'}: this field takes ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) + report(`${at}.path`, `${source} is ${type || 'of an unknown type'}: ${takes} ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) return null } let received = 0 diff --git a/packages/author/lib/node.mjs b/packages/author/lib/node.mjs index 98a4b3d..12db716 100644 --- a/packages/author/lib/node.mjs +++ b/packages/author/lib/node.mjs @@ -27,14 +27,16 @@ import { SourceError } from './source-error.mjs' * @typedef {import('./translate.mjs').TranslationReport} TranslationReport * @typedef {{ * output: string, source: import('./build.mjs').Source, builtWith: string, manifest: Record, content: Record, - * libraries: string[], install: string[], coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], media: string[], unread: string[], outline: string + * libraries: string[], install: string[], coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], media: string[], lengths: import('./media.mjs').MediaLength[], unread: string[], outline: string * }} BuildResult what was written, and what is worth telling about it: `libraries`, the folders the * package plays with; `install`, those carried for an H5P site's upload check; `coreApi`, the * newest H5P core they ask for, which a site needs to take the package (`coreApiLine` says it); * `outline`, the content as text for a review (`outlineOf`); `builtWith`, the content type and * the pack's version of it, "H5P.Blanks 1.14", and `source`, the source as built, naming it: what * to keep with the package, so that a build with a later pack can say the type has moved; - * `unread`, the files a check with `unread` did not look at, as the source names them + * `unread`, the files a check with `unread` did not look at, as the source names them; + * `lengths`, the length of each video an Interactive Video's times were held to, as the source + * names it (`lengthLine` says one): an mp4's from its index, a Vimeo video's as Vimeo said it * @typedef {{ libraries?: string, base?: string, fetch?: typeof fetch, within?: string[], check?: boolean, unread?: boolean }} BuildOptions * `libraries`, a library pack's parts folder in place of the pinned pack; `base`, the folder a * source's file paths are read from; `fetch`, for media named by web address; `within`, the @@ -58,6 +60,11 @@ import { SourceError } from './source-error.mjs' * folders of the parts it holds; `size`, the zip's in bytes * @typedef {{ dev: bigint, ino: bigint }} Made a file this module created, by the device and * inode it was given, which a file that takes its name later does not have + * @typedef {import('./media.mjs').MediaFacts} MediaFacts + * @typedef {{ base?: string, fetch?: typeof fetch, within?: string[] }} DescribeOptions + * `base`, the folder a path is read from; `fetch`, for a file named by web address and for + * asking a video's host; `within`, the folders a local file must be inside, on its real path, a + * list even of one */ /** @@ -118,11 +125,14 @@ export async function packVersion() { /** * A source's files on disk: beside the source, by their paths from `base`; downloads kept in * `temporary`, numbered. - * @param {{ base: string, temporary: string, within?: string[] }} folders `within`, the folders a file must be inside + * @param {{ base: string, temporary: string, within?: string[], beside?: string }} folders + * `within`, the folders a file must be inside; `beside`, where a file is looked for, as a + * problem says it of one that is not there * @returns {import('./media.mjs').MediaAccess} * @internal */ -export function nodeMedia({ base, temporary, within }) { +export function nodeMedia(folders) { + const { base, within, beside = ' beside the source' } = folders let downloads = 0 return { what: 'a file beside the source', @@ -133,7 +143,7 @@ export function nodeMedia({ base, temporary, within }) { // or not something is there, and a confined build names no path but the one written. if (within && !(await inside(from, within))) return { missing: 'is outside the folders this build may read' } const found = await stat(from).catch(() => null) - if (!found?.isFile()) return { missing: within ? 'no such file in the folders this build may read' : `no such file beside the source (${from})` } + if (!found?.isFile()) return { missing: within ? 'no such file in the folders this build may read' : `no such file${beside} (${from})` } // Opened once here, so a file the build cannot read is a problem of the source's, said with // the rest, and not a failure halfway through the build that names its whole path. try { @@ -145,7 +155,8 @@ export function nodeMedia({ base, temporary, within }) { }, async keep(body, extension) { downloads += 1 - const from = join(temporary, `download-${downloads}.${extension}`) + // Read when a download is kept, so a caller may move it between files. + const from = join(folders.temporary, `download-${downloads}.${extension}`) await body.pipeTo(/** @type {WritableStream} */ (Writable.toWeb(createWriteStream(from)))) return from }, @@ -409,6 +420,7 @@ export async function buildPackage(input, output, options = {}) { translations: built.translations, notes: built.notes, media: media.files.map((item) => item.name), + lengths: built.lengths, unread: [...media.unread], get outline() { return built.outline } } @@ -450,6 +462,7 @@ export async function buildPackage(input, output, options = {}) { translations: built.translations, notes: built.notes, media: media.files.map((item) => item.name), + lengths: built.lengths, unread: [], get outline() { return built.outline } } @@ -459,6 +472,38 @@ export async function buildPackage(input, output, options = {}) { } } +/** + * What files are, before a source names them (#260): a picture's size, a video's or a recording's + * container, an mp4's length and what is worth saying of its tracks, read as a build reads them; + * of a video on YouTube, Vimeo, Panopto or Echo360, its host, and its length where the host says + * one. A model that writes an Interactive Video's times needs the length first, and wrote a + * parser of its own for it where it could run one. A file named by a web address is downloaded to + * a temporary folder removed after, as a check downloads it. `mediaLine` says each in a line. + * @param {string[]} sources paths from `base`, or web addresses + * @param {DescribeOptions} [options] + * @returns {Promise} one for each, in their order + */ +export async function describeMedia(sources, options = {}) { + const within = foldersOf(options.within) + if (!Array.isArray(sources) || !sources.every((source) => typeof source === 'string' && source.trim())) throw new TypeError('describeMedia takes a list of paths or web addresses') + /** @type {MediaFacts[]} */ + const facts = [] + // A folder for each file, removed once it is read: one download on disk at a time, however + // many addresses are named. One store for all, so a host that does not answer is asked once. + let temporary = '' + const access = nodeMedia({ base: options.base ?? process.cwd(), get temporary() { return temporary }, within, beside: '' }) + const media = new MediaStore(access, { fetch: options.fetch }) + for (const source of sources) { + temporary = await mkdtemp(join(tmpdir(), '.h5p-author-')) + try { + facts.push(await media.describe(source)) + } finally { + await rm(temporary, { recursive: true, force: true }) + } + } + return facts +} + /** * Whether a media path a package's content names is one a read writes a file at, under its folder: * names joined by `/`, none of them empty, `.` or `..`, and none with a character a file name diff --git a/packages/author/lib/types.mjs b/packages/author/lib/types.mjs index e549b1d..6cb29df 100644 --- a/packages/author/lib/types.mjs +++ b/packages/author/lib/types.mjs @@ -463,21 +463,24 @@ const interactiveVideo = { } /** - * An Interactive Video's times held to its video's length, where the build read one (an mp4's - * index gives it): an interaction that starts past the end never shows, a bookmark or an end - * screen past it is never reached, a start past it plays nothing. An interaction may end past it, - * and shows to the end. + * An Interactive Video's times held to its video's length, where the build knows one (an mp4's + * index gives it, and Vimeo says a video's): an interaction that starts past the end never shows, + * a bookmark or an end screen past it is never reached, a start past it plays nothing. An + * interaction may end past it, and shows to the end. A host says a length in whole seconds, so a + * time is past the end of its video only a second beyond that. * @param {any} params an Interactive Video's, as H5P stores them * @param {string} path where they are - * @param {(file: string) => number | undefined} lengthOf a video's length in seconds, by its path in the package + * @param {(file: string) => import('./media.mjs').MediaLength | undefined} lengthOf a video's length, by its path in the package or the address it stays at * @param {(path: string, message: string) => void} report + * @returns {import('./media.mjs').MediaLength | undefined} the length the times were held to */ export function videoTimes(params, path, lengthOf, report) { const files = params?.interactiveVideo?.video?.files - const length = (Array.isArray(files) ? files : []).map((file) => (typeof file?.path === 'string' ? lengthOf(file.path) : undefined)).find((each) => each !== undefined) - if (length === undefined) return - const end = `the video ends at ${Math.round(length * 100) / 100} s` - const late = (/** @type {unknown} */ time) => typeof time === 'number' && time > length + const known = (Array.isArray(files) ? files : []).map((file) => (typeof file?.path === 'string' ? lengthOf(file.path) : undefined)).find((each) => each !== undefined) + if (known === undefined) return undefined + const { seconds: length, host } = known + const end = host ? `the video ends at about ${Math.round(length * 100) / 100} s, as ${host} says` : `the video ends at ${Math.round(length * 100) / 100} s` + const late = (/** @type {unknown} */ time) => typeof time === 'number' && time > length + (host ? 1 : 0) const list = (/** @type {unknown} */ value) => (Array.isArray(value) ? value : []) const assets = params.interactiveVideo.assets list(assets?.interactions).forEach((interaction, i) => { @@ -489,6 +492,43 @@ export function videoTimes(params, path, lengthOf, report) { }) } if (late(params.override?.startVideoAt)) report(`${path}.override.startVideoAt`, `is ${params.override.startVideoAt} s, after ${end}`) + return known +} + +/** + * What a note says of things placed on a picture or a map, one or several. + * @param {string} on what they are placed on + * @returns {(one: boolean) => string} + */ +const placedOn = (on) => (one) => `placed by numbers, which a build cannot hold to the ${on}: look at ${one ? 'it' : 'each'} in the preview` + +/** + * What a source puts on a picture or a video by numbers alone (#260): hotspots, areas and stages + * at places, interactions at times. A build holds none of them to what the picture or the video + * shows there, so it says each such list once, as a note for whoever hands the package over: only + * a person looking at the preview knows whether a hotspot sits on what it names. + * @type {Record string }>} + */ +const BY_NUMBER = { + 'H5P.ImageHotspots': { at: 'hotspots', what: ['hotspot', 'hotspots'], on: placedOn('picture') }, + 'H5P.ImageHotspotQuestion': { at: 'imageHotspotQuestion.hotspotSettings.hotspot', what: ['area', 'areas'], on: placedOn('picture') }, + 'H5P.ImageMultipleHotspotQuestion': { at: 'imageMultipleHotspotQuestion.hotspotSettings.hotspot', what: ['area', 'areas'], on: placedOn('picture') }, + 'H5P.GameMap': { at: 'gamemapSteps.gamemap.elements', what: ['stage', 'stages'], on: placedOn('map') }, + 'H5P.InteractiveVideo': { at: 'interactiveVideo.assets.interactions', what: ['interaction', 'interactions'], on: () => 'shown at the times written, which a build cannot hold to what the video shows then: play it through in the preview' } +} + +/** + * The note for what a library's content places or times by numbers alone, or none. + * @param {string} library its machine name + * @param {any} params its content, as H5P stores it + * @returns {{ at: string, message: string } | undefined} + */ +export function byNumber(library, params) { + const rule = Object.hasOwn(BY_NUMBER, library) ? BY_NUMBER[library] : undefined + if (!rule) return undefined + const list = rule.at.split('.').reduce((value, key) => (isObject(value) ? value[key] : undefined), params) + if (!Array.isArray(list) || !list.length) return undefined + return { at: rule.at, message: `holds ${list.length} ${rule.what[list.length === 1 ? 0 : 1]} ${rule.on(list.length === 1)}` } } /* ---------------------------------------------------------------- Branching Scenario */ diff --git a/packages/author/tests/build.test.ts b/packages/author/tests/build.test.ts index 45a3d79..b83a1d5 100644 --- a/packages/author/tests/build.test.ts +++ b/packages/author/tests/build.test.ts @@ -10,7 +10,7 @@ import { BlobReader, TextWriter, Uint8ArrayWriter, ZipReader } from '@zip.js/zip import { pack } from '@missing-elements/h5p-libraries' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { toJSONSchema } from 'zod/mini' -import { buildPackage, coreApiLine, coreApiOf, librariesIn, missingForInstall, SourceError, sourceSchema } from '../lib/author.mjs' +import { buildPackage, coreApiLine, coreApiOf, describeMedia, lengthLine, librariesIn, mediaLine, missingForInstall, SourceError, sourceSchema } from '../lib/author.mjs' import { readSource } from '../lib/build.mjs' import { LICENSES } from '../lib/metadata.mjs' import { MediaStore } from '../lib/media.mjs' @@ -799,6 +799,8 @@ describe('media', () => { // A file's page on a wiki, at an address that ends as the file's name does (#218). else if (request.url === '/wiki/File:clip.mp4') response.writeHead(200, { 'content-type': 'text/html' }).end('File:clip.mp4') else if (request.url === '/odd%zz.png') response.writeHead(200, { 'content-type': 'image/png' }).end(png(20, 10)) + // A recording at an address with no extension, its type the server's alone (#260). + else if (request.url === '/stream') response.writeHead(200, { 'content-type': 'audio/ogg' }).end(Buffer.concat([Buffer.from('OggS'), Buffer.alloc(60)])) else if (request.url === '/trickle.png') { // Slow, and never silent for long: eight pieces, 100 ms apart. const bytes = png(40, 30) @@ -1054,6 +1056,136 @@ describe('media', () => { ]) }) + it('holds an Interactive Video\'s times to the length Vimeo gives for its video, and says the length it held them to (#260)', async () => { + await writeFile(join(dir, 'lesson.mp4'), mp4(true, { seconds: 30.0333, tracks: [['vide', 'avc1'], ['soun', 'mp4a']] })) + const text = (from: number, to: number) => ({ duration: { from, to }, label: 'Look', action: { library: 'H5P.Text', params: { text: 'Look' } } }) + const source = (path: string, interactions: unknown[]) => ({ ...META, type: 'H5P.InteractiveVideo', params: { interactiveVideo: { video: { files: [{ path }] }, assets: { interactions } } } }) + const film = 'https://vimeo.com/76979871' + // A file's length is its index's. + const fromFile = await build(source('lesson.mp4', [text(5, 10)]), { base: dir }) + expect(fromFile.lengths).toEqual([{ file: 'lesson.mp4', seconds: 30.033 }]) + expect(fromFile.lengths.map(lengthLine)).toEqual(['The video lesson.mp4 is 30.03 s long: keep every time within it.']) + // Vimeo's is its own answer's, in whole seconds: a time is past the end only a second beyond it. + const answers = (body: unknown, type = 'application/json') => async () => new Response(JSON.stringify(body), { headers: { 'content-type': type } }) + const vimeo = answers({ type: 'video', provider_name: 'Vimeo', duration: 62, video_id: 76979871 }) + const hosted = await build(source(film, [text(5, 10), text(62.9, 70)]), { fetch: vimeo }) + expect(hosted.lengths).toEqual([{ file: film, seconds: 62, host: 'Vimeo' }]) + expect(hosted.lengths.map(lengthLine)).toEqual([`The video ${film} is about 62 s long, as Vimeo says: keep every time within it.`]) + expect(await problems(source(film, [text(5, 10), text(300, 310)]), { fetch: vimeo })).toEqual([ + 'params.interactiveVideo.assets.interactions[1].duration: starts at 300 s, after the video ends at about 62 s, as Vimeo says' + ]) + // An answer that is not Vimeo's own for a video it has says no length, and holds no time: + // one that does not name it, a page, a video being made ready, what is no JSON, and one far + // longer than a host's answer, which is not read to its end. + const long = answers({ provider_name: 'Vimeo', duration: 62, html: 'x'.repeat(70_000) }) + for (const fetch of [answers({ type: 'video', duration: 62 }), answers({ provider_name: 'Vimeo', duration: 62 }, 'text/html'), answers({ provider_name: 'Vimeo', duration: 0 }), long, async () => new Response('not an answer', { headers: { 'content-type': 'application/json' } })]) { + expect((await build(source(film, [text(300, 310)]), { fetch })).lengths).toEqual([]) + } + // YouTube says none. + expect((await build(source('https://www.youtube.com/watch?v=dQw4w9WgXcQ', [text(300, 310)]), { fetch: answers({ type: 'video', provider_name: 'YouTube', duration: 62 }) })).lengths).toEqual([]) + // The command line says it, for whoever changes the times next. + await writeFile(join(dir, 'lesson.json'), JSON.stringify(source('lesson.mp4', [text(5, 10)]))) + const { stdout } = await exec(process.execPath, [bin, 'build', '--check', join(dir, 'lesson.json')]) + expect(stdout).toContain('The video lesson.mp4 is 30.03 s long: keep every time within it.') + }) + + it('says what a source places or times by numbers alone, which only a look at the preview checks (#260)', async () => { + await writeFile(join(dir, 'delta.png'), png(40, 30)) + await writeFile(join(dir, 'spring.mp4'), mp4(true, { seconds: 30, tracks: [['vide', 'avc1'], ['soun', 'mp4a']] })) + const noted = async (source: Record) => (await build({ ...META, ...source }, { base: dir })).notes.filter(({ message }) => message.startsWith('holds ')).map(({ path, message }) => `${path}: ${message}`) + const spot = (x: number, y: number) => ({ position: { x, y }, header: 'Here', content: [{ library: 'H5P.Text', params: { text: 'Here.' } }] }) + const hotspots = (spots: unknown[]) => ({ type: 'H5P.ImageHotspots', params: { image: { path: 'delta.png' }, backgroundImageAltText: 'A delta', hotspots: spots } }) + expect(await noted(hotspots([spot(30, 40), spot(70, 65)]))).toEqual(['params.hotspots: holds 2 hotspots placed by numbers, which a build cannot hold to the picture: look at each in the preview']) + expect(await noted(hotspots([spot(30, 40)]))).toEqual(['params.hotspots: holds 1 hotspot placed by numbers, which a build cannot hold to the picture: look at it in the preview']) + const area = (x: number, correct: boolean) => ({ computedSettings: { x, y: 10, width: 20, height: 20, figure: 'circle' }, userSettings: { correct, feedbackText: 'There.' } }) + expect(await noted({ + type: 'H5P.ImageHotspotQuestion', + params: { imageHotspotQuestion: { backgroundImageSettings: { path: 'delta.png' }, hotspotSettings: { taskDescription: 'Click the mouth.', hotspot: [area(60, true), area(10, false)] } } } + })).toEqual(['params.imageHotspotQuestion.hotspotSettings.hotspot: holds 2 areas placed by numbers, which a build cannot hold to the picture: look at each in the preview']) + const stage = (label: string, x: number, more: Record = {}) => ({ + label, telemetry: { x, y: 40 }, contentsList: [{ contentType: { library: 'H5P.TrueFalse', params: { question: 'A river can begin at a glacier.', correct: 'true' } } }], ...more + }) + expect(await noted({ + type: 'H5P.GameMap', + params: { gamemapSteps: { backgroundImageSettings: { backgroundImage: { path: 'delta.png' } }, gamemap: { elements: [stage('Source', 15, { canBeStartStage: true, neighbors: ['Mouth'] }), stage('Mouth', 75)] } } } + })).toEqual(['params.gamemapSteps.gamemap.elements: holds 2 stages placed by numbers, which a build cannot hold to the map: look at each in the preview']) + // An Interactive Video's times, wherever the type is, by where the source has it; and none with nothing timed. + const video = (interactions: unknown[]) => ({ library: 'H5P.InteractiveVideo', params: { interactiveVideo: { video: { files: [{ path: 'spring.mp4' }] }, assets: { interactions } } } }) + const text = { duration: { from: 2, to: 6 }, label: 'Look', action: { library: 'H5P.Text', params: { text: 'Look' } } } + expect(await noted({ type: 'H5P.Column', params: { content: [{ content: video([text, text, text]) }] } })).toEqual([ + 'params.content[0].content.params.interactiveVideo.assets.interactions: holds 3 interactions shown at the times written, which a build cannot hold to what the video shows then: play it through in the preview' + ]) + expect(await noted({ type: 'H5P.Column', params: { content: [{ content: video([]) }] } })).toEqual([]) + }) + + it('says what a file is before a source names it: a picture\'s size, a video\'s length, its host\'s word (#260)', async () => { + const both: [string, string][] = [['vide', 'avc1'], ['soun', 'mp4a']] + await writeFile(join(dir, 'wide.png'), png(1200, 800)) + await writeFile(join(dir, 'photo.jpg'), jpeg(640, 480)) + await writeFile(join(dir, 'talk.mp4'), mp4(true, { seconds: 12.5, tracks: both })) + await writeFile(join(dir, 'mute.mp4'), mp4(false, { seconds: 12.5, tracks: [['vide', 'hvc1']] })) + await writeFile(join(dir, 'voice.m4a'), mp4(true, { seconds: 3, tracks: [['soun', 'mp4a']] })) + await writeFile(join(dir, 'reel.webm'), Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])) + await writeFile(join(dir, 'tune.mp3'), 'ID3 and then its frames') + await writeFile(join(dir, 'saved.mp4'), 'clip') + await writeFile(join(dir, 'torn.png'), 'not a picture') + await writeFile(join(dir, 'plan.txt'), 'notes') + const film = 'https://vimeo.com/76979871' + const tube = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' + const fetch = async (input: string | URL | Request) => { + const url = String(input) + if (url.startsWith(origin)) return globalThis.fetch(input) + if (url.includes('999999999')) return new Response('404 Not Found', { status: 404, headers: { 'content-type': 'text/html; charset=UTF-8' } }) + return Response.json(url.startsWith('https://vimeo.com/') ? { type: 'video', provider_name: 'Vimeo', duration: 62 } : { type: 'video', provider_name: 'YouTube' }) + } + const named = [ + 'wide.png', 'photo.jpg', 'talk.mp4', 'mute.mp4', 'voice.m4a', 'reel.webm', 'tune.mp3', `${origin}/pictures/map.png`, film, tube, + 'https://video.example.edu/Panopto/Pages/Viewer.aspx?id=0b6d3a5e', 'saved.mp4', 'torn.png', 'plan.txt', 'gone.png', 'https://vimeo.com/999999999', + 'https://www.youtube.com/playlist?list=PL0', `${origin}/page.html`, 'ftp://files.example/clip.mp4', `${origin}/stream` + ] + const facts = await describeMedia(named, { base: dir, fetch }) + expect(facts.map(({ source }) => source)).toEqual(named) + expect(facts.map(mediaLine)).toEqual([ + 'wide.png: a PNG picture, 1200 by 800 pixels', + 'photo.jpg: a JPEG picture, 640 by 480 pixels', + 'talk.mp4: an MP4 video, 12.5 s long', + 'mute.mp4: an MP4 video, 12.5 s long; it has no sound; it is HEVC (H.265), which not every browser plays; H.264 plays in all of them', + 'voice.m4a: an MP4 recording, 3 s long', + 'reel.webm: a WebM file, whose length a build does not read', + 'tune.mp3: an MP3 recording, whose length a build does not read', + `${origin}/pictures/map.png: a PNG picture, 40 by 20 pixels`, + `${film}: a video on Vimeo, about 62 s long`, + `${tube}: a video on YouTube, which does not say how long it is`, + 'https://video.example.edu/Panopto/Pages/Viewer.aspx?id=0b6d3a5e: a video on Panopto, which does not say how long it is', + 'saved.mp4: it is a web page, not a video', + 'torn.png is not a PNG image whose size can be read', + 'plan.txt: only a picture, a video or a recording is read: .png, .jpg, .jpeg, .gif, .bmp, .mp3, .m4a, .wav, .ogg, .webm, .mp4', + `gone.png: no such file (${join(dir, 'gone.png')})`, + 'https://vimeo.com/999999999: Vimeo has no video there that others can play: give https://vimeo.com/ and the number of a public video, or all of an unlisted video\'s link, which has more after the number (it answered 404)', + 'https://www.youtube.com/playlist?list=PL0 is an address on YouTube that H5P.Video cannot play: give https://www.youtube.com/watch?v= and the video\'s id', + `${origin}/page.html is text/html: only a picture, a video or a recording is read: .png, .jpg, .jpeg, .gif, .bmp, .mp3, .m4a, .wav, .ogg, .webm, .mp4`, + 'ftp://files.example/clip.mp4: expected a file or an http(s) address', + `${origin}/stream: an Ogg file, whose length a build does not read` + ]) + expect(facts.slice(0, 3)).toEqual([ + { source: 'wide.png', kind: 'image', format: 'PNG', width: 1200, height: 800, notes: [] }, + { source: 'photo.jpg', kind: 'image', format: 'JPEG', width: 640, height: 480, notes: [] }, + { source: 'talk.mp4', kind: 'video', format: 'MP4', seconds: 12.5, notes: [] } + ]) + // Confined, a file outside the folders is refused before it is looked for, and no path is named. + expect((await describeMedia(['../wide.png', 'wide.png'], { base: dir, within: [dir] })).map(mediaLine)).toEqual([ + '../wide.png: is outside the folders this build may read', 'wide.png: a PNG picture, 1200 by 800 pixels' + ]) + await expect(describeMedia('wide.png' as unknown as string[])).rejects.toThrow('takes a list of paths or web addresses') + // The command: a line each, a problem on standard error, and a failing exit where there is one. + const { stdout } = await exec(process.execPath, [bin, 'media', 'wide.png', 'talk.mp4'], { cwd: dir }) + expect(stdout).toBe('wide.png: a PNG picture, 1200 by 800 pixels\ntalk.mp4: an MP4 video, 12.5 s long\n') + const failed = await exec(process.execPath, [bin, 'media', 'wide.png', 'plan.txt'], { cwd: dir }).then(() => null, (error: { code: number, stdout: string, stderr: string }) => error) + expect(failed).toMatchObject({ code: 1, stdout: 'wide.png: a PNG picture, 1200 by 800 pixels\n', stderr: expect.stringContaining('plan.txt: only a picture, a video or a recording is read') }) + await expect(exec(process.execPath, [bin, 'media'])).rejects.toMatchObject({ stderr: expect.stringContaining('media takes the files to look at') }) + await expect(exec(process.execPath, [bin, 'media', 'wide.png', '--check'], { cwd: dir })).rejects.toMatchObject({ stderr: expect.stringContaining('media does not take --check') }) + }) + it('gives a download up once nothing has arrived for a while, however long a slow one takes', async () => { const reported: string[] = [] const report = (path: string, message: string) => reported.push(`${path}: ${message}`) diff --git a/packages/author/tests/layout.test.ts b/packages/author/tests/layout.test.ts index 50d92b7..d406f04 100644 --- a/packages/author/tests/layout.test.ts +++ b/packages/author/tests/layout.test.ts @@ -5,6 +5,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { buildPackage, SourceError } from '../lib/author.mjs' import { imageSize } from '../lib/media.mjs' import { GENERATED_END, GENERATED_START, schemaLines, schemaMarkdown, SOURCE_FIELDS, withSection } from '../lib/schema.mjs' +import { byNumber } from '../lib/types.mjs' import { jpeg, png } from './helpers/media' const META = { title: 'Layout', language: 'en', license: 'U', authors: [{ name: 'Ann Author', role: 'Author' }] } @@ -145,7 +146,10 @@ describe('Interactive Video', () => { expect(first).toMatchObject({ x: 5, y: 5, width: 17, height: 16 }) expect(second).toMatchObject({ x: 50, y: 5, width: 17, height: 16 }) expect(third).toMatchObject({ x: 5, y: 5 }) - expect(notes).toEqual([{ path: 'params.interactiveVideo.assets.interactions[2]', message: expect.stringContaining('has no room left for it') }]) + expect(notes).toEqual([ + { path: 'params.interactiveVideo.assets.interactions[2]', message: expect.stringContaining('has no room left for it') }, + { path: 'params.interactiveVideo.assets.interactions', message: expect.stringContaining('holds 6 interactions shown at the times written') } + ]) // A text its lines, a picture its shape, as the editor gives one. expect(text).toMatchObject({ x: 5, y: 5, width: 12, height: 5.6 }) expect(image).toMatchObject({ width: 13.33, height: 10 }) @@ -357,3 +361,12 @@ describe('what a file is', () => { expect(await imageSize(file(new Uint8Array([1, 2, 3])))).toBeNull() }) }) + +describe('what is placed or timed by numbers alone (#260)', () => { + it('notes a list of a library that places by numbers, and nothing of any other name', () => { + expect(byNumber('H5P.ImageHotspots', { hotspots: [{}, {}] })).toEqual({ at: 'hotspots', message: expect.stringMatching(/^holds 2 hotspots placed by numbers/) }) + expect(byNumber('H5P.ImageHotspots', { hotspots: [] })).toBeUndefined() + // A name an object has of its own kind is no library of the table's. + for (const name of ['constructor', 'toString', '__proto__', 'H5P.Blanks']) expect(byNumber(name, { hotspots: [{}] })).toBeUndefined() + }) +}) diff --git a/packages/author/tests/page.test.ts b/packages/author/tests/page.test.ts index cdd58f2..6434304 100644 --- a/packages/author/tests/page.test.ts +++ b/packages/author/tests/page.test.ts @@ -153,7 +153,9 @@ describe('the build in a page', () => { expect((built.content as any).interactiveVideo.video.files).toEqual([{ path: address, mime: 'video/mp4', copyright: { license: 'U' } }]) expect(built.linked).toEqual(['clip.mp4']) expect(built.media).toEqual([]) - expect(built.notes).toEqual([]) + // Nothing of the file is read, so no length is said, and the one note is of the times (#260). + expect(built.lengths).toEqual([]) + expect(built.notes).toEqual([{ path: 'params.interactiveVideo.assets.interactions', message: expect.stringContaining('holds 1 interaction shown at the times written') }]) expect(asked).not.toHaveBeenCalled() const { entries } = await archive(new Uint8Array(await built.blob.arrayBuffer())) expect(entries.filter(({ filename }) => /^content\/(?:videos|audios|images|files)\//.test(filename))).toEqual([]) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 1bccafa..6d2b422 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -47,6 +47,10 @@ gets a number, and it says which. - `h5p_build`: a package from a source, its source beside it as `.source.json`. A source with problems is refused, each problem named. It checks the package, says what it holds, and which H5P core a site needs to take it. +- `h5p_media`: what a picture, a video or a recording is, in its folders or at a web address, + before your content names it: a picture's size, an mp4's length, which an Interactive Video's + times are kept within. A file at an address is downloaded as a build downloads one, and a + YouTube or Vimeo video is asked of that site as below. - `h5p_preview`: opens a package in your browser, in the real player, served from your computer until its tab is closed. - `h5p_read`: a package back into its source, with its pictures and other files, in a new folder @@ -65,7 +69,7 @@ address, and refuses to download from an address on your local network: a guard or planted address, not against a hostile network. A video on YouTube, Vimeo, Panopto or Echo360 is not downloaded: it stays an address, which the player loads wherever it points, as H5P does anywhere. A YouTube or Vimeo address is sent to that site's oEmbed, to ask whether it has the -video. Math is drawn by the package's own copy of MathJax, which loads nothing from elsewhere. +video, and Vimeo answers with its length where it has one. Math is drawn by the package's own copy of MathJax, which loads nothing from elsewhere. The check and the preview play the package from your computer. Your app sends your conversation to its model, as it does without this server. diff --git a/packages/mcp/lib/answers.mjs b/packages/mcp/lib/answers.mjs index 7458015..59d8dbc 100644 --- a/packages/mcp/lib/answers.mjs +++ b/packages/mcp/lib/answers.mjs @@ -3,7 +3,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { SkillsExtension, memorySkillFiles } from '@modelcontextprotocol/server/ext/skills' import { z } from 'zod' -import { contentTypes, openPack, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author' +import { contentTypes, lengthLine, openPack, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author' /** * What both servers of this package say alike: the local one over standard input and output @@ -34,12 +34,12 @@ export const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text export const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true }) /** - * A build's notes, and what its content holds, as lines of an answer: the outline, 80 lines of it - * at most. - * @param {{ notes: { path: string, message: string }[], outline: string }} result + * The length of each video an Interactive Video's times were held to, a build's notes, and what + * its content holds, as lines of an answer: the outline, 80 lines of it at most. + * @param {{ notes: { path: string, message: string }[], lengths: import('@missing-elements/h5p-author').BuildResult['lengths'], outline: string }} result */ export function heldLines(result) { - const lines = result.notes.map(({ path, message }) => `Note: ${path} ${message}`) + const lines = [...result.lengths.map(lengthLine), ...result.notes.map(({ path, message }) => `Note: ${path} ${message}`)] const outline = result.outline.split('\n') lines.push('', 'What it holds:', ...outline.slice(0, OUTLINE_LINES)) if (outline.length > OUTLINE_LINES) lines.push(`… and ${outline.length - OUTLINE_LINES} more lines.`) diff --git a/packages/mcp/lib/server.mjs b/packages/mcp/lib/server.mjs index 03612f3..944a5db 100644 --- a/packages/mcp/lib/server.mjs +++ b/packages/mcp/lib/server.mjs @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { basename, dirname, join, resolve } from 'node:path' import { McpServer } from '@modelcontextprotocol/server' import { z } from 'zod' -import { SourceError, buildPackage, coreApiLine, inside, publicFetch, readPackage } from '@missing-elements/h5p-author' +import { SourceError, buildPackage, coreApiLine, describeMedia, inside, mediaLine, publicFetch, readPackage } from '@missing-elements/h5p-author' import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage } from '@missing-elements/h5p-verify' import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, skillCatalog, typeAnswers } from './answers.mjs' import { defaultFolders, fileStem, rootFolders } from './folders.mjs' @@ -20,7 +20,7 @@ import { defaultFolders, fileStem, rootFolders } from './folders.mjs' /** The skill's flow, which every app shows the model with the tools. */ const INSTRUCTIONS = `Builds H5P content as a .h5p file from a short JSON source, checks that it plays, and opens it in the person's browser. 1. The content type is chosen with the person: where their request names none, ask which, and ask nothing else. h5p_types with no type lists them. -2. Call h5p_types with the type and write the source from its notes, example and fields: only what differs from the defaults. +2. Call h5p_types with the type and write the source from its notes, example and fields: only what differs from the defaults. Before a video's times are written, h5p_media says its length. 3. Call h5p_build. Where it lists problems, fix each at its path and build again. 4. Tell the person where the file is and what the check found, and offer h5p_preview. The author and the licence are what the person gave; otherwise the name you know them by, or "Unknown", and the licence "U". Say which you used. @@ -30,6 +30,8 @@ const READ = `Reads a .h5p package back into its source, to change it and build const BUILD = `Builds a .h5p package from a source, its params holding only what differs from the type's defaults. A file is { "path": ... }, in a folder this server may use or at a web address. Writes the package and its source (.source.json) to output, or under a new name in the first folder it may use. A source with problems is refused, each problem named by its path. With verify (the default), plays the package in a headless browser and reports whether it works.` +const MEDIA = `Says what a picture, a video or a recording is before a source names it: a picture's size in pixels, a video's length and whether it has sound, a Vimeo video's length as Vimeo gives it. Call it before writing an Interactive Video's times.` + const PREVIEW = `Opens a .h5p package in the person's browser in the real player, served from this computer until its tab is closed. Answers with the address.` /** @param {number} bytes */ @@ -64,7 +66,7 @@ function located(value, folder) { } /** - * The server and its four tools. It holds no rules of its own: the build, the read, their checks + * The server and its five tools. It holds no rules of its own: the build, the read, their checks * and the confinement to folders are h5p-author's, the check and the preview h5p-verify's. * @param {ServerOptions} [options] */ @@ -205,6 +207,23 @@ export async function createServer(options = {}) { return { content: [{ type: /** @type {const} */ ('text'), text: lines.join('\n') }, ...images] } }) + server.registerTool('h5p_media', { + title: 'Look at media files', + description: MEDIA, + inputSchema: z.object({ files: z.array(z.string().regex(/\S/, 'a file name or an address, not blank')).min(1).max(20).describe('Each by its file name alone, its path in a folder this server may use, or its web address') }), + annotations: { readOnlyHint: true, openWorldHint: true } + }, async ({ files }) => { + const allowed = await folders() + if (!allowed.length) return refusal('This server has no folder to read in: start it with --allow , or give it a folder from the app.') + // Read as a build reads a source's files: a name alone from the first folder, a local file + // only in these folders, a web address only on the public internet. + const facts = await describeMedia(files, { base: allowed[0], within: allowed, fetch: publicFetch }) + const lines = facts.map(mediaLine) + // Said with the folders, since a model cannot know them: the refusal names none. + if (lines.some((line) => /the folders this build may read/.test(line))) lines.push(whereFiles(allowed)) + return facts.every(({ problem }) => problem) ? refusal(lines.join('\n')) : answer(lines.join('\n')) + }) + server.registerTool('h5p_read', { title: 'Read an H5P package', description: READ, diff --git a/packages/mcp/tests/server.test.ts b/packages/mcp/tests/server.test.ts index 971dec5..0d99541 100644 --- a/packages/mcp/tests/server.test.ts +++ b/packages/mcp/tests/server.test.ts @@ -5,6 +5,8 @@ import { Client } from '@modelcontextprotocol/client' import { StdioClientTransport } from '@modelcontextprotocol/client/stdio' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { z } from 'zod' +// An mp4 as its boxes, with the length its index gives: the author package's own test helper. +import { mp4 } from '../../author/tests/helpers/mp4' /** * The server as an app runs it: the command the package ships, started over standard input and @@ -23,6 +25,9 @@ const SOURCE = { params: { question: '

Water boils at 100 °C at sea level.

', correct: 'true' } } +const PIXEL = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') +const CLIP = mp4(true, { seconds: 20, tracks: [['vide', 'avc1'], ['soun', 'mp4a']] }) + type Content = { type: string, text?: string, data?: string, mimeType?: string } type Answer = { content: Content[], isError?: boolean } @@ -51,10 +56,10 @@ afterAll(async () => { }) describe('the server', () => { - it('offers four tools and the flow, in few words', async () => { + it('offers five tools and the flow, in few words', async () => { const { tools } = await client.listTools() - expect(tools.map((tool) => tool.name).sort()).toEqual(['h5p_build', 'h5p_preview', 'h5p_read', 'h5p_types']) - expect(client.getInstructions()).toMatch(/h5p_types[\s\S]*h5p_build[\s\S]*h5p_preview[\s\S]*h5p_read/) + expect(tools.map((tool) => tool.name).sort()).toEqual(['h5p_build', 'h5p_media', 'h5p_preview', 'h5p_read', 'h5p_types']) + expect(client.getInstructions()).toMatch(/h5p_types[\s\S]*h5p_media[\s\S]*h5p_build[\s\S]*h5p_preview[\s\S]*h5p_read/) // A source's own fields as the author package declares them, before one is written (#230), // with nothing required or forbidden, so no app refuses a source the build would read (#174). const source = tools.find((tool) => tool.name === 'h5p_build')?.inputSchema.properties?.source as Record @@ -165,10 +170,39 @@ describe('h5p_build', () => { }) }) +describe('h5p_media', () => { + it('says what a file in its folder is before a source names it, and refuses one outside (#260)', async () => { + await writeFile(join(folder, 'pixel.png'), PIXEL) + await writeFile(join(elsewhere, 'pixel.png'), PIXEL) + const answer = await call('h5p_media', { files: ['pixel.png', join(folder, 'pixel.png'), join(elsewhere, 'pixel.png'), 'gone.mp4'] }) + expect(answer.isError).toBeFalsy() + // Words alone, with no structured part to stand in for them in an app that reads only that. + expect(answer).not.toHaveProperty('structuredContent') + expect(textOf(answer).split('\n')).toEqual([ + 'pixel.png: a PNG picture, 1 by 1 pixels', + `${join(folder, 'pixel.png')}: a PNG picture, 1 by 1 pixels`, + // No path but the one written, and where the files are, since a model cannot know. + `${join(elsewhere, 'pixel.png')}: is outside the folders this build may read`, + 'gone.mp4: no such file in the folders this build may read', + `This server reads files and writes packages only in ${folder}. A file's path written alone, as { "path": "picture.png" }, is read from ${folder}.` + ]) + // Nothing read at all is an error, for an app that shows one. + expect((await call('h5p_media', { files: ['gone.mp4'] })).isError).toBe(true) + }) + + it('says the length an Interactive Video\'s times were held to, with its build (#260)', async () => { + await writeFile(join(folder, 'clip.mp4'), CLIP) + expect(textOf(await call('h5p_media', { files: ['clip.mp4'] }))).toBe('clip.mp4: an MP4 video, 20 s long') + const interaction = { duration: { from: 2, to: 6 }, label: 'Look', action: { library: 'H5P.Text', params: { text: 'Look' } } } + const video = { ...SOURCE, type: 'H5P.InteractiveVideo', title: 'Timed video', params: { interactiveVideo: { video: { files: [{ path: 'clip.mp4' }] }, assets: { interactions: [interaction] } } } } + const text = textOf(await call('h5p_build', { source: video, verify: false })) + expect(text).toContain('The video clip.mp4 is 20 s long: keep every time within it.') + expect(text).toContain('Note: params.interactiveVideo.assets.interactions holds 1 interaction shown at the times written') + }) +}) + describe('h5p_read', () => { /** A picture of one pixel, which a build reads the size of. */ - const PIXEL = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') - it('reads a package back into its source in a new folder beside it, its files named where they were written, to build again', async () => { await writeFile(join(folder, 'pixel.png'), PIXEL) const picture = { library: 'H5P.Image', params: { file: { path: 'pixel.png' }, alt: 'A pixel' } } diff --git a/skills/h5p-author/SKILL.md b/skills/h5p-author/SKILL.md index 529edcb..97e8c01 100644 --- a/skills/h5p-author/SKILL.md +++ b/skills/h5p-author/SKILL.md @@ -86,7 +86,10 @@ H5P.Video, H5P.Text. and `:` for `:`: `*10:30*` takes 10:30, where `*10:30*` is the answer 10 with the tip 30. A backslash escapes nothing. - A file is `{ "path": "photo.jpg" }`, beside the source or a web address, with `copyright` - when known. + when known. What a file is, a video's length or a picture's size, is one command, `media`: + `npx @missing-elements/h5p-author@latest media clip.mp4` where npm reaches its registry, + `node h5p-author.mjs media clip.mp4` beside the tool of route 1 or 3, `h5p_media` among + route 0's tools. - Sub-content is `{ "library": "H5P.MultiChoice", "params": { … }, "metadata": { "title": "…" } }`. Where it sits is the type file's to say, a level deeper than a guess puts it: an item of H5P.Column's `content` is `{ "content": }`, a slide's element diff --git a/skills/h5p-author/references/authoring.md b/skills/h5p-author/references/authoring.md index 3ebcfea..f6bf372 100644 --- a/skills/h5p-author/references/authoring.md +++ b/skills/h5p-author/references/authoring.md @@ -38,5 +38,7 @@ change it: `…/Panopto/Pages/Viewer.aspx?id=…`, Echo360's `echo360.org/media/…/h5p`. - Pictures: `.png`, `.jpg`, `.gif`, `.bmp`. Video: `.mp4`, `.webm`. Audio: `.mp3`, `.m4a`, `.wav`, `.ogg`. H5P takes no SVG or WebP. -- Positions on a picture (hotspots, areas, stages) are guesses until seen: look at the picture - if you can, and ask the user to check them in the preview. +- Places on a picture (hotspots, areas, stages) are guesses until seen: where you can see the + picture, look before you place anything (route 0 passes an attachment on unopened). No tool + watches a video, so its times stay guesses. The build notes what it placed or timed by numbers + alone: that note goes to the user. diff --git a/skills/h5p-author/references/build/built-here.md b/skills/h5p-author/references/build/built-here.md index 9130611..f7976a9 100644 --- a/skills/h5p-author/references/build/built-here.md +++ b/skills/h5p-author/references/build/built-here.md @@ -8,7 +8,7 @@ over it, so a later build takes a new name (`course-2.h5p`). Copy the one you ha name the user asked for without writing over a file already there (`cp -n`). If that name is taken, take a new name and say so. Never delete or overwrite a file to free a name. Pass the build's notes on to the user: texts left in English, a slide that holds -too much. +too much, hotspots or times to look at in the preview. ## Verify diff --git a/skills/h5p-author/references/build/tools.md b/skills/h5p-author/references/build/tools.md index 186f4de..a59cd10 100644 --- a/skills/h5p-author/references/build/tools.md +++ b/skills/h5p-author/references/build/tools.md @@ -5,6 +5,8 @@ folders and checks it, or `h5p_play`, which checks the source and plays the acti with a download of the file. They are the build: run no command and download nothing. - A type with no file here: `h5p_types` with the type gives its fields. +- What a file is before the source names it, a video's length or a picture's size: `h5p_media` + with the file, where this chat has it. - Call the tool with the source. Where it lists problems, fix each at its path and call it again. - A file the user attached in the chat goes in `h5p_play`'s `file` as it is: do not open it. - A package the user has is read into its source with `h5p_read`, where this chat has it. diff --git a/skills/h5p-author/references/types/H5P.ImageHotspots.md b/skills/h5p-author/references/types/H5P.ImageHotspots.md index 52dd9a0..1ad4742 100644 --- a/skills/h5p-author/references/types/H5P.ImageHotspots.md +++ b/skills/h5p-author/references/types/H5P.ImageHotspots.md @@ -3,7 +3,7 @@ A picture with spots that open text, a picture, audio or video when clicked: a labelled diagram, a map to explore. Not scored. - `image` is the picture; `backgroundImageAltText` describes it. -- Each item of `hotspots` sits at `position.x` and `position.y`, in percent of the picture's width and height from its top left. Look at the picture to place them; the preview shows where they landed. +- Each item of `hotspots` has its centre at `position.x` and `position.y`, in percent of the picture's width and height from its top left (its top left, where a package read back has `legacyPositioning: true`). Look at the picture to place them; the preview shows where they landed. - A hotspot's `content` is a list of sub-content: H5P.Text, H5P.Image, H5P.Audio or H5P.Video. `header` titles its popup. ## Example diff --git a/skills/h5p-author/references/types/H5P.InteractiveVideo.md b/skills/h5p-author/references/types/H5P.InteractiveVideo.md index a13a363..51b7384 100644 --- a/skills/h5p-author/references/types/H5P.InteractiveVideo.md +++ b/skills/h5p-author/references/types/H5P.InteractiveVideo.md @@ -3,11 +3,11 @@ A video with questions, text and links appearing over it at set times, a bookmark menu, and a summary task at the end. - `interactiveVideo.video.files` is the video: a file beside the source (`.mp4` or `.webm`), a web address of one, or the address of a video on YouTube, Vimeo, Panopto or Echo360, which plays from there. -- Each item of `interactiveVideo.assets.interactions` shows its `action` (sub-content) from `duration.from` to `duration.to`, in seconds. `pause: true` stops the video for it; `displayType` `"button"` shows an icon to open it, `"poster"` shows it open over the video. The build places each interaction; give `x` and `y` (percent of the picture) to place one yourself. +- Each item of `interactiveVideo.assets.interactions` shows its `action` (sub-content) from `duration.from` to `duration.to`, in seconds. A text over the video is H5P.Text: H5P.AdvancedText is not taken here. `pause: true` stops the video for it; `displayType` `"button"` shows an icon to open it, `"poster"` shows it open over the video. The build places each interaction; give `x` and `y` (percent of the picture) to place one yourself. - The build sizes a poster by what it holds: a question 17 by 16, room for four short answers and its buttons; a text as wide as keeps it short; a picture in its own shape. `width` and `height` size one yourself, in em: the video is 40 wide and 22.5 tall at 16:9. Check posters in the preview; on a phone they show as buttons. - Bookmarks: `interactiveVideo.assets.bookmarks`, `[{ "time": 30, "label": "…" }]`. - The summary task at the end is H5P.Summary at `interactiveVideo.summary.task`, shown at `interactiveVideo.summary.displayAt` seconds before the end; leave it out and there is none. -- Know the video's length, and keep every time within it. +- Read the video's length before you write a time, with `media` (SKILL.md, step 2) or the tool `h5p_media`, and keep every time within it: a start past the end is refused. Where it gives none (a WebM, a YouTube video), take the length the user gave, if any, and say in the reply that the times were not checked against it. ## Example