electron-cast 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/README.md +49 -20
- package/dist/electron/main.d.ts +15 -2
- package/dist/electron/main.js +200 -14
- package/dist/electron/main.js.map +1 -1
- package/dist/electron/preload.d.ts +13 -1
- package/dist/electron/preload.js +50 -1
- package/dist/electron/preload.js.map +1 -1
- package/dist/electron/presentation-envelope.d.ts +60 -0
- package/dist/electron/presentation-envelope.js +296 -0
- package/dist/electron/presentation-envelope.js.map +1 -0
- package/dist/electron/presentation-handler.d.ts +100 -0
- package/dist/electron/presentation-handler.js +487 -0
- package/dist/electron/presentation-handler.js.map +1 -0
- package/dist/polyfill/presentation-standin.d.ts +13 -0
- package/dist/polyfill/presentation-standin.js +275 -0
- package/dist/polyfill/presentation-standin.js.map +1 -0
- package/package.json +4 -3
- package/src/electron/main.ts +197 -14
- package/src/electron/preload.ts +59 -1
- package/src/electron/presentation-envelope.ts +311 -0
- package/src/electron/presentation-handler.ts +518 -0
- package/src/polyfill/presentation-standin.ts +271 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Installs a page-side stand-in for the Presentation API (`PresentationRequest`, `PresentationConnection`,
|
|
3
|
+
* `PresentationAvailability` and `navigator.presentation`) backed by the IPC bridge the preload script
|
|
4
|
+
* published at `globalThis[bridgeKey]`, so Google's own Cast sender script (clank.js) can run unmodified
|
|
5
|
+
* in Electron. Returns `true` when the stand-in was installed, `false` when the bridge is missing (in
|
|
6
|
+
* which case nothing is changed).
|
|
7
|
+
*
|
|
8
|
+
* Electron runs this function in the page's main world through `contextBridge.executeInMainWorld`, which
|
|
9
|
+
* serializes it to source; the body must therefore stay self-contained: no imports, no module-level
|
|
10
|
+
* helpers or state, and every host global reached through `globalThis`. Type annotations are stripped and
|
|
11
|
+
* leave no runtime references behind.
|
|
12
|
+
*/
|
|
13
|
+
export function installPresentationStandIn(bridgeKey) {
|
|
14
|
+
const g = globalThis;
|
|
15
|
+
const bridge = g[bridgeKey];
|
|
16
|
+
if (!bridge || typeof bridge.call !== "function")
|
|
17
|
+
return false;
|
|
18
|
+
const ET = g.EventTarget;
|
|
19
|
+
const EV = g.Event;
|
|
20
|
+
const ME = g.MessageEvent;
|
|
21
|
+
const DE = g.DOMException;
|
|
22
|
+
const URLC = g.URL;
|
|
23
|
+
const ST = g.setTimeout;
|
|
24
|
+
const uuid = () => g.crypto.randomUUID();
|
|
25
|
+
const MAX_QUEUED_MESSAGES = 1000;
|
|
26
|
+
const connections = new Map();
|
|
27
|
+
const watches = new Map();
|
|
28
|
+
let pendingStart = false;
|
|
29
|
+
// A queued message may be delivered only once the connection is "connected" AND a message handler
|
|
30
|
+
// exists (an onmessage value or an addEventListener("message") listener).
|
|
31
|
+
function messageReady(conn) {
|
|
32
|
+
return conn.state === "connected"
|
|
33
|
+
&& (typeof conn.__h_message === "function" || conn.__msgListeners > 0);
|
|
34
|
+
}
|
|
35
|
+
function maybeFlush(conn) {
|
|
36
|
+
if (conn.__flushScheduled || !messageReady(conn))
|
|
37
|
+
return;
|
|
38
|
+
conn.__flushScheduled = true;
|
|
39
|
+
ST(() => {
|
|
40
|
+
conn.__flushScheduled = false;
|
|
41
|
+
while (conn.__queue.length > 0 && messageReady(conn)) {
|
|
42
|
+
const data = conn.__queue.shift();
|
|
43
|
+
conn.dispatchEvent(new ME("message", { data }));
|
|
44
|
+
}
|
|
45
|
+
}, 0);
|
|
46
|
+
}
|
|
47
|
+
// Defines the on<name> getter/setter pairs (the setter stores a function or null) and wraps
|
|
48
|
+
// dispatchEvent so the stored handler is invoked in addition to addEventListener listeners.
|
|
49
|
+
const wireEvents = (proto, names, onHandlerSet) => {
|
|
50
|
+
for (const name of names) {
|
|
51
|
+
const slot = "__h_" + name;
|
|
52
|
+
Object.defineProperty(proto, "on" + name, {
|
|
53
|
+
configurable: true,
|
|
54
|
+
enumerable: true,
|
|
55
|
+
get() { return this[slot] ?? null; },
|
|
56
|
+
set(value) {
|
|
57
|
+
this[slot] = typeof value === "function" ? value : null;
|
|
58
|
+
if (typeof onHandlerSet === "function")
|
|
59
|
+
onHandlerSet(this);
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const nativeDispatch = proto.dispatchEvent;
|
|
64
|
+
proto.dispatchEvent = function (event) {
|
|
65
|
+
const handled = nativeDispatch.call(this, event);
|
|
66
|
+
const handler = this["__h_" + event.type];
|
|
67
|
+
if (typeof handler === "function")
|
|
68
|
+
handler.call(this, event);
|
|
69
|
+
return handled;
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
class PresentationAvailability extends ET {
|
|
73
|
+
__value;
|
|
74
|
+
constructor(value) {
|
|
75
|
+
super();
|
|
76
|
+
this.__value = !!value;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
Object.defineProperty(PresentationAvailability.prototype, "value", {
|
|
80
|
+
configurable: true,
|
|
81
|
+
enumerable: true,
|
|
82
|
+
get() { return this.__value; },
|
|
83
|
+
});
|
|
84
|
+
wireEvents(PresentationAvailability.prototype, ["change"]);
|
|
85
|
+
class PresentationConnection extends ET {
|
|
86
|
+
connectionId;
|
|
87
|
+
id;
|
|
88
|
+
url;
|
|
89
|
+
state;
|
|
90
|
+
binaryType;
|
|
91
|
+
__queue;
|
|
92
|
+
__flushScheduled;
|
|
93
|
+
__msgListeners;
|
|
94
|
+
__h_message;
|
|
95
|
+
constructor(connectionId, state) {
|
|
96
|
+
super();
|
|
97
|
+
this.connectionId = connectionId;
|
|
98
|
+
this.id = "";
|
|
99
|
+
this.url = "";
|
|
100
|
+
this.state = state;
|
|
101
|
+
this.binaryType = "arraybuffer";
|
|
102
|
+
this.__queue = [];
|
|
103
|
+
this.__flushScheduled = false;
|
|
104
|
+
this.__msgListeners = 0;
|
|
105
|
+
this.__h_message = null;
|
|
106
|
+
}
|
|
107
|
+
send(data) {
|
|
108
|
+
if (this.state !== "connected")
|
|
109
|
+
throw new DE("The connection is not open.", "InvalidStateError");
|
|
110
|
+
if (typeof data !== "string")
|
|
111
|
+
throw new TypeError("send() accepts strings only; binary data is not supported.");
|
|
112
|
+
bridge.send(this.connectionId, data);
|
|
113
|
+
}
|
|
114
|
+
close() { this.__end("closed"); }
|
|
115
|
+
terminate() { this.__end("terminated"); }
|
|
116
|
+
__end(state) {
|
|
117
|
+
if (this.state === "closed" || this.state === "terminated")
|
|
118
|
+
return;
|
|
119
|
+
this.state = state;
|
|
120
|
+
bridge.call(state === "closed" ? "close" : "terminate", { connectionId: this.connectionId });
|
|
121
|
+
connections.delete(this.connectionId);
|
|
122
|
+
this.dispatchEvent(new EV(state === "closed" ? "close" : "terminate"));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
wireEvents(PresentationConnection.prototype, ["message", "close", "terminate", "connect"], (conn) => maybeFlush(conn));
|
|
126
|
+
const nativeAdd = PresentationConnection.prototype.addEventListener;
|
|
127
|
+
const nativeRemove = PresentationConnection.prototype.removeEventListener;
|
|
128
|
+
PresentationConnection.prototype.addEventListener = function (type, listener, options) {
|
|
129
|
+
if (type === "message") {
|
|
130
|
+
this.__msgListeners += 1;
|
|
131
|
+
maybeFlush(this);
|
|
132
|
+
}
|
|
133
|
+
return nativeAdd.call(this, type, listener, options);
|
|
134
|
+
};
|
|
135
|
+
PresentationConnection.prototype.removeEventListener = function (type, listener, options) {
|
|
136
|
+
if (type === "message" && this.__msgListeners > 0)
|
|
137
|
+
this.__msgListeners -= 1;
|
|
138
|
+
return nativeRemove.call(this, type, listener, options);
|
|
139
|
+
};
|
|
140
|
+
function settleConnection(conn, connectionId, result) {
|
|
141
|
+
if (result && result.ok) {
|
|
142
|
+
const value = result.value || {};
|
|
143
|
+
conn.id = value.id ?? "";
|
|
144
|
+
conn.url = value.url ?? "";
|
|
145
|
+
conn.state = "connected";
|
|
146
|
+
conn.dispatchEvent(new EV("connect"));
|
|
147
|
+
maybeFlush(conn);
|
|
148
|
+
return conn;
|
|
149
|
+
}
|
|
150
|
+
connections.delete(connectionId);
|
|
151
|
+
throw new DE((result && result.description) ?? "", (result && result.code) ?? "OperationError");
|
|
152
|
+
}
|
|
153
|
+
class PresentationRequest extends ET {
|
|
154
|
+
urls;
|
|
155
|
+
constructor(urls) {
|
|
156
|
+
super();
|
|
157
|
+
const list = Array.isArray(urls) ? urls.slice() : [urls];
|
|
158
|
+
if (list.length === 0) {
|
|
159
|
+
throw new DE("PresentationRequest requires at least one url.", "NotSupportedError");
|
|
160
|
+
}
|
|
161
|
+
for (const u of list) {
|
|
162
|
+
try {
|
|
163
|
+
new URLC(String(u));
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
throw new DE("Invalid URL: " + String(u), "SyntaxError");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
this.urls = Object.freeze(list);
|
|
170
|
+
}
|
|
171
|
+
start() {
|
|
172
|
+
const nav = g.navigator;
|
|
173
|
+
const ua = nav ? nav.userActivation : undefined;
|
|
174
|
+
if (ua && ua.isActive === false) {
|
|
175
|
+
return Promise.reject(new DE("Presentation.start() requires a user gesture.", "AbortError"));
|
|
176
|
+
}
|
|
177
|
+
if (pendingStart) {
|
|
178
|
+
return Promise.reject(new DE("A call to start() is already in progress.", "OperationError"));
|
|
179
|
+
}
|
|
180
|
+
pendingStart = true;
|
|
181
|
+
const connectionId = uuid();
|
|
182
|
+
const conn = new PresentationConnection(connectionId, "connecting");
|
|
183
|
+
connections.set(connectionId, conn);
|
|
184
|
+
return Promise.resolve(bridge.call("start", { connectionId, urls: [...this.urls], hasGesture: !(ua && ua.isActive === false) }))
|
|
185
|
+
.then((result) => settleConnection(conn, connectionId, result))
|
|
186
|
+
.finally(() => {
|
|
187
|
+
pendingStart = false;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
reconnect(presentationId) {
|
|
191
|
+
const connectionId = uuid();
|
|
192
|
+
const conn = new PresentationConnection(connectionId, "connecting");
|
|
193
|
+
connections.set(connectionId, conn);
|
|
194
|
+
return Promise.resolve(bridge.call("reconnect", { connectionId, urls: [...this.urls], presentationId }))
|
|
195
|
+
.then((result) => settleConnection(conn, connectionId, result));
|
|
196
|
+
}
|
|
197
|
+
getAvailability() {
|
|
198
|
+
const watchId = uuid();
|
|
199
|
+
const avail = new PresentationAvailability(false);
|
|
200
|
+
watches.set(watchId, avail);
|
|
201
|
+
return Promise.resolve(bridge.call("getAvailability", { watchId, urls: [...this.urls] }))
|
|
202
|
+
.then((result) => {
|
|
203
|
+
avail.__value = !!(result && result.ok && result.value && result.value.available);
|
|
204
|
+
return avail;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
wireEvents(PresentationRequest.prototype, ["connectionavailable"]);
|
|
209
|
+
bridge.onEvent((e) => {
|
|
210
|
+
if (!e || typeof e !== "object")
|
|
211
|
+
return;
|
|
212
|
+
if (e.type === "availability") {
|
|
213
|
+
const avail = watches.get(e.watchId);
|
|
214
|
+
if (!avail)
|
|
215
|
+
return;
|
|
216
|
+
const next = !!e.value;
|
|
217
|
+
if (next !== avail.__value) {
|
|
218
|
+
avail.__value = next;
|
|
219
|
+
avail.dispatchEvent(new EV("change"));
|
|
220
|
+
}
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (e.type === "message") {
|
|
224
|
+
const conn = connections.get(e.connectionId);
|
|
225
|
+
if (!conn)
|
|
226
|
+
return;
|
|
227
|
+
conn.__queue.push(e.data);
|
|
228
|
+
if (conn.__queue.length > MAX_QUEUED_MESSAGES)
|
|
229
|
+
conn.__queue.shift();
|
|
230
|
+
maybeFlush(conn);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (e.type === "statechange") {
|
|
234
|
+
const conn = connections.get(e.connectionId);
|
|
235
|
+
if (!conn)
|
|
236
|
+
return;
|
|
237
|
+
const terminated = e.state === "terminated";
|
|
238
|
+
conn.state = terminated ? "terminated" : "closed";
|
|
239
|
+
connections.delete(e.connectionId);
|
|
240
|
+
const ev = new EV(terminated ? "terminate" : "close");
|
|
241
|
+
ev.reason = e.reason ?? null;
|
|
242
|
+
ev.message = e.message ?? null;
|
|
243
|
+
conn.dispatchEvent(ev);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (e.type === "connectionavailable") {
|
|
247
|
+
const conn = new PresentationConnection(e.connectionId, "connected");
|
|
248
|
+
conn.id = e.id ?? "";
|
|
249
|
+
conn.url = e.url ?? "";
|
|
250
|
+
connections.set(e.connectionId, conn);
|
|
251
|
+
const pres = g.navigator ? g.navigator.presentation : null;
|
|
252
|
+
const req = pres ? pres.defaultRequest : null;
|
|
253
|
+
if (req instanceof PresentationRequest) {
|
|
254
|
+
const ev = new EV("connectionavailable");
|
|
255
|
+
ev.connection = conn;
|
|
256
|
+
req.dispatchEvent(ev);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
const pres = { defaultRequest: null, receiver: null };
|
|
261
|
+
if (g.navigator) {
|
|
262
|
+
Object.defineProperty(g.navigator, "presentation", {
|
|
263
|
+
configurable: true,
|
|
264
|
+
enumerable: true,
|
|
265
|
+
get() { return pres; },
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
Object.defineProperty(g, "PresentationRequest", { value: PresentationRequest, writable: true, configurable: true, enumerable: true });
|
|
269
|
+
Object.defineProperty(g, "PresentationConnection", { value: PresentationConnection, writable: true, configurable: true, enumerable: true });
|
|
270
|
+
Object.defineProperty(g, "PresentationAvailability", { value: PresentationAvailability, writable: true, configurable: true, enumerable: true });
|
|
271
|
+
if (!g.chrome)
|
|
272
|
+
g.chrome = {};
|
|
273
|
+
return true;
|
|
274
|
+
}
|
|
275
|
+
//# sourceMappingURL=presentation-standin.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"presentation-standin.js","sourceRoot":"","sources":["../../src/polyfill/presentation-standin.ts"],"names":[],"mappings":"AAAA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AAC,cAAc,CAAC,CAAC,EAAE,wBAAwB,EAAE,EAAE,KAAK,EAAE,sBAAsB,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5I,MAAM,CAAC,cAAc,CAAC,CAAC,EAAE,0BAA0B,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IAChJ,IAAI,CAAC,CAAC,CAAC,MAAM;QAAE,CAAC,CAAC,MAAM,GAAG,EAAE,CAAC;IAE7B,OAAO,IAAI,CAAC;AACd,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "electron-cast",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Chromecast for Electron:
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Chromecast for Electron: lets pages run Google's own Cast SDK by supplying the Media Router Electron lacks, with device discovery and the Cast v2 protocol in the main process.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"electron",
|
|
7
7
|
"chromecast",
|
|
8
8
|
"cast",
|
|
9
9
|
"google-cast",
|
|
10
10
|
"chrome.cast",
|
|
11
|
-
"castv2"
|
|
11
|
+
"castv2",
|
|
12
|
+
"presentation-api"
|
|
12
13
|
],
|
|
13
14
|
"license": "MIT",
|
|
14
15
|
"author": "Adam Perkins",
|
package/src/electron/main.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { CastSessionService, type CastClientLike, type DeviceSource, type CastRe
|
|
|
2
2
|
import type { CastDevice } from "../discovery/index.ts";
|
|
3
3
|
import { CastDiscovery } from "../discovery/index.ts";
|
|
4
4
|
import { CastClient } from "../client/index.ts";
|
|
5
|
+
import { CastPresentationHandler, type PresentationConnectionHandle } from "./presentation-handler.ts";
|
|
5
6
|
|
|
6
7
|
export type { CastRequestInfo, DeviceChoice } from "./session-service.ts";
|
|
7
8
|
export type { CastDevice } from "../discovery/index.ts";
|
|
@@ -18,10 +19,14 @@ export interface WebContentsLike {
|
|
|
18
19
|
}
|
|
19
20
|
/** The subset of an Electron `IpcMainInvokeEvent` the manager needs. */
|
|
20
21
|
export interface IpcMainInvokeEventLike { sender: WebContentsLike; senderFrame: FrameLike | null }
|
|
21
|
-
/** The subset of an Electron `
|
|
22
|
+
/** The subset of an Electron `IpcMainEvent` the manager needs. */
|
|
23
|
+
export interface IpcMainEventLike { sender: WebContentsLike }
|
|
24
|
+
/** The subset of an Electron `IpcMain` the manager needs (`on`/`removeListener` unless `presentation: false`). */
|
|
22
25
|
export interface IpcMainLike {
|
|
23
26
|
handle(channel: string, listener: (event: IpcMainInvokeEventLike, ...args: any[]) => unknown): void;
|
|
24
27
|
removeHandler(channel: string): void;
|
|
28
|
+
on?(channel: string, listener: (event: IpcMainEventLike, ...args: any[]) => void): unknown;
|
|
29
|
+
removeListener?(channel: string, listener: (event: IpcMainEventLike, ...args: any[]) => void): unknown;
|
|
25
30
|
}
|
|
26
31
|
/** Dependencies of {@link createCastManager}; the Electron objects are passed in, never imported. */
|
|
27
32
|
export interface CastManagerOptions {
|
|
@@ -31,6 +36,12 @@ export interface CastManagerOptions {
|
|
|
31
36
|
discovery?: DeviceSource & { start(): Promise<void>; stop(): void }; // default new CastDiscovery()
|
|
32
37
|
createClient?(device: CastDevice): CastClientLike; // default new CastClient({ host, port })
|
|
33
38
|
channel?: string; // default "electron-cast"
|
|
39
|
+
/**
|
|
40
|
+
* Answer the preload's presentation mode (the page's own Google Cast SDK running on a stand-in Presentation API),
|
|
41
|
+
* which is the preload's default. Needs `ipcMain.on` and `ipcMain.removeListener`. Default true; false serves only
|
|
42
|
+
* the preload's `mode: "chromecast"`.
|
|
43
|
+
*/
|
|
44
|
+
presentation?: boolean;
|
|
34
45
|
}
|
|
35
46
|
/** The main-process cast manager. */
|
|
36
47
|
export interface CastManager {
|
|
@@ -39,22 +50,48 @@ export interface CastManager {
|
|
|
39
50
|
dispose(): Promise<void>;
|
|
40
51
|
}
|
|
41
52
|
|
|
53
|
+
/** Availability watches kept per webContents; the page never releases one, so the oldest are dropped. */
|
|
54
|
+
const MAX_WATCHES_PER_PAGE = 32;
|
|
55
|
+
/** Largest page-to-receiver message accepted (Cast messages are capped at 64 KiB on the wire). */
|
|
56
|
+
const MAX_MESSAGE_CHARS = 1 << 20;
|
|
57
|
+
|
|
58
|
+
/** The sending frame's origin; null when there is no frame. An unparseable URL gives "" so allowOrigin decides. */
|
|
59
|
+
function originOf(frame: FrameLike | null): string | null {
|
|
60
|
+
if (frame === null) return null;
|
|
61
|
+
if (typeof frame.origin === "string" && frame.origin !== "") return frame.origin;
|
|
62
|
+
try {
|
|
63
|
+
return new URL(frame.url).origin;
|
|
64
|
+
} catch {
|
|
65
|
+
return "";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
42
69
|
/**
|
|
43
70
|
* Wires the session service to Electron IPC: one invoke handler per app on
|
|
44
71
|
* `<channel>:call`, events sent back on `<channel>:event`. Each webContents is
|
|
45
|
-
* a sender that leaves its sessions when it is destroyed or navigates.
|
|
72
|
+
* a sender that leaves its sessions when it is destroyed or navigates. Unless
|
|
73
|
+
* `presentation: false` it also serves `<channel>:presentation` (see {@link CastManagerOptions.presentation}).
|
|
46
74
|
*/
|
|
47
75
|
export function createCastManager(options: CastManagerOptions): CastManager {
|
|
48
76
|
const channel = options.channel ?? "electron-cast";
|
|
77
|
+
if (options.presentation !== false && (typeof options.ipcMain.on !== "function" || typeof options.ipcMain.removeListener !== "function")) {
|
|
78
|
+
throw new TypeError("presentation mode needs ipcMain.on and ipcMain.removeListener");
|
|
79
|
+
}
|
|
49
80
|
const discovery = options.discovery ?? new CastDiscovery();
|
|
50
81
|
const createClient = options.createClient ?? ((d: CastDevice) => new CastClient({ host: d.host, port: d.port }));
|
|
51
82
|
const contents = new Map<number, WebContentsLike>();
|
|
83
|
+
let handler: CastPresentationHandler | undefined;
|
|
52
84
|
const service = new CastSessionService({
|
|
53
85
|
devices: discovery,
|
|
54
86
|
createClient,
|
|
55
87
|
selectDevice: options.selectDevice,
|
|
56
88
|
allowOrigin: options.allowOrigin,
|
|
57
89
|
emit(senderId, event) {
|
|
90
|
+
try {
|
|
91
|
+
handler?.onServiceEvent(senderId, event);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
console.error("electron-cast: presentation handler failed on a service event", err);
|
|
94
|
+
}
|
|
58
95
|
const wc = contents.get(senderId);
|
|
59
96
|
if (wc === undefined || wc.isDestroyed()) return;
|
|
60
97
|
try {
|
|
@@ -70,33 +107,178 @@ export function createCastManager(options: CastManagerOptions): CastManager {
|
|
|
70
107
|
if (contents.has(wc.id)) return;
|
|
71
108
|
contents.set(wc.id, wc);
|
|
72
109
|
wc.once("destroyed", () => {
|
|
110
|
+
presentation?.senderGone(wc.id);
|
|
73
111
|
contents.delete(wc.id);
|
|
74
112
|
service.senderGone(wc.id);
|
|
75
113
|
});
|
|
76
114
|
wc.on("did-navigate", () => {
|
|
115
|
+
presentation?.senderGone(wc.id);
|
|
77
116
|
service.senderGone(wc.id);
|
|
78
117
|
});
|
|
79
118
|
};
|
|
80
119
|
|
|
81
120
|
options.ipcMain.handle(`${channel}:call`, (event, method, params) => {
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
121
|
+
const origin = originOf(event.senderFrame);
|
|
122
|
+
if (origin === null) {
|
|
84
123
|
return Promise.resolve({ ok: false, code: "extension_missing", description: "No sender frame" });
|
|
85
124
|
}
|
|
86
|
-
let origin = "";
|
|
87
|
-
if (typeof frame.origin === "string" && frame.origin !== "") {
|
|
88
|
-
origin = frame.origin;
|
|
89
|
-
} else {
|
|
90
|
-
try {
|
|
91
|
-
origin = new URL(frame.url).origin;
|
|
92
|
-
} catch {
|
|
93
|
-
// invalid URL: keep "" so allowOrigin decides
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
125
|
watch(event.sender);
|
|
97
126
|
return service.handle({ id: event.sender.id, origin }, method, params);
|
|
98
127
|
});
|
|
99
128
|
|
|
129
|
+
/** Presentation mode: IPC for the page's stand-in Presentation API, answered by a CastPresentationHandler. */
|
|
130
|
+
const setUpPresentation = () => {
|
|
131
|
+
const ipc = options.ipcMain;
|
|
132
|
+
const on = ipc.on!.bind(ipc);
|
|
133
|
+
const off = ipc.removeListener!.bind(ipc);
|
|
134
|
+
const h = new CastPresentationHandler({ service });
|
|
135
|
+
handler = h;
|
|
136
|
+
const connections = new Map<string, { conn: PresentationConnectionHandle | null; wcId: number }>();
|
|
137
|
+
const watches = new Map<string, { ac: AbortController; wcId: number }>();
|
|
138
|
+
const sendTo = (wcId: number, payload: unknown): void => {
|
|
139
|
+
const wc = contents.get(wcId);
|
|
140
|
+
if (wc === undefined || wc.isDestroyed()) return;
|
|
141
|
+
try {
|
|
142
|
+
wc.send(`${channel}:presentation:event`, payload);
|
|
143
|
+
} catch {
|
|
144
|
+
// destroyed between the check and the send
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const invalid = (description: string) => ({ ok: false, code: "InvalidAccessError", description });
|
|
148
|
+
const isId = (v: unknown): v is string => typeof v === "string" && v !== "" && v.length <= 256;
|
|
149
|
+
const isUrls = (v: unknown): v is string[] =>
|
|
150
|
+
Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every((u) => typeof u === "string");
|
|
151
|
+
|
|
152
|
+
/** Finish a start/reconnect: register the connection and route its traffic to the page. */
|
|
153
|
+
const open = async (wcId: number, connectionId: string, opening: () => Promise<PresentationConnectionHandle>) => {
|
|
154
|
+
if (connections.has(connectionId)) return invalid("connectionId in use");
|
|
155
|
+
const slot: { conn: PresentationConnectionHandle | null; wcId: number } = { conn: null, wcId };
|
|
156
|
+
connections.set(connectionId, slot); // reserved while the picker or join is pending
|
|
157
|
+
let conn: PresentationConnectionHandle;
|
|
158
|
+
try {
|
|
159
|
+
conn = await opening();
|
|
160
|
+
} catch (err) {
|
|
161
|
+
if (connections.get(connectionId) === slot) connections.delete(connectionId);
|
|
162
|
+
const e = err as { name?: unknown; message?: unknown } | null;
|
|
163
|
+
const name = typeof e?.name === "string" && e.name !== "" && e.name !== "Error" ? e.name : "OperationError";
|
|
164
|
+
return { ok: false, code: name, description: typeof e?.message === "string" ? e.message : String(err) };
|
|
165
|
+
}
|
|
166
|
+
if (!contents.has(wcId) || connections.get(connectionId) !== slot) {
|
|
167
|
+
conn.close();
|
|
168
|
+
return { ok: false, code: "AbortError", description: "The page went away" };
|
|
169
|
+
}
|
|
170
|
+
slot.conn = conn;
|
|
171
|
+
conn.onclose = (state) => {
|
|
172
|
+
if (connections.get(connectionId) === slot) connections.delete(connectionId);
|
|
173
|
+
sendTo(wcId, { type: "statechange", connectionId, state });
|
|
174
|
+
};
|
|
175
|
+
// The stand-in registered this connectionId before calling, so it buffers anything sent before the reply.
|
|
176
|
+
conn.onmessage = (data) => sendTo(wcId, { type: "message", connectionId, data });
|
|
177
|
+
return { ok: true, value: { id: conn.id, url: conn.url } };
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
ipc.handle(`${channel}:presentation`, async (event, method, params) => {
|
|
181
|
+
const origin = originOf(event.senderFrame);
|
|
182
|
+
if (origin === null) return { ok: false, code: "NotAllowedError", description: "No sender frame" };
|
|
183
|
+
watch(event.sender);
|
|
184
|
+
const wcId = event.sender.id;
|
|
185
|
+
const p = (typeof params === "object" && params !== null ? params : {}) as Record<string, unknown>;
|
|
186
|
+
try {
|
|
187
|
+
switch (method) {
|
|
188
|
+
case "getAvailability": {
|
|
189
|
+
if (!isId(p.watchId) || !isUrls(p.urls)) return invalid("getAvailability expects { watchId, urls }");
|
|
190
|
+
const watchId = p.watchId;
|
|
191
|
+
const old = watches.get(watchId);
|
|
192
|
+
if (old !== undefined && old.wcId !== wcId) return invalid("watchId in use");
|
|
193
|
+
old?.ac.abort();
|
|
194
|
+
watches.delete(watchId);
|
|
195
|
+
const mine = [...watches].filter(([, w]) => w.wcId === wcId);
|
|
196
|
+
for (const [id, w] of mine.slice(0, Math.max(0, mine.length - (MAX_WATCHES_PER_PAGE - 1)))) {
|
|
197
|
+
w.ac.abort();
|
|
198
|
+
watches.delete(id);
|
|
199
|
+
}
|
|
200
|
+
const ac = new AbortController();
|
|
201
|
+
watches.set(watchId, { ac, wcId });
|
|
202
|
+
const available = await h.getAvailability({
|
|
203
|
+
urls: p.urls,
|
|
204
|
+
origin,
|
|
205
|
+
senderId: wcId,
|
|
206
|
+
signal: ac.signal,
|
|
207
|
+
onchange: (value) => sendTo(wcId, { type: "availability", watchId, value }),
|
|
208
|
+
});
|
|
209
|
+
return { ok: true, value: { available } };
|
|
210
|
+
}
|
|
211
|
+
case "stopWatching": {
|
|
212
|
+
const w = isId(p.watchId) ? watches.get(p.watchId) : undefined;
|
|
213
|
+
if (w !== undefined && w.wcId === wcId) {
|
|
214
|
+
w.ac.abort();
|
|
215
|
+
watches.delete(p.watchId as string);
|
|
216
|
+
}
|
|
217
|
+
return { ok: true, value: undefined };
|
|
218
|
+
}
|
|
219
|
+
case "start":
|
|
220
|
+
if (!isId(p.connectionId) || !isUrls(p.urls)) return invalid("start expects { connectionId, urls }");
|
|
221
|
+
{
|
|
222
|
+
const urls = p.urls;
|
|
223
|
+
return await open(wcId, p.connectionId, () => h.startPresentation({ urls, origin, senderId: wcId }));
|
|
224
|
+
}
|
|
225
|
+
case "reconnect":
|
|
226
|
+
if (!isId(p.connectionId) || !isUrls(p.urls) || !isId(p.presentationId)) {
|
|
227
|
+
return invalid("reconnect expects { connectionId, urls, presentationId }");
|
|
228
|
+
}
|
|
229
|
+
{
|
|
230
|
+
const { urls, presentationId } = p;
|
|
231
|
+
return await open(wcId, p.connectionId,
|
|
232
|
+
() => h.reconnectPresentation({ urls, origin, senderId: wcId, presentationId }));
|
|
233
|
+
}
|
|
234
|
+
case "close":
|
|
235
|
+
case "terminate": {
|
|
236
|
+
const c = isId(p.connectionId) ? connections.get(p.connectionId) : undefined;
|
|
237
|
+
if (c !== undefined && c.wcId === wcId && c.conn !== null) {
|
|
238
|
+
if (method === "close") c.conn.close();
|
|
239
|
+
else c.conn.terminate();
|
|
240
|
+
}
|
|
241
|
+
return { ok: true, value: undefined };
|
|
242
|
+
}
|
|
243
|
+
default:
|
|
244
|
+
return invalid(`unknown method: ${String(method)}`);
|
|
245
|
+
}
|
|
246
|
+
} catch (err) {
|
|
247
|
+
return { ok: false, code: "OperationError", description: err instanceof Error ? err.message : String(err) };
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
const onSend = (event: IpcMainEventLike, connectionId: unknown, data: unknown): void => {
|
|
252
|
+
if (typeof connectionId !== "string" || typeof data !== "string") return;
|
|
253
|
+
const c = connections.get(connectionId);
|
|
254
|
+
if (c === undefined || c.wcId !== event.sender.id || c.conn === null) return;
|
|
255
|
+
if (data.length > MAX_MESSAGE_CHARS) return;
|
|
256
|
+
c.conn.send(data);
|
|
257
|
+
};
|
|
258
|
+
on(`${channel}:presentation:send`, onSend);
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
/** Close the page's connections and watches before the service drops it. */
|
|
262
|
+
senderGone(wcId: number): void {
|
|
263
|
+
h.senderGone(wcId);
|
|
264
|
+
for (const [id, c] of connections) if (c.wcId === wcId) connections.delete(id);
|
|
265
|
+
for (const [id, w] of watches) {
|
|
266
|
+
if (w.wcId !== wcId) continue;
|
|
267
|
+
w.ac.abort();
|
|
268
|
+
watches.delete(id);
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
dispose(): void {
|
|
272
|
+
ipc.removeHandler(`${channel}:presentation`);
|
|
273
|
+
off(`${channel}:presentation:send`, onSend);
|
|
274
|
+
for (const w of watches.values()) w.ac.abort();
|
|
275
|
+
watches.clear();
|
|
276
|
+
connections.clear();
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
const presentation = options.presentation !== false ? setUpPresentation() : undefined;
|
|
281
|
+
|
|
100
282
|
let disposed = false;
|
|
101
283
|
return {
|
|
102
284
|
start: () => discovery.start(),
|
|
@@ -105,6 +287,7 @@ export function createCastManager(options: CastManagerOptions): CastManager {
|
|
|
105
287
|
if (disposed) return;
|
|
106
288
|
disposed = true;
|
|
107
289
|
options.ipcMain.removeHandler(`${channel}:call`);
|
|
290
|
+
presentation?.dispose();
|
|
108
291
|
discovery.stop();
|
|
109
292
|
await service.dispose();
|
|
110
293
|
contents.clear();
|