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-08-12 提交的版本,查看 最新版本

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