Open History to see the last commit
1import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
2import type { DevicePlatform } from "@t3tools/contracts";
3import type { PlatformOSType } from "react-native";
4
5export interface DeviceStreamConfiguration {
6 readonly access: DeviceHubAccess;
7 readonly platform: DevicePlatform;
8 readonly deviceId: string;
9 readonly colors: {
10 readonly background: string;
11 readonly foreground: string;
12 readonly muted: string;
13 readonly buttonBackground: string;
14 readonly buttonForeground: string;
15 readonly buttonBorder: string;
16 };
17}
18
19export function deviceStreamBaseUrl(
20 viewerPlatform: PlatformOSType,
21 devicePlatform: DevicePlatform,
22 httpBase: string,
23) {
24 if (viewerPlatform !== "android") return "file:///";
25 // Android targets stream through WebCodecs, which needs a secure context. iOS targets
26 // stream an MJPEG image from the environment, which a synthetic https document blocks as
27 // mixed content on plain-http environments even with mixedContentMode="always".
28 if (devicePlatform === "android") return "https://localhost/";
29 return `${new URL(httpBase).origin}/`;
30}
31
32export function deviceStreamDocument(configuration: string, script: string) {
33 const safeConfiguration = configuration.replace(/</g, "\\u003c");
34 const safeScript = script.replace(/<\/script/gi, "<\\/script");
35 const failure = `window.ReactNativeWebView.postMessage(JSON.stringify({type:"status",status:"error",detail:"Device viewer stopped unexpectedly."}));`;
36 return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>window.addEventListener("error",function(){${failure}});window.addEventListener("unhandledrejection",function(){${failure}});\n${safeScript}\ntry{T3DeviceStream.start(${safeConfiguration});}catch{${failure}}</script></body></html>`;
37}
38
39export function deviceStreamMessage(data: string) {
40 try {
41 const message: unknown = JSON.parse(data);
42 if (typeof message !== "object" || message === null || !("type" in message)) return null;
43 if (message.type === "unauthorized" || message.type === "retry") {
44 return { type: message.type } as const;
45 }
46 if (
47 message.type === "input" &&
48 "connected" in message &&
49 typeof message.connected === "boolean"
50 ) {
51 return { type: message.type, connected: message.connected } as const;
52 }
53 if (
54 message.type === "status" &&
55 "status" in message &&
56 (message.status === "connecting" ||
57 message.status === "streaming" ||
58 message.status === "error") &&
59 (!("detail" in message) || typeof message.detail === "string")
60 ) {
61 return {
62 type: message.type,
63 status: message.status,
64 detail:
65 "detail" in message && typeof message.detail === "string" ? message.detail : undefined,
66 } as const;
67 }
68 } catch {}
69 return null;
70}