YouTube Me Again!

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

目前为 2016-03-29 提交的版本。查看 最新版本

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