FYTE /Fast YouTube Embedded/ Player

Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.

当前为 2017-11-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name FYTE /Fast YouTube Embedded/ Player
  3. // @description Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.
  4. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. // @version 2.9.1
  6. // @include *
  7. // @exclude /^https:\/\/www\.youtube\.com\/(?!embed)/
  8. // @exclude https://accounts.google.*/o/oauth2/postmessageRelay*
  9. // @exclude https://clients*.google.*/youtubei/*
  10. // @exclude https://clients*.google.*/static/proxy*
  11. // @author wOxxOm
  12. // @namespace wOxxOm.scripts
  13. // @license MIT License
  14. // @grant GM_getValue
  15. // @grant GM_listValues
  16. // @grant GM_deleteValue
  17. // @grant GM_setValue
  18. // @grant GM_addStyle
  19. // @grant GM_xmlhttpRequest
  20. // @connect www.youtube.com
  21. // @connect youtube.com
  22. // @run-at document-start
  23. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACABAMAAAAxEHz4AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAwUExURUxpcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJuxkb8AAAAPdFJOUwDvH0biMvjOZFW6pxJ6kh7r3iMAAAPDSURBVGje7ZlNaBNBFMeXhNDWpkKgFg9iYlBB6SGwiPQkftaCYATjTaRKiwi1xVaKXpqTpHhosR66p4pQhb209CQGbSweK/TiRYwfFy+NkWBM2pR2nHm73abJzuceRMj/kEzSvl92Z9689+atpjXUUEMN1WgpoRupbH41nTbNUaxzlkIhe0C+M810Ov8zmzL0RGeNeeDThUEkof72N/Fqe/8LJK07sR173yJS0EbEATxFSurZtm9DilqxAV9VAZuWfbPbLBOFqtSBP9f/WxIAV2Bc6H5owiKPG7p+IpFIRG11LsPbEfyVrhvTqeyX1dfmaBiM9gFgjgwrTzJSfncMFq7s3EExJuu5/rHte3hPBvfkff84sbuEBxPkUiLygCC5hDV7CvpUtt81axICZBN9UwHsxYalOMxhIaIC8IVhFlvJtlALIWQl57Um/LquBpjBpkOwin1qADKLB7RD9moqiPz2TcAMqQGa4OI9Av5op/DrMzXAHmz6mw4IxEQA67AW825/bhngAVoBMEHzZD+aFQCsQUCkAAor/M2wCYAVdwCqxJmANgD8cmJjPQDt5wK22AD0nAVoBsAiE1BMcgAbAJikAqoTYP1CA4BEtBgdgC6yARUuAC3QI7sDiLMAxUk2YAwiIwNAn4YAhGU+YKcOqAUMCgJQziugHGMALmNAhANAWxkaoEgABS4ADdMyiyiglPMIcJ0GKQAayDAAGQEAuu8VUB/gJAH1AS4IgLAwAA24AAoygAeuAPFbqHPHoNwc1HuCJCDncRl7NG8At7Ak48qugVEGsOBxO7snB58T0ngASlwWjomFpMegOusxrFOLBCexsFMbvUzxCyVXRqEkBpjlpXdOgcEqFlsEKpRynFviMIus0md+kcUEDAuUeaxCcysjUGgySt1yTKTUZRTbOaFim17unxUr92doBw4f9zTKObGInZl+//NTW592VP3g+Q4Onh6Ovjfgt5vsPoSCJuDuPRz/58CFmhEtKPIEvY8kZAd3VxRxRJJSyIXcUu0/VOz3okITJRC2ex9kGdB5ecBVZLtgCyt70fUB2nGTTjOu/HFZohsXXLoOrbQKfDps1ePtTj9wSter2oGWoBnYRZqB+bQ5OnLaShpnrNAz6N6R7OW1I1HJjnmPVFuit7eDV1jNvuAkpJNqgJ0DQPCHiv3dqmULfJe3P7hrB/oej3T0S/Tme7tf1Xp/MArPB/Ayp82X5OlAaJfI8wHsJ2/zWXg6EGV4XXB5CbuN3mUYxnQKNI6HU9i3op0y3tpQQw39b/oLfDt0HcsiqWsAAAAASUVORK5CYII=
  24. // @compatible chrome
  25. // @compatible firefox
  26. // @compatible opera
  27. // ==/UserScript==
  28.  
  29. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  30.  
  31. // keep video info cache for a month since last time it's shown
  32. var CACHE_STALE_DURATION = 30 * 24 * 3600e3;
  33.  
  34. var playQuality = GM_getValue('quality', 'auto') || 'auto';
  35.  
  36. if (location.href.indexOf('https://www.youtube.com/') == 0) {
  37. if (playQuality != 'auto') {
  38. window.addEventListener('load', function _() {
  39. window.removeEventListener('load', _);
  40. var player = $('.html5-video-player');
  41. if (player && typeof player.setPlaybackQuality == 'function')
  42. player.setPlaybackQuality(playQuality);
  43. });
  44. }
  45. if (!window.chrome || window == window.parent
  46. || !location.href.match(/^https:\/\/www\.youtube\.com\/embed.*?FYTEfullscreen=1/))
  47. return;
  48. var fsbtn = document.getElementsByClassName('ytp-fullscreen-button');
  49. new MutationObserver(function() {
  50. if (fsbtn[0]) {
  51. this.disconnect();
  52. fsbtn[0].outerHTML = fsbtn[0].outerHTML;
  53. fsbtn[0].addEventListener('click', function(e) {
  54. window.parent.postMessage('FYTE-toggle-fullscreen', '*');
  55. });
  56. }
  57. }).observe(document, {subtree:true, childList:true});
  58. return;
  59. }
  60.  
  61. var resizeMode = GM_getValue('resize', 'Fit to width');
  62. if (typeof resizeMode != 'string')
  63. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  64.  
  65. var resizeWidth = GM_getValue('width', 1280) |0;
  66. var resizeHeight = GM_getValue('height', 720) |0;
  67. updateCustomSize();
  68.  
  69. var pinnedWidth = GM_getValue('pinnedWidth', 400) |0;
  70.  
  71. var playDirectly = !!GM_getValue('playHTML5', false);
  72. var playDirectlyShown = !!GM_getValue('playHTML5shown', false);
  73. var skipCustom = !!GM_getValue('skipCustom', true);
  74. var showStoryboard = !!GM_getValue('showStoryboard', true);
  75. var pinnable = GM_getValue('pinnable', 'on');
  76. if (!/^(on|hide|off)$/.test(pinnable))
  77. pinnable = !!pinnable ? 'on' : 'hide';
  78.  
  79. var _ = initTL();
  80.  
  81. var imageLoader = document.createElement('img');
  82. var imageLoader2 = document.createElement('img');
  83.  
  84. var fytedom = document.getElementsByClassName('instant-youtube-container');
  85. var iframes = document.getElementsByTagName('iframe');
  86. var objects = document.getElementsByTagName('object');
  87. var persite = (function() {
  88. var rules = [
  89. {host: 'developers.google.com',
  90. match: '[data-video-id]',
  91. src: function(e) { return '//youtube.com/embed/' + e.dataset.videoId }},
  92. {host: /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/, class:'g-blk', query: 'a[href*="youtube.com/watch"][data-ved]', eatparent: 1},
  93. {host: 'pikabu.ru', class:'b-video', match: '[data-url*="youtube.com/embed"]', attr: 'data-url'},
  94. {host: 'androidauthority.com', eatparent: '.video-container'},
  95. {host: 'reddit.com',
  96. match: '[data-url*="youtube.com/"] [src*="/mediaembed"], [data-url*="youtu.be/"] [src*="/mediaembed"]',
  97. src: function(e) { return e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url }},
  98. {host: /(www\.)?theverge\.com$/, eatparent: '.p-scalable-video'},
  99. {host: '9gag.com', eatparent: 0},
  100. {host: 'reddit.com', match: '[data-url*="youtube.com"] iframe[src*="redditmedia.com/mediaembed"]',
  101. src: function(e) { return e.closest('[data-url*="youtube.com"]').dataset.url }},
  102. ];
  103. for (var i=0, rule; (i<rules.length) && (rule=rules[i]); i++) {
  104. var rx = rule.host instanceof RegExp ? rule.host : new RegExp('(^|\\.)' + rule.host.replace(/\./g, '\\.') + '$', 'i');
  105. if (rx.test(location.hostname)) {
  106. if (!rule.tag && !rule.class)
  107. rule.tag = 'iframe';
  108. if (!rule.match && !rule.query)
  109. rule.match = '[src*="youtube.com/embed"]';
  110. return {
  111. nodes: rule.class ? document.getElementsByClassName(rule.class) : document.getElementsByTagName(rule.tag),
  112. match: rule.match ? function(e) { return e.matches(rule.match) ? e : null }
  113. : function(e) { return e.querySelector(rule.query) },
  114. attr: rule.attr,
  115. src: rule.src,
  116. eatparent: rule.eatparent,
  117. };
  118. }
  119. }
  120. })();
  121.  
  122. findEmbeds();
  123. injectStylesIfNeeded();
  124. new MutationObserver(findEmbeds).observe(document, {subtree:true, childList:true});
  125.  
  126. document.addEventListener('DOMContentLoaded', function(e) {
  127. injectStylesIfNeeded();
  128. adjustNodesIfNeeded(e);
  129. setTimeout(cleanupCache, 60e3);
  130. });
  131. window.addEventListener('resize', adjustNodesIfNeeded, true);
  132. window.addEventListener('message', function(e) {
  133. if (e.data == 'FYTE-toggle-fullscreen') {
  134. $$('iframe[allowfullscreen]').some(function(iframe) {
  135. if (iframe.contentWindow == e.source) {
  136. goFullscreen(iframe, !(document.webkitIsFullScreen || document.mozIsFullScreen || document.isFullScreen));
  137. return true;
  138. }
  139. });
  140. }
  141. else if (e.data == 'iframe-allowfs') {
  142. $$('iframe:not([allowfullscreen])').some(function(iframe) {
  143. if (iframe.contentWindow == e.source) {
  144. iframe.allowFullscreen = true;
  145. return true;
  146. }
  147. });
  148. if (window != window.top)
  149. window.parent.postMessage('iframe-allowfs', '*');
  150. }
  151. });
  152.  
  153. function findEmbeds(mutations) {
  154. var i, len, e, m;
  155. if (persite)
  156. for (i=0, len=persite.nodes.length; (i<len) && (e=persite.nodes[i]); i++)
  157. if ((e = persite.match(e)))
  158. processEmbed(e, persite.src && persite.src(e) || e.getAttribute(persite.attr));
  159. for (i=0, len=iframes.length; (i<len) && (e=iframes[i]); i++)
  160. if (/youtube\.com|youtu\.be/i.test(e.src || e.dataset.src))
  161. processEmbed(e, e.src || e.dataset.src);
  162. for (i=0, len=objects.length; (i<len) && (e=objects[i]); i++)
  163. if (m = e.querySelector('embed, [value*="youtu.be"], [value*="youtube.com"]'))
  164. processEmbed(e, m.src || e.dataset.src || 'https://' + m.value.match(/youtu\.be.*|youtube\.com.*/)[0]);
  165. }
  166.  
  167. function processEmbed(node, src) {
  168. function decodeEmbedUrl(url) {
  169. return url.indexOf('youtube.com%2Fembed') > 0
  170. ? decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube.com%2Fembed[^&]+).*$/i, '$1'))
  171. : url;
  172. }
  173. src = src || node.src || node.href || '';
  174. var n = node;
  175. var np = n.parentNode, npw;
  176. var srcFixed = decodeEmbedUrl(src).replace(/\/(watch\?v=|v\/)/, '/embed/');
  177. if (src.indexOf('cdn.embedly.com/') > 0 ||
  178. resizeMode != 'Original' && np && np.children.length == 1 && !np.className && !np.id)
  179. {
  180. n = location.hostname == 'disqus.com' ? np.parentNode : np;
  181. np = n.parentElement;
  182. }
  183. if (!np ||
  184. !np.parentNode ||
  185. skipCustom && srcFixed.indexOf('enablejsapi=1') > 0 ||
  186. node.matches('.instant-youtube-embed, .YTLT-embed') ||
  187. srcFixed.indexOf('/embed/videoseries') > 0 ||
  188. node.onload // skip some retarded loaders
  189. )
  190. return;
  191.  
  192. var id = srcFixed.match(/(?:^(?:https?:)?\/\/)(?:www\.)?(?:youtube\.com\/(?:embed\/(?:v=)?|\/.*?[&?\/]v[=\/])|youtu\.be\/)([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  193. if (!id)
  194. return;
  195. id = id[1];
  196.  
  197. var autoplay = srcFixed.indexOf('autoplay=1') > 0;
  198.  
  199. if (np.localName == 'object')
  200. n = np, np = n.parentElement;
  201.  
  202. var eatparent = persite && persite.eatparent || 0;
  203. if (typeof eatparent == 'string')
  204. n = np.closest(eatparent) || n, np = n.parentElement;
  205. else
  206. while (eatparent--)
  207. n = np, np = n.parentElement;
  208.  
  209. injectStylesIfNeeded('force');
  210.  
  211. var div = document.createElement('div');
  212. div.className = 'instant-youtube-container';
  213. div.FYTE = {
  214. state: 'querying',
  215. srcEmbed: srcFixed.replace(/&$/, ''),
  216. originalWidth: /%/.test(node.width) ? 320 : node.width|0 || n.clientWidth|0,
  217. originalHeight: /%/.test(node.height) ? 200 : node.height|0 || n.clientHeight|0,
  218. cache: tryJSONparse(GM_getValue('cache-' + id)) || {
  219. id: id,
  220. }
  221. };
  222. div.FYTE.srcEmbedFixed = div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace(/([&?])(wmode=\w+|feature=oembed)&?/, '$1').replace(/[&?]$/, '');
  223. div.FYTE.srcWatchFixed = div.FYTE.srcEmbedFixed.replace(/\/embed\//, '/watch?v=').replace(/(\?.*?)\?/, '$1&');
  224.  
  225. var cache = div.FYTE.cache;
  226. cache.lastUsed = Date.now();
  227. GM_setValue('cache-' + id, JSON.stringify(cache));
  228.  
  229. if (cache.reason)
  230. div.setAttribute('disabled', '');
  231.  
  232. var divSize = calcContainerSize(div, n);
  233. var origStyle = getComputedStyle(n);
  234. div.style.cssText = important(
  235. (autoplay ? '' : 'background-color:transparent; transition:background-color 2s;') +
  236. (origStyle.hasOwnProperty('position') ? Object.keys(origStyle) : Object.keys(origStyle.__proto__) /*FF*/)
  237. .filter(function(k) { return !!k.match(/^(position|left|right|top|bottom)$/) })
  238. .map(function(k) { return k + ':' + origStyle[k] })
  239. .join(';')
  240. .replace(/\b[^;:]+:\s*(auto|static|block)\s*(!\s*important)?;/g, '') +
  241. (origStyle.display == 'inline' ? ';display:inline-block;width:100%' : '') +
  242. ';min-width:' + Math.min(divSize.w, div.FYTE.originalWidth) + 'px' +
  243. ';min-height:' + Math.min(divSize.h, div.FYTE.originalHeight) + 'px' +
  244. (resizeMode == 'Fit to width' ? ';width:100%' : '') +
  245. ';max-width:' + divSize.w + 'px; height:' + (persite && persite.eatparent === 0 ? '100%;' : divSize.h + 'px;'));
  246. if (!autoplay) {
  247. setTimeout(function() { div.style.backgroundColor = '' }, 0);
  248. setTimeout(function() { div.style.transition = '' }, 2000);
  249. }
  250.  
  251. // consume parents of retardedly positioned videos
  252. var parentStyle = getComputedStyle(np);
  253. if (div.style.position.match('absolute|relative')
  254. && parseFloat(parentStyle.paddingTop) + parseFloat(parentStyle.paddingBottom) < parseFloat(parentStyle.height)) {
  255. if (np.children.length == 1 &&
  256. floatPadding(np, parentStyle, 'Top') >= div.FYTE.originalHeight-1 ||
  257. floatPadding(np, getComputedStyle(np, ':after'), 'Top') >= div.FYTE.originalHeight-1
  258. ) {
  259. n = np, np = n.parentElement;
  260. }
  261. div.style.cssText = div.style.cssText.replace(/\b(position|left|top|right|bottom):[^;]+/g, '');
  262. }
  263.  
  264. var wrapper = div.appendChild(document.createElement('div'));
  265. wrapper.className = 'instant-youtube-wrapper';
  266.  
  267. var img = wrapper.appendChild(document.createElement('img'));
  268. if (!autoplay)
  269. img.src = 'https://i.ytimg.com/vi/' + id + '/' + (cache.cover || 'maxresdefault.jpg');
  270. img.className = 'instant-youtube-thumbnail';
  271. img.style.cssText = important((cache.cover ? '' : 'transition:opacity 0.1s ease-out; opacity:0; ') +
  272. 'padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0; max-width:none; max-height:none;');
  273.  
  274. img.onload = function(e) {
  275. if (img.naturalWidth <= 120 && !cache.cover)
  276. return img.onerror(e);
  277. var fitToWidth = true;
  278. if (img.naturalHeight || cache.coverHeight) {
  279. if (!cache.coverHeight) {
  280. cache.coverWidth = img.naturalWidth;
  281. cache.coverHeight = img.naturalHeight;
  282. GM_setValue('cache-' + id, JSON.stringify(cache));
  283. }
  284. var ratio = cache.coverWidth / cache.coverHeight;
  285. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  286. img.style.cssText += important('width:auto; height:100%;');
  287. fitToWidth = false;
  288. }
  289. }
  290. if (fitToWidth) {
  291. img.style.cssText += important('width:100%; height:auto;');
  292. }
  293. if (cache.videoWidth)
  294. fixThumbnailAR(div);
  295. if (!autoplay)
  296. img.style.opacity = 1;
  297. };
  298. img.onerror = function(e) {
  299. if (img.src.indexOf('maxresdefault') > 0)
  300. img.src = img.src.replace('maxresdefault','sddefault');
  301. else if (img.src.indexOf('sddefault') > 0)
  302. img.src = img.src.replace('sddefault','hqdefault');
  303. };
  304. if (cache.coverWidth)
  305. img.onload();
  306.  
  307. translateHTML(wrapper, 'beforeend', '\
  308. <a class="instant-youtube-title" target="_blank" href="' + div.FYTE.srcWatchFixed + '">' +
  309. (cache.title || cache.reason ? '<strong>' + (cache.title || cache.reason || '') + '</strong>' +
  310. (cache.duration ? '<span>' + cache.duration + '</span>' : '') +
  311. (cache.fps ? '<i>, ' + cache.fps + 'fps</i>' : '')
  312. : '&nbsp;') + '</a>\
  313. <svg class="instant-youtube-play-button">\
  314. <path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z">\
  315. <title tl>msgAltPlayerHint</title>\
  316. </path>\
  317. <polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon>\
  318. </svg>\
  319. <span tl class="instant-youtube-alternative">' + (playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  320. <div tl class="instant-youtube-options-button">Options</div>\
  321. ');
  322.  
  323. np.insertBefore(div, n);
  324. n.remove();
  325.  
  326. if (!cache.title && !cache.reason || autoplay && playDirectly)
  327. fetchInfo();
  328.  
  329. if (autoplay)
  330. return startPlaying(div);
  331.  
  332. div.addEventListener('click', clickHandler);
  333. div.addEventListener('mousedown', clickHandler);
  334. div.addEventListener('mouseenter', fetchInfo);
  335.  
  336. function fetchInfo(e) {
  337. div.removeEventListener('mouseenter', fetchInfo);
  338. if (!div.FYTE.storyboard) {
  339. GM_xmlhttpRequest({
  340. method: 'GET',
  341. url: 'https://www.youtube.com/get_video_info?video_id=' + id +
  342. '&hl=en_US&html5=1&el=embedded&eurl=' + encodeURIComponent(location.href),
  343. context: div,
  344. onload: parseVideoInfo
  345. });
  346. }
  347. }
  348. }
  349.  
  350. function adjustNodesIfNeeded(e) {
  351. if (!fytedom[0])
  352. return;
  353. if (adjustNodesIfNeeded.scheduled)
  354. clearTimeout(adjustNodesIfNeeded.scheduled);
  355. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  356. adjustNodes(e);
  357. adjustNodesIfNeeded.scheduled = 0;
  358. }, 16);
  359. }
  360.  
  361. function adjustNodes(e, clickedContainer) {
  362. var force = !!clickedContainer;
  363. var nearest = force ? clickedContainer : null;
  364.  
  365. var vids = $$('.instant-youtube-container:not([pinned]):not([stub])');
  366.  
  367. if (!nearest && e.type != 'DOMContentLoaded') {
  368. var minDistance = window.innerHeight*3/4 |0;
  369. var nearTargetY = window.innerHeight/2;
  370. vids.forEach(function(n) {
  371. var bounds = n.getBoundingClientRect();
  372. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  373. if (distance < minDistance) {
  374. minDistance = distance;
  375. nearest = n;
  376. }
  377. });
  378. }
  379.  
  380. if (nearest) {
  381. var bounds = nearest.getBoundingClientRect();
  382. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  383. }
  384.  
  385. var resized = false;
  386.  
  387. vids.forEach(function(n) {
  388. var size = calcContainerSize(n);
  389. var w = size.w, h = size.h;
  390.  
  391. // prevent parent clipping
  392. for (var e=n.parentElement, style; e; e=e.parentElement)
  393. if (e.style.overflow != 'visible' && (style=getComputedStyle(e)))
  394. if ((style.overflow+style.overflowX+style.overflowY).match(/hidden|scroll/))
  395. if (n.offsetTop < e.clientHeight / 2 && n.offsetTop + n.clientHeight > e.clientHeight)
  396. e.style.cssText = e.style.cssText.replace(/\boverflow(-[xy])?:[^;]+/g, '') +
  397. important('overflow:visible;overflow-x:visible;overflow-y:visible;');
  398.  
  399. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  400. return;
  401.  
  402. if (n.style.maxWidth != w + 'px') overrideCSS(n, {'max-width': w + 'px'});
  403. if (n.style.height != h + 'px') overrideCSS(n, {'height': h + 'px'});
  404. if (parseFloat(n.style.minWidth) > w) overrideCSS(n, {'min-width': n.style.maxWidth});
  405. if (parseFloat(n.style.minHeight) > h) overrideCSS(n, {'min-height': n.style.height});
  406.  
  407. fixThumbnailAR(n);
  408. resized = true;
  409. });
  410.  
  411. if (resized && nearest)
  412. setTimeout(function() {
  413. var bounds = nearest.getBoundingClientRect();
  414. var h = bounds.bottom - bounds.top;
  415. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  416. var projectedTop = projectedCenterY - h/2;
  417. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  418. window.scrollBy(0, bounds.top - safeTop);
  419. }, 16);
  420. }
  421.  
  422. function calcContainerSize(div, origNode) {
  423. origNode = origNode || div;
  424. var w, h;
  425. var np = origNode.parentElement;
  426. var style = getComputedStyle(np);
  427. var parentWidth = parseFloat(style.width) - floatPadding(np, style, 'Left') - floatPadding(np, style, 'Right');
  428. if (+style.columnCount > 1)
  429. parentWidth = (parentWidth + parseFloat(style.columnGap)) / style.columnCount - parseFloat(style.columnGap);
  430. switch (resizeMode) {
  431. case 'Original':
  432. if (div.FYTE.originalWidth == 320 && div.FYTE.originalHeight == 200) {
  433. w = parentWidth;
  434. h = parentWidth / 16 * 9;
  435. } else {
  436. w = div.FYTE.originalWidth;
  437. h = div.FYTE.originalHeight;
  438. }
  439. break;
  440. case 'Custom':
  441. w = resizeWidth;
  442. h = resizeHeight;
  443. break;
  444. case '1080p':
  445. case '720p':
  446. case '480p':
  447. case '360p':
  448. h = parseInt(resizeMode);
  449. w = h / 9 * 16;
  450. break;
  451. default: // fit-to-width mode
  452. var n = origNode;
  453. do {
  454. n = n.parentElement;
  455. // find parent node with nonzero width (i.e. independent of our video element)
  456. } while (n && !(w = n.clientWidth));
  457. if (w)
  458. h = w / 16 * 9;
  459. else {
  460. w = origNode.clientWidth;
  461. h = origNode.clientHeight;
  462. }
  463. }
  464. if (parentWidth > 0 && parentWidth < w) {
  465. h = parentWidth / w * h;
  466. w = parentWidth;
  467. }
  468. if (resizeMode == 'Fit to width' && h < div.FYTE.originalHeight*0.9)
  469. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  470.  
  471. return {w: window.chrome ? w : Math.round(w), h:h};
  472. }
  473.  
  474. function parseVideoInfo(response) {
  475. var div = response.context;
  476. var txt = response.responseText;
  477. var info = tryCatch(function() {
  478. var json = txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}');
  479. return tryJSONparse(json);
  480. }) || {};
  481. var cache = div.FYTE.cache;
  482. var shouldUpdateCache = false;
  483. var videoSources = [];
  484.  
  485. // parse width & height to adjust the thumbnail
  486. var m = decodeURIComponent(info.adaptive_fmts || '').match(/size=(\d+)x(\d+)\b/) ||
  487. decodeURIComponent(txt).match(/\/(\d+)x(\d+)\//);
  488.  
  489. if (m && (cache.videoWidth != (m[1]|0) || cache.videoHeight != (m[2]|0))) {
  490. fixThumbnailAR(div, m[1]|0, m[2]|0);
  491. cache.videoWidth = m[1]|0;
  492. cache.videoHeight = m[2]|0;
  493. shouldUpdateCache = true;
  494. }
  495.  
  496. // parse video sources
  497. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  498. var streams = {};
  499. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  500. var params = {};
  501. stream.split('&').forEach(function(kv) {
  502. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  503. });
  504. streams[params.itag] = params;
  505. });
  506. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  507. var itag = fmt.split('/')[0];
  508. var dimensions = fmt.split('/')[1];
  509. var stream = streams[itag];
  510. if (stream) {
  511. videoSources.push({
  512. src: stream.url + (stream.s ? '&signature=' + stream.s : ''),
  513. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  514. });
  515. }
  516. });
  517. } else {
  518. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  519. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  520. while (m = rx.exec(text)) {
  521. videoSources.push({
  522. src: decodeURIComponent(decodeURIComponent(m[1]))
  523. });
  524. }
  525. }
  526.  
  527. var fps = {};
  528. (decodeURIComponent(info.adaptive_fmts || ''))
  529. .split(',')
  530. .filter(function(s) { return /(^|&)type=video/.test(s) && /\b(?:fps=)([\d.]+)/.test(s) })
  531. .forEach(function(s) { fps[s.match(/\b(?:fps=)([\d.]+)/)[1]] = true });
  532. fps = Object.keys(fps).join('/');
  533. if (fps && cache.fps != fps) {
  534. cache.fps = fps;
  535. shouldUpdateCache = true;
  536. }
  537.  
  538. var duration = div.FYTE.duration = info.length_seconds|0 || '';
  539. if (duration) {
  540. var d = new Date(null);
  541. d.setSeconds(duration);
  542. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '$1');
  543. if (cache.duration != duration) {
  544. cache.duration = duration;
  545. shouldUpdateCache = true;
  546. }
  547. }
  548. if (duration || fps)
  549. duration = '<span>' + duration + '</span>' +
  550. (fps ? '<i>, ' + fps + 'fps</i>' : '');
  551.  
  552. var title = decodeURIComponent(info.title || info.reason || '').replace(/\+/g, ' ');
  553. if (title) {
  554. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  555. if (cache.title != title) {
  556. cache.title = title;
  557. shouldUpdateCache = true;
  558. }
  559. }
  560. if (pinnable != 'off' && info.title)
  561. makeDraggable(div);
  562.  
  563. if (info.reason) {
  564. div.setAttribute('disabled', '');
  565. if (cache.reason != info.reason) {
  566. cache.reason = info.reason;
  567. shouldUpdateCache = true;
  568. }
  569. }
  570.  
  571. if (videoSources.length)
  572. div.FYTE.videoSources = videoSources;
  573.  
  574. if (info.storyboard_spec && div.FYTE.state != 'scheduled play') {
  575. m = decodeURIComponent(decodeURIComponent(info.storyboard_spec)).split('|');
  576. div.FYTE.storyboard = tryJSONparse(
  577. m[m.length-1].replace(
  578. /^(\d+)#(\d+)#(\d+)#(\d+)#(\d+)#.+$/,
  579. '{"w":$1, "h":$2, "len":$3, "rows":$4, "cols":$5}'
  580. ));
  581. if (div.FYTE.storyboard.w * div.FYTE.storyboard.h > 2000) {
  582. div.FYTE.storyboard.url = m[0].replace('$L/$N.jpg', (m.length-2) + '/M0.jpg?sigh=' + m[m.length-1].replace(/^.+?#([^#]+)$/, '$1'));
  583. $(div, '.instant-youtube-options-button').insertAdjacentHTML('beforebegin',
  584. '<div class="instant-youtube-storyboard"' + (showStoryboard ? '' : ' disabled') + '>' +
  585. important('<div style="width:' + (div.FYTE.storyboard.w-1) + 'px; height:' + div.FYTE.storyboard.h + 'px;') +
  586. '">&nbsp;</div>' +
  587. '</div>');
  588. if (showStoryboard)
  589. updateHoverHandler(div);
  590. }
  591. }
  592.  
  593. injectStylesIfNeeded();
  594.  
  595. if (div.FYTE.state == 'scheduled play')
  596. setTimeout(function() { startPlayingDirectly(div) }, 0);
  597.  
  598. div.FYTE.state = '';
  599.  
  600. var cover = decodeURIComponent(info.iurlmaxres || info.iurlhq || info.iurl || '').match(/[^\/]+$/);
  601. if (cover && cache.cover != cover[0]) {
  602. cache.cover = cover[0];
  603. shouldUpdateCache = true;
  604. }
  605. if (shouldUpdateCache)
  606. GM_setValue('cache-' + info.video_id, JSON.stringify(cache));
  607. }
  608.  
  609. function fixThumbnailAR(div, w, h) {
  610. var img = $(div, 'img');
  611. if (!img)
  612. return;
  613. var thw = img.naturalWidth, thh = img.naturalHeight;
  614. if (w && h) { // means thumbnail is still loading
  615. div.FYTE.cache.videoWidth = w;
  616. div.FYTE.cache.videoHeight = h;
  617. } else {
  618. w = div.FYTE.cache.videoWidth;
  619. h = div.FYTE.cache.videoHeight;
  620. if (!w || !h)
  621. return;
  622. }
  623. var divw = div.clientWidth, divh = div.clientHeight;
  624. // if both video and thumbnail are 4:3, fit the image to height
  625. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  626. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  627. img.style.maxHeight = img.clientHeight + 'px';
  628. if (!div.FYTE.cache.videoWidth) // skip animation if thumbnail is already loaded
  629. img.style.transition = 'height 1s ease, margin-top 1s ease';
  630. setTimeout(function() {
  631. img.style.maxHeight = 'none';
  632. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  633. setTimeout(function() {
  634. img.style.transition = '';
  635. }, 1000);
  636. }, 0);
  637. }
  638. }
  639.  
  640. function updateHoverHandler(div) {
  641. var sb = $(div, '.instant-youtube-storyboard');
  642. if (!showStoryboard) {
  643. if (!sb.getAttribute('disabled'))
  644. sb.setAttribute('disabled', '');
  645. return;
  646. }
  647. if (sb.hasAttribute('disabled'))
  648. sb.removeAttribute('disabled');
  649.  
  650. sb.addEventListener('click', storyboardClickHandler);
  651.  
  652. var oldIndex = null;
  653. var style = sb.firstElementChild.style;
  654. sb.addEventListener('mousemove', storyboardHoverHandler);
  655. sb.addEventListener('mouseout', storyboardHoverHandler);
  656.  
  657. div.addEventListener('mouseover', storyboardPreloader);
  658. div.addEventListener('mouseout', storyboardPreloader);
  659.  
  660. var spinner = document.createElement('span');
  661. spinner.className = 'instant-youtube-loading-spinner';
  662.  
  663. function storyboardClickHandler(e) {
  664. sb.removeEventListener('click', storyboardClickHandler);
  665. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  666. div.FYTE.startAt = offsetX / this.clientWidth * div.FYTE.duration |0;
  667. div.FYTE.srcEmbedFixed = setUrlParams(div.FYTE.srcEmbedFixed, {start: div.FYTE.startAt});
  668. startPlaying(div, {alternateMode: e.shiftKey});
  669. }
  670.  
  671. function storyboardPreloader(e) {
  672. if (e.type == 'mouseout') {
  673. imageLoader.onload = null; imageLoader.src = '';
  674. spinner.remove();
  675. return;
  676. }
  677. if (!div.FYTE.storyboard || div.FYTE.storyboard.preloaded)
  678. return;
  679. var lastpart = (div.FYTE.storyboard.len-1)/(div.FYTE.storyboard.rows * div.FYTE.storyboard.cols) |0;
  680. if (lastpart <= 0)
  681. return;
  682. var part = 0;
  683. imageLoader.src = setStoryboardUrl(part++);
  684. imageLoader.onload = function() {
  685. if (part > lastpart) {
  686. div.FYTE.storyboard.preloaded = true;
  687. div.removeEventListener('mouseover', storyboardPreloader);
  688. div.removeEventListener('mouseout', storyboardPreloader);
  689. imageLoader.onload = null;
  690. imageLoader.src = '';
  691. spinner.remove();
  692. return;
  693. }
  694. imageLoader.src = setStoryboardUrl(part++);
  695. };
  696. }
  697.  
  698. function setStoryboardUrl(part) {
  699. return div.FYTE.storyboard.url.replace(/M\d+\.jpg\?/, 'M' + part + '.jpg?');
  700. }
  701.  
  702. function storyboardHoverHandler(e) {
  703. if (!showStoryboard || !div.FYTE.storyboard)
  704. return;
  705. if (e.type == 'mouseout')
  706. return imageLoader2.onload && imageLoader2.onload();
  707. var w = div.FYTE.storyboard.w;
  708. var h = div.FYTE.storyboard.h;
  709. var cols = div.FYTE.storyboard.cols;
  710. var rows = div.FYTE.storyboard.rows;
  711. var len = div.FYTE.storyboard.len;
  712. var partlen = rows * cols;
  713.  
  714. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  715. var left = Math.min(this.clientWidth - w, Math.max(0, offsetX - w)) |0;
  716. if (!style.left || parseInt(style.left) != left) {
  717. style.left = left + 'px';
  718. if (spinner.parentElement)
  719. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  720. }
  721.  
  722. var index = Math.min(offsetX / this.clientWidth * (len+1) |0, len - 1);
  723. if (index == oldIndex)
  724. return;
  725.  
  726. var part = index/partlen|0;
  727. if (!oldIndex || part != (oldIndex/partlen|0)) {
  728. style.cssText = style.cssText.replace(/$|background-image[^;]+;/,
  729. 'background-image: url(' + setStoryboardUrl(part) + ')!important;');
  730. if (!div.FYTE.storyboard.preloaded) {
  731. if (spinner.timer)
  732. clearTimeout(spinner.timer);
  733. spinner.timer = setTimeout(function() {
  734. spinner.timer = 0;
  735. if (!imageLoader2.src)
  736. return;
  737. this.appendChild(spinner);
  738. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  739. }.bind(this), 50);
  740. imageLoader2.onload = function() {
  741. clearTimeout(spinner.timer);
  742. spinner.remove();
  743. spinner.timer = 0;
  744. imageLoader2.onload = null;
  745. imageLoader2.src = '';
  746. };
  747. imageLoader2.src = setStoryboardUrl(part);
  748. }
  749. }
  750.  
  751. oldIndex = index;
  752. index = index % partlen;
  753. style.backgroundPosition = '-' + (index % cols) * w + 'px -' + (index / cols |0) * h + 'px';
  754. }
  755. }
  756.  
  757. function clickHandler(e) {
  758. if (e.target.closest('a')
  759. || e.type == 'mousedown' && e.button != 1
  760. || e.type == 'click' && e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  761. return;
  762. if (e.type == 'click' && e.target.matches('.instant-youtube-options-button')) {
  763. showOptions(e);
  764. e.preventDefault();
  765. e.stopPropagation();
  766. return;
  767. }
  768.  
  769. e.preventDefault();
  770. e.stopPropagation();
  771. e.stopImmediatePropagation();
  772.  
  773. startPlaying(e.target.closest('.instant-youtube-container'), {
  774. alternateMode: e.shiftKey || e.target.matches('.instant-youtube-alternative'),
  775. fullscreen: e.button == 1,
  776. });
  777. }
  778.  
  779. function startPlaying(div, params) {
  780. div.removeEventListener('click', clickHandler);
  781. div.removeEventListener('mousedown', clickHandler);
  782.  
  783. $$remove(div, '.instant-youtube-alternative, .instant-youtube-storyboard, .instant-youtube-options-button, .instant-youtube-options');
  784. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-spinner"></span>';
  785.  
  786. if (pinnable != 'off') {
  787. makePinnable(div);
  788. if (params && params.pin)
  789. $(div, '[pin="' + params.pin + '"]').click();
  790. }
  791.  
  792. if (window != window.top)
  793. window.parent.postMessage('iframe-allowfs', '*');
  794.  
  795. if ((!!playDirectly + !!(params && params.alternateMode) == 1)
  796. && (div.FYTE.videoSources || div.FYTE.state == 'querying')) {
  797. if (div.FYTE.videoSources)
  798. startPlayingDirectly(div, params);
  799. else {
  800. // playback will start in parseVideoInfo
  801. div.FYTE.state = 'scheduled play';
  802. // fallback to iframe in 5s
  803. setTimeout(function() {
  804. if (div.FYTE.state) {
  805. div.FYTE.state = '';
  806. switchToIFrame.call(div, params);
  807. }
  808. }, 5000);
  809. }
  810. }
  811. else
  812. switchToIFrame.call(div, params);
  813. }
  814.  
  815. function startPlayingDirectly(div, params) {
  816. var video = document.createElement('video');
  817. video.controls = true;
  818. video.autoplay = true;
  819. video.style.cssText = important('position:absolute; left:0; top:0; right:0; bottom:0; padding:0; margin:auto; opacity:0; width:100%; height:100%;');
  820. video.className = 'instant-youtube-embed';
  821. video.volume = GM_getValue('volume', 0.5);
  822.  
  823. div.FYTE.videoSources.forEach(function(src) {
  824. var srcdom = video.appendChild(document.createElement('source'));
  825. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  826. srcdom.onerror = switchToIFrame.bind(div, params);
  827. });
  828.  
  829. overrideCSS($(div, 'img'), {transition: 'opacity 1s', opacity: '0'});
  830.  
  831. if (params && params.fullscreen) {
  832. div.firstElementChild.appendChild(video);
  833. div.setAttribute('playing', '');
  834. video.style.opacity = 1;
  835. goFullscreen(video);
  836. }
  837.  
  838. if (window.chrome) {
  839. video.addEventListener('click', function(e) {
  840. this.paused ? this.play() : this.pause();
  841. });
  842. }
  843.  
  844. var title = $(div, '.instant-youtube-title');
  845. if (title) {
  846. video.onpause = function() { title.removeAttribute('hidden') };
  847. video.onplay = function() { title.setAttribute('hidden', true) };
  848. }
  849.  
  850. var switchTimer = setTimeout(switchToIFrame.bind(div, params), 5000);
  851.  
  852. video.onloadedmetadata = div.FYTE.startAt && function(e) {
  853. clearTimeout(switchTimer);
  854. video.currentTime = div.FYTE.startAt;
  855. };
  856.  
  857. video.onloadeddata = function(e) {
  858. clearTimeout(switchTimer);
  859. pauseOtherVideos(video);
  860. video.interval = setInterval(function() {
  861. if (video.volume != GM_getValue('volume', 0.5))
  862. GM_setValue('volume', video.volume);
  863. }, 1000);
  864. if (params && params.fullscreen)
  865. return;
  866. div.setAttribute('playing', '');
  867. div.firstElementChild.appendChild(video);
  868. video.style.opacity = 1;
  869. };
  870. }
  871.  
  872. function switchToIFrame(params, e) {
  873. if (this.querySelector('iframe'))
  874. return;
  875. var div = this;
  876. var wrapper = div.firstElementChild;
  877. var fullscreen = params && params.fullscreen && !e;
  878. if (e instanceof Event) {
  879. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  880. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  881. while (video.lastElementChild)
  882. video.lastElementChild.remove();
  883. goFullscreen(video, false);
  884. video.remove();
  885. }
  886.  
  887. var url = setUrlParams(div.FYTE.srcEmbedFixed, {
  888. html5: 1,
  889. autoplay: 1,
  890. autohide: 2,
  891. border: 0,
  892. controls: 1,
  893. fs: 1,
  894. showinfo: 1,
  895. ssl: 1,
  896. theme: 'dark',
  897. enablejsapi: 1,
  898. FYTEfullscreen: fullscreen|0,
  899. });
  900.  
  901. ($(div, '[pin]') || wrapper).insertAdjacentHTML(pinnable != 'off' ? 'beforebegin' : 'beforeend',
  902. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' + url +
  903. '" style="' + important('position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0;') +
  904. '" frameborder="0" allowfullscreen width="100%" height="100%"></iframe>');
  905.  
  906. div.setAttribute('iframe', '');
  907. div.setAttribute('playing', '');
  908.  
  909. var iframe = $(div, 'iframe');
  910. if (fullscreen) {
  911. goFullscreen(iframe);
  912. iframe.style.opacity = 1;
  913. }
  914.  
  915. iframe.onload = function(e) {
  916. window.addEventListener('message', YTlistener);
  917. iframe.contentWindow.postMessage('{"event":"listening"}', '*');
  918. };
  919. setTimeout(function() {
  920. iframe.style.opacity = 1;
  921. window.removeEventListener('message', YTlistener);
  922. }, 5000);
  923.  
  924. function YTlistener(e) {
  925. if (e.source != iframe.contentWindow || !e.data)
  926. return;
  927. var data = tryJSONparse(e.data);
  928. if (!data.info || data.info.playerState != 1)
  929. return;
  930. window.removeEventListener('message', YTlistener);
  931. pauseOtherVideos(iframe);
  932. iframe.style.opacity = 1;
  933. $$remove(div, 'span, a');
  934. $(div, 'img').style.display = 'none';
  935. }
  936. }
  937.  
  938. function setUrlParams(url, params) {
  939. var names = Object.keys(params);
  940. var parts = url.split('?', 2)
  941. var query = (parts[1] || '').replace(new RegExp('(?:[?&]|^)(?:' + names.join('|') + ')(?:=[^?&]*)?', 'gi'), '');
  942. return parts[0] + '?' + query + (query ? '&' : '?') +
  943. names.map(function(n) { return n + '=' + params[n] }).join('&');
  944. }
  945.  
  946. function pauseOtherVideos(activePlayer) {
  947. $$(activePlayer.ownerDocument, '.instant-youtube-embed').forEach(function(v) {
  948. if (v == activePlayer)
  949. return;
  950. switch (v.localName) {
  951. case 'video':
  952. if (!v.paused)
  953. v.pause();
  954. break;
  955. case 'iframe':
  956. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  957. break;
  958. }
  959. });
  960. }
  961.  
  962. function goFullscreen(el, enable) {
  963. if (enable !== false)
  964. el.webkitRequestFullScreen && el.webkitRequestFullScreen()
  965. || el.mozRequestFullScreen && el.mozRequestFullScreen()
  966. || el.requestFullScreen && el.requestFullScreen();
  967. else
  968. document.webkitCancelFullScreen && document.webkitCancelFullScreen()
  969. || document.mozCancelFullScreen && document.mozCancelFullScreen()
  970. || document.cancelFullScreen && document.cancelFullScreen();
  971. }
  972.  
  973. function makePinnable(div) {
  974. div.firstElementChild.insertAdjacentHTML('beforeend',
  975. '<div size-gripper></div>' +
  976. '<div pin="top-left"></div><div pin="top-right"></div><div pin="bottom-right"></div><div pin="bottom-left"></div>');
  977.  
  978. $$(div, '[pin]').forEach(function(pin) {
  979. if (pinnable == 'hide')
  980. pin.setAttribute('transparent', '');
  981. pin.onclick = pinClicked;
  982. });
  983. $(div, '[size-gripper]').addEventListener('mousedown', startResize, true);
  984. $(div, '[size-gripper]').addEventListener('mousedown', function(e) { return false }, false);
  985.  
  986. function pinClicked(e) {
  987. var pin = this;
  988. var pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  989. var corner = pin.getAttribute('pin');
  990. var video = $(div, 'video');
  991. if (pinIt) {
  992. $$(div, '[pin][active]').forEach(function(p) { p.removeAttribute('active') });
  993. pin.setAttribute('active', '');
  994. if (!div.FYTE.unpinnedStyle) {
  995. div.FYTE.unpinnedStyle = div.style.cssText;
  996. var stub = div.cloneNode();
  997. var img = $(div, 'img').cloneNode();
  998. img.style.opacity = 1;
  999. img.style.display = 'block';
  1000. img.title = '';
  1001. stub.appendChild(img);
  1002. stub.onclick = function(e) { $(div, '[pin][active]').onclick(e) };
  1003. stub.style.cssText += 'opacity:0.3!important;';
  1004. stub.setAttribute('stub', '');
  1005. div.FYTE.stub = stub;
  1006. div.parentNode.insertBefore(stub, div);
  1007. }
  1008. var size = constrainPinnedSize(div, localStorage['width#' + location.hostname] || pinnedWidth);
  1009. div.style.cssText = important(
  1010. 'position: fixed;' +
  1011. 'width: ' + size.w + 'px;' +
  1012. 'z-index: 999999999;' +
  1013. 'height:' + size.h + 'px;' +
  1014. 'top:' + (corner.indexOf('top') >= 0 ? '0' : 'auto') + ';' +
  1015. 'bottom:' + (corner.indexOf('bottom') >= 0 ? '0' : 'auto') + ';' +
  1016. 'left:' + (corner.indexOf('left') >= 0 ? '0' : 'auto') + ';' +
  1017. 'right:' + (corner.indexOf('right') >= 0 ? '0' : 'auto') + ';'
  1018. );
  1019. adjustPinnedOffset(div, div, corner);
  1020. div.setAttribute('pinned', corner);
  1021. if (video && document.body)
  1022. document.body.appendChild(div);
  1023. }
  1024. else { // unpin
  1025. pin.removeAttribute('active');
  1026. div.removeAttribute('pinned');
  1027. div.style.cssText = div.FYTE.unpinnedStyle;
  1028. div.FYTE.unpinnedStyle = '';
  1029. if (div.FYTE.stub) {
  1030. if (video && document.body)
  1031. div.FYTE.stub.parentNode.replaceChild(div, div.FYTE.stub);
  1032. div.FYTE.stub.remove();
  1033. div.FYTE.stub = null;
  1034. }
  1035. }
  1036. if (video && video.paused)
  1037. video.play();
  1038. }
  1039.  
  1040. function startResize(e) {
  1041. var siteSaved = ('width#' + location.hostname) in localStorage;
  1042. var saveAs = siteSaved ? 'site' : 'global';
  1043. var oldSizeCSS = {w: div.style.width, h: div.style.height};
  1044. var oldDraggable = div.draggable;
  1045. div.draggable = false;
  1046.  
  1047. var gripper = this;
  1048. gripper.removeAttribute('tried-exceeding');
  1049. gripper.innerHTML = '<div>' +
  1050. '<div save-as="' + saveAs + '"><b>S</b> = Site mode: <span>' + getSiteOnlyText() + '</span></div>' +
  1051. (!siteSaved ? '' : '<div><b>R</b> = Reset to global size</div>') +
  1052. '<div><b>Esc</b> = Cancel</div>' +
  1053. '</div>';
  1054.  
  1055. document.addEventListener('mousemove', resize);
  1056. document.addEventListener('mouseup', resizeDone);
  1057. document.addEventListener('keydown', resizeKeyDown);
  1058. e.stopImmediatePropagation();
  1059. return false;
  1060.  
  1061. function getSiteOnlyText(state) {
  1062. return saveAs == 'site' ? 'only ' + location.hostname : 'global';
  1063. }
  1064.  
  1065. function resize(e) {
  1066. var deltaX = e.movementX || e.webkitMovementX || e.mozMovementX || 0;
  1067. if (/right/.test(div.getAttribute('pinned')))
  1068. deltaX = -deltaX;
  1069. var newSize = constrainPinnedSize(div, div.clientWidth + deltaX);
  1070. if (newSize.w != div.clientWidth) {
  1071. div.style.width = newSize.w + 'px';
  1072. div.style.height = newSize.h + 'px';
  1073. gripper.removeAttribute('tried-exceeding');
  1074. } else if (newSize.triedExceeding) {
  1075. gripper.setAttribute('tried-exceeding', '');
  1076. }
  1077. window.getSelection().removeAllRanges();
  1078. return false;
  1079. }
  1080.  
  1081. function resizeDone(e) {
  1082. div.draggable = oldDraggable;
  1083. gripper.removeAttribute('tried-exceeding');
  1084. gripper.innerHTML = '';
  1085. document.removeEventListener('mousemove', resize);
  1086. document.removeEventListener('mouseup', resizeDone);
  1087. document.removeEventListener('keydown', resizeKeyDown);
  1088. switch (saveAs) {
  1089. case 'site':
  1090. localStorage['width#' + location.hostname] = div.clientWidth;
  1091. break;
  1092. case 'global':
  1093. pinnedWidth = div.clientWidth;
  1094. GM_setValue('pinnedWidth', pinnedWidth);
  1095. // fallthrough to remove the locally saved value
  1096. case 'reset':
  1097. localStorage.removeItem('width#' + location.hostname);
  1098. break;
  1099. case '':
  1100. return false;
  1101. }
  1102. gripper.setAttribute('saveAs', saveAs);
  1103. setTimeout(function() { gripper.removeAttribute('saveAs'); }, 250);
  1104. return false;
  1105. }
  1106.  
  1107. function resizeKeyDown(e) {
  1108. switch (e.keyCode) {
  1109. case 27: // Esc
  1110. saveAs = 'cancel';
  1111. div.style.width = oldSizeCSS.w;
  1112. div.style.height = oldSizeCSS.h;
  1113. break;
  1114. case 83: // S
  1115. saveAs = saveAs == 'site' ? 'global' : 'site';
  1116. $(gripper, '[save-as]').setAttribute('save-as', saveAs);
  1117. $(gripper, '[save-as] span').textContent = getSiteOnlyText();
  1118. return false;
  1119. case 82: // R
  1120. if (!siteSaved)
  1121. return;
  1122. saveAs = 'reset';
  1123. var size = constrainPinnedSize(div, pinnedWidth);
  1124. div.style.width = size.w;
  1125. div.style.height = size.h;
  1126. break;
  1127. default:
  1128. return;
  1129. }
  1130. document.dispatchEvent(new MouseEvent('mouseup'));
  1131. return false;
  1132. }
  1133. }
  1134. }
  1135.  
  1136. function makeDraggable(div) {
  1137. div.draggable = true;
  1138. div.addEventListener('dragstart', function(e) {
  1139. var offsetY = e.offsetY || e.clientY - div.getBoundingClientRect().top;
  1140. if (offsetY > div.clientHeight - 30)
  1141. return e.preventDefault();
  1142.  
  1143. e.dataTransfer.setData('text/plain', '');
  1144.  
  1145. var dropZone = document.createElement('div');
  1146. var dropZoneHeight = 400 / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight;
  1147. dropZone.className = 'instant-youtube-dragndrop-placeholder';
  1148.  
  1149. document.body.addEventListener('dragenter', dragHandler);
  1150. document.body.addEventListener('dragover', dragHandler);
  1151. document.body.addEventListener('dragend', dragHandler);
  1152. document.body.addEventListener('drop', dragHandler);
  1153. function dragHandler(e) {
  1154. e.stopImmediatePropagation();
  1155. e.stopPropagation();
  1156. e.preventDefault();
  1157. switch (e.type) {
  1158. case 'dragover':
  1159. var playing = div.hasAttribute('playing');
  1160. var stub = e.target.closest('.instant-youtube-container[stub]') == div.FYTE.stub && div.FYTE.stub;
  1161. var gizmo = playing && !stub
  1162. ? {left:0, top:0, right:innerWidth, bottom:innerHeight}
  1163. : (stub || div).getBoundingClientRect();
  1164. var x = e.clientX, y = e.clientY;
  1165. var cx = (gizmo.left + gizmo.right) / 2;
  1166. var cy = (gizmo.top + gizmo.bottom) / 2;
  1167. var stay = !!stub || y >= cy-200 && y <= cy+200 && x >= cx-200 && x <= cx+200;
  1168. overrideCSS(dropZone, {
  1169. top: y < cy || stay ? '0' : 'auto',
  1170. bottom: y > cy || stay ? '0' : 'auto',
  1171. left: x < cx || stay ? '0' : 'auto',
  1172. right: x > cx || stay ? '0' : 'auto',
  1173. width: playing && stay && stub ? stub.clientWidth+'px' : '400px',
  1174. height: playing && stay && stub ? stub.clientHeight+'px' : dropZoneHeight + 'px',
  1175. margin: playing && stay ? 'auto' : '0',
  1176. position: !playing && stay || stub ? 'absolute' : 'fixed',
  1177. 'background-color': stub ? 'rgba(0,0,255,0.5)' : stay ? 'rgba(255,255,0,0.4)' : 'rgba(0,255,0,0.2)',
  1178. });
  1179. adjustPinnedOffset(dropZone, div);
  1180. (stay && !playing || stub ? (stub || div) : document.body).appendChild(dropZone);
  1181. break;
  1182. case 'dragend':
  1183. case 'drop':
  1184. var corner = calcPinnedCorner(dropZone);
  1185. dropZone.remove();
  1186. dropZone = null;
  1187. document.body.removeEventListener('dragenter', dragHandler);
  1188. document.body.removeEventListener('dragover', dragHandler);
  1189. document.body.removeEventListener('dragend', dragHandler);
  1190. document.body.removeEventListener('drop', dragHandler);
  1191. if (e.type == 'dragend')
  1192. break;
  1193. if (div.hasAttribute('playing'))
  1194. (corner ? $(div, '[pin="' + corner + '"]') : div.FYTE.stub).click();
  1195. else
  1196. startPlaying(div, {pin: corner});
  1197. }
  1198. }
  1199. });
  1200. }
  1201.  
  1202. function adjustPinnedOffset(el, self, corner) {
  1203. var offset = 0;
  1204. $$('.instant-youtube-container[pinned] [pin="' + (corner || calcPinnedCorner(el)) + '"][active]').forEach(function(pin) {
  1205. var container = pin.closest('[pinned]');
  1206. if (container != el && container != self) {
  1207. var bounds = container.getBoundingClientRect();
  1208. offset = Math.max(offset, el.style.top == '0px' ? bounds.bottom : innerHeight - bounds.top);
  1209. }
  1210. });
  1211. if (offset)
  1212. el.style[el.style.top == '0px' ? 'top' : 'bottom'] = offset + 'px';
  1213. }
  1214.  
  1215. function calcPinnedCorner(el) {
  1216. var t = el.style.top != 'auto';
  1217. var b = el.style.bottom != 'auto';
  1218. var l = el.style.left != 'auto';
  1219. var r = el.style.right != 'auto';
  1220. return t && b && l && r ? '' : (t ? 'top' : 'bottom') + '-' + (l ? 'left' : 'right');
  1221. }
  1222.  
  1223. function constrainPinnedSize(div, width) {
  1224. var maxWidth = window.innerWidth - 100 |0;
  1225. var triedExceeding = (width|0) > maxWidth;
  1226. width = Math.max(200, Math.min(maxWidth, width|0));
  1227. return {
  1228. w: width,
  1229. h: width / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight,
  1230. triedExceeding: triedExceeding,
  1231. };
  1232. }
  1233.  
  1234. function showOptions(e) {
  1235. var optionsButton = e.target;
  1236. translateHTML(optionsButton, 'afterend', '\
  1237. <div class="instant-youtube-options">\
  1238. <span>\
  1239. <label tl style="width: 100% !important;">Size:&nbsp;\
  1240. <select data-action="size-mode">\
  1241. <option tl value="Original">Original\
  1242. <option tl value="Fit to width">Fit to width\
  1243. <option>360p\
  1244. <option>480p\
  1245. <option>720p\
  1246. <option>1080p\
  1247. <option tl value="Custom">Custom...\
  1248. </select>\
  1249. </label>&nbsp;\
  1250. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  1251. <input type="number" min="320" max="9999" tl-placeholder="width" data-action="width" step="1" value="' + (resizeWidth||'') + '">\
  1252. x\
  1253. <input type="number" min="240" max="9999" tl-placeholder="height" data-action="height" step="1" value="' + (resizeHeight||'') + '">\
  1254. </label>\
  1255. </span>\
  1256. <label tl="content,title" title="msgStoryboardTip">\
  1257. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  1258. msgStoryboard\
  1259. </label>\
  1260. <span>\
  1261. <label tl="content,title" title="msgDirectTip">\
  1262. <input data-action="direct" type="checkbox" ' + (playDirectly ? 'checked' : '') + '>\
  1263. msgDirect\
  1264. </label>\
  1265. &nbsp;\
  1266. <label tl="content,title" title="msgDirectTip">\
  1267. <input data-action="direct-shown" type="checkbox" ' + (playDirectlyShown ? 'checked' : '') + '>\
  1268. msgDirectShown\
  1269. </label>\
  1270. </span>\
  1271. <label tl="content,title" title="msgSafeTip">\
  1272. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  1273. msgSafe\
  1274. </label>\
  1275. <table>\
  1276. <tr>\
  1277. <td><label tl="content,title" title="msgPinningTip">msgPinning</label></td>\
  1278. <td>\
  1279. <select data-action="pinnable">\
  1280. <option tl value="on">msgPinningOn\
  1281. <option tl value="hide">msgPinningHover\
  1282. <option tl value="off">msgPinningOff\
  1283. </select>\
  1284. </td>\
  1285. </tr>\
  1286. <tr tl="title" title="msgQualityTip">\
  1287. <td><label tl="content">msgQuality</td>\
  1288. <td>\
  1289. <select data-action="quality">\
  1290. <option value="auto" tl>msgQualityAuto\
  1291. <option value="tiny">144p\
  1292. <option value="small">240p\
  1293. <option value="medium">360p\
  1294. <option value="large">480p\
  1295. <option value="hd720">720p\
  1296. <option value="hd1080">1080p\
  1297. <option value="hd1440">1440p\
  1298. <option value="hd2160">2160p (4K)\
  1299. <option value="hd2880">2880p (5K)\
  1300. <option value="highres">4320p (8K)\
  1301. </select>\
  1302. </td>\
  1303. </tr>\
  1304. </table>\
  1305. <span data-action="buttons">\
  1306. <button tl data-action="ok">OK</button>\
  1307. <button tl data-action="cancel">Cancel</button>\
  1308. </span>\
  1309. </div>\
  1310. ');
  1311. var options = optionsButton.nextElementSibling;
  1312.  
  1313. options.addEventListener('keydown', function(e) {
  1314. if (e.target.localName == 'input' &&
  1315. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  1316. return false;
  1317. });
  1318.  
  1319. $(options, '[data-action="size-mode"]').value = resizeMode;
  1320. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  1321. var v = this.value != 'Custom';
  1322. var e = $(options, '[data-action="size-custom"]');
  1323. e.children[0].disabled = e.children[1].disabled = v;
  1324. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  1325. });
  1326.  
  1327. $(options, '[data-action="pinnable"]').value = pinnable;
  1328.  
  1329. $(options, '[data-action="quality"]').value = playQuality;
  1330.  
  1331. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  1332. if (e.target.dataset.action != 'ok') {
  1333. options.remove();
  1334. return;
  1335. }
  1336. var v, shouldAdjust;
  1337. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  1338. GM_setValue('resize', resizeMode = v);
  1339. shouldAdjust = true;
  1340. }
  1341. if (resizeMode == 'Custom') {
  1342. var w = $(options, '[data-action="width"]').value |0;
  1343. var h = $(options, '[data-action="height"]').value |0;
  1344. if (resizeWidth != w || resizeHeight != h) {
  1345. updateCustomSize(w, h);
  1346. GM_setValue('width', resizeWidth);
  1347. GM_setValue('height', resizeHeight);
  1348. shouldAdjust = true;
  1349. }
  1350. }
  1351. if (showStoryboard != (v = $(options, '[data-action="storyboard"]').checked)) {
  1352. GM_setValue('showStoryboard', showStoryboard = v);
  1353. $$('.instant-youtube-container').forEach(updateHoverHandler);
  1354. }
  1355. if (playDirectly != (v = $(options, '[data-action="direct"]').checked)) {
  1356. GM_setValue('playHTML5', playDirectly = v);
  1357. if (playDirectlyShown) {
  1358. var newAltText = _(playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)');
  1359. $$('.instant-youtube-alternative').forEach(function(e) {
  1360. e.textContent = newAltText;
  1361. });
  1362. }
  1363. }
  1364. if (playDirectlyShown != (v = $(options, '[data-action="direct-shown"]').checked)) {
  1365. GM_setValue('playHTML5', playDirectlyShown = v);
  1366. updateAltPlayerCSS();
  1367. }
  1368. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  1369. GM_setValue('skipCustom', skipCustom = v);
  1370. }
  1371. if (pinnable != (v = $(options, '[data-action="pinnable"]').value)) {
  1372. GM_setValue('pinnable', pinnable = v);
  1373. }
  1374. if (playQuality != (v = $(options, '[data-action="quality"]').value)) {
  1375. GM_setValue('quality', playQuality = v);
  1376. }
  1377.  
  1378. options.remove();
  1379.  
  1380. if (shouldAdjust)
  1381. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  1382. });
  1383. }
  1384.  
  1385. function updateCustomSize(w, h) {
  1386. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  1387. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  1388. }
  1389.  
  1390. function updateAltPlayerCSS() {
  1391. var s = '.instant-youtube-alternative { display:' + (playDirectlyShown ? 'block' : 'none') + '!important}';
  1392. $('style#instant-youtube-styles').textContent += s;
  1393. return s;
  1394. }
  1395.  
  1396. function important(cssText) {
  1397. return cssText.replace(/;/g, '!important;');
  1398. }
  1399.  
  1400. function tryCatch(func) {
  1401. try {
  1402. return func();
  1403. } catch(e) {
  1404. console.log(e);
  1405. }
  1406. }
  1407.  
  1408. function getFunctionComment(fn) {
  1409. return fn.toString().match(/\/\*([\s\S]*?)\*\/\s*\}$/)[1];
  1410. }
  1411.  
  1412. function $(selORnode, sel) {
  1413. return sel ? selORnode.querySelector(sel)
  1414. : document.querySelector(selORnode);
  1415. }
  1416.  
  1417. function $$(selORnode, sel) {
  1418. return Array.prototype.slice.call(
  1419. sel ? selORnode.querySelectorAll(sel)
  1420. : document.querySelectorAll(selORnode));
  1421. }
  1422.  
  1423. function $$remove(selORnode, sel) {
  1424. Array.prototype.forEach.call(
  1425. sel ? selORnode.querySelectorAll(sel)
  1426. : document.querySelectorAll(selORnode),
  1427. function(e) { e.remove() }
  1428. );
  1429. }
  1430.  
  1431. function overrideCSS(e, params) {
  1432. var names = Object.keys(params);
  1433. var style = e.style.cssText.replace(new RegExp('(^|\s|;)(' + names.join('|') + ')(:[^;]+)', 'gi'), '$1');
  1434. e.style.cssText = style.replace(/[^;]\s*$/, '$&;').replace(/^\s*;\s*/, '') +
  1435. names.map(function(n) { return n + ':' + params[n] + '!important' }).join(';') + ';';
  1436. }
  1437.  
  1438. // fix dumb Firefox bug
  1439. function floatPadding(node, style, dir) {
  1440. var padding = style['padding' + dir];
  1441. if (padding.indexOf('%') < 0)
  1442. return parseFloat(padding);
  1443. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  1444. }
  1445.  
  1446. function cleanupCache() {
  1447. GM_listValues().forEach(function(k) {
  1448. if (k.lastIndexOf('cache-', 0) == 0
  1449. && Date.now() - Number((tryJSONparse(GM_getValue(k)) || {}).lastUsed || 0) > CACHE_STALE_DURATION) {
  1450. GM_deleteValue(k);
  1451. }
  1452. });
  1453. }
  1454.  
  1455. function tryJSONparse(s) {
  1456. try { return JSON.parse(s) }
  1457. catch (e) {}
  1458. }
  1459.  
  1460. function translateHTML(baseElement, place, html) {
  1461. var tmp = document.createElement('div');
  1462. tmp.innerHTML = html;
  1463. $$(tmp, '[tl]').forEach(function(node) {
  1464. (node.getAttribute('tl') || 'content').split(',').forEach(function(what) {
  1465. var child, src, tl;
  1466. if (what == 'content') {
  1467. for (var i = node.childNodes.length-1, n; (i>=0) && (n=node.childNodes[i]); i--) {
  1468. if (n.nodeType == Node.TEXT_NODE && n.textContent.trim()) {
  1469. child = n;
  1470. break;
  1471. }
  1472. }
  1473. } else
  1474. child = node.getAttributeNode(what);
  1475. if (!child)
  1476. return;
  1477. src = child.textContent;
  1478. srcTrimmed = src.trim();
  1479. tl = src.replace(srcTrimmed, _(srcTrimmed));
  1480. if (src != tl)
  1481. child.textContent = tl;
  1482. });
  1483. });
  1484. baseElement.insertAdjacentHTML(place, tmp.innerHTML);
  1485. }
  1486.  
  1487. function initTL(src) {
  1488. var tlSource = {
  1489. 'watch on Youtube': {
  1490. 'ru': 'открыть на Youtube',
  1491. },
  1492. 'Play with Youtube player': {
  1493. 'ru': 'Включить плеер Youtube',
  1494. },
  1495. 'Play directly (up to 720p)': {
  1496. 'ru': 'Включить напрямую (макс. 720p)',
  1497. },
  1498. msgAltPlayerHint: {
  1499. 'en': 'Shift-click to use alternative player',
  1500. 'ru': 'Shift-клик для смены типа плеера',
  1501. },
  1502. 'Options': {
  1503. 'ru': 'Опции',
  1504. },
  1505. 'Size:': {
  1506. 'ru': 'Размер:',
  1507. },
  1508. 'Original': {
  1509. 'ru': 'Исходный',
  1510. },
  1511. 'Fit to width': {
  1512. 'ru': 'На всю ширину',
  1513. },
  1514. 'Custom...': {
  1515. 'ru': 'Настроить...',
  1516. },
  1517. 'width': {
  1518. 'ru': 'ширина',
  1519. },
  1520. 'height': {
  1521. 'ru': 'высота',
  1522. },
  1523. msgStoryboard: {
  1524. 'en': 'Storyboard thumbnails on hover',
  1525. 'ru': 'Раскадровка при наведении курсора',
  1526. },
  1527. msgStoryboardTip: {
  1528. 'en': 'Show storyboard preview on mouse hover at the bottom',
  1529. 'ru': 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1530. },
  1531. msgDirect: {
  1532. 'en': 'Play directly',
  1533. 'ru': 'Встроенный плеер браузера',
  1534. },
  1535. msgDirectTip: {
  1536. 'en': 'Note: Shift-click a thumbnail to use alternative player',
  1537. 'ru': 'Напоминание: удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1538. },
  1539. msgDirectShown: {
  1540. 'en': 'Show under play button',
  1541. 'ru': 'Показывать под кнопкой ►',
  1542. },
  1543. msgSafe: {
  1544. 'en': 'Safe (skip videos with enablejsapi=1)',
  1545. 'ru': 'Консервативный режим',
  1546. },
  1547. msgSafeTip: {
  1548. 'en': 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)',
  1549. 'ru': 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 (подействует после обновления страницы)',
  1550. },
  1551. msgPinning: {
  1552. 'en': 'Corner pinning',
  1553. 'ru': 'Закрепление по углам',
  1554. },
  1555. msgPinningTip: {
  1556. 'en': 'Enable corner pinning controls when a video is playing. \nTo restore the video click the active corner pin or the original video placeholder.',
  1557. 'ru': 'Включить шпильки по углам для закрепления видео во время просмотра. \nДля отмены можно нажать еще раз на активированный уголЪ или на заглушку, где исходно было видео',
  1558. },
  1559. msgPinningOn: {
  1560. 'en': 'On',
  1561. 'ru': 'Да',
  1562. },
  1563. msgPinningHover: {
  1564. 'en': 'On, hover a corner to show',
  1565. 'ru': 'Да, при наведении курсора',
  1566. },
  1567. msgPinningOff: {
  1568. 'en': 'Off',
  1569. 'ru': 'Нет',
  1570. },
  1571. msgQuality: {
  1572. 'en': 'Youtube quality',
  1573. 'ru': 'Качество youtube',
  1574. },
  1575. msgQualityTip: {
  1576. 'en': 'Youtube player video quality',
  1577. 'ru': 'Качество видео в youtube-плеере',
  1578. },
  1579. msgQualityAuto: {
  1580. 'en': 'auto',
  1581. 'ru': 'не выбрано',
  1582. },
  1583. 'OK': {
  1584. 'ru': 'ОК',
  1585. },
  1586. 'Cancel': {
  1587. 'ru': 'Оменить',
  1588. },
  1589. };
  1590. var browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1591. var browserLangMajor = browserLang.replace(/-.+/, '');
  1592. var tl = {};
  1593. Object.keys(tlSource).forEach(function(k) {
  1594. var langs = tlSource[k];
  1595. var text = langs[browserLang] || langs[browserLangMajor];
  1596. if (text)
  1597. tl[k] = text;
  1598. });
  1599. return function(src) { return tl[src] || src };
  1600. }
  1601.  
  1602. function injectStylesIfNeeded(force) {
  1603. if (!fytedom[0] && !force)
  1604. return;
  1605. var styledom = $('style#instant-youtube-styles');
  1606. if (styledom) {
  1607. // move our rules to the end of HEAD to increase CSS specificity
  1608. if (styledom.nextElementSibling && document.head)
  1609. document.head.insertBefore(styledom, null);
  1610. return;
  1611. }
  1612. styledom = (document.head || document.documentElement).appendChild(document.createElement('style'));
  1613. styledom.id = 'instant-youtube-styles';
  1614. styledom.textContent = important(getFunctionComment(function() { /*
  1615. .instant-youtube-container,
  1616. .instant-youtube-container * {
  1617. transform: translate3D(0,0,0);
  1618. }
  1619. .instant-youtube-container {
  1620. all: unset;
  1621. contain: strict;
  1622. display: block;
  1623. position: relative;
  1624. overflow: hidden;
  1625. cursor: pointer;
  1626. padding: 0;
  1627. margin: auto;
  1628. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1629. text-align: center;
  1630. background: black;
  1631. break-inside: avoid-column;
  1632. }
  1633. .instant-youtube-container[disabled] {
  1634. background: #888;
  1635. }
  1636. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1637. display: none;
  1638. }
  1639. .instant-youtube-container[pinned] {
  1640. box-shadow: 0 0 30px black;
  1641. }
  1642. .instant-youtube-container[playing] {
  1643. contain: none;
  1644. }
  1645. .instant-youtube-wrapper {
  1646. width: 100%;
  1647. height: 100%;
  1648. }
  1649. .instant-youtube-play-button {
  1650. display: block;
  1651. position: absolute;
  1652. width: 85px;
  1653. height: 60px;
  1654. left: 0;
  1655. right: 0;
  1656. top: 0;
  1657. bottom: 0;
  1658. margin: auto;
  1659. }
  1660. .instant-youtube-loading-spinner {
  1661. display: block;
  1662. position: absolute;
  1663. width: 20px;
  1664. height: 20px;
  1665. left: 0;
  1666. right: 0;
  1667. top: 0;
  1668. bottom: 0;
  1669. padding: 0;
  1670. margin: auto;
  1671. pointer-events: none;
  1672. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1673. }
  1674. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1675. fill: #CC181E;
  1676. }
  1677. .instant-youtube-alternative {
  1678. display: block;
  1679. position: absolute;
  1680. width: 20em;
  1681. height: 20px;
  1682. top: 50%;
  1683. left: 0;
  1684. right: 0;
  1685. margin: 60px auto;
  1686. padding: 0;
  1687. border: none;
  1688. text-align: center;
  1689. text-decoration: none;
  1690. text-shadow: 1px 1px 3px black;
  1691. font-weight: bold;
  1692. color: white;
  1693. z-index: 8;
  1694. font-weight: normal;
  1695. font-size: 12px;
  1696. }
  1697. .instant-youtube-alternative:hover {
  1698. text-decoration: underline;
  1699. color: white;
  1700. background: transparent;
  1701. }
  1702. .instant-youtube-embed {
  1703. z-index: 10;
  1704. background: transparent;
  1705. }
  1706. .instant-youtube-title {
  1707. z-index: 20;
  1708. display: block;
  1709. position: absolute;
  1710. width: auto;
  1711. top: 0;
  1712. left: 0;
  1713. right: 0;
  1714. margin: 0;
  1715. padding: 7px;
  1716. border: none;
  1717. text-shadow: 1px 1px 2px black;
  1718. text-align: center;
  1719. text-decoration: none;
  1720. color: white;
  1721. background-color: rgba(0, 0, 0, 0.5);
  1722. }
  1723. .instant-youtube-title strong {
  1724. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1725. }
  1726. .instant-youtube-title strong:after {
  1727. content: " - $tl:'watch on Youtube'";
  1728. font-weight: normal;
  1729. margin-right: 1ex;
  1730. }
  1731. .instant-youtube-title span {
  1732. color: inherit;
  1733. }
  1734. .instant-youtube-title span:before {
  1735. content: "(";
  1736. }
  1737. .instant-youtube-title span:after {
  1738. content: ")";
  1739. }
  1740. .instant-youtube-container .instant-youtube-title i {
  1741. all: unset;
  1742. opacity: .5;
  1743. font-style: normal;
  1744. color: white;
  1745. }
  1746. @-webkit-keyframes instant-youtube-fadein {
  1747. from { opacity: 0 }
  1748. to { opacity: 1 }
  1749. }
  1750. @-moz-keyframes instant-youtube-fadein {
  1751. from { opacity: 0 }
  1752. to { opacity: 1 }
  1753. }
  1754. @keyframes instant-youtube-fadein {
  1755. from { opacity: 0 }
  1756. to { opacity: 1 }
  1757. }
  1758. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1759. display: none;
  1760. margin: 0;
  1761. }
  1762. .instant-youtube-title:hover {
  1763. text-decoration: underline;
  1764. }
  1765. .instant-youtube-title strong {
  1766. color: white;
  1767. }
  1768. .instant-youtube-options-button {
  1769. opacity: 0.6;
  1770. position: absolute;
  1771. right: 0;
  1772. bottom: 0;
  1773. margin: 0;
  1774. padding: 1.5ex 2ex;
  1775. font-size: 11px;
  1776. text-shadow: 1px 1px 2px black;
  1777. color: white;
  1778. }
  1779. .instant-youtube-options-button:hover {
  1780. opacity: 1;
  1781. background: rgba(0, 0, 0, 0.5);
  1782. }
  1783. .instant-youtube-options {
  1784. display: flex;
  1785. position: absolute;
  1786. right: 0;
  1787. bottom: 0;
  1788. margin: 0;
  1789. padding: 1ex 1ex 2ex 2ex;
  1790. flex-direction: column;
  1791. align-items: flex-start;
  1792. line-height: 1.5;
  1793. text-align: left;
  1794. opacity: 1;
  1795. color: white;
  1796. background: black;
  1797. z-index: 999;
  1798. }
  1799. .instant-youtube-options * {
  1800. width: auto;
  1801. height: auto;
  1802. margin: 0;
  1803. padding: 0;
  1804. font: inherit;
  1805. font-size: 13px;
  1806. vertical-align: middle;
  1807. text-transform: none;
  1808. text-align: left;
  1809. border-radius: 0;
  1810. text-decoration: none;
  1811. color: white;
  1812. background: black;
  1813. }
  1814. .instant-youtube-options > * {
  1815. margin-top: 1ex;
  1816. }
  1817. .instant-youtube-options table {
  1818. all: unset;
  1819. display: table;
  1820. }
  1821. .instant-youtube-options tr {
  1822. all: unset;
  1823. display: table-row;
  1824. }
  1825. .instant-youtube-options td {
  1826. all: unset;
  1827. display: table-cell;
  1828. padding: 2px;
  1829. }
  1830. .instant-youtube-options label > * {
  1831. display: inline;
  1832. }
  1833. .instant-youtube-options select {
  1834. padding: .5ex .25ex;
  1835. border: 1px solid #444;
  1836. -webkit-appearance: menulist;
  1837. }
  1838. .instant-youtube-options [data-action="size-custom"] input {
  1839. width: 9ex;
  1840. padding: .5ex .5ex .4ex;
  1841. border: 1px solid #666;
  1842. }
  1843. .instant-youtube-options [data-action="buttons"] {
  1844. margin-top: 1em;
  1845. }
  1846. .instant-youtube-options button {
  1847. margin: 0 1ex 0 0;
  1848. padding: .5ex 2ex;
  1849. border: 2px solid gray;
  1850. font-weight: bold;
  1851. }
  1852. .instant-youtube-options button:hover {
  1853. border-color: white;
  1854. }
  1855. .instant-youtube-options label[disabled] {
  1856. opacity: 0.25;
  1857. }
  1858. .instant-youtube-storyboard {
  1859. height: 33%;
  1860. max-height: 90px;
  1861. display: block;
  1862. position: absolute;
  1863. left: 0;
  1864. right: 0;
  1865. bottom: 0;
  1866. overflow: visible;
  1867. overflow-x: visible;
  1868. overflow-y: visible;
  1869. }
  1870. .instant-youtube-storyboard:hover {
  1871. background-color: rgba(0,0,0,0.3);
  1872. }
  1873. .instant-youtube-storyboard[disabled] {
  1874. display:none;
  1875. }
  1876. .instant-youtube-storyboard div {
  1877. display: block;
  1878. position: absolute;
  1879. bottom: 0px;
  1880. pointer-events: none;
  1881. border: 3px solid #888;
  1882. box-shadow: 2px 2px 10px black;
  1883. transition: opacity .25s ease;
  1884. background-color: transparent;
  1885. background-origin: content-box;
  1886. opacity: 0;
  1887. }
  1888. .instant-youtube-storyboard:hover div {
  1889. opacity: 1;
  1890. }
  1891. .instant-youtube-container [pin] {
  1892. position: absolute;
  1893. width: 0;
  1894. height: 0;
  1895. margin: 0;
  1896. padding: 0;
  1897. top: auto; bottom: auto; left: auto; right: auto;
  1898. border-style: solid;
  1899. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  1900. opacity: 0;
  1901. z-index: 100;
  1902. }
  1903. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  1904. opacity: 1;
  1905. }
  1906. .instant-youtube-container[playing] [pin]:hover {
  1907. cursor: alias;
  1908. opacity: 1;
  1909. transition: opacity 0s;
  1910. }
  1911. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  1912. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  1913. .instant-youtube-container [pin=top-left] {
  1914. top: 0; left: 0;
  1915. border-width: 10px 10px 0 0;
  1916. border-color: red transparent transparent transparent;
  1917. }
  1918. .instant-youtube-container [pin=top-left][transparent] {
  1919. border-width: 10px 10px 0 0;
  1920. }
  1921. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  1922. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  1923. .instant-youtube-container [pin=top-right] {
  1924. top: 0; right: 0;
  1925. border-width: 0 10px 10px 0;
  1926. border-color: transparent red transparent transparent;
  1927. }
  1928. .instant-youtube-container [pin=top-right][transparent] {
  1929. border-width: 0 10px 10px 0;
  1930. }
  1931. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  1932. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  1933. .instant-youtube-container [pin=bottom-right] {
  1934. bottom: 0; right: 0;
  1935. border-width: 0 0 10px 10px;
  1936. border-color: transparent transparent red transparent;
  1937. }
  1938. .instant-youtube-container [pin=bottom-right][transparent] {
  1939. border-width: 0 0 10px 10px;
  1940. }
  1941. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  1942. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  1943. .instant-youtube-container [pin=bottom-left] {
  1944. bottom: 0; left: 0;
  1945. border-width: 10px 0 0 10px;
  1946. border-color: transparent transparent transparent red;
  1947. }
  1948. .instant-youtube-container [pin=bottom-left][transparent] {
  1949. border-width: 10px 0 0 10px;
  1950. }
  1951. .instant-youtube-dragndrop-placeholder {
  1952. z-index: 999999999;
  1953. margin: 0;
  1954. padding: 0;
  1955. background: rgba(0, 255, 0, 0.1);
  1956. border: 2px dotted green;
  1957. box-sizing: border-box;
  1958. pointer-events: none;
  1959. }
  1960. .instant-youtube-container [size-gripper] {
  1961. width: 0;
  1962. position: absolute;
  1963. top: 0;
  1964. bottom: 0;
  1965. cursor: e-resize;
  1966. border-color: rgba(50,100,255,0.5);
  1967. border-width: 12px;
  1968. background: rgba(50,100,255,0.2);
  1969. z-index: 99;
  1970. opacity: 0;
  1971. transition: opacity .1s ease-in-out, border-color .1s ease-in-out;
  1972. }
  1973. .instant-youtube-container[pinned*="right"] [size-gripper] {
  1974. border-style: none none none solid;
  1975. left: -4px;
  1976. }
  1977. .instant-youtube-container[pinned*="left"] [size-gripper] {
  1978. border-style: none solid none none;
  1979. right: -4px;
  1980. }
  1981. .instant-youtube-container [size-gripper]:hover {
  1982. opacity: 1;
  1983. }
  1984. .instant-youtube-container [size-gripper]:active {
  1985. opacity: 1;
  1986. width: auto;
  1987. left: -4px;
  1988. right: -4px;
  1989. }
  1990. .instant-youtube-container [size-gripper][tried-exceeding] {
  1991. border-color: rgba(255,0,0,0.5);
  1992. }
  1993. .instant-youtube-container [size-gripper][saveAs="global"] {
  1994. border-color: rgba(0,255,0,0.5);
  1995. }
  1996. .instant-youtube-container [size-gripper][saveAs="site"] {
  1997. border-color: rgba(0,255,255,0.5);
  1998. }
  1999. .instant-youtube-container [size-gripper][saveAs="reset"] {
  2000. border-color: rgba(255,255,0,0.5);
  2001. }
  2002. .instant-youtube-container [size-gripper][saveAs="cancel"] {
  2003. border-color: rgba(255,0,255,0.25);
  2004. }
  2005. .instant-youtube-container [size-gripper] > div {
  2006. white-space: nowrap;
  2007. color: white;
  2008. font-weight: normal;
  2009. line-height: 1.25;
  2010. text-align: left;
  2011. position: absolute;
  2012. top: 50%;
  2013. padding: 1ex 1em 1ex;
  2014. background-color: rgba(80,150,255,0.5);
  2015. }
  2016. .instant-youtube-container [size-gripper] [save-as="site"] {
  2017. font-weight: bold;
  2018. color: yellow;
  2019. }
  2020. .instant-youtube-container[pinned*="left"] [size-gripper] > div {
  2021. right: 0;
  2022. }
  2023. */}).replace(/\$tl:'(.+?)'/g, function(m, m1) { return _(m1) })
  2024. ) +
  2025. updateAltPlayerCSS();
  2026. }