youtube.js 13 KB

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