react-player
Version:
A React component for playing a variety of URLs, including file paths, YouTube, Facebook, Twitch, SoundCloud, Streamable, Vimeo, Wistia and DailyMotion
577 lines (471 loc) • 22 kB
JavaScript
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _utils = require("../utils");
var _patterns = require("../patterns");
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var HAS_NAVIGATOR = typeof navigator !== 'undefined';
var IS_IPAD_PRO = HAS_NAVIGATOR && navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
var IS_IOS = HAS_NAVIGATOR && (/iPad|iPhone|iPod/.test(navigator.userAgent) || IS_IPAD_PRO) && !window.MSStream;
var IS_SAFARI = HAS_NAVIGATOR && /^((?!chrome|android).)*safari/i.test(navigator.userAgent) && !window.MSStream;
var HLS_SDK_URL = 'https://cdn.jsdelivr.net/npm/hls.js@VERSION/dist/hls.min.js';
var HLS_GLOBAL = 'Hls';
var DASH_SDK_URL = 'https://cdnjs.cloudflare.com/ajax/libs/dashjs/VERSION/dash.all.min.js';
var DASH_GLOBAL = 'dashjs';
var FLV_SDK_URL = 'https://cdn.jsdelivr.net/npm/flv.js@VERSION/dist/flv.min.js';
var FLV_GLOBAL = 'flvjs';
var MATCH_DROPBOX_URL = /www\.dropbox\.com\/.+/;
var MATCH_CLOUDFLARE_STREAM = /https:\/\/watch\.cloudflarestream\.com\/([a-z0-9]+)/;
var REPLACE_CLOUDFLARE_STREAM = 'https://videodelivery.net/{id}/manifest/video.m3u8';
var FilePlayer = /*#__PURE__*/function (_Component) {
_inherits(FilePlayer, _Component);
var _super = _createSuper(FilePlayer);
function FilePlayer() {
var _this;
_classCallCheck(this, FilePlayer);
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(_args));
_defineProperty(_assertThisInitialized(_this), "onReady", function () {
var _this$props;
return (_this$props = _this.props).onReady.apply(_this$props, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onPlay", function () {
var _this$props2;
return (_this$props2 = _this.props).onPlay.apply(_this$props2, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onBuffer", function () {
var _this$props3;
return (_this$props3 = _this.props).onBuffer.apply(_this$props3, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onBufferEnd", function () {
var _this$props4;
return (_this$props4 = _this.props).onBufferEnd.apply(_this$props4, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onPause", function () {
var _this$props5;
return (_this$props5 = _this.props).onPause.apply(_this$props5, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onEnded", function () {
var _this$props6;
return (_this$props6 = _this.props).onEnded.apply(_this$props6, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onError", function () {
var _this$props7;
return (_this$props7 = _this.props).onError.apply(_this$props7, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onPlayBackRateChange", function (event) {
return _this.props.onPlaybackRateChange(event.target.playbackRate);
});
_defineProperty(_assertThisInitialized(_this), "onEnablePIP", function () {
var _this$props8;
return (_this$props8 = _this.props).onEnablePIP.apply(_this$props8, arguments);
});
_defineProperty(_assertThisInitialized(_this), "onDisablePIP", function (e) {
var _this$props9 = _this.props,
onDisablePIP = _this$props9.onDisablePIP,
playing = _this$props9.playing;
onDisablePIP(e);
if (playing) {
_this.play();
}
});
_defineProperty(_assertThisInitialized(_this), "onPresentationModeChange", function (e) {
if (_this.player && (0, _utils.supportsWebKitPresentationMode)(_this.player)) {
var webkitPresentationMode = _this.player.webkitPresentationMode;
if (webkitPresentationMode === 'picture-in-picture') {
_this.onEnablePIP(e);
} else if (webkitPresentationMode === 'inline') {
_this.onDisablePIP(e);
}
}
});
_defineProperty(_assertThisInitialized(_this), "onSeek", function (e) {
_this.props.onSeek(e.target.currentTime);
});
_defineProperty(_assertThisInitialized(_this), "mute", function () {
_this.player.muted = true;
});
_defineProperty(_assertThisInitialized(_this), "unmute", function () {
_this.player.muted = false;
});
_defineProperty(_assertThisInitialized(_this), "renderSourceElement", function (source, index) {
if (typeof source === 'string') {
return /*#__PURE__*/_react["default"].createElement("source", {
key: index,
src: source
});
}
return /*#__PURE__*/_react["default"].createElement("source", _extends({
key: index
}, source));
});
_defineProperty(_assertThisInitialized(_this), "renderTrack", function (track, index) {
return /*#__PURE__*/_react["default"].createElement("track", _extends({
key: index
}, track));
});
_defineProperty(_assertThisInitialized(_this), "ref", function (player) {
if (_this.player) {
// Store previous player to be used by removeListeners()
_this.prevPlayer = _this.player;
}
_this.player = player;
});
return _this;
}
_createClass(FilePlayer, [{
key: "componentDidMount",
value: function componentDidMount() {
this.props.onMount && this.props.onMount(this);
this.addListeners(this.player);
var src = this.getSource(this.props.url); // Ensure src is set in strict mode
if (src) {
this.player.src = src;
}
if (IS_IOS || this.props.config.forceDisableHls) {
this.player.load();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.shouldUseAudio(this.props) !== this.shouldUseAudio(prevProps)) {
this.removeListeners(this.prevPlayer, prevProps.url);
this.addListeners(this.player);
}
if (this.props.url !== prevProps.url && !(0, _utils.isMediaStream)(this.props.url) && !(this.props.url instanceof Array) // Avoid infinite loop
) {
this.player.srcObject = null;
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.player.removeAttribute('src');
this.removeListeners(this.player);
if (this.hls) {
this.hls.destroy();
}
}
}, {
key: "addListeners",
value: function addListeners(player) {
var _this$props10 = this.props,
url = _this$props10.url,
playsinline = _this$props10.playsinline;
player.addEventListener('play', this.onPlay);
player.addEventListener('waiting', this.onBuffer);
player.addEventListener('playing', this.onBufferEnd);
player.addEventListener('pause', this.onPause);
player.addEventListener('seeked', this.onSeek);
player.addEventListener('ended', this.onEnded);
player.addEventListener('error', this.onError);
player.addEventListener('ratechange', this.onPlayBackRateChange);
player.addEventListener('enterpictureinpicture', this.onEnablePIP);
player.addEventListener('leavepictureinpicture', this.onDisablePIP);
player.addEventListener('webkitpresentationmodechanged', this.onPresentationModeChange);
if (!this.shouldUseHLS(url)) {
// onReady is handled by hls.js
player.addEventListener('canplay', this.onReady);
}
if (playsinline) {
player.setAttribute('playsinline', '');
player.setAttribute('webkit-playsinline', '');
player.setAttribute('x5-playsinline', '');
}
}
}, {
key: "removeListeners",
value: function removeListeners(player, url) {
player.removeEventListener('canplay', this.onReady);
player.removeEventListener('play', this.onPlay);
player.removeEventListener('waiting', this.onBuffer);
player.removeEventListener('playing', this.onBufferEnd);
player.removeEventListener('pause', this.onPause);
player.removeEventListener('seeked', this.onSeek);
player.removeEventListener('ended', this.onEnded);
player.removeEventListener('error', this.onError);
player.removeEventListener('ratechange', this.onPlayBackRateChange);
player.removeEventListener('enterpictureinpicture', this.onEnablePIP);
player.removeEventListener('leavepictureinpicture', this.onDisablePIP);
player.removeEventListener('webkitpresentationmodechanged', this.onPresentationModeChange);
if (!this.shouldUseHLS(url)) {
// onReady is handled by hls.js
player.removeEventListener('canplay', this.onReady);
}
} // Proxy methods to prevent listener leaks
}, {
key: "shouldUseAudio",
value: function shouldUseAudio(props) {
if (props.config.forceVideo) {
return false;
}
if (props.config.attributes.poster) {
return false; // Use <video> so that poster is shown
}
return _patterns.AUDIO_EXTENSIONS.test(props.url) || props.config.forceAudio;
}
}, {
key: "shouldUseHLS",
value: function shouldUseHLS(url) {
if (IS_SAFARI && this.props.config.forceSafariHLS || this.props.config.forceHLS) {
return true;
}
if (IS_IOS || this.props.config.forceDisableHls) {
return false;
}
return _patterns.HLS_EXTENSIONS.test(url) || MATCH_CLOUDFLARE_STREAM.test(url);
}
}, {
key: "shouldUseDASH",
value: function shouldUseDASH(url) {
return _patterns.DASH_EXTENSIONS.test(url) || this.props.config.forceDASH;
}
}, {
key: "shouldUseFLV",
value: function shouldUseFLV(url) {
return _patterns.FLV_EXTENSIONS.test(url) || this.props.config.forceFLV;
}
}, {
key: "load",
value: function load(url) {
var _this2 = this;
var _this$props$config = this.props.config,
hlsVersion = _this$props$config.hlsVersion,
hlsOptions = _this$props$config.hlsOptions,
dashVersion = _this$props$config.dashVersion,
flvVersion = _this$props$config.flvVersion;
if (this.hls) {
this.hls.destroy();
}
if (this.dash) {
this.dash.reset();
}
if (this.shouldUseHLS(url)) {
(0, _utils.getSDK)(HLS_SDK_URL.replace('VERSION', hlsVersion), HLS_GLOBAL).then(function (Hls) {
_this2.hls = new Hls(hlsOptions);
_this2.hls.on(Hls.Events.MANIFEST_PARSED, function () {
_this2.props.onReady();
});
_this2.hls.on(Hls.Events.ERROR, function (e, data) {
_this2.props.onError(e, data, _this2.hls, Hls);
});
if (MATCH_CLOUDFLARE_STREAM.test(url)) {
var id = url.match(MATCH_CLOUDFLARE_STREAM)[1];
_this2.hls.loadSource(REPLACE_CLOUDFLARE_STREAM.replace('{id}', id));
} else {
_this2.hls.loadSource(url);
}
_this2.hls.attachMedia(_this2.player);
_this2.props.onLoaded();
});
}
if (this.shouldUseDASH(url)) {
(0, _utils.getSDK)(DASH_SDK_URL.replace('VERSION', dashVersion), DASH_GLOBAL).then(function (dashjs) {
_this2.dash = dashjs.MediaPlayer().create();
_this2.dash.initialize(_this2.player, url, _this2.props.playing);
_this2.dash.on('error', _this2.props.onError);
if (parseInt(dashVersion) < 3) {
_this2.dash.getDebug().setLogToBrowserConsole(false);
} else {
_this2.dash.updateSettings({
debug: {
logLevel: dashjs.Debug.LOG_LEVEL_NONE
}
});
}
_this2.props.onLoaded();
});
}
if (this.shouldUseFLV(url)) {
(0, _utils.getSDK)(FLV_SDK_URL.replace('VERSION', flvVersion), FLV_GLOBAL).then(function (flvjs) {
_this2.flv = flvjs.createPlayer({
type: 'flv',
url: url
});
_this2.flv.attachMediaElement(_this2.player);
_this2.flv.on(flvjs.Events.ERROR, function (e, data) {
_this2.props.onError(e, data, _this2.flv, flvjs);
});
_this2.flv.load();
_this2.props.onLoaded();
});
}
if (url instanceof Array) {
// When setting new urls (<source>) on an already loaded video,
// HTMLMediaElement.load() is needed to reset the media element
// and restart the media resource. Just replacing children source
// dom nodes is not enough
this.player.load();
} else if ((0, _utils.isMediaStream)(url)) {
try {
this.player.srcObject = url;
} catch (e) {
this.player.src = window.URL.createObjectURL(url);
}
}
}
}, {
key: "play",
value: function play() {
var promise = this.player.play();
if (promise) {
promise["catch"](this.props.onError);
}
}
}, {
key: "pause",
value: function pause() {
this.player.pause();
}
}, {
key: "stop",
value: function stop() {
this.player.removeAttribute('src');
if (this.dash) {
this.dash.reset();
}
}
}, {
key: "seekTo",
value: function seekTo(seconds) {
var keepPlaying = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
this.player.currentTime = seconds;
if (!keepPlaying) {
this.pause();
}
}
}, {
key: "setVolume",
value: function setVolume(fraction) {
this.player.volume = fraction;
}
}, {
key: "enablePIP",
value: function enablePIP() {
if (this.player.requestPictureInPicture && document.pictureInPictureElement !== this.player) {
this.player.requestPictureInPicture();
} else if ((0, _utils.supportsWebKitPresentationMode)(this.player) && this.player.webkitPresentationMode !== 'picture-in-picture') {
this.player.webkitSetPresentationMode('picture-in-picture');
}
}
}, {
key: "disablePIP",
value: function disablePIP() {
if (document.exitPictureInPicture && document.pictureInPictureElement === this.player) {
document.exitPictureInPicture();
} else if ((0, _utils.supportsWebKitPresentationMode)(this.player) && this.player.webkitPresentationMode !== 'inline') {
this.player.webkitSetPresentationMode('inline');
}
}
}, {
key: "setPlaybackRate",
value: function setPlaybackRate(rate) {
try {
this.player.playbackRate = rate;
} catch (error) {
this.props.onError(error);
}
}
}, {
key: "getDuration",
value: function getDuration() {
if (!this.player) return null;
var _this$player = this.player,
duration = _this$player.duration,
seekable = _this$player.seekable; // on iOS, live streams return Infinity for the duration
// so instead we use the end of the seekable timerange
if (duration === Infinity && seekable.length > 0) {
return seekable.end(seekable.length - 1);
}
return duration;
}
}, {
key: "getCurrentTime",
value: function getCurrentTime() {
if (!this.player) return null;
return this.player.currentTime;
}
}, {
key: "getSecondsLoaded",
value: function getSecondsLoaded() {
if (!this.player) return null;
var buffered = this.player.buffered;
if (buffered.length === 0) {
return 0;
}
var end = buffered.end(buffered.length - 1);
var duration = this.getDuration();
if (end > duration) {
return duration;
}
return end;
}
}, {
key: "getSource",
value: function getSource(url) {
var useHLS = this.shouldUseHLS(url);
var useDASH = this.shouldUseDASH(url);
var useFLV = this.shouldUseFLV(url);
if (url instanceof Array || (0, _utils.isMediaStream)(url) || useHLS || useDASH || useFLV) {
return undefined;
}
if (MATCH_DROPBOX_URL.test(url)) {
return url.replace('www.dropbox.com', 'dl.dropboxusercontent.com');
}
return url;
}
}, {
key: "render",
value: function render() {
var _this$props11 = this.props,
url = _this$props11.url,
playing = _this$props11.playing,
loop = _this$props11.loop,
controls = _this$props11.controls,
muted = _this$props11.muted,
config = _this$props11.config,
width = _this$props11.width,
height = _this$props11.height;
var useAudio = this.shouldUseAudio(this.props);
var Element = useAudio ? 'audio' : 'video';
var style = {
width: width === 'auto' ? width : '100%',
height: height === 'auto' ? height : '100%'
};
return /*#__PURE__*/_react["default"].createElement(Element, _extends({
ref: this.ref,
src: this.getSource(url),
style: style,
preload: "auto",
autoPlay: playing || undefined,
controls: controls,
muted: muted,
loop: loop
}, config.attributes), url instanceof Array && url.map(this.renderSourceElement), config.tracks.map(this.renderTrack));
}
}]);
return FilePlayer;
}(_react.Component);
exports["default"] = FilePlayer;
_defineProperty(FilePlayer, "displayName", 'FilePlayer');
_defineProperty(FilePlayer, "canPlay", _patterns.canPlay.file);