MediaWiki:Common.js

From Official Factorio Wiki
Revision as of 00:57, 4 October 2016 by TheWombatGuru (talk | contribs)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */
/*$(".navbox").css("background", "red");*/

//Spoiler template JavaScript
$(".spoiler-container .button").click(function() {
  $(this).siblings(".text").toggle("slow");
});

$("#start-edit-test").click(function(){
   targetAllPagesInCategory("Category:Combat");
});

function targetAllPagesInCategory(category) {
    var languageSuffixes = ["fr", "ru", "de"]; //, "/cs", "/de", "/es", "/fr", "/it", "/nl", "/pl", "/pt-br", "/ru", "/sv", "/uk", "/zh", ""];
    for (var j = 0; j < languageSuffixes.length; j++) {
      $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            list: 'categorymembers',
            cmtitle: (category + languageSuffixes[j]),
            cmlimit: 500
        },
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.categorymembers;
            for (var i = 0; i < pages.length; i++) {
                    //purgePage(pages[i].title);
                    extractPageInfo(pages[i].title, "9c28a1344a20bf189fda7d58339e518257f2dd9b+\\");
                    console.log(i + " - " + pages[i].title);
                
            }

            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info + 'Category' );
            } else {
                //alert( 'Error: Unknown result from API. Category' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed. Category' );
        }
    });
  }
}

function purgePage(pageTitle) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            action: 'purge',
            titles: pageTitle
        },
        async: false,
        type: 'GET',
        success: function( data ) {
            console.log("purging " + pageTitle);
            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
            console.log("Failed purging");
        }
    });
}

function extractPageInfo(pageTitle, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'query',
            titles: pageTitle,
            prop: 'revisions',
            rvprop: 'content'
        },
        async: false,
        dataType: 'json',
        type: 'GET',
        success: function( data ) {
            var pages = data.query.pages;
            var revisions = pages[Object.keys(pages)[0]].revisions[0];
            var content = revisions[Object.keys(revisions)[2]]
            var title = pages[Object.keys(pages)[0]].title;
            createNewInfoboxPage(title, content, token);
            if ( data && data.query && data.query.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}

function createNewInfoboxPage(page, contentOfMainPage, token) {
    var infoboxText = getInfoboxFromFullPageContent(contentOfMainPage);

    var infoboxPageTitle = page.replace(/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g, function(piece) {return "";}).concat("/infobox");
    var oldPageRevisedText = getOldPageRevisedText(page, contentOfMainPage, infoboxPageTitle);	
    removeInfoboxFromMain(page, oldPageRevisedText, token);

    if (infoboxText != null) {
      if (/\/(de|fr|nl|it|es|ru|pt\-br|cs|pl|sv|uk|zh)/g.test(page)) {
        return;
      }
      var newPageTitle = page.concat("/infobox");
      var convertedInfoboxText = convertInfobox(infoboxText, token);
      createPage(newPageTitle, convertedInfoboxText, token, page, contentOfMainPage);
    }
}

function getOldPageRevisedText(pageTitle, content, infoboxPageTitle) {
    content = content.replace(/{{\bCombat\b(\s+(\||{).+)+\s}}/gi, function (piece) {
        return "{{:" + infoboxPageTitle + "}}";
    });
    return content;
}

function removeInfoboxFromMain(pageTitle, content, token) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            token: token,
            summary: "(BOT) - Replaced old infobox with a link to the /infobox subpage"
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    })
};

function getInfoboxFromFullPageContent(contentOfPage) {
    var matches = contentOfPage.match(/{{\bCombat\b(\s+\|.+)+\s}}/gi);
if (matches != null && matches.length > 0) {
 infoboxText = matches[0];
} else {
 infoboxText = null;
}
    return infoboxText;
}

function convertInfobox(text) {
    text = text.replace(/{{(\w+)/g, function (piece, $1) {
        var returnText = "{{Infobox\n| category = ";

        $1 = $1.toLowerCase();

        switch ($1) {
            case "item":
                returnText = returnText.concat("Items");
                break;
            case "machinery":
                returnText = returnText.concat("Machinery");
                break;
            case "combat":
                returnText = returnText.concat("Combat");
                break;
            case "technology":
                returnText = returnText.concat("Technology");
        }

        switch ($1) {
            case "machinery":
                returnText = returnText.concat("\n| category-name = Machine");
                break;
            case "item":
                returnText = returnText.concat("\n| category-name = Item");
                break;
        }

        return returnText;
    });

    text = text.replace("stack_size", "stack-size");
    text = text.replace("poweroutput", "power-output");
    text = text.replace("input", "recipe");
    text = text.replace("raw", "total-raw");
    text = text.replace("technologies", "required-technologies");
    text = text.replace("costmultiplier", "cost-multiplier");
    text = text.replace("requirements", "required-technologies");
    text = text.replace("walkingspeed", "walking-speed");
    text = text.replace("storagesize", "storage-size");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("shootingspeed", "shooting-speed");
    text = text.replace("damagebonus", "damage-bonus");
    text = text.replace("clustersize", "cluster-size");
    text = text.replace("aoesize", "area-of-effect-size");
    text = text.replace("magazinesize", "magazine-size");
    text = text.replace("recharge", "robot-recharge-rate");
    text = text.replace("rechargebuffer", "internal-buffer-recharge-rate");
    text = text.replace("wirereach", "wire-reach");
    text = text.replace("craftingspeed", "crafting-speed");
    text = text.replace("smeltingspeed", "smelting-speed");
    text = text.replace("miningpower", "mining-power");
    text = text.replace("miningspeed", "mining-speed");
    text = text.replace("miningarea", "mining-area");
    text = text.replace("supplyarea", "supply-area");
    text = text.replace("constructionarea", "construction-area");
    text = text.replace("lifetime", "lifespan");
    text = text.replace("inventorysizebonus", "inventory-size-bonus");
    text = text.replace("gridsize", "grid-size");
    text = text.replace("boosttechs", "boosting-technologies");
    text = text.replace("allowstech", "allows");
    text = text.replace("storage", "storage-size");
    text = text.replace(/\|\s*\brecipe\b\s*=\s*(.+)\n\|\s*\boutput\b\s*=\s*(.+)/g, function (piece, $1, $2) {
        return "| recipe = " + $1 + " = " + $2;
    });

    text = text.concat("<noinclude>[[Category:Infobox page]]</noinclude>");

    return text;
}

function createPage(pageTitle, content, token, page, contentOfMainPage) {
    $.ajax({
        url: 'https://wiki.factorio.com/api.php',
        data: {
            format: 'json',
            action: 'edit',
            title: pageTitle,
            text: content,
            bot: true,
            createonly: true,
            token: token,
            summary: "(BOT) - Created infobox sub page for " + page
        },
        async: false,
        dataType: 'json',
        type: 'POST',
        success: function( data ) {
           
            if ( data && data.edit && data.edit.result == 'Success' ) {
                window.location.reload(); // reload page if edit was successful
            } else if ( data && data.error ) {
                //alert( 'Error: API returned error code "' + data.error.code + '": ' + data.error.info );
            } else {
                //alert( 'Error: Unknown result from API.' );
            }
        },
        error: function( xhr ) {
            //alert( 'Error: Request failed.' );
        }
    });
}