Skip to content

Commit

Permalink
refactor(api/internal/permissions.js): handle 'microphone' and 'camer…
Browse files Browse the repository at this point in the history
…a' permissions
  • Loading branch information
jwerle committed Jul 24, 2024
1 parent c3c726b commit f5b9e1a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions api/internal/permissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,20 @@ export async function query (descriptor, options) {
)
}

if (name === 'camera' || name === 'microphone') {
if (!globalThis.navigator.mediaDevices) {
if (globalThis.isServiceWorkerScope) {
throw new TypeError('MediaDevices are not supported in ServiceWorkerGlobalScope.')
} else if (globalThis.isSharedWorkerScope) {
throw new TypeError('MediaDevices are not supported in SharedWorkerGlobalScope.')
} else if (globalThis.isWorkerScope) {
throw new TypeError('MediaDevices are not supported in WorkerGlobalScope.')
} else {
throw new TypeError('MediaDevices are not supported.')
}
}
}

if (!isAndroid && !isApple) {
if (isLinux) {
if (name === 'notifications' || name === 'push') {
Expand Down Expand Up @@ -303,6 +317,39 @@ export async function request (descriptor, options) {
)
}

if (name === 'camera' || name === 'microphone') {
// will throw if `MediaDevices` are not supported
const status = await query({ name }, options)

if (status.state === 'granted') {
return new PermissionStatus(name, 'granted', options)
}

const constraints = { video: false, audio: false }
if (name === 'camera') {
constraints.video = true
delete constraints.audio
} else if (name === 'microphone') {
constraints.audio = true
delete constraints.video
}

try {
const stream = await globalThis.navigator.mediaDevices.getUserMedia(constraints)
const tracks = await stream.getTracks()
for (const track of tracks) {
await track.stop()
}
return new PermissionStatus(name, 'granted', options)
} catch (err) {
if (err.name === 'NotAllowedError') {
return new PermissionStatus(name, 'denied', options)
} else {
throw err
}
}
}

if (isLinux) {
if (name === 'notifications' || name === 'push') {
const currentState = Notification.permission
Expand Down

0 comments on commit f5b9e1a

Please sign in to comment.