-
Notifications
You must be signed in to change notification settings - Fork 10
/
cleanup.js
68 lines (55 loc) · 1.45 KB
/
cleanup.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
/* jshint node: true */
'use strict';
var debug = require('cog/logger')('rtc/cleanup');
var CANNOT_CLOSE_STATES = [
'closed'
];
var EVENTS_DECOUPLE_BC = [
'addstream',
'datachannel',
'icecandidate',
'negotiationneeded',
'removestream',
'signalingstatechange'
];
var EVENTS_DECOUPLE_AC = [
'iceconnectionstatechange'
];
/**
### rtc-tools/cleanup
```
cleanup(pc)
```
The `cleanup` function is used to ensure that a peer connection is properly
closed and ready to be cleaned up by the browser.
**/
module.exports = function(pc) {
if (!pc) return;
// see if we can close the connection
var currentState = pc.iceConnectionState;
var currentSignaling = pc.signalingState;
var canClose = CANNOT_CLOSE_STATES.indexOf(currentState) < 0 && CANNOT_CLOSE_STATES.indexOf(currentSignaling) < 0;
function decouple(events) {
events.forEach(function(evtName) {
if (pc['on' + evtName]) {
pc['on' + evtName] = null;
}
});
}
// decouple "before close" events
decouple(EVENTS_DECOUPLE_BC);
if (canClose) {
debug('attempting connection close, current state: '+ pc.iceConnectionState);
try {
pc.close();
} catch (e) {
console.warn('Could not close connection', e);
}
}
// remove the event listeners
// after a short delay giving the connection time to trigger
// close and iceconnectionstatechange events
setTimeout(function() {
decouple(EVENTS_DECOUPLE_AC);
}, 100);
};