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.

目前為 2017-07-24 提交的版本,檢視 最新版本

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