forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-youtube.js
652 lines (560 loc) · 16.8 KB
/
amp-youtube.js
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import {Deferred} from '#core/data-structures/promise';
import {
dispatchCustomEvent,
getDataParamsFromAttributes,
removeElement,
} from '#core/dom';
import {
fullscreenEnter,
fullscreenExit,
isFullscreenElement,
} from '#core/dom/fullscreen';
import {applyFillContent, isLayoutSizeDefined} from '#core/dom/layout';
import {propagateAttributes} from '#core/dom/propagate-attributes';
import {htmlFor} from '#core/dom/static-template';
import {setStyles} from '#core/dom/style';
import {PauseHelper} from '#core/dom/video/pause-helper';
import {Services} from '#service';
import {installVideoManagerForDoc} from '#service/video-manager-impl';
import {getData, listen} from '#utils/event-helper';
import {dev, userAssert} from '#utils/log';
import {
addUnsafeAllowAutoplay,
createFrameFor,
isJsonOrObj,
mutedOrUnmutedEvent,
objOrParseJson,
originMatches,
redispatch,
} from '../../../src/iframe-video';
import {addParamsToUrl} from '../../../src/url';
import {VideoEvents_Enum} from '../../../src/video-interface';
const TAG = 'amp-youtube';
// Correct PlayerStates taken from
// https://developers.google.com/youtube/iframe_api_reference#Playback_status
/**
* @enum {number}
* @private
*/
const PlayerStates = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
};
/**
* @enum {number}
* @private
*/
const PlayerFlags = {
// Config to tell YouTube to hide annotations by default
HIDE_ANNOTATION: 3,
};
/** @implements {../../../src/video-interface.VideoInterface} */
class AmpYoutube extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?string} */
this.videoid_ = null;
/** @private {?string} */
this.liveChannelid_ = null;
/** @private {?boolean} */
this.muted_ = false;
/** @private {?boolean} */
this.isLoop_ = false;
/** @private {?boolean} */
this.isPlaylist_ = false;
/** @private {?Element} */
this.iframe_ = null;
/** @private {?Object} Info object about video returned by YouTube API*/
this.info_ = null;
/** @private {?string} */
this.videoIframeSrc_ = null;
/** @private {?Promise} */
this.playerReadyPromise_ = null;
/** @private {?Function} */
this.playerReadyResolver_ = null;
/** @private {?Function} */
this.unlistenMessage_ = null;
/** @private {?Function} */
this.unlistenLooping_ = null;
/** @private @const */
this.pauseHelper_ = new PauseHelper(this.element);
}
/**
* @param {boolean=} opt_onLayout
* @override
*/
preconnectCallback(opt_onLayout) {
// NOTE: When preload `as=document` is natively supported in browsers
// we can switch to preloading the full source. For now this doesn't
// work, because we preload with a different type and in that case
// responses are only picked up if they are cacheable.
const preconnect = Services.preconnectFor(this.win);
const ampdoc = this.getAmpDoc();
preconnect.url(ampdoc, this.getVideoIframeSrc_());
// Host that YT uses to serve JS needed by player.
preconnect.url(ampdoc, 'https://s.ytimg.com', opt_onLayout);
// Load high resolution placeholder images for videos in prerender mode.
preconnect.url(ampdoc, 'https://i.ytimg.com', opt_onLayout);
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
renderOutsideViewport() {
// We are conservative about loading YT videos outside the viewport,
// because the player is pretty heavy.
// This will still start loading before they become visible, but it
// won't typically load a large number of embeds.
return 0.75;
}
/** @override */
buildCallback() {
this.videoid_ = this.getVideoId_();
this.liveChannelid_ = this.getLiveChannelId_();
this.assertDatasourceExists_();
const deferred = new Deferred();
this.playerReadyPromise_ = deferred.promise;
this.playerReadyResolver_ = deferred.resolve;
installVideoManagerForDoc(this.element);
}
/**
* @return {string}
* @private
*/
getEmbedUrl_() {
this.assertDatasourceExists_();
const urlSuffix = this.getCredentials_() === 'omit' ? '-nocookie' : '';
const baseUrl = `https://www.youtube${urlSuffix}.com/embed/`;
const descriptor = this.videoid_
? `${encodeURIComponent(this.videoid_ || '')}?`
: `live_stream?channel=${encodeURIComponent(this.liveChannelid_ || '')}&`;
return `${baseUrl}${descriptor}enablejsapi=1&=1`;
}
/**
* @return {string}
* @private
*/
getVideoIframeSrc_() {
if (this.videoIframeSrc_) {
return this.videoIframeSrc_;
}
let src = this.getEmbedUrl_();
const {element} = this;
const params = getDataParamsFromAttributes(element);
if ('autoplay' in params) {
// Autoplay is managed by video manager, do not pass it to YouTube.
delete params['autoplay'];
this.user().error(
'AMP-YOUTUBE',
'Use autoplay attribute instead of data-param-autoplay'
);
}
// Unless inline play policy is set explicitly, enable inline play for iOS
// in all cases similar to Android. Inline play is the desired default for
// video in AMP.
if (!('playsinline' in params)) {
params['playsinline'] = '1';
}
const hasAutoplay = element.hasAttribute('autoplay');
if (hasAutoplay) {
// Unless annotations policy is set explicitly, change the default to
// hide annotations when autoplay is set.
// We do this because we like the first user interaction with an
// autoplaying video to be just unmute tso annotations are not
// interactive during autoplay anyway.
if (!('iv_load_policy' in params)) {
params['iv_load_policy'] = `${PlayerFlags.HIDE_ANNOTATION}`;
}
// Inline play must be set for autoplay regardless of original value.
params['playsinline'] = '1';
}
if ('loop' in params) {
// Loop is managed by the amp-youtube extension, prefer loop param instead
this.user().warn(
'AMP-YOUTUBE',
'Use loop attribute instead of the deprecated data-param-loop'
);
}
// In the case of a playlist, looping is delegated to the Youtube player
// instead of AMP manually looping the video through the Youtube API
this.isLoop_ =
element.hasAttribute('loop') ||
('loop' in params && params['loop'] == '1');
this.isPlaylist_ = 'playlist' in params;
if (this.isLoop_) {
if (this.isPlaylist_) {
// Use native looping for playlists
params['loop'] = '1';
} else if ('loop' in params) {
// Use js-based looping for single videos
delete params['loop'];
}
}
src = addParamsToUrl(src, params);
return (this.videoIframeSrc_ = src);
}
/** @override */
layoutCallback() {
// See https://developers.google.com/youtube/iframe_api_reference
const iframe = createFrameFor(this, this.getVideoIframeSrc_());
iframe.title = this.element.title || 'YouTube video';
// This is temporary until M74 launches.
// TODO(aghassemi, #21247)
addUnsafeAllowAutoplay(iframe);
this.iframe_ = iframe;
// Listening for VideoEvents_Enum.LOAD in AutoFullscreenManager.register may
// introduce race conditions which may break elements e.g. amp-ima-video
Services.videoManagerForDoc(this.element).register(this);
this.unlistenMessage_ = listen(
this.win,
'message',
this.handleYoutubeMessage_.bind(this)
);
if (this.isLoop_ && !this.isPlaylist_) {
this.unlistenLooping_ = listen(
this.element,
VideoEvents_Enum.ENDED,
(unusedEvent) => this.play(false /** unusedIsAutoplay */)
);
}
const loaded = this.loadPromise(this.iframe_)
// Make sure the YT player is ready for this. For some reason YT player
// would send couple of messages but then stop. Waiting for a bit before
// sending the 'listening' event seems to fix that and allow YT Player
// to send messages continuously.
//
// This was removed in #6915 but due to #17979 it has been taken back
// for a workaround.
.then(() => Services.timerFor(this.win).promise(300))
.then(() => {
// Tell YT that we want to receive messages
this.listenToFrame_();
dispatchCustomEvent(this.element, VideoEvents_Enum.LOAD);
});
this.playerReadyResolver_(loaded);
return loaded;
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
}
if (this.unlistenLooping_) {
this.unlistenLooping_();
}
const deferred = new Deferred();
this.playerReadyPromise_ = deferred.promise;
this.playerReadyResolver_ = deferred.resolve;
this.pauseHelper_.updatePlaying(false);
return true; // Call layoutCallback again.
}
/** @override */
pauseCallback() {
if (this.iframe_ && this.iframe_.contentWindow) {
this.pause();
}
}
/** @override */
mutatedAttributesCallback(mutations) {
if (mutations['data-videoid'] == null) {
return;
}
this.videoid_ = this.getVideoId_();
if (!this.iframe_) {
return;
}
this.sendCommand_('loadVideoById', [this.videoid_]);
}
/**
* @return {?string}
* @private
*/
getLiveChannelId_() {
return this.element.getAttribute('data-live-channelid');
}
/**
* @return {?string}
* @private
*/
getVideoId_() {
return this.element.getAttribute('data-videoid');
}
/**
* @return {string}
* @private
*/
getCredentials_() {
return this.element.getAttribute('credentials') || 'include';
}
/**
* @private
*/
assertDatasourceExists_() {
const datasourceExists =
!(this.videoid_ && this.liveChannelid_) &&
(this.videoid_ || this.liveChannelid_);
userAssert(
datasourceExists,
'Exactly one of data-videoid or ' +
'data-live-channelid should be present for <amp-youtube> %s',
this.element
);
}
/**
* Sends a command to the player through postMessage.
* @param {string} command
* @param {Array=} opt_args
* @private
*/
sendCommand_(command, opt_args) {
this.playerReadyPromise_.then(() => {
if (this.iframe_ && this.iframe_.contentWindow) {
const message = JSON.stringify({
'event': 'command',
'func': command,
'args': opt_args || '',
});
this.iframe_.contentWindow./*OK*/ postMessage(message, '*');
}
});
}
/**
* @param {!Event} event
* @private
*/
handleYoutubeMessage_(event) {
if (!originMatches(event, this.iframe_, 'https://www.youtube.com')) {
return;
}
const eventData = getData(event);
if (!isJsonOrObj(eventData)) {
return;
}
const data = objOrParseJson(eventData);
if (data == null) {
return; // We only process valid JSON.
}
const eventType = data['event'];
const info = data['info'] || {};
const {element} = this;
const playerState = info['playerState'];
if (eventType == 'infoDelivery' && playerState != null) {
switch (playerState) {
case PlayerStates.PLAYING:
this.pauseHelper_.updatePlaying(true);
break;
case PlayerStates.PAUSED:
case PlayerStates.ENDED:
this.pauseHelper_.updatePlaying(false);
break;
}
redispatch(element, playerState.toString(), {
[PlayerStates.PLAYING]: VideoEvents_Enum.PLAYING,
[PlayerStates.PAUSED]: VideoEvents_Enum.PAUSE,
// YT does not fire pause and ended together.
[PlayerStates.ENDED]: [VideoEvents_Enum.ENDED, VideoEvents_Enum.PAUSE],
});
return;
}
const muted = info['muted'];
if (eventType == 'infoDelivery' && info && muted != null) {
if (this.muted_ == muted) {
return;
}
this.muted_ = muted;
dispatchCustomEvent(element, mutedOrUnmutedEvent(this.muted_));
return;
}
if (eventType == 'initialDelivery') {
this.info_ = info;
dispatchCustomEvent(element, VideoEvents_Enum.LOADEDMETADATA);
return;
}
if (eventType == 'infoDelivery' && info['currentTime'] !== undefined) {
this.info_.currentTime = info['currentTime'];
return;
}
}
/**
* Sends 'listening' message to the YouTube iframe to listen for events.
* @private
*/
listenToFrame_() {
if (!this.iframe_) {
return;
}
this.iframe_.contentWindow./*OK*/ postMessage(
JSON.stringify({
'event': 'listening',
}),
'*'
);
}
/** @override */
createPlaceholderCallback() {
if (!this.videoid_) {
return null;
}
const {element: el} = this;
const imgPlaceholder = htmlFor(el)`<img placeholder referrerpolicy=origin>`;
const videoid = dev().assertString(this.videoid_);
setStyles(imgPlaceholder, {
// Cover matches YouTube Player styling.
'object-fit': 'cover',
// Hiding the placeholder initially to give the browser time to fix
// the object-fit: cover.
'visibility': 'hidden',
});
propagateAttributes(['aria-label'], this.element, imgPlaceholder);
// TODO(mkhatib): Maybe add srcset to allow the browser to
// load the needed size or even better match YTPlayer logic for loading
// player thumbnails for different screen sizes for a cache win!
imgPlaceholder.src = `https://i.ytimg.com/vi/${encodeURIComponent(
videoid
)}/sddefault.jpg#404_is_fine`;
if (imgPlaceholder.hasAttribute('aria-label')) {
imgPlaceholder.setAttribute(
'alt',
'Loading video - ' + imgPlaceholder.getAttribute('aria-label')
);
} else {
imgPlaceholder.setAttribute('alt', 'Loading video');
}
applyFillContent(imgPlaceholder);
// Because sddefault.jpg isn't available for all videos, we try to load
// it and fallback to hqdefault.jpg.
this.loadPromise(imgPlaceholder)
.then(() => {
// A pretty ugly hack since onerror won't fire on YouTube image 404.
// This might be due to the fact that YouTube returns data to the request
// even when the status is 404. YouTube returns a placeholder image that
// is 120x90.
if (
imgPlaceholder.naturalWidth == 120 &&
imgPlaceholder.naturalHeight == 90
) {
throw new Error('sddefault.jpg is not found');
}
})
.catch(() => {
imgPlaceholder.src = `https://i.ytimg.com/vi/${encodeURIComponent(
videoid
)}/hqdefault.jpg`;
return this.loadPromise(imgPlaceholder);
})
.then(() => {
this.getVsync().mutate(() => {
setStyles(imgPlaceholder, {
'visibility': '',
});
});
});
return imgPlaceholder;
}
// VideoInterface Implementation. See ../src/video-interface.VideoInterface
/** @override */
supportsPlatform() {
return true;
}
/** @override */
isInteractive() {
// YouTube videos are always interactive. There is no YouTube param that
// makes the video non-interactive. Even data-param-control=0 will not
// prevent user from pausing or resuming the video.
return true;
}
/** @override */
play(unusedIsAutoplay) {
this.sendCommand_('playVideo');
}
/** @override */
pause() {
this.sendCommand_('pauseVideo');
}
/** @override */
mute() {
this.sendCommand_('mute');
}
/** @override */
unmute() {
this.sendCommand_('unMute');
}
/** @override */
showControls() {
// Not supported.
}
/** @override */
hideControls() {
// Not supported.
}
/** @override */
fullscreenEnter() {
if (!this.iframe_) {
return;
}
fullscreenEnter(dev().assertElement(this.iframe_));
}
/** @override */
fullscreenExit() {
if (!this.iframe_) {
return;
}
fullscreenExit(dev().assertElement(this.iframe_));
}
/** @override */
isFullscreen() {
if (!this.iframe_) {
return false;
}
return isFullscreenElement(dev().assertElement(this.iframe_));
}
/** @override */
getMetadata() {
// Not implemented
}
/** @override */
preimplementsMediaSessionAPI() {
// Youtube already updates the Media Session so no need for the video
// manager to update it too
return true;
}
/** @override */
preimplementsAutoFullscreen() {
return false;
}
/** @override */
getCurrentTime() {
if (this.info_) {
return this.info_.currentTime;
}
return NaN;
}
/** @override */
getDuration() {
if (this.info_) {
return this.info_.duration;
}
// Not supported.
return NaN;
}
/** @override */
getPlayedRanges() {
// Not supported.
return [];
}
/** @override */
seekTo(unusedTimeSeconds) {
this.user().error(TAG, '`seekTo` not supported.');
}
}
AMP.extension(TAG, '0.1', (AMP) => {
AMP.registerElement(TAG, AmpYoutube);
});