RaaW

Reddit as a Weapon script. Parts and idea by /u/noeatnosleep, enhanced by /u/enim

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

// ==UserScript==
// @name RaaW
// @version 1.7.0
// @namespace RaaW
// @description Reddit as a Weapon script. Parts and idea by /u/noeatnosleep, enhanced by /u/enim
// @include http://www.reddit.com/user/*
// @include http://www.reddit.com/r/*
// @include http://*reddit.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
// ==/UserScript==

this.$ = this.jQuery = jQuery.noConflict(true);

var currentPage = document.URL;
var parsedPage = currentPage.split('/');
var modHash = null;
var currentUser = null;
var subreddit = null;
var commentIDs = [];
var topicIDs = [];
var subredditList = [];
var reportID = [];

var commentPage;	
commentPage = document.getElementsByClassName('comment');

function getHash(callback) {
    var query = new XMLHttpRequest();
    query.onreadystatechange = function () {
        if (query.readyState == 4) {
            var info = JSON.parse(query.responseText);
            modHash = info.data.modhash;
            callback();
        }
    }
    query.open('GET', 'http://www.reddit.com/api/me.json', true);
    query.send(null);
}

function generateToolbar () {
	$(document).find('#header')[0].style.paddingTop='18px';
    var newToolbar = document.createElement("div");
	newToolbar.id = "newToolbar";
	document.body.insertBefore(newToolbar,document.body.firstChild);
	var subredditbar = document.getElementById('sr-header-area');
	newToolbar.style.cssText="color:black;background-color:'#f0f0f0';border-bottom:1px black solid;font-family:verdana, arial, helvetica, sans-serif;font-size:90%;height:12px;padding:3px 0px 3px 6px;text-transform:uppercase;width:100%;z-index:+999999;position:fixed;top:0;";
	newToolbar.style.backgroundColor='#f0f0f0';
	newToolbar.style.paddingLeft = '6px';
    newToolbar.style.paddingTop = '3px';
    newToolbar.style.paddingBottom = '3px';
    newToolbar.style.top='0px';
    newToolbar.innerHTML += "<a id='downvoteComment' style='color:black;' href='#'>DOWNVOTE ALL</a> | <a id='upvoteComment' style='color:black;' href='#'>UPVOTE ALL</a> |";
	if (commentPage.length == 0) {
		newToolbar.innerHTML += " <a id=reportComment style='color:black;' href='#'>REPORT POSTS</a> ";
	}
	else {
		newToolbar.innerHTML += "<a id=reportComment style='color:black;' href='#'> REPORT ALL</a> ";	
	}
	if (parsedPage[3] == 'user'){
		newToolbar.innerHTML += "<a id='upvoteAndOpen' style='color:black;' href='#'> |  OPEN AND UPVOTE  </a> <a id='downvoteAndOpen' style='color:black;' href='#'> | OPEN AND DOWNVOTE </a>  <a id='analyzeSend' style='color:black;' href='#'> | ANALYZE </a> <a id='reportUserToSpam' style='color:black;' href='#'> | REPORT ON /R/SPAM </a>";
	}

 }


function doStuff() {
    $('#reportComment').on('click',function(e) {
       for(var i = 0; i < reportID.length; i++) {reportItem(i, 3);}
    alert('All items on this page were reported.');
    });   
    $('#downvoteComment').on('click',function(e){
    	theDownvoter();
    });
    $('#upvoteComment').on('click',function(e){
    	theUpvoter();
    });
    $('#upvoteAndOpen').on('click',function(e){
    	clickYourUpvotes();
    });
    $('#downvoteAndOpen').on('click',function(e){
    	clickYourDownvotes();
    });
    $('#reportUserToSpam').on('click',function(e){
    	reportToSpam();
    });
    $('#analyzeSend').on('click',function(e){
    	analyzeSend();
    });
	
}

