-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpreload.js
More file actions
803 lines (686 loc) · 23.7 KB
/
preload.js
File metadata and controls
803 lines (686 loc) · 23.7 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
var { ipcRenderer, contextBridge } = require('electron');
let cachedEnvironment = null;
const environmentPromise = (async () => {
try {
const env = await ipcRenderer.invoke('ssapp:get-environment');
cachedEnvironment = env || {};
return cachedEnvironment;
} catch (error) {
console.error('[Preload] Failed to retrieve SSAPP environment:', error);
cachedEnvironment = {};
return cachedEnvironment;
}
})();
async function resolveSocialStreamUrl(relativePath, options = {}) {
try {
const result = await ipcRenderer.invoke('socialstream:resolve-file-url', relativePath, options);
if (result && result.success) {
return result;
}
return null;
} catch (error) {
console.error('[Preload] resolveSocialStreamUrl failed:', error);
return null;
}
}
async function readSocialStreamFile(relativePath, options = {}) {
try {
const result = await ipcRenderer.invoke('socialstream:read-file', relativePath, options);
if (result && result.success) {
return result.data;
}
return null;
} catch (error) {
console.error('[Preload] readSocialStreamFile failed:', error);
return null;
}
}
async function readSocialStreamJson(relativePath, options = {}) {
const text = await readSocialStreamFile(relativePath, options);
if (!text) return null;
try {
return JSON.parse(text);
} catch (error) {
console.error('[Preload] Failed to parse Social Stream JSON asset:', error);
return null;
}
}
const ssappFallbackBridge = {
resolveUrl: resolveSocialStreamUrl,
readFile: readSocialStreamFile,
readJson: readSocialStreamJson,
isAvailable: async (relativePath, options = {}) => {
const result = await resolveSocialStreamUrl(relativePath, options);
return !!(result && result.url);
}
};
const ssappEnvironmentBridge = {
get: () => environmentPromise,
getCached: () => cachedEnvironment,
isPackaged: () => cachedEnvironment ? !!cachedEnvironment.isPackaged : undefined,
preferLocalAssets: () => cachedEnvironment ? !!cachedEnvironment.preferLocalAssets : undefined,
hasFallbackBundle: () => cachedEnvironment ? !!cachedEnvironment.hasFallbackBundle : undefined,
refresh: async () => {
try {
const env = await ipcRenderer.invoke('ssapp:get-environment');
cachedEnvironment = env || {};
return cachedEnvironment;
} catch (error) {
console.error('[Preload] Failed to refresh SSAPP environment:', error);
return cachedEnvironment || {};
}
}
};
const WARN_FILTER_PATTERNS = [
/Potential permissions policy violation/i,
/Unrecognized feature/i,
/Electron Security Warning/i
];
const originalConsoleWarn = console.warn.bind(console);
console.warn = (...args) => {
try {
const message = args.map((part) => {
if (typeof part === 'string') return part;
if (part instanceof Error && part.message) return part.message;
return JSON.stringify(part);
}).join(' ');
if (WARN_FILTER_PATTERNS.some((pattern) => pattern.test(message))) {
return;
}
} catch (_) {
// Fall through to original handler on parsing issues
}
return originalConsoleWarn(...args);
};
// Debug flag for troubleshooting
const PRELOAD_DEBUG = false; // Set to true for debugging
// Get the random flag for this session
let INJECTED_SCRIPT_FLAG = null;
(async () => {
INJECTED_SCRIPT_FLAG = await ipcRenderer.invoke('get-injected-script-flag');
if (PRELOAD_DEBUG) {
console.log('[Preload] Got injected script flag:', INJECTED_SCRIPT_FLAG);
}
})();
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
// Generate a unique token for this session
const MESSAGE_AUTH_TOKEN = 'ssn_' + Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
// Security: Only accept messages from our injected scripts with proper authentication
window.addEventListener('message', (event) => {
// The injected scripts run in the same window, so we can't filter by source
// We rely on authentication tokens and message structure validation instead
// Check if the message has our expected structure
const { data } = event;
if (!data || typeof data !== 'object') {
return;
}
// Debug logging
if (PRELOAD_DEBUG && (data._authToken || data.message || data.getSettings)) {
console.log('[Preload] Received postMessage:', {
hasAuthToken: !!data._authToken,
authTokenPrefix: data._authToken ? data._authToken.substring(0, 20) : 'none',
hasMessage: !!data.message,
hasGetSettings: !!data.getSettings,
keys: Object.keys(data)
});
}
// Fast-path: forward lightweight WSS status messages (no token required)
if (data && data.wssStatus) {
try { ipcRenderer.send('postMessage', data); } catch(_) {}
return;
}
// Check for authentication token (for new secure messages)
if (data._authToken === MESSAGE_AUTH_TOKEN) {
// Remove token before forwarding
const messageData = { ...data };
delete messageData._authToken;
// Check if this message needs a response
const needsResponse = messageData._needsResponse;
const messageId = messageData._messageId;
delete messageData._needsResponse;
delete messageData._messageId;
if (needsResponse && messageId) {
// Send with callback expectation
const response = ipcRenderer.sendSync('postMessage', messageData);
// Send response back via postMessage
window.postMessage({
_isResponse: true,
_messageId: messageId,
response: response
}, '*');
} else {
// Send without expecting response
ipcRenderer.send('postMessage', messageData);
}
return;
}
// Support for injected scripts that can't access contextBridge
if (INJECTED_SCRIPT_FLAG && data[INJECTED_SCRIPT_FLAG]) {
// Remove the flag before forwarding
delete data[INJECTED_SCRIPT_FLAG];
// Extract tab ID if provided
const tabID = data.__tabID__;
delete data.__tabID__;
// Re-add tabID if it was present
if (tabID !== undefined && tabID !== null) {
data.__tabID__ = tabID;
}
// Send the message
ipcRenderer.send('postMessage', data);
return;
}
// Legacy support: Only forward messages that have our expected properties
// This prevents arbitrary messages from the page being forwarded
// TODO: Eventually remove this once all scripts are updated to use auth tokens
if (data.wssStatus || data.message || data.delete || data.getSettings || data.getBTTV ||
data.getSEVENTV || data.getFFZ || data.cmd || data.type === 'toBackground') {
ipcRenderer.send('postMessage', data);
}
});
window.addEventListener('error', (event) => {
console.error('Script error:', event.error);
});
/* window.alert = alert = function(title, val){
log("window.alert");
return ipcRenderer.send('alert', {title, val}); // call if needed in the future
}; */
var actualHandler = null;
var doSomethingInWebApp = function(callback){
if (callback){
actualHandler = callback;
}
};
// Create a wrapper that always delegates to the current handler
var doSomethingInWebAppWrapper = function(message, sender, sendResponse) {
if (actualHandler) {
try {
actualHandler(message, sender, sendResponse);
} catch (_) {}
}
};
function configureContextBridge(){
try {
console.log('[Preload] Configuring contextBridge with ninjafy (including OAuth methods)');
const effectiveLocale = process.env.SSAPP_LOCALE_EFFECTIVE || 'en-US';
const acceptLanguageHeader = process.env.SSAPP_ACCEPT_LANGUAGE || 'en-US,en;q=0.9';
const localeSource = process.env.SSAPP_LOCALE_SOURCE || 'system';
// Always expose to main world, regardless of whether it exists in isolated context
contextBridge.exposeInMainWorld('ninjafy', {
// Expose the auth token directly as a property
_authToken: MESSAGE_AUTH_TOKEN,
exposeDoSomethingInWebApp: doSomethingInWebApp,
checkUrlMatching: (url) => {
// checkSupported is not available in preload context
return false;
},
sendMessage: function(ignore=null, data=null, callback=false, tabID=false) {
// Add authentication token to messages
const authenticatedData = { ...data, _authToken: MESSAGE_AUTH_TOKEN };
// Add tabID if provided (maintaining security - only injected scripts have access to valid tabIDs)
if (tabID !== false && tabID !== null && tabID !== undefined) {
authenticatedData.__tabID__ = tabID;
}
if (callback) {
const response = ipcRenderer.sendSync('postMessage', authenticatedData);
callback(response);
} else {
ipcRenderer.send('postMessage', authenticatedData);
}
},
// Expose auth token getter for injected scripts that use window.postMessage directly
getAuthToken: () => MESSAGE_AUTH_TOKEN,
_authToken: MESSAGE_AUTH_TOKEN,
// Expose the injected script flag
getInjectedScriptFlag: () => INJECTED_SCRIPT_FLAG,
closeFileStream: async () => {
await ipcRenderer.invoke('close-file-stream');
},
onCloseFileStream: (callback) => {
ipcRenderer.on('close-file-stream', async () => {
callback();
});
},
showSaveDialog: async (opts) => {
return await ipcRenderer.invoke('show-save-dialog', opts);
},
appendToFile: (filePath, data) => {
ipcRenderer.send('append-to-file', { filePath, data });
},
tts: async (text, settings) => {
return await ipcRenderer.invoke('tts', {text, settings});
},
onSendToTab: (callback) => {
ipcRenderer.on('sendToTab', (event, ...args) => {
callback(args[0]);
});
},
onPostMessage: (callback) => {
ipcRenderer.on('postMessage', (event, ...args) => {
callback(args[0]);
});
},
onWebSocketMessage: (callback) => {
ipcRenderer.on('websocket-message', (event, data) => {
callback(data);
});
},
sendDeviceList: (response) => {
ipcRenderer.send('deviceList', response);
},
'updateVersion' : function (version) { // window.ninjafy.updateVersion(session.version);
console.log("Version: "+version);
},
'updatePPT' : function (PPTHotkey) {},
noCORSFetch: (args) => {},
readStreamChunk: (streamId) => {},
closeStream: (streamId) => {},
startYouTubeOAuth: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth', payload);
},
exchangeYouTubeOAuthCode: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth-exchange', payload);
},
refreshYouTubeOAuthToken: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth-refresh', payload);
},
startTwitchOAuth: async (payload) => {
return await ipcRenderer.invoke('twitch-oauth', payload);
},
startFacebookOAuth: async (payload) => {
return await ipcRenderer.invoke('facebook-oauth', payload);
},
exchangeFacebookOAuthCode: async (payload) => {
return await ipcRenderer.invoke('facebook-oauth-exchange', payload);
},
startKickOAuth: async (payload) => {
return await ipcRenderer.invoke('kick-oauth', payload);
},
startKickWebSocket: async (payload) => {
return await ipcRenderer.invoke('kick-ws-connect', payload);
},
stopKickWebSocket: async (payload) => {
return await ipcRenderer.invoke('kick-ws-disconnect', payload);
},
onKickWsEvent: (() => {
let registered = false;
return (callback) => {
if (registered) return;
registered = true;
ipcRenderer.on('kick-ws-event', (event, data) => {
callback(data);
});
};
})(),
onKickWsStatus: (() => {
let registered = false;
return (callback) => {
if (registered) return;
registered = true;
ipcRenderer.on('kick-ws-status', (event, data) => {
callback(data);
});
};
})(),
startYouTubeLiveChatGrpcStream: async (options) => {
return await ipcRenderer.invoke('youtube-livechat-grpc:start', options);
},
stopYouTubeLiveChatGrpcStream: async (streamId) => {
return await ipcRenderer.invoke('youtube-livechat-grpc:stop', streamId);
},
onYouTubeLiveChatGrpcEvent: (callback) => {
if (typeof callback !== 'function') {
return () => {};
}
const channel = 'youtube-livechat-grpc:event';
const handler = (_event, payload) => {
try {
callback(payload);
} catch (error) {
console.warn('[Preload] YouTube gRPC event handler failed', error);
}
};
ipcRenderer.on(channel, handler);
return () => {
ipcRenderer.removeListener(channel, handler);
};
},
// Performance monitoring
requestPerformanceData: async () => {
return await ipcRenderer.invoke('getPerformanceMetrics');
},
onPerformanceData: (callback) => {
ipcRenderer.on('performance-data', (event, data) => {
callback(data);
});
}
});
contextBridge.exposeInMainWorld('ssappLocale', {
locale: effectiveLocale,
acceptLanguage: acceptLanguageHeader,
source: localeSource,
getLocale: () => effectiveLocale,
getAcceptLanguage: () => acceptLanguageHeader,
getSource: () => localeSource
});
contextBridge.exposeInMainWorld('ssappFallback', ssappFallbackBridge);
contextBridge.exposeInMainWorld('ssappEnvironment', ssappEnvironmentBridge);
} catch(e){
// Silently fail if context isolation is disabled - this is expected
if (!e.message || !e.message.includes('contextBridge API can only be used when contextIsolation is enabled')) {
console.error('[Preload] Error configuring context bridge:', e);
}
throw e; // Re-throw to be caught by outer try-catch
}
}
// Only configure context bridge if context isolation is enabled
// When context isolation is disabled, we can access window directly
try {
// Try to use contextBridge - this will throw if contextIsolation is false
configureContextBridge();
} catch (e) {
if (e.message && e.message.includes('contextBridge API can only be used when contextIsolation is enabled')) {
// Context isolation is disabled - expose ninjafy directly on window
window.ninjafy = {
// Expose the auth token directly as a property
_authToken: MESSAGE_AUTH_TOKEN,
getInjectedScriptFlag: () => INJECTED_SCRIPT_FLAG,
sendMessage: (a, b, c, tabID) => {
const messageData = b || a;
// When tabID is provided, this is a message that should be routed to the background
// via postMessage handler, not directly to a tab
const outgoingData = { ...messageData };
if (tabID !== undefined && tabID !== null && tabID !== false) {
outgoingData.__tabID__ = tabID;
}
// If callback is provided, use synchronous IPC to get response
if (c) {
const response = ipcRenderer.sendSync('postMessage', outgoingData);
c(response);
} else {
// No callback, send asynchronously
ipcRenderer.send('postMessage', outgoingData);
}
},
onWebSocketMessage: (callback) => {
ipcRenderer.on('websocket-message', (event, data) => {
callback(data);
});
},
// Add other necessary methods
exposeDoSomethingInWebApp: (callback) => {
window.doSomethingInWebApp = callback;
},
sendDeviceList: (response) => {
ipcRenderer.send('deviceList', response);
},
updateVersion: function (version) {
console.log("Version: "+version);
},
startYouTubeOAuth: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth', payload);
},
exchangeYouTubeOAuthCode: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth-exchange', payload);
},
refreshYouTubeOAuthToken: async (payload) => {
return await ipcRenderer.invoke('youtube-oauth-refresh', payload);
},
startTwitchOAuth: async (payload) => {
return await ipcRenderer.invoke('twitch-oauth', payload);
},
startFacebookOAuth: async (payload) => {
return await ipcRenderer.invoke('facebook-oauth', payload);
},
exchangeFacebookOAuthCode: async (payload) => {
return await ipcRenderer.invoke('facebook-oauth-exchange', payload);
},
startKickOAuth: async (payload) => {
return await ipcRenderer.invoke('kick-oauth', payload);
},
startKickWebSocket: async (payload) => {
return await ipcRenderer.invoke('kick-ws-connect', payload);
},
stopKickWebSocket: async (payload) => {
return await ipcRenderer.invoke('kick-ws-disconnect', payload);
},
onKickWsEvent: (() => {
let registered = false;
return (callback) => {
if (registered) return;
registered = true;
ipcRenderer.on('kick-ws-event', (event, data) => {
callback(data);
});
};
})(),
onKickWsStatus: (() => {
let registered = false;
return (callback) => {
if (registered) return;
registered = true;
ipcRenderer.on('kick-ws-status', (event, data) => {
callback(data);
});
};
})()
};
window.ssappLocale = {
locale: process.env.SSAPP_LOCALE_EFFECTIVE || 'en-US',
acceptLanguage: process.env.SSAPP_ACCEPT_LANGUAGE || 'en-US,en;q=0.9',
source: process.env.SSAPP_LOCALE_SOURCE || 'system',
getLocale() { return this.locale; },
getAcceptLanguage() { return this.acceptLanguage; },
getSource() { return this.source; }
};
window.ssappFallback = ssappFallbackBridge;
window.ssappEnvironment = ssappEnvironmentBridge;
} else {
console.error('[Preload] Unexpected error configuring context bridge:', e);
}
}
function injectDockBridge() {
try {
const href = window.location && typeof window.location.href === 'string' ? window.location.href : '';
if (!href.includes('/dock.html')) return;
const scriptContent = `
(() => {
const resolveToken = () => {
try {
if (window.ninjafy && typeof window.ninjafy.getAuthToken === 'function') {
return window.ninjafy.getAuthToken();
}
if (window.ninjafy && typeof window.ninjafy._authToken === 'string') {
return window.ninjafy._authToken;
}
} catch (_) {}
return null;
};
const postToElectron = (payload) => {
const token = resolveToken();
const message = { ...payload };
if (token) {
message._authToken = token;
}
try {
window.postMessage(message, '*');
} catch (_) {}
};
const originalSend2Extension = window.send2Extension;
window.send2Extension = function(data, uid = null) {
try {
postToElectron({
overlayNinja: data,
__tabID__: uid,
fromDock: true
});
} catch (_) {}
// Response messages already go through Electron's main-process relay,
// which forwards them to background.html and separately handles any
// TikTok virtual tabs. Calling the original path here would duplicate
// the background.html send.
if (typeof originalSend2Extension === 'function' && !data?.response) {
return originalSend2Extension.apply(this, arguments);
}
};
const originalRespondP2P = window.respondP2P;
window.respondP2P = function(data, tid = false) {
try {
// respondP2P calls send2Extension internally; the send2Extension wrapper will forward to Electron.
} catch (_) {}
if (typeof originalRespondP2P === 'function') {
return originalRespondP2P.apply(this, arguments);
}
};
})();`;
const script = document.createElement('script');
script.textContent = scriptContent;
(document.head || document.documentElement).appendChild(script);
script.remove();
} catch (_) {
// Ignore dock bridge errors
}
}
window.addEventListener('DOMContentLoaded', injectDockBridge);
// Handle sendToTab-request messages that expect a response
ipcRenderer.on('sendToTab-request', (event, data) => {
//console.log("SEND TO TAB REQUEST", data);
const { message, requestId } = data;
// Call the handler and send back the response
doSomethingInWebAppWrapper(message, null, function(response) {
// Send the response back to main process
ipcRenderer.send(`sendToTab-response-${requestId}`, response);
});
});
// Handle regular sendToTab messages (no response expected)
ipcRenderer.on('sendToTab', (event, ...args) => {
doSomethingInWebAppWrapper(args[0], null, function(response){});
});
ipcRenderer.on('postMessage', (event, ...args) => { // GOT MESSAGE FROM MAIN.JS
try {
if ("doSomething" in args[0]){
if (args[0].node){ // run it directly, using NODE mode.
} else { // run it in the page via Electron API
var fauxEvent = {};
fauxEvent.data = {};
fauxEvent.data.doSomething = true;
doSomethingInWebAppWrapper(fauxEvent, null, function(){});
}
return;
}
if ("eval" in args[0]){
if (args[0].node){
eval(args[0].eval);
} else {
var fauxEvent = {};
fauxEvent.data = {};
fauxEvent.data.eval = args[0].eval;
doSomethingInWebAppWrapper(fauxEvent, null, function(){});
}
return;
}
if ("getDeviceList" in args[0]) {
var response = {};
if (typeof enumerateDevices === "function"){
enumerateDevices().then(function(deviceInfos) {
response.deviceInfos = deviceInfos;
response = JSON.parse(JSON.stringify(response));
ipcRenderer.send('deviceList', response);
})
} else {
requestOutputAudioStream().then(function(deviceInfos) {
response.deviceInfos = deviceInfos;
response = JSON.parse(JSON.stringify(response));
ipcRenderer.send('deviceList', response);
})
}
}
} catch(e){
console.error(e);
}
})
function setSink(ele, id){
ele.setSinkId(id).then(() => {
console.log("New Output Device:" + id);
}).catch(error => {
console.error(error);
});
}
var hello = true;
function changeAudioOutputDeviceByIdThirdParty(deviceID){
console.log("Output deviceID: "+deviceID);
document.querySelectorAll("audio, video").forEach(ele=>{
try {
if (ele.manualSink){
setSink(ele,ele.manualSink);
} else {
setSink(ele,deviceID);
}
} catch(e){}
});
document.querySelectorAll('iframe').forEach( item =>{
try{
item.contentWindow.document.body.querySelectorAll("audio, video").forEach(ele=>{
try {
if (ele.manualSink){
setSink(ele,ele.manualSink);
} else {
setSink(ele,deviceID);
}
} catch(e){}
});
} catch(e){}
});
}
function enumerateDevicesThirdParty() {
if (typeof navigator.enumerateDevices === "function") {
return navigator.enumerateDevices();
} else if (typeof navigator.mediaDevices === "object" && typeof navigator.mediaDevices.enumerateDevices === "function") {
return navigator.mediaDevices.enumerateDevices();
} else {
return new Promise((resolve, reject) => {
try {
if (window.MediaStreamTrack == null || window.MediaStreamTrack.getSources == null) {
throw new Error();
}
window.MediaStreamTrack.getSources((devices) => {
resolve(devices
.filter(device => {
return device.kind.toLowerCase() === "video" || device.kind.toLowerCase() === "videoinput";
})
.map(device => {
return {
deviceId: device.deviceId != null ? device.deviceId : ""
, groupId: device.groupId
, kind: "videoinput"
, label: device.label
, toJSON: /* */ function() {
return this;
}
};
}));
});
} catch (e) {}
});
}
}
function requestOutputAudioStream() {
console.log("requestOutputAudioStream");
return navigator.mediaDevices.getUserMedia({audio: true, video: false}).then(function(stream) { // Apple needs thi to happen before I can access EnumerateDevices.
return enumerateDevicesThirdParty().then(function(deviceInfos) {
console.log("enumerateDevicesThirdParty");
stream.getTracks().forEach(function(track) { // We don't want to keep it without audio; so we are going to try to add audio now.
track.stop(); // I need to do this after the enumeration step, else it breaks firefox's labels
});
console.log(deviceInfos);
return deviceInfos;
});
});
}