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.

当前为 2018-10-20 提交的版本,查看 最新版本

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