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. A fast simple HTML5 direct playback (720p max) can be selected if available for the video.
  4. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. // @version 2.5.6
  6. // @include *
  7. // @exclude https://www.youtube.com/*
  8. // @author wOxxOm
  9. // @namespace wOxxOm.scripts
  10. // @license MIT License
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_addStyle
  14. // @grant GM_xmlhttpRequest
  15. // @connect www.youtube.com
  16. // @connect youtube.com
  17. // @run-at document-start
  18. // @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=
  19. // @compatible chrome
  20. // @compatible firefox
  21. // @compatible opera
  22. // ==/UserScript==
  23.  
  24. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  25.  
  26. var resizeMode = GM_getValue('resize', 'Fit to width');
  27. if (typeof resizeMode != 'string')
  28. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  29.  
  30. var resizeWidth = GM_getValue('width', 1280) |0;
  31. var resizeHeight = GM_getValue('height', 720) |0;
  32. updateCustomSize();
  33.  
  34. var playDirectly = !!GM_getValue('playHTML5', false);
  35. var skipCustom = !!GM_getValue('skipCustom', true);
  36. var showStoryboard = !!GM_getValue('showStoryboard', true);
  37. var pinnable = GM_getValue('pinnable', 'on');
  38. if (!/^(on|hide|off)$/.test(pinnable))
  39. pinnable = !!pinnable ? 'on' : 'hide';
  40.  
  41. var _ = initTL();
  42.  
  43. var imageLoader = document.createElement('img');
  44. var imageLoader2 = document.createElement('img');
  45.  
  46. var fytedom = document.getElementsByClassName('instant-youtube-container');
  47. var iframes = document.getElementsByTagName('iframe');
  48. var oembeds = document.getElementsByTagName('embed');
  49. var persite = (function() {
  50. var rules = [
  51. {host: /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/, class:'g-blk', query: 'a[href*="youtube.com/watch"][data-ved]', eatparent: 1},
  52. {host: 'pikabu.ru', class:'b-video', match: '[data-url*="youtube.com/embed"]', attr: 'data-url'},
  53. {host: 'androidauthority.com', tag:'iframe', match: '[src*="youtube.com/embed"]', eatparent: '.video-container'},
  54. {host: 'reddit.com', tag:'iframe',
  55. match: '[data-url*="youtube.com/"] [src*="/mediaembed"], [data-url*="youtu.be/"] [src*="/mediaembed"]',
  56. src: function(e) { return e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url }},
  57. ];
  58. for (var i=0, rule; (i<rules.length) && (rule=rules[i]); i++) {
  59. var rx = rule.host instanceof RegExp ? rule.host : new RegExp('(^|\\.)' + rule.host.replace(/\./g, '\\.') + '$', 'i');
  60. if (rx.test(location.hostname))
  61. return {
  62. nodes: rule.class ? document.getElementsByClassName(rule.class) : document.getElementsByTagName(rule.tag),
  63. match: rule.match ? function(e) { return e.matches(rule.match) ? e : null }
  64. : function(e) { return e.querySelector(rule.query) },
  65. attr: rule.attr,
  66. src: rule.src,
  67. eatparent: rule.eatparent,
  68. };
  69. }
  70. })();
  71.  
  72. findEmbeds();
  73. injectStylesIfNeeded();
  74. new MutationObserver(findEmbeds).observe(document, {subtree:true, childList:true});
  75.  
  76. document.addEventListener('DOMContentLoaded', function(e) {
  77. injectStylesIfNeeded();
  78. adjustNodesIfNeeded(e);
  79. });
  80. window.addEventListener('resize', adjustNodesIfNeeded, true);
  81. window.addEventListener('message', function(e) {
  82. if (e.data == 'iframe-allowfs') {
  83. $$('iframe:not([allowfullscreen])').some(function(iframe) {
  84. if (iframe.contentWindow == e.source) {
  85. iframe.allowFullscreen = true;
  86. return true;
  87. }
  88. });
  89. if (window != window.top)
  90. window.parent.postMessage('iframe-allowfs', '*');
  91. }
  92. });
  93.  
  94. function findEmbeds(mutations) {
  95. var i, len, e;
  96. if (mutations && mutations.length == 1 && !mutations[0].addedNodes.length)
  97. return;
  98. if (persite)
  99. for (i=0, len=persite.nodes.length; (i<len) && (e=persite.nodes[i]); i++)
  100. if (e = persite.match(e))
  101. processEmbed(e, persite.src && persite.src(e) || e.getAttribute(persite.attr));
  102. for (i=0, len=iframes.length; (i<len) && (e=iframes[i]); i++)
  103. if (/youtube\.com(\/|%2F)(embed|v)(\/|%2F)/i.test(e.src))
  104. processEmbed(e);
  105. for (i=0, len=oembeds.length; (i<len) && (e=oembeds[i]); i++)
  106. if (/youtube\.com(\/|%2F)(embed|v)\//i.test(e.src))
  107. processEmbed(e);
  108. }
  109.  
  110. function processEmbed(node, src) {
  111. function decodeEmbedUrl(url) {
  112. return url.indexOf('youtube.com%2Fembed') > 0
  113. ? decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube.com%2Fembed[^&]+).*$/i, '$1'))
  114. : url;
  115. }
  116. src = src || node.src || node.href || '';
  117. var n = node;
  118. var np = n.parentNode, npw;
  119. var srcFixed = decodeEmbedUrl(src).replace(/\/(watch\?v=|v\/)/, '/embed/');
  120. if (src.indexOf('cdn.embedly.com/') > 0 ||
  121. resizeMode != 'Original' && np && np.children.length == 1 && !np.className && !np.id)
  122. {
  123. n = location.hostname == 'disqus.com' ? np.parentNode : np;
  124. np = n.parentElement;
  125. }
  126. if (!np ||
  127. !np.parentNode ||
  128. skipCustom && srcFixed.indexOf('enablejsapi=1') > 0 ||
  129. node.matches('.instant-youtube-embed, .YTLT-embed') ||
  130. node.onload // skip some retarded loaders
  131. )
  132. return;
  133.  
  134. var id = srcFixed.match(/(?:embed\/|v[=\/]|youtu\.be\/)([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  135. if (!id)
  136. return;
  137. id = id[1];
  138.  
  139. var autoplay = srcFixed.indexOf('autoplay=1') > 0;
  140.  
  141. if (np.localName == 'object')
  142. n = np, np = n.parentElement;
  143.  
  144. var eatparent = persite && persite.eatparent || 0;
  145. if (typeof eatparent == 'string')
  146. n = np.closest(eatparent) || n, np = n.parentElement;
  147. else
  148. while (eatparent--)
  149. n = np, np = n.parentElement;
  150.  
  151. injectStylesIfNeeded('force');
  152.  
  153. var div = document.createElement('div');
  154. div.className = 'instant-youtube-container';
  155. div.FYTE = {
  156. state: 'querying',
  157. srcEmbed: srcFixed.replace(/&$/, ''),
  158. videoID: id,
  159. originalWidth: /%/.test(node.width) ? 320 : node.width|0 || n.clientWidth|0,
  160. originalHeight: /%/.test(node.height) ? 200 : node.height|0 || n.clientHeight|0,
  161. };
  162. div.FYTE.srcEmbedFixed = div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace(/&?wmode=\w+/, '').replace(/[?&]feature=oembed/, '');
  163. div.FYTE.srcWatchFixed = div.FYTE.srcEmbedFixed.replace(/\/embed\//, '/watch?v=');
  164.  
  165. var divSize = calcContainerSize(div, n);
  166. var origStyle = getComputedStyle(n);
  167. div.style.cssText = important('background-color:transparent; transition:background-color 2s;' +
  168. (origStyle.hasOwnProperty('position') ? Object.keys(origStyle) : Object.keys(origStyle.__proto__) /*FF*/)
  169. .filter(function(k) { return !!k.match(/^(position|left|right|top|bottom)$/) })
  170. .map(function(k) { return k + ':' + origStyle[k] })
  171. .join(';')
  172. .replace(/\b[^;:]+:\s*(auto|static|block)\s*(!\s*important)?;/g, '') +
  173. (origStyle.display == 'inline' ? ';display:inline-block;width:100%' : '') +
  174. ';min-width:' + Math.min(divSize.w, div.FYTE.originalWidth) + 'px' +
  175. ';min-height:' + Math.min(divSize.h, div.FYTE.originalHeight) + 'px' +
  176. (resizeMode == 'Fit to width' ? ';width:100%' : '') +
  177. ';max-width:' + divSize.w + 'px; height:' + divSize.h + 'px;');
  178. if (!autoplay) {
  179. setTimeout(function() { div.style.backgroundColor = '' }, 0);
  180. setTimeout(function() { div.style.transition = '' }, 2000);
  181. }
  182.  
  183. // consume parents of retardedly positioned videos
  184. if (div.style.position.match('absolute|relative')) {
  185. if (np.children.length == 1 && floatPadding(np, getComputedStyle(np, ':after'), 'Top') >= div.FYTE.originalHeight)
  186. n = np, np = n.parentElement;
  187. div.style.cssText = div.style.cssText.replace(/\b(position|left|top|right|bottom):[^;]+/g, '');
  188. }
  189.  
  190. var wrapper = div.appendChild(document.createElement('div'));
  191. wrapper.className = 'instant-youtube-wrapper';
  192.  
  193. var img = wrapper.appendChild(document.createElement('img'));
  194. img.className = 'instant-youtube-thumbnail';
  195. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  196. img.style.cssText = important('transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0; max-width:none; max-height:none;');
  197.  
  198. img.title = _('Shift-click to use alternative player');
  199. img.onload = function(e) {
  200. if (img.naturalWidth <= 120)
  201. return img.onerror(e);
  202. var fitToWidth = true;
  203. if (img.naturalHeight) {
  204. var ratio = img.naturalWidth / img.naturalHeight;
  205. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  206. img.style.cssText += important('width:auto; height:100%;');
  207. fitToWidth = false;
  208. }
  209. }
  210. if (fitToWidth) {
  211. img.style.cssText += important('width:100%; height:auto;');
  212. }
  213. if (div.FYTE.videoWidth)
  214. fixThumbnailAR(div);
  215. if (!autoplay)
  216. img.style.opacity = 1;
  217. };
  218. img.onerror = function(e) {
  219. if (img.src.indexOf('maxresdefault') > 0)
  220. img.src = img.src.replace('maxresdefault','hqdefault');
  221. };
  222.  
  223. GM_xmlhttpRequest({
  224. method: 'GET',
  225. url: 'https://www.youtube.com/get_video_info?video_id=' + div.FYTE.videoID + '&el=detailpage',
  226. headers: {'Accept-Encoding': 'gzip'},
  227. context: div,
  228. onload: parseVideoInfo
  229. });
  230.  
  231. translateHTML(wrapper, 'beforeend', '\
  232. <a class="instant-youtube-title" target="_blank" href="' + div.FYTE.srcWatchFixed + '">&nbsp;</a>\
  233. <svg class="instant-youtube-play-button"><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"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>\
  234. <span tl class="instant-youtube-link">' + (playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  235. <div tl class="instant-youtube-options-button">Options</div>\
  236. ');
  237.  
  238. np.insertBefore(div, n);
  239. n.remove();
  240.  
  241. if (autoplay)
  242. return startPlaying(div);
  243.  
  244. div.addEventListener('click', clickHandler);
  245. }
  246.  
  247. function adjustNodesIfNeeded(e) {
  248. if (!fytedom.length)
  249. return;
  250. if (adjustNodesIfNeeded.scheduled)
  251. clearTimeout(adjustNodesIfNeeded.scheduled);
  252. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  253. adjustNodes(e);
  254. adjustNodesIfNeeded.scheduled = 0;
  255. }, 16);
  256. }
  257.  
  258. function adjustNodes(e, clickedContainer) {
  259. var force = !!clickedContainer;
  260. var nearest = force ? clickedContainer : null;
  261.  
  262. var vids = $$('.instant-youtube-container:not([pinned])');
  263.  
  264. if (!nearest && e.type != 'DOMContentLoaded') {
  265. var minDistance = window.innerHeight*3/4 |0;
  266. var nearTargetY = window.innerHeight/2;
  267. vids.forEach(function(n) {
  268. var bounds = n.getBoundingClientRect();
  269. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  270. if (distance < minDistance) {
  271. minDistance = distance;
  272. nearest = n;
  273. }
  274. });
  275. }
  276.  
  277. if (nearest) {
  278. var bounds = nearest.getBoundingClientRect();
  279. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  280. }
  281.  
  282. var resized = false;
  283.  
  284. vids.forEach(function(n) {
  285. var size = calcContainerSize(n);
  286. var w = size.w, h = size.h;
  287.  
  288. // prevent parent clipping
  289. for (var e=n.parentElement, style; e; e=e.parentElement)
  290. if (e.style.overflow != 'visible' && (style=getComputedStyle(e)))
  291. if ((style.overflow+style.overflowX+style.overflowY).match(/hidden|scroll/))
  292. if (n.offsetTop < e.clientHeight / 2 && n.offsetTop + n.clientHeight > e.clientHeight)
  293. e.style.cssText = e.style.cssText.replace(/\boverflow(-[xy])?:[^;]+/g, '') +
  294. important('overflow:visible;overflow-x:visible;overflow-y:visible;');
  295.  
  296. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  297. return;
  298.  
  299. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  300. if (n.style.height != h + 'px') n.style.height = h + 'px';
  301. if (parseFloat(n.style.minWidth) > w) n.style.minWidth = n.style.maxWidth;
  302. if (parseFloat(n.style.minHeight) > h) n.style.minHeight = n.style.height;
  303.  
  304. fixThumbnailAR(n);
  305. resized = true;
  306. });
  307.  
  308. if (resized && nearest)
  309. setTimeout(function() {
  310. var bounds = nearest.getBoundingClientRect();
  311. var h = bounds.bottom - bounds.top;
  312. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  313. var projectedTop = projectedCenterY - h/2;
  314. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  315. window.scrollBy(0, bounds.top - safeTop);
  316. }, 16);
  317. }
  318.  
  319. function calcContainerSize(div, origNode) {
  320. var w, h;
  321. origNode = origNode || div;
  322. switch (resizeMode) {
  323. case 'Original':
  324. w = div.FYTE.originalWidth;
  325. h = div.FYTE.originalHeight;
  326. break;
  327. case 'Custom':
  328. w = resizeWidth;
  329. h = resizeHeight;
  330. break;
  331. case '1080p':
  332. case '720p':
  333. case '480p':
  334. case '360p':
  335. h = parseInt(resizeMode);
  336. w = h / 9 * 16;
  337. break;
  338. default: // fit-to-width mode
  339. var n = origNode;
  340. do {
  341. n = n.parentElement;
  342. // find parent node with nonzero width (i.e. independent of our video element)
  343. } while (n && !(w = n.clientWidth));
  344. if (w)
  345. h = w / 16 * 9;
  346. else {
  347. w = origNode.clientWidth;
  348. h = origNode.clientHeight;
  349. }
  350. }
  351. var np = origNode.parentElement;
  352. var style = getComputedStyle(np);
  353. var parentWidth = parseFloat(style.width) - floatPadding(np, style, 'Left') - floatPadding(np, style, 'Right');
  354. if (parentWidth > 0 && parentWidth < w) {
  355. h = parentWidth / w * h;
  356. w = parentWidth;
  357. }
  358. if (resizeMode == 'Fit to width' && h < div.FYTE.originalHeight*0.9)
  359. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  360.  
  361. return {w: window.chrome ? w : Math.round(w), h:h};
  362. }
  363.  
  364. function parseVideoInfo(response) {
  365. var div = response.context;
  366. var txt = response.responseText;
  367. var info = tryCatch(function() { return JSON.parse(txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}')) }) || {};
  368. var videoSources = [];
  369.  
  370. // parse width & height to adjust the thumbnail
  371. var m = decodeURIComponent(info.adaptive_fmts || '').match(/size=(\d+)x(\d+)\b/) ||
  372. decodeURIComponent(txt).match(/\/(\d+)x(\d+)\//);
  373. if (m)
  374. fixThumbnailAR(div, m[1]|0, m[2]|0);
  375.  
  376. // parse video sources
  377. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  378. var streams = {};
  379. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  380. var params = {};
  381. stream.split('&').forEach(function(kv) {
  382. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  383. });
  384. streams[params.itag] = params;
  385. });
  386. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  387. var itag = fmt.split('/')[0];
  388. var dimensions = fmt.split('/')[1];
  389. var stream = streams[itag];
  390. if (stream) {
  391. videoSources.push({
  392. src: stream.url,
  393. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  394. });
  395. }
  396. });
  397. } else {
  398. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  399. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  400. while (m = rx.exec(text)) {
  401. videoSources.push({
  402. src: decodeURIComponent(decodeURIComponent(m[1]))
  403. });
  404. }
  405. }
  406.  
  407. var duration = div.FYTE.duration = info.length_seconds|0 || '';
  408. if (duration) {
  409. var d = new Date(null);
  410. d.setSeconds(duration);
  411. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '<span>$1</span>');
  412. }
  413. var title = decodeURIComponent(info.title || info.reason || '').replace(/\+/g, ' ');
  414. if (title || duration)
  415. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  416. if (pinnable != 'off' && info.title)
  417. makeDraggable(div);
  418. if (info.reason)
  419. div.setAttribute('disabled', '');
  420.  
  421. if (videoSources.length)
  422. div.FYTE.videoSources = videoSources;
  423.  
  424. if (info.storyboard_spec) {
  425. m = decodeURIComponent(decodeURIComponent(info.storyboard_spec)).split('|');
  426. div.FYTE.storyboard = JSON.parse(m[m.length-1].replace(/^(\d+)#(\d+)#(\d+)#(\d+)#(\d+)#.+$/, '{"w":$1, "h":$2, "len":$3, "rows":$4, "cols":$5}'));
  427. div.FYTE.storyboard.url = m[0].replace('$L/$N.jpg', (m.length-2) + '/M0.jpg?sigh=' + m[m.length-1].replace(/^.+?#([^#]+)$/, '$1'));
  428. $(div, '.instant-youtube-options-button').insertAdjacentHTML('beforebegin',
  429. '<div class="instant-youtube-storyboard"' + (showStoryboard ? '' : ' disabled') + '>' +
  430. important('<div style="width:' + (div.FYTE.storyboard.w-1) + 'px; height:' + div.FYTE.storyboard.h + 'px;') +
  431. '">&nbsp;</div>' +
  432. '</div>');
  433. if (showStoryboard)
  434. updateHoverHandler(div);
  435. }
  436.  
  437. injectStylesIfNeeded();
  438.  
  439. if (div.FYTE.state == 'scheduled play')
  440. setTimeout(function() { startPlayingDirectly(div) }, 0);
  441.  
  442. div.FYTE.state = '';
  443. }
  444.  
  445. function fixThumbnailAR(div, w, h) {
  446. var img = $(div, 'img');
  447. var thw = img.naturalWidth, thh = img.naturalHeight;
  448. if (w && h) { // means thumbnail is still loading
  449. div.FYTE.videoWidth = w;
  450. div.FYTE.videoHeight = h;
  451. } else {
  452. w = div.FYTE.videoWidth;
  453. h = div.FYTE.videoHeight;
  454. if (!w || !h)
  455. return;
  456. }
  457. var divw = div.clientWidth, divh = div.clientHeight;
  458. // if both video and thumbnail are 4:3, fit the image to height
  459. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  460. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  461. img.style.maxHeight = img.clientHeight + 'px';
  462. if (!div.FYTE.videoWidth) // skip animation if thumbnail is already loaded
  463. img.style.transition = 'height 1s ease, margin-top 1s ease';
  464. setTimeout(function() {
  465. img.style.maxHeight = 'none';
  466. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  467. setTimeout(function() {
  468. img.style.transition = '';
  469. }, 1000);
  470. }, 0);
  471. }
  472. }
  473.  
  474. function updateHoverHandler(div) {
  475. var sb = $(div, '.instant-youtube-storyboard');
  476. if (!showStoryboard) {
  477. if (!sb.getAttribute('disabled'))
  478. sb.setAttribute('disabled', '');
  479. return;
  480. }
  481. if (sb.hasAttribute('disabled'))
  482. sb.removeAttribute('disabled');
  483.  
  484. sb.addEventListener('click', storyboardClickHandler);
  485.  
  486. var oldIndex = null;
  487. var style = sb.firstElementChild.style;
  488. sb.addEventListener('mousemove', storyboardHoverHandler);
  489. sb.addEventListener('mouseout', storyboardHoverHandler);
  490.  
  491. div.addEventListener('mouseover', storyboardPreloader);
  492. div.addEventListener('mouseout', storyboardPreloader);
  493.  
  494. var spinner = document.createElement('span');
  495. spinner.className = 'instant-youtube-loading-button';
  496.  
  497. function storyboardClickHandler(e) {
  498. sb.removeEventListener('click', storyboardClickHandler);
  499. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  500. div.FYTE.startAt = offsetX / this.clientWidth * div.FYTE.duration |0;
  501. div.FYTE.srcEmbedFixed = setUrlParams(div.FYTE.srcEmbedFixed, {start: div.FYTE.startAt});
  502. startPlaying(div, {alternateMode: e.shiftKey});
  503. }
  504.  
  505. function storyboardPreloader(e) {
  506. if (e.type == 'mouseout') {
  507. imageLoader.onload = null; imageLoader.src = '';
  508. spinner.remove();
  509. return;
  510. }
  511. if (!div.FYTE.storyboard || div.FYTE.storyboard.preloaded)
  512. return;
  513. var lastpart = (div.FYTE.storyboard.len-1)/(div.FYTE.storyboard.rows * div.FYTE.storyboard.cols) |0;
  514. if (lastpart <= 0)
  515. return;
  516. var part = 0;
  517. imageLoader.src = setStoryboardUrl(part++);
  518. imageLoader.onload = function() {
  519. if (part > lastpart) {
  520. div.FYTE.storyboard.preloaded = true;
  521. div.removeEventListener('mouseover', storyboardPreloader);
  522. div.removeEventListener('mouseout', storyboardPreloader);
  523. imageLoader.onload = null;
  524. imageLoader.src = '';
  525. spinner.remove();
  526. return;
  527. }
  528. imageLoader.src = setStoryboardUrl(part++);
  529. };
  530. }
  531.  
  532. function setStoryboardUrl(part) {
  533. return div.FYTE.storyboard.url.replace(/M\d+\.jpg\?/, 'M' + part + '.jpg?');
  534. }
  535.  
  536. function storyboardHoverHandler(e) {
  537. if (!showStoryboard || !div.FYTE.storyboard)
  538. return;
  539. if (e.type == 'mouseout')
  540. return imageLoader2.onload && imageLoader2.onload();
  541. var w = div.FYTE.storyboard.w;
  542. var h = div.FYTE.storyboard.h;
  543. var cols = div.FYTE.storyboard.cols;
  544. var rows = div.FYTE.storyboard.rows;
  545. var len = div.FYTE.storyboard.len;
  546. var partlen = rows * cols;
  547.  
  548. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  549. var left = Math.min(this.clientWidth - w, Math.max(0, offsetX - w)) |0;
  550. if (!style.left || parseInt(style.left) != left) {
  551. style.left = left + 'px';
  552. if (spinner.parentElement)
  553. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  554. }
  555.  
  556. var index = Math.min(offsetX / this.clientWidth * (len+1) |0, len - 1);
  557. if (index == oldIndex)
  558. return;
  559.  
  560. var part = index/partlen|0;
  561. if (!oldIndex || part != (oldIndex/partlen|0)) {
  562. style.cssText = style.cssText.replace(/$|background-image[^;]+;/,
  563. 'background-image: url(' + setStoryboardUrl(part) + ')!important;');
  564. if (!div.FYTE.storyboard.preloaded) {
  565. if (spinner.timer)
  566. clearTimeout(spinner.timer);
  567. spinner.timer = setTimeout(function() {
  568. spinner.timer = 0;
  569. if (!imageLoader2.src)
  570. return;
  571. this.appendChild(spinner);
  572. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  573. }.bind(this), 50);
  574. imageLoader2.onload = function() {
  575. clearTimeout(spinner.timer);
  576. spinner.remove();
  577. spinner.timer = 0;
  578. imageLoader2.onload = null;
  579. imageLoader2.src = '';
  580. };
  581. imageLoader2.src = setStoryboardUrl(part);
  582. }
  583. }
  584.  
  585. oldIndex = index;
  586. index = index % partlen;
  587. style.backgroundPosition = '-' + (index % cols) * w + 'px -' + (index / cols |0) * h + 'px';
  588. }
  589. }
  590.  
  591. function clickHandler(e) {
  592. if (e.target.href)
  593. return;
  594. if (e.target.matches('.instant-youtube-options-button')) {
  595. showOptions(e);
  596. e.preventDefault();
  597. e.stopPropagation();
  598. return;
  599. }
  600. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  601. return;
  602.  
  603. e.preventDefault();
  604. e.stopPropagation();
  605.  
  606. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  607. startPlaying(e.target.closest('.instant-youtube-container'), {alternateMode: alternateMode});
  608. }
  609.  
  610. function startPlaying(div, options) {
  611. div.removeEventListener('click', clickHandler);
  612.  
  613. $$(div, '.instant-youtube-wrapper > *:not(img):not(a)').forEach(function(e) { e.style.cssText = 'display:none!important' });
  614. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  615.  
  616. if (pinnable != 'off') {
  617. div.firstElementChild.insertAdjacentHTML('beforeend',
  618. '<div pin="top-left"></div><div pin="top-right"></div><div pin="bottom-right"></div><div pin="bottom-left"></div>');
  619. $$(div, '[pin]').forEach(function(pin) {
  620. if (pinnable == 'hide')
  621. pin.setAttribute('transparent', '');
  622. pin.onclick = function(e) {
  623. var pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  624. var corner = pin.getAttribute('pin');
  625. var video = $(div, 'video');
  626. if (pinIt) {
  627. $$(div, '[pin][active]').forEach(function(p) { p.removeAttribute('active') });
  628. pin.setAttribute('active', '');
  629. if (!div.FYTE.unpinnedStyle) {
  630. div.FYTE.unpinnedStyle = div.style.cssText;
  631. var stub = div.cloneNode();
  632. var img = $(div, 'img').cloneNode();
  633. img.style.opacity = 1;
  634. img.style.display = 'block';
  635. img.title = '';
  636. stub.appendChild(img);
  637. stub.onclick = function(e) { $(div, '[pin][active]').onclick(e) };
  638. stub.style.cssText += 'opacity:0.3!important;';
  639. div.FYTE.stub = stub;
  640. div.parentNode.insertBefore(stub, div);
  641. }
  642. div.setAttribute('pinned', '');
  643. div.style.cssText = important(
  644. 'position: fixed;' +
  645. 'contain: inherit;' +
  646. 'width: 400px;' +
  647. 'z-index: 999999999;' +
  648. 'height:' + (400 / div.FYTE.videoWidth * div.FYTE.videoHeight) + 'px;' +
  649. 'top:' + (corner.indexOf('top') >= 0 ? '0' : 'auto') + ';' +
  650. 'bottom:' + (corner.indexOf('bottom') >= 0 ? '0' : 'auto') + ';' +
  651. 'left:' + (corner.indexOf('left') >= 0 ? '0' : 'auto') + ';' +
  652. 'right:' + (corner.indexOf('right') >= 0 ? '0' : 'auto') + ';'
  653. );
  654. if (video && document.body)
  655. document.body.appendChild(div);
  656. } else {
  657. pin.removeAttribute('active');
  658. div.removeAttribute('pinned');
  659. div.style.cssText = div.FYTE.unpinnedStyle;
  660. div.FYTE.unpinnedStyle = '';
  661. if (div.FYTE.stub) {
  662. if (video && document.body)
  663. div.FYTE.stub.parentNode.appendChild(div, div.FYTE.stub);
  664. div.FYTE.stub.remove();
  665. div.FYTE.stub = null;
  666. }
  667. }
  668. if (video && video.paused)
  669. video.play();
  670. };
  671. });
  672. if (options.pin)
  673. $(div, '[pin="' + options.pin + '"]').click();
  674. }
  675.  
  676. if (window != window.top)
  677. window.parent.postMessage('iframe-allowfs', '*');
  678.  
  679. if ((!!playDirectly + !!options.alternateMode == 1) && (div.FYTE.videoSources || div.FYTE.state == 'querying')) {
  680. if (div.FYTE.videoSources)
  681. startPlayingDirectly(div);
  682. else {
  683. // playback will start in parseVideoInfo
  684. div.FYTE.state = 'scheduled play';
  685. // fallback to iframe in 5s
  686. setTimeout(function() {
  687. if (div.FYTE.state) {
  688. div.FYTE.state = '';
  689. switchToIFrame.call(div);
  690. }
  691. }, 5000);
  692. }
  693. }
  694. else
  695. switchToIFrame.call(div);
  696. }
  697.  
  698. function startPlayingDirectly(div) {
  699. var video = document.createElement('video');
  700. video.controls = true;
  701. video.autoplay = true;
  702. video.style.cssText = important(
  703. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0; transition:opacity 2s;' +
  704. 'width:100%; height:100%;');
  705. video.className = 'instant-youtube-embed';
  706. video.volume = GM_getValue('volume', 0.5);
  707.  
  708. div.FYTE.videoSources.forEach(function(src) {
  709. var srcdom = video.appendChild(document.createElement('source'));
  710. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  711. srcdom.onerror = switchToIFrame.bind(div);
  712. });
  713.  
  714.  
  715. if (window.chrome) {
  716. video.addEventListener('click', function(e) {
  717. this.paused ? this.play() : this.pause();
  718. });
  719. }
  720. video.interval = (function() {
  721. return setInterval(function() {
  722. if (video.volume != GM_getValue('volume', 0.5))
  723. GM_setValue('volume', video.volume);
  724. }, 1000);
  725. })();
  726. var title = $(div, '.instant-youtube-title');
  727. if (title) {
  728. video.onpause = function() { title.removeAttribute('hidden') };
  729. video.onplay = function() { title.setAttribute('hidden', true) };
  730. }
  731. video.onloadedmetadata = div.FYTE.startAt && function(e) {
  732. video.currentTime = div.FYTE.startAt;
  733. };
  734. video.onloadeddata = function(e) {
  735. pauseOtherVideos(this);
  736. div.style.cssText += 'contain:inherit!important'; // allow fullscreen
  737. div.firstElementChild.appendChild(this);
  738. div.setAttribute('playing', '');
  739. this.style.opacity = 1;
  740. var img = $(div, 'img');
  741. img.style.transition = 'opacity 1s';
  742. img.style.opacity = 0;
  743. };
  744. }
  745.  
  746. function switchToIFrame(e) {
  747. var div = this;
  748. var wrapper = div.firstElementChild;
  749. if (e) {
  750. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  751. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  752. while (video.lastElementChild)
  753. video.lastElementChild.remove();
  754. }
  755.  
  756. ($(div, '[pin]') || wrapper).insertAdjacentHTML(pinnable != 'off' ? 'beforebegin' : 'beforeend',
  757. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  758. setUrlParams(div.FYTE.srcEmbedFixed, {
  759. html5: 1,
  760. autoplay: 1,
  761. autohide: 2,
  762. border: 0,
  763. controls: 1,
  764. fs: 1,
  765. showinfo: 1,
  766. ssl: 1,
  767. theme: 'dark',
  768. enablejsapi: 1,
  769. }) + '" frameborder="0" allowfullscreen width="100%" height="100%"></iframe>');
  770.  
  771. $(div, 'iframe').onload = function() {
  772. pauseOtherVideos(this);
  773. this.style.cssText = important(
  774. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:1; transition:opacity 2s;');
  775.  
  776. div.setAttribute('iframe', '');
  777. div.setAttribute('playing', '');
  778. div.style.cssText += 'contain:none!important'; // allow fullscreen
  779. setTimeout(function() {
  780. $(div, 'img').style.display = 'none';
  781. var title = $(div, '.instant-youtube-title');
  782. if (title)
  783. title.remove();
  784. }, 2000);
  785. };
  786. }
  787.  
  788. function setUrlParams(url, params) {
  789. var names = Object.keys(params);
  790. url = url.replace(new RegExp('[?&](' + names.join('|') + ')(=[^?&]*)?', 'gi'), '');
  791. return url +
  792. (url.indexOf('?') > 0 ? '&' : '?') +
  793. names.map(function(n) { return n + '=' + params[n] }).join('&');
  794. }
  795.  
  796. function pauseOtherVideos(activePlayer) {
  797. $$(activePlayer.ownerDocument, '.instant-youtube-embed').forEach(function(v) {
  798. if (v == activePlayer)
  799. return;
  800. switch (v.localName) {
  801. case 'video':
  802. if (!v.paused)
  803. v.pause();
  804. break;
  805. case 'iframe':
  806. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  807. break;
  808. }
  809. });
  810. }
  811.  
  812. function makeDraggable(div) {
  813. div.draggable = true;
  814. div.addEventListener('dragstart', function(e) {
  815. e.dataTransfer.setData('text/plain', '');
  816.  
  817. var dropZone = document.createElement('div');
  818. var dropZoneHeight = 400 / div.FYTE.videoWidth * div.FYTE.videoHeight;
  819. dropZone.className = 'instant-youtube-dragndrop-placeholder';
  820.  
  821. document.body.addEventListener('dragenter', dragHandler);
  822. document.body.addEventListener('dragover', dragHandler);
  823. document.body.addEventListener('dragend', dragHandler);
  824. document.body.addEventListener('drop', dragHandler);
  825. function dragHandler(e) {
  826. e.stopImmediatePropagation();
  827. e.stopPropagation();
  828. e.preventDefault();
  829. switch (e.type) {
  830. case 'dragover':
  831. var playing = div.hasAttribute('playing');
  832. var gizmo = playing
  833. ? {left:0, top:0, right:innerWidth, bottom:innerHeight}
  834. : div.getBoundingClientRect();
  835. var x = e.clientX, y = e.clientY;
  836. var cx = (gizmo.left + gizmo.right) / 2;
  837. var cy = (gizmo.top + gizmo.bottom) / 2;
  838. var stay = y >= cy-200 && y <= cy+200 && x >= cx-200 && x <= cx+200;
  839. overrideCSS(dropZone, {
  840. top: y < cy || stay ? '0' : 'auto',
  841. bottom: y > cy || stay ? '0' : 'auto',
  842. left: x < cx || stay ? '0' : 'auto',
  843. right: x > cy || stay ? '0' : 'auto',
  844. width: playing && stay ? (div.FYTE.stub || div).clientWidth+'px' : stay ? '100%' : '400px',
  845. height: playing && stay ? (div.FYTE.stub || div).clientHeight+'px' : stay ? '100%' : dropZoneHeight + 'px',
  846. margin: playing && stay ? 'auto' : '0',
  847. position: !playing && stay ? 'absolute' : 'fixed',
  848. 'background-color': stay ? 'rgba(255,255,0,0.2)' : 'rgba(0,255,0,0.2)',
  849. });
  850. (stay && !playing ? div : document.body).appendChild(dropZone);
  851. break;
  852. case 'dragend':
  853. case 'drop':
  854. var t = dropZone.style.top == '0px';
  855. var b = dropZone.style.bottom == '0px';
  856. var l = dropZone.style.left == '0px';
  857. var r = dropZone.style.right == '0px';
  858. var corner = t && b && l && r ? '' : (t ? 'top' : 'bottom') + '-' + (l ? 'left' : 'right');
  859. dropZone.remove();
  860. dropZone = null;
  861. document.body.removeEventListener('dragenter', dragHandler);
  862. document.body.removeEventListener('dragover', dragHandler);
  863. document.body.removeEventListener('dragend', dragHandler);
  864. document.body.removeEventListener('drop', dragHandler);
  865. if (e.type == 'dragend')
  866. break;
  867. if (div.hasAttribute('playing'))
  868. (corner ? $(div, '[pin="' + corner + '"]') : div.FYTE.stub).click();
  869. else
  870. startPlaying(div, {pin: corner});
  871. }
  872. }
  873. });
  874. }
  875.  
  876. function showOptions(e) {
  877. var optionsButton = e.target;
  878. translateHTML(optionsButton, 'afterend', '\
  879. <div class="instant-youtube-options">\
  880. <label tl style="width: 100% !important;">Size:<br>\
  881. <select data-action="size-mode" style="width:20ex!important">\
  882. <option tl value="Original">Original\
  883. <option tl value="Fit to width">Fit to width\
  884. <option>360p\
  885. <option>480p\
  886. <option>720p\
  887. <option>1080p\
  888. <option tl value="Custom">Custom...\
  889. </select>\
  890. </label>\
  891. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  892. <input type="number" min="320" max="9999" tl-placeholder="width" data-action="width" step="1" value="' + (resizeWidth||'') + '">\
  893. x\
  894. <input type="number" min="240" max="9999" tl-placeholder="height" data-action="height" step="1" value="' + (resizeHeight||'') + '">\
  895. </label>\
  896. <label tl="content,title" title="msgStoryboardTooltip">\
  897. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  898. Storyboard thumbs\
  899. </label>\
  900. <label tl="content,title" title="msgDirectTooltip">\
  901. <input data-action="direct" type="checkbox" ' + (playDirectly ? 'checked' : '') + '>\
  902. Play directly\
  903. </label>\
  904. <label tl="content,title" title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  905. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  906. Safe\
  907. </label>\
  908. <label tl="content,title" title="msgPinningTooltip">Pinning:\
  909. <select data-action="pinnable">\
  910. <option tl value="on">On\
  911. <option tl value="hide">On, hidden\
  912. <option tl value="off">Off\
  913. </select>\
  914. </label>\
  915. <span data-action="buttons">\
  916. <button tl data-action="ok">OK</button>\
  917. <button tl data-action="cancel">Cancel</button>\
  918. </span>\
  919. </div>\
  920. ');
  921. var options = optionsButton.nextElementSibling;
  922.  
  923. options.addEventListener('keydown', function(e) {
  924. if (e.target.localName == 'input' &&
  925. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  926. return false;
  927. });
  928.  
  929. $(options, '[data-action="size-mode"]').value = resizeMode;
  930. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  931. var v = this.value != 'Custom';
  932. var e = $(options, '[data-action="size-custom"]');
  933. e.children[0].disabled = e.children[1].disabled = v;
  934. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  935. });
  936.  
  937. $(options, '[data-action="pinnable"]').value = pinnable;
  938.  
  939. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  940. if (e.target.dataset.action != 'ok') {
  941. options.remove();
  942. return;
  943. }
  944. var v, shouldAdjust;
  945. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  946. GM_setValue('resize', resizeMode = v);
  947. shouldAdjust = true;
  948. }
  949. if (resizeMode == 'Custom') {
  950. var w = $(options, '[data-action="width"]').value |0;
  951. var h = $(options, '[data-action="height"]').value |0;
  952. if (resizeWidth != w || resizeHeight != h) {
  953. updateCustomSize(w, h);
  954. GM_setValue('width', resizeWidth);
  955. GM_setValue('height', resizeHeight);
  956. shouldAdjust = true;
  957. }
  958. }
  959. if (showStoryboard != (v = $(options, '[data-action="storyboard"]').checked)) {
  960. GM_setValue('showStoryboard', showStoryboard = v);
  961. $$('.instant-youtube-container').forEach(updateHoverHandler);
  962. }
  963. if (playDirectly != (v = $(options, '[data-action="direct"]').checked)) {
  964. GM_setValue('playHTML5', playDirectly = v);
  965. $$('.instant-youtube-container .instant-youtube-link').forEach(function(e) {
  966. e.textContent = playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  967. });
  968. }
  969. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  970. GM_setValue('skipCustom', skipCustom = v);
  971. }
  972. if (pinnable != (v = $(options, '[data-action="pinnable"]').value)) {
  973. GM_setValue('pinnable', pinnable = v);
  974. }
  975.  
  976. options.remove();
  977.  
  978. if (shouldAdjust)
  979. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  980. });
  981. }
  982.  
  983. function updateCustomSize(w, h) {
  984. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  985. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  986. }
  987.  
  988. function important(cssText) {
  989. return cssText.replace(/;/g, '!important;');
  990. }
  991.  
  992. function tryCatch(func) {
  993. try {
  994. return func();
  995. } catch(e) {
  996. console.log(e);
  997. }
  998. }
  999.  
  1000. function getFunctionComment(fn) {
  1001. return fn.toString().match(/\/\*([\s\S]*?)\*\/\s*\}$/)[1];
  1002. }
  1003.  
  1004. function $(selORnode, sel) {
  1005. return sel ? selORnode.querySelector(sel)
  1006. : document.querySelector(selORnode);
  1007. }
  1008.  
  1009. function $$(selORnode, sel) {
  1010. return Array.prototype.slice.call(
  1011. sel ? selORnode.querySelectorAll(sel)
  1012. : document.querySelectorAll(selORnode));
  1013. }
  1014.  
  1015. function overrideCSS(e, params) {
  1016. var names = Object.keys(params);
  1017. var style = e.style.cssText.replace(new RegExp('(^|\s|;)(' + names.join('|') + ')(:[^;]+)', 'gi'), '$1');
  1018. e.style.cssText = style.replace(/[^;]\s*$/, '$&;').replace(/^\s*;\s*/, '') +
  1019. names.map(function(n) { return n + ':' + params[n] + '!important' }).join(';') + ';';
  1020. }
  1021.  
  1022. // fix dumb Firefox bug
  1023. function floatPadding(node, style, dir) {
  1024. var padding = style['padding' + dir];
  1025. if (padding.indexOf('%') < 0)
  1026. return parseFloat(padding);
  1027. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  1028. }
  1029.  
  1030. function translateHTML(baseElement, place, html) {
  1031. var tmp = document.createElement('div');
  1032. tmp.innerHTML = html;
  1033. $$(tmp, '[tl]').forEach(function(node) {
  1034. (node.getAttribute('tl') || 'content').split(',').forEach(function(what) {
  1035. var child, src, tl;
  1036. if (what == 'content') {
  1037. for (var i = node.childNodes.length-1, n; (i>=0) && (n=node.childNodes[i]); i--) {
  1038. if (n.nodeType == Node.TEXT_NODE && n.textContent.trim()) {
  1039. child = n;
  1040. break;
  1041. }
  1042. }
  1043. } else
  1044. child = node.getAttributeNode(what);
  1045. if (!child)
  1046. return;
  1047. src = child.textContent;
  1048. srcTrimmed = src.trim();
  1049. tl = src.replace(srcTrimmed, _(srcTrimmed));
  1050. if (src != tl)
  1051. child.textContent = tl;
  1052. });
  1053. });
  1054. baseElement.insertAdjacentHTML(place, tmp.innerHTML);
  1055. }
  1056.  
  1057. function initTL(src) {
  1058. var tlSource = {
  1059. 'watch on Youtube': {
  1060. 'ru': 'открыть на Youtube',
  1061. },
  1062. 'Play with Youtube player': {
  1063. 'ru': 'Включить плеер Youtube',
  1064. },
  1065. 'Play directly (up to 720p)': {
  1066. 'ru': 'Включить напрямую (макс. 720p)',
  1067. },
  1068. 'Shift-click to use alternative player': {
  1069. 'ru': 'Shift-клик для смены типа плеера',
  1070. },
  1071. 'Options': {
  1072. 'ru': 'Опции',
  1073. },
  1074. 'Size:': {
  1075. 'ru': 'Размер:',
  1076. },
  1077. 'Original': {
  1078. 'ru': 'Исходный',
  1079. },
  1080. 'Fit to width': {
  1081. 'ru': 'На всю ширину',
  1082. },
  1083. 'Custom...': {
  1084. 'ru': 'Настроить...',
  1085. },
  1086. 'width': {
  1087. 'ru': 'ширина',
  1088. },
  1089. 'height': {
  1090. 'ru': 'высота',
  1091. },
  1092. 'Storyboard thumbs': {
  1093. 'ru': 'Раскадровка',
  1094. },
  1095. 'msgStoryboardTooltip': {
  1096. 'en': 'Show storyboard preview on mouse hover at the bottom',
  1097. 'ru': 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1098. },
  1099. 'Play directly': {
  1100. 'ru': 'Плеер браузера',
  1101. },
  1102. 'msgDirectTooltip': {
  1103. 'en': 'Shift-clicking thumbnails will use alternative player',
  1104. 'ru': 'Удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1105. },
  1106. 'Safe': {
  1107. 'ru': 'Консервативный режим',
  1108. },
  1109. 'Pinning': {
  1110. 'ru': 'Закрепление',
  1111. },
  1112. 'msgPinningTooltip': {
  1113. 'en': 'Enable corner pinning controls when a video is playing. \nTo restore the video click the active corner pin or the original video placeholder.',
  1114. 'ru': 'Включить шпильки по углам для закрепления видео во время просмотра. \nДля отмены можно нажать еще раз на активированный уголЪ или на заглушку, где исходно было видео',
  1115. },
  1116. 'On': {
  1117. 'ru': 'Да',
  1118. },
  1119. 'On, hide': {
  1120. 'ru': 'Да, невидимые',
  1121. },
  1122. 'Off': {
  1123. 'ru': 'Нет',
  1124. },
  1125. 'msgSafe': {
  1126. 'en': 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)',
  1127. 'ru': 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 (подействует после обновления страницы)',
  1128. },
  1129. 'OK': {
  1130. 'ru': 'ОК',
  1131. },
  1132. 'Cancel': {
  1133. 'ru': 'Оменить',
  1134. },
  1135. };
  1136. var browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1137. var browserLangMajor = browserLang.replace(/-.+/, '');
  1138. var tl = {};
  1139. Object.keys(tlSource).forEach(function(k) {
  1140. var langs = tlSource[k];
  1141. var text = langs[browserLang] || langs[browserLangMajor];
  1142. if (text)
  1143. tl[k] = text;
  1144. });
  1145. return function(src) { return tl[src] || src };
  1146. }
  1147.  
  1148. function injectStylesIfNeeded(force) {
  1149. if (!fytedom.length && !force)
  1150. return;
  1151. var styledom = $('style#instant-youtube-styles');
  1152. if (styledom) {
  1153. // move our rules to the end of HEAD to increase CSS specificity
  1154. if (styledom.nextElementSibling && document.head)
  1155. document.head.insertBefore(styledom, null);
  1156. return;
  1157. }
  1158. styledom = (document.head || document.documentElement).appendChild(document.createElement('style'));
  1159. styledom.id = 'instant-youtube-styles';
  1160. styledom.textContent = important(getFunctionComment(function() { /*
  1161. .instant-youtube-container {
  1162. contain: strict;
  1163. position: relative;
  1164. overflow: hidden;
  1165. cursor: pointer;
  1166. padding: 0;
  1167. margin: 0;
  1168. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1169. text-align: center;
  1170. background: black;
  1171. }
  1172. .instant-youtube-container[disabled] {
  1173. background: #888;
  1174. }
  1175. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1176. display: none;
  1177. }
  1178. .instant-youtube-container .instant-youtube-wrapper {
  1179. width: 100%;
  1180. height: 100%;
  1181. }
  1182. .instant-youtube-container .instant-youtube-play-button {
  1183. display: block;
  1184. position: absolute;
  1185. width: 85px;
  1186. height: 60px;
  1187. left: 0;
  1188. right: 0;
  1189. top: 0;
  1190. bottom: 0;
  1191. margin: auto;
  1192. }
  1193. .instant-youtube-container .instant-youtube-loading-button {
  1194. display: block;
  1195. position: absolute;
  1196. width: 20px;
  1197. height: 20px;
  1198. left: 0;
  1199. right: 0;
  1200. top: 0;
  1201. bottom: 0;
  1202. padding: 0;
  1203. margin: auto;
  1204. pointer-events: none;
  1205. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1206. }
  1207. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1208. fill: #CC181E;
  1209. }
  1210. .instant-youtube-container .instant-youtube-link {
  1211. display: block;
  1212. position: absolute;
  1213. width: 20em;
  1214. height: 20px;
  1215. top: 50%;
  1216. left: 0;
  1217. right: 0;
  1218. margin: 60px auto;
  1219. padding: 0;
  1220. border: none;
  1221. text-align: center;
  1222. text-decoration: none;
  1223. text-shadow: 1px 1px 3px black;
  1224. font-weight: bold;
  1225. color: white;
  1226. }
  1227. .instant-youtube-container span.instant-youtube-link {
  1228. z-index: 8;
  1229. font-weight: normal;
  1230. font-size: 12px;
  1231. }
  1232. .instant-youtube-container .instant-youtube-link:hover {
  1233. text-decoration: underline;
  1234. color: white;
  1235. background: transparent;
  1236. }
  1237. .instant-youtube-container iframe {
  1238. z-index: 10;
  1239. }
  1240. .instant-youtube-container .instant-youtube-title {
  1241. z-index: 9;
  1242. display: block;
  1243. position: absolute;
  1244. width: auto;
  1245. top: 0;
  1246. left: 0;
  1247. right: 0;
  1248. margin: 0;
  1249. padding: 7px;
  1250. border: none;
  1251. text-shadow: 1px 1px 2px black;
  1252. text-align: center;
  1253. text-decoration: none;
  1254. color: white;
  1255. background-color: rgba(0, 0, 0, 0.5);
  1256. }
  1257. .instant-youtube-container .instant-youtube-title strong {
  1258. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1259. }
  1260. .instant-youtube-container .instant-youtube-title strong:after {
  1261. content: " - $tl:'watch on Youtube'";
  1262. font-weight: normal;
  1263. margin-right: 1ex;
  1264. }
  1265. .instant-youtube-container .instant-youtube-title span {
  1266. color: inherit;
  1267. }
  1268. .instant-youtube-container .instant-youtube-title span:before {
  1269. content: "(";
  1270. }
  1271. .instant-youtube-container .instant-youtube-title span:after {
  1272. content: ")";
  1273. }
  1274. @-webkit-keyframes instant-youtube-fadein {
  1275. from { opacity: 0 }
  1276. to { opacity: 1 }
  1277. }
  1278. @-moz-keyframes instant-youtube-fadein {
  1279. from { opacity: 0 }
  1280. to { opacity: 1 }
  1281. }
  1282. @keyframes instant-youtube-fadein {
  1283. from { opacity: 0 }
  1284. to { opacity: 1 }
  1285. }
  1286. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1287. display: none;
  1288. margin: 0;
  1289. }
  1290. .instant-youtube-container .instant-youtube-title:hover {
  1291. text-decoration: underline;
  1292. }
  1293. .instant-youtube-container .instant-youtube-title strong {
  1294. color: white;
  1295. }
  1296. .instant-youtube-container .instant-youtube-options-button {
  1297. opacity: 0.6;
  1298. position: absolute;
  1299. right: 0;
  1300. bottom: 0;
  1301. margin: 0;
  1302. padding: 1.5ex 2ex;
  1303. font-size: 11px;
  1304. text-shadow: 1px 1px 2px black;
  1305. color: white;
  1306. }
  1307. .instant-youtube-container .instant-youtube-options-button:hover {
  1308. opacity: 1;
  1309. background: rgba(0, 0, 0, 0.5);
  1310. }
  1311. .instant-youtube-container .instant-youtube-options {
  1312. display: flex;
  1313. position: absolute;
  1314. right: 0;
  1315. bottom: 0;
  1316. margin: 0;
  1317. padding: 2ex 1ex 2ex 2ex;
  1318. flex-direction: column;
  1319. align-items: flex-start;
  1320. line-height: 1.5;
  1321. text-align: left;
  1322. opacity: 1;
  1323. color: white;
  1324. background: black;
  1325. }
  1326. .instant-youtube-container .instant-youtube-options * {
  1327. width: auto;
  1328. height: auto;
  1329. margin: 0;
  1330. padding: 0;
  1331. font: inherit;
  1332. font-size: 13px;
  1333. vertical-align: middle;
  1334. text-transform: none;
  1335. text-align: left;
  1336. border-radius: 0;
  1337. text-decoration: none;
  1338. color: white;
  1339. background: black;
  1340. }
  1341. .instant-youtube-container .instant-youtube-options > label {
  1342. margin-top: 1ex;
  1343. }
  1344. .instant-youtube-container .instant-youtube-options > label > * {
  1345. display: inline;
  1346. }
  1347. .instant-youtube-container .instant-youtube-options select {
  1348. padding: .5ex .25ex;
  1349. border: 1px solid #444;
  1350. -webkit-appearance: menulist;
  1351. }
  1352. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {
  1353. width: 9ex;
  1354. padding: .5ex .5ex .4ex;
  1355. border: 1px solid #666;
  1356. }
  1357. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {
  1358. margin-top: 1em;
  1359. }
  1360. .instant-youtube-container .instant-youtube-options button {
  1361. margin: 0 1ex 0 0;
  1362. padding: .5ex 2ex;
  1363. border: 2px solid gray;
  1364. font-weight: bold;
  1365. }
  1366. .instant-youtube-container .instant-youtube-options button:hover {
  1367. border-color: white;
  1368. }
  1369. .instant-youtube-container .instant-youtube-options > [disabled] {
  1370. opacity: 0.25;
  1371. }
  1372. .instant-youtube-container .instant-youtube-storyboard {
  1373. height: 33%;
  1374. max-height: 90px;
  1375. display: block;
  1376. position: absolute;
  1377. left: 0;
  1378. right: 0;
  1379. bottom: 0;
  1380. overflow: visible;
  1381. overflow-x: visible;
  1382. overflow-y: visible;
  1383. }
  1384. .instant-youtube-container .instant-youtube-storyboard:hover {
  1385. background-color: rgba(0,0,0,0.3);
  1386. }
  1387. .instant-youtube-container .instant-youtube-storyboard[disabled] {
  1388. display:none;
  1389. }
  1390. .instant-youtube-container .instant-youtube-storyboard div {
  1391. display: block;
  1392. position: absolute;
  1393. bottom: 0px;
  1394. pointer-events: none;
  1395. border: 3px solid #888;
  1396. box-shadow: 2px 2px 10px black;
  1397. transition: opacity .25s ease;
  1398. background-color: transparent;
  1399. background-origin: content-box;
  1400. opacity: 0;
  1401. }
  1402. .instant-youtube-container .instant-youtube-storyboard:hover div {
  1403. opacity: 1;
  1404. }
  1405. .instant-youtube-container [pin] {
  1406. position: absolute;
  1407. width: 0;
  1408. height: 0;
  1409. margin: 0;
  1410. padding: 0;
  1411. opacity: 1;
  1412. top: auto; bottom: auto; left: auto; right: auto;
  1413. border-style: solid;
  1414. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  1415. opacity: 0;
  1416. z-index: 100;
  1417. }
  1418. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  1419. opacity: 1;
  1420. }
  1421. .instant-youtube-container[playing] [pin]:hover {
  1422. cursor: alias;
  1423. opacity: 1;
  1424. transition: opacity 0s;
  1425. }
  1426. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  1427. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  1428. .instant-youtube-container [pin=top-left] {
  1429. top: 0; left: 0;
  1430. border-width: 10px 10px 0 0;
  1431. border-color: red transparent transparent transparent;
  1432. }
  1433. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  1434. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  1435. .instant-youtube-container [pin=top-right] {
  1436. top: 0; right: 0;
  1437. border-width: 0 10px 10px 0;
  1438. border-color: transparent red transparent transparent;
  1439. }
  1440. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  1441. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  1442. .instant-youtube-container [pin=bottom-right] {
  1443. bottom: 0; right: 0;
  1444. border-width: 0 0 10px 10px;
  1445. border-color: transparent transparent red transparent;
  1446. }
  1447. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  1448. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  1449. .instant-youtube-container [pin=bottom-left] {
  1450. bottom: 0; left: 0;
  1451. border-width: 10px 0 0 10px;
  1452. border-color: transparent transparent transparent red;
  1453. }
  1454. .instant-youtube-dragndrop-placeholder {
  1455. z-index: 999999999;
  1456. margin: 0;
  1457. padding: 0;
  1458. background: rgba(0, 255, 0, 0.1);
  1459. border: 2px dotted green;
  1460. box-sizing: border-box;
  1461. }
  1462. */}).replace(/\$tl:'(.+?)'/g, function(m, m1) { return _(m1) })
  1463. );
  1464. }