YouTube Me Again!

ytma! automatically converts YouTube(TM), Vimeo, Vine, Soundcloud, WebM, and MP4 links into real embedded videos.

当前为 2017-08-06 提交的版本,查看 最新版本

  1. /*jslint maxerr: 500, browser: true, devel: true, bitwise: true, white: true */
  2. // ==UserScript==
  3. // Do not modify and re-release this script!
  4. // If you would like to add support for other sites, please tell me and I'll put it in the includes.
  5.  
  6. // @id youtube-me-again
  7. // @name YouTube Me Again!
  8. // @namespace hateradio)))
  9. // @author hateradio
  10. // @version 7.2.1
  11. // @description ytma! automatically converts YouTube(TM), Vimeo, Vine, Soundcloud, WebM, and MP4 links into real embedded videos.
  12. // @homepage https://greasyfork.org/en/scripts/1023-youtube-me-again
  13. // @icon https://www.dropbox.com/s/b85qmq0bsim407s/ytma32.png?dl=1
  14. // @icon64 https://www.dropbox.com/s/5zw3al38yf39wxb/ytma64.png?dl=1
  15. // @screenshot https://www.dropbox.com/s/syy9916b1prygl9/ytmascreen5.png?dl=1
  16.  
  17. // @include https://vine.co/v/*/embed/simple
  18. // @match https://vine.co/v/*/embed/simple
  19.  
  20. // @include http*://*youtube-nocookie.com/embed/*
  21. // @match *://*.youtube-nocookie.com/embed/*
  22.  
  23. // @include http*://*youtube.com/embed/*
  24. // @match *://*.youtube.com/embed/*
  25.  
  26. // @include https://gfycat.com/iframe/*
  27. // @match https://gfycat.com/iframe/*
  28.  
  29. // @include http*://*.neogaf.com/forum/showthread.php*
  30. // @include http*://*.neogaf.com/forum/showpost.php?p*
  31. // @include http*://*.neogaf.com/forum/newreply.php*
  32. // @include http*://*.neogaf.com/forum/editpost.php*
  33. // @include http*://*.neogaf.com/forum/private.php*
  34.  
  35. // @match *://*.neogaf.com/forum/showthread.php*
  36. // @match *://*.neogaf.com/forum/showpost.php?p*
  37. // @match *://*.neogaf.com/forum/newreply.php*
  38. // @match *://*.neogaf.com/forum/editpost.php*
  39. // @match *://*.neogaf.com/forum/private.php*
  40.  
  41. // @updated 06 Aug 2017
  42.  
  43. // @grant GM_xmlhttpRequest
  44. // @grant unsafeWindow
  45.  
  46. // @run-at document-end
  47. // ==/UserScript==
  48.  
  49. /*
  50.  
  51. ## Updates
  52.  
  53. #### 7.2.1
  54.  
  55. * New: Extension info
  56. * Updates JSHint options
  57. * Removes outdated @include links
  58.  
  59. #### 7.2
  60.  
  61. * New: CSS rule to make videos fit within smaller windows
  62. * New: GitHub repository and update links
  63. * New: Streamable favicon
  64. * Fix: Vimeo favicon
  65.  
  66. #### 7.1
  67.  
  68. * HTTPS links for Vimeo and Gfycat
  69. * Fix: Safari bug
  70.  
  71. #### 7
  72.  
  73. * New: NeoGAF HTTPS Support
  74. * New: Streamable.com added
  75. * New: Soundcloud playlist support
  76. * Improved time parser
  77. * Upon scrolling, cached descriptions are shown
  78. * Code reorganization makes adding new media sites easier
  79.  
  80. ### 6
  81.  
  82. * New: Imgur GIFV (WEBM/MP4) support
  83. * New: Button to remove cache (descriptions/thumbnail links/etc)
  84. * New: SoundCloud playlist support
  85. * Default video quality is now 720p/HD
  86. * Soundcloud now uses HTML5 player
  87. * Players that open on scroll will no longer trigger the opening of players higher on the page
  88. * Adds HTML5, Gfycat, Imgur icons on links
  89. * Improved Soundcloud and GfyCat URL matchers
  90. * Restructured code base to simplify creation of media controls
  91. * Restructured CSS
  92. * Patched back Gfycat iFrame setting for Safari (it is incompatible with new settings)
  93. * Updates YouTube data API
  94. * Removes:
  95. * Object tag for YouTube for Flash (Deprecated)
  96. * "Batch" loading of descriptions (Only manual and scroll methods are supported)
  97.  
  98. // #Updates
  99.  
  100. Whitelist these sites on NoScript/NotScript/etc.
  101. ------------------------------------------------
  102.  
  103. * neogaf.com
  104. * youtube.com
  105. * youtube-nocookie.com
  106. * googlevideo.com (HTML5 player sends videos from this domain)
  107. * googleapis.com (YT video descriptions)
  108. * vimeo.com
  109. * vimeocdn.com
  110. * soundcloud.com
  111. * sndcdn.com
  112. * vineco.com
  113. * vine.com
  114. * vine.co
  115. * gfycat.com
  116. * github.io
  117.  
  118.  
  119. Whitelist these on Ghostery
  120. ---------------------------
  121.  
  122. * SoundCloud (Widgets, Audio / Music Player)
  123.  
  124. */
  125.  
  126. (function () {
  127. 'use strict';
  128.  
  129. var $$, strg, update;
  130.  
  131. if (!Function.prototype.bind) {
  132. Function.prototype.bind = function (self) {
  133. var args = [].slice.call(arguments, 1), fn = this;
  134. return function () {
  135. return fn.apply(self, args.concat([].slice.call(arguments)));
  136. };
  137. };
  138. }
  139.  
  140. function isNumber(n) {
  141. return !isNaN(parseFloat(n)) && isFinite(n);
  142. }
  143.  
  144. function inject(func) {
  145. var script = document.createElement('script');
  146. script.type = 'text/javascript';
  147. script.textContent = '(' + func + ')();';
  148. document.body.appendChild(script);
  149. document.body.removeChild(script);
  150. }
  151.  
  152. function removeSearch(uri, keepHash) { // removes search query from a uri
  153. var s = uri.indexOf('?'), h = uri.indexOf('#'), hash = '';
  154. if (s > -1) {
  155. if (keepHash && h > -1) {
  156. hash = uri.substr(h);
  157. }
  158. uri = uri.substr(0, s) + hash;
  159. }
  160. return uri;
  161. }
  162.  
  163. // D O M Handle
  164. $$ = {
  165. s: function (selector, cb) { var s = document.querySelectorAll(selector), i = -1; while (++i < s.length) { if (cb(s[i], i, s) === false) { break; } } },
  166. o: function (object, cb) { var i; for (i in object) { if (object.hasOwnProperty(i)) { if (cb(i, object[i], object) === false) { break; } } } },
  167. a: function (e) { var i = 1, j = arguments.length, f = document.createDocumentFragment(); for (i; i < j; i++) { if (arguments[i]) { f.appendChild(arguments[i]); } } e.appendChild(f); return e; },
  168. e: function (t, o, e, p) {
  169. var c = document.createElement(t);
  170. $$.o(o, function (k, v) {
  171. var b = k.charAt(0);
  172. switch (b) {
  173. case '_':
  174. c.dataset[k.substring(1)] = v;
  175. break;
  176. case '$':
  177. c.setAttribute(k.substring(1), v);
  178. break;
  179. default:
  180. c[k] = v;
  181. }
  182. });
  183.  
  184. if (e && p) {
  185. c.appendChild(e);
  186. } else if (e) {
  187. e.appendChild(c);
  188. }
  189. return c;
  190. },
  191. x: function (selector) { return this.ary(document.querySelectorAll(selector)); },
  192. ary: function (ary) { return Array.from ? Array.from(ary) : Array.prototype.slice.call(ary); },
  193. top: document.head || document.body,
  194. css: function (t) {
  195. if (!this.style) {
  196. this.style = document.createElement('style');
  197. this.style.type = 'text/css';
  198. this.top.appendChild(this.style);
  199. }
  200. this.style.appendChild(document.createTextNode(t + '\n'));
  201. },
  202. js: function (t) {
  203. var j = document.createElement('script');
  204. j.type = 'text/javascript';
  205. j[/^https?\:\/\//i.test(t) ? 'src' : 'textContent'] = t;
  206. this.top.appendChild(j);
  207. }
  208. };
  209.  
  210. // S T O R A G E HANDLE
  211. strg = {
  212. MAX: 5012,
  213. on: false,
  214. test: function () { try { var a, b = localStorage, c = Math.random().toString(16).substr(2, 8); b.setItem(c, c); a = b.getItem(c); return a === c ? !b.removeItem(c) : false; } catch (e) { return false; } },
  215. read: function (key) {
  216. try {
  217. return JSON.parse(localStorage.getItem(key));
  218. } catch (e) {
  219. console.error(e.lineNumber + ':' + e.message);
  220. return undefined;
  221. }
  222. },
  223. save: function (key, val) { return this.on ? !localStorage.setItem(key, JSON.stringify(val)) : false; },
  224. wipe: function (key) { return this.on ? !localStorage.removeItem(key) : false; },
  225. zero: function (o) { var k; for (k in o) { if (o.hasOwnProperty(k)) { return false; } } return true; },
  226. grab: function (key, def) { var s = strg.read(key); return strg.zero(s) ? def : s; },
  227. size: function () {
  228. var length = 0, key;
  229. try {
  230. for (key in window.localStorage) {
  231. if (window.localStorage.hasOwnProperty(key)) {
  232. length += window.localStorage[key].length;
  233. }
  234. }
  235. } catch (e) {}
  236. return 3 + ((length * 16) / (8 * 1024));
  237. },
  238. full: function () {
  239. try {
  240. var date = +(new Date());
  241. localStorage.setItem(date, date);
  242. localStorage.removeItem(date);
  243. return false;
  244. } catch (e) {
  245. if (e.name === 'QuotaExceededError' ||
  246. e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
  247. return true;
  248. }
  249. }
  250. },
  251. init: function () { this.on = this.test(); }
  252. };
  253. strg.init();
  254.  
  255. // U P D A T E HANDLE
  256. update = {
  257. name: 'ytma!',
  258. version: 7210,
  259. key: 'ujs_YTMA_UPDT_HR',
  260. callback: 'ytmaupdater',
  261. page: 'https://greasyfork.org/scripts/1023-youtube-me-again',
  262. urij: 'https://hateradio.github.io/ytma/update.json',
  263. interval: 5,
  264. day: (new Date()).getTime(),
  265. time: function () { return new Date(this.day + (1000 * 60 * 60 * 24 * this.interval)).getTime(); },
  266. notification: function (j) {
  267. if (this.version < j.version) {
  268. strg.save(this.key, { date: this.time(), version: j.version, page: j.page });
  269. this.link();
  270. }
  271. },
  272. link: function () {
  273. this.csstxt();
  274.  
  275. var a = document.createElement('a'), b = strg.read(this.key);
  276. a.href = b.page || '#';
  277. a.id = 'userscriptupdater2';
  278. a.title = 'Update now.';
  279. a.target = '_blank';
  280. a.textContent = 'An update for ' + this.name + ' is available.';
  281. a.addEventListener('click', function () { this.style.display = 'none'; }, false);
  282. document.body.appendChild(a);
  283. },
  284. xhr: function () {
  285. var x = new XMLHttpRequest();
  286. x.addEventListener('load', function () { update.notification(JSON.parse(this.responseText)); }, false);
  287. x.open('get', update.urij, true);
  288. x.send();
  289. },
  290. check: function (opt) {
  291. if (!strg.on) { return; }
  292. if (window.chrome && window.chrome.extension) { return; }
  293. var stored = strg.read(this.key), page;
  294.  
  295. if (opt || !stored || stored.date < this.day) {
  296. page = (stored && stored.page) || '#';
  297. strg.save(this.key, {date: this.time(), version: this.version, page: page});
  298. this.xhr();
  299. } else if (this.version < stored.version) {
  300. this.link();
  301. }
  302. },
  303. csstxt: function () {
  304. if (!this.pop) { this.pop = true; $$.css('#userscriptupdater2,#userscriptupdater2:visited{box-shadow:1px 1px 6px #7776;border-bottom:3px solid #d65e55;cursor:pointer;color:#555;font-family:sans-serif;font-size:12px;font-weight:700;text-align:justify;position:fixed;z-index:999999;right:10px;top:10px;background:#ebebeb url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxOTguODQ4NTMgMTk5LjM4MzA3Ij48ZyB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtNC4yNzYgLTE2LjM2NykiPjxjaXJjbGUgY3g9IjEwNC4zMjEiIGN5PSIxMTYuMzI3IiByPSI5OC4yNzQiIGZpbGw9IiNkNjVlNTUiLz48cGF0aCBmaWxsPSIjZTljZTAyIiBzdHJva2U9IiNlOWM4MDIiIHN0cm9rZS13aWR0aD0iMTYuNyIgZD0iTTE2Ni40NSAxNTcuMzEySDQxLjg5bDMxLjE0LTUzLjkzNSAzMS4xNC01My45MzUgMzEuMTM3IDUzLjkzNXoiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48dGV4dCB4PSI4NS42NDMiIHk9IjE1MS44NjYiIGZpbGw9IiNkNjVlNTUiIHN0cm9rZS13aWR0aD0iMS40NzciIHN0eWxlPSJsaW5lLWhlaWdodDoxLjI1Oy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J0Jvb2sgQW50aXF1YSciIGZvbnQtd2VpZ2h0PSI0MDAiIGZvbnQtc2l6ZT0iNTkuMDg4IiBmb250LWZhbWlseT0iQm9vayBBbnRpcXVhIiBsZXR0ZXItc3BhY2luZz0iMCIgd29yZC1zcGFjaW5nPSIwIj48dHNwYW4geD0iODUuNjQzIiB5PSIxNTEuODY2IiBzdHlsZT0iLWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonQm9vayBBbnRpcXVhJyIgZm9udC13ZWlnaHQ9IjcwMCIgZm9udC1zaXplPSIxMjYuMDU0Ij4hPC90c3Bhbj48L3RleHQ+PC9nPjwvc3ZnPg==) no-repeat 10px center;background-size:40px;padding:0 20px 0 60px;height:55px;line-height:55px}#userscriptupdater2:hover,#userscriptupdater2:visited:hover{color:#b33a3a !important;border-color:#ce4b30}'); }
  305. }
  306. };
  307. update.check();
  308.  
  309. /** Y T M A CLASS
  310. * Bare YTMA class, filled through _new() or _reactivate()
  311. */
  312. function YTMA() {}
  313.  
  314. YTMA.events = {
  315. clicks: function (e) { // YTMA global click dispatcher
  316. var t = e.target;
  317.  
  318. if (t) {
  319. // console.log('YTMA.clicks');
  320. if (t.tagName === 'VAR' && t.hasAttribute('data-ytmuid')) { // trigger the ui
  321. console.log('show', t.dataset.ytmuid);
  322. YTMA.UI.createFromTrigger(t).showPlayer();
  323. } else if (t.hasAttribute('data-ytmdescription')) {
  324. console.log('load', t.dataset.ytmid);
  325. YTMA.external.events.manualLoad(e);
  326. }
  327. }
  328. },
  329. thumb: {
  330. start: function (e) {
  331. var el = e.target;
  332. el.dataset.thumb = el.dataset.thumb > 0 ? (el.dataset.thumb % 3) + 1 : 2;
  333. el.style.backgroundImage = ['url(https://i3.ytimg.com/vi/', el.dataset.ytmid, '/', el.dataset.thumb, '.jpg)'].join('');
  334. el.dataset.timeout = window.setTimeout(YTMA.events.thumb.start.bind(this, e), 800);
  335. },
  336. stop: function (e) {
  337. window.clearTimeout(e.target.dataset.timeout);
  338. }
  339. }
  340. };
  341.  
  342. YTMA.num = 0;
  343.  
  344. YTMA.addToSet = function (ytma) {
  345. YTMA.set[ytma.data.uid] = ytma;
  346. };
  347.  
  348. YTMA.create = function (link) {
  349. return YTMA.grabIdAndSite(link, function (data, err) {
  350. if (err) {
  351. console.error(link.href, err);
  352. return {};
  353. }
  354.  
  355. var y = new YTMA()._new(data.id, data.site, link);
  356. YTMA.addToSet(y);
  357. y.setup();
  358.  
  359. return y;
  360. });
  361. };
  362.  
  363. YTMA.grabIdAndSite = function (link, cb) {
  364. var uri = link.href, id, site, match;
  365. try {
  366. site = YTMA.reg.siteByTest[YTMA.reg.siteExpressions.test(uri) ? RegExp.lastMatch : ''];
  367. // console.log(site);
  368.  
  369. if (site === 'html5') { // || site === 'html5-audio'
  370. id = uri.slice(-15);
  371. } else if (site === 'soundcloud') {
  372. if (!YTMA.reg.extra.soundcloud.playlist.test(uri)) {
  373. link.href = uri = YTMA.reg.fix.soundcloud(uri);
  374. }
  375.  
  376. match = YTMA.DB.sites.soundcloud.matcher.exec(uri);
  377. id = YTMA.escapeId(match[1]);
  378.  
  379. if (match && YTMA.reg.extra.soundcloud.tracks.test(uri)) {
  380. id = id.slice(-50);
  381. }
  382. } else {
  383. id = uri.match(YTMA.DB.sites[site].matcher)[1];
  384. }
  385.  
  386. console.log(id, site, match);
  387. if (id && YTMA.DB.sites[site]) {
  388. return cb({id: id, site: site}, null);
  389. }
  390. throw TypeError('Invalid ID/Site: ' + id + ' @ ' + site);
  391. } catch (e) {
  392. return cb(null, e);
  393. }
  394. };
  395.  
  396. YTMA.escapeId = function (id) {
  397. return (id += '').replace(/(?:\W)/g, '_');
  398. };
  399.  
  400. YTMA.route = {
  401. host: document.location.host.replace('www.', ''),
  402. control: {
  403. $: {
  404. patchSafari: function () {
  405. delete YTMA.DB.sites.gfycat.videoTag;
  406. delete YTMA.DB.sources.gfycat;
  407. },
  408. checkStorage: function () {
  409. if (strg.full() === true) {
  410. console.log('YTMA ERROR: Storage is full!');
  411. try {
  412. localStorage.removeItem(YTMA.external.version);
  413. strg.on = strg.test();
  414. } catch (e) {
  415. console.error(e);
  416. }
  417. }
  418. },
  419. runOnce: function () {
  420. if (!document.body.hasAttribute('ytma-enabled')) {
  421. document.body.setAttribute('ytma-enabled', true);
  422.  
  423. this.checkStorage();
  424.  
  425. if (!YTMA.DB.extension) { update.check(); }
  426.  
  427. YTMA.css();
  428. YTMA.user.init();
  429. YTMA.DB.postInit();
  430.  
  431. document.body.addEventListener('click', YTMA.events.clicks, false);
  432. }
  433. }
  434. },
  435. go: function (host) {
  436. if (/(?:googlevideo|youtube-nocookie\.com|youtube\.com\.?)/i.test(host)) {
  437. this.sites.youtube();
  438. } else if (this.sites[host]) {
  439. this.sites[host]();
  440. } else {
  441. this.sites.$generic();
  442. }
  443. },
  444. sites: {
  445. $generic: function () {
  446. YTMA.route.control.$.runOnce();
  447.  
  448. if (YTMA.DB.browser.safari) { // safari patch
  449. YTMA.route.control.$.patchSafari();
  450. }
  451.  
  452. if (YTMA.selector.processor() > 0) {
  453. YTMA.user.fn.loadPreferences();
  454. }
  455. },
  456. 'gfycat.com': function () {
  457. var v = document.querySelector('video');
  458. v.controls = true;
  459. $$.css('body,html {overflow:hidden;height:100%;width:100%} video {display:table;height:100%;margin:0 auto;}');
  460. document.body.appendChild(v);
  461. },
  462. 'vine.co': function () {
  463. // console.log('vine.co');
  464.  
  465. window.addEventListener('resize', function () {
  466. $$.s('[style]', function (e) {
  467. e.removeAttribute('style');
  468. });
  469. });
  470. },
  471. youtube: function () { // lets force some quality parity
  472. console.log('now inside youtube . . .', document.location);
  473.  
  474. if (/(?:vq=(\w+))/.test(document.location.search)) {
  475. document.body.setAttribute('gm-player-quality', RegExp.lastParen);
  476. }
  477.  
  478. if (/(?:volume=(\d+))/.test(document.location.search)) {
  479. document.body.setAttribute('gm-player-volume', RegExp.lastParen);
  480. }
  481.  
  482. inject(function () {
  483. var max = 10, count = 1, intr = window.setInterval(function () {
  484. console.log('inside says: ', count, !!window.yt);
  485. if (window.yt && window.player) {
  486. window.clearInterval(intr);
  487.  
  488. var p = window.yt.player.getPlayerByElement(window.player);
  489.  
  490. if (document.body.hasAttribute('gm-player-quality')) {
  491. console.log('inside says: setting quality to ', document.body.getAttribute('gm-player-quality'));
  492. p.setPlaybackQuality(document.body.getAttribute('gm-player-quality'));
  493. }
  494.  
  495. if (document.body.hasAttribute('gm-player-volume')) {
  496. console.log('inside says: setting volume to ', document.body.getAttribute('gm-player-volume'));
  497. p.setVolume(document.body.getAttribute('gm-player-volume'));
  498. }
  499. } else {
  500. console.log(count);
  501. count += 1;
  502. if (count > max) {
  503. window.clearInterval(intr);
  504. }
  505. }
  506. }, 500);
  507. });
  508. }
  509. }
  510. },
  511. load: function () {
  512. this.control.go(this.host);
  513. }
  514. };
  515.  
  516. YTMA.main = function () {
  517. YTMA.reg.siteExpressions = YTMA.DB.views.getAllSiteRegExps();
  518. // console.log(YTMA.reg.siteExpressions);
  519. YTMA.route.load();
  520. };
  521.  
  522. YTMA.set = {};
  523.  
  524. YTMA.collect = function (id) {
  525. var i, a = [];
  526. for (i in YTMA.set) {
  527. if (YTMA.set.hasOwnProperty(i) && YTMA.set[i].data.id === id) {
  528. a.push(YTMA.set[i]);
  529. }
  530. }
  531. return a;
  532. };
  533.  
  534. YTMA.reg = {
  535. siteExpressions: null,
  536. time: /(?:t\=(?:(\d+)m)?(\d+))/,
  537. ios: /(?:\b(?:ipod|iphone|ipad))\b/i,
  538. extra: {
  539. soundcloud: {
  540. playlist: /(?:soundcloud\.com\/.+\/sets\/)/,
  541. tracks: /(?:soundcloud\.com\/.+\/tracks\/)/
  542. }
  543. },
  544. siteByTest: {
  545. youtu: 'youtube',
  546. vimeo: 'vimeo',
  547. vine: 'vine',
  548. gfycat: 'gfycat',
  549. imgur: 'imgur',
  550. '.webm': 'html5',
  551. '.mp4': 'html5',
  552. // '.mp3': 'html5-audio',
  553. '.gifv': 'html5',
  554. soundcloud: 'soundcloud',
  555. 'streamable.com': 'streamable'
  556. },
  557. fix: {
  558. soundcloud: function (uri) {
  559. var match = YTMA.DB.sites.soundcloud.matcher.exec(uri), id;
  560. if (match) {
  561. id = match[1].split('/', 2).join('/');
  562. uri = removeSearch('https://soundcloud.com/' + id, true);
  563. }
  564.  
  565. return uri;
  566. }
  567. }
  568. };
  569.  
  570. YTMA.selector = { // to build the selector
  571. parentBlacklist: ['.smallfont', '.colhead_dark', '.spoiler', 'pre'],
  572. chrome37Blacklist: 'a[href*="pomf.se/"]',
  573. ignore: function () {
  574. var i, j, ignore = [], all = YTMA.DB.views.getAllSiteSelectors().split(','), blacklist = this.parentBlacklist;
  575. for (i = 0; i < blacklist.length; i++) {
  576. for (j = 0; j < all.length; j++) {
  577. ignore.push(blacklist[i] + ' ' + all[j]);
  578. }
  579. }
  580. //console.log(ignore);
  581. return ignore.join(',');
  582. },
  583. links: function () {
  584. var links;
  585.  
  586. $$.x(YTMA.selector.ignore()).map(function (el) { el.setAttribute('ytmaignore', true); });
  587.  
  588. links = $$.x(YTMA.DB.views.getAllSiteSelectors()).filter(function (el) {
  589. var r = !el.hasAttribute('ytmaprocessed') && !el.hasAttribute('ytmaignore');
  590. el.setAttribute('ytmaprocessed', true);
  591. return r;
  592. });
  593.  
  594. return links;
  595. },
  596. processor: function () {
  597. var links = this.links();
  598.  
  599. if (links.length > 0) {
  600. if (window.chrome && (/(?:Chrome\/(\d+))/.exec(window.navigator.appVersion) && RegExp.lastParen < 38)) {
  601. $$.s(YTMA.selector.chrome37Blacklist, function (a) {
  602. if (/(?:\.webm)/i.test(a.href)) {
  603. a.dataset.ytmscroll = false;
  604. }
  605. });
  606. }
  607.  
  608. links.forEach(YTMA.create);
  609. }
  610.  
  611. return links.length;
  612. }
  613. };
  614.  
  615. /**
  616. * User Preferences
  617. * size: Small (240p), Medium (360p), Large (480p), XL (720p)
  618. * ratio: 1 4:3, 2 16:9
  619. * quality: 240, 360, 480, 720, 1080
  620. * focus: 0/1; Will attempt to set the window's focus near the video
  621. * autoShow: 0/1; Will automatically display HTML5 videos, which currently lack descriptions and thumbnails
  622. * desc: (Descriptions) 0 None; 1 Yes on scroll; 2 Yes all at once
  623. * yt_nocookie: 0/1; Will disable/enable youtube-nocookie.com
  624. * yt_volume: positive number; youtube volume
  625. * yt_annotation: 0/1; youtube annotations
  626. */
  627. YTMA.user = {
  628. KEY: 'ytmasetts',
  629. $form: null,
  630. init: function () {
  631. this.load();
  632.  
  633. if (strg.on) {
  634. this.fn.makeForm();
  635. this.mark();
  636. }
  637. },
  638. valid: {
  639. focus: [0, 1],
  640. desc: [0, 1, 2],
  641. ratio: [1, 2],
  642. size: [240, 360, 480, 720],
  643. quality: [240, 360, 480, 720, 1080],
  644. autoShow: [0, 1],
  645. yt_nocookie: [0, 1],
  646. yt_annotation: [0, 1], // hide | show
  647. yt_volume: 100 // todo? (function () { var a = new Array(101); for (i = 0; i <= 100; i++) { a[i] = i; } return a; }())
  648. },
  649. mapping: { // map values to some other values used by an external API, for example
  650. yt_annotation: [3, 1] // 3 = hide | 1 = show
  651. },
  652. validate: function (property, n) {
  653. n = +n;
  654.  
  655. if (property === 'yt_volume') {
  656. return n >= 0 && n <= 100 ? (+n) : YTMA.user.defaults()[property];
  657. }
  658. return YTMA.user.valid[property].indexOf(n) > -1 ? n : YTMA.user.defaults()[property];
  659. },
  660. defaults: function () {
  661. return {
  662. focus : 0,
  663. desc : 1,
  664. ratio : 2,
  665. size : 360,
  666. quality : 720,
  667. autoShow : 1,
  668. yt_nocookie : 0,
  669. yt_annotation : 1,
  670. yt_volume : 100
  671. };
  672. },
  673. load: function () {
  674. var s = strg.grab(YTMA.user.KEY, {});
  675.  
  676. YTMA.user.preferences = {
  677. size : YTMA.user.validate('size', s.size),
  678. ratio : YTMA.user.validate('ratio', s.ratio),
  679. desc : YTMA.user.validate('desc', s.desc),
  680. focus : YTMA.user.validate('focus', s.focus),
  681. quality : YTMA.user.validate('quality', s.quality),
  682. autoShow : YTMA.user.validate('autoShow', s.autoShow),
  683. yt_nocookie : YTMA.user.validate('yt_nocookie', s.yt_nocookie),
  684. yt_annotation : YTMA.user.validate('yt_annotation', s.yt_annotation),
  685. yt_volume : YTMA.user.validate('yt_volume', s.yt_volume)
  686. };
  687.  
  688. $$.o(YTMA.user.mapping, function (key, val) {
  689. if (!val.hasOwnProperty('indexOf')) {
  690. YTMA.user.preferences[key] = val[YTMA.user.valid[key].indexOf(YTMA.user.preferences[key])];
  691. }
  692. });
  693.  
  694. console.log('loaded: ', YTMA.user.preferences);
  695. },
  696. mark: function () {
  697. var a = {};
  698. a.ytma__focus = !!YTMA.user.preferences.focus;
  699. a.ytma__autoShow = !!YTMA.user.preferences.autoShow;
  700. a.ytma__yt_nocookie = !!YTMA.user.preferences.yt_nocookie;
  701. a.ytma__yt_annotation = !!YTMA.user.preferences.yt_annotation;
  702. a.ytma__yt_volume = YTMA.user.preferences.yt_volume;
  703. a['ytma__ratio' + YTMA.user.preferences.ratio] = true;
  704. a['ytma__size' + YTMA.user.preferences.size] = true;
  705. a['ytma__desc' + YTMA.user.preferences.desc] = true;
  706. a['ytma__quality' + YTMA.user.preferences.quality] = !!YTMA.user.preferences.quality;
  707.  
  708. // console.log('marking', a);
  709. $$.o(a, function (id, val) {
  710. try {
  711. var el = document.getElementById(id);
  712. el.checked = val;
  713. el.value = val;
  714. } catch (e) {
  715. // console.log(id, e);
  716. }
  717. });
  718. },
  719. events: {
  720. save: function (e) {
  721. var o = {};
  722.  
  723. if (e && (/(?:INPUT|LABEL)/i).test(e.target.nodeName)) {
  724. // console.log(YTMA.user.$form.querySelectorAll('[data-key]'));
  725. // [data-key]:checked
  726. $$.ary(YTMA.user.$form.querySelectorAll('[data-key]')).forEach(function (e) {
  727. var key;
  728. key = e.dataset.key;
  729.  
  730. if (e.type === 'checkbox') {
  731. o[key] = +e.checked;
  732. } else if (e.type === 'radio') {
  733. if (e.checked) {
  734. if (e.hasAttribute('data-num')) {
  735. o[key] = +e.dataset.num;
  736. }
  737. }
  738. } else {
  739. o[key] = +e.value;
  740. }
  741. });
  742.  
  743. if (strg.save(YTMA.user.KEY, o)) {
  744. YTMA.user.load();
  745. } else {
  746. YTMA.user.error.classList.remove('ytm_none');
  747. }
  748. }
  749.  
  750. },
  751. reset: function () {
  752. YTMA.user.preferences = YTMA.user.defaults();
  753. YTMA.user.mark();
  754. strg.wipe(YTMA.user.KEY);
  755. YTMA.user.error.classList.add('ytm_none');
  756. },
  757. clear: function () {
  758. try {
  759. localStorage.removeItem(YTMA.external.version);
  760. YTMA.user.events.reset();
  761. console.log('removed all YTMA cache');
  762. } catch (e) {
  763. console.error(e);
  764. }
  765. },
  766. formToggle: function (e) {
  767. if (!e || (e && e.target && !(/(?:INPUT|LABEL)/i).test(e.target.nodeName))) {
  768. YTMA.user.$form.classList.toggle('ytm_none');
  769. }
  770. },
  771. formToggleKeyboard: function (e) {
  772. // press CTRL+SHIFT+Y (META+SHIFT+Y) to display settings form
  773. if ((e.ctrlKey || e.metaKey) && e.shiftKey && String.fromCharCode(e.which).toLowerCase() === 'y') {
  774. e.preventDefault();
  775. YTMA.user.events.formToggle();
  776. }
  777. }
  778. },
  779. fn: {
  780. $scroller: null,
  781. $once: false,
  782. loadPreferences: function () {
  783. YTMA.user.fn.onScrollLoadDescriptions(YTMA.user.preferences.desc === 1);
  784.  
  785. this.loadPreferencesOnce();
  786. },
  787. loadPreferencesOnce: function () {
  788. if (this.$once) { return; }
  789.  
  790. this.$once = true;
  791.  
  792. if (YTMA.user.preferences.autoShow === 1) {
  793. YTMA.user.fn.onScrollViewMedia();
  794. }
  795. },
  796. showMedia: function () {
  797. console.log('showMedia');
  798. return new YTMA.Scroll('a.ytm_scroll:not([data-ytmscroll="false"])', function (link) {
  799. if (YTMA.Scroll.visibleAll(link, 50)) {
  800. $$.s('var[data-ytmsid="' + link.dataset.ytmsid + '"]:not([data-ytmscroll="false"])', function (trigger) {
  801. var ui = YTMA.UI.createFromTrigger(trigger);
  802. ui.showOnScroll(link);
  803. });
  804. }
  805. });
  806. },
  807. toggleMedia: function () {
  808. return new YTMA.Scroll('div.ytm_panel_switcher', function (div) {
  809. var v = div.querySelector('video'),
  810. paused = v && (v.paused || v.ended),
  811. ui = YTMA.set[div.dataset.ytmuid].getUI();
  812.  
  813. if (paused && !YTMA.Scroll.visibleAll(div, 0)) {
  814. return ui.play.switchStandby();
  815. }
  816.  
  817. if (ui.play.isStandby() && YTMA.Scroll.visibleAll(div, 200)) {
  818. return ui.play.switchOn();
  819. }
  820.  
  821. // todo ascertain embedded player properties
  822. // f = div.querySelector('iframe, object');
  823. // if (f && !YTMA.Scroll.visibleAll(div, 200)) {
  824. // y.hidePlayer();
  825. // }
  826. });
  827. },
  828. onScrollViewMedia: function () {
  829. this.showMedia();
  830. this.toggleMedia();
  831. },
  832. onScrollLoadDescriptions: function (ajax) {
  833. if (YTMA.user.fn.$scroller) { YTMA.user.fn.$scroller.stop(); }
  834.  
  835. YTMA.user.fn.$scroller = new YTMA.Scroll('span.ytm_manual > a.ytm_title:not(.ytm_error)', function (a) {
  836. if (YTMA.Scroll.visibleAll(a, 200)) {
  837. if (ajax) {
  838. YTMA.ajax.loadFromDataset(a.dataset);
  839. } else {
  840. YTMA.ajax.loadFromCacheDataset(a.dataset);
  841. }
  842. // console.log('doc', document.querySelectorAll(YTMA.user.fn.$scroller.selector).length, a.dataset.id);
  843. }
  844.  
  845. if (document.querySelectorAll(YTMA.user.fn.$scroller.selector).length === 0) {
  846. YTMA.user.fn.$scroller.stop();
  847. }
  848. });
  849. },
  850. makeForm: function () {
  851. var e, f = [
  852. '<div id="ytm_settings" class="ytm_sans ytm_block ytm_normalize"><form action="" title="Double click to close"><div id="ytm_settingst">ytma! Site Settings</div><div class="ytm_field_container">',
  853. '<fieldset><legend title="Load descriptions from the content sever.">Load Descriptions</legend><p><span><input id="ytma__desc0" type="radio" data-num="0" name="ytma__desc" data-key="desc"><label for="ytma__desc0" title="Load descriptions on demand">Manually</label></span><span><input id="ytma__desc1" type="radio" data-num="1" name="ytma__desc" data-key="desc"><label for="ytma__desc1" title="Load descriptions as they become visible on the screen.">Automatically, on scrolling</label></span></p></fieldset>',
  854. '<fieldset><legend>HTML5 Players</legend><p><input name="ytma__autoShow" data-key="autoShow" id="ytma__autoShow" type="checkbox"><label for="ytma__autoShow">Automatically show WebM, MP4 and Soundcloud players</label></p></fieldset>',
  855. '<fieldset><legend>Player Size</legend><p><span><input type="radio" name="ytma__size" data-key="size" data-num="240" id="ytma__size240" /><label for="ytma__size240">S <small>240p</small></label></span><span><input name="ytma__size" data-key="size" type="radio" id="ytma__size360" data-num="360" /><label for="ytma__size360">M <small>360p</small></label></span><span><input type="radio" name="ytma__size" data-key="size" data-num="480" id="ytma__size480" /><label for="ytma__size480">L <small>480p</small></label></span><span><input type="radio" name="ytma__size" data-key="size" data-num="720" id="ytma__size720" /><label for="ytma__size720">X <small>720p</small></label></span></p></fieldset>',
  856. '<fieldset><legend>Quality</legend><p><span><input name="ytma__quality" data-key="quality" data-num="240" id="ytma__quality240" type="radio"><label for="ytma__quality240">240p</label></span><span><input name="ytma__quality" data-key="quality" id="ytma__quality360" data-num="360" type="radio"><label for="ytma__quality360">360p</label></span><span><input name="ytma__quality" data-key="quality" data-num="480" id="ytma__quality480" type="radio"><label for="ytma__quality480">480p</label></span><span><input name="ytma__quality" data-key="quality" data-num="720" id="ytma__quality720" type="radio"><label for="ytma__quality720">720p</label></span><span><input name="ytma__quality" data-key="quality" data-num="1080" id="ytma__quality1080" type="radio"><label for="ytma__quality1080">1080p</label></span></p></fieldset>',
  857. '<fieldset><legend>Aspect Ratio</legend><p><span><input name="ytma__ratio" data-key="ratio" type="radio" id="ytma__ratio2" data-num="2" /><label for="ytma__ratio2">16:9</label></span><span><input type="radio" name="ytma__ratio" data-key="ratio" data-num="1" id="ytma__ratio1" /><label for="ytma__ratio1">4:3</label></span></p></fieldset>',
  858. '<fieldset><legend>YouTube</legend>',
  859. '<p><input name="ytma__yt_annotation" data-key="yt_annotation" type="checkbox" id="ytma__yt_annotation" /><label for="ytma__yt_annotation">Enable video annotations</label></p>',
  860. '<p><input name="ytma__yt_nocookie" data-key="yt_nocookie" type="checkbox" id="ytma__yt_nocookie" /><label for="ytma__yt_nocookie">Use https://youtube-nocookie.com to load videos</label></p>',
  861. '<p><input name="ytma__yt_volume" data-key="yt_volume" type="number" style="width:4em" min=0 max=100 id="ytma__yt_volume" /><label for="ytma__yt_volume">Video volume (Experimental)</label></p>',
  862. '</fieldset>',
  863. '<fieldset><legend>Window Focus</legend><p><input name="ytma__focus" data-key="focus" type="checkbox" id="ytma__focus" value="focus" /><label for="ytma__focus">After clicking the thumbnail, set the video at the top of the window.</label></p></fieldset>',
  864. '</div><p><small id="ytm_settings_error" class="ytm_error ytm_none ytm_title">Error! Your settings could not be saved.</small></p><p id="ytm_opts"><button type="button" id="ytmaclose">Close</button> <button type="button" id="ytmareset">Reset</button> <button type="button" id="ytmaclear" title="Remove all video descriptions that have been cached">Reset & Remove Cache</button></p></form></div>'
  865. ].join('');
  866.  
  867. YTMA.user.$form = $$.e('div', {className: 'ytm_fix_center ytm_none ytm_box', innerHTML: f}, document.body);
  868. YTMA.user.error = document.getElementById('ytm_settings_error');
  869.  
  870. e = YTMA.Scroll.debounce(YTMA.user.events.save, 500);
  871. YTMA.user.$form.addEventListener('submit', function (evt) { evt.preventDefault(); }, false);
  872. YTMA.user.$form.addEventListener('keyup', e, false);
  873. YTMA.user.$form.addEventListener('click', e, false);
  874.  
  875. YTMA.user.$form.addEventListener('dblclick', YTMA.user.events.formToggle, false);
  876. document.getElementById('ytmaclose').addEventListener('click', YTMA.user.events.formToggle, false);
  877. document.getElementById('ytmareset').addEventListener('click', YTMA.user.events.reset, false);
  878. document.getElementById('ytmaclear').addEventListener('click', YTMA.user.events.clear, false);
  879. document.body.addEventListener('keydown', YTMA.user.events.formToggleKeyboard, false);
  880. }
  881. }
  882. };
  883.  
  884. YTMA.css = function () {
  885. var playerCss = YTMA.Player.css.generator(),
  886. loadingIcon = 'data:image/gif;base64,R0lGODlhDgAKAJEAAP///+BKV////wAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgACACwAAAAADgAKAAACHFSOeQYI71p6MtAJz41162yBH+do5Ih1kKG0QgEAIfkEBQoAAgAsAAABAA0ACAAAAhSUYGEoerkgdIzKGlu2ET/9ceJmFAAh+QQFCgACACwAAAEADQAIAAACFJRhcbmiglx78SXKYK6za+NxHyYVACH5BAUKAAIALAAAAQANAAgAAAIWVCSAl+hqEGRTLhtbdvTqnlUf9nhTAQAh+QQFCgACACwAAAEADQAIAAACFZRiYCh6uaCRzNXYsKVT+5eBW3gJBQAh+QQJCgACACwAAAAADgAKAAACGpSPaWGwfZhwQtIK8VTUvuxpm9Yp4XlmpiIUADs=';
  887.  
  888. // Roboto font-o
  889. // $$.e('link', {
  890. // rel: 'stylesheet',
  891. // $type: 'text/css',
  892. // href: 'https://fonts.googleapis.com/css?family=Roboto'
  893. // }, document.body);
  894.  
  895. // console.log(playerCss);
  896. $$.css(playerCss);
  897.  
  898. // images
  899. // todo update(site, size, padding)
  900. $$.css([
  901. '.ytm_loading{background:url(', loadingIcon, ') 0 3px no-repeat;}',
  902. '.ytm_link{background:url(', YTMA.DB.sites.youtube.favicon, ') 0 center no-repeat !important;margin-left:4px;padding-left:20px!important;}',
  903. '.ytm_link.ytm_link_vimeo{background-image:url(', YTMA.DB.sites.vimeo.favicon, ') !important;background-size:12px 12px !important;padding-left:18px!important}',
  904. '.ytm_link.ytm_link_vine{background-image:url(', YTMA.DB.sites.vine.favicon, ') !important;background-size:10px 10px!important;padding-left:16px!important}',
  905. '.ytm_link.ytm_link_soundcloud{background-image:url(', YTMA.DB.sites.soundcloud.favicon, ')!important;padding-left:17px!important}',
  906. '.ytm_link.ytm_link_html5{background-image:url(', YTMA.DB.sites.html5.favicon, ') !important;padding-left:16px!important}',
  907. '.ytm_link.ytm_link_gfycat{background-image:url(', YTMA.DB.sites.gfycat.favicon, ') !important;background-size:12px 12px !important;padding-left:16px!important;}',
  908. '.ytm_link.ytm_link_imgur{background-image:url(', YTMA.DB.sites.imgur.favicon, ') !important;background-size:12px 12px !important;padding-left:16px!important}',
  909. '.ytm_link.ytm_link_streamable{background-image:url(', YTMA.DB.sites.streamable.favicon, ') !important; background-size: 12px 12px !important;padding-left: 14px !important;}'
  910. ].join(''));
  911.  
  912. // todo
  913. // if (window.NO_YTMA_CSS) { return; }
  914.  
  915. $$.css('.ytm_none,.ytm_link br{display:none!important}.ytm_box{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.ytm_block{display:block;position:relative;clear:both;text-align:left;border:0;margin:0;padding:0;overflow:hidden}.ytm_normalize{font-weight:400!important;font-style:normal!important;line-height:1.2!important}.ytm_sans{font-family:Arial,Helvetica,sans-serif!important}.ytm_spacer{overflow:auto;margin:0 0 6px;padding:4px}.ytm_spacer.ytm_site_slim{display:inline}.ytm_clear:after{content:"";display:table;clear:both}.ytm_center{text-align:center}.ytm_link b,.ytm_link strong{font-weight:400!important}.ytm_link u{text-decoration:none!important}.ytm_link i,.ytm_link em{font-style:normal!important}.ytm_trigger{width:118px;height:66px;background-color:#262626!important;cursor:pointer;background-position:-1px -12px;float:left;box-shadow:2px 2px rgba(0,0,0,.3);background-size:auto 90px!important;color:#fff;text-shadow:#333 0 0 2px;font-size:13px}.ytm_trigger:hover{box-shadow:2px 2px #9eae9e;opacity:.95}.ytm_trigger var{z-index:2;height:100%;width:100%;position:absolute;left:0;top:0;text-align:right}.ytm_label{display:block;padding:3px 6px;line-height:1.2;font-style:normal}.ytm_init{height:22px;background:rgba(11,11,11,.62);padding:4px 25px 6px 6px}.ytm_site_vine .ytm_trigger{background-color:#90ee90!important;background-size:120px auto!important}.ytm_site_slim .ytm_trigger{background:#e34c26!important;height:auto;box-shadow:0 0 2px #ffdb9d inset,2px 2px rgba(0,0,0,.3);margin:0 3px 0 0;width:auto;transition:all .3s ease-in-out 0s}.ytm_site_slim .ytm_trigger:hover{opacity:.8}.ytm_site_slim .ytm_label{text-shadow:0 0 1px #f06529}.ytm_site_slim .ytm_init{background:transparent}.ytm_bd{float:left;max-width:500px;margin:2px 10px;font-size:90%}.ytm_title{font-weight:700}.ytm_error{color:#cc2f24;font-style:italic}.ytm_loading{font-style:italic;padding:1px 1.5em}.ytm_descr{word-wrap:break-word;max-height:48px;overflow:auto;padding-right:20px}.ytm_descr[data-full]{cursor:pointer}.ytm_descr_open{resize:both;white-space:pre-line}.ytm_descr_open[style]{max-height:none}.ytm_projector{margin-bottom:4px}ul.ytm_control{overflow:hidden;margin:0!important;padding:3px 0 1px;list-style-position:outside!important}.ytm_control li{display:inline;margin:0!important;padding:0!important}.ytm_control li>ul{display:inline-block;margin:0;padding:0 1px 0 0}.ytm_control li ul li{-webkit-user-select:none;-moz-user-select:none;-o-user-select:none;user-select:none;list-style-type:none;cursor:pointer;float:left;color:#858585;border:1px solid #1d1d1d;border-bottom:1px solid #000;border-top:1px solid #292929;box-shadow:0 0 1px #555;height:14px;font-size:12px!important;line-height:12px!important;background:#222;background:linear-gradient(#2d2c2c,#222);margin:0!important;padding:5px 9px 3px!important}.ytm_control li ul li:first-child{border-radius:2px 0 0 2px}.ytm_control li ul li:last-child{border-left:0!important;border-radius:0 2px 2px 0;margin:0 2px 0 0!important}.ytm_control li ul li:first-child:last-child,.ytm_li_setting{border-radius:2px}.ytm_control li ul li:hover{color:#ccc;text-shadow:1px 1px 0 #333;background:#181818}.ytm_control li ul li[id]{color:#ddd;text-shadow:0 0 2px #444}.ytm_panel_size{background:#000;max-width:100%;}.ytm_panel_switcher[data-standby="true"]{background:#111}.ytm_panel_switcher[data-standby="true"]:after{cursor:cell;color:#0e0e0e;content:"ytma!";display:block;font-size:85px;font-style:italic;font-weight:700;left:50%;position:absolute;text-shadow:2px 1px #181818,-1px -1px #0a0a0a;top:50%;transform:translate(-50%,-50%)}.ytm_site_soundcloud .ytm_panel_size.ytm_soundcloud-playlist{height:334px!important}.ytm_fix_center{background:rgba(51,51,51,.41);height:100%;left:0;position:fixed;top:0;width:100%;z-index:99998}#ytm_settings{z-index:99999;max-width:500px;max-height:85%;overflow:auto;background:#fbfbfb;border:1px solid #bbb;color:#444;box-shadow:0 0 5px rgba(0,0,0,.2),0 0 3px rgba(239,239,239,.1) inset;margin:4% auto;padding:4px 8px 0}#ytm_settings p{margin:5px 0;padding:0}#ytm_settings fieldset{vertical-align:top;border-radius:3px;border:1px solid #ccc;margin:0 0 5px}#ytm_settings fieldset span{display:inline-block;min-width:5em}#ytm_settings input{vertical-align:baseline!important;margin:3px 5px!important}#ytm_settingst{font-size:110%;border-bottom:1px solid #d00;margin:3px 0 9px;padding:0 3px 3px}#ytm_settings label{cursor:pointer}#ytm_settings small{font-size:90%}#ytm_opts button{cursor:pointer;margin:10px 5px 8px 2px;padding:3px;border:1px solid #adadad;border-radius:2px;background:#eee;font-size:90%}#ytm_opts button:hover{background:#ddd}');
  916. // $$.css('.ytm_site_youtube .ytm_sans { font-family: \'Roboto\'; }');
  917. };
  918.  
  919. YTMA.ajax = {
  920. load: function (site, id, uri) {
  921. console.log('YTMA.ajax.load:', site, id, uri);
  922. uri = YTMA.DB.sites[site].ajax.replace('%key', id).replace('%uri', uri);
  923.  
  924. if (YTMA.DB.sites[site].ajaxExtension) { return this.gmxhr(uri, site, id); }
  925.  
  926. console.log('ajax.site?', YTMA.DB.sites[site].ajax.replace('%key', id).replace('%uri', uri));
  927. if (YTMA.DB.sites[site].ajax) {
  928. console.log('preping uri');
  929. return this.xhr(uri, site, id);
  930. }
  931.  
  932. return null;
  933. },
  934. loadFromDataset: function (dataset) {
  935. if (!this.loadFromCacheDataset(dataset)) {
  936. return this.load(dataset.ytmsite, dataset.ytmid, dataset.ytmuri);
  937. }
  938. },
  939. loadFromCacheDataset: function (dataset) {
  940. var cache = YTMA.external.dataFromStorage(dataset.ytmsite, dataset.ytmid);
  941.  
  942. console.log('YTMA.ajax.cache:', dataset.ytmsite, dataset.ytmid);
  943. console.log('@cache:', cache);
  944.  
  945. if (cache) { YTMA.external.populate(cache); }
  946.  
  947. return cache;
  948. },
  949. gmxhr: function (uri, site, id) {
  950. try {
  951. // console.log('gmxhr starting!');
  952. GM_xmlhttpRequest({
  953. method: 'GET',
  954. url: uri,
  955. onload: function (response) {
  956. // console.log(response);
  957. YTMA.external.parse(response.responseText, site, id);
  958. },
  959. onerror: function () {
  960. console.log('GM Cannot XHR');
  961. YTMA.ajax.failure.call({id: id});
  962. }
  963. });
  964.  
  965. YTMA.ajax.preProcess(id);
  966.  
  967. } catch (e) {
  968. if (YTMA.DB.extension) {
  969. console.log('attempting cs xhr');
  970. this.xhr(uri, site, id);
  971. } else {
  972. console.log('No applicable CORS request available.');
  973. this.failure.call({id: id});
  974. }
  975. }
  976. },
  977. xhr: function (uri, site, id) {
  978. var x = new XMLHttpRequest();
  979. console.log('xhr', uri, id, site);
  980.  
  981. YTMA.ajax.preProcess(id);
  982.  
  983. x.onreadystatechange = function () {
  984. if (this.readyState === this.DONE) {
  985. // console.log(this.readyState, this.status);
  986. if (this.status === 200) {
  987. YTMA.external.parse(this.responseText, site, id);
  988. } else if (this.status === 403) {
  989. YTMA.external.populate({site: site, id: id, title: 'Error 403', desc: ''});
  990. YTMA.external.save({site: site, id: id, title: 'Error 403', desc: ''});
  991. } else { // if (this.status >= 400 || this.status === 0) {
  992. YTMA.ajax.failure.call({id: id});
  993. }
  994. }
  995. };
  996.  
  997. try {
  998. console.log('sending');
  999. x.open('get', uri, true);
  1000. x.send();
  1001. } catch (e) {
  1002. console.error('Cannot send xhr', uri);
  1003. YTMA.ajax.failure.call({id: id});
  1004. console.error(e);
  1005. }
  1006. },
  1007. failure: function () {
  1008. $$.s('.ytm_bd._' + YTMA.escapeId(this.id), function (el) {
  1009. var a = el.querySelector('a');
  1010. a.dataset.tries = a.dataset.tries ? parseFloat(a.dataset.tries) + 1 : 1;
  1011. a.textContent = 'Error, unable to load data. ' + (a.dataset.tries > 0 ? ('(' + a.dataset.tries + ')') : '[Retry]');
  1012. a.className = 'ytm_error ytm_title';
  1013. });
  1014. },
  1015. preProcess: function (id) {
  1016. $$.s('.ytm_manual._' + YTMA.escapeId(id) + ' a', function (el) {
  1017. el.classList.add('ytm_loading');
  1018. el.textContent = 'Loading data . . .';
  1019. el.title = 'Retry loading data.';
  1020. });
  1021. }
  1022. };
  1023.  
  1024. /** E X T E R N A L Apparatus
  1025. * Data from external sites
  1026. */
  1027. YTMA.external = {
  1028. version: 'ytma.4.1.dat',
  1029. parse: function (response, site, id) {
  1030. if (this.parsers[site]) {
  1031. response = YTMA.DB.sites[site].rawResponse ? response : JSON.parse(response);
  1032. this.populate(this.helper.cutDescription(this.parsers[site](response, id)));
  1033. }
  1034. },
  1035. parsers: {
  1036. soundcloud: function (j, id) {
  1037. return {
  1038. site: 'soundcloud',
  1039. id: id, //unescape(j.html).match(/tracks\/(\d+)/)[1],
  1040. title: j.title,
  1041. desc: j.description,
  1042. th: removeSearch(j.thumbnail_url)
  1043. };
  1044. },
  1045. vimeo: function (j) {
  1046. j = j[0];
  1047. return {
  1048. site: 'vimeo',
  1049. id: j.id,
  1050. title: j.title + ' ' + YTMA.external.time.fromSeconds(j.duration),
  1051. desc: j.description.replace(/<br.?.?>/g, ''),
  1052. th: decodeURI(j.thumbnail_medium)
  1053. };
  1054. },
  1055. youtube: function (j, id) {
  1056. if (j.pageInfo.totalResults < 1) {
  1057. return { id: id, error: true };
  1058. }
  1059.  
  1060. j = j.items[0];
  1061. var o = {
  1062. site: 'youtube',
  1063. id: id,
  1064. title: j.snippet.title + ' ' + YTMA.external.time.fromIso8601(j.contentDetails.duration),
  1065. desc: j.snippet.description
  1066. // aspectRatio: j.contentDetails.aspectRatio
  1067. };
  1068.  
  1069. return o;
  1070. },
  1071. vine: function (j, id) {
  1072. return {
  1073. site: 'vine',
  1074. id: id,
  1075. title: j.title,
  1076. th: removeSearch(j.thumbnail_url)
  1077. };
  1078. },
  1079. gfycat: function (j, id) {
  1080. j = j.gfyItem;
  1081. if (j) {
  1082. return {
  1083. site: 'gfycat',
  1084. id: id || j.gfyName,
  1085. title: j.title || j.gfyName
  1086. };
  1087. }
  1088. },
  1089. streamable: function (j, id) {
  1090. return {
  1091. site: 'streamable',
  1092. id: id,
  1093. title: j.title || 'Untitled'
  1094. };
  1095. }
  1096. },
  1097. set: function (data) {
  1098. if (!this.db[data.site]) {
  1099. this.db[data.site] = {};
  1100. }
  1101. this.db[data.site][data.id] = data;
  1102. return this.save();
  1103. },
  1104. unset: function (data) {
  1105. // console.log('unset', data.id);
  1106. if (data.site) {
  1107. delete this.db[data.site][data.id];
  1108. return this.save();
  1109. }
  1110. },
  1111. limitDB: function (max, db) {
  1112. // limits an object's items by half of the max
  1113. // removes the older items at the start of the object
  1114. var keys = Object.keys(db),
  1115. half = Math.floor(max / 2),
  1116. start,
  1117. ndb,
  1118. i;
  1119.  
  1120. if (keys.length > max) {
  1121. ndb = {};
  1122. start = keys.length - half;
  1123.  
  1124. for (i = start; i < keys.length; i++) {
  1125. ndb[keys[i]] = db[keys[i]];
  1126. }
  1127. }
  1128.  
  1129. return ndb || db;
  1130. },
  1131. save: function () {
  1132. this.db = this.limitDB(1000, this.db);
  1133. return strg.save(this.version, this.db);
  1134. },
  1135. helper: {
  1136. cutDescription: function (data) {
  1137. if (data.desc && data.desc.length > 140) {
  1138. data.full = data.desc;
  1139. data.desc = data.desc.substr(0, 130) + ' . . .';
  1140. }
  1141. return data;
  1142. },
  1143. thumbnail: function (data) {
  1144. $$.s('[data-ytmid="%id"].ytm_trigger'.replace('%id', data.id), function (el) {
  1145. el.setAttribute('style', 'background: url(' + data.th + ')');
  1146. });
  1147. },
  1148. titleToggle: function () {
  1149. this.classList.toggle('ytm_descr_open');
  1150. this.textContent = this.textContent.length < 140 ? this.dataset.full : this.dataset.full.substr(0, 130) + ' . . .';
  1151. this.removeAttribute('style');
  1152. }
  1153. },
  1154. time: {
  1155. keepMinutesAndSeconds: function (v, i) {
  1156. return i > 1 || v > 0;
  1157. },
  1158. leadingZero: function (v, i) {
  1159. return i > 0 ? ('00' + v).slice(-2) : v;
  1160. },
  1161. fromArray: function (a) { // [days, hours, mins, secs]
  1162. var b, p = '';
  1163.  
  1164. try {
  1165. // Remove empty values, but keep lower indexes (m:s); a[i] > 0 || i > 1
  1166. // Add leading 0's, ignoring the first index
  1167. // a.slice(0, 1).concat(a.slice(1))
  1168. b = a.filter(this.keepMinutesAndSeconds).map(this.leadingZero);
  1169. p = '(' + b.join(':') + ')';
  1170. } catch (e) {
  1171. console.error('Could not parse this time.');
  1172. }
  1173.  
  1174. console.log({a: a, b: b, p: p });
  1175. return p;
  1176. },
  1177. fromIso8601: function (iso8601) { // eg PT3M, T29S
  1178. var a,
  1179. parseDigits = function (reg) {
  1180. if (reg.test(iso8601)) {
  1181. return RegExp.lastParen;
  1182. }
  1183. return 0;
  1184. };
  1185.  
  1186. // P#DT#H#M#S || PT#H#M#S
  1187. a = [/(\d+)D/, /(\d+)H/, /(\d+)M/, /(\d+)S/].map(parseDigits);
  1188.  
  1189. return this.fromArray(a);
  1190. },
  1191. fromSeconds: function (seconds) {
  1192. var a = [
  1193. Math.floor(seconds / 86400) % 24,
  1194. Math.floor(seconds / 3600) % 60,
  1195. Math.floor(seconds / 60) % 60,
  1196. seconds % 60
  1197. ];
  1198. return this.fromArray(a);
  1199. }
  1200. },
  1201. validate: function (data) {
  1202. if (!data || !data.id || data.error) {
  1203. return YTMA.ajax.failure.call(data);
  1204. }
  1205.  
  1206. // todo? empty titles and descriptions should be okay
  1207. // if (data.id && !data.title && !data.desc) {
  1208. // this.unset(data.id);
  1209. // return YTMA.ajax.failure.call(data);
  1210. // }
  1211.  
  1212. return true;
  1213. },
  1214. populate: function (data, ignoreValidation) {
  1215. if (!ignoreValidation && !this.validate(data)) { return; }
  1216.  
  1217. this.set(data);
  1218.  
  1219. if (data.th) { this.helper.thumbnail(data); }
  1220.  
  1221. $$.s('.ytm_bd._' + YTMA.escapeId(data.id), function (el) {
  1222. var q;
  1223. el.innerHTML = '<span class="ytm_title">' + data.title + '</span>';
  1224. if (data.desc) {
  1225. q = $$.e('q', { className: 'ytm_descr ytm_block', textContent: data.desc }, el);
  1226. if (data.full) {
  1227. q.dataset.full = data.full;
  1228. q.title = 'Click to toggle the length of the description.';
  1229. q.addEventListener('dblclick', YTMA.external.helper.titleToggle, false);
  1230. }
  1231. }
  1232. });
  1233. },
  1234. dataFromStorage: function (site, id) {
  1235. if (this.db && this.db[site]) {
  1236. return this.db[site][id];
  1237. }
  1238. },
  1239. events: {
  1240. manualLoad: function (e) {
  1241. // console.log(this);
  1242. e.preventDefault();
  1243. YTMA.ajax.loadFromDataset(e.target.dataset);
  1244. }
  1245. }
  1246. };
  1247. YTMA.external.db = strg.grab(YTMA.external.version, {});
  1248.  
  1249. /** Database */
  1250. YTMA.DB = {
  1251. postInit: function () {
  1252. if (YTMA.user.preferences.yt_nocookie) {
  1253. YTMA.DB.sites.youtube.home = 'https://www.youtube-nocookie.com/';
  1254. YTMA.DB.sites.youtube.embed = 'https://www.youtube-nocookie.com/embed/%key';
  1255. }
  1256. },
  1257. extension: window.chrome && window.chrome.extension,
  1258. browser: {
  1259. pod: YTMA.reg.ios.test(navigator.userAgent),
  1260. ie: !!document.documentMode, // IE, basically | window.navigator.cpuClass
  1261. safari: Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0
  1262. },
  1263. views: {
  1264. getAllSiteRegExps: function () {
  1265. var regs = [];
  1266.  
  1267. $$.o(YTMA.DB.sites, function (k, site) {
  1268. if (site.reg) {
  1269. regs.push(site.reg);
  1270. }
  1271. });
  1272.  
  1273. return new RegExp('\\b' + regs.join('|'));
  1274. },
  1275. getAllSiteSelectors: function () {
  1276. var sels = [];
  1277.  
  1278. $$.o(YTMA.DB.sites, function (k, site) {
  1279. if (site.selector) {
  1280. sels.push(site.selector);
  1281. }
  1282. });
  1283.  
  1284. return sels.join();
  1285. },
  1286. getPlayerSources: function (siteName) {
  1287. return YTMA.DB.sources[siteName] || YTMA.DB.sources.iframe;
  1288. },
  1289. getToolbar: function (site) {
  1290. var bar = YTMA.DB.customToolbars[site] || {};
  1291.  
  1292. return {
  1293. ratio: bar.ratio === undefined ? true : bar.ratio,
  1294. size: bar.size === undefined ? true : bar.size
  1295. };
  1296. },
  1297. getPlayerDimmensions: function (ratio, size) {
  1298. return 'ytm_panel ytm_block ytm_panel-' + YTMA.DB.playerSize.ratios[ratio]
  1299. + ' ytm_panel-' + YTMA.DB.playerSize.sizes[size];
  1300. },
  1301. getPlayerQuality: function (quality) {
  1302. return YTMA.DB.qualities[quality] || YTMA.DB.qualities[360];
  1303. }
  1304. },
  1305. sites: { // supported sites - to add more also make a parser (if api is available) and add an item to sources (if necessary)
  1306. youtube: {
  1307. title: 'ytma!',
  1308. home: 'https://www.youtube.com/',
  1309. embed: 'https://www.youtube.com/embed/%key',
  1310. ajax: 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=%key' + window.atob('JmtleT1BSXphU3lEVG5INkxzRERyVElYaFZTZWRQQjlyRHo1czBSczQzZnM='),
  1311. thumb: 'url(https://i3.ytimg.com/vi/%key/1.jpg)',
  1312. selector: 'a[href*="youtube."], a[href*="youtu.be/"]',
  1313. favicon: 'https://www.youtube.com/favicon.ico',
  1314. key: 'id',
  1315. reg: '(youtu)',
  1316. matcher: /(?:(?:(?:v\=|#p\/u\/\d*?\/)|(?:v\=|#p\/c\/[a-zA-Z0-9]+\/\d*?\/)|(?:embed\/)|(?:v\/)|(?:\.be\/))([A-Za-z0-9-_]{11}))/i,
  1317. https: true
  1318. },
  1319. vimeo: {
  1320. title: 'vimeo too!',
  1321. home: 'https://vimeo.com/',
  1322. embed: 'https://player.vimeo.com/video/%key?badge=0',
  1323. ajax: 'https://vimeo.com/api/v2/video/%key.json',
  1324. selector: 'a[href*="vimeo.com/"]',
  1325. favicon: 'https://f.vimeocdn.com/images_v6/favicon.ico',
  1326. key: 'id',
  1327. reg: '(vimeo)',
  1328. matcher: /(?:vimeo\.com\/(\d+))/i,
  1329. https: true
  1330. },
  1331. vine: {
  1332. title: 'vine me!',
  1333. home: 'https://vine.co/',
  1334. embed: 'https://vine.co/v/%key/embed/simple?audio=1',
  1335. ajaxExtension: true,
  1336. ajax: 'https://vine.co/oembed.json?url=https%3A%2F%2Fvine.co%2Fv%2F%key',
  1337. selector: 'a[href*="vine.co/"]',
  1338. favicon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABcklEQVQ4jX2SvyvFYRTGP+9NdzAYbpIkysA/ICnKoEwvA4vlUkoyGQzvoOiK4R0YbDLhDhbi9maWIjEqcScWkyRhMNzXcM/3On39OMt5nvOe85wfvSbGyH9mgs8Cq8AUkAMegU1gJVpXqfu3umpbwITiLUBB8HJGuryb4KMJ/izVvUMVnwNjwJPwGYCMkLL4zlT3XoUL0boD4FBNUhO4Fd9ogm9SRVmFn8Una79qgWuV2K3wvcLJdG3iL7TaiUocAI4Fn0vnHDBrgt+L1g2q3NoEl8CH4KHkMVr3CSwI7QeOTPA9WsAk/8AEvw+MSrwrWleuJQVfABZJWbTOZBTfVXg6lbgEHKjQTcL1BFngAWimeuH2aN2LvHUDV1JcjNbl0zdI9l0T2pDsboKvB7Yl/ga4X2+gku+AVqAC9AFzwLik5KN1xT8FRGQEOBL6yfdn2onWTZKyTDoQrSsB60KT4lNSh/1TQETmgQ1ZowQMy41+2BeLRXeRaKuHSAAAAABJRU5ErkJggg==',
  1339. key: 'id',
  1340. reg: '(vine)',
  1341. matcher: /(?:vine\.co\/v\/([A-Za-z0-9-_]{11}))/i
  1342. },
  1343. soundcloud: {
  1344. title: 'sound off!',
  1345. home: 'https://soundcloud.com/',
  1346. embed: 'https://w.soundcloud.com/player/?show_comments=false&url=%key',
  1347. ajax: 'https://soundcloud.com/oembed?format=json&url=%uri',
  1348. favicon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAXZJREFUeNp0UjFOw0AQnD3bCYaEoIgiUIQKikiAKKGgSAkFL0BQ0FEgUfECShpewB+QEE+gokDiBxGRiCCEBBzHd8ucLYGQ4Kw7+9azc7OzJ6oKnFYUxgD+W/DHYNA54GIooifTitYqg1okaPFff6BcTLF5fECYb5IJNJ3kMfUP2dxHPycwcQ0SliARocSGsA46YkKWQW0GS6BDAGlu5Myu84AgSmHKM/DY0NegwwR2+AJrSjBre5BaA1H7GFKpI729QHp9jqiaeTBn5mB7fWirjWB9B9JYBrwEMnop5d0zfD53YO9vYMY8SQcpZGkTZvsIstiivDfoaxfIxt8exYeXCLYOSOwlJZQ6twSpL0DfX4EoZtkCqc7/Njalbxnfdt+oSwhurkBnCWI/1FlgqgKNZ3JnZDSA3FFSpYdQAoF56tKNDmhOYTzJ3OSHXZkflJhYEyawcnH02HpmxZ+DrRJlgmacvrsHRmHln2tRnIiAy5WTLwEGAK4QoBQmtGHkAAAAAElFTkSuQmCC',
  1349. selector: 'a[href*="soundcloud.com/"]',
  1350. key: 'uri',
  1351. reg: '(soundcloud)',
  1352. matcher: /(?:\/\/(?:\bwww|m\.\b)?soundcloud\.com\/(.+?\/.+))/i,
  1353. https: true,
  1354. scroll: true
  1355. },
  1356. gfycat: {
  1357. title: 'gfycat meow!',
  1358. home: 'https://gfycat.com/',
  1359. embed: 'https://gfycat.com/iframe/%key',
  1360. ajax: 'https://gfycat.com/cajax/get/%key',
  1361. thumb: 'url(https://thumbs.gfycat.com/%key-poster.jpg)',
  1362. selector: 'a[href*="gfycat.com/"]',
  1363. favicon: 'https://gfycat.com/favicon.ico',
  1364. key: 'id',
  1365. reg: '(gfycat)',
  1366. matcher: /(?:gfycat\.com\/(?:(\b(?:[A-Z][a-z]*){3,}\b)))/i,
  1367. https: true,
  1368. scroll: true,
  1369. videoTag: true
  1370. },
  1371. streamable: {
  1372. title: 'streamable!',
  1373. home: 'https://streamable.com/',
  1374. embed: 'https://streamable.com/e/%key',
  1375. ajax: 'https://api.streamable.com/oembed.json?url=%uri',
  1376. thumb: 'url(https://cdn.streamable.com/image/%key.jpg)',
  1377. selector: 'a[href*="streamable.com/"]',
  1378. favicon: 'https://streamable.com/favicon.ico',
  1379. key: 'id',
  1380. reg: '(streamable\\.com)',
  1381. matcher: /(?:streamable\.com\/([A-Za-z0-9-_]+))/i,
  1382. https: true
  1383. },
  1384. imgur: {
  1385. title: 'imgur it!',
  1386. home: 'https://i.imgur.com/',
  1387. embed: 'https://i.imgur.com/%key',
  1388. thumb: 'url(https://i.imgur.com/%keyh.jpg)',
  1389. selector: 'a[href*=".gifv"]',
  1390. favicon: 'https://imgur.com/favicon.ico',
  1391. reg: '(\\.gifv$)|(imgur)',
  1392. matcher: /(?:imgur\.com\/(\w+)\.(?:gifv|mp4|webm))/i,
  1393. https: true,
  1394. scroll: true,
  1395. videoTag: true
  1396. },
  1397. html5: {
  1398. home: true,
  1399. title: 'html5 go!',
  1400. selector: 'a[href*=".webm"], a[href*=".mp4"]',
  1401. favicon: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAANCAYAAABy6+R8AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAdlJREFUeNpcks9rE0EUx7+b3TRktxvbhUhrNm6SrUWtxxbxJ9iLl0JFKWg8WLD05EWhIuRieogXwYPX4tGb/gPSq/oP6KH+uG2MFaRJJXaTbp7fWbsl+uDDzLx533lv3ozmeyUM2VlSJxeISULygTwhr5Og1JDgOXlPrpLRMAxTIpLlfJa8Ipv/i56Re4lT07SYKIqQSh2eO0/eqYnujI35HF8O19jr9XBneRmt1je0d3ag63qy5ZIAvNObE+WKTJXKktENoVPsrCntdlsWFxbiNXNJyS3KdMUXxv8w6LzY7XZhmiYer9fBYOTzR5HL5XCzWsWxYhFnTs/gxcYGgiCAZVmOyhR5BVcm8nlZvbsi29+3ZdgGg4Gs1+viua4UJiZVpkiJeqo0VaIqxbGPSKfTORRduXQ59peLx5PyItWaj9yDQtmt21XYto1GoxGvbywtxaNhGHE3ab+V6L6aKYczPo7ZuTk8WnuIWq2G64vX4JU8zJw8BXXv5D21gx+xydrn7VEb/f0+tj5twa/4+Pz1C6Y4Oo6DZrOJdDrdYuxkIlKP+ZbZzoV7e8iyk8kD/9rdRXpkBJlMpsmDC/98I97pPF//AQUBl/2/jRvsm5b1kxmeJgJlfwQYAKZQxgzeI6/EAAAAAElFTkSuQmCC',
  1402. reg: '(\\.webm$)|(\\.mp4$)',
  1403. slim: true,
  1404. scroll: true,
  1405. videoTag: true
  1406. },
  1407. 'html5-audio': {
  1408. home: true,
  1409. title: 'hey, listen!',
  1410. selector: 'a[href*=".mp3"]',
  1411. reg: '(\\.mp3$)',
  1412. slim: true,
  1413. scroll: true
  1414. }
  1415. },
  1416. sources: {
  1417. iframe: function (data) {
  1418. var key = YTMA.DB.sites[data.site].key;
  1419.  
  1420. return [
  1421. {type: 'text/html', src: YTMA.DB.sites[data.site].embed.replace('%key', data[key]) }
  1422. ];
  1423. },
  1424. 'html5-audio': function (data) {
  1425. return [
  1426. {type: 'audio/mp3', src: data.uri}
  1427. ];
  1428. },
  1429. html5: function (data) {
  1430. // attaching the type as either mp4 or webm
  1431.  
  1432. if (/(?:webm)/.test(data.uri)) {
  1433. return [
  1434. {type: 'video/webm', src: data.uri}
  1435. ];
  1436. }
  1437.  
  1438. return [
  1439. {type: 'video/mp4', src: data.uri},
  1440. {type: 'video/webm', src: data.uri},
  1441. {type: 'video/ogg; codecs="theora, vorbis"', src: data.uri}
  1442. ];
  1443. },
  1444. imgur: function (data) {
  1445. var src = YTMA.DB.sites.imgur.embed.replace('%key', data.id);
  1446.  
  1447. return [
  1448. {type: 'video/webm', src: src + '.webm'},
  1449. {type: 'video/mp4', src: src + '.mp4'}
  1450. ];
  1451. },
  1452. gfycat: function (data) {
  1453. return [
  1454. {type: 'video/mp4', src: 'https://zippy.gfycat.com/' + data.id + '.mp4'},
  1455. {type: 'video/mp4', src: 'https://fat.gfycat.com/' + data.id + '.mp4'},
  1456. {type: 'video/mp4', src: 'https://giant.gfycat.com/' + data.id + '.mp4'},
  1457. {type: 'video/webm', src: 'https://zippy.gfycat.com/' + data.id + '.webm'},
  1458. {type: 'video/webm', src: 'https://fat.gfycat.com/' + data.id + '.webm'},
  1459. {type: 'video/webm', src: 'https://giant.gfycat.com/' + data.id + '.webm'}
  1460. ];
  1461. },
  1462. youtube: function (data, attrs) {
  1463. var params = '?html5=1&version=3&modestbranding=1&theme=dark&color=white&showinfo=1&vq=' + attrs.quality
  1464. + '&iv_load_policy=' + YTMA.user.preferences.yt_annotation
  1465. + '&start=' + attrs.start
  1466. + '&volume=' + YTMA.user.preferences.yt_volume;
  1467.  
  1468. return [
  1469. {type: 'text/html', src: YTMA.DB.sites.youtube.embed.replace('%key', data.id) + params}
  1470. ];
  1471. }
  1472. },
  1473. customToolbars: {
  1474. vine: {
  1475. ratio: false,
  1476. size: true
  1477. },
  1478. soundcloud: {
  1479. ratio: false,
  1480. size: false
  1481. }
  1482. },
  1483. playerSize: {
  1484. ratios: {
  1485. 1: 'sd',
  1486. 2: 'hd',
  1487. 3: 'pr'
  1488. },
  1489. sizes: {
  1490. 0 : 'h',
  1491. 240 : 's',
  1492. 360 : 'm',
  1493. 480 : 'l',
  1494. 720 : 'xl'
  1495. },
  1496. aspects: {
  1497. 1: 4 / 3,
  1498. 2: 16 / 9,
  1499. 3: 16 / 9
  1500. }
  1501. },
  1502. qualities: {
  1503. 240 : 'small',
  1504. 360 : 'medium',
  1505. 480 : 'large',
  1506. 720 : 'hd720',
  1507. 1080 : 'hd1080',
  1508. 1081 : 'highres'
  1509. }
  1510. // videoTypes: (function () {
  1511. // var v = document.createElement('video');
  1512.  
  1513. // return {
  1514. // ogg: !!v.canPlayType('video/ogg; codecs="theora, vorbis"'),
  1515. // webm: !!v.canPlayType('video/webm'),
  1516. // mp4: !!v.canPlayType('video/mp4')
  1517. // };
  1518. // }()),
  1519. };
  1520.  
  1521. /** U I CLASS
  1522. * Class for the player controls
  1523. */
  1524. YTMA.UI = function (ytma) {
  1525. this.ytmx = ytma;
  1526.  
  1527. this.play = new YTMA.Player(this.ytmx);
  1528. this.open = false;
  1529. this.selected = { size: null, ratio: null };
  1530.  
  1531. this.trigger = ytma.spn;
  1532. this.projector = $$.e('div', {className: 'ytm_projector ytm_none ytm_block ytm_normalize ytm_sans'});
  1533. this.control = $$.e('ul', {className: 'ytm_control ytm_sans'});
  1534. this.customBar = YTMA.DB.views.getToolbar(this.ytmx.data.site);
  1535. this.controlBar();
  1536. };
  1537.  
  1538. YTMA.UI.ratios = {
  1539. SD: 1,
  1540. HD: 2,
  1541. PORTRAIT: 3
  1542. };
  1543.  
  1544. YTMA.UI.sizes = {
  1545. HIDDEN: 0,
  1546. S: 240,
  1547. M: 360,
  1548. L: 480,
  1549. X: 720
  1550. };
  1551.  
  1552. /** Trigger is the VAR element */
  1553. YTMA.UI.createFromTrigger = function (t) {
  1554. console.log('createFromTrigger');
  1555. if (t.hasAttribute('data-ytmuid') && !YTMA.set[t.dataset.ytmuid]) {
  1556. console.log('createFromTrigger-new');
  1557. YTMA.addToSet(new YTMA()._reactivate(t));
  1558. }
  1559. console.log('createFromTrigger-ui');
  1560. return YTMA.set[t.dataset.ytmuid].getUI();
  1561. };
  1562.  
  1563. YTMA.UI.events = {
  1564. $fire: {
  1565. settings: function () {
  1566. YTMA.user.events.formToggle();
  1567. },
  1568. close: function () {
  1569. if (YTMA.DB.sites[this.ytmx.data.site].scroll) {
  1570. console.log('events.close-1');
  1571. this.hideAllPlayers();
  1572. } else {
  1573. console.log('events.close-2');
  1574. this.ytmx.disableOpenOnScroll();
  1575. this.hidePlayer();
  1576. }
  1577. },
  1578. ratio: function (li) {
  1579. var n = parseInt(li.dataset.value, 10);
  1580. this.play.dimmensions(n);
  1581. this.markSelected(li, 'ratio');
  1582. },
  1583. size: function (li) {
  1584. var n = parseInt(li.dataset.value, 10);
  1585. this.play.dimmensions(null, n);
  1586. this.markSelected(li, 'size');
  1587. }
  1588. },
  1589. videoBar: function (e) {
  1590. var el = e.target, t;
  1591.  
  1592. if (el.tagName.toLowerCase() === 'li' && el.dataset && el.dataset.type) {
  1593. t = el.dataset.type;
  1594. if (YTMA.UI.events.$fire[t]) {
  1595. YTMA.UI.events.$fire[t].call(this, el);
  1596. }
  1597. }
  1598. }
  1599. };
  1600.  
  1601. YTMA.UI.prototype = {
  1602. constructor: YTMA.UI,
  1603. resetViewSize: function () {
  1604. this.play.dimmensions();
  1605. this.setControlBarSize(this.play.attrs.size);
  1606. },
  1607. showOnScroll: function (el) {
  1608. if (!this.open && this.ytmx.canScroll() && this.ytmx.isBelow(el)) {
  1609. this.showPlayer();
  1610. }
  1611. },
  1612. showPlayer: function () {
  1613. this.open = true;
  1614.  
  1615. this.trigger.classList.add('ytm_none');
  1616. this.projector.classList.remove('ytm_none');
  1617.  
  1618. this.attachPlayPanel();
  1619. this.play.switchOn();
  1620.  
  1621. if (YTMA.user.preferences.focus) {
  1622. document.location.hash = '#' + this.ytmx.container.id;
  1623. }
  1624. },
  1625. hidePlayer: function () {
  1626. this.open = false;
  1627.  
  1628. this.play.switchOff();
  1629. this.trigger.classList.remove('ytm_none');
  1630. this.projector.classList.add('ytm_none');
  1631. },
  1632. attachPlayPanel: function () {
  1633. if (!this.play.panel.parentNode) {
  1634. // console.log('attaching display panel');
  1635. this.projector.appendChild(this.play.panel);
  1636. }
  1637. },
  1638. hideAllPlayers: function () {
  1639. var group = YTMA.collect(this.ytmx.data.id);
  1640. console.log('closing all', this.ytmx.data.id, group.length);
  1641. group.forEach(function (y) {
  1642. y.disableOpenOnScroll();
  1643. y.getUI().hidePlayer();
  1644. });
  1645. },
  1646. setControlBarSize: function (size) {
  1647. this.markSelected(this.control.querySelector('li[data-value="' + size + '"]'), 'size');
  1648. },
  1649. controlBar: function () {
  1650. var f = document.createDocumentFragment();
  1651.  
  1652. $$.a(f,
  1653. this.customBar.ratio ? this.buildList('ytm_ratios', [
  1654. {type: 'ratio', text: '4:3', value: YTMA.UI.ratios.SD, title: 'SD'},
  1655. {type: 'ratio', text: '16:9', value: YTMA.UI.ratios.HD, title: 'Landscape'},
  1656. {type: 'ratio', text: '9:16', value: YTMA.UI.ratios.PORTRAIT, title: 'Portrait'}]) : null,
  1657. this.customBar.size ? this.buildList('ytm_sizes', [
  1658. {type: 'size', text: '\u00D8', value: YTMA.UI.sizes.HIDDEN, title: 'Hide the video.'},
  1659. {type: 'size', text: 'S', value: YTMA.UI.sizes.S, title: '240p'},
  1660. {type: 'size', text: 'M', value: YTMA.UI.sizes.M, title: '360p'},
  1661. {type: 'size', text: 'L', value: YTMA.UI.sizes.L, title: '480p'},
  1662. {type: 'size', text: 'X', value: YTMA.UI.sizes.X, title: '720p'}]) : null,
  1663. this.buildList('ytm_options', [
  1664. strg.on ? {type: 'settings', text: '!', title: 'YTMA Settings'} : null,
  1665. {type: 'close', text: '\u00D7', title: 'Close the video.'}])
  1666. );
  1667.  
  1668. this.control.appendChild(f);
  1669. this.control.addEventListener('click', YTMA.UI.events.videoBar.bind(this), false);
  1670. this.projector.appendChild(this.control);
  1671. this.ytmx.container.insertBefore(this.projector, this.trigger.nextSibling);
  1672. },
  1673. markSelected: function (el, type) {
  1674. el.id = type + this.ytmx.data.uid;
  1675. try {
  1676. this.selected[type].removeAttribute('id');
  1677. } catch (e) {}
  1678. this.selected[type] = el;
  1679. },
  1680. buildList: function (className, elements) {
  1681. var li = $$.e('li'),
  1682. ul = $$.e('ul', {className: className}, li),
  1683. f = document.createDocumentFragment(),
  1684. i,
  1685. e;
  1686.  
  1687. for (i = 0; i < elements.length; i++) {
  1688. e = elements[i];
  1689. if (e) {
  1690. f.appendChild(this.li(e.type, e.text, e.value, e.title));
  1691. }
  1692. }
  1693. ul.appendChild(f);
  1694. return li;
  1695. },
  1696. li: function (type, txt, value, title) {
  1697. var l = $$.e('li', {_type: type, textContent: txt, _value: value, title: title});
  1698. if ((type === 'size' && this.play.attrs.size === value) || (type === 'ratio' && this.play.attrs.ratio === value)) {
  1699. this.markSelected(l, type);
  1700. }
  1701. return l;
  1702. }
  1703. };
  1704.  
  1705. /** P L A Y E R CLASS
  1706. * @param parent YTMA instance
  1707. */
  1708. YTMA.Player = function (parent) {
  1709. this.parent = parent;
  1710.  
  1711. this.mode = 'off';
  1712.  
  1713. this.attrs = {
  1714. sources: null,
  1715. quality: YTMA.DB.views.getPlayerQuality(YTMA.user.preferences.quality),
  1716. size: null,
  1717. ratio: null,
  1718. start: this.time(),
  1719. type: null
  1720. };
  1721.  
  1722. this.attrs.sources = YTMA.DB.views.getPlayerSources(parent.data.site)(parent.data, this.attrs);
  1723.  
  1724. // todo improve type/media
  1725. this.attrs.type = this.findType();
  1726. this.media = YTMA.Player.makeMedia[this.attrs.type](this);
  1727.  
  1728. this.channel = $$.e('div', {className: 'ytm_panel_channel ytm_block'}, this.media, true);
  1729. this.switcher = $$.e('div', {className: 'ytm_panel_switcher ytm_panel_size ytm_block ytm_' + this.attrs.type, _ytmuid: this.parent.data.uid, _standby: true});
  1730. this.panel = $$.e('div', {className: 'ytm_panel ytm_block'}, this.switcher, true);
  1731.  
  1732. if (parent.data.site === 'soundcloud' && YTMA.reg.extra.soundcloud.playlist.test(parent.anchor.href)) {
  1733. this.media.classList.add('ytm_soundcloud-playlist');
  1734. this.switcher.classList.add('ytm_soundcloud-playlist');
  1735. }
  1736.  
  1737. this.dimmensions(YTMA.user.preferences.ratio, YTMA.user.preferences.size);
  1738. };
  1739.  
  1740. YTMA.Player.css = {
  1741. item: function (key, value) {
  1742. if (isNumber(value)) {
  1743. value += 'px';
  1744. }
  1745.  
  1746. return '\t' + key + ': ' + value + ';\n';
  1747. },
  1748. iter: function (css, cssEntries) {
  1749. $$.o(cssEntries, function (key, value) {
  1750. css.push(YTMA.Player.css.item(key, value));
  1751. });
  1752. css.push('}');
  1753. },
  1754. generator: function () {
  1755. var css = [];
  1756.  
  1757. $$.o(this.sizes, function (size, sizes) {
  1758. $$.o(sizes, function (dimm, keys) {
  1759. css.push('\n.ytm_panel-' + size + '.ytm_panel-' + dimm + ' .ytm_panel_size {\n');
  1760. YTMA.Player.css.iter(css, keys);
  1761. });
  1762. });
  1763.  
  1764. // add site overrides
  1765. $$.o(this.sites, function (site, data) {
  1766. $$.o(data, function (setting, keys) {
  1767. if (setting === 'all') {
  1768. css.push('\n.ytm_site_' + site + ' .ytm_panel_size {\n');
  1769. } else {
  1770. css.push('\n.ytm_site_' + site + ' .ytm_panel-' + setting + ' .ytm_panel_size {\n');
  1771. }
  1772. YTMA.Player.css.iter(css, keys);
  1773. });
  1774. });
  1775.  
  1776. return css.join('');
  1777. },
  1778. sizes: (function () {
  1779. var merge = {};
  1780.  
  1781. $$.o(YTMA.DB.playerSize.sizes, function (num, size) {
  1782. if (num >= 0) {
  1783. merge[size] = {};
  1784.  
  1785. $$.o(YTMA.DB.playerSize.ratios, function (k, ratio) {
  1786. if (ratio === 'pr') {
  1787. var w = Math.floor(num * 0.95); // smaller than the normal sizes
  1788. merge[size][ratio] = {
  1789. width: w,
  1790. height: Math.floor(w * YTMA.DB.playerSize.aspects[k])
  1791. };
  1792. } else {
  1793. merge[size][ratio] = {
  1794. width: Math.floor(num * YTMA.DB.playerSize.aspects[k]),
  1795. height: num
  1796. };
  1797. }
  1798. });
  1799. }
  1800. });
  1801.  
  1802. return merge;
  1803. }()),
  1804. sites: { // custom sizes per site
  1805. soundcloud: {
  1806. all: {
  1807. height: '118px !important'
  1808. }
  1809. },
  1810. vine: {
  1811. s: {
  1812. width: 240,
  1813. height: 240
  1814. },
  1815. m: {
  1816. width: 360,
  1817. height: 360
  1818. },
  1819. l: {
  1820. width: 480,
  1821. height: 480
  1822. },
  1823. xl: {
  1824. width: 720,
  1825. height: 720
  1826. }
  1827. }
  1828. }
  1829. };
  1830.  
  1831. YTMA.Player.makeMedia = {
  1832. $css: function (type) {
  1833. return 'ytm_panel_media ytm_panel_size ytm_block ytm_' + type;
  1834. },
  1835. video: function (player) {
  1836. var video = $$.e('video', {
  1837. controls: true,
  1838. autoplay: false,
  1839. loop: true,
  1840. className: this.$css('video'),
  1841. $allowscriptaccess: true,
  1842. preload: 'metadata'
  1843. }), links = [];
  1844.  
  1845. player.attrs.sources.forEach(function (source) {
  1846. $$.e('source', {src: source.src, $type: source.type}, video);
  1847.  
  1848. links.push('<a href="' + source.src + '">' + source.src + '</a>');
  1849. });
  1850.  
  1851. $$.e('p', {innerHTML: 'Could not load source(s): ' + links.join('<br />')}, video);
  1852.  
  1853. return video;
  1854. },
  1855. iframe: function (player) {
  1856. return $$.e('iframe', {
  1857. $allowfullscreen: true,
  1858. // $sandbox: 'allow-same-origin allow-scripts allow-popups',
  1859. $type: player.attrs.sources[0].type,
  1860. src: player.attrs.sources[0].src,
  1861. className: this.$css('iframe')
  1862. });
  1863. },
  1864. audio: function (player) {
  1865. return $$.e('audio', {
  1866. src: player.attrs.sources[0].src,
  1867. $type: player.attrs.sources[0].type
  1868. });
  1869. }
  1870. };
  1871.  
  1872. YTMA.Player.prototype = {
  1873. constructor: YTMA.Player,
  1874. dimmensions: function (ratio, size) {
  1875. this.attrs.ratio = isNumber(ratio) ? ratio : this.attrs.ratio;
  1876. this.attrs.size = isNumber(size) ? size : this.attrs.size;
  1877. this.panel.className = YTMA.DB.views.getPlayerDimmensions(this.attrs.ratio, this.attrs.size);
  1878. },
  1879. time: function () {
  1880. try {
  1881. var m = this.parent.data.uri.match(YTMA.reg.time).slice(1, 3);
  1882. return ((+m[0] || 0) * 60) + (+m[1] || 0);
  1883. } catch (e) { return 0; }
  1884. },
  1885. findType: function () {
  1886. if (this.parent.data.site === 'html5-audio') { return 'audio'; }
  1887. if (YTMA.DB.sites[this.parent.data.site].videoTag) { return 'video'; }
  1888. return 'iframe';
  1889. },
  1890. switchOff: function () {
  1891. // console.log('removed media');
  1892.  
  1893. if (this.media.pause) {
  1894. console.log('pausing');
  1895. this.media.pause();
  1896. }
  1897.  
  1898. try {
  1899. this.switcher.removeChild(this.channel);
  1900. } catch (e) {
  1901. // console.error(e);
  1902. }
  1903. this.mode = 'off';
  1904. },
  1905. switchOn: function () {
  1906. if (this.attrs.size === 0) {
  1907. this.attrs.size = YTMA.user.preferences.size;
  1908. this.parent.ui.resetViewSize();
  1909. }
  1910. // console.log('switch to media');
  1911. this.switcher.appendChild(this.channel);
  1912. this.switcher.dataset.standby = false;
  1913. this.mode = 'on';
  1914. },
  1915. switchStandby: function () {
  1916. // console.log('switch to standby');
  1917. this.switchOff();
  1918. this.switcher.dataset.standby = true;
  1919. this.mode = 'standby';
  1920. },
  1921. isStandby: function () {
  1922. return this.mode === 'standby';
  1923. }
  1924. };
  1925.  
  1926. YTMA.prototype = {
  1927. constructor: YTMA,
  1928. getUI: function () {
  1929. if (!this.ui) {
  1930. this.ui = new YTMA.UI(this);
  1931. }
  1932.  
  1933. return this.ui;
  1934. },
  1935. setup: function () {
  1936. var site = YTMA.DB.sites[this.data.site];
  1937.  
  1938. if (site) {
  1939. this.spn.title = site.title || 'ytma!';
  1940.  
  1941. if (site.thumb) {
  1942. this.spn.style.backgroundImage = site.thumb.replace('%key', this.data.id);
  1943. }
  1944.  
  1945. if (site.https) {
  1946. this.anchor.href = this.anchor.href.replace('http:', 'https:');
  1947. }
  1948. }
  1949.  
  1950. try {
  1951. this.dom.custom[this.data.site].call(this);
  1952. } catch (e) {}
  1953.  
  1954. this.dom.link.call(this);
  1955. this.dom.span.call(this);
  1956. },
  1957. disableOpenOnScroll: function () {
  1958. this.anchor.dataset.ytmscroll = false;
  1959. },
  1960. canScroll: function () {
  1961. return this.anchor.dataset.ytmscroll === 'true';
  1962. },
  1963. isBelow: function (link) {
  1964. return YTMA.Scroll.compare(this.anchor, link) < 1;
  1965. },
  1966. dom: {
  1967. custom: { // modifies interface according to site
  1968. youtube: function () {
  1969. this.spn.addEventListener('mouseenter', YTMA.events.thumb.start, false);
  1970. this.spn.addEventListener('mouseleave', YTMA.events.thumb.stop, false);
  1971. this.anchor.href = this.anchor.href.replace('youtu.be/', 'youtube.com/watch?v=');
  1972. }
  1973. },
  1974. link: function () {
  1975. if (this.anchor.getElementsByTagName('img').length === 0) {
  1976. this.anchor.className += ' ytm_link ytm_link_' + this.data.site + ' ';
  1977. }
  1978. this.anchor.dataset.ytmid = this.data.id;
  1979. this.anchor.dataset.ytmuid = this.data.uid;
  1980. this.anchor.dataset.ytmsid = this.data.sid;
  1981. this.anchor.title = 'Visit the video page.';
  1982. this.anchor.parentNode.insertBefore(this.container, this.anchor.nextSibling);
  1983. },
  1984. span: function () {
  1985. var f = document.createDocumentFragment(),
  1986. site = YTMA.DB.sites[this.data.site];
  1987.  
  1988. $$.e('span', {className: 'ytm_init ytm_label ytm_sans ytm_box', textContent: this.spn.title}, this.spn);
  1989. $$.e('var', {className: 'ytm_label ytm_box', _ytmid: this.data.id, _ytmuid: this.data.uid, _ytmsid: this.data.sid, _ytmsite: this.data.site, textContent: '\u25B6'}, this.spn);
  1990.  
  1991. this.spn.title = 'Watch now!';
  1992. f.appendChild(this.spn);
  1993.  
  1994. if (site.ajax) { f.appendChild(this.dom.dataLoadLink.call(this)); }
  1995. if (site.slim) { this.container.classList.add('ytm_site_slim'); }
  1996. if (site.scroll) { this.anchor.classList.add('ytm_scroll'); }
  1997.  
  1998. this.container.appendChild(f);
  1999. },
  2000. dataLoadLink: function () {
  2001. var a, s;
  2002. s = $$.e('span', {className: 'ytm_bd ytm_normalize ytm_manual _' + this.data.sid});
  2003. a = $$.e('a', {
  2004. className: 'ytm_title',
  2005. textContent: 'Load description.',
  2006. href: '#',
  2007. title: 'Load this video\'s description.',
  2008. _ytmid: this.data.id,
  2009. _ytmsite: this.data.site,
  2010. _ytmuri: this.data.uri,
  2011. _ytmdescription: 'true'
  2012. });
  2013. return $$.a(s, a);
  2014. }
  2015. }
  2016. };
  2017.  
  2018. /**
  2019. * Creates a new YTMA from the given attributes
  2020. * @String|Number id Unique ID
  2021. * @String site Website eg: youtube, vimeo
  2022. * @HTMLAnchorElement a Anchor element
  2023. */
  2024. YTMA.prototype._new = function (id, site, a) {
  2025. var uid = YTMA.escapeId(id + '_' + (YTMA.num += 1));
  2026.  
  2027. this.data = {
  2028. id: id,
  2029. uid: YTMA.escapeId(uid), // unique id
  2030. sid: YTMA.escapeId(id), // shared id
  2031. site: site,
  2032. uri: a.href
  2033. };
  2034.  
  2035. this.ui = null;
  2036.  
  2037. if (!a.hasAttribute('data-ytmscroll')) { a.dataset.ytmscroll = true; }
  2038.  
  2039. this.anchor = a;
  2040.  
  2041. this.spn = $$.e('span', {className: 'ytm_trigger ytm_block ytm_normalize ytm_sans', _ytmid: this.data.id, _ytmsite: this.data.site});
  2042. this.container = $$.e('div', {id: 'w' + this.data.uid, className: 'ytm_spacer ytm_block ytm_site_' + this.data.site});
  2043.  
  2044. return this;
  2045. };
  2046.  
  2047. /**
  2048. * Recreates a YTMA object from a trigger element
  2049. * @HTMLElement
  2050. */
  2051. YTMA.prototype._reactivate = function (trigger) {
  2052. var id = trigger.dataset.ytmid,
  2053. a = document.querySelector('a[data-ytmuid="' + trigger.dataset.ytmuid + '"]');
  2054.  
  2055. this.data = {
  2056. id: id,
  2057. uid: trigger.dataset.ytmuid,
  2058. sid: trigger.dataset.ytmsid,
  2059. site: trigger.dataset.ytmsite,
  2060. uri: a.href
  2061. };
  2062.  
  2063. this.ui = null;
  2064. this.anchor = a;
  2065. this.spn = trigger.parentElement;
  2066. this.container = this.spn.parentElement;
  2067.  
  2068. return this;
  2069. };
  2070.  
  2071. /** S C R O L L CLASS
  2072. * Window-Scroll Event Helper
  2073. */
  2074. YTMA.Scroll = (function () {
  2075.  
  2076. function Scroll(selector, cb, delay) {
  2077. this.selector = selector;
  2078. this.cb = cb;
  2079.  
  2080. // console.log('YTMA.Scroll Monitor: ', selector);
  2081. this.bound = Scroll.debounce(this.monitor.bind(this), delay || 500);
  2082.  
  2083. this.bound();
  2084. window.addEventListener('scroll', this.bound, false);
  2085. }
  2086.  
  2087. Scroll.debounce = function (fn, delay) {
  2088. var timeout;
  2089. delay = delay || 250;
  2090.  
  2091. return function () {
  2092. var self = this, args = arguments, timed;
  2093.  
  2094. timed = function () {
  2095. timeout = null;
  2096. fn.apply(self, args);
  2097. };
  2098.  
  2099. window.clearTimeout(timeout);
  2100. timeout = window.setTimeout(timed, delay);
  2101. };
  2102. };
  2103.  
  2104. Scroll.visible = function (el) {
  2105. var bound = el.getBoundingClientRect();
  2106. return (bound.top >= 0 && bound.top <= document.documentElement.clientHeight);
  2107. };
  2108.  
  2109. Scroll.visibleAll = function (el, offset) {
  2110. var bound = el.getBoundingClientRect(),
  2111. height = document.documentElement.clientHeight;
  2112. offset = isNumber(offset) ? +offset : 0;
  2113. return ((bound.bottom + offset >= 0)
  2114. && (bound.top <= height + offset || bound.bottom <= height - offset));
  2115. };
  2116.  
  2117. /** Returns 1, 0, -1 when el1 is above, exactly the same, or below el2 */
  2118. Scroll.compare = function (el1, el2) {
  2119. var a = el1.getBoundingClientRect().y,
  2120. b = el2.getBoundingClientRect().y;
  2121.  
  2122. if (a < b) { return 1; }
  2123. if (a === b) { return 0; }
  2124. return -1;
  2125. };
  2126.  
  2127. Scroll.prototype = {
  2128. stop: function () {
  2129. // console.log('clear scroll: ', this.selector);
  2130. window.removeEventListener('scroll', this.bound);
  2131. },
  2132. monitor: function () {
  2133. $$.s(this.selector, this.cb);
  2134. }
  2135. };
  2136.  
  2137. return Scroll;
  2138.  
  2139. }());
  2140.  
  2141. YTMA.main();
  2142.  
  2143. }());