UNPKG

2.6 kBJavaScriptView Raw
1/**
2 * @file xhr.js
3 */
4
5/**
6 * A wrapper for videojs.xhr that tracks bandwidth.
7 *
8 * @param {Object} options options for the XHR
9 * @param {Function} callback the callback to call when done
10 * @return {Request} the xhr request that is going to be made
11 */
12import {
13 xhr as videojsXHR,
14 mergeOptions,
15 default as videojs
16} from 'video.js';
17
18const xhrFactory = function() {
19 const xhr = function XhrFunction(options, callback) {
20 // Add a default timeout for all hls requests
21 options = mergeOptions({
22 timeout: 45e3
23 }, options);
24
25 // Allow an optional user-specified function to modify the option
26 // object before we construct the xhr request
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 // videojs.xhr now uses a specific code on the error
51 // object to signal that a request has timed out instead
52 // of setting a boolean on the request object
53 if (error && error.code === 'ETIMEDOUT') {
54 request.timedout = true;
55 }
56
57 // videojs.xhr no longer considers status codes outside of 200 and 0
58 // (for file uris) to be errors, but the old XHR did, so emulate that
59 // behavior. Status 206 may be used in response to byterange requests.
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
85export default xhrFactory;