BTDigg_Chart_Adder

adds BTDigg popularity chart for Bit-torrent magnet-links

目前为 2014-09-12 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name BTDigg_Chart_Adder
  3. // @namespace BTDigg_Chart_Adder
  4. // @id BTDigg_Chart_Adder
  5. // @description adds BTDigg popularity chart for Bit-torrent magnet-links
  6. // @version 0.2.4
  7. // @author KOLANICH
  8. // @copyright KOLANICH, 2014
  9. // @homepageURL https://github.com/KOLANICH/BTDigg_Chart_Adder/
  10. // @icon https://btdigg.org/favicon.ico
  11. // @license GNU GPL v3
  12. // @screenshot ./images/screenshots/tpb.png ./images/screenshots/btdigg.png ./images/screenshots/nnm-club.ru.png ./images/screenshots/kickasstorrents.com.png ./images/screenshots/extratorrent.com.png
  13. // @contributionURL https://github.com/KOLANICH/BTDigg_Chart_Adder/fork
  14. // @contributionAmount feel free to fork and contribute
  15.  
  16. // @include *
  17. // @exclude /https?\:\/\/btdigg\.org.+/i
  18. // @noframes 1
  19. // @run-at document-idle
  20. // @optimize 1
  21.  
  22. // @resource flotr2lib https://raw.github.com/HumbleSoftware/Flotr2/master/flotr2.min.js
  23. // @resource tooltipcss ./tooltip.css
  24. // @resource preloader ./images/preloader.png
  25. // @btdiggBaseURL http://api.btdigg.org/api/public-8e9a50f8335b964f
  26. // @tooltipWidth 600
  27. // @tooltipHeight 200
  28. // @installationReportIteration 1
  29. // @scriptId 4706
  30. // ==/UserScript==
  31.  
  32. /*
  33. Preloader by http://preloaders.net/
  34. Tooltip by http://cssarrowplease.com/
  35. This script is distributed under conditions of GNU GPL v3.
  36. */
  37.  
  38. /*
  39. Copyright (C) 2013-2014 KOLANICH
  40. This program is free software: you can redistribute it and/or modify
  41. it under the terms of the GNU General Public License as published by
  42. the Free Software Foundation, either version 3 of the License, or
  43. (at your option) any later version.
  44. This program is distributed in the hope that it will be useful,
  45. but WITHOUT ANY WARRANTY; without even the implied warranty of
  46. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  47. GNU General Public License for more details.
  48. You should have received a copy of the GNU General Public License
  49. along with this program. If not, see <http://www.gnu.org/licenses/>.
  50. */
  51.  
  52. var btdiggApiBaseURL=GM_getMetadata("btdiggbaseurl")[0];
  53. var tooltipWidth=GM_getMetadata("tooltipwidth")[0];
  54. var tooltipHeight=GM_getMetadata("tooltipheight")[0];
  55. var preloader=new Image();
  56. preloader.src=GM_getResourceURL("preloader");
  57. var arrowHeight=40;
  58. var parseURIRx=/(\w+)=([^&]+)/ig;
  59. var infohashRx=/[A-F0-9]{40}|[A-Z2-7]{32}/i;
  60.  
  61. var site=null;
  62. var currentLink=null;
  63.  
  64. var BTDiggReportingEnabled=GM_getValue("enableBTDiggReporting",-1);
  65.  
  66. if(BTDiggReportingEnabled==-1){
  67. alert("Usage of this userscript may be very dangerous. Using this you will allow BTDigg site to gather information about magnet links YOU see. This destroys our privacy. We know nothing about BTDigg true intentions, they may be working for copyrust.\nAnother risk is that BTDigg have ssl certificate only for www.btdigg.com and btdigg.com, but noot for api.btdigg.com, so we have to USE UNENCRYPTED PROTOCOL, WHICH MAKES ANYONE WHO CANE EAVESDROP YOUR INTERNET CONNECTION, INCLUDING GOVERNMENT AGENCIES, KNOW WHAT LINKS DO YOU REQUEST STATISTICS FOR");
  68. alert("Remember:\nYOU DO THIS AT YOUR OWN RISK!!!\n THE AUTHOR(S) IS (ARE) NOT LIABLE FOR ANY DAMAGE OF ANY KIND OR LAW VIOLATION!!!");
  69. alert("Look BTDigg privacy policy...");
  70. GM_openInTab("https://btdigg.org/about/privacypolicy.html");
  71. alert("... and Terms of Service");
  72. GM_openInTab("https://btdigg.org/about/termsofservice.html");
  73. enableBTDiggReporting();
  74. }
  75. reportInstallationIfNeeded();
  76.  
  77. function GM_xhrPr(obj){
  78. return function(resolve, reject) {
  79. obj.onload=resolve;
  80. obj.onerror=reject;
  81. GM_xmlhttpRequest(obj);
  82. };
  83. }
  84.  
  85. function reportInstallationIfNeeded(){
  86. const instReptItKey="installationReportIteration";
  87. var instReptIt=GM_getMetadata(instReptItKey.toLowerCase())[0];
  88. if(GM_getValue(instReptItKey,0)<instReptIt){
  89. const scriptId=GM_getMetadata("scriptid")[0];
  90. const greaseForkScripts="https://greasyfork.org/scripts/";
  91. let token="";
  92. let pr=new Promise(GM_xhrPr({url:greaseForkScripts+scriptId, method:"GET", ignoreCache:true}))
  93. .then((xhr)=>findCSRFToken(xhr.responseText))
  94. .then((token)=>{
  95. new Promise(GM_xhrPr({
  96. url:"https://greasyfork.org/script_sets/add_to_set",method:"POST",
  97. ignoreCache:true,
  98. data:"utf8=%E2%9C%93&authenticity_token="+encodeURIComponent(token)+"&action-set=ai-336&script_id="+scriptId,
  99. headers:{"Content-Type":"application/x-www-form-urlencoded"}
  100. }))
  101. .then((xhr)=>findCSRFToken(xhr.responseText))
  102. .then((token)=>{
  103. new Promise(GM_xhrPr({
  104. url:greaseForkScripts+scriptId+"/install-ping?authenticity_token="+token,
  105. method:"POST", ignoreCache:true
  106. }))
  107. .then((xhr)=>GM_setValue(instReptItKey,instReptIt));
  108. });
  109. });
  110. }
  111. }
  112.  
  113. function findCSRFToken(source){
  114. const tokenFieldRx=/<meta[^<>]*name=(['"])csrf-token\1[^<>]*\/>/i
  115. const valueRx=/content=(["'])([A-Z0-9+=]*)\1/i;
  116. let m=source.match(tokenFieldRx);
  117. if(m[0]){
  118. m=m[0].match(valueRx);
  119. if(m[2])return m[2];
  120. }
  121. return false;
  122. }
  123.  
  124.  
  125. function enableBTDiggReporting(){
  126. if(
  127. confirm("Would you like to send BTDigg info about all magnet links clicked by you? I don't recommend you to do this, because any collected information may be used against you in a court of (sword) law. Make sure you wouldn't download anything illegal or copyrighted when you enabled this!!! This feature was implemented because I could implement it and I hope it will help BTDigg to index maget links.")
  128. &&
  129. prompt("YOU DO THIS AT YOUR OWN RISK!!!\n THE AUTHOR(S) IS (ARE) NOT LIABLE FOR ANY DAMAGE OF ANY KIND OR LAW VIOLATION!!!\n Now you were warned.\nA you really sure?\nType \"I am warned and accept.\" if you really want to enable this feature.")=="I am warned and accept."
  130. ){
  131. GM_setValue("enableBTDiggReporting",1);
  132. alert("BTDigg is now \"spying\" on you\nYou can disable it via script menu.");
  133. window.location.reload();
  134. return;
  135. }
  136. else{
  137. alert("Wise decision");
  138. };
  139. GM_setValue("enableBTDiggReporting",0);
  140. }
  141.  
  142. if(BTDiggReportingEnabled==1){
  143. GM_registerMenuCommand("BTDigg: disable reporting",function(){
  144. BTDiggReportingEnabled=0;
  145. GM_setValue("enableBTDiggReporting",BTDiggReportingEnabled);
  146. alert("Espionage stopped!!!");
  147. window.location.reload();
  148. });
  149. }
  150.  
  151.  
  152. function checkPlottingLibrary(){
  153. if(window.Flotr === undefined){
  154. eval(GM_getResourceText("flotr2lib"));
  155. }
  156. }
  157. var cssInjected=false;
  158. function checkCssStyle(){
  159. if(!cssInjected)GM_addStyle(GM_getResourceText("tooltipcss"));
  160. }
  161.  
  162. /*!
  163. @param btdescriptor
  164. {
  165. link: объект ссылки,
  166. infohash:инфохеш,
  167. ещё что-либо
  168. }
  169. */
  170. function BTDescriptor(uri){
  171. if(uri)this.parseMagnetURI(uri);
  172. console.log(this);
  173. };
  174. BTDescriptor.prototype.parseMagnetURI=function(uri){
  175. parseURIRx.lastIndex=0;
  176. var arr=uri.match(parseURIRx);
  177. for(var i=0;i<arr.length;i++){
  178. var el=arr[i].split('=');
  179. //console.log(el);
  180. this[el[0]]=decodeURIComponent(el[1].replace(/\+/g," "));
  181. }
  182. //console.log(this);
  183. if(this.xt){
  184. var infohash=this.xt.match(infohashRx)[0];
  185. if(infohash)this.infohash=infohash;
  186. }
  187. };
  188. BTDescriptor.parseMagnetURI=function(uri){
  189. var d=new BTDescriptor();
  190. d.parseMagnetURI(uri);
  191. return d;
  192. };
  193.  
  194. function getMagnetLinksFromPage(){
  195. return Array.prototype.filter.call(document.querySelectorAll("a[href]"),function(lnk){return lnk.protocol=="magnet:";});
  196. }
  197.  
  198. var isLoading=0;
  199.  
  200.  
  201. function requestTorrentPopularityByLink(btdescriptor){
  202. return new Promise(GM_xhrPr({
  203. method:"GET",
  204. url:btdiggApiBaseURL+"/h02?info_hash="+btdescriptor.infohash,
  205. })).then(addPlotToPage.bind(btdescriptor),showError);
  206. }
  207.  
  208. var tooltip=null;
  209.  
  210. var plotArea;
  211. function checkTooltip(){
  212. if(!tooltip){
  213. tooltip=document.createElement("div");
  214. tooltip.style.zIndex="2147483647";
  215. tooltip.style.position="absolute";
  216. checkCssStyle();
  217. tooltip.className="BTDigg_Chart_Adder_tooltip";
  218. plotArea=document.createElement("div");
  219. plotArea.style.width=tooltipWidth+"px";
  220. plotArea.style.height=tooltipHeight+"px";
  221. document.body.appendChild(tooltip);
  222. tooltip.appendChild(preloader);
  223. tooltip.appendChild(plotArea);
  224. }
  225. }
  226.  
  227. var tooltipCurrentWidth;
  228.  
  229. /*!
  230. @param link DOMNode to where tooltip should be placed
  231. */
  232. function placeTooltip(link,offsets){
  233. console.log(link);
  234. var linkRect=link.getBoundingClientRect();
  235. console.log(linkRect);
  236. tooltip.style.display="";
  237. tooltip.style.top=(linkRect.top+arrowHeight+window.pageYOffset)+"px";
  238. tooltip.style.left=(linkRect.left-tooltipCurrentWidth/2+linkRect.width/2+window.pageXOffset)+"px";
  239. return tooltip;
  240. }
  241.  
  242. function tsvToArray(txt){
  243. var arr=txt.split("\n").map(function(el){return el.split("\t").map(function(el){return parseInt(el)});});
  244. if(Number.isNaN(arr[arr.length-1][0]))arr.splice(arr.length-1,1);
  245. return arr;
  246. }
  247.  
  248. function cloneSize(target,donor){
  249. target.style.width=donor.style.width;
  250. target.style.height=donor.style.height;
  251. };
  252.  
  253. function addPlotToPage(evt){
  254. isLoading=0;//!< 0 is not loading now, 1 is loading now
  255. //console.log("link descriptor is",this);
  256. //console.log("got text",evt.responseText);
  257. currentLink=this.link;
  258. if(!evt.responseText){
  259. hideTooltip();
  260. GM_notification("Info is not available for this torrent");
  261. return;
  262. }
  263. var arr=tsvToArray(evt.responseText);
  264. console.log("splitted",arr);
  265. checkPlottingLibrary();
  266. placeTooltip(currentLink);
  267. //
  268. var flotrConfig={
  269. xaxis: {
  270. mode: 'time',
  271. timeUnit:"second",
  272. timeMode:'local',
  273. labelsAngle: 45,
  274. showMinorLabels: true,
  275. },
  276. selection: {
  277. mode: 'x'
  278. },
  279. grid: {
  280. minorVerticalLines: true,
  281. },
  282. points: {
  283. show: true,
  284. },
  285. lines: {
  286. show: true,
  287. },
  288. HtmlText: false,
  289. };
  290. if(this.dn)flotrConfig.title=this.dn;
  291. if(this.xl)flotrConfig.subtitle=this.xl+" Bytes";
  292. tooltip.style.width=tooltipWidth+"px";
  293. tooltip.style.height=tooltipHeight+"px";
  294. tooltipCurrentWidth=tooltipWidth;
  295. preloader.style.display="none";
  296. plotArea.style.display="";
  297. console.log(flotrConfig);
  298. Flotr.draw(plotArea, [arr], flotrConfig);
  299. placeTooltip(currentLink);
  300. }
  301.  
  302. function showError(evt){
  303. console.error(evt.statusText);
  304. }
  305.  
  306. function hideTooltip(){
  307. currentLink=null;
  308. if(!isLoading)tooltip.style.display="none";
  309. }
  310.  
  311. function showTooltipForLink(evt){
  312. if(!isLoading){
  313. checkTooltip();
  314. tooltip.style.width=preloader.width+"px";
  315. tooltip.style.height=preloader.height+"px";
  316. tooltipCurrentWidth=preloader.width;
  317. placeTooltip(evt.target);
  318. plotArea.style.display="none";
  319. preloader.style.display="";
  320. isLoading=1;
  321. requestTorrentPopularityByLink(evt.target.magnet);
  322. }
  323. }
  324.  
  325.  
  326. /*!
  327. gets some strange info in format
  328.  
  329. # TSL numbers divided by tab
  330. # NORM numbers divided by tab
  331.  
  332. every number from top line corresponds number from low line
  333. */
  334. function getSomethingStrange(btdescriptor){
  335. var data = new FormData();
  336. data.append("info_hash", btdescriptor.infohash);
  337. GM_xmlhttpRequest({
  338. method:"POST",
  339. url:btdiggApiBaseURL+"/h01",
  340. onload:console.log,
  341. onerror:console.warn,
  342. data:data
  343. });
  344. }
  345.  
  346. /*!
  347. this function is needed to send clicked magnet links to btdigg
  348. or to send info about clicked banners
  349. maybe this will help them to collect magnet links to track their torrents' popularity
  350. in any case enabling this must be voluntarily
  351. */
  352. function sendClick(href,banner){
  353. var data = new FormData();
  354. if(banner){
  355. data.append("banner", href);
  356. }else{
  357. data.append("magnet", href);
  358. }
  359. console.log("sending click on",link,"...");
  360. GM_xmlhttpRequest({
  361. method:"POST",
  362. url:"https://btdigg.org/click",
  363. onload:console.info,
  364. onerror:console.warn,
  365. data:data
  366. });
  367. }
  368.  
  369. function processClick(evt){
  370. try{
  371. GM_notification("Info about the click was sent!","BTDigg");
  372. }catch(e){}
  373. sendClick(evt.source.href);
  374. }
  375.  
  376. /*function processScroll(evt){
  377. console.log(evt);
  378. if(currentLink)placeTooltip(currentLink,{x:evt.mozMovementX,y:evt.mozMovementY});
  379. }*/
  380.  
  381. function main(){
  382. var links=getMagnetLinksFromPage();
  383. for(var i=0;i<links.length;i++){
  384. links[i].magnet=new BTDescriptor(links[i].href);
  385. if(links[i].magnet.infohash){
  386. links[i].magnet.link=links[i];
  387. links[i].addEventListener("mouseenter",showTooltipForLink,false);
  388. links[i].addEventListener("mouseleave",hideTooltip,false);
  389. if(BTDiggReportingEnabled)links[i].addEventListener("click",processClick,true);
  390. }
  391. }
  392. //document.body.addEventListener("DOMMouseScroll",processScroll,true);
  393. }
  394. main();