function buildReportArray() {
	if (commentPage.length == 0) {
		var threads;
		threads = $('#siteTable').find('.thing');
		for (i = 0; i < threads.length; i++) {
			 reportID.push(threads[i].getAttribute('data-fullname'));
		}
	}
	else if (commentPage.length != 0) {
		var threads;
		threads = $('.commentarea').find('.thing');
		for (i = 0; i < threads.length; i++) {
			 reportID.push(threads[i].getAttribute('data-fullname'));
		}
	}
}

function reportItem(index, num) {
  if(num == 3) {var fullname = topicIDs[index];}
  else{var fullname = commentIDs[index];}
  $.post('http://www.reddit.com/api/report', {'id': fullname, 'uh': modHash});
}


function theDownvoter() {
	if (parsedPage[3] == 'user'){
		var items = $('#siteTable').find('.arrow.down');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	}
	else {
		if (commentPage.length == 0) {
			var items = $('#siteTable').find('.arrow.down');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	 	}
	 	else {
			var items = $('.commentarea').find('.arrow.down');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	 	}
	}
}

function theUpvoter() {
	if (parsedPage[3] == 'user'){
		var items = $('#siteTable').find('.arrow.up');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	}
	else {
		if (commentPage.length == 0) {
			var items = $('#siteTable').find('.arrow.up');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	 	}
	 	else {
			var items = $('.commentarea').find('.arrow.up');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
	 	}
	}
}

function clickYourUpvotes() {
	var clickandupvote = [];
	$('#siteTable').find('.flat-list.buttons').find('.first').find('a.comments, a.bylink').each(function(index,value){
		clickandupvote.push($(this).attr('href'));	
	});
	for (i=0;i < clickandupvote.length;i++){
		window.open(clickandupvote[i]);
	}
	var items = $('#siteTable').find('.arrow.up');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
}

function clickYourDownvotes() {
	var clickandupvote = [];
	$('#siteTable').find('.flat-list.buttons').find('.first').find('a.comments, a.bylink').each(function(index,value){
		clickandupvote.push($(this).attr('href'));	
	});
	for (i=0;i < clickandupvote.length;i++){
		window.open(clickandupvote[i]);
	}
	var items = $('#siteTable').find('.arrow.down');
		    Array.prototype.forEach.call(items, function(el, i){
		      setTimeout(function(){
		        el.click();
		      },100 + ( i * 400 ));
		    });
		    return false;
}
		
function reportToSpam(){
	var username = $(document).find('.pagename.selected').text();
	window.open('http://www.reddit.com/r/spam/submit?title=overview for '+ username + '&url=http://www.reddit.com/user/' + username );
}

function analyzeSend(){
	var username = $(document).find('.pagename.selected').text();
	window.open('http://www.reddit.com/message/compose/?to=analyzereddit&subject=analyze&message='+ username);
}

if (document.documentElement.lang === 'np') {
    document.documentElement.lang = 'en-us';
}
document.body.classList.add('subscriber');

delete_function = function(thread_root) {
    var elmnts = document.getElementsByClassName('id-'+thread_root)[0].querySelectorAll('form input[value="removed"]~span.option.error a.yes,a[onclick^="return big_mod_action($(this), -1)"]');
    for(var i=0; i < elmnts.length; i++) {
	setTimeout(
	    (function(_elmnt) {
		return function() {
		    var event = document.createEvent('UIEvents');
		    event.initUIEvent('click', true, true, window, 1);
		    _elmnt.dispatchEvent(event);
		}}
	    )(elmnts[i]), 1500*i); // 1.5s timeout prevents overloading reddit.
    };
}

