-
Notifications
You must be signed in to change notification settings - Fork 116
/
PuppeteerStream.ts
348 lines (300 loc) · 9.18 KB
/
PuppeteerStream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import {
launch as puppeteerLaunch,
LaunchOptions,
Browser,
Page,
BrowserLaunchArgumentOptions,
BrowserConnectOptions,
} from "puppeteer-core";
import * as path from "path";
import { Transform } from "stream";
import WebSocket, { WebSocketServer } from "ws";
import { IncomingMessage } from "http";
const extensionId = "jjndjgheafjngoipoacpjgeicjeomjli";
let currentIndex = 0;
type StreamLaunchOptions = LaunchOptions &
BrowserLaunchArgumentOptions &
BrowserConnectOptions & {
allowIncognito?: boolean;
} & {
closeDelay?: number;
} & {
extensionPath?: string;
};
let port: number;
export const wss = (async () => {
for (let i = 55200; i <= 65535; i++) {
const ws = new WebSocketServer({ port: i });
const promise = await Promise.race([
new Promise((resolve) => {
ws.on("error", (e: any) => {
resolve(!e.message.includes("EADDRINUSE"));
});
}),
new Promise((resolve) => {
ws.on("listening", () => {
resolve(true);
});
}),
]);
if (promise) {
port = i;
return ws;
}
}
})();
export async function launch(
arg1: StreamLaunchOptions | { launch?: Function; [key: string]: any },
opts?: StreamLaunchOptions
): Promise<Browser> {
//if puppeteer library is not passed as first argument, then first argument is options
// @ts-ignore
if (typeof arg1.launch != "function") opts = arg1;
if (!opts) opts = {};
if (!opts.args) opts.args = [];
function addToArgs(arg: string, value?: string) {
if (!value) {
if (opts.args.includes(arg)) return;
return opts.args.push(arg);
}
let found = false;
opts.args = opts.args.map((x) => {
if (x.includes(arg)) {
found = true;
return x + "," + value;
}
return x;
});
if (!found) opts.args.push(arg + value);
}
if (!opts.extensionPath) {
opts.extensionPath = path.join(__dirname, "..", "extension");
}
addToArgs("--load-extension=", opts.extensionPath);
addToArgs("--disable-extensions-except=", opts.extensionPath);
addToArgs("--allowlisted-extension-id=", extensionId);
addToArgs("--autoplay-policy=no-user-gesture-required");
addToArgs("--auto-accept-this-tab-capture");
if (opts.defaultViewport?.width && opts.defaultViewport?.height) {
opts.args.push(`--window-size=${opts.defaultViewport.width},${opts.defaultViewport.height}`);
opts.args.push(`--ozone-override-screen-size=${opts.defaultViewport.width},${opts.defaultViewport.height}`);
}
// @ts-ignore
opts.headless = opts.headless === "new" ? "new" : false;
if (opts.headless) {
if (!opts.ignoreDefaultArgs) opts.ignoreDefaultArgs = [];
if (Array.isArray(opts.ignoreDefaultArgs) && !opts.ignoreDefaultArgs.includes("--mute-audio"))
opts.ignoreDefaultArgs.push("--mute-audio");
if (!opts.args.includes("--headless=new")) opts.args.push("--headless=new");
}
let browser: Browser;
// @ts-ignore
if (typeof arg1.launch == "function") {
// @ts-ignore
browser = await arg1.launch(opts);
} else {
browser = await puppeteerLaunch(opts);
}
if (opts.allowIncognito) {
const settings = await browser.newPage();
await settings.goto(`chrome://extensions/?id=${extensionId}`);
await settings.evaluate(() => {
(document as any)
.querySelector("extensions-manager")
.shadowRoot.querySelector("#viewManager > extensions-detail-view.active")
.shadowRoot.querySelector(
"div#container.page-container > div.page-content > div#options-section extensions-toggle-row#allow-incognito"
)
.shadowRoot.querySelector("label#label input")
.click();
});
await settings.close();
}
(await browser.newPage()).goto(`chrome-extension://${extensionId}/options.html#${port}`);
const old_browser_close = browser.close;
browser.close = async () => {
for (const page of await browser.pages()) {
if (!page.url().startsWith(`chrome-extension://${extensionId}/options.html`)) {
await page.close();
}
}
const extension = await getExtensionPage(browser);
await extension.evaluate(async () => {
return chrome.tabs.query({});
});
if (opts.closeDelay) {
await new Promise((r) => setTimeout(r, opts.closeDelay));
}
await old_browser_close.call(browser);
};
return browser;
}
export type BrowserMimeType =
| "video/webm"
| "video/webm;codecs=vp8"
| "video/webm;codecs=vp9"
| "video/webm;codecs=vp8.0"
| "video/webm;codecs=vp9.0"
| "video/webm;codecs=vp8,opus"
| "video/webm;codecs=vp8,pcm"
| "video/WEBM;codecs=VP8,OPUS"
| "video/webm;codecs=vp9,opus"
| "video/webm;codecs=vp8,vp9,opus"
| "audio/webm"
| "audio/webm;codecs=opus"
| "audio/webm;codecs=pcm";
export type Constraints = {
mandatory?: MediaTrackConstraints;
optional?: MediaTrackConstraints;
};
interface IPuppeteerStreamOpts {
onDestroy: () => Promise<void>;
highWaterMarkMB: number;
immediateResume: boolean;
port: number;
}
interface TabQueryOptions {
active?: boolean;
audible?: boolean;
autoDiscardable?: boolean;
currentWindow?: boolean;
discarded?: boolean;
groupId?: number;
highlighted?: boolean;
index?: number;
lastFocusedWindow?: boolean;
muted?: boolean;
pinned?: boolean;
status?: TabStatus;
title?: string;
url?: string | string[];
windowId?: number;
windowType?: WindowType;
}
type TabStatus = "unloaded" | "loading" | "complete";
type WindowType = "normal" | "popup" | "panel" | "app" | "devtools";
export interface getStreamOptions {
audio: boolean;
video: boolean;
videoConstraints?: Constraints;
audioConstraints?: Constraints;
mimeType?: BrowserMimeType;
audioBitsPerSecond?: number;
videoBitsPerSecond?: number;
bitsPerSecond?: number;
frameSize?: number;
delay?: number;
/**
* Tab query options to target the correct tab,
* see [Chrome's extensions documentation](https://developer.chrome.com/docs/extensions/reference/api/tabs#method-query) for more info.
*/
tabQuery?: TabQueryOptions;
retry?: {
each?: number;
times?: number;
};
streamConfig?: {
highWaterMarkMB?: number;
immediateResume?: boolean;
closeTimeout?: number;
};
}
export async function getExtensionPage(browser: Browser) {
const extensionTarget = await browser.waitForTarget((target) => {
return target.type() === "page" && target.url().startsWith(`chrome-extension://${extensionId}/options.html`);
});
if (!extensionTarget) throw new Error("cannot load extension");
const videoCaptureExtension = await extensionTarget.page();
if (!videoCaptureExtension) throw new Error("cannot get page of extension");
return videoCaptureExtension;
}
let mutex = false;
let queue: Function[] = [];
function lock() {
return new Promise((res) => {
if (!mutex) {
mutex = true;
return res(null);
}
queue.push(res);
});
}
function unlock() {
if (queue.length) queue.shift()();
else mutex = false;
}
export async function getStream(page: Page, opts: getStreamOptions) {
if (!opts.audio && !opts.video) throw new Error("At least audio or video must be true");
if (!opts.mimeType) {
if (opts.video) opts.mimeType = "video/webm";
else if (opts.audio) opts.mimeType = "audio/webm";
}
if (!opts.frameSize) opts.frameSize = 20;
const retryPolicy = Object.assign({}, { each: 20, times: 3 }, opts.retry);
const extension = await getExtensionPage(page.browser());
const highWaterMarkMB = opts.streamConfig?.highWaterMarkMB || 8;
const index = currentIndex++;
await lock();
await page.bringToFront();
const [tab] = await extension.evaluate(
async (x) => {
// @ts-ignore
return chrome.tabs.query(x);
},
opts.tabQuery || {
active: true,
}
);
unlock();
if (!tab) throw new Error("Cannot find tab, try providing your own tabQuery to getStream options");
const stream = new Transform({
highWaterMark: 1024 * 1024 * highWaterMarkMB,
transform(chunk, encoding, callback) {
callback(null, chunk);
},
});
function onConnection(ws: WebSocket, req: IncomingMessage) {
const url = new URL(`http://localhost:${port}${req.url}`);
if (url.searchParams.get("index") != index.toString()) return;
async function close() {
if (!stream.readableEnded && !stream.writableEnded) stream.end();
if (!extension.isClosed() && extension.browser().isConnected()) {
// @ts-ignore
extension.evaluate((index) => STOP_RECORDING(index), index);
}
if (ws.readyState != WebSocket.CLOSED) {
setTimeout(() => {
// await pending messages to be sent and then close the socket
if (ws.readyState != WebSocket.CLOSED) ws.close();
}, opts.streamConfig?.closeTimeout ?? 5000);
}
(await wss).off("connection", onConnection);
}
ws.on("message", (data) => {
stream.write(data);
});
ws.on("close", close);
page.on("close", close);
stream.on("close", close);
}
(await wss).on("connection", onConnection);
await lock();
await page.bringToFront();
await assertExtensionLoaded(extension, retryPolicy);
await extension.evaluate(
// @ts-ignore
(settings) => START_RECORDING(settings),
{ ...opts, index, tabId: tab.id }
);
unlock();
return stream;
}
async function assertExtensionLoaded(ext: Page, opt: getStreamOptions["retry"]) {
const wait = (ms: number) => new Promise((res) => setTimeout(res, ms));
for (let currentTick = 0; currentTick < opt.times; currentTick++) {
// @ts-ignore
if (await ext.evaluate(() => typeof START_RECORDING === "function")) return;
await wait(Math.pow(opt.each, currentTick));
}
throw new Error("Could not find START_RECORDING function in the browser context");
}