YouTube Links

Show the available video links.

目前为 2014-10-08 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Links
  3. // @namespace http://www.smallapple.net/
  4. // @description Show the available video links.
  5. // @author Ng Hun Yang
  6. // @include http://*.youtube.com/*
  7. // @include http://youtube.com/*
  8. // @include https://*.youtube.com/*
  9. // @include https://youtube.com/*
  10. // @match *://*.youtube.com/*
  11. // @match *://*.googlevideo.com/*
  12. // @match *://s.ytimg.com/yts/jsbin/*
  13. // @grant GM_xmlhttpRequest
  14. // @version 1.63
  15. // ==/UserScript==
  16.  
  17. /* This is based on YouTube HD Suite 3.4.1 */
  18.  
  19. /* Tested on Firefox 5.0, Chrome 13 and Opera 11.50 */
  20.  
  21. (function() {
  22.  
  23. // =============================================================================
  24.  
  25. var win = typeof(unsafeWindow) !== "undefined" ? unsafeWindow : window;
  26. var doc = win.document;
  27. var loc = win.location;
  28.  
  29. var unsafeWin = win;
  30.  
  31. // Hack to get unsafe window in Chrome
  32. (function() {
  33.  
  34. var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") >= 0;
  35.  
  36. if(!isChrome)
  37. return;
  38.  
  39. // Chrome 27 fixed this exploit, but luckily, its unsafeWin now works for us
  40. try {
  41. var div = doc.createElement("div");
  42. div.setAttribute("onclick", "return window;");
  43. unsafeWin = div.onclick();
  44. } catch(e) {
  45. }
  46.  
  47. }) ();
  48.  
  49. // =============================================================================
  50.  
  51. var SCRIPT_NAME = "YouTube Links";
  52.  
  53. var relInfo = {
  54. ver: 16300,
  55. ts: 2014100800,
  56. desc: "Switch to Greasy Fork"
  57. };
  58.  
  59. var SCRIPT_UPDATE_LINK = loc.protocol + "//greasyfork.org/scripts/5565-youtube-links-updater/code/YouTube Links Updater.user.js";
  60. var SCRIPT_LINK = loc.protocol + "//greasyfork.org/scripts/5566-youtube-links/code/YouTube Links.user.js";
  61.  
  62. // =============================================================================
  63.  
  64. var dom = {};
  65.  
  66. dom.gE = function(id) {
  67. return doc.getElementById(id);
  68. };
  69.  
  70. dom.gT = function(dom, tag) {
  71. if(arguments.length == 1) {
  72. tag = dom;
  73. dom = doc;
  74. }
  75.  
  76. return dom.getElementsByTagName(tag);
  77. };
  78.  
  79. dom.cE = function(tag) {
  80. return doc.createElement(tag);
  81. };
  82.  
  83. dom.cT = function(s) {
  84. return doc.createTextNode(s);
  85. };
  86.  
  87. dom.attr = function(obj, k, v) {
  88. if(arguments.length == 2)
  89. return obj.getAttribute(k);
  90.  
  91. obj.setAttribute(k, v);
  92. };
  93.  
  94. dom.prepend = function(obj, child) {
  95. obj.insertBefore(child, obj.firstChild);
  96. };
  97.  
  98. dom.append = function(obj, child) {
  99. obj.appendChild(child);
  100. };
  101.  
  102. dom.offset = function(obj) {
  103. var x = 0;
  104. var y = 0;
  105.  
  106. if(obj.getBoundingClientRect) {
  107. var box = obj.getBoundingClientRect();
  108. var owner = obj.ownerDocument;
  109.  
  110. x = box.left + Math.max(owner.documentElement.scrollLeft, owner.body.scrollLeft) - owner.documentElement.clientLeft;
  111. y = box.top + Math.max(owner.documentElement.scrollTop, owner.body.scrollTop) - owner.documentElement.clientTop;
  112.  
  113. return { left: x, top: y };
  114. }
  115.  
  116. if(obj.offsetParent) {
  117. do {
  118. x += obj.offsetLeft - obj.scrollLeft;
  119. y += obj.offsetTop - obj.scrollTop;
  120. obj = obj.offsetParent;
  121. } while(obj);
  122. }
  123.  
  124. return { left: x, top: y };
  125. };
  126.  
  127. dom.inViewport = function(el) {
  128. var rect = el.getBoundingClientRect();
  129.  
  130. return rect.bottom >= 0 &&
  131. rect.right >= 0 &&
  132. rect.top < (win.innerHeight || doc.documentElement.clientHeight) &&
  133. rect.left < (win.innerWidth || doc.documentElement.clientWidth);
  134. };
  135.  
  136. dom.html = function(obj, s) {
  137. if(arguments.length == 1)
  138. return obj.innerHTML;
  139.  
  140. obj.innerHTML = s;
  141. };
  142.  
  143. dom.emitHtml = function(tag, attrs, body) {
  144. if(arguments.length == 2) {
  145. if(typeof(attrs) == "string") {
  146. body = attrs;
  147. attrs = {};
  148. }
  149. }
  150.  
  151. var list = [];
  152.  
  153. for(var k in attrs) {
  154. list.push(k + "='" + attrs[k].replace(/'/g, "\\'") + "'");
  155. }
  156.  
  157. var s = "<" + tag + " " + list.join(" ") + ">";
  158.  
  159. if(body != null)
  160. s += body + "</" + tag + ">";
  161.  
  162. return s;
  163. };
  164.  
  165. dom.emitCssStyles = function(styles) {
  166. var list = [];
  167.  
  168. for(var k in styles) {
  169. list.push(k + ": " + styles[k] + ";");
  170. }
  171.  
  172. return " { " + list.join(" ") + " }";
  173. };
  174.  
  175. dom.ajax = function(opts) {
  176. function newXhr() {
  177. if(window.ActiveXObject) {
  178. try {
  179. return new ActiveXObject("Msxml2.XMLHTTP");
  180. } catch(e) {
  181. }
  182.  
  183. try {
  184. return new ActiveXObject("Microsoft.XMLHTTP");
  185. } catch(e) {
  186. return null;
  187. }
  188. }
  189.  
  190. if(window.XMLHttpRequest)
  191. return new XMLHttpRequest();
  192.  
  193. return null;
  194. }
  195.  
  196. function nop() {
  197. }
  198.  
  199. // Entry point
  200. var xhr = newXhr();
  201.  
  202. opts = addProp({
  203. type: "GET",
  204. async: true,
  205. success: nop,
  206. error: nop,
  207. complete: nop
  208. }, opts);
  209.  
  210. xhr.open(opts.type, opts.url, opts.async);
  211.  
  212. xhr.onreadystatechange = function() {
  213. if(xhr.readyState == 4) {
  214. var status = +xhr.status;
  215.  
  216. if(status >= 200 && status < 300) {
  217. opts.success(xhr.responseText, "success", xhr);
  218. }
  219. else {
  220. opts.error(xhr, "error");
  221. }
  222.  
  223. opts.complete(xhr);
  224. }
  225. };
  226.  
  227. xhr.send("");
  228. };
  229.  
  230. dom.crossAjax = function(opts) {
  231. function wrapXhr(xhr) {
  232. var headers = xhr.responseHeaders.replace("\r", "").split("\n");
  233.  
  234. var obj = {};
  235.  
  236. forEach(headers, function(idx, elm) {
  237. var nv = elm.split(":");
  238. if(nv[1] != null)
  239. obj[nv[0].toLowerCase()] = nv[1].replace(/^\s+/, "").replace(/\s+$/, "");
  240. });
  241.  
  242. return {
  243. responseText: xhr.responseText,
  244. status: xhr.status,
  245.  
  246. getAllResponseHeaders: function() {
  247. return xhr.responseHeaders;
  248. },
  249.  
  250. getResponseHeader: function(name) {
  251. return obj[name.toLowerCase()];
  252. }
  253. };
  254. }
  255.  
  256. function nop() {
  257. }
  258.  
  259. // Entry point
  260. opts = addProp({
  261. type: "GET",
  262. async: true,
  263. success: nop,
  264. error: nop,
  265. complete: nop
  266. }, opts);
  267.  
  268. if(typeof GM_xmlhttpRequest === "undefined") {
  269. setTimeout(function() {
  270. var xhr = {};
  271. opts.error(xhr, "error");
  272. opts.complete(xhr);
  273. }, 0);
  274. return;
  275. }
  276.  
  277. GM_xmlhttpRequest({
  278. method: opts.type,
  279. url: opts.url,
  280. synchronous: !opts.async,
  281.  
  282. onload: function(xhr) {
  283. xhr = wrapXhr(xhr);
  284.  
  285. if(xhr.status >= 200 && xhr.status < 300)
  286. opts.success(xhr.responseText, "success", xhr);
  287. else
  288. opts.error(xhr, "error");
  289.  
  290. opts.complete(xhr);
  291. },
  292.  
  293. onerror: function(xhr) {
  294. xhr = wrapXhr(xhr);
  295. opts.error(xhr, "error");
  296. opts.complete(xhr);
  297. }
  298. });
  299. };
  300.  
  301. dom.addEvent = function(e, type, fn) {
  302. function mouseEvent(event) {
  303. if(this != event.relatedTarget && !dom.isAChildOf(this, event.relatedTarget))
  304. fn.call(this, event);
  305. }
  306.  
  307. // Entry point
  308. if(e.addEventListener) {
  309. var effFn = fn;
  310.  
  311. if(type == "mouseenter") {
  312. type = "mouseover";
  313. effFn = mouseEvent;
  314. }
  315. else if(type == "mouseleave") {
  316. type = "mouseout";
  317. effFn = mouseEvent;
  318. }
  319.  
  320. e.addEventListener(type, effFn, /*capturePhase*/ false);
  321. }
  322. else
  323. e.attachEvent("on" + type, function() { fn(win.event); });
  324. };
  325.  
  326. dom.insertCss = function (styles) {
  327. var ss = dom.cE("style");
  328. dom.attr(ss, "type", "text/css");
  329.  
  330. var hh = dom.gT("head") [0];
  331. dom.append(hh, ss);
  332. dom.append(ss, dom.cT(styles));
  333. };
  334.  
  335. dom.isAChildOf = function(parent, child) {
  336. if(parent === child)
  337. return false;
  338.  
  339. while(child && child !== parent) {
  340. child = child.parentNode;
  341. }
  342.  
  343. return child === parent;
  344. };
  345.  
  346. // -----------------------------------------------------------------------------
  347.  
  348. function timeNowInSec() {
  349. return Math.round(+new Date() / 1000);
  350. }
  351.  
  352. function forLoop(opts, fn) {
  353. opts = addProp({ start: 0, inc: 1 }, opts);
  354.  
  355. for(var idx = opts.start; idx < opts.num; idx += opts.inc) {
  356. if(fn.call(opts, idx, opts) === false)
  357. break;
  358. }
  359. }
  360.  
  361. function forEach(list, fn) {
  362. forLoop({ num: list.length }, function(idx) {
  363. return fn.call(list[idx], idx, list[idx]);
  364. });
  365. }
  366.  
  367. function addProp(dest, src) {
  368. for(var k in src) {
  369. if(src[k] != null)
  370. dest[k] = src[k];
  371. }
  372.  
  373. return dest;
  374. }
  375.  
  376. function unescHtmlEntities(s) {
  377. return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
  378. }
  379.  
  380. function logMsg(s) {
  381. win.console.log(s);
  382. }
  383.  
  384. function cnvSafeFname(s) {
  385. s = s.replace(/:/g, "-").replace(/"/g, "'").replace(/[\\/|*?]/g, "_");
  386. return encodeURIComponent(s).replace(/'/g, "%27");
  387. }
  388.  
  389. function getVideoName(s) {
  390. var list = [
  391. { name: "3GP", codec: "video/3gpp" },
  392. { name: "FLV", codec: "video/x-flv" },
  393. { name: "M4V", codec: "video/x-m4v" },
  394. { name: "MP3", codec: "audio/mpeg" },
  395. { name: "MP4", codec: "video/mp4" },
  396. { name: "M4A", codec: "audio/mp4" },
  397. { name: "QT", codec: "video/quicktime" },
  398. { name: "WEBM", codec: "audio/webm" },
  399. { name: "WEBM", codec: "video/webm" },
  400. { name: "WMV", codec: "video/ms-wmv" }
  401. ];
  402.  
  403. var name = "?";
  404.  
  405. forEach(list, function(idx, elm) {
  406. if(s.match("^" + elm.codec)) {
  407. name = elm.name;
  408. return false;
  409. }
  410. });
  411.  
  412. return name;
  413. }
  414.  
  415. function snapToStdRes(res) {
  416. var horzResList = [ 3840, 2048, 1440, 960, 640, 480, 320, 176 ];
  417. var horzWideResList = [ 2880, 1920, 1280, 854, 640, 426, 256 ];
  418. var vertResList = [ 2160, 1536, 1080, 720, 480, 360, 240, 144 ];
  419.  
  420. if(!res.match(/^(\d+)x(\d+)/))
  421. return res;
  422.  
  423. var wd = +RegExp.$1;
  424. var ht = +RegExp.$2;
  425. var foundIdx;
  426.  
  427. // Snap to the nearest vert res first
  428. forEach(vertResList, function(idx, elm) {
  429. var tolerance = elm * 0.1;
  430. if(ht >= elm - tolerance && ht <= elm + tolerance) {
  431. foundIdx = idx;
  432. return false;
  433. }
  434. });
  435.  
  436. if(!foundIdx)
  437. return res;
  438.  
  439. var aspectRatio = wd / ht;
  440.  
  441. ht = vertResList[foundIdx];
  442. wd = Math.round(ht * aspectRatio);
  443.  
  444. // Snap to the nearest horz res
  445. forEach(aspectRatio < 1.5 ? horzResList : horzWideResList, function(idx, elm) {
  446. var tolerance = elm * 0.1;
  447. if(wd >= elm - tolerance && wd <= elm + tolerance) {
  448. wd = elm;
  449. return false;
  450. }
  451. });
  452.  
  453. return wd + "x" + ht;
  454. }
  455.  
  456. function cnvResName(res) {
  457. var resMap = {
  458. "audio": "Audio"
  459. };
  460.  
  461. if(resMap[res])
  462. return resMap[res];
  463.  
  464. if(!res.match(/^(\d+)x(\d+)/))
  465. return res;
  466.  
  467. var wd = +RegExp.$1;
  468. var ht = +RegExp.$2;
  469.  
  470. var vertResMap = {
  471. "2160": "2k",
  472. "1536": "1.5k",
  473. "240": "240v",
  474. "144": "144v"
  475. };
  476.  
  477. if(vertResMap[ht])
  478. return vertResMap[ht];
  479.  
  480. return String(ht) + (wd / ht < 1.5 ? "f" : "p");
  481. }
  482.  
  483. function mapResToQuality(res) {
  484. if(!res.match(/^[0-9]+x([0-9]+)$/))
  485. return res;
  486.  
  487. var resList = [
  488. { res: 1536, q : "highres" },
  489. { res: 1080, q: "hd1080" },
  490. { res: 720, q : "hd720" },
  491. { res: 480, q : "large" },
  492. { res: 360, q : "medium" }
  493. ];
  494.  
  495. var res = +RegExp.$1;
  496.  
  497. for(var i = 0; i < resList.length; ++i) {
  498. if(res >= resList[i].res)
  499. return resList[i].q;
  500. }
  501.  
  502. return "small";
  503. }
  504.  
  505. function getQualityIdx(quality) {
  506. var list = [ "small", "medium", "large", "hd720", "hd1080", "highres" ];
  507.  
  508. for(var i = 0; i < list.length; ++i) {
  509. if(list[i] == quality)
  510. return i;
  511. }
  512.  
  513. return -1;
  514. }
  515.  
  516. // =============================================================================
  517.  
  518. RegExp.escape = function(s) {
  519. return String(s).replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  520. };
  521.  
  522. var decryptSig = {
  523. store: {}
  524. };
  525.  
  526. (function () {
  527.  
  528. var SIG_STORE_ID = "ujsYtLinksSig";
  529.  
  530. var CHK_SIG_INTERVAL = 3 * 86400;
  531.  
  532. decryptSig.load = function() {
  533. var obj = localStorage[SIG_STORE_ID];
  534. if(obj == null)
  535. return;
  536.  
  537. decryptSig.store = JSON.parse(obj);
  538. };
  539.  
  540. decryptSig.save = function() {
  541. localStorage[SIG_STORE_ID] = JSON.stringify(decryptSig.store);
  542. };
  543.  
  544. decryptSig.extractScriptUrl = function(data) {
  545. if(data.match(/ytplayer.config\s*=.*\"assets"\s*:\s*{.*"js"\s*:\s*(".+?")/))
  546. return JSON.parse(RegExp.$1);
  547. else
  548. return false;
  549. };
  550.  
  551. decryptSig.getScriptName = function(url) {
  552. if(url.match(/\/yts\/jsbin\/html5player-(.*)\/html5player\.js$/))
  553. return RegExp.$1;
  554.  
  555. if(url.match(/\/html5player-(.*)\.js$/))
  556. return RegExp.$1;
  557.  
  558. return url;
  559. };
  560.  
  561. decryptSig.fetchScript = function(scriptName, url) {
  562. function success(data) {
  563. if(!data.match(/\.signature\s*=\s*(\w+)\(\w+\)/))
  564. return;
  565.  
  566. //console.log(scriptName + " sig fn: " + RegExp.$1);
  567.  
  568. if(!data.match(new RegExp("function " + RegExp.$1 + '\\s*\\((\\w+)\\)\\s*{(\\w+=\\w+\\.split\\(""\\);.+?;return \\w+\\.join\\(""\\))')))
  569. return;
  570.  
  571. var fnParam = RegExp.$1;
  572. var fnBody = RegExp.$2;
  573.  
  574. var fnHlp = {};
  575. var objHlp = {};
  576.  
  577. //console.log("param: " + fnParam);
  578. //console.log(fnBody);
  579.  
  580. fnBody = fnBody.split(";");
  581.  
  582. forEach(fnBody, function(idx, elm) {
  583. // its own property
  584. if(elm.match(new RegExp("^" + fnParam + "=" + fnParam + "\\.")))
  585. return;
  586.  
  587. // global fn
  588. if(elm.match(new RegExp("^" + fnParam + "=([a-zA-Z_$][a-zA-Z0-9_$]*)\\("))) {
  589. var name = RegExp.$1;
  590. //console.log("fnHlp: " + name);
  591.  
  592. if(fnHlp[name])
  593. return;
  594.  
  595. if(data.match(new RegExp("(function " + RegExp.escape(RegExp.$1) + ".+?;return \\w+})")))
  596. fnHlp[name] = RegExp.$1;
  597.  
  598. return;
  599. }
  600.  
  601. // object fn
  602. if(elm.match(new RegExp("^([a-zA-Z_$][a-zA-Z0-9_$]*)\.([a-zA-Z_$][a-zA-Z0-9_$]*)\\("))) {
  603. var name = RegExp.$1;
  604. console.log("objHlp: " + name);
  605.  
  606. if(objHlp[name])
  607. return;
  608.  
  609. if(data.match(new RegExp("(var " + RegExp.escape(RegExp.$1) + "={.+?};)")))
  610. objHlp[name] = RegExp.$1;
  611.  
  612. return;
  613. }
  614. });
  615.  
  616. //console.log(fnHlp);
  617. //console.log(objHlp);
  618.  
  619. var fnHlpStr = "";
  620.  
  621. for(var k in fnHlp)
  622. fnHlpStr += fnHlp[k];
  623.  
  624. for(var k in objHlp)
  625. fnHlpStr += objHlp[k];
  626.  
  627. var fullFn = "function(" + fnParam + "){" + fnHlpStr + fnBody.join(";") + "}";
  628. //console.log(fullFn);
  629.  
  630. decryptSig.store[scriptName] = { ver: relInfo.ver, ts: timeNowInSec(), fn: fullFn };
  631. //console.log(decryptSig);
  632.  
  633. decryptSig.save();
  634. }
  635.  
  636. // Entry point
  637. dom.crossAjax({ url: url, success: success });
  638. };
  639.  
  640. decryptSig.condFetchScript = function(url) {
  641. var scriptName = decryptSig.getScriptName(url);
  642. var store = decryptSig.store[scriptName];
  643. var now = timeNowInSec();
  644.  
  645. if(store && now - store.ts < CHK_SIG_INTERVAL && store.ver == relInfo.ver)
  646. return;
  647.  
  648. decryptSig.fetchScript(scriptName, url);
  649. };
  650.  
  651. }) ();
  652.  
  653. function deobfuscateVideoSig(scriptName, sig) {
  654. if(!decryptSig.store[scriptName])
  655. return sig;
  656.  
  657. //console.log(decryptSig.store[scriptName].fn);
  658.  
  659. try {
  660. sig = eval("(" + decryptSig.store[scriptName].fn + ") (\"" + sig + "\")");
  661. } catch(e) {
  662. }
  663.  
  664. return sig;
  665. }
  666.  
  667. // =============================================================================
  668.  
  669. function parseStreamMap(map, value) {
  670. var fmtUrlList = [];
  671.  
  672. forEach(value.split(","), function(idx, elm) {
  673. var elms = elm.replace(/(\\\/)/g, "/").replace(/(\\u0026)/g, "&").split("&");
  674. var obj = {};
  675.  
  676. forEach(elms, function(idx, elm) {
  677. var kv = elm.split("=");
  678. obj[kv[0]] = decodeURIComponent(kv[1]);
  679. });
  680.  
  681. obj.itag = +obj.itag;
  682.  
  683. if(obj.conn != null && obj.conn.match(/^rtmpe:\/\//))
  684. obj.isDrm = true;
  685.  
  686. if(obj.s != null && obj.sig == null) {
  687. var sig = deobfuscateVideoSig(map.scriptName, obj.s);
  688. if(sig != obj.s) {
  689. obj.sig = sig;
  690. delete obj.s;
  691. }
  692. }
  693.  
  694. fmtUrlList.push(obj);
  695. });
  696.  
  697. //logMsg(fmtUrlList);
  698.  
  699. map.fmtUrlList = fmtUrlList;
  700. }
  701.  
  702. function parseAdaptiveStreamMap(map, value) {
  703. var fmtUrlList = [];
  704.  
  705. forEach(value.split(","), function(idx, elm) {
  706. var elms = elm.replace(/(\\\/)/g, "/").replace(/(\\u0026)/g, "&").split("&");
  707. var obj = {};
  708.  
  709. forEach(elms, function(idx, elm) {
  710. var kv = elm.split("=");
  711. obj[kv[0]] = decodeURIComponent(kv[1]);
  712. });
  713.  
  714. obj.itag = +obj.itag;
  715.  
  716. if(obj.bitrate != null)
  717. obj.bitrate = +obj.bitrate;
  718.  
  719. //console.log(obj);
  720. //console.log(map.videoId + ": " + obj.index + " " + obj.init + " " + obj.itag + " " + obj.size + " " + obj.bitrate + " " + obj.type);
  721.  
  722. if(obj.type.match(/^video\/mp4/))
  723. obj.effType = "video/x-m4v";
  724.  
  725. if(obj.type.match(/^audio\//))
  726. obj.size = "audio";
  727.  
  728. var stdRes = snapToStdRes(obj.size);
  729. obj.quality = mapResToQuality(stdRes);
  730.  
  731. if(obj.s != null && obj.sig == null) {
  732. var sig = deobfuscateVideoSig(map.scriptName, obj.s);
  733. if(sig != obj.s) {
  734. obj.sig = sig;
  735. delete obj.s;
  736. }
  737. }
  738.  
  739. fmtUrlList.push(obj);
  740.  
  741. map.fmtMap[obj.itag] = { res: cnvResName(stdRes) };
  742. });
  743.  
  744. map.fmtUrlList = map.fmtUrlList.concat(fmtUrlList);
  745. }
  746.  
  747. function parseFmtList(map, value) {
  748. var list = value.split(",");
  749. var fmtMap = {};
  750.  
  751. forEach(list, function(idx, elm) {
  752. var elms = elm.replace(/(\\\/)/g, "/").split("/");
  753.  
  754. var fmtId = elms[0];
  755. var res = elms[1];
  756. elms.splice(/*idx*/ 0, /*rm*/ 2);
  757.  
  758. fmtMap[fmtId] = { res: cnvResName(res), vars: elms };
  759. });
  760.  
  761. map.fmtMap = fmtMap;
  762. }
  763.  
  764. function getExt(elm) {
  765. return "";
  766. }
  767.  
  768. function getVideoInfo(url, callback) {
  769. function success(data) {
  770. var map = {};
  771.  
  772. if(data.match(/<div\s+id="verify-details">/)) {
  773. logMsg("Skipping " + url);
  774. return;
  775. }
  776.  
  777. if(data.match(/<h1\s+id="unavailable-message">/)) {
  778. logMsg("Not avail " + url);
  779. return;
  780. }
  781.  
  782. if(data.match(/"t":\s?"(.+?)"/))
  783. map.t = RegExp.$1;
  784.  
  785. if(data.match(/"video_id":\s?"(.+?)"/))
  786. map.videoId = RegExp.$1;
  787.  
  788. map.scriptUrl = decryptSig.extractScriptUrl(data);
  789. if(map.scriptUrl) {
  790. //console.log(map.videoId + " script: " + map.scriptUrl);
  791. map.scriptName = decryptSig.getScriptName(map.scriptUrl);
  792. decryptSig.condFetchScript(map.scriptUrl);
  793. }
  794.  
  795. if(data.match(/<meta\s+itemprop="name"\s*content="(.+)"\s*>\s*\n/))
  796. map.title = unescHtmlEntities(RegExp.$1);
  797.  
  798. if(map.title == null && data.match(/<meta\s+name="title"\s*content="(.+)"\s*>/))
  799. map.title = unescHtmlEntities(RegExp.$1);
  800.  
  801. if(data.match(/"url_encoded_fmt_stream_map":\s?"(.+?)"/))
  802. parseStreamMap(map, RegExp.$1);
  803.  
  804. if(data.match(/"fmt_list":\s?"(.+?)"/))
  805. parseFmtList(map, RegExp.$1);
  806.  
  807. if(data.match(/"adaptive_fmts":\s?"(.+?)"/))
  808. parseAdaptiveStreamMap(map, RegExp.$1);
  809.  
  810. map.fmtUrlList.sort(function(a, b) {
  811. return getQualityIdx(b.quality) - getQualityIdx(a.quality);
  812. });
  813.  
  814. callback(map);
  815. }
  816.  
  817. // Entry point
  818. dom.ajax({ url: url, success: success });
  819. }
  820.  
  821. // -----------------------------------------------------------------------------
  822.  
  823. var CSS_PREFIX = "ujs-";
  824.  
  825. var HDR_LINKS_HTML_ID = CSS_PREFIX + "hdr-links-div";
  826. var LINKS_HTML_ID = CSS_PREFIX + "links-cls";
  827. var LINKS_TP_HTML_ID = CSS_PREFIX + "links-tp-div";
  828. var UPDATE_HTML_ID = CSS_PREFIX + "update-div";
  829. var VID_FMT_BTN_ID = CSS_PREFIX + "vid-fmt-btn";
  830.  
  831. /* The !important attr is to override the page's specificity. */
  832. var CSS_STYLES =
  833. "#" + VID_FMT_BTN_ID + dom.emitCssStyles({
  834. "margin": "0 0.333em"
  835. }) + "\n" +
  836. "#" + UPDATE_HTML_ID + dom.emitCssStyles({
  837. "background-color": "#f00",
  838. "border-radius": "2px",
  839. "color": "#fff",
  840. "padding": "5px",
  841. "text-align": "center",
  842. "text-decoration": "none",
  843. "position": "fixed",
  844. "top": "0.5em",
  845. "right": "0.5em",
  846. "z-index": "100"
  847. }) + "\n" +
  848. "#" + UPDATE_HTML_ID + ":hover" + dom.emitCssStyles({
  849. "background-color": "#0d0"
  850. }) + "\n" +
  851. "#" + HDR_LINKS_HTML_ID + dom.emitCssStyles({
  852. "background-color": "#eee",
  853. "border": "#ccc 1px solid",
  854. //"border-radius": "3px",
  855. "color": "#333",
  856. "font-size": "90%",
  857. "margin": "5px",
  858. "padding": "5px"
  859. }) + "\n" +
  860. "#" + HDR_LINKS_HTML_ID + " ." + CSS_PREFIX + "group" + dom.emitCssStyles({
  861. "background-color": "#fff",
  862. "color": "#000 !important",
  863. "border": "#ccc 1px solid",
  864. "border-radius": "3px",
  865. "display": "inline-block",
  866. "margin": "3px",
  867. }) + "\n" +
  868. "#" + HDR_LINKS_HTML_ID + " a" + dom.emitCssStyles({
  869. "display": "table-cell",
  870. "padding": "3px",
  871. "text-decoration": "none"
  872. }) + "\n" +
  873. "#" + HDR_LINKS_HTML_ID + " a:hover" + dom.emitCssStyles({
  874. "background-color": "#d1e1fa"
  875. }) + "\n" +
  876. "div." + LINKS_HTML_ID + dom.emitCssStyles({
  877. "border-radius": "3px",
  878. "font-size": "90%",
  879. "line-height": "1em",
  880. "position": "absolute",
  881. "left": "0",
  882. "top": "0",
  883. "z-index": "100"
  884. }) + "\n" +
  885. "#" + LINKS_TP_HTML_ID + dom.emitCssStyles({
  886. "background-color": "#eee",
  887. "border": "#aaa 1px solid",
  888. "padding": "3px 0",
  889. "text-decoration": "none",
  890. "white-space": "nowrap",
  891. "z-index": "110"
  892. }) + "\n" +
  893. "div." + LINKS_HTML_ID + " a" + dom.emitCssStyles({
  894. "display": "inline-block",
  895. "margin": "1px",
  896. "text-decoration": "none"
  897. }) + "\n" +
  898. "div." + LINKS_HTML_ID + " ." + CSS_PREFIX + "video" + dom.emitCssStyles({
  899. "display": "inline-block",
  900. "text-align": "center",
  901. "width": "3.5em"
  902. }) + "\n" +
  903. "div." + LINKS_HTML_ID + " ." + CSS_PREFIX + "quality" + dom.emitCssStyles({
  904. "display": "inline-block",
  905. "text-align": "center",
  906. "width": "5.5em"
  907. }) + "\n" +
  908. "." + CSS_PREFIX + "video" + dom.emitCssStyles({
  909. "color": "#fff !important",
  910. "padding": "1px 3px",
  911. "text-align": "center"
  912. }) + "\n" +
  913. "." + CSS_PREFIX + "quality" + dom.emitCssStyles({
  914. "color": "#000 !important",
  915. "display": "table-cell",
  916. "padding": "1px 3px",
  917. "vertical-align": "middle"
  918. }) + "\n" +
  919. "." + CSS_PREFIX + "filesize" + dom.emitCssStyles({
  920. "font-size": "90%",
  921. "margin-top": "2px",
  922. "padding": "1px 3px",
  923. "text-align": "center"
  924. }) + "\n" +
  925. "." + CSS_PREFIX + "filesize-err" + dom.emitCssStyles({
  926. "color": "#f00",
  927. "font-size": "90%",
  928. "margin-top": "2px",
  929. "padding": "1px 3px",
  930. "text-align": "center"
  931. }) + "\n" +
  932. "." + CSS_PREFIX + "not-avail" + dom.emitCssStyles({
  933. "background-color": "#700",
  934. "color": "#fff",
  935. "padding": "3px",
  936. }) + "\n" +
  937. "." + CSS_PREFIX + "3gp" + dom.emitCssStyles({
  938. "background-color": "#bbb"
  939. }) + "\n" +
  940. "." + CSS_PREFIX + "flv" + dom.emitCssStyles({
  941. "background-color": "#0dd"
  942. }) + "\n" +
  943. "." + CSS_PREFIX + "m4a" + dom.emitCssStyles({
  944. "background-color": "#07e"
  945. }) + "\n" +
  946. "." + CSS_PREFIX + "m4v" + dom.emitCssStyles({
  947. "background-color": "#07e"
  948. }) + "\n" +
  949. "." + CSS_PREFIX + "mp3" + dom.emitCssStyles({
  950. "background-color": "#7ba"
  951. }) + "\n" +
  952. "." + CSS_PREFIX + "mp4" + dom.emitCssStyles({
  953. "background-color": "#777"
  954. }) + "\n" +
  955. "." + CSS_PREFIX + "qt" + dom.emitCssStyles({
  956. "background-color": "#f08"
  957. }) + "\n" +
  958. "." + CSS_PREFIX + "webm" + dom.emitCssStyles({
  959. "background-color": "#e0e"
  960. }) + "\n" +
  961. "." + CSS_PREFIX + "wmv" + dom.emitCssStyles({
  962. "background-color": "#c75"
  963. }) + "\n" +
  964. "." + CSS_PREFIX + "small" + dom.emitCssStyles({
  965. "color": "#888 !important",
  966. }) + "\n" +
  967. "." + CSS_PREFIX + "medium" + dom.emitCssStyles({
  968. "color": "#fff !important",
  969. "background-color": "#0d0"
  970. }) + "\n" +
  971. "." + CSS_PREFIX + "large" + dom.emitCssStyles({
  972. "color": "#fff !important",
  973. "background-color": "#00d",
  974. "background-image": "linear-gradient(to right, #00d, #00a)"
  975. }) + "\n" +
  976. "." + CSS_PREFIX + "hd720" + dom.emitCssStyles({
  977. "color": "#fff !important",
  978. "background-color": "#f90",
  979. "background-image": "linear-gradient(to right, #f90, #d70)"
  980. }) + "\n" +
  981. "." + CSS_PREFIX + "hd1080" + dom.emitCssStyles({
  982. "color": "#fff !important",
  983. "background-color": "#f00",
  984. "background-image": "linear-gradient(to right, #f00, #c00)"
  985. }) + "\n" +
  986. "." + CSS_PREFIX + "highres" + dom.emitCssStyles({
  987. "color": "#fff !important",
  988. "background-color": "#c0f",
  989. "background-image": "linear-gradient(to right, #c0f, #90f)"
  990. }) + "\n" +
  991. "." + CSS_PREFIX + "pos-rel" + dom.emitCssStyles({
  992. "position": "relative"
  993. }) + "\n" +
  994. "";
  995.  
  996. function condInsertHdr(divId) {
  997. if(dom.gE(HDR_LINKS_HTML_ID))
  998. return true;
  999.  
  1000. var insertPtNode = dom.gE(divId);
  1001. if(!insertPtNode)
  1002. return false;
  1003.  
  1004. var divNode = dom.cE("div");
  1005. divNode.id = HDR_LINKS_HTML_ID;
  1006.  
  1007. insertPtNode.parentNode.insertBefore(divNode, insertPtNode);
  1008. return true;
  1009. }
  1010.  
  1011. function condInsertTooltip() {
  1012. if(dom.gE(LINKS_TP_HTML_ID))
  1013. return true;
  1014.  
  1015. var toolTipNode = dom.cE("div");
  1016. toolTipNode.id = LINKS_TP_HTML_ID;
  1017.  
  1018. dom.attr(toolTipNode, "class", LINKS_HTML_ID);
  1019. dom.attr(toolTipNode, "style", "display: none;");
  1020.  
  1021. dom.append(doc.body, toolTipNode);
  1022.  
  1023. dom.addEvent(toolTipNode, "mouseleave", function(event) {
  1024. //logMsg("mouse leave");
  1025. dom.attr(toolTipNode, "style", "display: none;");
  1026. });
  1027. }
  1028.  
  1029. function condInsertUpdateIcon() {
  1030. if(dom.gE(UPDATE_HTML_ID))
  1031. return;
  1032.  
  1033. var divNode = dom.cE("a");
  1034. divNode.id = UPDATE_HTML_ID;
  1035. dom.append(doc.body, divNode);
  1036. }
  1037.  
  1038. // -----------------------------------------------------------------------------
  1039.  
  1040. var STORE_ID = "ujsYtLinks";
  1041. var JSONP_ID = "ujsYtLinks";
  1042.  
  1043. var userConfig = {
  1044. showVideoFormats: true,
  1045. showVideoSize: true,
  1046. tagLinks: true
  1047. };
  1048.  
  1049. var videoInfoCache = {};
  1050.  
  1051. var TAG_LINK_NUM_PER_BATCH = 5;
  1052. var INI_TAG_LINK_DELAY_MS = 200;
  1053. var SUB_TAG_LINK_DELAY_MS = 500;
  1054.  
  1055. // -----------------------------------------------------------------------------
  1056.  
  1057. function Links() {
  1058. }
  1059.  
  1060. Links.prototype.init = function() {
  1061. };
  1062.  
  1063. Links.prototype.getPreferredFmt = function(map) {
  1064. var selElm = map.fmtUrlList[0];
  1065.  
  1066. forEach(map.fmtUrlList, function(idx, elm) {
  1067. if(getVideoName(elm.type).toLowerCase() != "webm") {
  1068. selElm = elm;
  1069. return false;
  1070. }
  1071. });
  1072.  
  1073. return selElm;
  1074. };
  1075.  
  1076. Links.prototype.checkFmts = function(forceFlag) {
  1077. var me = this;
  1078.  
  1079. if(!userConfig.showVideoFormats)
  1080. return;
  1081.  
  1082. if(!forceFlag && userConfig.showVideoFormats == "btn") {
  1083. if(dom.gE(VID_FMT_BTN_ID))
  1084. return;
  1085.  
  1086. var btn = dom.cE("button");
  1087. dom.attr(btn, "id", VID_FMT_BTN_ID);
  1088. dom.attr(btn, "class", "yt-uix-button yt-uix-button-default");
  1089. btn.innerHTML = "VidFmts";
  1090.  
  1091. var mastH = dom.gE("yt-masthead-signin") || dom.gE("yt-masthead-user");
  1092. if(!mastH)
  1093. return;
  1094.  
  1095. dom.prepend(mastH, btn);
  1096.  
  1097. dom.addEvent(btn, "click", function(event) {
  1098. me.checkFmts(/*force*/ true);
  1099. });
  1100.  
  1101. return;
  1102. }
  1103.  
  1104. if(!loc.href.match(/watch\?v=([a-zA-Z0-9_-]*)/))
  1105. return false;
  1106.  
  1107. var videoId = RegExp.$1;
  1108.  
  1109. var url = loc.protocol + "//" + loc.host + "/watch?v=" + videoId;
  1110.  
  1111. getVideoInfo(url, function(map) { me.showLinks("page", map); });
  1112. };
  1113.  
  1114. Links.prototype.genUrl = function(map, elm) {
  1115. var url = elm.url + "&title=" + cnvSafeFname(map.title + getExt(elm));
  1116.  
  1117. if(elm.sig != null)
  1118. url += "&signature=" + elm.sig;
  1119.  
  1120. return url;
  1121. };
  1122.  
  1123. Links.prototype.emitLinks = function(map) {
  1124. function fmtSize(size) {
  1125. var units = [ "kB", "MB", "GB" ];
  1126. var idx = 0;
  1127.  
  1128. for(idx = 0; idx < units.length; ++idx) {
  1129. size /= 1024;
  1130.  
  1131. if(size < 10)
  1132. return Math.round(size * 100) / 100 + units[idx];
  1133.  
  1134. if(size < 100)
  1135. return Math.round(size * 10) / 10 + units[idx];
  1136.  
  1137. if(size < 1024 || idx == units.length - 1)
  1138. return Math.round(size) + units[idx];
  1139. }
  1140. }
  1141.  
  1142. // Entry point
  1143. var me = this;
  1144. var s = [];
  1145.  
  1146. var resMap = {};
  1147.  
  1148. forEach(map.fmtUrlList, function(idx, elm) {
  1149. var fmtMap = map.fmtMap[elm.itag];
  1150.  
  1151. if(!resMap[fmtMap.res]) {
  1152. resMap[fmtMap.res] = [];
  1153. resMap[fmtMap.res].quality = elm.quality;
  1154. }
  1155.  
  1156. resMap[fmtMap.res].push(elm);
  1157. });
  1158.  
  1159. var hasHighRes = resMap["720p"] != null || resMap["1080p"] != null;
  1160.  
  1161. for(var res in resMap) {
  1162. if(hasHighRes && (res === "144v" || res === "240v"))
  1163. continue;
  1164.  
  1165. var qFields = [];
  1166.  
  1167. qFields.push(dom.emitHtml("div", { "class": CSS_PREFIX + "quality " + CSS_PREFIX + resMap[res].quality }, res));
  1168.  
  1169. forEach(resMap[res], function(idx, elm) {
  1170. var fields = [];
  1171. var fmtMap = map.fmtMap[elm.itag];
  1172. var videoName = getVideoName(elm.effType || elm.type);
  1173.  
  1174. var varMsg = "";
  1175.  
  1176. if(elm.bitrate != null)
  1177. varMsg = fmtSize(elm.bitrate) + "/s";
  1178. else if(fmtMap.vars != null)
  1179. varMsg = fmtMap.vars.join();
  1180.  
  1181. var addMsg = [ elm.itag, elm.type, elm.size || elm.quality, varMsg ];
  1182.  
  1183. if(elm.s != null)
  1184. addMsg.push("sig-" + elm.s.length);
  1185.  
  1186. if(elm.fileSize != null && elm.fileSize >= 0)
  1187. addMsg.push(fmtSize(elm.fileSize));
  1188.  
  1189. var vidSuffix = "";
  1190.  
  1191. if(elm.itag == 82 || elm.itag == 83 || elm.itag == 84 || elm.itag == 100 || elm.itag == 101 || elm.itag == 102)
  1192. vidSuffix = " (3D)";
  1193.  
  1194. fields.push(dom.emitHtml("div", { "class": CSS_PREFIX + "video " + CSS_PREFIX + videoName.toLowerCase() }, videoName + vidSuffix));
  1195.  
  1196. if(elm.fileSize != null) {
  1197. if(elm.fileSize >= 0) {
  1198. fields.push(dom.emitHtml("div", { "class": CSS_PREFIX + "filesize" }, fmtSize(elm.fileSize)));
  1199. }
  1200. else {
  1201. var msg;
  1202.  
  1203. if(elm.isDrm)
  1204. msg = "DRM";
  1205. else if(elm.s != null)
  1206. msg = "sig-" + elm.s.length;
  1207. else
  1208. msg = "Err";
  1209.  
  1210. fields.push(dom.emitHtml("div", { "class": CSS_PREFIX + "filesize-err" }, msg));
  1211. }
  1212. }
  1213.  
  1214. var url;
  1215.  
  1216. if(elm.isDrm)
  1217. url = elm.conn + "?" + elm.stream;
  1218. else
  1219. url = me.genUrl(map, elm);
  1220.  
  1221. var ahref = dom.emitHtml("a", {
  1222. href: url,
  1223. title: addMsg.join(" | ")
  1224. }, fields.join(""));
  1225.  
  1226. qFields.push(ahref);
  1227. });
  1228.  
  1229. s.push(dom.emitHtml("div", { "class": CSS_PREFIX + "group" }, qFields.join("")));
  1230. }
  1231.  
  1232. return s.join("");
  1233. };
  1234.  
  1235. var INI_SHOW_FILESIZE_DELAY_MS = 500;
  1236. var SUB_SHOW_FILESIZE_DELAY_MS = 200;
  1237.  
  1238. Links.prototype.showLinks = function(divId, map) {
  1239. function updateLinks() {
  1240. //!! Hack to update file size
  1241. if(condInsertHdr(divId))
  1242. dom.html(dom.gE(HDR_LINKS_HTML_ID), me.emitLinks(map));
  1243. }
  1244.  
  1245. // Entry point
  1246. var me = this;
  1247.  
  1248. // video is not avail
  1249. if(!map.fmtUrlList)
  1250. return;
  1251.  
  1252. //logMsg(JSON.stringify(map));
  1253.  
  1254. if(!condInsertHdr(divId))
  1255. return;
  1256.  
  1257. dom.html(dom.gE(HDR_LINKS_HTML_ID), me.emitLinks(map));
  1258.  
  1259. if(!userConfig.showVideoSize)
  1260. return;
  1261.  
  1262. forEach(map.fmtUrlList, function(idx, elm) {
  1263. //logMsg(elm.itag + " " + elm.url);
  1264.  
  1265. // We just fail outright for protected/obfuscated videos
  1266. if(elm.isDrm || elm.s != null) {
  1267. elm.fileSize = -1;
  1268. updateLinks();
  1269. return;
  1270. }
  1271.  
  1272. setTimeout(function() {
  1273. dom.crossAjax({
  1274. type: "HEAD",
  1275. url: me.genUrl(map, elm),
  1276.  
  1277. success: function(data, status, xhr) {
  1278. var fileSize = xhr.getResponseHeader("Content-Length");
  1279. if(fileSize == null)
  1280. return;
  1281.  
  1282. //logMsg(map.title + " " + elm.itag + ": " + fileSize);
  1283. elm.fileSize = fileSize;
  1284.  
  1285. updateLinks();
  1286. },
  1287.  
  1288. error: function(xhr, status) {
  1289. //logMsg(map.fmtMap[elm.itag].res + " " + getVideoName(elm.type) + ": " + xhr.status);
  1290.  
  1291. if(xhr.status != 403)
  1292. return;
  1293.  
  1294. elm.fileSize = -1;
  1295.  
  1296. updateLinks();
  1297. },
  1298.  
  1299. complete: function(xhr) {
  1300. //logMsg(map.title + ": " + xhr.getAllResponseHeaders());
  1301. }
  1302. });
  1303. }, INI_SHOW_FILESIZE_DELAY_MS + idx * SUB_SHOW_FILESIZE_DELAY_MS);
  1304. });
  1305. };
  1306.  
  1307. Links.prototype.tagLinks = function() {
  1308. var SCANNED = 1;
  1309. var REQ_INFO = 2;
  1310. var ADDED_INFO = 3;
  1311.  
  1312. function prepareTagHtml(node, map) {
  1313. var elm = me.getPreferredFmt(map);
  1314. var fmtMap = map.fmtMap[elm.itag];
  1315.  
  1316. dom.attr(node, "class", LINKS_HTML_ID + " " + CSS_PREFIX + "quality " + CSS_PREFIX + elm.quality);
  1317.  
  1318. dom.addEvent(node, "mouseenter", function(event) {
  1319. //logMsg("mouse enter " + map.videoId);
  1320. var pos = dom.offset(node);
  1321. //logMsg("mouse enter: x " + pos.left + ", y " + pos.top);
  1322.  
  1323. var toolTipNode = dom.gE(LINKS_TP_HTML_ID);
  1324.  
  1325. dom.attr(toolTipNode, "style", "position: absolute; left: " + pos.left + "px; top: " + pos.top + "px");
  1326.  
  1327. dom.html(toolTipNode, me.emitLinks(map));
  1328. });
  1329.  
  1330. node.href = elm.url + "&title=" + cnvSafeFname(map.title + getExt(elm));
  1331.  
  1332. return fmtMap.res;
  1333. }
  1334.  
  1335. function addTag(hNode, map) {
  1336. //logMsg(dom.html(hNode));
  1337. //logMsg("hNode " + dom.attr(hNode, "class"));
  1338. //var img = dom.gT(hNode, "img") [0];
  1339. //logMsg(dom.attr(img, "src"));
  1340. //logMsg(dom.attr(img, "class"));
  1341.  
  1342. dom.attr(hNode, CSS_PREFIX + "processed", ADDED_INFO);
  1343.  
  1344. var node = dom.cE("div");
  1345.  
  1346. if(map.fmtUrlList) {
  1347. tagHtml = prepareTagHtml(node, map);
  1348. }
  1349. else {
  1350. dom.attr(node, "class", LINKS_HTML_ID + " " + CSS_PREFIX + "not-avail");
  1351. tagHtml = "NA";
  1352. }
  1353.  
  1354. var parentNode = hNode.parentNode;
  1355. var parentCssPositionStyle = window.getComputedStyle(parentNode, null).getPropertyValue("position");
  1356.  
  1357. if(parentCssPositionStyle != "absolute" && parentCssPositionStyle != "relative")
  1358. dom.attr(parentNode, "class", dom.attr(parentNode, "class") + " " + CSS_PREFIX + "pos-rel");
  1359.  
  1360. hNode.parentNode.insertBefore(node, hNode);
  1361.  
  1362. dom.html(node, tagHtml);
  1363. }
  1364.  
  1365. function getFmt(videoId, hNode) {
  1366. if(videoInfoCache[videoId]) {
  1367. addTag(hNode, videoInfoCache[videoId]);
  1368. return;
  1369. }
  1370.  
  1371. var url;
  1372.  
  1373. if(videoId.match(/.+==$/))
  1374. url = loc.protocol + "//" + loc.host + "/cthru?key=" + videoId;
  1375. else
  1376. url = loc.protocol + "//" + loc.host + "/watch?v=" + videoId;
  1377.  
  1378. getVideoInfo(url, function(map) {
  1379. videoInfoCache[videoId] = map;
  1380. addTag(hNode, map);
  1381. });
  1382. }
  1383.  
  1384. // Entry point
  1385. var me = this;
  1386.  
  1387. var list = [];
  1388.  
  1389. forEach(dom.gT("a"), function(idx, hNode) {
  1390. if(dom.attr(hNode, CSS_PREFIX + "processed"))
  1391. return;
  1392.  
  1393. if(!dom.inViewport(hNode))
  1394. return;
  1395.  
  1396. dom.attr(hNode, CSS_PREFIX + "processed", SCANNED);
  1397.  
  1398. if(!hNode.href.match(/watch\?v=([a-zA-Z0-9_-]*)/) &&
  1399. !hNode.href.match(/watch_videos.+?&video_ids=([a-zA-Z0-9_-]*)/))
  1400. return;
  1401.  
  1402. var videoId = RegExp.$1;
  1403.  
  1404. var cls = dom.attr(hNode, "class") || "";
  1405. if(cls == "yt-button" || cls.match(/yt-uix-button/))
  1406. return;
  1407.  
  1408. if(dom.attr(hNode.parentNode, "class") == "video-time")
  1409. return;
  1410.  
  1411. if(dom.html(hNode).match(/video-logo/i))
  1412. return;
  1413.  
  1414. var img = dom.gT(hNode, "img");
  1415. if(img == null || img.length == 0)
  1416. return;
  1417.  
  1418. img = img[0];
  1419.  
  1420. var imgSrc = dom.attr(img, "src") || "";
  1421. if(imgSrc.indexOf("ytimg.com") < 0)
  1422. return;
  1423.  
  1424. var tnSrc = dom.attr(img, "thumb") || "";
  1425.  
  1426. if(imgSrc.match(/.+?\/([a-zA-Z0-9_-]*)\/default\.jpg$/))
  1427. videoId = RegExp.$1;
  1428. else if(tnSrc.match(/.+?\/([a-zA-Z0-9_-]*)\/default\.jpg$/))
  1429. videoId = RegExp.$1;
  1430.  
  1431. //logMsg(idx + " " + hNode.href);
  1432. //logMsg("videoId: " + videoId);
  1433.  
  1434. list.push({ videoId: videoId, hNode: hNode });
  1435.  
  1436. dom.attr(hNode, CSS_PREFIX + "processed", REQ_INFO);
  1437. });
  1438.  
  1439. forLoop({ num: list.length, inc: TAG_LINK_NUM_PER_BATCH, batchIdx: 0 }, function(idx) {
  1440. var batchIdx = this.batchIdx++;
  1441. var batchList = list.slice(idx, idx + TAG_LINK_NUM_PER_BATCH);
  1442.  
  1443. setTimeout(function() {
  1444. forEach(batchList, function(idx, elm) {
  1445. //logMsg(batchIdx + " " + idx + " " + elm.hNode.href);
  1446. getFmt(elm.videoId, elm.hNode);
  1447. });
  1448. }, INI_TAG_LINK_DELAY_MS + batchIdx * SUB_TAG_LINK_DELAY_MS);
  1449. });
  1450. };
  1451.  
  1452. Links.prototype.periodicTagLinks = function(delayMs) {
  1453. function poll() {
  1454. me.tagLinks();
  1455. me.tagLinksTimerId = setTimeout(poll, 3000);
  1456. }
  1457.  
  1458. // Entry point
  1459. if(!userConfig.tagLinks)
  1460. return;
  1461.  
  1462. var me = this;
  1463.  
  1464. delayMs = delayMs || 0;
  1465.  
  1466. if(me.tagLinksTimerId != null) {
  1467. clearTimeout(me.tagLinksTimerId);
  1468. delete me.tagLinksTimerId;
  1469. }
  1470.  
  1471. setTimeout(poll, delayMs);
  1472. };
  1473.  
  1474. // -----------------------------------------------------------------------------
  1475.  
  1476. Links.prototype.loadSettings = function() {
  1477. var obj = localStorage[STORE_ID];
  1478. if(obj == null)
  1479. return;
  1480.  
  1481. obj = JSON.parse(obj);
  1482.  
  1483. this.lastChkReqTs = +obj.lastChkReqTs;
  1484. this.lastChkTs = +obj.lastChkTs;
  1485. this.lastChkVer = +obj.lastChkVer;
  1486. };
  1487.  
  1488. Links.prototype.storeSettings = function() {
  1489. localStorage[STORE_ID] = JSON.stringify({
  1490. lastChkReqTs: this.lastChkReqTs,
  1491. lastChkTs: this.lastChkTs,
  1492. lastChkVer: this.lastChkVer
  1493. });
  1494. };
  1495.  
  1496. // -----------------------------------------------------------------------------
  1497.  
  1498. var UPDATE_CHK_INTERVAL = 5 * 86400;
  1499. var FAIL_TO_CHK_UPDATE_INTERVAL = 14 * 86400;
  1500.  
  1501. Links.prototype.chkVer = function(forceFlag) {
  1502. if(this.lastChkVer > relInfo.ver) {
  1503. this.showNewVer({ ver: this.lastChkVer });
  1504. return;
  1505. }
  1506.  
  1507. var now = timeNowInSec();
  1508.  
  1509. //logMsg("lastChkReqTs " + this.lastChkReqTs + ", diff " + (now - this.lastChkReqTs));
  1510. //logMsg("lastChkTs " + this.lastChkTs);
  1511. //logMsg("lastChkVer " + this.lastChkVer);
  1512.  
  1513. if(this.lastChkReqTs == null || now < this.lastChkReqTs) {
  1514. this.lastChkReqTs = now;
  1515. this.storeSettings();
  1516. return;
  1517. }
  1518.  
  1519. if(now - this.lastChkReqTs < UPDATE_CHK_INTERVAL)
  1520. return;
  1521.  
  1522. if(this.lastChkReqTs - this.lastChkTs > FAIL_TO_CHK_UPDATE_INTERVAL)
  1523. logMsg("Failed to check ver for " + ((this.lastChkReqTs - this.lastChkTs) / 86400) + " days");
  1524.  
  1525. this.lastChkReqTs = now;
  1526. this.storeSettings();
  1527.  
  1528. unsafeWin[JSONP_ID] = this;
  1529.  
  1530. var script = dom.cE("script");
  1531. script.type = "text/javascript";
  1532. script.src = SCRIPT_UPDATE_LINK;
  1533. dom.append(doc.body, script);
  1534. };
  1535.  
  1536. Links.prototype.chkVerCallback = function(data) {
  1537. delete unsafeWin[JSONP_ID];
  1538.  
  1539. this.lastChkTs = timeNowInSec();
  1540. this.storeSettings();
  1541.  
  1542. //logMsg(JSON.stringify(data));
  1543.  
  1544. var latestElm = data[0];
  1545.  
  1546. if(latestElm.ver <= relInfo.ver)
  1547. return;
  1548.  
  1549. this.showNewVer(latestElm);
  1550. };
  1551.  
  1552. Links.prototype.showNewVer = function(latestElm) {
  1553. function getVerStr(ver) {
  1554. var verStr = "" + ver;
  1555.  
  1556. var majorV = verStr.substr(0, verStr.length - 4) || "0";
  1557. var minorV = verStr.substr(verStr.length - 4, 2);
  1558. return majorV + "." + minorV;
  1559. }
  1560.  
  1561. // Entry point
  1562. this.lastChkVer = latestElm.ver;
  1563. this.storeSettings();
  1564.  
  1565. condInsertUpdateIcon();
  1566.  
  1567. var aNode = dom.gE(UPDATE_HTML_ID);
  1568.  
  1569. aNode.href = SCRIPT_LINK;
  1570.  
  1571. if(latestElm.desc != null)
  1572. dom.attr(aNode, "title", latestElm.desc);
  1573.  
  1574. dom.html(aNode, dom.emitHtml("b", SCRIPT_NAME + " " + getVerStr(relInfo.ver)) +
  1575. "<br>Click to update to " + getVerStr(latestElm.ver));
  1576. };
  1577.  
  1578. // -----------------------------------------------------------------------------
  1579.  
  1580. var inst = new Links();
  1581.  
  1582. inst.init();
  1583. inst.loadSettings();
  1584. decryptSig.load();
  1585.  
  1586. dom.insertCss(CSS_STYLES);
  1587.  
  1588. condInsertTooltip();
  1589.  
  1590. if(loc.pathname.match(/\/watch/)) {
  1591. inst.checkFmts();
  1592. }
  1593.  
  1594. inst.periodicTagLinks();
  1595.  
  1596. var scrollTop = win.pageYOffset || doc.documentElement.scrollTop;
  1597.  
  1598. dom.addEvent(win, "scroll", function(e) {
  1599. var newScrollTop = win.pageYOffset || doc.documentElement.scrollTop;
  1600.  
  1601. if(Math.abs(newScrollTop - scrollTop) < 100)
  1602. return;
  1603.  
  1604. //logMsg("scroll by " + (newScrollTop - scrollTop));
  1605.  
  1606. scrollTop = newScrollTop;
  1607.  
  1608. inst.periodicTagLinks(200);
  1609. });
  1610.  
  1611. inst.chkVer();
  1612.  
  1613. // -----------------------------------------------------------------------------
  1614.  
  1615. /* YouTube reuses the current page when the user clicks on a new video. We need
  1616. to detect it and reload the formats. */
  1617.  
  1618. (function() {
  1619.  
  1620. var PERIODIC_CHK_VIDEO_URL_MS = 1000;
  1621.  
  1622. var curVideoUrl = loc.toString();
  1623.  
  1624. function periodicChkVideoUrl() {
  1625. var newVideoUrl = loc.toString();
  1626.  
  1627. if(curVideoUrl != newVideoUrl) {
  1628. //console.log(curVideoUrl + " -> " + newVideoUrl);
  1629.  
  1630. curVideoUrl = newVideoUrl;
  1631.  
  1632. if(loc.pathname.match(/\/watch/))
  1633. inst.checkFmts();
  1634. }
  1635.  
  1636. setTimeout(periodicChkVideoUrl, PERIODIC_CHK_VIDEO_URL_MS);
  1637. }
  1638.  
  1639. periodicChkVideoUrl();
  1640.  
  1641. }) ();
  1642.  
  1643. // -----------------------------------------------------------------------------
  1644.  
  1645. }) ();