forked from PearInc/PearPlayer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-filter.js
executable file
·99 lines (80 loc) · 2.52 KB
/
node-filter.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* 过滤掉不能下载的节点
*/
module.exports = NodeFilter;
/*
nodesArray: {uri: string type: string capacity: number}
cb: function
range: {start: number end: number}
*/
var debug = require('debug')('pear:node-filter');
function NodeFilter(nodesArray, cb, range) {
// cb(nodesArray, 0);
var doneCount = 0;
var usefulNodes = [];
var fileLength = 0;
if (!range) {
range = {
start: 0,
end: nodesArray.length
}
} else if (range.end > nodesArray.length) {
range.end = nodesArray.length;
}
//计时
var timeStart = performance.now();
for (var i=range.start;i<range.end;++i) {
try {
connectTest(nodesArray[i]);
} catch (e) {
// debug(nodesArray[i].uri + ':' + JSON.stringify(e))
}
}
function connectTest(node) {
var xhr = new XMLHttpRequest;
xhr.timeout = 1500;
xhr.open('head', node.uri);
xhr.onload = function () {
doneCount ++;
node.time = performance.now() - timeStart;
// console.warn(`node.time ${node.time}`);
if (this.status >= 200 && this.status<300) {
usefulNodes.push(node);
fileLength = xhr.getResponseHeader('content-length');
}
chenkDone();
};
xhr.ontimeout = function() {
doneCount ++;
debug(node.uri + ' timeout');
chenkDone();
};
xhr.onerror = function() {
doneCount ++;
chenkDone();
};
xhr.send();
};
function chenkDone() {
// if (doneCount === nodesArray.length) {
// cb(usefulNodes, fileLength);
// }
if (doneCount === (range.end-range.start)) {
//根据capacity对节点进行排序
// usefulNodes.sort(function (a, b) { //按能力值从大到小排序
// return b.capacity - a.capacity;
// });
//根据响应时间排序
usefulNodes.sort(function (a, b) { //按响应时间从小到大排序
return a.time - b.time;
});
for(var i = 0; i < usefulNodes.length; i++) {
debug('node ' + i + ' capacity ' + usefulNodes[i].capacity);
}
debug('length: ' + usefulNodes.filter(function (node) {
return node.capacity >= 5;
}).length);
cb(usefulNodes, fileLength);
}
}
};