Advertisement
junh1024

APR CBH

Feb 5th, 2017
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name        APOLLO :: Collage Building Helper
  3. // @author      Z4ppy
  4. // @namespace   Z4ppy.What.CD
  5. // @description Make it easier to build your collage.
  6. // @include     https://*apollo.rip/torrents.php*
  7. // @include     https://*apollo.rip/collages.php*
  8. // @include     https://*apollo.rip/collage.php*
  9. // @include     https://*apollo.rip/artist.php*
  10. // @include     https://*apollo.rip/bookmarks.php*
  11. // @grant       GM_setValue
  12. // @grant       GM_getValue
  13. // @grant       GM_deleteValue
  14. // @grant       GM_registerMenuCommand
  15. // @grant       GM_xmlhttpRequest
  16. // @version     1.0.1
  17. // @date        2013-03-05
  18. // ==/UserScript==
  19.  
  20. var collageID, collName;
  21. // Momenticons: http://findicons.com/icon/263495/folder_open_add
  22. var ICON_ADD = 'http://i.imgur.com/snd3Doj.png=';
  23. // Yusuke Kamiyamane: http://findicons.com/icon/118036/cross
  24. var ICON_ERR = 'http://i.imgur.com/djo7YFS.png=';
  25. // Yusuke Kamiyamane: http://findicons.com/icon/119015/tick
  26. var ICON_OK = 'http://i.imgur.com/jCdKolj.png';
  27. // ajaxload.info
  28. var ICON_LOADING = 'data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==';
  29.  
  30. var torrentCache = {
  31.     Cache: [],
  32.     GM_read: function () {
  33.         this.clear();
  34.         this.Cache = JSON.parse(GM_getValue('torrentCache', '[]'));
  35.         return this.Cache.length;
  36.     },
  37.     GM_save: function () {
  38.         return GM_setValue('torrentCache', JSON.stringify(this.Cache));
  39.     },
  40.     GM_delete: function () {
  41.         GM_deleteValue('torrentCache');
  42.     },
  43.     add: function (torrentgroupid) {
  44.         if (this.Cache.indexOf(torrentgroupid) != -1) {
  45.             return false;
  46.         }
  47.         this.Cache.push(torrentgroupid);
  48.         return true;
  49.     },
  50.     contains: function (torrentgroupid) {
  51.         return (this.Cache.indexOf(torrentgroupid) != -1);
  52.     },
  53.     remove: function (torrentgroupid) {
  54.         if (this.Cache.indexOf(torrentgroupid) == -1) {
  55.             return false;
  56.         }
  57.         this.Cache.splice(this.Cache.indexOf(torrentgroupid), 1);
  58.         return true;
  59.     },
  60.     clear: function () {
  61.         this.Cache.length = 0;
  62.     }
  63. }
  64.  
  65. var URL = new Object();
  66. function parseURL() {
  67.     var URLArr = document.URL.match(/^(https:\/\/(?:ssl\.)?apollo\.rip)\/([\w\/\.]+?)(\?(.*?))?(#.*)?$/);
  68.     URL.Host = URLArr[1]; //protocol + hostname, eg. https://apollo.rip
  69.     URL.Path = URLArr[2];
  70.     URL.Hash = URLArr[5];
  71.     URL.Parameters = new Object();
  72.     if (typeof URLArr[4] != 'undefined') {
  73.         var URLPArr = URLArr[4].split('&'); //URL parameter array
  74.         var tmpP; //temporary Parameter
  75.         for (var i = 0; i < URLPArr.length; ++i) {
  76.             tmpP = URLPArr[i].split('=');
  77.             URL.Parameters[tmpP[0]] = tmpP[1];
  78.         }
  79.     }
  80. }
  81.  
  82. function init() {
  83.     parseURL();
  84.  
  85.     getCollageID();
  86.  
  87.     torrentCache.GM_read();
  88.  
  89.     // putting the add image on various pages (with an active collage)
  90.     // $.inArray(URL.Path, ['torrents.php', 'artist.php'])
  91.     if ((URL.Path == 'torrents.php' || URL.Path == 'artist.php' || URL.Path == 'bookmarks.php' || URL.Path == 'collages.php') && (collageID != 0)) {
  92.         if (URL.Path == 'torrents.php' && URL.Parameters['id']) {
  93.             //torrent group page
  94.             var title = document.getElementById('content').getElementsByTagName('h2')[0];
  95.             title.insertBefore(document.createTextNode(' '), null);
  96.             title.insertBefore(createAddIcon(URL.Host + '/torrents.php?id=' + URL.Parameters['id'], URL.Parameters['id']), null);
  97.         } else {
  98.             var tableId = '';
  99.             if (URL.Path == 'torrents.php' && (URL.Parameters['type'] || URL.Parameters['action'] == 'notify')) {
  100.                 // user uploaded/snatched/etc and notifications
  101.                 tableId = 'content';
  102.             } else if (URL.Path == 'artist.php' || (URL.Path == 'collages.php' && URL.Parameters['id'] && URL.Parameters['id'] != collageID)) {
  103.                 // artist page; other collages
  104.                 tableId = 'discog_table';
  105.             } else if (URL.Path == 'torrents.php' || URL.Path == 'bookmarks.php') {
  106.                 // search page; bookmarks
  107.                 tableId = 'torrent_table';
  108.             }
  109.  
  110.             if (tableId != '') {
  111.                 var linkArr = extractTorrentgroupLinks(tableId);
  112.                 for (var i = 0; i < linkArr.length; ++i) {
  113.                     linkArr[i].parentNode.insertBefore(document.createTextNode(' '), linkArr[i].parentNode.firstChild);
  114.                     linkArr[i].parentNode.insertBefore(createAddIcon(linkArr[i].href, linkArr[i].getAttribute('torrentgroupid')), linkArr[i].parentNode.firstChild);
  115.                 }
  116.             }
  117.         }
  118.     }
  119.    
  120.     if (URL.Path == 'collages.php' && URL.Parameters['id'] && !URL.Parameters['action']) {
  121.         var currentCollURL = URL.Parameters['id'];
  122.  
  123.         var cx = document.getElementsByTagName('h2')[0];
  124.  
  125.         if (collageID != 0 && collageID != currentCollURL) {
  126.             // if there is an active collage & the active collage is different than current page, use name + link
  127.             cx.parentNode.innerHTML = "\<h3\>The active collage is: \<a href\=\"" + URL.Host + "\/collages.php\?id\=" + collageID + "\"\>" + collName + "\<\/a\>" + cx.parentNode.innerHTML;
  128.         } else {
  129.             // else just display name
  130.             cx.parentNode.innerHTML = "\<h3\>The active collage is: " + collName + cx.parentNode.innerHTML;
  131.         }
  132.  
  133.         var jx = document.getElementsByTagName('h2')[0];
  134.  
  135.         // display "Make This Active Collage!"
  136.         if (currentCollURL != collageID) {
  137.             //standard collage pages
  138.             var collageLink = document.createElement('a');
  139.             collageLink.href = '#';
  140.             collageLink.textContent = 'Make this the active collage';
  141.             collageLink.setAttribute('collage-id', currentCollURL);
  142.             collageLink.setAttribute('collage-name', jx.innerHTML);
  143.             collageLink.className = 'brackets';
  144.             collageLink.id = 'thelink';
  145.             collageLink.addEventListener('click', function(e) { setCollageID(e.target); return false; }, false);
  146.             jx.parentNode.insertBefore(collageLink, jx);
  147.         }
  148.  
  149.         // display "Remove Active Collage"
  150.         if (collageID != 0) {
  151.             var removeActColl = document.createElement('a');
  152.             removeActColl.href = '#';
  153.             removeActColl.textContent = 'Remove the active collage';
  154.             removeActColl.setAttribute('collage-id', '0');
  155.             removeActColl.className = 'brackets';
  156.             removeActColl.id = 'thelink';
  157.             removeActColl.addEventListener('click', function(e) { setCollageID(e.target); return false; }, false);
  158.             jx.parentNode.insertBefore(removeActColl, jx);
  159.         }
  160.  
  161.        
  162.         makeitp = document.getElementById("thelink");
  163.         makeitp.insertAdjacentHTML("beforeBegin",'\<p\>');
  164.         makeitp.insertAdjacentHTML("afterEnd",'&nbsp;\</p\>\<hr\>');
  165.  
  166.         // cache the current contents of the active collage
  167.         if (currentCollURL == collageID) {
  168.             var linkArr = extractTorrentgroupLinks('discog_table');
  169.             torrentCache.clear();
  170.             for (var i = 0; i < linkArr.length; ++i) {
  171.                 torrentCache.add(linkArr[i].getAttribute('torrentgroupid'));
  172.             }
  173.             torrentCache.GM_save();
  174.         }
  175.     } else if (URL.Path == 'collages.php' && URL.Parameters['collageid'] && URL.Parameters['action'] == 'manage') {
  176.         manageStuff();
  177.     }
  178. }
  179.  
  180. function extractTorrentgroupLinks(tableId) {
  181.     var linkArr = new Array();
  182.  
  183.     if (document.getElementById(tableId) != null) {
  184.         var lx = document.getElementById(tableId).getElementsByTagName('a');
  185.         if (typeof lx != 'undefined') {
  186.             var curTorrID = '0';
  187.             for (var i = 0; i < lx.length; ++i) {
  188.                 match = /torrents\.php\?id=(\d+)/.exec(lx[i].href);
  189.                 if (match != null && match[1] != curTorrID) {
  190.                     lx[i].setAttribute('torrentgroupid', match[1]);
  191.                     linkArr.push(lx[i]);
  192.                     curTorrID = match[1];
  193.                 }
  194.             }
  195.         }
  196.     }
  197.  
  198.     return linkArr;
  199. }
  200.  
  201. function createAddIcon(torrent_url, torrentgroupid) {
  202.     var res = document.createElement('img');
  203.     res.setAttribute('torrent-url', torrent_url);
  204.     res.setAttribute('torrentgroupid', torrentgroupid);
  205.     updateAddIcon(res);
  206.     res.addEventListener('click', image_click, false);
  207.     return res;
  208. }
  209.  
  210. function updateAddIcon(img) {
  211.     if (torrentCache.contains(img.getAttribute('torrentgroupid'))) {
  212.         img.src = ICON_OK;
  213.         img.title = 'Remove from collage "' + collName + '"...';
  214.     } else {
  215.         img.src = ICON_ADD;
  216.         img.title = 'Add to collage "' + collName + '"...';
  217.     }
  218. }
  219.  
  220. function manageStuff() {
  221.     var authKey = findAuthKey();
  222.    
  223.     var activeCollageID = URL.Parameters['collageid'];
  224.     var allGroupNumbers=new Array();
  225.     var allNewSortNumbers=new Array();
  226.     var allOrigSortNumbers=new Array();
  227.     var isUpdated = 0;
  228.  
  229.     //get initial group numbers
  230.     var jx = document.getElementsByName('groupid');
  231.     for (var i = 0;i < jx.length; ++i) {
  232.         allGroupNumbers[i]=parseInt(jx[i].value);
  233.     }
  234.    
  235.     //get initial group sort numbers
  236.     var kx = document.getElementsByName('sort');
  237.     for (var i = 0; i < kx.length; ++i) {
  238.         allOrigSortNumbers[i]=parseInt(kx[i].value);
  239.     }
  240.    
  241.     var editAllButton = document.createElement('input');
  242.     editAllButton.type = 'button';
  243.     editAllButton.value = 'Edit All';
  244.    
  245.     var zx = document.getElementById('content').getElementsByTagName('h2')[0];
  246.     zx.parentNode.insertBefore(editAllButton, zx);
  247.    
  248.     //edit all button
  249.     editAllButton.addEventListener("click", function(){
  250.         var mx = document.getElementsByName('sort');
  251.         var i = 0;
  252.         isUpdated = 1;
  253.         editAllButton.value = 'Updating...';
  254.        
  255.         for (i = 0; i < mx.length; ++i) {
  256.             allNewSortNumbers[i]=parseInt(mx[i].value);
  257.            
  258.             //only update new numbers
  259.             if (allNewSortNumbers[i] != allOrigSortNumbers[i]) {
  260.                 GM_xmlhttpRequest({
  261.                     method: "POST",
  262.                     url: URL.Host + "/collages.php",
  263.                     data: "action=manage_handle&auth=" + authKey + "&collageid=" + activeCollageID + "&groupid=" + allGroupNumbers[i] + "&sort=" + allNewSortNumbers[i],
  264.                     headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  265.                     //I can't figure out a way to error check this page...
  266.                     onload: function(e) {
  267.                         if (e.responseText.match(/Invalid authorization key/)) {
  268.                             var temp = document.getElementById('content');
  269.                             temp.innerHTML = "Invalid authorization key (the system must have updated your authkey since you loaded the page).  Refresh the page and try again!<br>I strongly recommend rechecking your values, since it's possible (though unlikely) that some values updated while others didn't.  Sorry :(";
  270.                         }
  271.                     },
  272.                     onerror: function(e) {
  273.                         alert("some sort of error occured with the server.  Error occured with torrentID: \"" + allGroupNumbers[i] + "\" which had a new sort number of: \"" + allNewSortNumbers[i] + "\".  Recommend rechecking your values.");
  274.                         return;
  275.                     }
  276.                 });
  277.             }
  278.         }
  279.         // one more worthless request to reload the page after all previous requests finish
  280.         GM_xmlhttpRequest({
  281.             method: "POST",
  282.             url: URL.Host + "/collages.php",
  283.             data: "action=manage_handle&auth=" + authKey + "&collageid=" + activeCollageID + "&groupid=" + allGroupNumbers[i] + "&sort=" + allNewSortNumbers[i],
  284.             headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  285.             onload: function(e) {
  286.                 if (e.responseText.match(/Invalid authorization key/)) {
  287.                     var temp = document.getElementById('content');
  288.                     temp.innerHTML = "Invalid authorization key (the system must have updated your authkey since you loaded the page).  Refresh the page and try again!<br>I strongly recommend rechecking your values, since it's possible (though unlikely) that some values updated while others didn't.  Sorry :(";
  289.                 } else {
  290.                     document.location.href = document.location.href;
  291.                 }
  292.             }
  293.         });
  294.     }, false);
  295.    
  296.     //insert blank space between edit all image and math range image
  297.     var oNewP = document.createElement("b");
  298.     var oText = document.createTextNode(" ");
  299.     oNewP.appendChild(oText);
  300.     var beforeMe = document.getElementsByTagName('h2')[0];
  301.     beforeMe.parentNode.insertBefore(oNewP, beforeMe);
  302.    
  303.     if (GM_getValue("checkBoxAlwaysOn", "0") == 0) {
  304.         var mathRangeButton = document.createElement('input');
  305.         mathRangeButton.type = 'button';
  306.         mathRangeButton.value = 'Math Range';
  307.        
  308.         mathRangeButton.addEventListener("click", function() {
  309.             mathArray();
  310.             mathRangeButton.style.display = 'none';
  311.         }, false);
  312.        
  313.         var bx = document.getElementById('content').getElementsByTagName('h2')[0];
  314.         bx.parentNode.insertBefore(mathRangeButton, bx);
  315.     } else {
  316.         mathArray();
  317.     }
  318.    
  319.     //catch 'Remove' clicks for torrentcache update
  320.     var inputs = document.querySelectorAll('input[name=submit][value=Remove]');
  321.     var groupidnode;
  322.     for(var ii = 0; ii < inputs.length; ++ii) {
  323.         groupidnode = inputs[ii].parentNode.querySelector('input[type=hidden][name=groupid]');
  324.         inputs[ii].setAttribute('torrentgroupid', groupidnode.value);
  325.         inputs[ii].addEventListener('click', function(e) { manage_remove_click(e); });
  326.     }
  327. }
  328.  
  329. // used for operations on manage page
  330. function mathArray() {
  331.     // math Array checkboxes
  332.     var box=new Array();
  333.     var lx = document.getElementsByName('sort');
  334.    
  335.     for (var i =0; i< lx.length; ++i) {
  336.         box[i] = document.createElement("input");
  337.         box[i].type="checkbox";
  338.         box[i].setAttribute('realChecked', "0");
  339.         box[i].setAttribute('arrayValue', i);
  340.         lx[i].parentNode.insertBefore(box[i], lx[i]);
  341.        
  342.         //check for max of two boxes
  343.         box[i].addEventListener("click", function() {
  344.             var unclickCheck = 0;
  345.             if (this.checked == true) {
  346.                 this.setAttribute('realChecked', "1");
  347.             } else  {
  348.                 // if you unselect the box do the following:
  349.                 this.setAttribute('realChecked', "0");
  350.                 for (var m =0; m< lx.length; ++m) {
  351.                     if (box[m].getAttribute('realChecked') != "1") {
  352.                         box[m].checked = false;
  353.                         box[m].disabled = false;
  354.                     }
  355.                 }
  356.             }
  357.             var counter = 0;
  358.                        
  359.             var firstValue, secondValue, thirdValue;
  360.             for (var z=0; z< lx.length; ++z) {
  361.                 if (box[z].getAttribute('realChecked') == "1") {
  362.                     counter++;
  363.                     if (counter == 1) {
  364.                         firstValue = parseInt(z);
  365.                     } else if (counter == 2) {
  366.                         secondValue = parseInt(z);
  367.                     } else if (counter == 3) {
  368.                         thirdValue = parseInt(z);
  369.                     }
  370.                 }
  371.             }
  372.             if (counter == 2) {
  373.                 //visibly show which boxes you checked
  374.                 for (var x = firstValue+1; x <= secondValue-1; ++x) {
  375.                     box[x].checked = true;
  376.                     box[x].disabled = true;
  377.                 }
  378.             } else if (counter == 3) {
  379.                 alert("You can only select TWO check boxes.  One for the top of your range, one for the bottom of your range.  Unselecting the checkbox.");
  380.                 // if you select below the current range
  381.                 if  (this.getAttribute('arrayValue') > secondValue) {
  382.                     for (var x = firstValue+1; x <= secondValue+1; ++x) {
  383.                         box[x].checked = false;
  384.                         box[x].disabled = false;
  385.                         box[x].setAttribute('realChecked', "0");
  386.                     }
  387.                     //uncheck current selection
  388.                     box[thirdValue].checked = false;
  389.                     box[thirdValue].setAttribute('realChecked', "0");
  390.  
  391.                 }
  392.                 // if you select above the current range
  393.                 else if (this.getAttribute('arrayValue') < secondValue) {
  394.                     for (var y = secondValue; y <= thirdValue-1; ++y) {
  395.                        
  396.                         box[y].checked = false;
  397.                         box[y].disabled = false;
  398.                         box[y].setAttribute('realChecked', "0");
  399.                     }
  400.                     //uncheck current selection
  401.                     box[firstValue].checked = false;
  402.                     box[firstValue].setAttribute('realChecked', "0");
  403.                 }
  404.             }
  405.         }, false);
  406.     }
  407.    
  408.     //execute the math range button
  409.     var operationButton = document.createElement('input');
  410.     operationButton.type = 'button';
  411.     operationButton.value = 'Operation';
  412.    
  413.     var yx = document.getElementById('content').getElementsByTagName('h2')[0];
  414.     yx.parentNode.insertBefore(operationButton, yx);
  415.    
  416.     operationButton.addEventListener("click", function(e){
  417.         var upperRangeValue, lowerRangeValue;
  418.        
  419.         var counter = 0;
  420.         // check if they have two check boxes
  421.         for (var q =0; q< lx.length; ++q) {
  422.             if (box[q].getAttribute('realChecked') == "1"){
  423.                 counter++;
  424.                 if (counter == 1) { upperRangeValue = parseInt(q); }
  425.                 else if (counter == 2) { lowerRangeValue = parseInt(q); }  
  426.             }
  427.         }
  428.         if (counter == 1) {
  429.             alert("You must select two checkboxes to include your entire range.\nExample- select the 3rd checkbox and 6th checkbox to perform a math operation on torrents 3, 4, 5, 6\nAnother option is to select NO checkboxes.  When you perform an operation, it will perform on ALL torrents.\nRemember: click edit all to update the changes.");
  430.         } else {
  431.             // We are ready to do the math operations
  432.             var userOperationMessage = "What operation do you want to perform:\nadd: +\nsubtract: -\nmultiply: *\ndivide: \/\nfind missing torrents: m\nexport to tab delimitted file: e\n\nRemember: click edit all to update the changes.";
  433.             if (counter == 0) {            
  434.                 // check all the boxes so you can see you're doing stuff on everything
  435.                 for (var c = 0; c < lx.length; ++c) {
  436.                     box[c].checked = true;
  437.                     box[c].disabled = true;
  438.                 }
  439.                
  440.                 upperRangeValue = 0;
  441.                 lowerRangeValue = parseInt(c);
  442.  
  443.                 var userOperation = prompt("Now performing an operation on ALL elements.\n\n" + userOperationMessage);
  444.             } else {
  445.                 var userOperation = prompt(userOperationMessage);
  446.             }
  447.            
  448.             if (userOperation != null && userOperation != '') {
  449.                 userOperation = userOperation.toUpperCase();
  450.                 if (userOperation == "+" || userOperation == "-" || userOperation == "*" || userOperation == "\/") {
  451.                     var adjustValue = prompt("Current operation: \"" + userOperation + "\".  Input an integer to adjust the selected range by the operation.");
  452.                     if (adjustValue != null && adjustValue != '') {
  453.                         adjustValue = parseInt(adjustValue);
  454.                        
  455.                         if (isNaN(adjustValue)) {
  456.                             alert("Please pick a valid integer!");
  457.                             return;
  458.                         }
  459.                     } else {
  460.                         return;
  461.                     }
  462.                 } else if (userOperation == "M") {
  463.                     var diffValue = prompt("Current operation: \"Find Missing Torrents\".  Input the difference of sort numbers.\nExample: Input 10 if the collage sort numbers are 10, 20, 30, ...");
  464.                     if (diffValue != null && diffValue != '') {
  465.                         diffValue = parseInt(diffValue);
  466.                         if (isNaN(diffValue)) {
  467.                             alert("Please pick a valid integer!");
  468.                             return;
  469.                         }
  470.                     } else {
  471.                         return;
  472.                     }
  473.                 } else if (userOperation == "E") {
  474.                 } else {
  475.                     // uncheck all the boxes assuming the user never selecting any
  476.                     if (counter == 0) {                
  477.                         for (var c =0; c< lx.length; ++c) {
  478.                             if (c >= upperRangeValue && c <= lowerRangeValue) {
  479.                                 box[c].checked = false;
  480.                                 box[c].disabled = false;
  481.                             }  
  482.                         }
  483.                     }
  484.                     alert("Please select only the following characters \"+\", \"-\", \"*\", \"\/\", \"m\" (no quotes)");
  485.                     return;
  486.                 }
  487.             } else {
  488.                 // user hits cancel
  489.  
  490.                 // uncheck all the boxes assuming the user never selecting any
  491.                 if (counter == 0) {
  492.                     for (var c = 0; c < lx.length; ++c) {
  493.                         if (c >= upperRangeValue && c <= lowerRangeValue) {
  494.                             box[c].checked = false;
  495.                             box[c].disabled = false;
  496.                         }  
  497.                     }
  498.                 }
  499.                 return;
  500.             }
  501.                        
  502.             var allNewSortNumbers = new Array();
  503.  
  504.             if (userOperation == "+") {
  505.                 for (var b = 0; b < lx.length; ++b) {      
  506.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  507.                         allNewSortNumbers[b] = parseInt(lx[b].value) + adjustValue;
  508.                         lx[b].value=allNewSortNumbers[b];
  509.                     }              
  510.                 }
  511.             } else if (userOperation == "-") {
  512.                 for (var b = 0; b < lx.length; ++b) {      
  513.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  514.                         allNewSortNumbers[b] = parseInt(lx[b].value) - adjustValue;
  515.                         lx[b].value=allNewSortNumbers[b];
  516.                     }              
  517.                 }
  518.             } else if (userOperation == "*") {
  519.                 for (var b = 0; b < lx.length; ++b) {      
  520.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  521.                         allNewSortNumbers[b] = parseInt(lx[b].value) * adjustValue;
  522.                         lx[b].value=allNewSortNumbers[b];
  523.                     }              
  524.                 }          
  525.             } else if (userOperation == "\/") {
  526.                 for (var b = 0; b < lx.length; ++b) {      
  527.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  528.                         allNewSortNumbers[b] = parseInt(lx[b].value) / adjustValue;
  529.                         lx[b].value=allNewSortNumbers[b];
  530.                     }              
  531.                 }
  532.             } else if (userOperation == "M") {
  533.                 //find missing numbers
  534.                 var missingValues=new Array();
  535.                 var extraValues=new Array();
  536.                 var missingCount = 0;
  537.                 var extraCount = 0;
  538.                 var zzb = document.getElementsByName('sort');
  539.                 var checkNumber = parseInt(zzb[upperRangeValue].value);
  540.                 var nextNumber =0;
  541.                 for (var i = upperRangeValue; i < lowerRangeValue-1; ++i) {
  542.                     checkNumber += diffValue;
  543.                    
  544.                     nextNumber = parseInt(zzb[i + 1].value);
  545.  
  546.                     if (checkNumber != nextNumber) {
  547.                         if (checkNumber < nextNumber) {
  548.                             i--;
  549.                             if (checkNumber != missingValues[missingCount-1]) {
  550.                                 missingValues[missingCount] = checkNumber;
  551.                                 missingCount++;
  552.                             }
  553.                         } else {
  554.                             extraValues[extraCount] = nextNumber;
  555.                             extraCount++;
  556.                             if (checkNumber != missingValues[missingCount-1]) {
  557.                                 missingValues[missingCount] = checkNumber;
  558.                                 missingCount++;
  559.                                 checkNumber -= diffValue;
  560.                             }
  561.                         }
  562.                     } else {
  563.                         if (checkNumber == missingValues[missingCount-1]) {
  564.                                 missingCount--;
  565.                                 missingValues.pop();
  566.                         }
  567.                     }
  568.                 }
  569.                 if (missingCount == 0) {
  570.                     if (extraCount == 0) {
  571.                         alert("No missing sort numbers.\nAlso, no extra sort numbers tucked inbetween.");
  572.                     } else {
  573.                         alert("No missing sort numbers.\nBut the extra sort numbers are: " + extraValues);
  574.                     }  
  575.                 } else {
  576.                     if (extraCount == 0) {
  577.                         alert("The missing sort numbers are: " + missingValues + "\nAlso, no extra sort numbers tucked inbetween.");
  578.                     } else {
  579.                         alert("The missing sort numbers are: " + missingValues + "\nAnd the extra sort numbers are: " + extraValues);
  580.                     }
  581.                 }
  582.             } else if (userOperation == "E") {
  583.                 var items = document.getElementById("content").getElementsByTagName("a");
  584.                 var names = new Array();
  585.                 var artist, album;
  586.                 var artistMatch, artistMatchSecond, albumMatch;
  587.                 var combined;
  588.  
  589.                 for (var i = 0; i < items.length; ++i) {
  590.                     albumMatch = items[i].href.match(/torrents\.php\?id=([0-9]+)$/);
  591.                     if (albumMatch) {
  592.                         album = items[i].innerHTML;
  593.                         artistMatch = items[i-1].href.match(/artist\.php\?id=([0-9]+)$/);
  594.                        
  595.                         if (artistMatch) {
  596.                             artist = items[i-1].innerHTML;
  597.                             //check for 2 artists (eg. "Billy Bragg" and "Wilco" - "Mermaid Avenue")
  598.                             artistMatchSecond = items[i-2].href.match(/artist\.php\?id=([0-9]+)$/);
  599.                             if (artistMatchSecond) { artist = items[i-2].innerHTML + " and " + artist; }
  600.                             // sort by artist - album
  601.                             if (userOperation == "E" ) { combined = "\"" + artist + "\",\"" + album+  "\""; }
  602.                             // sort by album - artist
  603.                             else {combined = "\"" + album + "\",\"" + artist + "\""; }
  604.                         } else {
  605.                             // case for no artist found (ie pdf, audiobook, Various Artists etc)
  606.                             combined = ",\"" + album + "\"";
  607.                            
  608.                             // super ugly way to handle Various Artists for sort by artist (if anyone has a better idea, I'm all ears :)
  609.                             var itemsx = document.getElementById("content").getElementsByTagName("tr");
  610.                             outerLoop: for (var z = 0; z < itemsx.length; ++z) {
  611.                                 var itemsInnerHTML = itemsx[z].innerHTML
  612.                                 var match = itemsInnerHTML.match(/torrents\.php/);
  613.                                 if (match) {
  614.                                     if (itemsx[z].innerHTML.match(/Various Artists/)) {
  615.                                         var tempAlbumCheck = itemsInnerHTML.substring(itemsInnerHTML.indexOf("Torrent\">")+9, itemsInnerHTML.indexOf("</a>"));
  616.                                         if (album == tempAlbumCheck) {
  617.                                             //put at end of sort list
  618.                                             combined = "\"Various Artits\",\"" + album + "\"";
  619.                                             break outerLoop;
  620.                                         }
  621.                                     }
  622.                                 }
  623.                             }
  624.                         }
  625.                         names.push(combined);
  626.                     }
  627.                 }
  628.                 var message = '';
  629.                 for (var x = 0; x < names.length; ++x) {
  630.                     message = message + names[x] + "<br>";
  631.                 }
  632.                 document.body.innerHTML = message;
  633.                
  634.             }
  635.  
  636.             // uncheck the boxes in the range (note: the above/below loops should be separate for speed issues
  637.             for (var c =0; c< lx.length; ++c) {
  638.                 if (c >= upperRangeValue && c <= lowerRangeValue) {
  639.                     box[c].checked = false;
  640.                     box[c].disabled = false;
  641.                 }  
  642.             }
  643.             box[upperRangeValue].setAttribute('realChecked', "0");
  644.             box[lowerRangeValue].setAttribute('realChecked', "0");
  645.         }
  646.     }, false);
  647. }
  648.  
  649.  
  650. // get the collage ID from stored file
  651. function getCollageID() {
  652.     collageID = GM_getValue('activeCollageID', '0');
  653.     collName = GM_getValue('activeCollageName', 'None');
  654. }
  655.  
  656. // write the collage ID to the stored file
  657. function setCollageID(linkref) {
  658.     if (linkref.getAttribute('collage-id') == '0') {
  659.         GM_deleteValue('activeCollageID');
  660.         GM_deleteValue('activeCollageName');
  661.         torrentCache.GM_delete();
  662.     } else {
  663.         GM_setValue('activeCollageID', linkref.getAttribute('collage-id'));
  664.         GM_setValue('activeCollageName', linkref.getAttribute('collage-name'));
  665.     }
  666.     window.location.reload();
  667. }
  668.  
  669. function image_click(e) {
  670.     var authKey = findAuthKey();
  671.  
  672.     //error checking on collageID in case user updates collage and doesn't refresh torrents.php page
  673.     if (GM_getValue('activeCollageID') != collageID) {
  674.         alert('Active collage has changed. Refresh the page and try again!');
  675.         return;
  676.     }
  677.  
  678.     var img = this; //necessary to be able to change the image's src attribute from within the onload/onerror closures
  679.  
  680.     var inCollage = torrentCache.contains(img.getAttribute('torrentgroupid'));
  681.  
  682.     img.src = ICON_LOADING;
  683.  
  684.     GM_xmlhttpRequest({
  685.         method: "POST",
  686.         url: URL.Host + "/collages.php",
  687.         data: (inCollage ?
  688.             'action=manage_handle&auth=' + authKey + '&collageid=' + collageID + '&groupid=' + img.getAttribute('torrentgroupid') + '&submit=Remove' :
  689.             'action=add_torrent&auth=' + authKey + '&collageid=' + collageID + '&url=' + img.getAttribute('torrent-url')),
  690.         headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  691.         onload: function(response) {
  692.             // we get redirected if the action was successful, so if we are still on collages.php$, that means that something went wrong.
  693.             if (response.finalUrl.match(/\/collages\.php$/)) {
  694.                 // generically read out the error message. yes, this code isn't pretty :-/
  695.                 var title = response.responseText.substring(response.responseText.search('<h2>')+4);
  696.                 title = title.substring(0, title.search('</h2>'));
  697.                 var description = response.responseText.substring(response.responseText.search('<h2>Error</h2>'));
  698.                 description = description.substring(description.search('<p>')+3);
  699.                 description = description.substring(0, description.search('</p>'));
  700.                
  701.                 img.src = ICON_ERR;
  702.                 alert(title+"\n\n"+description);
  703.             } else {
  704.                 // Remember: inCollage is determined *before* sending the request. When inCollage is true, the torrent now isn't in the collage anymore!
  705.                 if (inCollage) {
  706.                     torrentCache.remove(img.getAttribute('torrentgroupid'));
  707.                 } else {
  708.                     torrentCache.add(img.getAttribute('torrentgroupid'));
  709.                 }
  710.                 torrentCache.GM_save();
  711.                 updateAddIcon(img);
  712.             }
  713.         },
  714.         onerror: function(f) {
  715.             img.src = ICON_ERR;
  716.             alert('Some unknown error occured. Refresh the page and try again!');
  717.         }
  718.     });
  719. }
  720.  
  721. function manage_remove_click(e) {
  722.     torrentCache.remove(e.target.getAttribute('torrentgroupid'));
  723.     torrentCache.GM_save();
  724.     return true;
  725. }
  726.  
  727. //find authkey
  728. function findAuthKey() {
  729.     return unsafeWindow.authkey;
  730. }
  731.  
  732. // preference for always showing checkboxes on manage page
  733. GM_registerMenuCommand("Apollo.rip :: Collage Building Helper - MathRange checkboxes", function() {
  734.     var checkBoxQuestion;
  735.     for (var zz = 1; zz <= 3 && isNaN(checkBoxQuestion); ++zz) {
  736.         checkBoxQuestion = prompt("Do you want the checkboxes to always appear on the manage collage page?\nType \"1\" for yes and \"0\" for no.\nCurrent selection is: " + GM_getValue("checkBoxAlwaysOn", "0") + " (0 is default)");
  737.         if (checkBoxQuestion != null && checkBoxQuestion != '') {
  738.             checkBoxQuestion = parseInt(checkBoxQuestion);
  739.             if (isNaN(checkBoxQuestion)) {
  740.                 if (zz==3) {
  741.                     alert("Try harder!  Better luck next time!");
  742.                 } else {
  743.                     alert("Please pick \"1\" or \"0\" (no quotes)");
  744.                 }
  745.             } else if (checkBoxQuestion == 0 || checkBoxQuestion == 1) {
  746.                 GM_setValue("checkBoxAlwaysOn", checkBoxQuestion);
  747.             } else {
  748.                 alert("Please pick \"1\" or \"0\" (no quotes)");
  749.             }
  750.         }
  751.     }
  752. });
  753.  
  754. init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement