Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[VBLOCKS-3256] Feat: listen for navigator permissions changes #283

Merged
merged 8 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@
2.11.3 (In Progress)
======================

Bug Fixes
---------

- Fixed an issue where `PreflightTest` throws an error when `RTCIceCandidateStatsReport` is not available. Thanks @phi-line for your [contribution](https://github.com/twilio/twilio-voice.js/pull/280).

Improvements
------------

- The SDK now updates its internal device list when the microphone permission changes.

2.11.2 (June 26, 2024)
======================

Expand Down
34 changes: 34 additions & 0 deletions lib/twilio/audiohelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,21 @@ class AudioHelper extends EventEmitter {
*/
private _mediaDevices: AudioHelper.MediaDevicesLike | null;

/**
* The microphone permission status
*/
private _microphonePermissionStatus: PermissionStatus | null;

/**
* Called with the new input stream when the active input is changed.
*/
private _onActiveInputChanged: (stream: MediaStream | null) => Promise<void>;

/**
* Handler for microphone permission status change
*/
private _onMicrophonePermissionStatusChanged: () => void;

/**
* Internal reference to the processed stream
*/
Expand Down Expand Up @@ -275,6 +285,20 @@ class AudioHelper extends EventEmitter {
if (isEnumerationSupported) {
this._initializeEnumeration();
}

// NOTE (kchoy): Currently microphone permissions are not supported in firefox.
// https://github.com/mozilla/standards-positions/issues/19#issuecomment-370158947
navigator.permissions.query({ name: 'microphone' }).then((microphonePermissionStatus) => {
if (microphonePermissionStatus.state !== 'granted') {
const handleStateChange = () => {
this._updateAvailableDevices();
this._stopMicrophonePermissionListener();
};
microphonePermissionStatus.addEventListener('change', handleStateChange);
this._microphonePermissionStatus = microphonePermissionStatus;
this._onMicrophonePermissionStatusChanged = handleStateChange;
}
}).catch((reason) => this._log.warn(`Warning: unable to listen for microphone permission changes. ${reason}`));
}

/**
Expand All @@ -287,6 +311,7 @@ class AudioHelper extends EventEmitter {
this._destroyProcessedStream();
this._maybeStopPollingVolume();
this.removeAllListeners();
this._stopMicrophonePermissionListener();
this._unbind();
}

Expand Down Expand Up @@ -799,6 +824,15 @@ class AudioHelper extends EventEmitter {
});
}

/**
* Remove event listener for microphone permissions
*/
private _stopMicrophonePermissionListener(): void {
if (this._microphonePermissionStatus?.removeEventListener) {
this._microphonePermissionStatus.removeEventListener('change', this._onMicrophonePermissionStatusChanged);
}
}

/**
* Stop the selected audio stream
*/
Expand Down
69 changes: 62 additions & 7 deletions tests/audiohelper.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const assert = require('assert');
const sinon = require('sinon');
const EventTarget = require('./eventtarget');
const AudioHelper = require('../lib/twilio/audiohelper').default;
const { AudioProcessorEventObserver } = require('../lib/twilio/audioprocessoreventobserver');

Expand All @@ -8,12 +9,14 @@ function getUserMedia() {
}

describe('AudioHelper', () => {
const wait = () => new Promise(res => res());

context('when enumerateDevices is not supported', () => {
const noop = () => {};

let audio;
let oldHTMLAudioElement;
let oldNavigator;
let oldMediaDevices;

beforeEach(() => {
audio = new AudioHelper(noop, noop, {
Expand All @@ -30,16 +33,15 @@ describe('AudioHelper', () => {
oldHTMLAudioElement = typeof HTMLAudioElement !== 'undefined'
? HTMLAudioElement
: undefined;
oldNavigator = typeof navigator !== 'undefined'
? navigator
: undefined;
HTMLAudioElement = undefined;
navigator = { };

oldMediaDevices = navigator.mediaDevices;
navigator.mediaDevices = undefined;
});

after(() => {
HTMLAudioElement = oldHTMLAudioElement;
navigator = oldNavigator;
navigator.mediaDevices = oldMediaDevices;
});

describe('constructor', () => {
Expand Down Expand Up @@ -124,6 +126,60 @@ describe('AudioHelper', () => {
});
});

describe('navigator.permissions', () => {
let oldMicPerm;
let mockMicPerm;
let mockEventTarget;
let enumerateDevices;

beforeEach(() => {
enumerateDevices = sinon.stub().returns(new Promise(res => res([])));
oldMicPerm = navigator.permissions;
mockEventTarget = new EventTarget();
mockMicPerm = {
query: function() {
return Promise.resolve(mockEventTarget);
}
};
navigator.permissions = mockMicPerm;
});

afterEach(() => {
navigator.permissions = oldMicPerm;
});

it('should update list of devices when microphone state is not granted', async () => {
audio = new AudioHelper(onActiveOutputsChanged, onActiveInputChanged, { enumerateDevices });
await wait();
mockEventTarget.dispatchEvent({ type: 'change' });
sinon.assert.calledTwice(enumerateDevices);
});

it('should update list of devices only once', async () => {
audio = new AudioHelper(onActiveOutputsChanged, onActiveInputChanged, { enumerateDevices });
await wait();
mockEventTarget.dispatchEvent({ type: 'change' });
mockEventTarget.dispatchEvent({ type: 'change' });
sinon.assert.calledTwice(enumerateDevices);
});

it('should not update list of devices when microphone state is granted', async () => {
mockEventTarget.state = 'granted';
audio = new AudioHelper(onActiveOutputsChanged, onActiveInputChanged, { enumerateDevices });
await wait();
mockEventTarget.dispatchEvent({ type: 'change' });
sinon.assert.calledOnce(enumerateDevices);
});

it('should remove the onchange handler on destroy', async () => {
audio = new AudioHelper(onActiveOutputsChanged, onActiveInputChanged, { enumerateDevices });
await wait();
audio._destroy();
mockEventTarget.dispatchEvent({ type: 'change' });
sinon.assert.calledOnce(enumerateDevices);
});
});

describe('._destroy', () => {
it('should properly dispose the audio instance', () => {
audio._stopDefaultInputDeviceStream = sinon.stub();
Expand All @@ -137,7 +193,6 @@ describe('AudioHelper', () => {
sinon.assert.calledOnce(audio._destroyProcessedStream);
sinon.assert.calledOnce(audio._maybeStopPollingVolume);
sinon.assert.calledOnce(mediaDevices.removeEventListener);

});
});

Expand Down
7 changes: 7 additions & 0 deletions tests/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as WebSocket from 'ws';

const EventTarget = require('./eventtarget');

const root = global as any;
let handlers = {};

Expand Down Expand Up @@ -73,6 +75,11 @@ root.navigator = {
},
platform: 'platform',
userAgent: 'userAgent',
permissions: {
query: function() {
return Promise.resolve(new EventTarget());
}
}
};

root.RTCPeerConnection = root.window.RTCPeerConnection = function() { };
Expand Down