forked from rtc-io/rtc-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.js
61 lines (49 loc) · 1.25 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
/* 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) {
// see if we can close the connection
var currentState = pc.iceConnectionState;
var canClose = CANNOT_CLOSE_STATES.indexOf(currentState) < 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);
pc.close();
}
// 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);
};