if(document.querySelector('body.moderator')){ // only execute if you are a moderator
    var nuke_button = new Array();
    var divels = document.querySelectorAll('div.noncollapsed');
    var comment_ids = new Array();


    for (var i = 0; i < divels.length; i++) {
	var author_link = divels[i].querySelector('p.tagline>a.author,p.tagline>span.author,p.tagline>em');
	// p.tagline>a.author is normal comment;
	// some author deleted comments seem to have either
	// p.tagline>span.author or p.tagline>em 
	
	comment_ids[i] = divels[i].parentElement.parentElement.getAttribute('data-fullname');
	
	if(author_link) {
	    // create link DOM element
	    nuke_button[i] = document.createElement('a')
	    nuke_button[i].setAttribute('href', 'javascript:void(0)');
	    nuke_button[i].setAttribute('title', 'Nuke!');
	    nuke_button[i].setAttribute('id', 'nuke_'+i);	    
	    nuke_button[i].innerHTML= "[<strong>Nuke</strong>]";
	    // append after the author's name
	    author_link.parentNode.insertBefore(nuke_button[i], author_link.nextSibling);

	    // Add listener for click; using IIFE to function with _i as value of i when created; not when clicked
	    nuke_button[i].addEventListener('click', 
                (function(_i) {
		    return function() {
			var continue_thread = divels[_i].parentElement.parentElement.querySelectorAll('span.morecomments>a');
			var comment_str = " comments?";
			if(continue_thread.length > 0) {
		    	    comment_str = "+ comments (more after expanding collapsed threads; there will be a pause before the first deletion to retrieve more comments)?";
			}
			var delete_button = divels[_i].parentElement.parentElement.querySelectorAll('form input[value="removed"]~span.option.error a.yes,a[onclick^="return big_mod_action($(this), -1)"]');
			// form input[value="removed"]~span.option.error a.yes -- finds the yes for normal deleting comments.
			// a.pretty-button.neutral finds the 'remove' button for flagged comments
			if (confirm("Are you sure you want to nuke the following " + delete_button.length + comment_str)) {
		    	    for (var indx=0; indx < continue_thread.length; indx++) {
		    		var elmnt = continue_thread[indx];
		    		setTimeout(
		    		    function() {
		    			var event = document.createEvent('UIEvents');
		    			event.initUIEvent('click', true, true, window, 1);
		    			elmnt.dispatchEvent(event);
		    		    }, 2000*indx); // wait two seconds before each ajax call before clicking each "load more comments"
		    	    } 
			    if(indx > 0) {
				setTimeout(function() {delete_function(comment_ids[_i])},
					   2000*(indx + 2)); // wait 4s after last ajax "load more comments"
			    } else {
				delete_function(comment_ids[_i]); // call immediately if not "load more comments"
			    }
			}
		    }
		}
		)(i)); // end of IIFE (immediately invoked function expression)
	}
    }
}

//reveal source

