User:Rutilant/reportSpam.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki>
/*
  <section begin=status/>Stable<section end=status/>
  <section begin=last_update/>July 12, 2019<section end=last_update/>
  <section begin=version/>1.2<section end=version/>
*/
$(function () {
  var config = {
    debug: false,
    disable_notification: false,
    report_page: 'Wikipedia:Administrator intervention against vandalism',
    edit_summary: "Added report for a possible spambot: [[Special:Contributions/$username|$username]] ([[User:RainFall/reportSpam|reportSpam]])"
  };
  if (typeof reportSpam_customconfig == "object") {
    Object.keys(reportSpam_customconfig).forEach((e) => {
      config[e] = reportSpam_customconfig[e];
    });
  }
  let allow_init = mw.config.get("wgCanonicalSpecialPageName") === "Recentchanges" || mw.config.get("wgCanonicalSpecialPageName") === "Contributions";
  if (allow_init) {
    class AIV_report {
      constructor(username, token) {
        this.username = username;
        this.ajax_data = {
          title: config.report_page,
          action: "edit",
          token: token,
          summary: config.edit_summary.replace(/\$username/g, username),
          appendtext: '\n*{{vandal|' + username + '}} &ndash; account is evidently a spambot. ~~' + '~~',
          format: 'json',
        };
      }

      submit_report(clicked) {
        var $this = this;
        $.ajax({
          type: 'POST',
          url: '/w/api.php',
          data: this.ajax_data,
          success: function (response) {
            $(clicked).text("reported");
            if (!config.disable_notification) mw.notify('Added report for ' + $this.username);
            if (config.debug) console.log(response);
          },
          error: function (e) {
            if (config.debug) console.log(e);
            $(clicked).text("editing failed");
            if (!config.disable_notification) mw.notify('reportSpam: unable to report the user; see console log.');
            return 'Unable to perform the edit.';
          },
        });
      }
    }

    let main = {
      get_token: () => {
        return $.get("/w/api.php?action=query&meta=tokens&format=json").then(response => {
          try {
            return response.query.tokens.csrftoken;
          } catch (e) {
            if (!config.disable_notification) mw.notify(s_appname + ': unable to parse the token; check console log for more detail.');
            if (config.debug) console.log(e);
            return false;
          }
        });
      },

      escape_regexp: (str) => {
        return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      },

      check_AIV: (username) => {
        return $.get("/w/api.php?action=parse&page=" + config.report_page + "&format=json&prop=wikitext")
          .then(response => {
            if (config.debug) console.log(response);
            let AIV_text = response.parse.wikitext["*"];
            let regexp = RegExp("{{vandal\\|" + main.escape_regexp(username) + "}}", "ig");
            return regexp.test(AIV_text);
          });
      },

      report_user: (username, clicked) => {
        $(clicked).text("reading AIV...");
        main.check_AIV(username).then(user_exists => {
          let confirm_text = "Report '" + username + "' to AIV?";
          if (user_exists) {
            alert("'" + username + "' seems to already have been reported.");
            return;
          }
          if (confirm(confirm_text)) {
            $(clicked).text("getting token");
            main.get_token().then(token => {
              if (token) {
                let report = new AIV_report(username, token);
                $(clicked).text("writing report");
                report.submit_report(clicked);
              } else {
                $(clicked).text("failed to get token");
              }
            });
          } else {
            $(clicked).text("report spam");
          }

        });
      }
    };

    let add_links = function () {
      $(".rp-spam-span").remove();
      $(".mw-changeslist-line").each(function () {
        let username = $(this).find(".mw-userlink").text();
        $(this).find(".mw-usertoollinks").append("<span class='rp-spam-span'><a class='rp-spam' data-user='" + username + "'>report spam</a></span>");
      });

      $(".mw-contributions-list li").each(function () {
        let username = $(this).find(".mw-userlink").text() || mw.config.get("wgRelevantUserName") /* for individual contrib page */ ;
        $(this).append("<span class='rp-spam-span'> [<a class='rp-spam' data-user='" + username + "'>report spam</a>] </span>");
      });

      $(".rp-spam").click(function () {
        main.report_user($(this).data("user"), $(this));
      });
    };
    mw.hook('wikipage.content').add(function () {
      add_links();
    });
  }
});
// </nowiki>