1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | import {
|
13 | xhr as videojsXHR,
|
14 | mergeOptions,
|
15 | default as videojs
|
16 | } from 'video.js';
|
17 |
|
18 | const xhrFactory = function() {
|
19 | const xhr = function XhrFunction(options, callback) {
|
20 |
|
21 | options = mergeOptions({
|
22 | timeout: 45e3
|
23 | }, options);
|
24 |
|
25 |
|
26 |
|
27 | let beforeRequest = XhrFunction.beforeRequest || videojs.Hls.xhr.beforeRequest;
|
28 |
|
29 | if (beforeRequest && typeof beforeRequest === 'function') {
|
30 | let newOptions = beforeRequest(options);
|
31 |
|
32 | if (newOptions) {
|
33 | options = newOptions;
|
34 | }
|
35 | }
|
36 |
|
37 | let request = videojsXHR(options, function(error, response) {
|
38 | let reqResponse = request.response;
|
39 |
|
40 | if (!error && reqResponse) {
|
41 | request.responseTime = Date.now();
|
42 | request.roundTripTime = request.responseTime - request.requestTime;
|
43 | request.bytesReceived = reqResponse.byteLength || reqResponse.length;
|
44 | if (!request.bandwidth) {
|
45 | request.bandwidth =
|
46 | Math.floor((request.bytesReceived / request.roundTripTime) * 8 * 1000);
|
47 | }
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | if (error && error.code === 'ETIMEDOUT') {
|
54 | request.timedout = true;
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | if (!error &&
|
61 | !request.aborted &&
|
62 | response.statusCode !== 200 &&
|
63 | response.statusCode !== 206 &&
|
64 | response.statusCode !== 0) {
|
65 | error = new Error('XHR Failed with a response of: ' +
|
66 | (request && (reqResponse || request.responseText)));
|
67 | }
|
68 |
|
69 | callback(error, request);
|
70 | });
|
71 | const originalAbort = request.abort;
|
72 |
|
73 | request.abort = function() {
|
74 | request.aborted = true;
|
75 | return originalAbort.apply(request, arguments);
|
76 | };
|
77 | request.uri = options.uri;
|
78 | request.requestTime = Date.now();
|
79 | return request;
|
80 | };
|
81 |
|
82 | return xhr;
|
83 | };
|
84 |
|
85 | export default xhrFactory;
|