A review of watching together against the code. The direct route holds: joining, playing, pausing, seeking and catching up need the room's signalling and the local player and nothing else. Five defects, each with a test that fails before the change. - The automatic start took the first resource of the page that played. An advertisement the page loaded before the film is such a resource. What the software takes out of a page for its person must now be as long as the video they chose; a choice made by hand is left alone. - One reply fixed the clock offset, so one slow reply moved a viewer by half its round trip until the next join or return to the tab. A slower reply that agrees with the kept offset now changes nothing, and one that contradicts it replaces it (the minimum-delay sample of RFC 5905 section 10, with the contradiction test for a clock that stepped). - The periodic alignment joined a running one. When a read of the player outlasted the second between two looks, that turn never ended and the sharer's own pause or seek waited behind it without limit. - A route the room refused after another failed left no player and no reason. The refusal is now reported. - A failed look for the next route was an unhandled rejection.
213 lines
13 KiB
TypeScript
213 lines
13 KiB
TypeScript
import { afterEach, expect, test, vi } from "vitest";
|
|
import { AppPage } from "../src/client/channel/app-link";
|
|
import * as pagePlayback from "../src/client/channel/watch-page-media";
|
|
import { AppPageMedia } from "../src/client/channel/watch-media";
|
|
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(), order: 0, 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, respond?: (command: { type: string; [key: string]: unknown }) => unknown) {
|
|
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(), order: 0, 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 => {
|
|
const response = respond?.(command);
|
|
if (response !== undefined) return response;
|
|
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(); }
|
|
});
|
|
|
|
test.each(["dash", "hls"] as const)("a mixed catalog commits the selected player's %s bytes", async current => {
|
|
const dash = crypto.randomUUID(), hls = crypto.randomUUID(), videoId = crypto.randomUUID(), sourceId = crypto.randomUUID();
|
|
const hlsBytes = { sessionId: crypto.randomUUID(), resourceId: crypto.randomUUID(), format: "hls" };
|
|
const dashBytes = { ...hlsBytes, resourceId: crypto.randomUUID(), format: "dash" };
|
|
const selected = current === "dash" ? dashBytes : hlsBytes;
|
|
const respond = vi.fn((command: { type: string; [key: string]: unknown }) => {
|
|
if (command.type === "page_media_sources") return {
|
|
choices: [{ id: hls, name: "HLS", order: current === "hls" ? 0 : 1, displayURL: "https://source.test/video.m3u8", format: "hls" }],
|
|
mpdCandidates: [{ id: dash, name: "DASH", hostname: "source.test", order: current === "dash" ? 0 : 1 }],
|
|
indexedCandidates: [], byteSource: null,
|
|
};
|
|
if (command.type === "page_media_resource" && command.action === "inspect_mpd" && command.choiceId === dash)
|
|
return { sourceId, tracks: [{ id: videoId, kind: "video", label: "", mimeType: "video/mp4", codec: "avc1",
|
|
language: "", role: "", width: 1280, height: 720, bandwidth: null, frameRate: null }] };
|
|
if (command.type === "page_media_prepare_mpd" && command.sourceId === sourceId && command.videoId === videoId) return dashBytes;
|
|
if (command.type === "page_media_prepare" && command.choiceId === hls) return hlsBytes;
|
|
if (command.type === "page_patch" || command.type === "page_media_stop") return null;
|
|
});
|
|
const { session, page, candidateId, open, request } = pageSession("https://source.test/watch", respond);
|
|
// Supply ready playback in Node while exercising the actual page commands and room commit.
|
|
const playback = vi.spyOn(pagePlayback, "preparePageSuppliedWatchMedia").mockImplementation(async () =>
|
|
new AppPageMedia(page, candidateId, page.hold()) as unknown as pagePlayback.PageSuppliedMedia);
|
|
try {
|
|
await open();
|
|
await session.startPageWatch("room", candidateId);
|
|
expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "start_watch", byteSource: selected }), expect.any(Function), "room");
|
|
// The software picked this offer for a video its person chose, so the player is told to hold it to that video.
|
|
expect(playback.mock.calls.map(call => call[4])).toEqual([true]);
|
|
expect(respond.mock.calls.map(([command]) => command).filter(command => command.type.startsWith("page_media_prepare")))
|
|
.toHaveLength(1);
|
|
} finally { playback.mockRestore(); session.close(); }
|
|
});
|