first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,798 @@
/* The MIT License (MIT)
Copyright (c) 2014-2015 Benoit Tremblay <trembl.ben@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
/*global define, YT*/
(function (root, factory) {
if(typeof exports==='object' && typeof module!=='undefined') {
var videojs = require('video.js');
module.exports = factory(videojs.default || videojs);
} else if(typeof define === 'function' && define.amd) {
define(['media_videojs/video-lazy'], function(videojs){
return (root.Youtube = factory(videojs));
});
} else {
root.Youtube = factory(root.videojs);
}
}(this, function(videojs) {
'use strict';
var _isOnMobile = videojs.browser.IS_IOS || videojs.browser.IS_NATIVE_ANDROID;
var Tech = videojs.getTech('Tech');
class Youtube extends Tech {
constructor(options, ready) {
super(options, ready);
this.setPoster(options.poster);
this.setSrc(this.options_.source, true);
// Set the vjs-youtube class to the player
// Parent is not set yet so we have to wait a tick
this.setTimeout(function() {
if (this.el_) {
this.el_.parentNode.className += ' vjs-youtube';
if (_isOnMobile) {
this.el_.parentNode.className += ' vjs-youtube-mobile';
}
if (Youtube.isApiReady) {
this.initYTPlayer();
} else {
Youtube.apiReadyQueue.push(this);
}
}
}.bind(this));
}
dispose() {
if (this.ytPlayer) {
//Dispose of the YouTube Player
if (this.ytPlayer.stopVideo) {
this.ytPlayer.stopVideo();
}
if (this.ytPlayer.destroy) {
this.ytPlayer.destroy();
}
} else {
//YouTube API hasn't finished loading or the player is already disposed
var index = Youtube.apiReadyQueue.indexOf(this);
if (index !== -1) {
Youtube.apiReadyQueue.splice(index, 1);
}
}
this.ytPlayer = null;
this.el_.parentNode.className = this.el_.parentNode.className
.replace(' vjs-youtube', '')
.replace(' vjs-youtube-mobile', '');
this.el_.parentNode.removeChild(this.el_);
//Needs to be called after the YouTube player is destroyed, otherwise there will be a null reference exception
Tech.prototype.dispose.call(this);
}
createEl() {
var div = document.createElement('div');
div.setAttribute('id', this.options_.techId);
div.setAttribute('style', 'width:100%;height:100%;top:0;left:0;position:absolute');
div.setAttribute('class', 'vjs-tech');
var divWrapper = document.createElement('div');
divWrapper.appendChild(div);
if (!_isOnMobile && !this.options_.ytControls) {
var divBlocker = document.createElement('div');
divBlocker.setAttribute('class', 'vjs-iframe-blocker');
divBlocker.setAttribute('style', 'position:absolute;top:0;left:0;width:100%;height:100%');
// In case the blocker is still there and we want to pause
divBlocker.onclick = function() {
this.pause();
}.bind(this);
divWrapper.appendChild(divBlocker);
}
return divWrapper;
}
initYTPlayer() {
var playerVars = {
controls: 0,
modestbranding: 1,
rel: 0,
showinfo: 0,
loop: this.options_.loop ? 1 : 0
};
// Let the user set any YouTube parameter
// https://developers.google.com/youtube/player_parameters?playerVersion=HTML5#Parameters
// To use YouTube controls, you must use ytControls instead
// To use the loop or autoplay, use the video.js settings
if (typeof this.options_.autohide !== 'undefined') {
playerVars.autohide = this.options_.autohide;
}
if (typeof this.options_['cc_load_policy'] !== 'undefined') {
playerVars['cc_load_policy'] = this.options_['cc_load_policy'];
}
if (typeof this.options_.ytControls !== 'undefined') {
playerVars.controls = this.options_.ytControls;
}
if (typeof this.options_.disablekb !== 'undefined') {
playerVars.disablekb = this.options_.disablekb;
}
if (typeof this.options_.color !== 'undefined') {
playerVars.color = this.options_.color;
}
if (!playerVars.controls) {
// Let video.js handle the fullscreen unless it is the YouTube native controls
playerVars.fs = 0;
} else if (typeof this.options_.fs !== 'undefined') {
playerVars.fs = this.options_.fs;
}
if (this.options_.source.src.indexOf('end=') !== -1) {
var srcEndTime = this.options_.source.src.match(/end=([0-9]*)/);
this.options_.end = parseInt(srcEndTime[1]);
}
if (typeof this.options_.end !== 'undefined') {
playerVars.end = this.options_.end;
}
if (typeof this.options_.hl !== 'undefined') {
playerVars.hl = this.options_.hl;
} else if (typeof this.options_.language !== 'undefined') {
// Set the YouTube player on the same language than video.js
playerVars.hl = this.options_.language.substr(0, 2);
}
if (typeof this.options_['iv_load_policy'] !== 'undefined') {
playerVars['iv_load_policy'] = this.options_['iv_load_policy'];
}
if (typeof this.options_.list !== 'undefined') {
playerVars.list = this.options_.list;
} else if (this.url && typeof this.url.listId !== 'undefined') {
playerVars.list = this.url.listId;
}
if (typeof this.options_.listType !== 'undefined') {
playerVars.listType = this.options_.listType;
}
if (typeof this.options_.modestbranding !== 'undefined') {
playerVars.modestbranding = this.options_.modestbranding;
}
if (typeof this.options_.playlist !== 'undefined') {
playerVars.playlist = this.options_.playlist;
}
if (typeof this.options_.playsinline !== 'undefined') {
playerVars.playsinline = this.options_.playsinline;
}
if (typeof this.options_.rel !== 'undefined') {
playerVars.rel = this.options_.rel;
}
if (typeof this.options_.showinfo !== 'undefined') {
playerVars.showinfo = this.options_.showinfo;
}
if (this.options_.source.src.indexOf('start=') !== -1) {
var srcStartTime = this.options_.source.src.match(/start=([0-9]*)/);
this.options_.start = parseInt(srcStartTime[1]);
}
if (typeof this.options_.start !== 'undefined') {
playerVars.start = this.options_.start;
}
if (typeof this.options_.theme !== 'undefined') {
playerVars.theme = this.options_.theme;
}
// Allow undocumented options to be passed along via customVars
if (typeof this.options_.customVars !== 'undefined') {
var customVars = this.options_.customVars;
Object.keys(customVars).forEach(function(key) {
playerVars[key] = customVars[key];
});
}
this.activeVideoId = this.url ? this.url.videoId : null;
this.activeList = playerVars.list;
var playerConfig = {
videoId: this.activeVideoId,
playerVars: playerVars,
events: {
onReady: this.onPlayerReady.bind(this),
onPlaybackQualityChange: this.onPlayerPlaybackQualityChange.bind(this),
onPlaybackRateChange: this.onPlayerPlaybackRateChange.bind(this),
onStateChange: this.onPlayerStateChange.bind(this),
onVolumeChange: this.onPlayerVolumeChange.bind(this),
onError: this.onPlayerError.bind(this)
}
};
if (typeof this.options_.enablePrivacyEnhancedMode !== 'undefined' && this.options_.enablePrivacyEnhancedMode) {
playerConfig.host = 'https://www.youtube-nocookie.com';
}
this.ytPlayer = new YT.Player(this.options_.techId, playerConfig);
}
onPlayerReady() {
if (this.options_.muted) {
this.ytPlayer.mute();
}
var playbackRates = this.ytPlayer.getAvailablePlaybackRates();
if (playbackRates.length > 1) {
this.featuresPlaybackRate = true;
}
this.playerReady_ = true;
this.triggerReady();
if (this.playOnReady) {
this.play();
} else if (this.cueOnReady) {
this.cueVideoById_(this.url.videoId);
this.activeVideoId = this.url.videoId;
}
}
onPlayerPlaybackQualityChange() {
}
onPlayerPlaybackRateChange() {
this.trigger('ratechange');
}
onPlayerStateChange(e) {
var state = e.data;
if (state === this.lastState || this.errorNumber) {
return;
}
this.lastState = state;
switch (state) {
case -1:
this.trigger('loadstart');
this.trigger('loadedmetadata');
this.trigger('durationchange');
this.trigger('ratechange');
break;
case YT.PlayerState.ENDED:
this.trigger('ended');
break;
case YT.PlayerState.PLAYING:
this.trigger('timeupdate');
this.trigger('durationchange');
this.trigger('playing');
this.trigger('play');
if (this.isSeeking) {
this.onSeeked();
}
break;
case YT.PlayerState.PAUSED:
this.trigger('canplay');
if (this.isSeeking) {
this.onSeeked();
} else {
this.trigger('pause');
}
break;
case YT.PlayerState.BUFFERING:
this.player_.trigger('timeupdate');
this.player_.trigger('waiting');
break;
}
}
onPlayerVolumeChange() {
this.trigger('volumechange');
}
onPlayerError(e) {
this.errorNumber = e.data;
this.trigger('pause');
this.trigger('error');
}
error() {
var code = 1000 + this.errorNumber; // as smaller codes are reserved
switch (this.errorNumber) {
case 5:
return { code: code, message: 'Error while trying to play the video' };
case 2:
case 100:
return { code: code, message: 'Unable to find the video' };
case 101:
case 150:
return {
code: code,
message: 'Playback on other Websites has been disabled by the video owner.'
};
}
return { code: code, message: 'YouTube unknown error (' + this.errorNumber + ')' };
}
loadVideoById_(id) {
var options = {
videoId: id
};
if (this.options_.start) {
options.startSeconds = this.options_.start;
}
if (this.options_.end) {
options.endSeconds = this.options_.end;
}
this.ytPlayer.loadVideoById(options);
}
cueVideoById_(id) {
var options = {
videoId: id
};
if (this.options_.start) {
options.startSeconds = this.options_.start;
}
if (this.options_.end) {
options.endSeconds = this.options_.end;
}
this.ytPlayer.cueVideoById(options);
}
src(src) {
if (src) {
this.setSrc({ src: src });
}
return this.source;
}
poster() {
// You can't start programmaticlly a video with a mobile
// through the iframe so we hide the poster and the play button (with CSS)
if (_isOnMobile) {
return null;
}
return this.poster_;
}
setPoster(poster) {
this.poster_ = poster;
}
setSrc(source) {
if (!source || !source.src) {
return;
}
delete this.errorNumber;
this.source = source;
this.url = Youtube.parseUrl(source.src);
if (!this.options_.poster) {
if (this.url.videoId) {
// Set the low resolution first
this.poster_ = 'https://img.youtube.com/vi/' + this.url.videoId + '/0.jpg';
this.trigger('posterchange');
// Check if their is a high res
this.checkHighResPoster();
}
}
if (this.options_.autoplay && !_isOnMobile) {
if (this.isReady_) {
this.play();
} else {
this.playOnReady = true;
}
} else if (this.activeVideoId !== this.url.videoId) {
if (this.isReady_) {
this.cueVideoById_(this.url.videoId);
this.activeVideoId = this.url.videoId;
} else {
this.cueOnReady = true;
}
}
}
autoplay() {
return this.options_.autoplay;
}
setAutoplay(val) {
this.options_.autoplay = val;
}
loop() {
return this.options_.loop;
}
setLoop(val) {
this.options_.loop = val;
}
play() {
if (!this.url || !this.url.videoId) {
return;
}
this.wasPausedBeforeSeek = false;
if (this.isReady_) {
if (this.url.listId) {
if (this.activeList === this.url.listId) {
this.ytPlayer.playVideo();
} else {
this.ytPlayer.loadPlaylist(this.url.listId);
this.activeList = this.url.listId;
}
}
if (this.activeVideoId === this.url.videoId) {
this.ytPlayer.playVideo();
} else {
this.loadVideoById_(this.url.videoId);
this.activeVideoId = this.url.videoId;
}
} else {
this.trigger('waiting');
this.playOnReady = true;
}
}
pause() {
if (this.ytPlayer) {
this.ytPlayer.pauseVideo();
}
}
paused() {
return (this.ytPlayer) ?
(this.lastState !== YT.PlayerState.PLAYING && this.lastState !== YT.PlayerState.BUFFERING)
: true;
}
currentTime() {
return this.ytPlayer ? this.ytPlayer.getCurrentTime() : 0;
}
setCurrentTime(seconds) {
if (this.lastState === YT.PlayerState.PAUSED) {
this.timeBeforeSeek = this.currentTime();
}
if (!this.isSeeking) {
this.wasPausedBeforeSeek = this.paused();
}
this.ytPlayer.seekTo(seconds, true);
this.trigger('timeupdate');
this.trigger('seeking');
this.isSeeking = true;
// A seek event during pause does not return an event to trigger a seeked event,
// so run an interval timer to look for the currentTime to change
if (this.lastState === YT.PlayerState.PAUSED && this.timeBeforeSeek !== seconds) {
clearInterval(this.checkSeekedInPauseInterval);
this.checkSeekedInPauseInterval = setInterval(function() {
if (this.lastState !== YT.PlayerState.PAUSED || !this.isSeeking) {
// If something changed while we were waiting for the currentTime to change,
// clear the interval timer
clearInterval(this.checkSeekedInPauseInterval);
} else if (this.currentTime() !== this.timeBeforeSeek) {
this.trigger('timeupdate');
this.onSeeked();
}
}.bind(this), 250);
}
}
seeking() {
return this.isSeeking;
}
seekable() {
if(!this.ytPlayer) {
return videojs.createTimeRange();
}
return videojs.createTimeRange(0, this.ytPlayer.getDuration());
}
onSeeked() {
clearInterval(this.checkSeekedInPauseInterval);
this.isSeeking = false;
if (this.wasPausedBeforeSeek) {
this.pause();
}
this.trigger('seeked');
}
playbackRate() {
return this.ytPlayer ? this.ytPlayer.getPlaybackRate() : 1;
}
setPlaybackRate(suggestedRate) {
if (!this.ytPlayer) {
return;
}
this.ytPlayer.setPlaybackRate(suggestedRate);
}
duration() {
return this.ytPlayer ? this.ytPlayer.getDuration() : 0;
}
currentSrc() {
return this.source && this.source.src;
}
ended() {
return this.ytPlayer ? (this.lastState === YT.PlayerState.ENDED) : false;
}
volume() {
return this.ytPlayer ? this.ytPlayer.getVolume() / 100.0 : 1;
}
setVolume(percentAsDecimal) {
if (!this.ytPlayer) {
return;
}
this.ytPlayer.setVolume(percentAsDecimal * 100.0);
}
muted() {
return this.ytPlayer ? this.ytPlayer.isMuted() : false;
}
setMuted(mute) {
if (!this.ytPlayer) {
return;
}
else{
this.muted(true);
}
if (mute) {
this.ytPlayer.mute();
} else {
this.ytPlayer.unMute();
}
this.setTimeout( function(){
this.trigger('volumechange');
}, 50);
}
buffered() {
if(!this.ytPlayer || !this.ytPlayer.getVideoLoadedFraction) {
return videojs.createTimeRange();
}
var bufferedEnd = this.ytPlayer.getVideoLoadedFraction() * this.ytPlayer.getDuration();
return videojs.createTimeRange(0, bufferedEnd);
}
// TODO: Can we really do something with this on YouTUbe?
preload() {}
load() {}
reset() {}
networkState() {
if (!this.ytPlayer) {
return 0; //NETWORK_EMPTY
}
switch (this.ytPlayer.getPlayerState()) {
case -1: //unstarted
return 0; //NETWORK_EMPTY
case 3: //buffering
return 2; //NETWORK_LOADING
default:
return 1; //NETWORK_IDLE
}
}
readyState() {
if (!this.ytPlayer) {
return 0; //HAVE_NOTHING
}
switch (this.ytPlayer.getPlayerState()) {
case -1: //unstarted
return 0; //HAVE_NOTHING
case 5: //video cued
return 1; //HAVE_METADATA
case 3: //buffering
return 2; //HAVE_CURRENT_DATA
default:
return 4; //HAVE_ENOUGH_DATA
}
}
supportsFullScreen() {
return document.fullscreenEnabled ||
document.webkitFullscreenEnabled ||
document.mozFullScreenEnabled ||
document.msFullscreenEnabled;
}
// Tries to get the highest resolution thumbnail available for the video
checkHighResPoster(){
var uri = 'https://img.youtube.com/vi/' + this.url.videoId + '/maxresdefault.jpg';
try {
var image = new Image();
image.onload = function(){
// Onload may still be called if YouTube returns the 120x90 error thumbnail
if('naturalHeight' in image){
if (image.naturalHeight <= 90 || image.naturalWidth <= 120) {
return;
}
} else if(image.height <= 90 || image.width <= 120) {
return;
}
this.poster_ = uri;
this.trigger('posterchange');
}.bind(this);
image.onerror = function(){};
image.src = uri;
}
catch(e){}
}
}
Youtube.isSupported = function() {
return true;
};
Youtube.canPlaySource = function(e) {
return Youtube.canPlayType(e.type);
};
Youtube.canPlayType = function(e) {
return (e === 'video/youtube');
};
Youtube.parseUrl = function(url) {
var result = {
videoId: null
};
var regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regex);
if (match && match[2].length === 11) {
result.videoId = match[2];
}
var regPlaylist = /[?&]list=([^#\&\?]+)/;
match = url.match(regPlaylist);
if(match && match[1]) {
result.listId = match[1];
}
return result;
};
function apiLoaded() {
YT.ready(function() {
Youtube.isApiReady = true;
for (var i = 0; i < Youtube.apiReadyQueue.length; ++i) {
Youtube.apiReadyQueue[i].initYTPlayer();
}
});
}
function loadScript(src, callback) {
var loaded = false;
var tag = document.createElement('script');
var firstScriptTag = document.getElementsByTagName('script')[0];
if (!firstScriptTag) {
// when loaded in jest without jsdom setup it doesn't get any element.
// In jest it doesn't really make sense to do anything, because no one is watching youtube in jest
return;
}
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
tag.onload = function () {
if (!loaded) {
loaded = true;
callback();
}
};
tag.onreadystatechange = function () {
if (!loaded && (this.readyState === 'complete' || this.readyState === 'loaded')) {
loaded = true;
callback();
}
};
tag.src = src;
}
function injectCss() {
var css = // iframe blocker to catch mouse events
'.vjs-youtube .vjs-iframe-blocker { display: none; }' +
'.vjs-youtube.vjs-user-inactive .vjs-iframe-blocker { display: block; }' +
'.vjs-youtube .vjs-poster { background-size: cover; }' +
'.vjs-youtube-mobile .vjs-big-play-button { display: none; }';
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
Youtube.apiReadyQueue = [];
if (typeof document !== 'undefined'){
loadScript('https://www.youtube.com/iframe_api', apiLoaded);
injectCss();
}
// Older versions of VJS5 doesn't have the registerTech function
if (typeof videojs.registerTech !== 'undefined') {
videojs.registerTech('Youtube', Youtube);
} else {
videojs.registerComponent('Youtube', Youtube);
}
}));
+154
View File
@@ -0,0 +1,154 @@
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Video JS loader.
*
* This takes care of applying the filter on content which was dynamically loaded.
*
* @module media_videojs/loader
* @copyright 2016 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
import Ajax from 'core/ajax';
import Config from 'core/config';
import {eventTypes} from 'core_filters/events';
import LocalStorage from 'core/localstorage';
import Notification from 'core/notification';
import jQuery from 'jquery';
/** @var {bool} Whether this is the first load of videojs module */
let firstLoad;
/** @var {string} The language that is used in the player */
let language;
/** @var {object} List of languages and translations for the current page */
let langStringCache;
/**
* Initialisei teh videojs Loader.
*
* Adds the listener for the event to then notify video.js.
*
* @method
* @param {string} lang Language to be used in the player
* @listens event:filterContentUpdated
*/
export const setUp = (lang) => {
language = lang;
firstLoad = true;
// Notify Video.js about the nodes already present on the page.
notifyVideoJS({
detail: {
nodes: document.body,
}
});
// We need to call popover automatically if nodes are added to the page later.
document.addEventListener(eventTypes.filterContentUpdated, notifyVideoJS);
};
/**
* Notify video.js of new nodes.
*
* @param {Event} e The event.
*/
const notifyVideoJS = e => {
const nodes = jQuery(e.detail.nodes);
const selector = '.mediaplugin_videojs';
const langStrings = getLanguageJson();
// Find the descendants matching the expected parent of the audio and video
// tags. Then also addBack the nodes matching the same selector. Finally,
// we find the audio and video tags contained in those parents. Kind thanks
// to jQuery for the simplicity.
nodes.find(selector)
.addBack(selector)
.find('audio, video').each((index, element) => {
const id = jQuery(element).attr('id');
const config = jQuery(element).data('setup-lazy');
const modulePromises = [import('media_videojs/video-lazy')];
if (config.techOrder && config.techOrder.indexOf('youtube') !== -1) {
// Add YouTube to the list of modules we require.
modulePromises.push(import('media_videojs/Youtube-lazy'));
}
if (config.techOrder && config.techOrder.indexOf('OgvJS') !== -1) {
config.ogvjs = {
worker: true,
wasm: true,
base: Config.wwwroot + '/media/player/videojs/ogvloader.php/' + Config.jsrev + '/'
};
// Add Ogv.JS to the list of modules we require.
modulePromises.push(import('media_videojs/videojs-ogvjs-lazy'));
}
Promise.all([langStrings, ...modulePromises])
.then(([langJson, videojs]) => {
if (firstLoad) {
videojs.addLanguage(language, langJson);
firstLoad = false;
}
videojs(id, config);
return;
})
.catch(Notification.exception);
});
};
/**
* Returns the json object of the language strings to be used in the player.
*
* @returns {Promise}
*/
const getLanguageJson = () => {
if (langStringCache) {
return Promise.resolve(langStringCache);
}
const cacheKey = `media_videojs/${language}`;
const rawCacheContent = LocalStorage.get(cacheKey);
if (rawCacheContent) {
const cacheContent = JSON.parse(rawCacheContent);
langStringCache = cacheContent;
return Promise.resolve(langStringCache);
}
const request = {
methodname: 'media_videojs_get_language',
args: {
lang: language,
},
};
return Ajax.call([request])[0]
.then(langStringData => {
LocalStorage.set(cacheKey, langStringData);
return langStringData;
})
.then(result => JSON.parse(result))
.then(langStrings => {
langStringCache = langStrings;
return langStrings;
});
};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,763 @@
/**
* videojs-ogvjs
* @version 1.0.0
* @copyright 2023 Huong Nguyen <huongnv13@gmail.com>
* @license MIT
*/
define(['media_videojs/video-lazy', './local/ogv/ogv'], (function (videojs, ogv) { 'use strict';
// We can access public classes either as ogv.OGVPlayer or just OGVPlayer.
// But ogv.OGVPlayer will make the lint tools happier.
const OGVCompat = ogv.OGVCompat;
const OGVLoader = ogv.OGVLoader;
const OGVPlayer = ogv.OGVPlayer;
const Tech = videojs.getComponent('Tech');
const androidOS = 'Android';
const iPhoneOS = 'iPhoneOS';
const iPadOS = 'iPadOS';
const otherOS = 'Other';
/**
* Object.defineProperty but "lazy", which means that the value is only set after
* it retrieved the first time, rather than being set right away.
*
* @param {Object} obj the object to set the property on.
* @param {string} key the key for the property to set.
* @param {Function} getValue the function used to get the value when it is needed.
* @param {boolean} setter whether a setter should be allowed or not.
*/
const defineLazyProperty = (obj, key, getValue, setter = true) => {
const set = (value) => {
Object.defineProperty(obj, key, {value, enumerable: true, writable: true});
};
const options = {
configurable: true,
enumerable: true,
get() {
const value = getValue();
set(value);
return value;
}
};
if (setter) {
options.set = set;
}
return Object.defineProperty(obj, key, options);
};
/**
* Get the device's OS.
*
* @return {string} Device's OS.
*/
const getDeviceOS = () => {
/* global navigator */
const ua = navigator.userAgent;
if (/android/i.test(ua)) {
return androidOS;
} else if (/iPad|iPhone|iPod/.test(ua)) {
return iPhoneOS;
} else if ((navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) {
return iPadOS;
}
return otherOS;
};
/**
* OgvJS Media Controller - Wrapper for ogv.js Media API
*
* @mixes Tech~SourceHandlerAdditions
* @extends Tech
*/
class OgvJS extends Tech {
/**
* Create an instance of this Tech.
*
* @param {Object} [options] The key/value store of player options.
* @param {Component~ReadyCallback} ready Callback function to call when the `OgvJS` Tech is ready.
*/
constructor(options, ready) {
super(options, ready);
this.el_.src = options.source.src;
OgvJS.setIfAvailable(this.el_, 'autoplay', options.autoplay);
OgvJS.setIfAvailable(this.el_, 'loop', options.loop);
OgvJS.setIfAvailable(this.el_, 'poster', options.poster);
OgvJS.setIfAvailable(this.el_, 'preload', options.preload);
this.on('loadedmetadata', () => {
if (getDeviceOS() === iPhoneOS) {
// iPhoneOS add some inline styles to the canvas, we need to remove it.
const canvas = this.el_.getElementsByTagName('canvas')[0];
canvas.style.removeProperty('width');
canvas.style.removeProperty('margin');
}
});
this.triggerReady();
}
/**
* Create the 'OgvJS' Tech's DOM element.
*
* @return {Element} The element that gets created.
*/
createEl() {
const options = this.options_;
if (options.base) {
OGVLoader.base = options.base;
} else {
throw new Error('Please specify the base for the ogv.js library');
}
const el = new OGVPlayer(options);
el.className += ' vjs-tech';
options.tag = el;
return el;
}
/**
* Start playback
*
* @method play
*/
play() {
this.el_.play();
}
/**
* Get the current playback speed.
*
* @return {number}
* @method playbackRate
*/
playbackRate() {
return this.el_.playbackRate || 1;
}
/**
* Set the playback speed.
*
* @param {number} val Speed for the player to play.
* @method setPlaybackRate
*/
setPlaybackRate(val) {
if (this.el_.hasOwnProperty('playbackRate')) {
this.el_.playbackRate = val;
}
}
/**
* Returns a TimeRanges object that represents the ranges of the media resource that the user agent has played.
*
* @return {TimeRangeObject} the range of points on the media timeline that has been reached through normal playback
*/
played() {
return this.el_.played;
}
/**
* Pause playback
*
* @method pause
*/
pause() {
this.el_.pause();
}
/**
* Is the player paused or not.
*
* @return {boolean}
* @method paused
*/
paused() {
return this.el_.paused;
}
/**
* Get current playing time.
*
* @return {number}
* @method currentTime
*/
currentTime() {
return this.el_.currentTime;
}
/**
* Set current playing time.
*
* @param {number} seconds Current time of audio/video.
* @method setCurrentTime
*/
setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
videojs.log(e, 'Media is not ready. (Video.JS)');
}
}
/**
* Get media's duration.
*
* @return {number}
* @method duration
*/
duration() {
if (this.el_.duration && this.el_.duration !== Infinity) {
return this.el_.duration;
}
return 0;
}
/**
* Get a TimeRange object that represents the intersection
* of the time ranges for which the user agent has all
* relevant media.
*
* @return {TimeRangeObject}
* @method buffered
*/
buffered() {
return this.el_.buffered;
}
/**
* Get current volume level.
*
* @return {number}
* @method volume
*/
volume() {
return this.el_.hasOwnProperty('volume') ? this.el_.volume : 1;
}
/**
* Set current playing volume level.
*
* @param {number} percentAsDecimal Volume percent as a decimal.
* @method setVolume
*/
setVolume(percentAsDecimal) {
// Apple does not allow iOS and iPadOS devices to set the volume on UI.
if (getDeviceOS() !== iPhoneOS && getDeviceOS() !== iPadOS && this.el_.hasOwnProperty('volume')) {
this.el_.volume = percentAsDecimal;
}
}
/**
* Is the player muted or not.
*
* @return {boolean}
* @method muted
*/
muted() {
return this.el_.muted;
}
/**
* Mute the player.
*
* @param {boolean} muted True to mute the player.
*/
setMuted(muted) {
this.el_.muted = !!muted;
}
/**
* Is the player muted by default or not.
*
* @return {boolean}
* @method defaultMuted
*/
defaultMuted() {
return this.el_.defaultMuted || false;
}
/**
* Get the player width.
*
* @return {number}
* @method width
*/
width() {
return this.el_.offsetWidth;
}
/**
* Get the player height.
*
* @return {number}
* @method height
*/
height() {
return this.el_.offsetHeight;
}
/**
* Get the video width.
*
* @return {number}
* @method videoWidth
*/
videoWidth() {
return this.el_.videoWidth;
}
/**
* Get the video height.
*
* @return {number}
* @method videoHeight
*/
videoHeight() {
return this.el_.videoHeight;
}
/**
* Get/set media source.
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
src(src) {
if (typeof src === 'undefined') {
return this.el_.src;
}
this.el_.src = src;
}
/**
* Load the media into the player.
*
* @method load
*/
load() {
this.el_.load();
}
/**
* Get current media source.
*
* @return {Object}
* @method currentSrc
*/
currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
}
return this.el_.currentSrc;
}
/**
* Get media poster URL.
*
* @return {string}
* @method poster
*/
poster() {
return this.el_.poster;
}
/**
* Set media poster URL.
*
* @param {string} url the poster image's url.
* @method
*/
setPoster(url) {
this.el_.poster = url;
}
/**
* Is the media preloaded or not.
*
* @return {string}
* @method preload
*/
preload() {
return this.el_.preload || 'none';
}
/**
* Set the media preload method.
*
* @param {string} val Value for preload attribute.
* @method setPreload
*/
setPreload(val) {
if (this.el_.hasOwnProperty('preload')) {
this.el_.preload = val;
}
}
/**
* Is the media auto-played or not.
*
* @return {boolean}
* @method autoplay
*/
autoplay() {
return this.el_.autoplay || false;
}
/**
* Set media autoplay method.
*
* @param {boolean} val Value for autoplay attribute.
* @method setAutoplay
*/
setAutoplay(val) {
if (this.el_.hasOwnProperty('autoplay')) {
this.el_.autoplay = !!val;
}
}
/**
* Does the media has controls or not.
*
* @return {boolean}
* @method controls
*/
controls() {
return this.el_.controls || false;
}
/**
* Set the media controls method.
*
* @param {boolean} val Value for controls attribute.
* @method setControls
*/
setControls(val) {
if (this.el_.hasOwnProperty('controls')) {
this.el_.controls = !!val;
}
}
/**
* Is the media looped or not.
*
* @return {boolean}
* @method loop
*/
loop() {
return this.el_.loop || false;
}
/**
* Set the media loop method.
*
* @param {boolean} val Value for loop attribute.
* @method setLoop
*/
setLoop(val) {
if (this.el_.hasOwnProperty('loop')) {
this.el_.loop = !!val;
}
}
/**
* Get a TimeRanges object that represents the
* ranges of the media resource to which it is possible
* for the user agent to seek.
*
* @return {TimeRangeObject}
* @method seekable
*/
seekable() {
return this.el_.seekable;
}
/**
* Is player in the "seeking" state or not.
*
* @return {boolean}
* @method seeking
*/
seeking() {
return this.el_.seeking;
}
/**
* Is the media ended or not.
*
* @return {boolean}
* @method ended
*/
ended() {
return this.el_.ended;
}
/**
* Get the current state of network activity
* NETWORK_EMPTY (numeric value 0)
* NETWORK_IDLE (numeric value 1)
* NETWORK_LOADING (numeric value 2)
* NETWORK_NO_SOURCE (numeric value 3)
*
* @return {number}
* @method networkState
*/
networkState() {
return this.el_.networkState;
}
/**
* Get the current state of the player.
* HAVE_NOTHING (numeric value 0)
* HAVE_METADATA (numeric value 1)
* HAVE_CURRENT_DATA (numeric value 2)
* HAVE_FUTURE_DATA (numeric value 3)
* HAVE_ENOUGH_DATA (numeric value 4)
*
* @return {number}
* @method readyState
*/
readyState() {
return this.el_.readyState;
}
/**
* Does the player support native fullscreen mode or not. (Mobile devices)
*
* @return {boolean}
*/
supportsFullScreen() {
// iOS devices have some problem with HTML5 fullscreen api so we need to fallback to fullWindow mode.
return false;
}
/**
* Get media player error.
*
* @return {string}
* @method error
*/
error() {
return this.el_.error;
}
}
/**
* List of available events of the media player.
*
* @private
* @type {Array}
*/
OgvJS.Events = [
'loadstart',
'suspend',
'abort',
'error',
'emptied',
'stalled',
'loadedmetadata',
'loadeddata',
'canplay',
'canplaythrough',
'playing',
'waiting',
'seeking',
'seeked',
'ended',
'durationchange',
'timeupdate',
'progress',
'play',
'pause',
'ratechange',
'resize',
'volumechange'
];
/**
* Set the value for the player is it has that property.
*
* @param {Element} el
* @param {string} name
* @param value
*/
OgvJS.setIfAvailable = (el, name, value) => {
if (el.hasOwnProperty(name)) {
el[name] = value;
}
};
/**
* Check if browser/device is supported by Ogv.JS.
*
* @return {boolean}
*/
OgvJS.isSupported = () => {
return OGVCompat.supported('OGVPlayer');
};
/**
* Check if the tech can support the given type.
*
* @param {string} type The mimetype to check
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
OgvJS.canPlayType = (type) => {
return (type.indexOf('/ogg') !== -1 || type.indexOf('/webm')) ? 'maybe' : '';
};
/**
* Check if the tech can support the given source
*
* @param srcObj The source object
* @return {string} The options passed to the tech
*/
OgvJS.canPlaySource = (srcObj) => {
return OgvJS.canPlayType(srcObj.type);
};
/**
* Check if the volume can be changed in this browser/device.
* Volume cannot be changed in a lot of mobile devices.
* Specifically, it can't be changed on iOS and iPadOS.
*
* @return {boolean} True if volume can be controlled.
*/
OgvJS.canControlVolume = () => {
if (getDeviceOS() === iPhoneOS || getDeviceOS() === iPadOS) {
return false;
}
const p = new OGVPlayer();
return p.hasOwnProperty('volume');
};
/**
* Check if the volume can be muted in this browser/device.
*
* @return {boolean} True if volume can be muted.
*/
OgvJS.canMuteVolume = () => {
return true;
};
/**
* Check if the playback rate can be changed in this browser/device.
*
* @return {boolean} True if playback rate can be controlled.
*/
OgvJS.canControlPlaybackRate = () => {
return true;
};
/**
* Check to see if native 'TextTracks' are supported by this browser/device.
*
* @return {boolean} True if native 'TextTracks' are supported.
*/
OgvJS.supportsNativeTextTracks = () => {
return false;
};
/**
* Check if the fullscreen resize is supported by this browser/device.
*
* @return {boolean} True if the fullscreen resize is supported.
*/
OgvJS.supportsFullscreenResize = () => {
return true;
};
/**
* Check if the progress events is supported by this browser/device.
*
* @return {boolean} True if the progress events is supported.
*/
OgvJS.supportsProgressEvents = () => {
return true;
};
/**
* Check if the time update events is supported by this browser/device.
*
* @return {boolean} True if the time update events is supported.
*/
OgvJS.supportsTimeupdateEvents = () => {
return true;
};
/**
* Boolean indicating whether the 'OgvJS' tech supports volume control.
*
* @type {boolean}
* @default {@link OgvJS.canControlVolume}
*/
/**
* Boolean indicating whether the 'OgvJS' tech supports muting volume.
*
* @type {boolean}
* @default {@link OgvJS.canMuteVolume}
*/
/**
* Boolean indicating whether the 'OgvJS' tech supports changing the speed at which the media plays.
* Examples:
* - Set player to play 2x (twice) as fast.
* - Set player to play 0.5x (half) as fast.
*
* @type {boolean}
* @default {@link OgvJS.canControlPlaybackRate}
*/
/**
* Boolean indicating whether the 'OgvJS' tech currently supports native 'TextTracks'.
*
* @type {boolean}
* @default {@link OgvJS.supportsNativeTextTracks}
*/
/**
* Boolean indicating whether the 'OgvJS' tech currently supports fullscreen resize.
*
* @type {boolean}
* @default {@link OgvJS.supportsFullscreenResize}
*/
/**
* Boolean indicating whether the 'OgvJS' tech currently supports progress events.
*
* @type {boolean}
* @default {@link OgvJS.supportsProgressEvents}
*/
/**
* Boolean indicating whether the 'OgvJS' tech currently supports time update events.
*
* @type {boolean}
* @default {@link OgvJS.supportsTimeupdateEvents}
*/
[
['featuresVolumeControl', 'canControlVolume'],
['featuresMuteControl', 'canMuteVolume'],
['featuresPlaybackRate', 'canControlPlaybackRate'],
['featuresNativeTextTracks', 'supportsNativeTextTracks'],
['featuresFullscreenResize', 'supportsFullscreenResize'],
['featuresProgressEvents', 'supportsProgressEvents'],
['featuresTimeupdateEvents', 'supportsTimeupdateEvents']
].forEach(([key, fn]) => {
defineLazyProperty(OgvJS.prototype, key, () => OgvJS[fn](), true);
});
Tech.registerTech('OgvJS', OgvJS);
return OgvJS;
}));