YouTube Me Again!

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

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

  1. // ==UserScript==
  2. // Do not modify and re-release this script!
  3. // If you would like to add support for other sites, please tell me and I'll put it in the includes.
  4.  
  5. // @id youtube-me-again
  6. // @name YouTube Me Again!
  7. // @namespace hateradio)))
  8. // @author hateradio
  9. // @version 7.9
  10. // @description ytma! automatically converts YouTube(TM), Vimeo, Vine, Soundcloud, WebM, and MP4 links into real embedded videos.
  11. // @homepageURL https://greasyfork.org/en/scripts/1023-youtube-me-again
  12. // @icon https://www.dropbox.com/s/b85qmq0bsim407s/ytma32.png?dl=1
  13. // @icon64 https://www.dropbox.com/s/5zw3al38yf39wxb/ytma64.png?dl=1
  14. // @screenshot https://www.dropbox.com/s/syy9916b1prygl9/ytmascreen5.png?dl=1
  15.  
  16. // @include https://vine.co/v/*/embed/simple
  17. // @match https://vine.co/v/*/embed/simple
  18.  
  19. // @include http*://*youtube-nocookie.com/embed/*
  20. // @match *://*.youtube-nocookie.com/embed/*
  21.  
  22. // @include http*://*youtube.com/embed/*
  23. // @match *://*.youtube.com/embed/*
  24.  
  25. // @include https://gfycat.com/iframe/*
  26. // @match https://gfycat.com/iframe/*
  27.  
  28. // @include http*://*.neogaf.com/threads/*
  29. // @include http*://*.resetera.com/threads/*
  30.  
  31. // @match *://*.neogaf.com/threads/*
  32. // @match *://*.resetera.com/threads/*
  33.  
  34. // @updated 05 Jan 2019
  35.  
  36. // @grant GM_xmlhttpRequest
  37.  
  38. // @run-at document-end
  39. // ==/UserScript==
  40.  
  41. /*
  42.  
  43. ## Updates
  44.  
  45. #### 7.9
  46.  
  47. * Fix: Ignore links in XenoForo text areas
  48.  
  49. #### 7.8
  50.  
  51. * Fix iFrame selectors
  52. * Adds a monitoring interface to check for updated pages
  53.  
  54. #### 7.7
  55.  
  56. * New: YTMA will now try to find new links on AJAX-loaded posts on ResetEra
  57. * Reverts Gfycat iFrame support; removes video tag for wider support
  58. * Removes an outdated Chrome blacklist
  59.  
  60. #### 7.6
  61.  
  62. * Fix: overrides resetera support of embeded videos
  63.  
  64. #### 7.5
  65.  
  66. * New: Support for ResetEra
  67. * Fix: Parses hours from YouTube URLs
  68.  
  69. #### 7.2.2
  70.  
  71. * Updates YouTube iFrame to hide related video feature when pausing
  72.  
  73. #### 7.2.1
  74.  
  75. * New: Extension info
  76. * Updates JSHint options
  77. * Removes outdated @include links
  78.  
  79. #### 7.2
  80.  
  81. * New: CSS rule to make videos fit within smaller windows
  82. * New: GitHub repository and update links
  83. * New: Streamable favicon
  84. * Fix: Vimeo favicon
  85.  
  86. #### 7.1
  87.  
  88. * HTTPS links for Vimeo and Gfycat
  89. * Fix: Safari bug
  90.  
  91. #### 7
  92.  
  93. * New: NeoGAF HTTPS Support
  94. * New: Streamable.com added
  95. * New: Soundcloud playlist support
  96. * Improved time parser
  97. * Upon scrolling, cached descriptions are shown
  98. * Code reorganization makes adding new media sites easier
  99.  
  100. ### 6
  101.  
  102. * New: Imgur GIFV (WEBM/MP4) support
  103. * New: Button to remove cache (descriptions/thumbnail links/etc)
  104. * New: SoundCloud playlist support
  105. * Default video quality is now 720p/HD
  106. * Soundcloud now uses HTML5 player
  107. * Players that open on scroll will no longer trigger the opening of players higher on the page
  108. * Adds HTML5, Gfycat, Imgur icons on links
  109. * Improved Soundcloud and GfyCat URL matchers
  110. * Restructured code base to simplify creation of media controls
  111. * Restructured CSS
  112. * Patched back Gfycat iFrame setting for Safari (it is incompatible with new settings)
  113. * Updates YouTube data API
  114. * Removes:
  115. * Object tag for YouTube for Flash (Deprecated)
  116. * "Batch" loading of descriptions (Only manual and scroll methods are supported)
  117.  
  118. // #Updates
  119.  
  120. Whitelist these sites on NoScript/NotScript/etc.
  121. ------------------------------------------------
  122.  
  123. * neogaf.com
  124. * youtube.com
  125. * youtube-nocookie.com
  126. * googlevideo.com (HTML5 player sends videos from this domain)
  127. * googleapis.com (YT video descriptions)
  128. * vimeo.com
  129. * vimeocdn.com
  130. * soundcloud.com
  131. * sndcdn.com
  132. * vineco.com
  133. * vine.com
  134. * vine.co
  135. * gfycat.com
  136. * github.io
  137.  
  138.  
  139. Whitelist these on Ghostery
  140. ---------------------------
  141.  
  142. * SoundCloud (Widgets, Audio / Music Player)
  143.  
  144. */
  145.  
  146. (function () {
  147. 'use strict';
  148.  
  149. var $$, strg, update;
  150.  
  151. if (!Function.prototype.bind) {
  152. Function.prototype.bind = function (self) {
  153. var args = [].slice.call(arguments, 1), fn = this;
  154. return function () {
  155. return fn.apply(self, args.concat([].slice.call(arguments)));
  156. };
  157. };
  158. }
  159.  
  160. function isNumber(n) {
  161. return !isNaN(parseFloat(n)) && isFinite(n);
  162. }
  163.  
  164. function removeSearch(uri, keepHash) { // removes search query from a uri
  165. var s = uri.indexOf('?'), h = uri.indexOf('#'), hash = '';
  166. if (s > -1) {
  167. if (keepHash && h > -1) {
  168. hash = uri.substr(h);
  169. }
  170. uri = uri.substr(0, s) + hash;
  171. }
  172. return uri;
  173. }
  174.  
  175. if (!Element.prototype.matches)
  176. Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
  177.  
  178. if (!Element.prototype.closest) {
  179. Element.prototype.closest = function (s) {
  180. var el = this;
  181. if (!document.documentElement.contains(el)) return null;
  182. do {
  183. if (el.matches(s)) return el;
  184. el = el.parentElement || el.parentNode;
  185. } while (el !== null && el.nodeType === 1);
  186. return null;
  187. };
  188. }
  189.  
  190. // D O M Handle
  191. $$ = {
  192. s: function (selector, cb) { var s = document.querySelectorAll(selector), i = -1; while (++i < s.length) { if (cb(s[i], i, s) === false) { break; } } },
  193. o: function (object, cb) { var i; for (i in object) { if (object.hasOwnProperty(i)) { if (cb(i, object[i], object) === false) { break; } } } },
  194. 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; },
  195. e: function (t, o, e, p) {
  196. var c = document.createElement(t);
  197. $$.o(o, function (k, v) {
  198. var b = k.charAt(0);
  199. switch (b) {
  200. case '_':
  201. c.dataset[k.substring(1)] = v;
  202. break;
  203. case '$':
  204. c.setAttribute(k.substring(1), v);
  205. break;
  206. default:
  207. c[k] = v;
  208. }
  209. });
  210.  
  211. if (e && p) {
  212. c.appendChild(e);
  213. } else if (e) {
  214. e.appendChild(c);
  215. }
  216. return c;
  217. },
  218. x: function (selector) { return this.ary(document.querySelectorAll(selector)); },
  219. ary: function (ary) { return Array.from ? Array.from(ary) : Array.prototype.slice.call(ary); },
  220. top: document.head || document.body,
  221. css: function (t) {
  222. if (!this.style) {
  223. this.style = document.createElement('style');
  224. this.style.type = 'text/css';
  225. this.top.appendChild(this.style);
  226. }
  227. this.style.appendChild(document.createTextNode(t + '\n'));
  228. },
  229. js: function (t) {
  230. var j = document.createElement('script');
  231. j.type = 'text/javascript';
  232. j[/^https?:\/\//i.test(t) ? 'src' : 'textContent'] = t;
  233. this.top.appendChild(j);
  234. }
  235. };
  236.  
  237. // S T O R A G E HANDLE
  238. strg = {
  239. MAX: 5012,
  240. on: false,
  241. 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; } },
  242. read: function (key) {
  243. try {
  244. return JSON.parse(localStorage.getItem(key));
  245. } catch (e) {
  246. console.error(e.lineNumber + ':' + e.message);
  247. return undefined;
  248. }
  249. },
  250. save: function (key, val) { return this.on ? !localStorage.setItem(key, JSON.stringify(val)) : false; },
  251. wipe: function (key) { return this.on ? !localStorage.removeItem(key) : false; },
  252. zero: function (o) { var k; for (k in o) { if (o.hasOwnProperty(k)) { return false; } } return true; },
  253. grab: function (key, def) { var s = strg.read(key); return strg.zero(s) ? def : s; },
  254. size: function () {
  255. var length = 0, key;
  256. try {
  257. for (key in window.localStorage) {
  258. if (window.localStorage.hasOwnProperty(key)) {
  259. length += window.localStorage[key].length;
  260. }
  261. }
  262. } catch (e) { }
  263. return 3 + ((length * 16) / (8 * 1024));
  264. },
  265. full: function () {
  266. try {
  267. var date = +(new Date());
  268. localStorage.setItem(date, date);
  269. localStorage.removeItem(date);
  270. return false;
  271. } catch (e) {
  272. if (e.name === 'QuotaExceededError' ||
  273. e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
  274. return true;
  275. }
  276. }
  277. },
  278. init: function () { this.on = this.test(); }
  279. };
  280. strg.init();
  281.  
  282. // U P D A T E HANDLE
  283. update = {
  284. name: 'ytma!',
  285. version: 7900,
  286. key: 'ujs_YTMA_UPDT_HR',
  287. callback: 'ytmaupdater',
  288. page: 'https://greasyfork.org/scripts/1023-youtube-me-again',
  289. urij: 'https://hateradio.github.io/ytma/update.json',
  290. interval: 5,
  291. day: (new Date()).getTime(),
  292. time: function () { return new Date(this.day + (1000 * 60 * 60 * 24 * this.interval)).getTime(); },
  293. notification: function (j) {
  294. if (this.version < j.version) {
  295. strg.save(this.key, { date: this.time(), version: j.version, page: j.page });
  296. this.link();
  297. }
  298. },
  299. link: function () {
  300. this.csstxt();
  301.  
  302. var a = document.createElement('a'), b = strg.read(this.key);
  303. a.href = b.page || this.page;
  304. a.id = 'userscriptupdater2';
  305. a.title = 'Update now.';
  306. a.target = '_blank';
  307. a.textContent = 'An update for ' + this.name + ' is available.';
  308. a.addEventListener('click', function () { this.style.display = 'none'; }, false);
  309. document.body.appendChild(a);
  310. },
  311. xhr: function () {
  312. var x = new XMLHttpRequest();
  313. x.addEventListener('load', function () { update.notification(JSON.parse(this.responseText)); }, false);
  314. x.open('get', update.urij, true);
  315. x.send();
  316. },
  317. check: function (opt) {
  318. if (!strg.on) { return; }
  319. if (window.chrome && window.chrome.extension) { return; }
  320. var stored = strg.read(this.key), page;
  321.  
  322. if (opt || !stored || stored.date < this.day) {
  323. page = (stored && stored.page) || this.page;
  324. strg.save(this.key, { date: this.time(), version: this.version, page: page });
  325. this.xhr();
  326. } else if (this.version < stored.version) {
  327. this.link();
  328. }
  329. },
  330. csstxt: function () {
  331. 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}'); }
  332. }
  333. };
  334. update.check();
  335.  
  336. /** Y T M A CLASS
  337. * Bare YTMA class, filled through _new() or _reactivate()
  338. */
  339. function YTMA() { }
  340.  
  341. YTMA.events = {
  342. clicks: function (e) { // YTMA global click dispatcher
  343. var t = e.target;
  344.  
  345. if (t) {
  346. // console.log('YTMA.clicks');
  347. if (t.tagName === 'VAR' && t.hasAttribute('data-ytmuid')) { // trigger the ui
  348. console.log('show', t.dataset.ytmuid);
  349. YTMA.UI.createFromTrigger(t).showPlayer();
  350. } else if (t.hasAttribute('data-ytmdescription')) {
  351. console.log('load', t.dataset.ytmid);
  352. YTMA.external.events.manualLoad(e);
  353. }
  354. }
  355. },
  356. thumb: {
  357. start: function (e) {
  358. var el = e.target;
  359. el.dataset.thumb = el.dataset.thumb > 0 ? (el.dataset.thumb % 3) + 1 : 2;
  360. el.style.backgroundImage = ['url(https://i3.ytimg.com/vi/', el.dataset.ytmid, '/', el.dataset.thumb, '.jpg)'].join('');
  361. el.dataset.timeout = window.setTimeout(YTMA.events.thumb.start.bind(this, e), 800);
  362. },
  363. stop: function (e) {
  364. window.clearTimeout(e.target.dataset.timeout);
  365. }
  366. }
  367. };
  368.  
  369. YTMA.num = 0;
  370.  
  371. YTMA.addToSet = function (ytma) {
  372. YTMA.set[ytma.data.uid] = ytma;
  373. };
  374.  
  375. YTMA.create = function (link) {
  376. return YTMA.grabIdAndSite(link, function (data, err) {
  377. if (err) {
  378. console.error(link.href, err);
  379. return {};
  380. }
  381.  
  382. var y = new YTMA()._new(data.id, data.site, link);
  383. YTMA.addToSet(y);
  384. y.setup();
  385.  
  386. return y;
  387. });
  388. };
  389.  
  390. YTMA.grabIdAndSite = function (link, cb) {
  391. var uri = link.href || link.src, id, site, match;
  392. try {
  393. site = YTMA.reg.siteByTest[YTMA.reg.siteExpressions.test(uri) ? RegExp.lastMatch : ''];
  394. // console.log(site);
  395.  
  396. if (site === 'html5') { // || site === 'html5-audio'
  397. id = uri.slice(-15);
  398. } else if (site === 'soundcloud') {
  399. if (!YTMA.reg.extra.soundcloud.playlist.test(uri)) {
  400. link.href = uri = YTMA.reg.fix.soundcloud(uri);
  401. }
  402.  
  403. match = YTMA.DB.sites.soundcloud.matcher.exec(uri);
  404. id = YTMA.escapeId(match[1]);
  405.  
  406. if (match && YTMA.reg.extra.soundcloud.tracks.test(uri)) {
  407. id = id.slice(-50);
  408. }
  409. } else {
  410. id = uri.match(YTMA.DB.sites[site].matcher)[1];
  411. }
  412.  
  413. console.log(id, site, match);
  414. if (id && YTMA.DB.sites[site]) {
  415. return cb({ id: id, site: site }, null);
  416. }
  417. throw TypeError('Invalid ID/Site: ' + id + ' @ ' + site);
  418. } catch (e) {
  419. return cb(null, e);
  420. }
  421. };
  422.  
  423. YTMA.escapeId = function (id) {
  424. return (id += '').replace(/(?:\W)/g, '_');
  425. };
  426.  
  427. YTMA.route = {
  428. host: document.location.host.replace('www.', ''),
  429. control: {
  430. $: {
  431. checkStorage: function () {
  432. if (strg.full() === true) {
  433. console.log('YTMA ERROR: Storage is full!');
  434. try {
  435. localStorage.removeItem(YTMA.external.version);
  436. strg.on = strg.test();
  437. } catch (e) {
  438. console.error(e);
  439. }
  440. }
  441. },
  442. runOnce: function (loop) {
  443. if (!document.body.hasAttribute('ytma-enabled')) {
  444. document.body.setAttribute('ytma-enabled', true);
  445.  
  446. this.checkStorage();
  447.  
  448. if (!YTMA.DB.extension) { update.check(); }
  449.  
  450. YTMA.css();
  451. YTMA.user.init();
  452. YTMA.DB.postInit();
  453.  
  454. if (loop) {
  455. document.body.dataset.YTMA_LOOP = window.setInterval(loop, 5000);
  456. loop();
  457. }
  458.  
  459. document.body.addEventListener('click', YTMA.events.clicks, false);
  460. }
  461. }
  462. },
  463. go: function (host) {
  464. console.log(host);
  465. if (/(?:googlevideo|youtube-nocookie\.com|youtube\.com\.?)/i.test(host)) {
  466. this.sites.youtube();
  467. } else if (this.sites[host]) {
  468. this.sites[host]();
  469. } else {
  470. this.sites.$generic();
  471. }
  472. },
  473. sites: {
  474. $generic: function () {
  475. function loop() {
  476. if (YTMA.selector.processor() > 0) {
  477. YTMA.user.fn.loadPreferences();
  478. }
  479.  
  480. console.log('ytma! . . . again!!');
  481. }
  482.  
  483. YTMA.route.control.$.runOnce(loop);
  484. },
  485. 'resetera.com': function () {
  486. $$.css('.ytm_control li ul li { height: 24px !important }');
  487. $$.css('.bbCodeQuote .quoteContainer .quote { max-height: initial } .bbCodeQuote .quoteContainer .quoteExpand.quoteCut { display: none }');
  488. $$.css('.bbCodeQuote .ytm_block iframe, .bbCodeQuote .ytm_block [data-s9e-mediaembed], .bbCodeQuote .ytm_block .fb_iframe_widget, .bbCodeQuote .ytm_block object, .bbCodeQuote .ytm_block embed { max-height: initial; max-width: initial }');
  489. this.$generic();
  490. },
  491. 'gfycat.com': function () {
  492. var v = document.querySelector('video');
  493. v.controls = true;
  494. $$.css('body,html {overflow:hidden;height:100%;width:100%} video {display:table;height:100%;margin:0 auto;}');
  495. document.body.appendChild(v);
  496. },
  497. 'vine.co': function () {
  498. // console.log('vine.co');
  499.  
  500. window.addEventListener('resize', function () {
  501. $$.s('[style]', function (e) {
  502. e.removeAttribute('style');
  503. });
  504. });
  505. },
  506. youtube: function () { // lets force some quality parity
  507. }
  508. }
  509. },
  510. load: function () {
  511. this.control.go(this.host);
  512. }
  513. };
  514.  
  515. YTMA.main = function () {
  516. YTMA.reg.siteExpressions = YTMA.DB.views.getAllSiteRegExps();
  517. // console.log(YTMA.reg.siteExpressions);
  518. YTMA.route.load();
  519. };
  520.  
  521. YTMA.set = {};
  522.  
  523. YTMA.collect = function (id) {
  524. var i, a = [];
  525. for (i in YTMA.set) {
  526. if (YTMA.set.hasOwnProperty(i) && YTMA.set[i].data.id === id) {
  527. a.push(YTMA.set[i]);
  528. }
  529. }
  530. return a;
  531. };
  532.  
  533. YTMA.reg = {
  534. siteExpressions: null,
  535. time: /(?:t=(?:(\d+)h)?(?:(\d+)m)?(\d+))/,
  536. ios: /(?:\b(?:ipod|iphone|ipad))\b/i,
  537. extra: {
  538. soundcloud: {
  539. playlist: /(?:soundcloud\.com\/.+\/sets\/)/,
  540. tracks: /(?:soundcloud\.com\/.+\/tracks\/)/
  541. }
  542. },
  543. siteByTest: {
  544. youtu: 'youtube',
  545. vimeo: 'vimeo',
  546. vine: 'vine',
  547. gfycat: 'gfycat',
  548. imgur: 'imgur',
  549. '.webm': 'html5',
  550. '.mp4': 'html5',
  551. // '.mp3': 'html5-audio',
  552. '.gifv': 'html5',
  553. soundcloud: 'soundcloud',
  554. 'streamable.com': 'streamable'
  555. },
  556. fix: {
  557. soundcloud: function (uri) {
  558. var match = YTMA.DB.sites.soundcloud.matcher.exec(uri), id;
  559. if (match) {
  560. id = match[1].split('/', 2).join('/');
  561. uri = removeSearch('https://soundcloud.com/' + id, true);
  562. }
  563.  
  564. return uri;
  565. }
  566. }
  567. };
  568.  
  569. YTMA.selector = { // to build the selector
  570. parentBlacklist: ['.smallfont', '.colhead_dark', '.spoiler', 'pre', '.messageUserInfo', '.message-editorWrapper'],
  571. ignore: function () {
  572. var i, j, ignore = [], all = YTMA.DB.views.getAllSiteSelectors().split(','), blacklist = this.parentBlacklist;
  573. for (i = 0; i < blacklist.length; i++) {
  574. for (j = 0; j < all.length; j++) {
  575. ignore.push(blacklist[i] + ' ' + all[j]);
  576. }
  577. }
  578. //console.log(ignore);
  579. return ignore.join(',');
  580. },
  581. iframes: function () { // for resetera, convert iframes back to anchors
  582. $$.x('.message-body iframe').forEach(function (f) {
  583. if (/vi\/(.+?)\/hqdefault/.test(f.style.backgroundImage)) {
  584. var src = 'https://youtu.be/' + RegExp.$1,
  585. span = f.closest('[data-s9e-mediaembed]');
  586. span.insertAdjacentHTML('beforebegin', '<a href=' + src + '>youtube</a>');
  587. span.parentElement.removeChild(span);
  588. }
  589. });
  590. },
  591. links: function () {
  592. var links;
  593.  
  594. $$.x(YTMA.selector.ignore()).map(function (el) { el.setAttribute('ytmaignore', true); });
  595.  
  596. links = $$.x(YTMA.DB.views.getAllSiteSelectors()).filter(function (el) {
  597. var r = !el.hasAttribute('ytmaprocessed') && !el.hasAttribute('ytmaignore');
  598. el.setAttribute('ytmaprocessed', true);
  599. return r;
  600. });
  601.  
  602. return links;
  603. },
  604. processor: function () {
  605. this.iframes();
  606. var links = this.links();
  607.  
  608. if (links.length > 0) {
  609. links.forEach(YTMA.create);
  610. }
  611.  
  612. return links.length;
  613. }
  614. };
  615.  
  616. /**
  617. * User Preferences
  618. * size: Small (240p), Medium (360p), Large (480p), XL (720p)
  619. * ratio: 1 4:3, 2 16:9
  620. * quality: 240, 360, 480, 720, 1080
  621. * focus: 0/1; Will attempt to set the window's focus near the video
  622. * autoShow: 0/1; Will automatically display HTML5 videos, which currently lack descriptions and thumbnails
  623. * desc: (Descriptions) 0 None; 1 Yes on scroll; 2 Yes all at once
  624. * yt_nocookie: 0/1; Will disable/enable youtube-nocookie.com
  625. * yt_volume: positive number; youtube volume
  626. * yt_annotation: 0/1; youtube annotations
  627. */
  628. YTMA.user = {
  629. KEY: 'ytmasetts',
  630. $form: null,
  631. init: function () {
  632. this.load();
  633.  
  634. if (strg.on) {
  635. this.fn.makeForm();
  636. this.mark();
  637. }
  638. },
  639. valid: {
  640. focus: [0, 1],
  641. desc: [0, 1, 2],
  642. ratio: [1, 2],
  643. size: [240, 360, 480, 720],
  644. quality: [240, 360, 480, 720, 1080],
  645. autoShow: [0, 1],
  646. yt_nocookie: [0, 1],
  647. yt_annotation: [0, 1], // hide | show
  648. yt_volume: 100 // todo? (function () { var a = new Array(101); for (i = 0; i <= 100; i++) { a[i] = i; } return a; }())
  649. },
  650. mapping: { // map values to some other values used by an external API, for example
  651. yt_annotation: [3, 1] // 3 = hide | 1 = show
  652. },
  653. validate: function (property, n) {
  654. n = +n;
  655.  
  656. if (property === 'yt_volume') {
  657. return n >= 0 && n <= 100 ? (+n) : YTMA.user.defaults()[property];
  658. }
  659. return YTMA.user.valid[property].indexOf(n) > -1 ? n : YTMA.user.defaults()[property];
  660. },
  661. defaults: function () {
  662. return {
  663. focus: 0,
  664. desc: 1,
  665. ratio: 2,
  666. size: 360,
  667. quality: 720,
  668. autoShow: 1,
  669. yt_nocookie: 0,
  670. yt_annotation: 1,
  671. yt_volume: 100
  672. };
  673. },
  674. load: function () {
  675. var s = strg.grab(YTMA.user.KEY, {});
  676.  
  677. YTMA.user.preferences = {
  678. size: YTMA.user.validate('size', s.size),
  679. ratio: YTMA.user.validate('ratio', s.ratio),
  680. desc: YTMA.user.validate('desc', s.desc),
  681. focus: YTMA.user.validate('focus', s.focus),
  682. quality: YTMA.user.validate('quality', s.quality),
  683. autoShow: YTMA.user.validate('autoShow', s.autoShow),
  684. yt_nocookie: YTMA.user.validate('yt_nocookie', s.yt_nocookie),
  685. yt_annotation: YTMA.user.validate('yt_annotation', s.yt_annotation),
  686. yt_volume: YTMA.user.validate('yt_volume', s.yt_volume)
  687. };
  688.  
  689. $$.o(YTMA.user.mapping, function (key, val) {
  690. if (!val.hasOwnProperty('indexOf')) {
  691. YTMA.user.preferences[key] = val[YTMA.user.valid[key].indexOf(YTMA.user.preferences[key])];
  692. }
  693. });
  694.  
  695. console.log('loaded: ', YTMA.user.preferences);
  696. },
  697. mark: function () {
  698. var a = {};
  699. a.ytma__focus = !!YTMA.user.preferences.focus;
  700. a.ytma__autoShow = !!YTMA.user.preferences.autoShow;
  701. a.ytma__yt_nocookie = !!YTMA.user.preferences.yt_nocookie;
  702. a.ytma__yt_annotation = !!YTMA.user.preferences.yt_annotation;
  703. a.ytma__yt_volume = YTMA.user.preferences.yt_volume;
  704. a['ytma__ratio' + YTMA.user.preferences.ratio] = true;
  705. a['ytma__size' + YTMA.user.preferences.size] = true;
  706. a['ytma__desc' + YTMA.user.preferences.desc] = true;
  707. a['ytma__quality' + YTMA.user.preferences.quality] = !!YTMA.user.preferences.quality;
  708.  
  709. // console.log('marking', a);
  710. $$.o(a, function (id, val) {
  711. try {
  712. var el = document.getElementById(id);
  713. el.checked = val;
  714. el.value = val;
  715. } catch (e) {
  716. // console.log(id, e);
  717. }
  718. });
  719. },
  720. events: {
  721. save: function (e) {
  722. var o = {};
  723.  
  724. if (e && (/(?:INPUT|LABEL)/i).test(e.target.nodeName)) {
  725. // console.log(YTMA.user.$form.querySelectorAll('[data-key]'));
  726. // [data-key]:checked
  727. $$.ary(YTMA.user.$form.querySelectorAll('[data-key]')).forEach(function (e) {
  728. var key;
  729. key = e.dataset.key;
  730.  
  731. if (e.type === 'checkbox') {
  732. o[key] = +e.checked;
  733. } else if (e.type === 'radio') {
  734. if (e.checked) {
  735. if (e.hasAttribute('data-num')) {
  736. o[key] = +e.dataset.num;
  737. }
  738. }
  739. } else {
  740. o[key] = +e.value;
  741. }
  742. });
  743.  
  744. if (strg.save(YTMA.user.KEY, o)) {
  745. YTMA.user.load();
  746. } else {
  747. YTMA.user.error.classList.remove('ytm_none');
  748. }
  749. }
  750.  
  751. },
  752. reset: function () {
  753. YTMA.user.preferences = YTMA.user.defaults();
  754. YTMA.user.mark();
  755. strg.wipe(YTMA.user.KEY);
  756. YTMA.user.error.classList.add('ytm_none');
  757. },
  758. clear: function () {
  759. try {
  760. localStorage.removeItem(YTMA.external.version);
  761. YTMA.user.events.reset();
  762. console.log('removed all YTMA cache');
  763. } catch (e) {
  764. console.error(e);
  765. }
  766. },
  767. formToggle: function (e) {
  768. if (!e || (e && e.target && !(/(?:INPUT|LABEL)/i).test(e.target.nodeName))) {
  769. YTMA.user.$form.classList.toggle('ytm_none');
  770. }
  771. },
  772. formToggleKeyboard: function (e) {
  773. // press CTRL+SHIFT+Y (META+SHIFT+Y) to display settings form
  774. if ((e.ctrlKey || e.metaKey) && e.shiftKey && String.fromCharCode(e.which).toLowerCase() === 'y') {
  775. e.preventDefault();
  776. YTMA.user.events.formToggle();
  777. }
  778. }
  779. },
  780. fn: {
  781. $scroller: null,
  782. $once: false,
  783. loadPreferences: function () {
  784. YTMA.user.fn.onScrollLoadDescriptions(YTMA.user.preferences.desc === 1);
  785.  
  786. this.loadPreferencesOnce();
  787. },
  788. loadPreferencesOnce: function () {
  789. if (this.$once) { return; }
  790.  
  791. this.$once = true;
  792.  
  793. if (YTMA.user.preferences.autoShow === 1) {
  794. YTMA.user.fn.onScrollViewMedia();
  795. }
  796. },
  797. showMedia: function () {
  798. console.log('showMedia');
  799. return new YTMA.Scroll('a.ytm_scroll:not([data-ytmscroll="false"])', function (link) {
  800. if (YTMA.Scroll.visibleAll(link, 50)) {
  801. $$.s('var[data-ytmsid="' + link.dataset.ytmsid + '"]:not([data-ytmscroll="false"])', function (trigger) {
  802. var ui = YTMA.UI.createFromTrigger(trigger);
  803. ui.showOnScroll(link);
  804. });
  805. }
  806. });
  807. },
  808. toggleMedia: function () {
  809. return new YTMA.Scroll('div.ytm_panel_switcher', function (div) {
  810. var v = div.querySelector('video'),
  811. paused = v && (v.paused || v.ended),
  812. ui = YTMA.set[div.dataset.ytmuid].getUI();
  813.  
  814. if (paused && !YTMA.Scroll.visibleAll(div, 0)) {
  815. return ui.play.switchStandby();
  816. }
  817.  
  818. if (ui.play.isStandby() && YTMA.Scroll.visibleAll(div, 200)) {
  819. return ui.play.switchOn();
  820. }
  821.  
  822. // todo ascertain embedded player properties
  823. // f = div.querySelector('iframe, object');
  824. // if (f && !YTMA.Scroll.visibleAll(div, 200)) {
  825. // y.hidePlayer();
  826. // }
  827. });
  828. },
  829. onScrollViewMedia: function () {
  830. this.showMedia();
  831. this.toggleMedia();
  832. },
  833. onScrollLoadDescriptions: function (ajax) {
  834. if (YTMA.user.fn.$scroller) { YTMA.user.fn.$scroller.stop(); }
  835.  
  836. YTMA.user.fn.$scroller = new YTMA.Scroll('span.ytm_manual > a.ytm_title:not(.ytm_error)', function (a) {
  837. if (YTMA.Scroll.visibleAll(a, 200)) {
  838. if (ajax) {
  839. YTMA.ajax.loadFromDataset(a.dataset);
  840. } else {
  841. YTMA.ajax.loadFromCacheDataset(a.dataset);
  842. }
  843. // console.log('doc', document.querySelectorAll(YTMA.user.fn.$scroller.selector).length, a.dataset.id);
  844. }
  845.  
  846. if (document.querySelectorAll(YTMA.user.fn.$scroller.selector).length === 0) {
  847. YTMA.user.fn.$scroller.stop();
  848. }
  849. });
  850. },
  851. makeForm: function () {
  852. var e, f = [
  853. '<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">',
  854. '<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>',
  855. '<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>',
  856. '<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>',
  857. '<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>',
  858. '<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>',
  859. '<fieldset><legend>YouTube</legend>',
  860. '<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>',
  861. '<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>',
  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 #60656b80;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 #181818;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;padding:3px}#ytm_settings legend{padding:3px}#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. },
  1370. streamable: {
  1371. title: 'streamable!',
  1372. home: 'https://streamable.com/',
  1373. embed: 'https://streamable.com/e/%key',
  1374. ajax: 'https://api.streamable.com/oembed.json?url=%uri',
  1375. thumb: 'url(https://cdn.streamable.com/image/%key.jpg)',
  1376. selector: 'a[href*="streamable.com/"]',
  1377. favicon: 'https://streamable.com/favicon.ico',
  1378. key: 'id',
  1379. reg: '(streamable\\.com)',
  1380. matcher: /(?:streamable\.com\/([A-Za-z0-9-_]+))/i,
  1381. https: true
  1382. },
  1383. imgur: {
  1384. title: 'imgur it!',
  1385. home: 'https://i.imgur.com/',
  1386. embed: 'https://i.imgur.com/%key',
  1387. thumb: 'url(https://i.imgur.com/%keyh.jpg)',
  1388. selector: 'a[href*=".gifv"]',
  1389. favicon: 'https://imgur.com/favicon.ico',
  1390. reg: '(\\.gifv$)|(imgur)',
  1391. matcher: /(?:imgur\.com\/(\w+)\.(?:gifv|mp4|webm))/i,
  1392. https: true,
  1393. scroll: true,
  1394. videoTag: true
  1395. },
  1396. html5: {
  1397. home: true,
  1398. title: 'html5 go!',
  1399. selector: 'a[href*=".webm"], a[href*=".mp4"]',
  1400. 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',
  1401. reg: '(\\.webm$)|(\\.mp4$)',
  1402. slim: true,
  1403. scroll: true,
  1404. videoTag: true
  1405. },
  1406. 'html5-audio': {
  1407. home: true,
  1408. title: 'hey, listen!',
  1409. selector: 'a[href*=".mp3"]',
  1410. reg: '(\\.mp3$)',
  1411. slim: true,
  1412. scroll: true
  1413. }
  1414. },
  1415. sources: {
  1416. iframe: function (data) {
  1417. var key = YTMA.DB.sites[data.site].key;
  1418.  
  1419. return [
  1420. { type: 'text/html', src: YTMA.DB.sites[data.site].embed.replace('%key', data[key]) }
  1421. ];
  1422. },
  1423. 'html5-audio': function (data) {
  1424. return [
  1425. { type: 'audio/mp3', src: data.uri }
  1426. ];
  1427. },
  1428. html5: function (data) {
  1429. // attaching the type as either mp4 or webm
  1430.  
  1431. if (/(?:webm)/.test(data.uri)) {
  1432. return [
  1433. { type: 'video/webm', src: data.uri }
  1434. ];
  1435. }
  1436.  
  1437. return [
  1438. { type: 'video/mp4', src: data.uri },
  1439. { type: 'video/webm', src: data.uri },
  1440. { type: 'video/ogg; codecs="theora, vorbis"', src: data.uri }
  1441. ];
  1442. },
  1443. imgur: function (data) {
  1444. var src = YTMA.DB.sites.imgur.embed.replace('%key', data.id);
  1445.  
  1446. return [
  1447. { type: 'video/webm', src: src + '.webm' },
  1448. { type: 'video/mp4', src: src + '.mp4' }
  1449. ];
  1450. },
  1451. youtube: function (data, attrs) {
  1452. var params = '?html5=1&version=3&modestbranding=1&rel=0&showinfo=1&vq=' + attrs.quality
  1453. + '&iv_load_policy=' + YTMA.user.preferences.yt_annotation
  1454. + '&start=' + attrs.start
  1455. + '&rel=0';// + YTMA.user.preferences.yt_volume;
  1456.  
  1457. return [
  1458. { type: 'text/html', src: YTMA.DB.sites.youtube.embed.replace('%key', data.id) + params }
  1459. ];
  1460. }
  1461. },
  1462. customToolbars: {
  1463. vine: {
  1464. ratio: false,
  1465. size: true
  1466. },
  1467. soundcloud: {
  1468. ratio: false,
  1469. size: false
  1470. }
  1471. },
  1472. playerSize: {
  1473. ratios: {
  1474. 1: 'sd',
  1475. 2: 'hd',
  1476. 3: 'pr'
  1477. },
  1478. sizes: {
  1479. 0: 'h',
  1480. 240: 's',
  1481. 360: 'm',
  1482. 480: 'l',
  1483. 720: 'xl'
  1484. },
  1485. aspects: {
  1486. 1: 4 / 3,
  1487. 2: 16 / 9,
  1488. 3: 16 / 9
  1489. }
  1490. },
  1491. qualities: {
  1492. 240: 'small',
  1493. 360: 'medium',
  1494. 480: 'large',
  1495. 720: 'hd720',
  1496. 1080: 'hd1080',
  1497. 1081: 'highres'
  1498. }
  1499. // videoTypes: (function () {
  1500. // var v = document.createElement('video');
  1501.  
  1502. // return {
  1503. // ogg: !!v.canPlayType('video/ogg; codecs="theora, vorbis"'),
  1504. // webm: !!v.canPlayType('video/webm'),
  1505. // mp4: !!v.canPlayType('video/mp4')
  1506. // };
  1507. // }()),
  1508. };
  1509.  
  1510. /** U I CLASS
  1511. * Class for the player controls
  1512. */
  1513. YTMA.UI = function (ytma) {
  1514. this.ytmx = ytma;
  1515.  
  1516. this.play = new YTMA.Player(this.ytmx);
  1517. this.open = false;
  1518. this.selected = { size: null, ratio: null };
  1519.  
  1520. this.trigger = ytma.spn;
  1521. this.projector = $$.e('div', { className: 'ytm_projector ytm_none ytm_block ytm_normalize ytm_sans' });
  1522. this.control = $$.e('ul', { className: 'ytm_control ytm_sans' });
  1523. this.customBar = YTMA.DB.views.getToolbar(this.ytmx.data.site);
  1524. this.controlBar();
  1525. };
  1526.  
  1527. YTMA.UI.ratios = {
  1528. SD: 1,
  1529. HD: 2,
  1530. PORTRAIT: 3
  1531. };
  1532.  
  1533. YTMA.UI.sizes = {
  1534. HIDDEN: 0,
  1535. S: 240,
  1536. M: 360,
  1537. L: 480,
  1538. X: 720
  1539. };
  1540.  
  1541. /** Trigger is the VAR element */
  1542. YTMA.UI.createFromTrigger = function (t) {
  1543. console.log('createFromTrigger');
  1544. if (t.hasAttribute('data-ytmuid') && !YTMA.set[t.dataset.ytmuid]) {
  1545. console.log('createFromTrigger-new');
  1546. YTMA.addToSet(new YTMA()._reactivate(t));
  1547. }
  1548. console.log('createFromTrigger-ui');
  1549. return YTMA.set[t.dataset.ytmuid].getUI();
  1550. };
  1551.  
  1552. YTMA.UI.events = {
  1553. $fire: {
  1554. settings: function () {
  1555. YTMA.user.events.formToggle();
  1556. },
  1557. close: function () {
  1558. if (YTMA.DB.sites[this.ytmx.data.site].scroll) {
  1559. console.log('events.close-1');
  1560. this.hideAllPlayers();
  1561. } else {
  1562. console.log('events.close-2');
  1563. this.ytmx.disableOpenOnScroll();
  1564. this.hidePlayer();
  1565. }
  1566. },
  1567. ratio: function (li) {
  1568. var n = parseInt(li.dataset.value, 10);
  1569. this.play.dimmensions(n);
  1570. this.markSelected(li, 'ratio');
  1571. },
  1572. size: function (li) {
  1573. var n = parseInt(li.dataset.value, 10);
  1574. this.play.dimmensions(null, n);
  1575. this.markSelected(li, 'size');
  1576. }
  1577. },
  1578. videoBar: function (e) {
  1579. var el = e.target, t;
  1580.  
  1581. if (el.tagName.toLowerCase() === 'li' && el.dataset && el.dataset.type) {
  1582. t = el.dataset.type;
  1583. if (YTMA.UI.events.$fire[t]) {
  1584. YTMA.UI.events.$fire[t].call(this, el);
  1585. }
  1586. }
  1587. }
  1588. };
  1589.  
  1590. YTMA.UI.prototype = {
  1591. constructor: YTMA.UI,
  1592. resetViewSize: function () {
  1593. this.play.dimmensions();
  1594. this.setControlBarSize(this.play.attrs.size);
  1595. },
  1596. showOnScroll: function (el) {
  1597. if (!this.open && this.ytmx.canScroll() && this.ytmx.isBelow(el)) {
  1598. this.showPlayer();
  1599. }
  1600. },
  1601. showPlayer: function () {
  1602. this.open = true;
  1603.  
  1604. this.trigger.classList.add('ytm_none');
  1605. this.projector.classList.remove('ytm_none');
  1606.  
  1607. this.attachPlayPanel();
  1608. this.play.switchOn();
  1609.  
  1610. if (YTMA.user.preferences.focus) {
  1611. document.location.hash = '#' + this.ytmx.container.id;
  1612. }
  1613. },
  1614. hidePlayer: function () {
  1615. this.open = false;
  1616.  
  1617. this.play.switchOff();
  1618. this.trigger.classList.remove('ytm_none');
  1619. this.projector.classList.add('ytm_none');
  1620. },
  1621. attachPlayPanel: function () {
  1622. if (!this.play.panel.parentNode) {
  1623. // console.log('attaching display panel');
  1624. this.projector.appendChild(this.play.panel);
  1625. }
  1626. },
  1627. hideAllPlayers: function () {
  1628. var group = YTMA.collect(this.ytmx.data.id);
  1629. console.log('closing all', this.ytmx.data.id, group.length);
  1630. group.forEach(function (y) {
  1631. y.disableOpenOnScroll();
  1632. y.getUI().hidePlayer();
  1633. });
  1634. },
  1635. setControlBarSize: function (size) {
  1636. this.markSelected(this.control.querySelector('li[data-value="' + size + '"]'), 'size');
  1637. },
  1638. controlBar: function () {
  1639. var f = document.createDocumentFragment();
  1640.  
  1641. $$.a(f,
  1642. this.customBar.ratio ? this.buildList('ytm_ratios', [
  1643. { type: 'ratio', text: '4:3', value: YTMA.UI.ratios.SD, title: 'SD' },
  1644. { type: 'ratio', text: '16:9', value: YTMA.UI.ratios.HD, title: 'Landscape' },
  1645. { type: 'ratio', text: '9:16', value: YTMA.UI.ratios.PORTRAIT, title: 'Portrait' }]) : null,
  1646. this.customBar.size ? this.buildList('ytm_sizes', [
  1647. { type: 'size', text: '\u00D8', value: YTMA.UI.sizes.HIDDEN, title: 'Hide the video.' },
  1648. { type: 'size', text: 'S', value: YTMA.UI.sizes.S, title: '240p' },
  1649. { type: 'size', text: 'M', value: YTMA.UI.sizes.M, title: '360p' },
  1650. { type: 'size', text: 'L', value: YTMA.UI.sizes.L, title: '480p' },
  1651. { type: 'size', text: 'X', value: YTMA.UI.sizes.X, title: '720p' }]) : null,
  1652. this.buildList('ytm_options', [
  1653. strg.on ? { type: 'settings', text: '!', title: 'YTMA Settings' } : null,
  1654. { type: 'close', text: '\u00D7', title: 'Close the video.' }])
  1655. );
  1656.  
  1657. this.control.appendChild(f);
  1658. this.control.addEventListener('click', YTMA.UI.events.videoBar.bind(this), false);
  1659. this.projector.appendChild(this.control);
  1660. this.ytmx.container.insertBefore(this.projector, this.trigger.nextSibling);
  1661. },
  1662. markSelected: function (el, type) {
  1663. el.id = type + this.ytmx.data.uid;
  1664. try {
  1665. this.selected[type].removeAttribute('id');
  1666. } catch (e) { }
  1667. this.selected[type] = el;
  1668. },
  1669. buildList: function (className, elements) {
  1670. var li = $$.e('li'),
  1671. ul = $$.e('ul', { className: className }, li),
  1672. f = document.createDocumentFragment(),
  1673. i,
  1674. e;
  1675.  
  1676. for (i = 0; i < elements.length; i++) {
  1677. e = elements[i];
  1678. if (e) {
  1679. f.appendChild(this.li(e.type, e.text, e.value, e.title));
  1680. }
  1681. }
  1682. ul.appendChild(f);
  1683. return li;
  1684. },
  1685. li: function (type, txt, value, title) {
  1686. var l = $$.e('li', { _type: type, textContent: txt, _value: value, title: title });
  1687. if ((type === 'size' && this.play.attrs.size === value) || (type === 'ratio' && this.play.attrs.ratio === value)) {
  1688. this.markSelected(l, type);
  1689. }
  1690. return l;
  1691. }
  1692. };
  1693.  
  1694. /** P L A Y E R CLASS
  1695. * @param parent YTMA instance
  1696. */
  1697. YTMA.Player = function (parent) {
  1698. this.parent = parent;
  1699.  
  1700. this.mode = 'off';
  1701.  
  1702. this.attrs = {
  1703. sources: null,
  1704. quality: YTMA.DB.views.getPlayerQuality(YTMA.user.preferences.quality),
  1705. size: null,
  1706. ratio: null,
  1707. start: this.time(),
  1708. type: null
  1709. };
  1710.  
  1711. this.attrs.sources = YTMA.DB.views.getPlayerSources(parent.data.site)(parent.data, this.attrs);
  1712.  
  1713. // todo improve type/media
  1714. this.attrs.type = this.findType();
  1715. this.media = YTMA.Player.makeMedia[this.attrs.type](this);
  1716.  
  1717. this.channel = $$.e('div', { className: 'ytm_panel_channel ytm_block' }, this.media, true);
  1718. this.switcher = $$.e('div', { className: 'ytm_panel_switcher ytm_panel_size ytm_block ytm_' + this.attrs.type, _ytmuid: this.parent.data.uid, _standby: true });
  1719. this.panel = $$.e('div', { className: 'ytm_panel ytm_block' }, this.switcher, true);
  1720.  
  1721. if (parent.data.site === 'soundcloud' && YTMA.reg.extra.soundcloud.playlist.test(parent.anchor.href)) {
  1722. this.media.classList.add('ytm_soundcloud-playlist');
  1723. this.switcher.classList.add('ytm_soundcloud-playlist');
  1724. }
  1725.  
  1726. this.dimmensions(YTMA.user.preferences.ratio, YTMA.user.preferences.size);
  1727. };
  1728.  
  1729. YTMA.Player.css = {
  1730. item: function (key, value) {
  1731. if (isNumber(value)) {
  1732. value += 'px';
  1733. }
  1734.  
  1735. return '\t' + key + ': ' + value + ';\n';
  1736. },
  1737. iter: function (css, cssEntries) {
  1738. $$.o(cssEntries, function (key, value) {
  1739. css.push(YTMA.Player.css.item(key, value));
  1740. });
  1741. css.push('}');
  1742. },
  1743. generator: function () {
  1744. var css = [];
  1745.  
  1746. $$.o(this.sizes, function (size, sizes) {
  1747. $$.o(sizes, function (dimm, keys) {
  1748. css.push('\n.ytm_panel-' + size + '.ytm_panel-' + dimm + ' .ytm_panel_size {\n');
  1749. YTMA.Player.css.iter(css, keys);
  1750. });
  1751. });
  1752.  
  1753. // add site overrides
  1754. $$.o(this.sites, function (site, data) {
  1755. $$.o(data, function (setting, keys) {
  1756. if (setting === 'all') {
  1757. css.push('\n.ytm_site_' + site + ' .ytm_panel_size {\n');
  1758. } else {
  1759. css.push('\n.ytm_site_' + site + ' .ytm_panel-' + setting + ' .ytm_panel_size {\n');
  1760. }
  1761. YTMA.Player.css.iter(css, keys);
  1762. });
  1763. });
  1764.  
  1765. return css.join('');
  1766. },
  1767. sizes: (function () {
  1768. var merge = {};
  1769.  
  1770. $$.o(YTMA.DB.playerSize.sizes, function (num, size) {
  1771. if (num >= 0) {
  1772. merge[size] = {};
  1773.  
  1774. $$.o(YTMA.DB.playerSize.ratios, function (k, ratio) {
  1775. if (ratio === 'pr') {
  1776. var w = Math.floor(num * 0.95); // smaller than the normal sizes
  1777. merge[size][ratio] = {
  1778. width: w,
  1779. height: Math.floor(w * YTMA.DB.playerSize.aspects[k])
  1780. };
  1781. } else {
  1782. merge[size][ratio] = {
  1783. width: Math.floor(num * YTMA.DB.playerSize.aspects[k]),
  1784. height: num
  1785. };
  1786. }
  1787. });
  1788. }
  1789. });
  1790.  
  1791. return merge;
  1792. }()),
  1793. sites: { // custom sizes per site
  1794. soundcloud: {
  1795. all: {
  1796. height: '118px !important'
  1797. }
  1798. },
  1799. vine: {
  1800. s: {
  1801. width: 240,
  1802. height: 240
  1803. },
  1804. m: {
  1805. width: 360,
  1806. height: 360
  1807. },
  1808. l: {
  1809. width: 480,
  1810. height: 480
  1811. },
  1812. xl: {
  1813. width: 720,
  1814. height: 720
  1815. }
  1816. }
  1817. }
  1818. };
  1819.  
  1820. YTMA.Player.makeMedia = {
  1821. $css: function (type) {
  1822. return 'ytm_panel_media ytm_panel_size ytm_block ytm_' + type;
  1823. },
  1824. video: function (player) {
  1825. var video = $$.e('video', {
  1826. controls: true,
  1827. autoplay: false,
  1828. loop: true,
  1829. className: this.$css('video'),
  1830. $allowscriptaccess: true,
  1831. preload: 'metadata'
  1832. }), links = [];
  1833.  
  1834. player.attrs.sources.forEach(function (source) {
  1835. $$.e('source', { src: source.src, $type: source.type }, video);
  1836.  
  1837. links.push('<a href="' + source.src + '">' + source.src + '</a>');
  1838. });
  1839.  
  1840. $$.e('p', { innerHTML: 'Could not load source(s): ' + links.join('<br />') }, video);
  1841.  
  1842. return video;
  1843. },
  1844. iframe: function (player) {
  1845. return $$.e('iframe', {
  1846. $allowfullscreen: true,
  1847. $referrerpolicy: 'no-referrer',
  1848. // $sandbox: 'allow-same-origin allow-scripts allow-popups',
  1849. $type: player.attrs.sources[0].type,
  1850. src: player.attrs.sources[0].src,
  1851. className: this.$css('iframe')
  1852. });
  1853. },
  1854. audio: function (player) {
  1855. return $$.e('audio', {
  1856. src: player.attrs.sources[0].src,
  1857. $type: player.attrs.sources[0].type
  1858. });
  1859. }
  1860. };
  1861.  
  1862. YTMA.Player.prototype = {
  1863. constructor: YTMA.Player,
  1864. dimmensions: function (ratio, size) {
  1865. this.attrs.ratio = isNumber(ratio) ? ratio : this.attrs.ratio;
  1866. this.attrs.size = isNumber(size) ? size : this.attrs.size;
  1867. this.panel.className = YTMA.DB.views.getPlayerDimmensions(this.attrs.ratio, this.attrs.size);
  1868. },
  1869. time: function () {
  1870. try {
  1871. var m = this.parent.data.uri.match(YTMA.reg.time).slice(1, 3);
  1872. return ((+m[0] || 0) * 60 * 60) + ((+m[1] || 0) * 60) + (+m[2] || 0);
  1873. } catch (e) { return 0; }
  1874. },
  1875. findType: function () {
  1876. if (this.parent.data.site === 'html5-audio') { return 'audio'; }
  1877. if (YTMA.DB.sites[this.parent.data.site].videoTag) { return 'video'; }
  1878. return 'iframe';
  1879. },
  1880. switchOff: function () {
  1881. // console.log('removed media');
  1882.  
  1883. if (this.media.pause) {
  1884. console.log('pausing');
  1885. this.media.pause();
  1886. }
  1887.  
  1888. try {
  1889. this.switcher.removeChild(this.channel);
  1890. } catch (e) {
  1891. // console.error(e);
  1892. }
  1893. this.mode = 'off';
  1894. },
  1895. switchOn: function () {
  1896. if (this.attrs.size === 0) {
  1897. this.attrs.size = YTMA.user.preferences.size;
  1898. this.parent.ui.resetViewSize();
  1899. }
  1900. // console.log('switch to media');
  1901. this.switcher.appendChild(this.channel);
  1902. this.switcher.dataset.standby = false;
  1903. this.mode = 'on';
  1904. },
  1905. switchStandby: function () {
  1906. // console.log('switch to standby');
  1907. this.switchOff();
  1908. this.switcher.dataset.standby = true;
  1909. this.mode = 'standby';
  1910. },
  1911. isStandby: function () {
  1912. return this.mode === 'standby';
  1913. }
  1914. };
  1915.  
  1916. YTMA.prototype = {
  1917. constructor: YTMA,
  1918. getUI: function () {
  1919. if (!this.ui) {
  1920. this.ui = new YTMA.UI(this);
  1921. }
  1922.  
  1923. return this.ui;
  1924. },
  1925. setup: function () {
  1926. var site = YTMA.DB.sites[this.data.site];
  1927.  
  1928. if (site) {
  1929. this.spn.title = site.title || 'ytma!';
  1930.  
  1931. if (site.thumb) {
  1932. this.spn.style.backgroundImage = site.thumb.replace('%key', this.data.id);
  1933. }
  1934.  
  1935. if (site.https) {
  1936. this.anchor.href = this.anchor.href.replace('http:', 'https:');
  1937. }
  1938. }
  1939.  
  1940. try {
  1941. this.dom.custom[this.data.site].call(this);
  1942. } catch (e) { }
  1943.  
  1944. this.dom.link.call(this);
  1945. this.dom.span.call(this);
  1946. },
  1947. disableOpenOnScroll: function () {
  1948. this.anchor.dataset.ytmscroll = false;
  1949. },
  1950. canScroll: function () {
  1951. return this.anchor.dataset.ytmscroll === 'true';
  1952. },
  1953. isBelow: function (link) {
  1954. return YTMA.Scroll.compare(this.anchor, link) < 1;
  1955. },
  1956. dom: {
  1957. custom: { // modifies interface according to site
  1958. youtube: function () {
  1959. this.spn.addEventListener('mouseenter', YTMA.events.thumb.start, false);
  1960. this.spn.addEventListener('mouseleave', YTMA.events.thumb.stop, false);
  1961. this.anchor.href = this.anchor.href.replace('youtu.be/', 'youtube.com/watch?v=');
  1962. }
  1963. },
  1964. link: function () {
  1965. if (this.anchor.getElementsByTagName('img').length === 0) {
  1966. this.anchor.className += ' ytm_link ytm_link_' + this.data.site + ' ';
  1967. }
  1968. this.anchor.dataset.ytmid = this.data.id;
  1969. this.anchor.dataset.ytmuid = this.data.uid;
  1970. this.anchor.dataset.ytmsid = this.data.sid;
  1971. this.anchor.title = 'Visit the video page.';
  1972. this.anchor.parentNode.insertBefore(this.container, this.anchor.nextSibling);
  1973. },
  1974. span: function () {
  1975. var f = document.createDocumentFragment(),
  1976. site = YTMA.DB.sites[this.data.site];
  1977.  
  1978. $$.e('span', { className: 'ytm_init ytm_label ytm_sans ytm_box', textContent: this.spn.title }, this.spn);
  1979. $$.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);
  1980.  
  1981. this.spn.title = 'Watch now!';
  1982. f.appendChild(this.spn);
  1983.  
  1984. if (site.ajax) { f.appendChild(this.dom.dataLoadLink.call(this)); }
  1985. if (site.slim) { this.container.classList.add('ytm_site_slim'); }
  1986. if (site.scroll) { this.anchor.classList.add('ytm_scroll'); }
  1987.  
  1988. this.container.appendChild(f);
  1989. },
  1990. dataLoadLink: function () {
  1991. var a, s;
  1992. s = $$.e('span', { className: 'ytm_bd ytm_normalize ytm_manual _' + this.data.sid });
  1993. a = $$.e('a', {
  1994. className: 'ytm_title',
  1995. textContent: 'Load description.',
  1996. href: '#',
  1997. title: 'Load this video\'s description.',
  1998. _ytmid: this.data.id,
  1999. _ytmsite: this.data.site,
  2000. _ytmuri: this.data.uri,
  2001. _ytmdescription: 'true'
  2002. });
  2003. return $$.a(s, a);
  2004. }
  2005. }
  2006. };
  2007.  
  2008. /**
  2009. * Creates a new YTMA from the given attributes
  2010. * @String|Number id Unique ID
  2011. * @String site Website eg: youtube, vimeo
  2012. * @HTMLAnchorElement a Anchor element
  2013. */
  2014. YTMA.prototype._new = function (id, site, a) {
  2015. var uid = YTMA.escapeId(id + '_' + (YTMA.num += 1));
  2016.  
  2017. this.data = {
  2018. id: id,
  2019. uid: YTMA.escapeId(uid), // unique id
  2020. sid: YTMA.escapeId(id), // shared id
  2021. site: site,
  2022. uri: a.href
  2023. };
  2024.  
  2025. this.ui = null;
  2026.  
  2027. if (!a.hasAttribute('data-ytmscroll')) { a.dataset.ytmscroll = true; }
  2028.  
  2029. this.anchor = a;
  2030.  
  2031. this.spn = $$.e('span', { className: 'ytm_trigger ytm_block ytm_normalize ytm_sans', _ytmid: this.data.id, _ytmsite: this.data.site });
  2032. this.container = $$.e('div', { id: 'w' + this.data.uid, className: 'ytm_spacer ytm_block ytm_site_' + this.data.site });
  2033.  
  2034. return this;
  2035. };
  2036.  
  2037. /**
  2038. * Recreates a YTMA object from a trigger element
  2039. * @HTMLElement
  2040. */
  2041. YTMA.prototype._reactivate = function (trigger) {
  2042. var id = trigger.dataset.ytmid,
  2043. a = document.querySelector('a[data-ytmuid="' + trigger.dataset.ytmuid + '"]');
  2044.  
  2045. this.data = {
  2046. id: id,
  2047. uid: trigger.dataset.ytmuid,
  2048. sid: trigger.dataset.ytmsid,
  2049. site: trigger.dataset.ytmsite,
  2050. uri: a.href
  2051. };
  2052.  
  2053. this.ui = null;
  2054. this.anchor = a;
  2055. this.spn = trigger.parentElement;
  2056. this.container = this.spn.parentElement;
  2057.  
  2058. return this;
  2059. };
  2060.  
  2061. /** S C R O L L CLASS
  2062. * Window-Scroll Event Helper
  2063. */
  2064. YTMA.Scroll = (function () {
  2065.  
  2066. function Scroll(selector, cb, delay) {
  2067. this.selector = selector;
  2068. this.cb = cb;
  2069.  
  2070. // console.log('YTMA.Scroll Monitor: ', selector);
  2071. this.bound = Scroll.debounce(this.monitor.bind(this), delay || 500);
  2072.  
  2073. this.bound();
  2074. window.addEventListener('scroll', this.bound, false);
  2075. }
  2076.  
  2077. Scroll.debounce = function (fn, delay) {
  2078. var timeout;
  2079. delay = delay || 250;
  2080.  
  2081. return function () {
  2082. var self = this, args = arguments, timed;
  2083.  
  2084. timed = function () {
  2085. timeout = null;
  2086. fn.apply(self, args);
  2087. };
  2088.  
  2089. window.clearTimeout(timeout);
  2090. timeout = window.setTimeout(timed, delay);
  2091. };
  2092. };
  2093.  
  2094. Scroll.visible = function (el) {
  2095. var bound = el.getBoundingClientRect();
  2096. return (bound.top >= 0 && bound.top <= document.documentElement.clientHeight);
  2097. };
  2098.  
  2099. Scroll.visibleAll = function (el, offset) {
  2100. var bound = el.getBoundingClientRect(),
  2101. height = document.documentElement.clientHeight;
  2102. offset = isNumber(offset) ? +offset : 0;
  2103. return ((bound.bottom + offset >= 0)
  2104. && (bound.top <= height + offset || bound.bottom <= height - offset));
  2105. };
  2106.  
  2107. /** Returns 1, 0, -1 when el1 is above, exactly the same, or below el2 */
  2108. Scroll.compare = function (el1, el2) {
  2109. var a = el1.getBoundingClientRect().y,
  2110. b = el2.getBoundingClientRect().y;
  2111.  
  2112. if (a < b) { return 1; }
  2113. if (a === b) { return 0; }
  2114. return -1;
  2115. };
  2116.  
  2117. Scroll.prototype = {
  2118. stop: function () {
  2119. // console.log('clear scroll: ', this.selector);
  2120. window.removeEventListener('scroll', this.bound);
  2121. },
  2122. monitor: function () {
  2123. $$.s(this.selector, this.cb);
  2124. }
  2125. };
  2126.  
  2127. return Scroll;
  2128.  
  2129. }());
  2130.  
  2131. YTMA.main();
  2132.  
  2133. }());