function reveal() {
  var l = window.document.location,
    h = l.href,
    q = l.search,
    u = h.substring(0, h.length - q.length) + ".json" + q;
  $.getJSON(u, function (json_data) {

    var dom_data = (function () {
      var result = {},
        key;
      $.each($(".thing"), function () {
        var thingDom = this;
        if ($(this).css("display") === "none") {
          return;
        }
        $.each(this.className.split(" "), function () {
          if (this.indexOf("id-") === 0) {
            var thing_type_name = this.substr(3).split("_");
            if (typeof(result[thing_type_name[0]]) === "undefined") {
              result[thing_type_name[0]] = [];
            }
            result[thing_type_name[0]].push({
              name: thing_type_name[1],
              domObj: thingDom
            });
          }
        });
      });
      return result;
    })();

    var json_result = {};

    function gather_data(json_data) {
      var crawl = function (obj) {
        if (obj && obj.length) {
          $.each(obj, function () {
            crawl(this);
          });
        } else if (typeof(obj) === "object") {
          var kind = obj.kind;
          var data = obj.data;
          if (kind) {
            if (kind === "Listing") {
              crawl(data.children);
            } else if (data) {
              if (typeof(json_result[kind]) === "undefined") {
                json_result[kind] = {};
              }
              json_result[kind][data.id] = data;
              if (kind === "t1" && data.replies) {
                crawl(data.replies);
              }
            }
          }
        }
      };
      crawl(json_data);
    }

    gather_data(json_data);

    var enable_source = function (entry, text) {
      if (entry.find(".usertext-edit").size() > 0 || entry.find(".usertext-body").size() === 0) {
        return;
      }
      entry.find(".usertext-body").after("<div class=\"usertext-edit\" style=\"display:none;\"><div><textarea rows=\"1\" cols=\"1\" name=\"text\">" + text + "</textarea></div><div class=\"bottom-area\"><div class=\"usertext-buttons\"><button type=\"button\" class=\"cancel\" onclick=\"cancel_usertext(this)\">hide</button></div></div></div>");
      entry.find(".flat-list.buttons").append("<li><a class=\"edit-usertext\" href=\"javascript:void(0)\" onclick=\"return edit_usertext(this)\">source</a></li>");
    };

    var get_upvote_downvote_html = function (data) {
      var rv = " (";
      rv += "<span style=\"color:orangeRed\">+" + data.ups + "</span>/";
      rv += "<span style=\"color:#5F99CF\">-" + data.downs + "</span>";
      rv += ") ";
      return rv;
    };

    var update_ui = function () {
      if (dom_data.t1) {
        $.each(dom_data.t1, function () {
          var id = this.name;
          var domObj = this.domObj;
          var data = json_result.t1[id];
          if (!data) {
            return;
          }
          var entry = $(domObj).children(".entry");
          entry.find(".score.likes").after(get_upvote_downvote_html(data));
          enable_source(entry, data.body);
        });
      }

      var update_t3_ui = function (domObj, data) {
        var thing = $(domObj);
        var entry = thing.children(".entry");
        var midcol = thing.children(".midcol");
        var score = data.score;

        // reveal up/down vote score
        //entry.find(".reddit-comment-link, .tagline").prepend(get_upvote_downvote_html(data));

        // reveal mark down source
        enable_source(entry, data.selftext);

        // reveal vote score
        //if (midcol.hasClass("likes")) {
        //  score--;
        //}
        //if (midcol.hasClass("dislikes")) {
        //  score++;
        //}
        //midcol.find(".score.likes").text(score + 1);
        //midcol.find(".score.unvoted").text(Math.max(0, score)); // min score is 0
        //midcol.find(".score.dislikes").text(Math.max(0, score - 1)); // min score is 0
      };

      if (dom_data.t3) {
        $.each(dom_data.t3, function () {
          var name = this.name;
          var domObj = this.domObj;
          var data = json_result.t3[name];
          if (!data) {
            $.getJSON("/by_id/t3_" + name + ".json", function (json_data) {
              update_t3_ui(domObj, json_data.data.children[0].data);
            });
            return;
          } else {
            update_t3_ui(domObj, data);
          }
        });
      }
    };
    update_ui();
  });

  $(".button").on("click", function(ev) {
  	  console.log(this.id);
      if (this.id.indexOf("more_t1_") === 0) {
        var id = this.id.split("_")[2];
        console.log(id);
      }
  });

  $(".author").on("mouseover", function (ev) {
  	  var username = $(this).text();
      var rev = $(this).next(".revelation");
      if (rev.size() === 0) {
        var tip = $("<span class=\"revelation\" style=\"position:relative;\"/>");
        $(this).after(tip);
        $.getJSON("/user/" + username + "/about.json", function (a) {
          tip.html(" (<span style=\"color:#B40404\"><b>" + a.data.link_karma + "</b> link karma</span>," + " <span style=\"color:#04B404\"><b>" + a.data.comment_karma + "</b> comment karma</span>, " + " <span style=\"color:#0404B4\"><b>" + parseInt((((new Date()).getTime() / 1000) - a.data.created_utc) / 86400, 10) + "</b> days</span>) ");
        });
      } else {
        rev.css("display", "");
      }
  }).on("mouseout", function (ev) {
      $(this).next(".revelation").css("display", "none");
  });
  
  }
  
  
(function () {
        var s = document.createElement('script');
        s.textContent = "(" + reveal.toString() + ')();';
        document.head.appendChild(s);
})();
generateToolbar(), getHash(),buildReportArray(), doStuff();