-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathyoutube.js
More file actions
343 lines (314 loc) · 11.6 KB
/
youtube.js
File metadata and controls
343 lines (314 loc) · 11.6 KB
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/* global YT */
import $ from 'jquery';
function addYoutubeFunctions(AblePlayer) {
AblePlayer.prototype.initYouTubePlayer = function () {
var thisObj, deferred, promise, youTubeId;
thisObj = this;
deferred = new this.defer();
promise = deferred.promise();
this.youTubePlayerReady = false;
// if a described version is available && user prefers desription
// init player using the described version
youTubeId = (this.youTubeDescId && this.prefDesc) ? this.youTubeDescId : this.youTubeId;
this.activeYouTubeId = youTubeId;
if (AblePlayer.youTubeIframeAPIReady) {
// Script already loaded and ready.
thisObj.finalizeYoutubeInit().then(function() {
deferred.resolve();
});
} else {
// Has another player already started loading the script? If so, abort...
if (!AblePlayer.loadingYouTubeIframeAPI) {
thisObj.getScript('https://www.youtube.com/iframe_api', function () {
console.log( 'YouTube API loaded' );
});
}
// Otherwise, keeping waiting for script load event...
$('body').on('youTubeIframeAPIReady', function () {
thisObj.finalizeYoutubeInit().then(function() {
deferred.resolve();
});
});
}
return promise;
};
AblePlayer.prototype.finalizeYoutubeInit = function () {
// This is called once we're sure the Youtube iFrame API is loaded -- see above
var deferred, promise, thisObj, containerId, ccLoadPolicy, autoplay;
deferred = new this.defer();
promise = deferred.promise();
thisObj = this;
containerId = this.mediaId + '_youtube';
this.$mediaContainer.prepend($('<div>').attr('id', containerId));
// cc_load_policy:
// 0 - show captions depending on user's preference on YouTube
// 1 - show captions by default, even if the user has turned them off
// IMPORTANT: This *must* be set to 1 or some browsers
// fail to load any text tracks (observed in Chrome, not in Firefox)
ccLoadPolicy = 1;
autoplay = (this.okToPlay) ? 1 : 0;
// Documentation https://developers.google.com/youtube/player_parameters
if (typeof this.captionLang == 'undefined') {
// init using the default player lang
this.captionLang = this.lang;
}
this.youTubePlayer = new YT.Player(containerId, {
videoId: this.activeYouTubeId,
host: this.youTubeNoCookie ? 'https://www.youtube-nocookie.com' : 'https://www.youtube.com',
playerVars: {
autoplay: autoplay,
cc_lang_pref: this.captionLang, // set the caption language
cc_load_policy: ccLoadPolicy,
controls: 0, // no controls, using our own
disableKb: 1, // disable keyboard shortcuts, using our own
enablejsapi: 1,
hl: this.lang, // set the UI language to match Able Player
iv_load_policy: 3, // do not show video annotations
origin: window.location.origin,
playsinline: this.playsInline,
rel: 0, // when video ends, show only related videos from same channel (1 shows any)
start: this.startTime
},
events: {
onReady: function () {
thisObj.youTubePlayerReady = true;
if (!thisObj.playerWidth || !thisObj.playerHeight) {
thisObj.getYouTubeDimensions();
}
if (thisObj.playerWidth && thisObj.playerHeight) {
thisObj.youTubePlayer.setSize(thisObj.playerWidth,thisObj.playerHeight);
}
if (thisObj.swappingSrc) {
// swap is now complete
thisObj.swappingSrc = false;
thisObj.restoreFocus();
thisObj.cueingPlaylistItem = false;
if (thisObj.playing || thisObj.okToPlay) {
// resume playing
thisObj.playMedia();
}
}
if (thisObj.userClickedPlaylist) {
thisObj.userClickedPlaylist = false; // reset
}
if (thisObj.recreatingPlayer) {
thisObj.recreatingPlayer = false; // reset
}
deferred.resolve();
},
onError: function (e) {
deferred.reject();
},
onStateChange: function (e) {
thisObj.getPlayerState().then(function(playerState) {
// values of playerState: 'playing','paused','buffering','ended'
if (playerState === 'playing') {
if (thisObj.hasSignLanguage && thisObj.signVideo) {
thisObj.signVideo.play(true);
}
thisObj.playing = true;
thisObj.startedPlaying = true;
thisObj.paused = false;
} else if (playerState == 'ended') {
thisObj.onMediaComplete();
} else {
thisObj.playing = false;
thisObj.paused = true;
}
if (thisObj.stoppingYouTube && playerState === 'paused') {
if (thisObj.hasSignLanguage && thisObj.signVideo) {
thisObj.signVideo.pause(true);
}
if (typeof thisObj.$posterImg !== 'undefined') {
thisObj.$posterImg.show();
}
thisObj.stoppingYouTube = false;
thisObj.seeking = false;
thisObj.playing = false;
thisObj.paused = true;
}
});
// If caption tracks are hosted locally, but are also available on YouTube,
// we need to turn them off on YouTube or there will be redundant captions
// This is the most reliable event on which to unload the caption module
if (thisObj.player === 'youtube' && !thisObj.usingYouTubeCaptions) {
if (thisObj.youTubePlayer.getOptions('captions')) {
thisObj.youTubePlayer.unloadModule('captions');
}
}
},
onApiChange: function() {
// getDuration() can be fetched during API change event.
thisObj.duration = thisObj.youTubePlayer.getDuration();
},
onPlaybackQualityChange: function () {
// do something
},
}
});
if (!this.hasPlaylist) {
// remove the media element, since YouTube replaces that with its own element in an iframe
// this is handled differently for playlists. See buildplayer.js > cuePlaylistItem()
this.$media.remove();
}
return promise;
};
AblePlayer.prototype.getYouTubeDimensions = function () {
// The YouTube iframe API does not have a getSize() of equivalent method
// so, need to get dimensions from YouTube's iframe
var $iframe, width, height;
$iframe = this.$ableWrapper.find('iframe');
if (typeof $iframe !== 'undefined') {
if ($iframe.prop('width')) {
width = $iframe.prop('width');
if ($iframe.prop('height')) {
height = $iframe.prop('height');
this.resizePlayer(width,height);
}
}
}
};
/**
* Get data from the YouTube iFrame API. Pushes data into `this.tracks` and `this.captions`.
* Initiates play to trigger loading the captions module, then stops and collects data.
*
* @returns {Promise} promise
*/
AblePlayer.prototype.getYouTubeCaptionTracks = function () {
var deferred = new this.defer();
var promise = deferred.promise();
var thisObj, ytTracks, i, trackLang, trackLabel, isDefaultTrack, apiTriggered = false;
thisObj = this;
if (!this.youTubePlayer.getOption('captions','tracklist') ) {
// no tracks were found, probably because the captions module hasn't loaded
// play video briefly (required to load the captions module)
// and after the apiChange event is triggered, try again to retrieve tracks
this.youTubePlayer.addEventListener('onApiChange',function() {
apiTriggered = true;
// getDuration() also requires video to play briefly
// so, let's set that while we're here
thisObj.duration = thisObj.youTubePlayer.getDuration();
if (thisObj.loadingYouTubeCaptions) {
// loadingYouTubeCaptions is a stopgap in case onApiChange is called more than once
ytTracks = thisObj.youTubePlayer.getOption('captions','tracklist');
if ( ! thisObj.okToPlay ) {
// Don't stopVideo() - that cancels loading, just pause.
// No need to seekTo(0) - the time passed isn't noticeable to the user
thisObj.youTubePlayer.pauseVideo();
}
if (ytTracks && ytTracks.length) {
// Step through ytTracks and add them to global tracks array
// Note: Unlike YouTube Data API, the IFrame Player API only returns
// tracks that are published, and does NOT include ASR captions
// So, no additional filtering is required
for (i=0; i < ytTracks.length; i++) {
trackLang = ytTracks[i].languageCode;
trackLabel = ytTracks[i].languageName; // displayName and languageName seem to always have the same value
isDefaultTrack = false;
if (typeof thisObj.captionLang !== 'undefined' && (trackLang === thisObj.captionLang) ) {
isDefaultTrack = true;
} else if (typeof thisObj.lang !== 'undefined') {
if (trackLang === thisObj.lang) {
isDefaultTrack = true;
}
}
thisObj.tracks.push({
'kind': 'captions',
'language': trackLang,
'label': trackLabel,
'def': isDefaultTrack
});
thisObj.captions.push({
'language': trackLang,
'label': trackLabel,
'def': isDefaultTrack,
'cues': null
});
}
thisObj.hasCaptions = true;
// setupPopups again with new captions array, replacing original
thisObj.setupPopups('captions');
} else {
// there are no YouTube captions
thisObj.usingYouTubeCaptions = false;
thisObj.hasCaptions = false;
}
thisObj.loadingYouTubeCaptions = false;
if (thisObj.okToPlay) {
thisObj.youTubePlayer.playVideo();
}
}
if (thisObj.captionLangPending) {
// user selected a new caption language prior to playback starting
// set it now
thisObj.youTubePlayer.setOption('captions', 'track', {'languageCode': thisObj.captionLangPending});
thisObj.captionLangPending = null;
}
if (typeof thisObj.prefCaptionsSize !== 'undefined') {
// set the default caption size
// this doesn't work until the captions module is loaded
thisObj.youTubePlayer.setOption('captions','fontSize',thisObj.translatePrefs('size',thisObj.prefCaptionsSize,'youtube'));
}
deferred.resolve();
});
// Trigger the above event listener by briefly playing the video
this.loadingYouTubeCaptions = true;
this.youTubePlayer.playVideo();
// If onApiChange has not been triggered, the captions module is not loading.
setTimeout(() => {
if ( ! apiTriggered ) {
setTimeout(() => {
// If a second passes without loading captions, assume there are none.
thisObj.youTubePlayer.pauseVideo();
deferred.resolve();
}, 500);
}
},500);
}
return promise;
};
AblePlayer.prototype.getYouTubePosterUrl = function (youTubeId, width) {
// return a URL for retrieving a YouTube poster image
// supported values of width: 120, 320, 480, 640, 1280, 1920.
var url = 'https://img.youtube.com/vi/' + youTubeId;
if (width == '120') {
// default (small) thumbnail, 120 x 90
return url + '/default.jpg';
} else if (width == '320') {
// medium quality thumbnail, 320 x 180
return url + '/mqdefault.jpg';
} else if (width == '480') {
// high quality thumbnail, 480 x 360
return url + '/hqdefault.jpg';
} else if (width == '640') {
// standard definition poster image, 640 x 480
return url + '/sddefault.jpg';
} else if (width == '1280') {
// standard definition poster image, 640 x 480
return url + '/hq720.jpg';
} else if ( width == '1920' ) {
// standard definition poster image, 640 x 480
return url + '/maxresdefault.jpg';
}
return false;
};
AblePlayer.prototype.getYouTubeId = function (url) {
// return a YouTube ID, extracted from a full YouTube URL
// Supported URL patterns:
// http|s://youtu.be/xxx
// http|s://www.youtube.com/watch?v=xxx
// http|s://www.youtube.com/embed/xxx
// in all supported patterns, the id is the last 11 characters
var idStartPos, id;
if (url.indexOf('youtu') !== -1) {
// this is a full Youtube URL
url = url.trim();
idStartPos = url.length - 11;
id = url.substring(idStartPos);
return id;
} else {
return url;
}
};
}
export default addYoutubeFunctions;