forked from branchard/fast-speedtest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApi.js
216 lines (192 loc) · 6.12 KB
/
Api.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const https = require('https');
const http = require('http');
const HttpsProxyAgent = require('https-proxy-agent');
const url = require('url');
const Timer = require('./Timer');
const ApiError = require('./ApiError');
const DEFAULT_SPEEDTEST_TIMEOUT = 5000; // ms
const DEFAULT_URL_COUNT = 5;
const DEFAULT_BUFFER_SIZE = 8;
const MAX_CHECK_INTERVAL = 200; // ms
class Api {
/**
* Create an Api object
*
* @param {object} options {token<string>, [verbose<boolean>, timeout<number>,
* https<boolean>, urlCount<number>, bufferSize<number>, unit<function>]}
*/
constructor(options) {
if (!options) {
throw new Error('You must define options in Api constructor');
}
if (!options.token) {
throw new Error('You must define app token');
}
if (options.unit && typeof options.unit !== 'function') {
throw new Error('Invalid unit');
}
if (options.proxy) {
this.proxy = new HttpsProxyAgent(options.proxy);
}
this.token = options.token;
this.verbose = options.verbose || false;
this.timeout = options.timeout || DEFAULT_SPEEDTEST_TIMEOUT;
this.https = options.https == null ? true : Boolean(options.https);
this.urlCount = options.urlCount || DEFAULT_URL_COUNT;
this.bufferSize = options.bufferSize || DEFAULT_BUFFER_SIZE;
this.unit = options.unit || Api.UNITS.Bps;
}
/**
* Compute average from array of number
*
* @static
* @param {Array} arr array of number or null
* @return {number} The average
*/
static average(arr) {
// remove nulls from list
const arrWithoutNulls = arr.filter(e => e);
if (arrWithoutNulls.length === 0) {
return 0;
}
return arrWithoutNulls.reduce((a, b) => a + b) / arrWithoutNulls.length;
}
/**
* Get data from the specified URL
*
* @async
* @param {string} options The http/s get options to download from
* @return {Promise} The request and response from the URL
*/
async get(options) {
return new Promise((resolve, reject) => {
const request = (this.https ? https : http).get(options, (response) => {
if (response.headers['content-type'].includes('json')) {
response.setEncoding('utf8');
let rawData = '';
response.on('data', (chunk) => {
rawData += chunk;
});
response.on('end', () => {
const parsedData = JSON.parse(rawData);
response.data = parsedData;
resolve({
response,
request,
});
});
} else {
resolve({
response,
request,
});
}
}).on('error', (e) => {
reject(e);
});
});
}
/**
* Get videos to download url from Fast api
*
* @async
* @return {Array<string>} List of videos url
*/
async getTargets() {
try {
const targets = [];
while (targets.length < this.urlCount) {
const target = `http${this.https ? 's' : ''}://api.fast.com/netflix/speedtest?https=${this.https ? 'true' : 'false'}&token=${this.token}&urlCount=${this.urlCount - targets.length}`;
const options = url.parse(target);
if (this.proxy) options.agent = this.proxy;
/* eslint-disable no-await-in-loop */
const { response } = await this.get(options);
/* eslint-enable no-await-in-loop */
if (response.statusCode !== 200) {
if (response.statusCode === 403) {
throw new ApiError({ code: ApiError.CODES.BAD_TOKEN });
}
if (response.statusCode === 407) {
throw new ApiError({ code: ApiError.CODES.PROXY_NOT_AUTHENTICATED });
}
console.log(response.statusCode);
throw new ApiError({ code: ApiError.CODES.UNKNOWN });
}
targets.push(...response.data);
}
return targets.map(target => target.url);
} catch (e) {
if (e.code === 'ENOTFOUND') {
if (this.https) {
throw new ApiError({ code: ApiError.CODES.UNREACHABLE_HTTPS_API });
} else {
throw new ApiError({ code: ApiError.CODES.UNREACHABLE_HTTP_API });
}
} else {
throw e;
}
}
}
/**
* Resolves when timeout or when the first video finished downloading
*
* @returns {Promise<number>} Speed in selected unit (Default: Bps)
*/
async getSpeed() {
let targets = null;
try {
targets = await this.getTargets();
} catch (e) {
throw e;
}
let bytes = 0;
const requestList = [];
const timer = new Timer(this.timeout, () => {
requestList.forEach(r => r.abort());
});
targets.forEach(async (target) => {
const {response, request} = await this.get(target);
requestList.push(request);
response.on('data', (data) => {
bytes += data.length;
});
response.on('end', () => {
// when first video is downloaded
timer.stop(); // stop timer and execute timer callback
});
});
return new Promise((resolve) => {
let i = 0;
const recents = new Array(this.bufferSize).fill(null); // list of most recent speeds
const interval = Math.min(
this.timeout / this.bufferSize,
MAX_CHECK_INTERVAL,
); // ms
const refreshIntervalId = setInterval(() => {
i = (i + 1) % recents.length; // loop through recents
recents[i] = bytes / (interval / 1000); // add most recent bytes/second
if (this.verbose) {
console.log(`Current speed: ${this.unit(this.constructor.average(recents))} ${this.unit.name}`);
}
bytes = 0;// reset bytes count
}, interval);
timer.addCallback(() => {
clearInterval(refreshIntervalId);
resolve(this.unit(this.constructor.average(recents)));
});
timer.start();
});
}
}
Api.UNITS = {
// rawSpeed is Bps
Bps: rawSpeed => rawSpeed,
KBps: rawSpeed => rawSpeed / 1000,
MBps: rawSpeed => rawSpeed / 1000000,
GBps: rawSpeed => rawSpeed / 1000000000,
bps: rawSpeed => rawSpeed * 8,
Kbps: rawSpeed => (rawSpeed * 8) / 1000,
Mbps: rawSpeed => (rawSpeed * 8) / 1000000,
Gbps: rawSpeed => (rawSpeed * 8) / 1000000000,
};
module.exports = Api;