-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
77 lines (58 loc) · 1.82 KB
/
index.js
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
let _id = null
const promises = []
let connection
function resolvePromises(value) {
_id = value
promises.forEach(({ resolve }) => resolve(_id))
promises.length = 0
connection.removeEventListener('icecandidate', onIceCandidate)
}
function rejectPromises() {
promises.forEach(({ reject }) =>
reject('This browser is not supported, so biri cannot provide a unique, static ID for this machine.')
)
promises.length = 0
}
function onIceCandidate({ candidate }) {
if (connection.iceGatheringState == 'complete' && _id == null) {
connection = null
return rejectPromises()
}
if(!candidate) return
// For Chrome
if (candidate.foundation) {
return resolvePromises(candidate.foundation)
}
// For Safari
if (candidate.candidate) {
const matches = /^candidate:(\d+)\s/.exec(candidate.candidate)
if (!matches || matches[1].length < 2) return
return resolvePromises(matches[1])
}
}
async function startConnection() {
if (connection) return
connection = new RTCPeerConnection()
// Required for Safari, causes an error on some other browsers.
try {
const stream = document.createElement('canvas').captureStream()
stream.getTracks().forEach((track) => connection.addTrack(track))
} catch (e) {}
connection.addEventListener('icecandidate', onIceCandidate);
const offer = await connection.createOffer({
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
})
connection.setLocalDescription(offer)
}
async function biri() {
if (typeof RTCPeerConnection == 'undefined')
throw new Error(`This browser doesn't support WebRTC, so biri cannot provide a unique, static ID for this machine.`)
if (_id) return _id
const promise = new Promise((resolve, reject) => {
startConnection()
promises.push({ resolve, reject })
})
return promise
}
module.exports = biri