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.

当前为 2020-01-30 提交的版本,查看 最新版本

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