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.

当前为 2019-06-18 提交的版本,查看 最新版本

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