Files
piik/tests/watch-source-selection.test.ts
T
AAA f8ed4c1c69 feat(watch): one address and one press start a shared video, and a viewer's route is the software's
A sharer was asked whether an address was a direct link or a webpage, which
of a page's media resources to use, by which method viewers should get it
and which tracks to forward, and a viewer whose site route failed had to
know to ask the sharer for the bytes. Those are the software's to find out.

Sharer. One field and one button: an embeddable page, a media address by its
name, or a webpage the linked App opens (watchTogether). The page's videos
are listed with their length and one press starts the pressed one by the
first offer that works (startPageWatch): the App's bytes with the site's
address beside them, the site's address alone, a manifest with default
tracks, separately loaded tracks, and last the page in each person's App.
When no offer starts, the page's offers stay on screen for a choice by hand,
which is otherwise behind one fold.

Viewer. One action wherever a route exists. A join that names no route takes
the site first and the sharer second, and a route that fails gives its place
to the next one not yet taken; a named route is its person's choice and
stays. The playback settings say when that happened.

The order of offers and of routes is one module (watch-plan). The session's
four selection entries commit through one function, so the choice by hand
and the automatic start cannot drift apart.
2026-11-28 23:45:21 +08:00

176 lines
10 KiB
TypeScript

import { afterEach, expect, test, vi } from "vitest";
import { AppPage } from "../src/client/channel/app-link";
import { ChannelSession } from "../src/client/channel/session";
import { watchSourceSchema } from "../src/client/channel/protocol";
import { canWatchInBrowser, originalWatchURL, sharedWatchEmbed } from "../src/client/channel/watch-embed-source";
afterEach(() => vi.unstubAllGlobals());
test("website locators are optional values and do not manufacture an original-page capability", () => {
const opaque = watchSourceSchema.parse({ kind: "website" });
expect(opaque).toEqual({ kind: "website" });
expect(originalWatchURL(opaque)).toBeUndefined();
expect(sharedWatchEmbed(opaque)).toBeNull();
expect(canWatchInBrowser(opaque)).toBe(false);
const portable = watchSourceSchema.parse({ kind: "website", mediaUrl: "https://media.test/film.mp4" });
expect(canWatchInBrowser(portable)).toBe(true);
expect(originalWatchURL(portable)).toBeUndefined();
for (const field of ["url", "mediaUrl"]) {
expect(watchSourceSchema.safeParse({ kind: "website", [field]: null }).success).toBe(false);
expect(watchSourceSchema.safeParse({ kind: "website", [field]: "javascript:invalid" }).success).toBe(false);
}
expect(watchSourceSchema.safeParse({ kind: "media" }).success).toBe(false);
});
test.each(["commit", "cancel", "unknown"] as const)("source discovery survives preparation failure until %s", async finish => {
vi.stubGlobal("window", { localStorage: { getItem: () => null } });
vi.stubGlobal("localStorage", { getItem: () => null });
vi.stubGlobal("location", { origin: "https://source.test", hash: "" });
vi.stubGlobal("history", { state: null });
const session = new ChannelSession();
const candidateId = crypto.randomUUID();
const media = (name: string) => ({ id: crypto.randomUUID(), displayURL: "https://source.test/" + name + ".mp4", name, format: "file" });
const [a, b, c] = ["A", "B", "C"].map(media);
let choices = [a];
let delayDiscovery = false;
let finishDiscovery!: () => void;
const late = new Promise<void>(resolve => { finishDiscovery = resolve; });
const prepare = vi.fn(async (_id: unknown) => { throw new Error("watch_media_access_denied"); });
const catalog = vi.fn(async () => {
if (delayDiscovery) await late;
return { choices, indexedCandidates: [], mpdCandidates: [], byteSource: null };
});
const dispose = vi.fn();
const request = vi.fn(async (_command: unknown, reply: (event: unknown) => void) => {
reply({ type: "watch_ready", serverTime: performance.now() });
});
const page = new AppPage(crypto.randomUUID(), "https://source.test/watch", async command => {
if (command.type === "page_media_sources") return catalog();
if (command.type === "page_media_prepare") return prepare(command.choiceId);
if (command.type === "page_select" || command.type === "page_read")
return { position: 0, rate: 1, readyState: 4, paused: false, duration: 20, ended: false, buffered: [] };
throw Error("unexpected " + command.type);
}, dispose, () => {});
Object.assign(session, { connectApp: async () => ({ preparePage: async () => page }), request });
const changed = () => page.receive({ type: "page_media_changed", pageId: page.id });
try {
await session.prepareWatchPage("room", page.url);
page.receive({ type: "page_candidates", pageId: page.id, url: page.url, candidates: [{ pageURL: page.url, id: candidateId, url: null, title: "Player", duration: 20 }] });
expect(await session.selectWatchPage("room", candidateId)).toBe(false);
const sources = session.watchPage("room")!.watchSources!;
expect(sources.choices).toEqual([a]);
choices = [b];
changed();
await vi.waitFor(() => expect(sources.choices).toEqual([b]));
await expect(session.selectWatchForwardSource("room", b.id, false)).rejects.toThrow("watch_media_access_denied");
choices = [c];
changed();
await vi.waitFor(() => expect(sources.choices).toEqual([c]));
expect(prepare.mock.calls).toEqual([[b.id]]);
expect(request).not.toHaveBeenCalled();
const read = vi.spyOn(page, "read").mockRejectedValueOnce(new Error("page_candidate_unavailable"));
await expect(session.selectWatchBrowserSource("room", null, false)).rejects.toThrow("page_candidate_unavailable");
read.mockRestore();
expect(session.watchPage("room")?.watchSources).toBe(sources);
expect(dispose).not.toHaveBeenCalled();
delayDiscovery = true;
choices = [a];
changed();
expect(catalog).toHaveBeenCalledTimes(4);
if (finish === "commit") {
await session.selectWatchBrowserSource("room", null);
expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "start_watch", source: { kind: "website", url: page.url } }), expect.any(Function), "room");
expect(dispose).not.toHaveBeenCalled();
} else if (finish === "unknown") {
request.mockRejectedValueOnce(new Error("unknown_outcome"));
await expect(session.selectWatchBrowserSource("room", null, false)).rejects.toThrow("unknown_outcome");
expect(dispose).toHaveBeenCalledOnce();
} else {
await session.cancelScreenSelection("room");
expect(dispose).toHaveBeenCalledOnce();
}
expect(session.watchPage("room")).toBeUndefined();
finishDiscovery();
await new Promise(resolve => setTimeout(resolve, 0));
changed();
expect(catalog).toHaveBeenCalledTimes(4);
expect(sources.choices).toEqual([c]);
} finally {
finishDiscovery();
session.close();
}
expect(dispose).toHaveBeenCalledOnce();
});
function pageSession(pageURL: string | null) {
vi.stubGlobal("window", { localStorage: { getItem: () => null } });
vi.stubGlobal("localStorage", { getItem: () => null });
vi.stubGlobal("location", { origin: "https://source.test", hash: "" });
vi.stubGlobal("history", { state: null });
// This page's own player cannot play the site's address here, so an offer that needs it does not start.
vi.stubGlobal("document", { documentElement: {}, createElement: () => { throw new Error("watch_media_unplayable"); } });
const session = new ChannelSession();
const candidateId = crypto.randomUUID();
const choice = { id: crypto.randomUUID(), displayURL: "https://source.test/film.mp4", name: "film.mp4", format: "file" };
const prepare = vi.fn(async (_id: unknown) => { throw new Error("watch_media_range_unsupported"); });
const dispose = vi.fn();
const request = vi.fn(async (_command: unknown, reply: (event: unknown) => void) => { reply({ type: "watch_ready", serverTime: performance.now() }); });
const page = new AppPage(crypto.randomUUID(), "https://source.test/watch", async command => {
if (command.type === "page_media_sources") return { choices: [choice], indexedCandidates: [], mpdCandidates: [], byteSource: null };
if (command.type === "page_media_prepare") return prepare(command.choiceId);
if (command.type === "page_select" || command.type === "page_read")
return { position: 0, rate: 1, readyState: 4, paused: false, duration: 20, ended: false, buffered: [] };
throw Error("unexpected " + command.type);
}, dispose, () => {});
Object.assign(session, { connectApp: async () => ({ preparePage: async () => page }), request });
const open = async () => {
await session.prepareWatchPage("room", page.url);
page.receive({ type: "page_candidates", pageId: page.id, url: page.url, candidates: [{ pageURL, id: candidateId, url: null, title: "Player", duration: 20 }] });
};
return { session, page, candidateId, choice, prepare, request, open };
}
test("a chosen video starts by the first offer that works: the App's bytes, the site's address, then the page itself", async () => {
const { session, page, candidateId, choice, prepare, request, open } = pageSession("https://source.test/watch");
try {
await open();
await session.startPageWatch("room", candidateId);
// The App could not read the file and this page could not play its address, each tried once and in that order.
expect(prepare.mock.calls).toEqual([[choice.id]]);
expect(request).toHaveBeenCalledTimes(1);
expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "start_watch", source: { kind: "website", url: page.url } }), expect.any(Function), "room");
expect(session.watchPage("room")).toBeUndefined();
} finally { session.close(); }
});
test("when no offer starts, the start fails with the last reason and the page's offers stay for a choice by hand", async () => {
const { session, candidateId, choice, request, open } = pageSession(null);
try {
await open();
await expect(session.startPageWatch("room", candidateId, false)).rejects.toThrow("watch_media_unplayable");
expect(request).not.toHaveBeenCalled();
expect(session.watchPage("room")?.watchSources?.choices).toEqual([choice]);
expect(session.getSnapshot().pending.has("screen:room")).toBe(false);
} finally { session.close(); }
});
test("one address finds its own way: a media address starts, a webpage opens in the linked App", async () => {
const { session, page } = pageSession("https://source.test/watch");
const started = vi.fn(async (..._call: unknown[]) => {}), opened = vi.fn(async (..._call: unknown[]) => {});
Object.assign(session, { startWatch: started, prepareWatchPage: opened });
const view = (session as unknown as { view: { appConnected: boolean; pagePlayer: boolean } }).view;
try {
expect(await session.watchTogether("room", " https://media.test/film.mp4 ")).toBe("started");
expect(await session.watchTogether("room", page.url)).toBe("started");
expect(started.mock.calls.map(call => call[1])).toEqual(["https://media.test/film.mp4", page.url]);
view.appConnected = true; view.pagePlayer = true;
expect(await session.watchTogether("room", page.url)).toBe("choosing");
expect(opened).toHaveBeenCalledWith("room", page.url, undefined, true);
// A known media address needs no page even with the App.
expect(await session.watchTogether("room", "https://media.test/list.m3u8")).toBe("started");
expect(opened).toHaveBeenCalledTimes(1);
} finally { session.close(); }
});