Debian Codegraph @

closure-library/closure/goog/ui/media/youtube.js

raw
1 // Copyright 2009 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview provides a reusable youtube UI component given a youtube data
17 * model.
18 *
19 * goog.ui.media.Youtube is actually a {@link goog.ui.ControlRenderer}, a
20 * stateless class - that could/should be used as a Singleton with the static
21 * method {@code goog.ui.media.Youtube.getInstance} -, that knows how to render
22 * youtube videos. It is designed to be used with a {@link goog.ui.Control},
23 * which will actually control the media renderer and provide the
24 * {@link goog.ui.Component} base. This design guarantees that all different
25 * types of medias will behave alike but will look different.
26 *
27 * goog.ui.media.Youtube expects {@code goog.ui.media.YoutubeModel} on
28 * {@code goog.ui.Control.getModel} as data models, and render a flash object
29 * that will play that URL.
30 *
31 * Example of usage:
32 *
33 * <pre>
34 * var video = goog.ui.media.YoutubeModel.newInstance(
35 * 'https://www.youtube.com/watch?v=ddl5f44spwQ');
36 * goog.ui.media.Youtube.newControl(video).render();
37 * </pre>
38 *
39 * youtube medias currently support the following states:
40 *
41 * <ul>
42 * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available'
43 * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video
44 * <li> {@link !goog.ui.Component.State.SELECTED}: a static thumbnail is shown
45 * <li> {@link goog.ui.Component.State.SELECTED}: video is playing
46 * </ul>
47 *
48 * Which can be accessed by
49 * <pre>
50 * youtube.setEnabled(true);
51 * youtube.setHighlighted(true);
52 * youtube.setSelected(true);
53 * </pre>
54 *
55 * This package also provides a few static auxiliary methods, such as:
56 *
57 * <pre>
58 * var videoId = goog.ui.media.Youtube.parseUrl(
59 * 'https://www.youtube.com/watch?v=ddl5f44spwQ');
60 * </pre>
61 *
62 * Requires flash to actually work.
63 *
64 */
65
66
67 goog.provide('goog.ui.media.Youtube');
68 goog.provide('goog.ui.media.YoutubeModel');
69
70 goog.require('goog.dom.TagName');
71 goog.require('goog.html.TrustedResourceUrl');
72 goog.require('goog.string');
73 goog.require('goog.string.Const');
74 goog.require('goog.ui.Component');
75 goog.require('goog.ui.media.FlashObject');
76 goog.require('goog.ui.media.Media');
77 goog.require('goog.ui.media.MediaModel');
78 goog.require('goog.ui.media.MediaRenderer');
79
80
81
82 /**
83 * Subclasses a goog.ui.media.MediaRenderer to provide a Youtube specific media
84 * renderer.
85 *
86 * This class knows how to parse youtube urls, and render the DOM structure
87 * of youtube video players and previews. This class is meant to be used as a
88 * singleton static stateless class, that takes {@code goog.ui.media.Media}
89 * instances and renders it. It expects {@code goog.ui.media.Media.getModel} to
90 * return a well formed, previously constructed, youtube video id, which is the
91 * data model this renderer will use to construct the DOM structure.
92 * {@see goog.ui.media.Youtube.newControl} for a example of constructing a
93 * control with this renderer.
94 *
95 * goog.ui.media.Youtube currently supports all {@link goog.ui.Component.State}.
96 * It will change its DOM structure between SELECTED and !SELECTED, and rely on
97 * CSS definitions on the others. On !SELECTED, the renderer will render a
98 * youtube static `<img>`, with a thumbnail of the video. On SELECTED, the
99 * renderer will append to the DOM a flash object, that contains the youtube
100 * video.
101 *
102 * This design is patterned after http://go/closure_control_subclassing
103 *
104 * It uses {@link goog.ui.media.FlashObject} to embed the flash object.
105 *
106 * @constructor
107 * @extends {goog.ui.media.MediaRenderer}
108 * @final
109 */
110 goog.ui.media.Youtube = function() {
111 goog.ui.media.MediaRenderer.call(this);
112 };
113 goog.inherits(goog.ui.media.Youtube, goog.ui.media.MediaRenderer);
114 goog.addSingletonGetter(goog.ui.media.Youtube);
115
116
117 /**
118 * A static convenient method to construct a goog.ui.media.Media control out of
119 * a youtube model. It sets it as the data model goog.ui.media.Youtube renderer
120 * uses, sets the states supported by the renderer, and returns a Control that
121 * binds everything together. This is what you should be using for constructing
122 * Youtube videos, except if you need finer control over the configuration.
123 *
124 * @param {goog.ui.media.YoutubeModel} youtubeModel The youtube data model.
125 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
126 * document interaction.
127 * @return {!goog.ui.media.Media} A Control binded to the youtube renderer.
128 */
129 goog.ui.media.Youtube.newControl = function(youtubeModel, opt_domHelper) {
130 var control = new goog.ui.media.Media(
131 youtubeModel, goog.ui.media.Youtube.getInstance(), opt_domHelper);
132 control.setStateInternal(goog.ui.Component.State.ACTIVE);
133 return control;
134 };
135
136
137 /**
138 * Default CSS class to be applied to the root element of components rendered
139 * by this renderer.
140 * @type {string}
141 */
142 goog.ui.media.Youtube.CSS_CLASS = goog.getCssName('goog-ui-media-youtube');
143
144
145 /**
146 * Changes the state of a {@code control}. Currently only changes the DOM
147 * structure when the youtube movie is SELECTED (by default fired by a MOUSEUP
148 * on the thumbnail), which means we have to embed the youtube flash video and
149 * play it.
150 *
151 * @param {goog.ui.Control} c The media control.
152 * @param {goog.ui.Component.State} state The state to be set or cleared.
153 * @param {boolean} enable Whether the state is enabled or disabled.
154 * @override
155 */
156 goog.ui.media.Youtube.prototype.setState = function(c, state, enable) {
157 var control = /** @type {goog.ui.media.Media} */ (c);
158 goog.ui.media.Youtube.superClass_.setState.call(this, control, state, enable);
159
160 // control.createDom has to be called before any state is set.
161 // Use control.setStateInternal if you need to set states
162 if (!control.getElement()) {
163 throw new Error(goog.ui.Component.Error.STATE_INVALID);
164 }
165
166 var domHelper = control.getDomHelper();
167 var dataModel =
168 /** @type {goog.ui.media.YoutubeModel} */ (control.getDataModel());
169
170 if (!!(state & goog.ui.Component.State.SELECTED) && enable) {
171 var flashEls = domHelper.getElementsByTagNameAndClass(
172 goog.dom.TagName.DIV, goog.ui.media.FlashObject.CSS_CLASS,
173 control.getElement());
174 if (flashEls.length > 0) {
175 return;
176 }
177 var youtubeFlash = new goog.ui.media.FlashObject(
178 dataModel.getPlayer().getTrustedResourceUrl(), domHelper);
179 control.addChild(youtubeFlash, true);
180 }
181 };
182
183
184 /**
185 * Returns the CSS class to be applied to the root element of components
186 * rendered using this renderer.
187 *
188 * @return {string} Renderer-specific CSS class.
189 * @override
190 */
191 goog.ui.media.Youtube.prototype.getCssClass = function() {
192 return goog.ui.media.Youtube.CSS_CLASS;
193 };
194
195
196
197 /**
198 * The {@code goog.ui.media.Youtube} media data model. It stores a required
199 * {@code videoId} field, sets the youtube URL, and allows a few optional
200 * parameters.
201 *
202 * @param {string} videoId The youtube video id.
203 * @param {string=} opt_caption An optional caption of the youtube video.
204 * @param {string=} opt_description An optional description of the youtube
205 * video.
206 * @constructor
207 * @extends {goog.ui.media.MediaModel}
208 * @final
209 */
210 goog.ui.media.YoutubeModel = function(videoId, opt_caption, opt_description) {
211 goog.ui.media.MediaModel.call(
212 this, goog.ui.media.YoutubeModel.buildUrl(videoId), opt_caption,
213 opt_description, goog.ui.media.MediaModel.MimeType.FLASH);
214
215 /**
216 * The Youtube video id.
217 * @type {string}
218 * @private
219 */
220 this.videoId_ = videoId;
221
222 this.setThumbnails([new goog.ui.media.MediaModel.Thumbnail(
223 goog.ui.media.YoutubeModel.getThumbnailUrl(videoId))]);
224
225 this.setPlayer(
226 new goog.ui.media.MediaModel.Player(
227 goog.ui.media.YoutubeModel.getFlashUrl(videoId, true)));
228 };
229 goog.inherits(goog.ui.media.YoutubeModel, goog.ui.media.MediaModel);
230
231
232 /**
233 * A youtube regular expression matcher. It matches the VIDEOID of URLs like
234 * https://www.youtube.com/watch?v=VIDEOID. Based on:
235 * googledata/contentonebox/opencob/specs/common/YTPublicExtractorCard.xml
236 * @type {RegExp}
237 * @private
238 * @const
239 */
240 // Be careful about the placement of the dashes in the character classes. Eg,
241 // use "[\\w=-]" instead of "[\\w-=]" if you mean to include the dash as a
242 // character and not create a character range like "[a-f]".
243 goog.ui.media.YoutubeModel.MATCHER_ = new RegExp(
244 // Lead in.
245 'https?://(?:[a-zA-Z]{1,3}\\.)?' +
246 // Watch short URL prefix. This should handle URLs of the form:
247 // https://youtu.be/jqxENMKaeCU?cgiparam=value
248 '(?:(?:youtu\\.be/([\\w-]+)(?:\\?[\\w=&-]+)?)|' +
249 // Watch URL prefix. This should handle new URLs of the form:
250 // https://www.youtube.com/watch#!v=jqxENMKaeCU&feature=related
251 // where the parameters appear after "#!" instead of "?".
252 '(?:youtube\\.com/watch)' +
253 // Get the video id:
254 // The video ID is a parameter v=[videoid] either right after the "?"
255 // or after some other parameters.
256 '(?:\\?(?:[\\w=-]+&(?:amp;)?)*v=([\\w-]+)' +
257 '(?:&(?:amp;)?[\\w=-]+)*)?' +
258 // Get any extra arguments in the URL's hash part.
259 '(?:#[!]?(?:' +
260 // Video ID from the v=[videoid] parameter, optionally surrounded by
261 // other
262 // & separated parameters.
263 '(?:(?:[\\w=-]+&(?:amp;)?)*(?:v=([\\w-]+))' +
264 '(?:&(?:amp;)?[\\w=-]+)*)' +
265 '|' +
266 // Continue supporting "?" for the video ID
267 // and "#" for other hash parameters.
268 '(?:[\\w=&-]+)' +
269 '))?)' +
270 // Should terminate with a non-word, non-dash (-) character.
271 '[^\\w-]?',
272 'i');
273
274
275 /**
276 * A auxiliary static method that parses a youtube URL, extracting the ID of the
277 * video, and builds a YoutubeModel.
278 *
279 * @param {string} youtubeUrl A youtube URL.
280 * @param {string=} opt_caption An optional caption of the youtube video.
281 * @param {string=} opt_description An optional description of the youtube
282 * video.
283 * @return {!goog.ui.media.YoutubeModel} The data model that represents the
284 * youtube URL.
285 * @see goog.ui.media.YoutubeModel.getVideoId()
286 * @throws Error in case the parsing fails.
287 */
288 goog.ui.media.YoutubeModel.newInstance = function(
289 youtubeUrl, opt_caption, opt_description) {
290 var extract = goog.ui.media.YoutubeModel.MATCHER_.exec(youtubeUrl);
291 if (extract) {
292 var videoId = extract[1] || extract[2] || extract[3];
293 return new goog.ui.media.YoutubeModel(
294 videoId, opt_caption, opt_description);
295 }
296
297 throw new Error('failed to parse video id from youtube url: ' + youtubeUrl);
298 };
299
300
301 /**
302 * The opposite of {@code goog.ui.media.Youtube.newInstance}: it takes a videoId
303 * and returns a youtube URL.
304 *
305 * @param {string} videoId The youtube video ID.
306 * @return {string} The youtube URL.
307 */
308 goog.ui.media.YoutubeModel.buildUrl = function(videoId) {
309 return 'https://www.youtube.com/watch?v=' + goog.string.urlEncode(videoId);
310 };
311
312
313 /**
314 * A static auxiliary method that builds a static image URL with a preview of
315 * the youtube video.
316 *
317 * NOTE(user): patterned after Gmail's gadgets/youtube,
318 *
319 * TODO(user): how do I specify the width/height of the resulting image on the
320 * url ? is there an official API for https://ytimg.com ?
321 *
322 * @param {string} youtubeId The youtube video ID.
323 * @return {string} An URL that contains an image with a preview of the youtube
324 * movie.
325 */
326 goog.ui.media.YoutubeModel.getThumbnailUrl = function(youtubeId) {
327 return 'https://i.ytimg.com/vi/' + youtubeId + '/default.jpg';
328 };
329
330
331 /**
332 * A static auxiliary method that builds URL of the flash movie to be embedded,
333 * out of the youtube video id.
334 *
335 * @param {string} videoId The youtube video ID.
336 * @param {boolean=} opt_autoplay Whether the flash movie should start playing
337 * as soon as it is shown, or if it should show a 'play' button.
338 * @return {!goog.html.TrustedResourceUrl} The flash URL to be embedded on the
339 * page.
340 */
341 goog.ui.media.YoutubeModel.getFlashUrl = function(videoId, opt_autoplay) {
342 // YouTube video ids are extracted from youtube URLs, which are user
343 // generated input. The video id is later used to embed a flash object,
344 // which is generated through HTML construction.
345 return goog.html.TrustedResourceUrl.format(
346 goog.string.Const.from(
347 'https://www.youtube.com/v/%{v}&hl=en&fs=1%{autoplay}'),
348 {
349 'v': videoId,
350 'autoplay': opt_autoplay ? goog.string.Const.from('&autoplay=1') : ''
351 });
352 };
353
354
355 /**
356 * Gets the Youtube video id.
357 * @return {string} The Youtube video id.
358 */
359 goog.ui.media.YoutubeModel.prototype.getVideoId = function() {
360 return this.videoId_;
361 };